@tomflow/chatloop-tools 0.9.63 → 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 (83) hide show
  1. package/README.md +13 -1
  2. package/index.mjs +7 -7
  3. package/lib/context-control-run.mjs +23 -5
  4. package/lib/extension-proxy.mjs +16 -7
  5. package/lib/native-owner-v2.mjs +128 -0
  6. package/lib/release-health-checks.mjs +29 -5
  7. package/lib/trace-gateway.mjs +3 -1
  8. package/node_modules/@tomflow/chatloop-context/README.md +56 -0
  9. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +24 -0
  10. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +1 -1
  11. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +2 -2
  12. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +69 -0
  13. package/node_modules/@tomflow/chatloop-context/index.mjs +3 -1
  14. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +50 -3
  15. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +54 -1
  16. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +2 -0
  17. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +61 -2
  18. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +33 -0
  19. package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +14 -0
  20. package/node_modules/@tomflow/chatloop-context/lib/core/run-recovery.mjs +112 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +31 -39
  22. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +6 -5
  23. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +84 -3
  24. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +52 -7
  25. package/node_modules/@tomflow/chatloop-context/package.json +2 -4
  26. package/node_modules/@tomflow/chatloop-extension/README.md +66 -0
  27. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +19 -4
  28. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +40 -1
  29. package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +1 -1
  30. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +54 -4
  31. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff-scoped.js +143 -0
  32. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +9 -3
  33. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +9 -5
  34. package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +53 -10
  35. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +34 -0
  36. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +16 -2
  37. package/node_modules/@tomflow/chatloop-extension/extension/background.js +16 -0
  38. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +1 -1
  39. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +7 -6
  40. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +64 -7
  41. package/node_modules/@tomflow/chatloop-extension/extension/loop/resource-maintenance.js +159 -0
  42. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +235 -95
  43. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +1 -0
  44. package/node_modules/@tomflow/chatloop-extension/extension/session.html +1 -0
  45. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +3 -0
  46. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +73 -16
  47. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +23 -6
  48. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +237 -13
  49. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-action-v2.js +278 -0
  50. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-recovery-v2.js +52 -0
  51. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-v2.js +93 -0
  52. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-continue-recovery-v2.js +78 -0
  53. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-recovery-v2.js +148 -0
  54. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-v2.js +325 -0
  55. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-hold-recovery-v2.js +109 -0
  56. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-dispatch-v2.js +220 -0
  57. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-v2.js +106 -0
  58. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-owner-resolver.js +110 -0
  59. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-recover-v2.js +209 -0
  60. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-routes-v2.js +357 -0
  61. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-run-store.js +400 -0
  62. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-scheduler.js +78 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-start-v2.js +361 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-terminal-v2.js +235 -0
  65. package/node_modules/@tomflow/chatloop-extension/index.mjs +7 -0
  66. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +94 -19
  67. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +3 -3
  68. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +9 -2
  69. package/node_modules/@tomflow/chatloop-extension/lib/owner-kernel-lock.mjs +106 -0
  70. package/node_modules/@tomflow/chatloop-extension/lib/owner-ledger.mjs +316 -0
  71. package/node_modules/@tomflow/chatloop-extension/lib/owner-locked-write.mjs +30 -0
  72. package/node_modules/@tomflow/chatloop-extension/lib/scoped-cancel-v2.mjs +190 -0
  73. package/node_modules/@tomflow/chatloop-extension/lib/scoped-continue-v2.mjs +214 -0
  74. package/node_modules/@tomflow/chatloop-extension/lib/scoped-handoff-v2.mjs +338 -0
  75. package/node_modules/@tomflow/chatloop-extension/lib/scoped-native-control.mjs +398 -0
  76. package/node_modules/@tomflow/chatloop-extension/lib/scoped-recovery-v2.mjs +234 -0
  77. package/node_modules/@tomflow/chatloop-extension/lib/scoped-retire-v2.mjs +70 -0
  78. package/node_modules/@tomflow/chatloop-extension/lib/scoped-terminal-v2.mjs +143 -0
  79. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +50 -7
  80. package/node_modules/@tomflow/chatloop-extension/package.json +1 -3
  81. package/node_modules/@tomflow/chatloop-trace/package.json +1 -3
  82. package/package.json +9 -11
  83. package/providers/extension.mjs +59 -16
@@ -804,7 +804,7 @@
804
804
  "id": "task.create",
805
805
  "group": "task",
806
806
  "mode": "write",
