@aiwg/cli 2026.10.14 → 2026.10.16

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 (210) hide show
  1. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.core.md +13 -0
  2. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.md +118 -0
  3. package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
  4. package/dist/src/artifacts/citation-parser.js +7 -6
  5. package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
  6. package/dist/src/artifacts/corpus-tools/cli.js +37 -0
  7. package/dist/src/artifacts/corpus-tools/discovery-log.js +27 -25
  8. package/dist/src/artifacts/corpus-tools/expand-cli.js +90 -0
  9. package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
  10. package/dist/src/artifacts/corpus-tools/expand-queue.js +41 -0
  11. package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
  12. package/dist/src/artifacts/corpus-tools/expand-state.js +56 -0
  13. package/dist/src/artifacts/corpus-tools/expand.js +124 -0
  14. package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
  15. package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
  16. package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
  17. package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
  18. package/dist/src/artifacts/corpus-tools/resolve-cli.js +99 -0
  19. package/dist/src/artifacts/corpus-tools/resolve-corpus.js +41 -0
  20. package/dist/src/artifacts/corpus-tools/resolve.js +119 -0
  21. package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
  22. package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
  23. package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
  24. package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
  25. package/dist/src/artifacts/graph-query.js +5 -3
  26. package/dist/src/artifacts/hybrid-query.js +11 -2
  27. package/dist/src/artifacts/index-refresh.js +2 -0
  28. package/dist/src/cli/handlers/daemon.js +17 -1
  29. package/dist/src/cli/handlers/doctor-args.js +45 -0
  30. package/dist/src/cli/handlers/doctor-help.js +8 -3
  31. package/dist/src/cli/handlers/index.js +2 -2
  32. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  33. package/dist/src/cli/handlers/models.js +3 -2
  34. package/dist/src/cli/handlers/regenerate.js +8 -16
  35. package/dist/src/cli/handlers/sessions.js +7 -7
  36. package/dist/src/cli/handlers/subcommands.js +8 -0
  37. package/dist/src/cli/handlers/update.js +157 -0
  38. package/dist/src/cli/handlers/use.js +14 -4
  39. package/dist/src/cli/handlers/utilities.js +3 -586
  40. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  41. package/dist/src/cli/services/deployment-verification.js +0 -1
  42. package/dist/src/config/aiwg-config.js +2 -1
  43. package/dist/src/config/authorization-cli.js +7 -3
  44. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  45. package/dist/src/config/dispatch-thresholds-runtime.mjs +17 -7
  46. package/dist/src/config/framework-aliases.js +12 -0
  47. package/dist/src/config/host-resource-report.d.mts +19 -0
  48. package/dist/src/config/host-resource-report.mjs +80 -0
  49. package/dist/src/config/host-resource-runtime.d.mts +34 -0
  50. package/dist/src/config/host-resource-runtime.mjs +293 -0
  51. package/dist/src/config/installed-selection.js +22 -0
  52. package/dist/src/config/worker-context.js +33 -4
  53. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  54. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  55. package/dist/src/decision/heldout/access.js +74 -0
  56. package/dist/src/decision/heldout/calibration.js +1 -0
  57. package/dist/src/decision/heldout/collector.js +9 -2
  58. package/dist/src/effects/verifiers/file.js +22 -5
  59. package/dist/src/extensions/claude-attribution.js +82 -0
  60. package/dist/src/extensions/claude-hooks-installer.js +115 -69
  61. package/dist/src/extensions/commands/daemon.js +109 -0
  62. package/dist/src/extensions/commands/definitions.js +5 -89
  63. package/dist/src/features/catalog.js +1 -1
  64. package/dist/src/gates/evaluate.js +2 -2
  65. package/dist/src/gates/heldout.js +52 -0
  66. package/dist/src/gates/index.js +2 -1
  67. package/dist/src/lint/check-patterns.js +163 -0
  68. package/dist/src/lint/checks.js +268 -0
  69. package/dist/src/lint/reference-resolution.js +54 -0
  70. package/dist/src/lint/runner.js +3 -465
  71. package/dist/src/mcp/helpers.mjs +11 -1
  72. package/dist/src/memory/project-registry.js +44 -4
  73. package/dist/src/models/worker-installation-store.mjs +228 -0
  74. package/dist/src/models/worker-installation.mjs +7 -162
  75. package/dist/src/models/worker-plan.js +36 -5
  76. package/dist/src/models/wrapper-deployment.js +25 -12
  77. package/dist/src/models/wrapper-enforcement.js +47 -7
  78. package/dist/src/network-analysis/research.js +2 -1
  79. package/dist/src/policy/hitl-check.js +14 -4
  80. package/dist/src/policy/hitl-consume.js +54 -0
  81. package/dist/src/policy/hitl-receipt.js +2 -0
  82. package/dist/src/policy/hitl.js +11 -3
  83. package/dist/src/providers/provider-context-contracts.js +162 -0
  84. package/dist/src/providers/provider-definition-schema.js +136 -0
  85. package/dist/src/providers/provider-definitions.js +8 -1298
  86. package/dist/src/providers/provider-seeds-1.js +360 -0
  87. package/dist/src/providers/provider-seeds-2.js +387 -0
  88. package/dist/src/providers/provider-seeds-3.js +262 -0
  89. package/dist/src/research/clients/arxiv.js +14 -34
  90. package/dist/src/research/clients/base.js +53 -26
  91. package/dist/src/research/clients/crossref.js +9 -1
  92. package/dist/src/research/clients/semantic-scholar.js +73 -44
  93. package/dist/src/research/identity.js +117 -0
  94. package/dist/src/research/index.js +1 -0
  95. package/dist/src/research/query-cli.js +3 -87
  96. package/dist/src/research/query-options.js +87 -0
  97. package/dist/src/research/reference-match.js +135 -0
  98. package/dist/src/research/services/acquisition.js +9 -7
  99. package/dist/src/research/services/citation.js +5 -2
  100. package/dist/src/research/types.js +2 -0
  101. package/dist/src/rules/core-startup.d.mts +2 -0
  102. package/dist/src/rules/core-startup.mjs +31 -0
  103. package/dist/src/serve/mission-conductor.js +48 -4
  104. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  105. package/dist/src/sessions/adapters/grok-build.js +14 -7
  106. package/dist/src/sessions/workspace-discovery.js +5 -5
  107. package/dist/src/smiths/context-pipeline/agents-md.js +34 -0
  108. package/dist/src/smiths/context-pipeline/aiwg-md.js +19 -46
  109. package/dist/src/smiths/context-pipeline/bridge-ownership.js +50 -0
  110. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  111. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  112. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  113. package/dist/src/smiths/context-pipeline/generator.js +49 -114
  114. package/dist/src/smiths/context-pipeline/managed-hook.js +11 -1
  115. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  116. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  117. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  118. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  119. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  120. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  121. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  122. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  123. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  124. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  125. package/package.json +13 -2
  126. package/schemas/decision/D29Study.v10.schema.json +65 -0
  127. package/tools/agents/deploy-agents.mjs +12 -123
  128. package/tools/agents/providers/antigravity.mjs +1 -1
  129. package/tools/agents/providers/claude-post-deploy.mjs +12 -1
  130. package/tools/agents/providers/context-write.mjs +16 -0
  131. package/tools/agents/providers/grok-build.mjs +8 -5
  132. package/tools/agents/providers/hermes-skill-lifecycle.mjs +144 -0
  133. package/tools/agents/providers/hermes-startup.mjs +209 -0
  134. package/tools/agents/providers/hermes.mjs +9 -359
  135. package/tools/agents/providers/model-wrapper.mjs +5 -1
  136. package/tools/agents/providers/muse.mjs +3 -3
  137. package/tools/agents/providers/pi.mjs +4 -2
  138. package/tools/agents/providers/rule-delivery-surface.mjs +332 -0
  139. package/tools/agents/providers/rule-delivery.mjs +20 -1346
  140. package/tools/agents/providers/rule-deployment-commit.mjs +144 -0
  141. package/tools/agents/providers/rule-deployment-prepare.mjs +452 -0
  142. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  143. package/tools/agents/providers/rule-presentation.mjs +13 -4
  144. package/tools/agents/providers/rule-projection.mjs +119 -0
  145. package/tools/agents/providers/rule-startup.mjs +70 -0
  146. package/tools/agents/providers/stale-artifact-prune.mjs +128 -0
  147. package/tools/agents/providers/warp.mjs +2 -2
  148. package/tools/agents/providers/windsurf.mjs +11 -57
  149. package/tools/daemon/README.md +511 -0
  150. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  151. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  152. package/tools/daemon/agent-supervisor.mjs +299 -0
  153. package/tools/daemon/automation-engine.mjs +310 -0
  154. package/tools/daemon/autonomous-engine.mjs +346 -0
  155. package/tools/daemon/behavior-loader.mjs +316 -0
  156. package/tools/daemon/behavior.mjs +174 -0
  157. package/tools/daemon/concierge/intent-router.mjs +401 -0
  158. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  159. package/tools/daemon/concierge/response-translator.mjs +462 -0
  160. package/tools/daemon/config.mjs +377 -0
  161. package/tools/daemon/cron-scheduler.mjs +178 -0
  162. package/tools/daemon/daemon-main.mjs +1169 -0
  163. package/tools/daemon/event-router.mjs +84 -0
  164. package/tools/daemon/file-watcher.mjs +383 -0
  165. package/tools/daemon/index.mjs +1181 -0
  166. package/tools/daemon/init-profile.mjs +124 -0
  167. package/tools/daemon/ipc-client.mjs +197 -0
  168. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  169. package/tools/daemon/ipc-server.mjs +275 -0
  170. package/tools/daemon/maintenance-owner.mjs +79 -0
  171. package/tools/daemon/memory-manager.mjs +386 -0
  172. package/tools/daemon/message-router.mjs +194 -0
  173. package/tools/daemon/provider-watcher.mjs +585 -0
  174. package/tools/daemon/pty-adapter.mjs +420 -0
  175. package/tools/daemon/repl-chat.mjs +359 -0
  176. package/tools/daemon/resource-bounds.mjs +88 -0
  177. package/tools/daemon/sandbox-transport.mjs +295 -0
  178. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  179. package/tools/daemon/task-store.mjs +450 -0
  180. package/tools/daemon/tmux-manager.mjs +324 -0
  181. package/tools/daemon/update-policy.mjs +517 -0
  182. package/tools/daemon/web-server.mjs +399 -0
  183. package/tools/daemon/web-ui/index.html +585 -0
  184. package/tools/daemon/web-ui/styles.css +156 -0
  185. package/tools/docker/Dockerfile.daemon +35 -0
  186. package/tools/docker/container-manager.mjs +291 -0
  187. package/tools/messaging/adapter-registry.mjs +230 -0
  188. package/tools/messaging/adapters/base.mjs +326 -0
  189. package/tools/messaging/adapters/discord.mjs +462 -0
  190. package/tools/messaging/adapters/slack.mjs +402 -0
  191. package/tools/messaging/adapters/telegram.mjs +552 -0
  192. package/tools/messaging/chat-handler.mjs +297 -0
  193. package/tools/messaging/command-router.mjs +269 -0
  194. package/tools/messaging/event-bus.mjs +199 -0
  195. package/tools/messaging/index.mjs +456 -0
  196. package/tools/messaging/message-formatter.mjs +320 -0
  197. package/tools/messaging/room-manager.mjs +277 -0
  198. package/tools/messaging/types.mjs +94 -0
  199. package/tools/plugin/plugin-links.mjs +3 -0
  200. package/tools/providers/pi-bridge-policy.mjs +4 -0
  201. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  202. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  203. package/tools/ralph-external/lib/worker-invocation-processes.mjs +3 -2
  204. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  205. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  206. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  207. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  208. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  209. package/tools/ralph-external/session-launcher.mjs +7 -7
  210. package/tools/scripts/resource-preflight.mjs +3 -242
