# aib CLI

CLI для подключения к живому `aib` extension instance.

Текущая цель пакета:

- discovery instance по локальному registry;
- session runtime, который переиспользуется между вызовами;
- базовые debug-команды;
- semantic operations поверх extension runtime.

## Current Commands

- `aib listInstances`
- `aib ping`
- `aib runtimeInfo`
- `aib printConfig`
- `aib init-skill-usage`
- `aib inspect file <file> [--ranges] [--local-only]`
- `aib inspect exports <file> [--ranges]`
- `aib inspect exports <file> --resolve-star`
- `aib inspect members <file> <entity> [--ranges] [--offset <n>] [--limit <n>] [--all]`
- `aib inspect code <file> <entity> [--parent <entity>] [--ranges] [--max-lines <n>] [--to-file <path>]`
- `aib inspect dependencies <file> <entity> [--ranges]`
- `aib inspect slice <file> <entity> [--max-lines <n>] [--to-file <path>]`
- `aib modulePlan preview --stdin [--details]`
- `aib modulePlan preview --from-json <plan.json> [--details]`
- `aib inspect graph <file-or-directory> [--depth 0|1|2] [--exclude <glob>] [--exclude-from <file>]`
- `aib inspect graph --from-file <graph.json> --focus <file> [--symbols] [--symbol-usage]`
- `aib inspect --stdin`
- `aib imports importers <file-or-directory>`
- `aib imports unused <file>`
- `aib move toFile preview --stdin`
- `aib rename preview --stdin`
- `aib modulePlan apply --stdin`
- `aib modulePlan apply --from-json <plan.json>`
- `aib modulePlan apply <planId>`
- `aib modulePlan validate --plan <planId>`
- `aib trace status|set|clear`
- `aib session init|status|where|read|write|clear`
- `aib session start|stop`

## Global Flags

- `--cwd <path>`: resolve the target IDE instance for this workspace path.
- `--instance <id>`: target a specific registry instance. This never auto-starts another IDE host.
- `--transport http|websocket`: choose the extension transport for the request.
- `--metrics`: include opt-in timing spans.
- `--auto-start-ide`: if no live IDE matches `--cwd`, start or reuse a managed Windows VS Code `serve-web + headless client` host.
- `--no-auto-start-ide`: disable auto-start for one command, even if the environment enables it.

Environment:

- `AIB_AUTO_START_IDE=1` enables the same opt-in managed IDE startup as `--auto-start-ide`.
- `AIB_EXTENSION_VSIX=<path>` points managed startup at a packaged extension VSIX.
- `AIB_INSTALL_CONFIG=<path>` points managed startup at an install config JSON with `extensionVsix`.
- `AIB_TRACE_DIR=<path>` enables opt-in CLI trace capture for every command in that environment.

Auto-start is conservative for now:

- it is off by default;
- it is Windows VS Code `serve-web` only;
- canonical commands are the validated path;
- workspace alias settings in managed serve-web mode still need separate verification.

## Trace Capture

Trace capture is off by default.

Enable it for one command:

```powershell
aib --trace-dir .aib-trace doctor
```

Enable it for a trial session:

```powershell
$env:AIB_TRACE_DIR = ".aib-trace"
aib move toFile preview --stdin
```

Enable it for the current project so it survives new shells:

```powershell
aib trace set .aib-trace
aib trace status
```

Clear the project trace setting without deleting existing trace files:

```powershell
aib trace clear
```

Priority is `--trace-dir`, then `AIB_TRACE_DIR`, then the project trace setting.
Relative trace paths are resolved against the CLI `cwd`. Trace output includes `trace.jsonl` plus per-call request/response/meta artifacts under `calls/`.

## Inspect / Progressive Disclosure

Use `inspect` when an agent needs a compact semantic map before refactoring.

```powershell
aib inspect file src/service.ts
aib inspect exports src/service.ts
aib inspect members src/service.ts c-Service
aib inspect members src/service.ts c-Service --offset 20 --limit 20
aib inspect members src/service.ts c-Service --all
aib inspect code src/service.ts m-save --parent c-Service
aib inspect code src/service.ts v-LARGE_TABLE --to-file .aib-slices/large-table.ts
aib inspect dependencies src/service.ts c-Service
aib inspect slice src/service.ts c-Service --to-file .aib-slices/service.ts
aib inspect exports src/index.ts --resolve-star
aib inspect file src/service.ts --ranges
aib inspect file src/index.ts --local-only
```

Batch inspect requests:

```powershell
@'
{
  "file": "src/service.ts",
  "requests": [
    { "op": "file" },
    { "op": "exports" },
    { "op": "members", "entity": "c-Service" },
    { "op": "code", "entity": "m-save", "parent": "c-Service" },
    { "op": "slice", "entity": "c-Service", "toFile": ".aib-slices/service.ts" }
  ]
}
'@ | aib inspect --stdin
```

