@tomflow/chatloop-context 0.1.5 → 0.6.1

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 (46) hide show
  1. package/README.md +240 -271
  2. package/bin/cli.mjs +25 -270
  3. package/capabilities/approval.mjs +151 -0
  4. package/capabilities/context.mjs +376 -0
  5. package/capabilities/document.mjs +266 -0
  6. package/capabilities/evidence.mjs +134 -0
  7. package/capabilities/presentation.mjs +82 -0
  8. package/capabilities/project.mjs +349 -0
  9. package/capabilities/sdk.mjs +72 -0
  10. package/capabilities/start.mjs +73 -0
  11. package/capabilities/task.mjs +507 -0
  12. package/capabilities.generated.mjs +11 -0
  13. package/docs/interfaces.md +182 -0
  14. package/docs/operator-and-migration.md +277 -0
  15. package/index.mjs +236 -0
  16. package/lib/api-aspect.mjs +190 -0
  17. package/lib/api-log.mjs +161 -0
  18. package/lib/approval-policy.mjs +24 -0
  19. package/lib/capability-catalog.generated.json +1989 -0
  20. package/lib/capability-router.mjs +67 -0
  21. package/lib/cli-commands.mjs +280 -0
  22. package/lib/context-cli.mjs +16 -19
  23. package/lib/context-migration.mjs +17 -9
  24. package/lib/core/context.mjs +115 -0
  25. package/lib/core/evidence.mjs +51 -0
  26. package/lib/core/health.mjs +55 -0
  27. package/lib/core/migration.mjs +262 -0
  28. package/lib/core/project.mjs +246 -0
  29. package/lib/core/review.mjs +147 -0
  30. package/lib/core/run.mjs +343 -0
  31. package/lib/core/store.mjs +391 -0
  32. package/lib/core/task.mjs +166 -0
  33. package/lib/line-review.mjs +13 -0
  34. package/lib/methods.mjs +49 -202
  35. package/lib/operations.mjs +33 -145
  36. package/lib/orphan-operator.mjs +17 -51
  37. package/lib/process-inventory.mjs +20 -0
  38. package/lib/project-branch.mjs +312 -0
  39. package/lib/project-diagnostic.mjs +26 -328
  40. package/lib/project-guards.mjs +19 -0
  41. package/lib/project-store.mjs +115 -0
  42. package/lib/trusted-run.mjs +86 -0
  43. package/lib/workspace-operator.mjs +12 -2
  44. package/package.json +32 -14
  45. package/scripts/build-capabilities.mjs +114 -0
  46. package/lib/context-protocol.mjs +0 -1687
package/lib/methods.mjs CHANGED
@@ -1,7 +1,16 @@
1
+ // Context public API metadata, assembled from the generated capability catalog.
2
+ // No new operation requires editing this registry or adding a switch branch.
1
3
  import {readFileSync} from 'node:fs';
2
4
  export const CONTEXT_PACKAGE_VERSION=JSON.parse(readFileSync(new URL('../package.json',import.meta.url),'utf8')).version;
3
- // Opt-in ContextService MCP adapter. Never a browser Owner or an admin endpoint.
4
- // Importing this module is safe on the published Node >=20 legacy runtime.
5
+ export const CONTEXT_CONTRACT='chat-loop.context-sdk.v2';
6
+ const registry=JSON.parse(readFileSync(
7
+ new URL('./capability-catalog.generated.json',import.meta.url),'utf8'));
8
+ const failure=code=>Object.assign(new Error(code),{code});
9
+ const groupGuide=registry.groups;
10
+ export const methodDefinitions=Object.freeze(registry.methods.map(m=>Object.freeze(m)));
11
+ export const methodById=new Map(methodDefinitions.map(m=>[m.id,m]));
12
+ if(methodDefinitions.length!==methodById.size||!groupGuide.length)
13
+ throw failure('CAPABILITY_CATALOG_INVALID');
5
14
  const ID='^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$';
6
15
  const scopeError=code=>Object.assign(new Error(code),{code});
7
16
  // A grant is an atomic permission statement, not a bag of best-effort tokens.
@@ -16,225 +25,63 @@ export function parseContextAllowedProjects(raw){
16
25
  throw scopeError('CONTEXT_PROJECT_SCOPE_INVALID');
17
26
  return new Set(entries);
18
27
  }
