@dailephd/my-centcom 0.2.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,785 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs';
3
+ import { join, relative, isAbsolute, sep } from 'node:path';
4
+ import { sha256Hex } from '../storage/sqliteLedger.js';
5
+ import { revalidateStored, hydrateStored } from '../context/changeProposal.js';
6
+ import { assessProjectReadAudit, walkProjectPath, readProjectFileWhole, PR_LIMITS } from '../context/projectReadService.js';
7
+ import { applyProposal, recoverJournal, persistenceFailure } from './changeApplier.js';
8
+ import { prepareRestrictedAccess } from '../runtime/testExecution.js';
9
+ import { assertValidLifecycleTransition } from '../../../../packages/contracts/dist/index.js';
10
+ import { isTrustedProposalRun } from '../projects/trustedCliConsent.js';
11
+ const b64 = (n) => randomBytes(n).toString('base64url');
12
+ const sha = (s) => createHash('sha256').update(s).digest('hex');
13
+ const ENVELOPE = /^cap\.[A-Za-z0-9_-]{16,64}\.[a-f0-9]{16}\.proposal\.json$/;
14
+ export class CodingWorkflowService {
15
+ get trustedCliConsent() { return this.d.trustedCliConsent; }
16
+ async close() { await this.d.tests.close(); }
17
+ d;
18
+ now;
19
+ constructor(d) { this.d = d; this.now = d.now ?? Date.now; }
20
+ iso() { return new Date(this.now()).toISOString(); }
21
+ ev(p, kind, event, decision, detail) {
22
+ this.d.ledger.appendCodingEvent({ at: this.iso(), runId: p.runId, subjectKind: kind, subjectId: p.proposalId, event, decision, detail });
23
+ }
24
+ own(principalId, proposalId) {
25
+ const p = this.d.ledger.getCodingProposal(proposalId);
26
+ return p && p.principalId === principalId && this.d.ledger.getRunOwnerPrincipalId(p.runId) === principalId ? p : undefined;
27
+ }
28
+ proposalOf(p) { return hydrateStored(p.canonicalJson); }
29
+ paths(proposalId) { return { ws: join(this.d.workspacesRoot, proposalId, 'ws'), journal: join(this.d.journalsRoot, proposalId) }; }
30
+ liveRoot(projectId) { return this.d.ledger.getProjectRoot(projectId); }
31
+ lastEvent(proposalId, kind, event) {
32
+ return this.d.ledger.readCodingEvents({ subjectId: proposalId }).filter((e) => e.subjectKind === kind && e.event === event).pop();
33
+ }
34
+ deny(code, detail) { return { ok: false, code, ...(detail ? { detail } : {}) }; }
35
+ sealed(principalId, proposalId) { return this.d.ledger.hasCodingResult(principalId, proposalId); }
36
+ testBoundaryAllows(p) {
37
+ const scope = this.d.offlineDisposableProjectsRoot, project = this.liveRoot(p.projectId);
38
+ if (!scope || !project || this.d.offlineDisposableRunAllowed?.(p.runId) !== true)
39
+ return false;
40
+ try {
41
+ const r = relative(realpathSync.native(scope), realpathSync.native(project));
42
+ return r !== '' && r !== '..' && !r.startsWith('..' + sep) && !isAbsolute(r);
43
+ }
44
+ catch {
45
+ return false;
46
+ }
47
+ }
48
+ // ---- 1. ingest -------------------------------------------------------------------------------------------------------------------------------
49
+ /**
50
+ * 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
51
+ * 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).
52
+ */
53
+ ingestProposals(i) {
54
+ const auth = this.d.authority.authorize({ principalId: i.principalId, projectId: i.projectId, runId: i.runId, operation: 'PROPOSE' });
55
+ if (!auth.ok)
56
+ return this.deny(auth.code);
57
+ const audit = assessProjectReadAudit({ auditText: i.auditText, capabilityId: i.capabilityId });
58
+ if (!audit.chainIntact)
59
+ return this.deny('AUDIT_UNTRUSTED');
60
+ const audited = new Set();
61
+ for (const line of i.auditText.split('\n')) {
62
+ if (!line)
63
+ continue;
64
+ try {
65
+ const r = JSON.parse(line);
66
+ if (r.event === 'TOOL_CALL' && r.tool === 'propose_change' && r.decision === 'ALLOWED' && typeof r.returnedSha256 === 'string')
67
+ audited.add(r.returnedSha256);
68
+ }
69
+ catch {
70
+ return this.deny('AUDIT_UNTRUSTED');
71
+ }
72
+ }
73
+ const root = this.liveRoot(i.projectId);
74
+ if (!root)
75
+ return this.deny('PROJECT_UNKNOWN');
76
+ const items = [];
77
+ const files = existsSync(i.proposalsDir) ? readdirSync(i.proposalsDir).filter((f) => f.startsWith(i.capabilityId + '.')).sort().slice(0, 10) : [];
78
+ for (const file of files) {
79
+ const refuse = (code) => { items.push({ file, ok: false, code }); this.d.ledger.appendCodingEvent({ at: this.iso(), runId: i.runId, subjectKind: 'PROPOSAL', subjectId: 'prop.none', event: 'INGEST_REFUSED', decision: 'DENIED', detail: { code, file: file.slice(0, 80) } }); };
80
+ if (!ENVELOPE.test(file)) {
81
+ refuse('ENVELOPE_NAME_INVALID');
82
+ continue;
83
+ }
84
+ let env;
85
+ try {
86
+ const full = join(i.proposalsDir, file);
87
+ if (statSync(full).size > 600_000) {
88
+ refuse('ENVELOPE_TOO_LARGE');
89
+ continue;
90
+ }
91
+ env = JSON.parse(readFileSync(full, 'utf8'));
92
+ }
93
+ catch {
94
+ refuse('ENVELOPE_UNREADABLE');
95
+ continue;
96
+ }
97
+ if (env.schema !== 'my-centcom.proposal-envelope/1' || env.runId !== i.runId || env.projectId !== i.projectId || env.capabilityId !== i.capabilityId || typeof env.canonicalJson !== 'string' || typeof env.digest !== 'string' || sha(env.canonicalJson) !== env.digest) {
98
+ refuse('ENVELOPE_INVALID');
99
+ continue;
100
+ }
101
+ if (!audited.has(env.digest)) {
102
+ refuse('NOT_IN_AUDIT');
103
+ continue;
104
+ }
105
+ const st = this.d.git.statusOf(root);
106
+ if (!st.ok || st.entries.length > 0) {
107
+ refuse('PROJECT_NOT_CLEAN');
108
+ continue;
109
+ }
110
+ const head = this.d.git.headOf(root);
111
+ if (!head) {
112
+ refuse('HEAD_UNKNOWN');
113
+ continue;
114
+ }
115
+ const v = revalidateStored(env.canonicalJson, { root });
116
+ if (!v.ok) {
117
+ refuse(String(v.code));
118
+ continue;
119
+ }
120
+ const proposalId = `prop.${b64(18)}`;
121
+ const ins = this.d.ledger.insertCodingProposal({ proposalId, runId: i.runId, projectId: i.projectId, principalId: i.principalId, digest: v.digest, baseHead: head, canonicalJson: v.canonicalJson, effectJson: JSON.stringify(v.effect), createdAtIso: this.iso() });
122
+ if (ins === 'DUPLICATE') {
123
+ refuse('DUPLICATE_PROPOSAL');
124
+ continue;
125
+ }
126
+ this.d.ledger.appendCodingEvent({ at: this.iso(), runId: i.runId, subjectKind: 'PROPOSAL', subjectId: proposalId, event: 'PROPOSAL_INGESTED', decision: 'ALLOWED', detail: { operations: v.effect.operations, destructive: v.effect.destructive, baseHead: head.slice(0, 12) } });
127
+ items.push({ file, ok: true, proposalId, digest: v.digest });
128
+ }
129
+ return { ok: true, items };
130
+ }
131
+ // ---- 2. approval -----------------------------------------------------------------------------------------------------------------------------
132
+ /** The exact content a person reviews. Everything is derived from the stored canonical proposal, never from the model's description. */
133
+ describeForApproval(principalId, proposalId) {
134
+ const p = this.own(principalId, proposalId);
135
+ if (!p)
136
+ return undefined;
137
+ const prop = this.proposalOf(p);
138
+ const root = this.liveRoot(p.projectId);
139
+ let valid = root !== undefined && revalidateStored(p.canonicalJson, { root }).ok;
140
+ const diff = valid ? prop.operations.map((o) => {
141
+ let before = '';
142
+ if (o.op !== 'create') {
143
+ const segs = o.path.split('/');
144
+ const node = walkProjectPath(root, segs, 'file');
145
+ const file = node.ok ? readProjectFileWhole(node.value, root, segs, PR_LIMITS.maxFileBytes) : undefined;
146
+ if (!file?.ok || sha(file.value.bytes.toString('utf8')) !== o.preimageSha256) {
147
+ valid = false;
148
+ return 'Preimage changed during review.';
149
+ }
150
+ before = file.value.bytes.toString('utf8');
151
+ }
152
+ const after = o.op === 'delete' ? '' : o.op === 'rename' ? before : o.content ?? '';
153
+ const lines = (s) => s === '' ? [] : s.replace(/\n$/, '').split('\n');
154
+ return [`--- ${o.op === 'create' ? '/dev/null' : 'a/' + o.path}`, `+++ ${o.op === 'delete' ? '/dev/null' : 'b/' + (o.to ?? o.path)}`, `@@ -1,${lines(before).length} +1,${lines(after).length} @@`, ...lines(before).map((s) => '-' + s), ...lines(after).map((s) => '+' + s)].join('\n');
155
+ }).join('\n') : 'Preimages changed; this proposal cannot be applied.';
156
+ return { executionMode: isTrustedProposalRun(this.d.ledger, p.runId) ? 'TRUSTED_LOCAL_CLI_PROPOSAL_ONLY' : 'STRICT_ISOLATED', testExecutionAvailable: !isTrustedProposalRun(this.d.ledger, p.runId) && this.testBoundaryAllows(p), diff, target: this.paths(p.proposalId).ws, preimagesValid: valid, proposalId: p.proposalId, runId: p.runId, digest: p.digest, baseHead: p.baseHead, status: this.copyProposal(principalId, proposalId) ? 'PROPOSAL_ONLY_UNVERIFIED' : p.status, summary: prop.summary, effect: JSON.parse(p.effectJson),
157
+ operations: prop.operations.map((o) => ({ op: o.op, path: o.path, ...(o.to ? { to: o.to } : {}), ...(o.preimageSha256 ? { preimageSha256: o.preimageSha256 } : {}), ...(o.contentSha256 ? { contentSha256: o.contentSha256 } : {}), contentBytes: o.contentBytes, ...(o.content !== undefined ? { content: o.content } : {}) })) };
158
+ }
159
+ /** ONE approval of ONE exact digest. Approval authorizes APPLY only; TEST, GIT_READ and COMMIT each require their own trusted action. */
160
+ approve(i) {
161
+ const p = this.own(i.principalId, i.proposalId);
162
+ if (!p)
163
+ return this.deny('PROPOSAL_UNKNOWN');
164
+ if (isTrustedProposalRun(this.d.ledger, p.runId))
165
+ return this.deny('PROPOSAL_ONLY_MODE');
166
+ if (this.sealed(i.principalId, i.proposalId))
167
+ return this.deny('RESULT_SEALED');
168
+ if (p.status !== 'SUBMITTED')
169
+ return this.deny('NOT_PENDING', p.status);
170
+ if (i.shownDigest !== p.digest) {
171
+ this.ev(p, 'PROPOSAL', 'APPROVAL_REFUSED', 'DENIED', { code: 'DIGEST_MISMATCH' });
172
+ return this.deny('DIGEST_MISMATCH');
173
+ }
174
+ const liveAuthority = this.d.authority.authorize({ principalId: i.principalId, projectId: p.projectId, runId: p.runId, operation: 'PROPOSE' });
175
+ if (!liveAuthority.ok)
176
+ return this.deny(liveAuthority.code);
177
+ const base = { principalId: i.principalId, projectId: p.projectId, runId: p.runId };
178
+ const apply = this.d.authority.grant({ ...base, operation: 'APPLY', scope: { proposalId: p.proposalId, digest: p.digest }, lifetimeMs: 10 * 60_000 });
179
+ const made = [apply];
180
+ if (!made.every((g) => g.ok)) {
181
+ for (const g of made)
182
+ if (g.ok)
183
+ this.d.authority.revoke(g.grantId);
184
+ return this.deny('GRANT_FAILED');
185
+ }
186
+ if (!this.d.ledger.transitionCodingProposal(p.proposalId, ['SUBMITTED'], 'APPROVED', this.iso())) {
187
+ for (const g of made)
188
+ if (g.ok)
189
+ this.d.authority.revoke(g.grantId);
190
+ return this.deny('NOT_PENDING', 'concurrent');
191
+ }
192
+ this.ev(p, 'PROPOSAL', 'APPROVED', 'ALLOWED', { digest12: p.digest.slice(0, 12), effect: 'APPLY_ONLY' });
193
+ return { ok: true, grants: { apply: apply.grantId } };
194
+ }
195
+ /** A separate deliberate action authorizes one fixed reviewed profile after apply. */
196
+ authorizeTest(i) {
197
+ const p = this.own(i.principalId, i.proposalId);
198
+ if (!p)
199
+ return this.deny('PROPOSAL_UNKNOWN');
200
+ if (isTrustedProposalRun(this.d.ledger, p.runId))
201
+ return this.deny('PROPOSAL_ONLY_MODE');
202
+ if (p.status !== 'APPLIED')
203
+ return this.deny('NOT_APPLIED', p.status);
204
+ if (!this.testBoundaryAllows(p)) {
205
+ this.ev(p, 'TEST', 'TEST_BOUNDARY_UNVERIFIED', 'DENIED', {});
206
+ return this.deny('TEST_BOUNDARY_UNVERIFIED');
207
+ }
208
+ const current = this.d.authority.authorize({ principalId: i.principalId, projectId: p.projectId, runId: p.runId, operation: 'PROPOSE' });
209
+ if (!current.ok)
210
+ return this.deny(current.code);
211
+ if (this.sealed(i.principalId, p.proposalId))
212
+ return this.deny('RESULT_SEALED');
213
+ const g = this.d.authority.grant({ principalId: i.principalId, projectId: p.projectId, runId: p.runId, operation: 'TEST', scope: { proposalId: p.proposalId, profileId: i.profileId }, lifetimeMs: 15 * 60_000 });
214
+ return g.ok ? { ok: true, grantId: g.grantId } : this.deny(g.code);
215
+ }
216
+ /** Git evidence is separately authorized and read only. */
217
+ authorizeGitRead(i) {
218
+ const p = this.own(i.principalId, i.proposalId);
219
+ if (!p)
220
+ return this.deny('PROPOSAL_UNKNOWN');
221
+ if (isTrustedProposalRun(this.d.ledger, p.runId))
222
+ return this.deny('PROPOSAL_ONLY_MODE');
223
+ if (p.status !== 'APPLIED' && p.status !== 'COMMITTED')
224
+ return this.deny('NOT_APPLIED', p.status);
225
+ const current = this.d.authority.authorize({ principalId: i.principalId, projectId: p.projectId, runId: p.runId, operation: 'PROPOSE' });
226
+ if (!current.ok)
227
+ return this.deny(current.code);
228
+ const g = this.d.authority.grant({ principalId: i.principalId, projectId: p.projectId, runId: p.runId, operation: 'GIT_READ', lifetimeMs: 15 * 60_000 });
229
+ return g.ok ? { ok: true, grantId: g.grantId } : this.deny(g.code);
230
+ }
231
+ reject(principalId, proposalId) {
232
+ const p = this.own(principalId, proposalId);
233
+ if (!p)
234
+ return this.deny('PROPOSAL_UNKNOWN');
235
+ if (this.sealed(principalId, proposalId))
236
+ return this.deny('RESULT_SEALED');
237
+ if (!this.d.ledger.transitionCodingProposal(p.proposalId, ['SUBMITTED', 'APPROVED'], 'REJECTED', this.iso()))
238
+ return this.deny('NOT_PENDING', p.status);
239
+ this.d.authority.revokeRun(p.runId);
240
+ this.ev(p, 'PROPOSAL', 'REJECTED', 'ALLOWED', {});
241
+ return { ok: true };
242
+ }
243
+ // ---- 3. apply --------------------------------------------------------------------------------------------------------------------------------
244
+ apply(i) {
245
+ const p = this.own(i.principalId, i.proposalId);
246
+ if (!p)
247
+ return this.deny('PROPOSAL_UNKNOWN');
248
+ if (isTrustedProposalRun(this.d.ledger, p.runId))
249
+ return this.deny('PROPOSAL_ONLY_MODE');
250
+ if (this.sealed(i.principalId, i.proposalId))
251
+ return this.deny('RESULT_SEALED');
252
+ if (p.status !== 'APPROVED')
253
+ return this.deny('NOT_APPROVED', p.status);
254
+ const auth = this.d.authority.authorize({ principalId: i.principalId, projectId: p.projectId, runId: p.runId, operation: 'APPLY', scope: { proposalId: p.proposalId, digest: p.digest } }); // single use: spent here
255
+ if (!auth.ok) {
256
+ this.ev(p, 'APPLY', 'APPLY_REFUSED', 'DENIED', { code: auth.code });
257
+ return this.deny(auth.code);
258
+ }
259
+ if (!this.d.ledger.transitionCodingProposal(p.proposalId, ['APPROVED'], 'APPLYING', this.iso()))
260
+ return this.deny('DUPLICATE_DISPATCH');
261
+ const stale = (code, detail) => { this.d.ledger.transitionCodingProposal(p.proposalId, ['APPLYING'], 'REJECTED', this.iso()); this.ev(p, 'APPLY', 'APPLY_REFUSED', 'DENIED', { code }); return { ok: false, code, detail }; };
262
+ const root = this.liveRoot(p.projectId);
263
+ if (!root)
264
+ return stale('PROJECT_UNKNOWN', 'project');
265
+ const live = this.d.git.statusOf(root);
266
+ if (!live.ok || live.entries.length > 0)
267
+ return stale('PROJECT_CHANGED', 'the project is no longer clean');
268
+ if (this.d.git.headOf(root) !== p.baseHead)
269
+ return stale('PROJECT_CHANGED', 'HEAD moved since the proposal');
270
+ const rv = revalidateStored(p.canonicalJson, { root });
271
+ if (!rv.ok || rv.digest !== p.digest)
272
+ return stale(rv.ok ? 'PROPOSAL_ALTERED' : String(rv.code), 'revalidation against the live project failed');
273
+ const { ws, journal } = this.paths(p.proposalId);
274
+ mkdirSync(join(this.d.workspacesRoot, p.proposalId), { recursive: true });
275
+ const w = this.d.git.createWorkspace(root, ws);
276
+ if (!w.ok) {
277
+ this.d.ledger.transitionCodingProposal(p.proposalId, ['APPLYING'], 'APPLY_UNCERTAIN', this.iso());
278
+ this.ev(p, 'APPLY', 'WORKSPACE_FAILED', 'DENIED', { code: w.code });
279
+ return this.deny('WORKSPACE_FAILED', w.code);
280
+ }
281
+ this.ev(p, 'APPLY', 'APPLY_STARTED', 'ALLOWED', { workspace: 'run-scoped clone', head: w.head.slice(0, 12) });
282
+ let r;
283
+ try {
284
+ r = applyProposal({ workspaceRoot: realpathSync.native(ws), journalDir: journal, proposalId: p.proposalId, proposalDigest: p.digest, proposal: this.proposalOf(p), ...(i.faults ? { faults: i.faults } : {}) });
285
+ }
286
+ catch (e) {
287
+ this.d.ledger.transitionCodingProposal(p.proposalId, ['APPLYING'], 'APPLY_UNCERTAIN', this.iso());
288
+ this.ev(p, 'APPLY', 'APPLY_UNCERTAIN', 'DENIED', { error: String(e.message).slice(0, 100) });
289
+ throw e;
290
+ }
291
+ if (r.ok) {
292
+ this.d.ledger.transitionCodingProposal(p.proposalId, ['APPLYING'], 'APPLIED', this.iso());
293
+ this.ev(p, 'APPLY', 'APPLIED', 'ALLOWED', { files: r.changed.length, changes: JSON.stringify(r.changed) });
294
+ return { ok: true, state: 'APPLIED', changed: r.changed };
295
+ }
296
+ const next = r.state === 'ROLLED_BACK' ? 'ROLLED_BACK' : r.state === 'ROLLBACK_INCOMPLETE' ? 'ROLLBACK_INCOMPLETE' : 'REJECTED';
297
+ this.d.ledger.transitionCodingProposal(p.proposalId, ['APPLYING'], next, this.iso());
298
+ this.ev(p, 'APPLY', next, 'DENIED', { code: r.code, unrestored: r.unrestored.length });
299
+ return { ok: false, code: r.code, state: r.state, unrestored: r.unrestored, detail: r.detail };
300
+ }
301
+ // ---- 4. controlled test execution ------------------------------------------------------------------------------------------------------------
302
+ async test(i) {
303
+ const p = this.own(i.principalId, i.proposalId);
304
+ if (!p)
305
+ return this.deny('PROPOSAL_UNKNOWN');
306
+ if (isTrustedProposalRun(this.d.ledger, p.runId))
307
+ return this.deny('PROPOSAL_ONLY_MODE');
308
+ if (p.status !== 'APPLIED')
309
+ return this.deny('NOT_APPLIED', p.status);
310
+ if (!this.testBoundaryAllows(p)) {
311
+ this.ev(p, 'TEST', 'TEST_BOUNDARY_UNVERIFIED', 'DENIED', {});
312
+ return this.deny('TEST_BOUNDARY_UNVERIFIED');
313
+ }
314
+ if (this.sealed(i.principalId, p.proposalId))
315
+ return this.deny('RESULT_SEALED');
316
+ const auth = this.d.authority.authorize({ principalId: i.principalId, projectId: p.projectId, runId: p.runId, operation: 'TEST', scope: { proposalId: p.proposalId, profileId: i.profileId } });
317
+ if (!auth.ok) {
318
+ this.ev(p, 'TEST', 'TEST_REFUSED', 'DENIED', { code: auth.code });
319
+ return this.deny(auth.code);
320
+ }
321
+ const { ws } = this.paths(p.proposalId);
322
+ const root = realpathSync.native(ws);
323
+ // the tests may only ever run against exactly the approved bytes
324
+ const pre = this.d.git.observe(root, p.baseHead, this.proposalOf(p));
325
+ if (!pre.ok || !pre.evidence.match) {
326
+ this.ev(p, 'TEST', 'TEST_REFUSED', 'DENIED', { code: 'WORKSPACE_DIVERGED' });
327
+ return this.deny('WORKSPACE_DIVERGED');
328
+ }
329
+ const testRunId = `run.test.${b64(12)}`;
330
+ const tempDir = join(this.d.testTempRoot, testRunId);
331
+ mkdirSync(tempDir, { recursive: true });
332
+ (this.d.prepareAccess ?? prepareRestrictedAccess)({ workspaceRoot: root, tempDir });
333
+ let handle;
334
+ if (this.d.telemetry) {
335
+ this.d.ledger.reserveIntent({ runId: testRunId, principalId: i.principalId, requestId: 'req.' + testRunId, idempotencyKey: 'idem.' + testRunId, fingerprint: sha(testRunId), projectId: p.projectId, pluginId: 'plugin.coding', operationId: 'op.test',
336
+ promptText: 'coding test of ' + p.proposalId, states: [{ state: 'CREATED', reason: 'CODING_TEST' }, { state: 'RUNNING', reason: 'CODING_TEST' }], nowIso: this.iso() });
337
+ handle = this.d.telemetry.begin({ runId: testRunId, driver: 'coding.test', outputProfile: null, pluginId: 'plugin.coding', operationId: 'op.test', executableSha256: await this.d.tests.executableSha256(), manifestFingerprint: sha(i.profileId),
338
+ config: { profile: i.profileId, identity: this.d.tests.executionIdentity ?? 'RESTRICTED_LOW_INTEGRITY', workspace: 'run-scoped clone, read-only', temp: 'task-owned' }, prompt: '' });
339
+ }
340
+ const res = await this.d.tests.run({ runId: testRunId, profileId: i.profileId, workspaceRoot: root, tempDir, expectedMinTests: i.expectedMinTests, ...(handle ? { observer: handle.observer } : {}) });
341
+ const finishTestLifecycle = (passed) => {
342
+ if (!handle)
343
+ return;
344
+ this.d.ledger.applyDecision(i.principalId, testRunId, undefined, this.iso(), (run) => {
345
+ const state = passed ? 'COMPLETED' : 'FAILED';
346
+ assertValidLifecycleTransition(run.lifecycleState, state);
347
+ return { kind: 'APPLY', states: [{ state, reason: 'CODING_TEST_FINISHED' }] };
348
+ });
349
+ };
350
+ if ('refused' in res) {
351
+ finishTestLifecycle(false);
352
+ handle?.finish({ lifecycleState: 'FAILED', observed: { kind: 'NOT_LAUNCHED', code: res.refused } });
353
+ this.ev(p, 'TEST', 'TEST_REFUSED', 'DENIED', { code: res.refused });
354
+ return this.deny('TEST_NOT_RUN', res.refused);
355
+ }
356
+ handle?.finish({ lifecycleState: res.passed ? 'COMPLETED' : 'FAILED', observed: { kind: 'FINISHED', processOutcome: res.outcome, processLaunched: true, exitCode: res.exitCode, treeTerminated: res.treeTerminated, childTokenVerified: res.identity === 'RESTRICTED_LOW_INTEGRITY', stdinStatus: null, hasFinalMessage: true, unparsedLines: 0 } });
357
+ const post = this.d.git.observe(root, p.baseHead, this.proposalOf(p));
358
+ const unchanged = post.ok && post.evidence.treeSha256 === pre.evidence.treeSha256 && post.evidence.match;
359
+ const passed = res.passed && unchanged;
360
+ finishTestLifecycle(passed);
361
+ const reasons = unchanged ? res.reasons : [...res.reasons, 'WORKSPACE_CHANGED_DURING_TEST'];
362
+ this.ev(p, 'TEST', 'TEST_FINISHED', passed ? 'ALLOWED' : 'DENIED', { passed, profile: i.profileId, testRunId, identity: res.identity, outcome: res.outcome, exit: res.exitCode, tests: res.summary?.tests ?? -1, pass: res.summary?.pass ?? -1, fail: res.summary?.fail ?? -1, tree: pre.evidence.treeSha256, reasons: reasons.join(',').slice(0, 200) });
363
+ return { ok: true, passed, reasons, summary: res.summary, treeSha256: pre.evidence.treeSha256, testRunId };
364
+ }
365
+ // ---- 5. independent Git verification ---------------------------------------------------------------------------------------------------------
366
+ verify(i) {
367
+ const p = this.own(i.principalId, i.proposalId);
368
+ if (!p)
369
+ return this.deny('PROPOSAL_UNKNOWN');
370
+ if (isTrustedProposalRun(this.d.ledger, p.runId))
371
+ return this.deny('PROPOSAL_ONLY_MODE');
372
+ if (p.status !== 'APPLIED' && p.status !== 'COMMITTED')
373
+ return this.deny('NOT_APPLIED', p.status);
374
+ const auth = this.d.authority.authorize({ principalId: i.principalId, projectId: p.projectId, runId: p.runId, operation: 'GIT_READ' });
375
+ if (!auth.ok)
376
+ return this.deny(auth.code);
377
+ const o = this.d.git.observe(realpathSync.native(this.paths(p.proposalId).ws), p.baseHead, this.proposalOf(p));
378
+ if (!o.ok)
379
+ return this.deny(o.code);
380
+ this.ev(p, 'GIT', 'GIT_VERIFIED', o.evidence.match ? 'ALLOWED' : 'DENIED', { match: o.evidence.match, head: o.evidence.headNow, headUnchanged: o.evidence.headUnchanged, unexpected: o.evidence.unexpected.length, missing: o.evidence.missing.length, mismatched: o.evidence.mismatched.length, tree: o.evidence.treeSha256, diff: o.evidence.diffSha256, changes: JSON.stringify(o.evidence.changes) });
381
+ return { ok: true, evidence: o.evidence };
382
+ }
383
+ // ---- 6. commit (its own explicit authorization) ----------------------------------------------------------------------------------------------
384
+ /** The explicit act of a person: authorizes ONE commit of this exact proposal. Without it, commit() cannot run, whatever a model asked for. */
385
+ authorizeCommit(i) {
386
+ const p = this.own(i.principalId, i.proposalId);
387
+ if (!p)
388
+ return this.deny('PROPOSAL_UNKNOWN');
389
+ if (isTrustedProposalRun(this.d.ledger, p.runId))
390
+ return this.deny('PROPOSAL_ONLY_MODE');
391
+ if (p.status !== 'APPLIED')
392
+ return this.deny('NOT_APPLIED', p.status);
393
+ const current = this.d.authority.authorize({ principalId: i.principalId, projectId: p.projectId, runId: p.runId, operation: 'PROPOSE' });
394
+ if (!current.ok)
395
+ return this.deny(current.code);
396
+ if (this.sealed(i.principalId, p.proposalId))
397
+ return this.deny('RESULT_SEALED');
398
+ const g = this.d.authority.grant({ principalId: i.principalId, projectId: p.projectId, runId: p.runId, operation: 'COMMIT', scope: { proposalId: p.proposalId, digest: p.digest }, lifetimeMs: 10 * 60_000 });
399
+ return g.ok ? { ok: true, grantId: g.grantId } : this.deny(g.code);
400
+ }
401
+ commit(i) {
402
+ const p = this.own(i.principalId, i.proposalId);
403
+ if (!p)
404
+ return this.deny('PROPOSAL_UNKNOWN');
405
+ if (isTrustedProposalRun(this.d.ledger, p.runId))
406
+ return this.deny('PROPOSAL_ONLY_MODE');
407
+ if (this.sealed(i.principalId, i.proposalId))
408
+ return this.deny('RESULT_SEALED');
409
+ if (p.status !== 'APPLIED')
410
+ return this.deny('NOT_APPLIED', p.status);
411
+ const auth = this.d.authority.authorize({ principalId: i.principalId, projectId: p.projectId, runId: p.runId, operation: 'COMMIT', scope: { proposalId: p.proposalId, digest: p.digest } }); // single use: spent here
412
+ if (!auth.ok) {
413
+ this.ev(p, 'COMMIT', 'COMMIT_REFUSED', 'DENIED', { code: auth.code });
414
+ return this.deny(auth.code);
415
+ }
416
+ const root = realpathSync.native(this.paths(p.proposalId).ws);
417
+ const test = this.lastEvent(p.proposalId, 'TEST', 'TEST_FINISHED');
418
+ const t = test ? JSON.parse(test.detailJson) : undefined;
419
+ const now = this.d.git.observe(root, p.baseHead, this.proposalOf(p));
420
+ // the commit needs: tests that PASSED, on exactly the bytes that are about to be committed, and Git evidence that equals the approved proposal
421
+ const why = !t || t.passed !== true ? 'NO_PASSING_TEST' : !now.ok || !now.evidence.match ? 'GIT_EVIDENCE_MISMATCH' : t.tree !== now.evidence.treeSha256 ? 'TESTED_BYTES_DIFFER' : undefined;
422
+ if (why) {
423
+ this.ev(p, 'COMMIT', 'COMMIT_REFUSED', 'DENIED', { code: why });
424
+ return this.deny(why);
425
+ }
426
+ const paths = [...new Set(this.proposalOf(p).operations.flatMap((o) => (o.to ? [o.path, o.to] : [o.path])))];
427
+ const msg = `sw-080 verified change ${p.proposalId}\n\n${this.proposalOf(p).summary.replace(/[^\x20-\x7e]/g, '?')}\n\nproposal-digest: ${p.digest}\nbase-head: ${p.baseHead}\n`;
428
+ const c = this.d.git.commit({ root, baseHead: p.baseHead, paths, message: msg });
429
+ if (!c.ok) {
430
+ this.ev(p, 'COMMIT', 'COMMIT_FAILED', 'DENIED', { code: c.code });
431
+ return this.deny('COMMIT_FAILED', c.code);
432
+ }
433
+ const expectedFiles = [...paths].sort();
434
+ if (JSON.stringify(c.files) !== JSON.stringify(expectedFiles)) {
435
+ this.ev(p, 'COMMIT', 'COMMIT_FILES_DIFFER', 'DENIED', { commit: c.commit.slice(0, 12) });
436
+ return this.deny('COMMIT_FILES_DIFFER');
437
+ }
438
+ this.d.ledger.transitionCodingProposal(p.proposalId, ['APPLIED'], 'COMMITTED', this.iso());
439
+ this.ev(p, 'COMMIT', 'COMMITTED', 'ALLOWED', { commit: c.commit, parent: c.parent });
440
+ return { ok: true, commit: c.commit, parent: c.parent, files: c.files };
441
+ }
442
+ // ---- 7. immutable verified result (Copy Result) ----------------------------------------------------------------------------------------------
443
+ /** Builds the raw summary ONLY from trusted records and stores it once. No sentence in it comes from the model. */
444
+ finalize(i) {
445
+ const p = this.own(i.principalId, i.proposalId);
446
+ if (!p)
447
+ return this.deny('PROPOSAL_UNKNOWN');
448
+ if (isTrustedProposalRun(this.d.ledger, p.runId))
449
+ return this.deny('PROPOSAL_ONLY_MODE');
450
+ const stored = this.copyResult(i.principalId, i.proposalId);
451
+ if (stored)
452
+ return { ok: true, result: stored };
453
+ if (this.sealed(i.principalId, i.proposalId))
454
+ return this.deny('RESULT_SEALED_OR_CORRUPT');
455
+ if (p.status !== 'APPLIED' && p.status !== 'COMMITTED')
456
+ return this.deny('NOT_APPLIED', p.status);
457
+ if (this.d.ledger.readCodingActions(p.proposalId).some((a) => a.action !== 'finalize' && a.result === null))
458
+ return this.deny('ACTION_UNCERTAIN');
459
+ const run = this.d.ledger.getRunDetailForPrincipal(i.principalId, p.runId);
460
+ const evs = this.d.ledger.readCodingEvents({ subjectId: p.proposalId });
461
+ const last = (kind, event) => { const e = evs.filter((x) => x.subjectKind === kind && x.event === event).pop(); return e ? { seq: e.seq, ...JSON.parse(e.detailJson) } : undefined; };
462
+ const t = last('TEST', 'TEST_FINISHED');
463
+ const gv = last('GIT', 'GIT_VERIFIED');
464
+ const cm = last('COMMIT', 'COMMITTED');
465
+ const ap = last('APPLY', 'APPLIED');
466
+ if (!t || !gv)
467
+ return this.deny('VERIFICATION_INCOMPLETE');
468
+ const verdict = t.passed === true && gv.match === true && t.tree === gv.tree ? 'PASS_VERIFIED_CHANGE' : 'FAIL_VERIFICATION';
469
+ const capture = this.d.ledger.getCaptureByRun(i.principalId, p.runId);
470
+ const prop = this.proposalOf(p);
471
+ const lines = [
472
+ 'my-centcom verified coding result', `verdict: ${verdict}`, `status: ${p.status}`, `run: ${p.runId}`, `coding operation: ${run?.pluginId ?? 'unknown'}/${run?.operationId ?? 'unknown'}`, `instruction capture: ${capture?.captureId ?? 'direct test input'}`, `instruction fingerprint: ${run?.fingerprint ?? 'unknown'}`, `proposal: ${p.proposalId}`, `proposal digest: ${p.digest}`, `base head: ${p.baseHead}`,
473
+ `summary (from the approved proposal): ${prop.summary}`, 'changes:', ...prop.operations.map((o) => ` ${o.op} ${o.path}${o.to ? ' -> ' + o.to : ''}${o.contentSha256 ? ' sha256=' + o.contentSha256 : ''}`),
474
+ `applied: ${ap ? 'yes (event ' + ap.seq + ')' : 'no'}`,
475
+ `actual modified files (trusted applier): ${ap?.changes ?? 'not recorded'}`,
476
+ `independent Git changes: ${gv.changes ?? 'not recorded'}; observed HEAD=${gv.head ?? 'unknown'}`,
477
+ `tests: ${t ? `profile=${t.profile} passed=${t.passed} tests=${t.tests} pass=${t.pass} fail=${t.fail} outcome=${t.outcome} exit=${t.exit} reasons=${t.reasons || '-'} tree=${t.tree} (event ${t.seq}, run ${t.testRunId})` : 'not run'}`,
478
+ `git evidence: ${gv ? `match=${gv.match} headUnchanged=${gv.headUnchanged} unexpected=${gv.unexpected} missing=${gv.missing} mismatched=${gv.mismatched} tree=${gv.tree} diff=${gv.diff} (event ${gv.seq})` : 'not verified'}`,
479
+ `commit: ${cm ? `${cm.commit} (parent ${cm.parent}, event ${cm.seq})` : 'NOT COMMITTED'}`,
480
+ 'workspace: run-scoped clone; the original project was not modified',
481
+ ...(t.identity === 'MXC_PROCESS_CONTAINER_SYNTHETIC' ? ['acceptance scope: SYNTHETIC_ENGINEERING_INTEGRATION; production TEST isolation NOT VERIFIED'] : []),
482
+ ];
483
+ const text = lines.join('\n') + '\n';
484
+ const row = this.d.ledger.insertCodingResult({ resultId: `cres.${b64(18)}`, runId: p.runId, principalId: i.principalId, proposalId: p.proposalId, text, createdAtIso: this.iso() });
485
+ if (row === 'DUPLICATE') {
486
+ const existing = this.d.ledger.getCodingResultForPrincipal(i.principalId, p.proposalId);
487
+ return existing ? { ok: true, result: existing } : this.deny('RESULT_UNAVAILABLE');
488
+ }
489
+ return { ok: true, result: row };
490
+ }
491
+ /** The exact stored bytes, and only to the owner. */
492
+ copyResult(principalId, proposalId) { const r = this.d.ledger.getCodingResultForPrincipal(principalId, proposalId); return r?.kind === 'VERIFIED_CODING_RESULT' ? r : undefined; }
493
+ copyProposal(principalId, proposalId) { return this.d.ledger.getCodingResultForPrincipal(principalId, proposalId, 'PROPOSAL_ONLY_UNVERIFIED'); }
494
+ copyAppliedResult(principalId, proposalId) { return this.d.ledger.getCodingResultForPrincipal(principalId, proposalId, 'APPLIED_UNTESTED_RESULT'); }
495
+ copyCommittedResult(principalId, proposalId) { return this.d.ledger.getCodingResultForPrincipal(principalId, proposalId, 'COMMITTED_UNTESTED_RESULT'); }
496
+ commitReview(principalId, origin, proposalId, message) {
497
+ const p = this.own(principalId, proposalId), applied = this.copyAppliedResult(principalId, proposalId);
498
+ if (!p || !applied)
499
+ throw Error('APPLIED_RESULT_REQUIRED');
500
+ if (sha(p.canonicalJson) !== p.digest || !this.d.ledger.verifyCodingChain().ok)
501
+ throw Error('COMMIT_INTEGRITY_FAILED');
502
+ const root = this.liveRoot(p.projectId);
503
+ const appliedAt = this.lastEvent(p.proposalId, 'APPLY', 'REVIEWED_APPLY_STARTED');
504
+ if (!appliedAt || JSON.parse(appliedAt.detailJson).root !== root || this.d.ledger.getRunDetailForPrincipal(principalId, p.runId)?.projectId !== p.projectId)
505
+ throw Error('APPLIED_PROJECT_BINDING_CHANGED');
506
+ const branch = this.d.git.branchOf(root), proposal = this.proposalOf(p), observed = this.d.git.observe(root, p.baseHead, proposal);
507
+ if (!observed.ok || !observed.evidence.match)
508
+ throw Error('COMMIT_WORKTREE_CHANGED');
509
+ const identity = 'my-centcom <my-centcom@localhost.invalid>', binding = JSON.stringify({ principalId, origin, proposalId, digest: p.digest, root, appliedId: applied.resultId, applied: applied.sha256, branch, paths: proposal.operations.map(o => ({ path: o.path, sha256: o.contentSha256 })), identity, message: message.trim(), parent: p.baseHead });
510
+ return { challenge: this.d.authority.commitChallenge(binding), binding, projectId: p.projectId, target: root, parent: p.baseHead, branch, message: message.trim(), identity };
511
+ }
512
+ reviewedCommit(i) {
513
+ const p = this.own(i.principalId, i.proposalId);
514
+ if (!p)
515
+ return this.deny('PROPOSAL_UNKNOWN');
516
+ const existing = this.copyCommittedResult(i.principalId, i.proposalId);
517
+ if (existing)
518
+ return { ok: true, result: existing, duplicate: true };
519
+ const review = this.commitReview(i.principalId, i.origin, i.proposalId, i.message);
520
+ if (review.challenge !== i.challenge)
521
+ return this.deny('COMMIT_APPROVAL_INVALID');
522
+ if (this.d.ledger.reserveCodingAction(p.proposalId, 'reviewed_commit', sha(review.binding), this.iso()) !== 'NEW')
523
+ return this.deny('COMMIT_UNRESOLVED');
524
+ const scope = { proposalId: p.proposalId, digest: p.digest, reviewKey: sha(review.binding) };
525
+ const g = this.d.authority.grant({ principalId: i.principalId, projectId: p.projectId, runId: p.runId, operation: 'COMMIT', scope, lifetimeMs: 60000 });
526
+ if (!g.ok)
527
+ return g;
528
+ this.ev(p, 'COMMIT', 'COMMIT_INTENT', 'ALLOWED', { binding: scope.reviewKey, root: review.target, parent: p.baseHead });
529
+ const candidate = this.d.git.prepareCommit({ root: review.target, baseHead: p.baseHead, proposal: this.proposalOf(p), indexFile: join(this.d.journalsRoot, p.proposalId, 'commit.index'), message: i.message });
530
+ this.ev(p, 'COMMIT', 'COMMIT_CANDIDATE', 'ALLOWED', candidate);
531
+ if (candidate.branch !== review.branch)
532
+ throw Error('COMMIT_BRANCH_CHANGED');
533
+ const a = this.d.authority.authorize({ principalId: i.principalId, projectId: p.projectId, runId: p.runId, operation: 'COMMIT', scope, consume: true });
534
+ if (!a.ok)
535
+ return a;
536
+ this.ev(p, 'COMMIT', 'COMMIT_REF_AUTHORIZED', 'ALLOWED', { grantId: a.grantId, candidate: candidate.candidate, reviewKey: scope.reviewKey });
537
+ this.d.git.finishCommit({ root: review.target, ...candidate, proposal: this.proposalOf(p) }, true);
538
+ return this.sealCommitted(p, candidate);
539
+ }
540
+ sealCommitted(p, c) {
541
+ const applied = this.copyAppliedResult(p.principalId, p.proposalId), authorization = this.lastEvent(p.proposalId, 'COMMIT', 'COMMIT_REF_AUTHORIZED');
542
+ if (!applied || !authorization)
543
+ throw Error('COMMIT_PROVENANCE_UNAVAILABLE');
544
+ const approval = JSON.parse(authorization.detailJson);
545
+ const text = ['my-centcom local commit result', 'COMMITTED — NOT TESTED — LOCAL ONLY', `proposal: ${p.proposalId}`, `proposal digest: ${p.digest}`, `source run: ${p.runId}`, `project: ${p.projectId}`, `applied result: ${applied.resultId}`, `applied result SHA-256: ${applied.sha256}`, `COMMIT grant: ${approval.grantId}`, `approval: ${approval.reviewKey}`, `branch: ${c.branch}`, `commit: ${c.candidate}`, `parent: ${c.parent}`, `tree: ${c.tree}`, 'author/committer: my-centcom <my-centcom@localhost.invalid>', `message: ${c.message}`, ...this.proposalOf(p).operations.map(o => `file: ${o.path} SHA-256=${o.contentSha256}`), 'Independent commit verification: MATCH. Worktree/index clean. No push, test or source execution.', ''].join('\n');
546
+ const result = this.d.ledger.insertCodingResult({ resultId: `cres.${b64(18)}`, runId: p.runId, principalId: p.principalId, proposalId: p.proposalId, text, kind: 'COMMITTED_UNTESTED_RESULT', createdAtIso: this.iso() });
547
+ if (result === 'DUPLICATE')
548
+ throw Error('COMMIT_RESULT_CONFLICT');
549
+ this.d.ledger.finishCodingAction(p.proposalId, 'reviewed_commit', { ok: true, state: 'COMMITTED_UNTESTED', result });
550
+ return { ok: true, result };
551
+ }
552
+ recoverReviewedCommits() {
553
+ if (!this.d.ledger.verifyCodingChain().ok)
554
+ return; // Untrusted durable evidence cannot authorize reconciliation.
555
+ for (const id of this.d.ledger.unresolvedReviewedCommits()) {
556
+ const p = this.d.ledger.getCodingProposal(id);
557
+ if (!p)
558
+ continue;
559
+ const existing = this.copyCommittedResult(p.principalId, id);
560
+ if (existing) {
561
+ this.d.ledger.finishCodingAction(id, 'reviewed_commit', { ok: true, state: 'COMMITTED_UNTESTED', result: existing });
562
+ continue;
563
+ }
564
+ const event = this.lastEvent(id, 'COMMIT', 'COMMIT_CANDIDATE'), intent = this.lastEvent(id, 'COMMIT', 'COMMIT_INTENT');
565
+ let state = 'COMMIT_UNRESOLVED';
566
+ try {
567
+ if (event && intent) {
568
+ const c = JSON.parse(event.detailJson), root = this.liveRoot(p.projectId), record = JSON.parse(intent.detailJson);
569
+ if (root !== record.root)
570
+ throw Error('ROOT_CHANGED');
571
+ const head = this.d.git.headOf(root);
572
+ if (head === c.candidate) {
573
+ const authorized = this.lastEvent(id, 'COMMIT', 'COMMIT_REF_AUTHORIZED');
574
+ if (!authorized || JSON.parse(authorized.detailJson).candidate !== c.candidate)
575
+ throw Error('COMMIT_AUTHORIZATION_UNPROVEN');
576
+ this.d.git.finishCommit({ root: root, ...c, proposal: this.proposalOf(p) }, false);
577
+ this.sealCommitted(p, c);
578
+ continue;
579
+ }
580
+ state = head === c.parent ? 'COMMIT_REFUSED' : 'COMMIT_CONFLICT';
581
+ }
582
+ }
583
+ catch {
584
+ state = 'COMMIT_UNRESOLVED';
585
+ }
586
+ this.ev(p, 'COMMIT', 'COMMIT_RECOVERED', 'DENIED', { state });
587
+ this.d.ledger.finishCodingAction(id, 'reviewed_commit', { ok: false, state, code: 'INTERRUPTED_COMMIT' });
588
+ }
589
+ }
590
+ /** A subsequent, non-model transaction. It never changes the model run's authorities or immutable proposal delivery. */
591
+ reviewedPatchView(principalId, origin, proposalId) {
592
+ const p = this.own(principalId, proposalId);
593
+ if (!p || !this.copyProposal(principalId, proposalId))
594
+ return undefined;
595
+ try {
596
+ const review = this.d.authority.reviewedPatch({ principalId, origin, projectId: p.projectId, proposalId, digest: p.digest, baseHead: p.baseHead });
597
+ const old = this.d.ledger.readCodingActions(proposalId).find(a => a.action === 'reviewed_apply');
598
+ const st = this.d.git.statusOf(review.target), valid = sha(p.canonicalJson) === p.digest && this.d.git.headOf(review.target) === p.baseHead && st.ok && st.entries.length === 0 && revalidateStored(p.canonicalJson, { root: review.target }).ok;
599
+ return { ...review, state: old ? old.result === null ? 'APPLICATION_UNRESOLVED' : old.result.state ?? 'REFUSED' : valid ? 'APPROVAL_REQUIRED' : 'STALE_OR_CONFLICTING', eligible: !old && valid, result: this.copyAppliedResult(principalId, proposalId) ?? null };
600
+ }
601
+ catch {
602
+ return undefined;
603
+ }
604
+ }
605
+ reviewedApply(i) {
606
+ const p = this.own(i.principalId, i.proposalId);
607
+ const refuse = (code) => { if (p)
608
+ this.ev(p, 'APPLY', 'REVIEWED_APPLY_REFUSED', 'DENIED', { code }); return this.deny(code); };
609
+ if (!p || p.projectId !== i.projectId || p.digest !== i.digest || sha(p.canonicalJson) !== p.digest || p.baseHead !== i.baseHead || !this.copyProposal(i.principalId, p.proposalId))
610
+ return refuse('REVIEW_SCOPE_MISMATCH');
611
+ const old = this.d.ledger.readCodingActions(p.proposalId).find(a => a.action === 'reviewed_apply');
612
+ if (old) {
613
+ if (!old.result)
614
+ return refuse('APPLICATION_UNRESOLVED');
615
+ const r = old.result;
616
+ if (r.ok && r.result && !this.copyAppliedResult(i.principalId, p.proposalId))
617
+ return refuse('RESULT_UNAVAILABLE');
618
+ return r.ok ? { ...r, duplicate: true } : r;
619
+ }
620
+ const view = this.reviewedPatchView(i.principalId, i.origin, p.proposalId);
621
+ if (!view || view.challenge !== i.challenge)
622
+ return refuse('REVIEW_APPROVAL_MISMATCH');
623
+ if (!view.eligible)
624
+ return refuse('PROJECT_CHANGED');
625
+ if (this.d.ledger.reserveCodingAction(p.proposalId, 'reviewed_apply', p.digest, this.iso()) !== 'NEW')
626
+ return refuse('APPLICATION_UNRESOLVED');
627
+ const finish = (r) => { this.d.ledger.finishCodingAction(p.proposalId, 'reviewed_apply', r); return r; };
628
+ if (i.action === 'cancel') {
629
+ this.ev(p, 'APPLY', 'REVIEWED_APPLY_CANCELLED', 'DENIED', {});
630
+ return finish({ ok: true, state: 'CANCELLED' });
631
+ }
632
+ const approval = this.d.authority.approveReviewedPatch(i);
633
+ if (!approval.ok || !approval.reviewKey)
634
+ return finish({ ok: false, code: approval.ok ? 'REVIEW_APPROVAL_MISMATCH' : approval.code, state: 'REFUSED' });
635
+ const scope = { proposalId: p.proposalId, digest: p.digest, reviewKey: approval.reviewKey };
636
+ const common = { principalId: i.principalId, projectId: p.projectId, runId: p.runId, scope };
637
+ // BOTH authorities must admit before the first repository write; Git is rechecked after mutation too.
638
+ const apply = this.d.authority.authorize({ ...common, operation: 'APPLY', consume: true });
639
+ const git = this.d.authority.authorize({ ...common, operation: 'GIT_READ' });
640
+ if (!apply.ok || !git.ok)
641
+ return finish({ ok: false, code: !apply.ok ? apply.code : !git.ok ? git.code : 'NO_GRANT', state: 'REFUSED' });
642
+ const root = this.liveRoot(p.projectId);
643
+ const st = this.d.git.statusOf(root), rv = revalidateStored(p.canonicalJson, { root });
644
+ if (!st.ok || st.entries.length || this.d.git.headOf(root) !== p.baseHead || !rv.ok || rv.digest !== p.digest || root !== view.target)
645
+ return finish({ ok: false, code: 'PROJECT_CHANGED', state: 'REFUSED' });
646
+ const journal = join(this.d.journalsRoot, p.proposalId, 'reviewed_apply');
647
+ this.ev(p, 'APPLY', 'REVIEWED_APPLY_STARTED', 'ALLOWED', { root, baseHead: p.baseHead, digest: p.digest, reviewKey: approval.reviewKey, applyGrant: apply.grantId, gitGrant: git.grantId });
648
+ try {
649
+ const written = applyProposal({ workspaceRoot: root, journalDir: journal, proposalId: p.proposalId, proposalDigest: p.digest, proposal: rv.proposal, ...(i.faults ? { faults: i.faults } : {}) });
650
+ if (!written.ok) {
651
+ this.ev(p, 'APPLY', 'REVIEWED_APPLY_FAILED', 'DENIED', { state: written.state, code: written.code, ...(written.ioFailure ? { ioFailure: JSON.stringify(written.ioFailure) } : {}), ...(written.rollbackIoFailure ? { rollbackIoFailure: JSON.stringify(written.rollbackIoFailure) } : {}) });
652
+ return finish({ ok: false, code: written.code, state: written.state });
653
+ }
654
+ const afterAuth = this.d.authority.authorize({ ...common, operation: 'GIT_READ' });
655
+ if (!afterAuth.ok)
656
+ return finish({ ok: false, code: afterAuth.code, state: 'APPLIED_GIT_UNVERIFIED' });
657
+ const observed = this.d.git.observe(root, p.baseHead, rv.proposal);
658
+ if (!observed.ok || !observed.evidence.match) {
659
+ this.ev(p, 'GIT', 'REVIEWED_GIT_MISMATCH', 'DENIED', {});
660
+ return finish({ ok: false, code: 'GIT_VERIFICATION_FAILED', state: 'APPLIED_GIT_UNVERIFIED' });
661
+ }
662
+ const e = observed.evidence;
663
+ this.ev(p, 'GIT', 'REVIEWED_GIT_VERIFIED', 'ALLOWED', { tree: e.treeSha256, diff: e.diffSha256, head: e.headNow, reviewKey: scope.reviewKey });
664
+ const text = ['my-centcom reviewed patch result', 'outcome: APPLIED — NOT TESTED — NOT COMMITTED', `proposal: ${p.proposalId}`, `proposal digest: ${p.digest}`, `source run: ${p.runId}`, `project: ${p.projectId}`, `target: ${root}`, `base HEAD: ${p.baseHead}`, `observed HEAD: ${e.headNow}`, `approval: ${scope.reviewKey}`, `APPLY grant: ${apply.grantId}`, `GIT_READ grant: ${git.grantId}`, 'independent Git verification: MATCH; no staged files; only approved paths and content', ...e.changes.map(c => ` ${c.xy} ${c.path} sha256=${c.sha256 ?? 'ABSENT'}`), `Git diff SHA-256: ${e.diffSha256}`, `Git tree SHA-256: ${e.treeSha256}`, 'Tests: NOT_RUN. No TEST or COMMIT authority issued. No automatic ChatGPT submission.', ''].join('\n');
665
+ const inserted = this.d.ledger.insertCodingResult({ resultId: `cres.${b64(18)}`, runId: p.runId, principalId: p.principalId, proposalId: p.proposalId, text, kind: 'APPLIED_UNTESTED_RESULT', createdAtIso: this.iso() });
666
+ if (inserted === 'DUPLICATE')
667
+ return finish({ ok: false, code: 'RESULT_CONFLICT', state: 'APPLICATION_UNRESOLVED' });
668
+ this.ev(p, 'APPLY', 'REVIEWED_APPLY_COMPLETED', 'ALLOWED', { result: inserted.resultId, sha256: inserted.sha256 });
669
+ return finish({ ok: true, state: 'APPLIED_NOT_TESTED', result: inserted });
670
+ }
671
+ catch (e) {
672
+ // A crash or storage failure must leave the durable reservation unresolved, never redispatch it.
673
+ this.ev(p, 'APPLY', 'REVIEWED_APPLY_UNCERTAIN', 'DENIED', { ...(persistenceFailure(e) ? { ioFailure: JSON.stringify(persistenceFailure(e)) } : {}) });
674
+ throw e;
675
+ }
676
+ }
677
+ recoverReviewedPatches() {
678
+ for (const id of this.d.ledger.unresolvedReviewedPatches()) {
679
+ const p = this.d.ledger.getCodingProposal(id);
680
+ if (!p)
681
+ continue;
682
+ const done = this.copyAppliedResult(p.principalId, id);
683
+ if (done) {
684
+ this.d.ledger.finishCodingAction(id, 'reviewed_apply', { ok: true, state: 'APPLIED_NOT_TESTED', result: done });
685
+ continue;
686
+ }
687
+ const start = this.lastEvent(id, 'APPLY', 'REVIEWED_APPLY_STARTED');
688
+ const root = this.liveRoot(p.projectId), detail = start ? JSON.parse(start.detailJson) : undefined;
689
+ let state = 'APPLICATION_UNRESOLVED';
690
+ if (root && detail?.root === root && detail.digest === p.digest && existsSync(root) && realpathSync.native(root).toLowerCase() === root.toLowerCase()) {
691
+ const recovered = recoverJournal({ workspaceRoot: root, journalDir: join(this.d.journalsRoot, id, 'reviewed_apply') });
692
+ state = recovered.state === 'ROLLED_BACK' ? 'ROLLED_BACK' : recovered.state === 'ROLLBACK_INCOMPLETE' ? 'ROLLBACK_INCOMPLETE' : recovered.state === 'APPLIED' ? 'APPLIED_GIT_UNVERIFIED' : state;
693
+ }
694
+ this.ev(p, 'APPLY', 'REVIEWED_APPLY_RECOVERED', 'DENIED', { state });
695
+ this.d.ledger.finishCodingAction(id, 'reviewed_apply', { ok: false, state, code: 'INTERRUPTED_APPLICATION' });
696
+ }
697
+ }
698
+ /** A terminal, immutable proposal snapshot. No apply/test/Git/commit authority
699
+ * is issued, consumed or inferred from copying it. */
700
+ finalizeProposal(i) {
701
+ const p = this.own(i.principalId, i.proposalId);
702
+ if (!p)
703
+ return this.deny('PROPOSAL_UNKNOWN');
704
+ if (i.shownDigest !== p.digest)
705
+ return this.deny('DIGEST_MISMATCH');
706
+ const previous = this.copyProposal(i.principalId, i.proposalId);
707
+ if (previous)
708
+ return { ok: true, result: previous };
709
+ if (this.sealed(i.principalId, i.proposalId))
710
+ return this.deny('RESULT_SEALED_OR_CORRUPT');
711
+ if (p.status !== 'SUBMITTED')
712
+ return this.deny('NOT_PENDING', p.status);
713
+ const auth = this.d.authority.authorize({ principalId: i.principalId, projectId: p.projectId, runId: p.runId, operation: 'PROPOSE' });
714
+ if (!auth.ok)
715
+ return this.deny(auth.code);
716
+ if (this.d.ledger.readCodingActions(p.proposalId).some(a => a.action !== 'proposal' && a.result === null))
717
+ return this.deny('ACTION_UNCERTAIN');
718
+ const view = this.describeForApproval(i.principalId, p.proposalId), root = this.liveRoot(p.projectId);
719
+ if (!view?.preimagesValid || !root || this.d.git.headOf(root) !== p.baseHead)
720
+ return this.deny('PROJECT_CHANGED');
721
+ const run = this.d.ledger.getRunDetailForPrincipal(i.principalId, p.runId), capture = this.d.ledger.getCaptureByRun(i.principalId, p.runId);
722
+ const text = ['my-centcom proposal — UNVERIFIED', 'outcome: PROPOSAL_ONLY_UNVERIFIED',
723
+ `execution mode: ${isTrustedProposalRun(this.d.ledger, p.runId) ? 'TRUSTED_LOCAL_CLI_PROPOSAL_ONLY; OS isolation NOT VERIFIED' : 'STRICT_ISOLATED'}`,
724
+ 'verification: NOT TESTED; NOT APPLIED; post-application Git evidence NOT COLLECTED; NOT COMMITTED',
725
+ `proposal: ${p.proposalId}`, `proposal digest: ${p.digest}`, `run: ${p.runId}`, `project: ${p.projectId}`, `base head: ${p.baseHead}`,
726
+ `instruction capture: ${capture?.captureId ?? 'direct input'}`, `instruction fingerprint: ${run?.fingerprint ?? 'unknown'}`, 'provenance: validated canonical proposal from the run-scoped, audited MCP propose_change tool',
727
+ 'files and preimages:', ...view.operations.map(o => ` ${o.op} ${o.path}${o.to ? ' -> ' + o.to : ''} preimage=${o.preimageSha256 ?? 'NEW_FILE'} content=${o.contentSha256 ?? 'UNCHANGED_OR_DELETED'}`),
728
+ 'exact proposed diff:', view.diff, 'This proposal does not authorize applying, executing tests, creating a commit or submitting a ChatGPT message.', ''].join('\n');
729
+ if (Buffer.byteLength(text, 'utf8') > 60000)
730
+ return this.deny('PROPOSAL_COPY_TOO_LARGE');
731
+ this.ev(p, 'PROPOSAL', 'PROPOSAL_ONLY_SEALED', 'ALLOWED', { digest: p.digest, verification: 'UNVERIFIED', bytes: Buffer.byteLength(text) });
732
+ const row = this.d.ledger.insertCodingResult({ resultId: `cres.${b64(18)}`, runId: p.runId, principalId: i.principalId, proposalId: p.proposalId, text, kind: 'PROPOSAL_ONLY_UNVERIFIED', createdAtIso: this.iso() });
733
+ if (row === 'DUPLICATE') {
734
+ const stored = this.copyProposal(i.principalId, p.proposalId);
735
+ return stored ? { ok: true, result: stored } : this.deny('RESULT_UNAVAILABLE');
736
+ }
737
+ return { ok: true, result: row };
738
+ }
739
+ /** Transport preflight: rejected requests cannot reserve a later legitimate effect. Lifecycle guards remain independently enforced by each operation. */
740
+ actionReady(principalId, proposalId, action) {
741
+ const p = this.own(principalId, proposalId);
742
+ if (!p)
743
+ return false;
744
+ if (action === 'proposal')
745
+ return !!this.copyProposal(principalId, proposalId) || (p.status === 'SUBMITTED' && !this.sealed(principalId, proposalId));
746
+ if (this.sealed(principalId, proposalId) && !this.copyResult(principalId, proposalId))
747
+ return false;
748
+ if (action !== 'finalize' && action !== 'git' && this.sealed(principalId, proposalId))
749
+ return false;
750
+ if (action === 'apply')
751
+ return p.status === 'SUBMITTED';
752
+ if (action === 'reject')
753
+ return p.status === 'SUBMITTED' || p.status === 'APPROVED';
754
+ if (p.status !== 'APPLIED' && p.status !== 'COMMITTED')
755
+ return false;
756
+ if (action === 'test')
757
+ return p.status === 'APPLIED';
758
+ if (action === 'commit') {
759
+ const t = this.lastEvent(proposalId, 'TEST', 'TEST_FINISHED');
760
+ return p.status === 'APPLIED' && !!t && JSON.parse(t.detailJson).passed === true;
761
+ }
762
+ if (action === 'finalize')
763
+ return !!this.lastEvent(proposalId, 'TEST', 'TEST_FINISHED') && !!this.lastEvent(proposalId, 'GIT', 'GIT_VERIFIED');
764
+ return action === 'git';
765
+ }
766
+ // ---- crash recovery --------------------------------------------------------------------------------------------------------------------------
767
+ /** 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. */
768
+ recover(proposalIds) {
769
+ const out = [];
770
+ for (const id of proposalIds) {
771
+ const p = this.d.ledger.getCodingProposal(id);
772
+ if (!p || (p.status !== 'APPLYING' && p.status !== 'APPLY_UNCERTAIN'))
773
+ continue;
774
+ const { ws, journal } = this.paths(id);
775
+ const r = recoverJournal({ workspaceRoot: existsSync(ws) ? realpathSync.native(ws) : ws, journalDir: journal });
776
+ const next = !r.found ? 'APPLY_UNCERTAIN' : r.state === 'ROLLED_BACK' ? 'ROLLED_BACK' : r.state === 'APPLIED' ? 'APPLIED' : 'ROLLBACK_INCOMPLETE';
777
+ this.d.ledger.transitionCodingProposal(id, ['APPLYING', 'APPLY_UNCERTAIN'], next, this.iso());
778
+ this.ev(p, 'APPLY', 'RECOVERED', next === 'ROLLBACK_INCOMPLETE' || next === 'APPLY_UNCERTAIN' ? 'DENIED' : 'ALLOWED', { journal: r.found, state: next, unrestored: r.unrestored?.length ?? 0 });
779
+ out.push({ proposalId: id, found: r.found, state: next, ...(r.unrestored ? { unrestored: r.unrestored } : {}) });
780
+ }
781
+ return out;
782
+ }
783
+ }
784
+ void sha256Hex;
785
+ //# sourceMappingURL=codingWorkflowService.js.map