@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,398 @@
1
+ // Authoritative single-handle Context SQLite Core. Domain methods compose here.
2
+ // No Chrome Owner, second writer, or independently committed domain transaction.
3
+ import {DatabaseSync} from 'node:sqlite';
4
+ import {createHash, randomUUID} from 'node:crypto';
5
+ import {mkdirSync,lstatSync,existsSync,chmodSync} from 'node:fs';
6
+ import {dirname} from 'node:path';
7
+
8
+ // This module declares ports; index.mjs is the only dependency assembler.
9
+ // No implementation module imports another implementation module.
10
+ let createHealthMethods, createMigrationMethods, createProjectMethods, createTaskMethods, createReviewMethods, createEvidenceMethods, createContextMethods, createRunMethods, createCancelMethods, createRecoveryMethods, verifySourceUnit, inspectRegistryReferenceForReview, hasApprovedPlan, hasRequirementApproval, approvedTurnSourceMatches;
11
+ let connected=false;
12
+ export function configureCore(capabilities){
13
+ if(connected)throw Error('CONTEXT_MODULE_ALREADY_COMPOSED');
14
+ for(const name of ['createHealthMethods', 'createMigrationMethods', 'createProjectMethods', 'createTaskMethods', 'createReviewMethods', 'createEvidenceMethods', 'createContextMethods', 'createRunMethods', 'createCancelMethods', 'createRecoveryMethods', 'verifySourceUnit', 'inspectRegistryReferenceForReview', 'hasApprovedPlan', 'hasRequirementApproval', 'approvedTurnSourceMatches']){
15
+ if(capabilities?.[name]===undefined)throw Error('CONTEXT_MODULE_PORT_MISSING:'+name);
16
+ }
17
+ ({createHealthMethods, createMigrationMethods, createProjectMethods, createTaskMethods, createReviewMethods, createEvidenceMethods, createContextMethods, createRunMethods, createCancelMethods, createRecoveryMethods, verifySourceUnit, inspectRegistryReferenceForReview, hasApprovedPlan, hasRequirementApproval, approvedTurnSourceMatches}=capabilities);
18
+ connected=true;
19
+ }
20
+
21
+ const fail=(code)=>Object.assign(new Error(code),{code});
22
+ const assert=(truth,code)=>{if(!truth)throw fail(code)};
23
+ const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
24
+ const canonical=x=>x===null||typeof x!=='object'?JSON.stringify(x):
25
+ Array.isArray(x)?'['+x.map(canonical).join(',')+']':
26
+ '{'+Object.keys(x).sort().map(k=>JSON.stringify(k)+':'+canonical(x[k])).join(',')+'}';
27
+ const digest=x=>createHash('sha256').update(typeof x==='string'?x:canonical(x)).digest('hex');
28
+ const runDigest=(epoch,projectId,taskId,runRef,credential)=>digest(['context-write-v1',epoch,projectId,taskId,runRef,credential]);
29
+ const parse=x=>JSON.parse(x);
30
+
31
+ export function openContextProtocol(file,{authorizeInternal=()=>false,authorizeData=()=>false,
32
+ authorizeAdmin=()=>false,principalId='private-mcp',
33
+ enableTestFixtures=false,allowCreate=false,verifyIntegrity=false,
34
+ readOnly=false}={}){
35
+ // Project access is derived from a trusted adapter; never from request principal.
36
+ assert(typeof principalId==='string' && principalId.length>0 && principalId.length<=64,
37
+ 'PRINCIPAL_INVALID');
38
+ // The decision is injected by the trusted adapter, not read from client payload.
39
+ // W01 tests use an explicit isolated fixture adapter. The normal default DENIES.
40
+ assert(typeof file==='string'&&file.length>0,'INVALID_DATABASE');
41
+ // A read request must not create a missing directory as a side effect.
42
+ if(readOnly)assert(existsSync(dirname(file)),'STORE_MISSING');
43
+ else mkdirSync(dirname(file),{recursive:true,mode:0o700});
44
+ const dir=lstatSync(dirname(file));
45
+ assert(dir.isDirectory()&&!dir.isSymbolicLink()&&!(dir.mode&0o077),'STATE_DIRECTORY_UNTRUSTED');
46
+ // existsSync follows dangling symlinks. A dangling Store path is not
47
+ // an absent database, even when the operator explicitly allows creation.
48
+ let fileStat=null;
49
+ try{fileStat=lstatSync(file)}
50
+ catch(error){
51
+ if(error.code!=='ENOENT')throw fail('STORE_FILE_UNTRUSTED');
52
+ }
53
+ const existed=fileStat!==null;
54
+ if(!existed)assert(allowCreate===true&&!readOnly,'STORE_MISSING');
55
+ else assert(fileStat.isFile()&&!fileStat.isSymbolicLink()
56
+ &&!(fileStat.mode&0o077)
57
+ &&(!process.getuid||fileStat.uid===process.getuid()),'STORE_FILE_UNTRUSTED');
58
+ const db=new DatabaseSync(file,{timeout:3500,readOnly});
59
+ // Check the existing schema BEFORE creating any application table or changing WAL.
60
+ // Never silently adopt an unrelated DB or recreate an empty authority.
61
+ if(existed){
62
+ const known=db.prepare("SELECT 1 AS present FROM sqlite_master WHERE type='table' AND name='meta'").get();
63
+ if(!known){db.close();throw fail('STORE_SCHEMA_UNKNOWN');}
64
+ const version=db.prepare("SELECT value FROM meta WHERE key='schemaVersion'").get()?.value;
65
+ const previousEpoch=db.prepare("SELECT value FROM meta WHERE key='storeEpoch'").get()?.value;
66
+ if(version!=='6'||!previousEpoch){db.close();throw fail('STORE_SCHEMA_MISMATCH');}
67
+ const previousMode=db.prepare("SELECT value FROM meta WHERE key='storeMode'").get()?.value;
68
+ if(!['ACTIVE','DIAGNOSTIC_ONLY','CUTOVER_FENCED'].includes(previousMode)){
69
+ db.close();throw fail('STORE_MODE_UNKNOWN');
70
+ }
71
+ const mandatory=['meta','projects','tasks','documents','issues','artifacts',
72
+ 'checkpoints','receipts','migrations','start_leases','permits','project_materials'];
73
+ const present=new Set(db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all()
74
+ .map(row=>row.name));
75
+ if(mandatory.some(name=>!present.has(name))){
76
+ db.close();throw fail('STORE_SCHEMA_INCOMPLETE');
77
+ }
78
+ // A v5 marker is not sufficient: SQLite IF NOT EXISTS will not repair
79
+ // a table whose columns were lost during an interrupted candidate update.
80
+ // Verify the security-critical layout before opening for writes.
81
+ const requiredColumns={
82
+ meta:['key','value'],
83
+ projects:['project_id','project_revision','title','shared_context_json','archived'],
84
+ tasks:['project_id','task_id','business_revision','adopted_project_revision',
85
+ 'binding_revision','writer_approval_revision','context_json',
86
+ 'approval_revision','approval_json','writable_ref','credential_digest',
87
+ 'pending_attempt','pending_checkpoint','pending_target_generation',
88
+ 'pending_credential_digest','pending_next_ref'],
89
+ checkpoints:['project_id','task_id','checkpoint_id','business_revision','snapshot_json'],
90
+ receipts:['store_epoch','principal','project_id','request_id','request_digest','result_json'],
91
+ documents:['project_id','task_id','document_id','version','kind','body',
92
+ 'content_hash','requirement_ref'],
93
+ issues:['project_id','task_id','issue_id','document_id','version',
94
+ 'content_hash','state','presented_ref'],
95
+ artifacts:['project_id','task_id','artifact_id','locator','role',
96
+ 'content_hash','retention','observed_at','source_status'],
97
+ migrations:['source_unit_id','project_id','source_path','source_hash',
98
+ 'source_scope','status','migration_revision','manifest_json','updated_at'],
99
+ start_leases:['lease_ref','project_id','task_id','approval_revision',
100
+ 'business_revision','expires_at'],
101
+ permits:['project_id','task_id','action_token','approval_revision','kind'],
102
+ project_materials:['project_id','material_id','version','kind','body','content_hash','source_path','provenance','created_at']
103
+ };
104
+ const incomplete=Object.entries(requiredColumns).some(([table,columns])=>{
105
+ const actual=new Set(db.prepare('PRAGMA table_info('+table+')').all()
106
+ .map(item=>item.name));
107
+ return columns.some(column=>!actual.has(column));
108
+ });
109
+ if(incomplete){db.close();throw fail('STORE_SCHEMA_INCOMPLETE');}
110
+ // Full integrity scan is an explicit local-admin/offline maintenance
111
+ // operation; never run O(database_size) on every MCP request.
112
+ if(verifyIntegrity){
113
+ const quick=db.prepare('PRAGMA quick_check').all();
114
+ if(quick.length!==1||quick[0].quick_check!=='ok'){
115
+ db.close();throw fail('STORE_INTEGRITY_FAILED');
116
+ }
117
+ }
118
+ }
119
+ if(!existed)chmodSync(file,0o600);
120
+ if(readOnly){
121
+ // Pure data reads never negotiate a journal change or perform DDL.
122
+ db.exec('PRAGMA query_only=ON; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=3500;');
123
+ }else{
124
+ // WAL and schema initialization are persistent: avoid write locks on
125
+ // the common path where the short-lived CLI opens an existing Store.
126
+ const journalMode=db.prepare('PRAGMA journal_mode').get()?.journal_mode;
127
+ if(journalMode!=='wal')db.exec('PRAGMA journal_mode=WAL;');
128
+ db.exec('PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=3500;');
129
+ }
130
+ if(!existed)db.exec(`
131
+ CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);
132
+ CREATE TABLE IF NOT EXISTS tasks(
133
+ project_id TEXT NOT NULL,task_id TEXT NOT NULL,
134
+ business_revision INTEGER NOT NULL DEFAULT 1,
135
+ adopted_project_revision INTEGER NOT NULL DEFAULT 1,
136
+ binding_revision INTEGER NOT NULL DEFAULT 0,
137
+ writer_approval_revision INTEGER,
138
+ context_json TEXT NOT NULL,
139
+ approval_revision INTEGER NOT NULL DEFAULT 1,
140
+ approval_json TEXT NOT NULL,
141
+ writable_ref TEXT,
142
+ credential_digest TEXT,
143
+ pending_attempt TEXT,
144
+ pending_checkpoint TEXT,
145
+ pending_target_generation INTEGER,
146
+ pending_credential_digest TEXT,
147
+ pending_next_ref TEXT,
148
+ PRIMARY KEY(project_id,task_id)
149
+ );
150
+ CREATE TABLE IF NOT EXISTS checkpoints(
151
+ project_id TEXT NOT NULL,task_id TEXT NOT NULL,checkpoint_id TEXT NOT NULL,
152
+ business_revision INTEGER NOT NULL,snapshot_json TEXT NOT NULL,
153
+ PRIMARY KEY(project_id,task_id,checkpoint_id),
154
+ FOREIGN KEY(project_id,task_id) REFERENCES tasks(project_id,task_id)
155
+ );
156
+ CREATE TABLE IF NOT EXISTS receipts(
157
+ store_epoch TEXT NOT NULL,principal TEXT NOT NULL,project_id TEXT NOT NULL,
158
+ request_id TEXT NOT NULL,request_digest TEXT NOT NULL,
159
+ result_json TEXT NOT NULL,
160
+ PRIMARY KEY(store_epoch,principal,project_id,request_id)
161
+ );
162
+ CREATE TABLE IF NOT EXISTS projects(
163
+ project_id TEXT PRIMARY KEY,project_revision INTEGER NOT NULL DEFAULT 1,
164
+ title TEXT NOT NULL,shared_context_json TEXT NOT NULL,
165
+ archived INTEGER NOT NULL DEFAULT 0
166
+ );
167
+ CREATE TABLE IF NOT EXISTS documents(
168
+ project_id TEXT NOT NULL,task_id TEXT NOT NULL,document_id TEXT NOT NULL,
169
+ version INTEGER NOT NULL,kind TEXT NOT NULL,body TEXT NOT NULL,
170
+ content_hash TEXT NOT NULL,requirement_ref TEXT,
171
+ PRIMARY KEY(project_id,task_id,document_id,version),
172
+ FOREIGN KEY(project_id,task_id) REFERENCES tasks(project_id,task_id)
173
+ );
174
+ CREATE TABLE IF NOT EXISTS issues(
175
+ project_id TEXT NOT NULL,task_id TEXT NOT NULL,issue_id TEXT NOT NULL,
176
+ document_id TEXT NOT NULL,version INTEGER NOT NULL,content_hash TEXT NOT NULL,
177
+ state TEXT NOT NULL DEFAULT 'PENDING',presented_ref TEXT,
178
+ PRIMARY KEY(project_id,task_id,issue_id),
179
+ FOREIGN KEY(project_id,task_id) REFERENCES tasks(project_id,task_id)
180
+ );
181
+ CREATE TABLE IF NOT EXISTS artifacts(
182
+ project_id TEXT NOT NULL,task_id TEXT NOT NULL,artifact_id TEXT NOT NULL,
183
+ locator TEXT NOT NULL,role TEXT NOT NULL,
184
+ content_hash TEXT,retention TEXT NOT NULL,
185
+ observed_at INTEGER NOT NULL,source_status TEXT NOT NULL,
186
+ PRIMARY KEY(project_id,task_id,artifact_id),
187
+ FOREIGN KEY(project_id,task_id) REFERENCES tasks(project_id,task_id)
188
+ );
189
+ CREATE TABLE IF NOT EXISTS migrations(
190
+ source_unit_id TEXT PRIMARY KEY,project_id TEXT NOT NULL,
191
+ source_path TEXT NOT NULL,source_hash TEXT NOT NULL,
192
+ source_scope TEXT NOT NULL,status TEXT NOT NULL,
193
+ migration_revision INTEGER NOT NULL DEFAULT 1,
194
+ manifest_json TEXT NOT NULL,updated_at INTEGER NOT NULL
195
+ );
196
+ CREATE TABLE IF NOT EXISTS project_materials(
197
+ project_id TEXT NOT NULL,material_id TEXT NOT NULL,
198
+ version INTEGER NOT NULL,kind TEXT NOT NULL,body TEXT NOT NULL,
199
+ content_hash TEXT NOT NULL,source_path TEXT,provenance TEXT NOT NULL,
200
+ created_at INTEGER NOT NULL,
201
+ PRIMARY KEY(project_id,material_id,version),
202
+ FOREIGN KEY(project_id) REFERENCES projects(project_id)
203
+ );
204
+ CREATE TABLE IF NOT EXISTS start_leases(
205
+ lease_ref TEXT PRIMARY KEY,project_id TEXT NOT NULL,task_id TEXT NOT NULL,
206
+ approval_revision INTEGER NOT NULL,business_revision INTEGER NOT NULL,
207
+ expires_at INTEGER NOT NULL
208
+ );
209
+ CREATE TABLE IF NOT EXISTS permits(
210
+ project_id TEXT NOT NULL,task_id TEXT NOT NULL,action_token TEXT NOT NULL,
211
+ approval_revision INTEGER NOT NULL,kind TEXT NOT NULL,
212
+ PRIMARY KEY(project_id,task_id,action_token)
213
+ );
214
+ `);
215
+ let epoch=db.prepare("SELECT value FROM meta WHERE key='storeEpoch'").get()?.value;
216
+ if(!existed){
217
+ epoch=randomUUID();
218
+ db.prepare("INSERT INTO meta(key,value) VALUES('schemaVersion','6')").run();
219
+ db.prepare("INSERT INTO meta(key,value) VALUES('storeEpoch',?)").run(epoch);
220
+ db.prepare("INSERT INTO meta(key,value) VALUES('storeMode','ACTIVE')").run();
221
+ }
222
+ const storeMode=db.prepare("SELECT value FROM meta WHERE key='storeMode'").get()?.value;
223
+ // Missing authority mode is not evidence of an ACTIVE database. In
224
+ // particular, never promote a partial/restored v5 Store by default.
225
+ if(!['ACTIVE','DIAGNOSTIC_ONLY','CUTOVER_FENCED'].includes(storeMode)){
226
+ db.close();throw fail('STORE_MODE_UNKNOWN');
227
+ }
228
+ const row=(p,t)=>db.prepare('SELECT * FROM tasks WHERE project_id=? AND task_id=?').get(p,t);
229
+ const required=(p,t)=>{const r=row(p,t);assert(!!r,'TASK_NOT_FOUND');return r;};
230
+ const projectDrift=r=>{
231
+ const p=db.prepare('SELECT project_revision FROM projects WHERE project_id=?')
232
+ .get(r.project_id);
233
+ return p?{projectRevision:p.project_revision,
234
+ adoptedProjectRevision:r.adopted_project_revision,
235
+ projectDrift:p.project_revision!==r.adopted_project_revision}
236
+ :{projectRevision:r.adopted_project_revision,
237
+ adoptedProjectRevision:r.adopted_project_revision,projectDrift:false};
238
+ };
239
+ const currentMode=()=>db.prepare("SELECT value FROM meta WHERE key='storeMode'")
240
+ .get()?.value;
241
+ const assertWriteMode=()=>{
242
+ const mode=currentMode();
243
+ assert(storeMode==='ACTIVE'&&mode==='ACTIVE',
244
+ mode==='CUTOVER_FENCED'||storeMode==='CUTOVER_FENCED'?
245
+ 'STORE_CUTOVER_FENCED':'STORE_DIAGNOSTIC_ONLY');
246
+ };
247
+ // One read-only snapshot transaction across Project, Task and Context.
248
+ // Keep each multi-read projection on the same revision or roll back on error.
249
+ const readSnapshot=fn=>{
250
+ db.exec('BEGIN');
251
+ try{const result=fn();db.exec('COMMIT');return result;}
252
+ catch(err){try{db.exec('ROLLBACK')}catch{}throw err;}
253
+ };
254
+ const tx=fn=>{
255
+ db.exec('BEGIN IMMEDIATE');
256
+ try{assertWriteMode();const v=fn();db.exec('COMMIT');return v;}
257
+ catch(e){try{db.exec('ROLLBACK')}catch{}throw e}
258
+ };
259
+ const checkIds=(p,t)=>assert(ID.test(p||'')&&ID.test(t||''),'INVALID_SCOPE');
260
+ const receipt=(req,op,fn)=>{
261
+ assert(req&&typeof req==='object','INVALID_ARGUMENT');
262
+ // Restored snapshots are a read-only diagnostic fork; they cannot be
263
+ // reauthorized by supplying the NEW epoch, a new token, or fake owner.
264
+ assertWriteMode();
265
+ const {projectId,taskId,expectedStoreEpoch,writeRequestId}=req;
266
+ assert(!Object.hasOwn(req,'principal'),'PRINCIPAL_FORBIDDEN');
267
+ assert(authorizeData('write',projectId,taskId,op)===true,'PROJECT_ACCESS_DENIED');
268
+ const principal=principalId;
269
+ checkIds(projectId,taskId);
270
+ assert(expectedStoreEpoch===epoch,'STALE_EPOCH');
271
+ assert(typeof writeRequestId==='string'&&writeRequestId.length>=8&&writeRequestId.length<=128,'REQUEST_ID_REQUIRED');
272
+ assert(typeof principal==='string'&&principal.length>0&&principal.length<=64,'INVALID_PRINCIPAL');
273
+ const identity={...req};
274
+ const hash=digest([op,identity]);
275
+ return tx(()=>{
276
+ const old=db.prepare('SELECT * FROM receipts WHERE store_epoch=? AND principal=? AND project_id=? AND request_id=?')
277
+ .get(epoch,principal,projectId,writeRequestId);
278
+ if(old){
279
+ assert(old.request_digest===hash,'REQUEST_ID_REUSE');
280
+ return parse(old.result_json);
281
+ }
282
+ const result=fn();
283
+ // Every result stored here is a non-secret durable receipt.
284
+ const safe=JSON.stringify(result);
285
+ db.prepare('INSERT INTO receipts VALUES(?,?,?,?,?,?)')
286
+ .run(epoch,principal,projectId,writeRequestId,hash,safe);
287
+ return result;
288
+ });
289
+ };
290
+ const internal=(op,a)=>{
291
+ assertWriteMode();
292
+ const decision=authorizeInternal(op,a);
293
+ assert(decision===true,'INTERNAL_ONLY');
294
+ };
295
+ const admin=(op,scope)=>assert(authorizeAdmin(op,scope)===true,'ADMIN_REQUIRED');
296
+ const readAuth=(projectId,taskId,op)=>{
297
+ assert(authorizeData('read',projectId,taskId,op)===true,'PROJECT_ACCESS_DENIED');
298
+ };
299
+ const protectedCurrentFields=new Set([
300
+ 'approval','approvals','approved','approvalRevision','rRef','pRef',
301
+ 'runRef','runCredential','credentialDigest','writableRunRef','pendingHandoff',
302
+ 'writeFenceRevision','bindingRevision','taskRevision','storeEpoch',
303
+ 'projectRuleReview','scopeCorrection','effectResolutions','projectId','taskId','stage','executionOutcome',
304
+ 'deliveryRef','deliveredAt','acceptedAt','acceptance','acceptanceFeedback',
305
+ 'sessionCancellation',
306
+ 'reopenReason','reopenRequest','archivedAt','authority','migrationSourceUnitId',
307
+ '__proto__','prototype','constructor'
308
+ ]);
309
+ const validContextPatch=(patch,current)=>{
310
+ assert(patch && typeof patch==='object'&&!Array.isArray(patch),'INVALID_PATCH');
311
+ assert(!Object.keys(patch).some(k=>protectedCurrentFields.has(k)),'PROTECTED_FIELD');
312
+ if(Object.hasOwn(patch,'unknownEffects')){
313
+ const previous=current?.unknownEffects??[];
314
+ const next=patch.unknownEffects;
315
+ assert(Array.isArray(previous)&&Array.isArray(next)&&next.length>=previous.length
316
+ &&next.length<=500,'UNKNOWN_EFFECTS_MUST_APPEND');
317
+ for(let i=0;i<previous.length;i++)
318
+ assert(canonical(previous[i])===canonical(next[i]),'UNKNOWN_EFFECTS_MUST_APPEND');
319
+ const seen=new Set();
320
+ for(const effect of next){
321
+ const ref=effect?.ref??effect?.id;
322
+ assert(effect&&typeof effect==='object'&&!Array.isArray(effect)
323
+ &&typeof ref==='string'&&ref.length>0&&ref.length<=256
324
+ &&['UNKNOWN','IN_FLIGHT'].includes(effect.status??effect.state)
325
+ &&!seen.has(ref),'UNKNOWN_EFFECT_INVALID');
326
+ seen.add(ref);
327
+ }
328
+ }
329
+ };
330
+ const unresolvedEffects=context=>{
331
+ const active=context.unknownEffects??[],resolutions=context.effectResolutions??[];
332
+ assert(Array.isArray(active)&&Array.isArray(resolutions),'UNKNOWN_EFFECTS_INVALID');
333
+ const resolved=new Set(resolutions.map(e=>e.ref));
334
+ return active.filter(e=>!resolved.has(e.ref??e.id));
335
+ };
336
+ const ensureNoPendingIssue=(p,t)=>{
337
+ assert(!db.prepare("SELECT 1 FROM issues WHERE project_id=? AND task_id=? AND state='PENDING' LIMIT 1")
338
+ .get(p,t),'ISSUE_PENDING');
339
+ };
340
+ const expectedBusiness=(r,v)=>assert(r.business_revision===v,'BUSINESS_VERSION_CONFLICT');
341
+ const expectedBinding=(r,v)=>assert(r.binding_revision===v,'BINDING_VERSION_CONFLICT');
342
+ // The frozen handoff names one immutable BUSINESS snapshot. A later agent
343
+ // cannot refresh expectedTaskRevision to reactivate a stale handoff, even
344
+ // if the private target credential and real Owner/Native proof still match.
345
+ const assertPinnedHandoffCurrent=(r,checkpointId)=>{
346
+ const cp=db.prepare('SELECT business_revision,snapshot_json FROM checkpoints WHERE project_id=? AND task_id=? AND checkpoint_id=?')
347
+ .get(r.project_id,r.task_id,checkpointId);
348
+ assert(cp&&cp.business_revision===r.business_revision,'CHECKPOINT_BUSINESS_DRIFT');
349
+ const snapshot=parse(cp.snapshot_json);
350
+ assert(snapshot.approvalRevision===r.approval_revision,
351
+ 'CHECKPOINT_APPROVAL_DRIFT');
352
+ assert(!projectDrift(r).projectDrift,'PROJECT_RULES_DRIFT');
353
+ ensureNoPendingIssue(r.project_id,r.task_id);
354
+ };
355
+ const written=(r,args)=>{
356
+ expectedBusiness(r,args.expectedTaskRevision);
357
+ expectedBinding(r,args.expectedBindingRevision);
358
+ assert(r.writable_ref!==null,'WRITER_FENCED');
359
+ assert(r.writable_ref===args.runRef,'RUN_REF_MISMATCH');
360
+ assert(typeof args.runCredential==='string' && args.runCredential.length===64,'WRITE_CREDENTIAL_MISSING');
361
+ assert(runDigest(epoch,args.projectId,args.taskId,args.runRef,args.runCredential)===r.credential_digest,
362
+ 'WRITE_CREDENTIAL_INVALID');
363
+ assert(hasApprovedPlan(parse(r.approval_json)),'APPROVAL_REVOKED');
364
+ assert(r.writer_approval_revision===r.approval_revision,
365
+ 'ACTIVE_RUN_APPROVAL_STALE');
366
+ assert(!projectDrift(r).projectDrift,'PROJECT_RULES_DRIFT');
367
+ ensureNoPendingIssue(r.project_id,r.task_id);
368
+ };
369
+ // The transaction/receipt caller owns authorization and CAS; this helper
370
+ // only centralizes the identical context-json + revision persistence SQL.
371
+ const saveTaskContext=(projectId,taskId,context)=>db.prepare(
372
+ 'UPDATE tasks SET context_json=?,business_revision=business_revision+1 WHERE project_id=? AND task_id=?'
373
+ ).run(JSON.stringify(context),projectId,taskId);
374
+ const publicTask=r=>({
375
+ projectId:r.project_id,taskId:r.task_id,
376
+ ...projectDrift(r),
377
+ taskRevision:r.business_revision,bindingRevision:r.binding_revision,
378
+ currentContext:parse(r.context_json),approvalRevision:r.approval_revision,
379
+ runRef:r.writable_ref,pendingHandoff:r.pending_attempt!==null,
380
+ pendingCheckpointId:r.pending_checkpoint
381
+ // never expose raw credential or hash, including pending digest
382
+ });
383
+ const scope=(a)=>required(a.projectId,a.taskId);
384
+ const scopeValues={fail, assert, ID, canonical, digest, runDigest, parse, db, epoch, storeMode, principalId, authorizeData, authorizeAdmin, enableTestFixtures, verifySourceUnit, inspectRegistryReferenceForReview, hasApprovedPlan, hasRequirementApproval, approvedTurnSourceMatches, randomUUID, row, required, projectDrift, currentMode, readSnapshot, checkIds, receipt, internal, admin, readAuth, validContextPatch, unresolvedEffects, ensureNoPendingIssue, expectedBusiness, expectedBinding, assertPinnedHandoffCurrent, written, saveTaskContext, publicTask, scope};
385
+ // Domain modules share ONE SQLite handle, transaction gate, and receipt authority.
386
+ return Object.assign({epoch,mode:storeMode},
387
+ createHealthMethods(scopeValues),
388
+ createMigrationMethods(scopeValues),
389
+ createProjectMethods(scopeValues),
390
+ createTaskMethods(scopeValues),
391
+ createReviewMethods(scopeValues),
392
+ createEvidenceMethods(scopeValues),
393
+ createContextMethods(scopeValues),
394
+ createRunMethods(scopeValues),
395
+ createCancelMethods(scopeValues),
396
+ createRecoveryMethods(scopeValues)
397
+ );
398
+ }