@krisada-m/ksd-intelligence 0.0.0-stage → 1.0.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 (110) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +167 -2
  3. package/dist/adapters/agy/skills.js +252 -0
  4. package/dist/adapters/cli/check-changed.js +3 -0
  5. package/dist/adapters/cli/main.js +1002 -0
  6. package/dist/adapters/cli/policy-bin.js +10 -0
  7. package/dist/adapters/cli/review-verdict.js +3 -0
  8. package/dist/adapters/omp/extension.js +893 -0
  9. package/dist/adapters/omp/skills.js +130 -0
  10. package/dist/adapters/ui/hud.js +318 -0
  11. package/dist/adapters/ui/tree.js +460 -0
  12. package/dist/core/audit/index.js +2 -0
  13. package/dist/core/audit/log.js +505 -0
  14. package/dist/core/audit/summary.js +188 -0
  15. package/dist/core/changes/changes.js +591 -0
  16. package/dist/core/changes/git.js +266 -0
  17. package/dist/core/changes/plan.js +109 -0
  18. package/dist/core/changes/render.js +356 -0
  19. package/dist/core/engine/build.js +178 -0
  20. package/dist/core/engine/child.js +389 -0
  21. package/dist/core/engine/host.js +206 -0
  22. package/dist/core/engine/lock.js +133 -0
  23. package/dist/core/engine/protocol.js +43 -0
  24. package/dist/core/engine/runtime.js +44 -0
  25. package/dist/core/engine/status.js +381 -0
  26. package/dist/core/engine/typescript.js +194 -0
  27. package/dist/core/engine/workspace.js +72 -0
  28. package/dist/core/graph/graph.js +127 -0
  29. package/dist/core/graph/limits.js +16 -0
  30. package/dist/core/impact/query.js +1292 -0
  31. package/dist/core/impact/render.js +590 -0
  32. package/dist/core/impact/session.js +694 -0
  33. package/dist/core/indexing/declarations.js +455 -0
  34. package/dist/core/indexing/differential.js +345 -0
  35. package/dist/core/indexing/doctor.js +120 -0
  36. package/dist/core/indexing/indexer.js +792 -0
  37. package/dist/core/indexing/keys.js +451 -0
  38. package/dist/core/indexing/lexical.js +212 -0
  39. package/dist/core/indexing/packages.js +57 -0
  40. package/dist/core/indexing/program.js +171 -0
  41. package/dist/core/indexing/resolve.js +1004 -0
  42. package/dist/core/indexing/stamp.js +52 -0
  43. package/dist/core/indexing/surface.js +335 -0
  44. package/dist/core/indexing/ui-progress.js +37 -0
  45. package/dist/core/indexing/verify.js +76 -0
  46. package/dist/core/kernel/config.js +383 -0
  47. package/dist/core/kernel/glob.js +105 -0
  48. package/dist/core/kernel/guards.js +4 -0
  49. package/dist/core/kernel/types.js +3 -0
  50. package/dist/core/kernel/verdict.js +142 -0
  51. package/dist/core/knowledge/anchors.js +139 -0
  52. package/dist/core/knowledge/knowledge.js +95 -0
  53. package/dist/core/knowledge/learning.js +102 -0
  54. package/dist/core/knowledge/render.js +76 -0
  55. package/dist/core/knowledge/store.js +109 -0
  56. package/dist/core/knowledge/yaml.js +87 -0
  57. package/dist/core/search/lexical.js +382 -0
  58. package/dist/core/search/render.js +98 -0
  59. package/dist/core/search/segments.js +118 -0
  60. package/dist/core/verify/parse.js +127 -0
  61. package/dist/core/verify/render.js +67 -0
  62. package/dist/core/verify/report.js +40 -0
  63. package/dist/core/verify/revision.js +79 -0
  64. package/dist/core/verify/run.js +117 -0
  65. package/dist/core/verify/store.js +66 -0
  66. package/dist/core/verify/verify.js +173 -0
  67. package/dist/core/workspace/init.js +267 -0
  68. package/dist/core/workspace/probe.js +56 -0
  69. package/dist/core/workspace/scan.js +420 -0
  70. package/dist/index.js +20 -0
  71. package/dist/policy/change-scope.js +500 -0
  72. package/dist/policy/check-changed.js +40 -0
  73. package/dist/policy/config.js +106 -0
  74. package/dist/policy/dist/policy.d.ts +17 -0
  75. package/dist/policy/dist/policy.js +147 -0
  76. package/dist/policy/dist/runtime.d.ts +40 -0
  77. package/dist/policy/dist/runtime.js +75 -0
  78. package/dist/policy/dist/sdlc.d.ts +7 -0
  79. package/dist/policy/dist/sdlc.js +27 -0
  80. package/dist/policy/eslint-rules/index.js +107 -0
  81. package/dist/policy/index.d.ts +2 -0
  82. package/dist/policy/index.js +241 -0
  83. package/dist/policy/package.json +33 -0
  84. package/dist/policy/policy.d.ts +2 -0
  85. package/dist/policy/policy.js +2 -0
  86. package/dist/policy/review-verdict.js +262 -0
  87. package/dist/policy/sdlc.js +2 -0
  88. package/dist/storage/records.js +245 -0
  89. package/dist/storage/sqlite.js +314 -0
  90. package/dist/workflow/catalog.js +69 -0
  91. package/dist/workflow/classify.js +55 -0
  92. package/dist/workflow/loader.js +140 -0
  93. package/dist/workflow/packs.js +469 -0
  94. package/dist/workflow/registry.js +359 -0
  95. package/dist/workflow/render.js +61 -0
  96. package/dist/workflow/router.js +141 -0
  97. package/dist/workflow/sources.js +229 -0
  98. package/dist/workflow/types.js +44 -0
  99. package/dist/workflow/updates.js +532 -0
  100. package/package.json +74 -4
  101. package/scripts/agy-mcp.mjs +27 -0
  102. package/scripts/mcp/stdio.mjs +304 -0
  103. package/scripts/mcp/tools.mjs +451 -0
  104. package/skills/ksd-intelligence/SKILL.md +54 -0
  105. package/skills/matt-sdlc/SKILL.md +42 -0
  106. package/skills/osmani-quality/SKILL.md +38 -0
  107. package/skills/poteto-mode/SKILL.md +40 -0
  108. package/skills/pstack-analysis/SKILL.md +36 -0
  109. package/skills.lock.json +71 -0
  110. package/skills.registry.json +181 -0
