@tomflow/chatloop-context 0.1.5 → 0.6.0
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/README.md +240 -271
- package/bin/cli.mjs +25 -270
- package/capabilities/approval.mjs +151 -0
- package/capabilities/context.mjs +376 -0
- package/capabilities/document.mjs +266 -0
- package/capabilities/evidence.mjs +134 -0
- package/capabilities/presentation.mjs +82 -0
- package/capabilities/project.mjs +349 -0
- package/capabilities/sdk.mjs +72 -0
- package/capabilities/start.mjs +73 -0
- package/capabilities/task.mjs +507 -0
- package/capabilities.generated.mjs +11 -0
- package/docs/interfaces.md +182 -0
- package/docs/operator-and-migration.md +277 -0
- package/index.mjs +236 -0
- package/lib/api-aspect.mjs +190 -0
- package/lib/api-log.mjs +161 -0
- package/lib/approval-policy.mjs +24 -0
- package/lib/capability-catalog.generated.json +1989 -0
- package/lib/capability-router.mjs +67 -0
- package/lib/cli-commands.mjs +280 -0
- package/lib/context-cli.mjs +16 -19
- package/lib/context-migration.mjs +17 -9
- package/lib/core/context.mjs +115 -0
- package/lib/core/evidence.mjs +51 -0
- package/lib/core/health.mjs +55 -0
- package/lib/core/migration.mjs +262 -0
- package/lib/core/project.mjs +246 -0
- package/lib/core/review.mjs +147 -0
- package/lib/core/run.mjs +343 -0
- package/lib/core/store.mjs +391 -0
- package/lib/core/task.mjs +166 -0
- package/lib/line-review.mjs +13 -0
- package/lib/methods.mjs +49 -202
- package/lib/operations.mjs +33 -145
- package/lib/orphan-operator.mjs +17 -51
- package/lib/process-inventory.mjs +20 -0
- package/lib/project-branch.mjs +312 -0
- package/lib/project-diagnostic.mjs +26 -328
- package/lib/project-guards.mjs +19 -0
- package/lib/project-store.mjs +115 -0
- package/lib/trusted-run.mjs +86 -0
- package/lib/workspace-operator.mjs +12 -2
- package/package.json +32 -14
- package/scripts/build-capabilities.mjs +114 -0
- package/lib/context-protocol.mjs +0 -1687
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// Composes capabilities declared in the build manifest, never scans at runtime.
|
|
2
|
+
// Domain methods stay behind the existing Store's authority/CAS/receipt gates.
|
|
3
|
+
// New capability routes use a restricted, project-scoped read-only service port.
|
|
4
|
+
const fail=code=>Object.assign(new Error(code),{code});
|
|
5
|
+
const isObject=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
|
|
6
|
+
const value=(spec,args)=>{
|
|
7
|
+
if(spec==='$args')return args;
|
|
8
|
+
if(typeof spec==='string')return args[spec];
|
|
9
|
+
if(isObject(spec)&&isObject(spec.$object))
|
|
10
|
+
return Object.fromEntries(Object.entries(spec.$object).map(([key,x])=>
|
|
11
|
+
[key,isObject(x)&&typeof x.$field==='string'
|
|
12
|
+
?args[x.$field]??x.$default
|
|
13
|
+
:x]));
|
|
14
|
+
throw fail('CAPABILITY_ROUTE_PARAMETER_INVALID');
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export function createCapabilityRouter(definitions,capabilities){
|
|
18
|
+
if(!Array.isArray(definitions)||!Array.isArray(capabilities))
|
|
19
|
+
throw fail('CAPABILITY_REGISTRY_INVALID');
|
|
20
|
+
const registry=new Map();
|
|
21
|
+
for(const cap of capabilities){
|
|
22
|
+
if(!cap||typeof cap.id!=='string'||!Array.isArray(cap.methods))
|
|
23
|
+
throw fail('CAPABILITY_REGISTRY_INVALID');
|
|
24
|
+
for(const entry of cap.methods){
|
|
25
|
+
if(registry.has(entry.id))throw fail('CAPABILITY_METHOD_CONFLICT');
|
|
26
|
+
registry.set(entry.id,{cap,entry});
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
if(registry.size!==definitions.length)throw fail('CAPABILITY_MANIFEST_MISMATCH');
|
|
30
|
+
for(const def of definitions){
|
|
31
|
+
const source=registry.get(def.id);
|
|
32
|
+
if(!source||JSON.stringify(source.entry.route)!==JSON.stringify(def.route)
|
|
33
|
+
||JSON.stringify(source.entry.inputSchema)!==JSON.stringify(def.inputSchema)
|
|
34
|
+
||source.entry.description!==def.description
|
|
35
|
+
||source.entry.mode!==def.mode||source.entry.group!==def.group)
|
|
36
|
+
throw fail('CAPABILITY_MANIFEST_MISMATCH');
|
|
37
|
+
}
|
|
38
|
+
return Object.freeze({
|
|
39
|
+
execute(method,args,services){
|
|
40
|
+
const source=registry.get(method?.id);
|
|
41
|
+
if(!source||source.entry.mode!==method.mode)
|
|
42
|
+
throw fail('CAPABILITY_METHOD_UNKNOWN');
|
|
43
|
+
const route=method.route;
|
|
44
|
+
if(route.kind==='core'){
|
|
45
|
+
const fn=services?.db?.[route.method];
|
|
46
|
+
if(typeof fn!=='function')throw fail('CAPABILITY_CORE_PROVIDER_MISSING');
|
|
47
|
+
return Reflect.apply(fn,services.db,
|
|
48
|
+
route.params.map(param=>value(param,args)));
|
|
49
|
+
}
|
|
50
|
+
if(route.kind==='module'){
|
|
51
|
+
if(method.mode!=='read'||typeof source.cap.execute!=='function'
|
|
52
|
+
||args.projectId!==services?.projectRef)
|
|
53
|
+
throw fail('CAPABILITY_PERMISSION_DENIED');
|
|
54
|
+
const read=Object.freeze({
|
|
55
|
+
projectRef:args.projectId,
|
|
56
|
+
// No raw DB handle, credential, CAS mutation or cross-project lookup.
|
|
57
|
+
material:(materialId,version)=>
|
|
58
|
+
services.db.projectMaterialGet(args.projectId,materialId,version),
|
|
59
|
+
document:(taskId,documentId,version)=>
|
|
60
|
+
services.db.documentGet(args.projectId,taskId,documentId,version)
|
|
61
|
+
});
|
|
62
|
+
return source.cap.execute(method.id,args,read);
|
|
63
|
+
}
|
|
64
|
+
throw fail('CAPABILITY_ADAPTER_ROUTE_REQUIRED');
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
}
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
// CLI command implementation: no imports from other internal modules.
|
|
2
|
+
// Only bin/cli.mjs exports a shell command. index.mjs supplies scoped API
|
|
3
|
+
// dependencies; local admin/SQLite safety gates remain in their owners.
|
|
4
|
+
import {randomUUID,createHash} from 'node:crypto';
|
|
5
|
+
import {existsSync,mkdirSync,mkdtempSync,renameSync,rmSync} from 'node:fs';
|
|
6
|
+
import {join} from 'node:path';
|
|
7
|
+
|
|
8
|
+
const fail=code=>Object.assign(new Error(code),{code});
|
|
9
|
+
let openContextProtocol,contextRoot,allowedProjects,
|
|
10
|
+
verifySourceUnit,createProjectDiagnosticBranch,createManagedProjectBranch,
|
|
11
|
+
fenceLegacyProjectStore,auditLegacyProjectSources,inspectLegacyRegistryReference,
|
|
12
|
+
activeLegacyWriters,fenceOrphanRunOperator,canonicalWorkspaceRefs,
|
|
13
|
+
confirmWorkspaceOperator,assertWorkspaceUnclaimed,withWorkspaceRegistryLock,
|
|
14
|
+
rebindProjectWorkspaces,readOperatorWorkspaceReceipt,runContextCli,
|
|
15
|
+
requestContext,listMethods,describeMethod,CONTEXT_PACKAGE_VERSION;
|
|
16
|
+
let connected=false;
|
|
17
|
+
export function configureCliCommands(api){
|
|
18
|
+
if(connected)throw Error('CONTEXT_MODULE_ALREADY_COMPOSED');
|
|
19
|
+
const names=['openContextProtocol','contextRoot','allowedProjects',
|
|
20
|
+
'verifySourceUnit','createProjectDiagnosticBranch','createManagedProjectBranch',
|
|
21
|
+
'fenceLegacyProjectStore','auditLegacyProjectSources',
|
|
22
|
+
'inspectLegacyRegistryReference','activeLegacyWriters',
|
|
23
|
+
'fenceOrphanRunOperator','canonicalWorkspaceRefs',
|
|
24
|
+
'confirmWorkspaceOperator','assertWorkspaceUnclaimed','withWorkspaceRegistryLock',
|
|
25
|
+
'rebindProjectWorkspaces','readOperatorWorkspaceReceipt','runContextCli',
|
|
26
|
+
'requestContext','listMethods','describeMethod','CONTEXT_PACKAGE_VERSION'];
|
|
27
|
+
for(const name of names)
|
|
28
|
+
if(api?.[name]===undefined)throw Error('CONTEXT_MODULE_PORT_MISSING:'+name);
|
|
29
|
+
({openContextProtocol,contextRoot,allowedProjects,
|
|
30
|
+
verifySourceUnit,createProjectDiagnosticBranch,createManagedProjectBranch,
|
|
31
|
+
fenceLegacyProjectStore,auditLegacyProjectSources,inspectLegacyRegistryReference,
|
|
32
|
+
activeLegacyWriters,fenceOrphanRunOperator,canonicalWorkspaceRefs,
|
|
33
|
+
confirmWorkspaceOperator,assertWorkspaceUnclaimed,withWorkspaceRegistryLock,
|
|
34
|
+
rebindProjectWorkspaces,readOperatorWorkspaceReceipt,runContextCli,
|
|
35
|
+
requestContext,listMethods,describeMethod,CONTEXT_PACKAGE_VERSION}=api);
|
|
36
|
+
connected=true;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function registerProject(projectId,title,workspaces=[],reviewed=false){
|
|
40
|
+
if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
|
|
41
|
+
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
42
|
+
if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(projectId))throw fail('INVALID_SCOPE');
|
|
43
|
+
if(typeof title!=='string'||!title.trim()||title.length>200)throw fail('INVALID_TITLE');
|
|
44
|
+
if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
|
|
45
|
+
const refs=canonicalWorkspaceRefs(workspaces,{allowEmpty:!reviewed});
|
|
46
|
+
const root=contextRoot(),final=join(root,projectId);
|
|
47
|
+
if(existsSync(final))throw fail('PROJECT_EXISTS');
|
|
48
|
+
// The user-reviewed entry never creates a Store (or even a directory)
|
|
49
|
+
// before the local operator confirms the exact canonical roots.
|
|
50
|
+
if(reviewed)await confirmWorkspaceOperator('REGISTER',projectId,0,refs);
|
|
51
|
+
mkdirSync(root,{recursive:true,mode:0o700});
|
|
52
|
+
return withWorkspaceRegistryLock(root,()=>{
|
|
53
|
+
let tmp;
|
|
54
|
+
try{
|
|
55
|
+
if(existsSync(final))throw fail('PROJECT_EXISTS');
|
|
56
|
+
if(reviewed){
|
|
57
|
+
const current=canonicalWorkspaceRefs(workspaces);
|
|
58
|
+
if(JSON.stringify(current)!==JSON.stringify(refs))throw fail('WORKSPACE_CHANGED');
|
|
59
|
+
assertWorkspaceUnclaimed(root,projectId,refs);
|
|
60
|
+
}
|
|
61
|
+
tmp=mkdtempSync(join(root,'.register-'));
|
|
62
|
+
const db=openContextProtocol(join(tmp,'context.sqlite'),{
|
|
63
|
+
allowCreate:true,authorizeData:()=>true,principalId:'local-operator'});
|
|
64
|
+
let result;
|
|
65
|
+
try{
|
|
66
|
+
result=db.projectCreate({projectId,title,sharedContext:{workspaceRefs:refs},
|
|
67
|
+
expectedStoreEpoch:db.epoch,writeRequestId:randomUUID()});
|
|
68
|
+
}finally{db.close()}
|
|
69
|
+
renameSync(tmp,final);tmp=null;
|
|
70
|
+
return {...result,workspaceRefs:refs,projectDirectory:final};
|
|
71
|
+
}finally{
|
|
72
|
+
// Incomplete staging is diagnostic only, never silently promoted.
|
|
73
|
+
if(tmp)rmSync(tmp,{recursive:true,force:true});
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
export async function runLocalCliCommand(args,readJson){
|
|
78
|
+
const [command,sub,...rest]=args;
|
|
79
|
+
let value;
|
|
80
|
+
if(command==='methods'&&sub==='list'&&rest.length<=1)
|
|
81
|
+
value=await requestContext({operation:'sdk.methods.list',
|
|
82
|
+
...(rest[0]&&rest[0]!=='--json'?{group:rest[0]}:{})});
|
|
83
|
+
else if(command==='methods'&&sub==='groups'&&rest.length<=1)
|
|
84
|
+
value=await requestContext({operation:'sdk.methods.list',view:'groups',
|
|
85
|
+
...(rest[0]?{group:rest[0]}:{})});
|
|
86
|
+
else if(command==='methods'&&sub==='describe'&&rest.length===1)
|
|
87
|
+
value=await requestContext({operation:'sdk.methods.describe',methodId:rest[0]});
|
|
88
|
+
else if(command==='admin'&&sub){
|
|
89
|
+
value=await runContextCli([sub,...rest]);
|
|
90
|
+
}
|
|
91
|
+
else if(command==='request'&&sub==='--json'&&rest.length===0){
|
|
92
|
+
const payload=await readJson();
|
|
93
|
+
if(!payload||typeof payload!=='object'||Array.isArray(payload))throw fail('INVALID_ARGUMENT');
|
|
94
|
+
value=await requestContext(payload);
|
|
95
|
+
}else if(command==='task'&&sub==='fence-orphan'&&rest.length===10){
|
|
96
|
+
const [projectId,taskId,expectedRunRef,revision,bindingRevision,
|
|
97
|
+
expectedStoreEpoch,evidenceDocumentId,evidenceVersion,evidenceHash,
|
|
98
|
+
writeRequestId]=rest;
|
|
99
|
+
value=await fenceOrphanRunOperator({projectId,taskId,expectedRunRef,
|
|
100
|
+
expectedTaskRevision:Number(revision),
|
|
101
|
+
expectedBindingRevision:Number(bindingRevision),
|
|
102
|
+
expectedStoreEpoch,evidenceDocumentId,
|
|
103
|
+
evidenceVersion:Number(evidenceVersion),evidenceHash,writeRequestId});
|
|
104
|
+
}else if(command==='task'&&sub==='orphan-receipt'&&rest.length===3){
|
|
105
|
+
const [projectId,storeEpoch,writeRequestId]=rest;
|
|
106
|
+
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
107
|
+
if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
|
|
108
|
+
const file=join(contextRoot(),projectId,'context.sqlite');
|
|
109
|
+
const db=openContextProtocol(file,{readOnly:true,principalId:'local-operator',
|
|
110
|
+
authorizeData:(_mode,p)=>p===projectId});
|
|
111
|
+
try{value=db.requestStatus({projectId,storeEpoch,writeRequestId})}
|
|
112
|
+
finally{db.close()}
|
|
113
|
+
}else if(command==='project'&&sub==='init'&&(rest.length===2||rest.length===3))
|
|
114
|
+
value=await registerProject(rest[0],rest[1],rest.slice(2));
|
|
115
|
+
else if(command==='project'&&sub==='register'&&rest.length>=3&&rest.length<=18)
|
|
116
|
+
value=await registerProject(rest[0],rest[1],rest.slice(2),true);
|
|
117
|
+
else if(command==='project'&&sub==='bind'&&rest.length>=4&&rest.length<=20){
|
|
118
|
+
const [projectId,revision,epoch,requestId,...paths]=rest;
|
|
119
|
+
if(paths.length===1&&paths[0]==='--clear')paths.length=0;
|
|
120
|
+
value=await rebindProjectWorkspaces({projectId,
|
|
121
|
+
expectedProjectRevision:Number(revision),expectedStoreEpoch:epoch,
|
|
122
|
+
writeRequestId:requestId,workspaces:paths});
|
|
123
|
+
}else if(command==='project'&&sub==='receipt'&&rest.length===3)
|
|
124
|
+
value=await readOperatorWorkspaceReceipt({projectId:rest[0],
|
|
125
|
+
storeEpoch:rest[1],writeRequestId:rest[2]});
|
|
126
|
+
else if(command==='project'&&sub==='reconcile-reference'&&rest.length===10){
|
|
127
|
+
const [projectId,sourceDb,expectedStoreEpoch,sourceUnitId,revision,
|
|
128
|
+
taskId,originalArchivePath,expectedCurrentHash,reviewRef,writeRequestId]=rest;
|
|
129
|
+
if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
|
|
130
|
+
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
131
|
+
if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
|
|
132
|
+
const expectedMigrationRevision=Number(revision);
|
|
133
|
+
if(!Number.isSafeInteger(expectedMigrationRevision)||expectedMigrationRevision<1)
|
|
134
|
+
throw fail('MIGRATION_VERSION_CONFLICT');
|
|
135
|
+
// Fail closed before any writable handle exists. Review is NOT user R/P.
|
|
136
|
+
const evidence=inspectLegacyRegistryReference({sourceDb,projectId,
|
|
137
|
+
expectedStoreEpoch,sourceUnitId,taskId,archiveFile:originalArchivePath});
|
|
138
|
+
if(evidence.changeKind!=='INSERTIONS_ONLY'||
|
|
139
|
+
evidence.currentTaskHash!==expectedCurrentHash)
|
|
140
|
+
throw fail('REGISTRY_REFERENCE_VERSION_CONFLICT');
|
|
141
|
+
await confirmWorkspaceOperator('RECONCILE_REFERENCE',projectId,
|
|
142
|
+
expectedMigrationRevision,[sourceDb,sourceUnitId,taskId,
|
|
143
|
+
evidence.archivedTaskHash,expectedCurrentHash,reviewRef]);
|
|
144
|
+
const db=openContextProtocol(sourceDb,{principalId:'local-operator',
|
|
145
|
+
authorizeData:(_mode,p)=>p===projectId,
|
|
146
|
+
authorizeAdmin:(op,p)=>p===projectId&&[
|
|
147
|
+
'migration.reference.reconcile',
|
|
148
|
+
'migration.reference.reconcile.reviewed'].includes(op)});
|
|
149
|
+
try{
|
|
150
|
+
value=db.migrationReconcileReference({projectId,sourceUnitId,
|
|
151
|
+
expectedMigrationRevision,expectedStoreEpoch,writeRequestId,
|
|
152
|
+
taskId,originalArchivePath,expectedCurrentHash,
|
|
153
|
+
sourceHash:evidence.sourceHash,reviewRef});
|
|
154
|
+
}finally{db.close()}
|
|
155
|
+
}else if(command==='project'&&sub==='migration-receipt'&&rest.length===4){
|
|
156
|
+
const [projectId,sourceDb,storeEpoch,writeRequestId]=rest;
|
|
157
|
+
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
158
|
+
const db=openContextProtocol(sourceDb,{readOnly:true,
|
|
159
|
+
principalId:'local-operator',
|
|
160
|
+
authorizeData:(_mode,p)=>p===projectId});
|
|
161
|
+
try{value=db.requestStatus({projectId,storeEpoch,writeRequestId})}
|
|
162
|
+
finally{db.close()}
|
|
163
|
+
}else if(command==='project'&&sub==='classify-evidence'&&rest.length===8){
|
|
164
|
+
const [projectId,sourceDb,expectedStoreEpoch,sourceUnitId,revision,
|
|
165
|
+
sourceHash,reviewRef,writeRequestId]=rest;
|
|
166
|
+
if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
|
|
167
|
+
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
168
|
+
if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
|
|
169
|
+
const expectedMigrationRevision=Number(revision);
|
|
170
|
+
if(!Number.isSafeInteger(expectedMigrationRevision)||expectedMigrationRevision<1)
|
|
171
|
+
throw fail('MIGRATION_VERSION_CONFLICT');
|
|
172
|
+
if(typeof reviewRef!=='string'||reviewRef.length<8||reviewRef.length>256)
|
|
173
|
+
throw fail('REVIEW_REFERENCE_REQUIRED');
|
|
174
|
+
// The historical body's original bytes must already be a matching
|
|
175
|
+
// LEGACY_UNVERIFIED Project Material, never a synthesized current Task.
|
|
176
|
+
const reader=openContextProtocol(sourceDb,{readOnly:true,
|
|
177
|
+
principalId:'local-operator',authorizeData:(_mode,p)=>p===projectId,
|
|
178
|
+
authorizeAdmin:(op,p)=>op==='migration.list'&&p===projectId});
|
|
179
|
+
let unit;
|
|
180
|
+
try{
|
|
181
|
+
if(reader.mode!=='ACTIVE')throw fail('STORE_DIAGNOSTIC_ONLY');
|
|
182
|
+
if(reader.epoch!==expectedStoreEpoch)throw fail('STALE_EPOCH');
|
|
183
|
+
unit=reader.migrationList(projectId).find(x=>x.sourceUnitId===sourceUnitId);
|
|
184
|
+
if(!unit||unit.status!=='SHADOW_RO'||
|
|
185
|
+
unit.manifest.sourceKind!=='MIXED_CONTEXT')
|
|
186
|
+
throw fail('MIXED_SOURCE_NOT_SHADOW');
|
|
187
|
+
if(unit.migrationRevision!==expectedMigrationRevision)
|
|
188
|
+
throw fail('MIGRATION_VERSION_CONFLICT');
|
|
189
|
+
if(unit.sourceHash!==sourceHash)throw fail('SOURCE_CHANGED');
|
|
190
|
+
verifySourceUnit(unit.manifest);
|
|
191
|
+
const material=reader.projectMaterialList(projectId).filter(m=>
|
|
192
|
+
m.sourcePath===unit.sourcePath&&m.contentHash===sourceHash&&
|
|
193
|
+
m.provenance==='LEGACY_UNVERIFIED');
|
|
194
|
+
if(!material.some(m=>createHash('sha256').update(
|
|
195
|
+
reader.projectMaterialGet(projectId,m.materialId,m.version).body
|
|
196
|
+
).digest('hex')===sourceHash))throw fail('MIGRATION_BODY_NOT_IMPORTED');
|
|
197
|
+
}finally{reader.close()}
|
|
198
|
+
// Human-reviewed disposition: preserve FULL mixed history as
|
|
199
|
+
// EvidenceOnly/UNKNOWN. Do not assert any current Task or R/P fact.
|
|
200
|
+
await confirmWorkspaceOperator('CLASSIFY_EVIDENCE_ONLY',projectId,
|
|
201
|
+
expectedMigrationRevision,[sourceDb,sourceUnitId,sourceHash,reviewRef]);
|
|
202
|
+
const db=openContextProtocol(sourceDb,{principalId:'local-operator',
|
|
203
|
+
authorizeData:(_mode,p)=>p===projectId,
|
|
204
|
+
authorizeAdmin:(op,p)=>p===projectId&&
|
|
205
|
+
['migration.classify','migration.classify.reviewed'].includes(op)});
|
|
206
|
+
try{
|
|
207
|
+
value=db.migrationClassify({projectId,sourceUnitId,sourceHash,
|
|
208
|
+
expectedStoreEpoch,expectedMigrationRevision,writeRequestId,
|
|
209
|
+
classification:{projectId,sourceUnitId,sourceHash,
|
|
210
|
+
currentFactsComplete:true,reviewRef,taskContexts:[],
|
|
211
|
+
projectSharedContext:{},
|
|
212
|
+
unknownHistoryRefs:[{locator:unit.sourcePath,sourceHash}]}});
|
|
213
|
+
}finally{db.close()}
|
|
214
|
+
}else if(command==='project'&&sub==='inspect-reference'&&rest.length===6){
|
|
215
|
+
const [projectId,sourceDb,expectedStoreEpoch,sourceUnitId,taskId,archiveFile]=rest;
|
|
216
|
+
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
217
|
+
value=inspectLegacyRegistryReference({projectId,sourceDb,
|
|
218
|
+
expectedStoreEpoch,sourceUnitId,taskId,archiveFile});
|
|
219
|
+
}else if(command==='project'&&sub==='audit-sources'&&rest.length===3){
|
|
220
|
+
const [projectId,sourceDb,expectedStoreEpoch]=rest;
|
|
221
|
+
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
222
|
+
value=auditLegacyProjectSources({projectId,sourceDb,expectedStoreEpoch});
|
|
223
|
+
// Observe known, supported MCP writers without claiming an independent
|
|
224
|
+
// old-writer fence. Only PIDs are returned, never process argv or secrets.
|
|
225
|
+
let writerObservation;
|
|
226
|
+
try{
|
|
227
|
+
const pids=await activeLegacyWriters();
|
|
228
|
+
writerObservation={status:pids.length?'MATCHED':'NO_SUPPORTED_PROCESS_MATCH',pids};
|
|
229
|
+
}catch{writerObservation={status:'UNVERIFIED',pids:[]}}
|
|
230
|
+
value={...value,supportedWriterObservation:writerObservation};
|
|
231
|
+
}else if(command==='project'&&sub==='seal-source'&&rest.length===6){
|
|
232
|
+
const [projectId,sourceDb,epoch,revision,backupPath,sealManifestPath]=rest;
|
|
233
|
+
if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
|
|
234
|
+
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
235
|
+
if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
|
|
236
|
+
const expectedProjectRevision=Number(revision);
|
|
237
|
+
if(!Number.isSafeInteger(expectedProjectRevision)||expectedProjectRevision<1)
|
|
238
|
+
throw fail('PROJECT_VERSION_CONFLICT');
|
|
239
|
+
await confirmWorkspaceOperator('SEAL_SOURCE',projectId,
|
|
240
|
+
expectedProjectRevision,[sourceDb,epoch,backupPath,sealManifestPath]);
|
|
241
|
+
value=await fenceLegacyProjectStore({sourceDb,projectId,
|
|
242
|
+
expectedStoreEpoch:epoch,expectedProjectRevision,backupPath,sealManifestPath});
|
|
243
|
+
}else if(command==='project'&&sub==='publish-managed'&&rest.length===6){
|
|
244
|
+
const [projectId,sourceDb,epoch,revision,sealManifest,expectedSealHash]=rest;
|
|
245
|
+
if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
|
|
246
|
+
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
247
|
+
if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
|
|
248
|
+
const expectedProjectRevision=Number(revision);
|
|
249
|
+
if(!Number.isSafeInteger(expectedProjectRevision)||expectedProjectRevision<1)
|
|
250
|
+
throw fail('PROJECT_VERSION_CONFLICT');
|
|
251
|
+
await confirmWorkspaceOperator('PUBLISH_MANAGED',projectId,
|
|
252
|
+
expectedProjectRevision,[sourceDb,epoch,sealManifest,expectedSealHash]);
|
|
253
|
+
const root=contextRoot();
|
|
254
|
+
mkdirSync(root,{recursive:true,mode:0o700});
|
|
255
|
+
value=await withWorkspaceRegistryLock(root,()=>createManagedProjectBranch({
|
|
256
|
+
sourceDb,targetRoot:root,projectId,expectedStoreEpoch:epoch,
|
|
257
|
+
expectedProjectRevision,sealManifest,expectedSealHash
|
|
258
|
+
}));
|
|
259
|
+
}else if(command==='project'&&sub==='stage-diagnostic'&&rest.length===4){
|
|
260
|
+
const [projectId,sourceDb,expectedStoreEpoch,revision]=rest;
|
|
261
|
+
if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
|
|
262
|
+
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
263
|
+
if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
|
|
264
|
+
const expectedProjectRevision=Number(revision);
|
|
265
|
+
if(!Number.isSafeInteger(expectedProjectRevision)||expectedProjectRevision<1)
|
|
266
|
+
throw fail('PROJECT_VERSION_CONFLICT');
|
|
267
|
+
// This is an offline diagnostic extract; NEVER a source cutover.
|
|
268
|
+
// The operator must review the exact source path and source CAS identity.
|
|
269
|
+
await confirmWorkspaceOperator('STAGE_DIAGNOSTIC',projectId,
|
|
270
|
+
expectedProjectRevision,[sourceDb,expectedStoreEpoch]);
|
|
271
|
+
const root=contextRoot();
|
|
272
|
+
mkdirSync(root,{recursive:true,mode:0o700});
|
|
273
|
+
value=await withWorkspaceRegistryLock(root,()=>createProjectDiagnosticBranch({
|
|
274
|
+
sourceDb,targetRoot:root,projectId,expectedStoreEpoch,expectedProjectRevision
|
|
275
|
+
}));
|
|
276
|
+
}else if(command==='doctor'&&sub==='--json'&&rest.length===0)
|
|
277
|
+
value={status:'READY',packageVersion:CONTEXT_PACKAGE_VERSION,projectRoot:contextRoot()};
|
|
278
|
+
else throw fail('UNKNOWN_COMMAND');
|
|
279
|
+
return value;
|
|
280
|
+
}
|
package/lib/context-cli.mjs
CHANGED
|
@@ -3,14 +3,22 @@
|
|
|
3
3
|
// This is a SAME-UID trust boundary, not a proof of ChatGPT user identity.
|
|
4
4
|
import {realpathSync,existsSync,lstatSync,readFileSync} from 'node:fs';
|
|
5
5
|
import {randomUUID,createHash} from 'node:crypto';
|
|
6
|
-
import {execFileSync} from 'node:child_process';
|
|
7
6
|
import {createInterface} from 'node:readline/promises';
|
|
8
7
|
import {isAbsolute,resolve} from 'node:path';
|
|
9
8
|
import {DatabaseSync} from 'node:sqlite';
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
9
|
+
// This module declares ports; index.mjs is the only dependency assembler.
|
|
10
|
+
// No implementation module imports another implementation module.
|
|
11
|
+
let activeLegacyWriters, openContextProtocol, parseContextAllowedProjects, scanSourceUnit, saveShadowManifest, readShadowManifest, verifyShadowManifest, backupContextDb, createRecoveryManifest, restoreBackupToDiagnosticBranch;
|
|
12
|
+
let connected=false;
|
|
13
|
+
export function configureContextAdmin(capabilities){
|
|
14
|
+
if(connected)throw Error('CONTEXT_MODULE_ALREADY_COMPOSED');
|
|
15
|
+
for(const name of ['activeLegacyWriters', 'openContextProtocol', 'parseContextAllowedProjects', 'scanSourceUnit', 'saveShadowManifest', 'readShadowManifest', 'verifyShadowManifest', 'backupContextDb', 'createRecoveryManifest', 'restoreBackupToDiagnosticBranch']){
|
|
16
|
+
if(capabilities?.[name]===undefined)throw Error('CONTEXT_MODULE_PORT_MISSING:'+name);
|
|
17
|
+
}
|
|
18
|
+
({activeLegacyWriters, openContextProtocol, parseContextAllowedProjects, scanSourceUnit, saveShadowManifest, readShadowManifest, verifyShadowManifest, backupContextDb, createRecoveryManifest, restoreBackupToDiagnosticBranch}=capabilities);
|
|
19
|
+
connected=true;
|
|
20
|
+
}
|
|
21
|
+
|
|
14
22
|
const fail=code=>Object.assign(new Error(code),{code});
|
|
15
23
|
const hash=x=>createHash('sha256').update(x).digest('hex');
|
|
16
24
|
const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
|
|
@@ -25,18 +33,7 @@ async function operatorConfirm(expected){
|
|
|
25
33
|
if(answer!==expected)throw fail('OPERATOR_CONFIRMATION_MISMATCH');
|
|
26
34
|
}finally{rl.close()}
|
|
27
35
|
}
|
|
28
|
-
|
|
29
|
-
// Observable supported-client process inventory, NOT proof of every old
|
|
30
|
-
// npx cache or arbitrary same-UID shell. Operator must verify those too.
|
|
31
|
-
const output=execFileSync('/bin/ps',['-axo','pid=,command='],
|
|
32
|
-
{encoding:'utf8',timeout:5000,maxBuffer:2*1024*1024});
|
|
33
|
-
const pid=process.pid;
|
|
34
|
-
return output.split('\n').map(x=>x.trim()).filter(Boolean).filter(line=>{
|
|
35
|
-
const match=line.match(/^(\d+)\s+(.+)$/);
|
|
36
|
-
return match&&Number(match[1])!==pid
|
|
37
|
-
&&(/chatloop-tools\/bin\/cli\.mjs\s+mcp|@tomflow\/chatloop-tools.*\/bin\/cli\.mjs\s+mcp|chat-loop-local-tools.*\/bin\/cli\.mjs\s+mcp/.test(match[2]));
|
|
38
|
-
}).slice(0,20);
|
|
39
|
-
}
|
|
36
|
+
|
|
40
37
|
const open=(allowCreate=false)=>openContextProtocol(process.env.CHAT_LOOP_CONTEXT_DB,{
|
|
41
38
|
allowCreate,
|
|
42
39
|
principalId:'local-operator',
|
|
@@ -281,7 +278,7 @@ export async function runContextCli(argv,{confirm=operatorConfirm}={}){
|
|
|
281
278
|
const unit=manifest.sourceUnits.find(x=>x.sourceUnitId===sourceUnitId
|
|
282
279
|
&&x.projectId===projectId);
|
|
283
280
|
if(!unit)throw fail('SOURCE_UNIT_NOT_FOUND');
|
|
284
|
-
const writers=activeLegacyWriters();
|
|
281
|
+
const writers=await activeLegacyWriters();
|
|
285
282
|
if(writers.length)throw Object.assign(fail('KNOWN_LEGACY_WRITER_ACTIVE'),{writers});
|
|
286
283
|
const db=open();
|
|
287
284
|
try{
|
|
@@ -291,7 +288,7 @@ export async function runContextCli(argv,{confirm=operatorConfirm}={}){
|
|
|
291
288
|
// No model payload grants authorization; operator confirms exact physical
|
|
292
289
|
// unit after inspecting old clients/caches and the private backup.
|
|
293
290
|
await confirm('ACTIVATE '+projectId+' '+sourceUnitId);
|
|
294
|
-
if(activeLegacyWriters().length)throw fail('KNOWN_LEGACY_WRITER_ACTIVE');
|
|
291
|
+
if((await activeLegacyWriters()).length)throw fail('KNOWN_LEGACY_WRITER_ACTIVE');
|
|
295
292
|
return db.migrationActivate(write({projectId,sourceUnitId,
|
|
296
293
|
expectedMigrationRevision:stage.migrationRevision,sourceHash:unit.sourceHash},
|
|
297
294
|
{epoch:db.epoch}));
|
|
@@ -6,6 +6,19 @@ import {readFileSync,writeFileSync,mkdirSync,existsSync,lstatSync,copyFileSync,c
|
|
|
6
6
|
realpathSync,renameSync,unlinkSync,openSync,readSync,closeSync} from 'node:fs';
|
|
7
7
|
import {basename,dirname,join,resolve,isAbsolute} from 'node:path';
|
|
8
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
|
+
|
|
9
22
|
const fail=code=>Object.assign(new Error(code),{code});
|
|
10
23
|
const assert=(b,c)=>{if(!b)throw fail(c)};
|
|
11
24
|
const hash=x=>createHash('sha256').update(x).digest('hex');
|
|
@@ -256,17 +269,12 @@ export function inspectRegistryReferenceForReview(manifest,{
|
|
|
256
269
|
const newest=safeRead(current.taskDocPath,512*1024);
|
|
257
270
|
assert(hash(newest.bytes)===expectedCurrentHash,
|
|
258
271
|
'DOCUMENT_CHANGED_DURING_REVIEW');
|
|
259
|
-
const
|
|
260
|
-
|
|
261
|
-
let position=0;
|
|
262
|
-
for(const line of newLines){
|
|
263
|
-
if(position<oldLines.length&&oldLines[position]===line)position++;
|
|
264
|
-
}
|
|
265
|
-
assert(position===oldLines.length&&newLines.length>oldLines.length,
|
|
272
|
+
const lines=reviewPreservedLines(archive.bytes,newest.bytes);
|
|
273
|
+
assert(lines.insertionsOnly&&lines.insertedLines>0,
|
|
266
274
|
'REGISTRY_REVIEW_NOT_INSERTIONS_ONLY');
|
|
267
275
|
return {currentTasks:source.tasks,originalHash:previous.taskDocumentHash,
|
|
268
276
|
currentHash:expectedCurrentHash,originalArchiveHash:hash(archive.bytes),
|
|
269
|
-
originalArchivePath:archive.path,insertedLines:
|
|
270
|
-
originalLines:
|
|
277
|
+
originalArchivePath:archive.path,insertedLines:lines.insertedLines,
|
|
278
|
+
originalLines:lines.originalLines,currentLines:lines.currentLines,
|
|
271
279
|
sourceHash:source.sourceHash};
|
|
272
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
|
+
}
|