@aiwg/cli 2026.11.1 → 2026.11.3

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 (120) 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/capability-matrix.yaml +2 -2
  4. package/agentic/code/providers/model-capabilities.v1.json +44 -39
  5. package/agentic/code/providers/model-catalog.v1.json +3 -3
  6. package/dist/src/artifacts/cli.js +10 -11
  7. package/dist/src/artifacts/discover-cli-help.js +25 -0
  8. package/dist/src/artifacts/discover-session-facets.js +2 -1
  9. package/dist/src/artifacts/fortemi-core-prebuilt-freshness.js +28 -0
  10. package/dist/src/artifacts/fortemi-core-sync.js +3 -0
  11. package/dist/src/artifacts/framework-capabilities.js +4 -0
  12. package/dist/src/artifacts/framework-source-digest.js +1 -1
  13. package/dist/src/artifacts/index-builder.js +10 -10
  14. package/dist/src/artifacts/index-dependencies.js +72 -0
  15. package/dist/src/artifacts/query-engine-discover-output.js +13 -5
  16. package/dist/src/artifacts/query-engine-discover.js +49 -21
  17. package/dist/src/artifacts/query-engine-entries.js +56 -2
  18. package/dist/src/artifacts/query-engine-options.js +14 -1
  19. package/dist/src/artifacts/query-engine-scoring.js +8 -4
  20. package/dist/src/artifacts/query-engine-show-card.js +2 -0
  21. package/dist/src/artifacts/query-engine-show-load.js +1 -1
  22. package/dist/src/artifacts/query-engine-show.js +3 -1
  23. package/dist/src/artifacts/query-engine-templates.js +33 -0
  24. package/dist/src/artifacts/query-engine-verbose.js +25 -0
  25. package/dist/src/artifacts/relations-builder.js +49 -4
  26. package/dist/src/artifacts/relations.js +9 -0
  27. package/dist/src/artifacts/template-references.js +42 -0
  28. package/dist/src/artifacts/types.js +1 -1
  29. package/dist/src/cli/handlers/bundle-reconciliation.js +7 -3
  30. package/dist/src/cli/handlers/checkpoint-handoff.js +48 -0
  31. package/dist/src/cli/handlers/checkpoint-record.js +20 -0
  32. package/dist/src/cli/handlers/checkpoint.js +50 -17
  33. package/dist/src/cli/handlers/dataset.js +17 -0
  34. package/dist/src/cli/handlers/decision.js +1 -1
  35. package/dist/src/cli/handlers/doctor-args.js +3 -1
  36. package/dist/src/cli/handlers/doctor-help.js +2 -1
  37. package/dist/src/cli/handlers/help.js +1 -1
  38. package/dist/src/cli/handlers/refresh-bundles.js +2 -1
  39. package/dist/src/cli/handlers/refresh-managed-deployment.js +196 -0
  40. package/dist/src/cli/handlers/refresh.js +10 -2
  41. package/dist/src/cli/handlers/subcommands-discovery.js +8 -1
  42. package/dist/src/cli/handlers/use.js +26 -5
  43. package/dist/src/cli/services/deployment-verification.js +11 -7
  44. package/dist/src/config/decision-config.js +2 -1
  45. package/dist/src/config/jev-credential-reference.js +56 -0
  46. package/dist/src/config/user-config.js +13 -19
  47. package/dist/src/config/worker-write.js +4 -10
  48. package/dist/src/decision/ask.js +3 -2
  49. package/dist/src/decision/jev-credentials.js +22 -0
  50. package/dist/src/decision/ledger.js +15 -15
  51. package/dist/src/decision/offload.js +7 -8
  52. package/dist/src/decision/openbao-kv-resolver.mjs +96 -0
  53. package/dist/src/decision/openbao-runtime.js +101 -0
  54. package/dist/src/delivery/pr.js +2 -0
  55. package/dist/src/delivery/template-sections.js +56 -0
  56. package/dist/src/extensions/claude-hooks-installer.js +61 -53
  57. package/dist/src/extensions/managed-hook-script-state.js +48 -0
  58. package/dist/src/extensions/muse-managed-hooks.js +49 -0
  59. package/dist/src/issues/cli.js +3 -0
  60. package/dist/src/issues/external-cli.js +4 -1
  61. package/dist/src/issues/live.js +9 -2
  62. package/dist/src/issues/local.js +5 -1
  63. package/dist/src/issues/tracker-policy.js +11 -1
  64. package/dist/src/mcp/json-document.d.mts +2 -0
  65. package/dist/src/models/model-capabilities.v1.json +44 -39
  66. package/dist/src/models/model-catalog.v1.json +3 -3
  67. package/dist/src/models/provider-policy.js +8 -0
  68. package/dist/src/models/worker-health-readiness.js +20 -4
  69. package/dist/src/models/worker-health-snapshot.js +29 -0
  70. package/dist/src/models/worker-installation.d.mts +5 -1
  71. package/dist/src/models/worker-installation.mjs +11 -5
  72. package/dist/src/models/worker-qualification-policy.js +54 -0
  73. package/dist/src/providers/capability-matrix.yaml +2 -2
  74. package/dist/src/providers/skill-ownership.d.mts +1 -0
  75. package/dist/src/providers/transformation-receipt-integration.js +4 -2
  76. package/dist/src/providers/transformation-receipt.js +4 -2
  77. package/dist/src/serve/worker-invocation.js +4 -2
  78. package/dist/src/smiths/context-pipeline/workspace-audit.js +34 -17
  79. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +12 -6
  80. package/dist/src/smiths/context-pipeline/workspace-doctor.js +48 -4
  81. package/dist/src/smiths/context-pipeline/workspace-document.js +5 -2
  82. package/dist/src/smiths/context-pipeline/workspace-migration.js +2 -1
  83. package/dist/src/smiths/hook-bridge/codex-translator.js +150 -94
  84. package/dist/src/smiths/hook-bridge/codex-trust.js +50 -0
  85. package/dist/src/smiths/hook-bridge/factory-hook-config.js +132 -0
  86. package/dist/src/smiths/hook-bridge/factory-translator.js +88 -33
  87. package/dist/src/smiths/hook-bridge/factory-trust.js +56 -0
  88. package/dist/src/smiths/hook-bridge/index.js +3 -3
  89. package/dist/src/smiths/hook-bridge/loader.js +10 -2
  90. package/dist/src/smiths/hook-bridge/prompt-discovery-gaps.js +0 -1
  91. package/dist/src/storage/workspace-permissions-health.js +64 -0
  92. package/dist/src/storage/workspace-permissions.js +51 -0
  93. package/package.json +6 -1
  94. package/tools/agents/providers/base-files.mjs +2 -1
  95. package/tools/agents/providers/base-flat-artifacts.mjs +6 -3
  96. package/tools/agents/providers/base-models-platforms.mjs +3 -3
  97. package/tools/agents/providers/base-skill-copy.mjs +2 -0
  98. package/tools/agents/providers/bound-rules-pointer.mjs +21 -0
  99. package/tools/agents/providers/claude-post-deploy.mjs +9 -5
  100. package/tools/agents/providers/codex-post-deploy.mjs +10 -0
  101. package/tools/agents/providers/factory-hooks.mjs +43 -0
  102. package/tools/agents/providers/factory.mjs +4 -91
  103. package/tools/agents/providers/muse-hooks.mjs +4 -43
  104. package/tools/agents/providers/muse-prompt-discovery.mjs +3 -7
  105. package/tools/agents/providers/packaged-codex-agents.mjs +48 -0
  106. package/tools/agents/providers/rule-delivery-surface.mjs +4 -4
  107. package/tools/agents/providers/rule-presentation.mjs +6 -5
  108. package/tools/agents/providers/rule-projection.mjs +10 -2
  109. package/tools/agents/providers/rule-startup.mjs +8 -1
  110. package/tools/cli/decision-offload-report.mjs +9 -2
  111. package/tools/plugin/issue-template-copies.mjs +24 -0
  112. package/tools/plugin/package-plugins.mjs +17 -4
  113. package/tools/ralph-external/lib/claude-adapter.mjs +2 -2
  114. package/tools/ralph-external/lib/factory-adapter.mjs +7 -8
  115. package/tools/ralph-external/lib/worker-artifacts.mjs +4 -2
  116. package/tools/ralph-external/lib/worker-final.mjs +43 -8
  117. package/tools/ralph-external/lib/worker-launch-cli.mjs +10 -1
  118. package/tools/ralph-external/lib/worker-prompt.mjs +35 -0
  119. package/tools/ralph-external/lib/worker-run-directory-refusal.mjs +8 -0
  120. package/tools/ralph-external/session-launcher.mjs +10 -7
