@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.
- package/agentic/code/addons/aiwg-hooks/canonical/aiwg-prompt-discovery.yaml +3 -2
- package/agentic/code/addons/aiwg-hooks/hooks/aiwg-prompt-discovery.cjs +12 -9
- package/agentic/code/addons/aiwg-utils/rules/anti-laziness.md +2 -0
- package/agentic/code/addons/composition-engine/lib/runtime.mjs +5 -26
- package/agentic/code/addons/composition-engine/schemas/flow-graph.schema.json +22 -0
- package/agentic/code/providers/capability-matrix.yaml +17 -20
- package/agentic/code/providers/model-capabilities.v1.json +17 -16
- package/dist/src/a2a/hitl-authorization.js +46 -0
- package/dist/src/a2a/hitl-driver.js +5 -5
- package/dist/src/artifacts/browser-export.js +2 -0
- package/dist/src/artifacts/framework-source-digest.js +1 -1
- package/dist/src/artifacts/index-builder.js +5 -25
- package/dist/src/artifacts/index-capability.js +24 -0
- package/dist/src/artifacts/query-engine-discover-output.js +8 -3
- package/dist/src/artifacts/query-engine-rules.js +27 -9
- package/dist/src/artifacts/query-engine-scoring.js +5 -5
- package/dist/src/artifacts/query-engine-show-card.js +5 -1
- package/dist/src/artifacts/query-engine-show-load.js +1 -1
- package/dist/src/artifacts/query-engine-show.js +3 -3
- package/dist/src/artifacts/query-engine-templates.js +10 -4
- package/dist/src/artifacts/query-engine-verbose.js +18 -4
- package/dist/src/artifacts/relations-builder.js +1 -0
- package/dist/src/artifacts/types.js +1 -1
- package/dist/src/cli/handlers/checkpoint-handoff.js +2 -1
- package/dist/src/cli/handlers/dataset.js +17 -0
- package/dist/src/cli/handlers/guided-setup.js +3 -1
- package/dist/src/cli/handlers/refresh-managed-deployment.js +17 -5
- package/dist/src/cli/handlers/rules.js +1 -1
- package/dist/src/cli/handlers/sessions.js +1 -1
- package/dist/src/cli/handlers/steward.js +1 -1
- package/dist/src/cli/handlers/use.js +18 -5
- package/dist/src/cli/handlers/utility-doctor.js +5 -2
- package/dist/src/cli/handlers/workspace.js +1 -1
- package/dist/src/cli/services/deployment-probe-scope.js +40 -0
- package/dist/src/cli/services/deployment-verification.js +5 -6
- package/dist/src/config/aiwg-config.js +6 -0
- package/dist/src/config/authorization-cli.js +61 -3
- package/dist/src/config/cli-help.js +1 -1
- package/dist/src/config/cli.js +4 -2
- package/dist/src/config/decision-config.js +2 -1
- package/dist/src/config/host-resource-runtime.mjs +1 -1
- package/dist/src/config/jev-credential-reference.js +56 -0
- package/dist/src/config/user-config.js +13 -19
- package/dist/src/config/user-registry.js +9 -1
- package/dist/src/config/worker-owner-lock.js +90 -10
- package/dist/src/decision/ask.js +3 -2
- package/dist/src/decision/graph-flow-adapter.js +1 -1
- package/dist/src/decision/jev-credentials.js +22 -0
- package/dist/src/decision/offload.js +1 -1
- package/dist/src/decision/openbao-kv-resolver.mjs +96 -0
- package/dist/src/decision/openbao-runtime.js +101 -0
- package/dist/src/effects/authorization-grant.js +50 -0
- package/dist/src/effects/authorization-store.js +130 -0
- package/dist/src/effects/index.js +2 -0
- package/dist/src/effects/ledger.js +1 -0
- package/dist/src/effects/lifecycle.js +1 -1
- package/dist/src/effects/reader.js +4 -0
- package/dist/src/effects/records.js +4 -0
- package/dist/src/effects/schema.js +2 -0
- package/dist/src/extensions/claude-hooks-installer.js +7 -7
- package/dist/src/extensions/muse-managed-hooks.js +11 -0
- package/dist/src/extensions/user-hook-diagnostics.js +32 -0
- package/dist/src/extensions/verified-hook-command.js +32 -0
- package/dist/src/lint/rule-conflicts.js +52 -0
- package/dist/src/lint/runner.js +3 -0
- package/dist/src/mcp/cli.mjs +3 -1
- package/dist/src/mcp/elicitation.mjs +30 -0
- package/dist/src/mcp/grok-build-config.mjs +1 -1
- package/dist/src/mcp/muse-native-config.mjs +1 -0
- package/dist/src/mcp/server.mjs +2 -0
- package/dist/src/mcp/tools/authorization.mjs +78 -0
- package/dist/src/models/model-capabilities.v1.json +17 -16
- package/dist/src/policy/authorization-capture.js +64 -0
- package/dist/src/policy/authorization-operations.js +108 -0
- package/dist/src/policy/hitl-check.js +3 -2
- package/dist/src/policy/hitl-consume.js +14 -0
- package/dist/src/policy/hitl-durable-store.js +60 -0
- package/dist/src/policy/hitl-durable.js +60 -0
- package/dist/src/policy/hitl-receipt.js +5 -0
- package/dist/src/policy/hitl.js +44 -6
- package/dist/src/process/bounded-child-process.mjs +49 -39
- package/dist/src/providers/capability-matrix.yaml +17 -20
- package/dist/src/providers/deployment-ownership.d.mts +1 -0
- package/dist/src/providers/deployment-ownership.mjs +21 -2
- package/dist/src/providers/grok-build-headless.js +170 -77
- package/dist/src/providers/grok-build-inspect.js +1 -0
- package/dist/src/providers/grok-build-paths.js +2 -0
- package/dist/src/providers/muse-paths.js +4 -2
- package/dist/src/providers/provider-context-contracts.js +12 -4
- package/dist/src/providers/provider-definition-schema.js +6 -0
- package/dist/src/providers/provider-seeds-1.js +3 -3
- package/dist/src/providers/provider-seeds-2.js +6 -4
- package/dist/src/providers/provider-seeds-3.js +6 -6
- package/dist/src/rules/activation.d.mts +2 -0
- package/dist/src/rules/activation.mjs +16 -7
- package/dist/src/rules/inline-budget.d.mts +2 -1
- package/dist/src/rules/inline-budget.mjs +4 -2
- package/dist/src/rules/inventory.js +3 -0
- package/dist/src/rules/precedence.d.mts +6 -0
- package/dist/src/rules/precedence.mjs +49 -0
- package/dist/src/rules/project-precedence.js +73 -0
- package/dist/src/rules/rule-frontmatter.schema.json +15 -0
- package/dist/src/serve/a2a-terminal-observer.js +12 -3
- package/dist/src/serve/mission-hitl.js +20 -1
- package/dist/src/sessions/adapters/grok-build-fallback.js +33 -0
- package/dist/src/sessions/adapters/grok-build-native-records.js +64 -0
- package/dist/src/sessions/adapters/grok-build-native.js +92 -100
- package/dist/src/sessions/adapters/grok-build.js +65 -24
- package/dist/src/sessions/grok-build-cli-output.js +113 -0
- package/dist/src/sessions/grok-build-cli.js +4 -28
- package/dist/src/smiths/context-pipeline/bridge-ownership.js +4 -3
- package/dist/src/smiths/context-pipeline/finalization.js +5 -0
- package/dist/src/smiths/context-pipeline/generator.js +1 -1
- package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +20 -17
- package/dist/src/smiths/context-pipeline/workspace-doctor.js +6 -1
- package/dist/src/smiths/context-pipeline/workspace-document.js +6 -0
- package/dist/src/smiths/context-pipeline/workspace-migration.js +2 -12
- package/dist/src/smiths/hook-bridge/codex-translator.js +11 -14
- package/dist/src/smiths/hook-bridge/codex-trust.js +7 -2
- package/dist/src/smiths/hook-bridge/copilot-translator.js +2 -1
- package/dist/src/smiths/hook-bridge/factory-trust.js +56 -0
- package/dist/src/smiths/hook-bridge/grok-build-translator.js +3 -1
- package/dist/src/smiths/hook-bridge/hermes-prompt-discovery.js +78 -0
- package/dist/src/smiths/hook-bridge/hermes-translator.js +5 -3
- package/dist/src/smiths/hook-bridge/index.js +3 -1
- package/dist/src/smiths/hook-bridge/prompt-discovery-gaps.js +3 -2
- package/package.json +7 -1
- package/tools/agents/deploy-agents.mjs +5 -6
- package/tools/agents/deploy-options.mjs +1 -0
- package/tools/agents/providers/base-frontmatter.mjs +3 -2
- package/tools/agents/providers/claude-post-deploy.mjs +1 -1
- package/tools/agents/providers/codex-post-deploy.mjs +1 -1
- package/tools/agents/providers/generic.mjs +66 -0
- package/tools/agents/providers/grok-build.mjs +3 -1
- package/tools/agents/providers/muse-hooks.mjs +13 -11
- package/tools/agents/providers/muse-prompt-discovery.mjs +5 -1
- package/tools/agents/providers/muse.mjs +2 -1
- package/tools/agents/providers/openclaw.mjs +2 -1
- package/tools/agents/providers/rule-deployment-prepare.mjs +5 -3
- package/tools/agents/providers/rule-deployment-state.mjs +14 -6
- package/tools/agents/providers/rule-startup.mjs +11 -10
- package/tools/agents/providers/staged-directory-reference.mjs +14 -0
- package/tools/agents/providers/user-hooks.mjs +26 -0
- package/tools/cli/authorization-health.mjs +20 -0
- package/tools/cli/decision-offload-report.mjs +2 -0
- package/tools/cli/workspace-status.mjs +7 -0
- package/tools/commands/deploy-prompts-codex.mjs +15 -1
- package/tools/plugin/package-plugins.mjs +6 -1
- package/tools/ralph-external/lib/claude-adapter.mjs +2 -2
- package/vscode-extension/schemas/aiwg.config.v1.json +20 -0
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// Shared exact-path OpenBao KV policy for runtime and qualification callers.
|
|
2
|
+
export class CredentialResolutionError extends Error {
|
|
3
|
+
constructor(category) {
|
|
4
|
+
super('credential resolution failed');
|
|
5
|
+
this.name = 'CredentialResolutionError';
|
|
6
|
+
this.category = category;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const SEGMENT = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/;
|
|
11
|
+
const REF = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
12
|
+
|
|
13
|
+
/** Validates the host-only config. It holds locators, never secret values. */
|
|
14
|
+
export function validateResolverConfig(config) {
|
|
15
|
+
const fail = () => { throw new CredentialResolutionError('configuration'); };
|
|
16
|
+
if (!config || typeof config !== 'object' || Array.isArray(config)) fail();
|
|
17
|
+
const allowed = ['schemaVersion', 'addr', 'caFile', 'appRole', 'tokenScript', 'mount', 'refs'];
|
|
18
|
+
if (Object.keys(config).some(key => !allowed.includes(key)) || config.schemaVersion !== 'openbao-kv-resolver-config/v1') fail();
|
|
19
|
+
let addr;
|
|
20
|
+
try { addr = new URL(config.addr); } catch { fail(); }
|
|
21
|
+
if (addr.protocol !== 'https:' || addr.username || addr.password || addr.search || addr.hash || addr.pathname !== '/') fail();
|
|
22
|
+
if (config.caFile !== undefined && (typeof config.caFile !== 'string' || !config.caFile.startsWith('/'))) fail();
|
|
23
|
+
if (!SEGMENT.test(config.appRole ?? '') || typeof config.tokenScript !== 'string' || !config.tokenScript.startsWith('/') || !SEGMENT.test(config.mount ?? '')) fail();
|
|
24
|
+
if (!config.refs || typeof config.refs !== 'object' || Array.isArray(config.refs) || !Object.keys(config.refs).length) fail();
|
|
25
|
+
for (const [ref, target] of Object.entries(config.refs)) {
|
|
26
|
+
if (!REF.test(ref) || !target || typeof target !== 'object' || Object.keys(target).some(key => !['path', 'field'].includes(key))) fail();
|
|
27
|
+
if (typeof target.path !== 'string' || !target.path.split('/').every(part => SEGMENT.test(part))) fail();
|
|
28
|
+
if (target.field !== undefined && !SEGMENT.test(target.field)) fail();
|
|
29
|
+
}
|
|
30
|
+
return config;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Creates the resolver. `tokenProvider` and `request` are injectable for offline tests.
|
|
35
|
+
* Granted values are cached per logical ref for the run and zeroed by `dispose()`.
|
|
36
|
+
*/
|
|
37
|
+
export function createOpenBaoKvResolver(rawConfig, seams) {
|
|
38
|
+
// Refuse a process that has disabled TLS verification globally, even with an injected request seam.
|
|
39
|
+
if (process.env.NODE_TLS_REJECT_UNAUTHORIZED === '0') throw new CredentialResolutionError('configuration');
|
|
40
|
+
const config = validateResolverConfig(rawConfig);
|
|
41
|
+
const tokenProvider = seams.tokenProvider;
|
|
42
|
+
const request = seams.request;
|
|
43
|
+
const entries = [];
|
|
44
|
+
const cache = new Map();
|
|
45
|
+
let token;
|
|
46
|
+
let disposed = false;
|
|
47
|
+
let seq = 0;
|
|
48
|
+
const record = (op, ref, outcome, httpStatus) => { entries.push({ seq: ++seq, op, ref, outcome, httpStatus }); };
|
|
49
|
+
const login = () => {
|
|
50
|
+
token ??= tokenProvider().then(value => { record('login', null, 'granted', null); return value; },
|
|
51
|
+
() => { record('login', null, 'failed', null); throw new CredentialResolutionError('failed'); });
|
|
52
|
+
return token;
|
|
53
|
+
};
|
|
54
|
+
return {
|
|
55
|
+
async resolveCredential(ref) {
|
|
56
|
+
if (disposed) throw new CredentialResolutionError('failed');
|
|
57
|
+
const target = typeof ref === 'string' && REF.test(ref) ? config.refs[ref] : undefined;
|
|
58
|
+
if (!target || !Object.hasOwn(config.refs, ref)) { record('read', REF.test(String(ref)) ? ref : 'invalid-ref', 'configuration', null); throw new CredentialResolutionError('configuration'); }
|
|
59
|
+
if (cache.has(ref)) return new Uint8Array(cache.get(ref));
|
|
60
|
+
const value = await login();
|
|
61
|
+
const url = new URL(`/v1/${config.mount}/data/${target.path}`, config.addr);
|
|
62
|
+
let response;
|
|
63
|
+
try { response = await request(url, { 'X-Vault-Token': value, accept: 'application/json' }); }
|
|
64
|
+
catch { record('read', ref, 'failed', null); throw new CredentialResolutionError('failed'); }
|
|
65
|
+
const status = response?.status ?? 0;
|
|
66
|
+
if (status === 403) { record('read', ref, 'denied', status); throw new CredentialResolutionError('denied'); }
|
|
67
|
+
if (status === 404) { record('read', ref, 'missing', status); throw new CredentialResolutionError('missing'); }
|
|
68
|
+
const data = status === 200 ? response.json?.data?.data : undefined;
|
|
69
|
+
const keys = data && typeof data === 'object' && !Array.isArray(data) ? Object.keys(data) : [];
|
|
70
|
+
const field = target.field ?? (keys.length === 1 ? keys[0] : undefined);
|
|
71
|
+
const secret = field !== undefined && data ? data[field] : undefined;
|
|
72
|
+
if (typeof secret !== 'string' || !secret) { record('read', ref, status === 200 ? 'configuration' : 'failed', status); throw new CredentialResolutionError(status === 200 ? 'configuration' : 'failed'); }
|
|
73
|
+
record('read', ref, 'granted', status);
|
|
74
|
+
const bytes = new TextEncoder().encode(secret);
|
|
75
|
+
cache.set(ref, bytes);
|
|
76
|
+
return new Uint8Array(bytes);
|
|
77
|
+
},
|
|
78
|
+
/** Sanitized: logical refs, operation, outcome and HTTP status only. */
|
|
79
|
+
audit: () => entries.map(entry => ({ ...entry })),
|
|
80
|
+
/** Zeroes cached values and revokes the AppRole token itself. Revocation failure is recorded, never thrown. */
|
|
81
|
+
async dispose() {
|
|
82
|
+
disposed = true;
|
|
83
|
+
for (const bytes of cache.values()) bytes.fill(0);
|
|
84
|
+
cache.clear();
|
|
85
|
+
const pending = token; token = undefined;
|
|
86
|
+
if (!pending) return;
|
|
87
|
+
let value;
|
|
88
|
+
try { value = await pending; } catch { return; }
|
|
89
|
+
try {
|
|
90
|
+
const response = await request(new URL('/v1/auth/token/revoke-self', config.addr), { 'X-Vault-Token': value }, 'POST');
|
|
91
|
+
const status = response?.status ?? 0;
|
|
92
|
+
record('revoke', null, status === 204 || status === 200 ? 'revoked' : 'failed', status);
|
|
93
|
+
} catch { record('revoke', null, 'failed', null); }
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// Resolve Jev references through the shared KV policy and host native secret store.
|
|
2
|
+
import { request as httpsRequest } from 'node:https';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import { createSecretStore } from '../auth/credential-store.js';
|
|
5
|
+
// @ts-expect-error Shared ESM policy also consumed directly by qualification tools.
|
|
6
|
+
import { createOpenBaoKvResolver } from './openbao-kv-resolver.mjs';
|
|
7
|
+
export class JevReferenceUnavailable extends Error {
|
|
8
|
+
constructor() { super('credential-unavailable'); }
|
|
9
|
+
}
|
|
10
|
+
const cache = new Map();
|
|
11
|
+
const safeToken = (value) => typeof value === 'string' && /^[\x21-\x7e]{1,4096}$/.test(value);
|
|
12
|
+
/** Fixed diagnostics, no redirects, bounded body and deadline, verified TLS only. */
|
|
13
|
+
function requestJson(url, method, headers, ca, body) {
|
|
14
|
+
return new Promise((resolve, reject) => {
|
|
15
|
+
const fail = () => { reject(new JevReferenceUnavailable()); };
|
|
16
|
+
const req = httpsRequest(url, { method, headers, ca, rejectUnauthorized: true, timeout: 10_000 }, res => {
|
|
17
|
+
const chunks = [];
|
|
18
|
+
let size = 0;
|
|
19
|
+
res.on('data', (chunk) => {
|
|
20
|
+
size += chunk.length;
|
|
21
|
+
if (size > 64 * 1024) {
|
|
22
|
+
req.destroy();
|
|
23
|
+
fail();
|
|
24
|
+
}
|
|
25
|
+
else
|
|
26
|
+
chunks.push(chunk);
|
|
27
|
+
});
|
|
28
|
+
res.on('error', fail);
|
|
29
|
+
res.on('aborted', fail);
|
|
30
|
+
res.on('end', () => {
|
|
31
|
+
let json;
|
|
32
|
+
try {
|
|
33
|
+
json = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
json = null;
|
|
37
|
+
}
|
|
38
|
+
resolve({ status: res.statusCode ?? 0, json });
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
const deadline = setTimeout(() => { req.destroy(); fail(); }, 10_000);
|
|
42
|
+
req.on('close', () => clearTimeout(deadline));
|
|
43
|
+
req.on('error', fail);
|
|
44
|
+
req.on('timeout', () => { req.destroy(); fail(); });
|
|
45
|
+
req.end(body);
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
export async function resolveOpenBaoJev(ref, env) {
|
|
49
|
+
try {
|
|
50
|
+
const addr = new URL(env.BAO_ADDR?.trim() || ref.addr || '');
|
|
51
|
+
if (addr.protocol !== 'https:' || addr.username || addr.password || addr.search || addr.hash || addr.pathname !== '/'
|
|
52
|
+
|| env.NODE_TLS_REJECT_UNAUTHORIZED === '0' || process.env.NODE_TLS_REJECT_UNAUTHORIZED === '0')
|
|
53
|
+
throw new JevReferenceUnavailable();
|
|
54
|
+
const key = JSON.stringify([addr.href, env.BAO_CACERT, ref]);
|
|
55
|
+
let pending = cache.get(key);
|
|
56
|
+
if (!pending) {
|
|
57
|
+
pending = resolveReference(ref, addr, env).catch(() => { cache.delete(key); throw new JevReferenceUnavailable(); });
|
|
58
|
+
cache.set(key, pending);
|
|
59
|
+
}
|
|
60
|
+
return await pending;
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
throw new JevReferenceUnavailable();
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
async function resolveReference(ref, addr, env) {
|
|
67
|
+
const ca = env.BAO_CACERT ? await readFile(env.BAO_CACERT) : undefined;
|
|
68
|
+
const [mount, , ...segments] = ref.path.split('/');
|
|
69
|
+
const resolver = createOpenBaoKvResolver({ schemaVersion: 'openbao-kv-resolver-config/v1', addr: addr.href,
|
|
70
|
+
appRole: ref.auth.role, tokenScript: '/unused-native-store', mount,
|
|
71
|
+
refs: { jev: { path: segments.join('/'), field: ref.field } } }, {
|
|
72
|
+
tokenProvider: async () => {
|
|
73
|
+
const read = (suffix) => createSecretStore({ service: 'aiwg.openbao', account: `${addr.origin}/${ref.auth.role}:${suffix}` }).loadSecret();
|
|
74
|
+
const [roleId, secretId] = await Promise.all([read('role-id'), read('secret-id')]);
|
|
75
|
+
if (!safeToken(roleId) || !safeToken(secretId))
|
|
76
|
+
throw new JevReferenceUnavailable();
|
|
77
|
+
const result = await requestJson(new URL('/v1/auth/approle/login', addr), 'POST', { 'content-type': 'application/json' }, ca, JSON.stringify({ role_id: roleId, secret_id: secretId }));
|
|
78
|
+
const token = result.json?.auth?.client_token;
|
|
79
|
+
if (result.status !== 200 || !safeToken(token))
|
|
80
|
+
throw new JevReferenceUnavailable();
|
|
81
|
+
return token;
|
|
82
|
+
},
|
|
83
|
+
request: (url, headers, method = 'GET') => requestJson(url, method, headers, ca),
|
|
84
|
+
});
|
|
85
|
+
try {
|
|
86
|
+
const bytes = await resolver.resolveCredential('jev');
|
|
87
|
+
try {
|
|
88
|
+
const token = new TextDecoder().decode(bytes);
|
|
89
|
+
if (!safeToken(token))
|
|
90
|
+
throw new JevReferenceUnavailable();
|
|
91
|
+
return token;
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
bytes.fill(0);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
await resolver.dispose();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
//# sourceMappingURL=openbao-runtime.js.map
|
|
@@ -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:
|
|
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
|