@krisada-m/ksd-intelligence 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/.antigravity-plugin/plugin.json +20 -0
  2. package/README.md +36 -8
  3. package/agy-skills/erosiano-review/SKILL.md +17 -0
  4. package/dist/adapters/cli/check-changed.js +1 -1
  5. package/dist/adapters/cli/main.js +29 -18
  6. package/dist/adapters/cli/review-verdict.js +1 -1
  7. package/dist/adapters/omp/extension.js +7 -16
  8. package/dist/adapters/ui/hud.js +99 -28
  9. package/dist/adapters/ui/tree.js +11 -0
  10. package/dist/core/engine/status.js +73 -2
  11. package/dist/core/indexing/indexer.js +24 -5
  12. package/dist/engineering/baseline.js +337 -0
  13. package/dist/{policy → engineering}/config.js +33 -10
  14. package/dist/{policy → engineering}/dist/policy.d.ts +3 -3
  15. package/dist/{policy → engineering}/dist/policy.js +25 -22
  16. package/dist/{policy → engineering}/dist/runtime.js +11 -9
  17. package/dist/engineering/index.d.ts +7 -0
  18. package/dist/engineering/index.js +319 -0
  19. package/dist/engineering/intelligence.js +44 -0
  20. package/dist/{policy → engineering}/package.json +7 -4
  21. package/dist/engineering/practice-tool.js +72 -0
  22. package/dist/engineering/practices.js +283 -0
  23. package/dist/engineering/practices.json +2453 -0
  24. package/engineering.lock.json +94 -0
  25. package/package.json +13 -6
  26. package/rules/engineering.md +20 -0
  27. package/scripts/mcp/engineering.mjs +91 -0
  28. package/scripts/mcp/tools.mjs +45 -5
  29. package/dist/policy/index.d.ts +0 -2
  30. package/dist/policy/index.js +0 -241
  31. package/dist/policy/policy.d.ts +0 -2
  32. /package/dist/{policy → engineering}/change-scope.js +0 -0
  33. /package/dist/{policy → engineering}/check-changed.js +0 -0
  34. /package/dist/{policy → engineering}/dist/runtime.d.ts +0 -0
  35. /package/dist/{policy → engineering}/dist/sdlc.d.ts +0 -0
  36. /package/dist/{policy → engineering}/dist/sdlc.js +0 -0
  37. /package/dist/{policy → engineering}/eslint-rules/index.js +0 -0
  38. /package/dist/{policy → engineering}/policy.js +0 -0
  39. /package/dist/{policy → engineering}/review-verdict.js +0 -0
  40. /package/dist/{policy → engineering}/sdlc.js +0 -0
@@ -0,0 +1,20 @@
1
+ {
2
+ "$schema": "https://antigravity.google/schemas/v1/plugin.json",
3
+ "name": "ksd-intelligence",
4
+ "displayName": "KSD Intelligence",
5
+ "version": "1.1.0",
6
+ "description": "Pinned erosiano-dev engineering guidance and local code intelligence skills.",
7
+ "author": {
8
+ "name": "Krisada-M",
9
+ "url": "https://github.com/Krisada-M"
10
+ },
11
+ "repository": "https://github.com/Krisada-M/ksd-intelligence",
12
+ "license": "MIT",
13
+ "skills": [
14
+ "./agy-skills"
15
+ ],
16
+ "suggestedPrompts": [
17
+ "Establish the effective project baseline before a change",
18
+ "Review the current diff using engineering evidence"
19
+ ]
20
+ }
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # ksd-intelligence
2
2
 
3
- KSD helps you find TypeScript and JavaScript code, see what depends on a symbol before editing it, and review what an actual Git diff affects. It builds a private local SQLite index. It suggests checks; it does not run your tests, edit source, approve changes, or deploy. In Oh My Pi (OMP) it also supplies the KSD engineering policy and a skill workflow. Antigravity (AGY) uses the same analysis through local MCP stdio, without the OMP policy.
3
+ KSD helps you find TypeScript and JavaScript code, see what depends on a symbol before editing it, and review what an actual Git diff affects. It builds a private local SQLite index. It suggests checks; it does not run your tests, edit source, approve changes, or deploy. It also supplies the pinned **erosiano-dev** engineering core (baseline, 138 practices, quality gates and evidence-aware review). One product, two host adapters: native extension in OMP and native rules/skills plus fixed-root local MCP in Antigravity (AGY). The integration branch is a candidate, not a released version.
4
4
 
5
5
  ## Install
6
6
 
@@ -8,7 +8,7 @@ Requirements: Git and **Node ≥ 22.5**; use Node 24 LTS. On Node 22.5–22.12 o
8
8
 
9
9
  ### OMP: marketplace
10
10
 
11
- If you already use `engineering-proxy@engineering-proxy`, uninstall it first (`omp plugin uninstall engineering-proxy@engineering-proxy`). Running both plugins can inject the policy twice.
11
+ Only install `ksd-intelligence@ksd-intelligence` as the engineering/intelligence product. Before switching to the integrated build, back up configuration and uninstall any standalone `engineering-proxy@engineering-proxy` or `erosiano-dev@erosiano-dev` installation that exists. Do not activate both policy owners. Ponytail is independent.
12
12
 
13
13
  ```sh
14
14
  omp plugin marketplace add Krisada-M/ksd-intelligence
@@ -16,11 +16,21 @@ omp plugin install ksd-intelligence@ksd-intelligence
16
16
  omp plugin list
17
17
  ```