19
- const req=(operation,required,optional=[])=>({
20
- type:'object',required:['operation',...required],additionalProperties:false,
21
- properties:Object.fromEntries([['operation',{const:operation}],...required.map(k=>[k,fields[k]]),
22
- ...optional.map(k=>[k,fields[k]])])
23
- });
24
- const fields={
25
- projectId:{type:'string',pattern:ID},taskId:{type:'string',pattern:ID},
26
- materialId:{type:'string',pattern:ID},
27
- title:{type:'string',minLength:1,maxLength:200},objective:{type:'string',maxLength:10000},
28
- sharedContext:{type:'object'},context:{type:'object'},patch:{type:'object'},
29
- expectedStoreEpoch:{type:'string',minLength:10,maxLength:64},
30
- expectedProjectRevision:{type:'integer',minimum:1},
31
- expectedTaskRevision:{type:'integer',minimum:1},
32
- expectedBindingRevision:{type:'integer',minimum:0},
33
- expectedApprovalRevision:{type:'integer',minimum:1},
34
- writeRequestId:{type:'string',minLength:8,maxLength:128},
35
- documentId:{type:'string',pattern:ID},version:{type:'integer',minimum:1},
36
- kind:{enum:['R','P','INSTRUCTIONS','HISTORY','LEGACY_EVIDENCE','REFERENCE']},
37
- body:{type:'string',minLength:1,maxLength:4194304},
38
- provenance:{enum:['USER_AUTHORED','LEGACY_UNVERIFIED']},
39
- sourcePath:{type:'string',minLength:1,maxLength:4096},
40
- requirementRef:{type:'object',additionalProperties:false,
41
- required:['documentId','version','contentHash'],
42
- properties:{documentId:{type:'string',pattern:ID},version:{type:'integer',minimum:1},
43
- contentHash:{type:'string',pattern:'^[a-f0-9]{64}$'}}},
44
- contentHash:{type:'string',pattern:'^[a-f0-9]{64}$'},
45
- limit:{type:'integer',minimum:1,maximum:100},
46
- cursor:{type:'string',pattern:ID},
47
- issueId:{type:'string',minLength:8,maxLength:64},
48
- decision:{enum:['APPROVE','REJECT','REQUEST_CHANGE','CUSTOM','ACCEPT']},
49
- outcome:{enum:['CANCELLED','FAILED','REJECTED']},
50
- reason:{const:'REPAIR_SAME_SCOPE'},
51
- purpose:{enum:['NEW_EXECUTION','REPAIR_SAME_SCOPE']},
52
- impact:{enum:['NO_SCOPE_IMPACT','R_AND_P_REAPPROVAL']},
53
- reviewEvidenceRef:{type:'string',minLength:8,maxLength:4096},
54
- effectRef:{type:'string',minLength:1,maxLength:256},
55
- resolutionEvidenceRef:{type:'string',minLength:8,maxLength:4096},
56
- sourceRef:{type:'string',minLength:8,maxLength:256},
57
- deliveryRef:{type:'string',minLength:8,maxLength:4096},
58
- comment:{type:'string',maxLength:2000},
59
- artifactId:{type:'string',minLength:8,maxLength:128},
60
- locator:{type:'string',minLength:1,maxLength:4096},
61
- role:{type:'string',pattern:'^[a-z][a-z0-9_-]{0,63}$'},
62
- retention:{enum:['RETAINED','EXTERNAL','EPHEMERAL']},
63
- sourceRole:{const:'user'},
64
- userTurn:{type:'string',minLength:8,maxLength:256},
65
- presentedAssistantRef:{type:'string',minLength:8,maxLength:256},
66
- checkpointId:{type:'string',minLength:8,maxLength:64},
67
- storeEpoch:{type:'string',minLength:10,maxLength:64},
68
- maxBytes:{type:'integer',minimum:16384,maximum:262144},
69
- runRef:{type:'string',minLength:8,maxLength:256},
70
- runCredential:{type:'string',pattern:'^[0-9a-f]{64}$'},
71
- evidenceRefs:{type:'array',maxItems:200,items:{type:'object'}},
72
- unknownEffects:{type:'array',maxItems:200,items:{type:'object'}}
73
- };
74
- const w=['expectedStoreEpoch','writeRequestId'];
75
- fields.group={type:'string',minLength:1,maxLength:64};
76
- fields.methodId={type:'string',minLength:3,maxLength:128};
77
- fields.workspaceRoots={type:'array',minItems:1,maxItems:16,items:{type:'string',maxLength:4096}};
78
-
79
- const readDefs=[
80
- ['project.list',[],['limit','cursor']],['project.get',['projectId'],[]],
81
- ['project.authority',['projectId'],[]],
82
- ['project.registryAuthority',['projectId'],[]],
83
- ['project.material.list',['projectId'],[]],
84
- ['project.material.get',['projectId','materialId','version'],[]],
85
- ['task.list',['projectId'],['limit','cursor']],['task.get',['projectId','taskId'],[]],
86
- ['document.get',['projectId','taskId','documentId','version'],[]],
87
- ['document.list',['projectId','taskId'],[]],
88
- ['evidence.list',['projectId','taskId'],[]],
89
- ['context.history',['projectId','taskId'],[]],
90
- ['context.resume',['projectId','taskId','checkpointId'],['maxBytes']],
91
- ['context.request.status',['projectId','storeEpoch','writeRequestId'],[]]
92
- ];
93
- const mutateDefs=[
94
- ['project.create',['projectId','title',...w],['sharedContext']],
95
- ['project.material.put',['projectId','materialId','version','kind','body',
96
- 'expectedProjectRevision',...w],['sourcePath','contentHash','provenance']],
97
- ['project.patch',['projectId','expectedProjectRevision','sharedContext',...w],[]],
98
- ['project.archive',['projectId','expectedProjectRevision',...w],[]],
99
- ['task.create',['projectId','taskId','title',...w],['objective','context']],
100
- ['task.archive',['projectId','taskId','expectedTaskRevision',...w],[]],
101
- ['task.reopen',['projectId','taskId','expectedTaskRevision','reason','userTurn',...w],[]],
102
- ['task.reviewProjectRules',['projectId','taskId','expectedTaskRevision',
103
- 'expectedProjectRevision','impact','reviewEvidenceRef',...w],[]],
104
- ['task.accept',['projectId','taskId','expectedTaskRevision','decision','userTurn',...w],['comment']],
105
- ['task.complete',['projectId','taskId','expectedTaskRevision','expectedBindingRevision',
106
- 'runRef','runCredential','deliveryRef',...w],[]],
107
- ['task.patch',['projectId','taskId','expectedTaskRevision','patch',...w],
108
- ['expectedBindingRevision','runRef','runCredential']],
109
- ['document.createDraft',['projectId','taskId','documentId','version','kind','body',
110
- 'expectedTaskRevision',...w],['requirementRef']],
111
- ['presentation.resolve',['projectId','taskId','issueId','outcome','sourceRef',
112
- 'expectedTaskRevision',...w],[]],
113
- ['document.prepareIssue',['projectId','taskId','documentId','version','contentHash',
114
- 'expectedTaskRevision',...w],[]],
115
- ['approval.observe',['projectId','taskId','issueId','decision','sourceRole','userTurn',
116
- 'presentedAssistantRef','expectedTaskRevision',...w],[]],
117
- ['approval.revoke',['projectId','taskId','expectedTaskRevision','expectedApprovalRevision',...w],[]],
118
- ['evidence.attach',['projectId','taskId','expectedTaskRevision','locator',
119
- 'role',...w],['contentHash','retention','expectedBindingRevision','runRef','runCredential']],
120
- ['evidence.detach',['projectId','taskId','expectedTaskRevision','artifactId',
121
- ...w],['expectedBindingRevision','runRef','runCredential']],
122
- ['start.reserve',['projectId','taskId','expectedTaskRevision',
123
- 'expectedApprovalRevision',...w],['purpose']],
124
- ['context.patch',['projectId','taskId','expectedTaskRevision','expectedBindingRevision',
125
- 'runRef','runCredential','patch',...w],[]],
126
- ['context.unknown.resolve',['projectId','taskId','expectedTaskRevision',
127
- 'expectedBindingRevision','runRef','runCredential','effectRef','resolutionEvidenceRef',...w],[]],
128
- ['context.checkpoint',['projectId','taskId','expectedTaskRevision','expectedBindingRevision',
129
- 'runRef','runCredential',...w],['evidenceRefs','unknownEffects']]
130
- ];
131
28
 
