@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
@@ -754,7 +754,7 @@ async function qualificationSignatureFailure(record, trust) {
754
754
  * This is historical evidence, not current launch authority; loadRecordedWorkerInstallations
755
755
  * performs binary/version/scope checks when dispatch actually requests a binding.
756
756
  */
757
- export async function inspectRecordedWorkerQualifications({ cwd, policy, parallelism }) {
757
+ export async function inspectRecordedWorkerQualifications({ cwd, policy, parallelism, includeInputs = false }) {
758
758
  const filename = installationStorePath();
759
759
  await assertTrustedStore(filename, [cwd]);
760
760
  const { stored } = await readInstallationStore(filename);
@@ -776,7 +776,8 @@ export async function inspectRecordedWorkerQualifications({ cwd, policy, paralle
776
776
  if (!proof || ['scopeDigest', 'fixtureDigest', 'verifiedAt', 'evidenceRef'].some(key => proof[key] !== installation.evidence?.[key])) continue;
777
777
  if (await qualificationSignatureFailure(record, () => qualificationTrust(cwd))) continue;
778
778
  await assertWorkerInstallationEvidence({ ...installation, adapter, now: Date.now(), policy }, proof.scopeDigest);
779
- results.push({ cli, provider: adapter.provider });
779
+ results.push({ cli, provider: adapter.provider, ...(includeInputs
780
+ ? { binding: structuredClone(binding), adapter: structuredClone(adapter), observations: structuredClone(record.modelObservations) } : {}) });
780
781
  } catch { /* Malformed, expired or unbound evidence is not qualification. */ }
781
782
  }
782
783
  return results.filter(row => results.filter(other => row.cli === other.cli).length === 1);
@@ -836,15 +837,20 @@ export async function recordWorkerInstallation(instance, options) {
836
837
  /** Read recorded host authority, validate installation bytes and the current CLI
837
838
  * version, then load the same approved factory used by Ralph. */
838
839
  export async function loadRecordedWorkerInstallations({ registry, cwd, policy, parallelism, storePath, storeDigest, precheckPolicy }) {
839
- const { WorkerPolicyError, parseProviderModelCapabilities } = await import('./provider-policy.js');
840
+ const { WorkerPolicyError, WorkerQualificationPolicyError, parseProviderModelCapabilities } = await import('./provider-policy.js');
841
+ // Compiled TS modules load lazily so the managed launcher's ESM-only import chain stays minimal (#3851).
842
+ const { workerQualificationPolicyDiagnostic } = await import('./worker-qualification-policy.js');
840
843
  const { qualificationDigest } = await import('./qualification-digest.mjs');
841
- // Only fixed stage codes and bounded record indexes may leave this boundary.
844
+ // Only fixed stage codes, bounded indexes and signed policy-drift summaries leave this boundary.
842
845
  // Underlying errors can contain probe output, environment values or paths.
843
846
  const rejections = [];
844
- const fail = () => new WorkerPolicyError('OG_ADAPTER_UNQUALIFIED',
847
+ const fail = () => {
848
+ const mismatch = workerQualificationPolicyDiagnostic(rejections, stored?.registrations, policy);
849
+ return mismatch ? new WorkerQualificationPolicyError(mismatch, rejections) : new WorkerPolicyError('OG_ADAPTER_UNQUALIFIED',
845
850
  `Trusted installation qualification is required (${[...new Set(rejections.map(row => row.reason))].join(', ')})${rejections.some(row => row.reason.startsWith('signature-'))
846
851
  ? `. ${rejections.some(row => row.reason === 'signature-trust-unavailable') ? keyRecoveryMessage : requalifyMessage}` : ''}`,
847
852
  { rejections });
853
+ };
848
854
  let reason = 'store-binding';
849
855
  let filename;
850
856
  let stored, digest;
@@ -0,0 +1,54 @@
1
+ /** Explain recorded worker-policy drift without disclosing policy values or dynamic keys. */
2
+ import path from 'node:path';
3
+ import { WorkerSelectionPolicySchema } from './worker-selection-policy.js';
4
+ import { qualificationDigest } from './qualification-digest.mjs';
5
+ const policyPointer = '/defaults/workerSelection';
6
+ // Schema-owned names are public; model IDs, role aliases, paths and values are not.
7
+ const fieldNames = {
8
+ guards: Object.keys(WorkerSelectionPolicySchema.shape.guards.unwrap().shape),
9
+ dataPolicy: Object.keys(WorkerSelectionPolicySchema.shape.dataPolicy.unwrap().shape),
10
+ freshness: Object.keys(WorkerSelectionPolicySchema.shape.freshness.unwrap().shape),
11
+ };
12
+ function changedPointers(before, after) {
13
+ const pointers = [];
14
+ const oldPolicy = before;
15
+ const newPolicy = (after ?? {});
16
+ for (const key of Object.keys(WorkerSelectionPolicySchema.shape)) {
17
+ if (qualificationDigest([oldPolicy[key]]) === qualificationDigest([newPolicy[key]]))
18
+ continue;
19
+ const fields = fieldNames[key];
20
+ if (!fields) {
21
+ pointers.push(`${policyPointer}/${key}`);
22
+ continue;
23
+ }
24
+ const oldFields = (oldPolicy[key] ?? {});
25
+ const newFields = (newPolicy[key] ?? {});
26
+ for (const field of fields) {
27
+ if (qualificationDigest([oldFields[field]]) !== qualificationDigest([newFields[field]])) {
28
+ pointers.push(`${policyPointer}/${key}/${field}`);
29
+ }
30
+ }
31
+ }
32
+ return pointers.length ? pointers : [policyPointer];
33
+ }
34
+ /** Called only for the loader's fixed rejection stages, after signature verification. */
35
+ export function workerQualificationPolicyDiagnostic(rejections, records, policy) {
36
+ const diagnostics = rejections.filter(row => row.reason === 'effective-config-digest' && row.registration !== null)
37
+ .map(row => {
38
+ const installed = records?.[row.registration]?.installation;
39
+ // Older or inconsistent records cannot establish which individual fields changed.
40
+ const pointers = installed?.policy && qualificationDigest(installed.policy) === installed.effectiveConfigDigest
41
+ ? changedPointers(installed.policy, policy) : [policyPointer];
42
+ const workspace = typeof installed?.cwd === 'string' && path.isAbsolute(installed.cwd)
43
+ ? ` ${JSON.stringify(installed.cwd)}` : '';
44
+ return { code: 'OG_ADAPTER_UNQUALIFIED',
45
+ pointer: pointers.length === 1 ? pointers[0] : policyPointer,
46
+ message: `Worker policy changed since qualification (effective-config-digest; pointers: ${pointers.join(', ')}); `
47
+ + `align the shared project policy in the conductor and worker trees, then requalify the worker tree${workspace} `
48
+ + 'by running aiwg doctor --probe-workers --qualify there.' };
49
+ });
50
+ return diagnostics.length ? { code: 'OG_ADAPTER_UNQUALIFIED',
51
+ pointer: diagnostics.length === 1 ? diagnostics[0].pointer : policyPointer,
52
+ message: diagnostics.map(row => row.message).join(' ') } : null;
53
+ }
54
+ //# sourceMappingURL=worker-qualification-policy.js.map
@@ -26,10 +26,10 @@ providers:
26
26
  probe_budget: { status: authorized, calls: 3, tokens: 30000, authorized_by: operator, authorized_at: "2026-10-07", hosts: [titan, noodle] }
27
27
  coverage:
28
28
  profile_issue: "roctinam/aiwg#2900"
29
- source_date: "2026-10-08"
29
+ source_date: "2026-11-07"
30
30
  live_qualified: false
31
31
  sources:
32
- - "host-help: claude 2.1.295 on titan (--version/--help only)"
32
+ - "host-help: claude 2.1.319 on titan (--version/--help/-p --help only)"
33
33
  - "tools/ralph-external/lib/claude-adapter.mjs"
34
34
  status: stable
35
35
  daemon_tier: unsupported
@@ -4,6 +4,7 @@ export interface ArtifactOwnershipRecord {
4
4
  frameworkSlug?: string;
5
5
  source?: string;
6
6
  sourcePath?: string;
7
+ sourceHash?: string;
7
8
  version?: string;
8
9
  kind?: string;
9
10
  settings?: Record<string, SettingsOwnershipRecord>;
@@ -1,3 +1,4 @@
1
+ import { workspaceFileMode, workspaceDirectoryMode, preserveReplacementMode } from '../storage/workspace-permissions.js';
1
2
  import { createHash, randomUUID } from 'node:crypto';
2
3
  import { access, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
4
  import { homedir } from 'node:os';
@@ -37,7 +38,7 @@ function validateEvidenceState(value) {
37
38
  async function writeEvidenceState(options, disposition) {
38
39
  const provider = normalizeProviderDefinitionId(options.provider) ?? options.provider;
39
40
  const target = providerTransformationEvidenceStatePath(options.projectRoot, provider, options.scope);
40
- await mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
41
+ await mkdir(path.dirname(target), { recursive: true, mode: workspaceDirectoryMode(path.dirname(target)) });
41
42
  const temporary = path.join(path.dirname(target), `.${path.basename(target)}.${randomUUID()}.tmp`);
42
43
  const state = {
43
44
  schemaVersion: PROVIDER_TRANSFORMATION_EVIDENCE_STATE_SCHEMA,
@@ -47,7 +48,8 @@ async function writeEvidenceState(options, disposition) {
47
48
  disposition,
48
49
  };
49
50
  try {
50
- await writeFile(temporary, `${JSON.stringify(state, null, 2)}\n`, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
51
+ await writeFile(temporary, `${JSON.stringify(state, null, 2)}\n`, { encoding: 'utf8', mode: workspaceFileMode(target), flag: 'wx' });
52
+ await preserveReplacementMode(temporary, target);
51
53
  await rename(temporary, target);
52
54
  }
53
55
  catch (error) {
@@ -1,3 +1,4 @@
1
+ import { workspaceFileMode, workspaceDirectoryMode, preserveReplacementMode } from '../storage/workspace-permissions.js';
1
2
  import { createHash, randomUUID } from 'node:crypto';
2
3
  import { lstat, mkdir, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises';
3
4
  import path from 'node:path';
@@ -110,7 +111,7 @@ export async function createProviderTransformationReceipt(options) {
110
111
  export async function writeProviderTransformationReceipt(projectRoot, receipt) {
111
112
  validateProviderTransformationReceipt(receipt);
112
113
  const destination = projectAiwgWritePath(projectRoot, 'receipts', 'providers', `${receipt.provider}.${receipt.scope}.json`);
113
- await mkdir(path.dirname(destination), { recursive: true });
114
+ await mkdir(path.dirname(destination), { recursive: true, mode: workspaceDirectoryMode(path.dirname(destination)) });
114
115
  try {
115
116
  const existing = validateProviderTransformationReceipt(JSON.parse(await readFile(destination, 'utf8')));
116
117
  const semantic = (value) => JSON.stringify({ ...value, generatedAt: undefined });
@@ -123,8 +124,9 @@ export async function writeProviderTransformationReceipt(projectRoot, receipt) {
123
124
  const temporary = `${destination}.${randomUUID()}.tmp`;
124
125
  try {
125
126
  await writeFile(temporary, `${JSON.stringify(receipt, null, 2)}\n`, {
126
- encoding: 'utf8', mode: 0o600, flag: 'wx',
127
+ encoding: 'utf8', mode: workspaceFileMode(destination), flag: 'wx',
127
128
  });
129
+ await preserveReplacementMode(temporary, destination);
128
130
  await rename(temporary, destination);
129
131
  }
130
132
  catch (error) {
@@ -12,7 +12,7 @@ import { assertValidWorkerPayload } from '../mission-protocol/codecs.js';
12
12
  import { qualificationDigest } from '../models/qualification-digest.mjs';
13
13
  import { prepareWorkerInvocation } from './worker-invocation-preparation.js';
14
14
  export { prepareWorkerInvocation, mcpToolSchemaDigest } from './worker-invocation-preparation.js';
15
- import { isOperatorQualifiedWorkerAdapter, assertOperatorWorkerNativeArgv, assertWorkerLaunchMode, WorkerRoleEffortError, requiredWorkerControls, isCanonicalWorkerModelKey, WorkerPolicyError, DEFAULT_WORKER_SELECTION } from '../models/provider-policy.js';
15
+ import { isOperatorQualifiedWorkerAdapter, assertOperatorWorkerNativeArgv, assertWorkerLaunchMode, WorkerRoleEffortError, WorkerQualificationPolicyError, requiredWorkerControls, isCanonicalWorkerModelKey, WorkerPolicyError, DEFAULT_WORKER_SELECTION } from '../models/provider-policy.js';
16
16
  /** Frozen per-attempt windows; parent/transport ceilings include time already spent. */
17
17
  export function resolveWorkerEffectiveHealth(config, input) {
18
18
  const roleDefaults = { efficiency: 1, coding: 1, reasoning: 2 };
@@ -374,8 +374,10 @@ export async function resolveWorkerInvocation(snapshot, request, drivers, now =
374
374
  return plan;
375
375
  }
376
376
  }
377
- /** Public diagnostics contain fixed summaries or explicit typed request-path details. */
377
+ /** Public diagnostics contain fixed summaries or explicit typed policy and path details. */
378
378
  export function workerInvocationDiagnostic(error, pointer, fallback = 'OG_CONFIG_REFERENCE') {
379
+ if (error instanceof WorkerQualificationPolicyError)
380
+ return { code: error.code, pointer: error.pointer, message: error.message };
379
381
  if (error instanceof WorkerRoleEffortError)
380
382
  return { code: error.code, pointer: error.pointer, message: error.message };
381
383
  if (error instanceof WorkerPathScopeError || error instanceof WorkerRequestArgumentError) {
@@ -27,17 +27,43 @@ export function directivePolarity(directive) {
27
27
  return /^(?:never|do not|don't|avoid)\b/i.test(directive) ? 'negative' : 'positive';
28
28
  }
29
29
  export function sensitiveEvidence(content) {
30
+ return sensitiveLineEvidence(content).map((finding) => finding.evidence);
31
+ }
32
+ function sensitiveLineEvidence(content) {
30
33
  const findings = [];
31
- for (const line of content.split('\n')) {
34
+ for (const [index, line] of content.split('\n').entries()) {
32
35
  if (/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/.test(line)) {
33
- findings.push(`private-key material (${sha256(line).slice(0, 12)})`);
36
+ findings.push({ line: index + 1, evidence: `private-key material (${sha256(line).slice(0, 12)})` });
34
37
  }
35
- if (/\b(?:api[_-]?key|token|secret|password)\s*[:=]\s*(?!<|\$\{|\*{3}|example|placeholder)["']?[A-Za-z0-9_\-/.+=]{12,}/i.test(line)) {
36
- findings.push(`credential-like assignment (${sha256(line).slice(0, 12)})`);
38
+ // Inspect whole values before applying the length threshold: ellipses and
39
+ // redaction characters are documentation, including inside quoted agent bodies.
40
+ const assignments = line.matchAll(/\b(?:api[_-]?key|token|secret|password)\s*[:=]\s*["']?([A-Za-z0-9_\-/.+=…*]+)/gi);
41
+ for (const [, value] of assignments) {
42
+ if (value.length < 12 || /(?:\.{3}|…)$/.test(value)
43
+ || /^(?:example|placeholder|\*{3})/i.test(value) || /^x+$/i.test(value)
44
+ || (value.match(/\./g)?.length ?? 0) > value.length / 2)
45
+ continue;
46
+ findings.push({ line: index + 1, evidence: `credential-like assignment (${sha256(line).slice(0, 12)})` });
47
+ break;
37
48
  }
38
49
  }
39
50
  return findings;
40
51
  }
52
+ function operatorContext(relativePath, content, preserveLines = false) {
53
+ if (relativePath === 'WORKSPACE.md') {
54
+ const start = content.indexOf(WORKSPACE_OPERATOR_START);
55
+ const end = content.indexOf(WORKSPACE_OPERATOR_END);
56
+ if (start >= 0 && end > start) {
57
+ const offset = start + WORKSPACE_OPERATOR_START.length;
58
+ const body = content.slice(offset, end);
59
+ return preserveLines
60
+ ? '\n'.repeat(content.slice(0, offset).split('\n').length - 1) + stripGeneratedBlocks(body, true)
61
+ : body.trim();
62
+ }
63
+ return stripGeneratedBlocks(content, preserveLines);
64
+ }
65
+ return isGeneratedRootContext(relativePath, content) ? '' : stripGeneratedBlocks(content, preserveLines);
66
+ }
41
67
  // Directory names the context-graph walk always skips, regardless of where
42
68
  // the walk root is: VCS/build output that is never hand-authored project
43
69
  // content (#277, pre-existing) plus two reserved, self-identifying names
@@ -194,19 +220,10 @@ export async function auditWorkspaceContext(projectPath) {
194
220
  const content = await readOptional(path.join(projectPath, relativePath));
195
221
  if (content === null)
196
222
  continue;
197
- const operatorContent = relativePath === 'WORKSPACE.md'
198
- ? (() => {
199
- const start = content.indexOf(WORKSPACE_OPERATOR_START);
200
- const end = content.indexOf(WORKSPACE_OPERATOR_END);
201
- return start >= 0 && end > start
202
- ? content.slice(start + WORKSPACE_OPERATOR_START.length, end).trim()
203
- : stripGeneratedBlocks(content);
204
- })()
205
- : isGeneratedRootContext(relativePath, content)
206
- ? ''
207
- : stripGeneratedBlocks(content);
208
- for (const evidence of sensitiveEvidence(operatorContent))
209
- sensitiveFindings.push({ path: relativePath, evidence });
223
+ const operatorContent = operatorContext(relativePath, content);
224
+ for (const finding of sensitiveLineEvidence(operatorContext(relativePath, content, true))) {
225
+ sensitiveFindings.push({ path: relativePath, ...finding });
226
+ }
210
227
  sources.push({
211
228
  path: relativePath,
212
229
  provider: providerForPath(relativePath),
@@ -85,20 +85,26 @@ export function replaceBlock(content, start, end, block) {
85
85
  const renderedBlock = withLineEnding(block, dominantLineEnding(content));
86
86
  return content.slice(0, startIndex) + renderedBlock + content.slice(endIndex + end.length);
87
87
  }
88
- export function stripGeneratedBlocks(content) {
88
+ export function stripGeneratedBlocks(content, preserveLines = false) {
89
89
  let stripped = content;
90
90
  for (const [start, end] of GENERATED_BLOCKS) {
91
91
  while (stripped.includes(start) || stripped.includes(end)) {
92
- const replaced = replaceBlock(stripped, start, end, '');
92
+ const startIndex = stripped.indexOf(start);
93
+ const endIndex = stripped.indexOf(end);
94
+ const replacement = preserveLines && startIndex >= 0 && endIndex > startIndex
95
+ ? '\n'.repeat(stripped.slice(startIndex, endIndex + end.length).split('\n').length - 1)
96
+ : '';
97
+ const replaced = replaceBlock(stripped, start, end, replacement);
93
98
  if (replaced === null)
94
99
  break;
95
100
  stripped = replaced;
96
101
  }
97
102
  }
98
- return stripped
99
- .replace(/^(?:\uFEFF)?<!-- aiwg-managed -->[ \t]*(?:\r?\n|$)/, '')
100
- .replace(/^<!-- Generated by AIWG[^\r\n]*-->[ \t]*(?:\r?\n|$)/, '')
101
- .trim();
103
+ const removeMetadata = (text) => preserveLines ? text.replace(/[^\n]/g, '') : '';
104
+ stripped = stripped
105
+ .replace(/^(?:\uFEFF)?<!-- aiwg-managed -->[ \t]*(?:\r?\n|$)/, removeMetadata)
106
+ .replace(/^<!-- Generated by AIWG[^\r\n]*-->[ \t]*(?:\r?\n|$)/, removeMetadata);
107
+ return preserveLines ? stripped : stripped.trim();
102
108
  }
103
109
  export function isGeneratedRootContext(relativePath, content) {
104
110
  const head = maskCodeRegions(content.replace(/^\uFEFF/, '')).split('\n').slice(0, 12).join('\n');
@@ -7,6 +7,8 @@ import { auditWorkspaceContext } from './workspace-audit.js';
7
7
  import { PROVIDER_BOOTSTRAP_START, readOptional, resolveProjectRelative, WORKSPACE_MANAGED_START, WORKSPACE_OPERATOR_START, WORKSPACE_SIGNATURE, } from './workspace-context-shared.js';
8
8
  import { BOOTSTRAP_AUTHORITY_SIGNATURE, WORKSPACE_PRECEDENCE_SIGNATURE, WORKSPACE_PRECEDENCE_SUPERSEDED } from './workspace-document.js';
9
9
  import { configuredProviders } from './workspace-migration.js';
10
+ import { diagnoseCodexHookTrust } from '../hook-bridge/codex-trust.js';
11
+ import { diagnoseFactoryHookTrust } from '../hook-bridge/factory-trust.js';
10
12
  import { maskCodeRegions } from './code-regions.js';
11
13
  export { maskCodeRegions } from './code-regions.js';
12
14
  export function markdownLinks(content) {
@@ -36,6 +38,47 @@ export async function workspaceLinkedFiles(projectPath) {
36
38
  }
37
39
  export async function diagnoseWorkspaceContext(projectPath) {
38
40
  const diagnostics = [];
41
+ const codexTrust = await diagnoseCodexHookTrust(projectPath);
42
+ if (codexTrust)
43
+ diagnostics.push(codexTrust);
44
+ const factoryTrust = await diagnoseFactoryHookTrust(projectPath);
45
+ if (factoryTrust)
46
+ diagnostics.push(factoryTrust);
47
+ const root = path.resolve(projectPath);
48
+ const scopes = new Map();
49
+ // Ordinary subdirectories share root policy; repository/project markers start a separate scope.
50
+ function directoryScope(directory) {
51
+ if (directory === root || !directory.startsWith(`${root}${path.sep}`))
52
+ return Promise.resolve(null);
53
+ let scope = scopes.get(directory);
54
+ if (!scope) {
55
+ scope = (async () => {
56
+ const markers = await Promise.all(['.git', '.aiwg/aiwg.config'].map(async (marker) => {
57
+ try {
58
+ await fs.stat(path.join(directory, marker));
59
+ return true;
60
+ }
61
+ catch {
62
+ return false;
63
+ }
64
+ }));
65
+ return markers.some(Boolean)
66
+ ? path.relative(root, directory).replace(/\\/g, '/')
67
+ : directoryScope(path.dirname(directory));
68
+ })();
69
+ scopes.set(directory, scope);
70
+ }
71
+ return scope;
72
+ }
73
+ async function reportSourceDiagnostic(diagnostic, sources) {
74
+ const sourceScopes = await Promise.all(sources.map((source) => directoryScope(path.dirname(path.resolve(root, source)))));
75
+ const nestedOnly = sourceScopes.length > 0 && sourceScopes.every((scope) => scope !== null);
76
+ diagnostics.push(nestedOnly ? {
77
+ ...diagnostic,
78
+ severity: diagnostic.severity === 'error' ? 'warning' : diagnostic.severity,
79
+ message: `Advisory for nested project(s) ${[...new Set(sourceScopes)].join(', ')}: ${diagnostic.message}`,
80
+ } : diagnostic);
81
+ }
39
82
  const { existing, notes } = await readAiwgOperatorNotes(projectPath);
40
83
  if (existing !== null && existing !== notes)
41
84
  diagnostics.push({
@@ -87,7 +130,7 @@ export async function diagnoseWorkspaceContext(projectPath) {
87
130
  }
88
131
  }
89
132
  for (const conflict of audit.conflicts) {
90
- diagnostics.push({ severity: 'error', code: 'directive-conflict', message: `Conflicting duplicate directive group '${conflict.key}' appears in ${conflict.sources.map((source) => source.path).join(', ')}.` });
133
+ await reportSourceDiagnostic({ severity: 'error', code: 'directive-conflict', message: `Conflicting duplicate directive group '${conflict.key}' appears in ${conflict.sources.map((source) => source.path).join(', ')}.` }, conflict.sources.map((source) => source.path));
91
134
  }
92
135
  // One diagnostic per source pair, not one per duplicated line: a shared
93
136
  // pointer stub otherwise reports every line as a separate policy conflict
@@ -102,13 +145,13 @@ export async function diagnoseWorkspaceContext(projectPath) {
102
145
  const paths = pair.split(', ');
103
146
  const bodies = paths.map((item) => operatorBodies.get(item) ?? '');
104
147
  const wholeFileDuplicate = bodies.every((body) => body.length > 0 && body === bodies[0]);
105
- diagnostics.push({
148
+ await reportSourceDiagnostic({
106
149
  severity: wholeFileDuplicate ? 'info' : 'warning',
107
150
  code: 'duplicate-directive',
108
151
  message: wholeFileDuplicate
109
152
  ? `${pair} carry identical operator content (${count} directive(s)); keep one copy or accept the shared stub.`
110
153
  : `${count} identical directive(s) duplicated across ${pair}.`,
111
- });
154
+ }, paths);
112
155
  }
113
156
  for (const source of audit.sources) {
114
157
  if (!source.path.replace(/\\/g, '/').includes('/context/providers/') || !source.operatorContent.trim())
@@ -121,7 +164,8 @@ export async function diagnoseWorkspaceContext(projectPath) {
121
164
  });
122
165
  }
123
166
  for (const finding of audit.sensitiveFindings) {
124
- diagnostics.push({ severity: 'error', code: 'possible-secret', message: 'Possible credential value found in context; remove it.', path: finding.path });
167
+ const location = finding.line ? `${finding.path}:${finding.line}` : finding.path;
168
+ await reportSourceDiagnostic({ severity: 'error', code: 'possible-secret', message: `Possible credential value found in ${location}; remove it.`, path: finding.path }, [finding.path]);
125
169
  }
126
170
  // #2512 — "points at WORKSPACE.md" is not the same as "carries current policy".
127
171
  // Without this, a workspace generated before the precedence correction reads
@@ -1,7 +1,7 @@
1
1
  // Render and preserve the canonical WORKSPACE document and resident memory.
2
2
  import * as path from 'node:path';
3
3
  import { readAiwgConfigCandidate } from '../../config/aiwg-config.js';
4
- import { projectControlPath } from '../../config/project-artifacts.js';
4
+ import { isProjectArtifactRootExternal, projectControlPath } from '../../config/project-artifacts.js';
5
5
  import { listProviderDefinitions } from '../../providers/provider-definitions.js';
6
6
  import { resolveRulesInlineBudget } from '../../rules/inline-budget.mjs';
7
7
  import { writeContextFileSync } from './context-file-safety.js';
@@ -131,7 +131,10 @@ export function buildWorkspaceManagedBlock(projectPath, providerFiles = [], resi
131
131
  '',
132
132
  '- Before any agent or provider writes AIWG payload, run `aiwg artifacts path --json --check-write` and write beneath its `artifact_root`.',
133
133
  '- Treat `.aiwg/...` in skills and templates as a logical artifact path, not necessarily a repository-local filesystem path.',
134
- '- Only `aiwg.config`, `frameworks/registry.json`, and optional operator-only `AIWG.md` notes belong in the repository-local `.aiwg` control plane; generated framework context lives in root `AIWG.md`.',
134
+ '- Configure an external artifact root with a path in `.aiwg-location`; `AIWG_ARTIFACTS_PATH` overrides that pointer.',
135
+ isProjectArtifactRootExternal(projectPath)
136
+ ? '- Only `aiwg.config`, `frameworks/registry.json`, and optional operator-only `AIWG.md` notes belong in the repository-local `.aiwg` control plane; generated framework context lives in root `AIWG.md`.'
137
+ : '- With no external artifact root configured, repository-local `.aiwg` stores AIWG payload alongside control-plane files; generated framework context lives in root `AIWG.md`.',
135
138
  '- If the configured external artifact root is unavailable, stop with an actionable error; never fall back to repository-local payload.',
136
139
  '',
137
140
  '### Linked Context',
@@ -156,7 +156,8 @@ export async function migrateWorkspaceContext(projectPath, options = {}) {
156
156
  const audit = await auditWorkspaceContext(projectPath);
157
157
  const sensitiveFindingCount = audit.sensitiveFindings.length;
158
158
  if (sensitiveFindingCount > 0) {
159
- throw new Error(`Migration refused: ${sensitiveFindingCount} possible secret/credential value(s) found. Remove them before migration.`);
159
+ const locations = audit.sensitiveFindings.map((finding) => finding.line ? `${finding.path}:${finding.line}` : finding.path);
160
+ throw new Error(`Migration refused: ${sensitiveFindingCount} possible secret/credential value(s) found in ${locations.join(', ')}. Remove them before migration.`);
160
161
  }
161
162
  if (audit.conflicts.length > 0 && !options.allowConflicts) {
162
163
  throw new Error(`Migration refused: ${audit.conflicts.length} ambiguous directive conflict(s). Review the deterministic audit or pass --allow-conflicts to preserve each source separately.`);