@tomflow/chatloop-tools 0.9.64 → 0.9.70

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/node_modules/@tomflow/chatloop-context/README.md +296 -0
  2. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
  3. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
  4. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
  5. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +290 -0
  6. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
  7. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
  8. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
  9. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
  10. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
  11. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
  12. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
  13. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +261 -0
  14. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
  15. package/node_modules/@tomflow/chatloop-context/index.mjs +238 -0
  16. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
  17. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +77 -0
  18. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +2036 -0
  19. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +69 -0
  20. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +338 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
  22. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +286 -0
  23. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +117 -0
  24. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
  25. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +134 -0
  26. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
  27. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
  28. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +180 -0
  29. package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +68 -0
  30. package/node_modules/@tomflow/chatloop-context/lib/core/run-recovery.mjs +112 -0
  31. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +367 -0
  32. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +398 -0
  33. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +264 -0
  34. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
  35. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
  36. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
  37. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +118 -0
  38. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
  39. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +316 -0
  40. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
  41. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
  42. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +117 -0
  43. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +142 -0
  44. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
  45. package/node_modules/@tomflow/chatloop-context/package.json +38 -0
  46. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
  47. package/node_modules/@tomflow/chatloop-extension/README.md +190 -0
  48. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +13 -0
  49. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +168 -0
  50. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +246 -0
  51. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
  52. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
  53. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
  54. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
  55. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
  56. package/node_modules/@tomflow/chatloop-extension/capabilities/entry_test.mjs +1 -0
  57. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
  58. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
  59. package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +1 -0
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
  61. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
  62. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +123 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +183 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +390 -0
  65. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
  66. package/node_modules/@tomflow/chatloop-extension/extension/actions/entry_test.js +241 -0
  67. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff-scoped.js +143 -0
  68. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +399 -0
  69. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +60 -0
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +77 -0
  74. package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +95 -0
  75. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +329 -0
  76. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +38 -0
  77. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
  78. package/node_modules/@tomflow/chatloop-extension/extension/background.js +33 -0
  79. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
  80. package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
  81. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
  82. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
  83. package/node_modules/@tomflow/chatloop-extension/extension/entry_test.html +6 -0
  84. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
  85. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
  86. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
  87. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +84 -0
  88. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
  89. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
  90. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +299 -0
  91. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
  92. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +172 -0
  93. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
  94. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +211 -0
  95. package/node_modules/@tomflow/chatloop-extension/extension/loop/resource-maintenance.js +159 -0
  96. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +399 -0
  97. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +43 -0
  98. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
  99. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +99 -0
  100. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
  101. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
  102. package/node_modules/@tomflow/chatloop-extension/extension/session.html +7 -0
  103. package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
  104. package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
  105. package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
  106. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
  107. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +218 -0
  108. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +127 -0
  109. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +296 -0
  110. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +186 -0
  111. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +126 -0
  112. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +287 -0
  113. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +163 -0
  114. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +345 -0
  115. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +209 -0
  116. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +385 -0
  117. package/node_modules/@tomflow/chatloop-extension/extension/worker/session-control.js +75 -0
  118. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-action-v2.js +278 -0
  119. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-recovery-v2.js +52 -0
  120. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-v2.js +93 -0
  121. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-continue-recovery-v2.js +78 -0
  122. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-recovery-v2.js +148 -0
  123. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-v2.js +325 -0
  124. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-hold-recovery-v2.js +109 -0
  125. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-dispatch-v2.js +220 -0
  126. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-v2.js +106 -0
  127. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-owner-resolver.js +110 -0
  128. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-recover-v2.js +209 -0
  129. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-routes-v2.js +357 -0
  130. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-run-store.js +400 -0
  131. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-scheduler.js +78 -0
  132. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-start-v2.js +361 -0
  133. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-terminal-v2.js +235 -0
  134. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
  135. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +205 -0
  136. package/node_modules/@tomflow/chatloop-extension/index.mjs +78 -0
  137. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +19 -0
  138. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +82 -0
  139. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +378 -0
  140. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +89 -0
  141. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
  142. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +122 -0
  143. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +75 -0
  144. package/node_modules/@tomflow/chatloop-extension/lib/owner-kernel-lock.mjs +106 -0
  145. package/node_modules/@tomflow/chatloop-extension/lib/owner-ledger.mjs +316 -0
  146. package/node_modules/@tomflow/chatloop-extension/lib/owner-locked-write.mjs +30 -0
  147. package/node_modules/@tomflow/chatloop-extension/lib/scoped-cancel-v2.mjs +190 -0
  148. package/node_modules/@tomflow/chatloop-extension/lib/scoped-continue-v2.mjs +214 -0
  149. package/node_modules/@tomflow/chatloop-extension/lib/scoped-handoff-v2.mjs +338 -0
  150. package/node_modules/@tomflow/chatloop-extension/lib/scoped-native-control.mjs +398 -0
  151. package/node_modules/@tomflow/chatloop-extension/lib/scoped-recovery-v2.mjs +234 -0
  152. package/node_modules/@tomflow/chatloop-extension/lib/scoped-retire-v2.mjs +70 -0
  153. package/node_modules/@tomflow/chatloop-extension/lib/scoped-terminal-v2.mjs +143 -0
  154. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +228 -0
  155. package/node_modules/@tomflow/chatloop-extension/package.json +36 -0
  156. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +138 -0
  157. package/node_modules/@tomflow/chatloop-trace/README.md +118 -0
  158. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
  159. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
  160. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
  161. package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
  162. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
  163. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +308 -0
  164. package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +140 -0
  165. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +236 -0
  166. package/node_modules/@tomflow/chatloop-trace/package.json +28 -0
  167. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
  168. package/node_modules/ps-list/index.d.ts +76 -0
  169. package/node_modules/ps-list/index.js +366 -0
  170. package/node_modules/ps-list/license +9 -0
  171. package/node_modules/ps-list/package.json +44 -0
  172. package/node_modules/ps-list/readme.md +56 -0
  173. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  174. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
  175. package/package.json +12 -4