Uniform batch requests can avoid repeating both `file` and `op`:

```powershell
@'
{
  "file": "src/service.ts",
  "op": "dependencies",
  "entities": [
    "f-createService",
    "c-Service"
  ]
}
'@ | aib inspect --stdin
```

Uniform `dependencies` and `members` batches return grouped compact output keyed by entity selector.

`dependencies` output is grouped by usage:

```json
{
	"typeOnly": ["i-CartLine", "t-CurrencyCode"],
	"value": ["f-createMoney", "v-TIER_DISCOUNT"]
}
```

`unclassified` is shown only when nonempty. It means the inspect layer found a local dependency but could not safely classify the usage position with the current syntax heuristic.

Default inspect output is compact and uses fixed selector aliases (`c-`, `i-`, `t-`, `f-`, `v-`, `e-`, `m-`, `p-`). Workspace selector alias overrides are intentionally ignored.

`inspect file --local-only` answers the physical-file question. It reports local declarations and re-export modules without resolving `export *` through a facade:

```json
{
	"file": "src/index.ts",
	"results": [
		{
			"op": "file",
			"mode": "local",
			"summary": "facade only; 3 re-exports; 0 local declarations",
			"symbols": [],
			"reexports": ["./core/types.js", "./core/service.js", "./core/index.js"]
		}
	]
}
```

Use `inspect exports <file> --resolve-star` for the public API visible through a facade.

`inspect graph` gives a compact local file relationship map. It is local CLI logic and does not require an IDE runtime:

```powershell
aib inspect graph src/main --depth 1
aib inspect graph src/main --depth 1 --exclude "**/* copy.ts"
aib inspect graph src/main --depth 1 --exclude-from .aib-graph-ignore
```

Graph excludes can also be configured in `.aib.json`, `.aib.json`, or `.vscode/settings.json`:

```json
{
	"inspect": {
		"graph": {
			"exclude": ["**/* copy.ts", "src/generated/**"]
		}
	}
}
```

Excludes are applied before the graph model is built, so excluded files do not affect counts, hubs, leaves, edges, or saved graph files.

`members` is compact by default: it returns the first page of members plus a hidden-count marker when more members exist. Use `--all` for the full list or `--offset <n> --limit <n>` to page through a large class/interface without printing every member.

`code --to-file <path>` writes exact selected code to disk without printing it to stdout. Use it for large declarations that an agent needs to mechanically move or inspect without polluting context.

`inspect --stdin` supports per-request `toFile` / `outputFile` for `code` and `slice` rows. This lets an agent extract several selected declarations in one CLI call while stdout only reports compact `writtenTo` paths.

With a session workspace, use `save` to write selected code/slices and keep stdout compact:

```powershell
aib session init --dir .tmp/aib
@'
{
  "file": "src/service.ts",
  "parent": "c-Service",
  "requests": [
    { "op": "code", "entity": "m-save", "save": "service-save-method" },
    { "op": "slice", "entity": "c-Service", "parent": null, "save": "service-class" }
  ]
}
'@ | aib inspect --stdin
```

Use `bundleSave` when several inspect rows form one reusable context packet. Per-request `save` still works:

```powershell
@'
{
  "file": "src/service.ts",
  "parent": "c-Service",
  "bundleSave": "service-context",
  "requests": [
    { "op": "members", "entity": "c-Service" },
    { "op": "code", "entity": "m-save", "save": "service-save-method" },
    { "op": "slice", "entity": "c-Service", "parent": null, "save": "service-class" }
  ]
}
'@ | aib inspect --stdin
```

The bundle is saved as `aib:inspect:service-context` and can be read with `session read`.

Read saved artifacts back into context by handle:

```powershell
aib session read aib:code:service-save-method
aib session read aib:slice:service-class --head 80
```

Batch reads avoid repeated CLI calls:

```powershell
@'
{
  "reads": [
    { "handle": "aib:code:service-save-method" },
    { "handle": "aib:slice:service-class", "offset": 30, "limit": 50 }
  ]
}
'@ | aib session read --stdin
```

`modulePlan` validates an agent-proposed module split without editing source files. It reports compact per-target summaries with exported symbols, private symbols, type-only imports, runtime imports, unassigned dependencies, runtime cycles, and facade export suggestions:

```powershell
@'
{
  "file": "src/service.ts",
  "op": "modulePlan",
  "facade": "src/service.ts",
  "modules": [
    {
      "target": "src/core/types.ts",
      "symbols": ["i-ServiceOptions", "t-ServiceMode"]
    },
    {
      "target": "src/core/service.ts",
      "symbols": ["c-Service", "f-createService"]
    }
  ]
}
'@ | aib modulePlan preview --stdin
```