18
18
 
19
- Restart OMP. Run `/engineering-proxy status` and check the KSD status segment. To get the `ei` shell command, install the npm package below; it does not replace the marketplace install. From a built checkout you can instead run `node dist/adapters/cli/main.js` in place of `ei`.
19
+ Restart OMP. Run `/erosiano-dev status` and inspect the EROSIANO status segment. `/engineering-proxy` and `/engineering-review` are migration aliases owned by the same new core. Existing legacy config/session modes are migrated by erosiano-dev; the former policy is not loaded. Default engineering integration uses the four native `ei_*` tools; explicit `intelligenceMode` config overrides it. A missing/inactive tool falls back to native evidence. New core commands include `/erosiano-dev baseline [scope]`, `/erosiano-dev practices [scope]`, `/erosiano-dev review [scope]`. To get the `ei` shell command, install the npm package below; it does not replace the marketplace install. From a built checkout you can instead run `node dist/adapters/cli/main.js` in place of `ei`.
20
20
 
21
- ### AGY and terminal: npm
21
+ ### AGY: native plugin and terminal/MCP
22
22
 
23
- After 1.0.0 is published:
23
+ The same repository has an Antigravity-native manifest, a generated balanced rule, existing skills and an on-demand `erosiano-review` skill. From a trusted checkout of this candidate, validate and install locally:
24
+
25
+ ```sh
26
+ agy plugin validate /absolute/path/to/ksd-intelligence
27
+ agy plugin install /absolute/path/to/ksd-intelligence
28
+ agy plugin list
29
+ ```
30
+
31
+ Once the integrated build is accepted on main, the same repository URL can be used for AGY installation. AGY's static rule does not implement OMP's session mode or config hooks. Disable the AGY plugin using the host controls. MCP stays an explicit per-workspace setup with an approved absolute root; a global plugin cannot safely infer the active project. Live AGY validation and installation are still required.
32
+
33
+ For terminal tools and the MCP launcher, install an accepted package (or pack/install this candidate from a trusted checkout):
24
34
 
25
35
  ```sh
26
36
  npm install -g @krisada-m/ksd-intelligence
@@ -43,6 +53,8 @@ Configure AGY to launch `ei mcp --root /absolute/path/to/project`. In AGY's MCP
43
53
  }
44
54
  ```
45
55
 
