@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,367 @@
1
+ // Context Core run methods. Shared access and transactions are injected from store.mjs.
2
+ export function createRunMethods(values) {
3
+ const {fail, assert, ID, runDigest, parse, db, epoch, hasApprovedPlan, approvedTurnSourceMatches, randomUUID, projectDrift, receipt, internal, admin, unresolvedEffects, ensureNoPendingIssue, expectedBusiness, expectedBinding, assertPinnedHandoffCurrent, scope} = values;
4
+ // A review-only Task cannot become executable merely because R/P was approved.
5
+ // This is an explicit denial, not a substitute for independent install/IO grants.
6
+ const assertExecutableScope=context=>assert(
7
+ !Object.hasOwn(context,'executionPermission'),
8
+ 'EXECUTION_SCOPE_NOT_AUTHORIZED');
9
+ return {
10
+ reserve(a){
11
+ return receipt(a,'start.reserve',()=>{
12
+ const r=scope(a);expectedBusiness(r,a.expectedTaskRevision);
13
+ assert(!r.pending_attempt,'HANDOFF_PENDING');
14
+ assert(!r.writable_ref,'RUN_ALREADY_BOUND');
15
+ assert(!projectDrift(r).projectDrift,'PROJECT_RULES_DRIFT');
16
+ ensureNoPendingIssue(a.projectId,a.taskId);
17
+ const approvals=parse(r.approval_json);
18
+ assert(hasApprovedPlan(approvals),'APPROVAL_REQUIRED');
19
+ assert(r.approval_revision===a.expectedApprovalRevision,'APPROVAL_CONFLICT');
20
+ const current=parse(r.context_json);
21
+ assertExecutableScope(current);
22
+ if(a.purpose==='REPAIR_SAME_SCOPE'){
23
+ assert(current.stage==='REOPENED'&&current.reopenReason==='REPAIR_SAME_SCOPE'
24
+ &&current.reopenRequest?.sourceRole==='user'
25
+ &&typeof current.reopenRequest?.userTurn==='string'
26
+ &&current.reopenRequest.userTurn.length>=8,'REOPEN_INTENT_REQUIRED');
27
+ }else {
28
+ assert(a.purpose===undefined || a.purpose==='NEW_EXECUTION','START_PURPOSE_INVALID');
29
+ // Terminal DONE cannot be silently restarted with the old R/P permit.
30
+ // Only a user-requested same-scope reopen may issue a repair lease.
31
+ assert(current.executionOutcome!=='DONE'&&current.stage!=='ARCHIVED',
32
+ 'TASK_ALREADY_DELIVERED');
33
+ assert(!current.sessionCancellation,'SESSION_CANCELLED_NEW_TASK_REQUIRED');
34
+ }
35
+ // Never re-reserve an initial Start whose execution permit may have
36
+ // been consumed. Expired, unconsumed leases cannot commit later.
37
+ if(r.binding_revision===0){
38
+ assert(!db.prepare('SELECT 1 FROM permits WHERE project_id=? AND task_id=? LIMIT 1')
39
+ .get(a.projectId,a.taskId),'START_PERMIT_ALREADY_CONSUMED');
40
+ db.prepare('DELETE FROM start_leases WHERE project_id=? AND task_id=? AND expires_at<=?')
41
+ .run(a.projectId,a.taskId,Date.now());
42
+ }
43
+ const leaseRef=randomUUID();
44
+ db.prepare('INSERT INTO start_leases VALUES(?,?,?,?,?,?)').run(leaseRef,
45
+ a.projectId,a.taskId,r.approval_revision,r.business_revision,Date.now()+60000);
46
+ return {status:'RESERVED',leaseRef,approvalRevision:r.approval_revision,
47
+ taskRevision:r.business_revision};
48
+ });
49
+ },
50
+ consumePermit(a){
51
+ internal('permit.consume',a);
52
+ return receipt(a,'permit.consume',()=>{
53
+ const r=scope(a);expectedBusiness(r,a.expectedTaskRevision);
54
+ assert(r.approval_revision===a.expectedApprovalRevision,'APPROVAL_CONFLICT');
55
+ assert(!projectDrift(r).projectDrift,'PROJECT_RULES_DRIFT');
56
+ ensureNoPendingIssue(a.projectId,a.taskId);
57
+ const approvals=parse(r.approval_json);
58
+ assert(hasApprovedPlan(approvals),'APPROVAL_REVOKED');
59
+ if((a.kind??'START')==='START')assertExecutableScope(parse(r.context_json));
60
+ // Managed original-Chat Adopt is not authorized by a valid lease
61
+ // alone. The observed R/P user turns must also be those approved for
62
+ // THIS Task. The browser proof is soft; Native still owns the lease,
63
+ // CAS and one-use permit. No new approval or second fact store.
64
+ if(a.adopt!==undefined||a.approvalEvidence!==undefined){
65
+ assert(a.kind==='START'&&a.adopt===true,
66
+ 'ADOPTION_APPROVAL_EVIDENCE_REQUIRED');
67
+ const e=a.approvalEvidence;
68
+ const validTurn=(kind,record)=>approvedTurnSourceMatches(record,{
69
+ userText:e?.[kind+'UserText'],userKey:e?.[kind+'UserKey'],
70
+ version:e?.[kind+'Version']},kind.toUpperCase());
71
+ assert(e&&typeof e==='object'&&!Array.isArray(e)
72
+ &&Object.keys(e).length===6
73
+ &&['rUserText','rUserKey','rVersion','pUserText',
74
+ 'pUserKey','pVersion'].every(k=>Object.hasOwn(e,k)),
75
+ 'ADOPTION_APPROVAL_EVIDENCE_REQUIRED');
76
+ assert(validTurn('r',approvals[0])&&validTurn('p',approvals[1])
77
+ &&e.rUserKey!==e.pUserKey,
78
+ 'ADOPTION_APPROVAL_SOURCE_MISMATCH');
79
+ }
80
+ if(['CONTINUE','HANDOFF'].includes(a.kind)){
81
+ // A terminal Task with no holder is NOT eligible for more work.
82
+ // Only a named pending Handoff may reserve the single NOT_SENT
83
+ // Continue recovery; ordinary HANDOFF requires the old holder.
84
+ assert(r.writable_ref!==null
85
+ ||a.kind==='CONTINUE'&&r.pending_attempt!==null,
86
+ 'WRITER_FENCED');
87
+ if(a.kind==='HANDOFF')assert(r.pending_attempt===null,'HANDOFF_PENDING');
88
+ if(r.writable_ref!==null)
89
+ assert(r.writer_approval_revision===r.approval_revision,
90
+ 'ACTIVE_RUN_APPROVAL_STALE');
91
+ }
92
+ if(a.kind==='RECOVER_HANDOFF'){
93
+ // This permit is only for a separately signed Native BLOCKED
94
+ // recovery Action. It never licenses the old Handoff send.
95
+ expectedBinding(r,a.expectedBindingRevision);
96
+ assert(r.writable_ref===null&&r.credential_digest===null
97
+ &&r.pending_attempt===a.recoveryOfAttemptId
98
+ &&r.pending_checkpoint===a.checkpointId
99
+ &&r.pending_target_generation===a.generation+1
100
+ &&r.pending_next_ref===a.sessionId+':'+a.taskId+':'+(a.generation+1),
101
+ 'HANDOFF_RECOVERY_FENCE_MISMATCH');
102
+ assertPinnedHandoffCurrent(r,a.checkpointId);
103
+ const state=parse(r.context_json);
104
+ assert(state.executionOutcome!=='DONE'&&!state.deliveryRef
105
+ &&!state.sessionCancellation&&unresolvedEffects(state).length===0,
106
+ 'RUN_RECOVERY_UNSAFE');
107
+ assert(!db.prepare("SELECT 1 FROM permits WHERE project_id=? AND task_id=? AND kind!='USED' LIMIT 1")
108
+ .get(a.projectId,a.taskId),'RECOVERY_PERMIT_CONFLICT');
109
+ const original=db.prepare('SELECT kind,approval_revision FROM permits WHERE project_id=? AND task_id=? AND action_token=?')
110
+ .get(a.projectId,a.taskId,a.recoveryOfAttemptId);
111
+ assert(original?.kind==='USED'
112
+ &&original.approval_revision===r.approval_revision,
113
+ 'ORIGINAL_HANDOFF_PERMIT_UNVERIFIED');
114
+ }
115
+ if((a.kind??'START')==='START'){
116
+ assert(r.writable_ref===null&&r.pending_attempt===null,'RUN_ALREADY_BOUND');
117
+ const lease=db.prepare('SELECT * FROM start_leases WHERE lease_ref=?').get(a.leaseRef);
118
+ assert(lease&&lease.project_id===a.projectId&&lease.task_id===a.taskId,
119
+ 'START_LEASE_REQUIRED');
120
+ assert(lease.expires_at>Date.now(),'START_LEASE_EXPIRED');
121
+ assert(lease.approval_revision===r.approval_revision &&
122
+ lease.business_revision===r.business_revision,'START_LEASE_STALE');
123
+ }
124
+ assert(typeof a.actionToken==='string'&&a.actionToken.length>=8,'ACTION_TOKEN_REQUIRED');
125
+ const existing=db.prepare('SELECT * FROM permits WHERE project_id=? AND task_id=? AND action_token=?')
126
+ .get(a.projectId,a.taskId,a.actionToken);
127
+ if(existing)throw fail('ACTION_TOKEN_ALREADY_USED');
128
+ // Bind each START permit to its exact lease, not just an approval
129
+ // revision; the lease survives until the initial bind transaction.
130
+ const permitKind=(a.kind??'START')==='START'?'START:'+a.leaseRef:a.kind;
131
+ db.prepare('INSERT INTO permits VALUES(?,?,?,?,?)')
132
+ .run(a.projectId,a.taskId,a.actionToken,r.approval_revision,permitKind);
133
+ return {status:'PERMITTED',actionToken:a.actionToken,approvalRevision:r.approval_revision};
134
+ });
135
+ },
136
+ bindInitial(a){
137
+ internal('run.bind.initial',a);
138
+ return receipt(a,'run.bind.initial',()=>{
139
+ assert(a.ownerCommitted===true,'OWNER_UNVERIFIED');
140
+ const r=scope(a);
141
+ expectedBusiness(r,a.expectedTaskRevision);expectedBinding(r,a.expectedBindingRevision);
142
+ assert(r.writable_ref===null && r.pending_attempt===null,'BINDING_CONFLICT');
143
+ assert(typeof a.runCredential==='string'&&a.runCredential.length===64,'WRITE_CREDENTIAL_INVALID');
144
+ assert(typeof a.runRef==='string'&&a.runRef.length>=8,'RUN_REF_MISSING');
145
+ const permit=db.prepare('SELECT * FROM permits WHERE project_id=? AND task_id=? AND action_token=?')
146
+ .get(a.projectId,a.taskId,a.actionToken);
147
+ assert(permit&&permit.kind==='START:'+a.leaseRef,'START_PERMIT_REQUIRED');
148
+ const lease=db.prepare('SELECT * FROM start_leases WHERE lease_ref=?')
149
+ .get(a.leaseRef);
150
+ assert(lease&&lease.project_id===a.projectId&&lease.task_id===a.taskId,
151
+ 'START_LEASE_REQUIRED');
152
+ // A committed permit is not authority to bind a later business
153
+ // revision. The browser send is in flight: fail closed, never resend.
154
+ assert(lease.business_revision===r.business_revision
155
+ &&lease.approval_revision===r.approval_revision,'START_LEASE_STALE');
156
+ assert(permit.approval_revision===r.approval_revision &&
157
+ hasApprovedPlan(parse(r.approval_json)),'APPROVAL_REVOKED');
158
+ const initialContext=parse(r.context_json);
159
+ assertExecutableScope(initialContext);
160
+ assert(initialContext.stage==='REOPENED' &&
161
+ initialContext.reopenReason==='REPAIR_SAME_SCOPE' ||
162
+ initialContext.executionOutcome!=='DONE' &&
163
+ !['DELIVERED','ARCHIVED','REOPENED'].includes(initialContext.stage),
164
+ 'START_REOPEN_REQUIRED');
165
+ db.prepare(`UPDATE tasks SET writable_ref=?,credential_digest=?,
166
+ writer_approval_revision=?,binding_revision=binding_revision+1 WHERE project_id=? AND task_id=?`)
167
+ .run(a.runRef,runDigest(epoch,a.projectId,a.taskId,a.runRef,a.runCredential),
168
+ r.approval_revision,a.projectId,a.taskId);
169
+ // Retain a durable one-use tombstone, so the same token cannot be reissued.
170
+ db.prepare("UPDATE permits SET kind='USED' WHERE project_id=? AND task_id=? AND action_token=?")
171
+ .run(a.projectId,a.taskId,a.actionToken);
172
+ db.prepare('DELETE FROM start_leases WHERE lease_ref=?').run(a.leaseRef);
173
+ return {status:'BOUND',runRef:a.runRef,bindingRevision:r.binding_revision+1};
174
+ });
175
+ },
176
+ rotateCredential(a){
177
+ // Native/Worker-only recovery of an Adopt owner's lost DELIVERY
178
+ // capability. This is NOT an MCP method or a second Owner binding.
179
+ internal('run.credential.rotate',a);
180
+ return receipt(a,'run.credential.rotate',()=>{
181
+ const r=scope(a);expectedBusiness(r,a.expectedTaskRevision);
182
+ expectedBinding(r,a.expectedBindingRevision);
183
+ assert(r.writable_ref!==null&&r.pending_attempt===null
184
+ &&r.writable_ref===a.runRef,'WRITER_FENCED');
185
+ assert(hasApprovedPlan(parse(r.approval_json))
186
+ &&r.writer_approval_revision===r.approval_revision
187
+ &&r.approval_revision===a.expectedApprovalRevision,
188
+ 'ACTIVE_RUN_APPROVAL_STALE');
189
+ assert(!projectDrift(r).projectDrift,'PROJECT_RULES_DRIFT');
190
+ ensureNoPendingIssue(a.projectId,a.taskId);
191
+ const context=parse(r.context_json);
192
+ assert(context.executionOutcome!=='DONE'
193
+ &&unresolvedEffects(context).length===0,'RUN_RECOVERY_UNSAFE');
194
+ assert(typeof a.newRunCredential==='string'
195
+ &&/^[0-9a-f]{64}$/.test(a.newRunCredential),
196
+ 'WRITE_CREDENTIAL_INVALID');
197
+ assert(typeof a.actionToken==='string'&&a.actionToken.length>=8,
198
+ 'ACTION_TOKEN_REQUIRED');
199
+ const permit=db.prepare('SELECT kind,approval_revision FROM permits WHERE project_id=? AND task_id=? AND action_token=?')
200
+ .get(a.projectId,a.taskId,a.actionToken);
201
+ assert(permit?.kind==='CONTINUE'
202
+ &&permit.approval_revision===r.approval_revision,
203
+ 'RECOVERY_PERMIT_MISSING');
204
+ db.prepare('UPDATE tasks SET credential_digest=?,binding_revision=binding_revision+1 WHERE project_id=? AND task_id=?')
205
+ .run(runDigest(epoch,a.projectId,a.taskId,a.runRef,a.newRunCredential),
206
+ a.projectId,a.taskId);
207
+ db.prepare("UPDATE permits SET kind='USED' WHERE project_id=? AND task_id=? AND action_token=?")
208
+ .run(a.projectId,a.taskId,a.actionToken);
209
+ return {status:'CREDENTIAL_ROTATED',runRef:r.writable_ref,
210
+ taskRevision:r.business_revision,bindingRevision:r.binding_revision+1};
211
+ });
212
+ },
213
+ fenceOrphan(a){
214
+ // LOCAL OPERATOR ONLY. Recover a stale writer whose Native Owner was
215
+ // replaced by another Project. This explicitly does NOT deliver Task
216
+ // work or manufacture a missing same-Session terminal fence.
217
+ admin('run.orphan.fence',a.projectId);
218
+ admin('run.orphan.fence.reviewed',a.projectId);
219
+ return receipt(a,'run.orphan.fence',()=>{
220
+ const r=scope(a);
221
+ expectedBusiness(r,a.expectedTaskRevision);
222
+ expectedBinding(r,a.expectedBindingRevision);
223
+ assert(r.writable_ref===a.expectedRunRef&&!!a.expectedRunRef
224
+ &&r.pending_attempt===null,'ORPHAN_RUN_NOT_BOUND');
225
+ assert(typeof a.oldSessionId==='string'
226
+ &&a.expectedRunRef.startsWith(a.oldSessionId+':'+a.taskId+':'),
227
+ 'ORPHAN_SOURCE_MISMATCH');
228
+ assert(typeof a.nativeSessionId==='string'
229
+ &&a.nativeSessionId!==a.oldSessionId
230
+ &&typeof a.nativeProjectId==='string'
231
+ &&(a.nativeProjectId!==a.projectId
232
+ ||typeof a.nativeTaskId==='string'&&a.nativeTaskId!==a.taskId)
233
+ &&a.nativePhase==='DONE'
234
+ &&Number.isSafeInteger(a.nativeUpdatedAt),
235
+ 'ORPHAN_NATIVE_NOT_TERMINAL');
236
+ assert(!projectDrift(r).projectDrift,'PROJECT_RULES_DRIFT');
237
+ assert(this.projectBusinessAuthority(a.projectId).writable,
238
+ 'PROJECT_CUTOVER_NOT_VERIFIED');
239
+ const current=parse(r.context_json);
240
+ assert(current.executionOutcome!=='DONE'&&!current.deliveryRef
241
+ &&current.stage!=='DELIVERED','ORPHAN_ALREADY_DELIVERED');
242
+ assert(unresolvedEffects(current).length===0,'UNKNOWN_EFFECTS_UNRESOLVED');
243
+ assert(typeof a.evidenceDocumentId==='string'
244
+ &&ID.test(a.evidenceDocumentId)
245
+ &&Number.isInteger(a.evidenceVersion)&&a.evidenceVersion>0
246
+ &&/^[0-9a-f]{64}$/.test(a.evidenceHash||''),
247
+ 'ORPHAN_EVIDENCE_INVALID');
248
+ const proof=db.prepare(
249
+ 'SELECT kind,body,content_hash FROM documents WHERE project_id=? AND task_id=? AND document_id=? AND version=?')
250
+ .get(a.projectId,a.taskId,a.evidenceDocumentId,a.evidenceVersion);
251
+ assert(proof&&proof.kind==='REFERENCE'
252
+ &&proof.content_hash===a.evidenceHash
253
+ &&proof.body.includes(a.expectedRunRef),
254
+ 'ORPHAN_EVIDENCE_UNVERIFIED');
255
+ const blockers=Array.isArray(current.blockers)?current.blockers:[];
256
+ const orphanRef={runRef:a.expectedRunRef,oldSessionId:a.oldSessionId,
257
+ currentNativeSessionId:a.nativeSessionId,
258
+ currentNativeProjectId:a.nativeProjectId,
259
+ currentNativeTaskId:a.nativeTaskId??null,
260
+ currentNativeUpdatedAt:a.nativeUpdatedAt,
261
+ evidenceDocumentId:a.evidenceDocumentId,
262
+ evidenceVersion:a.evidenceVersion,evidenceHash:a.evidenceHash,
263
+ status:'FENCED_NOT_DELIVERED',operator:'USER_DELEGATED_AGENT',
264
+ at:Date.now()};
265
+ const next={...current,
266
+ blockers:[...blockers.filter(x=>x!=='ORPHAN_RUN_FENCED'),
267
+ 'ORPHAN_RUN_FENCED'],
268
+ orphanRunRecovery:orphanRef,
269
+ nextStep:'Obtain a new verified R/P-authorized Owner before delivery; no old send replay.'};
270
+ db.prepare(`UPDATE tasks SET writable_ref=NULL,credential_digest=NULL,
271
+ writer_approval_revision=NULL,binding_revision=binding_revision+1,
272
+ business_revision=business_revision+1,context_json=?
273
+ WHERE project_id=? AND task_id=?`)
274
+ .run(JSON.stringify(next),a.projectId,a.taskId);
275
+ db.prepare("UPDATE permits SET kind='USED' WHERE project_id=? AND task_id=?")
276
+ .run(a.projectId,a.taskId);
277
+ db.prepare('DELETE FROM start_leases WHERE project_id=? AND task_id=?')
278
+ .run(a.projectId,a.taskId);
279
+ return {status:'ORPHAN_FENCED',projectId:a.projectId,taskId:a.taskId,
280
+ oldRunRef:a.expectedRunRef,
281
+ taskRevision:r.business_revision+1,bindingRevision:r.binding_revision+1,
282
+ executionOutcome:null,deliveryRef:null};
283
+ });
284
+ },
285
+ fence(a){
286
+ internal('run.fence',a);
287
+ return receipt(a,'run.fence',()=>{
288
+ const r=scope(a);
289
+ expectedBusiness(r,a.expectedTaskRevision);expectedBinding(r,a.expectedBindingRevision);
290
+ assert(r.writable_ref===a.runRef&&!!a.runRef,'WRITER_FENCED');
291
+ assert(r.writer_approval_revision===r.approval_revision,
292
+ 'ACTIVE_RUN_APPROVAL_STALE');
293
+ assert(!projectDrift(r).projectDrift,'PROJECT_RULES_DRIFT');
294
+ ensureNoPendingIssue(a.projectId,a.taskId);
295
+ assert(!r.pending_attempt,'HANDOFF_PENDING');
296
+ const cp=db.prepare('SELECT * FROM checkpoints WHERE project_id=? AND task_id=? AND checkpoint_id=?')
297
+ .get(a.projectId,a.taskId,a.checkpointId);
298
+ assert(cp&&cp.business_revision===r.business_revision,'CHECKPOINT_STALE');
299
+ assert(typeof a.attemptId==='string'&&a.attemptId.length>=8,'ATTEMPT_MISSING');
300
+ const permit=db.prepare('SELECT * FROM permits WHERE project_id=? AND task_id=? AND action_token=?')
301
+ .get(a.projectId,a.taskId,a.actionToken);
302
+ assert(permit&&permit.kind==='HANDOFF','HANDOFF_PERMIT_REQUIRED');
303
+ assert(typeof a.nextRunRef==='string'&&a.nextRunRef.length>=8,'NEXT_RUN_MISSING');
304
+ assert(typeof a.nextRunCredential==='string'&&a.nextRunCredential.length===64,'NEXT_CREDENTIAL_INVALID');
305
+ db.prepare(`UPDATE tasks SET writable_ref=NULL,credential_digest=NULL,
306
+ writer_approval_revision=NULL,pending_attempt=?,pending_checkpoint=?,pending_target_generation=?,
307
+ pending_credential_digest=?,pending_next_ref=?,binding_revision=binding_revision+1
308
+ WHERE project_id=? AND task_id=?`).run(a.attemptId,a.checkpointId,a.targetGeneration,
309
+ runDigest(epoch,a.projectId,a.taskId,a.nextRunRef,a.nextRunCredential),
310
+ a.nextRunRef,a.projectId,a.taskId);
311
+ // Retain a durable one-use tombstone, so the same token cannot be reissued.
312
+ db.prepare("UPDATE permits SET kind='USED' WHERE project_id=? AND task_id=? AND action_token=?")
313
+ .run(a.projectId,a.taskId,a.actionToken);
314
+ return {status:'FENCED',attemptId:a.attemptId,checkpointId:a.checkpointId,
315
+ taskRevision:r.business_revision,bindingRevision:r.binding_revision+1};
316
+ });
317
+ },
318
+ bindHandoff(a){
319
+ internal('run.bind.handoff',a);
320
+ return receipt(a,'run.bind.handoff',()=>{
321
+ assert(a.ownerCommitted===true&&a.nativeCommitted===true,'OWNER_UNVERIFIED');
322
+ const r=scope(a);
323
+ expectedBusiness(r,a.expectedTaskRevision);expectedBinding(r,a.expectedBindingRevision);
324
+ assert(r.writable_ref===null&&r.pending_attempt===a.attemptId
325
+ &&r.pending_checkpoint===a.checkpointId
326
+ &&r.pending_target_generation===a.targetGeneration
327
+ &&r.pending_next_ref===a.runRef,'HANDOFF_MISMATCH');
328
+ assert(runDigest(epoch,a.projectId,a.taskId,a.runRef,a.runCredential)===r.pending_credential_digest,
329
+ 'WRITE_CREDENTIAL_INVALID');
330
+ assertPinnedHandoffCurrent(r,a.checkpointId);
331
+ assert(hasApprovedPlan(parse(r.approval_json)),'APPROVAL_REVOKED');
332
+ db.prepare(`UPDATE tasks SET writable_ref=?,credential_digest=pending_credential_digest,
333
+ writer_approval_revision=?,
334
+ pending_attempt=NULL,pending_checkpoint=NULL,pending_target_generation=NULL,
335
+ pending_credential_digest=NULL,pending_next_ref=NULL,binding_revision=binding_revision+1
336
+ WHERE project_id=? AND task_id=?`).run(a.runRef,r.approval_revision,
337
+ a.projectId,a.taskId);
338
+ return {status:'BOUND',runRef:a.runRef,bindingRevision:r.binding_revision+1,
339
+ taskRevision:r.business_revision};
340
+ });
341
+ },
342
+ fenceTerminal(a){
343
+ internal('run.fence.terminal',a);
344
+ return receipt(a,'run.fence.terminal',()=>{
345
+ const r=scope(a);
346
+ expectedBusiness(r,a.expectedTaskRevision);
347
+ expectedBinding(r,a.expectedBindingRevision);
348
+ assert(r.writable_ref!==null&&r.pending_attempt===null,'WRITER_FENCED');
349
+ assert(r.writable_ref===a.runRef,'RUN_REF_MISMATCH');
350
+ const ctx=parse(r.context_json);
351
+ assert(ctx.executionOutcome==='DONE'&&ctx.deliveryRef,
352
+ 'DELIVERY_NOT_COMMITTED');
353
+ db.prepare(`UPDATE tasks SET writable_ref=NULL,credential_digest=NULL,
354
+ writer_approval_revision=NULL,binding_revision=binding_revision+1 WHERE project_id=? AND task_id=?`)
355
+ .run(a.projectId,a.taskId);
356
+ // A terminal run invalidates every unused permit and old START lease.
357
+ // Keep used-token tombstones so later replay cannot mint a fresh action.
358
+ db.prepare("UPDATE permits SET kind='USED' WHERE project_id=? AND task_id=?")
359
+ .run(a.projectId,a.taskId);
360
+ db.prepare('DELETE FROM start_leases WHERE project_id=? AND task_id=?')
361
+ .run(a.projectId,a.taskId);
362
+ return {status:'TERMINAL_FENCED',taskRevision:r.business_revision,
363
+ bindingRevision:r.binding_revision+1};
364
+ });
365
+ }
366
+ };
367
+ }