@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,264 @@
1
+ // Context Core task methods. Shared access and transactions are injected from store.mjs.
2
+ export function createTaskMethods(values) {
3
+ const {assert, ID, parse, db, saveTaskContext, authorizeData, enableTestFixtures, hasApprovedPlan, row, required, checkIds, receipt, readAuth, readSnapshot, validContextPatch, unresolvedEffects, ensureNoPendingIssue, expectedBusiness, written, publicTask, scope, admin, projectDrift} = values;
4
+ // Prior to first Start, an approved Task may record preflight findings only.
5
+ // No scope, permissions, business approvals or protected state can be patched.
6
+ const preflightFields=new Set(['progress','blockers','nextStep']);
7
+ const immutableScopeFields=new Set(['executionPermission','authorizedWorkspace','sourceAccess']);
8
+ const assertScopeUnchanged=patch=>assert(
9
+ !Object.keys(patch).some(key=>immutableScopeFields.has(key)),
10
+ 'TASK_SCOPE_IMMUTABLE');
11
+ const validPreflightReport=patch=>{
12
+ const keys=Object.keys(patch);
13
+ assert(keys.length>0&&keys.every(key=>preflightFields.has(key)),
14
+ 'PREFLIGHT_PATCH_SCOPE_DENIED');
15
+ for(const key of ['progress','blockers']){
16
+ if(!Object.hasOwn(patch,key))continue;
17
+ const entries=patch[key];
18
+ assert(Array.isArray(entries)&&entries.length<=100
19
+ &&entries.every(item=>typeof item==='string'&&item.length<=1200),
20
+ 'PREFLIGHT_PATCH_VALUE_INVALID');
21
+ }
22
+ if(Object.hasOwn(patch,'nextStep'))
23
+ assert(typeof patch.nextStep==='string'&&patch.nextStep.length<=1200,
24
+ 'PREFLIGHT_PATCH_VALUE_INVALID');
25
+ };
26
+ return {
27
+ taskCreate(a){
28
+ return receipt(a,'task.create',()=>{
29
+ const parent=db.prepare('SELECT project_revision,archived FROM projects WHERE project_id=?')
30
+ .get(a.projectId);
31
+ assert(parent&&!parent.archived,'PROJECT_NOT_FOUND');
32
+ assert(!row(a.projectId,a.taskId),'TASK_EXISTS');
33
+ assert(typeof a.title==='string'&&a.title.trim()&&a.title.length<=200,'INVALID_TITLE');
34
+ validContextPatch(a.context??{},{
35
+ unknownEffects:[]
36
+ });
37
+ // Task creation does not assign durable execution eligibility.
38
+ // A review round is governed by R/P approvals; old scope restrictions
39
+ // remain immutable and are still enforced by the Stage 03 Start gate.
40
+ assert(!Object.hasOwn(a.context??{},'executionPermission'),
41
+ 'TASK_CREATE_REVIEW_SCOPE_FORBIDDEN');
42
+ const ctx={title:a.title,objective:a.objective??'',stage:'DRAFT',
43
+ progress:[],blockers:[],unknownEffects:[],nextStep:'',...a.context};
44
+ db.prepare('INSERT INTO tasks(project_id,task_id,adopted_project_revision,context_json,approval_json) VALUES(?,?,?,?,?)')
45
+ .run(a.projectId,a.taskId,parent.project_revision,JSON.stringify(ctx),'[]');
46
+ return {status:'COMMITTED',taskId:a.taskId,taskRevision:1,bindingRevision:0};
47
+ });
48
+ },
49
+ taskList(projectId,options={}){
50
+ assert(ID.test(projectId||''),'INVALID_SCOPE');readAuth(projectId,null,'task.list');
51
+ const paged=options.limit!==undefined||options.cursor!==undefined;
52
+ // Preserve the legacy array for old local operator/readers. New agents
53
+ // request a bounded page explicitly and never hydrate hidden tasks.
54
+ if(!paged)return db.prepare('SELECT * FROM tasks WHERE project_id=? ORDER BY task_id')
55
+ .all(projectId).filter(r=>authorizeData('read',projectId,r.task_id,'task.get')===true)
56
+ .map(publicTask);
57
+ const limit=options.limit??30,cursor=options.cursor??null;
58
+ assert(Number.isSafeInteger(limit)&&limit>=1&&limit<=100,'TASK_PAGE_LIMIT_INVALID');
59
+ assert(cursor===null||ID.test(cursor),'TASK_CURSOR_INVALID');
60
+ return readSnapshot(()=>{
61
+ if(cursor!==null){
62
+ const row=db.prepare('SELECT 1 FROM tasks WHERE project_id=? AND task_id=?')
63
+ .get(projectId,cursor);
64
+ assert(row&&authorizeData('read',projectId,cursor,'task.get')===true,
65
+ 'TASK_CURSOR_INVALID');
66
+ }
67
+ const visibleIds=db.prepare('SELECT task_id FROM tasks WHERE project_id=? AND task_id>? ORDER BY task_id')
68
+ .all(projectId,cursor??'').map(r=>r.task_id)
69
+ .filter(id=>authorizeData('read',projectId,id,'task.get')===true)
70
+ .slice(0,limit+1);
71
+ const incomplete=visibleIds.length>limit,chosen=visibleIds.slice(0,limit);
72
+ const rows=chosen.length
73
+ ?db.prepare('SELECT * FROM tasks WHERE project_id=? AND task_id IN ('
74
+ +chosen.map(()=>'?').join(',')+') ORDER BY task_id')
75
+ .all(projectId,...chosen) : [];
76
+ return {tasks:rows.map(publicTask),incomplete,
77
+ nextCursor:incomplete?chosen.at(-1):null,limit};
78
+ });
79
+ },
80
+ // A review-only scope written from a stage-only intent may be corrected
81
+ // only by an independently confirmed local operator. This is not an MCP
82
+ // capability, not a generic patch, and not a grant to install or write.
83
+ taskCorrectReviewScope(a){
84
+ admin('task.reviewScope.correct',a.projectId);
85
+ return receipt(a,'task.correctReviewScope',()=>{
86
+ const r=scope(a);expectedBusiness(r,a.expectedTaskRevision);
87
+ assert(r.approval_revision===a.expectedApprovalRevision,'APPROVAL_CONFLICT');
88
+ assert(r.binding_revision===0&&r.writable_ref===null&&r.pending_attempt===null,
89
+ 'SCOPE_CORRECTION_ACTIVE_TASK');
90
+ assert(!projectDrift(r).projectDrift,'PROJECT_RULES_DRIFT');
91
+ ensureNoPendingIssue(a.projectId,a.taskId);
92
+ assert(hasApprovedPlan(parse(r.approval_json)),'APPROVAL_REQUIRED');
93
+ assert(!db.prepare('SELECT 1 FROM start_leases WHERE project_id=? AND task_id=? LIMIT 1')
94
+ .get(a.projectId,a.taskId),'SCOPE_CORRECTION_START_HISTORY');
95
+ assert(!db.prepare('SELECT 1 FROM permits WHERE project_id=? AND task_id=? LIMIT 1')
96
+ .get(a.projectId,a.taskId),'SCOPE_CORRECTION_START_HISTORY');
97
+ const current=parse(r.context_json);
98
+ assert(['REQUIREMENTS_REVIEW_ONLY','PLAN_REVIEW_ONLY'].includes(
99
+ current.executionPermission)
100
+ &&current.executionPermission===a.expectedPermission
101
+ &&!Object.hasOwn(current,'scopeCorrection'),
102
+ 'SCOPE_CORRECTION_NOT_ELIGIBLE');
103
+ assert(a.reason==='STAGE_ONLY_INTENT_MISCLASSIFIED'
104
+ &&typeof a.operatorEvidenceRef==='string'
105
+ &&a.operatorEvidenceRef.length>=8&&a.operatorEvidenceRef.length<=256,
106
+ 'SCOPE_CORRECTION_EVIDENCE_REQUIRED');
107
+ assert(current.executionOutcome!=='DONE'&&current.stage!=='ARCHIVED'
108
+ &&!current.sessionCancellation,'SCOPE_CORRECTION_TERMINAL_TASK');
109
+ assert(unresolvedEffects(current).length===0,'UNKNOWN_EFFECTS_UNRESOLVED');
110
+ const next={...current};
111
+ delete next.executionPermission;
112
+ next.scopeCorrection={from:a.expectedPermission,
113
+ to:'UNSPECIFIED_EXECUTION_ELIGIBILITY',
114
+ reason:a.reason,operatorEvidenceRef:a.operatorEvidenceRef,
115
+ proofLevel:'LOCAL_OPERATOR_TTY_CONFIRMATION',at:Date.now()};
116
+ saveTaskContext(a.projectId,a.taskId,next);
117
+ return {status:'SCOPE_CORRECTED_NOT_OPERATION_AUTHORIZED',
118
+ taskRevision:r.business_revision+1,bindingRevision:r.binding_revision,
119
+ approvalRevision:r.approval_revision};
120
+ });
121
+ },
122
+ taskPatch(a){
123
+ return receipt(a,'task.patch',()=>{
124
+ const r=scope(a);expectedBusiness(r,a.expectedTaskRevision);
125
+ const current=parse(r.context_json);
126
+ validContextPatch(a.patch,current);
127
+ assertScopeUnchanged(a.patch);
128
+ if(r.writable_ref!==null)written(r,a);
129
+ else{
130
+ assert(r.pending_attempt===null,'WRITER_FENCED');
131
+ const approvals=parse(r.approval_json);
132
+ if(approvals.length===0){
133
+ assert(current.stage==='DRAFT','CURRENT_CONTEXT_REQUIRES_ACTIVE_RUN');
134
+ }else{
135
+ assert(r.binding_revision===0&&hasApprovedPlan(approvals),
136
+ 'PREFLIGHT_REPORT_REQUIRES_APPROVED_IDLE_TASK');
137
+ validPreflightReport(a.patch);
138
+ // A pending/consumed Start is not a safe idle reporting window.
139
+ assert(!db.prepare('SELECT 1 FROM start_leases WHERE project_id=? AND task_id=? AND expires_at>? LIMIT 1')
140
+ .get(a.projectId,a.taskId,Date.now()),'PREFLIGHT_START_IN_FLIGHT');
141
+ assert(!db.prepare('SELECT 1 FROM permits WHERE project_id=? AND task_id=? LIMIT 1')
142
+ .get(a.projectId,a.taskId),'PREFLIGHT_START_IN_FLIGHT');
143
+ }
144
+ ensureNoPendingIssue(a.projectId,a.taskId);
145
+ }
146
+ const next={...current,...a.patch};
147
+ saveTaskContext(a.projectId,a.taskId,next);
148
+ return {status:'COMMITTED',taskRevision:r.business_revision+1,
149
+ bindingRevision:r.binding_revision};
150
+ });
151
+ },
152
+ taskReviewProjectRules(a){
153
+ return receipt(a,'task.reviewProjectRules',()=>{
154
+ const r=scope(a);expectedBusiness(r,a.expectedTaskRevision);
155
+ const p=db.prepare('SELECT project_revision FROM projects WHERE project_id=?')
156
+ .get(a.projectId);
157
+ assert(p&&p.project_revision===a.expectedProjectRevision,
158
+ 'PROJECT_VERSION_CONFLICT');
159
+ assert(['NO_SCOPE_IMPACT','R_AND_P_REAPPROVAL'].includes(a.impact),
160
+ 'PROJECT_RULE_IMPACT_REQUIRED');
161
+ assert(typeof a.reviewEvidenceRef==='string'&&a.reviewEvidenceRef.length>=8,
162
+ 'PROJECT_REVIEW_EVIDENCE_REQUIRED');
163
+ assert(r.writable_ref===null&&r.pending_attempt===null,'ACTIVE_TASK_REVIEW_DENIED');
164
+ const c={...parse(r.context_json),projectRuleReview:{
165
+ impact:a.impact,evidenceRef:a.reviewEvidenceRef,
166
+ adoptedRevision:p.project_revision,reviewedAt:Date.now(),proofLevel:'SOFT_AGENT_REVIEW'}};
167
+ const approvals=a.impact==='R_AND_P_REAPPROVAL'?'[]':r.approval_json;
168
+ db.prepare('UPDATE tasks SET adopted_project_revision=?,context_json=?,approval_json=?,approval_revision=approval_revision+?,business_revision=business_revision+1 WHERE project_id=? AND task_id=?')
169
+ .run(p.project_revision,JSON.stringify(c),approvals,
170
+ a.impact==='R_AND_P_REAPPROVAL'?1:0,a.projectId,a.taskId);
171
+ return {status:'REVIEWED',projectRevision:p.project_revision,
172
+ taskRevision:r.business_revision+1,
173
+ approvalRevision:r.approval_revision+(a.impact==='R_AND_P_REAPPROVAL'?1:0)};
174
+ });
175
+ },
176
+ taskArchive(a){
177
+ return receipt(a,'task.archive',()=>{
178
+ const r=scope(a);expectedBusiness(r,a.expectedTaskRevision);
179
+ assert(r.writable_ref===null&&r.pending_attempt===null,'ACTIVE_TASK_PREVENTS_ARCHIVE');
180
+ const next={...parse(r.context_json),stage:'ARCHIVED',archivedAt:Date.now()};
181
+ saveTaskContext(a.projectId,a.taskId,next);
182
+ return {status:'ARCHIVED',taskRevision:r.business_revision+1};
183
+ });
184
+ },
185
+ taskReopen(a){
186
+ return receipt(a,'task.reopen',()=>{
187
+ const r=scope(a);expectedBusiness(r,a.expectedTaskRevision);
188
+ assert(r.writable_ref===null&&r.pending_attempt===null,'ACTIVE_TASK_REOPEN_DENIED');
189
+ assert(a.reason==='REPAIR_SAME_SCOPE'&&typeof a.userTurn==='string'
190
+ &&a.userTurn.length>=8,'REOPEN_INTENT_REQUIRED');
191
+ const current=parse(r.context_json);
192
+ assert(unresolvedEffects(current).length===0,'UNKNOWN_EFFECTS_UNRESOLVED');
193
+ assert(current.executionOutcome==='DONE'||current.stage==='ARCHIVED',
194
+ 'REOPEN_STAGE_INVALID');
195
+ assert(hasApprovedPlan(parse(r.approval_json)),
196
+ 'REOPEN_APPROVAL_INVALID');
197
+ const next={...current,stage:'REOPENED',reopenReason:a.reason,
198
+ reopenRequest:{sourceRole:'user',userTurn:a.userTurn,at:Date.now()},
199
+ acceptance:'AWAITING',acceptedAt:null};
200
+ saveTaskContext(a.projectId,a.taskId,next);
201
+ return {status:'REOPENED',taskRevision:r.business_revision+1};
202
+ });
203
+ },
204
+ taskAccept(a){
205
+ return receipt(a,'task.accept',()=>{
206
+ const r=scope(a);expectedBusiness(r,a.expectedTaskRevision);
207
+ assert(typeof a.userTurn==='string'&&a.userTurn.length>=8,'ACCEPTANCE_SOURCE_REQUIRED');
208
+ const current=parse(r.context_json);
209
+ // REOPENED still retains the old DONE history but is not a new
210
+ // deliverable for acceptance until the repair is completed.
211
+ assert(current.executionOutcome==='DONE'&&current.stage==='DELIVERED',
212
+ 'DELIVERY_NOT_DONE');
213
+ // The user acceptance follows a committed terminal fence, not merely
214
+ // the model's DONE or an in-flight Context delivery.
215
+ assert(r.writable_ref===null&&r.pending_attempt===null,
216
+ 'TERMINAL_FENCE_REQUIRED');
217
+ // Record one independent decision per delivery. A rejection must
218
+ // proceed through an explicit user-authorized reopen and new delivery.
219
+ assert(current.acceptance==='AWAITING','ACCEPTANCE_ALREADY_RECORDED');
220
+ const next={...current,acceptance:a.decision==='ACCEPT'?'ACCEPTED':'REJECTED',
221
+ acceptanceFeedback:{userTurn:a.userTurn,sourceRole:'user',
222
+ comment:typeof a.comment==='string'?a.comment.slice(0,2000):'',
223
+ at:Date.now()},acceptedAt:a.decision==='ACCEPT'?Date.now():null};
224
+ assert(['ACCEPT','REJECT'].includes(a.decision),'INVALID_ACCEPTANCE_DECISION');
225
+ saveTaskContext(a.projectId,a.taskId,next);
226
+ return {status:next.acceptance,taskRevision:r.business_revision+1};
227
+ });
228
+ },
229
+ taskComplete(a){
230
+ return receipt(a,'task.complete',()=>{
231
+ const r=scope(a);written(r,a);
232
+ assert(typeof a.deliveryRef==='string'&&a.deliveryRef.length>=8,
233
+ 'DELIVERY_REF_REQUIRED');
234
+ const current=parse(r.context_json);
235
+ // A new requestId must not overwrite an already committed delivery.
236
+ // A user-authorized same-scope REOPENED run may deliver a repair.
237
+ assert(current.executionOutcome!=='DONE'
238
+ ||current.stage==='REOPENED'
239
+ &&current.reopenReason==='REPAIR_SAME_SCOPE',
240
+ 'TASK_ALREADY_DELIVERED');
241
+ assert(unresolvedEffects(current).length===0,
242
+ 'UNKNOWN_EFFECTS_UNRESOLVED');
243
+ const next={...current,stage:'DELIVERED',executionOutcome:'DONE',
244
+ deliveryRef:a.deliveryRef,acceptance:'AWAITING',deliveredAt:Date.now()};
245
+ saveTaskContext(a.projectId,a.taskId,next);
246
+ return {status:'DELIVERED',taskRevision:r.business_revision+1};
247
+ });
248
+ },
249
+ createFixtureTask(a){
250
+ assert(enableTestFixtures===true,'FIXTURE_DISABLED');
251
+ return receipt(a,'fixture.create',()=>{
252
+ assert(!row(a.projectId,a.taskId),'TASK_EXISTS');
253
+ assert(hasApprovedPlan(a.softApprovals),'APPROVAL_FIXTURE_INVALID');
254
+ db.prepare('INSERT INTO tasks(project_id,task_id,context_json,approval_json) VALUES(?,?,?,?)')
255
+ .run(a.projectId,a.taskId,JSON.stringify(a.context??{nextStep:'W1'}),JSON.stringify(a.softApprovals));
256
+ return {projectId:a.projectId,taskId:a.taskId,taskRevision:1,bindingRevision:0,approvalRevision:1};
257
+ });
258
+ },
259
+ get(projectId,taskId){
260
+ checkIds(projectId,taskId);readAuth(projectId,taskId,'task.get');
261
+ return publicTask(required(projectId,taskId));
262
+ }
263
+ };
264
+ }
@@ -0,0 +1,13 @@
1
+ // Pure, bounded line comparison for historical evidence reviews. Preserving
2
+ // each old line as an ordered subsequence is NOT approval or authorization.
3
+ export function reviewPreservedLines(archived,current){
4
+ const oldLines=archived.toString('utf8').split(/(?<=\n)/);
5
+ const newLines=current.toString('utf8').split(/(?<=\n)/);
6
+ let matched=0;
7
+ for(const line of newLines){
8
+ if(matched<oldLines.length&&line===oldLines[matched])matched++;
9
+ }
10
+ const insertionsOnly=matched===oldLines.length&&newLines.length>=oldLines.length;
11
+ return {originalLines:oldLines.length,currentLines:newLines.length,
12
+ insertionsOnly,insertedLines:insertionsOnly?newLines.length-oldLines.length:null};
13
+ }
@@ -0,0 +1,111 @@
1
+ // Context public API metadata, assembled from the generated capability catalog.
2
+ // No new operation requires editing this registry or adding a switch branch.
3
+ import {readFileSync} from 'node:fs';
4
+ export const CONTEXT_PACKAGE_VERSION=JSON.parse(readFileSync(new URL('../package.json',import.meta.url),'utf8')).version;
5
+ export const CONTEXT_CONTRACT='chat-loop.context-sdk.v2';
6
+ const registry=JSON.parse(readFileSync(
7
+ new URL('./capability-catalog.generated.json',import.meta.url),'utf8'));
8
+ const failure=code=>Object.assign(new Error(code),{code});
9
+ const groupGuide=registry.groups;
10
+ export const methodDefinitions=Object.freeze(registry.methods.map(m=>Object.freeze(m)));
11
+ export const methodById=new Map(methodDefinitions.map(m=>[m.id,m]));
12
+ if(methodDefinitions.length!==methodById.size||!groupGuide.length)
13
+ throw failure('CAPABILITY_CATALOG_INVALID');
14
+ const ID='^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$';
15
+ const scopeError=code=>Object.assign(new Error(code),{code});
16
+ // A grant is an atomic permission statement, not a bag of best-effort tokens.
17
+ // Do not silently drop malformed entries or normalize duplicate grants.
18
+ // Reused by the SDK CLI, Context Core, MCP Gateway, and Native binding.
19
+ export function parseContextAllowedProjects(raw){
20
+ if(typeof raw!=='string'||raw.trim()==='')
21
+ throw scopeError('CONTEXT_ALLOWED_PROJECTS_REQUIRED');
22
+ const entries=raw.split(',').map(x=>x.trim());
23
+ if(entries.some(x=>!new RegExp(ID).test(x))||
24
+ new Set(entries).size!==entries.length)
25
+ throw scopeError('CONTEXT_PROJECT_SCOPE_INVALID');
26
+ return new Set(entries);
27
+ }
28
+
29
+ export function listMethods(group,view='methods'){
30
+ const selected=methodDefinitions.filter(m=>!group||m.group===group);
31
+ if(view==='groups')return {
32
+ contractVersion:CONTEXT_CONTRACT,packageVersion:CONTEXT_PACKAGE_VERSION,
33
+ groups:groupGuide.filter(g=>!group||g.id===group).map(g=>{
34
+ const members=selected.filter(m=>m.group===g.id);
35
+ return {group:g.id,purpose:g.purpose,startWith:g.startWith,
36
+ methodCount:members.length,
37
+ readCount:members.filter(m=>m.mode==='read').length,
38
+ writeCount:members.filter(m=>m.mode==='write').length,
39
+ legacyMethods:members.filter(m=>m.lifecycle?.surface==='legacy').map(m=>m.id)};
40
+ })
41
+ };
42
+ if(view!=='methods')throw failure('INVALID_ARGUMENT');
43
+ return {contractVersion:CONTEXT_CONTRACT,packageVersion:CONTEXT_PACKAGE_VERSION,
44
+ methods:selected.map(({id,group,mode,description})=>
45
+ ({methodId:id,group,mode,description}))};
46
+ }
47
+ export function describeMethod(methodId){
48
+ const m=methodById.get(methodId);
49
+ if(!m)throw failure('METHOD_NOT_FOUND');
50
+ return {contractVersion:CONTEXT_CONTRACT,packageVersion:CONTEXT_PACKAGE_VERSION,
51
+ methodId:m.id,group:m.group,mode:m.mode,
52
+ description:m.description,inputSchema:m.inputSchema,
53
+ lifecycle:m.lifecycle??{surface:'public'},
54
+ outputContract:'JSON value, immutable hashes and explicit revision/authority where applicable',
55
+ errorContract:'typed error code; unknown write outcome requires original requestId receipt lookup'};
56
+ }
57
+ export const contextGatewayTools=[
58
+ {name:'chat_loop_context_get',
59
+ description:'Context SDK READ. First use sdk.methods.list, then sdk.methods.describe to discover authorized Project/Task/Document/Checkpoint operations; read project summary before expanding detail.',
60
+ inputSchema:{oneOf:methodDefinitions.filter(m=>m.mode==='read').map(m=>m.inputSchema)},
61
+ annotations:{readOnlyHint:true}},
62
+ {name:'chat_loop_context_mutate',
63
+ description:'Context SDK WRITE. First inspect current version and method Schema; use expectedStoreEpoch, revisions and unique writeRequestId. No internal Native run controls.',
64
+ inputSchema:{oneOf:methodDefinitions.filter(m=>m.mode==='write').map(m=>m.inputSchema)},
65
+ annotations:{readOnlyHint:false}}
66
+ ];
67
+ export function validateContextCall(name,args){
68
+ const mode=name==='chat_loop_context_get'?'read':
69
+ name==='chat_loop_context_mutate'?'write':null;
70
+ if(!mode)throw failure('UNKNOWN_TOOL');
71
+ if(!args||typeof args!=='object'||Array.isArray(args))
72
+ throw failure('INVALID_ARGUMENT');
73
+ const method=methodById.get(args.operation);
74
+ if(!method||method.mode!==mode)
75
+ throw failure('UNSUPPORTED_CONTEXT_OPERATION');
76
+ const spec=method.inputSchema;
77
+ if(spec.required.some(key=>!Object.hasOwn(args,key))
78
+ ||Object.keys(args).some(key=>!Object.hasOwn(spec.properties,key)))
79
+ throw failure('INVALID_ARGUMENT');
80
+ for(const [key,value] of Object.entries(args)){
81
+ if(!matchesSchema(value,spec.properties[key]))
82
+ throw failure('INVALID_ARGUMENT');
83
+ }
84
+ return method;
85
+ }
86
+ // Validate nested and top-level inputs from the *same* schema exposed to MCP.
87
+ // Open-ended domain objects (patch/context/evidence) remain validated by Core.
88
+ function matchesSchema(value,spec){
89
+ if(spec.const!==undefined&&value!==spec.const)return false;
90
+ if(spec.enum&&!spec.enum.includes(value))return false;
91
+ if(spec.type==='string')
92
+ return typeof value==='string'&&value.length>=(spec.minLength??0)
93
+ &&value.length<=(spec.maxLength??Infinity)
94
+ &&(!spec.pattern||new RegExp(spec.pattern).test(value));
95
+ if(spec.type==='integer')
96
+ return Number.isSafeInteger(value)&&(spec.minimum===undefined||value>=spec.minimum)
97
+ &&(spec.maximum===undefined||value<=spec.maximum);
98
+ if(spec.type==='array')
99
+ return Array.isArray(value)&&value.length>=(spec.minItems??0)
100
+ &&value.length<=(spec.maxItems??Infinity)
101
+ &&value.every(x=>!spec.items||matchesSchema(x,spec.items));
102
+ if(spec.type==='object'){
103
+ if(!value||typeof value!=='object'||Array.isArray(value))return false;
104
+ if(spec.required?.some(k=>!Object.hasOwn(value,k)))return false;
105
+ if(spec.additionalProperties===false&&Object.keys(value).some(k=>!Object.hasOwn(spec.properties??{},k)))
106
+ return false;
107
+ return Object.entries(spec.properties??{}).every(([key,child])=>
108
+ !Object.hasOwn(value,key)||matchesSchema(value[key],child));
109
+ }
110
+ return true;
111
+ }
@@ -0,0 +1,107 @@
1
+ // This module declares ports; index.mjs is the only dependency assembler.
2
+ // No implementation module imports another implementation module.
3
+ let openContextProtocol, CONTEXT_CONTRACT, validateContextCall, listMethods, describeMethod, projectDatabase, projectMeta, verifiedStoreFile, resolveProjects;
4
+ export let allowedProjects;
5
+ let connected=false;
6
+ export function configureOperations(capabilities){
7
+ if(connected)throw Error('CONTEXT_MODULE_ALREADY_COMPOSED');
8
+ for(const name of ['openContextProtocol', 'CONTEXT_CONTRACT', 'validateContextCall', 'listMethods', 'describeMethod', 'projectDatabase', 'projectMeta', 'verifiedStoreFile', 'resolveProjects', 'allowedProjects']){
9
+ if(capabilities?.[name]===undefined)throw Error('CONTEXT_MODULE_PORT_MISSING:'+name);
10
+ }
11
+ ({openContextProtocol, CONTEXT_CONTRACT, validateContextCall, listMethods, describeMethod, projectDatabase, projectMeta, verifiedStoreFile, resolveProjects, allowedProjects}=capabilities);
12
+ if(capabilities.capabilityRouter===undefined)throw Error('CONTEXT_MODULE_PORT_MISSING:capabilityRouter');
13
+ capabilityRouter=capabilities.capabilityRouter;
14
+ connected=true;
15
+ }
16
+ let capabilityRouter;
17
+
18
+ // Authorized Context SDK dispatcher. No Browser Owner and no internal run controls.
19
+ const fail=code=>Object.assign(new Error(code),{code});
20
+ // The single public dispatch already validated both the tool and Method Catalog.
21
+ // Do not duplicate schema parsing on every read (not even for SDK discovery).
22
+ async function runContextOperation(args,method){
23
+ const methodId=method.id;
24
+ if(method.id==='sdk.methods.list')return listMethods(args.group,args.view);
25
+ if(method.id==='sdk.methods.describe')return describeMethod(args.methodId);
26
+ const allowed=allowedProjects();
27
+ if(!allowed.size)throw fail('CONTEXT_ALLOWED_PROJECTS_REQUIRED');
28
+ if(methodId==='project.resolve')return resolveProjects(args,allowed);
29
+ if(methodId==='project.list'){
30
+ if(!process.env.CHAT_LOOP_CONTEXT_DB){
31
+ const publicProject=meta=>({
32
+ projectId:meta.projectId,title:meta.title,
33
+ projectRevision:meta.projectRevision,sharedContext:meta.sharedContext,
34
+ archived:meta.archived
35
+ });
36
+ const limit=args.limit??30,cursor=args.cursor??null;
37
+ if(cursor!==null&&(!allowed.has(cursor)||!projectMeta(cursor)))
38
+ throw fail('PROJECT_CURSOR_INVALID');
39
+ const entries=[];
40
+ for(const id of [...allowed].sort()){
41
+ if(cursor!==null&&id<=cursor)continue;
42
+ const meta=projectMeta(id);
43
+ if(!meta)continue;
44
+ entries.push(publicProject(meta));
45
+ if(entries.length>limit)break;
46
+ }
47
+ const incomplete=entries.length>limit,projects=entries.slice(0,limit);
48
+ return {projects,incomplete,nextCursor:incomplete?projects.at(-1).projectId:null,limit};
49
+ }
50
+ const db=openContextProtocol(process.env.CHAT_LOOP_CONTEXT_DB,{
51
+ readOnly:true,principalId:'private-mcp',
52
+ authorizeData:(_type,projectId)=>allowed.has(projectId),
53
+ authorizeInternal:()=>false});
54
+ try{return db.projectList({limit:args.limit??30,cursor:args.cursor})}finally{db.close()}
55
+ }
56
+ if(args.projectId!==undefined&&!allowed.has(args.projectId))throw fail('PROJECT_ACCESS_DENIED');
57
+ if(!args.projectId)throw fail('PROJECT_ID_REQUIRED');
58
+ return executeDb(args,allowed,method.mode,method);
59
+ }
60
+ export async function dispatchContextCall(name,args){
61
+ const method=validateContextCall(name,args);
62
+ if(method.mode==='read')return runContextOperation(args,method);
63
+ const allowed=allowedProjects();
64
+ if(!allowed.size)throw fail('CONTEXT_ALLOWED_PROJECTS_REQUIRED');
65
+ if(!allowed.has(args.projectId))throw fail('PROJECT_ACCESS_DENIED');
66
+ // A model-authorized business patch is NOT permission to bind a new workspace.
67
+ // Keep binding violations distinct even when generic project creation is disabled.
68
+ if(method.id==='project.patch' && Object.hasOwn(args.sharedContext,'workspaceRefs'))
69
+ throw fail('WORKSPACE_REBIND_REQUIRES_OPERATOR');
70
+ return executeDb(args,allowed,method.mode,method);
71
+ }
72
+ async function executeDb(a,allowed,mode,method){
73
+ if(Number(process.versions.node.split('.')[0])<24)throw fail('CONTEXT_RUNTIME_UNSUPPORTED');
74
+ // A read or ordinary write must never create a project directory or SQLite.
75
+ // Only explicit operator project init may create a previously absent Store.
76
+ const file=projectDatabase(a.projectId);
77
+ verifiedStoreFile(file,'STORE_MISSING');
78
+ // project.list/resolve already verify this; ordinary get/mutate must too.
79
+ // Read-only identity check precedes any writable SQLite open and rules out
80
+ // a copied/renamed or multi-Project database under the wrong directory.
81
+ if(!process.env.CHAT_LOOP_CONTEXT_DB)projectMeta(a.projectId);
82
+ const db=openContextProtocol(file,{
83
+ readOnly:mode==='read',
84
+ principalId:'private-mcp',authorizeData:(_type,projectId)=>allowed.has(projectId),
85
+ authorizeInternal:()=>false
86
+ });
87
+ try{
88
+ if(mode==='write'){
89
+ if(!db.projectBusinessAuthority(a.projectId).writable)
90
+ throw fail('PROJECT_CUTOVER_NOT_VERIFIED');
91
+ }
92
+ if(a.operation==='project.open'){
93
+ const {project,authority,tasks,taskCount,storeEpoch}=db.projectSnapshot(a.projectId);
94
+ return {contractVersion:CONTEXT_CONTRACT,project,authority,storeEpoch,
95
+ taskCount,tasks,incomplete:taskCount>tasks.length,
96
+ nextOperation:taskCount>tasks.length?'task.list':null};
97
+ }
98
+ if(a.operation==='task.open'){
99
+ const {project,authority,task,storeEpoch}=db.projectSnapshot(a.projectId,a.taskId);
100
+ return {contractVersion:CONTEXT_CONTRACT,task,storeEpoch,
101
+ projectRevision:project.projectRevision,authority};
102
+ }
103
+ // Keep the read-only Store alive through async capability completion.
104
+ // Never close the handle before a module's Promise settles.
105
+ return await capabilityRouter.execute(method,a,{db,projectRef:a.projectId});
106
+ }finally{db.close()}
107
+ }
@@ -0,0 +1,118 @@
1
+ // Restricted LOCAL OPERATOR path for orphaned Managed Run writer fencing.
2
+ // Not reachable through public Context MCP, and never asserts Task DONE.
3
+ import {createHash,randomUUID} from 'node:crypto';
4
+ import {DatabaseSync,backup} from 'node:sqlite';
5
+ import {chmodSync,existsSync,lstatSync,mkdirSync,readFileSync,writeFileSync} from 'node:fs';
6
+ import {homedir} from 'node:os';
7
+ import {verifyOrphanOwnerIdle} from '@tomflow/chatloop-extension';
8
+ import {join} from 'node:path';
9
+ // This module declares ports; index.mjs is the only dependency assembler.
10
+ // No implementation module imports another implementation module.
11
+ let openContextProtocol, contextRoot, allowedProjects, confirmWorkspaceOperator;
12
+ let connected=false;
13
+ export function configureOrphanOperator(capabilities){
14
+ if(connected)throw Error('CONTEXT_MODULE_ALREADY_COMPOSED');
15
+ for(const name of ['openContextProtocol', 'contextRoot', 'allowedProjects', 'confirmWorkspaceOperator']){
16
+ if(capabilities?.[name]===undefined)throw Error('CONTEXT_MODULE_PORT_MISSING:'+name);
17
+ }
18
+ ({openContextProtocol, contextRoot, allowedProjects, confirmWorkspaceOperator}=capabilities);
19
+ connected=true;
20
+ }
21
+
22
+ const fail=code=>Object.assign(Error(code),{code});
23
+ const assert=(ok,code)=>{if(!ok)throw fail(code)};
24
+ const SHA=/^[0-9a-f]{64}$/;
25
+ const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
26
+ const sha=buf=>createHash('sha256').update(buf).digest('hex');
27
+
28
+ export async function fenceOrphanRunOperator({
29
+ projectId,taskId,expectedRunRef,expectedTaskRevision,
30
+ expectedBindingRevision,expectedStoreEpoch,evidenceDocumentId,
31
+ evidenceVersion,evidenceHash,writeRequestId
32
+ }){
33
+ assert(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE==='1','ADMIN_REQUIRED');
34
+ assert(!process.env.CHAT_LOOP_CONTEXT_DB,'EXPLICIT_DB_INIT_REQUIRED');
35
+ assert(ID.test(projectId||'')&&ID.test(taskId||'')
36
+ &&allowedProjects().has(projectId),'PROJECT_ACCESS_DENIED');
37
+ assert(Number.isSafeInteger(expectedTaskRevision)&&expectedTaskRevision>=1
38
+ &&Number.isSafeInteger(expectedBindingRevision)&&expectedBindingRevision>=1
39
+ &&typeof expectedStoreEpoch==='string'&&expectedStoreEpoch.length>=10
40
+ &&typeof expectedRunRef==='string'&&expectedRunRef.length>=12
41
+ &&ID.test(evidenceDocumentId||'')&&Number.isSafeInteger(evidenceVersion)
42
+ &&evidenceVersion>0&&SHA.test(evidenceHash||'')
43
+ &&typeof writeRequestId==='string'&&writeRequestId.length>=8
44
+ &&writeRequestId.length<=128,'ORPHAN_ARGUMENT_INVALID');
45
+ const oldSessionId=expectedRunRef.split(':')[0];
46
+ assert(/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(oldSessionId)
47
+ &&expectedRunRef===oldSessionId+':'+taskId+':0','ORPHAN_RUN_REF_INVALID');
48
+ const before=verifyOrphanOwnerIdle({oldRunRef:expectedRunRef,projectId});
49
+ const file=join(contextRoot(),projectId,'context.sqlite');
50
+ const reader=openContextProtocol(file,{readOnly:true,principalId:'local-operator',
51
+ authorizeData:(_mode,p)=>p===projectId});
52
+ try{
53
+ assert(reader.epoch===expectedStoreEpoch,'STALE_EPOCH');
54
+ assert(reader.projectBusinessAuthority(projectId).writable,
55
+ 'PROJECT_CUTOVER_NOT_VERIFIED');
56
+ const task=reader.get(projectId,taskId);
57
+ assert(task.taskRevision===expectedTaskRevision
58
+ &&task.bindingRevision===expectedBindingRevision
59
+ &&task.runRef===expectedRunRef,'ORPHAN_CAS_STALE');
60
+ const evidence=reader.documentGet(projectId,taskId,evidenceDocumentId,evidenceVersion);
61
+ assert(evidence.kind==='REFERENCE'&&evidence.contentHash===evidenceHash
62
+ &&evidence.body.includes(expectedRunRef),'ORPHAN_EVIDENCE_UNVERIFIED');
63
+ }finally{reader.close()}
64
+ // Local operator approval is explicitly USER_DELEGATED_AGENT, not a
65
+ // platform-authenticated human R/P approval or an execution permission.
66
+ await confirmWorkspaceOperator('FENCE_ORPHAN',projectId,expectedTaskRevision,
67
+ [taskId,expectedRunRef,evidenceDocumentId,evidenceHash,before.sessionId]);
68
+ const after=verifyOrphanOwnerIdle({oldRunRef:expectedRunRef,projectId});
69
+ assert(JSON.stringify(after)===JSON.stringify(before),
70
+ 'NATIVE_CHANGED_DURING_REVIEW');
71
+ const archiveRoot=join(homedir(),'.chat-loop','backups');
72
+ const archive=join(archiveRoot,'orphan-fence-'+projectId+'-'+taskId+'-'+
73
+ expectedTaskRevision);
74
+ assert(!existsSync(archive),'ORPHAN_BACKUP_ALREADY_EXISTS');
75
+ mkdirSync(archive,{recursive:false,mode:0o700});
76
+ const dest=join(archive,'context-before.sqlite');
77
+ const source=new DatabaseSync(file,{readOnly:true});
78
+ try{await backup(source,dest)}finally{source.close()}
79
+ chmodSync(dest,0o600);
80
+ const backupHash=sha(readFileSync(dest));
81
+ const record={contract:'chat-loop.orphan-fence-operator.v1',
82
+ operator:'USER_DELEGATED_AGENT',projectId,taskId,oldSessionId,
83
+ expectedRunRef,expectedTaskRevision,expectedBindingRevision,
84
+ expectedStoreEpoch,evidenceDocumentId,evidenceVersion,evidenceHash,
85
+ currentNative:after,backup:dest,backupHash,
86
+ result:'PENDING',createdAt:new Date().toISOString()};
87
+ const manifest=join(archive,'manifest.json');
88
+ writeFileSync(manifest,JSON.stringify(record,null,2)+'\n',{mode:0o600,flag:'wx'});
89
+ const last=verifyOrphanOwnerIdle({oldRunRef:expectedRunRef,projectId});
90
+ assert(JSON.stringify(last)===JSON.stringify(before),
91
+ 'NATIVE_CHANGED_BEFORE_FENCE');
92
+ const db=openContextProtocol(file,{principalId:'local-operator',
93
+ authorizeData:(_mode,p)=>p===projectId,
94
+ authorizeAdmin:(op,p)=>p===projectId&&
95
+ ['run.orphan.fence','run.orphan.fence.reviewed'].includes(op)
96
+ &&JSON.stringify(verifyOrphanOwnerIdle({oldRunRef:expectedRunRef,projectId}))===JSON.stringify(before)});
97
+ let result;
98
+ try{
99
+ result=db.fenceOrphan({projectId,taskId,oldSessionId,
100
+ expectedRunRef,expectedTaskRevision,expectedBindingRevision,
101
+ expectedStoreEpoch,evidenceDocumentId,evidenceVersion,evidenceHash,
102
+ nativeSessionId:last.sessionId,nativeProjectId:last.projectId,
103
+ nativeTaskId:last.taskId,nativePhase:last.phase,
104
+ nativeUpdatedAt:last.updatedAt,writeRequestId});
105
+ const checked=db.get(projectId,taskId);
106
+ assert(checked.runRef===null
107
+ &&checked.bindingRevision===result.bindingRevision
108
+ &&checked.currentContext.executionOutcome!=='DONE',
109
+ 'ORPHAN_FENCE_RECEIPT_UNVERIFIED');
110
+ }finally{db.close()}
111
+ // Record final durable result without updating or replaying the receipt.
112
+ record.result=result;
113
+ const completion=join(archive,'completed.json');
114
+ writeFileSync(completion,JSON.stringify(record,null,2)+'\n',
115
+ {mode:0o600,flag:'wx'});
116
+ return {...result,backupManifest:manifest,completionReceipt:completion,
117
+ backupHash,operator:'USER_DELEGATED_AGENT'};
118
+ }
@@ -0,0 +1,20 @@
1
+ // Explicit ps-list dependency. This is a bounded observation, NOT a stop receipt.
2
+ import psList from 'ps-list';
3
+ const fail=code=>Object.assign(new Error(code),{code});
4
+ // Process observation uses the declared ps-list provider, not /bin/ps.
5
+ // Never treat a momentary empty snapshot as proof of all future writers.
6
+ export async function activeLegacyWriters(){
7
+ if(process.platform==='win32')throw fail('PROCESS_COMMAND_UNAVAILABLE');
8
+ let processes;
9
+ try{processes=await psList({all:false})}
10
+ catch{throw fail('PROCESS_INVENTORY_UNAVAILABLE')}
11
+ if(!Array.isArray(processes))throw fail('PROCESS_INVENTORY_UNAVAILABLE');
12
+ return processes.filter(p=>Number.isSafeInteger(p.pid)&&p.pid>1
13
+ &&p.pid!==process.pid&&typeof p.cmd==='string'
14
+ &&(/chatloop-tools\/bin\/cli\.mjs\s+mcp|@tomflow\/chatloop-tools.*\/bin\/cli\.mjs\s+mcp|chat-loop-local-tools.*\/bin\/cli\.mjs\s+mcp/.test(p.cmd)))
15
+ .slice(0,20).map(p=>p.pid);
16
+ }
17
+
18
+ // Internal seam for isolated fixture tests. Not part of npm entrypoints or
19
+ // the migration arguments; callers cannot provide a fake writer predicate.
20
+ export const knownWriterInventory={scan:activeLegacyWriters};