@aiwg/cli 2026.11.1 → 2026.11.2

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 (108) hide show
  1. package/agentic/code/addons/aiwg-hooks/canonical/aiwg-prompt-discovery.yaml +9 -0
  2. package/agentic/code/addons/aiwg-hooks/hooks/aiwg-prompt-discovery.cjs +136 -0
  3. package/agentic/code/providers/model-capabilities.v1.json +27 -23
  4. package/agentic/code/providers/model-catalog.v1.json +3 -3
  5. package/dist/src/artifacts/cli.js +10 -11
  6. package/dist/src/artifacts/discover-cli-help.js +25 -0
  7. package/dist/src/artifacts/discover-session-facets.js +2 -1
  8. package/dist/src/artifacts/fortemi-core-prebuilt-freshness.js +28 -0
  9. package/dist/src/artifacts/fortemi-core-sync.js +3 -0
  10. package/dist/src/artifacts/framework-capabilities.js +4 -0
  11. package/dist/src/artifacts/framework-source-digest.js +1 -1
  12. package/dist/src/artifacts/index-builder.js +10 -10
  13. package/dist/src/artifacts/index-dependencies.js +72 -0
  14. package/dist/src/artifacts/query-engine-discover-output.js +13 -5
  15. package/dist/src/artifacts/query-engine-discover.js +49 -21
  16. package/dist/src/artifacts/query-engine-entries.js +56 -2
  17. package/dist/src/artifacts/query-engine-options.js +14 -1
  18. package/dist/src/artifacts/query-engine-scoring.js +8 -4
  19. package/dist/src/artifacts/query-engine-show-card.js +2 -0
  20. package/dist/src/artifacts/query-engine-show-load.js +1 -1
  21. package/dist/src/artifacts/query-engine-show.js +3 -1
  22. package/dist/src/artifacts/query-engine-templates.js +33 -0
  23. package/dist/src/artifacts/query-engine-verbose.js +25 -0
  24. package/dist/src/artifacts/relations-builder.js +49 -4
  25. package/dist/src/artifacts/relations.js +9 -0
  26. package/dist/src/artifacts/template-references.js +42 -0
  27. package/dist/src/artifacts/types.js +1 -1
  28. package/dist/src/cli/handlers/bundle-reconciliation.js +7 -3
  29. package/dist/src/cli/handlers/checkpoint-handoff.js +48 -0
  30. package/dist/src/cli/handlers/checkpoint-record.js +20 -0
  31. package/dist/src/cli/handlers/checkpoint.js +50 -17
  32. package/dist/src/cli/handlers/decision.js +1 -1
  33. package/dist/src/cli/handlers/doctor-args.js +3 -1
  34. package/dist/src/cli/handlers/doctor-help.js +2 -1
  35. package/dist/src/cli/handlers/help.js +1 -1
  36. package/dist/src/cli/handlers/refresh-bundles.js +2 -1
  37. package/dist/src/cli/handlers/refresh-managed-deployment.js +196 -0
  38. package/dist/src/cli/handlers/refresh.js +10 -2
  39. package/dist/src/cli/handlers/subcommands-discovery.js +8 -1
  40. package/dist/src/cli/handlers/use.js +10 -3
  41. package/dist/src/cli/services/deployment-verification.js +11 -7
  42. package/dist/src/config/worker-write.js +4 -10
  43. package/dist/src/decision/ledger.js +15 -15
  44. package/dist/src/decision/offload.js +6 -7
  45. package/dist/src/delivery/pr.js +2 -0
  46. package/dist/src/delivery/template-sections.js +56 -0
  47. package/dist/src/extensions/claude-hooks-installer.js +61 -53
  48. package/dist/src/extensions/managed-hook-script-state.js +48 -0
  49. package/dist/src/extensions/muse-managed-hooks.js +49 -0
  50. package/dist/src/issues/cli.js +3 -0
  51. package/dist/src/issues/external-cli.js +4 -1
  52. package/dist/src/issues/live.js +9 -2
  53. package/dist/src/issues/local.js +5 -1
  54. package/dist/src/issues/tracker-policy.js +11 -1
  55. package/dist/src/mcp/json-document.d.mts +2 -0
  56. package/dist/src/models/model-capabilities.v1.json +27 -23
  57. package/dist/src/models/model-catalog.v1.json +3 -3
  58. package/dist/src/models/provider-policy.js +8 -0
  59. package/dist/src/models/worker-health-readiness.js +20 -4
  60. package/dist/src/models/worker-health-snapshot.js +29 -0
  61. package/dist/src/models/worker-installation.d.mts +5 -1
  62. package/dist/src/models/worker-installation.mjs +11 -5
  63. package/dist/src/models/worker-qualification-policy.js +54 -0
  64. package/dist/src/providers/skill-ownership.d.mts +1 -0
  65. package/dist/src/providers/transformation-receipt-integration.js +4 -2
  66. package/dist/src/providers/transformation-receipt.js +4 -2
  67. package/dist/src/serve/worker-invocation.js +4 -2
  68. package/dist/src/smiths/context-pipeline/workspace-audit.js +34 -17
  69. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +12 -6
  70. package/dist/src/smiths/context-pipeline/workspace-doctor.js +44 -4
  71. package/dist/src/smiths/context-pipeline/workspace-document.js +5 -2
  72. package/dist/src/smiths/context-pipeline/workspace-migration.js +2 -1
  73. package/dist/src/smiths/hook-bridge/codex-translator.js +150 -94
  74. package/dist/src/smiths/hook-bridge/codex-trust.js +50 -0
  75. package/dist/src/smiths/hook-bridge/factory-hook-config.js +132 -0
  76. package/dist/src/smiths/hook-bridge/factory-translator.js +88 -33
  77. package/dist/src/smiths/hook-bridge/index.js +3 -3
  78. package/dist/src/smiths/hook-bridge/loader.js +10 -2
  79. package/dist/src/smiths/hook-bridge/prompt-discovery-gaps.js +0 -1
  80. package/dist/src/storage/workspace-permissions-health.js +64 -0
  81. package/dist/src/storage/workspace-permissions.js +51 -0
  82. package/package.json +6 -1
  83. package/tools/agents/providers/base-files.mjs +2 -1
  84. package/tools/agents/providers/base-flat-artifacts.mjs +6 -3
  85. package/tools/agents/providers/base-models-platforms.mjs +3 -3
  86. package/tools/agents/providers/base-skill-copy.mjs +2 -0
  87. package/tools/agents/providers/bound-rules-pointer.mjs +21 -0
  88. package/tools/agents/providers/claude-post-deploy.mjs +9 -5
  89. package/tools/agents/providers/codex-post-deploy.mjs +10 -0
  90. package/tools/agents/providers/factory-hooks.mjs +43 -0
  91. package/tools/agents/providers/factory.mjs +4 -91
  92. package/tools/agents/providers/muse-hooks.mjs +4 -43
  93. package/tools/agents/providers/muse-prompt-discovery.mjs +3 -7
  94. package/tools/agents/providers/packaged-codex-agents.mjs +48 -0
  95. package/tools/agents/providers/rule-delivery-surface.mjs +4 -4
  96. package/tools/agents/providers/rule-presentation.mjs +6 -5
  97. package/tools/agents/providers/rule-projection.mjs +10 -2
  98. package/tools/agents/providers/rule-startup.mjs +8 -1
  99. package/tools/cli/decision-offload-report.mjs +7 -2
  100. package/tools/plugin/issue-template-copies.mjs +24 -0
  101. package/tools/plugin/package-plugins.mjs +11 -3
  102. package/tools/ralph-external/lib/factory-adapter.mjs +7 -8
  103. package/tools/ralph-external/lib/worker-artifacts.mjs +4 -2
  104. package/tools/ralph-external/lib/worker-final.mjs +43 -8
  105. package/tools/ralph-external/lib/worker-launch-cli.mjs +10 -1
  106. package/tools/ralph-external/lib/worker-prompt.mjs +35 -0
  107. package/tools/ralph-external/lib/worker-run-directory-refusal.mjs +8 -0
  108. package/tools/ralph-external/session-launcher.mjs +10 -7
