ai-engineering-loop 1.9.3 → 1.10.0
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/.agents/workflows/ai-engineering-loop.md +2 -2
- package/.claude/skills/ai-engineering-loop/SKILL.md +3 -1
- package/.gemini/skills/ai-engineering-loop/SKILL.md +3 -1
- package/.grok/skills/ai-engineering-loop/SKILL.md +3 -1
- package/bin/ai-engineering-loop.js +260 -0
- package/lib/goal-runtime.js +149 -15
- package/lib/run-checkout.js +70 -10
- package/lib/run-journey.js +75 -0
- package/lib/run-lifecycle.js +203 -0
- package/lib/safe-context.js +11 -0
- package/lib/studio-runtime.js +1 -1
- package/lib/studio-server.js +109 -6
- package/lib/workflow-runtime.js +5 -4
- package/package.json +1 -1
- package/studio/app.js +354 -33
- package/studio/index.html +31 -5
- package/studio/styles.css +11 -2
|
@@ -7,11 +7,11 @@ Follow `policies/review-budget.md`. Parent is Maker plus orchestrator. Do not us
|
|
|
7
7
|
|
|
8
8
|
Compact map (not a second OS): Specify (stages 0-1), Make (stages 2-4), Review (stages 5-7), Deliver (stage 8). Keep the 8-stage numbers. Do not skip Goal Contract, verification, Devil's Advocate, or Judge.
|
|
9
9
|
|
|
10
|
-
Deterministic gates are mandatory. Read `core/runtime-safety.md`. Stage 0 runs sync-hosts, status, then `npx ai-engineering-loop run [--mode report-only|assisted|unattended]`; `state --json` gives runId, immutable mode, and `.ai-engineering-loop/runs/<runId>/` (`RUN_DIR`). Never edit state.json. Run `budget status --run <runId>` before every model/subagent call and `budget record --input <actual> --output <actual> --model <id> --run <runId>` immediately after provider usage is returned. Never invent counts. Missing accounting stops UNATTENDED and requires human direction in ASSISTED. `budget pause` is the kill switch.
|
|
10
|
+
Deterministic gates are mandatory. Read `core/runtime-safety.md`. Stage 0 runs sync-hosts, status, then `npx ai-engineering-loop run [--mode report-only|assisted|unattended]`; `state --json` gives runId, immutable mode, and `.ai-engineering-loop/runs/<runId>/` (`RUN_DIR`). Never edit state.json. Run `budget status --run <runId>` before every model/subagent call and `budget record --input <actual> --output <actual> --model <id> --run <runId>` immediately after provider usage is returned. Never invent counts. Missing accounting stops UNATTENDED and requires human direction in ASSISTED. `budget pause` is the kill switch. Keep Workflow Studio alive without exposing chain-of-thought: before each stage or long operation emit `npx ai-engineering-loop activity heartbeat --run <runId> --phase <phase> --message <short factual summary>`. Existing node and gate commands publish their lifecycle automatically. Persist human questions with `interaction question` so they appear once in Studio.
|
|
11
11
|
|
|
12
12
|
Inherited invariants: read `core/grill-policy.md`, `policies/tdd-policy.md`, and `.ai-engineering-loop/glossary.md`. On `adapter_type: dot`, grill includes blast radius: lifecycle sketch and load `task-impact-inquiry`. If the user prompt has no numbered AC, draft the contract, list a short menu and wait. Chat agreement is not freeze. AC is a failure table. One red test per AC row. Do not freeze sunny-path-only. Write claimed-vs-reality.md. Do not spawn Devil's Advocate if the file is missing or any Claimed row lacks Reality. Report Spec and Standards separately. DA prompt: "at most 8 tool calls; read the diff file; skip css and generated files". Judge prompt: "at most 4 tool calls; ledger and contract only; skip css; do not re-review the whole diff". Never use `browser_subagent` as reviewer. `generate-workflow` reads workflow.md and lessons.md; missing maker_intern means INVOCATION_UNAVAILABLE. Do not type a model name.
|
|
13
13
|
|
|
14
|
-
Stage 1: if the user asks for ideas, list a short menu and wait; do not implement. Grill if the task is ambiguous (`core/grill-policy.md`)
|
|
14
|
+
Stage 1: if the user asks for ideas, list a short menu and wait; do not implement. Grill if the task is ambiguous (`core/grill-policy.md`). Chat agreement is not freeze. Publish the complete failure-table JSON through `npx ai-engineering-loop goal draft --run <runId> --file <repository-local-json> --revision <currentRevision>` so Studio shows the exact draft, then wait. After explicit human freeze, run `goal freeze --run <runId> --revision <reviewedRevision> --hash <reviewedHash> --by human`; `gate goal` remains legacy compatibility only. Do not start Maker before freeze. On business-logic change, and always on `adapter_type: dot`, grill includes blast radius: lifecycle sketch, four pillars (state, sibling, approval, queues), ASCII picture. Load `task-impact-inquiry` if present. Do not run a second interview. Passing unit tests are not isolation proof. Use `.ai-engineering-loop/glossary.md`. Name test seams. AC is a failure table (happy, empty/omit, boundary, sibling, error). One red test per AC row. Do not freeze sunny-path-only. Stages 2-4 branch on mode: REPORT_ONLY never edits repository files, writes RUN_DIR/report.json, runs `gate report`, and stops. ASSISTED uses normal Maker. UNATTENDED runs `sandbox create --run <runId>`, Maker only in the returned worktreePath, never edits the parent checkout, and runs `sandbox capture --run <runId>`. Read `maker_intern` from workflow.md (missing or none = parent is Maker). Do not type a model name. If intern is set, confirm it came from this host's list (`/models` if that command exists). If the list command is missing or the id is not on it, parent is Maker; say intern INVOCATION_UNAVAILABLE. Intern cannot skip verification, Devil's Advocate, or Judge. Maker: TDD at those seams (`policies/tdd-policy.md`): one red test per AC row. ASSISTED writes RUN_DIR/diff.patch; UNATTENDED capture writes it; then `gate maker`. Stage 5 writes current RUN_DIR/verification.json and runs `gate verification`. Bugs: red repro first (`core/root-cause-analysis.md`). Mid-loop stop: `core/handoff-policy.md`.
|
|
15
15
|
|
|
16
16
|
If `invoke_subagent` (or Task) exists, spawn `devil-advocate` then `judge` as siblings. Wait for each child. Do not run them in the background. Use `general-purpose` only if the named type is rejected.
|
|
17
17
|
|
|
@@ -37,6 +37,8 @@ Parent session is Maker plus orchestrator. Spawn Devil's Advocate and Judge as *
|
|
|
37
37
|
|
|
38
38
|
## Deterministic artifact gates (mandatory)
|
|
39
39
|
|
|
40
|
+
Keep Workflow Studio alive without exposing chain-of-thought: before each stage or long operation emit `npx ai-engineering-loop activity heartbeat --run <runId> --phase <phase> --message <short factual summary>`. Existing `node start|activity|complete` and `gate` commands publish node lifecycle automatically. Before asking the human, persist the question with `npx ai-engineering-loop interaction question --run <runId> --id <id> --message <text>` so it appears once in Studio. Never put secrets, hidden reasoning, or raw model context in activity messages.
|
|
41
|
+
|
|
40
42
|
Run `npx ai-engineering-loop state --json` to get the current `runId` and use `.ai-engineering-loop/runs/<runId>/` as `RUN_DIR`. Never edit `state.json` or `current.json`.
|
|
41
43
|
|
|
42
44
|
Read `core/runtime-safety.md`. The ledger mode is immutable. Before every model or Task call, run `npx ai-engineering-loop budget status --run <runId>`; after it returns, record actual provider-reported usage with `budget record --input <n> --output <n> --model <id> --run <runId>`. Never invent actual token counts. If usage metadata is unavailable, UNATTENDED stops and escalates; ASSISTED discloses the gap and asks the human whether to continue. `budget pause` is an emergency kill switch.
|
|
@@ -44,7 +46,7 @@ Read `core/runtime-safety.md`. The ledger mode is immutable. Before every model
|
|
|
44
46
|
Inherited invariants remain mandatory: read `core/grill-policy.md`, `policies/tdd-policy.md`, and `.ai-engineering-loop/glossary.md`. On `adapter_type: dot`, grill includes blast radius: lifecycle sketch and load `task-impact-inquiry`. If the user prompt has no numbered AC, draft the contract, list a short menu and wait. Chat agreement is not freeze. AC is a failure table. One red test per AC row. Do not freeze sunny-path-only. Write claimed-vs-reality.md. Do not spawn Devil's Advocate if the file is missing or any Claimed row lacks Reality. Report Spec and Standards separately. DA prompt includes "at most 8 tool calls; read the diff file; skip css and generated files". Judge prompt includes "at most 4 tool calls; ledger and contract only; skip css; do not re-review the whole diff".
|
|
45
47
|
|
|
46
48
|
1. Stage 0: `npx ai-engineering-loop sync-hosts`, `status`, then `run [--mode report-only|assisted|unattended]` to create or resume the ledger. Run `state --json` and `budget status`. Read `.ai-engineering-loop/glossary.md`. Read `.ai-engineering-loop/lessons.md` and `.ai-engineering-loop/workflow.md` if they exist. Follow workflow.md hooks (`before_grill`, `after_freeze`, `after_pass`). Do not skip required gates even if workflow.md asks. If workflow.md is missing, run the default 8-stage loop. If sync-hosts copied files, tell the user a new session is needed; keep going with this session.
|
|
47
|
-
2. Stage 1: Goal Contract (`core/goal-contract.md`). If the user asks for ideas, list a short menu and wait; do not implement. If the task is ambiguous and the user can answer, grill first (`core/grill-policy.md`): design tree, recommended answers, do not ask look-up facts. On business-logic change, and always on `adapter_type: dot`, include blast radius. Chat agreement is not freeze.
|
|
49
|
+
2. Stage 1: Goal Contract (`core/goal-contract.md`). If the user asks for ideas, list a short menu and wait; do not implement. If the task is ambiguous and the user can answer, grill first (`core/grill-policy.md`): design tree, recommended answers, do not ask look-up facts. On business-logic change, and always on `adapter_type: dot`, include blast radius. Chat agreement is not freeze. Emit `npx ai-engineering-loop activity goal-drafting --run <runId> --message <summary>` before drafting. Write the contract JSON to a repository-local temporary file, then publish it with `npx ai-engineering-loop goal draft --run <runId> --file <file> --revision <currentRevision>` so Workflow Studio sees the exact draft and its ready state. Wait. After the user explicitly freezes, use `npx ai-engineering-loop goal freeze --run <runId> --revision <reviewedRevision> --hash <reviewedHash> --by human`; do not edit production code unless it passes. `gate goal` remains the legacy compatibility command, not the preferred revision-bound path.
|
|
48
50
|
3. After Goal freeze, branch on mode. REPORT_ONLY: do not edit repository files; write `RUN_DIR/report.json` with summary and recommendations, then run `gate report` and stop. ASSISTED: run the normal Maker and later require human approval. UNATTENDED: run `sandbox create --run <runId>`, set Maker's working directory to the returned worktreePath, never edit the parent checkout, then run `sandbox capture --run <runId>`. For Maker, read `maker_intern` from workflow.md (missing or none = parent is Maker). Do not type a model name. Confirm it through `/models` when available; otherwise parent is Maker and report INVOCATION_UNAVAILABLE. Intern cannot skip later gates. Bugs: red repro first. Features: one red test per AC row. In ASSISTED write the exact review diff to `RUN_DIR/diff.patch`; UNATTENDED capture writes it. Then run `npx ai-engineering-loop gate maker`.
|
|
49
51
|
4. Stage 5: run commands from `.ai-engineering-loop/verification.md`. Write `RUN_DIR/verification.json` with current git revision, gated diff hash, command, execution identity, times, exit code, stdout, timeout status, and test counts. Vague "seems green" is invalid. Keep `.ai-engineering-loop/tasks/claimed-vs-reality.md`. Run `npx ai-engineering-loop gate verification`; do not spawn Devil's Advocate unless it passes.
|
|
50
52
|
5. Write artifacts, then spawn. Before Devil's Advocate:
|
|
@@ -30,6 +30,8 @@ Compact map (not a second OS): Specify (stages 0-1), Make (stages 2-4), Review (
|
|
|
30
30
|
|
|
31
31
|
## Deterministic artifact gates (mandatory)
|
|
32
32
|
|
|
33
|
+
Keep Workflow Studio alive without exposing chain-of-thought: before each stage or long operation emit `npx ai-engineering-loop activity heartbeat --run <runId> --phase <phase> --message <short factual summary>`. Existing `node start|activity|complete` and `gate` commands publish node lifecycle automatically. Before asking the human, persist the question with `npx ai-engineering-loop interaction question --run <runId> --id <id> --message <text>` so it appears once in Studio. Never put secrets, hidden reasoning, or raw model context in activity messages.
|
|
34
|
+
|
|
33
35
|
Run `npx ai-engineering-loop state --json` to get the current runId and use `.ai-engineering-loop/runs/<runId>/` as `RUN_DIR`. Never edit state.json or current.json.
|
|
34
36
|
|
|
35
37
|
Read `core/runtime-safety.md`. Before every model or subagent call, run `budget status --run <runId>` and afterward run `budget record --input <actual> --output <actual> --model <id> --run <runId>` using provider-reported usage. Never invent usage. Missing usage stops UNATTENDED and requires human direction in ASSISTED. `budget pause` is the kill switch.
|
|
@@ -37,7 +39,7 @@ Read `core/runtime-safety.md`. Before every model or subagent call, run `budget
|
|
|
37
39
|
Inherited invariants remain mandatory: read `core/grill-policy.md`, `policies/tdd-policy.md`, and `.ai-engineering-loop/glossary.md`. On `adapter_type: dot`, grill includes blast radius: lifecycle sketch and load `task-impact-inquiry`. If the user prompt has no numbered AC, draft the contract, list a short menu and wait. Chat agreement is not freeze. AC is a failure table. One red test per AC row. Do not freeze sunny-path-only. Write claimed-vs-reality.md. Do not spawn Devil's Advocate if the file is missing or any Claimed row lacks Reality. Report Spec and Standards separately. DA prompt includes "at most 8 tool calls; read the diff file; skip css and generated files". Judge prompt includes "at most 4 tool calls; ledger and contract only; skip css; do not re-review the whole diff". `generate-workflow` still reads workflow.md and lessons.md; missing maker_intern means INVOCATION_UNAVAILABLE. Do not type a model name.
|
|
38
40
|
|
|
39
41
|
1. Stage 0: sync hosts, check status, then run `npx ai-engineering-loop run [--mode report-only|assisted|unattended]` to create or resume the ledger. Run `state --json` and `budget status`. Read glossary, lessons, and workflow overlays. Required gates cannot be skipped.
|
|
40
|
-
2. Stage 1:
|
|
42
|
+
2. Stage 1: grill ambiguous decisions and business blast radius first. Emit `npx ai-engineering-loop activity goal-drafting --run <runId> --message <summary>`. Write the Goal Contract JSON to a repository-local temporary file, then publish it with `npx ai-engineering-loop goal draft --run <runId> --file <file> --revision <currentRevision>` so Workflow Studio sees it and its ready state. Wait. Chat agreement is not freeze. After explicit human freeze, use `npx ai-engineering-loop goal freeze --run <runId> --revision <reviewedRevision> --hash <reviewedHash> --by human`; do not edit production code unless it passes. `gate goal` remains the legacy compatibility command, not the preferred revision-bound path.
|
|
41
43
|
3. After Goal freeze, branch on mode. REPORT_ONLY: never edit repository files; write `RUN_DIR/report.json`, run `gate report`, and stop. ASSISTED: use the normal Maker. UNATTENDED: run `sandbox create --run <runId>`, run Maker only in the returned worktreePath, never edit the parent checkout, then run `sandbox capture --run <runId>`. Resolve maker_intern only through the host catalog; otherwise parent is Maker. Intern cannot skip gates. Use red repro or TDD. ASSISTED writes `RUN_DIR/diff.patch`; UNATTENDED capture writes it. Then run `npx ai-engineering-loop gate maker`.
|
|
42
44
|
4. Stage 5: write `RUN_DIR/verification.json` with current git revision, gated diff hash, command, execution identity, times, exit code, stdout, timeout status, and test counts. Keep claimed-vs-reality.md. Run `npx ai-engineering-loop gate verification`; do not spawn DA unless it passes.
|
|
43
45
|
5. Write artifacts, then spawn. Before Devil's Advocate:
|
|
@@ -48,6 +48,8 @@ Compact map (not a second OS): Specify (stages 0-1), Make (stages 2-4), Review (
|
|
|
48
48
|
|
|
49
49
|
## Deterministic artifact gates (mandatory)
|
|
50
50
|
|
|
51
|
+
Keep Workflow Studio alive without exposing chain-of-thought: before each stage or long operation emit `npx ai-engineering-loop activity heartbeat --run <runId> --phase <phase> --message <short factual summary>`. Existing `node start|activity|complete` and `gate` commands publish node lifecycle automatically. Before asking the human, persist the question with `npx ai-engineering-loop interaction question --run <runId> --id <id> --message <text>` so it appears once in Studio. Never put secrets, hidden reasoning, or raw model context in activity messages.
|
|
52
|
+
|
|
51
53
|
Run `npx ai-engineering-loop state --json` to get the current `runId` and use `.ai-engineering-loop/runs/<runId>/` as `RUN_DIR`. Never edit `state.json` or `current.json`.
|
|
52
54
|
|
|
53
55
|
Read `core/runtime-safety.md`. Before every model or subagent call, run `budget status --run <runId>`; immediately afterward run `budget record --input <actual> --output <actual> --model <id> --run <runId>` from provider-reported metadata. Never invent usage. Missing usage stops UNATTENDED and requires human direction in ASSISTED. `budget pause` is the kill switch.
|
|
@@ -55,7 +57,7 @@ Read `core/runtime-safety.md`. Before every model or subagent call, run `budget
|
|
|
55
57
|
Inherited invariants remain mandatory: read `core/grill-policy.md`, `policies/tdd-policy.md`, and `.ai-engineering-loop/glossary.md`. On `adapter_type: dot`, grill includes blast radius: lifecycle sketch and load `task-impact-inquiry`. If the user prompt has no numbered AC, draft the contract, list a short menu and wait. Chat agreement is not freeze. AC is a failure table. One red test per AC row. Do not freeze sunny-path-only. Write claimed-vs-reality.md. Do not spawn Devil's Advocate if the file is missing or any Claimed row lacks Reality. Report Spec and Standards separately. DA prompt includes "at most 8 tool calls; read the diff file; skip css and generated files". Judge prompt includes "at most 4 tool calls; ledger and contract only; skip css; do not re-review the whole diff". `generate-workflow` still reads workflow.md and lessons.md; missing maker_intern means INVOCATION_UNAVAILABLE. Do not type a model name.
|
|
56
58
|
|
|
57
59
|
1. Stage 0: `npx ai-engineering-loop sync-hosts`, `status`, then `run [--mode report-only|assisted|unattended]` to create or resume the ledger. Run `state --json` and `budget status`. Read glossary, lessons, and workflow overlays. Required gates cannot be skipped.
|
|
58
|
-
2. Stage 1:
|
|
60
|
+
2. Stage 1: grill ambiguous decisions and business blast radius first. Emit `npx ai-engineering-loop activity goal-drafting --run <runId> --message <summary>`. Write the Goal Contract JSON to a repository-local temporary file, then publish it with `npx ai-engineering-loop goal draft --run <runId> --file <file> --revision <currentRevision>` so Workflow Studio sees it and its ready state. Wait. Chat agreement is not freeze. After explicit human freeze, use `npx ai-engineering-loop goal freeze --run <runId> --revision <reviewedRevision> --hash <reviewedHash> --by human`; do not edit production code unless it passes. `gate goal` remains the legacy compatibility command, not the preferred revision-bound path.
|
|
59
61
|
3. After Goal freeze, branch on mode. REPORT_ONLY: never edit repository files; write `RUN_DIR/report.json`, run `gate report`, and stop. ASSISTED: use the normal Maker. UNATTENDED: run `sandbox create --run <runId>`, run Maker only in the returned worktreePath, never edit the parent checkout, then run `sandbox capture --run <runId>`. Resolve `maker_intern` only through `grok models`; unknown means parent Maker. Intern cannot skip gates or spawn DA/Judge. Use red repro or TDD. ASSISTED writes `RUN_DIR/diff.patch`; UNATTENDED capture writes it. Then run `npx ai-engineering-loop gate maker`.
|
|
60
62
|
4. Stage 5: run verification and write `RUN_DIR/verification.json` with current git revision, gated diff hash, command, execution identity, times, exit code, stdout, timeout status, and test counts. Keep claimed-vs-reality.md. Run `npx ai-engineering-loop gate verification`; do not spawn DA unless it passes.
|
|
61
63
|
5. Write artifacts to disk so children do not need parent chat:
|
|
@@ -82,6 +82,16 @@ const {
|
|
|
82
82
|
appendRunQuestion,
|
|
83
83
|
listRunInteractions
|
|
84
84
|
} = require('../lib/run-interactions.js');
|
|
85
|
+
const {
|
|
86
|
+
appendRunLifecycle,
|
|
87
|
+
listRunLifecycle,
|
|
88
|
+
runAgentPresence
|
|
89
|
+
} = require('../lib/run-lifecycle.js');
|
|
90
|
+
const {
|
|
91
|
+
freezeGoal,
|
|
92
|
+
loadGoalDraft,
|
|
93
|
+
saveGoalDraft
|
|
94
|
+
} = require('../lib/goal-runtime.js');
|
|
85
95
|
const {
|
|
86
96
|
abortSandbox,
|
|
87
97
|
captureSandbox,
|
|
@@ -1139,9 +1149,36 @@ function handleGate() {
|
|
|
1139
1149
|
try {
|
|
1140
1150
|
const target = runId ? loadRun(CWD, runId) : getCurrentRun(CWD);
|
|
1141
1151
|
if (!target) throw new Error('No current run. Start one with `ai-engineering-loop run`.');
|
|
1152
|
+
listRunLifecycle(CWD, target.runId);
|
|
1153
|
+
let lifecycleNode = null;
|
|
1154
|
+
if (target.workflow) {
|
|
1155
|
+
const workflow = workflowStatus(CWD, { runId: target.runId });
|
|
1156
|
+
lifecycleNode = workflow.plan.nodes.find((node) => node.legacyGate === gate) || null;
|
|
1157
|
+
if (lifecycleNode && workflow.state.nodes[lifecycleNode.id].status === 'READY') {
|
|
1158
|
+
startWorkflowNode(CWD, lifecycleNode.id, { runId: target.runId });
|
|
1159
|
+
appendRunLifecycle(CWD, target.runId, {
|
|
1160
|
+
type: 'NODE_STARTED',
|
|
1161
|
+
nodeId: lifecycleNode.id,
|
|
1162
|
+
phase: gate,
|
|
1163
|
+
actor: 'agent',
|
|
1164
|
+
message: `${lifecycleNode.displayName || lifecycleNode.id} started`
|
|
1165
|
+
});
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1142
1168
|
const run = target.workflow
|
|
1143
1169
|
? applyWorkflowGate(CWD, gate, { runId: target.runId }).run
|
|
1144
1170
|
: applyGate(CWD, gate, { runId: target.runId });
|
|
1171
|
+
const runCompleted = run.state === 'DELIVERED' || run.state === 'REPORTED';
|
|
1172
|
+
appendRunLifecycle(CWD, target.runId, {
|
|
1173
|
+
type: runCompleted
|
|
1174
|
+
? 'RUN_COMPLETED'
|
|
1175
|
+
: (lifecycleNode ? 'NODE_COMPLETED' : 'PHASE_COMPLETED'),
|
|
1176
|
+
...(!runCompleted && lifecycleNode ? { nodeId: lifecycleNode.id } : {}),
|
|
1177
|
+
phase: gate,
|
|
1178
|
+
actor: 'agent',
|
|
1179
|
+
status: 'PASSED',
|
|
1180
|
+
message: `${lifecycleNode?.displayName || gate} completed`
|
|
1181
|
+
});
|
|
1145
1182
|
if (json) {
|
|
1146
1183
|
console.log(JSON.stringify({
|
|
1147
1184
|
ok: true,
|
|
@@ -1201,6 +1238,8 @@ function handleNode() {
|
|
|
1201
1238
|
return;
|
|
1202
1239
|
}
|
|
1203
1240
|
if (!nodeId || nodeId.startsWith('-')) throw new Error(`node ${action} requires a node id`);
|
|
1241
|
+
const beforeAction = workflowStatus(CWD, { runId });
|
|
1242
|
+
listRunLifecycle(CWD, beforeAction.run.runId);
|
|
1204
1243
|
let workflow;
|
|
1205
1244
|
if (action === 'start') {
|
|
1206
1245
|
workflow = startWorkflowNode(CWD, nodeId, { runId });
|
|
@@ -1230,6 +1269,32 @@ function handleNode() {
|
|
|
1230
1269
|
throw new Error(`Unknown node action: ${action}`);
|
|
1231
1270
|
}
|
|
1232
1271
|
const node = workflow.state.nodes[nodeId];
|
|
1272
|
+
const lifecycleType = {
|
|
1273
|
+
start: 'NODE_STARTED',
|
|
1274
|
+
activity: 'NODE_ACTIVITY',
|
|
1275
|
+
complete: 'NODE_COMPLETED',
|
|
1276
|
+
approve: 'NODE_COMPLETED',
|
|
1277
|
+
fail: 'NODE_ACTIVITY',
|
|
1278
|
+
retry: 'NODE_ACTIVITY'
|
|
1279
|
+
}[action];
|
|
1280
|
+
if (lifecycleType) {
|
|
1281
|
+
const lifecycleMessage = {
|
|
1282
|
+
start: `Node ${nodeId} started`,
|
|
1283
|
+
complete: `Node ${nodeId} completed`,
|
|
1284
|
+
approve: `Node ${nodeId} approved`,
|
|
1285
|
+
fail: `Node ${nodeId} failed`,
|
|
1286
|
+
retry: `Node ${nodeId} queued for retry`
|
|
1287
|
+
}[action];
|
|
1288
|
+
appendRunLifecycle(CWD, workflow.run.runId, {
|
|
1289
|
+
type: lifecycleType,
|
|
1290
|
+
nodeId,
|
|
1291
|
+
phase: nodeId,
|
|
1292
|
+
actor: action === 'approve' ? argValue('--by') || 'human' : 'agent',
|
|
1293
|
+
message: action === 'activity'
|
|
1294
|
+
? argValue('--message')
|
|
1295
|
+
: lifecycleMessage
|
|
1296
|
+
});
|
|
1297
|
+
}
|
|
1233
1298
|
if (json) console.log(JSON.stringify({ ok: true, nodeId, ...node }));
|
|
1234
1299
|
else log.success(`✓ Node ${nodeId}: ${node.status}`);
|
|
1235
1300
|
} catch (err) {
|
|
@@ -1568,6 +1633,180 @@ function openStudio(url) {
|
|
|
1568
1633
|
child.unref();
|
|
1569
1634
|
}
|
|
1570
1635
|
|
|
1636
|
+
function requiredRunId(command) {
|
|
1637
|
+
const runId = argValue('--run') || getCurrentRun(CWD)?.runId;
|
|
1638
|
+
if (!runId) {
|
|
1639
|
+
const error = new Error(`${command} requires --run <id> or a current Run`);
|
|
1640
|
+
error.code = 'INVALID_USAGE';
|
|
1641
|
+
throw error;
|
|
1642
|
+
}
|
|
1643
|
+
return runId;
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
function integerArg(name, fallback) {
|
|
1647
|
+
const raw = argValue(name);
|
|
1648
|
+
if (raw == null) return fallback;
|
|
1649
|
+
const value = Number(raw);
|
|
1650
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
1651
|
+
const error = new Error(`${name} must be a non-negative integer`);
|
|
1652
|
+
error.code = 'INVALID_USAGE';
|
|
1653
|
+
throw error;
|
|
1654
|
+
}
|
|
1655
|
+
return value;
|
|
1656
|
+
}
|
|
1657
|
+
|
|
1658
|
+
function requiredIntegerArg(name) {
|
|
1659
|
+
const value = integerArg(name, undefined);
|
|
1660
|
+
if (value == null) {
|
|
1661
|
+
const error = new Error(`${name} is required`);
|
|
1662
|
+
error.code = 'INVALID_USAGE';
|
|
1663
|
+
throw error;
|
|
1664
|
+
}
|
|
1665
|
+
return value;
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1668
|
+
function readBoundedJsonInput(fileName) {
|
|
1669
|
+
if (!fileName) {
|
|
1670
|
+
const error = new Error('goal draft requires --file <json>');
|
|
1671
|
+
error.code = 'INVALID_USAGE';
|
|
1672
|
+
throw error;
|
|
1673
|
+
}
|
|
1674
|
+
const file = path.resolve(CWD, fileName);
|
|
1675
|
+
const relative = path.relative(CWD, file);
|
|
1676
|
+
if (relative.startsWith('..') || path.isAbsolute(relative)) {
|
|
1677
|
+
const error = new Error('Goal draft input must stay inside the repository');
|
|
1678
|
+
error.code = 'UNSAFE_GOAL_PATH';
|
|
1679
|
+
throw error;
|
|
1680
|
+
}
|
|
1681
|
+
const stat = fs.lstatSync(file);
|
|
1682
|
+
if (stat.isSymbolicLink() || !stat.isFile() || stat.nlink !== 1 || stat.size > 256 * 1024) {
|
|
1683
|
+
const error = new Error('Goal draft input must be a bounded regular file');
|
|
1684
|
+
error.code = 'INVALID_GOAL_DRAFT';
|
|
1685
|
+
throw error;
|
|
1686
|
+
}
|
|
1687
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1690
|
+
function handleGoal() {
|
|
1691
|
+
const action = args[1] || 'show';
|
|
1692
|
+
try {
|
|
1693
|
+
const runId = requiredRunId('goal');
|
|
1694
|
+
let result;
|
|
1695
|
+
if (action === 'show') {
|
|
1696
|
+
result = loadGoalDraft(CWD, runId);
|
|
1697
|
+
} else if (action === 'draft') {
|
|
1698
|
+
appendRunLifecycle(CWD, runId, {
|
|
1699
|
+
type: 'GOAL_DRAFTING',
|
|
1700
|
+
phase: 'goal',
|
|
1701
|
+
actor: argValue('--by') || 'agent',
|
|
1702
|
+
message: argValue('--message') || 'Updating the Goal draft'
|
|
1703
|
+
});
|
|
1704
|
+
result = saveGoalDraft(CWD, runId, readBoundedJsonInput(argValue('--file')), {
|
|
1705
|
+
actor: argValue('--by') || 'agent',
|
|
1706
|
+
expectedRevision: requiredIntegerArg('--revision')
|
|
1707
|
+
});
|
|
1708
|
+
appendRunLifecycle(CWD, runId, {
|
|
1709
|
+
type: 'GOAL_DRAFT_UPDATED',
|
|
1710
|
+
phase: 'goal',
|
|
1711
|
+
actor: argValue('--by') || 'agent',
|
|
1712
|
+
message: `Goal draft revision ${result.metadata.revision} was saved`
|
|
1713
|
+
});
|
|
1714
|
+
appendRunLifecycle(CWD, runId, {
|
|
1715
|
+
type: 'GOAL_READY',
|
|
1716
|
+
phase: 'goal',
|
|
1717
|
+
actor: argValue('--by') || 'agent',
|
|
1718
|
+
message: `Goal draft revision ${result.metadata.revision} is ready for review`
|
|
1719
|
+
});
|
|
1720
|
+
} else if (action === 'freeze') {
|
|
1721
|
+
const expectedHash = argValue('--hash');
|
|
1722
|
+
if (!expectedHash) {
|
|
1723
|
+
const error = new Error('--hash is required');
|
|
1724
|
+
error.code = 'INVALID_USAGE';
|
|
1725
|
+
throw error;
|
|
1726
|
+
}
|
|
1727
|
+
const target = loadRun(CWD, runId);
|
|
1728
|
+
let goalNode = null;
|
|
1729
|
+
if (target.workflow) {
|
|
1730
|
+
const workflow = workflowStatus(CWD, { runId });
|
|
1731
|
+
goalNode = workflow.plan.nodes.find((node) => node.legacyGate === 'goal') || null;
|
|
1732
|
+
if (goalNode && workflow.state.nodes[goalNode.id].status === 'READY') {
|
|
1733
|
+
startWorkflowNode(CWD, goalNode.id, { runId });
|
|
1734
|
+
appendRunLifecycle(CWD, runId, {
|
|
1735
|
+
type: 'NODE_STARTED',
|
|
1736
|
+
nodeId: goalNode.id,
|
|
1737
|
+
phase: 'goal',
|
|
1738
|
+
actor: 'agent',
|
|
1739
|
+
message: `${goalNode.displayName || goalNode.id} freeze started`
|
|
1740
|
+
});
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
result = freezeGoal(CWD, runId, {
|
|
1744
|
+
actor: argValue('--by') || 'human',
|
|
1745
|
+
expectedRevision: requiredIntegerArg('--revision'),
|
|
1746
|
+
expectedHash
|
|
1747
|
+
});
|
|
1748
|
+
appendRunLifecycle(CWD, runId, {
|
|
1749
|
+
type: goalNode ? 'NODE_COMPLETED' : 'GOAL_FROZEN',
|
|
1750
|
+
...(goalNode ? { nodeId: goalNode.id } : {}),
|
|
1751
|
+
phase: 'goal',
|
|
1752
|
+
actor: argValue('--by') || 'human',
|
|
1753
|
+
message: 'Goal Contract frozen'
|
|
1754
|
+
});
|
|
1755
|
+
} else {
|
|
1756
|
+
const error = new Error('goal must be show, draft, or freeze');
|
|
1757
|
+
error.code = 'INVALID_USAGE';
|
|
1758
|
+
throw error;
|
|
1759
|
+
}
|
|
1760
|
+
console.log(JSON.stringify({ ok: true, runId, [action === 'show' ? 'draft' : 'result']: result }, null, 2));
|
|
1761
|
+
} catch (error) {
|
|
1762
|
+
log.error(`${error.code || 'GOAL_FAILED'}: ${error.message}`);
|
|
1763
|
+
process.exitCode = 1;
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
|
|
1767
|
+
function handleActivity() {
|
|
1768
|
+
const aliases = {
|
|
1769
|
+
'goal-drafting': 'GOAL_DRAFTING',
|
|
1770
|
+
'goal-ready': 'GOAL_READY',
|
|
1771
|
+
heartbeat: 'AGENT_HEARTBEAT',
|
|
1772
|
+
waiting: 'AGENT_WAITING',
|
|
1773
|
+
'node-started': 'NODE_STARTED',
|
|
1774
|
+
'node-activity': 'NODE_ACTIVITY',
|
|
1775
|
+
'node-completed': 'NODE_COMPLETED',
|
|
1776
|
+
'node-failed': 'NODE_FAILED',
|
|
1777
|
+
'loop-iterated': 'LOOP_ITERATED',
|
|
1778
|
+
'run-completed': 'RUN_COMPLETED'
|
|
1779
|
+
};
|
|
1780
|
+
try {
|
|
1781
|
+
const action = args[1] || 'heartbeat';
|
|
1782
|
+
const type = aliases[action];
|
|
1783
|
+
if (!type) throw Object.assign(new Error(`Unknown activity type: ${action}`), { code: 'INVALID_USAGE' });
|
|
1784
|
+
const runId = requiredRunId('activity');
|
|
1785
|
+
const nodeId = argValue('--node');
|
|
1786
|
+
if (type.startsWith('NODE_') && !nodeId) {
|
|
1787
|
+
throw Object.assign(new Error(`${action} requires --node <id>`), { code: 'INVALID_USAGE' });
|
|
1788
|
+
}
|
|
1789
|
+
const event = appendRunLifecycle(CWD, runId, {
|
|
1790
|
+
type,
|
|
1791
|
+
phase: argValue('--phase'),
|
|
1792
|
+
nodeId,
|
|
1793
|
+
actor: argValue('--by') || 'agent',
|
|
1794
|
+
message: argValue('--message') || 'Agent is working',
|
|
1795
|
+
status: argValue('--status'),
|
|
1796
|
+
...(argValue('--evidence-path') ? {
|
|
1797
|
+
evidence: {
|
|
1798
|
+
path: argValue('--evidence-path'),
|
|
1799
|
+
sha256: argValue('--evidence-hash')
|
|
1800
|
+
}
|
|
1801
|
+
} : {})
|
|
1802
|
+
});
|
|
1803
|
+
console.log(JSON.stringify({ ok: true, event, presence: runAgentPresence(CWD, runId) }, null, 2));
|
|
1804
|
+
} catch (error) {
|
|
1805
|
+
log.error(`${error.code || 'ACTIVITY_FAILED'}: ${error.message}`);
|
|
1806
|
+
process.exitCode = 1;
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
|
|
1571
1810
|
function handleStudio() {
|
|
1572
1811
|
const requestedPort = argValue('--port');
|
|
1573
1812
|
const port = requestedPort == null ? 4317 : Number(requestedPort);
|
|
@@ -1606,7 +1845,14 @@ function handleInteraction() {
|
|
|
1606
1845
|
if (action === 'list') {
|
|
1607
1846
|
result = listRunInteractions(CWD, runId);
|
|
1608
1847
|
} else if (action === 'question') {
|
|
1848
|
+
listRunLifecycle(CWD, runId);
|
|
1609
1849
|
result = appendRunQuestion(CWD, runId, { message, actor: actor || 'agent' });
|
|
1850
|
+
appendRunLifecycle(CWD, runId, {
|
|
1851
|
+
type: 'AGENT_WAITING',
|
|
1852
|
+
phase: 'goal',
|
|
1853
|
+
actor: actor || 'agent',
|
|
1854
|
+
message: `Waiting for answer to Q${result.number}`
|
|
1855
|
+
});
|
|
1610
1856
|
} else if (action === 'answer') {
|
|
1611
1857
|
result = appendRunAnswer(CWD, runId, args[2], { message, actor: actor || 'human' });
|
|
1612
1858
|
} else {
|
|
@@ -1655,6 +1901,14 @@ Commands:
|
|
|
1655
1901
|
goal | report | maker | verification | review | judge | delivery
|
|
1656
1902
|
--run <id> target a non-current run
|
|
1657
1903
|
--json print machine-readable gate output
|
|
1904
|
+
goal Share one revision-bound Goal draft between the Agent and Studio
|
|
1905
|
+
show [--run <id>]
|
|
1906
|
+
draft --file <json> --revision <n> [--run <id>] [--by <agent>]
|
|
1907
|
+
freeze --revision <n> --hash <sha256> [--run <id>] [--by <name>]
|
|
1908
|
+
activity Publish safe Run lifecycle summaries for Studio
|
|
1909
|
+
goal-drafting | goal-ready | heartbeat | waiting
|
|
1910
|
+
node-started | node-activity | node-completed | loop-iterated | run-completed
|
|
1911
|
+
[--run <id>] [--node <id>] [--phase <id>] --message <text>
|
|
1658
1912
|
node Operate custom nodes in a recipe-bound run
|
|
1659
1913
|
status [--run <id>] [--json]
|
|
1660
1914
|
start <id> [--run <id>] [--json]
|
|
@@ -1748,6 +2002,12 @@ switch (command) {
|
|
|
1748
2002
|
case 'gate':
|
|
1749
2003
|
handleGate();
|
|
1750
2004
|
break;
|
|
2005
|
+
case 'goal':
|
|
2006
|
+
handleGoal();
|
|
2007
|
+
break;
|
|
2008
|
+
case 'activity':
|
|
2009
|
+
handleActivity();
|
|
2010
|
+
break;
|
|
1751
2011
|
case 'node':
|
|
1752
2012
|
handleNode();
|
|
1753
2013
|
break;
|
package/lib/goal-runtime.js
CHANGED
|
@@ -3,8 +3,10 @@
|
|
|
3
3
|
const fs = require('fs');
|
|
4
4
|
const path = require('path');
|
|
5
5
|
const { validateGoalContract, hashFile } = require('./gates.js');
|
|
6
|
+
const { sha256 } = require('./recipe.js');
|
|
6
7
|
const {
|
|
7
8
|
RUN_STATES,
|
|
9
|
+
atomicWritePrivateFile,
|
|
8
10
|
atomicWriteJson,
|
|
9
11
|
loadRun,
|
|
10
12
|
runsDir,
|
|
@@ -35,26 +37,147 @@ function goalPaths(rootDir, runId, version) {
|
|
|
35
37
|
};
|
|
36
38
|
}
|
|
37
39
|
|
|
38
|
-
function
|
|
40
|
+
function readDraftFile(filePath) {
|
|
41
|
+
if (!fs.existsSync(filePath)) return null;
|
|
42
|
+
const stat = fs.lstatSync(filePath);
|
|
43
|
+
if (stat.isSymbolicLink() || !stat.isFile() || stat.nlink !== 1 || stat.size > 256 * 1024) {
|
|
44
|
+
throw goalError('Goal draft must be a bounded regular file', 'INVALID_GOAL_DRAFT');
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
48
|
+
} catch (cause) {
|
|
49
|
+
throw goalError(`Goal draft is invalid: ${cause.message}`, 'INVALID_GOAL_DRAFT');
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function normalizeDraft(value, runId) {
|
|
54
|
+
if (value?.contract && value?.metadata) {
|
|
55
|
+
const { contract, metadata } = value;
|
|
56
|
+
const revision = Number(metadata.revision);
|
|
57
|
+
const contentHash = sha256(contract);
|
|
58
|
+
if (
|
|
59
|
+
contract.runId !== runId ||
|
|
60
|
+
!Number.isSafeInteger(revision) ||
|
|
61
|
+
revision < 1 ||
|
|
62
|
+
!/^[A-Za-z0-9@._-]{1,64}$/.test(String(metadata.actor || '')) ||
|
|
63
|
+
!metadata.updatedAt ||
|
|
64
|
+
!Number.isFinite(Date.parse(metadata.updatedAt)) ||
|
|
65
|
+
metadata.contentHash !== contentHash
|
|
66
|
+
) {
|
|
67
|
+
throw goalError('Goal draft envelope failed integrity validation', 'INVALID_GOAL_DRAFT');
|
|
68
|
+
}
|
|
69
|
+
return value;
|
|
70
|
+
}
|
|
71
|
+
if (value?.objective) {
|
|
72
|
+
const contract = { ...value, schemaVersion: 1, runId };
|
|
73
|
+
return {
|
|
74
|
+
contract,
|
|
75
|
+
metadata: {
|
|
76
|
+
revision: 0,
|
|
77
|
+
actor: 'legacy',
|
|
78
|
+
updatedAt: null,
|
|
79
|
+
contentHash: sha256(contract)
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
throw goalError('Goal draft envelope is invalid', 'INVALID_GOAL_DRAFT');
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function loadGoalDraft(rootDir, runId) {
|
|
87
|
+
const run = loadRun(rootDir, runId);
|
|
88
|
+
const value = readDraftFile(goalPaths(rootDir, runId, run.goal?.version || 1).draft);
|
|
89
|
+
return value ? normalizeDraft(value, runId) : null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function markdownCell(value) {
|
|
93
|
+
return String(value || '').replace(/\r?\n/g, ' ').replace(/\|/g, '\\|');
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function writeGoalMirror(rootDir, envelope) {
|
|
97
|
+
const { contract, metadata } = envelope;
|
|
98
|
+
const rows = (contract.acceptanceCriteria || []).map((criterion) => (
|
|
99
|
+
`| ${markdownCell(criterion.id)} | ${markdownCell(criterion.statement)} | ` +
|
|
100
|
+
`${markdownCell(criterion.evidenceRequired)} | ${markdownCell((criterion.failureCases || []).join('; '))} |`
|
|
101
|
+
));
|
|
102
|
+
const markdown = [
|
|
103
|
+
'# Goal Contract Draft',
|
|
104
|
+
'',
|
|
105
|
+
`**Run:** \`${contract.runId}\` `,
|
|
106
|
+
`**Revision:** ${metadata.revision} `,
|
|
107
|
+
`**Status:** DRAFT — not frozen `,
|
|
108
|
+
`**Content hash:** \`${metadata.contentHash}\``,
|
|
109
|
+
'',
|
|
110
|
+
'## Objective',
|
|
111
|
+
'',
|
|
112
|
+
contract.objective,
|
|
113
|
+
'',
|
|
114
|
+
'## Acceptance criteria and failure table',
|
|
115
|
+
'',
|
|
116
|
+
'| AC | Required behavior | Evidence seam | Failure cases |',
|
|
117
|
+
'|---|---|---|---|',
|
|
118
|
+
...rows,
|
|
119
|
+
''
|
|
120
|
+
].join('\n');
|
|
121
|
+
atomicWritePrivateFile(
|
|
122
|
+
path.join(rootDir, '.ai-engineering-loop', 'tasks', 'goal-contract.md'),
|
|
123
|
+
markdown
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function saveGoalDraft(
|
|
128
|
+
rootDir,
|
|
129
|
+
runId,
|
|
130
|
+
contract,
|
|
131
|
+
{ actor = 'studio-user', expectedRevision, now = new Date() } = {}
|
|
132
|
+
) {
|
|
39
133
|
const run = loadRun(rootDir, runId);
|
|
40
134
|
if (run.goal?.frozen) throw goalError('Frozen Goal must be unfrozen before editing', 'GOAL_IS_FROZEN');
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
135
|
+
if (contract?.runId && contract.runId !== runId) {
|
|
136
|
+
throw goalError('Goal draft belongs to another Run', 'GOAL_RUN_MISMATCH');
|
|
137
|
+
}
|
|
138
|
+
const human = actorId(actor);
|
|
139
|
+
const current = loadGoalDraft(rootDir, runId);
|
|
140
|
+
const currentRevision = current?.metadata.revision || 0;
|
|
141
|
+
if (expectedRevision != null && Number(expectedRevision) !== currentRevision) {
|
|
142
|
+
throw goalError(
|
|
143
|
+
`Goal draft changed from revision ${expectedRevision} to ${currentRevision}`,
|
|
144
|
+
'GOAL_DRAFT_CONFLICT'
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
const normalized = { ...contract, schemaVersion: 1, runId };
|
|
148
|
+
const validation = validateGoalContract(normalized);
|
|
149
|
+
if (!validation.valid) throw goalError('Goal Contract draft is invalid', 'GATE_FAILED', validation.errors);
|
|
150
|
+
const envelope = {
|
|
151
|
+
contract: normalized,
|
|
152
|
+
metadata: {
|
|
153
|
+
revision: currentRevision + 1,
|
|
154
|
+
actor: human,
|
|
155
|
+
updatedAt: now.toISOString(),
|
|
156
|
+
contentHash: sha256(normalized)
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
atomicWriteJson(goalPaths(rootDir, runId, run.goal?.version || 1).draft, envelope);
|
|
160
|
+
writeGoalMirror(rootDir, envelope);
|
|
161
|
+
return envelope;
|
|
44
162
|
}
|
|
45
163
|
|
|
46
|
-
function freezeGoal(
|
|
164
|
+
function freezeGoal(
|
|
165
|
+
rootDir,
|
|
166
|
+
runId,
|
|
167
|
+
{ actor, expectedRevision, expectedHash, now = new Date() } = {}
|
|
168
|
+
) {
|
|
47
169
|
const run = loadRun(rootDir, runId);
|
|
48
170
|
if (run.state !== RUN_STATES.STARTED || run.goal?.frozen) {
|
|
49
171
|
throw goalError(`Run ${runId} cannot freeze a Goal from ${run.state}`, 'INVALID_GOAL_TRANSITION');
|
|
50
172
|
}
|
|
51
173
|
const version = run.goal?.version || 1;
|
|
52
174
|
const paths = goalPaths(rootDir, runId, version);
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
175
|
+
const draft = loadGoalDraft(rootDir, runId);
|
|
176
|
+
if (!draft) throw goalError('Goal draft is unavailable', 'GOAL_DRAFT_MISSING');
|
|
177
|
+
const { contract, metadata } = draft;
|
|
178
|
+
if ((expectedRevision != null && Number(expectedRevision) !== metadata.revision) ||
|
|
179
|
+
(expectedHash != null && String(expectedHash) !== metadata.contentHash)) {
|
|
180
|
+
throw goalError('Goal draft changed after review', 'GOAL_DRAFT_CONFLICT');
|
|
58
181
|
}
|
|
59
182
|
const validation = validateGoalContract(contract);
|
|
60
183
|
if (!validation.valid) throw goalError('Goal Contract gate failed', 'GATE_FAILED', validation.errors);
|
|
@@ -64,19 +187,30 @@ function freezeGoal(rootDir, runId, { actor, now = new Date() } = {}) {
|
|
|
64
187
|
}
|
|
65
188
|
atomicWriteJson(paths.version, contract);
|
|
66
189
|
atomicWriteJson(paths.canonical, contract);
|
|
67
|
-
const
|
|
190
|
+
const artifactHash = hashFile(paths.version);
|
|
191
|
+
const contentHash = sha256(contract);
|
|
192
|
+
if (contentHash !== metadata.contentHash) {
|
|
193
|
+
throw goalError('Goal draft hash does not match its reviewed content', 'GOAL_DRAFT_HASH_MISMATCH');
|
|
194
|
+
}
|
|
68
195
|
const transitionOptions = {
|
|
69
196
|
artifacts: {
|
|
70
197
|
goalContract: {
|
|
71
198
|
path: path.relative(rootDir, paths.version).split(path.sep).join('/'),
|
|
72
|
-
sha256:
|
|
199
|
+
sha256: artifactHash,
|
|
73
200
|
goalVersion: version
|
|
74
201
|
}
|
|
75
202
|
},
|
|
76
203
|
statePatch: {
|
|
77
|
-
goal: {
|
|
204
|
+
goal: {
|
|
205
|
+
version,
|
|
206
|
+
frozen: true,
|
|
207
|
+
hash: contentHash,
|
|
208
|
+
draftRevision: metadata.revision,
|
|
209
|
+
actor: human,
|
|
210
|
+
frozenAt: now.toISOString()
|
|
211
|
+
}
|
|
78
212
|
},
|
|
79
|
-
historyMetadata: { actor: human, goalVersion: version, goalHash:
|
|
213
|
+
historyMetadata: { actor: human, goalVersion: version, goalHash: contentHash },
|
|
80
214
|
now
|
|
81
215
|
};
|
|
82
216
|
if (run.workflow) {
|
|
@@ -127,4 +261,4 @@ function unfreezeGoal(rootDir, runId, { actor, reason, now = new Date() } = {})
|
|
|
127
261
|
});
|
|
128
262
|
}
|
|
129
263
|
|
|
130
|
-
module.exports = { saveGoalDraft, freezeGoal, unfreezeGoal };
|
|
264
|
+
module.exports = { saveGoalDraft, loadGoalDraft, freezeGoal, unfreezeGoal };
|