807
- "description": "Create a project-scoped task with an initial DRAFT state.",
807
+ "description": "Create a project-scoped DRAFT task without durable review-only executionPermission. Current-round R/P limits are not permanent Task scope; R/P approvals and Stage 03 independently guard Start. Existing legacy restrictions remain enforced.",
808
808
  "inputSchema": {
809
809
  "type": "object",
810
810
  "required": [
@@ -1144,7 +1144,7 @@
1144
1144
  "id": "task.patch",
1145
1145
  "group": "task",
1146
1146
  "mode": "write",
1147
- "description": "Patch permitted Task fields with revision and run-holder checks.",
1147
+ "description": "Patch permitted Task fields with CAS/run-holder checks; an R/P-approved idle Task may report bounded preflight progress, blockers and nextStep only.",
1148
1148
  "inputSchema": {
1149
1149
  "type": "object",
1150
1150
  "required": [
@@ -1279,6 +1279,53 @@
1279
1279
  "minLength": 8,
1280
1280
  "maxLength": 128
1281
1281
  },
1282
+ "literalRevision": {
1283
+ "type": "object",
1284
+ "additionalProperties": false,
1285
+ "required": [
1286
+ "baseVersion",
1287
+ "baseContentHash",
1288
+ "replacements"
1289
+ ],
1290
+ "properties": {
1291
+ "baseVersion": {
1292
+ "type": "integer",
1293
+ "minimum": 1
1294
+ },
1295
+ "baseContentHash": {
1296
+ "type": "string",
1297
+ "pattern": "^[a-f0-9]{64}$"
1298
+ },
1299
+ "replacements": {
1300
+ "type": "array",
1301
+ "minItems": 1,
1302
+ "maxItems": 32,
1303
+ "items": {
1304
+ "type": "object",
1305
+ "additionalProperties": false,
1306
+ "required": [
1307
+ "from",
1308
+ "to",
1309
+ "expectedCount"
1310
+ ],
1311
+ "properties": {
1312
+ "from": {
1313
+ "type": "string",
1314
+ "minLength": 1
1315
+ },
1316
+ "to": {
1317
+ "type": "string"
1318
+ },
1319
+ "expectedCount": {
1320
+ "type": "integer",
1321
+ "minimum": 1,
1322
+ "maximum": 100
1323
+ }
1324
+ }
1325
+ }
1326
+ }
1327
+ }
1328
+ },
1282
1329
  "requirementRef": {
1283
1330
  "type": "object",
1284
1331
  "additionalProperties": false,
@@ -1688,7 +1735,7 @@
1688
1735
  "id": "start.reserve",
1689
1736
  "group": "start",
1690
1737
  "mode": "write",
1691
- "description": "Reserve a short-lived start lease after both effective R/P approvals.",
1738
+ "description": "Reserve a short-lived Start lease after both effective R/P approvals; an explicit Task executionPermission (including review-only or unknown) is a restriction and cannot be overridden by R/P. Legacy tasks without this field retain their prior Start eligibility. No installation or filesystem grants.",
1692
1739
  "inputSchema": {
1693
1740
  "type": "object",
1694
1741
  "required": [
@@ -106,7 +106,60 @@ export async function runLocalCliCommand(args,readJson){
106
106
  expectedBindingRevision:Number(bindingRevision),
107
107
  expectedStoreEpoch,evidenceDocumentId,
108
108
  evidenceVersion:Number(evidenceVersion),evidenceHash,writeRequestId});
109
- }else if(command==='task'&&sub==='orphan-receipt'&&rest.length===3){
109
+ }else if(command==='task'&&sub==='correct-review-scope'&&rest.length===8){
110
+ // Independent, explicit local operator action; NOT exposed via Context MCP.
111
+ const [projectId,taskId,revision,approvalRevision,storeEpoch,
112
+ expectedPermission,operatorEvidenceRef,writeRequestId]=rest;
113
+ if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
114
+ if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
115
+ if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
116
+ const expectedTaskRevision=Number(revision),
117
+ expectedApprovalRevision=Number(approvalRevision);
118
+ if(!Number.isSafeInteger(expectedTaskRevision)||expectedTaskRevision<1
119
+ ||!Number.isSafeInteger(expectedApprovalRevision)||expectedApprovalRevision<1)
120
+ throw fail('SCOPE_CORRECTION_REVISION_INVALID');
121
+ if(!['REQUIREMENTS_REVIEW_ONLY','PLAN_REVIEW_ONLY'].includes(expectedPermission)
122
+ ||typeof operatorEvidenceRef!=='string'||operatorEvidenceRef.length<8
123
+ ||operatorEvidenceRef.length>256
124
+ ||typeof writeRequestId!=='string'||writeRequestId.length<8
125
+ ||writeRequestId.length>128)
126
+ throw fail('SCOPE_CORRECTION_ARGUMENT_INVALID');
127
+ const file=join(contextRoot(),projectId,'context.sqlite');
128
+ const read=openContextProtocol(file,{readOnly:true,principalId:'local-operator',
129
+ authorizeData:(_mode,p)=>p===projectId});
130
+ try{
131
+ const current=read.get(projectId,taskId);
132
+ if(read.epoch!==storeEpoch)throw fail('STALE_EPOCH');
133
+ if(current.taskRevision!==expectedTaskRevision)
134
+ throw fail('BUSINESS_VERSION_CONFLICT');
135
+ if(current.approvalRevision!==expectedApprovalRevision)
136
+ throw fail('APPROVAL_CONFLICT');
137
+ if(current.currentContext.executionPermission!==expectedPermission)
138
+ throw fail('SCOPE_CORRECTION_NOT_ELIGIBLE');
139
+ if(read.projectBusinessAuthority(projectId).writable!==true)
140
+ throw fail('PROJECT_CUTOVER_NOT_VERIFIED');
141
+ }finally{read.close()}
142
+ await confirmWorkspaceOperator('CORRECT_REVIEW_SCOPE',projectId,
143
+ expectedTaskRevision,[taskId,expectedPermission,
144
+ String(expectedApprovalRevision),storeEpoch,operatorEvidenceRef]);
145
+ const db=openContextProtocol(file,{principalId:'local-operator',
146
+ authorizeData:(_mode,p)=>p===projectId,
147
+ authorizeAdmin:(op,p)=>op==='task.reviewScope.correct'&&p===projectId});
148
+ try{
149
+ value=db.taskCorrectReviewScope({projectId,taskId,
150
+ expectedTaskRevision,expectedApprovalRevision,
151
+ expectedPermission,operatorEvidenceRef,
152
+ reason:'STAGE_ONLY_INTENT_MISCLASSIFIED',
153
+ expectedStoreEpoch:storeEpoch,writeRequestId});
154
+ const after=db.get(projectId,taskId);
155
+ if(after.taskRevision!==value.taskRevision
156
+ ||after.bindingRevision!==0||after.runRef!==null
157
+ ||Object.hasOwn(after.currentContext,'executionPermission')
158
+ ||after.currentContext.scopeCorrection?.operatorEvidenceRef!==operatorEvidenceRef)
159
+ throw fail('SCOPE_CORRECTION_READBACK_FAILED');
160
+ value={...value,projectId,taskId,storeEpoch,writeRequestId};
161
+ }finally{db.close()}
162
+ }else if(command==='task'&&['orphan-receipt','scope-correction-receipt'].includes(sub)&&rest.length===3){
110
163
  const [projectId,storeEpoch,writeRequestId]=rest;
111
164
  if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
112
165
  if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
@@ -29,6 +29,8 @@ export function createContextMethods(values) {
29
29
  const r=scope(a);written(r,a);
30
30
  const current=parse(r.context_json);
31
31
  validContextPatch(a.patch,current);
32
+ assert(!['executionPermission','authorizedWorkspace','sourceAccess'].some(
33
+ key=>Object.hasOwn(a.patch,key)),'TASK_SCOPE_IMMUTABLE');
32
34
  const context={...current,...a.patch};
33
35
  saveTaskContext(a.projectId,a.taskId,context);
34
36
  return {status:'COMMITTED',taskRevision:r.business_revision+1,bindingRevision:r.binding_revision};
@@ -28,13 +28,36 @@ export function createHealthMethods(values) {
28
28
  reopenUserTurn:c.reopenRequest?.userTurn??null,
29
29
  previousDeliveryRef:c.deliveryRef??null};
30
30
  },
31
- terminalStatus(projectId,taskId,startRecoveryLeaseRef=null){
31
+ terminalStatus(projectId,taskId,startRecoveryLeaseRef=null,
32
+ expectedHandoffAttemptId=null){
32
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');
33
41
  return readSnapshot(()=>{
34
42
  const r=required(projectId,taskId),c=parse(r.context_json);
35
- const state={projectId,taskId,taskRevision:r.business_revision,
43
+ const state={projectId,taskId,storeEpoch:epoch,
44
+ taskRevision:r.business_revision,
36
45
  bindingRevision:r.binding_revision,approvalRevision:r.approval_revision,
37
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,
38
61
  runRef:r.writable_ref,executionOutcome:c.executionOutcome??null,
39
62
  deliveryRef:c.deliveryRef??null,
40
63
  sessionCancellation:c.sessionCancellation??null};
@@ -57,6 +80,42 @@ export function createHealthMethods(values) {
57
80
  return {...state,storeEpoch:epoch,startRecovery:{status:'UNBOUND_NO_PERMIT',leaseRef:startRecoveryLeaseRef}};
58
81
  });
59
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
+ },
60
119
  latestCheckpoint(projectId,taskId){
61
120
  checkIds(projectId,taskId);readAuth(projectId,taskId,'context.latestCheckpoint');
62
121
  const r=required(projectId,taskId);
@@ -5,6 +5,10 @@ export function createReviewMethods(values) {
5
5
  documentCreate(a){
6
6
  return receipt(a,'document.createDraft',()=>{
7
7
  const r=scope(a);expectedBusiness(r,a.expectedTaskRevision);
8
+ // An R/P replacement must first record the user's decision on the
9
+ // pending issue. A draft written before REQUEST_CHANGE would create
10
+ // an immutable orphan version that cannot be legally presented.
11
+ if(a.kind==='R'||a.kind==='P')ensureNoPendingIssue(a.projectId,a.taskId);
8
12
  // The public Method Catalog also advertises immutable task-scoped
9
13
  // reference and historical-evidence drafts. They are storage only:
10
14
  // document.prepareIssue must never turn them into R/P approval issues.
@@ -24,6 +28,35 @@ export function createReviewMethods(values) {
24
28
  }
25
29
  assert(!db.prepare('SELECT 1 FROM documents WHERE project_id=? AND task_id=? AND document_id=? AND version=?')
26
30
  .get(a.projectId,a.taskId,a.documentId,a.version),'DOCUMENT_EXISTS');
31
+ if(a.literalRevision!==undefined){
32
+ const guard=a.literalRevision;
33
+ assert(a.kind==='P'&&Number.isInteger(guard?.baseVersion)
34
+ &&guard.baseVersion>=1&&guard.baseVersion<a.version
35
+ &&typeof guard.baseContentHash==='string'
36
+ &&Array.isArray(guard.replacements)
37
+ &&guard.replacements.length>=1&&guard.replacements.length<=32,
38
+ 'LITERAL_REVISION_INVALID');
39
+ const base=db.prepare('SELECT body,content_hash FROM documents WHERE project_id=? AND task_id=? AND document_id=? AND version=? AND kind=?')
40
+ .get(a.projectId,a.taskId,a.documentId,guard.baseVersion,a.kind);
41
+ assert(base&&base.content_hash===guard.baseContentHash,
42
+ 'LITERAL_REVISION_BASE_MISMATCH');
43
+ let candidate=base.body;
44
+ const used=new Set();
45
+ for(const edit of guard.replacements){
46
+ assert(typeof edit?.from==='string'&&edit.from.length>0
47
+ &&typeof edit.to==='string'&&edit.from!==edit.to
48
+ &&!edit.to.includes(edit.from)
49
+ &&Number.isInteger(edit.expectedCount)
50
+ &&edit.expectedCount>=1&&edit.expectedCount<=100
51
+ &&!used.has(edit.from),'LITERAL_REVISION_INVALID');
52
+ used.add(edit.from);
53
+ const parts=candidate.split(edit.from);
54
+ assert(parts.length-1===edit.expectedCount,
55
+ 'LITERAL_REVISION_COUNT_MISMATCH');
56
+ candidate=parts.join(edit.to);
57
+ }
58
+ assert(candidate===a.body,'LITERAL_REVISION_CONTENT_MISMATCH');
59
+ }
27
60
  const contentHash=digest(a.body);
28
61
  db.prepare('INSERT INTO documents VALUES(?,?,?,?,?,?,?,?)')
29
62
  .run(a.projectId,a.taskId,a.documentId,a.version,a.kind,a.body,contentHash,
@@ -15,6 +15,20 @@ export function createCancelMethods(values){
15
15
  &&a.runRef===a.sessionId+':'+a.taskId+':'+a.generation,
16
16
  'RUN_REF_MISMATCH');
17
17
  assert(!r.pending_attempt,'HANDOFF_PENDING');
18
+ if(a.scopedStartActionToken!==undefined){
19
+ // V2 idle Cancel must prove IN THIS SAME Context transaction that
20
+ // no Continue/Handoff permit was ever consumed or reserved. The
21
+ // earlier read-only query alone has a time-of-check race.
22
+ assert(typeof a.scopedStartActionToken==='string'
23
+ &&/^[a-f0-9]{32}$/.test(a.scopedStartActionToken),
24
+ 'IDLE_START_TOKEN_INVALID');
25
+ const all=db.prepare(
26
+ 'SELECT action_token,kind FROM permits WHERE project_id=? AND task_id=?'
27
+ ).all(a.projectId,a.taskId);
28
+ assert(all.length===1
29
+ &&all[0].action_token===a.scopedStartActionToken
30
+ &&all[0].kind==='USED','IDLE_CANCEL_EXECUTION_PERMIT_EXISTS');
31
+ }
18
32
  assert(r.writer_approval_revision===r.approval_revision,
19
33
  'ACTIVE_RUN_APPROVAL_STALE');
20
34
  assert(!projectDrift(r).projectDrift,'PROJECT_RULES_DRIFT');
@@ -0,0 +1,112 @@
1
+ // The two same-Task recovery transactions share the original Context SQLite
2
+ // receipt authority. V1 and V2 have distinct Native admission contracts;
3
+ // neither is a public MCP capability or a browser sender.
4
+ export function createRecoveryMethods(values){
5
+ const {internal,receipt,assert,scope,expectedBusiness,expectedBinding,
6
+ assertPinnedHandoffCurrent,parse,unresolvedEffects,db,runDigest,epoch,
7
+ hasApprovedPlan}=values;
8
+ return {
9
+ restoreSameOwner(a){
10
+ internal('run.bind.restore-same-owner',a);
11
+ return receipt(a,'run.bind.restore-same-owner',()=>{
12
+ // These proofs are adapter assertions in W01 only. Real Worker/Native
13
+ // provenance MUST be verified by the transport before W07 enables this.
14
+ assert(a.sendState==='NOT_SENT' && a.oldActionTokenRevoked===true,
15
+ 'SEND_NOT_PROVEN_ABSENT');
16
+ assert(a.workerRestored===true && a.nativeRestored===true &&
17
+ a.ownerStillSame===true,'OWNER_UNVERIFIED');
18
+ const r=scope(a);expectedBusiness(r,a.expectedTaskRevision);
19
+ expectedBinding(r,a.expectedBindingRevision);
20
+ assert(r.writable_ref===null && r.pending_attempt===a.attemptId
21
+ &&r.pending_checkpoint===a.checkpointId
22
+ &&r.pending_target_generation===a.generation+1
23
+ &&r.pending_next_ref===a.sessionId+':'+a.taskId+':'+(a.generation+1),
24
+ 'HANDOFF_MISMATCH');
25
+ assertPinnedHandoffCurrent(r,a.checkpointId);
26
+ const state=parse(r.context_json);
27
+ assert(state.executionOutcome!=='DONE'&&!state.deliveryRef
28
+ &&!state.sessionCancellation
29
+ &&unresolvedEffects(state).length===0,'RUN_RECOVERY_UNSAFE');
30
+ assert(typeof a.recoveryCredential==='string'&&a.recoveryCredential.length===64,
31
+ 'WRITE_CREDENTIAL_INVALID');
32
+ assert(typeof a.recoveryActionToken==='string'&&a.recoveryActionToken.length>=8,
33
+ 'ACTION_TOKEN_REQUIRED');
34
+ assert(typeof a.sourceRunRef==='string'&&a.sourceRunRef.length>=8,
35
+ 'RUN_REF_MISSING');
36
+ const permit=db.prepare('SELECT * FROM permits WHERE project_id=? AND task_id=? AND action_token=?')
37
+ .get(a.projectId,a.taskId,a.recoveryActionToken);
38
+ assert(permit&&permit.kind==='CONTINUE'
39
+ &&permit.approval_revision===r.approval_revision,'RECOVERY_PERMIT_MISSING');
40
+ assert(hasApprovedPlan(parse(r.approval_json)),'APPROVAL_REVOKED');
41
+ db.prepare(`UPDATE tasks SET writable_ref=?,credential_digest=?,
42
+ writer_approval_revision=?,pending_attempt=NULL,pending_checkpoint=NULL,
43
+ pending_target_generation=NULL,pending_credential_digest=NULL,
44
+ pending_next_ref=NULL,binding_revision=binding_revision+1
45
+ WHERE project_id=? AND task_id=?`).run(a.sourceRunRef,
46
+ runDigest(epoch,a.projectId,a.taskId,a.sourceRunRef,a.recoveryCredential),
47
+ r.approval_revision,a.projectId,a.taskId);
48
+ // Retain a durable one-use tombstone, so the same token cannot be reissued.
49
+ db.prepare("UPDATE permits SET kind='USED' WHERE project_id=? AND task_id=? AND action_token=?")
50
+ .run(a.projectId,a.taskId,a.recoveryActionToken);
51
+ return {status:'RESTORED_SAME_OWNER',runRef:a.sourceRunRef,
52
+ bindingRevision:r.binding_revision+1,recoveryActionToken:a.recoveryActionToken};
53
+ });
54
+ },
55
+
56
+ restoreFencedHandoff(a){
57
+ internal('run.bind.restore-fenced-handoff',a);
58
+ return receipt(a,'run.bind.restore-fenced-handoff',()=>{
59
+ const r=scope(a);
60
+ expectedBusiness(r,a.expectedTaskRevision);
61
+ expectedBinding(r,a.expectedBindingRevision);
62
+ const next=a.sessionId+':'+a.taskId+':'+(a.generation+1);
63
+ const source=a.sessionId+':'+a.taskId+':'+a.generation;
64
+ assert(r.writable_ref===null&&r.credential_digest===null
65
+ &&r.writer_approval_revision===null
66
+ &&r.pending_attempt===a.attemptId
67
+ &&r.pending_checkpoint===a.checkpointId
68
+ &&r.pending_target_generation===a.generation+1
69
+ &&r.pending_next_ref===next
70
+ &&r.pending_credential_digest!==null
71
+ &&a.sourceRunRef===source,'HANDOFF_RECOVERY_FENCE_MISMATCH');
72
+ assertPinnedHandoffCurrent(r,a.checkpointId);
73
+ const state=parse(r.context_json);
74
+ assert(state.executionOutcome!=='DONE'&&!state.deliveryRef
75
+ &&!state.sessionCancellation
76
+ &&unresolvedEffects(state).length===0,'RUN_RECOVERY_UNSAFE');
77
+ assert(hasApprovedPlan(parse(r.approval_json))
78
+ &&r.approval_revision===a.expectedApprovalRevision,
79
+ 'APPROVAL_REVOKED');
80
+ assert(typeof a.newRunCredential==='string'
81
+ &&/^[0-9a-f]{64}$/.test(a.newRunCredential),
82
+ 'WRITE_CREDENTIAL_INVALID');
83
+ assert(typeof a.recoveryActionToken==='string'
84
+ &&/^[a-f0-9]{32}$/.test(a.recoveryActionToken),
85
+ 'RECOVERY_TOKEN_INVALID');
86
+ const permits=db.prepare(
87
+ 'SELECT action_token,kind,approval_revision FROM permits WHERE project_id=? AND task_id=?'
88
+ ).all(a.projectId,a.taskId);
89
+ assert(permits.some(p=>p.action_token===a.attemptId
90
+ &&p.kind==='USED'&&p.approval_revision===r.approval_revision),
91
+ 'ORIGINAL_HANDOFF_PERMIT_UNVERIFIED');
92
+ assert(permits.filter(p=>p.kind!=='USED').length===1
93
+ &&permits.some(p=>p.action_token===a.recoveryActionToken
94
+ &&p.kind==='RECOVER_HANDOFF'
95
+ &&p.approval_revision===r.approval_revision),
96
+ 'RECOVERY_PERMIT_NOT_UNIQUE');
97
+ db.prepare('UPDATE tasks SET writable_ref=?,credential_digest=?,'
98
+ +'writer_approval_revision=?,pending_attempt=NULL,pending_checkpoint=NULL,'
99
+ +'pending_target_generation=NULL,pending_credential_digest=NULL,'
100
+ +'pending_next_ref=NULL,binding_revision=binding_revision+1 '
101
+ +'WHERE project_id=? AND task_id=?').run(source,
102
+ runDigest(epoch,a.projectId,a.taskId,source,a.newRunCredential),
103
+ r.approval_revision,a.projectId,a.taskId);
104
+ db.prepare("UPDATE permits SET kind='USED' WHERE project_id=? AND task_id=? AND action_token=?")
105
+ .run(a.projectId,a.taskId,a.recoveryActionToken);
106
+ return {status:'HANDOFF_WRITER_RESTORED',runRef:source,
107
+ bindingRevision:r.binding_revision+1,
108
+ recoveryActionToken:a.recoveryActionToken};
109
+ });
110
+ }
111
+ };
112
+ }
@@ -1,6 +1,11 @@
1
1
  // Context Core run methods. Shared access and transactions are injected from store.mjs.
2
2
  export function createRunMethods(values) {
3
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');
4
9
  return {
5
10
  reserve(a){
6
11
  return receipt(a,'start.reserve',()=>{
@@ -13,6 +18,7 @@ export function createRunMethods(values) {
13
18
  assert(hasApprovedPlan(approvals),'APPROVAL_REQUIRED');
14
19
  assert(r.approval_revision===a.expectedApprovalRevision,'APPROVAL_CONFLICT');
15
20
  const current=parse(r.context_json);
21
+ assertExecutableScope(current);
16
22
  if(a.purpose==='REPAIR_SAME_SCOPE'){
17
23
  assert(current.stage==='REOPENED'&&current.reopenReason==='REPAIR_SAME_SCOPE'
18
24
  &&current.reopenRequest?.sourceRole==='user'
@@ -50,6 +56,7 @@ export function createRunMethods(values) {
50
56
  ensureNoPendingIssue(a.projectId,a.taskId);
51
57
  const approvals=parse(r.approval_json);
52
58
  assert(hasApprovedPlan(approvals),'APPROVAL_REVOKED');
59
+ if((a.kind??'START')==='START')assertExecutableScope(parse(r.context_json));
53
60
  // Managed original-Chat Adopt is not authorized by a valid lease
54
61
  // alone. The observed R/P user turns must also be those approved for
55
62
  // THIS Task. The browser proof is soft; Native still owns the lease,
@@ -82,6 +89,29 @@ export function createRunMethods(values) {
82
89
  assert(r.writer_approval_revision===r.approval_revision,
83
90
  'ACTIVE_RUN_APPROVAL_STALE');
84
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
+ }
85
115
  if((a.kind??'START')==='START'){
86
116
  assert(r.writable_ref===null&&r.pending_attempt===null,'RUN_ALREADY_BOUND');
87
117
  const lease=db.prepare('SELECT * FROM start_leases WHERE lease_ref=?').get(a.leaseRef);
@@ -126,6 +156,7 @@ export function createRunMethods(values) {
126
156
  assert(permit.approval_revision===r.approval_revision &&
127
157
  hasApprovedPlan(parse(r.approval_json)),'APPROVAL_REVOKED');
128
158
  const initialContext=parse(r.context_json);
159
+ assertExecutableScope(initialContext);
129
160
  assert(initialContext.stage==='REOPENED' &&
130
161
  initialContext.reopenReason==='REPAIR_SAME_SCOPE' ||
131
162
  initialContext.executionOutcome!=='DONE' &&
@@ -331,45 +362,6 @@ export function createRunMethods(values) {
331
362
  return {status:'TERMINAL_FENCED',taskRevision:r.business_revision,
332
363
  bindingRevision:r.binding_revision+1};
333
364
  });
334
- },
335
- restoreSameOwner(a){
336
- internal('run.bind.restore-same-owner',a);
337
- return receipt(a,'run.bind.restore-same-owner',()=>{
338
- // These proofs are adapter assertions in W01 only. Real Worker/Native
339
- // provenance MUST be verified by the transport before W07 enables this.
340
- assert(a.sendState==='NOT_SENT' && a.oldActionTokenRevoked===true,
341
- 'SEND_NOT_PROVEN_ABSENT');
342
- assert(a.workerRestored===true && a.nativeRestored===true &&
343
- a.ownerStillSame===true,'OWNER_UNVERIFIED');
344
- const r=scope(a);expectedBusiness(r,a.expectedTaskRevision);
345
- expectedBinding(r,a.expectedBindingRevision);
346
- assert(r.writable_ref===null && r.pending_attempt===a.attemptId
347
- && r.pending_checkpoint===a.checkpointId,'HANDOFF_MISMATCH');
348
- assertPinnedHandoffCurrent(r,a.checkpointId);
349
- assert(typeof a.recoveryCredential==='string'&&a.recoveryCredential.length===64,
350
- 'WRITE_CREDENTIAL_INVALID');
351
- assert(typeof a.recoveryActionToken==='string'&&a.recoveryActionToken.length>=8,
352
- 'ACTION_TOKEN_REQUIRED');
353
- assert(typeof a.sourceRunRef==='string'&&a.sourceRunRef.length>=8,
354
- 'RUN_REF_MISSING');
355
- const permit=db.prepare('SELECT * FROM permits WHERE project_id=? AND task_id=? AND action_token=?')
356
- .get(a.projectId,a.taskId,a.recoveryActionToken);
357
- assert(permit&&permit.kind==='CONTINUE'
358
- &&permit.approval_revision===r.approval_revision,'RECOVERY_PERMIT_MISSING');
359
- assert(hasApprovedPlan(parse(r.approval_json)),'APPROVAL_REVOKED');
360
- db.prepare(`UPDATE tasks SET writable_ref=?,credential_digest=?,
361
- writer_approval_revision=?,pending_attempt=NULL,pending_checkpoint=NULL,
362
- pending_target_generation=NULL,pending_credential_digest=NULL,
363
- pending_next_ref=NULL,binding_revision=binding_revision+1
364
- WHERE project_id=? AND task_id=?`).run(a.sourceRunRef,
365
- runDigest(epoch,a.projectId,a.taskId,a.sourceRunRef,a.recoveryCredential),
366
- r.approval_revision,a.projectId,a.taskId);
367
- // Retain a durable one-use tombstone, so the same token cannot be reissued.
368
- db.prepare("UPDATE permits SET kind='USED' WHERE project_id=? AND task_id=? AND action_token=?")
369
- .run(a.projectId,a.taskId,a.recoveryActionToken);
370
- return {status:'RESTORED_SAME_OWNER',runRef:a.sourceRunRef,
371
- bindingRevision:r.binding_revision+1,recoveryActionToken:a.recoveryActionToken};
372
- });
373
365
  }
374
366
  };
375
367
  }
@@ -7,14 +7,14 @@ import {dirname} from 'node:path';
7
7
 
8
8
  // This module declares ports; index.mjs is the only dependency assembler.
9
9
  // No implementation module imports another implementation module.
10
- let createHealthMethods, createMigrationMethods, createProjectMethods, createTaskMethods, createReviewMethods, createEvidenceMethods, createContextMethods, createRunMethods, createCancelMethods, verifySourceUnit, inspectRegistryReferenceForReview, hasApprovedPlan, hasRequirementApproval, approvedTurnSourceMatches;
10
+ let createHealthMethods, createMigrationMethods, createProjectMethods, createTaskMethods, createReviewMethods, createEvidenceMethods, createContextMethods, createRunMethods, createCancelMethods, createRecoveryMethods, verifySourceUnit, inspectRegistryReferenceForReview, hasApprovedPlan, hasRequirementApproval, approvedTurnSourceMatches;
11
11
  let connected=false;
12
12
  export function configureCore(capabilities){
13
13
  if(connected)throw Error('CONTEXT_MODULE_ALREADY_COMPOSED');
14
- for(const name of ['createHealthMethods', 'createMigrationMethods', 'createProjectMethods', 'createTaskMethods', 'createReviewMethods', 'createEvidenceMethods', 'createContextMethods', 'createRunMethods', 'createCancelMethods', 'verifySourceUnit', 'inspectRegistryReferenceForReview', 'hasApprovedPlan', 'hasRequirementApproval', 'approvedTurnSourceMatches']){
14
+ for(const name of ['createHealthMethods', 'createMigrationMethods', 'createProjectMethods', 'createTaskMethods', 'createReviewMethods', 'createEvidenceMethods', 'createContextMethods', 'createRunMethods', 'createCancelMethods', 'createRecoveryMethods', 'verifySourceUnit', 'inspectRegistryReferenceForReview', 'hasApprovedPlan', 'hasRequirementApproval', 'approvedTurnSourceMatches']){
15
15
  if(capabilities?.[name]===undefined)throw Error('CONTEXT_MODULE_PORT_MISSING:'+name);
16
16
  }
17
- ({createHealthMethods, createMigrationMethods, createProjectMethods, createTaskMethods, createReviewMethods, createEvidenceMethods, createContextMethods, createRunMethods, createCancelMethods, verifySourceUnit, inspectRegistryReferenceForReview, hasApprovedPlan, hasRequirementApproval, approvedTurnSourceMatches}=capabilities);
17
+ ({createHealthMethods, createMigrationMethods, createProjectMethods, createTaskMethods, createReviewMethods, createEvidenceMethods, createContextMethods, createRunMethods, createCancelMethods, createRecoveryMethods, verifySourceUnit, inspectRegistryReferenceForReview, hasApprovedPlan, hasRequirementApproval, approvedTurnSourceMatches}=capabilities);
18
18
  connected=true;
19
19
  }
20
20
 
@@ -300,7 +300,7 @@ export function openContextProtocol(file,{authorizeInternal=()=>false,authorizeD
300
300
  'approval','approvals','approved','approvalRevision','rRef','pRef',
301
301
  'runRef','runCredential','credentialDigest','writableRunRef','pendingHandoff',
302
302
  'writeFenceRevision','bindingRevision','taskRevision','storeEpoch',
303
- 'projectRuleReview','effectResolutions','projectId','taskId','stage','executionOutcome',
303
+ 'projectRuleReview','scopeCorrection','effectResolutions','projectId','taskId','stage','executionOutcome',
304
304
  'deliveryRef','deliveredAt','acceptedAt','acceptance','acceptanceFeedback',
305
305
  'sessionCancellation',
306
306
  'reopenReason','reopenRequest','archivedAt','authority','migrationSourceUnitId',
@@ -392,6 +392,7 @@ export function openContextProtocol(file,{authorizeInternal=()=>false,authorizeD
392
392
  createEvidenceMethods(scopeValues),
393
393
  createContextMethods(scopeValues),
394
394
  createRunMethods(scopeValues),
395
- createCancelMethods(scopeValues)
395
+ createCancelMethods(scopeValues),
396
+ createRecoveryMethods(scopeValues)
396
397
  );
397
398
  }