@aiwg/cli 2026.11.3 → 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 (135) 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 +15 -18
  7. package/dist/src/a2a/hitl-authorization.js +46 -0
  8. package/dist/src/a2a/hitl-driver.js +5 -5
  9. package/dist/src/artifacts/browser-export.js +2 -0
  10. package/dist/src/artifacts/framework-source-digest.js +1 -1
  11. package/dist/src/artifacts/index-builder.js +5 -25
  12. package/dist/src/artifacts/index-capability.js +24 -0
  13. package/dist/src/artifacts/query-engine-discover-output.js +8 -3
  14. package/dist/src/artifacts/query-engine-rules.js +27 -9
  15. package/dist/src/artifacts/query-engine-scoring.js +5 -5
  16. package/dist/src/artifacts/query-engine-show-card.js +5 -1
  17. package/dist/src/artifacts/query-engine-show-load.js +1 -1
  18. package/dist/src/artifacts/query-engine-show.js +3 -3
  19. package/dist/src/artifacts/query-engine-templates.js +10 -4
  20. package/dist/src/artifacts/query-engine-verbose.js +18 -4
  21. package/dist/src/artifacts/relations-builder.js +1 -0
  22. package/dist/src/artifacts/types.js +1 -1
  23. package/dist/src/cli/handlers/checkpoint-handoff.js +2 -1
  24. package/dist/src/cli/handlers/guided-setup.js +3 -1
  25. package/dist/src/cli/handlers/refresh-managed-deployment.js +17 -5
  26. package/dist/src/cli/handlers/rules.js +1 -1
  27. package/dist/src/cli/handlers/sessions.js +1 -1
  28. package/dist/src/cli/handlers/steward.js +1 -1
  29. package/dist/src/cli/handlers/use.js +1 -2
  30. package/dist/src/cli/handlers/utility-doctor.js +5 -2
  31. package/dist/src/cli/handlers/workspace.js +1 -1
  32. package/dist/src/cli/services/deployment-probe-scope.js +40 -0
  33. package/dist/src/cli/services/deployment-verification.js +4 -5
  34. package/dist/src/config/aiwg-config.js +6 -0
  35. package/dist/src/config/authorization-cli.js +61 -3
  36. package/dist/src/config/cli-help.js +1 -1
  37. package/dist/src/config/cli.js +4 -2
  38. package/dist/src/config/host-resource-runtime.mjs +1 -1
  39. package/dist/src/config/user-registry.js +9 -1
  40. package/dist/src/config/worker-owner-lock.js +90 -10
  41. package/dist/src/decision/graph-flow-adapter.js +1 -1
  42. package/dist/src/effects/authorization-grant.js +50 -0
  43. package/dist/src/effects/authorization-store.js +130 -0
  44. package/dist/src/effects/index.js +2 -0
  45. package/dist/src/effects/ledger.js +1 -0
  46. package/dist/src/effects/lifecycle.js +1 -1
  47. package/dist/src/effects/reader.js +4 -0
  48. package/dist/src/effects/records.js +4 -0
  49. package/dist/src/effects/schema.js +2 -0
  50. package/dist/src/extensions/claude-hooks-installer.js +7 -7
  51. package/dist/src/extensions/muse-managed-hooks.js +11 -0
  52. package/dist/src/extensions/user-hook-diagnostics.js +32 -0
  53. package/dist/src/extensions/verified-hook-command.js +32 -0
  54. package/dist/src/lint/rule-conflicts.js +52 -0
  55. package/dist/src/lint/runner.js +3 -0
  56. package/dist/src/mcp/cli.mjs +3 -1
  57. package/dist/src/mcp/elicitation.mjs +30 -0
  58. package/dist/src/mcp/grok-build-config.mjs +1 -1
  59. package/dist/src/mcp/muse-native-config.mjs +1 -0
  60. package/dist/src/mcp/server.mjs +2 -0
  61. package/dist/src/mcp/tools/authorization.mjs +78 -0
  62. package/dist/src/policy/authorization-capture.js +64 -0
  63. package/dist/src/policy/authorization-operations.js +108 -0
  64. package/dist/src/policy/hitl-check.js +3 -2
  65. package/dist/src/policy/hitl-consume.js +14 -0
  66. package/dist/src/policy/hitl-durable-store.js +60 -0
  67. package/dist/src/policy/hitl-durable.js +60 -0
  68. package/dist/src/policy/hitl-receipt.js +5 -0
  69. package/dist/src/policy/hitl.js +44 -6
  70. package/dist/src/process/bounded-child-process.mjs +49 -39
  71. package/dist/src/providers/capability-matrix.yaml +15 -18
  72. package/dist/src/providers/deployment-ownership.d.mts +1 -0
  73. package/dist/src/providers/deployment-ownership.mjs +21 -2
  74. package/dist/src/providers/grok-build-headless.js +170 -77
  75. package/dist/src/providers/grok-build-inspect.js +1 -0
  76. package/dist/src/providers/grok-build-paths.js +2 -0
  77. package/dist/src/providers/muse-paths.js +4 -2
  78. package/dist/src/providers/provider-context-contracts.js +12 -4
  79. package/dist/src/providers/provider-definition-schema.js +6 -0
  80. package/dist/src/providers/provider-seeds-1.js +3 -3
  81. package/dist/src/providers/provider-seeds-2.js +6 -4
  82. package/dist/src/providers/provider-seeds-3.js +6 -6
  83. package/dist/src/rules/activation.d.mts +2 -0
  84. package/dist/src/rules/activation.mjs +16 -7
  85. package/dist/src/rules/inline-budget.d.mts +2 -1
  86. package/dist/src/rules/inline-budget.mjs +4 -2
  87. package/dist/src/rules/inventory.js +3 -0
  88. package/dist/src/rules/precedence.d.mts +6 -0
  89. package/dist/src/rules/precedence.mjs +49 -0
  90. package/dist/src/rules/project-precedence.js +73 -0
  91. package/dist/src/rules/rule-frontmatter.schema.json +15 -0
  92. package/dist/src/serve/a2a-terminal-observer.js +12 -3
  93. package/dist/src/serve/mission-hitl.js +20 -1
  94. package/dist/src/sessions/adapters/grok-build-fallback.js +33 -0
  95. package/dist/src/sessions/adapters/grok-build-native-records.js +64 -0
  96. package/dist/src/sessions/adapters/grok-build-native.js +92 -100
  97. package/dist/src/sessions/adapters/grok-build.js +65 -24
  98. package/dist/src/sessions/grok-build-cli-output.js +113 -0
  99. package/dist/src/sessions/grok-build-cli.js +4 -28
  100. package/dist/src/smiths/context-pipeline/bridge-ownership.js +4 -3
  101. package/dist/src/smiths/context-pipeline/finalization.js +5 -0
  102. package/dist/src/smiths/context-pipeline/generator.js +1 -1
  103. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +20 -17
  104. package/dist/src/smiths/context-pipeline/workspace-doctor.js +2 -1
  105. package/dist/src/smiths/context-pipeline/workspace-document.js +6 -0
  106. package/dist/src/smiths/context-pipeline/workspace-migration.js +2 -12
  107. package/dist/src/smiths/hook-bridge/codex-translator.js +11 -14
  108. package/dist/src/smiths/hook-bridge/codex-trust.js +7 -2
  109. package/dist/src/smiths/hook-bridge/copilot-translator.js +2 -1
  110. package/dist/src/smiths/hook-bridge/grok-build-translator.js +3 -1
  111. package/dist/src/smiths/hook-bridge/hermes-prompt-discovery.js +78 -0
  112. package/dist/src/smiths/hook-bridge/hermes-translator.js +5 -3
  113. package/dist/src/smiths/hook-bridge/index.js +3 -1
  114. package/dist/src/smiths/hook-bridge/prompt-discovery-gaps.js +3 -2
  115. package/package.json +7 -1
  116. package/tools/agents/deploy-agents.mjs +5 -6
  117. package/tools/agents/deploy-options.mjs +1 -0
  118. package/tools/agents/providers/base-frontmatter.mjs +3 -2
  119. package/tools/agents/providers/claude-post-deploy.mjs +1 -1
  120. package/tools/agents/providers/codex-post-deploy.mjs +1 -1
  121. package/tools/agents/providers/generic.mjs +66 -0
  122. package/tools/agents/providers/grok-build.mjs +3 -1
  123. package/tools/agents/providers/muse-hooks.mjs +13 -11
  124. package/tools/agents/providers/muse-prompt-discovery.mjs +5 -1
  125. package/tools/agents/providers/muse.mjs +2 -1
  126. package/tools/agents/providers/openclaw.mjs +2 -1
  127. package/tools/agents/providers/rule-deployment-prepare.mjs +5 -3
  128. package/tools/agents/providers/rule-deployment-state.mjs +14 -6
  129. package/tools/agents/providers/rule-startup.mjs +11 -10
  130. package/tools/agents/providers/staged-directory-reference.mjs +14 -0
  131. package/tools/agents/providers/user-hooks.mjs +26 -0
  132. package/tools/cli/authorization-health.mjs +20 -0
  133. package/tools/cli/workspace-status.mjs +7 -0
  134. package/tools/commands/deploy-prompts-codex.mjs +15 -1
  135. package/vscode-extension/schemas/aiwg.config.v1.json +20 -0