For large plans, write the same JSON to a temporary file and edit that file with normal file tools instead of repeatedly printing long heredocs:

```powershell
aib modulePlan preview --from-json .aib-plan/module-plan.json
```

Add `"previewFiles": true` to write read-only preview artifacts without changing source files:

```json
{
	"file": "src/service.ts",
	"op": "modulePlan",
	"facade": "src/service.ts",
	"previewFiles": true,
	"previewDir": ".aib-preview/service-split",
	"modules": [
		{
			"target": "src/core/types.ts",
			"symbols": ["i-ServiceOptions", "t-ServiceMode"]
		},
		{
			"target": "src/core/service.ts",
			"symbols": ["c-Service", "f-createService"]
		}
	]
}
```

The response stays compact and points to generated artifacts:

```json
{
	"planId": "plan_abc123",
	"planHash": "sha256:...",
	"next": "Run modulePlan apply plan_abc123 if the plan matches intent.",
	"preview": {
		"dir": ".aib-plan-cache/previews/plan_abc123",
		"summary": "2 files; facade 2l; patch 120l; cycles none",
		"files": {
			"src/core/service.ts": {
				"file": ".aib-plan-cache/previews/plan_abc123/files/core/service.ts",
				"lines": 80
			}
		},
		"facade": {
			"file": ".aib-preview/service-split/facade/service.ts",
			"lines": 2
		},
		"patch": {
			"file": ".aib-preview/service-split/module-plan.preview.patch",
			"lines": 120
		},
		"next": ["check summary/api/cycles/imports", "read targeted preview artifacts only if a warning/check points there", "use top-level next for apply/revise action"]
	}
}
```

Default `modulePlan` output uses compact `targets[].summary` rows, for example `exports c-Service; private f-normalize; imports type src/core/types.ts: i-Options; run src/core/helpers.ts: f-createHelper`. Add `--details` only when an agent needs the full module ownership/import map in stdout.

When `modulePlan preview` includes preview files, the plan is cached under `.aib-plan-cache/` and can be applied without resending the module JSON if it is executable:

```powershell
aib modulePlan apply plan_abc123
```

After apply, run a compact generated-module validation:

```powershell
aib modulePlan validate --plan plan_abc123
```

It checks that expected generated files exist, generated relative import/export specifiers use `.js`, generated modules do not import back from the facade, and the cached facade/API expectation is still visible.

`modulePlan` also reports public API preservation when a facade is requested:

```json
{
	"api": {
		"status": "preserved",
		"before": 44,
		"after": 44
	}
}
```

If a generated module would import a symbol from another generated module that is not exported there, `modulePlan` returns a compact diagnostic-first response. The plan is cached as non-executable, so it can be revised by id but cannot be applied:

```json
{
	"ok": false,
	"planId": "plan_blocked123",
	"executable": false,
	"blocking": [
		{
			"from": "src/commerce/pricing.ts",
			"source": "src/commerce/customer.ts",
			"usage": "value",
			"symbols": ["v-TIER_DISCOUNT"],
			"suggestedFixes": [{ "kind": "moveSymbol", "symbol": "v-TIER_DISCOUNT", "to": "src/commerce/pricing.ts" }],
			"hint": "Move the symbol into the importing module, move the dependent symbol into the owner module, or intentionally export it before applying."
		}
	],
	"next": "Revise with: aib modulePlan revise --plan plan_blocked123 --stdin"
}
```

Revise a blocked plan without resending the full module JSON:

```powershell
@'
{
  "applySuggestedFixes": [0]
}
'@ | aib modulePlan revise --plan plan_blocked123 --stdin
```

Or move a symbol explicitly:

```powershell
@'
{
  "moves": [
    { "symbol": "v-TIER_DISCOUNT", "to": "src/commerce/pricing.ts" }
  ]
}
'@ | aib modulePlan revise --plan plan_blocked123 --stdin
```

When generated preview artifacts are large, the response adds a compact `large` list and changes the first `next` hint so agents do not read large files or patches by default:

```json
{
	"preview": {
		"summary": "11 files; facade 11l; patch 2687l; cycles none",
		"large": ["src/commerce/workflow.ts 1336l", "patch 2687l"],
		"next": ["check summary/imports/exports before reading large preview artifacts", "copy preview if acceptable", "run project checks"]
	}
}
```

If runtime cycles are detected, the preview response warns and points the next action back at the plan instead of applying files.

Preview artifacts are intentionally read-only planning outputs. They do not remove declarations from the source file or apply edits.

