@tomflow/chatloop-tools 0.9.15 → 0.9.17

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 (148) hide show
  1. package/README.md +2 -1
  2. package/index.mjs +12 -1
  3. package/lib/gateway.mjs +15 -3
  4. package/lib/mcp-tool-router.mjs +50 -3
  5. package/lib/trace-observation.mjs +19 -0
  6. package/node_modules/@tomflow/chatloop-context/README.md +240 -0
  7. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
  8. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
  9. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
  10. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +266 -0
  11. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
  12. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
  13. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
  14. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
  15. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
  16. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
  17. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
  18. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +182 -0
  19. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
  20. package/node_modules/@tomflow/chatloop-context/index.mjs +233 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
  22. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +24 -0
  23. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +1989 -0
  24. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +67 -0
  25. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +280 -0
  26. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
  27. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +280 -0
  28. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +115 -0
  29. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
  30. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +55 -0
  31. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
  32. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
  33. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +147 -0
  34. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +343 -0
  35. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +391 -0
  36. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +166 -0
  37. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
  38. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
  39. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
  40. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +117 -0
  41. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
  42. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +312 -0
  43. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
  44. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
  45. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +115 -0
  46. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +86 -0
  47. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
  48. package/node_modules/@tomflow/chatloop-context/package.json +40 -0
  49. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
  50. package/node_modules/@tomflow/chatloop-extension/README.md +94 -0
  51. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +11 -0
  52. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +141 -0
  53. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +109 -0
  54. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
  55. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
  56. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
  57. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
  58. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
  59. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
  61. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
  62. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +120 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +180 -0
  65. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +322 -0
  66. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
  67. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +378 -0
  68. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
  69. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +54 -0
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +69 -0
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +287 -0
  74. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +23 -0
  75. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
  76. package/node_modules/@tomflow/chatloop-extension/extension/background.js +16 -0
  77. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
  78. package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
  79. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
  80. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
  81. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
  82. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
  83. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
  84. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +76 -0
  85. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
  86. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
  87. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +227 -0
  88. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
  89. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +171 -0
  90. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
  91. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +154 -0
  92. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +254 -0
  93. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +42 -0
  94. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
  95. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +93 -0
  96. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
  97. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
  98. package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
  99. package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
  100. package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
  101. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
  102. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +220 -0
  103. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +122 -0
  104. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +155 -0
  105. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +185 -0
  106. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +120 -0
  107. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +172 -0
  108. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +165 -0
  109. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +244 -0
  110. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +181 -0
  111. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +147 -0
  112. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
  113. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +200 -0
  114. package/node_modules/@tomflow/chatloop-extension/index.mjs +71 -0
  115. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +18 -0
  116. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +74 -0
  117. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +208 -0
  118. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +40 -0
  119. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
  120. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +111 -0
  121. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +67 -0
  122. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +120 -0
  123. package/node_modules/@tomflow/chatloop-extension/package.json +38 -0
  124. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +133 -0
  125. package/node_modules/@tomflow/chatloop-trace/README.md +105 -0
  126. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
  127. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
  128. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
  129. package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
  130. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
  131. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +265 -0
  132. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +205 -0
  133. package/node_modules/@tomflow/chatloop-trace/package.json +30 -0
  134. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
  135. package/node_modules/ps-list/index.d.ts +76 -0
  136. package/node_modules/ps-list/index.js +366 -0
  137. package/node_modules/ps-list/license +9 -0
  138. package/node_modules/ps-list/package.json +44 -0
  139. package/node_modules/ps-list/readme.md +56 -0
  140. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  141. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
  142. package/package.json +23 -8
  143. package/providers/form.mjs +286 -0
  144. package/providers.generated.mjs +3 -2
  145. package/scripts/build-form-app.mjs +27 -0
  146. package/ui/form/review-app.js +128 -0
  147. package/ui/form/review.html +859 -0
  148. package/ui/form/review.template.html +45 -0