@@ -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
+ }
@@ -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
@@ -0,0 +1,60 @@
1
+ // Matches verified durable grants deterministically without trusting descriptor-supplied authority.
2
+ import { assertAuthorizationGrant } from '../effects/authorization-grant.js';
3
+ export const AUTHORIZATION_USE_KIND = 'x.aiwg.authorization-use';
4
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
5
+ const forbidden = /(?:^|[^a-z0-9])(?:secrets?|credentials?|tokens?|destructive|irreversible|production|prod|delete|destroy|wipe|drop|override)(?:$|[^a-z0-9])/i;
6
+ export const unsafeDurableAction = (action) => [action.category, action.environment, action.verb ?? '', action.target ?? ''].some(value => forbidden.test(value))
7
+ || !action.reversible || action.impact === 'high';
8
+ export function matchDurableAuthorization(action, snapshot, now, glob) {
9
+ const revoked = new Set(snapshot.grants.flatMap(({ grant }) => [grant.revokes, grant.supersedes].filter((id) => !!id)));
10
+ const candidates = snapshot.grants.map(entry => {
11
+ const { grant: g } = entry;
12
+ const fields = [];
13
+ try {
14
+ assertAuthorizationGrant(g);
15
+ }
16
+ catch {
17
+ return { entry, fields: ['invalid-grant'] };
18
+ }
19
+ const { targets } = g.scope;
20
+ if (!g.scope.categories.includes(action.category))
21
+ fields.push('category');
22
+ if (!targets.includes(action.target ?? `repo:${action.repo}`))
23
+ fields.push('target');
24
+ if (!targets.includes(`repo:${action.repo}`))
25
+ fields.push('repo');
26
+ // A bare repo name cannot authorize another checkout or workspace with that same repo identity.
27
+ if (!snapshot.workspaces.length || snapshot.workspaces.some(path => !targets.includes(`workspace:${path}`)))
28
+ fields.push('workspace');
29
+ if (!g.scope.environments.includes(action.environment))
30
+ fields.push('environment');
31
+ if (!action.resources.every(path => g.scope.resources.some(pattern => glob(pattern, path))))
32
+ fields.push('resources');
33
+ if (!g.scope.verbs.includes(action.verb ?? action.category.split('.').at(-1)))
34
+ fields.push('verb');
35
+ if (!action.reversible)
36
+ fields.push('reversible');
37
+ if (action.impact === 'high' || (action.impact === 'medium' && g.constraints.maxImpact !== 'medium'))
38
+ fields.push('impact');
39
+ if (now < Date.parse(g.createdAt))
40
+ fields.push('createdAt');
41
+ if (g.expiresAt !== 'until-revoked' && now >= Date.parse(g.expiresAt))
42
+ fields.push('expiresAt');
43
+ if (snapshot.historyUnavailable || g.revocation.state !== 'active' || revoked.has(g.grantId) || g.revokes)
44
+ fields.push('revocation');
45
+ // Free-text conditions are not executable predicates; never assume they have been satisfied.
46
+ if (g.constraints.conditions.length)
47
+ fields.push('conditions');
48
+ if (g.constraints.maxUses !== undefined && (snapshot.usageUnavailable
49
+ || (snapshot.uses[entry.effectId] ?? 0) >= g.constraints.maxUses))
50
+ fields.push('maxUses');
51
+ return { entry, fields };
52
+ }).sort((a, b) => a.fields.length - b.fields.length || compare(a.entry.grant.grantId, b.entry.grant.grantId)
53
+ || compare(a.entry.effectId, b.entry.effectId));
54
+ const nearest = candidates[0];
55
+ if (!nearest)
56
+ return {};
57
+ return nearest.fields.length ? { nearest: { grantId: nearest.entry.grant.grantId, fields: nearest.fields } }
58
+ : { match: nearest.entry };
59
+ }
60
+ //# sourceMappingURL=hitl-durable.js.map
@@ -9,14 +9,19 @@ import { fileDigestVerifier } from '../effects/verifiers/file.js';
9
9
  import { createVerifierRegistry } from '../effects/verifiers/registry.js';
