@aiwg/cli 2026.11.3 → 2026.11.5
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 +85 -18
- package/agentic/code/providers/model-capabilities.v1.json +35 -27
- 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 +9 -27
- 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 +29 -11
- 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/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/script-runner.js +7 -4
- package/dist/src/cli/handlers/sessions.js +1 -1
- package/dist/src/cli/handlers/steward-format.js +12 -0
- package/dist/src/cli/handlers/steward.js +1 -1
- package/dist/src/cli/handlers/use.js +14 -6
- package/dist/src/cli/handlers/utility-doctor.js +9 -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 +4 -5
- 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/host-resource-runtime.mjs +1 -1
- package/dist/src/config/user-registry.js +9 -1
- package/dist/src/config/worker-owner-lock.js +90 -10
- package/dist/src/decision/graph-flow-adapter.js +1 -1
- 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/manifest.js +6 -0
- package/dist/src/extensions/muse-managed-hooks.js +11 -0
- package/dist/src/extensions/project-local-discovery.js +21 -1
- package/dist/src/extensions/project-local-scaffold.js +19 -7
- 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/factory-models.js +144 -0
- package/dist/src/models/model-capabilities.v1.json +35 -27
- package/dist/src/models/model-discovery.js +7 -3
- package/dist/src/models/worker-installation.d.mts +2 -0
- package/dist/src/models/worker-installation.mjs +11 -2
- package/dist/src/models/worker-invocation-policy.js +25 -1
- package/dist/src/models/wrapper-enforcement.js +1 -1
- 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/policy/repo-access.js +3 -1
- package/dist/src/process/bounded-child-process.mjs +49 -39
- package/dist/src/providers/capability-matrix.yaml +85 -18
- package/dist/src/providers/deployment-ownership.d.mts +1 -0
- package/dist/src/providers/deployment-ownership.mjs +29 -3
- package/dist/src/providers/deployment-preservation.mjs +44 -3
- package/dist/src/providers/grok-build-acp.js +13 -5
- package/dist/src/providers/grok-build-dispatch.js +35 -2
- package/dist/src/providers/grok-build-headless.js +171 -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/serve/worker-stdin-frame.mjs +1 -1
- package/dist/src/sessions/adapters/grok-build-fallback.js +33 -0
- package/dist/src/sessions/adapters/grok-build-native-records.js +134 -0
- package/dist/src/sessions/adapters/grok-build-native.js +237 -98
- package/dist/src/sessions/adapters/grok-build.js +95 -32
- package/dist/src/sessions/grok-build-cli-output.js +113 -0
- package/dist/src/sessions/grok-build-cli.js +4 -28
- package/dist/src/sessions/normalization.js +1 -1
- 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 +2 -2
- package/dist/src/smiths/hook-bridge/grok-build-translator.js +3 -1
- package/dist/src/smiths/hook-bridge/hermes-prompt-discovery.js +81 -0
- package/dist/src/smiths/hook-bridge/hermes-translator.js +5 -3
- package/dist/src/smiths/hook-bridge/hermes-trust.js +65 -0
- 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 +9 -8
- package/tools/agents/deploy-options.mjs +3 -0
- package/tools/agents/providers/base-frontmatter.mjs +3 -2
- package/tools/agents/providers/base-inventory.mjs +3 -1
- package/tools/agents/providers/base-kernel-skills.mjs +11 -5
- 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 +34 -41
- package/tools/agents/providers/model-wrapper.mjs +2 -5
- 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-commit.mjs +3 -0
- package/tools/agents/providers/rule-deployment-prepare.mjs +7 -5
- package/tools/agents/providers/rule-deployment-state.mjs +14 -6
- package/tools/agents/providers/rule-projection.mjs +39 -4
- package/tools/agents/providers/rule-startup.mjs +11 -10
- package/tools/agents/providers/skill-copy-prune.mjs +12 -0
- package/tools/agents/providers/staged-directory-reference.mjs +14 -0
- package/tools/agents/providers/stale-artifact-prune.mjs +24 -10
- package/tools/agents/providers/user-hooks.mjs +26 -0
- package/tools/cli/authorization-health.mjs +20 -0
- package/tools/cli/workspace-status.mjs +7 -0
- package/tools/commands/deploy-prompts-codex.mjs +15 -1
- package/tools/ralph-external/lib/claude-adapter.mjs +2 -0
- package/tools/ralph-external/lib/factory-adapter.mjs +6 -2
- package/tools/ralph-external/lib/worker-inputs.mjs +20 -1
- package/tools/ralph-external/lib/worker-isolation.mjs +1 -0
- package/tools/ralph-external/lib/worker-termination.mjs +21 -12
- package/tools/ralph-external/session-launcher.mjs +22 -17
- package/vscode-extension/schemas/aiwg.config.v1.json +20 -0
|
@@ -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),
|
package/dist/src/policy/hitl.js
CHANGED
|
@@ -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' || (
|
|
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
|
-
|
|
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 (
|
|
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;
|
|
@@ -123,7 +123,9 @@ function normalizeRepoEntry(entry, index, projectRoot) {
|
|
|
123
123
|
export function loadRepoAccessManifest(startDir = process.cwd()) {
|
|
124
124
|
const manifestPath = findRepoAccessManifest(startDir);
|
|
125
125
|
if (!manifestPath) {
|
|
126
|
-
throw new Error(
|
|
126
|
+
throw new Error('Repo access manifest not found. Expected .aiwg/aiwg.config workspace + repos blocks (canonical). '
|
|
127
|
+
+ `Legacy compatibility fallbacks: ${REPO_ACCESS_MANIFEST_PATHS.join(' or ')}. `
|
|
128
|
+
+ 'Register a repo with aiwg repo-access add --path <repo-or-file> --name <name> --allow read,write.');
|
|
127
129
|
}
|
|
128
130
|
const workspaceProjectRoot = findProjectRootFromManifest(manifestPath);
|
|
129
131
|
const isWorkspaceConfig = manifestPath.endsWith('/.aiwg/aiwg.config')
|
|
@@ -10,6 +10,10 @@
|
|
|
10
10
|
* normal Node `ETIMEDOUT` error/result with a message that names the
|
|
11
11
|
* command, tier and bound.
|
|
12
12
|
*
|
|
13
|
+
* Stdin defaults to ignore. Synchronous `input` is delivered through a private
|
|
14
|
+
* mode-0600 temporary file descriptor, closed and removed after each call.
|
|
15
|
+
* This avoids synchronous stdin pipes that fail in Codex sandboxes (#4032).
|
|
16
|
+
*
|
|
13
17
|
* Tiers (see `SYNC_PROCESS_TIER_BOUNDS_MS`):
|
|
14
18
|
* - `quick` 30s — local queries: git status/rev-parse/config, version
|
|
15
19
|
* probes, `which`/`where`, `df`, tmux queries.
|
|
@@ -75,6 +79,9 @@ import {
|
|
|
75
79
|
execFileSync as nodeExecFileSync,
|
|
76
80
|
spawnSync as nodeSpawnSync,
|
|
77
81
|
} from 'node:child_process';
|
|
82
|
+
import { closeSync, mkdtempSync, openSync, rmSync, writeFileSync } from 'node:fs';
|
|
83
|
+
import { tmpdir } from 'node:os';
|
|
84
|
+
import { join } from 'node:path';
|
|
78
85
|
import { signalChild } from './signal-child.mjs';
|
|
79
86
|
|
|
80
87
|
/** Env var that raises or disables the `long` tier bound. `0` disables it (no timeout). */
|
|
@@ -208,45 +215,41 @@ function isParentStdinDescriptor(value) {
|
|
|
208
215
|
return value === 'inherit' || value === 0 || value === process.stdin;
|
|
209
216
|
}
|
|
210
217
|
|
|
211
|
-
/**
|
|
212
|
-
* A bounded call never inherits stdin; stdout/stderr may still be inherited
|
|
213
|
-
* for progress output. When the caller supplies `input`, an inherited
|
|
214
|
-
* stdin form is normalized to `'pipe'` instead of `'ignore'` — `input`
|
|
215
|
-
* needs a real pipe to deliver its payload through, and `'ignore'` would
|
|
216
|
-
* silently drop it (#3062 B/C finding 9). `options` is otherwise left
|
|
217
|
-
* untouched when stdin was not going to be inherited anyway.
|
|
218
|
-
*
|
|
219
|
-
* @param {Record<string, unknown>} options
|
|
220
|
-
* @returns {Record<string, unknown>}
|
|
221
|
-
*/
|
|
218
|
+
/** Normalize stdin without changing output streams or caller-owned options. */
|
|
222
219
|
function withoutInheritedStdin(options) {
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
// `stdio: 'inherit'`/fd `0`/`process.stdin` could still leave stdin
|
|
229
|
-
// connected to the parent's real stdin instead of the pipe `input`
|
|
230
|
-
// is written to). stdout/stderr and the payload itself are untouched.
|
|
231
|
-
if (options.stdio === 'inherit') {
|
|
232
|
-
return { ...options, stdio: ['pipe', 'inherit', 'inherit'] };
|
|
233
|
-
}
|
|
234
|
-
if (Array.isArray(options.stdio) && isParentStdinDescriptor(options.stdio[0])) {
|
|
235
|
-
const stdio = options.stdio.slice();
|
|
236
|
-
stdio[0] = 'pipe';
|
|
237
|
-
return { ...options, stdio };
|
|
238
|
-
}
|
|
239
|
-
return options;
|
|
240
|
-
}
|
|
241
|
-
if (options.stdio === 'inherit') {
|
|
242
|
-
return { ...options, stdio: ['ignore', 'inherit', 'inherit'] };
|
|
220
|
+
const stdio = Array.isArray(options.stdio)
|
|
221
|
+
? options.stdio.slice()
|
|
222
|
+
: [options.stdio, options.stdio ?? 'pipe', options.stdio ?? 'pipe'];
|
|
223
|
+
if (stdio[0] == null || stdio[0] === 'pipe' || stdio[0] === 'overlapped' || isParentStdinDescriptor(stdio[0])) {
|
|
224
|
+
stdio[0] = options.input === undefined ? 'ignore' : 'pipe';
|
|
243
225
|
}
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
226
|
+
return { ...options, stdio };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Deliver synchronous input without Node's sandbox-sensitive stdin pipe (#4032). */
|
|
230
|
+
function withSyncStdin(options, run) {
|
|
231
|
+
if (options.input === undefined) return run(options);
|
|
232
|
+
// Never fall back to Node's synchronous input pipe: in sandboxes it blocks the
|
|
233
|
+
// child until the timeout. Without writable temp storage the call fails fast;
|
|
234
|
+
// boundedSpawnSync turns this into a returned error, as spawnSync does.
|
|
235
|
+
let directory;
|
|
236
|
+
try { directory = mkdtempSync(join(tmpdir(), 'aiwg-sync-stdin-')); }
|
|
237
|
+
catch (error) { throw Object.assign(error, { aiwgStdinTempUnavailable: true }); }
|
|
238
|
+
let fd;
|
|
239
|
+
try {
|
|
240
|
+
const filename = join(directory, 'stdin');
|
|
241
|
+
writeFileSync(filename, options.input, {
|
|
242
|
+
flag: 'wx', mode: 0o600, encoding: options.encoding ?? 'utf8',
|
|
243
|
+
});
|
|
244
|
+
fd = openSync(filename, 'r');
|
|
245
|
+
const { input: _input, ...nodeOptions } = options;
|
|
246
|
+
nodeOptions.stdio = options.stdio.slice();
|
|
247
|
+
nodeOptions.stdio[0] = fd;
|
|
248
|
+
return run(nodeOptions);
|
|
249
|
+
} finally {
|
|
250
|
+
try { if (fd !== undefined) closeSync(fd); }
|
|
251
|
+
finally { rmSync(directory, { recursive: true, force: true }); }
|
|
248
252
|
}
|
|
249
|
-
return options;
|
|
250
253
|
}
|
|
251
254
|
|
|
252
255
|
/**
|
|
@@ -328,7 +331,7 @@ export function boundedExecSync(command, tier, options) {
|
|
|
328
331
|
const boundMs = effectiveTimeoutMs(tier, options);
|
|
329
332
|
const nodeOptions = toNodeOptions(options, boundMs);
|
|
330
333
|
try {
|
|
331
|
-
return nodeExecSync(command,
|
|
334
|
+
return withSyncStdin(nodeOptions, prepared => nodeExecSync(command, prepared));
|
|
332
335
|
} catch (error) {
|
|
333
336
|
throw enrichTimeoutError(error, { description: command, tier, boundMs });
|
|
334
337
|
}
|
|
@@ -351,7 +354,7 @@ export function boundedExecFileSync(file, args, tier, options) {
|
|
|
351
354
|
const boundMs = effectiveTimeoutMs(tier, options);
|
|
352
355
|
const nodeOptions = toNodeOptions(options, boundMs);
|
|
353
356
|
try {
|
|
354
|
-
return nodeExecFileSync(file, args,
|
|
357
|
+
return withSyncStdin(nodeOptions, prepared => nodeExecFileSync(file, args, prepared));
|
|
355
358
|
} catch (error) {
|
|
356
359
|
throw enrichTimeoutError(error, { description: describeCommand(file, args), tier, boundMs });
|
|
357
360
|
}
|
|
@@ -383,7 +386,14 @@ export function boundedSpawnSync(command, args, tier, options) {
|
|
|
383
386
|
assertValidTier(tier);
|
|
384
387
|
const boundMs = effectiveTimeoutMs(tier, options);
|
|
385
388
|
const nodeOptions = toNodeOptions(options, boundMs);
|
|
386
|
-
|
|
389
|
+
let result;
|
|
390
|
+
try {
|
|
391
|
+
result = withSyncStdin(nodeOptions, prepared => nodeSpawnSync(command, args, prepared));
|
|
392
|
+
} catch (error) {
|
|
393
|
+
// Like spawnSync, report a missing temp directory for input as a returned error; other throws propagate.
|
|
394
|
+
if (!error?.aiwgStdinTempUnavailable) throw error;
|
|
395
|
+
result = { pid: 0, output: [null, null, null], stdout: null, stderr: null, status: null, signal: null, error };
|
|
396
|
+
}
|
|
387
397
|
enrichTimeoutError(result.error, { description: describeCommand(command, args), tier, boundMs, signal: result.signal });
|
|
388
398
|
return result;
|
|
389
399
|
}
|