@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
@@ -2,11 +2,91 @@
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { hostname } from 'node:os';
4
4
  import { basename, dirname, join, resolve } from 'node:path';
5
- import { mkdir, writeFile, symlink, readlink, unlink, rm, readdir } from 'node:fs/promises';
6
- import { readFileSync, readlinkSync } from 'node:fs';
5
+ import { link, mkdir, open, writeFile, symlink, unlink, rm, readdir } from 'node:fs/promises';
6
+ import { lstatSync, readFileSync, readlinkSync, realpathSync } from 'node:fs';
7
7
  import { projectControlPath } from './project-artifacts.js';
8
8
  export const workerWriteLock = (project) => projectControlPath(project, 'aiwg.config.apply-lock');
9
9
  const missing = (error) => error.code === 'ENOENT';
10
+ function samePath(left, right) {
11
+ const canonical = process.platform === 'win32' ? realpathSync.native : resolve;
12
+ return canonical(left) === canonical(right);
13
+ }
14
+ function lockDirectoryTarget(path) {
15
+ const target = resolve(dirname(path), readlinkSync(path));
16
+ const targetGeneration = basename(target).slice(`${basename(path)}.`.length);
17
+ if (!samePath(dirname(target), dirname(path)) ||
18
+ !basename(target).startsWith(`${basename(path)}.`) ||
19
+ !/^[a-f0-9-]{36}$/.test(targetGeneration))
20
+ throw new Error(`Invalid worker configuration lock target: ${target}`);
21
+ return target;
22
+ }
23
+ function generationValue(path) {
24
+ const stat = lstatSync(path);
25
+ if (stat.isSymbolicLink())
26
+ return readlinkSync(path);
27
+ if (stat.isFile())
28
+ return readFileSync(path, 'utf8');
29
+ throw new Error(`Invalid worker lock generation record: ${path}`);
30
+ }
31
+ async function publishOwnerDirectory(directory, path) {
32
+ if (process.platform === 'win32') {
33
+ // Junctions preserve directory traversal without requiring symlink privilege.
34
+ await symlink(resolve(directory), path, 'junction');
35
+ }
36
+ else {
37
+ await symlink(basename(directory), path);
38
+ }
39
+ }
40
+ async function publishGeneration(path, value) {
41
+ if (process.platform !== 'win32')
42
+ return symlink(value, path);
43
+ // Publish a complete immutable record atomically. A Windows file symlink needs
44
+ // privilege, while a same-directory hard link is exclusive and works without it.
45
+ const temporary = join(dirname(path), `.worker-lock-record-${randomUUID()}.tmp`);
46
+ let temporaryCreated = false;
47
+ try {
48
+ const handle = await open(temporary, 'wx', 0o600);
49
+ temporaryCreated = true;
50
+ let writeError;
51
+ try {
52
+ await handle.writeFile(value);
53
+ await handle.sync();
54
+ }
55
+ catch (error) {
56
+ writeError = error;
57
+ }
58
+ try {
59
+ await handle.close();
60
+ }
61
+ catch (error) {
62
+ if (writeError)
63
+ throw new AggregateError([writeError, error], 'Could not close a worker lock record', { cause: writeError });
64
+ throw error;
65
+ }
66
+ if (writeError)
67
+ throw writeError;
68
+ await link(temporary, path);
69
+ }
70
+ catch (error) {
71
+ if (temporaryCreated) {
72
+ try {
73
+ await unlink(temporary);
74
+ }
75
+ catch (cleanupError) {
76
+ if (!missing(cleanupError))
77
+ throw new AggregateError([error, cleanupError], 'Could not clean up an unpublished worker lock record', { cause: error });
78
+ }
79
+ }
80
+ throw error;
81
+ }
82
+ try {
83
+ await unlink(temporary);
84
+ }
85
+ catch (error) {
86
+ if (!missing(error))
87
+ process.emitWarning(`Published worker lock record but could not remove its temporary hard-link name: ${String(error)}`, { code: 'AIWG_WORKER_LOCK_TEMP_CLEANUP' });
88
+ }
89
+ }
10
90
  function processStart(pid) {
11
91
  try {
12
92
  const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
@@ -35,12 +115,12 @@ function provablyDead(owner) {
35
115
  }
36
116
  function latest(directory) {
37
117
  let owner = JSON.parse(readFileSync(join(directory, 'owner.json'), 'utf8'));
38
- // Immutable successor links are a compare-and-swap: only one contender can claim a generation.
118
+ // Immutable successor records are a compare-and-swap: only one contender can claim a generation.
39
119
  for (;;) {
40
120
  if (!/^[a-f0-9-]{36}$/.test(owner.generation))
41
121
  throw new Error('Invalid worker lock generation');
42
122
  try {
43
- owner = JSON.parse(readlinkSync(join(directory, `next-${owner.generation}`)));
123
+ owner = JSON.parse(generationValue(join(directory, `next-${owner.generation}`)));
44
124
  }
45
125
  catch (error) {
46
126
  if (missing(error))
@@ -66,7 +146,7 @@ async function sweepOrphanedOwners(path) {
66
146
  if (!provablyDead(owner))
67
147
  continue;
68
148
  try {
69
- if (resolve(parent, await readlink(path)) === directory)
149
+ if (samePath(lockDirectoryTarget(path), directory))
70
150
  continue;
71
151
  }
72
152
  catch (error) {
@@ -79,7 +159,7 @@ async function sweepOrphanedOwners(path) {
79
159
  function lease(path, directory, owner) {
80
160
  const assertOwned = () => {
81
161
  try {
82
- if (readlinkSync(path) === basename(directory) && latest(directory).generation === owner.generation)
162
+ if (samePath(lockDirectoryTarget(path), directory) && latest(directory).generation === owner.generation)
83
163
  return;
84
164
  }
85
165
  catch { /* Missing or replaced ownership must never authorize another write. */ }
@@ -89,7 +169,7 @@ function lease(path, directory, owner) {
89
169
  assertOwned();
90
170
  if (keepBlocked) {
91
171
  // A caught failure can be retried even while this embedding process stays alive.
92
- await symlink(JSON.stringify({ ...identity(), released: true }), join(directory, `next-${owner.generation}`));
172
+ await publishGeneration(join(directory, `next-${owner.generation}`), JSON.stringify({ ...identity(), released: true }));
93
173
  }
94
174
  else {
95
175
  // A live owner cannot be reclaimed; unlink only while we still own this exact generation.
@@ -110,7 +190,7 @@ export async function acquireWorkerWriteLock(project, block = false, proposalDig
110
190
  if (block)
111
191
  await writeFile(join(directory, 'blocked'), 'Worker policy apply/recovery in progress.\n', { mode: 0o600 });
112
192
  // No visible lock can exist without an owner, even if initialization is interrupted.
113
- await symlink(basename(directory), path);
193
+ await publishOwnerDirectory(directory, path);
114
194
  }
115
195
  catch (error) {
116
196
  await rm(directory, { recursive: true, force: true });
@@ -125,7 +205,7 @@ export async function reclaimWorkerWriteLock(project) {
125
205
  let directory;
126
206
  let previous;
127
207
  try {
128
- directory = resolve(dirname(path), await readlink(path));
208
+ directory = lockDirectoryTarget(path);
129
209
  previous = latest(directory);
130
210
  }
131
211
  catch (error) {
@@ -137,7 +217,7 @@ export async function reclaimWorkerWriteLock(project) {
137
217
  throw new Error(`Worker configuration is locked by a live or unverifiable owner (${previous.host}:${previous.pid}); ${path}`);
138
218
  const owner = identity();
139
219
  try {
140
- await symlink(JSON.stringify(owner), join(directory, `next-${previous.generation}`));
220
+ await publishGeneration(join(directory, `next-${previous.generation}`), JSON.stringify(owner));
141
221
  }
142
222
  catch (error) {
143
223
  if (error.code === 'EEXIST')
@@ -9,7 +9,7 @@ export function admittedDecisionFlowAdapter(ledger, estimate, invoke, signal, on
9
9
  ledger.cancel();
10
10
  throw new DecisionGraphError('graph cancelled');
11
11
  }
12
- // Flow invokes a gate only after the host approved it. The gate dispatches
12
+ // Flow invokes a gate only after host approval or a signed HITL check. The gate dispatches
13
13
  // nothing, spends no decision budget and is not a decision observation.
14
14
  if (request.node.kind === 'gate' && request.node.sideEffectMode === 'none' && request.node.ref === undefined) {
15
15
  return { outputs: {}, attempts: 1, usage: { tokens: 0, costUsd: 0, timeMs: 0 } };
@@ -0,0 +1,50 @@
1
+ // Defines and validates bounded human grants and their signed effect bindings.
2
+ import { canonicalJson } from '../security/artifact-trust.js';
3
+ import { usageError } from './errors.js';
4
+ import { payloadDigest } from './identity.js';
5
+ import { assertDigestOnly } from './redaction.js';
6
+ import { isEffectSchemaValid } from './schema.js';
7
+ // Extensible names cannot opt into any class the human-authorization rule excludes.
8
+ const FORBIDDEN = /(?:^|[^a-z0-9])(?:secrets?|credentials?|tokens?|destructive|production|prod|policy[._ -]?override|delete|destroy|wipe|drop)(?:$|[^a-z0-9])/i;
9
+ const ACTION_NAME = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/;
10
+ export function assertAuthorizationGrant(value) {
11
+ if (!isEffectSchemaValid('authorizationGrant', value))
12
+ throw usageError('Invalid authorization grant', 'grant-schema-invalid');
13
+ const grant = value;
14
+ assertDigestOnly(grant);
15
+ const { categories, targets, resources, verbs } = grant.scope;
16
+ if ([...categories, ...verbs].some(name => !ACTION_NAME.test(name))
17
+ || [...categories, ...targets, ...resources, ...verbs].some(name => FORBIDDEN.test(name))) {
18
+ throw usageError('Authorization grant covers a prohibited action class', 'grant-prohibited');
19
+ }
20
+ const created = Date.parse(grant.createdAt);
21
+ const expiry = grant.expiresAt === 'until-revoked' ? Infinity : Date.parse(grant.expiresAt);
22
+ const revoked = grant.revocation.state === 'revoked' ? Date.parse(grant.revocation.revokedAt) : created;
23
+ if (!Number.isFinite(created) || Number.isNaN(expiry) || !Number.isFinite(revoked)
24
+ || expiry <= created || revoked < created
25
+ || grant.supersedes === grant.grantId || grant.revokes === grant.grantId) {
26
+ throw usageError('Invalid authorization grant time or link', 'grant-bounds-invalid');
27
+ }
28
+ }
29
+ // Grants are internal ledger records with no external effect to verify, so they use the
30
+ // x.aiwg.* vendor namespace (like x.aiwg.ledger-lock-recovery) rather than a core kind.
31
+ export const AUTHORIZATION_GRANT_KIND = 'x.aiwg.authorization-grant';
32
+ export function authorizationGrantIdentity(grantId) {
33
+ return { kind: AUTHORIZATION_GRANT_KIND, target: `x-authorization-grant:${grantId}`, context: { grantId } };
34
+ }
35
+ /** Also used on read: generic effect writers cannot bypass grant validation or digest binding. */
36
+ export function authorizationGrantFailure(predicate) {
37
+ if (predicate.kind !== AUTHORIZATION_GRANT_KIND || predicate.phase !== 'intent')
38
+ return null;
39
+ const grant = predicate.authorizationGrant;
40
+ try {
41
+ assertAuthorizationGrant(grant);
42
+ }
43
+ catch {
44
+ return 'authorization-grant-invalid';
45
+ }
46
+ const identity = authorizationGrantIdentity(grant.grantId);
47
+ return predicate.target !== identity.target || canonicalJson(predicate.context) !== canonicalJson(identity.context)
48
+ || predicate.payloadDigest !== payloadDigest(canonicalJson(grant)) ? 'authorization-grant-binding' : null;
49
+ }
50
+ //# sourceMappingURL=authorization-grant.js.map
@@ -0,0 +1,130 @@
1
+ // Stores grants in the existing signed ledger; the private descriptor index is derived only.
2
+ import { lstat, readFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { canonicalJson } from '../security/artifact-trust.js';
5
+ import { AUTHORIZATION_GRANT_KIND, assertAuthorizationGrant, authorizationGrantIdentity } from './authorization-grant.js';
6
+ import { integrityError } from './errors.js';
7
+ import { payloadDigest } from './identity.js';
8
+ import { assertKeyring } from './keyring.js';
9
+ import { recordIntent } from './ledger.js';
10
+ import { lineFailures, readAllSegments, readKeyring } from './reader.js';
11
+ import { ensureLedgerDirectories, replaceFile, withLedgerLock } from './store.js';
12
+ import { verifyLedger } from './verify.js';
13
+ /** Fail closed on ledger damage. Expired/revoked grants remain history; matching belongs to #4001. */
14
+ export async function readAuthorizationGrants(ledger) {
15
+ const verification = await verifyLedger(ledger);
16
+ if (!verification.ok)
17
+ return { grants: [], failures: verification.failures };
18
+ const segments = await readAllSegments(ledger.paths());
19
+ const count = segments.reduce((total, segment) => total + segment.lines.length, 0);
20
+ if (count !== verification.records)
21
+ return { grants: [], failures: [{ reason: 'ledger-changed-during-read' }] };
22
+ if (!count)
23
+ return { grants: [], failures: [] };
24
+ const ring = await readKeyring(ledger.paths());
25
+ try {
26
+ assertKeyring(ring, ledger.scope);
27
+ }
28
+ catch {
29
+ return { grants: [], failures: [{ reason: 'keyring-invalid' }] };
30
+ }
31
+ const grants = [];
32
+ const failures = [];
33
+ for (const segment of segments) {
34
+ let previous = null;
35
+ if (segment.torn)
36
+ failures.push({ reason: 'segment-torn', writer: segment.writer });
37
+ for (const read of segment.lines) {
38
+ if (!read.decoded) {
39
+ failures.push({ reason: read.failure, writer: segment.writer, seq: read.index });
40
+ continue;
41
+ }
42
+ const { line, statement: { predicate } } = read.decoded;
43
+ for (const reason of lineFailures(ring, ledger.scope, segment.writer, read.index, read.decoded, previous)) {
44
+ failures.push({ reason, writer: segment.writer, seq: read.index });
45
+ }
46
+ previous = line.recordHash;
47
+ if (predicate.kind === AUTHORIZATION_GRANT_KIND && predicate.phase === 'intent') {
48
+ grants.push({ grant: structuredClone(predicate.authorizationGrant), effectId: predicate.effectId, recordHash: line.recordHash });
49
+ }
50
+ }
51
+ }
52
+ // A purged grant is never resurrected from its earlier signed intent.
53
+ const tombstoned = new Set(segments.flatMap(segment => segment.lines.flatMap(read => read.decoded?.statement.predicate.phase === 'tombstone' ? [read.decoded.statement.predicate.effectId] : [])));
54
+ return { grants: failures.length ? [] : grants.filter(entry => !tombstoned.has(entry.effectId))
55
+ .sort((a, b) => a.effectId.localeCompare(b.effectId)), failures };
56
+ }
57
+ const indexPath = (ledger) => join(ledger.paths().root, 'authorization-index.json');
58
+ const indexBytes = (ledger, entries) => `${canonicalJson({
59
+ apiVersion: 'authorization-grant-index.aiwg.io/v1', ledgerScope: ledger.scope,
60
+ entries: entries.map(({ grant, effectId, recordHash }) => ({
61
+ grantId: grant.grantId, effectId, recordHash, scope: grant.scope, constraints: grant.constraints,
62
+ createdAt: grant.createdAt, expiresAt: grant.expiresAt, revocation: grant.revocation,
63
+ })),
64
+ })}\n`;
65
+ /** Trusted host API only: it records supplied human evidence, and does not authenticate a user. */
66
+ export async function recordAuthorizationGrant(ledger, value, links = {}) {
67
+ assertAuthorizationGrant(value);
68
+ const grant = structuredClone(value);
69
+ const paths = ledger.paths();
70
+ await ensureLedgerDirectories(paths);
71
+ return withLedgerLock(paths, 'authorization-index', ledger.lockTimeoutMs, async () => {
72
+ const before = await readAuthorizationGrants(ledger);
73
+ if (before.failures.length)
74
+ throw integrityError('authorization-ledger-invalid');
75
+ const receipt = await recordIntent(ledger, {
76
+ ...authorizationGrantIdentity(grant.grantId), authorizationGrant: grant,
77
+ payloadDigest: payloadDigest(canonicalJson(grant)), links,
78
+ });
79
+ const after = await readAuthorizationGrants(ledger);
80
+ if (after.failures.length)
81
+ throw integrityError('authorization-ledger-invalid');
82
+ await replaceFile(paths.root, indexPath(ledger), indexBytes(ledger, after.grants));
83
+ return receipt;
84
+ });
85
+ }
86
+ /** Inspect derived index drift without creating directories, repairing files or acquiring signing keys. */
87
+ export async function inspectAuthorizationIndex(ledger, read) {
88
+ try {
89
+ const stat = await lstat(indexPath(ledger));
90
+ if (!stat.isFile() || (stat.mode & 0o077) !== 0)
91
+ return 'drift';
92
+ return await readFile(indexPath(ledger), 'utf8') === indexBytes(ledger, read.grants) ? 'current' : 'drift';
93
+ }
94
+ catch (error) {
95
+ if (error.code === 'ENOENT')
96
+ return read.grants.length ? 'missing' : 'absent';
97
+ throw error;
98
+ }
99
+ }
100
+ /** Rebuild and compare the index, retaining a nonzero result for damage found before repair. */
101
+ export async function verifyAuthorizationGrants(ledger) {
102
+ const paths = ledger.paths();
103
+ await ensureLedgerDirectories(paths);
104
+ return withLedgerLock(paths, 'authorization-index', ledger.lockTimeoutMs, async () => {
105
+ const read = await readAuthorizationGrants(ledger);
106
+ const expected = indexBytes(ledger, read.grants);
107
+ let current = null;
108
+ let privateFile = true;
109
+ try {
110
+ const stat = await lstat(indexPath(ledger));
111
+ privateFile = stat.isFile() && (stat.mode & 0o077) === 0;
112
+ // Do not follow a substituted index symlink.
113
+ if (stat.isFile())
114
+ current = await readFile(indexPath(ledger), 'utf8');
115
+ }
116
+ catch (error) {
117
+ if (error.code !== 'ENOENT')
118
+ throw error;
119
+ }
120
+ const indexChanged = current !== expected || !privateFile;
121
+ const failures = [...read.failures];
122
+ if ((!privateFile || current !== null) && indexChanged)
123
+ failures.push({ reason: 'authorization-index-mismatch' });
124
+ // A missing derived index is safe to rebuild; no grant data is trusted from it.
125
+ if (indexChanged)
126
+ await replaceFile(paths.root, indexPath(ledger), expected);
127
+ return { ok: failures.length === 0, exitCode: failures.length ? 6 : 0, grants: read.grants.length, indexChanged, failures };
128
+ });
129
+ }
130
+ //# sourceMappingURL=authorization-store.js.map
@@ -23,4 +23,6 @@ export { DISPATCH_KIND, DISPATCH_VERIFIER_VERSION, INVOCATION_PATTERN, createDis
23
23
  export { assertDigestOnly, containsRestrictedMaterial } from './redaction.js';
24
24
  export { EFFECT_SCHEMA_IDS, effectSchemaErrors, isEffectSchemaValid } from './schema.js';
25
25
  export { decisionLinkOf, verifyDecisionLinks, } from './decision-links.js';
26
+ export { assertAuthorizationGrant, authorizationGrantIdentity } from './authorization-grant.js';
27
+ export { readAuthorizationGrants, recordAuthorizationGrant, verifyAuthorizationGrants } from './authorization-store.js';
26
28
  //# sourceMappingURL=index.js.map
@@ -233,6 +233,7 @@ export async function recordIntent(ledger, input) {
233
233
  schemaVersion: RECORD_SCHEMA_VERSION, effectId: id, idDerivation: derivation, scope: ledger.scope,
234
234
  kind: input.kind, target: input.target, context: structuredClone(input.context), phase: 'intent',
235
235
  payloadDigest: input.payloadDigest, writer: ledger.writer, seq, prev, recordedAt, links: structuredClone(input.links ?? {}),
236
+ ...(input.authorizationGrant ? { authorizationGrant: structuredClone(input.authorizationGrant) } : {}),
236
237
  }),
237
238
  }, id);
238
239
  if (lost)
@@ -79,7 +79,7 @@ export async function purgeEffect(ledger, id, options) {
79
79
  const original = read.decoded.statement;
80
80
  if (original.predicate.effectId !== id || original.predicate.phase === 'tombstone')
81
81
  return read.text;
82
- const { target: _target, context: _context, verification: _verification, failure: _failure, ...kept } = original.predicate;
82
+ const { target: _target, context: _context, verification: _verification, failure: _failure, authorizationGrant: _grant, ...kept } = original.predicate;
83
83
  const predicate = {
84
84
  ...kept,
85
85
  phase: 'tombstone',
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { readFile } from 'node:fs/promises';
7
7
  import { canonicalJson } from '../security/artifact-trust.js';
8
+ import { authorizationGrantFailure } from './authorization-grant.js';
8
9
  import { integrityError } from './errors.js';
9
10
  import { checkSignature } from './keyring.js';
10
11
  import { decodeSegmentLine, effectIdBindingHolds, recordHashFor, signedAt, subjectBindingHolds, } from './records.js';
@@ -58,6 +59,9 @@ export function lineFailures(keyring, scope, writer, index, decoded, previousHas
58
59
  const failures = [];
59
60
  const { line, payload, statement } = decoded;
60
61
  const predicate = statement.predicate;
62
+ const grantFailure = authorizationGrantFailure(predicate);
63
+ if (grantFailure)
64
+ failures.push(grantFailure);
61
65
  if (line.writer !== writer || predicate.writer !== writer)
62
66
  failures.push('writer-mismatch');
63
67
  if (line.seq !== index || predicate.seq !== index)
@@ -8,6 +8,7 @@
8
8
  * @see docs/contracts/effect-ledger.v1.md "Envelope and record"
9
9
  */
10
10
  import { canonicalJson, decodeBase64, dssePae } from '../security/artifact-trust.js';
11
+ import { authorizationGrantFailure } from './authorization-grant.js';
11
12
  import { integrityError } from './errors.js';
12
13
  import { effectIdDerivation, sha256Digest } from './identity.js';
13
14
  import { assertDigestOnly } from './redaction.js';
@@ -37,6 +38,9 @@ export function recordHashFor(payload) {
37
38
  export function signSegmentLine(statement, key, recordHash) {
38
39
  assertDigestOnly(statement);
39
40
  assertEffectSchema('record', statement);
41
+ const grantFailure = authorizationGrantFailure(statement.predicate);
42
+ if (grantFailure)
43
+ throw integrityError(grantFailure);
40
44
  const payload = Buffer.from(canonicalJson(statement), 'utf8');
41
45
  const line = {
42
46
  schemaVersion: SEGMENT_LINE_SCHEMA_VERSION,
@@ -9,12 +9,14 @@ import Ajv2020 from 'ajv/dist/2020.js';
9
9
  import addFormats from 'ajv-formats';
10
10
  import { integrityError } from './errors.js';
11
11
  export const EFFECT_SCHEMA_IDS = Object.freeze({
12
+ authorizationGrant: 'https://aiwg.io/schemas/authorization-grant.aiwg.io/v1',
12
13
  record: 'https://aiwg.io/schemas/effects/EffectRecord.v1.schema.json',
13
14
  checkpoint: 'https://aiwg.io/schemas/effects/EffectCheckpoint.v1.schema.json',
14
15
  keyring: 'https://aiwg.io/schemas/effects/EffectKeyring.v1.schema.json',
15
16
  verifierResult: 'https://aiwg.io/schemas/effects/EffectVerifierResult.v1.schema.json',
16
17
  });
17
18
  const SCHEMA_FILES = {
19
+ authorizationGrant: 'AuthorizationGrant.v1.schema.json',
18
20
  record: 'EffectRecord.v1.schema.json',
19
21
  checkpoint: 'EffectCheckpoint.v1.schema.json',
20
22
  keyring: 'EffectKeyring.v1.schema.json',
@@ -26,6 +26,8 @@
26
26
  * shape on read. `aiwg refresh --restore-hooks` reads the most-recent
27
27
  * .bak.<timestamp> file and restores it.
28
28
  */
29
+ import { readFileSync } from 'node:fs';
30
+ import { verifiedHookCommand } from './verified-hook-command.js';
29
31
  import { promises as fs } from 'node:fs';
30
32
  import * as path from 'node:path';
31
33
  import { captureDeploymentOutputs, recordDeploymentOutputs } from '../providers/deployment-ownership.mjs';
@@ -46,12 +48,14 @@ const HOOK_SCRIPTS = [
46
48
  },
47
49
  ];
48
50
  /** Canonical registrations shared by installation and the read-only drift check. */
49
- export function managedClaudeHooks(sourceFiles) {
51
+ export function managedClaudeHooks(sourceFiles, root, sourceDirectory, scope) {
50
52
  return HOOK_SCRIPTS.filter(({ file }) => sourceFiles.includes(file)).flatMap(({ file, events }) => Object.entries(events).map(([event, argument]) => ({
51
53
  event,
52
54
  script: path.posix.join('.claude', 'hooks', file),
53
55
  hookId: file.replace(/\.(cjs|js)$/, ''),
54
- command: `node ${path.posix.join('.claude', 'hooks', file)}${argument ? ` ${argument}` : ''}`,
56
+ command: root && sourceDirectory
57
+ ? verifiedHookCommand(root, path.posix.join('.claude', 'hooks', file), readFileSync(path.join(sourceDirectory, file)), argument ? [argument] : [], scope)
58
+ : `node ${path.posix.join('.claude', 'hooks', file)}${argument ? ` ${argument}` : ''}`,
55
59
  })));
56
60
  }
57
61
  /**
@@ -210,11 +214,7 @@ export async function installAiwgHooks(opts) {
210
214
  result.warnings.push('Migrated legacy array-shaped hooks field to object form (#107).');
211
215
  }
212
216
  settings.hooks = hooksObj;
213
- for (const { event, script, hookId, command } of managedClaudeHooks(sourceFiles)) {
214
- // Claude Code parses hook commands as shell command strings. Keep the
215
- // embedded script path POSIX-style on every host: native Windows
216
- // backslashes are interpreted as escapes and collapse into a nonexistent
217
- // path such as `.claudehooksaiwg-session.cjs` (#133).
217
+ for (const { event, script, hookId, command } of managedClaudeHooks(sourceFiles, opts.commandRoot ?? opts.projectPath, sourceHooksDir, opts.scope)) {
218
218
  if (!hooksObj[event])
219
219
  hooksObj[event] = [];
220
220
  const groups = hooksObj[event];
@@ -1,3 +1,4 @@
1
+ import { verifiedHookCommand } from './verified-hook-command.js';
1
2
  // Canonical Muse hook registrations shared by deployment and read-only drift checks.
2
3
  export const promptDiscoveryHook = {
3
4
  id: 'aiwg-prompt-discovery',
@@ -46,4 +47,14 @@ export const AIWG_MANAGED_HOOKS = [
46
47
  },
47
48
  promptDiscoveryHook,
48
49
  ];
50
+ /** Resolve registrations against the final deployment root, never the session cwd. */
51
+ export function managedMuseHooks(root, bytes, scope) {
52
+ return AIWG_MANAGED_HOOKS.map(hook => hook.id === promptDiscoveryHook.id ? {
53
+ ...hook, group: { ...hook.group, hooks: [{ ...hook.group.hooks[0],
54
+ command: verifiedHookCommand(root, '.muse/hooks/aiwg-prompt-discovery.cjs', bytes, [], scope),
55
+ }] },
56
+ } : process.platform === 'win32' ? { ...hook, group: { ...hook.group,
57
+ hooks: hook.group.hooks.map(entry => ({ ...entry, command: entry.command.replace('> /dev/null', '> NUL') })),
58
+ } } : hook);
59
+ }
49
60
  //# sourceMappingURL=muse-managed-hooks.js.map
@@ -0,0 +1,32 @@
1
+ // Report legacy cwd-relative user hook commands without reading credentials or writing config.
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+ export async function diagnoseUserHookCommands() {
6
+ const diagnostics = [];
7
+ for (const provider of ['claude', 'muse']) {
8
+ const file = path.join(os.homedir(), `.${provider}`, provider === 'claude' ? 'settings.json' : 'hooks.json');
9
+ let doc;
10
+ try {
11
+ doc = JSON.parse(await fs.readFile(file, 'utf8'));
12
+ }
13
+ catch {
14
+ continue;
15
+ } // Existing config diagnostics own unreadable documents.
16
+ for (const [event, groups] of Object.entries(doc.hooks || {})) {
17
+ if (!Array.isArray(groups))
18
+ continue;
19
+ for (const group of groups) {
20
+ for (const hook of Array.isArray(group?.hooks) ? group.hooks : []) {
21
+ if (typeof hook?.command !== 'string' ||
22
+ !/^node\s+["']?\.[\\/]?(?:claude|muse)[\\/]hooks[\\/]aiwg-[\w-]+\.(?:cjs|js)(?:["'\s]|$)/.test(hook.command))
23
+ continue;
24
+ diagnostics.push({ severity: 'warning', code: 'relative-user-hook-command', path: file,
25
+ message: `${provider} user ${event} hook depends on the session cwd. Run aiwg use all --global --providers ${provider} to anchor and verify it.` });
26
+ }
27
+ }
28
+ }
29
+ }
30
+ return diagnostics;
31
+ }
32
+ //# sourceMappingURL=user-hook-diagnostics.js.map
@@ -0,0 +1,32 @@
1
+ // Render a shell-neutral Node loader that executes only the anchored, reviewed bytes.
2
+ import { createHash } from 'node:crypto';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+ export function verifiedHookCommand(root, relative, bytes, args = [], scope) {
6
+ if (relative.split('/').includes('..') || !/^[.\w/-]+\.(?:cjs|js)$/.test(relative))
7
+ throw new Error('Invalid managed hook script path');
8
+ const paths = process.platform === 'win32' ? path.win32 : path;
9
+ const anchor = paths.resolve(root);
10
+ const userHome = process.platform === 'win32' ? process.env.USERPROFILE || os.homedir() : os.homedir();
11
+ const user = scope === 'user' || (scope === undefined && anchor === paths.resolve(userHome));
12
+ const projectEnv = !user && relative.startsWith('.claude/') ? 'CLAUDE_PROJECT_DIR' : '';
13
+ // Encoding data avoids shell expansion of $, %, backticks, quotes and backslashes
14
+ // in install paths under sh, cmd.exe and PowerShell. The loader itself contains
15
+ // only single-quoted JS strings inside the shell's double-quoted argument.
16
+ const data = Buffer.from(JSON.stringify({ anchor, relative, args, projectEnv })).toString('base64');
17
+ const hash = createHash('sha256').update(bytes).digest('hex');
18
+ const loader = [
19
+ "const fs=require('node:fs'),p=require('node:path'),M=require('node:module');",
20
+ `const c=JSON.parse(Buffer.from('${data}','base64').toString());`,
21
+ 'const root=c.projectEnv?process.env[c.projectEnv]||c.anchor:c.anchor;',
22
+ `const script=p.resolve(root,'${relative}');`,
23
+ "if(p.relative(fs.realpathSync(script),script)!==''||!fs.lstatSync(script).isFile())throw Error('Unsafe AIWG hook path');",
24
+ 'const bytes=fs.readFileSync(script);',
25
+ `if(require('node:crypto').createHash('sha256').update(bytes).digest('hex')!=='${hash}')throw Error('AIWG hook changed; redeploy and review');`,
26
+ 'process.argv=[process.execPath,script,...c.args];',
27
+ 'const m=new M(script);m.filename=script;m.paths=M._nodeModulePaths(p.dirname(script));',
28
+ "m._compile(bytes.toString('utf8'),script);",
29
+ ].join('');
30
+ return `node -e "${loader}"`;
31
+ }
32
+ //# sourceMappingURL=verified-hook-command.js.map
@@ -0,0 +1,52 @@
1
+ // Warn on literal opposite directives for an explicitly declared subject at equal precedence.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { parseRuleFrontmatter } from '../rules/activation.mjs';
5
+ import { loadRulePinConfigs } from '../rules/pins.mjs';
6
+ import { resolveRulePrecedence } from '../rules/precedence.mjs';
7
+ import { ruleOrderingAliases } from '../rules/project-precedence.js';
8
+ import { resolveFrameworkIndexRoot } from '../artifacts/framework-index-paths.js';
9
+ export function lintRuleConflicts(targetDir, files, projectRoot) {
10
+ const seen = new Map();
11
+ const diagnostics = [];
12
+ const emitted = new Set();
13
+ const configs = loadRulePinConfigs(projectRoot);
14
+ const root = resolveFrameworkIndexRoot(projectRoot);
15
+ for (const file of [...files].sort()) {
16
+ if (/\.core\.md$|\/(?:README|RULES-INDEX|RULES-ONDEMAND)\.md$/.test(file))
17
+ continue;
18
+ const absolute = path.resolve(targetDir, file);
19
+ const parsed = parseRuleFrontmatter(fs.readFileSync(absolute, 'utf8'));
20
+ if (!parsed.valid)
21
+ continue;
22
+ const data = parsed.data;
23
+ const subjects = typeof data.subject === 'string' ? [data.subject] : Array.isArray(data.subjects) ? data.subjects : [];
24
+ if (!subjects.length)
25
+ continue;
26
+ const ordering = resolveRulePrecedence({ ...parsed.rule, name: String(data.name ?? path.basename(file, '.md')) }, configs, ruleOrderingAliases(absolute, root, projectRoot));
27
+ for (const line of parsed.body.split('\n')) {
28
+ const match = line.trim().match(/^(?:[-*]\s+)?(always|never|must not|must|do not)\s+(.+?)[.!]?$/i);
29
+ if (!match)
30
+ continue;
31
+ const positive = /^(always|must)$/i.test(match[1]);
32
+ const directive = match[2].toLowerCase().replace(/\s+/g, ' ');
33
+ for (const subject of subjects.filter((item) => typeof item === 'string' && !!item.trim())) {
34
+ const key = JSON.stringify([subject.trim().toLowerCase(), ordering.precedence, directive]);
35
+ const previous = seen.get(key) ?? [];
36
+ for (const other of previous) {
37
+ if (other.file === file || other.positive === positive)
38
+ continue;
39
+ const pair = JSON.stringify([other.file, file, subject]);
40
+ if (emitted.has(pair))
41
+ continue;
42
+ emitted.add(pair);
43
+ diagnostics.push({ ruleId: 'rules/activation', ruleName: 'Rule activation contract', severity: 'warn', file,
44
+ message: `Possible conflicting rules ${other.file} and ${file}: opposite directives on declared subject '${subject}' at precedence ${ordering.precedence}. Review scope and ordering.` });
45
+ }
46
+ seen.set(key, [...previous, { file, positive }]);
47
+ }
48
+ }
49
+ }
50
+ return diagnostics;
51
+ }
52
+ //# sourceMappingURL=rule-conflicts.js.map
@@ -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