10
10
  import { hitlDigest, resolveHitlAuthorization, validHitlAction } from './hitl.js';
11
11
  import { HITL_CATEGORIES, HITL_ENVIRONMENTS } from './hitl-types.js';
12
+ import { refreshDurableAuthorization } from './hitl-durable-store.js';
12
13
  /** Resolve again at receipt time. A preview result supplied by an agent is never trusted. */
13
14
  export async function recordHitlAuthorization(ledger, action, context) {
15
+ context = await refreshDurableAuthorization(ledger, context);
14
16
  const resolution = resolveHitlAuthorization(action, context);
15
17
  const receipt = {
16
18
  kind: 'hitl-authorization', evaluatedAtDigest: hitlDigest(context.now),
17
19
  sessionGrantDigest: hitlDigest(context.sessionAuthorization ?? null), ...resolution,
18
20
  // Arbitrary user strings become digests, including paths, repo identity and profile names.
19
21
  matchedProfile: resolution.matchedProfile ? hitlDigest(resolution.matchedProfile) : null,
22
+ // Diagnostic grant IDs may be arbitrary strings; only verified grant links are stored verbatim.
23
+ ...(resolution.nearestGrant ? { nearestGrant: { ...resolution.nearestGrant, grantId: hitlDigest(resolution.nearestGrant.grantId) },
24
+ reason: 'durable-grant-scope-mismatch' } : {}),
20
25
  action: validHitlAction(action) ? {
21
26
  category: HITL_CATEGORIES.find(category => category === action.category) ?? 'restricted',
22
27
  descriptorDigest: hitlDigest(action), categoryDigest: hitlDigest(action.category),
@@ -2,6 +2,7 @@
2
2
  import { createHash } from 'node:crypto';
3
3
  import { HITL_CATEGORIES, HITL_ENVIRONMENTS } from './hitl-types.js';
4
4
  import { validateHitlPolicy } from './hitl-validation.js';
5
+ import { matchDurableAuthorization, unsafeDurableAction } from './hitl-durable.js';
5
6
  export function hitlDigest(value) {
6
7
  const canonical = (v) => Array.isArray(v) ? v.map(canonical)
7
8
  : v && typeof v === 'object' ? Object.fromEntries(Object.entries(v).filter(([, x]) => x !== undefined)
@@ -19,9 +20,11 @@ export function validHitlAction(value) {
19
20
  }
20
21
  function actionFieldsValid(a) {
21
22
  const keys = ['category', 'repo', 'environment', 'resources', 'reversible', 'impact'];
22
- const binding = ['actor', 'inputDigest'];
23
+ const binding = ['actor', 'inputDigest', 'target', 'verb'];
23
24
  return Object.keys(a).every(k => [...keys, ...binding].includes(k)) && keys.every(k => Object.hasOwn(a, k))
24
- && (a.category !== 'repo.edit' || (binding.every(k => Object.hasOwn(a, k)) && typeof a.actor === 'string' && typeof a.inputDigest === 'string'))
25
+ && (a.category !== 'repo.edit' || (typeof a.actor === 'string' && typeof a.inputDigest === 'string'))
26
+ && (a.target === undefined || (typeof a.target === 'string' && /^[A-Za-z0-9][A-Za-z0-9_.:/@#=-]{0,255}$/.test(a.target)))
27
+ && (a.verb === undefined || (typeof a.verb === 'string' && /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/.test(a.verb)))
25
28
  && (a.actor === undefined || (typeof a.actor === 'string' && identifier.test(a.actor)))
26
29
  && (a.inputDigest === undefined || (typeof a.inputDigest === 'string' && /^sha256:[a-f0-9]{64}$/.test(a.inputDigest)))
27
30
  && [a.category, a.repo, a.environment].every(x => typeof x === 'string' && identifier.test(x))
@@ -29,7 +32,7 @@ function actionFieldsValid(a) {
29
32
  && typeof a.reversible === 'boolean' && ['low', 'medium', 'high'].includes(a.impact);
30
33
  }
31
34
  /** Deliberately small glob language: * within a segment; ** crosses directories; ? one character. */
32
- function glob(pattern, path) {
35
+ export function glob(pattern, path) {
33
36
  // Memoized matching bounds work by pattern length × path length, without regex backtracking.
34
37
  const memo = new Map();
35
38
  const match = (i, j) => {
@@ -72,13 +75,16 @@ function grant(p, a, now) {
72
75
  }
73
76
  export function resolveHitlAuthorization(action, context) {
74
77
  const policyVersion = hitlPolicyVersion(context.layers);
75
- const result = (decision, reason, provenance, matchedProfile = null) => ({ decision, reason, policyVersion, matchedProfile, provenance });
78
+ let nearestGrant;
79
+ const result = (decision, reason, provenance, matchedProfile = null) => ({ decision,
80
+ reason: nearestGrant && decision === 'escalate'
81
+ ? `${reason}; nearest-grant:${nearestGrant.grantId}; differing-fields:${nearestGrant.fields.join(',')}` : reason,
82
+ policyVersion, matchedProfile, provenance, ...(nearestGrant && decision === 'escalate' ? { nearestGrant } : {}) });
76
83
  if (context.platform)
77
84
  return result(context.platform === 'deny' ? 'deny' : 'escalate', 'platform-constraint', 'platform');
78
85
  if (!validHitlAction(action))
79
86
  return result('escalate', 'invalid-action-descriptor', 'default');
80
- if (!HITL_CATEGORIES.some(c => c === action.category) || !HITL_ENVIRONMENTS.some(e => e === action.environment)
81
- || !action.reversible || action.impact === 'high')
87
+ if (unsafeDurableAction(action))
82
88
  return result('escalate', 'safety-category-requires-explicit-review', 'platform');
83
89
  // Revalidate even when invoked directly with objects that bypassed the config loader.
84
90
  if (context.layers.some(l => validateHitlPolicy(l.policy).length))
@@ -88,6 +94,8 @@ export function resolveHitlAuthorization(action, context) {
88
94
  const now = Date.parse(context.now);
89
95
  if (!Number.isFinite(now))
90
96
  return result('escalate', 'invalid-clock', 'default');
97
+ if (context.durableAuthorization?.failures.length)
98
+ return result('escalate', 'authorization-ledger-invalid', 'default');
91
99
  const session = context.sessionAuthorization;
92
100
  if (session?.source === 'session-user') {
93
101
  const probe = { version: '1', enabled: true, reviewedAt: context.now, maxAgeSeconds: 1,
@@ -99,6 +107,36 @@ export function resolveHitlAuthorization(action, context) {
99
107
  }
100
108
  if (context.expectedPolicyVersion && policyVersion !== context.expectedPolicyVersion)
101
109
  return result('escalate', 'stale-policy-version', 'project-policy');
110
+ if (context.durableAuthorization) {
111
+ const durable = matchDurableAuthorization(action, context.durableAuthorization, now, glob);
112
+ nearestGrant = durable.nearest;
113
+ // An independent human grant needs no profile, but cannot bypass a governing review/revocation.
114
+ for (const { policy: p } of durable.match ? context.layers : []) {
115
+ if (!p)
116
+ continue;
117
+ if (!p.enabled)
118
+ return result('escalate', 'policy-revoked', 'project-policy');
119
+ if (now >= Date.parse(p.expiresAt))
120
+ return result('escalate', 'policy-expired', 'project-policy');
121
+ const reviewed = Date.parse(p.reviewedAt);
122
+ if (reviewed > now || now - reviewed >= p.maxAgeSeconds * 1000)
123
+ return result('escalate', 'stale-policy-review', 'project-policy');
124
+ if (p.requireReview.some(s => selected(s, action)))
125
+ return result('escalate', 'policy-requires-review', 'project-policy');
126
+ }
127
+ if (durable.match) {
128
+ const { grant: g, effectId, recordHash } = durable.match;
129
+ const policyExpiry = context.layers.flatMap(({ policy: p }) => p ? [Date.parse(p.expiresAt),
130
+ Date.parse(p.reviewedAt) + p.maxAgeSeconds * 1000] : []);
131
+ // Even until-revoked grants issue finite receipts; every consumption still reloads revocations.
132
+ const expiresAt = new Date(Math.min(g.expiresAt === 'until-revoked' ? now + 86400_000 : Date.parse(g.expiresAt), ...policyExpiry)).toISOString();
133
+ return { ...result('auto-authorized', 'durable-user-authorization', 'durable-user'), expiresAt,
134
+ authorizationGrant: { grantId: g.grantId, effectId, recordHash } };
135
+ }
136
+ }
137
+ if (!HITL_CATEGORIES.some(c => c === action.category) || !HITL_ENVIRONMENTS.some(e => e === action.environment)) {
138
+ return result('escalate', 'safety-category-requires-explicit-review', 'platform');
139
+ }
102
140
  if (!context.layers.length)
103
141
  return result('escalate', 'no-project-policy', 'default');
104
142
  let matched = null;