@tea-agent/loop-agent 0.41.0 → 0.42.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/CHANGELOG.md +102 -14
  2. package/dist/adapters/context-transfer/optional-pi-handoff.js +31 -0
  3. package/dist/adapters/context-transfer/pi-session.js +61 -0
  4. package/dist/build-stamp.json +3 -3
  5. package/dist/cli/command-definitions.js +12 -0
  6. package/dist/cli/program.js +23 -1
  7. package/dist/commands/dag-artifact.js +284 -0
  8. package/dist/commands/dag-context.js +184 -0
  9. package/dist/commands/dag-rerun.js +206 -1
  10. package/dist/executors/dag-pi-executor.js +39 -12
  11. package/dist/executors/pi-sdk-executor.js +3 -0
  12. package/dist/{worker → infrastructure}/console/app-data.js +4 -0
  13. package/dist/infrastructure/console/artifact-revision-store.js +430 -0
  14. package/dist/infrastructure/console/context-export-store.js +160 -0
  15. package/dist/infrastructure/console/dir-lock.js +132 -0
  16. package/dist/{worker → infrastructure}/console/operation-store.js +28 -0
  17. package/dist/infrastructure/harness/artifact-store.js +10 -1
  18. package/dist/infrastructure/harness/atomic-write.js +12 -2
  19. package/dist/shared/context-transfer/artifact-revision.js +172 -0
  20. package/dist/shared/context-transfer.js +418 -0
  21. package/dist/shared/operator/capabilities.js +14 -0
  22. package/dist/shared/operator/safe-run-summary.js +1 -0
  23. package/dist/shared/path-safety.js +93 -0
  24. package/dist/shared/preview.js +28 -4
  25. package/dist/task/config-types.js +2 -1
  26. package/dist/task/task-demand-routing.js +3 -0
  27. package/dist/worker/console/chat/chat-event-store.js +2 -2
  28. package/dist/worker/console/chat/resource-preferences-store.js +1 -1
  29. package/dist/worker/console/chat/routes.js +1 -1
  30. package/dist/worker/console/chat/session-store.js +1 -1
  31. package/dist/worker/console/chat/user-questions.js +1 -1
  32. package/dist/worker/console/console-update-runtime.js +1 -1
  33. package/dist/worker/console/context-transfer-diagnostics.js +198 -0
  34. package/dist/worker/console/dag-confirmation.js +1 -1
  35. package/dist/worker/console/dag-execution-receipt.js +1 -1
  36. package/dist/worker/console/doctor.js +1 -1
  37. package/dist/worker/console/draft-store.js +1 -1
  38. package/dist/worker/console/human-gate-token.js +1 -1
  39. package/dist/worker/console/index.js +3 -3
  40. package/dist/worker/console/interview/assessment.js +1 -1
  41. package/dist/worker/console/interview/session.js +1 -1
  42. package/dist/worker/console/operation-runner.js +45 -4
  43. package/dist/worker/console/operation-sse.js +1 -1
  44. package/dist/worker/console/operation-wait.js +1 -1
  45. package/dist/worker/console/operator-actions.js +104 -3
  46. package/dist/worker/console/operator-surface-health.js +1 -1
  47. package/dist/worker/console/operator-user-error.js +169 -0
  48. package/dist/worker/console/pi-plugins.js +57 -0
  49. package/dist/worker/console/routes.js +637 -8
  50. package/dist/worker/console/security.js +35 -0
  51. package/dist/worker/console/server.js +6 -3
  52. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-DwVJxUxz.js → abnfDiagram-N423BO3Z-DZZ8m3PO.js} +1 -1
  53. package/dist/worker/console/static/assets/{arc-DqfCcXdu.js → arc-D6PvaVd-.js} +1 -1
  54. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-qMVtggRv.js → architectureDiagram-T3A2C74G-B_OTOiI8.js} +1 -1
  55. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-ECrV38dh.js → blockDiagram-VBNYF7ZC-Bv6rqHBg.js} +1 -1
  56. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-DBaaLqQv.js → c4Diagram-5PPSVZJV-B8eHr0oz.js} +1 -1
  57. package/dist/worker/console/static/assets/channel-BU5gOilw.js +1 -0
  58. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-BvfNHkAz.js → chunk-2GRJ4B5K-DYwR0im2.js} +1 -1
  59. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-C5StiIbc.js → chunk-2Q5K7J3B-D2WPGqXt.js} +1 -1
  60. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-HabGiJkS.js → chunk-5RXB4S5H-CQISJ_I7.js} +1 -1
  61. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-BiTg127i.js → chunk-5VM5RSS4-C0o2Du1e.js} +1 -1
  62. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-CZsXBPuR.js → chunk-6Q2QTUOP-4f8kr-U7.js} +1 -1
  63. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-D-r1MxLK.js → chunk-GF5L2VYU-D_OWvXzX.js} +1 -1
  64. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-DQxb9plr.js → chunk-JWPE2WC7-CasdPz5X.js} +1 -1
  65. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-DMndGvCT.js → chunk-KBJHAD2P-Cj8lRrla.js} +1 -1
  66. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-ByL4BgOJ.js → chunk-RYQCIY6F-CUvD1FSd.js} +1 -1
  67. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-BVe1b1gL.js → chunk-XXDRQBXY-CqLw_eqB.js} +1 -1
  68. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DIzKJGHr.js +1 -0
  69. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DIzKJGHr.js +1 -0
  70. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-BAyGzN8j.js → cose-bilkent-JH36ORCC-ku-WqJPx.js} +1 -1
  71. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-C5yVYU7E.js → cynefin-VYW2F7L2-Bq_PYDhl.js} +1 -1
  72. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-x-MwsEm9.js → cynefinDiagram-MW4NZA55-BiGZV641.js} +1 -1
  73. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-CT5Tle5F.js → dagre-VZM6K2ZE-C4JRlglF.js} +1 -1
  74. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-BARERhlS.js → diagram-7IWD3JNH-B0dNeWYG.js} +1 -1
  75. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-BwfUz0VM.js → diagram-B4RE2ZJO-Cj35YvYM.js} +1 -1
  76. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-Mk4r2WvJ.js → diagram-LBJQPF4R-uzQoJ2-8.js} +1 -1
  77. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-KUrxuBs0.js → diagram-Q27KOJAE-D1a-Buoz.js} +1 -1
  78. package/dist/worker/console/static/assets/{diagram-UB23O5K3-CjZOceZn.js → diagram-UB23O5K3-XjRrLRSs.js} +1 -1
  79. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-rnwUCiEI.js → ebnfDiagram-BXEA7PRR-Da_O24cW.js} +1 -1
  80. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-DM4j23FM.js → erDiagram-JOGREHBK-BLJ8jrYU.js} +1 -1
  81. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-DD5HdDEs.js → flowDiagram-UKHOOZJN-B9GrLjM0.js} +1 -1
  82. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-CIAGSF47.js → ganttDiagram-PKOTCBZU-CeJ0TqiK.js} +1 -1
  83. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-DbwFbVEL.js → gitGraphDiagram-DS77QQ5N-Bm2eNNFX.js} +1 -1
  84. package/dist/worker/console/static/assets/index-H9rFJiGL.css +1 -0
  85. package/dist/worker/console/static/assets/{index-Bih9w9h9.js → index-xwu9GxEc.js} +80 -80
  86. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-B-Pb0T66.js → infoDiagram-6WML65LV-DB26i3d8.js} +1 -1
  87. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-B9Unk-YX.js → ishikawaDiagram-WSZJBQD7-BOGRyeZT.js} +1 -1
  88. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-C2F3JkPt.js → journeyDiagram-NVQOT4AX-CZRoBO_6.js} +1 -1
  89. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-Bl8-Xcoz.js → kanban-definition-27J2QSJJ-qlWhJyoB.js} +1 -1
  90. package/dist/worker/console/static/assets/{linear-yK4uZmC5.js → linear-CfUiDDB3.js} +1 -1
  91. package/dist/worker/console/static/assets/{mermaid.core-Bpa6PmuE.js → mermaid.core-BQe6fpqj.js} +5 -5
  92. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-BfGRoCSe.js → mindmap-definition-FAOFIHXS-zFzWHw64.js} +1 -1
  93. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-Bz6_HtST.js → pegDiagram-VL7TDLO6-DFGUqjZO.js} +1 -1
  94. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-i0Umbsby.js → pieDiagram-7S7Q4E2Y-BB5i0l8Z.js} +1 -1
  95. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-DaVQBobe.js → quadrantDiagram-CIZ2JOQS-obbVZ_X5.js} +1 -1
  96. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-DMTGnSq7.js → railroadDiagram-AXF67PYL-BwdaNzc1.js} +1 -1
  97. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-2ao_DaSq.js → requirementDiagram-LRYGKXZP-CkTJaugh.js} +1 -1
  98. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-2SG1lTB9.js → sankeyDiagram-W5VNT64P-BwJ-hIgq.js} +1 -1
  99. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-BQYOLybR.js → sequenceDiagram-SI44F4Z6-BzSgmm7w.js} +1 -1
  100. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-C8g3yjuI.js → sizeCapture-X5ZJPWSS-Bn3oj5Q1.js} +1 -1
  101. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-q_F8nAQG.js → stateDiagram-OKZ733FA-dxhGtL8K.js} +1 -1
  102. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Cld2qK9v.js +1 -0
  103. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-8LrWpH2s.js → swimlanes-SLNWSIFB-BLpEInya.js} +2 -2
  104. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-TIHpiT7w.js +8 -0
  105. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-BQoY3qzl.js → timeline-definition-Z64GVDOM-ChJGYcXy.js} +1 -1
  106. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-BDu1UjSp.js → vennDiagram-T6HMQDX7-DK-qjRer.js} +1 -1
  107. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-C48M7Y0a.js → wardleyDiagram-T6FBY63Y-3qeaWAg-.js} +1 -1
  108. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-YU6FTl_F.js → xychartDiagram-ELKLHX3M-CootlyP9.js} +1 -1
  109. package/dist/worker/console/static/index.html +7 -2
  110. package/dist/worker/console/static-src/app/useOperatorActions.js +3 -2
  111. package/dist/worker/console/static-src/shell/console-update-reload.js +25 -0
  112. package/dist/worker/console/workspace-context.js +28 -2
  113. package/dist/worker/console/workspace-registry.js +2 -2
  114. package/dist/worker/continuation/worker-continuation.js +278 -0
  115. package/dist/worker/observe/health.js +1 -1
  116. package/dist/worker/observe/node-transparency.js +572 -0
  117. package/dist/worker/observe/routes.js +51 -1
  118. package/dist/worker/observe/static/api.js +69 -5
  119. package/dist/worker/observe/static/dag-context-reason-labels.d.ts +9 -0
  120. package/dist/worker/observe/static/dag-context-reason-labels.js +120 -0
  121. package/dist/worker/observe/static/state.js +3 -1
  122. package/dist/worker/observe/static/styles.css +1037 -126
  123. package/dist/worker/observe/static/views/dag-inspector.js +1215 -58
  124. package/dist/worker/observe/static/views/session-timeline.js +75 -10
  125. package/dist/worker/outcomes/adapters.js +19 -0
  126. package/dist/worker/outcomes/types.js +1 -0
  127. package/dist/worker/pool/attempt-lease.js +97 -66
  128. package/dist/worker/pool/begin-attempt-with-lease.js +1 -0
  129. package/dist/worker/pool/reconcile.js +46 -1
  130. package/dist/worker/pool/run-store.js +2 -0
  131. package/dist/worker/pool/state-projection.js +2 -0
  132. package/dist/worker/task-spec/workflow-routing.js +8 -3
  133. package/dist/workflows/dag/artifact-bindings.js +149 -0
  134. package/dist/workflows/dag/artifact-revision-schema-registry.js +31 -0
  135. package/dist/workflows/dag/budget-enforcement.js +10 -0
  136. package/dist/workflows/dag/context-receipt.js +305 -0
  137. package/dist/workflows/dag/context-transfer/context-bundle.js +423 -0
  138. package/dist/workflows/dag/context-transfer/operator-actions.js +61 -0
  139. package/dist/workflows/dag/context-transfer/renderers.js +93 -0
  140. package/dist/workflows/dag/frontend-writer-rollback.js +32 -0
  141. package/dist/workflows/dag/init-hybrid.js +146 -0
  142. package/dist/workflows/dag/node-execution.js +112 -27
  143. package/dist/workflows/dag/path-safety.js +1 -0
  144. package/dist/workflows/dag/prompt.js +29 -4
  145. package/dist/workflows/dag/rerun-plan.js +555 -1
  146. package/dist/workflows/dag/rerun-run.js +601 -15
  147. package/dist/workflows/dag/runner.js +20 -1
  148. package/dist/workflows/dag/skill-snapshot.js +17 -0
  149. package/dist/workflows/dag/types.js +183 -7
  150. package/docs/architecture/runtime-boundaries.md +6 -6
  151. package/docs/architecture/worker-and-feature.md +1 -1
  152. package/docs/templates/agent-dag.schema.json +32 -0
  153. package/docs/templates/product-line/task.yaml +1 -1
  154. package/package.json +3 -1
  155. package/skills/loop-agent/references/command-reference.md +6 -0
  156. package/dist/worker/console/static/assets/channel-CL1NRAmS.js +0 -1
  157. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-PBGzzjZA.js +0 -1
  158. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-PBGzzjZA.js +0 -1
  159. package/dist/worker/console/static/assets/index-BfleX-qj.css +0 -1
  160. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-DrxGBDJu.js +0 -1
  161. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-BhpDxzAf.js +0 -8
  162. /package/dist/{worker → infrastructure}/console/repo-fingerprint.js +0 -0
