@tomflow/chatloop-tools 0.9.63 → 0.9.64

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 (154) 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/package.json +2 -12
  9. package/providers/extension.mjs +59 -16
  10. package/node_modules/@tomflow/chatloop-context/README.md +0 -240
  11. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +0 -48
  12. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +0 -151
  13. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +0 -376
  14. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +0 -266
  15. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +0 -134
  16. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +0 -82
  17. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +0 -349
  18. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +0 -72
  19. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +0 -73
  20. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +0 -507
  21. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +0 -11
  22. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +0 -192
  23. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +0 -277
  24. package/node_modules/@tomflow/chatloop-context/index.mjs +0 -236
  25. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +0 -86
  26. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +0 -77
  27. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +0 -1989
  28. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +0 -69
  29. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +0 -285
  30. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +0 -298
  31. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +0 -286
  32. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +0 -115
  33. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +0 -51
  34. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +0 -75
  35. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +0 -262
  36. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +0 -246
  37. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +0 -147
  38. package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +0 -54
  39. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +0 -375
  40. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +0 -397
  41. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +0 -183
  42. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +0 -13
  43. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +0 -111
  44. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +0 -107
  45. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +0 -118
  46. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +0 -20
  47. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +0 -316
  48. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +0 -153
  49. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +0 -19
  50. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +0 -117
  51. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +0 -97
  52. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +0 -169
  53. package/node_modules/@tomflow/chatloop-context/package.json +0 -40
  54. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +0 -114
  55. package/node_modules/@tomflow/chatloop-extension/README.md +0 -124
  56. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +0 -13
  57. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +0 -153
  58. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +0 -207
  59. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +0 -1
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +0 -1
  61. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +0 -1
  62. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +0 -1
  63. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +0 -1
  64. package/node_modules/@tomflow/chatloop-extension/capabilities/entry_test.mjs +0 -1
  65. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +0 -1
  66. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +0 -1
  67. package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +0 -1
  68. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +0 -1
  69. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +0 -1
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +0 -123
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +0 -183
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +0 -340
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +0 -2
  74. package/node_modules/@tomflow/chatloop-extension/extension/actions/entry_test.js +0 -241
  75. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +0 -393
  76. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +0 -2
  77. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +0 -56
  78. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +0 -9
  79. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +0 -20
  80. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +0 -77
  81. package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +0 -52
  82. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +0 -295
  83. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +0 -24
  84. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +0 -2
  85. package/node_modules/@tomflow/chatloop-extension/extension/background.js +0 -17
  86. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +0 -5
  87. package/node_modules/@tomflow/chatloop-extension/extension/content.js +0 -40
  88. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +0 -9
  89. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +0 -17
  90. package/node_modules/@tomflow/chatloop-extension/extension/entry_test.html +0 -6
  91. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +0 -9
  92. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +0 -2
  93. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +0 -275
  94. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +0 -84
  95. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +0 -107
  96. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +0 -36
  97. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +0 -299
  98. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +0 -144
  99. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +0 -171
  100. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +0 -109
  101. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +0 -154
  102. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +0 -259
  103. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +0 -42
  104. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +0 -25
  105. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +0 -99
  106. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +0 -17
  107. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +0 -17
  108. package/node_modules/@tomflow/chatloop-extension/extension/session.html +0 -6
  109. package/node_modules/@tomflow/chatloop-extension/extension/start.html +0 -6
  110. package/node_modules/@tomflow/chatloop-extension/extension/status.html +0 -6
  111. package/node_modules/@tomflow/chatloop-extension/extension/text.html +0 -17
  112. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +0 -136
  113. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +0 -218
  114. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +0 -124
  115. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +0 -296
  116. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +0 -186
  117. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +0 -126
  118. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +0 -230
  119. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +0 -163
  120. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +0 -345
  121. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +0 -192
  122. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +0 -161
  123. package/node_modules/@tomflow/chatloop-extension/extension/worker/session-control.js +0 -75
  124. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +0 -197
  125. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +0 -205
  126. package/node_modules/@tomflow/chatloop-extension/index.mjs +0 -71
  127. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +0 -19
  128. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +0 -82
  129. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +0 -303
  130. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +0 -89
  131. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +0 -45
  132. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +0 -115
  133. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +0 -75
  134. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +0 -185
  135. package/node_modules/@tomflow/chatloop-extension/package.json +0 -38
  136. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +0 -138
  137. package/node_modules/@tomflow/chatloop-trace/README.md +0 -118
  138. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +0 -23
  139. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +0 -22
  140. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +0 -4
  141. package/node_modules/@tomflow/chatloop-trace/index.mjs +0 -59
  142. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +0 -273
  143. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +0 -308
  144. package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +0 -140
  145. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +0 -236
  146. package/node_modules/@tomflow/chatloop-trace/package.json +0 -30
  147. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +0 -68
  148. package/node_modules/ps-list/index.d.ts +0 -76
  149. package/node_modules/ps-list/index.js +0 -366
  150. package/node_modules/ps-list/license +0 -9
  151. package/node_modules/ps-list/package.json +0 -44
  152. package/node_modules/ps-list/readme.md +0 -56
  153. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  154. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