56
+ To expose the same engineering resolver through MCP, explicitly set `env: { "KSD_MCP_ENGINEERING": "1" }` on this server and append `erosiano_baseline` and `erosiano_resolve_practices` to `enabledTools`. The first captures scoped hashes; the second resolves practices using a supplied current fingerprint and path provenance. Both use the configured root, never a tool-supplied root or subprocess. Leave the flag unset to keep the original tool list.
57
+
46
58
  Use the absolute path to `ei` if AGY does not inherit your npm bin `PATH`. This is a stdio process, not an HTTP server. The root cannot change through a tool call; use a separate server entry for each project. To expose workflow, append `--workflow`, add `ei_workflow` to `enabledTools`, and set the skill roots below. See the [AGY guide](https://github.com/Krisada-M/ksd-intelligence/blob/main/docs/integrations/antigravity.md).
47
59
 
48
60
  ## Set up a repository
@@ -128,7 +140,7 @@ Workflow fails closed without the configured skill sources. For indexed work, fo
128
140
  | `riskZones` | `"default"` (payments, auth, migrations, production config), custom `{zone,floor,match}` entries, or `[]`. Zones only raise risk |
129
141
  | `search.enabled` | Lexical search only |
130
142
 
131
- Set `EI_DISABLED=1` before launching OMP or AGY to disable EI tools. Set `ENGINEERING_PROXY_DISABLED=1` before launching OMP to disable KSD policy injection and delegated review; KSD status remains available. Use both to disable both surfaces. KSD mode has separate configuration in `~/.omp/agent/engineering-proxy.json` and project `.engineering-proxy.json`.
143
+ Set `EI_DISABLED=1` before launching OMP or the MCP server to disable EI tools. In OMP, `EROSIANO_DEV_DISABLED=1` (or legacy `ENGINEERING_PROXY_DISABLED=1`) disables policy guidance and review independently; it is not a way to co-install two policy owners. Engineering configuration lives in `~/.omp/agent/erosiano-dev.json` and project `.erosiano-dev.json`; missing new files fall back to the old files. See the [engineering guide](https://github.com/Krisada-M/ksd-engineering) for precedence and migration. AGY uses its own plugin activation; these environment flags do not control its static rule.
132
144
 
133
145
  Index and audit are local under `~/.cache/ksd-intelligence/`. SQLite keeps symbols, references, capped signature text and first JSDoc paragraphs, not whole source files. `ei audit --since 7d` summarizes tool use. `ei cache clear` deletes the current project's index and audit, **not** the shared runtime; it refuses during a live build.
134
146
 
@@ -157,12 +169,28 @@ Index and audit are local under `~/.cache/ksd-intelligence/`. SQLite keeps symbo
157
169
  omp plugin marketplace update ksd-intelligence
158
170
  omp plugin upgrade ksd-intelligence@ksd-intelligence
159
171
 
160
- # Remove; optionally restore the old OMP policy plugin, never both at once.
172
+ # Remove the composed product (both OMP policy and intelligence).
161
173
  omp plugin uninstall ksd-intelligence@ksd-intelligence
162
- omp plugin install engineering-proxy@engineering-proxy
174
+ # AGY: uninstall its native plugin and remove the separately configured MCP entry.
175
+ agy plugin uninstall ksd-intelligence
163
176
 
164
177
  # Remove the AGY MCP entry and reload AGY, then remove the CLI.
165
178
  npm uninstall -g @krisada-m/ksd-intelligence
166
179
  ```
167
180
 
168
181
  For npm rollback, reinstall a previous approved version or saved tarball, then run `ei setup` and `ei index --full`. Do not use the old index as evidence for the new version. Back up the audit log before `ei cache clear` if you need it. See the [changelog](CHANGELOG.md) and [release checklist](https://github.com/Krisada-M/ksd-intelligence/blob/main/docs/release-checklist.md) for verification and owner gates.
182
+
183
+ ## Engineering bundle provenance
184
+
185
+ [`engineering.lock.json`](engineering.lock.json) pins the exact upstream commit and every allowed runtime Git blob/mode. `src/engineering/` contains byte-identical runtime files; build verifies them offline and copies them to `dist/engineering/`, never fetching dependencies at agent startup. The old `src/policy/` and its frozen tests remain historical contract evidence; no legacy policy is registered or distributed under `dist/policy/`. `npm run verify:engineering` validates both source and distribution. The exported ESLint rules and all four engineering companion CLIs now use the new bundle. To update the core, review the upstream PR, update the pin and bytes together using the sync script, regenerate host assets, build, run CI, then approve the composed product. See [provenance](PROVENANCE.md).
186
+
187
+ ```sh
188
+ # Owner-run, from the consuming repo with a trusted upstream checkout and reviewed full commit.
189
+ node scripts/sync-engineering.mjs /absolute/path/to/ksd-engineering <exact-commit>
190
+ node scripts/generate-agy-engineering.mjs --write
191
+ npm run build
192
+ npm run verify:engineering
193
+ npm test
194
+ ```
195
+
196
+ The upstream allowlist is explicit; newly introduced runtime files require a reviewed change to it. Commit the pin, source, dist and generated AGY rule together. CI also checks the source blob IDs against the separately checked-out upstream commit. No runtime dependency is added.
@@ -0,0 +1,17 @@
1
+ ---
2
+ name: erosiano-review
3
+ description: Review scoped changes using the shared erosiano-dev engineering standard, project baseline, code impact and actual verification evidence. Use when reviewing a diff or assessing release readiness.
4
+ ---
5
+
6
+ # Evidence-based engineering review
7
+
8
+ Use the enabled plugin's generated balanced engineering rule. Project instructions, contracts and native safety gates take precedence over personal preferences. Do not reproduce the entire practice catalog.
9
+
10
+ 1. Identify the requested scope, acceptance criteria, affected contracts and risk. Read applicable instructions, maintained code, callers, tests and native gate configuration. Distinguish current, legacy, transitional, local, exception and unknown observations, with evidence and confidence.
11
+ 2. If the explicitly configured workspace MCP is available, check its fixed root and index status; use `ei_search`, `ei_impact` and `ei_changes` for discovery and impact. Partial or degraded evidence is not a safety verdict. If unavailable, inspect source and tests directly.
12
+ 3. For a scoped practice selection, use the approved terminal companions `erosiano-baseline` and `erosiano-practices` from the same installed KSD package. Capture the actual scope and relevant caller/test/config files, then provide the snapshot fingerprint and path-based observation provenance. Never invent a fingerprint or supply another repository root. If the engineering MCP tools are explicitly configured, use them instead. A stale or incomplete baseline must be refreshed or reported unknown.
13
+ 4. Inspect tracked and intended untracked changes, including deletion/rename effects. Determine required native checks from the repository. Verify only through AGY's permitted tools, and record commands, cwd, exit status, counts and exact reviewed revision. Never infer PASS from a test definition, skipped check, admin-only access or synthetic fixture.
14
+ 5. Escalate authentication, tenant isolation, payment replay, database migration, secrets and concurrency based on behavior. Check normal-user denial and failure paths; never execute real payments or destructive shared-database tests.
15
+ 6. Report severity, file/line evidence, affected contracts, verification results, remaining unknowns, rollback impact and approval blockers. Do not merge, publish or deploy.
16
+
17
+ AGY does not emulate OMP's command/session lifecycle. Do not invoke OMP slash commands or change host tool permissions. No automatic execution of bundled scripts or installation of dependencies.
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import { runPolicyBin } from './policy-bin.js';
3
- await runPolicyBin(new URL('../../policy/check-changed.js', import.meta.url), 'ksd-check-changed --diff git.patch --eslint-report eslint.json');
3
+ await runPolicyBin(new URL('../../engineering/check-changed.js', import.meta.url), 'ksd-check-changed --diff git.patch --eslint-report eslint.json');
@@ -292,7 +292,9 @@ async function run(argv) {
292
292
  return 0;
293
293
  }
294
294
  const started = performance.now();
295
- const status = await workspaceStatus(values.root ?? process.cwd());
295
+ const status = await workspaceStatus(values.root ?? process.cwd(), {
296
+ presentation: view === undefined ? undefined : 'status',
297
+ });
296
298
  recordAudit(status.cacheDir, {
297
299
  ts: new Date().toISOString(),
298
300
  tool: 'ei_status',
@@ -373,13 +375,19 @@ async function run(argv) {
373
375
  repo: basename(workspace.root),
374
376
  previous,
375
377
  });
378
+ let rebuildReason;
376
379
  const outcome = await duringHud(hud, () => buildIndex(workspace, {
377
380
  full: values.full === true,
378
381
  onProgress: hud === undefined ? (message) => console.error(`ei index: ${message}`) : undefined,
379
- onHudProgress: hud?.update,
382
+ onHudProgress: hud === undefined && view === undefined
383
+ ? undefined
384
+ : (event) => {
385
+ rebuildReason = event.reason ?? rebuildReason;
386
+ hud?.update(event);
387
+ },
380
388
  }));
381
389
  if (!outcome.ok) {
382
- if (hud !== undefined && view !== undefined) {
390
+ if (view !== undefined) {
383
391
  const status = await workspaceStatus(workspace.root);
384
392
  console.log(renderHudSummary({
385
393
  ...view,
@@ -402,18 +410,23 @@ async function run(argv) {
402
410
  const durationMs = performance.now() - started;
403
411
  const seconds = (durationMs / 1000).toFixed(2);
404
412
  const { action, reason } = outcome.value;
405
- if (hud !== undefined &&
406
- view !== undefined &&
413
+ if (view !== undefined &&
407
414
  (action === 'cold' || action === 'update' || action === 'unchanged' || action === 'failed')) {
408
- const { index } = await workspaceStatus(workspace.root);
409
- const problems = Array.isArray(outcome.value.problems)
410
- ? outcome.value.problems.filter((value) => typeof value === 'string')
411
- : [];
415
+ const { index, presentation, includeWarnings } = await workspaceStatus(workspace.root, {
416
+ presentation: action === 'failed' ? undefined : 'index',
417
+ });
418
+ let shownReason = rebuildReason ?? String(reason);
419
+ if (action === 'failed') {
420
+ shownReason = String(reason);
421
+ const problems = Array.isArray(outcome.value.problems)
422
+ ? outcome.value.problems.filter((value) => typeof value === 'string')
423
+ : [];
424
+ if (problems.length > 0)
425
+ shownReason += `: ${problems.join('; ')}`;
426
+ }
412
427
  const actionLabel = action === 'cold' ? 'built' : 'updated';
413
428
  const activeIndex = index === null ? 'none' : homeRelative(index.path);
414
429
  const drift = isRecord(outcome.value.drift) ? outcome.value.drift : {};
415
- const coverage = index?.coverage;
416
- const extraction = index?.graph.extraction;
417
430
  console.log(renderHudSummary({
418
431
  ...view,
419
432
  command: 'index',
@@ -421,19 +434,17 @@ async function run(argv) {
421
434
  kind: action === 'cold' || action === 'update' ? action : undefined,
422
435
  durationMs,
423
436
  previous,
424
- reason: problems.length === 0 ? String(reason) : `${String(reason)}: ${problems.join('; ')}`,
437
+ reason: shownReason,
425
438
  phases: phaseTimes(outcome.value.phases),
426
- files: coverage?.scanned,
427
- indexed: extraction === undefined ? undefined : (extraction.ok ?? 0),
428
- outsideScope: coverage?.reasons['outside-index-scope'] ?? (index === null ? undefined : 0),
429
- errors: extraction === undefined
439
+ coverage: index === null || presentation === undefined
430
440
  ? undefined
431
- : (extraction['parse-error'] ?? 0) + (extraction['not-in-program'] ?? 0),
441
+ : { scanned: index.coverage.scanned, ...presentation },
442
+ includeWarnings,
432
443
  drift: action === 'update'
433
444
  ? `+${String(drift.added)} · ~${String(drift.changed)} · −${String(drift.deleted)}`
434
445
  : undefined,
435
446
  activeIndex: action === 'failed' ? activeIndex : undefined,
436
- throughput: hud.throughput,
447
+ throughput: hud?.throughput,
437
448
  next: action === 'failed' ? 'check ei status before retrying' : 'ready for ei impact',
438
449
  }));
439
450
  return action === 'failed' ? 1 : 0;
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import { runPolicyBin } from './policy-bin.js';
3
- await runPolicyBin(new URL('../../policy/review-verdict.js', import.meta.url), 'ksd-review-verdict --report assessment.json');
3
+ await runPolicyBin(new URL('../../engineering/review-verdict.js', import.meta.url), 'ksd-review-verdict --report assessment.json');
@@ -1,17 +1,7 @@
1
1
  /**
2
- * OMP extension entry: KSD policy module + `ei_workflow`, `ei_status` and `ei_impact` tools in one plugin.
3
- *
4
- * STATUS: live-verified pieces — policy module migrated byte-identical from KSD 0.6.0
5
- * (73fc916) in M1c, ei_workflow verified live in OMP 18.18.8 in M1, ei_status (M2a.1) uses the
6
- * `ctx.cwd` documented for tool `execute` in OMP 18.19.0 (omp://extensions.md §2), ei_impact
7
- * (M2b) verified against OMP 18.22.0 extension types (`@oh-my-pi/pi-coding-agent`
8
- * `extensibility/extensions/types.d.ts`, `wrapper.ts`, `@oh-my-pi/omptype` `src/zod.ts`).
9
- *
10
- * Registration order is KSD first, then ei_* (docs/DESIGN.md §10.1). A failure in
11
- * either part must not prevent the other from registering. Kill switches are
12
- * independent: ENGINEERING_PROXY_DISABLED=1 (checked inside the policy module)
13
- * disables only policy injection and /engineering-review; EI_DISABLED=1 disables
14
- * only the ei_* tools.
2
+ * Single OMP composition root: pinned erosiano-dev engineering policy and native ei_* tools.
3
+ * Registration failures are isolated. EI_DISABLED affects intelligence only; the engineering
4
+ * library owns its config, commands, lifecycle and disable flags.
15
5
  */
16
6
  import { auditFieldsForChanges, auditFieldsForImpact, auditFieldsForSearch, auditFieldsForWorkflow, consumeAuditWarning, recordAudit, } from '../../core/audit/index.js';
17
7
  import { runChanges } from '../../core/changes/changes.js';
@@ -33,8 +23,8 @@ import { prepareWorkflow } from '../../workflow/loader.js';
33
23
  import { renderWorkflow } from '../../workflow/render.js';
34
24
  import { defaultLockPath, readLock } from '../../workflow/sources.js';
35
25
  import { RISKS, STAGES, TASK_TYPES, WorkflowError } from '../../workflow/types.js';
36
- import { createExtension as createPolicyExtension } from '../../policy/index.js';
37
- import { SECTION_KEY } from '../../policy/policy.js';
26
+ import { createExtension as createPolicyExtension } from '../../engineering/index.js';
27
+ import { SECTION_KEY } from '../../engineering/dist/policy.js';
38
28
  import { renderResultView } from '../ui/tree.js';
39
29
  function isImpactResult(value) {
40
30
  return (isRecord(value) &&
@@ -825,7 +815,8 @@ function registerEiVerify(pi, deps, env, loadConfig) {
825
815
  // Advisory tool: every failure becomes an error result for the agent, never a crashed session.
826
816
  export default function ksdIntelligenceExtension(pi, deps = {}) {
827
817
  const env = deps.env ?? process.env;
828
- const startPolicy = deps.createPolicyExtension ?? ((api) => createPolicyExtension(api));
818
+ const startPolicy = deps.createPolicyExtension ??
819
+ ((api) => createPolicyExtension(api, { defaultIntelligenceMode: 'native', label: 'ksd-intelligence' }));
829
820
  try {
830
821
  startPolicy(pi);
831
822
  }
@@ -1,6 +1,9 @@
1
1
  const blocks = ['', '▏', '▎', '▍', '▌', '▋', '▊', '▉', '█'];
2
2
  const sparkBlocks = '⣀⣄⣤⣦⣶⣷⣿';
3
3
  const phaseOrder = ['scan', 'program', 'extract', 'resolve', 'verify', 'publish'];
4
+ const phaseRamp = ['34', '36', '35', '95', '33', '94'];
5
+ const minThroughputMs = 2000;
6
+ const minThroughputSamples = 5;
4
7
  const reset = '\x1b[0m';
5
8
  function safe(text) {
6
9
  return text.replace(/[\x00-\x1f\x7f-\x9f]/g, ' ');
@@ -10,6 +13,31 @@ function duration(ms) {
10
13
  return '?';
11
14
  return `${Number((ms / 1000).toFixed(2))}s`;
12
15
  }
16
+ function wrap(text, prefix, columns) {
17
+ const lines = [];
18
+ const indent = ' '.repeat(width(prefix));
19
+ let line = prefix;
20
+ let hasWord = false;
21
+ for (const word of safe(text).split(/ +/)) {
22
+ if (hasWord && width(`${line} ${word}`) > columns) {
23
+ lines.push(line);
24
+ line = indent;
25
+ hasWord = false;
26
+ }
27
+ let remaining = word;
28
+ const room = columns - width(line);
29
+ while (width(remaining) > room) {
30
+ const piece = fit(remaining, room);
31
+ lines.push(line + piece);
32
+ remaining = remaining.slice(piece.length);
33
+ line = indent;
34
+ }
35
+ line += `${hasWord ? ' ' : ''}${remaining}`;
36
+ hasWord = true;
37
+ }
38
+ lines.push(line);
39
+ return lines;
40
+ }
13
41
  function width(text) {
14
42
  let size = 0;
15
43
  for (const char of text) {
@@ -132,7 +160,8 @@ export function openHud(options) {
132
160
  : [...phases.keys()];
133
161
  const currentIndex = phaseNames.indexOf(current.phase);
134
162
  const prefix = `${ascii ? '|' : '▌'}ei ${options.command} `;
135
- const suffix = `${current.kind ? ` · ${current.kind}` : ''} ${duration(now() - started)}`;
163
+ const elapsed = now() - started;
164
+ const suffix = `${current.kind ? ` · ${current.kind}` : ''} ${duration(elapsed)}`;
136
165
  const heading = `${prefix}${fit(options.repo, Math.max(0, columns - width(prefix) - width(suffix)))}${suffix}`;
137
166
  const body = [heading];
138
167
  if (!narrow && (options.previous || (current.kind === 'cold' && current.reason)))
@@ -175,10 +204,8 @@ export function openHud(options) {
175
204
  const label = ` ${glyph[status]} ${phase.padEnd(8)} ${beam} ${count}`;
176
205
  body.push(label);
177
206
  }
178
- if (!narrow)
179
- body.push('', samples.length
180
- ? ` files/s ${spark(samples, ascii)} ${Math.round(latestRate).toLocaleString('en-US')}`
181
- : ' files/s measuring');
207
+ if (!narrow && elapsed >= minThroughputMs && samples.length >= minThroughputSamples)
208
+ body.push('', ` files/s ${spark(samples, ascii)} ${Math.round(latestRate).toLocaleString('en-US')}`);
182
209
  if (current.file)
183
210
  body.push(` ${ascii ? '>' : '›'} ${safe(current.file)}`);
184
211
  erase();
@@ -215,7 +242,11 @@ export function openHud(options) {
215
242
  observations.shift();
216
243
  }
217
244
  phases.set(event.phase, event);
218
- current = event;
245
+ current = {
246
+ ...event,
247
+ kind: event.kind ?? current?.kind,
248
+ reason: event.reason ?? current?.reason,
249
+ };
219
250
  if (time - drawnAt < 100)
220
251
  return;
221
252
  clearTimeout(timer);
@@ -275,11 +306,29 @@ export function renderHudSummary(input) {
275
306
  sign = ascii ? '-' : '−';
276
307
  comparison = ` ${sign}${duration(Math.abs(diff))} vs last`;
277
308
  }
278
- const count = input.files === undefined ? '' : ` · ${input.files.toLocaleString('en-US')} files`;
309
+ const coverage = success ? input.coverage : undefined;
310
+ const scanned = coverage?.scanned.toLocaleString('en-US');
311
+ const codeFiles = coverage?.codeFiles ?? 0;
312
+ const count = scanned === undefined
313
+ ? ''
314
+ : ` · ${scanned} scanned · ${codeFiles.toLocaleString('en-US')} code files`;
279
315
  const header = `${mark} ${name}${input.kind ? ` ${input.kind}` : ''}${count} · ${duration(input.durationMs)}${comparison}`;
280
- const lines = [color(fit(header, columns), success ? '32' : '31', enabled)];
316
+ const compiler = coverage?.extraction.ok ?? 0;
317
+ const lexical = coverage?.extraction.lexical ?? 0;
318
+ const notInProgram = coverage?.extraction['not-in-program'] ?? 0;
319
+ const errors = coverage?.extraction['parse-error'] ?? 0;
320
+ const indexed = compiler + lexical + notInProgram + errors;
321
+ const fraction = codeFiles > 0 ? indexed / codeFiles : 0;
322
+ const lowCoverage = codeFiles > 0 && fraction < 0.8;
323
+ const highLexical = lexical * 5 > indexed;
324
+ let tone = '32';
325
+ if (lowCoverage || highLexical)
326
+ tone = '33';
327
+ if (!success || (codeFiles > 0 && fraction < 0.3))
328
+ tone = '31';
329
+ const lines = wrap(header, '', columns).map((line) => color(line, tone, enabled));
281
330
  if (input.reason)
282
- lines.push(` ${safe(input.reason)}`);
331
+ lines.push(...wrap(input.reason, ' ', columns));
283
332
  if (input.drift)
284
333
  lines.push(` drift ${safe(input.drift)}`);
285
334
  if (input.activeIndex && !success)
@@ -287,32 +336,54 @@ export function renderHudSummary(input) {
287
336
  const phases = input.phases?.filter((phase) => Number.isFinite(phase.durationMs) && phase.durationMs >= 0) ??
288
337
  [];
289
338
  const totalTime = phases.reduce((sum, phase) => sum + phase.durationMs, 0);
290
- if (success && phases.length && totalTime > 0) {
291
- const size = Math.min(24, columns - 12);
339
+ if (success && phases.length) {
340
+ const extra = Math.max(0, Math.min(24, columns - 12) - phases.length);
292
341
  let spent = 0;
342
+ let used = 0;
293
343
  const segments = phases.map((phase, index) => {
294
- const start = Math.round((spent / totalTime) * size);
295
344
  spent += phase.durationMs;
296
- const end = index === phases.length - 1 ? size : Math.round((spent / totalTime) * size);
297
- const ramp = ['32', '34', '35', '95'];
298
- let stroke = index % 2 ? '─' : '━';
345
+ const end = totalTime > 0 ? Math.round((spent / totalTime) * extra) : 0;
346
+ let stroke = '━';
299
347
  if (ascii)
300
- stroke = index % 2 ? '-' : '=';
301
- return color(stroke.repeat(Math.max(0, end - start)), ramp[index % ramp.length] ?? '32', enabled);
348
+ stroke = phase.phase === 'publish' ? 'u' : (phase.phase[0] ?? '?');
349
+ const segment = color(stroke.repeat(1 + end - used), phaseRamp[index % phaseRamp.length] ?? '34', enabled);
350
+ used = end;
351
+ return segment;
302
352
  });
303
- lines.push('', ` timeline ${segments.join('')}`, ` ${phases.map((phase) => safe(phase.phase)).join(' ')}`);
353
+ lines.push('', ` timeline ${segments.join('')}`, ...wrap(phases
354
+ .map(({ phase, durationMs }) => `${phase} ${durationMs < 1000 ? `${durationMs}ms` : duration(durationMs)}`)
355
+ .join(' · '), ' ', columns));
304
356
  }
305
- if (success && input.throughput?.length)
306
- lines.push(` files/s ${spark(input.throughput, ascii)} ${Math.round(input.throughput[input.throughput.length - 1] ?? 0).toLocaleString('en-US')}`);
357
+ const throughput = input.throughput;
307
358
  if (success &&
308
- input.indexed !== undefined &&
309
- input.outsideScope !== undefined &&
310
- input.indexed + input.outsideScope > 0) {
311
- const percentage = Math.round((100 * input.indexed) / (input.indexed + input.outsideScope));
312
- lines.push(` coverage ${bar(input.indexed / (input.indexed + input.outsideScope), Math.min(16, columns - 15), enabled ? '256' : 'none', ascii)} ${percentage}%`);
313
- lines.push(` ${input.indexed.toLocaleString('en-US')} indexed · ${input.outsideScope.toLocaleString('en-US')} outside scope${input.errors === undefined ? '' : ` · ${input.errors.toLocaleString('en-US')} errors`}`);
359
+ input.durationMs >= minThroughputMs &&
360
+ throughput &&
361
+ throughput.length >= minThroughputSamples)
362
+ lines.push(` files/s ${spark(throughput, ascii)} ${Math.round(throughput.at(-1) ?? 0).toLocaleString('en-US')}`);
363
+ const outsideScope = coverage?.outsideScope ?? 0;
364
+ if (codeFiles > 0) {
365
+ const barLine = bar(fraction, Math.min(16, columns - 16), 'none', ascii);
366
+ lines.push(color(` coverage ${barLine} ${Math.round(fraction * 100)}%`, tone, enabled));
367
+ lines.push(...wrap(`${indexed.toLocaleString('en-US')} indexed · ${outsideScope.toLocaleString('en-US')} outside scope`, ' ', columns));
368
+ const missing = notInProgram === 0 ? '' : ` · ${notInProgram.toLocaleString('en-US')} not in program`;
369
+ lines.push(...wrap(`${compiler.toLocaleString('en-US')} compiler · ${lexical.toLocaleString('en-US')} lexical only · ${errors.toLocaleString('en-US')} errors${missing}`, ' ', columns));
370
+ }
371
+ const hints = [...(input.includeWarnings ?? [])];
372
+ if (lowCoverage) {
373
+ if (outsideScope > 0) {
374
+ hints.push(`${outsideScope.toLocaleString('en-US')} code files outside scope: ei_impact will be partial; check include in ei.config.json`);
375
+ }
376
+ else {
377
+ hints.push(`${(codeFiles - indexed).toLocaleString('en-US')} code files unindexed: ei_impact will be partial; check ei status`);
378
+ }
314
379
  }
315
- if (input.next)
316
- lines.push('', ` ${ascii ? '>' : '›'} ${safe(input.next)}`);
380
+ if (highLexical)
381
+ hints.push(`${lexical.toLocaleString('en-US')} files are not in a TypeScript program: ei_impact will be partial; check tsconfig include / allowJs`);
382
+ if (!lowCoverage && !highLexical && input.next)
383
+ hints.push(input.next);
384
+ if (hints.length > 0)
385
+ lines.push('');
386
+ for (const hint of hints)
387
+ lines.push(...wrap(hint, ascii ? ' > ' : ' › ', columns));
317
388
  return `${lines.map((line) => fitAnsi(line, columns)).join('\n')}\n`;
318
389
  }
@@ -342,9 +342,19 @@ function renderStatus(status, options) {
342
342
  text: `${index.coverage.indexable} indexable · ${index.coverage.scanned} scanned · ${index.coverage.packages} packages`,
343
343
  },
344
344
  { text: `${index.graph.declarations} declarations · ${index.graph.edges} edges` },
345
+ section('extraction', ['ok', 'lexical', 'not-in-program', 'parse-error'].map((name) => ({
346
+ text: `${name} ${(index.graph.extraction[name] ?? 0).toLocaleString('en-US')}`,
347
+ }))),
345
348
  ...index.tsconfigErrors.map((text) => ({ text, role: 'unknown' })),
346
349
  ]
347
350
  : [{ text: status.indexError ?? 'none yet', role: 'unknown' }]),
351
+ ...(index
352
+ ? [
353
+ section('unindexed', Object.entries(index.coverage.reasons)
354
+ .sort(([a, aCount], [b, bCount]) => bCount - aCount || a.localeCompare(b))
355
+ .map(([reason, count]) => ({ text: `${reason} ${count.toLocaleString('en-US')}` }))),
356
+ ]
357
+ : []),
348
358
  section('runtime', [
349
359
  {
350
360
  text: `${status.runtime.kind} ${status.runtime.version} · TypeScript ${status.typescript.ok ? status.typescript.runtime.version : status.typescript.reason}`,
@@ -353,6 +363,7 @@ function renderStatus(status, options) {
353
363
  section('config', [
354
364
  { text: status.config.path ?? 'defaults · run ei init' },
355
365
  ...status.config.errors.map((text) => ({ text, role: 'unknown' })),
366
+ ...(status.includeWarnings ?? []).map((text) => ({ text, role: 'warning' })),
356
367
  ]),
357
368
  section('store', [{ text: index?.path ?? status.cacheDir }]),
358
369
  ];
@@ -5,7 +5,9 @@ import { repositoryLimits } from '../graph/limits.js';
5
5
  import { resolveRiskZones } from '../kernel/config.js';
6
6
  import { isRecord } from '../kernel/guards.js';
7
7
  import { impactConfigHash } from '../indexing/stamp.js';
8
+ import { matchGlob } from '../kernel/glob.js';
8
9
  import { probe } from '../workspace/probe.js';
10
+ import { isCodeKind, kindOf, statVisible } from '../workspace/scan.js';
9
11
  import { FAILURE_FILE, SCHEMA_VERSION, indexPath, openPublished, readFiles, readMeta, readSchemaVersion, } from '../../storage/sqlite.js';
10
12
  import { consumeAuditWarning } from '../audit/log.js';
11
13
  import { isHolderAlive, readLockHolder } from './lock.js';
@@ -72,8 +74,59 @@ function graphOf(db) {
72
74
  limits: repositoryLimits(db),
73
75
  };
74
76
  }
77
+ function presentationOf(db, files) {
78
+ let codeFiles = 0;
79
+ let outsideScope = 0;
80
+ for (const file of files) {
81
+ if (!isCodeKind(kindOf(file.path)))
82
+ continue;
83
+ codeFiles++;
84
+ if (file.reason === 'outside-index-scope')
85
+ outsideScope++;
86
+ }
87
+ return {
88
+ codeFiles,
89
+ outsideScope,
90
+ // Out-of-scope lexical rows serve the name cross-check, not index coverage.
91
+ extraction: grouped(db, `SELECT fi.extraction AS k, COUNT(*) AS n FROM file_index fi
92
+ JOIN files f ON f.path = fi.file
93
+ WHERE f.status IN ('indexable', 'orphan') GROUP BY k`),
94
+ };
95
+ }
96
+ /** Warn (strictly M > 2*N) when a positive `dir/*` include matches far fewer files than `dir/**`. */
97
+ function includeWarningsOf(include, paths) {
98
+ const warnings = [];
99
+ for (const pattern of include) {
100
+ if (pattern.startsWith('!') || !pattern.endsWith('/*'))
101
+ continue;
102
+ const wide = `${pattern}*`;
103
+ let narrow = 0;
104
+ let broad = 0;
105
+ for (const path of paths) {
106
+ if (matchGlob(pattern, path))
107
+ narrow++;
108
+ if (matchGlob(wide, path))
109
+ broad++;
110
+ }
111
+ if (broad > 2 * narrow) {
112
+ warnings.push(`include "${pattern}" matches ${narrow.toLocaleString('en-US')} files; "${wide}" would match ${broad.toLocaleString('en-US')}`);
113
+ }
114
+ }
115
+ return warnings;
116
+ }
117
+ /** Current visible paths: the stored census patched by drift, else one disk listing. */
118
+ async function visiblePaths(root, files, drift) {
119
+ if (files !== null && drift !== null) {
120
+ const gone = new Set(drift.deleted);
121
+ return [
122
+ ...files.filter((file) => !gone.has(file.path)).map((file) => file.path),
123
+ ...drift.added,
124
+ ];
125
+ }
126
+ return (await statVisible(root)).entries.map((entry) => entry.path);
127
+ }
75
128
  /** The published index, read-only; null when none exists. Throws when it cannot be read. */
76
- function readIndex(cacheDir) {
129
+ function readIndex(cacheDir, presentation) {
77
130
  const db = openPublished(cacheDir);
78
131
  if (db === null)
79
132
  return null;
@@ -106,6 +159,7 @@ function readIndex(cacheDir) {
106
159
  },
107
160
  },
108
161
  files,
162
+ ...(current && presentation ? { presentation: presentationOf(db, files) } : {}),
109
163
  };
110
164
  }
111
165
  finally {
@@ -177,16 +231,31 @@ export async function workspaceStatus(start, options = {}) {
177
231
  let index = null;
178
232
  let indexError = null;
179
233
  let drift = null;
234
+ let census = null;
235
+ let presentation;
180
236
  try {
181
- const read = readIndex(workspace.cacheDir);
237
+ const read = readIndex(workspace.cacheDir, options.presentation === 'index');
182
238
  index = read?.info ?? null;
239
+ presentation = read?.presentation;
183
240
  if (read && read.info.schemaVersion === SCHEMA_VERSION) {
241
+ census = read.files;
184
242
  drift = await probe(workspace.root, impact, read.files);
185
243
  }
186
244
  }
187
245
  catch (error) {
188
246
  indexError = error instanceof Error ? error.message : String(error);
189
247
  }
248
+ let includeWarnings = [];
249
+ // Reuses the census patched by drift; walks disk only when no probe result exists.
250
+ if (options.presentation !== undefined &&
251
+ impact.include.some((pattern) => !pattern.startsWith('!') && pattern.endsWith('/*'))) {
252
+ try {
253
+ includeWarnings = includeWarningsOf(impact.include, await visiblePaths(workspace.root, census, drift));
254
+ }
255
+ catch {
256
+ includeWarnings = []; // a failed scan must not break an otherwise valid status
257
+ }
258
+ }
190
259
  const holder = readLockHolder(workspace.cacheDir);
191
260
  const zones = resolveRiskZones(workspace.config.riskZones).map((zone) => zone.zone);
192
261
  const partial = {
@@ -211,6 +280,8 @@ export async function workspaceStatus(start, options = {}) {
211
280
  fix: degraded?.[1] ?? null,
212
281
  ...partial,
213
282
  ...(auditWarning !== null ? { auditWarning } : {}),
283
+ ...(presentation !== undefined ? { presentation } : {}),
284
+ ...(includeWarnings.length > 0 ? { includeWarnings } : {}),
214
285
  };
215
286
  }
216
287
  /** DESIGN §14: the engine's peak memory, as of the last build. */