`modulePlan apply` is the apply gate for a validated module plan. Its preview accepts the same layout shape as `modulePlan preview`, writes cached preview artifacts, and returns a compact apply summary instead of repeating the full module map:

```powershell
@'
{
  "sourceFile": "src/service.ts",
  "facadeFile": "src/service.ts",
  "modules": [
    {
      "targetFile": "src/core/types.ts",
      "symbols": ["i-ServiceOptions", "t-ServiceMode"]
    },
    {
      "targetFile": "src/core/service.ts",
      "symbols": ["c-Service", "f-createService"]
    }
  ],
  "execute": false
}
'@ | aib modulePlan apply --stdin
```

Compact preview:

```json
{
	"operation": "modulePlan.apply",
	"execute": false,
	"planId": "plan_abc123",
	"summary": "2 files; facade 2l; patch 120l; cycles none; public API preserved",
	"targets": [
		{
			"file": "src/core/types.ts",
			"summary": "exports i-ServiceOptions, t-ServiceMode"
		},
		{
			"file": "src/core/service.ts",
			"summary": "exports c-Service, f-createService; imports type ./types.js: i-ServiceOptions, t-ServiceMode"
		}
	],
	"api": {
		"status": "preserved",
		"before": 4,
		"after": 4,
		"removed": [],
		"added": []
	},
	"integrity": "2 declarations moved unchanged; 1 imports generated; facade exports 2",
	"writes": ["src/core/types.ts", "src/core/service.ts", "src/service.ts"],
	"warnings": [],
	"next": "Run modulePlan apply plan_abc123 if the summary matches intent."
}
```

Apply:

```powershell
aib modulePlan apply plan_abc123
```

Apply echoes the validation signals that matter after mutation:

```json
{
	"operation": "modulePlan.apply",
	"execute": true,
	"applied": true,
	"planId": "plan_abc123",
	"api": { "status": "preserved", "before": 4, "after": 4 },
	"cycles": "none",
	"facade": { "file": "src/service.ts", "exports": 2 },
	"integrity": "2 declarations moved unchanged; 1 imports generated; facade exports 2",
	"filesWritten": ["src/core/types.ts", "src/core/service.ts", "src/service.ts"],
	"summary": "3 files written"
}
```

`integrity` summarizes the current module-plan mutation strategy: selected declarations are moved unchanged from original source ranges, while imports and facade exports are generated around those declarations.

Inspect output intentionally avoids IDE/debug-only details in the agent-facing path:

- file paths are relative to the CLI `cwd` when possible;
- a shared file path is emitted once at response level instead of repeated on every result;
- successful results omit noisy `ok: true` wrappers;
- `--ranges` emits compact line metadata such as `l19 1260..1278`;
- character offsets and `selectionRange` stay out of stdout; use trace/debug artifacts if exact IDE ranges are needed.

Line metadata is 1-based and inclusive for human/agent navigation. Add `--ranges` only when line/range navigation is needed.

## Workspace Config And Aliases

Agent-facing command and selector aliases are fixed product defaults. The CLI ignores workspace-level selector alias overrides so agents can rely on one selector contract across repositories.

CLI также умеет генерировать agent-facing usage instructions на основе effective config:

```powershell
aib --cwd D:\dev\agent-ide\fixtures\ts-sandbox init-skill-usage
aib --cwd D:\dev\agent-ide\fixtures\ts-sandbox init-skill-usage --cli-name myagentcli
```

## Local Development

Из корня workspace:

```powershell
cd D:\dev\agent-ide
npm run cli:typecheck
npm run cli:build
npm run cli:link
```

После `npm link` команда доступна как:

```powershell
aib ping
```

## Local Tarball / npx-Oriented Flow

Собрать локальный tarball:

```powershell
cd D:\dev\agent-ide
npm run cli:pack
```

Tarball появится в:

- `D:\dev\agent-ide\.tmp\aib-<version>.tgz`

Дальше можно запускать CLI не через `npm link`, а через временную установку tarball.

Пример:

```powershell
npx --yes --package D:\dev\agent-ide\.tmp\aib-0.0.1.tgz aib ping --cwd D:\dev\agent-ide
```

Это полезно как переходный локальный шаг перед будущим publishable `npx aib ...` flow.

Примеры semantic-команд через tarball:

```powershell
npx --yes --package D:\dev\agent-ide\.tmp\aib-0.0.1.tgz aib imports importers fixtures\ts-sandbox\src\utils --cwd D:\dev\agent-ide
npx --yes --package D:\dev\agent-ide\.tmp\aib-0.0.1.tgz aib imports unused fixtures\ts-sandbox\src\services\unused-imports.ts --cwd D:\dev\agent-ide
```