@@ -10,49 +10,12 @@
10
10
  * @issue #33, #342
11
11
  */
12
12
  import fs from 'fs';
13
- import fsp from 'fs/promises';
14
13
  import path from 'path';
15
14
  import { createScriptRunner } from './script-runner.js';
16
- import { DOCTOR_HELP } from './doctor-help.js';
17
15
  import { getFrameworkRoot } from '../../channel/manager.mjs';
18
- import { updateInstallation } from '../../update/service.mjs';
19
- import { useHandler as useFrameworkHandler } from './use.js';
20
- import { projectAiwgPath } from '../../config/project-artifacts.js';
21
- import { argsTerminatorIndex, hasPositionalOrSwitch, requireFlagValue, valueTokenIndexes } from '../flag-parsing.js';
22
- import { checkCollisions, } from '../../smiths/skillsmith/collision-detector.js';
23
- import { renderUseDeploymentResult, verifyConfiguredDeployments, } from '../services/deployment-verification.js';
24
- /**
25
- * Maps framework registry IDs (e.g. 'sdlc-complete') to `aiwg use` names (e.g. 'sdlc').
26
- */
27
- const REGISTRY_ID_TO_USE_NAME = {
28
- 'sdlc-complete': 'sdlc',
29
- 'media-marketing-kit': 'marketing',
30
- 'media-curator': 'media-curator',
31
- 'research-complete': 'research',
32
- 'forensics-complete': 'forensics',
33
- };
34
- function flagValue(args, flag) {
35
- const index = args.indexOf(flag);
36
- if (index >= 0)
37
- return args[index + 1];
38
- const prefix = `${flag}=`;
39
- return args.find((arg) => arg.startsWith(prefix))?.slice(prefix.length);
40
- }
41
- /**
42
- * Read the installed frameworks from the on-disk registry.
43
- */
44
- function readFrameworkRegistry(cwd) {
45
- const registryPath = projectAiwgPath(cwd, 'frameworks', 'registry.json');
46
- if (!fs.existsSync(registryPath)) {
47
- return null;
48
- }
49
- try {
50
- return JSON.parse(fs.readFileSync(registryPath, 'utf8'));
51
- }
52
- catch {
53
- return null;
54
- }
55
- }
16
+ import { doctorHandler } from './utility-doctor.js';
17
+ import { updateHandler } from './update.js';
18
+ export { doctorHandler, updateHandler };
56
19
  /**
57
20
  * Handler for prefill-cards command
58
21
  *
@@ -328,427 +291,6 @@ export const validateMetadataHandler = {
328
291
  return result;
329
292
  },
330
293
  };
331
- /**
332
- * A directory is a deployed skill only if it carries a SKILL.md manifest —
333
- * the same marker `isOwnedByNamespace()` in collision-detector.ts reads for
334
- * ownership. Harness container/bucket directories (e.g. Claude Code's own
335
- * `.claude/skills/synced/` sync storage, which holds UUID-named dirs with
336
- * `manifest.json`, not SKILL.md) have no manifest of their own and must
337
- * never be reported as a colliding skill (#278).
338
- *
339
- * A container directory without its own SKILL.md is still descended exactly
340
- * one level: a real skill nested inside it (`<container>/<skill>/SKILL.md`)
341
- * is reported as `<container>/<skill>`, while the container itself never is.
342
- */
343
- async function hasSkillManifest(dirPath) {
344
- try {
345
- await fsp.access(path.join(dirPath, 'SKILL.md'));
346
- return true;
347
- }
348
- catch {
349
- return false;
350
- }
351
- }
352
- async function collectDeployedSkillDirNames(skillsDir) {
353
- let topEntries;
354
- try {
355
- topEntries = await fsp.readdir(skillsDir, { withFileTypes: true });
356
- }
357
- catch {
358
- return [];
359
- }
360
- const names = [];
361
- for (const entry of topEntries) {
362
- if (!entry.isDirectory())
363
- continue;
364
- const dirPath = path.join(skillsDir, entry.name);
365
- if (await hasSkillManifest(dirPath)) {
366
- names.push(entry.name);
367
- continue;
368
- }
369
- let nestedEntries;
370
- try {
371
- nestedEntries = await fsp.readdir(dirPath, { withFileTypes: true });
372
- }
373
- catch {
374
- continue;
375
- }
376
- for (const nested of nestedEntries) {
377
- if (!nested.isDirectory())
378
- continue;
379
- const nestedPath = path.join(dirPath, nested.name);
380
- if (await hasSkillManifest(nestedPath)) {
381
- names.push(path.join(entry.name, nested.name));
382
- }
383
- }
384
- }
385
- return names;
386
- }
387
- /**
388
- * #1156 Phase 1 — Validate the per-user registry at `~/.aiwg/installed.json`.
389
- *
390
- * Checks each registered framework+provider deploy:
391
- * - Registry entry parses correctly
392
- * - Recorded artifact entries (Cycle 3 mirrors) still exist on disk
393
- * - Per-artifact-type counts match the actual entry-name list length
394
- * - Pre-Cycle-3 entries (no `entries` snapshot) are surfaced as "limited
395
- * drift detection" rather than failures
396
- *
397
- * Returns exit 1 when drift is detected, exit 0 otherwise. Output is plain
398
- * text suitable for terminal consumption.
399
- */
400
- async function runUserScopeDoctor(verbose) {
401
- const { readUserRegistry, userRegistryPath } = await import('../../config/user-registry.js');
402
- const { USER_SCOPE_PATHS } = await import('../scope-resolver.js');
403
- const fsp2 = await import('node:fs/promises');
404
- const path2 = await import('node:path');
405
- const registry = await readUserRegistry();
406
- const frameworks = Object.entries(registry.installed);
407
- const lines = [];
408
- lines.push('');
409
- lines.push('── User-scope registry validation ──');
410
- lines.push(`Registry path: ${userRegistryPath()}`);
411
- lines.push('');
412
- if (frameworks.length === 0) {
413
- lines.push('No frameworks deployed at user scope. Run `aiwg use <fw> --scope user` to install.');
414
- return { exitCode: 0, message: lines.join('\n') + '\n' };
415
- }
416
- let driftCount = 0;
417
- let limitedCount = 0;
418
- for (const [name, entry] of frameworks) {
419
- lines.push(`▸ ${name} v${entry.version} [${entry.source}]`);
420
- for (const [provider, providerDeployRaw] of Object.entries(entry.deployedTo)) {
421
- // Cast through unknown for the optional `entries` snapshot.
422
- const providerDeploy = providerDeployRaw;
423
- const userPaths = USER_SCOPE_PATHS[provider];
424
- if (!userPaths) {
425
- lines.push(` ${provider}: ⚠ no user-scope path map registered for this provider`);
426
- driftCount++;
427
- continue;
428
- }
429
- const recorded = providerDeploy.entries;
430
- if (!recorded) {
431
- lines.push(` ${provider}: ⚠ pre-Cycle-3 entry — no per-artifact manifest, drift detection limited`);
432
- lines.push(` counts: agents=${providerDeploy.agents} commands=${providerDeploy.commands} skills=${providerDeploy.skills} rules=${providerDeploy.rules}`);
433
- limitedCount++;
434
- continue;
435
- }
436
- // Walk the recorded entry names and check each one exists on disk.
437
- const checks = [
438
- ['agents', userPaths.agents, recorded.agents, providerDeploy.agents],
439
- ['commands', userPaths.commands, recorded.commands, providerDeploy.commands],
440
- ['skills', userPaths.skills, recorded.skills, providerDeploy.skills],
441
- ['rules', userPaths.rules, recorded.rules, providerDeploy.rules],
442
- ];
443
- const issues = [];
444
- for (const [type, dir, names, expectedCount] of checks) {
445
- if (!dir || !names)
446
- continue;
447
- let present = 0;
448
- const missing = [];
449
- for (const n of names) {
450
- const target = path2.join(dir, n);
451
- const stat = await fsp2.stat(target).catch(() => null);
452
- if (stat)
453
- present++;
454
- else
455
- missing.push(n);
456
- }
457
- if (names.length !== expectedCount) {
458
- issues.push(`count drift on ${type}: registry says ${expectedCount}, manifest lists ${names.length}`);
459
- }
460
- if (missing.length > 0) {
461
- issues.push(`${type}: ${missing.length}/${names.length} entries missing from ${dir}`);
462
- if (verbose) {
463
- for (const m of missing)
464
- issues.push(` missing: ${path2.join(dir, m)}`);
465
- }
466
- }
467
- else if (verbose) {
468
- issues.push(`${type}: ${present}/${names.length} present at ${dir}`);
469
- }
470
- }
471
- if (issues.length === 0) {
472
- lines.push(` ${provider}: ✓ all recorded artifacts present`);
473
- }
474
- else {
475
- const hasMissing = issues.some(i => i.includes('missing') || i.includes('drift'));
476
- const marker = hasMissing ? '✗' : 'ℹ';
477
- lines.push(` ${provider}: ${marker}`);
478
- for (const i of issues)
479
- lines.push(` ${i}`);
480
- if (hasMissing)
481
- driftCount++;
482
- }
483
- }
484
- }
485
- lines.push('');
486
- lines.push('═'.repeat(60));
487
- lines.push(`Frameworks: ${frameworks.length} Drift: ${driftCount} Limited (pre-Cycle-3): ${limitedCount}`);
488
- if (driftCount > 0) {
489
- lines.push('');
490
- lines.push('Drift detected. To repair, re-run `aiwg use <framework> --scope user --provider <p>`.');
491
- lines.push('To remove a stale registry entry, run `aiwg remove <framework> --scope user`.');
492
- }
493
- return {
494
- exitCode: driftCount > 0 ? 1 : 0,
495
- message: lines.join('\n') + '\n',
496
- };
497
- }
498
- /**
499
- * Handler for doctor command
500
- *
501
- * Runs health diagnostics on the AIWG installation and workspace.
502
- *
503
- * Usage:
504
- * aiwg doctor
505
- * aiwg -doctor
506
- * aiwg --doctor
507
- * aiwg doctor --verbose
508
- * aiwg doctor --scope user # validate ~/.aiwg/installed.json
509
- */
510
- export const doctorHandler = {
511
- id: 'doctor',
512
- name: 'Doctor',
513
- description: 'Run health diagnostics',
514
- category: 'maintenance',
515
- aliases: ['-doctor', '--doctor'],
516
- async help() {
517
- return { exitCode: 0, message: DOCTOR_HELP, rawOutput: true };
518
- },
519
- async execute(ctx) {
520
- // Validate before any early-return mode: deployment and user-scope doctor
521
- // never invoke doctor.mjs, so they must enforce the same flag contract.
522
- const valueFlags = ['--provider', '--bundle', '--scope', '--context-baseline', '--context-budget-tokens', '--cli'];
523
- const knownFlags = new Set([
524
- ...valueFlags, '--all-providers', '--probe-workers', '--qualify', '--yes', '--dry-run', '--no-budget-check', '--strict-context', '--json',
525
- '--decision-offload', '--deployment', '--user', '--verbose', '-v', '--project-local', '--quiet', '--help', '-h',
526
- ]);
527
- const hasSwitch = (name) => hasPositionalOrSwitch(ctx.args, name, valueFlags);
528
- const values = new Map();
529
- try {
530
- for (const flag of valueFlags) {
531
- values.set(flag, requireFlagValue(ctx.args, { rejectEmpty: true, precedence: 'last' }, flag));
532
- }
533
- const consumed = valueTokenIndexes(ctx.args, valueFlags);
534
- for (let i = 0; i < argsTerminatorIndex(ctx.args); i += 1) {
535
- const token = ctx.args[i];
536
- if (consumed.has(i) || !token.startsWith('-'))
537
- continue;
538
- const name = token.split('=')[0];
539
- if (!knownFlags.has(name) || (token.includes('=') && !valueFlags.includes(name))) {
540
- throw new Error(`Unknown flag: ${name}`);
541
- }
542
- }
543
- if (hasSwitch('--decision-offload') && (hasSwitch('--probe-workers') || hasSwitch('--deployment') || hasSwitch('--user') || values.get('--scope') !== undefined)) {
544
- throw new Error('--decision-offload is a separate offline mode; do not combine it with worker, deployment or user-scope checks');
545
- }
546
- if (['--qualify', '--cli', '--yes', '--dry-run'].some(flag => hasSwitch(flag) || values.get(flag)) && !hasSwitch('--probe-workers')) {
547
- throw new Error('--qualify, --cli, --yes and --dry-run require --probe-workers');
548
- }
549
- if (hasSwitch('--json') && !hasSwitch('--probe-workers') && !hasSwitch('--deployment') && !hasSwitch('--decision-offload')) {
550
- throw new Error('--json requires --probe-workers or --deployment or --decision-offload');
551
- }
552
- }
553
- catch (error) {
554
- return { exitCode: 2, message: `${error instanceof Error ? error.message : String(error)}. See 'aiwg doctor --help'.` };
555
- }
556
- if (hasSwitch('--help') || hasSwitch('-h')) {
557
- return { exitCode: 0, message: DOCTOR_HELP, rawOutput: true };
558
- }
559
- if (hasSwitch('--deployment')) {
560
- const scopeValue = values.get('--scope');
561
- if (scopeValue && scopeValue !== 'project' && scopeValue !== 'user') {
562
- return { exitCode: 2, message: `Invalid deployment verification scope: ${scopeValue}` };
563
- }
564
- const result = await verifyConfiguredDeployments(ctx.cwd || process.cwd(), {
565
- provider: values.get('--provider'),
566
- bundle: values.get('--bundle'),
567
- scope: scopeValue,
568
- }, ctx.frameworkRoot);
569
- const { rulePinState } = await import('../../rules/pin-state.js');
570
- const pins = rulePinState(ctx.cwd, ctx.frameworkRoot);
571
- return {
572
- exitCode: result.exitCode,
573
- message: hasSwitch('--json')
574
- ? JSON.stringify({ ...result, rule_pins: { rules: pins.rules, warnings: pins.warnings } }, null, 2)
575
- : renderUseDeploymentResult(result) + '\n' + pins.rules.map(rule => `${rule.name}: pinned kernel (canonical ${rule.canonical_activation})`).concat(pins.warnings).join('\n'),
576
- rawOutput: hasSwitch('--json'),
577
- };
578
- }
579
- // #1156 Phase 1 — `aiwg doctor --scope user` / `aiwg doctor --user`
580
- // validates the per-user registry (~/.aiwg/installed.json) without
581
- // running the project-scope diagnostics. Operators need this to verify
582
- // their user-scope deployments from any cwd, including shells with no
583
- // project at all.
584
- const userScopeRequested = hasSwitch('--user') || values.get('--scope') === 'user';
585
- if (userScopeRequested && !hasSwitch('--probe-workers')) {
586
- return await runUserScopeDoctor(hasSwitch('--verbose') || hasSwitch('-v'));
587
- }
588
- const frameworkRoot = hasSwitch('--decision-offload') ? ctx.frameworkRoot : await getFrameworkRoot();
589
- const runner = createScriptRunner(frameworkRoot);
590
- // Run core doctor diagnostics
591
- const result = await runner.run('tools/cli/doctor.mjs', ctx.args, { cwd: ctx.cwd });
592
- // Machine-readable worker probes (#3066): tools/cli/doctor.mjs already
593
- // printed exactly one JSON document (or a usage error) on its own
594
- // stdio — every section below writes human-readable text, so returning
595
- // here keeps stdout to the JSON document alone.
596
- if (hasSwitch('--decision-offload') || hasSwitch('--json') || hasSwitch('--qualify') || hasSwitch('--cli') || hasSwitch('--dry-run') || result.exitCode === 2)
597
- return result;
598
- let agentSkillsFailure = false;
599
- try {
600
- const { inspectGrokBuildNative } = await import('../../mcp/grok-build-config.mjs');
601
- const native = await inspectGrokBuildNative({ projectDir: ctx.cwd || process.cwd() });
602
- console.log(`\n── Grok Build native extensions ──\n MCP: ${native.mcp}\n Hooks: ${native.hooks}`);
603
- for (const diagnostic of native.diagnostics)
604
- console.log(` ⚠ ${diagnostic}`);
605
- }
606
- catch (error) {
607
- console.log(`\n── Grok Build native extensions ──\n ⚠ unable to audit: ${error instanceof Error ? error.message : String(error)}`);
608
- }
609
- try {
610
- const projectDir = ctx.cwd || process.cwd();
611
- const provider = flagValue(ctx.args, '--provider');
612
- const requested = provider === 'muse' || ctx.args.includes('--all-providers');
613
- const { inspectMuseNative, isMuseDeployedProject } = await import('../../mcp/muse-native-config.mjs');
614
- if (requested || await isMuseDeployedProject(projectDir)) {
615
- const native = await inspectMuseNative({ projectDir });
616
- console.log(`\n── Muse Code native extensions ──\n CLI: ${native.cli}\n Hooks: ${native.hooks}\n MCP: ${native.mcp}`);
617
- }
618
- }
619
- catch (error) {
620
- console.log(`\n── Muse Code native extensions ──\n ⚠ unable to audit: ${error instanceof Error ? error.message : String(error)}`);
621
- }
622
- try {
623
- const { buildAgentSkillsDoctorSection } = await import('../../skills/doctor.js');
624
- const section = buildAgentSkillsDoctorSection(ctx.cwd || process.cwd());
625
- console.log(section.output);
626
- agentSkillsFailure = section.hasFailures;
627
- }
628
- catch (error) {
629
- console.log(`\n── Agent Skills conformance ──\n ⚠ unable to audit: ${error instanceof Error ? error.message : String(error)}`);
630
- }
631
- // Surface feedback escape hatch when doctor finds issues
632
- if (result.exitCode !== 0) {
633
- console.log(`
634
- ── Recovery options ──
635
- aiwg session --no-repair — launch anyway (skip auto-repair)
636
- aiwg sync — sync to latest and redeploy
637
- aiwg feedback --type bug — report this issue to GitHub
638
- `);
639
- }
640
- // Append collision scan: check deployed skills dir for bad-state collisions
641
- // (platform built-ins and AIWG CLI command shadows)
642
- try {
643
- const projectDir = ctx.cwd || process.cwd();
644
- const skillsDir = path.join(projectDir, '.claude', 'skills');
645
- const deployedSkillNames = await collectDeployedSkillDirNames(skillsDir);
646
- if (deployedSkillNames.length > 0) {
647
- const collisions = await checkCollisions({
648
- platform: 'claude',
649
- projectPath: projectDir,
650
- skillNames: deployedSkillNames,
651
- namespace: 'aiwg',
652
- skillsBaseDir: skillsDir,
653
- });
654
- // Two distinct causes share this scan, and conflating them mislabels
655
- // one as the other: an `error` is a name that shadows a Claude
656
- // built-in; a `warn` is a deployed skill this namespace does not own
657
- // (#2504). Report each under its own heading with its own remedy.
658
- const builtinCollisions = collisions.filter(r => r.severity === 'error');
659
- const unownedCollisions = collisions.filter(r => r.severity === 'warn');
660
- if (builtinCollisions.length > 0 || unownedCollisions.length > 0) {
661
- console.log('\n── Skill collision scan ──');
662
- if (builtinCollisions.length > 0) {
663
- console.log('');
664
- console.log('⚠ Stale skills detected (names collide with Claude built-ins):');
665
- for (const r of builtinCollisions) {
666
- console.log(` ✗ ${r.skillName}: ${r.reason}`);
667
- }
668
- console.log('');
669
- console.log(' Fix: run `aiwg use <framework>` to redeploy and auto-clean stale skill directories.');
670
- }
671
- if (unownedCollisions.length > 0) {
672
- console.log('');
673
- console.log("⚠ Deployed skills not owned by namespace 'aiwg' (a redeploy would overwrite them):");
674
- for (const r of unownedCollisions) {
675
- console.log(` ✗ ${r.skillName}: ${r.reason}`);
676
- }
677
- console.log('');
678
- console.log(" Fix: if the skill is yours, move it out of the AIWG-managed skills directory");
679
- console.log(" or give it its own namespace. If AIWG generated it, re-run `aiwg use` to");
680
- console.log(' restore the ownership marker.');
681
- }
682
- }
683
- }
684
- }
685
- catch {
686
- // Collision scan is non-fatal for doctor
687
- }
688
- // #1037 / #1049 — Project-local artifacts section: per-type counts,
689
- // validation errors, shadows, denylist violations, drift detection,
690
- // and provider deployment matrix. Replaces the older inline shadow
691
- // scan with the richer section spec'd by design-doctor-log-promote.md.
692
- try {
693
- const projectDir = ctx.cwd || process.cwd();
694
- const fr = await getFrameworkRoot();
695
- const { readAiwgConfig } = await import('../../config/aiwg-config.js');
696
- const config = await readAiwgConfig(projectDir);
697
- const { buildProjectLocalDoctorSection } = await import('../../extensions/project-local-doctor.js');
698
- const onlyProjectLocal = ctx.args.includes('--project-local');
699
- const quiet = ctx.args.includes('--quiet');
700
- const section = await buildProjectLocalDoctorSection({
701
- projectDir, frameworkRoot: fr, config, quiet,
702
- });
703
- if (section.output) {
704
- console.log(section.output);
705
- }
706
- // When --project-local is requested as the only output and the rest
707
- // of doctor printed nothing project-local-specific, fold result exit
708
- // into our own findings.
709
- if (onlyProjectLocal && section.hasFailures) {
710
- return { exitCode: 1, message: '' };
711
- }
712
- }
713
- catch {
714
- // Project-local section is non-fatal for doctor
715
- }
716
- // Web-backed resource lock/cache diagnostics (#1850). Report lock source
717
- // mode, cold cache, and digest drift without requiring web mode to be in use.
718
- try {
719
- const { buildWebResourceDoctorSection } = await import('../../resources/doctor.js');
720
- const section = buildWebResourceDoctorSection(ctx.cwd || process.cwd(), {
721
- cacheRoot: process.env.AIWG_RESOURCE_CACHE_ROOT,
722
- });
723
- if (section.output)
724
- console.log(section.output);
725
- if (section.hasFailures)
726
- return { exitCode: 1, message: '' };
727
- }
728
- catch (error) {
729
- console.log(`\n── Web resource cache ──\n ⚠ unable to audit: ${error instanceof Error ? error.message : String(error)}`);
730
- }
731
- // Canonical workspace-context graph diagnostics (#1811). Legacy projects
732
- // remain valid; drift, loops, conflicts, and possible credentials fail.
733
- try {
734
- const { diagnoseWorkspaceContext } = await import('../../smiths/context-pipeline/workspace-context.js');
735
- const diagnostics = await diagnoseWorkspaceContext(ctx.cwd || process.cwd());
736
- console.log('\n── Workspace context graph ──');
737
- for (const diagnostic of diagnostics) {
738
- const mark = diagnostic.severity === 'error' ? '✗' : diagnostic.severity === 'warning' ? '⚠' : '✓';
739
- console.log(` ${mark} ${diagnostic.message}`);
740
- }
741
- if (diagnostics.some((item) => item.severity === 'error'))
742
- return { exitCode: 1, message: '' };
743
- }
744
- catch (error) {
745
- console.log(`\n── Workspace context graph ──\n ⚠ unable to audit: ${error instanceof Error ? error.message : String(error)}`);
746
- }
747
- return agentSkillsFailure
748
- ? { exitCode: 1, message: '' }
749
- : result;
750
- },
751
- };
752
294
  const CONTEXT_FIREWALL_HELP = `aiwg context-firewall — inspect provider context and reviewed memory
753
295
 
754
296
  Usage:
@@ -857,131 +399,6 @@ export const contextFirewallHandler = {
857
399
  return runner.run('tools/security/context-memory-firewall.mjs', forwarded, { cwd: ctx.cwd });
858
400
  },
859
401
  };
860
- /**
861
- * Handler for update command
862
- *
863
- * Updates AIWG and re-deploys installed frameworks/addons.
864
- * - Checks for npm/git updates first
865
- * - Reads .aiwg/frameworks/registry.json to detect installed items
866
- * - Re-deploys only those (preserving the user's current selection)
867
- * - Use --all to deploy everything (equivalent to `aiwg use all`)
868
- *
869
- * Usage:
870
- * aiwg update # Update + re-deploy installed frameworks
871
- * aiwg update --all # Update + deploy everything
872
- * aiwg update --dry-run # Show what would be updated
873
- * aiwg update --provider <name> # Pass through provider to deployment
874
- * aiwg update --skip-check # Skip npm/git update check, only re-deploy
875
- *
876
- * @issue #342
877
- */
878
- export const updateHandler = {
879
- id: 'update',
880
- name: 'Update',
881
- description: 'Update AIWG and re-deploy installed frameworks',
882
- category: 'maintenance',
883
- aliases: ['-update', '--update', 'upgrade'],
884
- async execute(ctx) {
885
- const args = ctx.args;
886
- const deployAll = args.includes('--all');
887
- const dryRun = args.includes('--dry-run');
888
- const skipCheck = args.includes('--skip-check');
889
- // Extract --provider value if present
890
- const providerIdx = args.findIndex(a => a === '--provider' || a === '--platform');
891
- const providerArgs = providerIdx >= 0 && args[providerIdx + 1]
892
- ? ['--provider', args[providerIdx + 1]]
893
- : [];
894
- // Step 1: Check for package updates (unless --skip-check)
895
- if (!skipCheck) {
896
- try {
897
- console.log('Updating AIWG installation...\n');
898
- const update = await updateInstallation({
899
- dryRun,
900
- offline: args.includes('--offline'),
901
- });
902
- console.log(`${update.message}\n`);
903
- }
904
- catch (error) {
905
- if (error.code === 'AIWG_INSTALLATION_DRIFT'
906
- || error.code === 'AIWG_INSTALLATION_INVALID') {
907
- return { exitCode: 78, message: error instanceof Error ? error.message : String(error) };
908
- }
909
- console.error(`Warning: Update check failed: ${error instanceof Error ? error.message : String(error)}`);
910
- console.log('Continuing with re-deployment...\n');
911
- }
912
- }
913
- // Step 2: Determine what to re-deploy
914
- if (deployAll) {
915
- // --all: deploy everything (equivalent to `aiwg use all`)
916
- const frameworks = ['all'];
917
- if (dryRun) {
918
- console.log('Dry run: Would re-deploy all frameworks and addons');
919
- return { exitCode: 0 };
920
- }
921
- console.log('Re-deploying all frameworks and addons...\n');
922
- const result = await useFrameworkHandler.execute({
923
- ...ctx,
924
- args: [...frameworks, ...providerArgs],
925
- });
926
- return result;
927
- }
928
- // Read registry to determine installed frameworks
929
- const registry = readFrameworkRegistry(ctx.cwd);
930
- if (!registry || registry.frameworks.length === 0) {
931
- console.log('No frameworks found in .aiwg/frameworks/registry.json');
932
- console.log('');
933
- console.log('To deploy a framework first, run:');
934
- console.log(' aiwg use sdlc');
935
- console.log(' aiwg use marketing');
936
- console.log(' aiwg use all');
937
- return { exitCode: 0 };
938
- }
939
- // Canonical framework IDs need their historical public aliases. Add-ons,
940
- // extensions, and project-local bundles are already accepted by `aiwg use`,
941
- // so preserve their registry IDs instead of silently skipping them.
942
- const installedFrameworks = registry.frameworks.map(item => REGISTRY_ID_TO_USE_NAME[item.id] ?? item.id);
943
- // Report what will be updated
944
- console.log(`Installed frameworks: ${installedFrameworks.join(', ')}`);
945
- console.log('');
946
- if (dryRun) {
947
- console.log('Dry run: Would re-deploy the following frameworks:');
948
- for (const fw of installedFrameworks) {
949
- console.log(` - ${fw}`);
950
- }
951
- return { exitCode: 0 };
952
- }
953
- // Step 3: Re-deploy each installed framework
954
- const results = [];
955
- for (const fw of installedFrameworks) {
956
- console.log(`Re-deploying ${fw}...`);
957
- const result = await useFrameworkHandler.execute({
958
- ...ctx,
959
- args: [fw, ...providerArgs],
960
- });
961
- results.push({ framework: fw, exitCode: result.exitCode });
962
- if (result.exitCode !== 0) {
963
- console.error(`Warning: Failed to re-deploy ${fw}`);
964
- }
965
- }
966
- // Step 4: Report summary
967
- console.log('');
968
- console.log('Update Summary:');
969
- const succeeded = results.filter(r => r.exitCode === 0);
970
- const failed = results.filter(r => r.exitCode !== 0);
971
- for (const r of results) {
972
- const status = r.exitCode === 0 ? 'updated' : 'FAILED';
973
- console.log(` ${r.framework}: ${status}`);
974
- }
975
- console.log('');
976
- console.log(`Updated: ${succeeded.length}/${results.length}`);
977
- return {
978
- exitCode: failed.length > 0 ? 1 : 0,
979
- message: failed.length > 0
980
- ? `Some frameworks failed to update: ${failed.map(f => f.framework).join(', ')}`
981
- : `Successfully updated ${succeeded.length} framework(s)`,
982
- };
983
- },
984
- };
985
402
  /**
986
403
  * All utility handlers
987
404
  */