ai-engineering-loop 1.9.3 → 1.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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. Stage 1 keeps Goal Contract Markdown, writes goal-contract.json with failure cases, then runs `gate goal`.
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`), then freeze the Goal Contract file. Chat agreement is not freeze. If the user prompt has no numbered AC, draft `.ai-engineering-loop/tasks/goal-contract.md` with a failure table, show it, wait for freeze. Do not start Maker. 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`.
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. Keep the human Markdown contract and write `RUN_DIR/goal-contract.json` with `schemaVersion`, `runId`, objective, numbered AC, evidenceRequired, and non-empty failureCases. Run `npx ai-engineering-loop gate goal`; do not edit production code unless it passes.
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: keep the human Goal Contract Markdown and write `RUN_DIR/goal-contract.json` with schemaVersion, runId, objective, numbered AC, evidenceRequired, and non-empty failureCases. Grill ambiguous decisions and business blast radius first. Run `npx ai-engineering-loop gate goal`; do not edit production code unless it passes.
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: keep the human Goal Contract Markdown and write `RUN_DIR/goal-contract.json` with schemaVersion, runId, objective, numbered AC, evidenceRequired, and non-empty failureCases. Grill ambiguous decisions and business blast radius first. Run `npx ai-engineering-loop gate goal`; do not edit production code unless it passes.
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,32 @@ 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
+ appendRunLifecycle(CWD, target.runId, {
1172
+ type: run.state === 'DELIVERED' || run.state === 'REPORTED' ? 'RUN_COMPLETED' : 'NODE_COMPLETED',
1173
+ ...(lifecycleNode ? { nodeId: lifecycleNode.id } : {}),
1174
+ phase: gate,
1175
+ actor: 'agent',
1176
+ message: `${lifecycleNode?.displayName || gate} completed`
1177
+ });
1145
1178
  if (json) {
1146
1179
  console.log(JSON.stringify({
1147
1180
  ok: true,
@@ -1201,6 +1234,8 @@ function handleNode() {
1201
1234
  return;
1202
1235
  }
1203
1236
  if (!nodeId || nodeId.startsWith('-')) throw new Error(`node ${action} requires a node id`);
1237
+ const beforeAction = workflowStatus(CWD, { runId });
1238
+ listRunLifecycle(CWD, beforeAction.run.runId);
1204
1239
  let workflow;
1205
1240
  if (action === 'start') {
1206
1241
  workflow = startWorkflowNode(CWD, nodeId, { runId });
@@ -1230,6 +1265,32 @@ function handleNode() {
1230
1265
  throw new Error(`Unknown node action: ${action}`);
1231
1266
  }
1232
1267
  const node = workflow.state.nodes[nodeId];
1268
+ const lifecycleType = {
1269
+ start: 'NODE_STARTED',
1270
+ activity: 'NODE_ACTIVITY',
1271
+ complete: 'NODE_COMPLETED',
1272
+ approve: 'NODE_COMPLETED',
1273
+ fail: 'NODE_ACTIVITY',
1274
+ retry: 'NODE_ACTIVITY'
1275
+ }[action];
1276
+ if (lifecycleType) {
1277
+ const lifecycleMessage = {
1278
+ start: `Node ${nodeId} started`,
1279
+ complete: `Node ${nodeId} completed`,
1280
+ approve: `Node ${nodeId} approved`,
1281
+ fail: `Node ${nodeId} failed`,
1282
+ retry: `Node ${nodeId} queued for retry`
1283
+ }[action];
1284
+ appendRunLifecycle(CWD, workflow.run.runId, {
1285
+ type: lifecycleType,
1286
+ nodeId,
1287
+ phase: nodeId,
1288
+ actor: action === 'approve' ? argValue('--by') || 'human' : 'agent',
1289
+ message: action === 'activity'
1290
+ ? argValue('--message')
1291
+ : lifecycleMessage
1292
+ });
1293
+ }
1233
1294
  if (json) console.log(JSON.stringify({ ok: true, nodeId, ...node }));
1234
1295
  else log.success(`✓ Node ${nodeId}: ${node.status}`);
1235
1296
  } catch (err) {
@@ -1568,6 +1629,172 @@ function openStudio(url) {
1568
1629
  child.unref();
1569
1630
  }
1570
1631
 
1632
+ function requiredRunId(command) {
1633
+ const runId = argValue('--run') || getCurrentRun(CWD)?.runId;
1634
+ if (!runId) {
1635
+ const error = new Error(`${command} requires --run <id> or a current Run`);
1636
+ error.code = 'INVALID_USAGE';
1637
+ throw error;
1638
+ }
1639
+ return runId;
1640
+ }
1641
+
1642
+ function integerArg(name, fallback) {
1643
+ const raw = argValue(name);
1644
+ if (raw == null) return fallback;
1645
+ const value = Number(raw);
1646
+ if (!Number.isSafeInteger(value) || value < 0) {
1647
+ const error = new Error(`${name} must be a non-negative integer`);
1648
+ error.code = 'INVALID_USAGE';
1649
+ throw error;
1650
+ }
1651
+ return value;
1652
+ }
1653
+
1654
+ function requiredIntegerArg(name) {
1655
+ const value = integerArg(name, undefined);
1656
+ if (value == null) {
1657
+ const error = new Error(`${name} is required`);
1658
+ error.code = 'INVALID_USAGE';
1659
+ throw error;
1660
+ }
1661
+ return value;
1662
+ }
1663
+
1664
+ function readBoundedJsonInput(fileName) {
1665
+ if (!fileName) {
1666
+ const error = new Error('goal draft requires --file <json>');
1667
+ error.code = 'INVALID_USAGE';
1668
+ throw error;
1669
+ }
1670
+ const file = path.resolve(CWD, fileName);
1671
+ const relative = path.relative(CWD, file);
1672
+ if (relative.startsWith('..') || path.isAbsolute(relative)) {
1673
+ const error = new Error('Goal draft input must stay inside the repository');
1674
+ error.code = 'UNSAFE_GOAL_PATH';
1675
+ throw error;
1676
+ }
1677
+ const stat = fs.lstatSync(file);
1678
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.nlink !== 1 || stat.size > 256 * 1024) {
1679
+ const error = new Error('Goal draft input must be a bounded regular file');
1680
+ error.code = 'INVALID_GOAL_DRAFT';
1681
+ throw error;
1682
+ }
1683
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
1684
+ }
1685
+
1686
+ function handleGoal() {
1687
+ const action = args[1] || 'show';
1688
+ try {
1689
+ const runId = requiredRunId('goal');
1690
+ let result;
1691
+ if (action === 'show') {
1692
+ result = loadGoalDraft(CWD, runId);
1693
+ } else if (action === 'draft') {
1694
+ appendRunLifecycle(CWD, runId, {
1695
+ type: 'GOAL_DRAFTING',
1696
+ phase: 'goal',
1697
+ actor: argValue('--by') || 'agent',
1698
+ message: argValue('--message') || 'Updating the Goal draft'
1699
+ });
1700
+ result = saveGoalDraft(CWD, runId, readBoundedJsonInput(argValue('--file')), {
1701
+ actor: argValue('--by') || 'agent',
1702
+ expectedRevision: requiredIntegerArg('--revision')
1703
+ });
1704
+ appendRunLifecycle(CWD, runId, {
1705
+ type: 'GOAL_DRAFT_UPDATED',
1706
+ phase: 'goal',
1707
+ actor: argValue('--by') || 'agent',
1708
+ message: `Goal draft revision ${result.metadata.revision} was saved`
1709
+ });
1710
+ appendRunLifecycle(CWD, runId, {
1711
+ type: 'GOAL_READY',
1712
+ phase: 'goal',
1713
+ actor: argValue('--by') || 'agent',
1714
+ message: `Goal draft revision ${result.metadata.revision} is ready for review`
1715
+ });
1716
+ } else if (action === 'freeze') {
1717
+ const expectedHash = argValue('--hash');
1718
+ if (!expectedHash) {
1719
+ const error = new Error('--hash is required');
1720
+ error.code = 'INVALID_USAGE';
1721
+ throw error;
1722
+ }
1723
+ const target = loadRun(CWD, runId);
1724
+ let goalNode = null;
1725
+ if (target.workflow) {
1726
+ const workflow = workflowStatus(CWD, { runId });
1727
+ goalNode = workflow.plan.nodes.find((node) => node.legacyGate === 'goal') || null;
1728
+ if (goalNode && workflow.state.nodes[goalNode.id].status === 'READY') {
1729
+ startWorkflowNode(CWD, goalNode.id, { runId });
1730
+ appendRunLifecycle(CWD, runId, {
1731
+ type: 'NODE_STARTED',
1732
+ nodeId: goalNode.id,
1733
+ phase: 'goal',
1734
+ actor: 'agent',
1735
+ message: `${goalNode.displayName || goalNode.id} freeze started`
1736
+ });
1737
+ }
1738
+ }
1739
+ result = freezeGoal(CWD, runId, {
1740
+ actor: argValue('--by') || 'human',
1741
+ expectedRevision: requiredIntegerArg('--revision'),
1742
+ expectedHash
1743
+ });
1744
+ appendRunLifecycle(CWD, runId, {
1745
+ type: 'NODE_COMPLETED',
1746
+ ...(goalNode ? { nodeId: goalNode.id } : {}),
1747
+ phase: 'goal',
1748
+ actor: argValue('--by') || 'human',
1749
+ message: 'Goal Contract frozen'
1750
+ });
1751
+ } else {
1752
+ const error = new Error('goal must be show, draft, or freeze');
1753
+ error.code = 'INVALID_USAGE';
1754
+ throw error;
1755
+ }
1756
+ console.log(JSON.stringify({ ok: true, runId, [action === 'show' ? 'draft' : 'result']: result }, null, 2));
1757
+ } catch (error) {
1758
+ log.error(`${error.code || 'GOAL_FAILED'}: ${error.message}`);
1759
+ process.exitCode = 1;
1760
+ }
1761
+ }
1762
+
1763
+ function handleActivity() {
1764
+ const aliases = {
1765
+ 'goal-drafting': 'GOAL_DRAFTING',
1766
+ 'goal-ready': 'GOAL_READY',
1767
+ heartbeat: 'AGENT_HEARTBEAT',
1768
+ waiting: 'AGENT_WAITING',
1769
+ 'node-started': 'NODE_STARTED',
1770
+ 'node-activity': 'NODE_ACTIVITY',
1771
+ 'node-completed': 'NODE_COMPLETED',
1772
+ 'loop-iterated': 'LOOP_ITERATED',
1773
+ 'run-completed': 'RUN_COMPLETED'
1774
+ };
1775
+ try {
1776
+ const action = args[1] || 'heartbeat';
1777
+ const type = aliases[action];
1778
+ if (!type) throw Object.assign(new Error(`Unknown activity type: ${action}`), { code: 'INVALID_USAGE' });
1779
+ const runId = requiredRunId('activity');
1780
+ const nodeId = argValue('--node');
1781
+ if (type.startsWith('NODE_') && !nodeId) {
1782
+ throw Object.assign(new Error(`${action} requires --node <id>`), { code: 'INVALID_USAGE' });
1783
+ }
1784
+ const event = appendRunLifecycle(CWD, runId, {
1785
+ type,
1786
+ phase: argValue('--phase'),
1787
+ nodeId,
1788
+ actor: argValue('--by') || 'agent',
1789
+ message: argValue('--message') || 'Agent is working'
1790
+ });
1791
+ console.log(JSON.stringify({ ok: true, event, presence: runAgentPresence(CWD, runId) }, null, 2));
1792
+ } catch (error) {
1793
+ log.error(`${error.code || 'ACTIVITY_FAILED'}: ${error.message}`);
1794
+ process.exitCode = 1;
1795
+ }
1796
+ }
1797
+
1571
1798
  function handleStudio() {
1572
1799
  const requestedPort = argValue('--port');
1573
1800
  const port = requestedPort == null ? 4317 : Number(requestedPort);
@@ -1606,7 +1833,14 @@ function handleInteraction() {
1606
1833
  if (action === 'list') {
1607
1834
  result = listRunInteractions(CWD, runId);
1608
1835
  } else if (action === 'question') {
1836
+ listRunLifecycle(CWD, runId);
1609
1837
  result = appendRunQuestion(CWD, runId, { message, actor: actor || 'agent' });
1838
+ appendRunLifecycle(CWD, runId, {
1839
+ type: 'AGENT_WAITING',
1840
+ phase: 'goal',
1841
+ actor: actor || 'agent',
1842
+ message: `Waiting for answer to Q${result.number}`
1843
+ });
1610
1844
  } else if (action === 'answer') {
1611
1845
  result = appendRunAnswer(CWD, runId, args[2], { message, actor: actor || 'human' });
1612
1846
  } else {
@@ -1655,6 +1889,14 @@ Commands:
1655
1889
  goal | report | maker | verification | review | judge | delivery
1656
1890
  --run <id> target a non-current run
1657
1891
  --json print machine-readable gate output
1892
+ goal Share one revision-bound Goal draft between the Agent and Studio
1893
+ show [--run <id>]
1894
+ draft --file <json> --revision <n> [--run <id>] [--by <agent>]
1895
+ freeze --revision <n> --hash <sha256> [--run <id>] [--by <name>]
1896
+ activity Publish safe Run lifecycle summaries for Studio
1897
+ goal-drafting | goal-ready | heartbeat | waiting
1898
+ node-started | node-activity | node-completed | loop-iterated | run-completed
1899
+ [--run <id>] [--node <id>] [--phase <id>] --message <text>
1658
1900
  node Operate custom nodes in a recipe-bound run
1659
1901
  status [--run <id>] [--json]
1660
1902
  start <id> [--run <id>] [--json]
@@ -1748,6 +1990,12 @@ switch (command) {
1748
1990
  case 'gate':
1749
1991
  handleGate();
1750
1992
  break;
1993
+ case 'goal':
1994
+ handleGoal();
1995
+ break;
1996
+ case 'activity':
1997
+ handleActivity();
1998
+ break;
1751
1999
  case 'node':
1752
2000
  handleNode();
1753
2001
  break;
@@ -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 saveGoalDraft(rootDir, runId, contract) {
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
- const value = { ...contract, schemaVersion: 1, runId };
42
- atomicWriteJson(goalPaths(rootDir, runId, run.goal?.version || 1).draft, value);
43
- return value;
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(rootDir, runId, { actor, now = new Date() } = {}) {
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
- let contract;
54
- try {
55
- contract = JSON.parse(fs.readFileSync(paths.draft, 'utf8'));
56
- } catch (cause) {
57
- throw goalError(`Goal draft is unavailable: ${cause.message}`, 'GOAL_DRAFT_MISSING');
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 hash = hashFile(paths.version);
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: hash,
199
+ sha256: artifactHash,
73
200
  goalVersion: version
74
201
  }
75
202
  },
76
203
  statePatch: {
77
- goal: { version, frozen: true, hash, actor: human, frozenAt: now.toISOString() }
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: hash },
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 };