@@ -0,0 +1,1002 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync } from 'node:fs';
3
+ import { rm } from 'node:fs/promises';
4
+ import { basename } from 'node:path';
5
+ import { parseArgs } from 'node:util';
6
+ import { auditFieldsForChanges, auditFieldsForImpact, auditFieldsForSearch, auditFieldsForWorkflow, clearAuditState, consumeAuditWarning, parseSince, recordAudit, renderAuditSummary, summarizeAudit, } from '../../core/audit/index.js';
7
+ import { buildIndex, doctorDeep } from '../../core/engine/build.js';
8
+ import { isHolderAlive, readLockHolder } from '../../core/engine/lock.js';
9
+ import { homeRelative, renderStatus, workspaceStatus } from '../../core/engine/status.js';
10
+ import { checkTypescriptRuntime, engineVersion, pinnedTypescriptVersion, setupTypescriptRuntime, } from '../../core/engine/typescript.js';
11
+ import { loadWorkspace, resolveWorkspaceCache } from '../../core/engine/workspace.js';
12
+ import { readBuildHistory } from '../../core/indexing/ui-progress.js';
13
+ import { isRecord } from '../../core/kernel/guards.js';
14
+ import { runChanges } from '../../core/changes/changes.js';
15
+ import { renderChangesOutcome } from '../../core/changes/render.js';
16
+ import { changesVerificationNote, renderVerifyOutcome } from '../../core/verify/render.js';
17
+ import { loadVerificationState, runVerification, validateVerifyInput, } from '../../core/verify/verify.js';
18
+ import { impactDetails, renderImpact } from '../../core/impact/render.js';
19
+ import { ImpactSession } from '../../core/impact/session.js';
20
+ import { runSearch, validateSearchInput } from '../../core/search/lexical.js';
21
+ import { renderSearchOutcome } from '../../core/search/render.js';
22
+ import { withAnchorIndex, snapshot } from '../../core/knowledge/knowledge.js';
23
+ import { learningLabel, quoteClaim, renderLearningList } from '../../core/knowledge/render.js';
24
+ import { approveProposal, rejectProposal, reviewLearning } from '../../core/knowledge/store.js';
25
+ import { initProject } from '../../core/workspace/init.js';
26
+ import { discoverAgySkills } from '../agy/skills.js';
27
+ import { discoverOmpSkills } from '../omp/skills.js';
28
+ import { rootsFromEnv } from '../../workflow/catalog.js';
29
+ import { prepareWorkflow } from '../../workflow/loader.js';
30
+ import { listSkillPacks } from '../../workflow/packs.js';
31
+ import { defaultRegistryPath, readRegistry, validateRegistryConsistency, } from '../../workflow/registry.js';
32
+ import { renderWorkflow } from '../../workflow/render.js';
33
+ import { routeTask } from '../../workflow/router.js';
34
+ import { checkUpstreamUpdates, publishStagedUpdate, rollbackSkillUpdate, stageSkillUpdate, } from '../../workflow/updates.js';
35
+ import { checkSources, defaultLockPath, formatReports, readLock, reportStatus, writeLock, } from '../../workflow/sources.js';
36
+ import { WorkflowError } from '../../workflow/types.js';
37
+ import { openHud, renderHudSummary } from '../ui/hud.js';
38
+ import { renderResultView, terminalViewOptions } from '../ui/tree.js';
39
+ function doctorPassed(report) {
40
+ const differences = report.differences;
41
+ const count = typeof differences === 'object' && differences !== null && 'count' in differences
42
+ ? differences.count
43
+ : 1;
44
+ const differential = report.differential;
45
+ const misses = typeof differential === 'object' &&
46
+ differential !== null &&
47
+ 'misses' in differential &&
48
+ Array.isArray(differential.misses)
49
+ ? differential.misses.length
50
+ : 0;
51
+ return count === 0 && misses === 0;
52
+ }
53
+ function counterNote(report) {
54
+ const counters = report.counterDifferences;
55
+ const count = typeof counters === 'object' && counters !== null && 'count' in counters ? counters.count : 0;
56
+ return typeof count === 'number' && count > 0
57
+ ? `INFO ${count} files have use counters that differ from the cold rebuild (statistics only, not a failure: TypeScript infers lazily, so they depend on checking order)`
58
+ : '';
59
+ }
60
+ function renderDoctor(report) {
61
+ return [
62
+ doctorPassed(report) ? 'DOCTOR ok' : 'DOCTOR differences found',
63
+ counterNote(report),
64
+ JSON.stringify({
65
+ differences: report.differences,
66
+ counterDifferences: report.counterDifferences,
67
+ differential: report.differential,
68
+ }, null, 2),
69
+ ]
70
+ .filter((line) => line !== '')
71
+ .join('\n');
72
+ }
73
+ const USAGE = `usage:
74
+ main.js init [--root <path>] [--force] [--dry-run] [--json]
75
+ main.js setup [--check] (installs the pinned TypeScript runtime; --check only verifies)
76
+ main.js index [--root <path>] [--full] [--json] (update the index from the working tree; --full rebuilds cold)
77
+ main.js impact <target…> [--depth <n>] [--root <path>] [--json] (who depends on 1–5 targets)
78
+ main.js changes [--base <ref>] [--depth <n>] [--planned <target>]... [--root <path>] [--json] (impact of uncommitted changes)
79
+ main.js search <query> [--limit <n>] [--root <path>] [--json] (find declarations by words or identifier)
80
+ main.js learning list [--status <state>] | show <id> | approve <id> | review <id> | reject <id> [--root <path>] [--json] (owner commands for .ksd/learnings)
81
+ main.js verify <check> | --report <name> [--root <path>] [--json] (run an allowlisted check or read a result file; needs verification.enabled)
82
+ main.js doctor --deep [--root <path>] [--differential <n|all>] [--json] (cold rebuild diffed against the index)
83
+ main.js status [--root <path>] [--json] (index, coverage, runtime, TypeScript, store, lock)
84
+ main.js audit [--since <7d|24h|30m|ISO>] [--root <path>] [--json] (summarize audit.jsonl)
85
+ main.js cache clear [--root <path>] [--json] (remove index and audit cache for this repository)
86
+ main.js route --task "..." [--stage plan|investigate|implement|verify|review|ship] [--risk normal|high] [--type bug|feature|refactor|security|performance|ui] [--poteto-mode]
87
+ main.js load --task "..." [same options] (needs checkouts; fails closed)
88
+ main.js skills list|check [--platform agy|omp] [--root <path>] [--profile <name>] [--detect-host] [--json]
89
+ main.js skills diff [--lock <path>] [--registry <path>] [--json]
90
+ main.js skills sync [--stage] [--state-dir <path>] [--lock <path>] [--registry <path>] [--json]
91
+ main.js skills publish --stage-id <id> --approve [--state-dir <path>] [--lock <path>] [--registry <path>] [--json]
92
+ main.js skills rollback [--release <id>] [--state-dir <path>] [--lock <path>] [--registry <path>] [--json]
93
+ main.js sources check [--write] [--lock <path>] (never clones or fetches)
94
+ main.js mcp --root <path> [--workflow] (local stdio MCP server for Antigravity)`;
95
+ async function tryResolveCacheCli(root) {
96
+ try {
97
+ const info = await resolveWorkspaceCache(root ?? process.cwd());
98
+ return { root: info.root, cacheDir: info.cacheDir };
99
+ }
100
+ catch {
101
+ return null;
102
+ }
103
+ }
104
+ async function duringHud(hud, run) {
105
+ if (hud === undefined)
106
+ return run();
107
+ const interrupt = () => {
108
+ hud.close();
109
+ process.exit(130);
110
+ };
111
+ process.once('SIGINT', interrupt);
112
+ try {
113
+ return await run();
114
+ }
115
+ finally {
116
+ process.removeListener('SIGINT', interrupt);
117
+ hud.close();
118
+ }
119
+ }
120
+ function phaseTimes(raw) {
121
+ if (!isRecord(raw))
122
+ return [];
123
+ return Object.entries(raw).flatMap(([phase, durationMs]) => typeof durationMs === 'number' && Number.isFinite(durationMs) && durationMs >= 0
124
+ ? [{ phase, durationMs }]
125
+ : []);
126
+ }
127
+ const LEARNING_STATES = ['active', 'needs-review', 'orphaned', 'superseded'];
128
+ // Owner commands. approve and review are the only code paths that write `.ksd/learnings/`.
129
+ async function runLearningCommand(sub, id, root, status, json) {
130
+ const workspace = await loadWorkspace(root ?? process.cwd());
131
+ const session = new ImpactSession(workspace, {
132
+ waitAfterExpiry: true,
133
+ onProgress: (message) => console.error(`ei learning: ${message}`),
134
+ });
135
+ if (status !== undefined && !LEARNING_STATES.includes(status)) {
136
+ console.error(`ei learning: --status must be one of ${LEARNING_STATES.join(', ')}`);
137
+ return 2;
138
+ }
139
+ if (sub === 'list' || sub === 'show') {
140
+ const snap = await withAnchorIndex(session, (index) => snapshot(workspace, index));
141
+ const keep = (entry) => (status === undefined || entry.state === status) &&
142
+ (sub === 'list' || entry.learning.id === id);
143
+ const learnings = snap.learnings.filter(keep);
144
+ const proposals = snap.proposals.filter(keep);
145
+ if (sub === 'show' && learnings.length + proposals.length === 0) {
146
+ console.error(`ei learning: no learning or proposal "${id ?? ''}"`);
147
+ return 1;
148
+ }
149
+ console.log(json
150
+ ? JSON.stringify({ learnings, proposals, problems: snap.problems }, null, 2)
151
+ : renderLearningList({
152
+ scope: sub === 'show' ? (id ?? '') : 'all',
153
+ learnings,
154
+ proposals,
155
+ problems: snap.problems,
156
+ }));
157
+ return 0;
158
+ }
159
+ if (id === undefined) {
160
+ console.error(USAGE);
161
+ return 2;
162
+ }
163
+ try {
164
+ if (sub === 'approve') {
165
+ const learning = approveProposal(workspace.root, workspace.cacheDir, id);
166
+ console.log(`APPROVED ${learning.id} → .ksd/learnings/${learning.id}.yaml (owner-confirmed)\n > ${quoteClaim(learning.claim)}`);
167
+ return 0;
168
+ }
169
+ if (sub === 'reject') {
170
+ rejectProposal(workspace.cacheDir, id);
171
+ console.log(`REJECTED ${id} (proposal removed)`);
172
+ return 0;
173
+ }
174
+ if (sub === 'review') {
175
+ const snap = await withAnchorIndex(session, (index) => snapshot(workspace, index));
176
+ const entry = snap.learnings.find((candidate) => candidate.learning.id === id);
177
+ if (entry === undefined)
178
+ throw new Error(`no learning "${id}" in .ksd/learnings`);
179
+ if (entry.currentHash === undefined) {
180
+ throw new Error(`${id} cannot be re-anchored: ${learningLabel(entry)}`);
181
+ }
182
+ const learning = reviewLearning(workspace.root, id, entry.currentHash);
183
+ console.log(`REVIEWED ${learning.id} — re-anchored to the current ${learning.anchor.key}`);
184
+ return 0;
185
+ }
186
+ }
187
+ catch (error) {
188
+ console.error(`ei learning: ${error instanceof Error ? error.message : String(error)}`);
189
+ return 1;
190
+ }
191
+ console.error(USAGE);
192
+ return 2;
193
+ }
194
+ async function run(argv) {
195
+ const { values, positionals } = parseArgs({
196
+ args: argv,
197
+ allowPositionals: true,
198
+ options: {
199
+ help: { type: 'boolean', short: 'h' },
200
+ root: { type: 'string' },
201
+ force: { type: 'boolean' },
202
+ 'dry-run': { type: 'boolean' },
203
+ json: { type: 'boolean' },
204
+ plain: { type: 'boolean' },
205
+ all: { type: 'boolean' },
206
+ task: { type: 'string' },
207
+ stage: { type: 'string' },
208
+ risk: { type: 'string' },
209
+ type: { type: 'string' },
210
+ 'poteto-mode': { type: 'boolean' },
211
+ platform: { type: 'string' },
212
+ profile: { type: 'string' },
213
+ 'detect-host': { type: 'boolean' },
214
+ registry: { type: 'string' },
215
+ 'state-dir': { type: 'string' },
216
+ 'stage-id': { type: 'string' },
217
+ release: { type: 'string' },
218
+ approve: { type: 'boolean' },
219
+ write: { type: 'boolean' },
220
+ lock: { type: 'string' },
221
+ check: { type: 'boolean' },
222
+ full: { type: 'boolean' },
223
+ deep: { type: 'boolean' },
224
+ differential: { type: 'string' },
225
+ depth: { type: 'string' },
226
+ limit: { type: 'string' },
227
+ base: { type: 'string' },
228
+ planned: { type: 'string', multiple: true },
229
+ since: { type: 'string' },
230
+ status: { type: 'string' },
231
+ report: { type: 'string' },
232
+ workflow: { type: 'boolean' },
233
+ },
234
+ });
235
+ if (values.help) {
236
+ console.log(USAGE.replaceAll('main.js ', 'ei '));
237
+ return 0;
238
+ }
239
+ const [command, sub] = positionals;
240
+ const lockPath = values.lock ?? defaultLockPath();
241
+ const registryPath = values.registry ?? defaultRegistryPath();
242
+ const view = terminalViewOptions({
243
+ env: process.env,
244
+ columns: process.stdout.columns || 80,
245
+ isTTY: process.stdout.isTTY === true,
246
+ plain: values.plain === true,
247
+ json: values.json === true,
248
+ all: values.all === true,
249
+ });
250
+ const show = (input, plain) => {
251
+ console.log(view === undefined ? plain() : renderResultView(input, view).join('\n'));
252
+ };
253
+ const hudOptions = {
254
+ stream: process.stderr,
255
+ env: process.env,
256
+ plain: values.plain === true,
257
+ json: values.json === true,
258
+ };
259
+ if (command === 'setup') {
260
+ const version = pinnedTypescriptVersion();
261
+ const started = performance.now();
262
+ const check = values.check === true;
263
+ const hud = check
264
+ ? undefined
265
+ : openHud({ ...hudOptions, command: 'setup', repo: basename(process.cwd()) });
266
+ const result = await duringHud(hud, () => check
267
+ ? checkTypescriptRuntime({ version })
268
+ : setupTypescriptRuntime({ version, onHudProgress: hud?.update }));
269
+ if (hud !== undefined && view !== undefined) {
270
+ console.log(renderHudSummary({
271
+ ...view,
272
+ command: 'setup',
273
+ outcome: result.ok ? 'completed' : 'failed',
274
+ durationMs: performance.now() - started,
275
+ reason: result.ok
276
+ ? `typescript ${result.runtime.version} · ${result.runtime.path} · sha256 ${result.sha256}`
277
+ : result.reason,
278
+ next: result.ok ? 'ready for ei index' : result.fix,
279
+ }));
280
+ return result.ok ? 0 : 1;
281
+ }
282
+ if (!result.ok) {
283
+ console.log(`typescript ${version}: degraded (${result.reason}) · ${result.fix}`);
284
+ return 1;
285
+ }
286
+ console.log(`typescript ${result.runtime.version}: ready · ${result.runtime.path} · sha256 ${result.sha256}`);
287
+ return 0;
288
+ }
289
+ if (command === 'status') {
290
+ if (process.env.EI_DISABLED === '1') {
291
+ console.log('STATUS disabled (EI_DISABLED)');
292
+ return 0;
293
+ }
294
+ const started = performance.now();
295
+ const status = await workspaceStatus(values.root ?? process.cwd());
296
+ recordAudit(status.cacheDir, {
297
+ ts: new Date().toISOString(),
298
+ tool: 'ei_status',
299
+ adapter: 'cli',
300
+ outcome: 'result',
301
+ ms: performance.now() - started,
302
+ engine: engineVersion(),
303
+ ...(status.typescript.ok ? { ts_version: status.typescript.runtime.version } : {}),
304
+ statusState: status.state,
305
+ }, { root: status.root });
306
+ const extraWarning = consumeAuditWarning(status.cacheDir);
307
+ if (extraWarning !== null)
308
+ status.auditWarning = extraWarning;
309
+ if (values.json === true)
310
+ console.log(JSON.stringify(status, null, 2));
311
+ else
312
+ show({ kind: 'status', value: status }, () => renderStatus(status));
313
+ return status.state === 'ready' ? 0 : 1;
314
+ }
315
+ if (command === 'audit') {
316
+ let sinceMs;
317
+ if (values.since !== undefined) {
318
+ const parsed = parseSince(values.since);
319
+ if (parsed === null) {
320
+ console.error(`INVALID_INPUT: invalid --since ${JSON.stringify(values.since)}; expected e.g. 7d, 24h, 30m, or ISO timestamp`);
321
+ return 2;
322
+ }
323
+ sinceMs = parsed;
324
+ }
325
+ const { cacheDir } = await resolveWorkspaceCache(values.root ?? process.cwd());
326
+ const summary = summarizeAudit(cacheDir, {
327
+ ...(sinceMs !== undefined ? { sinceMs, sinceLabel: values.since } : {}),
328
+ });
329
+ if (values.json === true)
330
+ console.log(JSON.stringify(summary, null, 2));
331
+ else
332
+ show({ kind: 'audit', value: summary }, () => renderAuditSummary(summary));
333
+ return 0;
334
+ }
335
+ if (command === 'cache') {
336
+ if (sub !== 'clear') {
337
+ console.error(USAGE);
338
+ return 2;
339
+ }
340
+ const { repoId, cacheDir } = await resolveWorkspaceCache(values.root ?? process.cwd());
341
+ const holder = readLockHolder(cacheDir);
342
+ if (holder !== null && isHolderAlive(holder)) {
343
+ if (values.json === true) {
344
+ console.log(JSON.stringify({ cleared: false, locked: true, repoId, pid: holder.pid }, null, 2));
345
+ }
346
+ else {
347
+ console.error(`CACHE LOCKED ${repoId} · build lock held by pid ${holder.pid} since ${holder.startedAt}`);
348
+ }
349
+ return 1;
350
+ }
351
+ const existed = existsSync(cacheDir);
352
+ await rm(cacheDir, { recursive: true, force: true });
353
+ clearAuditState(cacheDir);
354
+ if (values.json === true) {
355
+ console.log(JSON.stringify({ cleared: true, existed, repoId, cacheDir }, null, 2));
356
+ }
357
+ else {
358
+ console.log(existed
359
+ ? `CACHE CLEARED ${repoId} · removed ${homeRelative(cacheDir)}`
360
+ : `CACHE CLEARED ${repoId} · nothing to clear (${homeRelative(cacheDir)})`);
361
+ }
362
+ return 0;
363
+ }
364
+ if (command === 'index') {
365
+ const workspace = await loadWorkspace(values.root ?? process.cwd());
366
+ const started = performance.now();
367
+ const previous = view !== undefined && process.stderr.isTTY
368
+ ? readBuildHistory(workspace.cacheDir).at(-1)
369
+ : undefined;
370
+ const hud = openHud({
371
+ ...hudOptions,
372
+ command: 'index',
373
+ repo: basename(workspace.root),
374
+ previous,
375
+ });
376
+ const outcome = await duringHud(hud, () => buildIndex(workspace, {
377
+ full: values.full === true,
378
+ onProgress: hud === undefined ? (message) => console.error(`ei index: ${message}`) : undefined,
379
+ onHudProgress: hud?.update,
380
+ }));
381
+ if (!outcome.ok) {
382
+ if (hud !== undefined && view !== undefined) {
383
+ const status = await workspaceStatus(workspace.root);
384
+ console.log(renderHudSummary({
385
+ ...view,
386
+ command: 'index',
387
+ outcome: 'failed',
388
+ durationMs: performance.now() - started,
389
+ reason: `${outcome.code}: ${outcome.message}`,
390
+ activeIndex: status.index === null ? 'none' : homeRelative(status.index.path),
391
+ next: outcome.fix,
392
+ }));
393
+ return 1;
394
+ }
395
+ console.log(`INDEX ${outcome.code}: ${outcome.message} · ${outcome.fix}`);
396
+ return 1;
397
+ }
398
+ if (values.json === true) {
399
+ console.log(JSON.stringify(outcome.value, null, 2));
400
+ return outcome.value.action === 'failed' ? 1 : 0;
401
+ }
402
+ const durationMs = performance.now() - started;
403
+ const seconds = (durationMs / 1000).toFixed(2);
404
+ const { action, reason } = outcome.value;
405
+ if (hud !== undefined &&
406
+ view !== undefined &&
407
+ (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
+ : [];
412
+ const actionLabel = action === 'cold' ? 'built' : 'updated';
413
+ const activeIndex = index === null ? 'none' : homeRelative(index.path);
414
+ const drift = isRecord(outcome.value.drift) ? outcome.value.drift : {};
415
+ const coverage = index?.coverage;
416
+ const extraction = index?.graph.extraction;
417
+ console.log(renderHudSummary({
418
+ ...view,
419
+ command: 'index',
420
+ outcome: action === 'failed' || action === 'unchanged' ? action : actionLabel,
421
+ kind: action === 'cold' || action === 'update' ? action : undefined,
422
+ durationMs,
423
+ previous,
424
+ reason: problems.length === 0 ? String(reason) : `${String(reason)}: ${problems.join('; ')}`,
425
+ 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
430
+ ? undefined
431
+ : (extraction['parse-error'] ?? 0) + (extraction['not-in-program'] ?? 0),
432
+ drift: action === 'update'
433
+ ? `+${String(drift.added)} · ~${String(drift.changed)} · −${String(drift.deleted)}`
434
+ : undefined,
435
+ activeIndex: action === 'failed' ? activeIndex : undefined,
436
+ throughput: hud.throughput,
437
+ next: action === 'failed' ? 'check ei status before retrying' : 'ready for ei impact',
438
+ }));
439
+ return action === 'failed' ? 1 : 0;
440
+ }
441
+ console.log(`INDEX ${String(action)} in ${seconds} s (${String(reason)})`);
442
+ console.log(renderStatus(await workspaceStatus(workspace.root)));
443
+ return action === 'failed' ? 1 : 0;
444
+ }
445
+ if (command === 'impact') {
446
+ const started = performance.now();
447
+ const targets = positionals.slice(1);
448
+ const rawDepth = values.depth;
449
+ const depth = rawDepth === undefined ? undefined : Number.parseInt(rawDepth, 10);
450
+ if (targets.length < 1 ||
451
+ targets.length > 5 ||
452
+ (rawDepth !== undefined &&
453
+ (depth === undefined ||
454
+ !Number.isInteger(depth) ||
455
+ String(depth) !== rawDepth.trim() ||
456
+ depth < 1 ||
457
+ depth > 10))) {
458
+ const cache = await tryResolveCacheCli(values.root);
459
+ if (cache !== null) {
460
+ recordAudit(cache.cacheDir, {
461
+ ts: new Date().toISOString(),
462
+ tool: 'ei_impact',
463
+ adapter: 'cli',
464
+ outcome: 'failure',
465
+ ms: performance.now() - started,
466
+ engine: engineVersion(),
467
+ code: 'INVALID_INPUT',
468
+ codes: ['INVALID_INPUT'],
469
+ ...(targets.length > 0 ? { targets } : {}),
470
+ }, { root: cache.root });
471
+ }
472
+ const batch = {
473
+ answers: [
474
+ {
475
+ input: targets[0] ?? '',
476
+ kind: 'failure',
477
+ code: 'INVALID_INPUT',
478
+ message: 'provide 1–5 targets and depth 1–10',
479
+ },
480
+ ],
481
+ index: { state: 'fresh', updatedFiles: 0, driftedFiles: [] },
482
+ };
483
+ if (values.json === true)
484
+ console.log(JSON.stringify(batch.answers[0], null, 2));
485
+ else
486
+ show({ kind: 'impact', value: batch }, () => renderImpact(batch));
487
+ return 2;
488
+ }
489
+ const workspace = await loadWorkspace(values.root ?? process.cwd());
490
+ const session = new ImpactSession(workspace, {
491
+ waitAfterExpiry: true,
492
+ onProgress: (message) => console.error(`ei impact: ${message}`),
493
+ });
494
+ const batch = await session.query(targets, depth);
495
+ recordAudit(workspace.cacheDir, {
496
+ ts: new Date().toISOString(),
497
+ tool: 'ei_impact',
498
+ adapter: 'cli',
499
+ outcome: 'result',
500
+ ms: performance.now() - started,
501
+ engine: engineVersion(),
502
+ ...auditFieldsForImpact(batch, engineVersion()),
503
+ }, { root: workspace.root });
504
+ const details = values.json === true ? impactDetails(batch) : undefined;
505
+ if (details !== undefined) {
506
+ console.log(JSON.stringify(details.length === 1 ? details[0] : details, null, 2));
507
+ }
508
+ else {
509
+ show({ kind: 'impact', value: batch }, () => renderImpact(batch));
510
+ }
511
+ return batch.answers.some((answer) => answer.kind === 'failure') ? 1 : 0;
512
+ }
513
+ if (command === 'changes') {
514
+ if (process.env.EI_DISABLED === '1') {
515
+ console.log('CHANGES disabled (EI_DISABLED)');
516
+ return 0;
517
+ }
518
+ const started = performance.now();
519
+ const rawDepth = values.depth;
520
+ const depth = rawDepth === undefined ? undefined : Number.parseInt(rawDepth, 10);
521
+ if (rawDepth !== undefined &&
522
+ (depth === undefined ||
523
+ !Number.isInteger(depth) ||
524
+ String(depth) !== rawDepth.trim() ||
525
+ depth < 1 ||
526
+ depth > 10)) {
527
+ const cache = await tryResolveCacheCli(values.root);
528
+ if (cache !== null) {
529
+ recordAudit(cache.cacheDir, {
530
+ ts: new Date().toISOString(),
531
+ tool: 'ei_changes',
532
+ adapter: 'cli',
533
+ outcome: 'failure',
534
+ ms: performance.now() - started,
535
+ engine: engineVersion(),
536
+ code: 'INVALID_INPUT',
537
+ codes: ['INVALID_INPUT'],
538
+ }, { root: cache.root });
539
+ }
540
+ const outcome = {
541
+ kind: 'failure',
542
+ code: 'INVALID_INPUT',
543
+ message: 'depth must be an integer 1–10',
544
+ };
545
+ if (values.json === true)
546
+ console.log(JSON.stringify(outcome, null, 2));
547
+ else
548
+ show({ kind: 'changes', value: outcome }, () => renderChangesOutcome(outcome));
549
+ return 2;
550
+ }
551
+ const workspace = await loadWorkspace(values.root ?? process.cwd());
552
+ const session = new ImpactSession(workspace, {
553
+ waitAfterExpiry: true,
554
+ onProgress: (message) => console.error(`ei changes: ${message}`),
555
+ });
556
+ const outcome = await runChanges(session, {
557
+ base: values.base,
558
+ depth,
559
+ planned: values.planned,
560
+ });
561
+ recordAudit(workspace.cacheDir, {
562
+ ts: new Date().toISOString(),
563
+ tool: 'ei_changes',
564
+ adapter: 'cli',
565
+ outcome: outcome.kind,
566
+ ms: performance.now() - started,
567
+ engine: engineVersion(),
568
+ ...auditFieldsForChanges(outcome, engineVersion()),
569
+ }, { root: workspace.root });
570
+ if (values.json === true) {
571
+ console.log(JSON.stringify(outcome.kind === 'result' ? outcome.value : outcome, null, 2));
572
+ }
573
+ else {
574
+ const verification = await loadVerificationState(workspace);
575
+ const verificationNote = verification &&
576
+ changesVerificationNote(verification.reports, verification.revision, verification.checkNames);
577
+ show({ kind: 'changes', value: outcome, verificationNote }, () => renderChangesOutcome(outcome, undefined, verificationNote));
578
+ }
579
+ return outcome.kind === 'failure' ? 1 : 0;
580
+ }
581
+ if (command === 'learning') {
582
+ return runLearningCommand(sub, positionals[2], values.root, values.status, values.json === true);
583
+ }
584
+ if (command === 'verify') {
585
+ if (process.env.EI_DISABLED === '1') {
586
+ console.log('VERIFY disabled (EI_DISABLED)');
587
+ return 0;
588
+ }
589
+ const name = positionals[1];
590
+ const raw = values.report === undefined ? { check: name } : { check: name, report: values.report };
591
+ const valid = validateVerifyInput(raw);
592
+ if (!valid.ok) {
593
+ const failure = {
594
+ kind: 'failure',
595
+ code: 'INVALID_INPUT',
596
+ message: valid.message,
597
+ };
598
+ console.log(values.json === true
599
+ ? JSON.stringify(failure, null, 2)
600
+ : renderVerifyOutcome(failure, engineVersion()));
601
+ return 2;
602
+ }
603
+ const workspace = await loadWorkspace(values.root ?? process.cwd());
604
+ const outcome = await runVerification(workspace, valid.request);
605
+ console.log(values.json === true
606
+ ? JSON.stringify(outcome.kind === 'result' ? outcome.value : outcome, null, 2)
607
+ : renderVerifyOutcome(outcome, engineVersion()));
608
+ if (outcome.kind === 'failure')
609
+ return 2;
610
+ return outcome.value.status === 'PASS' ? 0 : 1;
611
+ }
612
+ if (command === 'search') {
613
+ if (process.env.EI_DISABLED === '1') {
614
+ console.log('SEARCH disabled (EI_DISABLED)');
615
+ return 0;
616
+ }
617
+ const started = performance.now();
618
+ const rawLimit = values.limit;
619
+ const parsedLimit = rawLimit === undefined
620
+ ? undefined
621
+ : /^\d+$/.test(rawLimit.trim())
622
+ ? Number.parseInt(rawLimit.trim(), 10)
623
+ : Number.NaN;
624
+ const query = positionals.slice(1).join(' ');
625
+ const valid = validateSearchInput(query, parsedLimit);
626
+ if (!valid.ok) {
627
+ const cache = await tryResolveCacheCli(values.root);
628
+ if (cache !== null) {
629
+ recordAudit(cache.cacheDir, {
630
+ ts: new Date().toISOString(),
631
+ tool: 'ei_search',
632
+ adapter: 'cli',
633
+ outcome: 'failure',
634
+ ms: performance.now() - started,
635
+ engine: engineVersion(),
636
+ code: 'INVALID_INPUT',
637
+ codes: ['INVALID_INPUT'],
638
+ ...(query !== '' ? { query } : {}),
639
+ ...(parsedLimit !== undefined && Number.isInteger(parsedLimit)
640
+ ? { limit: parsedLimit }
641
+ : {}),
642
+ }, { root: cache.root });
643
+ }
644
+ const outcome = {
645
+ kind: 'failure',
646
+ code: 'INVALID_INPUT',
647
+ message: valid.message,
648
+ };
649
+ if (values.json === true)
650
+ console.log(JSON.stringify(outcome, null, 2));
651
+ else
652
+ show({ kind: 'search', value: outcome }, () => renderSearchOutcome(outcome));
653
+ return 2;
654
+ }
655
+ const workspace = await loadWorkspace(values.root ?? process.cwd());
656
+ const session = new ImpactSession(workspace, {
657
+ waitAfterExpiry: true,
658
+ onProgress: (message) => console.error(`ei search: ${message}`),
659
+ });
660
+ const outcome = await runSearch(session, {
661
+ query: valid.query,
662
+ limit: valid.limit,
663
+ });
664
+ recordAudit(workspace.cacheDir, {
665
+ ts: new Date().toISOString(),
666
+ tool: 'ei_search',
667
+ adapter: 'cli',
668
+ outcome: outcome.kind,
669
+ ms: performance.now() - started,
670
+ engine: engineVersion(),
671
+ ...auditFieldsForSearch(outcome, engineVersion(), valid.query, valid.limit),
672
+ }, { root: workspace.root });
673
+ if (values.json === true) {
674
+ console.log(JSON.stringify(outcome.kind === 'result' ? outcome.value : outcome, null, 2));
675
+ }
676
+ else {
677
+ show({ kind: 'search', value: outcome }, () => renderSearchOutcome(outcome));
678
+ }
679
+ return outcome.kind === 'failure' ? 1 : 0;
680
+ }
681
+ if (command === 'doctor') {
682
+ if (values.deep !== true) {
683
+ console.error(USAGE);
684
+ return 2;
685
+ }
686
+ const workspace = await loadWorkspace(values.root ?? process.cwd());
687
+ const raw = values.differential ?? '0';
688
+ const differential = raw === 'all' ? -1 : Number.parseInt(raw, 10);
689
+ if (!Number.isInteger(differential)) {
690
+ console.error(`--differential must be a number or "all", got ${raw}`);
691
+ return 2;
692
+ }
693
+ const started = performance.now();
694
+ const previous = view !== undefined && process.stderr.isTTY
695
+ ? readBuildHistory(workspace.cacheDir).at(-1)
696
+ : undefined;
697
+ const hud = openHud({
698
+ ...hudOptions,
699
+ command: 'doctor',
700
+ repo: basename(workspace.root),
701
+ previous,
702
+ });
703
+ const outcome = await duringHud(hud, () => doctorDeep(workspace, {
704
+ differential,
705
+ onProgress: hud === undefined ? (message) => console.error(`ei doctor: ${message}`) : undefined,
706
+ onHudProgress: hud?.update,
707
+ }));
708
+ if (!outcome.ok) {
709
+ if (hud !== undefined && view !== undefined) {
710
+ console.log(renderHudSummary({
711
+ ...view,
712
+ command: 'doctor',
713
+ outcome: 'failed',
714
+ durationMs: performance.now() - started,
715
+ reason: `${outcome.code}: ${outcome.message}`,
716
+ next: outcome.fix,
717
+ }));
718
+ return 1;
719
+ }
720
+ console.log(`DOCTOR ${outcome.code}: ${outcome.message} · ${outcome.fix}`);
721
+ return 1;
722
+ }
723
+ if (values.json === true) {
724
+ console.log(JSON.stringify(outcome.value, null, 2));
725
+ }
726
+ else if (hud !== undefined && view !== undefined) {
727
+ const ok = doctorPassed(outcome.value);
728
+ const cold = isRecord(outcome.value.cold) ? outcome.value.cold : {};
729
+ const compared = differential === 0
730
+ ? 'canonical differences'
731
+ : 'canonical differences or differential misses';
732
+ console.log(renderHudSummary({
733
+ ...view,
734
+ command: 'doctor',
735
+ outcome: ok ? 'completed' : 'failed',
736
+ durationMs: performance.now() - started,
737
+ reason: ok ? `no ${compared}` : 'differences found',
738
+ phases: phaseTimes(cold.phases),
739
+ throughput: hud.throughput,
740
+ next: ok
741
+ ? 'ready for ei impact'
742
+ : 'check the reported differences before using this index',
743
+ }));
744
+ const note = counterNote(outcome.value);
745
+ if (!ok)
746
+ console.log(renderDoctor(outcome.value));
747
+ else if (note !== '')
748
+ console.log(note);
749
+ }
750
+ else {
751
+ console.log(renderDoctor(outcome.value));
752
+ }
753
+ return doctorPassed(outcome.value) ? 0 : 1;
754
+ }
755
+ if (command === 'init') {
756
+ const result = await initProject({
757
+ root: values.root,
758
+ force: values.force === true,
759
+ dryRun: values['dry-run'] === true,
760
+ });
761
+ if (values.json === true) {
762
+ console.log(JSON.stringify(result, null, 2));
763
+ return 0;
764
+ }
765
+ const dry = values['dry-run'] === true;
766
+ const status = result.configOverwritten
767
+ ? dry
768
+ ? 'would overwrite'
769
+ : 'overwritten'
770
+ : result.configCreated
771
+ ? dry
772
+ ? 'would create'
773
+ : 'created'
774
+ : 'already exists, skipped';
775
+ console.log('Project initialized:');
776
+ console.log(` Repo ID: ${result.repoId}`);
777
+ console.log(` Root: ${result.root}`);
778
+ console.log(` Cache dir: ${result.cacheDir}`);
779
+ console.log(` Config: ${result.configPath} (${status})`);
780
+ console.log(` Git: ${result.git.isRepo ? `yes (${result.git.gitRoot ?? 'root'})` : 'not a git repository'}`);
781
+ console.log(` Include: ${result.config.impact.include.join(', ')}`);
782
+ console.log(` TS configs: ${result.tsconfigs.length > 0 ? result.tsconfigs.join(', ') : 'none found'}`);
783
+ console.log(` Omitted tsconfig dirs: ${result.omittedTsconfigDirs.length > 0 ? result.omittedTsconfigDirs.join(', ') : 'none'}`);
784
+ if (result.warnings.length > 0) {
785
+ console.log('\nWarnings:');
786
+ for (const warning of result.warnings) {
787
+ console.log(` - ${warning}`);
788
+ }
789
+ }
790
+ return 0;
791
+ }
792
+ if (command === 'route' || command === 'load') {
793
+ const query = {
794
+ task: values.task ?? '',
795
+ stage: values.stage,
796
+ risk: values.risk,
797
+ type: values.type,
798
+ potetoMode: values['poteto-mode'] === true,
799
+ };
800
+ if (command === 'route') {
801
+ console.log(JSON.stringify(routeTask(query), null, 2));
802
+ return 0;
803
+ }
804
+ const started = performance.now();
805
+ try {
806
+ const workflow = await prepareWorkflow({
807
+ ...query,
808
+ strict: true,
809
+ roots: rootsFromEnv(process.env),
810
+ lock: await readLock(lockPath),
811
+ });
812
+ const cache = await tryResolveCacheCli(values.root);
813
+ if (cache !== null) {
814
+ recordAudit(cache.cacheDir, {
815
+ ts: new Date().toISOString(),
816
+ tool: 'ei_workflow',
817
+ adapter: 'cli',
818
+ outcome: 'result',
819
+ ms: performance.now() - started,
820
+ engine: engineVersion(),
821
+ ...auditFieldsForWorkflow(workflow),
822
+ }, { root: cache.root });
823
+ }
824
+ console.log(renderWorkflow(workflow));
825
+ return 0;
826
+ }
827
+ catch (error) {
828
+ const cache = await tryResolveCacheCli(values.root);
829
+ if (cache !== null) {
830
+ recordAudit(cache.cacheDir, {
831
+ ts: new Date().toISOString(),
832
+ tool: 'ei_workflow',
833
+ adapter: 'cli',
834
+ outcome: 'error',
835
+ ms: performance.now() - started,
836
+ engine: engineVersion(),
837
+ code: error instanceof WorkflowError ? error.code : 'WORKFLOW_ERROR',
838
+ ...(query.task !== '' ? { task: query.task } : {}),
839
+ ...(query.stage !== undefined ? { stage: query.stage } : {}),
840
+ }, { root: cache.root });
841
+ }
842
+ throw error;
843
+ }
844
+ }
845
+ if (command === 'skills' && (sub === 'list' || sub === 'check')) {
846
+ const rawPlatform = values.platform ?? 'omp';
847
+ if (rawPlatform !== 'agy' && rawPlatform !== 'omp') {
848
+ console.error(`invalid --platform ${JSON.stringify(rawPlatform)}; expected agy or omp`);
849
+ return 2;
850
+ }
851
+ const platform = rawPlatform;
852
+ const result = platform === 'agy'
853
+ ? await discoverAgySkills({
854
+ workspaceRoot: values.root,
855
+ detectHostPaths: values['detect-host'] === true,
856
+ requireCatalog: true,
857
+ })
858
+ : await discoverOmpSkills({
859
+ workspaceRoot: values.root,
860
+ profile: values.profile,
861
+ detectHostPaths: values['detect-host'] === true,
862
+ requireCatalog: true,
863
+ });
864
+ const registryIssues = sub === 'check'
865
+ ? await validateRegistryConsistency(await readRegistry(registryPath), await readLock(lockPath))
866
+ : [];
867
+ const totalIssues = result.issues.length + registryIssues.length;
868
+ if (values.json === true) {
869
+ console.log(JSON.stringify(sub === 'list'
870
+ ? { platform, packs: listSkillPacks(), discovery: result }
871
+ : { ...result, registryIssues }, null, 2));
872
+ return sub === 'check' && totalIssues > 0 ? 1 : 0;
873
+ }
874
+ if (view !== undefined) {
875
+ console.log(renderResultView({ kind: 'skills', platform, discovery: result, registryIssues }, view).join('\n'));
876
+ return sub === 'check' && totalIssues > 0 ? 1 : 0;
877
+ }
878
+ console.log(`SKILLS ${platform} · ${result.skills.length} discovered (${result.autoVisible.length} auto, ${result.explicitOnly.length} opt-in) · ${totalIssues} issues`);
879
+ for (const skill of result.skills) {
880
+ const mode = skill.explicitOnly ? 'opt-in' : 'auto';
881
+ console.log(` ${skill.name.padEnd(28)} ${mode.padEnd(8)} ${skill.sourceLabel}`);
882
+ }
883
+ for (const issue of result.issues) {
884
+ console.log(` ISSUE ${issue.code}: ${issue.message}`);
885
+ }
886
+ for (const issue of registryIssues) {
887
+ console.log(` REGISTRY ${issue.code}: ${issue.message}`);
888
+ }
889
+ return sub === 'check' && totalIssues > 0 ? 1 : 0;
890
+ }
891
+ if (command === 'skills' && sub === 'diff') {
892
+ const check = await checkUpstreamUpdates({
893
+ roots: rootsFromEnv(process.env),
894
+ lockPath,
895
+ registryPath,
896
+ });
897
+ if (values.json === true) {
898
+ console.log(JSON.stringify(check, null, 2));
899
+ return check.blockingFindings.length > 0 ? 1 : 0;
900
+ }
901
+ console.log(`SKILLS DIFF · updates=${check.hasUpdates ? 'yes' : 'no'} · blocking=${check.blockingFindings.length} · warnings=${check.findings.length - check.blockingFindings.length}`);
902
+ for (const p of check.providers) {
903
+ console.log(` ${p.provider.padEnd(8)} commit ${(p.previousCommit ?? '-').slice(0, 12)} -> ${(p.nextCommit ?? '-').slice(0, 12)} · changed=${p.changed.length} added=${p.added.length} removed=${p.removed.length} renamed=${p.renamed.length}`);
904
+ }
905
+ for (const finding of check.findings) {
906
+ console.log(` [${finding.severity.toUpperCase()}] ${finding.code}: ${finding.message}`);
907
+ }
908
+ return check.blockingFindings.length > 0 ? 1 : 0;
909
+ }
910
+ if (command === 'skills' && sub === 'sync') {
911
+ const { stagePath, staged } = await stageSkillUpdate({
912
+ roots: rootsFromEnv(process.env),
913
+ lockPath,
914
+ registryPath,
915
+ stateDir: values['state-dir'],
916
+ workspaceRoot: values.root,
917
+ });
918
+ if (values.json === true) {
919
+ console.log(JSON.stringify({ stagePath, staged }, null, 2));
920
+ return staged.validation.ok ? 0 : 1;
921
+ }
922
+ console.log(`SKILLS SYNC ${staged.status.toUpperCase()} · stageId=${staged.stageId} · agy=${staged.validation.runtimes.agy.ok ? 'OK' : 'FAIL'} · omp=${staged.validation.runtimes.omp.ok ? 'OK' : 'FAIL'} · file=${stagePath}`);
923
+ for (const finding of staged.diff.findings) {
924
+ console.log(` [${finding.severity.toUpperCase()}] ${finding.code}: ${finding.message}`);
925
+ }
926
+ if (staged.validation.ok) {
927
+ console.log(`Next: review diff, then run: ei skills publish --stage-id ${staged.stageId} --approve`);
928
+ }
929
+ return staged.validation.ok ? 0 : 1;
930
+ }
931
+ if (command === 'skills' && sub === 'publish') {
932
+ const stageId = values['stage-id'];
933
+ if (!stageId) {
934
+ console.error('usage: main.js skills publish --stage-id <id> --approve [--state-dir <path>]');
935
+ return 2;
936
+ }
937
+ const { snapshotPath, snapshot } = await publishStagedUpdate({
938
+ stageId,
939
+ approve: values.approve === true,
940
+ lockPath,
941
+ registryPath,
942
+ stateDir: values['state-dir'],
943
+ force: values.force === true,
944
+ });
945
+ if (values.json === true) {
946
+ console.log(JSON.stringify({ snapshotPath, snapshot }, null, 2));
947
+ return 0;
948
+ }
949
+ console.log(`SKILLS PUBLISHED releaseId=${snapshot.releaseId} from ${snapshot.stageId} · rollback snapshot=${snapshotPath}`);
950
+ return 0;
951
+ }
952
+ if (command === 'skills' && sub === 'rollback') {
953
+ const restored = await rollbackSkillUpdate({
954
+ releaseId: values.release,
955
+ lockPath,
956
+ registryPath,
957
+ stateDir: values['state-dir'],
958
+ });
959
+ if (values.json === true) {
960
+ console.log(JSON.stringify(restored, null, 2));
961
+ return 0;
962
+ }
963
+ console.log(`SKILLS ROLLED BACK to previous state of release ${restored.restoredFrom}`);
964
+ return 0;
965
+ }
966
+ if (command === 'sources' && sub === 'check') {
967
+ const lock = await readLock(lockPath);
968
+ const result = await checkSources(lock, rootsFromEnv(process.env), {
969
+ write: values.write === true,
970
+ });
971
+ console.log(formatReports(result.reports));
972
+ if (result.reports.some((report) => report.written))
973
+ await writeLock(lockPath, result.lock);
974
+ return result.reports.some((report) => reportStatus(report) === 'ERROR') ? 1 : 0;
975
+ }
976
+ if (command === 'mcp') {
977
+ if (sub !== undefined) {
978
+ console.error('usage: main.js mcp --root /absolute/path/to/repository [--workflow]');
979
+ return 2;
980
+ }
981
+ const stdioUrl = new URL('../../../scripts/mcp/stdio.mjs', import.meta.url).href;
982
+ const { createStdioServer, resolveMcpRoot } = (await import(stdioUrl));
983
+ const resolved = await resolveMcpRoot(values.root, process.env);
984
+ if (!resolved.ok) {
985
+ console.error(resolved.message);
986
+ return 2;
987
+ }
988
+ const env = values.workflow === true ? { ...process.env, KSD_MCP_WORKFLOW: '1' } : process.env;
989
+ const server = createStdioServer({ root: resolved.root, env });
990
+ await server.done;
991
+ return 0;
992
+ }
993
+ console.error(USAGE);
994
+ return 2;
995
+ }
996
+ try {
997
+ process.exitCode = await run(process.argv.slice(2));
998
+ }
999
+ catch (error) {
1000
+ console.error(error instanceof Error ? error.message : String(error));
1001
+ process.exitCode = 1;
1002
+ }