@@ -5,7 +5,9 @@ export const indexHandler = {
5
5
  description: "Artifact index commands (build, query, deps, stats)",
6
6
  category: "index",
7
7
  aliases: [],
8
- async help() {
8
+ async help(ctx) {
9
+ if (ctx.args[0] === "discover")
10
+ return discoverHandler.help(ctx);
9
11
  const { printIndexUsage } = await import("../../artifacts/cli.js");
10
12
  printIndexUsage();
11
13
  return { exitCode: 0 };
@@ -67,6 +69,11 @@ export const discoverHandler = {
67
69
  description: "Find AIWG operational assets by capability — index-driven on-demand discovery",
68
70
  category: "index",
69
71
  aliases: [],
72
+ async help() {
73
+ const { printDiscoverUsage } = await import("../../artifacts/discover-cli-help.js");
74
+ printDiscoverUsage();
75
+ return { exitCode: 0 };
76
+ },
70
77
  async execute(ctx) {
71
78
  try {
72
79
  // Delegate to the same handler `aiwg index discover` uses, by
@@ -1,5 +1,6 @@
1
1
  import { ContextWriteJournal } from '../../smiths/context-pipeline/context-file-safety.js';
2
2
  import { trackTemporaryDirectory } from '../../utils/temporary-directory.js';
3
+ import { codexHookTrustNextStep, readCodexHookTrust } from '../../smiths/hook-bridge/codex-trust.js';
3
4
  /**
4
5
  * Use Command Handler
5
6
  *
@@ -2586,6 +2587,12 @@ export class UseHandler {
2586
2587
  result.exitClassification = 'failure';
2587
2588
  }
2588
2589
  }
2590
+ const codexTrustStep = !dryRun && result.exitCode === 0 && requestedScope === 'project' && providers.includes('codex')
2591
+ ? codexHookTrustNextStep(await readCodexHookTrust(projectDir)) : '';
2592
+ if (codexTrustStep)
2593
+ result.findings.push({
2594
+ id: 'codex-prompt-discovery-trust', provider: 'codex', severity: 'info', message: codexTrustStep,
2595
+ });
2589
2596
  if (json) {
2590
2597
  return { exitCode: result.exitCode, message: JSON.stringify(result, null, 2), rawOutput: true };
2591
2598
  }
@@ -2610,7 +2617,7 @@ export class UseHandler {
2610
2617
  });
2611
2618
  return {
2612
2619
  exitCode: result.exitCode,
2613
- message: [coreResult.message, rendered, ...(previewActions ? [...previewActions].sort() : [])].filter(Boolean).join('\n'),
2620
+ message: [coreResult.message, rendered, ...(previewActions ? [...previewActions].sort() : []), codexTrustStep].filter(Boolean).join('\n'),
2614
2621
  };
2615
2622
  }
2616
2623
  async executeCore(ctx, resolvedProviders) {
@@ -4088,10 +4095,10 @@ export class UseHandler {
4088
4095
  // PUW-018 (#1119) cross-provider hook bridge — opt-in via
4089
4096
  // --enable-cross-provider-hooks. When enabled and at least one canonical
4090
4097
  // hook source exists at agentic/code/addons/aiwg-hooks/canonical/*.yaml,
4091
- // translate to provider-native artifacts (Codex TOML, Copilot JSON,
4098
+ // translate to provider-native artifacts (Codex project JSON, Copilot JSON,
4092
4099
  // Factory shell, Hermes Python plugin). Per ADR-3 §7 autoInstall policy
4093
4100
  // this is opt-in.
4094
- if (remainingArgs.includes('--enable-cross-provider-hooks') && !dryRun) {
4101
+ if (remainingArgs.includes('--enable-cross-provider-hooks') && !remainingArgs.includes('--no-hooks') && !dryRun) {
4095
4102
  try {
4096
4103
  const { loadHookSources, bridgeAll } = await import('../../smiths/hook-bridge/index.js');
4097
4104
  const { sources, errors } = await loadHookSources(frameworkRoot);
@@ -594,6 +594,8 @@ export async function verifyProviderDeployment(options) {
594
594
  }
595
595
  const diagnostics = await diagnoseWorkspaceContext(options.projectRoot);
596
596
  for (const diagnostic of diagnostics) {
597
+ if (diagnostic.code === 'codex-prompt-discovery-trust')
598
+ continue; // Doctor advisory; use appends its short next step.
597
599
  if (diagnostic.severity === 'info')
598
600
  continue;
599
601
  findings.push(finding(normalized, `context-diagnostic:${diagnostic.code}`, diagnostic.severity === 'error' ? 'blocking' : 'advisory', diagnostic.message, diagnostic.severity === 'error'
@@ -895,13 +897,15 @@ export function renderUseDeploymentResult(result, options = {}) {
895
897
  else {
896
898
  lines.push(' Unavailable — the framework index could not be read.');
897
899
  }
898
- const visibleFindings = result.findings.filter((candidate) => candidate.severity !== 'info');
899
- if (visibleFindings.length > 0) {
900
- lines.push('', result.outcome === 'failed' ? 'Blocking findings' : 'Advisories');
901
- for (const item of visibleFindings) {
902
- lines.push(...wrapParagraph(`${item.provider}: ${item.message}`, width));
903
- if (item.remediation)
904
- lines.push(...wrapParagraph(`Fix: ${item.remediation}`, width, ' '));
900
+ for (const severity of ['blocking', 'advisory']) {
901
+ const visibleFindings = result.findings.filter((candidate) => candidate.severity === severity);
902
+ if (visibleFindings.length > 0) {
903
+ lines.push('', severity === 'blocking' ? 'Blocking findings' : 'Advisories');
904
+ for (const item of visibleFindings) {
905
+ lines.push(...wrapParagraph(`${item.provider}: ${item.message}`, width));
906
+ if (item.remediation)
907
+ lines.push(...wrapParagraph(`Fix: ${item.remediation}`, width, ' '));
908
+ }
905
909
  }
906
910
  }
907
911
  if (options.verbose) {
@@ -1,6 +1,7 @@
1
1
  // Shares atomic replacement and serialization across worker configuration owners.
2
+ import { workspaceFileMode, preserveReplacementMode } from '../storage/workspace-permissions.js';
2
3
  import { AsyncLocalStorage } from 'node:async_hooks';
3
- import { mkdir, writeFile, rename, unlink, stat } from 'node:fs/promises';
4
+ import { mkdir, writeFile, rename, unlink } from 'node:fs/promises';
4
5
  import { statSync, readFileSync } from 'node:fs';
5
6
  import { randomBytes } from 'node:crypto';
6
7
  import { dirname, join } from 'node:path';
@@ -24,17 +25,10 @@ export async function atomicConfigWrite(file, content, assertOwned) {
24
25
  assertOwned?.();
25
26
  await mkdir(dirname(file), { recursive: true });
26
27
  const temporary = `${file}.${randomBytes(6).toString('hex')}.tmp`;
27
- let mode = 0o600;
28
- try {
29
- mode = (await stat(file)).mode;
30
- }
31
- catch (error) {
32
- if (error.code !== 'ENOENT')
33
- throw error;
34
- }
35
28
  try {
36
29
  assertOwned?.();
37
- await writeFile(temporary, content, { encoding: 'utf8', mode });
30
+ await writeFile(temporary, content, { encoding: 'utf8', mode: workspaceFileMode(file), flag: 'wx' });
31
+ await preserveReplacementMode(temporary, file);
38
32
  assertOwned?.();
39
33
  await rename(temporary, file);
40
34
  }
@@ -19,7 +19,7 @@
19
19
  * ACCIDENTAL hazard — a stray symlink, a hard link, loose permissions left
20
20
  * by another tool, a previous crash's partial write — all under the
21
21
  * assumption that the artifact root is owned and written by the SAME local
22
- * user running `aiwg`. It does not and cannot defend against a HOSTILE
22
+ * user running `aiwg`, or its stat-verified shared workspace group. It does not and cannot defend against a HOSTILE
23
23
  * process running as that same user: such a process already has read/write
24
24
  * access to everything the ledger could protect. Appenders, rotation and
25
25
  * readers share the existing cross-process directory-lock helper. There is
@@ -52,6 +52,7 @@
52
52
  * attribution-to-append stage starts once the deadline has fired. An append
53
53
  * already waiting for the ledger lock can still complete after that deadline.
54
54
  */
55
+ import { workspaceFileMode, workspaceDirectoryMode, workspacePermissionsAllowed, preserveReplacementMode } from '../storage/workspace-permissions.js';
55
56
  import { randomUUID, createHash } from 'node:crypto';
56
57
  import { constants as fsConstants, createReadStream, existsSync } from 'node:fs';
57
58
  import { lstat, mkdir, open, readdir, rename, rm } from 'node:fs/promises';
@@ -120,8 +121,6 @@ export const MAX_RECORD_TEXT_BYTES = 600;
120
121
  export const MAX_LEDGER_RECORD_BYTES = 4000;
121
122
  /** Bounds how long `recordDecisionAsk` waits on attribution resolution and the write. On timeout the outcome is reported as unknown, not "abandoned" — see the module doc comment. */
122
123
  export const DECISION_LEDGER_RECORD_TIMEOUT_MS = 250;
123
- const LEDGER_DIR_MODE = 0o700;
124
- const LEDGER_FILE_MODE = 0o600;
125
124
  const LEDGER_LOCK_TIMEOUT_MS = 30_000;
126
125
  const IS_WINDOWS = process.platform === 'win32';
127
126
  const HAS_O_NOFOLLOW = typeof fsConstants.O_NOFOLLOW === 'number';
@@ -316,14 +315,14 @@ function currentUid() {
316
315
  /**
317
316
  * Create (if needed) the owner-only `decision` directory and verify it is
318
317
  * safe to use: a real directory (not a symlink), and on POSIX owned by the
319
- * current user. An existing directory that fails either check is never
318
+ * current user or its stat-verified workspace group. An existing directory that fails either check is never
320
319
  * modified (no chmod) — recording is skipped.
321
320
  */
322
321
  async function ensurePrivateDecisionDir(projectRoot, warn) {
323
322
  const artifactRoot = projectAiwgWritePath(projectRoot);
324
323
  const decisionDir = join(artifactRoot, DECISION_LEDGER_DIR_NAME);
325
324
  try {
326
- await mkdir(decisionDir, { recursive: true, mode: LEDGER_DIR_MODE });
325
+ await mkdir(decisionDir, { recursive: true, mode: workspaceDirectoryMode(decisionDir) });
327
326
  }
328
327
  catch (error) {
329
328
  warn(`warning: cannot create decision ledger directory: ${errorMessage(error)}`);
@@ -343,7 +342,7 @@ async function ensurePrivateDecisionDir(projectRoot, warn) {
343
342
  }
344
343
  if (!IS_WINDOWS) {
345
344
  const uid = currentUid();
346
- if (uid !== null && stat.uid !== uid) {
345
+ if (uid !== null && stat.uid !== uid && !((stat.mode & 0o070) !== 0 && workspacePermissionsAllowed(decisionDir, stat))) {
347
346
  warn('warning: decision ledger directory is not owned by the current user; skipping record');
348
347
  return null;
349
348
  }
@@ -355,7 +354,7 @@ async function ensurePrivateDecisionDir(projectRoot, warn) {
355
354
  * retention) and verify it is a regular file with exactly one hard link (rejects a
356
355
  * pre-planted hard link to an unrelated file, which `O_NOFOLLOW` alone does
357
356
  * not catch), and on POSIX owned by the current user with no group/other
358
- * permission bits. `O_NOFOLLOW` is applied when the platform defines it
357
+ * permission bits outside a matching shared workspace group. `O_NOFOLLOW` is applied when the platform defines it
359
358
  * (refusing a pre-planted symlink at open time on POSIX); on platforms
360
359
  * without it (Windows) a prior plain `lstat` is the only symlink check —
361
360
  * see the module doc comment on the trust boundary. A file that fails any
@@ -378,7 +377,7 @@ async function openPrivateLedgerFile(ledgerPath, warn, flags = fsConstants.O_APP
378
377
  }
379
378
  let handle;
380
379
  try {
381
- handle = await open(ledgerPath, flags | (HAS_O_NOFOLLOW ? fsConstants.O_NOFOLLOW : 0), LEDGER_FILE_MODE);
380
+ handle = await open(ledgerPath, flags | (HAS_O_NOFOLLOW ? fsConstants.O_NOFOLLOW : 0), workspaceFileMode(ledgerPath));
382
381
  }
383
382
  catch (error) {
384
383
  warn(`warning: cannot open decision ledger file: ${errorMessage(error)}`);
@@ -398,12 +397,12 @@ async function openPrivateLedgerFile(ledgerPath, warn, flags = fsConstants.O_APP
398
397
  }
399
398
  if (!IS_WINDOWS) {
400
399
  const uid = currentUid();
401
- if (uid !== null && stat.uid !== uid) {
400
+ if (uid !== null && stat.uid !== uid && !((stat.mode & 0o070) !== 0 && workspacePermissionsAllowed(ledgerPath, stat))) {
402
401
  warn('warning: decision ledger file is not owned by the current user; skipping record');
403
402
  await handle.close();
404
403
  return null;
405
404
  }
406
- if ((stat.mode & 0o077) !== 0) {
405
+ if (!workspacePermissionsAllowed(ledgerPath, stat)) {
407
406
  warn('warning: decision ledger file has group or other permission bits set; skipping record');
408
407
  await handle.close();
409
408
  return null;
@@ -516,7 +515,7 @@ async function privateArchiveDirectory(root, target, create) {
516
515
  current = join(current, part);
517
516
  if (create) {
518
517
  try {
519
- await mkdir(current, { mode: LEDGER_DIR_MODE });
518
+ await mkdir(current, { mode: workspaceDirectoryMode(current) });
520
519
  if (!IS_WINDOWS)
521
520
  await syncDirectory(dirname(current));
522
521
  }
@@ -535,9 +534,9 @@ async function privateArchiveDirectory(root, target, create) {
535
534
  throw error;
536
535
  }
537
536
  // archive/ is shared with the activity log and may already be readable.
538
- // Its decision/ subtree (and any nested directories) must be private.
537
+ // Its decision/ subtree must be private or match the shared workspace group.
539
538
  const modeMask = current === join(root, 'archive') ? 0o022 : 0o077;
540
- if (!info.isDirectory() || (!IS_WINDOWS && (info.uid !== currentUid() || (info.mode & modeMask) !== 0))) {
539
+ if (!info.isDirectory() || (!IS_WINDOWS && ((info.uid !== currentUid() || (info.mode & modeMask) !== 0) && !((info.mode & 0o070) !== 0 && workspacePermissionsAllowed(current, info))))) {
541
540
  throw new Error(`Unsafe decision archive directory (requires a private, owned real directory): ${current}`);
542
541
  }
543
542
  }
@@ -602,7 +601,7 @@ export async function rotateDecisionLedger(options) {
602
601
  if (!archived.length)
603
602
  return result;
604
603
  await privateArchiveDirectory(artifactRoot, dirname(archivePath), true);
605
- const archive = await open(archivePath, 'wx', LEDGER_FILE_MODE);
604
+ const archive = await open(archivePath, 'wx', workspaceFileMode(archivePath));
606
605
  archiveCreated = true;
607
606
  try {
608
607
  await writeFully(archive, Buffer.concat(archived));
@@ -613,9 +612,10 @@ export async function rotateDecisionLedger(options) {
613
612
  }
614
613
  if (!IS_WINDOWS)
615
614
  await syncDirectory(dirname(archivePath));
616
- const replacement = await open(tempPath, 'wx', LEDGER_FILE_MODE);
615
+ const replacement = await open(tempPath, 'wx', workspaceFileMode(ledgerPath));
617
616
  try {
618
617
  await writeFully(replacement, Buffer.concat(kept));
618
+ await preserveReplacementMode(tempPath, ledgerPath);
619
619
  await replacement.sync();
620
620
  }
621
621
  finally {
@@ -6,6 +6,7 @@
6
6
  * opportunity denominator. Completed-call records remain in ledger.ts; the
7
7
  * shared correlation id joins the two append-only journals.
8
8
  */
9
+ import { workspaceFileMode, workspaceDirectoryMode, workspacePermissionsAllowed } from '../storage/workspace-permissions.js';
9
10
  import { randomUUID } from 'node:crypto';
10
11
  import { constants as fsConstants, createReadStream } from 'node:fs';
11
12
  import { lstat, mkdir, open } from 'node:fs/promises';
@@ -22,8 +23,6 @@ import { ATTRIBUTION_FIELD_PATTERN, decisionLedgerHistory, DECISION_LEDGER_RECOR
22
23
  export const DECISION_OPPORTUNITY_SCHEMA = 'aiwg-decision-opportunity/v1';
23
24
  export const DECISION_OFFLOAD_SNAPSHOT_SCHEMA = 'aiwg-decision-offload-snapshot/v1';
24
25
  const OPPORTUNITY_FILE = 'opportunities.jsonl';
25
- const DIR_MODE = 0o700;
26
- const FILE_MODE = 0o600;
27
26
  const MAX_OPPORTUNITY_RECORD_BYTES = 4000;
28
27
  export const DECISION_OPPORTUNITY_RECORD_TIMEOUT_MS = DECISION_LEDGER_RECORD_TIMEOUT_MS;
29
28
  const TIMED_OUT = Symbol('decision-offload-timeout');
@@ -161,22 +160,22 @@ export async function appendDecisionOpportunity(record, projectRoot, warn = mess
161
160
  try {
162
161
  const directory = projectAiwgWritePath(projectRoot, 'decision');
163
162
  const file = path.join(directory, OPPORTUNITY_FILE);
164
- await mkdir(directory, { recursive: true, mode: DIR_MODE });
163
+ await mkdir(directory, { recursive: true, mode: workspaceDirectoryMode(directory) });
165
164
  const dirStat = await lstat(directory);
166
- if (!dirStat.isDirectory() || dirStat.isSymbolicLink() || (dirStat.mode & 0o077) !== 0)
165
+ if (!dirStat.isDirectory() || dirStat.isSymbolicLink() || !workspacePermissionsAllowed(directory, dirStat))
167
166
  throw new Error('unsafe opportunity directory');
168
167
  try {
169
168
  const fileStat = await lstat(file);
170
- if (!fileStat.isFile() || fileStat.isSymbolicLink() || fileStat.nlink !== 1 || (fileStat.mode & 0o077) !== 0)
169
+ if (!fileStat.isFile() || fileStat.isSymbolicLink() || fileStat.nlink !== 1 || !workspacePermissionsAllowed(file, fileStat))
171
170
  throw new Error('unsafe opportunity file');
172
171
  }
173
172
  catch (error) {
174
173
  if (error.code !== 'ENOENT')
175
174
  throw error;
176
175
  }
177
- handle = await open(file, fsConstants.O_APPEND | fsConstants.O_CREAT | fsConstants.O_WRONLY | (fsConstants.O_NOFOLLOW ?? 0), FILE_MODE);
176
+ handle = await open(file, fsConstants.O_APPEND | fsConstants.O_CREAT | fsConstants.O_WRONLY | (fsConstants.O_NOFOLLOW ?? 0), workspaceFileMode(file));
178
177
  const opened = await handle.stat();
179
- if (!opened.isFile() || opened.nlink !== 1 || (opened.mode & 0o077) !== 0)
178
+ if (!opened.isFile() || opened.nlink !== 1 || !workspacePermissionsAllowed(file, opened))
180
179
  throw new Error('unsafe opened opportunity file');
181
180
  await writeFully(handle, Buffer.from(line, 'utf8'));
182
181
  return true;
@@ -6,6 +6,7 @@ import { readAiwgConfig, resolveDelivery, resolveRemotes, resolveProject, resolv
6
6
  import { sensitiveInputOptions } from '../auth/sensitive-input.js';
7
7
  import { deliveryTracker } from './tracker.js';
8
8
  import { commitOptions, git, push, signingEnabled, verifyCommit } from './git.js';
9
+ import { warnTemplateSections } from './template-sections.js';
9
10
  async function branchCommits(cwd, base, head, config) {
10
11
  if (!signingEnabled(config.delivery))
11
12
  return;
@@ -18,6 +19,7 @@ export async function openPr(cwd, config, client, options) {
18
19
  throw new Error('Opening a PR requires delivery.mode=pr-required');
19
20
  if (!options.title)
20
21
  throw new Error('open requires --title');
22
+ warnTemplateSections(options.body ?? '', 'agentic/code/addons/aiwg-utils/templates/pull-requests/description.md');
21
23
  const remote = resolveRemotes(config.remotes).primary;
22
24
  const head = options.head ?? await git(cwd, 'symbolic-ref', '--short', 'HEAD');
23
25
  await git(cwd, 'check-ref-format', '--branch', head);
@@ -0,0 +1,56 @@
1
+ // Advise issue and PR composers about missing sections using the shipped template headings.
2
+ import { readFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { findPackageRoot } from '../cli/find-package-root.js';
6
+ function headings(markdown) {
7
+ const result = [];
8
+ let fence = '';
9
+ let optional = false;
10
+ for (const line of markdown.split(/\r?\n/)) {
11
+ const marker = line.match(/^\s{0,3}(`{3,}|~{3,})/);
12
+ if (marker) {
13
+ if (!fence)
14
+ fence = marker[1];
15
+ else if (marker[1][0] === fence[0] && marker[1].length >= fence.length)
16
+ fence = '';
17
+ continue;
18
+ }
19
+ if (fence)
20
+ continue;
21
+ const match = line.match(/^##[ \t]+(.+?)[ \t]*#*[ \t]*$/);
22
+ if (match) {
23
+ result.push({ title: match[1], optional: optional || /\(optional\b|<!--\s*optional\s*-->/i.test(match[1]) });
24
+ optional = false;
25
+ }
26
+ else if (line.trim()) {
27
+ optional = /^\s*<!--\s*optional\s*-->\s*$/i.test(line);
28
+ }
29
+ }
30
+ return result;
31
+ }
32
+ const headingKey = (title) => title.replace(/<!--.*?-->/g, '')
33
+ .replace(/\s+\(.*$/, '').trim().replace(/\s+/g, ' ').toLowerCase();
34
+ export function missingTemplateSections(body, template) {
35
+ const present = new Set(headings(body).map(heading => headingKey(heading.title)));
36
+ return headings(template).filter(heading => !heading.optional && !present.has(headingKey(heading.title)))
37
+ .map(heading => heading.title);
38
+ }
39
+ export function warnTemplateSections(body, template, warn = console.warn) {
40
+ const root = process.env.AIWG_ROOT ?? findPackageRoot(path.dirname(fileURLToPath(import.meta.url)));
41
+ let content;
42
+ try {
43
+ if (!root && !path.isAbsolute(template))
44
+ throw new Error('AIWG package root unavailable');
45
+ content = readFileSync(path.resolve(root ?? '.', template), 'utf8');
46
+ }
47
+ catch {
48
+ warn(`Template warning: could not read ${template}; required sections were not checked.`);
49
+ return [];
50
+ }
51
+ const missing = missingTemplateSections(body, content);
52
+ if (missing.length)
53
+ warn(`Template warning (${path.basename(template)}): missing required sections: ${missing.join(', ')}`);
54
+ return missing;
55
+ }
56
+ //# sourceMappingURL=template-sections.js.map
@@ -30,6 +30,7 @@ import { promises as fs } from 'node:fs';
30
30
  import * as path from 'node:path';
31
31
  import { captureDeploymentOutputs, recordDeploymentOutputs } from '../providers/deployment-ownership.mjs';
32
32
  import { mergeClaudeAttribution, undoClaudeAttribution } from './claude-attribution.js';
33
+ import { managedHookScriptState } from './managed-hook-script-state.js';
33
34
  /**
34
35
  * Hook script → Claude Code hook event mapping.
35
36
  *
@@ -44,6 +45,15 @@ const HOOK_SCRIPTS = [
44
45
  events: { SubagentStart: 'start', SubagentStop: 'stop' },
45
46
  },
46
47
  ];
48
+ /** Canonical registrations shared by installation and the read-only drift check. */
49
+ export function managedClaudeHooks(sourceFiles) {
50
+ return HOOK_SCRIPTS.filter(({ file }) => sourceFiles.includes(file)).flatMap(({ file, events }) => Object.entries(events).map(([event, argument]) => ({
51
+ event,
52
+ script: path.posix.join('.claude', 'hooks', file),
53
+ hookId: file.replace(/\.(cjs|js)$/, ''),
54
+ command: `node ${path.posix.join('.claude', 'hooks', file)}${argument ? ` ${argument}` : ''}`,
55
+ })));
56
+ }
47
57
  /**
48
58
  * Migrate a legacy array-shaped `hooks` field to the object form Claude
49
59
  * Code expects. Returns the normalized object.
@@ -143,6 +153,11 @@ export async function installAiwgHooks(opts) {
143
153
  }
144
154
  const src = path.join(sourceHooksDir, file);
145
155
  const dst = path.join(claudeHooksDir, file);
156
+ const state = await managedHookScriptState(opts.projectPath, path.relative(opts.projectPath, dst), await fs.readFile(src));
157
+ if (state === 'operator-edited' || state === 'unreadable') {
158
+ result.warnings.push(`${dst}: kept (${state})`);
159
+ continue;
160
+ }
146
161
  if (opts.dryRun) {
147
162
  result.installedScripts.push(`${dst} (dry-run)`);
148
163
  continue;
@@ -195,67 +210,60 @@ export async function installAiwgHooks(opts) {
195
210
  result.warnings.push('Migrated legacy array-shaped hooks field to object form (#107).');
196
211
  }
197
212
  settings.hooks = hooksObj;
198
- for (const { file, events } of HOOK_SCRIPTS) {
199
- if (!sourceFiles.includes(file))
200
- continue;
213
+ for (const { event, script, hookId, command } of managedClaudeHooks(sourceFiles)) {
201
214
  // Claude Code parses hook commands as shell command strings. Keep the
202
215
  // embedded script path POSIX-style on every host: native Windows
203
216
  // backslashes are interpreted as escapes and collapse into a nonexistent
204
217
  // path such as `.claudehooksaiwg-session.cjs` (#133).
205
- const script = path.posix.join('.claude', 'hooks', file);
206
- const hookId = file.replace(/\.(cjs|js)$/, '');
207
- for (const [event, argument] of Object.entries(events)) {
208
- const command = `node ${script}${argument ? ` ${argument}` : ''}`;
209
- if (!hooksObj[event])
210
- hooksObj[event] = [];
211
- const groups = hooksObj[event];
212
- // Find any existing AIWG-managed entry for this hookId and refresh
213
- // its `command` to the current script path/extension. Required for
214
- // users upgrading from pre-`.cjs` installs where the registered
215
- // command still references `aiwg-{session,trace,permissions}.js` —
216
- // those files no longer exist on disk after refresh, causing
217
- // `MODULE_NOT_FOUND` at `node:internal/modules/cjs/loader` on every
218
- // hook invocation. (Fixes regression report on Claude Code 2.1.157.)
219
- // Match by `_aiwg_id` first, then by the script path. An entry invoking an
220
- // AIWG-owned hook script without the managed tag is AIWG residue from an
221
- // earlier install; appending a managed entry beside it registers the hook
222
- // twice and runs it twice per event. Adopt it instead. (#2543)
223
- let updated = false;
224
- for (const group of groups) {
225
- if (!Array.isArray(group.hooks))
218
+ if (!hooksObj[event])
219
+ hooksObj[event] = [];
220
+ const groups = hooksObj[event];
221
+ // Find any existing AIWG-managed entry for this hookId and refresh
222
+ // its `command` to the current script path/extension. Required for
223
+ // users upgrading from pre-`.cjs` installs where the registered
224
+ // command still references `aiwg-{session,trace,permissions}.js` —
225
+ // those files no longer exist on disk after refresh, causing
226
+ // `MODULE_NOT_FOUND` at `node:internal/modules/cjs/loader` on every
227
+ // hook invocation. (Fixes regression report on Claude Code 2.1.157.)
228
+ // Match by `_aiwg_id` first, then by the script path. An entry invoking an
229
+ // AIWG-owned hook script without the managed tag is AIWG residue from an
230
+ // earlier install; appending a managed entry beside it registers the hook
231
+ // twice and runs it twice per event. Adopt it instead. (#2543)
232
+ let updated = false;
233
+ for (const group of groups) {
234
+ if (!Array.isArray(group.hooks))
235
+ continue;
236
+ for (const h of group.hooks) {
237
+ const sameId = h._aiwg_id === hookId;
238
+ const sameScript = typeof h.command === 'string' && h.command.includes(script);
239
+ if (!sameId && !sameScript)
226
240
  continue;
227
- for (const h of group.hooks) {
228
- const sameId = h._aiwg_id === hookId;
229
- const sameScript = typeof h.command === 'string' && h.command.includes(script);
230
- if (!sameId && !sameScript)
231
- continue;
232
- const adopting = !sameId && sameScript;
233
- if (h.command !== command || h.type !== 'command' || h._aiwg_managed !== true || h._aiwg_id !== hookId) {
234
- h.type = 'command';
235
- h.command = command;
236
- h._aiwg_managed = true;
237
- h._aiwg_id = hookId;
238
- result.warnings.push(adopting
239
- ? `Adopted pre-existing untagged ${event} → ${hookId} entry instead of registering a duplicate`
240
- : `Refreshed stale ${event} → ${hookId} command path`);
241
- }
242
- updated = true;
241
+ const adopting = !sameId && sameScript;
242
+ if (h.command !== command || h.type !== 'command' || h._aiwg_managed !== true || h._aiwg_id !== hookId) {
243
+ h.type = 'command';
244
+ h.command = command;
245
+ h._aiwg_managed = true;
246
+ h._aiwg_id = hookId;
247
+ result.warnings.push(adopting
248
+ ? `Adopted pre-existing untagged ${event} → ${hookId} entry instead of registering a duplicate`
249
+ : `Refreshed stale ${event} → ${hookId} command path`);
243
250
  }
251
+ updated = true;
244
252
  }
245
- if (updated)
246
- continue;
247
- groups.push({
248
- hooks: [
249
- {
250
- type: 'command',
251
- command,
252
- _aiwg_managed: true,
253
- _aiwg_id: hookId,
254
- },
255
- ],
256
- });
257
- result.registeredEvents.push(`${event} → ${hookId}`);
258
253
  }
254
+ if (updated)
255
+ continue;
256
+ groups.push({
257
+ hooks: [
258
+ {
259
+ type: 'command',
260
+ command,
261
+ _aiwg_managed: true,
262
+ _aiwg_id: hookId,
263
+ },
264
+ ],
265
+ });
266
+ result.registeredEvents.push(`${event} → ${hookId}`);
259
267
  }
260
268
  }
261
269
  // 5. Atomic write
@@ -0,0 +1,48 @@
1
+ // Compare hook bytes and deployment receipts without changing either file.
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { createHash } from 'node:crypto';
5
+ export async function managedHookScriptState(projectRoot, file, expected) {
6
+ const target = path.resolve(projectRoot, file);
7
+ let actual;
8
+ try {
9
+ actual = await fs.readFile(target);
10
+ }
11
+ catch (error) {
12
+ return error.code === 'ENOENT' ? 'missing' : 'unreadable';
13
+ }
14
+ const digest = `sha256:${createHash('sha256').update(actual).digest('hex')}`;
15
+ // Writers may record hooks beside the script, at the provider root, or in
16
+ // the project-scoped receipt. Match the same relative claims as preservation.
17
+ const projectReceipt = path.join(projectRoot, '.aiwg/.aiwg-manifest.json');
18
+ const receipts = [];
19
+ for (let dir = path.dirname(target); dir !== path.resolve(projectRoot); dir = path.dirname(dir)) {
20
+ if (!dir.startsWith(`${path.resolve(projectRoot)}${path.sep}`))
21
+ break;
22
+ receipts.push(path.join(dir, '.aiwg-manifest.json'));
23
+ }
24
+ receipts.push(projectReceipt);
25
+ for (const receipt of receipts) {
26
+ let doc;
27
+ try {
28
+ doc = JSON.parse(await fs.readFile(receipt, 'utf8'));
29
+ }
30
+ catch (error) {
31
+ if (error.code === 'ENOENT')
32
+ continue;
33
+ return 'unreadable';
34
+ }
35
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc))
36
+ return 'unreadable';
37
+ const base = receipt === projectReceipt && doc.scope === 'project' ? projectRoot : path.dirname(receipt);
38
+ const name = path.relative(base, target).split(path.sep).join('/');
39
+ const record = doc.managed?.[name];
40
+ if (record?.hash && record.hash !== digest)
41
+ return 'operator-edited';
42
+ // A nearer receipt supersedes an older ancestor claim.
43
+ if (record)
44
+ break;
45
+ }
46
+ return actual.equals(expected) ? undefined : 'outdated';
47
+ }
48
+ //# sourceMappingURL=managed-hook-script-state.js.map
@@ -0,0 +1,49 @@
1
+ // Canonical Muse hook registrations shared by deployment and read-only drift checks.
2
+ export const promptDiscoveryHook = {
3
+ id: 'aiwg-prompt-discovery',
4
+ event: 'UserPromptSubmit',
5
+ group: { matcher: '*', hooks: [{ type: 'command', command: 'node .muse/hooks/aiwg-prompt-discovery.cjs', timeout: 2 }] },
6
+ reason: 'Inject strong AIWG candidates or require discover before answering or declining; skip system turns, bounded and fail open.',
7
+ removal: 'Set AIWG_PROMPT_DISCOVERY=0, or remove this group from .muse/hooks.json.',
8
+ };
9
+ /**
10
+ * The AIWG-managed hook set. Each entry carries a stated reason (why this
11
+ * hook runs on the operator's machine, outside the agent sandbox) and a
12
+ * removal path (how the operator takes it back out).
13
+ *
14
+ * SessionEnd is intentionally *not* installed yet: Muse documents SessionEnd
15
+ * as observational-only (its output cannot block termination or inject
16
+ * context), and AIWG has no session-catalog note command to invoke — wiring
17
+ * a hook to a command that does not exist would fail every session end.
18
+ * When a real catalog-note command lands, it slots in here with its own
19
+ * reason + removal path.
20
+ */
21
+ export const AIWG_MANAGED_HOOKS = [
22
+ {
23
+ id: 'aiwg-session-start',
24
+ event: 'SessionStart',
25
+ // Muse matcher groups take ONLY `hooks` + optional `matcher`; no
26
+ // in-band AIWG tags (they would break the group).
27
+ //
28
+ // Muse Code 1.4.0 parses hook stdout as hook output: empty output, plain
29
+ // text, and `{"hookSpecificOutput": ...}` are accepted, but any other
30
+ // JSON key fails the hook ("unsupported `deploymentFailures` in output of
31
+ // SessionStart hook output"). `aiwg refresh --quiet` prints its JSON
32
+ // report, so stdout is discarded; the exit status still records a failed
33
+ // drift check in Muse's hook log. `--provider muse` is required because
34
+ // provider detection is fail-closed for muse and would resolve `claude`.
35
+ // Hook commands run through a shell, so the redirect is honored.
36
+ group: {
37
+ matcher: '*',
38
+ hooks: [{ type: 'command', command: 'aiwg refresh --dry-run --quiet --provider muse > /dev/null', timeout: 60 }],
39
+ },
40
+ reason: 'Session-start drift check. Runs a read-only `aiwg refresh --dry-run --provider muse` ' +
41
+ 'and records its exit status in the Muse hook log. Dry-run by construction: it ' +
42
+ 'never mutates the repo, and its report is not injected into the session.',
43
+ removal: 'Delete this matcher group from `.muse/hooks.json` (the one whose command is ' +
44
+ '`aiwg refresh --dry-run --quiet --provider muse > /dev/null`), or run `aiwg use --provider muse --no-hooks` ' +
45
+ 'to stop AIWG managing hooks for this project.',
46
+ },
47
+ promptDiscoveryHook,
48
+ ];
49
+ //# sourceMappingURL=muse-managed-hooks.js.map
@@ -117,6 +117,7 @@ async function handleNew(issues, args, cwd) {
117
117
  if (plan.authorizationRequired && authorizationDigest !== plan.digest) {
118
118
  throw new Error(`Issue draft requires explicit policy authorization. Review 'aiwg issue plan', then pass --authorize-policy ${plan.digest}. No issue was written.`);
119
119
  }
120
+ await issues.requireInitialized();
120
121
  const composer = await loadIssueComposer();
121
122
  const records = new Map();
122
123
  const adapter = {
@@ -191,6 +192,8 @@ async function handleList(issues, args) {
191
192
  console.log(JSON.stringify(result, null, 2));
192
193
  return;
193
194
  }
195
+ if (result.issues.length === 0)
196
+ console.log('No matching issues found.');
194
197
  for (const issue of result.issues) {
195
198
  console.log(`${issue.id}\t${issue.status}\t${issue.priority}\t${issue.title}`);
196
199
  }