@@ -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;
@@ -510,7 +509,7 @@ export async function buildDecisionOffloadSnapshot(options) {
510
509
  since: sessionId ? null : since.toISOString(), windowHours: sessionId ? null : windowHours, generatedAt: now.toISOString() },
511
510
  readiness: {
512
511
  ask: { state: askReadinessState(askConfigured, latestTransportEvidence), configured: credential.configured,
513
- enabled: credential.enabled, source: credential.source, probed: false },
512
+ enabled: credential.enabled, source: credential.source, ...(credential.path ? { path: credential.path } : {}), probed: false },
514
513
  evaluate: { state: evaluateState, enabled: enablement?.enabled ?? null,
515
514
  source: configReadable && enablement ? enablement.source : 'unknown', probed: false },
516
515
  observed: latestObserved ? {
@@ -0,0 +1,96 @@
1
+ // Shared exact-path OpenBao KV policy for runtime and qualification callers.
2
+ export class CredentialResolutionError extends Error {
3
+ constructor(category) {
4
+ super('credential resolution failed');
5
+ this.name = 'CredentialResolutionError';
6
+ this.category = category;
7
+ }
8
+ }
9
+
10
+ const SEGMENT = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/;
11
+ const REF = /^[a-z0-9][a-z0-9._-]{0,63}$/;
12
+
13
+ /** Validates the host-only config. It holds locators, never secret values. */
14
+ export function validateResolverConfig(config) {
15
+ const fail = () => { throw new CredentialResolutionError('configuration'); };
16
+ if (!config || typeof config !== 'object' || Array.isArray(config)) fail();
17
+ const allowed = ['schemaVersion', 'addr', 'caFile', 'appRole', 'tokenScript', 'mount', 'refs'];
18
+ if (Object.keys(config).some(key => !allowed.includes(key)) || config.schemaVersion !== 'openbao-kv-resolver-config/v1') fail();
19
+ let addr;
20
+ try { addr = new URL(config.addr); } catch { fail(); }
21
+ if (addr.protocol !== 'https:' || addr.username || addr.password || addr.search || addr.hash || addr.pathname !== '/') fail();
22
+ if (config.caFile !== undefined && (typeof config.caFile !== 'string' || !config.caFile.startsWith('/'))) fail();
23
+ if (!SEGMENT.test(config.appRole ?? '') || typeof config.tokenScript !== 'string' || !config.tokenScript.startsWith('/') || !SEGMENT.test(config.mount ?? '')) fail();
24
+ if (!config.refs || typeof config.refs !== 'object' || Array.isArray(config.refs) || !Object.keys(config.refs).length) fail();
25
+ for (const [ref, target] of Object.entries(config.refs)) {
26
+ if (!REF.test(ref) || !target || typeof target !== 'object' || Object.keys(target).some(key => !['path', 'field'].includes(key))) fail();
27
+ if (typeof target.path !== 'string' || !target.path.split('/').every(part => SEGMENT.test(part))) fail();
28
+ if (target.field !== undefined && !SEGMENT.test(target.field)) fail();
29
+ }
30
+ return config;
31
+ }
32
+
33
+ /**
34
+ * Creates the resolver. `tokenProvider` and `request` are injectable for offline tests.
35
+ * Granted values are cached per logical ref for the run and zeroed by `dispose()`.
36
+ */
37
+ export function createOpenBaoKvResolver(rawConfig, seams) {
38
+ // Refuse a process that has disabled TLS verification globally, even with an injected request seam.
39
+ if (process.env.NODE_TLS_REJECT_UNAUTHORIZED === '0') throw new CredentialResolutionError('configuration');
40
+ const config = validateResolverConfig(rawConfig);
41
+ const tokenProvider = seams.tokenProvider;
42
+ const request = seams.request;
43
+ const entries = [];
44
+ const cache = new Map();
45
+ let token;
46
+ let disposed = false;
47
+ let seq = 0;
48
+ const record = (op, ref, outcome, httpStatus) => { entries.push({ seq: ++seq, op, ref, outcome, httpStatus }); };
49
+ const login = () => {
50
+ token ??= tokenProvider().then(value => { record('login', null, 'granted', null); return value; },
51
+ () => { record('login', null, 'failed', null); throw new CredentialResolutionError('failed'); });
52
+ return token;
53
+ };
54
+ return {
55
+ async resolveCredential(ref) {
56
+ if (disposed) throw new CredentialResolutionError('failed');
57
+ const target = typeof ref === 'string' && REF.test(ref) ? config.refs[ref] : undefined;
58
+ if (!target || !Object.hasOwn(config.refs, ref)) { record('read', REF.test(String(ref)) ? ref : 'invalid-ref', 'configuration', null); throw new CredentialResolutionError('configuration'); }
59
+ if (cache.has(ref)) return new Uint8Array(cache.get(ref));
60
+ const value = await login();
61
+ const url = new URL(`/v1/${config.mount}/data/${target.path}`, config.addr);
62
+ let response;
63
+ try { response = await request(url, { 'X-Vault-Token': value, accept: 'application/json' }); }
64
+ catch { record('read', ref, 'failed', null); throw new CredentialResolutionError('failed'); }
65
+ const status = response?.status ?? 0;
66
+ if (status === 403) { record('read', ref, 'denied', status); throw new CredentialResolutionError('denied'); }
67
+ if (status === 404) { record('read', ref, 'missing', status); throw new CredentialResolutionError('missing'); }
68
+ const data = status === 200 ? response.json?.data?.data : undefined;
69
+ const keys = data && typeof data === 'object' && !Array.isArray(data) ? Object.keys(data) : [];
70
+ const field = target.field ?? (keys.length === 1 ? keys[0] : undefined);
71
+ const secret = field !== undefined && data ? data[field] : undefined;
72
+ if (typeof secret !== 'string' || !secret) { record('read', ref, status === 200 ? 'configuration' : 'failed', status); throw new CredentialResolutionError(status === 200 ? 'configuration' : 'failed'); }
73
+ record('read', ref, 'granted', status);
74
+ const bytes = new TextEncoder().encode(secret);
75
+ cache.set(ref, bytes);
76
+ return new Uint8Array(bytes);
77
+ },
78
+ /** Sanitized: logical refs, operation, outcome and HTTP status only. */
79
+ audit: () => entries.map(entry => ({ ...entry })),
80
+ /** Zeroes cached values and revokes the AppRole token itself. Revocation failure is recorded, never thrown. */
81
+ async dispose() {
82
+ disposed = true;
83
+ for (const bytes of cache.values()) bytes.fill(0);
84
+ cache.clear();
85
+ const pending = token; token = undefined;
86
+ if (!pending) return;
87
+ let value;
88
+ try { value = await pending; } catch { return; }
89
+ try {
90
+ const response = await request(new URL('/v1/auth/token/revoke-self', config.addr), { 'X-Vault-Token': value }, 'POST');
91
+ const status = response?.status ?? 0;
92
+ record('revoke', null, status === 204 || status === 200 ? 'revoked' : 'failed', status);
93
+ } catch { record('revoke', null, 'failed', null); }
94
+ },
95
+ };
96
+ }
@@ -0,0 +1,101 @@
1
+ // Resolve Jev references through the shared KV policy and host native secret store.
2
+ import { request as httpsRequest } from 'node:https';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { createSecretStore } from '../auth/credential-store.js';
5
+ // @ts-expect-error Shared ESM policy also consumed directly by qualification tools.
6
+ import { createOpenBaoKvResolver } from './openbao-kv-resolver.mjs';
7
+ export class JevReferenceUnavailable extends Error {
8
+ constructor() { super('credential-unavailable'); }
9
+ }
10
+ const cache = new Map();
11
+ const safeToken = (value) => typeof value === 'string' && /^[\x21-\x7e]{1,4096}$/.test(value);
12
+ /** Fixed diagnostics, no redirects, bounded body and deadline, verified TLS only. */
13
+ function requestJson(url, method, headers, ca, body) {
14
+ return new Promise((resolve, reject) => {
15
+ const fail = () => { reject(new JevReferenceUnavailable()); };
16
+ const req = httpsRequest(url, { method, headers, ca, rejectUnauthorized: true, timeout: 10_000 }, res => {
17
+ const chunks = [];
18
+ let size = 0;
19
+ res.on('data', (chunk) => {
20
+ size += chunk.length;
21
+ if (size > 64 * 1024) {
22
+ req.destroy();
23
+ fail();
24
+ }
25
+ else
26
+ chunks.push(chunk);
27
+ });
28
+ res.on('error', fail);
29
+ res.on('aborted', fail);
30
+ res.on('end', () => {
31
+ let json;
32
+ try {
33
+ json = JSON.parse(Buffer.concat(chunks).toString('utf8'));
34
+ }
35
+ catch {
36
+ json = null;
37
+ }
38
+ resolve({ status: res.statusCode ?? 0, json });
39
+ });
40
+ });
41
+ const deadline = setTimeout(() => { req.destroy(); fail(); }, 10_000);
42
+ req.on('close', () => clearTimeout(deadline));
43
+ req.on('error', fail);
44
+ req.on('timeout', () => { req.destroy(); fail(); });
45
+ req.end(body);
46
+ });
47
+ }
48
+ export async function resolveOpenBaoJev(ref, env) {
49
+ try {
50
+ const addr = new URL(env.BAO_ADDR?.trim() || ref.addr || '');
51
+ if (addr.protocol !== 'https:' || addr.username || addr.password || addr.search || addr.hash || addr.pathname !== '/'
52
+ || env.NODE_TLS_REJECT_UNAUTHORIZED === '0' || process.env.NODE_TLS_REJECT_UNAUTHORIZED === '0')
53
+ throw new JevReferenceUnavailable();
54
+ const key = JSON.stringify([addr.href, env.BAO_CACERT, ref]);
55
+ let pending = cache.get(key);
56
+ if (!pending) {
57
+ pending = resolveReference(ref, addr, env).catch(() => { cache.delete(key); throw new JevReferenceUnavailable(); });
58
+ cache.set(key, pending);
59
+ }
60
+ return await pending;
61
+ }
62
+ catch {
63
+ throw new JevReferenceUnavailable();
64
+ }
65
+ }
66
+ async function resolveReference(ref, addr, env) {
67
+ const ca = env.BAO_CACERT ? await readFile(env.BAO_CACERT) : undefined;
68
+ const [mount, , ...segments] = ref.path.split('/');
69
+ const resolver = createOpenBaoKvResolver({ schemaVersion: 'openbao-kv-resolver-config/v1', addr: addr.href,
70
+ appRole: ref.auth.role, tokenScript: '/unused-native-store', mount,
71
+ refs: { jev: { path: segments.join('/'), field: ref.field } } }, {
72
+ tokenProvider: async () => {
73
+ const read = (suffix) => createSecretStore({ service: 'aiwg.openbao', account: `${addr.origin}/${ref.auth.role}:${suffix}` }).loadSecret();
74
+ const [roleId, secretId] = await Promise.all([read('role-id'), read('secret-id')]);
75
+ if (!safeToken(roleId) || !safeToken(secretId))
76
+ throw new JevReferenceUnavailable();
77
+ const result = await requestJson(new URL('/v1/auth/approle/login', addr), 'POST', { 'content-type': 'application/json' }, ca, JSON.stringify({ role_id: roleId, secret_id: secretId }));
78
+ const token = result.json?.auth?.client_token;
79
+ if (result.status !== 200 || !safeToken(token))
80
+ throw new JevReferenceUnavailable();
81
+ return token;
82
+ },
83
+ request: (url, headers, method = 'GET') => requestJson(url, method, headers, ca),
84
+ });
85
+ try {
86
+ const bytes = await resolver.resolveCredential('jev');
87
+ try {
88
+ const token = new TextDecoder().decode(bytes);
89
+ if (!safeToken(token))
90
+ throw new JevReferenceUnavailable();
91
+ return token;
92
+ }
93
+ finally {
94
+ bytes.fill(0);
95
+ }
96
+ }
97
+ finally {
98
+ await resolver.dispose();
99
+ }
100
+ }
101
+ //# sourceMappingURL=openbao-runtime.js.map
@@ -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