@@ -1,286 +0,0 @@
1
- // SourceUnit migration helpers shared by Chat Loop self-host and user projects.
2
- // Never infer task approvals, Browser Owner, or a runnable checkpoint from
3
- // Markdown/legacy Registry. Default mode is read-only SHADOW.
4
- import {createHash,randomUUID} from 'node:crypto';
5
- import {readFileSync,writeFileSync,mkdirSync,lstatSync,copyFileSync,chmodSync,constants,
6
- realpathSync,linkSync,unlinkSync,openSync,readSync,closeSync} from 'node:fs';
7
- import {basename,dirname,join,resolve,isAbsolute} from 'node:path';
8
- import {DatabaseSync,backup} from 'node:sqlite';
9
- // This module declares ports; index.mjs is the only dependency assembler.
10
- // No implementation module imports another implementation module.
11
- let reviewPreservedLines;
12
- let connected=false;
13
- export function configureMigrationSource(capabilities){
14
- if(connected)throw Error('CONTEXT_MODULE_ALREADY_COMPOSED');
15
- for(const name of ['reviewPreservedLines']){
16
- if(capabilities?.[name]===undefined)throw Error('CONTEXT_MODULE_PORT_MISSING:'+name);
17
- }
18
- ({reviewPreservedLines}=capabilities);
19
- connected=true;
20
- }
21
-
22
- const fail=code=>Object.assign(new Error(code),{code});
23
- const assert=(b,c)=>{if(!b)throw fail(c)};
24
- const hash=x=>createHash('sha256').update(x).digest('hex');
25
- const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
26
- // A dangling link is an occupied output path, never an absent artifact.
27
- const occupied=file=>{
28
- try{lstatSync(file);return true}
29
- catch(error){if(error.code==='ENOENT')return false;throw error}
30
- };
31
- // Hash large online backups incrementally; never load a 2 GiB database
32
- // into the Agent/CLI process just to check its integrity.
33
- const hashLargeFile=(file,max=2*1024*1024*1024)=>{
34
- assert(typeof file==='string'&&isAbsolute(file),'SOURCE_PATH_INVALID');
35
- const st=lstatSync(file);
36
- assert(st.isFile()&&!st.isSymbolicLink()&&st.size>0&&st.size<=max,
37
- 'BACKUP_SOURCE_UNTRUSTED');
38
- const fd=openSync(file,constants.O_RDONLY);
39
- const hasher=createHash('sha256'),chunk=Buffer.alloc(64*1024);
40
- let length=0;
41
- try{
42
- let n;
43
- while((n=readSync(fd,chunk,0,chunk.length,null))>0){
44
- hasher.update(chunk.subarray(0,n));length+=n;
45
- assert(length<=max,'BACKUP_TOO_LARGE');
46
- }
47
- }finally{closeSync(fd)}
48
- assert(length===st.size,'BACKUP_CHANGED_WHILE_READING');
49
- return {path:realpathSync(file),hash:hasher.digest('hex'),bytes:length};
50
- };
51
- const safeRead=(file,max=4*1024*1024)=>{
52
- assert(typeof file==='string'&&isAbsolute(file),'SOURCE_PATH_INVALID');
53
- const st=lstatSync(file);
54
- assert(st.isFile()&&!st.isSymbolicLink()&&st.size>0&&st.size<=max,'SOURCE_UNTRUSTED');
55
- return {stat:st,bytes:readFileSync(file),path:realpathSync(file)};
56
- };
57
- const privateDirectory=dir=>{
58
- mkdirSync(dir,{recursive:true,mode:0o700});
59
- const st=lstatSync(dir);
60
- assert(st.isDirectory()&&!st.isSymbolicLink()&&!(st.mode&0o077)
61
- &&(!process.getuid||st.uid===process.getuid()),'PRIVATE_DIR_UNTRUSTED');
62
- };
63
- const safeOutput=(file,value)=>{
64
- const dir=dirname(file);privateDirectory(dir);
65
- const tmp=join(dir,'.'+basename(file)+'.'+randomUUID()+'.tmp');
66
- try{
67
- writeFileSync(tmp,JSON.stringify(value,null,2)+'\n',{flag:'wx',mode:0o600});
68
- // Atomic create-if-absent: rename would replace an existing artifact.
69
- linkSync(tmp,file);
70
- }finally{try{unlinkSync(tmp)}catch{}}
71
- };
72
- export function scanSourceUnit({sourcePath,projectId,kind}){
73
- assert(ID.test(projectId||''),'PROJECT_ID_INVALID');
74
- assert(['REGISTRY_JSON','MIXED_CONTEXT','DOCUMENT'].includes(kind),'SOURCE_KIND_INVALID');
75
- const source=safeRead(sourcePath,kind==='MIXED_CONTEXT'?8*1024*1024:4*1024*1024);
76
- const evidence={sourceUnitId:hash(source.path),sourcePath:source.path,
77
- projectId,sourceHash:hash(source.bytes),sourceSize:source.stat.size,
78
- sourceKind:kind,sourceScope:kind==='MIXED_CONTEXT'?'PROJECT_SHARED':'SOURCE_FILE',
79
- observedAt:Date.now(),status:'SHADOW_RO',ownership:'EVIDENCE_ONLY',
80
- tasks:[],unknownItems:[],knownWriters:['legacy-gateway','file-tools','user-editor'],
81
- provenance:'SOURCE_READ_ONLY'};
82
- if(kind!=='REGISTRY_JSON'){
83
- // A mixed CURRENT can span Projects/Tasks; never parse arbitrary prose
84
- // into a verified Task or R/P/approval fact.
85
- evidence.unknownItems.push({reason:'UNCLASSIFIED_HISTORICAL_CONTENT',
86
- sourcePath:source.path,sourceHash:evidence.sourceHash});
87
- return evidence;
88
- }
89
- let legacy;
90
- try{legacy=JSON.parse(source.bytes.toString('utf8'))}catch{throw fail('LEGACY_REGISTRY_CORRUPT')}
91
- assert(legacy?.schemaVersion===1&&legacy.projects&&typeof legacy.projects==='object'
92
- &&!Array.isArray(legacy.projects),'LEGACY_REGISTRY_INVALID');
93
- const legacyProject=legacy.projects[projectId];
94
- if(!legacyProject){
95
- evidence.unknownItems.push({reason:'PROJECT_NOT_IN_REGISTRY',sourceHash:evidence.sourceHash});
96
- return evidence;
97
- }
98
- assert(legacyProject.tasks&&typeof legacyProject.tasks==='object'
99
- &&!Array.isArray(legacyProject.tasks),'LEGACY_TASK_MAP_INVALID');
100
- evidence.ownership='VERIFIED_REGISTRY_IDENTITIES_ONLY';
101
- for(const [taskId,t] of Object.entries(legacyProject.tasks)){
102
- assert(ID.test(taskId),'LEGACY_TASK_ID_INVALID');
103
- // The only guaranteed importable fact is the old registry's identity
104
- // and source reference. Approval/status/Owner are NEVER synthesized.
105
- assert(t.taskId===taskId&&t.projectId===projectId,'LEGACY_TASK_ID_MISMATCH');
106
- const doc=safeRead(t.taskDocPath,512*1024);
107
- const labels=[...doc.bytes.toString('utf8').matchAll(
108
- /^\s*(?:[-*]\s*)?taskId\s*[::]\s*["'\x60]?([a-zA-Z0-9][a-zA-Z0-9._-]*)/gmi)];
109
- assert(labels.length===1&&labels[0][1]===taskId,'LEGACY_DOCUMENT_TASK_ID_UNVERIFIED');
110
- evidence.tasks.push({taskId,title:t.title,taskDocPath:doc.path,
111
- taskDocumentHash:hash(doc.bytes),parentTaskId:t.parentTaskId??null,
112
- legacyRevision:t.revision,
113
- documents:(t.documents??[]).map(d=>({role:d.role,locator:d.sourcePath,
114
- versionRef:d.versionRef??null,sourceStatus:'UNVERIFIED'})),
115
- approvalStatus:'UNVERIFIED',executionOutcome:'UNVERIFIED'});
116
- }
117
- return evidence;
118
- }
119
- export function verifySourceUnit(manifest){
120
- const current=scanSourceUnit({sourcePath:manifest.sourcePath,
121
- projectId:manifest.projectId,kind:manifest.sourceKind});
122
- assert(current.sourceHash===manifest.sourceHash,'SOURCE_CHANGED');
123
- assert(current.sourceUnitId===manifest.sourceUnitId,'SOURCE_REPLACED');
124
- if(manifest.sourceKind==='REGISTRY_JSON'){
125
- assert(JSON.stringify(current.tasks)===JSON.stringify(manifest.tasks),
126
- 'LEGACY_REFERENCE_CHANGED');
127
- }
128
- return {status:'MATCHED',sourceUnitId:manifest.sourceUnitId,
129
- sourceHash:current.sourceHash};
130
- }
131
- export function saveShadowManifest(file,items){
132
- assert(Array.isArray(items)&&items.length>0&&items.length<=128,'MANIFEST_INVALID');
133
- const unique=new Set(items.map(x=>x.sourceUnitId));
134
- assert(unique.size===items.length,'SOURCE_UNIT_DUPLICATED');
135
- const manifest={contract:'chat-loop.context-source-units.v1',
136
- instanceLineage:randomUUID(),createdAt:Date.now(),
137
- status:'SHADOW_RO',sourceUnits:items,permissions:'READ_ONLY',
138
- taskApprovalsImported:false,ownerImported:false,
139
- knownWritersStopped:false};
140
- assert(!occupied(file),'MANIFEST_EXISTS');
141
- safeOutput(file,manifest);
142
- return manifest;
143
- }
144
- export function readShadowManifest(file){
145
- const path=resolve(file),st=lstatSync(path);
146
- assert(st.isFile()&&!st.isSymbolicLink()&&!(st.mode&0o077)
147
- &&(!process.getuid||st.uid===process.getuid()),'MANIFEST_UNTRUSTED');
148
- const manifest=JSON.parse(readFileSync(path,'utf8'));
149
- assert(manifest?.contract==='chat-loop.context-source-units.v1'
150
- &&Array.isArray(manifest.sourceUnits)&&manifest.sourceUnits.length>0,
151
- 'MANIFEST_SCHEMA_INVALID');
152
- return manifest;
153
- }
154
- export function verifyShadowManifest(file){
155
- const m=readShadowManifest(file);
156
- return {status:'SHADOW_MATCHED',checks:m.sourceUnits.map(verifySourceUnit),
157
- sourceUnits:m.sourceUnits.length};
158
- }
159
- // SQLite online backup: never copy a live database's main file.
160
- export async function backupContextDb(dbHandle,targetFile){
161
- assert(typeof targetFile==='string'&&isAbsolute(targetFile),'BACKUP_PATH_INVALID');
162
- assert(!occupied(targetFile),'BACKUP_EXISTS');
163
- privateDirectory(dirname(targetFile));
164
- try{
165
- await backup(dbHandle,targetFile);
166
- chmodSync(targetFile,0o600);
167
- const st=lstatSync(targetFile);
168
- assert(st.isFile()&&!st.isSymbolicLink(),'BACKUP_UNTRUSTED');
169
- const ready=hashLargeFile(targetFile);
170
- return {...ready,status:'BACKED_UP'};
171
- }catch(e){try{unlinkSync(targetFile)}catch{}throw e}
172
- }
173
- // Restore is an OFFLINE fork with a fresh Store epoch, never an in-place
174
- // replacement of an active database or a Browser Owner resurrector.
175
- export function restoreBackupToDiagnosticBranch({
176
- backupFile,targetDb,expectedBackupHash,manifestFile
177
- }){
178
- assert(typeof backupFile==='string'&&isAbsolute(backupFile)
179
- &&typeof targetDb==='string'&&isAbsolute(targetDb)
180
- &&typeof manifestFile==='string'&&isAbsolute(manifestFile)
181
- &&typeof expectedBackupHash==='string'&&/^[a-f0-9]{64}$/.test(expectedBackupHash),
182
- 'RESTORE_ARGUMENT_INVALID');
183
- assert(!occupied(targetDb)&&!occupied(manifestFile),'RESTORE_TARGET_EXISTS');
184
- const source=hashLargeFile(backupFile);
185
- assert(source.hash===expectedBackupHash,'BACKUP_HASH_MISMATCH');
186
- privateDirectory(dirname(targetDb));
187
- copyFileSync(source.path,targetDb,constants.COPYFILE_EXCL);
188
- chmodSync(targetDb,0o600);
189
- let db;
190
- try{
191
- db=new DatabaseSync(targetDb);
192
- const version=db.prepare("SELECT value FROM meta WHERE key='schemaVersion'").get()?.value;
193
- const previousEpoch=db.prepare("SELECT value FROM meta WHERE key='storeEpoch'").get()?.value;
194
- assert(version==='6'&&typeof previousEpoch==='string'&&previousEpoch.length>0,
195
- 'BACKUP_SCHEMA_UNSUPPORTED');
196
- const integrity=db.prepare('PRAGMA integrity_check').all();
197
- assert(integrity.length===1&&integrity[0].integrity_check==='ok','BACKUP_CORRUPT');
198
- const newEpoch=randomUUID();
199
- db.exec('PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON;');
200
- db.exec('BEGIN IMMEDIATE');
201
- try{
202
- db.prepare("UPDATE meta SET value=? WHERE key='storeEpoch'").run(newEpoch);
203
- db.prepare("INSERT OR REPLACE INTO meta(key,value) VALUES('storeMode','DIAGNOSTIC_ONLY')").run();
204
- db.prepare("INSERT OR REPLACE INTO meta(key,value) VALUES('restoredFromEpoch',?)")
205
- .run(previousEpoch);
206
- db.exec(`UPDATE tasks SET writable_ref=NULL,credential_digest=NULL,
207
- writer_approval_revision=NULL,pending_attempt=NULL,pending_checkpoint=NULL,pending_target_generation=NULL,
208
- pending_credential_digest=NULL,pending_next_ref=NULL,binding_revision=binding_revision+1;
209
- DELETE FROM permits;DELETE FROM start_leases;
210
- UPDATE migrations SET status='RESTORED_DIAGNOSTIC',
211
- migration_revision=migration_revision+1,updated_at=0;`);
212
- db.exec('COMMIT');
213
- }catch(e){db.exec('ROLLBACK');throw e}
214
- const record={contract:'chat-loop.context-restore.v1',
215
- status:'RESTORED_DIAGNOSTIC',previousEpoch,newEpoch,
216
- sourceBackup:{path:backupFile,hash:expectedBackupHash},
217
- targetDb,ownerRestored:false,writeCapabilitiesRestored:false,
218
- sourceUnitsRequireRevalidation:true,
219
- canExecute:false,generatedAt:Date.now()};
220
- safeOutput(manifestFile,record);
221
- return record;
222
- }catch(e){
223
- try{unlinkSync(targetDb)}catch{}
224
- throw e;
225
- }finally{try{db?.close()}catch{}}
226
- }
227
- export function createRecoveryManifest(file,{projectId,taskId,storeEpoch,storeLineage,
228
- checkpointRef,backupRef,readerVersion='context-v1',unknownEffects=[]}){
229
- assert(ID.test(projectId||'')&&ID.test(taskId||'')&&
230
- typeof storeEpoch==='string'&&storeEpoch.length>0,'RECOVERY_ID_INVALID');
231
- assert(Array.isArray(unknownEffects)&&unknownEffects.length<=500,'RECOVERY_UNKNOWN_INVALID');
232
- const record={contract:'chat-loop.context-recovery.v1',projectId,taskId,
233
- storeEpoch,storeLineage,checkpointRef:checkpointRef??null,
234
- backupRef,readerVersion,unknownEffects,generatedAt:Date.now(),
235
- mode:'DIAGNOSTIC_ONLY',canExecute:false};
236
- assert(!occupied(file),'RECOVERY_MANIFEST_EXISTS');
237
- safeOutput(file,record);
238
- return record;
239
- }
240
-
241
- /**
242
- * Legacy Registry references may drift when a source document gets a benign
243
- * superseded note. Compare the original archive, the unchanged Registry and
244
- * its current task document. The result is evidence, not permission to cut over.
245
- * A trusted operator may later use it under the Core's revision/CAS receipt.
246
- */
247
- export function inspectRegistryReferenceForReview(manifest,{
248
- taskId,archiveFile,expectedCurrentHash
249
- }){
250
- assert(manifest?.sourceKind==='REGISTRY_JSON'&&
251
- typeof taskId==='string'&&ID.test(taskId),'REGISTRY_REVIEW_INVALID');
252
- const source=scanSourceUnit({sourcePath:manifest.sourcePath,
253
- projectId:manifest.projectId,kind:'REGISTRY_JSON'});
254
- assert(source.sourceHash===manifest.sourceHash&&
255
- source.sourceUnitId===manifest.sourceUnitId,'SOURCE_CHANGED');
256
- assert(source.tasks.length===manifest.tasks.length,'REGISTRY_TASK_SET_CHANGED');
257
- const previous=manifest.tasks.find(t=>t.taskId===taskId);
258
- const current=source.tasks.find(t=>t.taskId===taskId);
259
- assert(previous&&current,'REGISTRY_TASK_NOT_FOUND');
260
- for(const old of manifest.tasks){
261
- const next=source.tasks.find(t=>t.taskId===old.taskId);
262
- assert(next&&Object.keys(old).every(k=>
263
- (k==='taskDocumentHash'&&old.taskId===taskId)
264
- ||JSON.stringify(next[k])===JSON.stringify(old[k])),
265
- 'REGISTRY_TASK_IDENTITY_CHANGED');
266
- }
267
- assert(/^[a-f0-9]{64}$/.test(previous.taskDocumentHash??'')&&
268
- typeof expectedCurrentHash==='string'&&
269
- expectedCurrentHash===current.taskDocumentHash&&
270
- current.taskDocPath===previous.taskDocPath,
271
- 'REGISTRY_REFERENCE_VERSION_CONFLICT');
272
- const archive=safeRead(archiveFile,512*1024);
273
- assert(hash(archive.bytes)===previous.taskDocumentHash,
274
- 'ARCHIVE_HASH_MISMATCH');
275
- const newest=safeRead(current.taskDocPath,512*1024);
276
- assert(hash(newest.bytes)===expectedCurrentHash,
277
- 'DOCUMENT_CHANGED_DURING_REVIEW');
278
- const lines=reviewPreservedLines(archive.bytes,newest.bytes);
279
- assert(lines.insertionsOnly&&lines.insertedLines>0,
280
- 'REGISTRY_REVIEW_NOT_INSERTIONS_ONLY');
281
- return {currentTasks:source.tasks,originalHash:previous.taskDocumentHash,
282
- currentHash:expectedCurrentHash,originalArchiveHash:hash(archive.bytes),
283
- originalArchivePath:archive.path,insertedLines:lines.insertedLines,
284
- originalLines:lines.originalLines,currentLines:lines.currentLines,
285
- sourceHash:source.sourceHash};
286
- }
@@ -1,115 +0,0 @@
1
- // Context Core context methods. Shared access and transactions are injected from store.mjs.
2
- export function createContextMethods(values) {
3
- const {assert, canonical, parse, db, saveTaskContext, epoch, principalId, randomUUID, required, projectDrift, checkIds, receipt, readAuth, readSnapshot, validContextPatch, unresolvedEffects, written, publicTask, scope} = values;
4
- return {
5
- history(projectId,taskId){
6
- checkIds(projectId,taskId);readAuth(projectId,taskId,'context.history');
7
- const current=required(projectId,taskId);
8
- const docs=db.prepare('SELECT document_id,version,kind,content_hash FROM documents WHERE project_id=? AND task_id=? ORDER BY rowid')
9
- .all(projectId,taskId);
10
- const approvals=db.prepare('SELECT issue_id,document_id,version,state,presented_ref FROM issues WHERE project_id=? AND task_id=? ORDER BY rowid')
11
- .all(projectId,taskId);
12
- const checkpoints=db.prepare('SELECT checkpoint_id,business_revision FROM checkpoints WHERE project_id=? AND task_id=? ORDER BY rowid')
13
- .all(projectId,taskId);
14
- return {projectId,taskId,taskRevision:current.business_revision,
15
- documents:docs,issueHistory:approvals,checkpoints,
16
- // no raw Context credential, no automatic hard approval attribution
17
- approvalRecords:parse(current.approval_json)};
18
- },
19
- // W01 fixture: real DB operations, soft approvals explicitly TEST_ONLY.,
20
- requestStatus({projectId,storeEpoch,writeRequestId}){
21
- readAuth(projectId,null,'context.request.status');const principal=principalId;
22
- assert(storeEpoch===epoch,'STALE_EPOCH');
23
- const r=db.prepare('SELECT result_json FROM receipts WHERE store_epoch=? AND principal=? AND project_id=? AND request_id=?')
24
- .get(epoch,principal,projectId,writeRequestId);
25
- return r?parse(r.result_json):{status:'NOT_FOUND'};
26
- },
27
- patch(a){
28
- return receipt(a,'context.patch',()=>{
29
- const r=scope(a);written(r,a);
30
- const current=parse(r.context_json);
31
- validContextPatch(a.patch,current);
32
- const context={...current,...a.patch};
33
- saveTaskContext(a.projectId,a.taskId,context);
34
- return {status:'COMMITTED',taskRevision:r.business_revision+1,bindingRevision:r.binding_revision};
35
- });
36
- },
37
- resolveUnknownEffect(a){
38
- return receipt(a,'context.unknown.resolve',()=>{
39
- const r=scope(a);written(r,a);
40
- assert(typeof a.effectRef==='string'&&a.effectRef.length>0
41
- &&a.effectRef.length<=256,'UNKNOWN_EFFECT_REF_REQUIRED');
42
- assert(typeof a.resolutionEvidenceRef==='string'
43
- &&a.resolutionEvidenceRef.length>=8
44
- &&a.resolutionEvidenceRef.length<=4096,
45
- 'RESOLUTION_EVIDENCE_REQUIRED');
46
- const context=parse(r.context_json);
47
- assert((context.unknownEffects??[]).some(e=>(e.ref??e.id)===a.effectRef),
48
- 'UNKNOWN_EFFECT_NOT_FOUND');
49
- assert(!(context.effectResolutions??[]).some(e=>e.ref===a.effectRef),
50
- 'UNKNOWN_EFFECT_ALREADY_RESOLVED');
51
- const updated={...context,effectResolutions:[
52
- ...(context.effectResolutions??[]),
53
- {ref:a.effectRef,evidenceRef:a.resolutionEvidenceRef,
54
- proofLevel:'SOFT_AGENT_VERIFICATION',resolvedAt:Date.now()}
55
- ]};
56
- saveTaskContext(a.projectId,a.taskId,updated);
57
- return {status:'RESOLUTION_RECORDED',effectRef:a.effectRef,
58
- proofLevel:'SOFT_AGENT_VERIFICATION',
59
- taskRevision:r.business_revision+1};
60
- });
61
- },
62
- checkpoint(a){
63
- return receipt(a,'context.checkpoint',()=>{
64
- const r=scope(a);written(r,a);
65
- const current=parse(r.context_json);
66
- const unresolved=current.unknownEffects??[];
67
- assert(Array.isArray(unresolved),'UNKNOWN_EFFECTS_INVALID');
68
- if(Object.hasOwn(a,'unknownEffects'))
69
- assert(canonical(a.unknownEffects)===canonical(unresolved),
70
- 'UNKNOWN_EFFECTS_MISMATCH');
71
- const cpId=randomUUID(),snap={
72
- projectId:a.projectId,taskId:a.taskId,taskRevision:r.business_revision+1,
73
- approvalRevision:r.approval_revision,context:current,
74
- evidenceRefs:a.evidenceRefs??[],unknownEffects:unresolved,
75
- effectResolutions:current.effectResolutions??[],
76
- coverage:'DECLARED_REFS_UNVERIFIED'
77
- };
78
- db.prepare('INSERT INTO checkpoints VALUES(?,?,?,?,?)')
79
- .run(a.projectId,a.taskId,cpId,snap.taskRevision,JSON.stringify(snap));
80
- db.prepare('UPDATE tasks SET business_revision=business_revision+1 WHERE project_id=? AND task_id=?')
81
- .run(a.projectId,a.taskId);
82
- return {status:'COMMITTED',checkpointId:cpId,taskRevision:snap.taskRevision,
83
- bindingRevision:r.binding_revision};
84
- });
85
- },
86
- resume(projectId,taskId,checkpointId,maxBytes=262144){
87
- checkIds(projectId,taskId);readAuth(projectId,taskId,'context.resume');
88
- assert(Number.isSafeInteger(maxBytes)&&maxBytes>=16384&&maxBytes<=262144,
89
- 'RESUME_BUDGET_INVALID');
90
- // A deferred SQLite reader transaction pins the SAME snapshot across
91
- // checkpoint, task, approvals and project revision, even with a
92
- // concurrent Gateway/Native writer in another process.
93
- return readSnapshot(()=>{
94
- const current=required(projectId,taskId);
95
- const cp=db.prepare('SELECT * FROM checkpoints WHERE project_id=? AND task_id=? AND checkpoint_id=?')
96
- .get(projectId,taskId,checkpointId);
97
- assert(cp,'CHECKPOINT_NOT_FOUND');
98
- const snapshot=parse(cp.snapshot_json);
99
- const drift=projectDrift(current);
100
- const unresolved=unresolvedEffects(snapshot.context??{}).length;
101
- const result={checkpointId,storeEpoch:epoch,snapshot,
102
- ...drift,liveHead:publicTask(current),
103
- businessDrift:current.business_revision!==cp.business_revision,
104
- bindingMatchesSource:current.writable_ref!==null,
105
- canResumeRead:true,canExecute:false,
106
- requireWorkerNativeCommitProof:true,
107
- nextActionSafety:unresolved?'BLOCKED_UNKNOWN':'REQUIRES_EXTERNAL_EVIDENCE',
108
- asOf:Date.now()};
109
- const bytes=Buffer.byteLength(JSON.stringify(result),'utf8');
110
- assert(bytes<=maxBytes,'RESUME_INCOMPLETE');
111
- return result;
112
- });
113
- }
114
- };
115
- }
@@ -1,51 +0,0 @@
1
- // Context Core evidence methods. Shared access and transactions are injected from store.mjs.
2
- export function createEvidenceMethods(values) {
3
- const {assert, db, randomUUID, checkIds, receipt, readAuth, expectedBusiness, written, scope} = values;
4
- return {
5
- evidenceAttach(a){
6
- return receipt(a,'evidence.attach',()=>{
7
- const r=scope(a);expectedBusiness(r,a.expectedTaskRevision);
8
- if(r.writable_ref!==null)written(r,a);
9
- else assert(r.pending_attempt===null,'WRITER_FENCED');
10
- assert(typeof a.locator==='string'&&a.locator.length>0&&a.locator.length<=4096
11
- &&typeof a.role==='string'&&/^[a-z][a-z0-9_-]{0,63}$/.test(a.role),
12
- 'INVALID_EVIDENCE_LOCATOR');
13
- const retention=['RETAINED','EXTERNAL','EPHEMERAL'].includes(a.retention)
14
- ?a.retention:'EXTERNAL';
15
- assert(a.contentHash===undefined||
16
- typeof a.contentHash==='string'&&/^[a-f0-9]{64}$/.test(a.contentHash),
17
- 'INVALID_EVIDENCE_HASH');
18
- const artifactId=randomUUID();
19
- db.prepare('INSERT INTO artifacts VALUES(?,?,?,?,?,?,?,?,?)')
20
- .run(a.projectId,a.taskId,artifactId,a.locator,a.role,a.contentHash??null,
21
- retention,Date.now(),'UNVERIFIED');
22
- db.prepare('UPDATE tasks SET business_revision=business_revision+1 WHERE project_id=? AND task_id=?')
23
- .run(a.projectId,a.taskId);
24
- return {status:'ATTACHED',artifactId,taskRevision:r.business_revision+1,
25
- sourceStatus:'UNVERIFIED'};
26
- });
27
- },
28
- evidenceList(projectId,taskId){
29
- checkIds(projectId,taskId);readAuth(projectId,taskId,'evidence.list');
30
- return db.prepare('SELECT artifact_id,locator,role,content_hash,retention,observed_at,source_status FROM artifacts WHERE project_id=? AND task_id=? ORDER BY observed_at,artifact_id')
31
- .all(projectId,taskId).map(r=>({artifactId:r.artifact_id,
32
- locator:r.locator,role:r.role,contentHash:r.content_hash,
33
- retention:r.retention,observedAt:r.observed_at,sourceStatus:r.source_status}));
34
- },
35
- evidenceDetach(a){
36
- return receipt(a,'evidence.detach',()=>{
37
- const r=scope(a);expectedBusiness(r,a.expectedTaskRevision);
38
- if(r.writable_ref!==null)written(r,a);
39
- else assert(r.pending_attempt===null,'WRITER_FENCED');
40
- const old=db.prepare('SELECT 1 FROM artifacts WHERE project_id=? AND task_id=? AND artifact_id=?')
41
- .get(a.projectId,a.taskId,a.artifactId);
42
- assert(old,'EVIDENCE_NOT_FOUND');
43
- db.prepare('DELETE FROM artifacts WHERE project_id=? AND task_id=? AND artifact_id=?')
44
- .run(a.projectId,a.taskId,a.artifactId);
45
- db.prepare('UPDATE tasks SET business_revision=business_revision+1 WHERE project_id=? AND task_id=?')
46
- .run(a.projectId,a.taskId);
47
- return {status:'DETACHED',taskRevision:r.business_revision+1};
48
- });
49
- }
50
- };
51
- }
@@ -1,75 +0,0 @@
1
- // Context Core health methods. Shared access and transactions are injected from store.mjs.
2
- export function createHealthMethods(values) {
3
- const {assert, parse, db, epoch, storeMode, hasApprovedPlan, required, checkIds, admin, readAuth, unresolvedEffects, readSnapshot, projectDrift, ensureNoPendingIssue} = values;
4
- return {
5
- pragmas:()=>({
6
- journalMode:db.prepare('PRAGMA journal_mode').get().journal_mode,
7
- synchronous:db.prepare('PRAGMA synchronous').get().synchronous,
8
- foreignKeys:db.prepare('PRAGMA foreign_keys').get().foreign_keys
9
- }),
10
- close:()=>db.close(),
11
- integrity:()=>{
12
- admin('store.integrity',null);
13
- const checks=db.prepare('PRAGMA integrity_check').all();
14
- const badRefs=db.prepare('PRAGMA foreign_key_check').all();
15
- return {integrity:checks.length===1&&checks[0].integrity_check==='ok'
16
- ?'PASS':'FAILED',foreignKeys:badRefs.length===0?'PASS':'FAILED',
17
- storeMode,storeEpoch:epoch};
18
- },
19
- reopenStatus(projectId,taskId){
20
- checkIds(projectId,taskId);readAuth(projectId,taskId,'run.reopenStatus');
21
- const r=required(projectId,taskId),c=parse(r.context_json);
22
- const approvals=parse(r.approval_json);
23
- assert(c.stage==='REOPENED'&&c.reopenReason==='REPAIR_SAME_SCOPE'
24
- &&r.writable_ref===null&&r.pending_attempt===null
25
- &&hasApprovedPlan(approvals),'REPAIR_NOT_READY');
26
- return {projectId,taskId,taskRevision:r.business_revision,
27
- approvalRevision:r.approval_revision,stage:c.stage,
28
- reopenUserTurn:c.reopenRequest?.userTurn??null,
29
- previousDeliveryRef:c.deliveryRef??null};
30
- },
31
- terminalStatus(projectId,taskId,startRecoveryLeaseRef=null){
32
- checkIds(projectId,taskId);readAuth(projectId,taskId,'run.terminalStatus');
33
- return readSnapshot(()=>{
34
- const r=required(projectId,taskId),c=parse(r.context_json);
35
- const state={projectId,taskId,taskRevision:r.business_revision,
36
- bindingRevision:r.binding_revision,approvalRevision:r.approval_revision,
37
- unknownEffectCount:unresolvedEffects(c).length,
38
- runRef:r.writable_ref,executionOutcome:c.executionOutcome??null,
39
- deliveryRef:c.deliveryRef??null,
40
- sessionCancellation:c.sessionCancellation??null};
41
- if(startRecoveryLeaseRef===null)return state;
42
- // Read-only, scoped to the fresh lease. The prior expired leases were
43
- // removed transactionally by reserve; no prior permit may exist.
44
- assert(r.binding_revision===0&&r.writable_ref===null&&r.pending_attempt===null
45
- &&state.unknownEffectCount===0&&state.executionOutcome===null
46
- &&!['ARCHIVED','DELIVERED','REOPENED'].includes(c.stage)
47
- &&!projectDrift(r).projectDrift&&hasApprovedPlan(parse(r.approval_json)),
48
- 'START_RECOVERY_UNSAFE');
49
- ensureNoPendingIssue(projectId,taskId);
50
- const leases=db.prepare('SELECT * FROM start_leases WHERE project_id=? AND task_id=?')
51
- .all(projectId,taskId);
52
- assert(leases.length===1&&leases[0].lease_ref===startRecoveryLeaseRef
53
- &&leases[0].expires_at>Date.now()&&leases[0].business_revision===r.business_revision
54
- &&leases[0].approval_revision===r.approval_revision,'START_RECOVERY_LEASE_UNVERIFIED');
55
- assert(!db.prepare('SELECT 1 FROM permits WHERE project_id=? AND task_id=? LIMIT 1')
56
- .get(projectId,taskId),'START_PERMIT_ALREADY_CONSUMED');
57
- return {...state,storeEpoch:epoch,startRecovery:{status:'UNBOUND_NO_PERMIT',leaseRef:startRecoveryLeaseRef}};
58
- });
59
- },
60
- latestCheckpoint(projectId,taskId){
61
- checkIds(projectId,taskId);readAuth(projectId,taskId,'context.latestCheckpoint');
62
- const r=required(projectId,taskId);
63
- const cp=db.prepare('SELECT checkpoint_id,business_revision,snapshot_json FROM checkpoints WHERE project_id=? AND task_id=? ORDER BY rowid DESC LIMIT 1')
64
- .get(projectId,taskId);
65
- assert(cp,'CHECKPOINT_NOT_FOUND');
66
- const snap=parse(cp.snapshot_json);
67
- return {projectId,taskId,checkpointId:cp.checkpoint_id,
68
- taskRevision:r.business_revision,bindingRevision:r.binding_revision,
69
- approvalRevision:r.approval_revision,checkpointRevision:cp.business_revision,
70
- unknownEffectCount:unresolvedEffects(snap.context??{}).length,
71
- runRef:r.writable_ref,
72
- checkpointCurrent:cp.business_revision===r.business_revision};
73
- }
74
- };
75
- }