132
- // This catalog is the single source for SDK, CLI and ChatGPT MCP descriptions.
133
- export const CONTEXT_CONTRACT='chat-loop.context-sdk.v1';
134
- readDefs.push(
135
- ['sdk.methods.list',[],['group']],
136
- ['sdk.methods.describe',['methodId'],[]],
137
- ['project.resolve',['workspaceRoots'],[]],
138
- ['project.open',['projectId'],[]],
139
- ['context.open',['projectId'],[]],
140
- ['task.open',['projectId','taskId'],[]]
141
- );
142
- const READ_DESC={
143
- 'sdk.methods.list':'Discover available SDK methods by group without reading project data.',
144
- 'sdk.methods.describe':'Read the exact input schema, semantics and failure conditions of one method.',
145
- 'project.resolve':'Find authorized projects matching confirmed workspace roots; never guesses identity.',
146
- 'project.open':'Open an authorized project summary, current instruction reference and task candidates.',
147
- 'context.open':'Open the level-one project Context summary without loading historical documents.',
148
- 'task.open':'Load one chosen task current state and versioned recovery references.',
149
- 'project.list':'List authorized Project identities. Use limit (1–100) and optional last-visible Project cursor for bounded pages; omit pagination arguments for the legacy array.',
150
- 'project.get':'Read the selected project identity and shared context.',
151
- 'project.authority':'Check whether a project is actually managed and writable.',
152
- 'project.registryAuthority':'Read the exact legacy Registry physical source authority; independent of business write eligibility.',
153
- 'project.material.list':'List versioned project materials without returning full bodies.',
154
- 'project.material.get':'Read exact reviewed project Instructions or historical material by version.',
155
- 'task.list':'List authorized tasks of a selected project; supply limit (1–100) and optional last-visible task cursor for bounded keyset pages. Without pagination arguments, returns the legacy array.',
156
- 'task.get':'Read exact task state, revisions, progress and blocker details.',
157
- 'document.get':'Read an immutable R/P document at a precise version.',
158
- 'document.list':'List versioned R/P documents of a task.',
159
- 'evidence.list':'List task evidence references and verification state.',
160
- 'context.history':'Read versioned history and receipts for a task.',
161
- 'context.resume':'Read one verified checkpoint snapshot; does not grant Browser Owner.',
162
- 'context.request.status':'Check an unknown write using its original durable writeRequestId.'
163
- };
164
- const WRITE_DESC={
165
- 'project.create':'Legacy unified-Store only: add a project to an initialized authorized Store; per-project databases require operator project init.',
166
- 'project.material.put':'Write one immutable project material version.',
167
- 'project.patch':'Change project context and explicit current Instructions reference with CAS.',
168
- 'project.archive':'Archive an authorized project after checking active tasks.',
169
- 'task.create':'Create a project-scoped task with an initial DRAFT state.',
170
- 'task.patch':'Patch permitted Task fields with revision and run-holder checks.',
171
- 'task.archive':'Archive an authorized task without bypassing active run restrictions.',
172
- 'task.reopen':'Reopen a delivered task only for authorized same-scope repair.',
173
- 'task.reviewProjectRules':'Adopt verified new project rules or require R/P reapproval.',
174
- 'task.accept':'Record actual user delivery acceptance decision.',
175
- 'task.complete':'Commit machine delivery outcome under current run-binding authorization.',
176
- 'document.createDraft':'Create immutable R/P draft version linked to a task.',
177
- 'document.prepareIssue':'Record intent to present a precise R/P version.',
178
- 'presentation.resolve':'Resolve an uncompleted R/P presentation attempt with evidence.',
179
- 'approval.observe':'Record soft evidence of a real user decision on a displayed R/P version.',
180
- 'approval.revoke':'Invalidate earlier approvals at the correct task revision.',
181
- 'evidence.attach':'Attach a verified external evidence reference to one task.',
182
- 'evidence.detach':'Detach a task evidence reference with CAS and permission checks.',
183
- 'start.reserve':'Reserve a short-lived start lease after both effective R/P approvals.',
184
- 'context.patch':'Write active-run progress under the current holder and revisions.',
185
- 'context.unknown.resolve':'Resolve a known unknown side effect only with matching evidence.',
186
- 'context.checkpoint':'Create a durable business checkpoint, not Browser Owner permission.'
187
- };
188
- const groupOf=op=>op.split('.')[0];
189
- export const methodDefinitions=[
190
- ...readDefs.map(([id,required,optional])=>({id,group:groupOf(id),mode:'read',
191
- description:READ_DESC[id]||'Read '+id.replaceAll('.',' ')+' from authorized Context.',
192
- inputSchema:req(id,required,optional)})),
193
- ...mutateDefs.map(([id,required,optional])=>({id,group:groupOf(id),mode:'write',
194
- description:WRITE_DESC[id]||'Write '+id.replaceAll('.',' ')+' to authorized Context.',
195
- inputSchema:req(id,required,optional)}))
196
- ];
197
- export const methodById=new Map(methodDefinitions.map(m=>[m.id,m]));
198
- export function listMethods(group){
199
- return {contractVersion:CONTEXT_CONTRACT,packageVersion:CONTEXT_PACKAGE_VERSION,methods:methodDefinitions
200
- .filter(m=>!group||m.group===group)
201
- .map(({id,group,mode,description})=>({methodId:id,group,mode,description}))};
29
+ export function listMethods(group,view='methods'){
30
+ const selected=methodDefinitions.filter(m=>!group||m.group===group);
31
+ if(view==='groups')return {
32
+ contractVersion:CONTEXT_CONTRACT,packageVersion:CONTEXT_PACKAGE_VERSION,
33
+ groups:groupGuide.filter(g=>!group||g.id===group).map(g=>{
34
+ const members=selected.filter(m=>m.group===g.id);
35
+ return {group:g.id,purpose:g.purpose,startWith:g.startWith,
36
+ methodCount:members.length,
37
+ readCount:members.filter(m=>m.mode==='read').length,
38
+ writeCount:members.filter(m=>m.mode==='write').length,
39
+ legacyMethods:members.filter(m=>m.lifecycle?.surface==='legacy').map(m=>m.id)};
40
+ })
41
+ };
42
+ if(view!=='methods')throw failure('INVALID_ARGUMENT');
43
+ return {contractVersion:CONTEXT_CONTRACT,packageVersion:CONTEXT_PACKAGE_VERSION,
44
+ methods:selected.map(({id,group,mode,description})=>
45
+ ({methodId:id,group,mode,description}))};
202
46
  }
203
47
  export function describeMethod(methodId){
204
48
  const m=methodById.get(methodId);
205
- if(!m)throw Object.assign(new Error('METHOD_NOT_FOUND'),{code:'METHOD_NOT_FOUND'});
206
- return {contractVersion:CONTEXT_CONTRACT,packageVersion:CONTEXT_PACKAGE_VERSION,methodId:m.id,group:m.group,mode:m.mode,
49
+ if(!m)throw failure('METHOD_NOT_FOUND');
50
+ return {contractVersion:CONTEXT_CONTRACT,packageVersion:CONTEXT_PACKAGE_VERSION,
51
+ methodId:m.id,group:m.group,mode:m.mode,
207
52
  description:m.description,inputSchema:m.inputSchema,
53
+ lifecycle:m.lifecycle??{surface:'public'},
208
54
  outputContract:'JSON value, immutable hashes and explicit revision/authority where applicable',
209
55
  errorContract:'typed error code; unknown write outcome requires original requestId receipt lookup'};
210
56
  }
211
57
  export const contextGatewayTools=[
212
58
  {name:'chat_loop_context_get',
213
59
  description:'Context SDK READ. First use sdk.methods.list, then sdk.methods.describe to discover authorized Project/Task/Document/Checkpoint operations; read project summary before expanding detail.',
214
- inputSchema:{oneOf:readDefs.map(([id,required,optional])=>req(id,required,optional))},
60
+ inputSchema:{oneOf:methodDefinitions.filter(m=>m.mode==='read').map(m=>m.inputSchema)},
215
61
  annotations:{readOnlyHint:true}},
216
62
  {name:'chat_loop_context_mutate',
217
63
  description:'Context SDK WRITE. First inspect current version and method Schema; use expectedStoreEpoch, revisions and unique writeRequestId. No internal Native run controls.',
218
- inputSchema:{oneOf:mutateDefs.map(([id,required,optional])=>req(id,required,optional))},
64
+ inputSchema:{oneOf:methodDefinitions.filter(m=>m.mode==='write').map(m=>m.inputSchema)},
219
65
  annotations:{readOnlyHint:false}}
220
66
  ];
221
67
  export function validateContextCall(name,args){
222
- const defs=name==='chat_loop_context_get'?readDefs:
223
- name==='chat_loop_context_mutate'?mutateDefs:null;
224
- if(!defs)throw Object.assign(new Error('UNKNOWN_TOOL'),{code:'UNKNOWN_TOOL'});
68
+ const mode=name==='chat_loop_context_get'?'read':
69
+ name==='chat_loop_context_mutate'?'write':null;
70
+ if(!mode)throw failure('UNKNOWN_TOOL');
225
71
  if(!args||typeof args!=='object'||Array.isArray(args))
226
- throw Object.assign(new Error('INVALID_ARGUMENT'),{code:'INVALID_ARGUMENT'});
227
- const op=defs.find(([id])=>id===args.operation);
228
- if(!op)throw Object.assign(new Error('UNSUPPORTED_CONTEXT_OPERATION'),{code:'UNSUPPORTED_CONTEXT_OPERATION'});
229
- const [,required,optional]=op;
230
- if(required.some(k=>!Object.hasOwn(args,k))||
231
- Object.keys(args).some(k=>k!=='operation'&&!required.includes(k)&&!optional.includes(k)))
232
- throw Object.assign(new Error('INVALID_ARGUMENT'),{code:'INVALID_ARGUMENT'});
233
- for(const key of [...required,...optional]){
234
- if(Object.hasOwn(args,key)&&!matchesSchema(args[key],fields[key]))
235
- throw Object.assign(new Error('INVALID_ARGUMENT'),{code:'INVALID_ARGUMENT'});
72
+ throw failure('INVALID_ARGUMENT');
73
+ const method=methodById.get(args.operation);
74
+ if(!method||method.mode!==mode)
75
+ throw failure('UNSUPPORTED_CONTEXT_OPERATION');
76
+ const spec=method.inputSchema;
77
+ if(spec.required.some(key=>!Object.hasOwn(args,key))
78
+ ||Object.keys(args).some(key=>!Object.hasOwn(spec.properties,key)))
79
+ throw failure('INVALID_ARGUMENT');
80
+ for(const [key,value] of Object.entries(args)){
81
+ if(!matchesSchema(value,spec.properties[key]))
82
+ throw failure('INVALID_ARGUMENT');
236
83
  }
237
- return methodById.get(args.operation);
84
+ return method;
238
85
  }
239
86
  // Validate nested and top-level inputs from the *same* schema exposed to MCP.
240
87
  // Open-ended domain objects (patch/context/evidence) remain validated by Core.
@@ -1,93 +1,27 @@
1
- // Authorized Context SDK dispatcher. No Browser Owner and no internal run controls.
2
- import {DatabaseSync} from 'node:sqlite';
3
- import {existsSync,lstatSync,realpathSync} from 'node:fs';
4
- import {homedir} from 'node:os';
5
- import {isAbsolute,join,resolve} from 'node:path';
6
- import {openContextProtocol} from './context-protocol.mjs';
7
- import {CONTEXT_CONTRACT,validateContextCall,listMethods,describeMethod,
8
- parseContextAllowedProjects} from './methods.mjs';
9
- const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
10
- const fail=code=>Object.assign(new Error(code),{code});
11
- export const contextRoot=()=>resolve(process.env.CHAT_LOOP_CONTEXT_ROOT||join(homedir(),'.chat-loop','context'));
12
- export const allowedProjects=()=>parseContextAllowedProjects(process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS);
13
- function projectDatabase(projectId){
14
- if(!ID.test(projectId||''))throw fail('INVALID_SCOPE');
15
- // Never silently keep routing to an old shared Store when a per-Project
16
- // root was configured for cutover. Two data roots are not a valid mode.
17
- if(process.env.CHAT_LOOP_CONTEXT_DB&&process.env.CHAT_LOOP_CONTEXT_ROOT)
18
- throw fail('CONTEXT_SOURCE_AMBIGUOUS');
19
- const explicit=process.env.CHAT_LOOP_CONTEXT_DB;
20
- if(explicit){
21
- if(!isAbsolute(explicit))throw fail('CONTEXT_DB_NOT_ABSOLUTE');
22
- return explicit; // Explicit legacy Store is a separately verified transition mode.
23
- }
24
- const root=contextRoot();
25
- if(existsSync(root)){
26
- const st=lstatSync(root);
27
- if(!st.isDirectory()||st.isSymbolicLink()||(st.mode&0o077))throw fail('CONTEXT_ROOT_UNTRUSTED');
1
+ // This module declares ports; index.mjs is the only dependency assembler.
2
+ // No implementation module imports another implementation module.
3
+ let openContextProtocol, CONTEXT_CONTRACT, validateContextCall, listMethods, describeMethod, projectDatabase, projectMeta, verifiedStoreFile, resolveProjects;
4
+ export let allowedProjects;
5
+ let connected=false;
6
+ export function configureOperations(capabilities){
7
+ if(connected)throw Error('CONTEXT_MODULE_ALREADY_COMPOSED');
8
+ for(const name of ['openContextProtocol', 'CONTEXT_CONTRACT', 'validateContextCall', 'listMethods', 'describeMethod', 'projectDatabase', 'projectMeta', 'verifiedStoreFile', 'resolveProjects', 'allowedProjects']){
9
+ if(capabilities?.[name]===undefined)throw Error('CONTEXT_MODULE_PORT_MISSING:'+name);
28
10
  }
29
- const dir=join(root,projectId);
30
- if(existsSync(dir)){
31
- const st=lstatSync(dir);
32
- if(!st.isDirectory()||st.isSymbolicLink()||(st.mode&0o077))throw fail('PROJECT_DIRECTORY_UNTRUSTED');
33
- }
34
- return join(dir,'context.sqlite');
35
- }
36
- // Real read-only SQLite discovery: never initializes a missing database or turns WAL on.
37
- function projectMeta(projectId){
38
- const file=projectDatabase(projectId);
39
- if(!existsSync(file))return null;
40
- const st=lstatSync(file);
41
- if(!st.isFile()||st.isSymbolicLink()||(st.mode&0o077))throw fail('STORE_FILE_UNTRUSTED');
42
- const db=new DatabaseSync(file,{readOnly:true,timeout:3500});
43
- try{
44
- db.exec('PRAGMA query_only=ON');
45
- if(!db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='projects'").get())
46
- throw fail('STORE_SCHEMA_UNKNOWN');
47
- const schema=db.prepare("SELECT value FROM meta WHERE key='schemaVersion'").get()?.value;
48
- if(schema!=='6')throw fail('STORE_SCHEMA_MISMATCH');
49
- const r=db.prepare('SELECT project_id,title,project_revision,shared_context_json,archived FROM projects WHERE project_id=?').get(projectId);
50
- if(!r)throw fail('PROJECT_IDENTITY_MISMATCH');
51
- if(!process.env.CHAT_LOOP_CONTEXT_DB){
52
- const others=db.prepare('SELECT project_id FROM projects WHERE project_id<>?').all(projectId);
53
- if(others.length)throw fail('PROJECT_IDENTITY_MISMATCH');
54
- }
55
- const sharedContext=JSON.parse(r.shared_context_json);
56
- return {projectId,title:r.title,projectRevision:r.project_revision,
57
- sharedContext,workspaceRefs:Array.isArray(sharedContext.workspaceRefs)?
58
- sharedContext.workspaceRefs:[],archived:!!r.archived};
59
- }finally{db.close()}
11
+ ({openContextProtocol, CONTEXT_CONTRACT, validateContextCall, listMethods, describeMethod, projectDatabase, projectMeta, verifiedStoreFile, resolveProjects, allowedProjects}=capabilities);
12
+ if(capabilities.capabilityRouter===undefined)throw Error('CONTEXT_MODULE_PORT_MISSING:capabilityRouter');
13
+ capabilityRouter=capabilities.capabilityRouter;
14
+ connected=true;
60
15
  }
61
- // Shared, security-reviewed Project identity resolver for the private Native
62
- // adapter. It must never create a Store or resolve a different Project's DB.
63
- export function resolveVerifiedProjectDatabase(projectId){
64
- if(!projectMeta(projectId))throw fail('STORE_MISSING');
65
- return projectDatabase(projectId);
66
- }
67
- function resolveProjects(a,allowed){
68
- if(!Array.isArray(a.workspaceRoots)||!a.workspaceRoots.length)throw fail('WORKSPACE_REQUIRED');
69
- const roots=a.workspaceRoots.map(s=>{
70
- if(typeof s!=='string'||!isAbsolute(s))throw fail('WORKSPACE_INVALID');
71
- try{return realpathSync(s)}catch{throw fail('WORKSPACE_UNVERIFIED')}
72
- });
73
- const matches=[];
74
- for(const id of allowed){
75
- const meta=projectMeta(id);
76
- if(!meta||meta.archived)continue;
77
- const registered=meta.workspaceRefs.filter(x=>typeof x==='string'&&isAbsolute(x));
78
- const resolved=registered.map(x=>{try{return realpathSync(x)}catch{return null}});
79
- const matchingRoots=roots.filter(x=>resolved.includes(x));
80
- if(matchingRoots.length){
81
- const {sharedContext,...publicMeta}=meta;
82
- matches.push({...publicMeta,matchingRoots});
83
- }
84
- }
85
- return {candidates:matches,ambiguous:matches.length!==1};
86
- }
87
- async function runContextOperation(args){
88
- const methodId=args?.operation;
89
- const method=validateContextCall('chat_loop_context_get',args);
90
- if(method.id==='sdk.methods.list')return listMethods(args.group);
16
+ let capabilityRouter;
17
+
18
+ // Authorized Context SDK dispatcher. No Browser Owner and no internal run controls.
19
+ const fail=code=>Object.assign(new Error(code),{code});
20
+ // The single public dispatch already validated both the tool and Method Catalog.
21
+ // Do not duplicate schema parsing on every read (not even for SDK discovery).
22
+ async function runContextOperation(args,method){
23
+ const methodId=method.id;
24
+ if(method.id==='sdk.methods.list')return listMethods(args.group,args.view);
91
25
  if(method.id==='sdk.methods.describe')return describeMethod(args.methodId);
92
26
  const allowed=allowedProjects();
93
27
  if(!allowed.size)throw fail('CONTEXT_ALLOWED_PROJECTS_REQUIRED');
@@ -99,9 +33,6 @@ async function runContextOperation(args){
99
33
  projectRevision:meta.projectRevision,sharedContext:meta.sharedContext,
100
34
  archived:meta.archived
101
35
  });
102
- // Preserve the old array shape unless the caller explicitly pages.
103
- if(args.limit===undefined&&args.cursor===undefined)
104
- return [...allowed].map(projectMeta).filter(Boolean).map(publicProject);
105
36
  const limit=args.limit??30,cursor=args.cursor??null;
106
37
  if(cursor!==null&&(!allowed.has(cursor)||!projectMeta(cursor)))
107
38
  throw fail('PROJECT_CURSOR_INVALID');
@@ -120,15 +51,15 @@ async function runContextOperation(args){
120
51
  readOnly:true,principalId:'private-mcp',
121
52
  authorizeData:(_type,projectId)=>allowed.has(projectId),
122
53
  authorizeInternal:()=>false});
123
- try{return db.projectList({limit:args.limit,cursor:args.cursor})}finally{db.close()}
54
+ try{return db.projectList({limit:args.limit??30,cursor:args.cursor})}finally{db.close()}
124
55
  }
125
56
  if(args.projectId!==undefined&&!allowed.has(args.projectId))throw fail('PROJECT_ACCESS_DENIED');
126
57
  if(!args.projectId)throw fail('PROJECT_ID_REQUIRED');
127
- return executeDb(args,allowed,method.mode);
58
+ return executeDb(args,allowed,method.mode,method);
128
59
  }
129
60
  export async function dispatchContextCall(name,args){
130
61
  const method=validateContextCall(name,args);
131
- if(method.mode==='read')return runContextOperation(args);
62
+ if(method.mode==='read')return runContextOperation(args,method);
132
63
  const allowed=allowedProjects();
133
64
  if(!allowed.size)throw fail('CONTEXT_ALLOWED_PROJECTS_REQUIRED');
134
65
  if(!allowed.has(args.projectId))throw fail('PROJECT_ACCESS_DENIED');
@@ -136,21 +67,14 @@ export async function dispatchContextCall(name,args){
136
67
  // Keep binding violations distinct even when generic project creation is disabled.
137
68
  if(method.id==='project.patch' && Object.hasOwn(args.sharedContext,'workspaceRefs'))
138
69
  throw fail('WORKSPACE_REBIND_REQUIRES_OPERATOR');
139
- if(method.id==='project.create' && args.sharedContext &&
140
- Object.hasOwn(args.sharedContext,'workspaceRefs'))
141
- throw fail('WORKSPACE_BIND_REQUIRES_OPERATOR');
142
- // Per-project SQLite is created ONLY via the local operator's validated init.
143
- // Never allow a generic MCP mutation to add a second Project into that file.
144
- if(method.id==='project.create'&&!process.env.CHAT_LOOP_CONTEXT_DB)
145
- throw fail('PROJECT_CREATE_OPERATOR_ONLY');
146
- return executeDb(args,allowed,method.mode);
70
+ return executeDb(args,allowed,method.mode,method);
147
71
  }
148
- function executeDb(a,allowed,mode){
72
+ async function executeDb(a,allowed,mode,method){
149
73
  if(Number(process.versions.node.split('.')[0])<24)throw fail('CONTEXT_RUNTIME_UNSUPPORTED');
150
74
  // A read or ordinary write must never create a project directory or SQLite.
151
75
  // Only explicit operator project init may create a previously absent Store.
152
76
  const file=projectDatabase(a.projectId);
153
- if(!existsSync(file))throw fail('STORE_MISSING');
77
+ verifiedStoreFile(file,'STORE_MISSING');
154
78
  // project.list/resolve already verify this; ordinary get/mutate must too.
155
79
  // Read-only identity check precedes any writable SQLite open and rules out
156
80
  // a copied/renamed or multi-Project database under the wrong directory.
@@ -161,11 +85,11 @@ function executeDb(a,allowed,mode){
161
85
  authorizeInternal:()=>false
162
86
  });
163
87
  try{
164
- if(mode==='write'&&a.operation!=='project.create'){
88
+ if(mode==='write'){
165
89
  if(!db.projectBusinessAuthority(a.projectId).writable)
166
90
  throw fail('PROJECT_CUTOVER_NOT_VERIFIED');
167
91
  }
168
- if(a.operation==='project.open'||a.operation==='context.open'){
92
+ if(a.operation==='project.open'){
169
93
  const {project,authority,tasks,taskCount,storeEpoch}=db.projectSnapshot(a.projectId);
170
94
  return {contractVersion:CONTEXT_CONTRACT,project,authority,storeEpoch,
171
95
  taskCount,tasks,incomplete:taskCount>tasks.length,
@@ -176,44 +100,8 @@ function executeDb(a,allowed,mode){
176
100
  return {contractVersion:CONTEXT_CONTRACT,task,storeEpoch,
177
101
  projectRevision:project.projectRevision,authority};
178
102
  }
179
- switch(a.operation){
180
- case 'project.list':return db.projectList();
181
- case 'project.get':return db.projectGet(a.projectId);
182
- case 'project.authority':return db.projectBusinessAuthority(a.projectId);
183
- case 'project.registryAuthority':return db.registryAuthority(a.projectId);
184
- case 'project.material.list':return db.projectMaterialList(a.projectId);
185
- case 'project.material.get':return db.projectMaterialGet(a.projectId,a.materialId,a.version);
186
- case 'project.material.put':return db.projectMaterialPut(a);
187
- case 'project.create':return db.projectCreate(a);
188
- case 'project.patch':return db.projectPatch(a);
189
- case 'project.archive':return db.projectArchive(a);
190
- case 'task.list':return db.taskList(a.projectId,{limit:a.limit,cursor:a.cursor});
191
- case 'task.get':return db.get(a.projectId,a.taskId);
192
- case 'task.create':return db.taskCreate(a);
193
- case 'task.patch':return db.taskPatch(a);
194
- case 'task.archive':return db.taskArchive(a);
195
- case 'task.reopen':return db.taskReopen(a);
196
- case 'task.reviewProjectRules':return db.taskReviewProjectRules(a);
197
- case 'task.accept':return db.taskAccept(a);
198
- case 'task.complete':return db.taskComplete(a);
199
- case 'document.get':return db.documentGet(a.projectId,a.taskId,a.documentId,a.version);
200
- case 'document.list':return db.documentList(a.projectId,a.taskId);
201
- case 'document.createDraft':return db.documentCreate(a);
202
- case 'document.prepareIssue':return db.prepareIssue(a);
203
- case 'presentation.resolve':return db.presentationResolve(a);
204
- case 'approval.observe':return db.observeApproval(a);
205
- case 'approval.revoke':return db.revokeApproval(a);
206
- case 'start.reserve':return db.reserve(a);
207
- case 'evidence.list':return db.evidenceList(a.projectId,a.taskId);
208
- case 'evidence.attach':return db.evidenceAttach(a);
209
- case 'evidence.detach':return db.evidenceDetach(a);
210
- case 'context.history':return db.history(a.projectId,a.taskId);
211
- case 'context.patch':return db.patch(a);
212
- case 'context.unknown.resolve':return db.resolveUnknownEffect(a);
213
- case 'context.checkpoint':return db.checkpoint(a);
214
- case 'context.resume':return db.resume(a.projectId,a.taskId,a.checkpointId,a.maxBytes);
215
- case 'context.request.status':return db.requestStatus(a);
216
- default:throw Error('UNSUPPORTED_CONTEXT_OPERATION');
217
- }
103
+ // Keep the read-only Store alive through async capability completion.
104
+ // Never close the handle before a module's Promise settles.
105
+ return await capabilityRouter.execute(method,a,{db,projectRef:a.projectId});
218
106
  }finally{db.close()}
219
107
  }
@@ -1,63 +1,29 @@
1
1
  // Restricted LOCAL OPERATOR path for orphaned Managed Run writer fencing.
2
2
  // Not reachable through public Context MCP, and never asserts Task DONE.
3
- import {execFileSync} from 'node:child_process';
4
3
  import {createHash,randomUUID} from 'node:crypto';
5
4
  import {DatabaseSync,backup} from 'node:sqlite';
6
5
  import {chmodSync,existsSync,lstatSync,mkdirSync,readFileSync,writeFileSync} from 'node:fs';
7
6
  import {homedir} from 'node:os';
7
+ import {verifyOrphanOwnerIdle} from '@tomflow/chatloop-extension';
8
8
  import {join} from 'node:path';
9
- import {openContextProtocol} from './context-protocol.mjs';
10
- import {contextRoot,allowedProjects} from './operations.mjs';
11
- import {confirmWorkspaceOperator} from './workspace-operator.mjs';
9
+ // This module declares ports; index.mjs is the only dependency assembler.
10
+ // No implementation module imports another implementation module.
11
+ let openContextProtocol, contextRoot, allowedProjects, confirmWorkspaceOperator;
12
+ let connected=false;
13
+ export function configureOrphanOperator(capabilities){
14
+ if(connected)throw Error('CONTEXT_MODULE_ALREADY_COMPOSED');
15
+ for(const name of ['openContextProtocol', 'contextRoot', 'allowedProjects', 'confirmWorkspaceOperator']){
16
+ if(capabilities?.[name]===undefined)throw Error('CONTEXT_MODULE_PORT_MISSING:'+name);
17
+ }
18
+ ({openContextProtocol, contextRoot, allowedProjects, confirmWorkspaceOperator}=capabilities);
19
+ connected=true;
20
+ }
12
21
 
13
22
  const fail=code=>Object.assign(Error(code),{code});
14
23
  const assert=(ok,code)=>{if(!ok)throw fail(code)};
15
24
  const SHA=/^[0-9a-f]{64}$/;
16
25
  const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
17
26
  const sha=buf=>createHash('sha256').update(buf).digest('hex');
18
- const nativePath=()=>join(homedir(),'.chat-loop','session','active-session.json');
19
- const readTrustedNative=()=>{
20
- const file=nativePath(),stat=lstatSync(file);
21
- assert(stat.isFile()&&!stat.isSymbolicLink()
22
- &&!(stat.mode&0o077)&&(!process.getuid||stat.uid===process.getuid()),
23
- 'NATIVE_POINTER_UNTRUSTED');
24
- const raw=readFileSync(file);
25
- const x=JSON.parse(raw.toString('utf8'));
26
- assert(x?.phase==='DONE'&&typeof x.sessionId==='string'
27
- &&typeof x.projectId==='string'&&Number.isSafeInteger(x.updatedAt),
28
- 'NATIVE_NOT_TERMINAL');
29
- return {sessionId:x.sessionId,projectId:x.projectId,taskId:x.taskId||null,
30
- phase:x.phase,updatedAt:x.updatedAt,rawHash:sha(raw)};
31
- };
32
- const readExtensionIdle=()=>{
33
- const cli=join(homedir(),'.chat-loop','extension','npm','node_modules',
34
- '@tomflow','chatloop-extension','bin','cli.mjs');
35
- const st=lstatSync(cli);
36
- assert(st.isFile()&&!st.isSymbolicLink(),'EXTENSION_CLI_UNTRUSTED');
37
- const out=execFileSync(process.execPath,[cli,'extension','status'],{
38
- encoding:'utf8',timeout:14000,maxBuffer:524288,stdio:['ignore','pipe','pipe']});
39
- const rows=out.trim().split('\n').map(s=>JSON.parse(s));
40
- const result=rows.findLast(x=>x.event==='RESULT');
41
- assert(result?.ok===true&&result.value?.verified===true
42
- &&result.value?.truncated===false,'EXTENSION_STATUS_UNVERIFIED');
43
- const v=JSON.parse(result.value.content||'{}');
44
- assert(v.status==='OK'&&v.state==='IDLE'
45
- &&v.lastSession?.phase==='DONE','EXTENSION_OWNER_NOT_IDLE');
46
- return v;
47
- };
48
- const verifyExternal=(oldRunRef,projectId)=>{
49
- const native=readTrustedNative(),extension=readExtensionIdle();
50
- const oldId=oldRunRef.split(':')[0];
51
- assert(native.sessionId!==oldId&&native.projectId!==projectId,
52
- 'ORPHAN_OWNER_STILL_CURRENT');
53
- assert(extension.lastSession.sessionId===native.sessionId
54
- &&extension.lastSession.projectId===native.projectId
55
- &&extension.lastSession.updatedAt===native.updatedAt
56
- &&extension.lastSession.activeChatId===JSON.parse(
57
- readFileSync(nativePath(),'utf8')).activeChatId,
58
- 'EXTENSION_NATIVE_POINTER_MISMATCH');
59
- return native;
60
- };
61
27
 
62
28
  export async function fenceOrphanRunOperator({
63
29
  projectId,taskId,expectedRunRef,expectedTaskRevision,
@@ -79,7 +45,7 @@ export async function fenceOrphanRunOperator({
79
45
  const oldSessionId=expectedRunRef.split(':')[0];
80
46
  assert(/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(oldSessionId)
81
47
  &&expectedRunRef===oldSessionId+':'+taskId+':0','ORPHAN_RUN_REF_INVALID');
82
- const before=verifyExternal(expectedRunRef,projectId);
48
+ const before=verifyOrphanOwnerIdle({oldRunRef:expectedRunRef,projectId});
83
49
  const file=join(contextRoot(),projectId,'context.sqlite');
84
50
  const reader=openContextProtocol(file,{readOnly:true,principalId:'local-operator',
85
51
  authorizeData:(_mode,p)=>p===projectId});
@@ -99,7 +65,7 @@ export async function fenceOrphanRunOperator({
99
65
  // platform-authenticated human R/P approval or an execution permission.
100
66
  await confirmWorkspaceOperator('FENCE_ORPHAN',projectId,expectedTaskRevision,
101
67
  [taskId,expectedRunRef,evidenceDocumentId,evidenceHash,before.sessionId]);
102
- const after=verifyExternal(expectedRunRef,projectId);
68
+ const after=verifyOrphanOwnerIdle({oldRunRef:expectedRunRef,projectId});
103
69
  assert(JSON.stringify(after)===JSON.stringify(before),
104
70
  'NATIVE_CHANGED_DURING_REVIEW');
105
71
  const archiveRoot=join(homedir(),'.chat-loop','backups');
@@ -120,14 +86,14 @@ export async function fenceOrphanRunOperator({
120
86
  result:'PENDING',createdAt:new Date().toISOString()};
121
87
  const manifest=join(archive,'manifest.json');
122
88
  writeFileSync(manifest,JSON.stringify(record,null,2)+'\n',{mode:0o600,flag:'wx'});
123
- const last=verifyExternal(expectedRunRef,projectId);
89
+ const last=verifyOrphanOwnerIdle({oldRunRef:expectedRunRef,projectId});
124
90
  assert(JSON.stringify(last)===JSON.stringify(before),
125
91
  'NATIVE_CHANGED_BEFORE_FENCE');
126
92
  const db=openContextProtocol(file,{principalId:'local-operator',
127
93
  authorizeData:(_mode,p)=>p===projectId,
128
94
  authorizeAdmin:(op,p)=>p===projectId&&
129
95
  ['run.orphan.fence','run.orphan.fence.reviewed'].includes(op)
130
- &&JSON.stringify(readTrustedNative())===JSON.stringify(before)});
96
+ &&JSON.stringify(verifyOrphanOwnerIdle({oldRunRef:expectedRunRef,projectId}))===JSON.stringify(before)});
131
97
  let result;
132
98
  try{
133
99
  result=db.fenceOrphan({projectId,taskId,oldSessionId,