@@ -0,0 +1,198 @@
1
+ import path from "node:path";
2
+ import { appendFile, chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
3
+ import { randomBytes } from "node:crypto";
4
+ import { assertSafeAppDataPath, readJsonIfExists, writeSecureJson, } from "../../infrastructure/console/app-data.js";
5
+ const diagnosticWriteChains = new Map();
6
+ function serializeDiagnostic(filePath, operation) {
7
+ const previous = diagnosticWriteChains.get(filePath) ?? Promise.resolve();
8
+ const next = previous.then(operation, operation);
9
+ diagnosticWriteChains.set(filePath, next.then(() => undefined, () => undefined));
10
+ return next;
11
+ }
12
+ function diagnosticsPath(appData) {
13
+ const repoNamespace = path.dirname(appData.operations);
14
+ return assertSafeAppDataPath(repoNamespace, path.join(repoNamespace, "context-transfer-diagnostics.json"));
15
+ }
16
+ function safeNonNegative(value) {
17
+ return Number.isFinite(value) && (value ?? 0) >= 0 ? Math.round(value ?? 0) : 0;
18
+ }
19
+ function safeReasonCode(value) {
20
+ if (!value)
21
+ return undefined;
22
+ const normalized = value.trim().slice(0, 96);
23
+ return /^[A-Za-z0-9_.-]+$/.test(normalized) ? normalized : "UNCLASSIFIED";
24
+ }
25
+ export async function recordContextTransferDiagnostic(input) {
26
+ const filePath = diagnosticsPath(input.appData);
27
+ return serializeDiagnostic(filePath, async () => {
28
+ const current = (await readJsonIfExists(filePath)) ?? {
29
+ schemaVersion: 1,
30
+ updatedAt: (input.now ?? new Date()).toISOString(),
31
+ counters: [],
32
+ };
33
+ const dimensions = {
34
+ outcome: input.dimensions.outcome,
35
+ ...(input.dimensions.target ? { target: input.dimensions.target } : {}),
36
+ ...(input.dimensions.profile ? { profile: input.dimensions.profile } : {}),
37
+ ...(input.dimensions.diffKind ? { diffKind: input.dimensions.diffKind } : {}),
38
+ ...(safeReasonCode(input.dimensions.reasonCode)
39
+ ? { reasonCode: safeReasonCode(input.dimensions.reasonCode) }
40
+ : {}),
41
+ };
42
+ const key = JSON.stringify({ event: input.event, ...dimensions });
43
+ const existing = current.counters.find((counter) => JSON.stringify({ event: counter.event, ...dimensionsFromCounter(counter) }) === key);
44
+ if (existing) {
45
+ existing.count += 1;
46
+ existing.bytes += safeNonNegative(input.dimensions.bytes);
47
+ existing.durationMs += safeNonNegative(input.dimensions.durationMs);
48
+ existing.affectedNodeCount += safeNonNegative(input.dimensions.affectedNodeCount);
49
+ existing.importedNodeCount += safeNonNegative(input.dimensions.importedNodeCount);
50
+ }
51
+ else {
52
+ current.counters.push({
53
+ event: input.event,
54
+ ...dimensions,
55
+ count: 1,
56
+ bytes: safeNonNegative(input.dimensions.bytes),
57
+ durationMs: safeNonNegative(input.dimensions.durationMs),
58
+ affectedNodeCount: safeNonNegative(input.dimensions.affectedNodeCount),
59
+ importedNodeCount: safeNonNegative(input.dimensions.importedNodeCount),
60
+ });
61
+ }
62
+ current.updatedAt = (input.now ?? new Date()).toISOString();
63
+ await writeSecureJson(filePath, current);
64
+ return current;
65
+ });
66
+ }
67
+ function dimensionsFromCounter(counter) {
68
+ return {
69
+ outcome: counter.outcome,
70
+ ...(counter.target ? { target: counter.target } : {}),
71
+ ...(counter.profile ? { profile: counter.profile } : {}),
72
+ ...(counter.diffKind ? { diffKind: counter.diffKind } : {}),
73
+ ...(counter.reasonCode ? { reasonCode: counter.reasonCode } : {}),
74
+ };
75
+ }
76
+ export async function readContextTransferDiagnostics(appData) {
77
+ return readJsonIfExists(diagnosticsPath(appData));
78
+ }
79
+ /**
80
+ * Append-only lifecycle event log for context-transfer mutations
81
+ * (exec-plan observability: context_export.* / artifact_revision.* /
82
+ * artifact_rerun.*). Events carry ids, counts, bytes, duration and reason
83
+ * codes only — never prompt text, artifact content, secret finding values or
84
+ * host absolute paths. The Console emits only stages it truly observes;
85
+ * CLI-kernel-internal stages (capture, secret scan, adapters) stay in the
86
+ * kernel's own evidence.
87
+ */
88
+ export const CONTEXT_TRANSFER_EVENT_LOG_LIMIT = 512;
89
+ const CONTEXT_TRANSFER_EVENT_NAME_PATTERN = /^(?:context_export|artifact_revision|artifact_rerun)\.[a-z][a-z_]{0,47}$/;
90
+ const CONTEXT_TRANSFER_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
91
+ export async function recordContextTransferEvent(input) {
92
+ const at = (input.now ?? new Date()).toISOString();
93
+ if (!CONTEXT_TRANSFER_EVENT_NAME_PATTERN.test(input.event)) {
94
+ return { recorded: false, total: 0 };
95
+ }
96
+ const fields = input.fields ?? {};
97
+ const entry = {
98
+ schemaVersion: 1,
99
+ at,
100
+ event: input.event,
101
+ ...sanitizeLifecycleFields(fields),
102
+ };
103
+ const filePath = lifecycleEventsPath(input.appData);
104
+ return serializeDiagnostic(filePath, async () => {
105
+ await appendLifecycleEvent(filePath, entry);
106
+ const total = await countLifecycleEvents(filePath);
107
+ if (total > CONTEXT_TRANSFER_EVENT_LOG_LIMIT) {
108
+ await trimLifecycleEvents(filePath, CONTEXT_TRANSFER_EVENT_LOG_LIMIT);
109
+ return { recorded: true, total: CONTEXT_TRANSFER_EVENT_LOG_LIMIT };
110
+ }
111
+ return { recorded: true, total };
112
+ });
113
+ }
114
+ export async function readContextTransferEvents(appData) {
115
+ const filePath = lifecycleEventsPath(appData);
116
+ const raw = await readFile(filePath, "utf8").catch(() => "");
117
+ const events = [];
118
+ for (const line of raw.split("\n")) {
119
+ if (!line.trim())
120
+ continue;
121
+ try {
122
+ const parsed = JSON.parse(line);
123
+ if (parsed &&
124
+ typeof parsed === "object" &&
125
+ parsed.schemaVersion === 1 &&
126
+ typeof parsed.event === "string") {
127
+ events.push(parsed);
128
+ }
129
+ }
130
+ catch {
131
+ // A torn final line after a crash must not break readers.
132
+ }
133
+ }
134
+ return events;
135
+ }
136
+ function lifecycleEventsPath(appData) {
137
+ const repoNamespace = path.dirname(appData.operations);
138
+ return assertSafeAppDataPath(repoNamespace, path.join(repoNamespace, "context-transfer-events.jsonl"));
139
+ }
140
+ function safeLifecycleId(value) {
141
+ if (!value)
142
+ return undefined;
143
+ return CONTEXT_TRANSFER_ID_PATTERN.test(value) ? value : undefined;
144
+ }
145
+ function sanitizeLifecycleFields(fields) {
146
+ return {
147
+ ...(safeLifecycleId(fields.runId) ? { runId: fields.runId } : {}),
148
+ ...(safeLifecycleId(fields.nodeId) ? { nodeId: fields.nodeId } : {}),
149
+ ...(safeLifecycleId(fields.exportId) ? { exportId: fields.exportId } : {}),
150
+ ...(safeLifecycleId(fields.revisionId)
151
+ ? { revisionId: fields.revisionId }
152
+ : {}),
153
+ ...(safeLifecycleId(fields.operationId)
154
+ ? { operationId: fields.operationId }
155
+ : {}),
156
+ ...(fields.profile === "redacted" || fields.profile === "raw"
157
+ ? { profile: fields.profile }
158
+ : {}),
159
+ ...(fields.target === "generic" ||
160
+ fields.target === "pi-session" ||
161
+ fields.target === "pi-handoff" ||
162
+ fields.target === "readable"
163
+ ? { target: fields.target }
164
+ : {}),
165
+ ...(fields.bytes !== undefined
166
+ ? { bytes: safeNonNegative(fields.bytes) }
167
+ : {}),
168
+ ...(fields.durationMs !== undefined
169
+ ? { durationMs: safeNonNegative(fields.durationMs) }
170
+ : {}),
171
+ ...(safeReasonCode(fields.reasonCode)
172
+ ? { reasonCode: safeReasonCode(fields.reasonCode) }
173
+ : {}),
174
+ };
175
+ }
176
+ async function appendLifecycleEvent(filePath, entry) {
177
+ await mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
178
+ await appendFile(filePath, `${JSON.stringify(entry)}\n`, { mode: 0o600 });
179
+ await chmod(filePath, 0o600).catch(() => undefined);
180
+ }
181
+ async function countLifecycleEvents(filePath) {
182
+ const raw = await readFile(filePath, "utf8").catch(() => "");
183
+ let total = 0;
184
+ for (const line of raw.split("\n")) {
185
+ if (line.trim())
186
+ total += 1;
187
+ }
188
+ return total;
189
+ }
190
+ async function trimLifecycleEvents(filePath, limit) {
191
+ const raw = await readFile(filePath, "utf8").catch(() => "");
192
+ const lines = raw.split("\n").filter((line) => line.trim());
193
+ const kept = lines.slice(-limit);
194
+ const tmp = `${filePath}.${randomBytes(8).toString("hex")}.tmp`;
195
+ await writeFile(tmp, `${kept.join("\n")}\n`, { mode: 0o600, flag: "wx" });
196
+ await rename(tmp, filePath);
197
+ await chmod(filePath, 0o600).catch(() => undefined);
198
+ }
@@ -1,6 +1,6 @@
1
1
  import { createHash, randomBytes } from "node:crypto";
2
2
  import path from "node:path";
3
- import { readJsonIfExists, sha256Utf8, writeSecureJson, } from "./app-data.js";
3
+ import { readJsonIfExists, sha256Utf8, writeSecureJson, } from "../../infrastructure/console/app-data.js";
4
4
  import { confirmationPayloadHash, issueHumanGateToken, verifyHumanGateToken, } from "./human-gate-token.js";
5
5
  export const ALL_CONFIRMATION_CHALLENGES = [
6
6
  "source",
@@ -20,7 +20,7 @@ import { randomBytes } from "node:crypto";
20
20
  import { readFile } from "node:fs/promises";
21
21
  import path from "node:path";
22
22
  import { pathMatchesPattern } from "../../shared/git-progress.js";
23
- import { readJsonIfExists, sha256Utf8, writeSecureJson, } from "./app-data.js";
23
+ import { readJsonIfExists, sha256Utf8, writeSecureJson, } from "../../infrastructure/console/app-data.js";
24
24
  import { hashDagBytes, } from "./dag-confirmation.js";
25
25
  /**
26
26
  * Structured verification command patterns for the G2 autonomous-execution
@@ -6,7 +6,7 @@ import { LoopAgentClient } from "../loop-agent/loop-agent-client.js";
6
6
  import { preflightTargetRepo } from "../preflight.js";
7
7
  import { probePiReadiness, } from "./pi-readiness.js";
8
8
  import { DEFAULT_OBSERVE_BASE_URL, OBSERVE_START_COMMAND, probeAndClassifyObserve, } from "./observe-health-match.js";
9
- import { repoFingerprintV1 } from "./repo-fingerprint.js";
9
+ import { repoFingerprintV1 } from "../../infrastructure/console/repo-fingerprint.js";
10
10
  import { resolveSiblingLoopAgentBin } from "./sibling-controller.js";
11
11
  import { defaultObserveStaticDir, ROUTES } from "../observe/routes.js";
12
12
  import { deriveObserveRouteCapabilities } from "../observe/health.js";
@@ -1,5 +1,5 @@
1
1
  import path from "node:path";
2
- import { readJsonIfExists, sha256Json, writeSecureJson, } from "./app-data.js";
2
+ import { readJsonIfExists, sha256Json, writeSecureJson, } from "../../infrastructure/console/app-data.js";
3
3
  /**
4
4
  * 从任意上游载荷安全投影 ledger 摘要(未知形状丢弃,绝不抛错、绝不信任字段外的数据)。
5
5
  * 供 DraftStore / prd-intake-bridge 把 prepare/advance 结果中的 ledger 摘要带入草稿。
@@ -85,7 +85,7 @@ export function verifyHumanGateToken(presented, expected, secret, now = new Date
85
85
  * invalidates the token (defense against drift-then-confirm).
86
86
  */
87
87
  import { createHash } from "node:crypto";
88
- import { sha256Utf8 } from "./app-data.js";
88
+ import { sha256Utf8 } from "../../infrastructure/console/app-data.js";
89
89
  export function confirmationPayloadHash(b) {
90
90
  const canonical = [
91
91
  `dag=${b.dagSha256}`,
@@ -3,14 +3,14 @@ export { buildOperatorSurfaceHealthV1 } from "./operator-surface-health.js";
3
3
  export { runConsoleDoctor, formatConsoleDoctorHuman } from "./doctor.js";
4
4
  export { isLoopbackHost } from "./loopback.js";
5
5
  export { shouldOpenConsoleBrowser, normalizeConsoleBrowserUrl, openSystemBrowser, maybeOpenConsoleBrowser, } from "./open-browser.js";
6
- export { repoFingerprintV1, normalizeWorktreeRealpath, } from "./repo-fingerprint.js";
6
+ export { repoFingerprintV1, normalizeWorktreeRealpath, } from "../../infrastructure/console/repo-fingerprint.js";
7
7
  export { buildObserveDeepLink } from "./observe-link.js";
8
8
  export { classifyObserveHealth, probeAndClassifyObserve, capabilityForObserveTarget, OBSERVE_START_COMMAND, DEFAULT_OBSERVE_BASE_URL, } from "./observe-health-match.js";
9
9
  export { allowedRecoveryCtas, classifyRecoveryFact, partitionRecoveryCtas, recoveryMatrixInvariants, } from "./recovery-cta.js";
10
10
  export { createClosedResourceLoader, createInterviewResourceLoader, tryActivateTool, assertOfficialToolAllowed, listOfficialTools, OFFICIAL_DENIED_TOOL_IDS, INTERVIEW_ALLOWED_TOOLS, INTERVIEW_DENIED_TOOLS, authorizeInterviewTool, } from "./resource-loader.js";
11
11
  export { resolveSiblingLoopAgentBin } from "./sibling-controller.js";
12
- export { openConsoleAppData, defaultConsoleAppDataRoot } from "./app-data.js";
13
- export { OperationStore } from "./operation-store.js";
12
+ export { openConsoleAppData, defaultConsoleAppDataRoot } from "../../infrastructure/console/app-data.js";
13
+ export { OperationStore } from "../../infrastructure/console/operation-store.js";
14
14
  export { createOperationEventStore } from "./operation-sse.js";
15
15
  export { DagConfirmationStore } from "./dag-confirmation.js";
16
16
  export { DraftStore } from "./draft-store.js";
@@ -1,6 +1,6 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import path from "node:path";
3
- import { readJsonIfExists, writeSecureJson, } from "../app-data.js";
3
+ import { readJsonIfExists, writeSecureJson, } from "../../../infrastructure/console/app-data.js";
4
4
  import { computeDraftSha256, } from "../draft-store.js";
5
5
  function assessmentPath(appData, assessmentId) {
6
6
  return path.join(appData.assessments, `${assessmentId}.json`);
@@ -1,6 +1,6 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import path from "node:path";
3
- import { readJsonIfExists, writeSecureJson, } from "../app-data.js";
3
+ import { readJsonIfExists, writeSecureJson, } from "../../../infrastructure/console/app-data.js";
4
4
  import { createInterviewResourceLoader, } from "./tools.js";
5
5
  function sessionPath(appData, sessionId) {
6
6
  return path.join(appData.interviews, `${sessionId}.json`);
@@ -1,6 +1,14 @@
1
- import { clipPreview, } from "./operation-store.js";
1
+ import { clipPreview, } from "../../infrastructure/console/operation-store.js";
2
2
  import { stateEvent } from "./operation-sse.js";
3
3
  import { extractTrustedRunFacts } from "./operation-run-facts.js";
4
+ /** Swallow-all invoker so observers can never break the state path. */
5
+ function notifySettled(deps, operation, state, info) {
6
+ if (!deps.onSettled)
7
+ return;
8
+ void Promise.resolve()
9
+ .then(() => deps.onSettled?.(operation, state, info))
10
+ .catch(() => undefined);
11
+ }
4
12
  /**
5
13
  * Execute a queued operation via LoopAgentClient (or inject).
6
14
  * Timeout without proven exit → needs-reconcile (never Cancel).
@@ -42,6 +50,7 @@ export async function runOperation(operationId, deps) {
42
50
  artifactName: `operation-${operationId}`,
43
51
  expectJson: true,
44
52
  timeoutMs: deps.defaultTimeoutMs,
53
+ env: deps.env,
45
54
  onSpawn: (info) => {
46
55
  // Chain onto the per-operation write lock; never fire-and-forget a
47
56
  // rejected update (unhandled rejection can crash Console on Windows).
@@ -119,6 +128,10 @@ export async function runOperation(operationId, deps) {
119
128
  message: finished.errorMessage,
120
129
  state: "needs-reconcile",
121
130
  });
131
+ notifySettled(deps, finished, "needs-reconcile", {
132
+ ok: false,
133
+ errorCode: finished.errorCode,
134
+ });
122
135
  }
123
136
  return finished;
124
137
  }
@@ -169,9 +182,10 @@ async function finalizeFromWorkerResult(operationId, result, deps) {
169
182
  // Supervisory timeout without classified CLI timeout → needs-reconcile
170
183
  // Only mark timed-out when we have a machine timeout result after exit.
171
184
  const state = result.exitCode !== null ? "timed-out" : "needs-reconcile";
172
- const updated = await deps.store.update(operationId, {
185
+ const finishedAt = new Date().toISOString();
186
+ const patch = {
173
187
  state,
174
- finishedAt: new Date().toISOString(),
188
+ finishedAt,
175
189
  artifactRefs,
176
190
  stdoutPreview: previewStdout,
177
191
  stderrPreview: previewStderr,
@@ -186,7 +200,15 @@ async function finalizeFromWorkerResult(operationId, result, deps) {
186
200
  ...(runFacts.runSummary ? { runSummary: runFacts.runSummary } : {}),
187
201
  }
188
202
  : {}),
203
+ };
204
+ const current = await deps.store.get(operationId);
205
+ if (!current)
206
+ throw new Error(`operation not found: ${operationId}`);
207
+ await deps.beforeTerminal?.({ ...current, ...patch }, state, {
208
+ ok: false,
209
+ errorCode: patch.errorCode,
189
210
  });
211
+ const updated = await deps.store.update(operationId, patch);
190
212
  stateEvent(deps.events, updated, state, updated.errorMessage);
191
213
  if (runFacts) {
192
214
  appendSafeResultEvent(deps, operationId, state, {
@@ -202,6 +224,10 @@ async function finalizeFromWorkerResult(operationId, result, deps) {
202
224
  data: { ok: false, exitCode: result.exitCode },
203
225
  });
204
226
  }
227
+ notifySettled(deps, updated, state, {
228
+ ok: false,
229
+ errorCode: updated.errorCode,
230
+ });
205
231
  return updated;
206
232
  }
207
233
  const envelope = coerceEnvelope(result);
@@ -210,7 +236,7 @@ async function finalizeFromWorkerResult(operationId, result, deps) {
210
236
  const processOk = envelope?.ok === true || (result.ok && result.exitCode === 0);
211
237
  const ok = processOk && !businessBlock;
212
238
  const state = ok ? "succeeded" : "failed";
213
- const updated = await deps.store.update(operationId, {
239
+ const patch = {
214
240
  state,
215
241
  finishedAt: new Date().toISOString(),
216
242
  artifactRefs,
@@ -238,9 +264,20 @@ async function finalizeFromWorkerResult(operationId, result, deps) {
238
264
  ...(runFacts.runSummary ? { runSummary: runFacts.runSummary } : {}),
239
265
  }
240
266
  : {}),
267
+ };
268
+ if (!operation)
269
+ throw new Error(`operation not found: ${operationId}`);
270
+ await deps.beforeTerminal?.({ ...operation, ...patch }, state, {
271
+ ok,
272
+ errorCode: patch.errorCode,
241
273
  });
274
+ const updated = await deps.store.update(operationId, patch);
242
275
  stateEvent(deps.events, updated, state, updated.errorMessage);
243
276
  appendSafeResultEvent(deps, operationId, state, { ok, exitCode: result.exitCode }, runFacts);
277
+ notifySettled(deps, updated, state, {
278
+ ok,
279
+ errorCode: updated.errorCode,
280
+ });
244
281
  if (ok && operation?.action === "dagRequestInterrupt") {
245
282
  await projectInterruptRequestOntoTarget(operation, result.json, deps);
246
283
  }
@@ -300,6 +337,10 @@ export function scheduleOperation(operationId, deps) {
300
337
  })
301
338
  .then((updated) => {
302
339
  stateEvent(deps.events, updated, "needs-reconcile", message);
340
+ notifySettled(deps, updated, "needs-reconcile", {
341
+ ok: false,
342
+ errorCode: updated.errorCode,
343
+ });
303
344
  })
304
345
  .catch(() => {
305
346
  // A failed canonical store update cannot be represented safely.
@@ -1,6 +1,6 @@
1
1
  import { existsSync, readFileSync, rmSync } from "node:fs";
2
2
  import path from "node:path";
3
- import { ensureSecureDir, writeSecureJsonSync } from "./app-data.js";
3
+ import { ensureSecureDir, writeSecureJsonSync } from "../../infrastructure/console/app-data.js";
4
4
  const DEFAULT_MAX_EVENTS = 1000;
5
5
  function safeOperationId(operationId) {
6
6
  return operationId.replace(/[^a-zA-Z0-9._-]+/g, "_").slice(0, 180);
@@ -1,5 +1,5 @@
1
1
  import { projectOperationEventSummary, projectOperationForChat, } from "./chat/chat-event-store.js";
2
- import { isTerminalOperationState, } from "./operation-store.js";
2
+ import { isTerminalOperationState, } from "../../infrastructure/console/operation-store.js";
3
3
  /**
4
4
  * P2: read-only event-driven long poll on the canonical operation event ring
5
5
  * (2026-08-13 Operator Chat long-run supervision). Server contract bounds:
@@ -4,13 +4,14 @@ import { DAG_RERUN_PROMPT_OVERRIDE_ENV, isDagRerunPromptOverrideEnabled, MAX_DAG
4
4
  import { buildOperatorResult, operatorFailed, operatorSucceeded, } from "../../shared/operator/envelope.js";
5
5
  import { CANONICAL_TASK_ID_PATTERN, formatLocalBusinessDate, getTaskPaths, loadTaskConfig, } from "../../task/runtime.js";
6
6
  import { diffTaskContract, validateDraftForTask, } from "../../task/contract/index.js";
7
- import { stageUtf8Text } from "./app-data.js";
7
+ import { stageUtf8Text } from "../../infrastructure/console/app-data.js";
8
8
  import { ALL_CONFIRMATION_CHALLENGES, hashDagBytes, } from "./dag-confirmation.js";
9
9
  import { capabilityForObserveTarget, DEFAULT_OBSERVE_BASE_URL, OBSERVE_START_COMMAND, probeAndClassifyObserve, } from "./observe-health-match.js";
10
10
  import { buildInspectDeepLink, buildObserveDeepLink, } from "./observe-link.js";
11
11
  import { resolveLatestDagRunIdForTask } from "./resolve-dag-run-for-task.js";
12
- import { repoFingerprintV1 } from "./repo-fingerprint.js";
12
+ import { repoFingerprintV1 } from "../../infrastructure/console/repo-fingerprint.js";
13
13
  import { scheduleOperation, } from "./operation-runner.js";
14
+ import { recordContextTransferEvent } from "./context-transfer-diagnostics.js";
14
15
  import { readinessGateFailure, } from "./pi-readiness.js";
15
16
  import { validatePiModelMatrixTiers, writePiModelMatrix, } from "./harness-pi-model-matrix.js";
16
17
  import { isAssessmentFreshForDraft } from "./interview/assessment.js";
@@ -481,7 +482,7 @@ async function buildPromptOverrideCliArgs(ctx, overrides) {
481
482
  }
482
483
  return args;
483
484
  }
484
- async function acceptOperation(ctx, input) {
485
+ export async function acceptOperation(ctx, input) {
485
486
  const created = await ctx.operations.create({
486
487
  clientRequestId: input.clientRequestId,
487
488
  action: input.action,
@@ -517,12 +518,55 @@ async function acceptOperation(ctx, input) {
517
518
  },
518
519
  };
519
520
  }
521
+ if (input.onAdmitted) {
522
+ try {
523
+ await input.onAdmitted(created.operation);
524
+ }
525
+ catch {
526
+ // Lifecycle observation must never block admission.
527
+ }
528
+ }
529
+ if (input.prepare) {
530
+ try {
531
+ await input.prepare();
532
+ }
533
+ catch (error) {
534
+ const message = error instanceof Error ? error.message : String(error);
535
+ const preparedFailure = input.prepareFailure?.(error);
536
+ await ctx.operations.update(created.operation.operationId, {
537
+ state: "failed",
538
+ startedAt: created.operation.createdAt,
539
+ finishedAt: new Date().toISOString(),
540
+ errorCode: preparedFailure?.errorCode ?? "INVALID_INPUT",
541
+ errorMessage: message,
542
+ });
543
+ return {
544
+ kind: "error",
545
+ status: preparedFailure?.status ?? 400,
546
+ body: preparedFailure?.body ?? operatorFailed({
547
+ command: input.action,
548
+ outcome: "blocked",
549
+ code: "INVALID_INPUT",
550
+ message,
551
+ }),
552
+ };
553
+ }
554
+ }
555
+ const transferObserver = contextTransferSettledObserver(ctx, input.action, input.actionParams);
520
556
  const runnerDeps = {
521
557
  store: ctx.operations,
522
558
  events: ctx.events,
523
559
  client: ctx.client,
524
560
  repoRoot: ctx.repoRoot,
561
+ env: { ...process.env, LOOP_CONSOLE_APP_DATA: ctx.appData.root },
525
562
  runCommand: ctx.runCommand,
563
+ beforeTerminal: input.beforeTerminal,
564
+ onSettled: async (operation, state, info) => {
565
+ // Diagnostics are best-effort and must not prevent authoritative Worker
566
+ // settlement from running.
567
+ await Promise.resolve(transferObserver?.(operation, state, info)).catch(() => undefined);
568
+ await input.onSettled?.(operation, state, info);
569
+ },
526
570
  };
527
571
  scheduleOperation(created.operation.operationId, runnerDeps);
528
572
  return {
@@ -536,6 +580,63 @@ async function acceptOperation(ctx, input) {
536
580
  },
537
581
  };
538
582
  }
583
+ /**
584
+ * Map artifact revision / rerun operation outcomes onto the append-only
585
+ * context-transfer lifecycle event log. Only stages the Console truly
586
+ * observes (admission + settle) are recorded; CLI-kernel-internal stages
587
+ * stay in the kernel. Unknown actions emit nothing.
588
+ */
589
+ function contextTransferSettledObserver(ctx, action, actionParams) {
590
+ if (action !== "artifactRevisionStage" &&
591
+ action !== "artifactRevisionPlan" &&
592
+ action !== "artifactRevisionExecute") {
593
+ return undefined;
594
+ }
595
+ const strParam = (key) => {
596
+ const value = actionParams[key];
597
+ return typeof value === "string" ? value.trim() : undefined;
598
+ };
599
+ const baseFields = {
600
+ runId: strParam("runId"),
601
+ nodeId: strParam("nodeId"),
602
+ revisionId: strParam("revisionId"),
603
+ };
604
+ return (operation, state, info) => {
605
+ let event;
606
+ if (action === "artifactRevisionStage") {
607
+ event = info.ok ? "artifact_revision.validated" : "artifact_revision.rejected";
608
+ }
609
+ else if (action === "artifactRevisionPlan") {
610
+ event = info.ok ? "artifact_rerun.plan_created" : "artifact_rerun.blocked";
611
+ }
612
+ else if (state === "needs-reconcile") {
613
+ event = "artifact_rerun.needs_reconcile";
614
+ }
615
+ else {
616
+ event = info.ok ? "artifact_rerun.finished" : "artifact_rerun.failed";
617
+ }
618
+ // The stage CLI assigns the revision id; it only exists in the settle
619
+ // result, never in admission params.
620
+ let resultRevisionId;
621
+ const resultRevision = operation.result
622
+ ?.revision;
623
+ if (resultRevision && typeof resultRevision === "object") {
624
+ resultRevisionId = resultRevision.revisionId;
625
+ }
626
+ return recordContextTransferEvent({
627
+ appData: ctx.appData,
628
+ event,
629
+ fields: {
630
+ ...baseFields,
631
+ ...(typeof resultRevisionId === "string"
632
+ ? { revisionId: resultRevisionId }
633
+ : {}),
634
+ operationId: operation.operationId,
635
+ ...(info.ok ? {} : { reasonCode: info.errorCode ?? "INTERNAL_ERROR" }),
636
+ },
637
+ }).catch(() => undefined);
638
+ };
639
+ }
539
640
  async function acceptConsoleUpdateAndInit(ctx, clientRequestId, channel) {
540
641
  if (!ctx.consoleUpdateExecutor) {
541
642
  return {
@@ -1,5 +1,5 @@
1
1
  import { deriveObserveRouteCapabilities, resolveObservePackageIdentity, } from "../observe/health.js";
2
- import { repoFingerprintV1 } from "./repo-fingerprint.js";
2
+ import { repoFingerprintV1 } from "../../infrastructure/console/repo-fingerprint.js";
3
3
  export function buildOperatorSurfaceHealthV1(input) {
4
4
  const { packageName, packageVersion } = resolveObservePackageIdentity();
5
5
  const snapshotAvailable = input.routes.some((route) => route.method === "GET" && route.pattern.test("/api/snapshot"));