@aiwg/cli 2026.11.2 → 2026.11.4

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 (150) hide show
  1. package/agentic/code/addons/aiwg-hooks/canonical/aiwg-prompt-discovery.yaml +3 -2
  2. package/agentic/code/addons/aiwg-hooks/hooks/aiwg-prompt-discovery.cjs +12 -9
  3. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.md +2 -0
  4. package/agentic/code/addons/composition-engine/lib/runtime.mjs +5 -26
  5. package/agentic/code/addons/composition-engine/schemas/flow-graph.schema.json +22 -0
  6. package/agentic/code/providers/capability-matrix.yaml +17 -20
  7. package/agentic/code/providers/model-capabilities.v1.json +17 -16
  8. package/dist/src/a2a/hitl-authorization.js +46 -0
  9. package/dist/src/a2a/hitl-driver.js +5 -5
  10. package/dist/src/artifacts/browser-export.js +2 -0
  11. package/dist/src/artifacts/framework-source-digest.js +1 -1
  12. package/dist/src/artifacts/index-builder.js +5 -25
  13. package/dist/src/artifacts/index-capability.js +24 -0
  14. package/dist/src/artifacts/query-engine-discover-output.js +8 -3
  15. package/dist/src/artifacts/query-engine-rules.js +27 -9
  16. package/dist/src/artifacts/query-engine-scoring.js +5 -5
  17. package/dist/src/artifacts/query-engine-show-card.js +5 -1
  18. package/dist/src/artifacts/query-engine-show-load.js +1 -1
  19. package/dist/src/artifacts/query-engine-show.js +3 -3
  20. package/dist/src/artifacts/query-engine-templates.js +10 -4
  21. package/dist/src/artifacts/query-engine-verbose.js +18 -4
  22. package/dist/src/artifacts/relations-builder.js +1 -0
  23. package/dist/src/artifacts/types.js +1 -1
  24. package/dist/src/cli/handlers/checkpoint-handoff.js +2 -1
  25. package/dist/src/cli/handlers/dataset.js +17 -0
  26. package/dist/src/cli/handlers/guided-setup.js +3 -1
  27. package/dist/src/cli/handlers/refresh-managed-deployment.js +17 -5
  28. package/dist/src/cli/handlers/rules.js +1 -1
  29. package/dist/src/cli/handlers/sessions.js +1 -1
  30. package/dist/src/cli/handlers/steward.js +1 -1
  31. package/dist/src/cli/handlers/use.js +18 -5
  32. package/dist/src/cli/handlers/utility-doctor.js +5 -2
  33. package/dist/src/cli/handlers/workspace.js +1 -1
  34. package/dist/src/cli/services/deployment-probe-scope.js +40 -0
  35. package/dist/src/cli/services/deployment-verification.js +5 -6
  36. package/dist/src/config/aiwg-config.js +6 -0
  37. package/dist/src/config/authorization-cli.js +61 -3
  38. package/dist/src/config/cli-help.js +1 -1
  39. package/dist/src/config/cli.js +4 -2
  40. package/dist/src/config/decision-config.js +2 -1
  41. package/dist/src/config/host-resource-runtime.mjs +1 -1
  42. package/dist/src/config/jev-credential-reference.js +56 -0
  43. package/dist/src/config/user-config.js +13 -19
  44. package/dist/src/config/user-registry.js +9 -1
  45. package/dist/src/config/worker-owner-lock.js +90 -10
  46. package/dist/src/decision/ask.js +3 -2
  47. package/dist/src/decision/graph-flow-adapter.js +1 -1
  48. package/dist/src/decision/jev-credentials.js +22 -0
  49. package/dist/src/decision/offload.js +1 -1
  50. package/dist/src/decision/openbao-kv-resolver.mjs +96 -0
  51. package/dist/src/decision/openbao-runtime.js +101 -0
  52. package/dist/src/effects/authorization-grant.js +50 -0
  53. package/dist/src/effects/authorization-store.js +130 -0
  54. package/dist/src/effects/index.js +2 -0
  55. package/dist/src/effects/ledger.js +1 -0
  56. package/dist/src/effects/lifecycle.js +1 -1
  57. package/dist/src/effects/reader.js +4 -0
  58. package/dist/src/effects/records.js +4 -0
  59. package/dist/src/effects/schema.js +2 -0
  60. package/dist/src/extensions/claude-hooks-installer.js +7 -7
  61. package/dist/src/extensions/muse-managed-hooks.js +11 -0
  62. package/dist/src/extensions/user-hook-diagnostics.js +32 -0
  63. package/dist/src/extensions/verified-hook-command.js +32 -0
  64. package/dist/src/lint/rule-conflicts.js +52 -0
  65. package/dist/src/lint/runner.js +3 -0
  66. package/dist/src/mcp/cli.mjs +3 -1
  67. package/dist/src/mcp/elicitation.mjs +30 -0
  68. package/dist/src/mcp/grok-build-config.mjs +1 -1
  69. package/dist/src/mcp/muse-native-config.mjs +1 -0
  70. package/dist/src/mcp/server.mjs +2 -0
  71. package/dist/src/mcp/tools/authorization.mjs +78 -0
  72. package/dist/src/models/model-capabilities.v1.json +17 -16
  73. package/dist/src/policy/authorization-capture.js +64 -0
  74. package/dist/src/policy/authorization-operations.js +108 -0
  75. package/dist/src/policy/hitl-check.js +3 -2
  76. package/dist/src/policy/hitl-consume.js +14 -0
  77. package/dist/src/policy/hitl-durable-store.js +60 -0
  78. package/dist/src/policy/hitl-durable.js +60 -0
  79. package/dist/src/policy/hitl-receipt.js +5 -0
  80. package/dist/src/policy/hitl.js +44 -6
  81. package/dist/src/process/bounded-child-process.mjs +49 -39
  82. package/dist/src/providers/capability-matrix.yaml +17 -20
  83. package/dist/src/providers/deployment-ownership.d.mts +1 -0
  84. package/dist/src/providers/deployment-ownership.mjs +21 -2
  85. package/dist/src/providers/grok-build-headless.js +170 -77
  86. package/dist/src/providers/grok-build-inspect.js +1 -0
  87. package/dist/src/providers/grok-build-paths.js +2 -0
  88. package/dist/src/providers/muse-paths.js +4 -2
  89. package/dist/src/providers/provider-context-contracts.js +12 -4
  90. package/dist/src/providers/provider-definition-schema.js +6 -0
  91. package/dist/src/providers/provider-seeds-1.js +3 -3
  92. package/dist/src/providers/provider-seeds-2.js +6 -4
  93. package/dist/src/providers/provider-seeds-3.js +6 -6
  94. package/dist/src/rules/activation.d.mts +2 -0
  95. package/dist/src/rules/activation.mjs +16 -7
  96. package/dist/src/rules/inline-budget.d.mts +2 -1
  97. package/dist/src/rules/inline-budget.mjs +4 -2
  98. package/dist/src/rules/inventory.js +3 -0
  99. package/dist/src/rules/precedence.d.mts +6 -0
  100. package/dist/src/rules/precedence.mjs +49 -0
  101. package/dist/src/rules/project-precedence.js +73 -0
  102. package/dist/src/rules/rule-frontmatter.schema.json +15 -0
  103. package/dist/src/serve/a2a-terminal-observer.js +12 -3
  104. package/dist/src/serve/mission-hitl.js +20 -1
  105. package/dist/src/sessions/adapters/grok-build-fallback.js +33 -0
  106. package/dist/src/sessions/adapters/grok-build-native-records.js +64 -0
  107. package/dist/src/sessions/adapters/grok-build-native.js +92 -100
  108. package/dist/src/sessions/adapters/grok-build.js +65 -24
  109. package/dist/src/sessions/grok-build-cli-output.js +113 -0
  110. package/dist/src/sessions/grok-build-cli.js +4 -28
  111. package/dist/src/smiths/context-pipeline/bridge-ownership.js +4 -3
  112. package/dist/src/smiths/context-pipeline/finalization.js +5 -0
  113. package/dist/src/smiths/context-pipeline/generator.js +1 -1
  114. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +20 -17
  115. package/dist/src/smiths/context-pipeline/workspace-doctor.js +6 -1
  116. package/dist/src/smiths/context-pipeline/workspace-document.js +6 -0
  117. package/dist/src/smiths/context-pipeline/workspace-migration.js +2 -12
  118. package/dist/src/smiths/hook-bridge/codex-translator.js +11 -14
  119. package/dist/src/smiths/hook-bridge/codex-trust.js +7 -2
  120. package/dist/src/smiths/hook-bridge/copilot-translator.js +2 -1
  121. package/dist/src/smiths/hook-bridge/factory-trust.js +56 -0
  122. package/dist/src/smiths/hook-bridge/grok-build-translator.js +3 -1
  123. package/dist/src/smiths/hook-bridge/hermes-prompt-discovery.js +78 -0
  124. package/dist/src/smiths/hook-bridge/hermes-translator.js +5 -3
  125. package/dist/src/smiths/hook-bridge/index.js +3 -1
  126. package/dist/src/smiths/hook-bridge/prompt-discovery-gaps.js +3 -2
  127. package/package.json +7 -1
  128. package/tools/agents/deploy-agents.mjs +5 -6
  129. package/tools/agents/deploy-options.mjs +1 -0
  130. package/tools/agents/providers/base-frontmatter.mjs +3 -2
  131. package/tools/agents/providers/claude-post-deploy.mjs +1 -1
  132. package/tools/agents/providers/codex-post-deploy.mjs +1 -1
  133. package/tools/agents/providers/generic.mjs +66 -0
  134. package/tools/agents/providers/grok-build.mjs +3 -1
  135. package/tools/agents/providers/muse-hooks.mjs +13 -11
  136. package/tools/agents/providers/muse-prompt-discovery.mjs +5 -1
  137. package/tools/agents/providers/muse.mjs +2 -1
  138. package/tools/agents/providers/openclaw.mjs +2 -1
  139. package/tools/agents/providers/rule-deployment-prepare.mjs +5 -3
  140. package/tools/agents/providers/rule-deployment-state.mjs +14 -6
  141. package/tools/agents/providers/rule-startup.mjs +11 -10
  142. package/tools/agents/providers/staged-directory-reference.mjs +14 -0
  143. package/tools/agents/providers/user-hooks.mjs +26 -0
  144. package/tools/cli/authorization-health.mjs +20 -0
  145. package/tools/cli/decision-offload-report.mjs +2 -0
  146. package/tools/cli/workspace-status.mjs +7 -0
  147. package/tools/commands/deploy-prompts-codex.mjs +15 -1
  148. package/tools/plugin/package-plugins.mjs +6 -1
  149. package/tools/ralph-external/lib/claude-adapter.mjs +2 -2
  150. package/vscode-extension/schemas/aiwg.config.v1.json +20 -0
