@dailephd/my-centcom 0.1.0 → 0.3.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.
Files changed (175) hide show
  1. package/README.md +10 -5
  2. package/apps/daemon/dist/artifacts/returnSnapshots.d.ts +12 -0
  3. package/apps/daemon/dist/artifacts/returnSnapshots.js +41 -0
  4. package/apps/daemon/dist/bootstrap/app.d.ts +21 -0
  5. package/apps/daemon/dist/bootstrap/app.js +27 -0
  6. package/apps/daemon/dist/bootstrap/installLayout.d.ts +81 -0
  7. package/apps/daemon/dist/bootstrap/installLayout.js +164 -0
  8. package/apps/daemon/dist/bootstrap/main.d.ts +14 -0
  9. package/apps/daemon/dist/bootstrap/main.js +141 -0
  10. package/apps/daemon/dist/bootstrap/operatorConsole.d.ts +75 -0
  11. package/apps/daemon/dist/bootstrap/operatorConsole.js +293 -0
  12. package/apps/daemon/dist/bootstrap/privateDataRoot.d.ts +38 -0
  13. package/apps/daemon/dist/bootstrap/privateDataRoot.js +204 -0
  14. package/apps/daemon/dist/bootstrap/secureMain.d.ts +118 -0
  15. package/apps/daemon/dist/bootstrap/secureMain.js +403 -0
  16. package/apps/daemon/dist/bootstrap/setup.d.ts +93 -0
  17. package/apps/daemon/dist/bootstrap/setup.js +738 -0
  18. package/apps/daemon/dist/context/changeProposal.d.ts +97 -0
  19. package/apps/daemon/dist/context/changeProposal.js +259 -0
  20. package/apps/daemon/dist/context/gitEvidence.d.ts +88 -0
  21. package/apps/daemon/dist/context/gitEvidence.js +332 -0
  22. package/apps/daemon/dist/context/gitObservation.d.ts +30 -0
  23. package/apps/daemon/dist/context/gitObservation.js +113 -0
  24. package/apps/daemon/dist/context/projectReadIssuer.d.ts +68 -0
  25. package/apps/daemon/dist/context/projectReadIssuer.js +158 -0
  26. package/apps/daemon/dist/context/projectReadService.d.ts +153 -0
  27. package/apps/daemon/dist/context/projectReadService.js +652 -0
  28. package/apps/daemon/dist/context/projectViewService.d.ts +85 -0
  29. package/apps/daemon/dist/context/projectViewService.js +332 -0
  30. package/apps/daemon/dist/context/proposalRecorder.d.ts +11 -0
  31. package/apps/daemon/dist/context/proposalRecorder.js +19 -0
  32. package/apps/daemon/dist/plugins/drivers/codexMcpConfig.d.ts +40 -0
  33. package/apps/daemon/dist/plugins/drivers/codexMcpConfig.js +73 -0
  34. package/apps/daemon/dist/plugins/drivers/codexModelCompatibility.d.ts +49 -0
  35. package/apps/daemon/dist/plugins/drivers/codexModelCompatibility.js +70 -0
  36. package/apps/daemon/dist/plugins/drivers/fakePluginDriver.d.ts +16 -0
  37. package/apps/daemon/dist/plugins/drivers/fakePluginDriver.js +115 -0
  38. package/apps/daemon/dist/plugins/drivers/finiteCliDriver.d.ts +153 -0
  39. package/apps/daemon/dist/plugins/drivers/finiteCliDriver.js +505 -0
  40. package/apps/daemon/dist/plugins/registry/operationCatalog.d.ts +23 -0
  41. package/apps/daemon/dist/plugins/registry/operationCatalog.js +41 -0
  42. package/apps/daemon/dist/plugins/registry/registryOperationCatalog.d.ts +14 -0
  43. package/apps/daemon/dist/plugins/registry/registryOperationCatalog.js +29 -0
  44. package/apps/daemon/dist/plugins/registry/verifiedCapabilityRegistry.d.ts +151 -0
  45. package/apps/daemon/dist/plugins/registry/verifiedCapabilityRegistry.js +579 -0
  46. package/apps/daemon/dist/projects/codingAuthority.d.ts +102 -0
  47. package/apps/daemon/dist/projects/codingAuthority.js +244 -0
  48. package/apps/daemon/dist/projects/fixtureAuthorization.d.ts +54 -0
  49. package/apps/daemon/dist/projects/fixtureAuthorization.js +172 -0
  50. package/apps/daemon/dist/projects/pairedAuthority.d.ts +158 -0
  51. package/apps/daemon/dist/projects/pairedAuthority.js +273 -0
  52. package/apps/daemon/dist/projects/trustedCliConsent.d.ts +47 -0
  53. package/apps/daemon/dist/projects/trustedCliConsent.js +84 -0
  54. package/apps/daemon/dist/runs/changeApplier.d.ts +59 -0
  55. package/apps/daemon/dist/runs/changeApplier.js +319 -0
  56. package/apps/daemon/dist/runs/codingWorkflowService.d.ts +283 -0
  57. package/apps/daemon/dist/runs/codingWorkflowService.js +785 -0
  58. package/apps/daemon/dist/runs/durableIntentCoordinator.d.ts +72 -0
  59. package/apps/daemon/dist/runs/durableIntentCoordinator.js +160 -0
  60. package/apps/daemon/dist/runs/inMemoryCoordinator.d.ts +55 -0
  61. package/apps/daemon/dist/runs/inMemoryCoordinator.js +375 -0
  62. package/apps/daemon/dist/runs/runExecutor.d.ts +154 -0
  63. package/apps/daemon/dist/runs/runExecutor.js +295 -0
  64. package/apps/daemon/dist/runs/workflowService.d.ts +185 -0
  65. package/apps/daemon/dist/runs/workflowService.js +300 -0
  66. package/apps/daemon/dist/runtime/boundedProcessHost.d.ts +111 -0
  67. package/apps/daemon/dist/runtime/boundedProcessHost.js +752 -0
  68. package/apps/daemon/dist/runtime/evidenceRedaction.d.ts +30 -0
  69. package/apps/daemon/dist/runtime/evidenceRedaction.js +79 -0
  70. package/apps/daemon/dist/runtime/executionDiagnostics.d.ts +134 -0
  71. package/apps/daemon/dist/runtime/executionDiagnostics.js +213 -0
  72. package/apps/daemon/dist/runtime/modelExecutionPolicy.d.ts +22 -0
  73. package/apps/daemon/dist/runtime/modelExecutionPolicy.js +19 -0
  74. package/apps/daemon/dist/runtime/mxcExecution.d.ts +12 -0
  75. package/apps/daemon/dist/runtime/mxcExecution.js +163 -0
  76. package/apps/daemon/dist/runtime/mxcIntegrity.d.ts +24 -0
  77. package/apps/daemon/dist/runtime/mxcIntegrity.js +81 -0
  78. package/apps/daemon/dist/runtime/mxcWorker.d.ts +2 -0
  79. package/apps/daemon/dist/runtime/mxcWorker.js +45 -0
  80. package/apps/daemon/dist/runtime/provisionedExecution.d.ts +150 -0
  81. package/apps/daemon/dist/runtime/provisionedExecution.js +653 -0
  82. package/apps/daemon/dist/runtime/testExecution.d.ts +76 -0
  83. package/apps/daemon/dist/runtime/testExecution.js +106 -0
  84. package/apps/daemon/dist/runtime/testProfiles.d.ts +10 -0
  85. package/apps/daemon/dist/runtime/testProfiles.js +4 -0
  86. package/apps/daemon/dist/runtime/trustedAgentStaging.d.ts +89 -0
  87. package/apps/daemon/dist/runtime/trustedAgentStaging.js +262 -0
  88. package/apps/daemon/dist/runtime/trustedCaBundle.d.ts +77 -0
  89. package/apps/daemon/dist/runtime/trustedCaBundle.js +125 -0
  90. package/apps/daemon/dist/runtime/windows/windowsJobSupervisor.d.ts +166 -0
  91. package/apps/daemon/dist/runtime/windows/windowsJobSupervisor.js +521 -0
  92. package/apps/daemon/dist/storage/diagnosticLog.d.ts +63 -0
  93. package/apps/daemon/dist/storage/diagnosticLog.js +136 -0
  94. package/apps/daemon/dist/storage/executionTelemetry.d.ts +63 -0
  95. package/apps/daemon/dist/storage/executionTelemetry.js +247 -0
  96. package/apps/daemon/dist/storage/protectedSecrets.d.ts +39 -0
  97. package/apps/daemon/dist/storage/protectedSecrets.js +106 -0
  98. package/apps/daemon/dist/storage/sqliteLedger.d.ts +786 -0
  99. package/apps/daemon/dist/storage/sqliteLedger.js +1303 -0
  100. package/apps/daemon/dist/transports/http/dispatch.d.ts +43 -0
  101. package/apps/daemon/dist/transports/http/dispatch.js +405 -0
  102. package/apps/daemon/dist/transports/http/secureRoutes.d.ts +40 -0
  103. package/apps/daemon/dist/transports/http/secureRoutes.js +332 -0
  104. package/apps/daemon/dist/transports/http/workflowRoutes.d.ts +41 -0
  105. package/apps/daemon/dist/transports/http/workflowRoutes.js +473 -0
  106. package/apps/daemon/dist/transports/mcp/localProjectReadServer.d.ts +182 -0
  107. package/apps/daemon/dist/transports/mcp/localProjectReadServer.js +221 -0
  108. package/apps/daemon/dist/transports/native/nativeHost.d.ts +24 -0
  109. package/apps/daemon/dist/transports/native/nativeHost.js +344 -0
  110. package/apps/daemon/package.json +24 -0
  111. package/apps/daemon/src/runtime/benign/referenceEcho.mjs +27 -0
  112. package/apps/daemon/src/runtime/windows/buildSupervisor.mjs +87 -0
  113. package/apps/daemon/src/runtime/windows/supervisorMain.cs +676 -0
  114. package/apps/extension/manifest.secure.json +25 -0
  115. package/apps/extension/scripts/build.mjs +173 -0
  116. package/apps/extension/src/background/secureWorker.ts +1595 -0
  117. package/apps/extension/src/background/serviceWorker.ts +892 -0
  118. package/apps/extension/src/content/captureSelection.ts +64 -0
  119. package/apps/extension/src/content/secureInsert.ts +207 -0
  120. package/apps/extension/src/probe/index.html +41 -0
  121. package/apps/extension/src/probe/main.ts +201 -0
  122. package/apps/extension/src/sidepanel/index.html +203 -0
  123. package/apps/extension/src/sidepanel/main.ts +903 -0
  124. package/package.json +19 -3
  125. package/packages/contracts/dist/artifacts.d.ts +66 -0
  126. package/packages/contracts/dist/artifacts.js +64 -0
  127. package/packages/contracts/dist/automation.d.ts +540 -0
  128. package/packages/contracts/dist/automation.js +191 -0
  129. package/packages/contracts/dist/browser.d.ts +251 -0
  130. package/packages/contracts/dist/browser.js +131 -0
  131. package/packages/contracts/dist/context.d.ts +71 -0
  132. package/packages/contracts/dist/context.js +73 -0
  133. package/packages/contracts/dist/diagnostics.d.ts +99 -0
  134. package/packages/contracts/dist/diagnostics.js +284 -0
  135. package/packages/contracts/dist/effects.d.ts +42 -0
  136. package/packages/contracts/dist/effects.js +42 -0
  137. package/packages/contracts/dist/errors.d.ts +75 -0
  138. package/packages/contracts/dist/errors.js +70 -0
  139. package/packages/contracts/dist/events.d.ts +50 -0
  140. package/packages/contracts/dist/events.js +34 -0
  141. package/packages/contracts/dist/executionDiagnostics.d.ts +212 -0
  142. package/packages/contracts/dist/executionDiagnostics.js +101 -0
  143. package/packages/contracts/dist/identity.d.ts +54 -0
  144. package/packages/contracts/dist/identity.js +40 -0
  145. package/packages/contracts/dist/index.d.ts +20 -0
  146. package/packages/contracts/dist/index.js +20 -0
  147. package/packages/contracts/dist/invocation.d.ts +90 -0
  148. package/packages/contracts/dist/invocation.js +77 -0
  149. package/packages/contracts/dist/lifecycle.d.ts +130 -0
  150. package/packages/contracts/dist/lifecycle.js +135 -0
  151. package/packages/contracts/dist/plugin.d.ts +214 -0
  152. package/packages/contracts/dist/plugin.js +117 -0
  153. package/packages/contracts/dist/projectRead.d.ts +205 -0
  154. package/packages/contracts/dist/projectRead.js +162 -0
  155. package/packages/contracts/dist/secure.d.ts +128 -0
  156. package/packages/contracts/dist/secure.js +99 -0
  157. package/packages/contracts/package.json +32 -0
  158. package/packages/contracts/src/artifacts.ts +83 -0
  159. package/packages/contracts/src/automation.ts +238 -0
  160. package/packages/contracts/src/browser.ts +164 -0
  161. package/packages/contracts/src/context.ts +91 -0
  162. package/packages/contracts/src/diagnostics.ts +318 -0
  163. package/packages/contracts/src/effects.ts +49 -0
  164. package/packages/contracts/src/errors.ts +83 -0
  165. package/packages/contracts/src/events.ts +46 -0
  166. package/packages/contracts/src/executionDiagnostics.ts +116 -0
  167. package/packages/contracts/src/identity.ts +68 -0
  168. package/packages/contracts/src/index.ts +20 -0
  169. package/packages/contracts/src/invocation.ts +96 -0
  170. package/packages/contracts/src/lifecycle.ts +169 -0
  171. package/packages/contracts/src/plugin.ts +174 -0
  172. package/packages/contracts/src/projectRead.ts +179 -0
  173. package/packages/contracts/src/secure.ts +136 -0
  174. package/provenance.json +179 -9
  175. package/source.zip +0 -0
