@tomflow/chatloop-tools 0.9.20 → 0.9.21
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.
- package/node_modules/@tomflow/chatloop-context/README.md +240 -0
- package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +266 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
- package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
- package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +182 -0
- package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
- package/node_modules/@tomflow/chatloop-context/index.mjs +233 -0
- package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
- package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +24 -0
- package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +1989 -0
- package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +67 -0
- package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +280 -0
- package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
- package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +280 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +115 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +55 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +147 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +343 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +391 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +166 -0
- package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
- package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
- package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
- package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +117 -0
- package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +312 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +115 -0
- package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +86 -0
- package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
- package/node_modules/@tomflow/chatloop-context/package.json +40 -0
- package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
- package/node_modules/@tomflow/chatloop-trace/README.md +105 -0
- package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
- package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
- package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
- package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
- package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +265 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +205 -0
- package/node_modules/@tomflow/chatloop-trace/package.json +30 -0
- package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
- package/package.json +5 -1
|
@@ -0,0 +1,280 @@
|
|
|
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,existsSync,lstatSync,copyFileSync,chmodSync,constants,
|
|
6
|
+
realpathSync,renameSync,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
|
+
// Hash large online backups incrementally; never load a 2 GiB database
|
|
27
|
+
// into the Agent/CLI process just to check its integrity.
|
|
28
|
+
const hashLargeFile=(file,max=2*1024*1024*1024)=>{
|
|
29
|
+
assert(typeof file==='string'&&isAbsolute(file),'SOURCE_PATH_INVALID');
|
|
30
|
+
const st=lstatSync(file);
|
|
31
|
+
assert(st.isFile()&&!st.isSymbolicLink()&&st.size>0&&st.size<=max,
|
|
32
|
+
'BACKUP_SOURCE_UNTRUSTED');
|
|
33
|
+
const fd=openSync(file,constants.O_RDONLY);
|
|
34
|
+
const hasher=createHash('sha256'),chunk=Buffer.alloc(64*1024);
|
|
35
|
+
let length=0;
|
|
36
|
+
try{
|
|
37
|
+
let n;
|
|
38
|
+
while((n=readSync(fd,chunk,0,chunk.length,null))>0){
|
|
39
|
+
hasher.update(chunk.subarray(0,n));length+=n;
|
|
40
|
+
assert(length<=max,'BACKUP_TOO_LARGE');
|
|
41
|
+
}
|
|
42
|
+
}finally{closeSync(fd)}
|
|
43
|
+
assert(length===st.size,'BACKUP_CHANGED_WHILE_READING');
|
|
44
|
+
return {path:realpathSync(file),hash:hasher.digest('hex'),bytes:length};
|
|
45
|
+
};
|
|
46
|
+
const safeRead=(file,max=4*1024*1024)=>{
|
|
47
|
+
assert(typeof file==='string'&&isAbsolute(file),'SOURCE_PATH_INVALID');
|
|
48
|
+
const st=lstatSync(file);
|
|
49
|
+
assert(st.isFile()&&!st.isSymbolicLink()&&st.size>0&&st.size<=max,'SOURCE_UNTRUSTED');
|
|
50
|
+
return {stat:st,bytes:readFileSync(file),path:realpathSync(file)};
|
|
51
|
+
};
|
|
52
|
+
const privateDirectory=dir=>{
|
|
53
|
+
mkdirSync(dir,{recursive:true,mode:0o700});
|
|
54
|
+
const st=lstatSync(dir);
|
|
55
|
+
assert(st.isDirectory()&&!st.isSymbolicLink()&&!(st.mode&0o077)
|
|
56
|
+
&&(!process.getuid||st.uid===process.getuid()),'PRIVATE_DIR_UNTRUSTED');
|
|
57
|
+
};
|
|
58
|
+
const safeOutput=(file,value)=>{
|
|
59
|
+
const dir=dirname(file);privateDirectory(dir);
|
|
60
|
+
const tmp=join(dir,'.'+basename(file)+'.'+randomUUID()+'.tmp');
|
|
61
|
+
try{
|
|
62
|
+
writeFileSync(tmp,JSON.stringify(value,null,2)+'\n',{flag:'wx',mode:0o600});
|
|
63
|
+
renameSync(tmp,file);
|
|
64
|
+
}finally{try{unlinkSync(tmp)}catch{}}
|
|
65
|
+
};
|
|
66
|
+
export function scanSourceUnit({sourcePath,projectId,kind}){
|
|
67
|
+
assert(ID.test(projectId||''),'PROJECT_ID_INVALID');
|
|
68
|
+
assert(['REGISTRY_JSON','MIXED_CONTEXT','DOCUMENT'].includes(kind),'SOURCE_KIND_INVALID');
|
|
69
|
+
const source=safeRead(sourcePath,kind==='MIXED_CONTEXT'?8*1024*1024:4*1024*1024);
|
|
70
|
+
const evidence={sourceUnitId:hash(source.path),sourcePath:source.path,
|
|
71
|
+
projectId,sourceHash:hash(source.bytes),sourceSize:source.stat.size,
|
|
72
|
+
sourceKind:kind,sourceScope:kind==='MIXED_CONTEXT'?'PROJECT_SHARED':'SOURCE_FILE',
|
|
73
|
+
observedAt:Date.now(),status:'SHADOW_RO',ownership:'EVIDENCE_ONLY',
|
|
74
|
+
tasks:[],unknownItems:[],knownWriters:['legacy-gateway','file-tools','user-editor'],
|
|
75
|
+
provenance:'SOURCE_READ_ONLY'};
|
|
76
|
+
if(kind!=='REGISTRY_JSON'){
|
|
77
|
+
// A mixed CURRENT can span Projects/Tasks; never parse arbitrary prose
|
|
78
|
+
// into a verified Task or R/P/approval fact.
|
|
79
|
+
evidence.unknownItems.push({reason:'UNCLASSIFIED_HISTORICAL_CONTENT',
|
|
80
|
+
sourcePath:source.path,sourceHash:evidence.sourceHash});
|
|
81
|
+
return evidence;
|
|
82
|
+
}
|
|
83
|
+
let legacy;
|
|
84
|
+
try{legacy=JSON.parse(source.bytes.toString('utf8'))}catch{throw fail('LEGACY_REGISTRY_CORRUPT')}
|
|
85
|
+
assert(legacy?.schemaVersion===1&&legacy.projects&&typeof legacy.projects==='object'
|
|
86
|
+
&&!Array.isArray(legacy.projects),'LEGACY_REGISTRY_INVALID');
|
|
87
|
+
const legacyProject=legacy.projects[projectId];
|
|
88
|
+
if(!legacyProject){
|
|
89
|
+
evidence.unknownItems.push({reason:'PROJECT_NOT_IN_REGISTRY',sourceHash:evidence.sourceHash});
|
|
90
|
+
return evidence;
|
|
91
|
+
}
|
|
92
|
+
assert(legacyProject.tasks&&typeof legacyProject.tasks==='object'
|
|
93
|
+
&&!Array.isArray(legacyProject.tasks),'LEGACY_TASK_MAP_INVALID');
|
|
94
|
+
evidence.ownership='VERIFIED_REGISTRY_IDENTITIES_ONLY';
|
|
95
|
+
for(const [taskId,t] of Object.entries(legacyProject.tasks)){
|
|
96
|
+
assert(ID.test(taskId),'LEGACY_TASK_ID_INVALID');
|
|
97
|
+
// The only guaranteed importable fact is the old registry's identity
|
|
98
|
+
// and source reference. Approval/status/Owner are NEVER synthesized.
|
|
99
|
+
assert(t.taskId===taskId&&t.projectId===projectId,'LEGACY_TASK_ID_MISMATCH');
|
|
100
|
+
const doc=safeRead(t.taskDocPath,512*1024);
|
|
101
|
+
const labels=[...doc.bytes.toString('utf8').matchAll(
|
|
102
|
+
/^\s*(?:[-*]\s*)?taskId\s*[::]\s*["'\x60]?([a-zA-Z0-9][a-zA-Z0-9._-]*)/gmi)];
|
|
103
|
+
assert(labels.length===1&&labels[0][1]===taskId,'LEGACY_DOCUMENT_TASK_ID_UNVERIFIED');
|
|
104
|
+
evidence.tasks.push({taskId,title:t.title,taskDocPath:doc.path,
|
|
105
|
+
taskDocumentHash:hash(doc.bytes),parentTaskId:t.parentTaskId??null,
|
|
106
|
+
legacyRevision:t.revision,
|
|
107
|
+
documents:(t.documents??[]).map(d=>({role:d.role,locator:d.sourcePath,
|
|
108
|
+
versionRef:d.versionRef??null,sourceStatus:'UNVERIFIED'})),
|
|
109
|
+
approvalStatus:'UNVERIFIED',executionOutcome:'UNVERIFIED'});
|
|
110
|
+
}
|
|
111
|
+
return evidence;
|
|
112
|
+
}
|
|
113
|
+
export function verifySourceUnit(manifest){
|
|
114
|
+
const current=scanSourceUnit({sourcePath:manifest.sourcePath,
|
|
115
|
+
projectId:manifest.projectId,kind:manifest.sourceKind});
|
|
116
|
+
assert(current.sourceHash===manifest.sourceHash,'SOURCE_CHANGED');
|
|
117
|
+
assert(current.sourceUnitId===manifest.sourceUnitId,'SOURCE_REPLACED');
|
|
118
|
+
if(manifest.sourceKind==='REGISTRY_JSON'){
|
|
119
|
+
assert(JSON.stringify(current.tasks)===JSON.stringify(manifest.tasks),
|
|
120
|
+
'LEGACY_REFERENCE_CHANGED');
|
|
121
|
+
}
|
|
122
|
+
return {status:'MATCHED',sourceUnitId:manifest.sourceUnitId,
|
|
123
|
+
sourceHash:current.sourceHash};
|
|
124
|
+
}
|
|
125
|
+
export function saveShadowManifest(file,items){
|
|
126
|
+
assert(Array.isArray(items)&&items.length>0&&items.length<=128,'MANIFEST_INVALID');
|
|
127
|
+
const unique=new Set(items.map(x=>x.sourceUnitId));
|
|
128
|
+
assert(unique.size===items.length,'SOURCE_UNIT_DUPLICATED');
|
|
129
|
+
const manifest={contract:'chat-loop.context-source-units.v1',
|
|
130
|
+
instanceLineage:randomUUID(),createdAt:Date.now(),
|
|
131
|
+
status:'SHADOW_RO',sourceUnits:items,permissions:'READ_ONLY',
|
|
132
|
+
taskApprovalsImported:false,ownerImported:false,
|
|
133
|
+
knownWritersStopped:false};
|
|
134
|
+
assert(!existsSync(file),'MANIFEST_EXISTS');
|
|
135
|
+
safeOutput(file,manifest);
|
|
136
|
+
return manifest;
|
|
137
|
+
}
|
|
138
|
+
export function readShadowManifest(file){
|
|
139
|
+
const path=resolve(file),st=lstatSync(path);
|
|
140
|
+
assert(st.isFile()&&!st.isSymbolicLink()&&!(st.mode&0o077)
|
|
141
|
+
&&(!process.getuid||st.uid===process.getuid()),'MANIFEST_UNTRUSTED');
|
|
142
|
+
const manifest=JSON.parse(readFileSync(path,'utf8'));
|
|
143
|
+
assert(manifest?.contract==='chat-loop.context-source-units.v1'
|
|
144
|
+
&&Array.isArray(manifest.sourceUnits)&&manifest.sourceUnits.length>0,
|
|
145
|
+
'MANIFEST_SCHEMA_INVALID');
|
|
146
|
+
return manifest;
|
|
147
|
+
}
|
|
148
|
+
export function verifyShadowManifest(file){
|
|
149
|
+
const m=readShadowManifest(file);
|
|
150
|
+
return {status:'SHADOW_MATCHED',checks:m.sourceUnits.map(verifySourceUnit),
|
|
151
|
+
sourceUnits:m.sourceUnits.length};
|
|
152
|
+
}
|
|
153
|
+
// SQLite online backup: never copy a live database's main file.
|
|
154
|
+
export async function backupContextDb(dbHandle,targetFile){
|
|
155
|
+
assert(typeof targetFile==='string'&&isAbsolute(targetFile),'BACKUP_PATH_INVALID');
|
|
156
|
+
assert(!existsSync(targetFile),'BACKUP_EXISTS');
|
|
157
|
+
privateDirectory(dirname(targetFile));
|
|
158
|
+
try{
|
|
159
|
+
await backup(dbHandle,targetFile);
|
|
160
|
+
chmodSync(targetFile,0o600);
|
|
161
|
+
const st=lstatSync(targetFile);
|
|
162
|
+
assert(st.isFile()&&!st.isSymbolicLink(),'BACKUP_UNTRUSTED');
|
|
163
|
+
const ready=hashLargeFile(targetFile);
|
|
164
|
+
return {...ready,status:'BACKED_UP'};
|
|
165
|
+
}catch(e){try{unlinkSync(targetFile)}catch{}throw e}
|
|
166
|
+
}
|
|
167
|
+
// Restore is an OFFLINE fork with a fresh Store epoch, never an in-place
|
|
168
|
+
// replacement of an active database or a Browser Owner resurrector.
|
|
169
|
+
export function restoreBackupToDiagnosticBranch({
|
|
170
|
+
backupFile,targetDb,expectedBackupHash,manifestFile
|
|
171
|
+
}){
|
|
172
|
+
assert(typeof backupFile==='string'&&isAbsolute(backupFile)
|
|
173
|
+
&&typeof targetDb==='string'&&isAbsolute(targetDb)
|
|
174
|
+
&&typeof manifestFile==='string'&&isAbsolute(manifestFile)
|
|
175
|
+
&&typeof expectedBackupHash==='string'&&/^[a-f0-9]{64}$/.test(expectedBackupHash),
|
|
176
|
+
'RESTORE_ARGUMENT_INVALID');
|
|
177
|
+
assert(!existsSync(targetDb)&&!existsSync(manifestFile),'RESTORE_TARGET_EXISTS');
|
|
178
|
+
const source=hashLargeFile(backupFile);
|
|
179
|
+
assert(source.hash===expectedBackupHash,'BACKUP_HASH_MISMATCH');
|
|
180
|
+
privateDirectory(dirname(targetDb));
|
|
181
|
+
copyFileSync(source.path,targetDb,constants.COPYFILE_EXCL);
|
|
182
|
+
chmodSync(targetDb,0o600);
|
|
183
|
+
let db;
|
|
184
|
+
try{
|
|
185
|
+
db=new DatabaseSync(targetDb);
|
|
186
|
+
const version=db.prepare("SELECT value FROM meta WHERE key='schemaVersion'").get()?.value;
|
|
187
|
+
const previousEpoch=db.prepare("SELECT value FROM meta WHERE key='storeEpoch'").get()?.value;
|
|
188
|
+
assert(version==='6'&&typeof previousEpoch==='string'&&previousEpoch.length>0,
|
|
189
|
+
'BACKUP_SCHEMA_UNSUPPORTED');
|
|
190
|
+
const integrity=db.prepare('PRAGMA integrity_check').all();
|
|
191
|
+
assert(integrity.length===1&&integrity[0].integrity_check==='ok','BACKUP_CORRUPT');
|
|
192
|
+
const newEpoch=randomUUID();
|
|
193
|
+
db.exec('PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON;');
|
|
194
|
+
db.exec('BEGIN IMMEDIATE');
|
|
195
|
+
try{
|
|
196
|
+
db.prepare("UPDATE meta SET value=? WHERE key='storeEpoch'").run(newEpoch);
|
|
197
|
+
db.prepare("INSERT OR REPLACE INTO meta(key,value) VALUES('storeMode','DIAGNOSTIC_ONLY')").run();
|
|
198
|
+
db.prepare("INSERT OR REPLACE INTO meta(key,value) VALUES('restoredFromEpoch',?)")
|
|
199
|
+
.run(previousEpoch);
|
|
200
|
+
db.exec(`UPDATE tasks SET writable_ref=NULL,credential_digest=NULL,
|
|
201
|
+
writer_approval_revision=NULL,pending_attempt=NULL,pending_checkpoint=NULL,pending_target_generation=NULL,
|
|
202
|
+
pending_credential_digest=NULL,pending_next_ref=NULL,binding_revision=binding_revision+1;
|
|
203
|
+
DELETE FROM permits;DELETE FROM start_leases;
|
|
204
|
+
UPDATE migrations SET status='RESTORED_DIAGNOSTIC',
|
|
205
|
+
migration_revision=migration_revision+1,updated_at=0;`);
|
|
206
|
+
db.exec('COMMIT');
|
|
207
|
+
}catch(e){db.exec('ROLLBACK');throw e}
|
|
208
|
+
const record={contract:'chat-loop.context-restore.v1',
|
|
209
|
+
status:'RESTORED_DIAGNOSTIC',previousEpoch,newEpoch,
|
|
210
|
+
sourceBackup:{path:backupFile,hash:expectedBackupHash},
|
|
211
|
+
targetDb,ownerRestored:false,writeCapabilitiesRestored:false,
|
|
212
|
+
sourceUnitsRequireRevalidation:true,
|
|
213
|
+
canExecute:false,generatedAt:Date.now()};
|
|
214
|
+
safeOutput(manifestFile,record);
|
|
215
|
+
return record;
|
|
216
|
+
}catch(e){
|
|
217
|
+
try{unlinkSync(targetDb)}catch{}
|
|
218
|
+
throw e;
|
|
219
|
+
}finally{try{db?.close()}catch{}}
|
|
220
|
+
}
|
|
221
|
+
export function createRecoveryManifest(file,{projectId,taskId,storeEpoch,storeLineage,
|
|
222
|
+
checkpointRef,backupRef,readerVersion='context-v1',unknownEffects=[]}){
|
|
223
|
+
assert(ID.test(projectId||'')&&ID.test(taskId||'')&&
|
|
224
|
+
typeof storeEpoch==='string'&&storeEpoch.length>0,'RECOVERY_ID_INVALID');
|
|
225
|
+
assert(Array.isArray(unknownEffects)&&unknownEffects.length<=500,'RECOVERY_UNKNOWN_INVALID');
|
|
226
|
+
const record={contract:'chat-loop.context-recovery.v1',projectId,taskId,
|
|
227
|
+
storeEpoch,storeLineage,checkpointRef:checkpointRef??null,
|
|
228
|
+
backupRef,readerVersion,unknownEffects,generatedAt:Date.now(),
|
|
229
|
+
mode:'DIAGNOSTIC_ONLY',canExecute:false};
|
|
230
|
+
assert(!existsSync(file),'RECOVERY_MANIFEST_EXISTS');
|
|
231
|
+
safeOutput(file,record);
|
|
232
|
+
return record;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Legacy Registry references may drift when a source document gets a benign
|
|
237
|
+
* superseded note. Compare the original archive, the unchanged Registry and
|
|
238
|
+
* its current task document. The result is evidence, not permission to cut over.
|
|
239
|
+
* A trusted operator may later use it under the Core's revision/CAS receipt.
|
|
240
|
+
*/
|
|
241
|
+
export function inspectRegistryReferenceForReview(manifest,{
|
|
242
|
+
taskId,archiveFile,expectedCurrentHash
|
|
243
|
+
}){
|
|
244
|
+
assert(manifest?.sourceKind==='REGISTRY_JSON'&&
|
|
245
|
+
typeof taskId==='string'&&ID.test(taskId),'REGISTRY_REVIEW_INVALID');
|
|
246
|
+
const source=scanSourceUnit({sourcePath:manifest.sourcePath,
|
|
247
|
+
projectId:manifest.projectId,kind:'REGISTRY_JSON'});
|
|
248
|
+
assert(source.sourceHash===manifest.sourceHash&&
|
|
249
|
+
source.sourceUnitId===manifest.sourceUnitId,'SOURCE_CHANGED');
|
|
250
|
+
assert(source.tasks.length===manifest.tasks.length,'REGISTRY_TASK_SET_CHANGED');
|
|
251
|
+
const previous=manifest.tasks.find(t=>t.taskId===taskId);
|
|
252
|
+
const current=source.tasks.find(t=>t.taskId===taskId);
|
|
253
|
+
assert(previous&¤t,'REGISTRY_TASK_NOT_FOUND');
|
|
254
|
+
for(const old of manifest.tasks){
|
|
255
|
+
const next=source.tasks.find(t=>t.taskId===old.taskId);
|
|
256
|
+
assert(next&&Object.keys(old).every(k=>
|
|
257
|
+
(k==='taskDocumentHash'&&old.taskId===taskId)
|
|
258
|
+
||JSON.stringify(next[k])===JSON.stringify(old[k])),
|
|
259
|
+
'REGISTRY_TASK_IDENTITY_CHANGED');
|
|
260
|
+
}
|
|
261
|
+
assert(/^[a-f0-9]{64}$/.test(previous.taskDocumentHash??'')&&
|
|
262
|
+
typeof expectedCurrentHash==='string'&&
|
|
263
|
+
expectedCurrentHash===current.taskDocumentHash&&
|
|
264
|
+
current.taskDocPath===previous.taskDocPath,
|
|
265
|
+
'REGISTRY_REFERENCE_VERSION_CONFLICT');
|
|
266
|
+
const archive=safeRead(archiveFile,512*1024);
|
|
267
|
+
assert(hash(archive.bytes)===previous.taskDocumentHash,
|
|
268
|
+
'ARCHIVE_HASH_MISMATCH');
|
|
269
|
+
const newest=safeRead(current.taskDocPath,512*1024);
|
|
270
|
+
assert(hash(newest.bytes)===expectedCurrentHash,
|
|
271
|
+
'DOCUMENT_CHANGED_DURING_REVIEW');
|
|
272
|
+
const lines=reviewPreservedLines(archive.bytes,newest.bytes);
|
|
273
|
+
assert(lines.insertionsOnly&&lines.insertedLines>0,
|
|
274
|
+
'REGISTRY_REVIEW_NOT_INSERTIONS_ONLY');
|
|
275
|
+
return {currentTasks:source.tasks,originalHash:previous.taskDocumentHash,
|
|
276
|
+
currentHash:expectedCurrentHash,originalArchiveHash:hash(archive.bytes),
|
|
277
|
+
originalArchivePath:archive.path,insertedLines:lines.insertedLines,
|
|
278
|
+
originalLines:lines.originalLines,currentLines:lines.currentLines,
|
|
279
|
+
sourceHash:source.sourceHash};
|
|
280
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
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} = 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){
|
|
32
|
+
checkIds(projectId,taskId);readAuth(projectId,taskId,'run.terminalStatus');
|
|
33
|
+
const r=required(projectId,taskId),c=parse(r.context_json);
|
|
34
|
+
return {projectId,taskId,taskRevision:r.business_revision,
|
|
35
|
+
bindingRevision:r.binding_revision,approvalRevision:r.approval_revision,
|
|
36
|
+
unknownEffectCount:unresolvedEffects(c).length,
|
|
37
|
+
runRef:r.writable_ref,executionOutcome:c.executionOutcome??null,
|
|
38
|
+
deliveryRef:c.deliveryRef??null};
|
|
39
|
+
},
|
|
40
|
+
latestCheckpoint(projectId,taskId){
|
|
41
|
+
checkIds(projectId,taskId);readAuth(projectId,taskId,'context.latestCheckpoint');
|
|
42
|
+
const r=required(projectId,taskId);
|
|
43
|
+
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')
|
|
44
|
+
.get(projectId,taskId);
|
|
45
|
+
assert(cp,'CHECKPOINT_NOT_FOUND');
|
|
46
|
+
const snap=parse(cp.snapshot_json);
|
|
47
|
+
return {projectId,taskId,checkpointId:cp.checkpoint_id,
|
|
48
|
+
taskRevision:r.business_revision,bindingRevision:r.binding_revision,
|
|
49
|
+
approvalRevision:r.approval_revision,checkpointRevision:cp.business_revision,
|
|
50
|
+
unknownEffectCount:unresolvedEffects(snap.context??{}).length,
|
|
51
|
+
runRef:r.writable_ref,
|
|
52
|
+
checkpointCurrent:cp.business_revision===r.business_revision};
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
}
|