@@ -0,0 +1,111 @@
1
+ // Context public API metadata, assembled from the generated capability catalog.
2
+ // No new operation requires editing this registry or adding a switch branch.
3
+ import {readFileSync} from 'node:fs';
4
+ export const CONTEXT_PACKAGE_VERSION=JSON.parse(readFileSync(new URL('../package.json',import.meta.url),'utf8')).version;
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');
14
+ const ID='^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$';
15
+ const scopeError=code=>Object.assign(new Error(code),{code});
16
+ // A grant is an atomic permission statement, not a bag of best-effort tokens.
17
+ // Do not silently drop malformed entries or normalize duplicate grants.
18
+ // Reused by the SDK CLI, Context Core, MCP Gateway, and Native binding.
19
+ export function parseContextAllowedProjects(raw){
20
+ if(typeof raw!=='string'||raw.trim()==='')
21
+ throw scopeError('CONTEXT_ALLOWED_PROJECTS_REQUIRED');
22
+ const entries=raw.split(',').map(x=>x.trim());
23
+ if(entries.some(x=>!new RegExp(ID).test(x))||
24
+ new Set(entries).size!==entries.length)
25
+ throw scopeError('CONTEXT_PROJECT_SCOPE_INVALID');
26
+ return new Set(entries);
27
+ }
28
+
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}))};
46
+ }
47
+ export function describeMethod(methodId){
48
+ const m=methodById.get(methodId);
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,
52
+ description:m.description,inputSchema:m.inputSchema,
53
+ lifecycle:m.lifecycle??{surface:'public'},
54
+ outputContract:'JSON value, immutable hashes and explicit revision/authority where applicable',
55
+ errorContract:'typed error code; unknown write outcome requires original requestId receipt lookup'};
56
+ }
57
+ export const contextGatewayTools=[
58
+ {name:'chat_loop_context_get',
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.',
60
+ inputSchema:{oneOf:methodDefinitions.filter(m=>m.mode==='read').map(m=>m.inputSchema)},
61
+ annotations:{readOnlyHint:true}},
62
+ {name:'chat_loop_context_mutate',
63
+ description:'Context SDK WRITE. First inspect current version and method Schema; use expectedStoreEpoch, revisions and unique writeRequestId. No internal Native run controls.',
64
+ inputSchema:{oneOf:methodDefinitions.filter(m=>m.mode==='write').map(m=>m.inputSchema)},
65
+ annotations:{readOnlyHint:false}}
66
+ ];
67
+ export function validateContextCall(name,args){
68
+ const mode=name==='chat_loop_context_get'?'read':
69
+ name==='chat_loop_context_mutate'?'write':null;
70
+ if(!mode)throw failure('UNKNOWN_TOOL');
71
+ if(!args||typeof args!=='object'||Array.isArray(args))
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');
83
+ }
84
+ return method;
85
+ }
86
+ // Validate nested and top-level inputs from the *same* schema exposed to MCP.
87
+ // Open-ended domain objects (patch/context/evidence) remain validated by Core.
88
+ function matchesSchema(value,spec){
89
+ if(spec.const!==undefined&&value!==spec.const)return false;
90
+ if(spec.enum&&!spec.enum.includes(value))return false;
91
+ if(spec.type==='string')
92
+ return typeof value==='string'&&value.length>=(spec.minLength??0)
93
+ &&value.length<=(spec.maxLength??Infinity)
94
+ &&(!spec.pattern||new RegExp(spec.pattern).test(value));
95
+ if(spec.type==='integer')
96
+ return Number.isSafeInteger(value)&&(spec.minimum===undefined||value>=spec.minimum)
97
+ &&(spec.maximum===undefined||value<=spec.maximum);
98
+ if(spec.type==='array')
99
+ return Array.isArray(value)&&value.length>=(spec.minItems??0)
100
+ &&value.length<=(spec.maxItems??Infinity)
101
+ &&value.every(x=>!spec.items||matchesSchema(x,spec.items));
102
+ if(spec.type==='object'){
103
+ if(!value||typeof value!=='object'||Array.isArray(value))return false;
104
+ if(spec.required?.some(k=>!Object.hasOwn(value,k)))return false;
105
+ if(spec.additionalProperties===false&&Object.keys(value).some(k=>!Object.hasOwn(spec.properties??{},k)))
106
+ return false;
107
+ return Object.entries(spec.properties??{}).every(([key,child])=>
108
+ !Object.hasOwn(value,key)||matchesSchema(value[key],child));
109
+ }
110
+ return true;
111
+ }
@@ -0,0 +1,107 @@
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);
10
+ }
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;
15
+ }
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);
25
+ if(method.id==='sdk.methods.describe')return describeMethod(args.methodId);
26
+ const allowed=allowedProjects();
27
+ if(!allowed.size)throw fail('CONTEXT_ALLOWED_PROJECTS_REQUIRED');
28
+ if(methodId==='project.resolve')return resolveProjects(args,allowed);
29
+ if(methodId==='project.list'){
30
+ if(!process.env.CHAT_LOOP_CONTEXT_DB){
31
+ const publicProject=meta=>({
32
+ projectId:meta.projectId,title:meta.title,
33
+ projectRevision:meta.projectRevision,sharedContext:meta.sharedContext,
34
+ archived:meta.archived
35
+ });
36
+ const limit=args.limit??30,cursor=args.cursor??null;
37
+ if(cursor!==null&&(!allowed.has(cursor)||!projectMeta(cursor)))
38
+ throw fail('PROJECT_CURSOR_INVALID');
39
+ const entries=[];
40
+ for(const id of [...allowed].sort()){
41
+ if(cursor!==null&&id<=cursor)continue;
42
+ const meta=projectMeta(id);
43
+ if(!meta)continue;
44
+ entries.push(publicProject(meta));
45
+ if(entries.length>limit)break;
46
+ }
47
+ const incomplete=entries.length>limit,projects=entries.slice(0,limit);
48
+ return {projects,incomplete,nextCursor:incomplete?projects.at(-1).projectId:null,limit};
49
+ }
50
+ const db=openContextProtocol(process.env.CHAT_LOOP_CONTEXT_DB,{
51
+ readOnly:true,principalId:'private-mcp',
52
+ authorizeData:(_type,projectId)=>allowed.has(projectId),
53
+ authorizeInternal:()=>false});
54
+ try{return db.projectList({limit:args.limit??30,cursor:args.cursor})}finally{db.close()}
55
+ }
56
+ if(args.projectId!==undefined&&!allowed.has(args.projectId))throw fail('PROJECT_ACCESS_DENIED');
57
+ if(!args.projectId)throw fail('PROJECT_ID_REQUIRED');
58
+ return executeDb(args,allowed,method.mode,method);
59
+ }
60
+ export async function dispatchContextCall(name,args){
61
+ const method=validateContextCall(name,args);
62
+ if(method.mode==='read')return runContextOperation(args,method);
63
+ const allowed=allowedProjects();
64
+ if(!allowed.size)throw fail('CONTEXT_ALLOWED_PROJECTS_REQUIRED');
65
+ if(!allowed.has(args.projectId))throw fail('PROJECT_ACCESS_DENIED');
66
+ // A model-authorized business patch is NOT permission to bind a new workspace.
67
+ // Keep binding violations distinct even when generic project creation is disabled.
68
+ if(method.id==='project.patch' && Object.hasOwn(args.sharedContext,'workspaceRefs'))
69
+ throw fail('WORKSPACE_REBIND_REQUIRES_OPERATOR');
70
+ return executeDb(args,allowed,method.mode,method);
71
+ }
72
+ async function executeDb(a,allowed,mode,method){
73
+ if(Number(process.versions.node.split('.')[0])<24)throw fail('CONTEXT_RUNTIME_UNSUPPORTED');
74
+ // A read or ordinary write must never create a project directory or SQLite.
75
+ // Only explicit operator project init may create a previously absent Store.
76
+ const file=projectDatabase(a.projectId);
77
+ verifiedStoreFile(file,'STORE_MISSING');
78
+ // project.list/resolve already verify this; ordinary get/mutate must too.
79
+ // Read-only identity check precedes any writable SQLite open and rules out
80
+ // a copied/renamed or multi-Project database under the wrong directory.
81
+ if(!process.env.CHAT_LOOP_CONTEXT_DB)projectMeta(a.projectId);
82
+ const db=openContextProtocol(file,{
83
+ readOnly:mode==='read',
84
+ principalId:'private-mcp',authorizeData:(_type,projectId)=>allowed.has(projectId),
85
+ authorizeInternal:()=>false
86
+ });
87
+ try{
88
+ if(mode==='write'){
89
+ if(!db.projectBusinessAuthority(a.projectId).writable)
90
+ throw fail('PROJECT_CUTOVER_NOT_VERIFIED');
91
+ }
92
+ if(a.operation==='project.open'){
93
+ const {project,authority,tasks,taskCount,storeEpoch}=db.projectSnapshot(a.projectId);
94
+ return {contractVersion:CONTEXT_CONTRACT,project,authority,storeEpoch,
95
+ taskCount,tasks,incomplete:taskCount>tasks.length,
96
+ nextOperation:taskCount>tasks.length?'task.list':null};
97
+ }
98
+ if(a.operation==='task.open'){
99
+ const {project,authority,task,storeEpoch}=db.projectSnapshot(a.projectId,a.taskId);
100
+ return {contractVersion:CONTEXT_CONTRACT,task,storeEpoch,
101
+ projectRevision:project.projectRevision,authority};
102
+ }
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});
106
+ }finally{db.close()}
107
+ }
@@ -0,0 +1,117 @@
1
+ // Restricted LOCAL OPERATOR path for orphaned Managed Run writer fencing.
2
+ // Not reachable through public Context MCP, and never asserts Task DONE.
3
+ import {createHash,randomUUID} from 'node:crypto';
4
+ import {DatabaseSync,backup} from 'node:sqlite';
5
+ import {chmodSync,existsSync,lstatSync,mkdirSync,readFileSync,writeFileSync} from 'node:fs';
6
+ import {homedir} from 'node:os';
7
+ import {verifyOrphanOwnerIdle} from '@tomflow/chatloop-extension';
8
+ import {join} from 'node:path';
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
+ }
21
+
22
+ const fail=code=>Object.assign(Error(code),{code});
23
+ const assert=(ok,code)=>{if(!ok)throw fail(code)};
24
+ const SHA=/^[0-9a-f]{64}$/;
25
+ const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
26
+ const sha=buf=>createHash('sha256').update(buf).digest('hex');
27
+
28
+ export async function fenceOrphanRunOperator({
29
+ projectId,taskId,expectedRunRef,expectedTaskRevision,
30
+ expectedBindingRevision,expectedStoreEpoch,evidenceDocumentId,
31
+ evidenceVersion,evidenceHash,writeRequestId
32
+ }){
33
+ assert(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE==='1','ADMIN_REQUIRED');
34
+ assert(!process.env.CHAT_LOOP_CONTEXT_DB,'EXPLICIT_DB_INIT_REQUIRED');
35
+ assert(ID.test(projectId||'')&&ID.test(taskId||'')
36
+ &&allowedProjects().has(projectId),'PROJECT_ACCESS_DENIED');
37
+ assert(Number.isSafeInteger(expectedTaskRevision)&&expectedTaskRevision>=1
38
+ &&Number.isSafeInteger(expectedBindingRevision)&&expectedBindingRevision>=1
39
+ &&typeof expectedStoreEpoch==='string'&&expectedStoreEpoch.length>=10
40
+ &&typeof expectedRunRef==='string'&&expectedRunRef.length>=12
41
+ &&ID.test(evidenceDocumentId||'')&&Number.isSafeInteger(evidenceVersion)
42
+ &&evidenceVersion>0&&SHA.test(evidenceHash||'')
43
+ &&typeof writeRequestId==='string'&&writeRequestId.length>=8
44
+ &&writeRequestId.length<=128,'ORPHAN_ARGUMENT_INVALID');
45
+ const oldSessionId=expectedRunRef.split(':')[0];
46
+ assert(/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(oldSessionId)
47
+ &&expectedRunRef===oldSessionId+':'+taskId+':0','ORPHAN_RUN_REF_INVALID');
48
+ const before=verifyOrphanOwnerIdle({oldRunRef:expectedRunRef,projectId});
49
+ const file=join(contextRoot(),projectId,'context.sqlite');
50
+ const reader=openContextProtocol(file,{readOnly:true,principalId:'local-operator',
51
+ authorizeData:(_mode,p)=>p===projectId});
52
+ try{
53
+ assert(reader.epoch===expectedStoreEpoch,'STALE_EPOCH');
54
+ assert(reader.projectBusinessAuthority(projectId).writable,
55
+ 'PROJECT_CUTOVER_NOT_VERIFIED');
56
+ const task=reader.get(projectId,taskId);
57
+ assert(task.taskRevision===expectedTaskRevision
58
+ &&task.bindingRevision===expectedBindingRevision
59
+ &&task.runRef===expectedRunRef,'ORPHAN_CAS_STALE');
60
+ const evidence=reader.documentGet(projectId,taskId,evidenceDocumentId,evidenceVersion);
61
+ assert(evidence.kind==='REFERENCE'&&evidence.contentHash===evidenceHash
62
+ &&evidence.body.includes(expectedRunRef),'ORPHAN_EVIDENCE_UNVERIFIED');
63
+ }finally{reader.close()}
64
+ // Local operator approval is explicitly USER_DELEGATED_AGENT, not a
65
+ // platform-authenticated human R/P approval or an execution permission.
66
+ await confirmWorkspaceOperator('FENCE_ORPHAN',projectId,expectedTaskRevision,
67
+ [taskId,expectedRunRef,evidenceDocumentId,evidenceHash,before.sessionId]);
68
+ const after=verifyOrphanOwnerIdle({oldRunRef:expectedRunRef,projectId});
69
+ assert(JSON.stringify(after)===JSON.stringify(before),
70
+ 'NATIVE_CHANGED_DURING_REVIEW');
71
+ const archiveRoot=join(homedir(),'.chat-loop','backups');
72
+ const archive=join(archiveRoot,'orphan-fence-'+projectId+'-'+taskId+'-'+
73
+ expectedTaskRevision);
74
+ assert(!existsSync(archive),'ORPHAN_BACKUP_ALREADY_EXISTS');
75
+ mkdirSync(archive,{recursive:false,mode:0o700});
76
+ const dest=join(archive,'context-before.sqlite');
77
+ const source=new DatabaseSync(file,{readOnly:true});
78
+ try{await backup(source,dest)}finally{source.close()}
79
+ chmodSync(dest,0o600);
80
+ const backupHash=sha(readFileSync(dest));
81
+ const record={contract:'chat-loop.orphan-fence-operator.v1',
82
+ operator:'USER_DELEGATED_AGENT',projectId,taskId,oldSessionId,
83
+ expectedRunRef,expectedTaskRevision,expectedBindingRevision,
84
+ expectedStoreEpoch,evidenceDocumentId,evidenceVersion,evidenceHash,
85
+ currentNative:after,backup:dest,backupHash,
86
+ result:'PENDING',createdAt:new Date().toISOString()};
87
+ const manifest=join(archive,'manifest.json');
88
+ writeFileSync(manifest,JSON.stringify(record,null,2)+'\n',{mode:0o600,flag:'wx'});
89
+ const last=verifyOrphanOwnerIdle({oldRunRef:expectedRunRef,projectId});
90
+ assert(JSON.stringify(last)===JSON.stringify(before),
91
+ 'NATIVE_CHANGED_BEFORE_FENCE');
92
+ const db=openContextProtocol(file,{principalId:'local-operator',
93
+ authorizeData:(_mode,p)=>p===projectId,
94
+ authorizeAdmin:(op,p)=>p===projectId&&
95
+ ['run.orphan.fence','run.orphan.fence.reviewed'].includes(op)
96
+ &&JSON.stringify(verifyOrphanOwnerIdle({oldRunRef:expectedRunRef,projectId}))===JSON.stringify(before)});
97
+ let result;
98
+ try{
99
+ result=db.fenceOrphan({projectId,taskId,oldSessionId,
100
+ expectedRunRef,expectedTaskRevision,expectedBindingRevision,
101
+ expectedStoreEpoch,evidenceDocumentId,evidenceVersion,evidenceHash,
102
+ nativeSessionId:last.sessionId,nativeProjectId:last.projectId,
103
+ nativePhase:last.phase,nativeUpdatedAt:last.updatedAt,writeRequestId});
104
+ const checked=db.get(projectId,taskId);
105
+ assert(checked.runRef===null
106
+ &&checked.bindingRevision===result.bindingRevision
107
+ &&checked.currentContext.executionOutcome!=='DONE',
108
+ 'ORPHAN_FENCE_RECEIPT_UNVERIFIED');
109
+ }finally{db.close()}
110
+ // Record final durable result without updating or replaying the receipt.
111
+ record.result=result;
112
+ const completion=join(archive,'completed.json');
113
+ writeFileSync(completion,JSON.stringify(record,null,2)+'\n',
114
+ {mode:0o600,flag:'wx'});
115
+ return {...result,backupManifest:manifest,completionReceipt:completion,
116
+ backupHash,operator:'USER_DELEGATED_AGENT'};
117
+ }
@@ -0,0 +1,20 @@
1
+ // Explicit ps-list dependency. This is a bounded observation, NOT a stop receipt.
2
+ import psList from 'ps-list';
3
+ const fail=code=>Object.assign(new Error(code),{code});
4
+ // Process observation uses the declared ps-list provider, not /bin/ps.
5
+ // Never treat a momentary empty snapshot as proof of all future writers.
6
+ export async function activeLegacyWriters(){
7
+ if(process.platform==='win32')throw fail('PROCESS_COMMAND_UNAVAILABLE');
8
+ let processes;
9
+ try{processes=await psList({all:false})}
10
+ catch{throw fail('PROCESS_INVENTORY_UNAVAILABLE')}
11
+ if(!Array.isArray(processes))throw fail('PROCESS_INVENTORY_UNAVAILABLE');
12
+ return processes.filter(p=>Number.isSafeInteger(p.pid)&&p.pid>1
13
+ &&p.pid!==process.pid&&typeof p.cmd==='string'
14
+ &&(/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(p.cmd)))
15
+ .slice(0,20).map(p=>p.pid);
16
+ }
17
+
18
+ // Internal seam for isolated fixture tests. Not part of npm entrypoints or
19
+ // the migration arguments; callers cannot provide a fake writer predicate.
20
+ export const knownWriterInventory={scan:activeLegacyWriters};