@@ -1,3 +1,4 @@
1
+ import { lintRuleConflicts } from './rule-conflicts.js';
1
2
  /**
2
3
  * Lint Runner
3
4
  *
@@ -86,6 +87,8 @@ async function runRule(rule, targetDir, allFiles, referenceIndex, projectRoot, a
86
87
  }
87
88
  }
88
89
  }
90
+ if (rule.checks.some(check => check.type === 'rule-activation'))
91
+ diagnostics.push(...lintRuleConflicts(targetDir, matchingFiles, projectRoot));
89
92
  // Run per-file checks
90
93
  for (const file of matchingFiles) {
91
94
  const absPath = path.resolve(targetDir, file);
@@ -613,7 +613,7 @@ POSITIONING:
613
613
  MCP is optional and provider-agnostic. Baseline AIWG reachability is file
614
614
  deployment plus CLI discovery: aiwg discover / aiwg show <type> <name>.
615
615
 
616
- CORE TOOLS (17, always registered):
616
+ CORE TOOLS (19, always registered):
617
617
  discover Cross-type ranked catalog search
618
618
  skill-list / skill-show Skill catalog and SKILL.md body fetch
619
619
  command-list / command-show CLI command catalog and command spec fetch
@@ -625,6 +625,8 @@ CORE TOOLS (17, always registered):
625
625
  command-run Allow-listed CLI dispatch; confirmation-gated when needed
626
626
  artifact-read / artifact-write Project .aiwg/ artifact IO
627
627
  ask-user Structured user question via elicitation or Markdown
628
+ aiwg_authorization_grant_lookup Read-only list/search/explain of signed grants
629
+ aiwg_authorization_grant_request Save a bounded grant only after native form confirmation
628
630
 
629
631
  OPT-IN TOOLSETS (71 additional tools, including explicit workers):
630
632
  flows flow-list / flow-show / flow-run
@@ -40,6 +40,36 @@ export function clientSupportsFormElicitation(mcpServer) {
40
40
  }
41
41
  }
42
42
 
43
+ // Observe actual outgoing JSON-RPC IDs without depending on SDK private counters.
44
+ const elicitationTransports = new WeakMap();
45
+ export async function elicitWithRequestId(mcpServer, params, options) {
46
+ const transport = mcpServer.server.transport;
47
+ if (!transport) throw new Error('Elicitation requires a connected transport');
48
+ let pending = elicitationTransports.get(transport);
49
+ if (!pending) {
50
+ pending = new Map();
51
+ const send = transport.send.bind(transport);
52
+ transport.send = (message, ...rest) => {
53
+ if (message.method === 'elicitation/create') {
54
+ const capture = pending.get(message.params?._meta?.['aiwg.io/authorization-event']);
55
+ if (capture) capture.requestId = message.id;
56
+ }
57
+ return send(message, ...rest);
58
+ };
59
+ elicitationTransports.set(transport, pending);
60
+ }
61
+ const event = params._meta['aiwg.io/authorization-event'];
62
+ const capture = {};
63
+ pending.set(event, capture);
64
+ try {
65
+ const result = await mcpServer.server.elicitInput(params, options);
66
+ if (capture.requestId === undefined) throw new Error('Missing elicitation request ID');
67
+ return { result, requestId: String(capture.requestId) };
68
+ } finally {
69
+ pending.delete(event);
70
+ }
71
+ }
72
+
43
73
  /**
44
74
  * Build a restricted JSON-schema (MCP elicitation `requestedSchema`) for a
45
75
  * single- or multi-select choice over the given options.
@@ -147,7 +147,7 @@ export async function unmanageGrokBuildMcp(configPath, names, options = {}) {
147
147
  }
148
148
 
149
149
  function runJson(binary, args, cwd, env) {
150
- const run = spawnSync(binary, args, { cwd, env: helperEnvironment(env), encoding: 'utf8', timeout: 30_000, killSignal: 'SIGKILL' });
150
+ const run = spawnSync(binary, args, { cwd, env: helperEnvironment(env), stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8', timeout: 30_000, killSignal: 'SIGKILL' });
151
151
  if (run.error || run.status !== 0) return { ok: false, detail: run.error?.message || run.stderr || `exit ${run.status}` };
152
152
  try { return { ok: true, value: JSON.parse(run.stdout || '{}') }; }
153
153
  catch { return { ok: false, detail: 'Grok returned malformed JSON' }; }
@@ -22,6 +22,7 @@ function deepEqual(a, b) {
22
22
  function inspectMuseCli(env) {
23
23
  const result = spawnSync('muse', ['--version'], {
24
24
  env: helperEnvironment(env),
25
+ stdio: ['ignore', 'pipe', 'pipe'],
25
26
  encoding: 'utf8',
26
27
  timeout: MUSE_VERSION_TIMEOUT_MS,
27
28
  killSignal: 'SIGKILL',
@@ -22,6 +22,7 @@ import { registerWriterProfileResources } from './tools/writer-profiles.mjs';
22
22
  import { registerDiscoveryTools } from './tools/discovery.mjs';
23
23
  import { registerCommandRunTool } from './tools/command-run.mjs';
24
24
  import { registerInteractionTools } from './tools/interaction.mjs';
25
+ import { registerAuthorizationTools } from './tools/authorization.mjs';
25
26
  import { parseToolsets, registerOptInToolsets, KNOWN_TOOLSETS } from './tools/subsystems.mjs';
26
27
  import { AIWG_ROOT, findProjectRoot, resolveProjectAiwgDir } from './helpers.mjs';
27
28
  import { pinContainedRoot as pinArtifactRoot, openContainedFile as openArtifact, readContainedFile, listContainedFiles, validateContainedPath } from '../utils/contained-filesystem.mjs';
@@ -155,6 +156,7 @@ export async function createServer(options = {}) {
155
156
  // store. Callers select other projects explicitly via `project_dir`.
156
157
  const artifactEnv = { ...process.env };
157
158
  const trustedProjectRoot = await fs.realpath(options.projectDir ?? process.cwd());
159
+ registerAuthorizationTools(server, { projectRoot: trustedProjectRoot });
158
160
  const trustedArtifactRoot = await resolveProjectAiwgDir(trustedProjectRoot, { env: artifactEnv });
159
161
  const startupStore = options.artifactStore ?? await pinArtifactRoot(trustedArtifactRoot, trustedProjectRoot);
160
162
  const trustedStore = startupStore.root;
@@ -0,0 +1,78 @@
1
+ // Captures durable grants exclusively through confirmed native MCP form elicitation.
2
+ import { randomUUID } from 'node:crypto';
3
+ import { access } from 'node:fs/promises';
4
+ import { z } from 'zod';
5
+ import { buildChoiceSchema, clientSupportsFormElicitation, elicitWithRequestId } from '../elicitation.mjs';
6
+
7
+ const descriptors = z.array(z.string().min(1).max(256)).min(1).max(64);
8
+ const proposalSchema = z.strictObject({
9
+ categories: descriptors, targets: descriptors, environments: descriptors, resources: descriptors, verbs: descriptors,
10
+ maxImpact: z.enum(['low', 'medium']), expiresAt: z.string(), maxUses: z.number().int().positive().safe().optional(),
11
+ });
12
+ const reply = (value, isError = false) => ({ content: [{ type: 'text', text: JSON.stringify(value) }], ...(isError ? { isError } : {}) });
13
+
14
+ async function authorizationApi(module) {
15
+ // Shipped dist has the compiled module beside this file's tree; a source checkout uses dist/.
16
+ for (const location of [new URL(`../../policy/${module}.js`, import.meta.url),
17
+ new URL(`../../../dist/src/policy/${module}.js`, import.meta.url)]) {
18
+ try { await access(location); } catch { continue; }
19
+ return import(location.href);
20
+ }
21
+ throw new Error('Authorization grant capture requires the built CLI package.');
22
+ }
23
+
24
+ export function registerAuthorizationTools(server, { projectRoot }) {
25
+ const lookupSchema = z.strictObject({
26
+ operation: z.enum(['list', 'search', 'explain']), status: z.enum(['active', 'expired', 'revoked']).optional(),
27
+ query: z.string().min(1).max(4096).optional(), action: z.record(z.string(), z.unknown()).optional(),
28
+ });
29
+ server.registerTool('aiwg_authorization_grant_lookup', {
30
+ title: 'Inspect durable authorization grants',
31
+ description: 'Read verified grants: list, deterministic token search with match reasons, or explain a host-classified action. Never records grants, revocations, receipts or uses.',
32
+ inputSchema: lookupSchema,
33
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
34
+ }, async args => {
35
+ try {
36
+ const input = lookupSchema.parse(args);
37
+ const field = { list: 'status', search: 'query', explain: 'action' }[input.operation];
38
+ if (Object.keys(input).some(key => key !== 'operation' && key !== field)
39
+ || (input.operation !== 'list' && input[field] === undefined)) throw new Error('Invalid lookup fields');
40
+ const api = await authorizationApi('authorization-operations');
41
+ return reply(input.operation === 'list' ? await api.listAuthorizationGrants(projectRoot, input.status)
42
+ : input.operation === 'search' ? await api.searchAuthorizationGrants(projectRoot, input.query)
43
+ : await api.explainAuthorization(projectRoot, input.action));
44
+ } catch {
45
+ return reply({ status: 'unavailable', reason: 'invalid-query-or-authorization-ledger-unavailable' }, true);
46
+ }
47
+ });
48
+ const connectionId = `mcp-session:${randomUUID()}`;
49
+ server.registerTool('aiwg_authorization_grant_request', {
50
+ title: 'Request a durable human authorization grant',
51
+ description: 'Propose bounded authorization and ask the person through native MCP form elicitation. Only explicit confirmation records a signed grant. Text claims never authorize. The server adds and displays governing workspace bindings.',
52
+ inputSchema: proposalSchema,
53
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },
54
+ }, async (args, extra) => {
55
+ try {
56
+ const proposal = proposalSchema.parse(args);
57
+ const api = await authorizationApi('authorization-capture');
58
+ const sessionId = extra?.sessionId ?? connectionId;
59
+ const identity = { sessionId, id: extra?.authInfo?.clientId ?? `session:${sessionId}` };
60
+ const { grant, question } = await api.prepareAuthorizationGrant(projectRoot, proposal, identity);
61
+ if (!clientSupportsFormElicitation(server)) return reply({ status: 'refused', reason: 'form-elicitation-required',
62
+ message: 'Use your harness native question tool to ask the user, then retry from a client supporting MCP form elicitation. No grant was recorded; text replies cannot record grants.' }, true);
63
+ const { requestedSchema } = buildChoiceSchema({ key: 'confirm', title: 'Save this authorization scope?',
64
+ options: [{ value: 'confirm', label: 'Confirm this scope' }, { value: 'decline', label: 'Decline' }] });
65
+ const { result, requestId } = await elicitWithRequestId(server, {
66
+ mode: 'form', message: question, requestedSchema,
67
+ _meta: { 'aiwg.io/authorization-event': randomUUID() },
68
+ }, { signal: extra?.signal, relatedRequestId: extra?.requestId, timeout: 60_000 });
69
+ if (extra?.signal?.aborted || result?.action !== 'accept' || result?.content?.confirm !== 'confirm') {
70
+ return reply({ status: 'not-recorded', reason: 'native-confirmation-required' });
71
+ }
72
+ return reply(await api.recordConfirmedAuthorizationGrant(projectRoot, grant, requestId, result));
73
+ } catch {
74
+ // Do not echo arguments, raw questions, answers, or transport errors.
75
+ return reply({ status: 'not-recorded', reason: 'invalid-scope-or-confirmation-unavailable' }, true);
76
+ }
77
+ });
78
+ }
@@ -256,7 +256,7 @@
256
256
  "id": "claude-direct",
257
257
  "provider": "claude",
258
258
  "adapterVersion": "1",
259
- "supportedVersions": "2.1.295",
259
+ "supportedVersions": ">=2.1.295 <2.2.0",
260
260
  "runtimeDriver": "installed:claude",
261
261
  "catalogAdapter": {
262
262
  "kind": "file",
@@ -329,67 +329,67 @@
329
329
  "invocationProfiles": {
330
330
  "direct-shell": {
331
331
  "transport": "shell",
332
- "supportedVersions": "2.1.295",
332
+ "supportedVersions": ">=2.1.295 <2.2.0",
333
333
  "controls": {
334
334
  "model": {
335
335
  "support": "unqualified",
336
336
  "mapping": "--model ${model}; moving aliases denied",
337
- "evidence": "H: claude 2.1.295 --help (2026-10-09); --model <model> Model for the current session. Provide; full verbatim excerpts: docs/providers/claude-direct.md"
337
+ "evidence": "H: claude 2.1.319 --help and -p --help (2026-11-07); --model <model> Model for the current session. Provide; full verbatim excerpts: docs/providers/claude-direct.md"
338
338
  },
339
339
  "effort": {
340
340
  "support": "unqualified",
341
341
  "mapping": "--effort ${effort}; explicit low/medium/high/xhigh/max",
342
- "evidence": "H: claude 2.1.295 --help (2026-10-09); --effort <level> Effort level for the current session (low, medium, high, xhigh, max); full verbatim excerpts: docs/providers/claude-direct.md"
342
+ "evidence": "H: claude 2.1.319 --help and -p --help (2026-11-07); --effort <level> Effort level for the current session (low, medium, high, xhigh, max); full verbatim excerpts: docs/providers/claude-direct.md"
343
343
  },
344
344
  "sandbox": {
345
345
  "support": "unqualified",
346
346
  "mapping": "partial: --restricted confines whitelisted file tools, scoped by --tools/--allowedTools (workspace-write: Read,Glob,Grep,Edit,Write; read-only: Read,Glob,Grep); OS sandbox unavailable in CLI, external boundary required",
347
- "evidence": "H: claude 2.1.295 --help (2026-10-09); --restricted Restricted mode: removes the built-in tools that run commands or code; full verbatim excerpts: docs/providers/claude-direct.md"
347
+ "evidence": "H: claude 2.1.319 --help and -p --help (2026-11-07); --restricted Restricted mode: removes the built-in tools that run commands or code; full verbatim excerpts: docs/providers/claude-direct.md"
348
348
  },
349
349
  "approval": {
350
350
  "support": "unqualified",
351
351
  "mapping": "--permission-mode dontAsk --permission-prompts none; prompting and bypass modes denied",
352
- "evidence": "H: claude 2.1.295 --help (2026-10-09); --permission-prompts <target> Who answers permission prompts with --print: \"host\" (the SDK host or --permission-prompt-tool) or \"none\" (nobody: anything that would prompt is denied automatically; the permission mode still decides everything else); full verbatim excerpts: docs/providers/claude-direct.md"
352
+ "evidence": "H: claude 2.1.319 --help and -p --help (2026-11-07); --permission-prompts <target> Who answers permission prompts with --print: \"host\" (the SDK host or --permission-prompt-tool) or \"none\" (nobody: anything that would prompt is denied automatically; the permission mode still decides everything else); full verbatim excerpts: docs/providers/claude-direct.md"
353
353
  },
354
354
  "workdir": {
355
355
  "support": "unqualified",
356
356
  "mapping": "spawn cwd from conductor; no invented --cwd flag",
357
- "evidence": "H: claude 2.1.295 --help (2026-10-09); Usage: claude [options] [command] [prompt]; no workspace switch is emitted; full verbatim excerpts: docs/providers/claude-direct.md"
357
+ "evidence": "H: claude 2.1.319 --help and -p --help (2026-11-07); Usage: claude [options] [command] [prompt]; no workspace switch is emitted; full verbatim excerpts: docs/providers/claude-direct.md"
358
358
  },
359
359
  "finalOutput": {
360
360
  "support": "unqualified",
361
361
  "mapping": "parse exactly one success result envelope from stdout; result JSON text or structured_output; exit-zero error fails",
362
- "evidence": "H: claude 2.1.295 --help (2026-10-09); --output-format <format> Output format (only works with --print): \"text\" (default), \"json\" (single result), or \"stream-json\" (realtime streaming); full verbatim excerpts: docs/providers/claude-direct.md"
362
+ "evidence": "H: claude 2.1.319 --help and -p --help (2026-11-07); --output-format <format> Output format (only works with --print): \"text\" (default), \"json\" (single result), or \"stream-json\" (realtime streaming); full verbatim excerpts: docs/providers/claude-direct.md"
363
363
  },
364
364
  "stdin": {
365
365
  "support": "unqualified",
366
366
  "mapping": "--input-format text; brief-text on stdin through EOF; never prompt argv",
367
- "evidence": "H: claude 2.1.295 --help (2026-10-09); --input-format <format> Input format (only works with --print): \"text\" (default), or \"stream-json\"; full verbatim excerpts: docs/providers/claude-direct.md"
367
+ "evidence": "H: claude 2.1.319 --help and -p --help (2026-11-07); --input-format <format> Input format (only works with --print): \"text\" (default), or \"stream-json\"; full verbatim excerpts: docs/providers/claude-direct.md"
368
368
  },
369
369
  "structuredOutput": {
370
370
  "support": "unqualified",
371
371
  "mapping": "unavailable in current renderer: CLI --json-schema exists but schema input is not passed to this driver",
372
- "evidence": "H: claude 2.1.295 --help (2026-10-09); --json-schema <schema> JSON Schema for structured output validation.; full verbatim excerpts: docs/providers/claude-direct.md"
372
+ "evidence": "H: claude 2.1.319 --help and -p --help (2026-11-07); --json-schema <schema> JSON Schema for structured output validation (only works with --print).; full verbatim excerpts: docs/providers/claude-direct.md"
373
373
  },
374
374
  "stepCap": {
375
375
  "support": "unqualified",
376
376
  "mapping": "unavailable: --max-turns is not listed by installed help; never emitted",
377
- "evidence": "H: claude 2.1.295 --help (2026-10-09); No --max-turns line appears in claude 2.1.295 --help; full verbatim excerpts: docs/providers/claude-direct.md"
377
+ "evidence": "H: claude 2.1.319 --help and -p --help (2026-11-07); No --max-turns line appears in claude 2.1.319 --help or -p --help; full verbatim excerpts: docs/providers/claude-direct.md"
378
378
  },
379
379
  "trust": {
380
380
  "support": "unqualified",
381
381
  "mapping": "--print --safe-mode --restricted --setting-sources \"\" --strict-mcp-config --mcp-config {\"mcpServers\":{}}; inherited customization disabled",
382
- "evidence": "H: claude 2.1.295 --help (2026-10-09); --safe-mode Start with all customizations (CLAUDE.md, skills, installed plugins, hooks, MCP servers, custom commands and agents, output styles, workflows, custom themes, keybindings, and more) disabled; full verbatim excerpts: docs/providers/claude-direct.md"
382
+ "evidence": "H: claude 2.1.319 --help and -p --help (2026-11-07); --safe-mode Start with all customizations (CLAUDE.md, skills, installed plugins, hooks, MCP servers, custom commands and agents, output styles, workflows, custom themes, keybindings, and more) disabled; full verbatim excerpts: docs/providers/claude-direct.md"
383
383
  },
384
384
  "children": {
385
385
  "support": "unqualified",
386
386
  "mapping": "--tools/--allowedTools Read,Glob,Grep,Edit,Write (workspace-write) or Read,Glob,Grep (read-only) --disallowedTools Agent,Task,Bash,PowerShell,REPL,WebFetch; no child/command tool or external MCP",
387
- "evidence": "H: claude 2.1.295 --help (2026-10-09); --tools <tools...> Specify the list of available tools from the built-in set.; full verbatim excerpts: docs/providers/claude-direct.md"
387
+ "evidence": "H: claude 2.1.319 --help and -p --help (2026-11-07); --tools <tools...> Specify the list of available tools from the built-in set.; full verbatim excerpts: docs/providers/claude-direct.md"
388
388
  },
389
389
  "fallback": {
390
390
  "support": "unqualified",
391
391
  "mapping": "exact model; --safe-mode; never emit --fallback-model; model substitutions do not qualify the profile",
392
- "evidence": "H: claude 2.1.295 --help (2026-10-09); --fallback-model <model> Enable automatic fallback to specified model(s) when the default model is overloaded or not available.; full verbatim excerpts: docs/providers/claude-direct.md"
392
+ "evidence": "H: claude 2.1.319 --help and -p --help (2026-11-07); --fallback-model <model> Enable automatic fallback to specified model(s) when the default model is overloaded or not available.; full verbatim excerpts: docs/providers/claude-direct.md"
393
393
  }
394
394
  },
395
395
  "envAllowlist": [
@@ -403,6 +403,7 @@
403
403
  "Final output is the captured .stdout JSONL stream, not a CLI-created finalPath file. Normalize with ClaudeAdapter.parseWorkerFinal before verification.",
404
404
  "Unavailable: renderer schema input, help-evidenced turn cap, native MCP reasoning worker. claude mcp serve exposes only debug/help/verbose and is a code-tools server.",
405
405
  "Commands, Agent/Task, inherited MCP, hooks, plugins and skills are disabled in this restricted file-tools profile.",
406
+ "Version policy: >=2.1.295 <2.2.0 preserves the earlier help-verified baseline and accepts compatible 2.1 patch updates; 2.1.319 help was rechecked on titan on 2026-11-07. Range/resolver tests cover 2.1.317 and 2.1.319 synthetically, not live inference. Older versions, prereleases and 2.2+ remain blocked.",
406
407
  "Bare mode is not used: installed help states it changes auth to API-key-only. No account or credential files were inspected."
407
408
  ],
408
409
  "health": {
@@ -429,8 +430,8 @@
429
430
  {
430
431
  "kind": "help",
431
432
  "ref": "docs/providers/claude-direct.md",
432
- "observedAt": "2026-10-09T00:00:00Z",
433
- "cliVersion": "2.1.295"
433
+ "observedAt": "2026-11-08T01:49:23Z",
434
+ "cliVersion": "2.1.319"
434
435
  },
435
436
  {
436
437
  "kind": "repository",
@@ -0,0 +1,64 @@
1
+ // Prepares bounded grants and digest-only human evidence for native MCP confirmation.
2
+ import { randomUUID } from 'node:crypto';
3
+ import { realpath } from 'node:fs/promises';
4
+ import { dirname, isAbsolute } from 'node:path';
5
+ import { assertAuthorizationGrant } from '../effects/authorization-grant.js';
6
+ import { effectSession, openLedger } from '../effects/host.js';
7
+ import { payloadDigest } from '../effects/identity.js';
8
+ import { recordAuthorizationGrant } from '../effects/authorization-store.js';
9
+ import { loadHitlLayers } from './hitl-config.js';
10
+ import { hitlPolicyVersion } from './hitl.js';
11
+ export async function prepareAuthorizationGrant(projectDir, proposal, identity) {
12
+ const loaded = await loadHitlLayers(projectDir);
13
+ const root = await realpath(projectDir);
14
+ if (root !== loaded.projectDir)
15
+ throw new Error('Serve the AIWG project root to request a grant');
16
+ const workspaces = new Set([root]);
17
+ for (const layer of loaded.layers) {
18
+ if (isAbsolute(layer.source))
19
+ workspaces.add(await realpath(dirname(dirname(layer.source))));
20
+ }
21
+ const grant = {
22
+ apiVersion: 'authorization-grant.aiwg.io/v1', grantId: `grant-${randomUUID()}`,
23
+ scope: { categories: [...proposal.categories], targets: [...new Set([...proposal.targets, ...[...workspaces].map(path => `workspace:${path}`)])],
24
+ environments: [...proposal.environments], resources: [...proposal.resources], verbs: [...proposal.verbs] },
25
+ constraints: { reversible: true, maxImpact: proposal.maxImpact,
26
+ exclusions: ['secrets', 'destructive', 'production', 'policy-override'], conditions: [],
27
+ ...(proposal.maxUses === undefined ? {} : { maxUses: proposal.maxUses }) },
28
+ grantedBy: { kind: 'human', id: identity.id, issuer: 'aiwg-mcp', authenticationRef: 'pending-elicitation' },
29
+ provenance: { provider: 'mcp', sessionId: identity.sessionId, userTurnDigest: payloadDigest('pending') },
30
+ questionDigest: payloadDigest('pending'), policyVersion: hitlPolicyVersion(loaded.layers),
31
+ createdAt: new Date().toISOString(), expiresAt: proposal.expiresAt, revocation: { state: 'active' },
32
+ };
33
+ // Validate before asking, including prohibited classes and medium-impact expiry bounds.
34
+ assertAuthorizationGrant(grant);
35
+ const list = (values) => values.map(value => JSON.stringify(value)).join(', ');
36
+ const question = [
37
+ 'Allow AIWG to perform the following actions automatically in the future?',
38
+ `Action categories: ${list(grant.scope.categories)}. Allowed verbs: ${list(grant.scope.verbs)}.`,
39
+ `Only these targets (including workspace bindings): ${list(grant.scope.targets)}.`,
40
+ `Only these environments: ${list(grant.scope.environments)}. Resource patterns: ${list(grant.scope.resources)}.`,
41
+ `Actions must be reversible with at most ${grant.constraints.maxImpact} impact.`,
42
+ 'Secrets, destructive actions, production and policy overrides are excluded.',
43
+ grant.expiresAt === 'until-revoked' ? 'Duration: until revoked.' : `Expires at ${JSON.stringify(grant.expiresAt)}.`,
44
+ grant.constraints.maxUses === undefined ? 'No use-count limit.' : `At most ${grant.constraints.maxUses} uses.`,
45
+ 'Confirm to save this scope as a signed authorization grant, or decline to save nothing.',
46
+ ].join('\n');
47
+ grant.questionDigest = payloadDigest(question);
48
+ return { grant, question };
49
+ }
50
+ /** Called only with a successful, explicit native confirmation, never model-supplied evidence. */
51
+ export async function recordConfirmedAuthorizationGrant(projectDir, grant, requestId, result) {
52
+ const confirmation = result;
53
+ if (confirmation?.action !== 'accept' || confirmation.content?.confirm !== 'confirm')
54
+ throw new Error('Native confirmation required');
55
+ grant.grantedBy.authenticationRef = `mcp-elicitation:${grant.provenance.sessionId}:${requestId}`;
56
+ grant.provenance.nativeEventRef = requestId;
57
+ grant.provenance.userTurnDigest = payloadDigest(JSON.stringify(result));
58
+ assertAuthorizationGrant(grant);
59
+ if (grant.expiresAt !== 'until-revoked' && Date.now() >= Date.parse(grant.expiresAt))
60
+ throw new Error('Grant expired during confirmation');
61
+ await recordAuthorizationGrant(openLedger(await effectSession(projectDir, 'custom')), grant);
62
+ return { status: 'recorded', grantId: grant.grantId };
63
+ }
64
+ //# sourceMappingURL=authorization-capture.js.map
@@ -0,0 +1,108 @@
1
+ // Shares verified operator lookup, deterministic explanation, health and signed revocation across existing surfaces.
2
+ import { randomUUID } from 'node:crypto';
3
+ import { effectSession, openLedger } from '../effects/host.js';
4
+ import { openEffectLedger } from '../effects/ledger.js';
5
+ import { inspectAuthorizationIndex, readAuthorizationGrants, recordAuthorizationGrant } from '../effects/authorization-store.js';
6
+ import { integrityError, usageError } from '../effects/errors.js';
7
+ import { readAllSegments } from '../effects/reader.js';
8
+ import { AUTHORIZATION_GRANT_KIND } from '../effects/authorization-grant.js';
9
+ import { loadHitlLayers } from './hitl-config.js';
10
+ import { canonicalHitlAction } from './hitl-check.js';
11
+ import { refreshDurableAuthorization } from './hitl-durable-store.js';
12
+ import { matchDurableAuthorization, unsafeDurableAction } from './hitl-durable.js';
13
+ import { glob, hitlDigest, resolveHitlAuthorization, validHitlAction } from './hitl.js';
14
+ /** Seven days, inclusive of the end of the window; expired grants are excluded. */
15
+ export const AUTHORIZATION_EXPIRING_SOON_MS = 7 * 24 * 60 * 60 * 1000;
16
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
17
+ export async function authorizationReadLedger(projectDir) {
18
+ const session = await effectSession(projectDir, 'custom');
19
+ return openEffectLedger({ projectDir, scope: session.scope, writer: 'cli' });
20
+ }
21
+ export function authorizationEntries(entries, now = Date.now()) {
22
+ const removed = new Set(entries.flatMap(({ grant: g }) => [g.revokes, g.supersedes].filter(Boolean)));
23
+ return entries.map(entry => {
24
+ const g = entry.grant;
25
+ const status = g.revokes || g.revocation.state !== 'active' || removed.has(g.grantId) ? 'revoked'
26
+ : g.expiresAt !== 'until-revoked' && Date.parse(g.expiresAt) <= now ? 'expired'
27
+ : Date.parse(g.createdAt) > now ? 'pending' : 'active';
28
+ return { ...entry, status };
29
+ }).sort((a, b) => compare(a.grant.grantId, b.grant.grantId) || compare(a.effectId, b.effectId));
30
+ }
31
+ async function verifiedEntries(projectDir) {
32
+ const read = await readAuthorizationGrants(await authorizationReadLedger(projectDir));
33
+ if (read.failures.length)
34
+ throw integrityError('authorization-ledger-invalid');
35
+ return authorizationEntries(read.grants);
36
+ }
37
+ export async function listAuthorizationGrants(projectDir, status) {
38
+ const entries = await verifiedEntries(projectDir);
39
+ return { grants: status ? entries.filter(entry => entry.status === status) : entries };
40
+ }
41
+ export async function showAuthorizationGrant(projectDir, grantId) {
42
+ const entry = (await verifiedEntries(projectDir)).find(entry => entry.grant.grantId === grantId);
43
+ if (!entry)
44
+ throw usageError('Unknown authorization grant', 'grant-not-found');
45
+ return entry;
46
+ }
47
+ const tokens = (text) => [...new Set(text.toLowerCase().match(/[a-z0-9]+/g) ?? [])];
48
+ export async function searchAuthorizationGrants(projectDir, query) {
49
+ if (!query.trim() || query.length > 4096)
50
+ throw usageError('Search requires 1–4096 characters', 'grant-query-invalid');
51
+ const queryTokens = tokens(query);
52
+ const matches = (await verifiedEntries(projectDir)).map(entry => {
53
+ const fields = { ...entry.grant.scope, ids: [entry.grant.grantId, entry.effectId, entry.recordHash] };
54
+ const reasons = Object.entries(fields).flatMap(([field, values]) => queryTokens.flatMap(token => {
55
+ const matched = values.filter(value => tokens(value).includes(token));
56
+ return matched.length ? [{ field, token, values: matched }] : [];
57
+ }));
58
+ return { ...entry, score: reasons.length, reasons };
59
+ }).filter(entry => entry.score > 0).sort((a, b) => b.score - a.score
60
+ || compare(a.grant.grantId, b.grant.grantId) || compare(a.effectId, b.effectId)).slice(0, 20);
61
+ return { query, matches };
62
+ }
63
+ export async function explainAuthorization(projectDir, input) {
64
+ const loaded = await loadHitlLayers(projectDir);
65
+ const action = await canonicalHitlAction(loaded.projectDir, input);
66
+ const ledger = await authorizationReadLedger(loaded.projectDir);
67
+ const context = await refreshDurableAuthorization(ledger, { now: new Date().toISOString(), layers: loaded.layers });
68
+ const snapshot = context.durableAuthorization;
69
+ const resolution = resolveHitlAuthorization(action, context);
70
+ const matched = validHitlAction(action) && !snapshot.failures.length
71
+ ? matchDurableAuthorization(action, snapshot, Date.parse(context.now), glob) : {};
72
+ return { ...resolution, matchingGrant: matched.match ?? null, nearestGrant: matched.nearest ?? null,
73
+ safetyClassForcesEscalation: validHitlAction(action) && (unsafeDurableAction(action)
74
+ || resolution.reason === 'safety-category-requires-explicit-review'), failures: snapshot.failures };
75
+ }
76
+ /** Only removes authority: original scope/human evidence is retained as lineage, never fresh approval. */
77
+ export async function revokeAuthorizationGrant(projectDir, grantId) {
78
+ const original = await showAuthorizationGrant(projectDir, grantId);
79
+ if (original.status === 'revoked')
80
+ return { revokes: grantId, alreadyRevoked: true };
81
+ const now = new Date().toISOString();
82
+ const event = { operation: 'revoke', grantId, at: now, id: randomUUID() };
83
+ const grant = { ...original.grant, grantId: `revocation-${event.id}`, revokes: grantId,
84
+ createdAt: now, expiresAt: 'until-revoked', constraints: { ...original.grant.constraints, maxImpact: 'low' },
85
+ revocation: { state: 'revoked', revokedAt: now, decisionEventId: hitlDigest(event) } };
86
+ delete grant.supersedes;
87
+ const receipt = await recordAuthorizationGrant(openLedger(await effectSession(projectDir, 'custom')), grant);
88
+ return { revokes: grantId, revocationGrantId: grant.grantId, effectId: receipt.effectId };
89
+ }
90
+ export async function authorizationHealth(projectDir, now = Date.now()) {
91
+ const ledger = await authorizationReadLedger(projectDir);
92
+ const read = await readAuthorizationGrants(ledger);
93
+ const entries = authorizationEntries(read.grants, now);
94
+ let unverifiable = 0;
95
+ if (read.failures.length) {
96
+ const segments = await readAllSegments(ledger.paths());
97
+ // Count untrusted records only; never expose their fields or treat them as authority.
98
+ unverifiable = segments.some(s => s.torn || s.lines.some(l => !l.decoded)) ? null
99
+ : segments.reduce((n, s) => n + s.lines.filter(l => l.decoded?.statement.predicate.kind === AUTHORIZATION_GRANT_KIND
100
+ && l.decoded.statement.predicate.phase === 'intent').length, 0);
101
+ }
102
+ return { active: entries.filter(e => e.status === 'active').length,
103
+ expiringSoon: entries.filter(e => e.status === 'active' && e.grant.expiresAt !== 'until-revoked'
104
+ && Date.parse(e.grant.expiresAt) <= now + AUTHORIZATION_EXPIRING_SOON_MS).length,
105
+ expiringSoonWindowMs: AUTHORIZATION_EXPIRING_SOON_MS, unverifiable, failures: read.failures,
106
+ index: await inspectAuthorizationIndex(ledger, read) };
107
+ }
108
+ //# sourceMappingURL=authorization-operations.js.map
@@ -6,6 +6,7 @@ import { loadHitlLayers } from './hitl-config.js';
6
6
  import { recordHitlAuthorization } from './hitl-receipt.js';