@@ -0,0 +1,117 @@
1
+ // Context Core context methods. Shared access and transactions are injected from store.mjs.
2
+ export function createContextMethods(values) {
3
+ const {assert, canonical, parse, db, saveTaskContext, epoch, principalId, randomUUID, required, projectDrift, checkIds, receipt, readAuth, readSnapshot, validContextPatch, unresolvedEffects, written, publicTask, scope} = values;
4
+ return {
5
+ history(projectId,taskId){
6
+ checkIds(projectId,taskId);readAuth(projectId,taskId,'context.history');
7
+ const current=required(projectId,taskId);
8
+ const docs=db.prepare('SELECT document_id,version,kind,content_hash FROM documents WHERE project_id=? AND task_id=? ORDER BY rowid')
9
+ .all(projectId,taskId);
10
+ const approvals=db.prepare('SELECT issue_id,document_id,version,state,presented_ref FROM issues WHERE project_id=? AND task_id=? ORDER BY rowid')
11
+ .all(projectId,taskId);
12
+ const checkpoints=db.prepare('SELECT checkpoint_id,business_revision FROM checkpoints WHERE project_id=? AND task_id=? ORDER BY rowid')
13
+ .all(projectId,taskId);
14
+ return {projectId,taskId,taskRevision:current.business_revision,
15
+ documents:docs,issueHistory:approvals,checkpoints,
16
+ // no raw Context credential, no automatic hard approval attribution
17
+ approvalRecords:parse(current.approval_json)};
18
+ },
19
+ // W01 fixture: real DB operations, soft approvals explicitly TEST_ONLY.,
20
+ requestStatus({projectId,storeEpoch,writeRequestId}){
21
+ readAuth(projectId,null,'context.request.status');const principal=principalId;
22
+ assert(storeEpoch===epoch,'STALE_EPOCH');
23
+ const r=db.prepare('SELECT result_json FROM receipts WHERE store_epoch=? AND principal=? AND project_id=? AND request_id=?')
24
+ .get(epoch,principal,projectId,writeRequestId);
25
+ return r?parse(r.result_json):{status:'NOT_FOUND'};
26
+ },
27
+ patch(a){
28
+ return receipt(a,'context.patch',()=>{
29
+ const r=scope(a);written(r,a);
30
+ const current=parse(r.context_json);
31
+ validContextPatch(a.patch,current);
32
+ assert(!['executionPermission','authorizedWorkspace','sourceAccess'].some(
33
+ key=>Object.hasOwn(a.patch,key)),'TASK_SCOPE_IMMUTABLE');
34
+ const context={...current,...a.patch};
35
+ saveTaskContext(a.projectId,a.taskId,context);
36
+ return {status:'COMMITTED',taskRevision:r.business_revision+1,bindingRevision:r.binding_revision};
37
+ });
38
+ },
39
+ resolveUnknownEffect(a){
40
+ return receipt(a,'context.unknown.resolve',()=>{
41
+ const r=scope(a);written(r,a);
42
+ assert(typeof a.effectRef==='string'&&a.effectRef.length>0
43
+ &&a.effectRef.length<=256,'UNKNOWN_EFFECT_REF_REQUIRED');
44
+ assert(typeof a.resolutionEvidenceRef==='string'
45
+ &&a.resolutionEvidenceRef.length>=8
46
+ &&a.resolutionEvidenceRef.length<=4096,
47
+ 'RESOLUTION_EVIDENCE_REQUIRED');
48
+ const context=parse(r.context_json);
49
+ assert((context.unknownEffects??[]).some(e=>(e.ref??e.id)===a.effectRef),
50
+ 'UNKNOWN_EFFECT_NOT_FOUND');
51
+ assert(!(context.effectResolutions??[]).some(e=>e.ref===a.effectRef),
52
+ 'UNKNOWN_EFFECT_ALREADY_RESOLVED');
53
+ const updated={...context,effectResolutions:[
54
+ ...(context.effectResolutions??[]),
55
+ {ref:a.effectRef,evidenceRef:a.resolutionEvidenceRef,
56
+ proofLevel:'SOFT_AGENT_VERIFICATION',resolvedAt:Date.now()}
57
+ ]};
58
+ saveTaskContext(a.projectId,a.taskId,updated);
59
+ return {status:'RESOLUTION_RECORDED',effectRef:a.effectRef,
60
+ proofLevel:'SOFT_AGENT_VERIFICATION',
61
+ taskRevision:r.business_revision+1};
62
+ });
63
+ },
64
+ checkpoint(a){
65
+ return receipt(a,'context.checkpoint',()=>{
66
+ const r=scope(a);written(r,a);
67
+ const current=parse(r.context_json);
68
+ const unresolved=current.unknownEffects??[];
69
+ assert(Array.isArray(unresolved),'UNKNOWN_EFFECTS_INVALID');
70
+ if(Object.hasOwn(a,'unknownEffects'))
71
+ assert(canonical(a.unknownEffects)===canonical(unresolved),
72
+ 'UNKNOWN_EFFECTS_MISMATCH');
73
+ const cpId=randomUUID(),snap={
74
+ projectId:a.projectId,taskId:a.taskId,taskRevision:r.business_revision+1,
75
+ approvalRevision:r.approval_revision,context:current,
76
+ evidenceRefs:a.evidenceRefs??[],unknownEffects:unresolved,
77
+ effectResolutions:current.effectResolutions??[],
78
+ coverage:'DECLARED_REFS_UNVERIFIED'
79
+ };
80
+ db.prepare('INSERT INTO checkpoints VALUES(?,?,?,?,?)')
81
+ .run(a.projectId,a.taskId,cpId,snap.taskRevision,JSON.stringify(snap));
82
+ db.prepare('UPDATE tasks SET business_revision=business_revision+1 WHERE project_id=? AND task_id=?')
83
+ .run(a.projectId,a.taskId);
84
+ return {status:'COMMITTED',checkpointId:cpId,taskRevision:snap.taskRevision,
85
+ bindingRevision:r.binding_revision};
86
+ });
87
+ },
88
+ resume(projectId,taskId,checkpointId,maxBytes=262144){
89
+ checkIds(projectId,taskId);readAuth(projectId,taskId,'context.resume');
90
+ assert(Number.isSafeInteger(maxBytes)&&maxBytes>=16384&&maxBytes<=262144,
91
+ 'RESUME_BUDGET_INVALID');
92
+ // A deferred SQLite reader transaction pins the SAME snapshot across
93
+ // checkpoint, task, approvals and project revision, even with a
94
+ // concurrent Gateway/Native writer in another process.
95
+ return readSnapshot(()=>{
96
+ const current=required(projectId,taskId);
97
+ const cp=db.prepare('SELECT * FROM checkpoints WHERE project_id=? AND task_id=? AND checkpoint_id=?')
98
+ .get(projectId,taskId,checkpointId);
99
+ assert(cp,'CHECKPOINT_NOT_FOUND');
100
+ const snapshot=parse(cp.snapshot_json);
101
+ const drift=projectDrift(current);
102
+ const unresolved=unresolvedEffects(snapshot.context??{}).length;
103
+ const result={checkpointId,storeEpoch:epoch,snapshot,
104
+ ...drift,liveHead:publicTask(current),
105
+ businessDrift:current.business_revision!==cp.business_revision,
106
+ bindingMatchesSource:current.writable_ref!==null,
107
+ canResumeRead:true,canExecute:false,
108
+ requireWorkerNativeCommitProof:true,
109
+ nextActionSafety:unresolved?'BLOCKED_UNKNOWN':'REQUIRES_EXTERNAL_EVIDENCE',
110
+ asOf:Date.now()};
111
+ const bytes=Buffer.byteLength(JSON.stringify(result),'utf8');
112
+ assert(bytes<=maxBytes,'RESUME_INCOMPLETE');
113
+ return result;
114
+ });
115
+ }
116
+ };
117
+ }
@@ -0,0 +1,51 @@
1
+ // Context Core evidence methods. Shared access and transactions are injected from store.mjs.
2
+ export function createEvidenceMethods(values) {
3
+ const {assert, db, randomUUID, checkIds, receipt, readAuth, expectedBusiness, written, scope} = values;
4
+ return {
5
+ evidenceAttach(a){
6
+ return receipt(a,'evidence.attach',()=>{
7
+ const r=scope(a);expectedBusiness(r,a.expectedTaskRevision);
8
+ if(r.writable_ref!==null)written(r,a);
9
+ else assert(r.pending_attempt===null,'WRITER_FENCED');
10
+ assert(typeof a.locator==='string'&&a.locator.length>0&&a.locator.length<=4096
11
+ &&typeof a.role==='string'&&/^[a-z][a-z0-9_-]{0,63}$/.test(a.role),
12
+ 'INVALID_EVIDENCE_LOCATOR');
13
+ const retention=['RETAINED','EXTERNAL','EPHEMERAL'].includes(a.retention)
14
+ ?a.retention:'EXTERNAL';
15
+ assert(a.contentHash===undefined||
16
+ typeof a.contentHash==='string'&&/^[a-f0-9]{64}$/.test(a.contentHash),
17
+ 'INVALID_EVIDENCE_HASH');
18
+ const artifactId=randomUUID();
19
+ db.prepare('INSERT INTO artifacts VALUES(?,?,?,?,?,?,?,?,?)')
20
+ .run(a.projectId,a.taskId,artifactId,a.locator,a.role,a.contentHash??null,
21
+ retention,Date.now(),'UNVERIFIED');
22
+ db.prepare('UPDATE tasks SET business_revision=business_revision+1 WHERE project_id=? AND task_id=?')
23
+ .run(a.projectId,a.taskId);
24
+ return {status:'ATTACHED',artifactId,taskRevision:r.business_revision+1,
25
+ sourceStatus:'UNVERIFIED'};
26
+ });
27
+ },
28
+ evidenceList(projectId,taskId){
29
+ checkIds(projectId,taskId);readAuth(projectId,taskId,'evidence.list');
30
+ return db.prepare('SELECT artifact_id,locator,role,content_hash,retention,observed_at,source_status FROM artifacts WHERE project_id=? AND task_id=? ORDER BY observed_at,artifact_id')
31
+ .all(projectId,taskId).map(r=>({artifactId:r.artifact_id,
32
+ locator:r.locator,role:r.role,contentHash:r.content_hash,
33
+ retention:r.retention,observedAt:r.observed_at,sourceStatus:r.source_status}));
34
+ },
35
+ evidenceDetach(a){
36
+ return receipt(a,'evidence.detach',()=>{
37
+ const r=scope(a);expectedBusiness(r,a.expectedTaskRevision);
38
+ if(r.writable_ref!==null)written(r,a);
39
+ else assert(r.pending_attempt===null,'WRITER_FENCED');
40
+ const old=db.prepare('SELECT 1 FROM artifacts WHERE project_id=? AND task_id=? AND artifact_id=?')
41
+ .get(a.projectId,a.taskId,a.artifactId);
42
+ assert(old,'EVIDENCE_NOT_FOUND');
43
+ db.prepare('DELETE FROM artifacts WHERE project_id=? AND task_id=? AND artifact_id=?')
44
+ .run(a.projectId,a.taskId,a.artifactId);
45
+ db.prepare('UPDATE tasks SET business_revision=business_revision+1 WHERE project_id=? AND task_id=?')
46
+ .run(a.projectId,a.taskId);
47
+ return {status:'DETACHED',taskRevision:r.business_revision+1};
48
+ });
49
+ }
50
+ };
51
+ }
@@ -0,0 +1,134 @@
1
+ // Context Core health methods. Shared access and transactions are injected from store.mjs.
2
+ export function createHealthMethods(values) {
3
+ const {assert, parse, db, epoch, storeMode, hasApprovedPlan, required, checkIds, admin, readAuth, unresolvedEffects, readSnapshot, projectDrift, ensureNoPendingIssue} = values;
4
+ return {
5
+ pragmas:()=>({
6
+ journalMode:db.prepare('PRAGMA journal_mode').get().journal_mode,
7
+ synchronous:db.prepare('PRAGMA synchronous').get().synchronous,
8
+ foreignKeys:db.prepare('PRAGMA foreign_keys').get().foreign_keys
9
+ }),
10
+ close:()=>db.close(),
11
+ integrity:()=>{
12
+ admin('store.integrity',null);
13
+ const checks=db.prepare('PRAGMA integrity_check').all();
14
+ const badRefs=db.prepare('PRAGMA foreign_key_check').all();
15
+ return {integrity:checks.length===1&&checks[0].integrity_check==='ok'
16
+ ?'PASS':'FAILED',foreignKeys:badRefs.length===0?'PASS':'FAILED',
17
+ storeMode,storeEpoch:epoch};
18
+ },
19
+ reopenStatus(projectId,taskId){
20
+ checkIds(projectId,taskId);readAuth(projectId,taskId,'run.reopenStatus');
21
+ const r=required(projectId,taskId),c=parse(r.context_json);
22
+ const approvals=parse(r.approval_json);
23
+ assert(c.stage==='REOPENED'&&c.reopenReason==='REPAIR_SAME_SCOPE'
24
+ &&r.writable_ref===null&&r.pending_attempt===null
25
+ &&hasApprovedPlan(approvals),'REPAIR_NOT_READY');
26
+ return {projectId,taskId,taskRevision:r.business_revision,
27
+ approvalRevision:r.approval_revision,stage:c.stage,
28
+ reopenUserTurn:c.reopenRequest?.userTurn??null,
29
+ previousDeliveryRef:c.deliveryRef??null};
30
+ },
31
+ terminalStatus(projectId,taskId,startRecoveryLeaseRef=null,
32
+ expectedHandoffAttemptId=null){
33
+ checkIds(projectId,taskId);readAuth(projectId,taskId,'run.terminalStatus');
34
+ // Only report whether the caller's exact original attempt matches.
35
+ // Never return the private request token or pending credential.
36
+ assert(expectedHandoffAttemptId===null
37
+ ||startRecoveryLeaseRef===null
38
+ &&typeof expectedHandoffAttemptId==='string'
39
+ &&/^[a-f0-9]{32}$/.test(expectedHandoffAttemptId),
40
+ 'HANDOFF_STATUS_PROBE_INVALID');
41
+ return readSnapshot(()=>{
42
+ const r=required(projectId,taskId),c=parse(r.context_json);
43
+ const state={projectId,taskId,storeEpoch:epoch,
44
+ taskRevision:r.business_revision,
45
+ bindingRevision:r.binding_revision,approvalRevision:r.approval_revision,
46
+ unknownEffectCount:unresolvedEffects(c).length,
47
+ // A bound Writer is not sufficient evidence that its prior
48
+ // Handoff has settled. Native V2 read-only checks must distinguish
49
+ // an outstanding attempt from an available, unambiguous Owner.
50
+ pendingHandoff:r.pending_attempt!==null,
51
+ pendingCheckpointId:r.pending_checkpoint??null,
52
+ ...(expectedHandoffAttemptId!==null
53
+ ?{pendingAttemptMatches:r.pending_attempt===expectedHandoffAttemptId}
54
+ :{}),
55
+ // A current RunRef cannot implicitly inherit a later R/P or
56
+ // altered Project rules; read the business approval at source.
57
+ writerApprovalCurrent:r.writer_approval_revision!==null
58
+ &&r.writer_approval_revision===r.approval_revision
59
+ &&hasApprovedPlan(parse(r.approval_json)),
60
+ projectRulesDrift:projectDrift(r).projectDrift,
61
+ runRef:r.writable_ref,executionOutcome:c.executionOutcome??null,
62
+ deliveryRef:c.deliveryRef??null,
63
+ sessionCancellation:c.sessionCancellation??null};
64
+ if(startRecoveryLeaseRef===null)return state;
65
+ // Read-only, scoped to the fresh lease. The prior expired leases were
66
+ // removed transactionally by reserve; no prior permit may exist.
67
+ assert(r.binding_revision===0&&r.writable_ref===null&&r.pending_attempt===null
68
+ &&state.unknownEffectCount===0&&state.executionOutcome===null
69
+ &&!['ARCHIVED','DELIVERED','REOPENED'].includes(c.stage)
70
+ &&!projectDrift(r).projectDrift&&hasApprovedPlan(parse(r.approval_json)),
71
+ 'START_RECOVERY_UNSAFE');
72
+ ensureNoPendingIssue(projectId,taskId);
73
+ const leases=db.prepare('SELECT * FROM start_leases WHERE project_id=? AND task_id=?')
74
+ .all(projectId,taskId);
75
+ assert(leases.length===1&&leases[0].lease_ref===startRecoveryLeaseRef
76
+ &&leases[0].expires_at>Date.now()&&leases[0].business_revision===r.business_revision
77
+ &&leases[0].approval_revision===r.approval_revision,'START_RECOVERY_LEASE_UNVERIFIED');
78
+ assert(!db.prepare('SELECT 1 FROM permits WHERE project_id=? AND task_id=? LIMIT 1')
79
+ .get(projectId,taskId),'START_PERMIT_ALREADY_CONSUMED');
80
+ return {...state,storeEpoch:epoch,startRecovery:{status:'UNBOUND_NO_PERMIT',leaseRef:startRecoveryLeaseRef}};
81
+ });
82
+ },
83
+ idleStartPermitStatus(projectId,taskId,startActionToken){
84
+ checkIds(projectId,taskId);
85
+ readAuth(projectId,taskId,'run.idleStartPermitStatus');
86
+ assert(typeof startActionToken==='string'
87
+ &&/^[a-f0-9]{32}$/.test(startActionToken),
88
+ 'START_PERMIT_TOKEN_INVALID');
89
+ return readSnapshot(()=>{
90
+ required(projectId,taskId);
91
+ const permits=db.prepare(
92
+ 'SELECT action_token,kind FROM permits WHERE project_id=? AND task_id=?'
93
+ ).all(projectId,taskId);
94
+ // BindInitial preserves a USED tombstone. Any later Continue,
95
+ // Handoff or unknown permit means idle cancellation is unsafe,
96
+ // even if a Worker reason still says ADOPTED_IDLE_BASELINE.
97
+ return {projectId,taskId,
98
+ startOnly:permits.length===1
99
+ &&permits[0].action_token===startActionToken
100
+ &&permits[0].kind==='USED'};
101
+ });
102
+ },
103
+ permitStatus(projectId,taskId,actionToken){
104
+ checkIds(projectId,taskId);readAuth(projectId,taskId,'permit.status');
105
+ assert(typeof actionToken==='string'
106
+ &&/^[a-f0-9]{32}$/.test(actionToken),
107
+ 'PERMIT_STATUS_TOKEN_INVALID');
108
+ return readSnapshot(()=>{
109
+ required(projectId,taskId);
110
+ const permit=db.prepare(
111
+ 'SELECT kind,approval_revision FROM permits WHERE project_id=? AND task_id=? AND action_token=?'
112
+ ).get(projectId,taskId,actionToken);
113
+ return {projectId,taskId,actionToken,
114
+ status:permit?'RECORDED':'NOT_FOUND',
115
+ kind:permit?.kind??null,
116
+ approvalRevision:permit?.approval_revision??null};
117
+ });
118
+ },
119
+ latestCheckpoint(projectId,taskId){
120
+ checkIds(projectId,taskId);readAuth(projectId,taskId,'context.latestCheckpoint');
121
+ const r=required(projectId,taskId);
122
+ const cp=db.prepare('SELECT checkpoint_id,business_revision,snapshot_json FROM checkpoints WHERE project_id=? AND task_id=? ORDER BY rowid DESC LIMIT 1')
123
+ .get(projectId,taskId);
124
+ assert(cp,'CHECKPOINT_NOT_FOUND');
125
+ const snap=parse(cp.snapshot_json);
126
+ return {projectId,taskId,checkpointId:cp.checkpoint_id,
127
+ taskRevision:r.business_revision,bindingRevision:r.binding_revision,
128
+ approvalRevision:r.approval_revision,checkpointRevision:cp.business_revision,
129
+ unknownEffectCount:unresolvedEffects(snap.context??{}).length,
130
+ runRef:r.writable_ref,
131
+ checkpointCurrent:cp.business_revision===r.business_revision};
132
+ }
133
+ };
134
+ }
@@ -0,0 +1,262 @@
1
+ // Context Core migration methods. Shared access and transactions are injected from store.mjs.
2
+ export function createMigrationMethods(values) {
3
+ const {fail, assert, ID, digest, parse, db, saveTaskContext, authorizeAdmin, verifySourceUnit, inspectRegistryReferenceForReview, row, required, receipt, admin, readAuth, validContextPatch} = values;
4
+ return {
5
+ migrationList(projectId){
6
+ assert(ID.test(projectId||''),'INVALID_SCOPE');
7
+ readAuth(projectId,null,'migration.list');
8
+ admin('migration.list',projectId);
9
+ return db.prepare('SELECT source_unit_id,source_path,source_hash,source_scope,status,migration_revision,manifest_json FROM migrations WHERE project_id=? ORDER BY source_unit_id')
10
+ .all(projectId).map(m=>({sourceUnitId:m.source_unit_id,
11
+ sourcePath:m.source_path,sourceHash:m.source_hash,
12
+ sourceScope:m.source_scope,status:m.status,
13
+ migrationRevision:m.migration_revision,manifest:parse(m.manifest_json)}));
14
+ },
15
+ migrationShadow(a){
16
+ admin('migration.shadow',a.projectId);
17
+ return receipt({...a,taskId:'migration-meta'},'migration.shadow',()=>{
18
+ const {sourceUnitId,sourcePath,sourceHash,sourceScope,manifest}=a;
19
+ assert(typeof sourceUnitId==='string'&&/^[a-f0-9]{64}$/.test(sourceUnitId)
20
+ &&typeof sourcePath==='string'&&sourcePath.startsWith('/')
21
+ &&typeof sourceHash==='string'&&/^[a-f0-9]{64}$/.test(sourceHash)
22
+ &&['SOURCE_FILE','PROJECT_SHARED'].includes(sourceScope)
23
+ &&manifest&&typeof manifest==='object'
24
+ &&manifest.sourceUnitId===sourceUnitId
25
+ &&manifest.projectId===a.projectId
26
+ &&manifest.sourcePath===sourcePath
27
+ &&manifest.sourceHash===sourceHash
28
+ &&manifest.sourceScope===sourceScope
29
+ &&manifest.status==='SHADOW_RO','MIGRATION_MANIFEST_INVALID');
30
+ const existing=db.prepare('SELECT * FROM migrations WHERE source_unit_id=?').get(sourceUnitId);
31
+ assert(!existing,'MIGRATION_ALREADY_REGISTERED');
32
+ db.prepare('INSERT INTO migrations VALUES(?,?,?,?,?,?,?,?,?)')
33
+ .run(sourceUnitId,a.projectId,sourcePath,sourceHash,sourceScope,
34
+ 'SHADOW_RO',1,JSON.stringify(manifest),Date.now());
35
+ return {status:'SHADOW_RO',sourceUnitId,migrationRevision:1};
36
+ });
37
+ },
38
+ migrationReconcileReference(a){
39
+ admin('migration.reference.reconcile',a.projectId);
40
+ return receipt({...a,taskId:'migration-meta'},'migration.reference.reconcile',()=>{
41
+ assert(authorizeAdmin('migration.reference.reconcile.reviewed',
42
+ a.projectId)===true,'OPERATOR_REVIEW_REQUIRED');
43
+ const r=db.prepare(
44
+ 'SELECT * FROM migrations WHERE source_unit_id=? AND project_id=?'
45
+ ).get(a.sourceUnitId,a.projectId);
46
+ assert(r&&r.status==='SHADOW_RO','MIGRATION_STAGE_MISMATCH');
47
+ assert(r.migration_revision===a.expectedMigrationRevision,
48
+ 'MIGRATION_VERSION_CONFLICT');
49
+ const m=parse(r.manifest_json);
50
+ assert(m.sourceKind==='REGISTRY_JSON'&&
51
+ m.sourceHash===a.sourceHash,'SOURCE_KIND_MISMATCH');
52
+ assert(typeof a.reviewRef==='string'&&a.reviewRef.length>=8
53
+ &&a.reviewRef.length<=256,'REVIEW_REFERENCE_REQUIRED');
54
+ const task=db.prepare(
55
+ 'SELECT 1 FROM tasks WHERE project_id=? AND (writable_ref IS NOT NULL OR pending_attempt IS NOT NULL) LIMIT 1'
56
+ ).get(a.projectId);
57
+ assert(!task,'MIGRATION_ACTIVE_RUN');
58
+ const validated=inspectRegistryReferenceForReview(m,{
59
+ taskId:a.taskId,archiveFile:a.originalArchivePath,
60
+ expectedCurrentHash:a.expectedCurrentHash
61
+ });
62
+ const reviews=m.referenceReviews??[];
63
+ assert(Array.isArray(reviews)&&reviews.length<250,'REGISTRY_REVIEW_LIMIT');
64
+ const record={taskId:a.taskId,reviewRef:a.reviewRef,
65
+ originalHash:validated.originalHash,
66
+ currentHash:validated.currentHash,
67
+ originalArchiveHash:validated.originalArchiveHash,
68
+ originalArchivePath:validated.originalArchivePath,
69
+ insertedLines:validated.insertedLines,
70
+ reviewedAt:Date.now(),proofLevel:'LOCAL_OPERATOR_REVIEW',
71
+ approvalsImported:false,ownerRestored:false};
72
+ const updated={...m,tasks:validated.currentTasks,
73
+ referenceReviews:[...reviews,record]};
74
+ db.prepare(
75
+ 'UPDATE migrations SET manifest_json=?, migration_revision=migration_revision+1,updated_at=? WHERE source_unit_id=?'
76
+ ).run(JSON.stringify(updated),Date.now(),a.sourceUnitId);
77
+ // The REGISTRY_JSON source stays SHADOW_RO. No Task or browser Owner
78
+ // is created, promoted, or granted run write authority.
79
+ return {status:'REFERENCE_RECONCILED_SHADOW',sourceUnitId:a.sourceUnitId,
80
+ migrationRevision:r.migration_revision+1,
81
+ taskId:a.taskId,originalHash:record.originalHash,
82
+ currentHash:record.currentHash,insertedLines:record.insertedLines,
83
+ sourceState:'SHADOW_RO',approvalsImported:false,canActivate:false};
84
+ });
85
+ },
86
+ migrationClassify(a){
87
+ admin('migration.classify',a.projectId);
88
+ return receipt({...a,taskId:'migration-meta'},'migration.classify',()=>{
89
+ assert(authorizeAdmin('migration.classify.reviewed',a.projectId)===true,
90
+ 'OPERATOR_REVIEW_REQUIRED');
91
+ const r=db.prepare('SELECT * FROM migrations WHERE source_unit_id=? AND project_id=?')
92
+ .get(a.sourceUnitId,a.projectId);
93
+ assert(r&&r.status==='SHADOW_RO','MIGRATION_STAGE_MISMATCH');
94
+ assert(r.migration_revision===a.expectedMigrationRevision,'MIGRATION_VERSION_CONFLICT');
95
+ const m=parse(r.manifest_json);
96
+ assert(m.sourceKind==='MIXED_CONTEXT'&&m.sourceHash===a.sourceHash,
97
+ 'SOURCE_KIND_MISMATCH');
98
+ verifySourceUnit(m);
99
+ const c=a.classification;
100
+ assert(c&&typeof c==='object'&&!Array.isArray(c)
101
+ &&c.sourceHash===m.sourceHash&&c.projectId===a.projectId
102
+ &&c.sourceUnitId===a.sourceUnitId
103
+ &&c.currentFactsComplete===true
104
+ &&typeof c.reviewRef==='string'&&c.reviewRef.length>=8
105
+ &&Array.isArray(c.taskContexts)&&c.taskContexts.length<=250
106
+ &&Array.isArray(c.unknownHistoryRefs)&&c.unknownHistoryRefs.length<=500
107
+ &&c.projectSharedContext&&typeof c.projectSharedContext==='object'
108
+ &&!Array.isArray(c.projectSharedContext),'MIXED_CLASSIFICATION_INVALID');
109
+ const known=new Set();
110
+ for(const task of c.taskContexts){
111
+ assert(ID.test(task?.taskId||'')&&!known.has(task.taskId),
112
+ 'MIXED_CLASSIFICATION_TASK_INVALID');
113
+ known.add(task.taskId);
114
+ assert(task.context&&typeof task.context==='object'
115
+ &&!Array.isArray(task.context),'MIXED_CLASSIFICATION_CONTEXT_INVALID');
116
+ validContextPatch(task.context,{unknownEffects:[]});
117
+ const existing=required(a.projectId,task.taskId);
118
+ assert(existing.writable_ref===null&&existing.pending_attempt===null
119
+ &&parse(existing.approval_json).length===0,
120
+ 'MIXED_TASK_NOT_SAFE_TO_IMPORT');
121
+ }
122
+ for(const ref of c.unknownHistoryRefs){
123
+ assert(ref&&typeof ref==='object'&&typeof ref.locator==='string'
124
+ &&ref.locator.length>0&&ref.locator.length<=4096
125
+ &&ref.sourceHash===m.sourceHash,
126
+ 'MIXED_HISTORY_REF_INVALID');
127
+ }
128
+ // Preserve the ENTIRE physical mixed source as EvidenceOnly even
129
+ // after an operator selects current facts. A "complete" boolean
130
+ // must never silently discard unknown owners or historical turns.
131
+ assert(c.unknownHistoryRefs.some(ref=>
132
+ ref.locator===m.sourcePath && ref.sourceHash===m.sourceHash),
133
+ 'MIXED_ORIGINAL_EVIDENCE_REQUIRED');
134
+ for(const key of Object.keys(c.projectSharedContext))
135
+ assert(!['__proto__','constructor','prototype'].includes(key),
136
+ 'MIXED_SHARED_CONTEXT_INVALID');
137
+ const saved={...m,classification:{...c,
138
+ proofLevel:'LOCAL_OPERATOR_REVIEW',classifiedAt:Date.now()}};
139
+ db.prepare('UPDATE migrations SET manifest_json=?,migration_revision=migration_revision+1,updated_at=? WHERE source_unit_id=?')
140
+ .run(JSON.stringify(saved),Date.now(),a.sourceUnitId);
141
+ return {status:'CLASSIFIED',sourceUnitId:a.sourceUnitId,
142
+ taskContexts:c.taskContexts.length,
143
+ evidenceOnlyRefs:c.unknownHistoryRefs.length,
144
+ migrationRevision:r.migration_revision+1};
145
+ });
146
+ },
147
+ migrationPrepare(a){
148
+ admin('migration.prepare',a.projectId);
149
+ return receipt({...a,taskId:'migration-meta'},'migration.prepare',()=>{
150
+ const r=db.prepare('SELECT * FROM migrations WHERE source_unit_id=? AND project_id=?')
151
+ .get(a.sourceUnitId,a.projectId);
152
+ assert(r&&r.status==='SHADOW_RO','MIGRATION_STAGE_MISMATCH');
153
+ assert(r.migration_revision===a.expectedMigrationRevision,'MIGRATION_VERSION_CONFLICT');
154
+ assert(a.sourceHash===r.source_hash,'SOURCE_CHANGED');
155
+ verifySourceUnit(parse(r.manifest_json));
156
+ const candidate=parse(r.manifest_json);
157
+ if(candidate.sourceKind==='MIXED_CONTEXT')
158
+ assert(candidate.classification?.currentFactsComplete===true,
159
+ 'MIXED_SOURCE_UNCLASSIFIED');
160
+ assert(typeof a.backupHash==='string'&&/^[a-f0-9]{64}$/.test(a.backupHash),
161
+ 'BACKUP_REQUIRED');
162
+ assert(typeof a.recoveryManifestHash==='string'&&/^[a-f0-9]{64}$/.test(a.recoveryManifestHash),
163
+ 'RECOVERY_MANIFEST_REQUIRED');
164
+ // Verification of real writers is a separate local operator gate.
165
+ const m={...parse(r.manifest_json),backupHash:a.backupHash,
166
+ recoveryManifestHash:a.recoveryManifestHash,preparedAt:Date.now()};
167
+ db.prepare("UPDATE migrations SET status='CUTOVER_FENCED',migration_revision=migration_revision+1,manifest_json=?,updated_at=? WHERE source_unit_id=?")
168
+ .run(JSON.stringify(m),Date.now(),a.sourceUnitId);
169
+ return {status:'CUTOVER_FENCED',sourceUnitId:a.sourceUnitId,
170
+ migrationRevision:r.migration_revision+1};
171
+ });
172
+ },
173
+ migrationActivate(a){
174
+ admin('migration.activate',a.projectId);
175
+ return receipt({...a,taskId:'migration-meta'},'migration.activate',()=>{
176
+ const r=db.prepare('SELECT * FROM migrations WHERE source_unit_id=? AND project_id=?')
177
+ .get(a.sourceUnitId,a.projectId);
178
+ assert(r&&r.status==='CUTOVER_FENCED','MIGRATION_STAGE_MISMATCH');
179
+ assert(r.migration_revision===a.expectedMigrationRevision,'MIGRATION_VERSION_CONFLICT');
180
+ assert(r.source_hash===a.sourceHash,'SOURCE_CHANGED');
181
+ verifySourceUnit(parse(r.manifest_json));
182
+ // No model boolean or raw payload can grant production cutover.
183
+ // The trusted local admin adapter MUST have already verified all
184
+ // known writer processes and source hashes. Otherwise fail-closed.
185
+ assert(authorizeAdmin('migration.activate.writers',a.projectId)===true,
186
+ 'LEGACY_WRITERS_NOT_FENCED');
187
+ const m=parse(r.manifest_json);
188
+ // Mixed project CURRENT and arbitrary historical Markdown have no
189
+ // verified Task/Project ownership. They are EvidenceOnly until an
190
+ // operator explicitly maps current facts through a separately
191
+ // reviewed import. Never cut over and silently abandon current state.
192
+ assert(m.sourceKind==='REGISTRY_JSON'||m.sourceKind==='DOCUMENT'
193
+ ||m.sourceKind==='MIXED_CONTEXT'&&m.classification?.currentFactsComplete===true,
194
+ 'MIXED_SOURCE_UNCLASSIFIED');
195
+ // A source hash pointing to a file that will be removed is not enough:
196
+ // the entire source body MUST already exist in the same managed Store,
197
+ // with its original physical path and SHA. Other task/approval facts
198
+ // still require their separate operator review.
199
+ if(['DOCUMENT','MIXED_CONTEXT'].includes(m.sourceKind)){
200
+ const stored=db.prepare('SELECT body FROM project_materials WHERE project_id=? AND source_path=? AND content_hash=? LIMIT 1')
201
+ .get(a.projectId,m.sourcePath,m.sourceHash);
202
+ assert(stored&&digest(stored.body)===m.sourceHash,
203
+ 'MIGRATION_BODY_NOT_IMPORTED');
204
+ }
205
+ assert(m.backupHash&&m.recoveryManifestHash,'MIGRATION_BACKUP_MISSING');
206
+ assert(db.prepare('SELECT 1 FROM projects WHERE project_id=?').get(a.projectId),
207
+ 'PROJECT_NOT_REGISTERED');
208
+ if(m.sourceKind==='MIXED_CONTEXT'){
209
+ const c=m.classification;
210
+ assert(authorizeAdmin('migration.activate.mixed.reviewed',a.projectId)===true,
211
+ 'OPERATOR_REVIEW_REQUIRED');
212
+ const project=db.prepare('SELECT * FROM projects WHERE project_id=?')
213
+ .get(a.projectId);
214
+ assert(project&&!project.archived,'PROJECT_NOT_REGISTERED');
215
+ const shared={...parse(project.shared_context_json),...c.projectSharedContext,
216
+ legacyEvidenceRefs:c.unknownHistoryRefs,
217
+ legacySourceHash:m.sourceHash};
218
+ db.prepare('UPDATE projects SET shared_context_json=?,project_revision=project_revision+1 WHERE project_id=?')
219
+ .run(JSON.stringify(shared),a.projectId);
220
+ for(const task of c.taskContexts){
221
+ const r=required(a.projectId,task.taskId);
222
+ assert(r.writable_ref===null&&r.pending_attempt===null
223
+ &&parse(r.approval_json).length===0,
224
+ 'MIXED_TASK_NOT_SAFE_TO_IMPORT');
225
+ validContextPatch(task.context,parse(r.context_json));
226
+ const next={...parse(r.context_json),...task.context,
227
+ stage:'UNVERIFIED',legacySourceHash:m.sourceHash,
228
+ legacyClassificationRef:c.reviewRef,
229
+ approvalEvidence:'UNVERIFIED'};
230
+ saveTaskContext(a.projectId,task.taskId,next);
231
+ }
232
+ }
233
+ // Import only verified legacy identity metadata, not R/P approvals,
234
+ // machine DONE or Browser Owner.
235
+ for(const t of m.tasks??[]){
236
+ assert(ID.test(t.taskId||'')&&typeof t.taskDocPath==='string'
237
+ &&typeof t.taskDocumentHash==='string',
238
+ 'LEGACY_IDENTITY_UNVERIFIED');
239
+ const existing=row(a.projectId,t.taskId);
240
+ assert(!existing,'MIGRATION_TASK_COLLISION');
241
+ db.prepare('INSERT INTO tasks(project_id,task_id,context_json,approval_json) VALUES(?,?,?,?)')
242
+ .run(a.projectId,t.taskId,JSON.stringify({
243
+ title:t.title,taskDocPath:t.taskDocPath,
244
+ taskDocumentHash:t.taskDocumentHash,parentTaskId:t.parentTaskId,
245
+ legacyRevision:t.legacyRevision,legacyDocuments:t.documents,
246
+ stage:'UNVERIFIED',progress:[],unknownEffects:[],
247
+ nextStep:'VERIFY_SOURCE',migrationSourceUnitId:a.sourceUnitId,
248
+ authority:'MANAGED_RW',approvalEvidence:'UNVERIFIED'
249
+ }),'[]');
250
+ }
251
+ db.prepare("UPDATE migrations SET status='MANAGED_RW',migration_revision=migration_revision+1,updated_at=? WHERE source_unit_id=?")
252
+ .run(Date.now(),a.sourceUnitId);
253
+ return {status:'MANAGED_RW',projectId:a.projectId,
254
+ sourceUnitId:a.sourceUnitId,migrationRevision:r.migration_revision+1,
255
+ importedTaskIdentities:(m.tasks??[]).length,
256
+ importedReviewedTaskContexts:m.classification?.taskContexts?.length??0,
257
+ evidenceOnlyRefs:m.classification?.unknownHistoryRefs?.length??0,
258
+ approvalsImported:false};
259
+ });
260
+ }
261
+ };
262
+ }