@@ -0,0 +1,319 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import { PR_LIMITS, readProjectFileWhole, walkProjectPath } from '../context/projectReadService.js';
5
+ /**
6
+ * C05 TRUSTED CHANGE APPLIER (SW-080). Applies ONE already-approved, already-revalidated proposal to a run workspace. The model never holds a write tool: this runs in the daemon,
7
+ * only after C03 consumed a single-use APPLY grant, and it trusts nothing but the proposal's own bytes and the workspace on disk.
8
+ *
9
+ * Safety model:
10
+ * - WRITE-AHEAD JOURNAL in a daemon-private directory (never inside the workspace): before any mutation the journal records every operation, and a backup of every preimage is written
11
+ * there. The journal is rewritten atomically (temp + rename) around every step, so a crash always leaves a readable account of what was started.
12
+ * - Every path is re-walked with the no-link, no-alias reader at the moment of use; modify/delete/rename re-check the preimage hash; create uses an exclusive create.
13
+ * - After the last operation every touched path is read back and compared with the proposal. Any failure triggers a ROLLBACK from the backups, which is itself verified.
14
+ * - A rollback that cannot be proven complete is reported as ROLLBACK_INCOMPLETE with the affected paths. It is never retried silently and the proposal is never re-applied.
15
+ * - recover() after a crash NEVER re-applies: it rolls back from the journal (restoring preimages is idempotent) and reports the outcome.
16
+ */
17
+ const sha = (b) => createHash('sha256').update(b).digest('hex');
18
+ class AtomicWriteError extends Error {
19
+ evidence;
20
+ constructor(stage, file, cause) {
21
+ const e = cause;
22
+ super('ATOMIC_' + stage + '_' + (e.code ?? 'UNKNOWN'));
23
+ this.evidence = { stage, code: String(e.code ?? 'UNKNOWN').slice(0, 40), syscall: String(e.syscall ?? 'UNKNOWN').slice(0, 40), ...(typeof e.errno === 'number' ? { errno: e.errno } : {}), targetSha256: sha(file) };
24
+ }
25
+ }
26
+ export function persistenceFailure(e) { return e instanceof AtomicWriteError ? e.evidence : undefined; }
27
+ /** Thrown by fault injection to emulate a process death: the applier deliberately does NOT clean up after it, exactly like a killed process. */
28
+ export class SimulatedCrash extends Error {
29
+ at;
30
+ constructor(at) {
31
+ super('SIMULATED_CRASH ' + at);
32
+ this.at = at;
33
+ }
34
+ }
35
+ const segsOf = (rel) => rel.split('/');
36
+ function writeAtomic(file, text, faults, kind = 'PROJECT') {
37
+ const tmp = file + '.' + randomBytes(4).toString('hex') + '.tmp';
38
+ let fd, owned = false;
39
+ const step = (stage, f) => {
40
+ try {
41
+ faults?.before?.(`${kind}_${stage}`, 0, { targetFile: file, tempFile: tmp });
42
+ return f();
43
+ }
44
+ catch (e) {
45
+ if (e instanceof SimulatedCrash)
46
+ throw e;
47
+ throw new AtomicWriteError(stage, file, e);
48
+ }
49
+ };
50
+ try {
51
+ fd = step('OPEN', () => openSync(tmp, 'wx'));
52
+ owned = true;
53
+ step('WRITE', () => writeFileSync(fd, text));
54
+ step('FLUSH', () => fsyncSync(fd));
55
+ step('CLOSE', () => closeSync(fd));
56
+ fd = undefined;
57
+ // Windows readers/scanners may temporarily deny delete sharing. Retry only
58
+ // that bounded replacement failure, keeping the flushed temp and old target;
59
+ // never unlink the target or re-run an operation. Persistent denial fails.
60
+ for (let attempt = 0;; attempt += 1) {
61
+ try {
62
+ step('REPLACE', () => renameSync(tmp, file));
63
+ break;
64
+ }
65
+ catch (e) {
66
+ const code = persistenceFailure(e)?.code;
67
+ if (process.platform !== 'win32' || !['EPERM', 'EACCES', 'EBUSY'].includes(code ?? '') || attempt >= 5)
68
+ throw e;
69
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, [10, 20, 40, 80, 100][attempt]);
70
+ }
71
+ }
72
+ }
73
+ finally {
74
+ if (fd !== undefined) {
75
+ try {
76
+ closeSync(fd);
77
+ }
78
+ catch { /* original failure remains authoritative */ }
79
+ }
80
+ if (owned && existsSync(tmp)) {
81
+ try {
82
+ unlinkSync(tmp);
83
+ }
84
+ catch { /* only our exclusive temp; recovery trusts journal.json, not temps */ }
85
+ }
86
+ }
87
+ }
88
+ const journalFile = (dir) => join(dir, 'journal.json');
89
+ function readState(root, rel) {
90
+ const n = walkProjectPath(root, segsOf(rel), 'file');
91
+ if (!n.ok)
92
+ return n.code === 'PATH_NOT_FOUND' ? { exists: false } : { exists: 'UNSAFE', code: n.code };
93
+ const w = readProjectFileWhole(n.value, root, segsOf(rel), PR_LIMITS.maxFileBytes);
94
+ return w.ok ? { exists: true, sha256: sha(w.value.bytes), bytes: w.value.bytes } : { exists: 'UNSAFE', code: w.code };
95
+ }
96
+ function parentDirOk(root, rel) {
97
+ const s = segsOf(rel);
98
+ return s.length === 1 || walkProjectPath(root, s.slice(0, -1), 'directory').ok;
99
+ }
100
+ const abs = (root, rel) => join(root, ...segsOf(rel));
101
+ function persist(dir, j, faults) { const f = journalFile(dir); writeAtomic(f, JSON.stringify(j), faults, 'JOURNAL'); }
102
+ /** Restores every started operation in reverse order, then PROVES the restoration. */
103
+ function rollback(root, dir, j, faults) {
104
+ const bad = [];
105
+ for (const o of [...j.ops].reverse()) {
106
+ if (!o.started)
107
+ continue;
108
+ try {
109
+ if (o.op === 'create') {
110
+ const cur = readState(root, o.path);
111
+ if (cur.exists === true) {
112
+ if (cur.sha256 === o.expectedSha256)
113
+ unlinkSync(abs(root, o.path));
114
+ else
115
+ bad.push(o.path);
116
+ } // never delete something we did not write
117
+ else if (cur.exists === 'UNSAFE')
118
+ bad.push(o.path);
119
+ }
120
+ else if (o.op === 'modify' || o.op === 'delete') {
121
+ const pre = readFileSync(join(dir, o.backup));
122
+ if (sha(pre) !== o.preimageSha256) {
123
+ bad.push(o.path);
124
+ continue;
125
+ }
126
+ const cur = readState(root, o.path);
127
+ if (cur.exists === 'UNSAFE') {
128
+ bad.push(o.path);
129
+ continue;
130
+ }
131
+ if (cur.exists === true && cur.sha256 === o.preimageSha256)
132
+ continue; // already original
133
+ if (o.op === 'modify') {
134
+ if (cur.exists !== true || cur.sha256 === o.expectedSha256)
135
+ writeAtomic(abs(root, o.path), pre, faults);
136
+ else
137
+ bad.push(o.path);
138
+ }
139
+ else if (cur.exists === false)
140
+ writeFileSync(abs(root, o.path), pre, { flag: 'wx' });
141
+ else
142
+ bad.push(o.path);
143
+ }
144
+ else {
145
+ const from = readState(root, o.path);
146
+ const to = readState(root, o.to);
147
+ if (from.exists === false && to.exists === true && to.sha256 === o.preimageSha256)
148
+ renameSync(abs(root, o.to), abs(root, o.path));
149
+ else if (!(from.exists === true && from.sha256 === o.preimageSha256 && to.exists === false))
150
+ bad.push(o.path);
151
+ }
152
+ }
153
+ catch {
154
+ bad.push(o.path);
155
+ }
156
+ }
157
+ // proof: every touched path is back to its preimage state
158
+ for (const o of j.ops) {
159
+ if (!o.started)
160
+ continue;
161
+ const check = (rel, want) => { const c = readState(root, rel); const ok = want === null ? c.exists === false : c.exists === true && c.sha256 === want; if (!ok && !bad.includes(rel))
162
+ bad.push(rel); };
163
+ if (o.op === 'create')
164
+ check(o.path, null);
165
+ else if (o.op === 'rename') {
166
+ check(o.path, o.preimageSha256);
167
+ check(o.to, null);
168
+ }
169
+ else
170
+ check(o.path, o.preimageSha256);
171
+ }
172
+ const state = bad.length === 0 ? 'ROLLED_BACK' : 'ROLLBACK_INCOMPLETE';
173
+ j.state = state;
174
+ j.unrestored = [...new Set(bad)];
175
+ try {
176
+ persist(dir, j, faults);
177
+ }
178
+ catch (e) {
179
+ return { state: 'ROLLBACK_INCOMPLETE', unrestored: [...new Set([...bad, 'journal durability unverified'])], ...(persistenceFailure(e) ? { ioFailure: persistenceFailure(e) } : {}) };
180
+ }
181
+ return { state, unrestored: [...new Set(bad)] };
182
+ }
183
+ export function applyProposal(i) {
184
+ const { workspaceRoot: root, journalDir: dir, proposal } = i;
185
+ const F = i.faults;
186
+ if (existsSync(journalFile(dir)))
187
+ return { ok: false, code: 'JOURNAL_EXISTS', state: 'NOT_STARTED', detail: 'a journal already exists for this proposal; it is never re-applied', unrestored: [] };
188
+ // Reserve the whole journal directory atomically, including create-only
189
+ // proposals with no preimage backup to accidentally act as a lock.
190
+ mkdirSync(dirname(dir), { recursive: true });
191
+ try {
192
+ mkdirSync(dir);
193
+ }
194
+ catch (e) {
195
+ if (e.code === 'EEXIST')
196
+ return { ok: false, code: 'JOURNAL_EXISTS', state: 'NOT_STARTED', detail: 'journal directory already reserved; never overwritten or re-applied', unrestored: [] };
197
+ throw e;
198
+ }
199
+ const j = { schema: 'my-centcom.apply-journal/1', proposalId: i.proposalId, proposalDigest: i.proposalDigest, state: 'PREPARED', ops: [] };
200
+ // ---- prepare: validate every operation against the workspace NOW and back up every preimage, before the first mutation ----
201
+ for (let k = 0; k < proposal.operations.length; k += 1) {
202
+ const o = proposal.operations[k];
203
+ const op = { index: k, op: o.op, path: o.path, ...(o.to ? { to: o.to } : {}), ...(o.preimageSha256 ? { preimageSha256: o.preimageSha256 } : {}), ...(o.contentSha256 ? { expectedSha256: o.contentSha256 } : {}), started: false, done: false };
204
+ if (o.op !== 'create') {
205
+ const cur = readState(root, o.path);
206
+ if (cur.exists !== true || cur.sha256 !== o.preimageSha256)
207
+ return { ok: false, code: 'PREIMAGE_CHANGED', state: 'NOT_STARTED', detail: `operation ${k}: the file is not in the approved state`, unrestored: [] };
208
+ if (o.op !== 'rename') {
209
+ op.backup = `b${k}.bin`;
210
+ writeFileSync(join(dir, op.backup), cur.bytes, { flag: 'wx', flush: true });
211
+ }
212
+ }
213
+ else {
214
+ const cur = readState(root, o.path);
215
+ if (cur.exists !== false || !parentDirOk(root, o.path))
216
+ return { ok: false, code: 'TARGET_NOT_FREE', state: 'NOT_STARTED', detail: `operation ${k}: the create target is not free`, unrestored: [] };
217
+ }
218
+ if (o.op === 'rename') {
219
+ const t = readState(root, o.to);
220
+ if (t.exists !== false || !parentDirOk(root, o.to))
221
+ return { ok: false, code: 'TARGET_NOT_FREE', state: 'NOT_STARTED', detail: `operation ${k}: the rename target is not free`, unrestored: [] };
222
+ }
223
+ j.ops.push(op);
224
+ }
225
+ persist(dir, j, F);
226
+ j.state = 'APPLYING';
227
+ persist(dir, j, F);
228
+ const fail = (code, detail) => { const r = rollback(root, dir, j, F); return { ok: false, code, state: r.state, detail, unrestored: r.unrestored, ...(r.ioFailure ? { rollbackIoFailure: r.ioFailure } : {}) }; };
229
+ try {
230
+ for (let k = 0; k < proposal.operations.length; k += 1) {
231
+ const o = proposal.operations[k];
232
+ const jo = j.ops[k];
233
+ F?.before?.('BEFORE_OP', k);
234
+ const injected = F?.failWith?.('OP', k);
235
+ if (injected)
236
+ throw new Error(injected);
237
+ jo.started = true;
238
+ persist(dir, j, F); // started is durable BEFORE the mutation: a crash mid-operation is therefore always covered by rollback
239
+ F?.before?.('AFTER_START', k);
240
+ if (o.op === 'create') {
241
+ if (!parentDirOk(root, o.path))
242
+ return fail('PARENT_CHANGED', `operation ${k}`);
243
+ writeFileSync(abs(root, o.path), o.content, { flag: 'wx' });
244
+ }
245
+ else if (o.op === 'modify') {
246
+ const cur = readState(root, o.path);
247
+ if (cur.exists !== true || cur.sha256 !== o.preimageSha256)
248
+ return fail('PREIMAGE_CHANGED', `operation ${k}`);
249
+ writeAtomic(abs(root, o.path), o.content, F);
250
+ }
251
+ else if (o.op === 'delete') {
252
+ const cur = readState(root, o.path);
253
+ if (cur.exists !== true || cur.sha256 !== o.preimageSha256)
254
+ return fail('PREIMAGE_CHANGED', `operation ${k}`);
255
+ unlinkSync(abs(root, o.path));
256
+ }
257
+ else {
258
+ const cur = readState(root, o.path);
259
+ const t = readState(root, o.to);
260
+ if (cur.exists !== true || cur.sha256 !== o.preimageSha256 || t.exists !== false)
261
+ return fail('PREIMAGE_CHANGED', `operation ${k}`);
262
+ renameSync(abs(root, o.path), abs(root, o.to));
263
+ }
264
+ jo.done = true;
265
+ persist(dir, j, F);
266
+ F?.before?.('AFTER_OP', k);
267
+ }
268
+ // ---- verify: read every touched path back against the proposal ----
269
+ const changed = [];
270
+ for (const o of proposal.operations) {
271
+ if (o.op === 'create' || o.op === 'modify') {
272
+ const c = readState(root, o.path);
273
+ if (c.exists !== true || c.sha256 !== o.contentSha256)
274
+ return fail('VERIFY_FAILED', `${o.path} does not hold the approved bytes`);
275
+ changed.push({ path: o.path, sha256: o.contentSha256 });
276
+ }
277
+ else if (o.op === 'delete') {
278
+ if (readState(root, o.path).exists !== false)
279
+ return fail('VERIFY_FAILED', `${o.path} still exists`);
280
+ changed.push({ path: o.path, sha256: null });
281
+ }
282
+ else {
283
+ const a = readState(root, o.path);
284
+ const b = readState(root, o.to);
285
+ if (a.exists !== false || b.exists !== true || b.sha256 !== o.preimageSha256)
286
+ return fail('VERIFY_FAILED', `${o.path} was not renamed intact`);
287
+ changed.push({ path: o.path, sha256: null }, { path: o.to, sha256: b.sha256 });
288
+ }
289
+ }
290
+ j.state = 'APPLIED';
291
+ persist(dir, j, F);
292
+ return { ok: true, state: 'APPLIED', changed };
293
+ }
294
+ catch (e) {
295
+ if (e instanceof SimulatedCrash)
296
+ throw e; // a dead process cleans nothing up
297
+ return { ...fail('APPLY_FAILED', String(e.message).slice(0, 160)), ...(e instanceof AtomicWriteError ? { ioFailure: e.evidence } : {}) };
298
+ }
299
+ }
300
+ /** After a daemon crash: an unfinished journal is rolled back (never re-applied) and the outcome is reported. A finished journal is reported as it is. */
301
+ export function recoverJournal(i) {
302
+ const f = journalFile(i.journalDir);
303
+ if (!existsSync(f))
304
+ return existsSync(i.journalDir) ? { found: true, state: 'ROLLBACK_INCOMPLETE', unrestored: ['journal missing'] } : { found: false };
305
+ let j;
306
+ try {
307
+ j = JSON.parse(readFileSync(f, 'utf8'));
308
+ }
309
+ catch {
310
+ return { found: true, priorState: 'ROLLBACK_INCOMPLETE', state: 'ROLLBACK_INCOMPLETE', unrestored: ['journal unreadable'] };
311
+ }
312
+ if (j.state === 'APPLIED' || j.state === 'ROLLED_BACK' || j.state === 'ROLLBACK_INCOMPLETE')
313
+ return { found: true, priorState: j.state, state: j.state, unrestored: j.unrestored ?? [] };
314
+ const prior = j.state;
315
+ const r = rollback(i.workspaceRoot, i.journalDir, j);
316
+ return { found: true, priorState: prior, state: r.state, unrestored: r.unrestored };
317
+ }
318
+ export const __journalFileForTests = journalFile;
319
+ //# sourceMappingURL=changeApplier.js.map
@@ -0,0 +1,283 @@
1
+ import { type CodingResultRow, type SqliteLedger } from '../storage/sqliteLedger.js';
2
+ import type { CodingAuthority, CodingDenied } from '../projects/codingAuthority.js';
3
+ import type { GitEvidence, GitEvidenceService } from '../context/gitEvidence.js';
4
+ import { type ApplyFaults } from './changeApplier.js';
5
+ import { type TestExecutor } from '../runtime/testExecution.js';
6
+ import type { ExecutionTelemetry } from '../storage/executionTelemetry.js';
7
+ import { type TrustedCliConsent } from '../projects/trustedCliConsent.js';
8
+ /**
9
+ * C05 CODING WORKFLOW (SW-080). The single trusted orchestration of:
10
+ * ingest proposal -> approve -> apply -> test -> verify Git evidence -> (separately authorized) commit -> immutable verified result.
11
+ *
12
+ * It owns no storage (C09 ledger tables), no authorization rules (C03 CodingAuthority), no process creation (C06 test executor), no Git commands (C07 git evidence) and no file
13
+ * mechanics (the applier). It composes them and enforces the ORDER: every step names the exact lifecycle state it needs, consumes the matching authority, and writes durable evidence.
14
+ *
15
+ * The model's role ends at a proposal. Nothing here believes the model: proposals are re-validated against the live project, applied only by this service after a person's approval
16
+ * of the exact digest, tested only through a reviewed profile, and judged only from independently observed Git state and the test runner's own summary.
17
+ *
18
+ * The original project is never modified: every change is applied to a run workspace (a clone) and the verified result is a commit THERE. Promoting that commit into the original
19
+ * project is a further, separately authorized capability that this task deliberately does not implement.
20
+ */
21
+ export interface CodingWorkflowDeps {
22
+ ledger: SqliteLedger;
23
+ authority: CodingAuthority;
24
+ trustedCliConsent?: TrustedCliConsent;
25
+ git: GitEvidenceService;
26
+ tests: TestExecutor;
27
+ telemetry?: ExecutionTelemetry;
28
+ /** Run workspaces (clones) live under this task-owned directory. */
29
+ workspacesRoot: string;
30
+ /** Apply journals and backups: daemon-private, never inside a workspace. */
31
+ journalsRoot: string;
32
+ /** Per-test-run TEMP directories (the only location the test identity can write). */
33
+ testTempRoot: string;
34
+ /** Explicit offline-only exception for synthetic repositories under a reviewed scratch root. Production has no test authority until per-run filesystem isolation is verified. */
35
+ offlineDisposableProjectsRoot?: string;
36
+ offlineDisposableRunAllowed?: (runId: string) => boolean;
37
+ /** Grants the restricted identity its access. Default: read-only workspace + one writable TEMP (icacls). Tests may inject a stub for platforms without it. */
38
+ prepareAccess?: (i: {
39
+ workspaceRoot: string;
40
+ tempDir: string;
41
+ }) => void;
42
+ now?: () => number;
43
+ }
44
+ export type Step<T = object> = ({
45
+ readonly ok: true;
46
+ } & T) | {
47
+ readonly ok: false;
48
+ readonly code: string;
49
+ readonly detail?: string;
50
+ };
51
+ export interface IngestItem {
52
+ readonly file: string;
53
+ readonly ok: boolean;
54
+ readonly proposalId?: string;
55
+ readonly digest?: string;
56
+ readonly code?: string;
57
+ }
58
+ export interface ApprovalView {
59
+ readonly executionMode: 'STRICT_ISOLATED' | 'TRUSTED_LOCAL_CLI_PROPOSAL_ONLY';
60
+ readonly testExecutionAvailable: boolean;
61
+ readonly diff: string;
62
+ readonly target: string;
63
+ readonly preimagesValid: boolean;
64
+ readonly proposalId: string;
65
+ readonly runId: string;
66
+ readonly digest: string;
67
+ readonly baseHead: string;
68
+ readonly status: string;
69
+ readonly summary: string;
70
+ readonly effect: unknown;
71
+ readonly operations: readonly {
72
+ op: string;
73
+ path: string;
74
+ to?: string;
75
+ preimageSha256?: string;
76
+ contentSha256?: string;
77
+ contentBytes: number;
78
+ content?: string;
79
+ }[];
80
+ }
81
+ export declare class CodingWorkflowService {
82
+ get trustedCliConsent(): TrustedCliConsent | undefined;
83
+ close(): Promise<void>;
84
+ private readonly d;
85
+ private readonly now;
86
+ constructor(d: CodingWorkflowDeps);
87
+ private iso;
88
+ private ev;
89
+ private own;
90
+ private proposalOf;
91
+ private paths;
92
+ private liveRoot;
93
+ private lastEvent;
94
+ private deny;
95
+ private sealed;
96
+ private testBoundaryAllows;
97
+ /**
98
+ * Imports the proposals the MCP adapter recorded for a run. Each envelope is UNTRUSTED data: it must be named by the fixed pattern, belong to this run and project, be bound by an
99
+ * ALLOWED propose_change record in the intact audit chain with the same digest, and re-validate against the LIVE project (which must be clean at its recorded HEAD).
100
+ */
101
+ ingestProposals(i: {
102
+ principalId: string;
103
+ projectId: string;
104
+ runId: string;
105
+ proposalsDir: string;
106
+ capabilityId: string;
107
+ auditText: string;
108
+ }): Step<{
109
+ items: readonly IngestItem[];
110
+ }>;
111
+ /** The exact content a person reviews. Everything is derived from the stored canonical proposal, never from the model's description. */
112
+ describeForApproval(principalId: string, proposalId: string): ApprovalView | undefined;
113
+ /** ONE approval of ONE exact digest. Approval authorizes APPLY only; TEST, GIT_READ and COMMIT each require their own trusted action. */
114
+ approve(i: {
115
+ principalId: string;
116
+ proposalId: string;
117
+ shownDigest: string;
118
+ }): Step<{
119
+ grants: {
120
+ apply: string;
121
+ };
122
+ }>;
123
+ /** A separate deliberate action authorizes one fixed reviewed profile after apply. */
124
+ authorizeTest(i: {
125
+ principalId: string;
126
+ proposalId: string;
127
+ profileId: string;
128
+ }): Step<{
129
+ grantId: string;
130
+ }>;
131
+ /** Git evidence is separately authorized and read only. */
132
+ authorizeGitRead(i: {
133
+ principalId: string;
134
+ proposalId: string;
135
+ }): Step<{
136
+ grantId: string;
137
+ }>;
138
+ reject(principalId: string, proposalId: string): Step;
139
+ apply(i: {
140
+ principalId: string;
141
+ proposalId: string;
142
+ faults?: ApplyFaults;
143
+ }): Step<{
144
+ state: string;
145
+ changed: readonly {
146
+ path: string;
147
+ sha256: string | null;
148
+ }[];
149
+ }> | {
150
+ ok: false;
151
+ code: string;
152
+ state: string;
153
+ unrestored: readonly string[];
154
+ detail?: string;
155
+ };
156
+ test(i: {
157
+ principalId: string;
158
+ proposalId: string;
159
+ profileId: string;
160
+ expectedMinTests: number;
161
+ }): Promise<Step<{
162
+ passed: boolean;
163
+ reasons: readonly string[];
164
+ summary: unknown;
165
+ treeSha256: string;
166
+ testRunId: string;
167
+ }>>;
168
+ verify(i: {
169
+ principalId: string;
170
+ proposalId: string;
171
+ }): Step<{
172
+ evidence: GitEvidence;
173
+ }>;
174
+ /** The explicit act of a person: authorizes ONE commit of this exact proposal. Without it, commit() cannot run, whatever a model asked for. */
175
+ authorizeCommit(i: {
176
+ principalId: string;
177
+ proposalId: string;
178
+ }): Step<{
179
+ grantId: string;
180
+ }>;
181
+ commit(i: {
182
+ principalId: string;
183
+ proposalId: string;
184
+ }): Step<{
185
+ commit: string;
186
+ parent: string;
187
+ files: readonly string[];
188
+ }>;
189
+ /** Builds the raw summary ONLY from trusted records and stores it once. No sentence in it comes from the model. */
190
+ finalize(i: {
191
+ principalId: string;
192
+ proposalId: string;
193
+ }): Step<{
194
+ result: CodingResultRow;
195
+ }>;
196
+ /** The exact stored bytes, and only to the owner. */
197
+ copyResult(principalId: string, proposalId: string): CodingResultRow | undefined;
198
+ copyProposal(principalId: string, proposalId: string): CodingResultRow | undefined;
199
+ copyAppliedResult(principalId: string, proposalId: string): CodingResultRow | undefined;
200
+ copyCommittedResult(principalId: string, proposalId: string): CodingResultRow | undefined;
201
+ commitReview(principalId: string, origin: string, proposalId: string, message: string): {
202
+ challenge: string;
203
+ binding: string;
204
+ projectId: string;
205
+ target: string;
206
+ parent: string;
207
+ branch: string;
208
+ message: string;
209
+ identity: string;
210
+ };
211
+ reviewedCommit(i: {
212
+ principalId: string;
213
+ origin: string;
214
+ proposalId: string;
215
+ message: string;
216
+ challenge: string;
217
+ }): {
218
+ readonly ok: false;
219
+ readonly code: CodingDenied;
220
+ } | {
221
+ ok: false;
222
+ code: string;
223
+ detail?: string;
224
+ } | {
225
+ ok: boolean;
226
+ result: CodingResultRow;
227
+ } | {
228
+ ok: boolean;
229
+ result: CodingResultRow;
230
+ duplicate: boolean;
231
+ };
232
+ private sealCommitted;
233
+ recoverReviewedCommits(): void;
234
+ /** A subsequent, non-model transaction. It never changes the model run's authorities or immutable proposal delivery. */
235
+ reviewedPatchView(principalId: string, origin: string, proposalId: string): {
236
+ state: string;
237
+ eligible: boolean;
238
+ result: CodingResultRow | null;
239
+ projectId: string;
240
+ target: string;
241
+ baseHead: string;
242
+ digest: string;
243
+ reviewKey: string;
244
+ challenge: string;
245
+ expiresAt: number;
246
+ authorities: readonly ["APPLY", "GIT_READ"];
247
+ } | undefined;
248
+ reviewedApply(i: {
249
+ principalId: string;
250
+ origin: string;
251
+ proposalId: string;
252
+ projectId: string;
253
+ digest: string;
254
+ baseHead: string;
255
+ challenge: string;
256
+ action: 'apply' | 'cancel';
257
+ faults?: ApplyFaults;
258
+ }): Step<{
259
+ state: string;
260
+ result?: CodingResultRow;
261
+ duplicate?: boolean;
262
+ }>;
263
+ recoverReviewedPatches(): void;
264
+ /** A terminal, immutable proposal snapshot. No apply/test/Git/commit authority
265
+ * is issued, consumed or inferred from copying it. */
266
+ finalizeProposal(i: {
267
+ principalId: string;
268
+ proposalId: string;
269
+ shownDigest: string;
270
+ }): Step<{
271
+ result: CodingResultRow;
272
+ }>;
273
+ /** Transport preflight: rejected requests cannot reserve a later legitimate effect. Lifecycle guards remain independently enforced by each operation. */
274
+ actionReady(principalId: string, proposalId: string, action: string): boolean;
275
+ /** After a daemon restart: every proposal left APPLYING is rolled back from its journal (never re-applied) and moved to a terminal state that says what is true. */
276
+ recover(proposalIds: readonly string[]): {
277
+ proposalId: string;
278
+ found: boolean;
279
+ state?: string;
280
+ unrestored?: readonly string[];
281
+ }[];
282
+ }
283
+ //# sourceMappingURL=codingWorkflowService.d.ts.map