7
7
  import { consumeHitlAuthorization } from './hitl-consume.js';
8
8
  import { resolveHitlAuthorization, validHitlAction } from './hitl.js';
9
+ import { refreshDurableAuthorization } from './hitl-durable-store.js';
9
10
  /** Resolve existing ancestors as well as new leaves; dangling links fail closed. */
10
11
  async function canonical(path) {
11
12
  try {
@@ -60,8 +61,9 @@ export async function checkHitlAuthorization(projectDir, input, options = {}) {
60
61
  const loaded = await loadHitlLayers(projectDir);
61
62
  context = { ...context, layers: loaded.layers };
62
63
  const action = await canonicalHitlAction(loaded.projectDir, input);
64
+ const ledger = openLedger(await effectSession(loaded.projectDir, 'custom', { clock: () => Date.parse(context.now) }));
65
+ context = await refreshDurableAuthorization(ledger, context);
63
66
  if (options.receipt) {
64
- const ledger = openLedger(await effectSession(loaded.projectDir, 'custom', { clock: () => Date.parse(context.now) }));
65
67
  const consumed = await consumeHitlAuthorization(ledger, action, context, options.receipt);
66
68
  return consumed.decision === 'auto-authorized' ? { ...consumed, receipt: options.receipt } : consumed;
67
69
  }
@@ -71,7 +73,6 @@ export async function checkHitlAuthorization(projectDir, input, options = {}) {
71
73
  // Reload policies and the clock at consumption time, including expiry and revocation.
72
74
  context = { ...context, now: options.now ?? new Date().toISOString(), layers: (await loadHitlLayers(projectDir)).layers,
73
75
  expectedPolicyVersion: options.expectedPolicyVersion ?? decision.policyVersion };
74
- const ledger = openLedger(await effectSession(loaded.projectDir, 'custom', { clock: () => Date.parse(context.now) }));
75
76
  const recorded = await recordHitlAuthorization(ledger, action, context);
76
77
  if (recorded.resolution.decision !== 'auto-authorized')
77
78
  return recorded.resolution;
@@ -7,12 +7,21 @@ import { payloadDigest } from '../effects/identity.js';
7
7
  import { fileDigestVerifier } from '../effects/verifiers/file.js';
8
8
  import { runVerifier } from '../effects/verifiers/registry.js';
9
9
  import { hitlDigest, resolveHitlAuthorization, validHitlAction } from './hitl.js';
10
+ import { ensureLedgerDirectories, withLedgerLock } from '../effects/store.js';
11
+ import { recordDurableUse, refreshDurableAuthorization } from './hitl-durable-store.js';
10
12
  /** Receipt existence is historical evidence; only this fresh comparison authorizes dispatch. */
11
13
  export async function consumeHitlAuthorization(ledger, action, context, reference) {
14
+ await ensureLedgerDirectories(ledger.paths());
15
+ return withLedgerLock(ledger.paths(), 'authorization-index', ledger.lockTimeoutMs, () => consumeCurrentAuthorization(ledger, action, context, reference));
16
+ }
17
+ async function consumeCurrentAuthorization(ledger, action, context, reference) {
18
+ context = await refreshDurableAuthorization(ledger, context);
12
19
  const resolution = resolveHitlAuthorization(action, context);
13
20
  const refuse = (reason) => ({ ...resolution, decision: 'escalate', reason });
14
21
  if (!validHitlAction(action))
15
22
  return refuse('invalid-action-descriptor');
23
+ if (context.durableAuthorization?.failures.length)
24
+ return resolution;
16
25
  const effect = await lookupEffect(ledger, reference.effectId);
17
26
  const intent = effect.records.find(record => record.phase === 'intent');
18
27
  if (effect.kind !== 'file.digest' || effect.tombstoned || effect.result !== 'present' || !intent
@@ -49,6 +58,11 @@ export async function consumeHitlAuthorization(ledger, action, context, referenc
49
58
  if (receipt.policyVersion !== resolution.policyVersion || receipt.sessionGrantDigest !== hitlDigest(context.sessionAuthorization ?? null)) {
50
59
  return refuse('stale-policy-version');
51
60
  }
61
+ if (receipt.provenance !== resolution.provenance
62
+ || JSON.stringify(receipt.authorizationGrant) !== JSON.stringify(resolution.authorizationGrant))
63
+ return refuse('approval-grant-mismatch');
64
+ if (resolution.provenance === 'durable-user')
65
+ await recordDurableUse(ledger, resolution, reference.effectId);
52
66
  return resolution;
53
67
  }
54
68
  //# sourceMappingURL=hitl-consume.js.map
@@ -0,0 +1,60 @@
1
+ // Refreshes signed grant/use snapshots and records bounded receipt consumption in the existing ledger.
2
+ import { randomUUID } from 'node:crypto';
3
+ import { realpath } from 'node:fs/promises';
4
+ import { dirname, isAbsolute } from 'node:path';
5
+ import { readAuthorizationGrants } from '../effects/authorization-store.js';
6
+ import { recordIntent } from '../effects/ledger.js';
7
+ import { payloadDigest } from '../effects/identity.js';
8
+ import { readAllSegments } from '../effects/reader.js';
9
+ import { AUTHORIZATION_GRANT_KIND } from '../effects/authorization-grant.js';
10
+ import { AUTHORIZATION_USE_KIND } from './hitl-durable.js';
11
+ export async function refreshDurableAuthorization(ledger, context) {
12
+ const read = await readAuthorizationGrants(ledger);
13
+ const workspaces = [await realpath(ledger.projectDir)];
14
+ for (const layer of context.layers) {
15
+ if (isAbsolute(layer.source))
16
+ workspaces.push(await realpath(dirname(dirname(layer.source))));
17
+ }
18
+ const snapshot = { ...read, workspaces: [...new Set(workspaces)].sort(), uses: {} };
19
+ if (!read.failures.length) {
20
+ for (const segment of await readAllSegments(ledger.paths())) {
21
+ for (const line of segment.lines) {
22
+ const p = line.decoded?.statement.predicate;
23
+ if (!p || segment.torn) {
24
+ snapshot.failures.push({ reason: 'authorization-use-unreadable' });
25
+ continue;
26
+ }
27
+ // Purging a revocation can erase its link to an older grant. Do not resurrect authority.
28
+ if (p.phase === 'tombstone' && p.kind === AUTHORIZATION_GRANT_KIND) {
29
+ snapshot.historyUnavailable = true;
30
+ }
31
+ if (p.kind !== AUTHORIZATION_USE_KIND)
32
+ continue;
33
+ if (p.phase === 'tombstone')
34
+ snapshot.usageUnavailable = true;
35
+ else if (p.phase === 'intent') {
36
+ const grantEffectId = p.context?.grantEffectId;
37
+ if (typeof grantEffectId !== 'string')
38
+ snapshot.usageUnavailable = true;
39
+ else
40
+ snapshot.uses[grantEffectId] = (snapshot.uses[grantEffectId] ?? 0) + 1;
41
+ }
42
+ }
43
+ }
44
+ // Verify again after the use scan: a concurrently damaged segment never supplies authority.
45
+ const after = await readAuthorizationGrants(ledger);
46
+ snapshot.failures.push(...after.failures);
47
+ if (JSON.stringify(read.grants) !== JSON.stringify(after.grants))
48
+ snapshot.failures.push({ reason: 'authorization-grants-changed' });
49
+ }
50
+ return { ...context, durableAuthorization: snapshot };
51
+ }
52
+ /** Caller holds authorization-index lock, shared with grant recording and other consumers. */
53
+ export async function recordDurableUse(ledger, resolution, receiptEffectId) {
54
+ const grant = resolution.authorizationGrant;
55
+ const context = { grantId: grant.grantId, grantEffectId: grant.effectId, grantRecordHash: grant.recordHash,
56
+ receiptEffectId, useId: randomUUID() };
57
+ return recordIntent(ledger, { kind: AUTHORIZATION_USE_KIND, target: `x-authorization-use:${grant.grantId}`,
58
+ context, payloadDigest: payloadDigest(JSON.stringify(context)) });
59
+ }
60
+ //# sourceMappingURL=hitl-durable-store.js.map