@tomflow/chatloop-tools 0.4.19 → 0.4.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/README.md +89 -3
  2. package/bin/cli.mjs +27 -6
  3. package/lib/context-cli.mjs +2 -0
  4. package/lib/context-control-auth.mjs +40 -0
  5. package/lib/context-control-run.mjs +117 -0
  6. package/lib/context-gateway.mjs +97 -0
  7. package/lib/context-migration.mjs +2 -0
  8. package/lib/context-protocol.mjs +2 -0
  9. package/lib/extension-contract.mjs +16 -0
  10. package/lib/extension-proxy.mjs +11 -2
  11. package/lib/gateway.mjs +89 -4
  12. package/lib/release.mjs +174 -5
  13. package/lib/supervisor.mjs +78 -3
  14. package/lib/task-registry-managed.mjs +38 -0
  15. package/lib/task-registry.mjs +221 -0
  16. package/lib/trace-gateway.mjs +99 -0
  17. package/node_modules/@tomflow/chatloop-context/README.md +204 -0
  18. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +236 -0
  19. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +301 -0
  20. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +272 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/context-protocol.mjs +1595 -0
  22. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +264 -0
  23. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +219 -0
  24. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +289 -0
  25. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +159 -0
  26. package/node_modules/@tomflow/chatloop-context/package.json +21 -0
  27. package/node_modules/@tomflow/chatloop-trace/README.md +13 -0
  28. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +259 -0
  29. package/node_modules/@tomflow/chatloop-trace/package.json +11 -0
  30. package/package.json +9 -3
package/lib/gateway.mjs CHANGED
@@ -4,9 +4,40 @@ import {readFileSync} from 'node:fs';
4
4
  import {CONTRACT,PACKAGE_VERSION,registry,talk,toolCallDeadlineMs} from './control.mjs';
5
5
  import {extensionTools,forwardExtensionAction} from './extension-proxy.mjs';
6
6
  import {probeTool,handleProbeForm} from './approval-form-probe.mjs';
7
+ import {taskRegistryTool,runTaskRegistry} from './task-registry.mjs';
8
+ import {managedTaskRegistry} from './task-registry-managed.mjs';
9
+ import {contextGatewayTools,contextGatewayEnabled,runContextGateway} from './context-gateway.mjs';
7
10
  import {runtimeNeedsUpgrade} from './release.mjs';
11
+ import {traceDiagnoseTool,traceGatewayEnabled,runTraceDiagnose,observeExtensionResult} from './trace-gateway.mjs';
8
12
 
9
- const desktopTools=JSON.parse(readFileSync(new URL('./desktop-commander-tools.json',import.meta.url),'utf8'));
13
+ // Keep the pinned Desktop Commander as the implementation, but expose only
14
+ // the file/search/process API useful to Chat Loop. Hidden tools are NOT routable
15
+ // by tools/call either; runtime/admin/onboarding controls are not agent tools.
16
+ const hiddenDesktopTools=new Set([
17
+ 'set_config_value','get_usage_stats','get_recent_tool_calls',
18
+ 'give_feedback_to_desktop_commander','get_prompts'
19
+ ]);
20
+ // The vendor descriptions contain long onboarding instructions and even
21
+ // directives to start unnecessary REPLs. Keep the exact vendor inputSchema,
22
+ // but describe the supported API succinctly at this single MCP boundary.
23
+ const desktopDescriptions={
24
+ read_file:'Read a file or URL (text, images, PDF, DOCX, spreadsheets). Use absolute path and optional offset/length to limit output; respect allowed directories.',
25
+ read_multiple_files:'Read several authorized absolute file paths in one request. Returns each result with its source path.',
26
+ write_file:'Create/replace or append to a file. mode is rewrite or append; prefer small chunks. Check the existing file and user authorization before overwriting.',
27
+ write_pdf:'Create or modify a PDF with markdown/operations. Use a new outputPath for modifications; never silently overwrite the original.',
28
+ list_directory:'List files and folders under an authorized absolute path; depth limits recursion and output.',
29
+ start_search:'Search filenames (searchType=files) or file contents (searchType=content) from an authorized root. Returns a session for paginated results.',
30
+ get_more_search_results:'Get additional results from an existing search session using sessionId and pagination.',
31
+ edit_block:'Apply an exact targeted edit; pass file_path and old_string/new_string for text, or range/content for spreadsheets. Refuse ambiguous replacements.',
32
+ start_process:'Run an authorized local command once. A returned PID means still running, not successful; read the same process output instead of restarting.',
33
+ read_process_output:'Read output of an already-started PID with optional offset/length/timeout_ms. Does not start the command again.',
34
+ interact_with_process:'Send input to an existing interactive PID and obtain output. Do not repeat commands with unknown side effects.',
35
+ get_config:'Read Desktop Commander configuration/allowed directories for diagnosis; does not grant or change permissions.'
36
+ };
37
+ const desktopTools=JSON.parse(readFileSync(
38
+ new URL('./desktop-commander-tools.json',import.meta.url),'utf8'))
39
+ .filter(t=>!hiddenDesktopTools.has(t.name))
40
+ .map(t=>({...t,description:desktopDescriptions[t.name]||t.description.trim()}));
10
41
  const fixtureTool={name:'ping',description:'Inert lifecycle test health check',
11
42
  inputSchema:{type:'object',properties:{},additionalProperties:false}};
12
43
  const toolsFor=t=>t.kind==='mcp-child'?desktopTools:t.kind==='fixture'?[fixtureTool]:[];
@@ -28,7 +59,10 @@ const published=()=>[
28
59
  toolsFor(t).map(({_meta,...x})=>({...x,name:prefix(t.id)+x.name}))),
29
60
  ...(extEnabled()?extensionTools.map(t=>({...t,name:'chat_loop_extension__'+t.name})):[]),
30
61
  ...(formProbeEnabled()?[probeTool]:[]),
31
- receiptTool
62
+ receiptTool,
63
+ taskRegistryTool,
64
+ ...(contextGatewayEnabled()?contextGatewayTools:[]),
65
+ ...(traceGatewayEnabled()?[traceDiagnoseTool]:[])
32
66
  ];
33
67
  function resolveTool(name){
34
68
  if(extEnabled()&&typeof name==='string'&&name.startsWith('chat_loop_extension__')){
@@ -70,6 +104,54 @@ export function runGateway(){
70
104
  if(m.method==='ping')return reply(m.id,{});
71
105
  if(m.method==='tools/list')return reply(m.id,{tools:published()});
72
106
  if(m.method==='tools/call'){
107
+ if(traceGatewayEnabled()&&m.params?.name===traceDiagnoseTool.name){
108
+ try{
109
+ const result=await runTraceDiagnose(m.params.arguments);
110
+ return reply(m.id,{content:[{type:'text',text:JSON.stringify(result)}]});
111
+ }catch(e){return reply(m.id,failure(e.code||'TRACE_DIAGNOSE_FAILED'))}
112
+ }
113
+ if(m.params?.name===taskRegistryTool.name){
114
+ try{
115
+ // Opting into managed Context must never silently revive JSON
116
+ // Registry writes when its SDK, Node runtime or binding is absent.
117
+ if(process.env.CHAT_LOOP_CONTEXT_API_ENABLE==='1'&&!contextGatewayEnabled())
118
+ throw Error('CONTEXT_GATEWAY_UNAVAILABLE');
119
+ let value;
120
+ // Authority is the durable SourceUnit migration record, never a
121
+ // process-local env flag that could go stale after cutover.
122
+ if(contextGatewayEnabled()){
123
+ const args=m.params.arguments||{},projectId=args.projectId;
124
+ const authority=await runContextGateway('chat_loop_context_get',{
125
+ operation:'project.registryAuthority',projectId});
126
+ if(authority==='RESTORED_DIAGNOSTIC')
127
+ throw Error('REGISTRY_RESTORE_READ_ONLY');
128
+ if(authority==='CUTOVER_FENCED')
129
+ throw Error('REGISTRY_CUTOVER_FENCED');
130
+ if(!['LEGACY_RW','MANAGED_RW'].includes(authority))
131
+ throw Error('REGISTRY_AUTHORITY_UNKNOWN');
132
+ if(authority==='MANAGED_RW'){
133
+ // The legacy registry is a read-only projection through the
134
+ // independent Context SDK, not a second SQLite client.
135
+ if(args.action==='list'){
136
+ const tasks=await runContextGateway('chat_loop_context_get',{
137
+ operation:'task.list',projectId});
138
+ value=managedTaskRegistry({taskList:()=>tasks},args);
139
+ }else if(args.action==='get'){
140
+ const task=await runContextGateway('chat_loop_context_get',{
141
+ operation:'task.get',projectId,taskId:args.taskId});
142
+ value=managedTaskRegistry({get:()=>task},args);
143
+ }else throw Error('REGISTRY_MANAGED_USE_CONTEXT_MUTATE');
144
+ }else value=runTaskRegistry(args);
145
+ }else value=runTaskRegistry(m.params.arguments);
146
+ return reply(m.id,{content:[{type:'text',text:JSON.stringify(value)}]});
147
+ }catch(e){return reply(m.id,failure(e.code||e.message||'TASK_REGISTRY_FAILED'));}
148
+ }
149
+ if(contextGatewayEnabled()&&contextGatewayTools.some(t=>t.name===m.params?.name)){
150
+ try{
151
+ const value=await runContextGateway(m.params.name,m.params.arguments);
152
+ return reply(m.id,{content:[{type:'text',text:JSON.stringify(value)}]});
153
+ }catch(e){return reply(m.id,failure(e.code||e.message||'CONTEXT_OPERATION_FAILED'));}
154
+ }
73
155
  if(formProbeEnabled() && m.params?.name===probeTool.name)
74
156
  return reply(m.id,negotiatedVersion==='2026-07-28'
75
157
  ?handleProbeForm(m.params)
@@ -94,8 +176,11 @@ export function runGateway(){
94
176
  !process.env.CHAT_LOOP_LOCAL_TOOLS_STATE_DIR&&
95
177
  !process.env.CHAT_LOOP_LOCAL_TOOLS_FIXTURES&&runtimeNeedsUpgrade())
96
178
  return reply(m.id,failure('RUNTIME_UPGRADE_REQUIRED'));
97
- if(routed.toolId==='chat-loop-extension')
98
- return reply(m.id,await forwardExtensionAction(routed.name,args));
179
+ if(routed.toolId==='chat-loop-extension'){
180
+ const result=await forwardExtensionAction(routed.name,args);
181
+ await observeExtensionResult(routed.name,args,result);
182
+ return reply(m.id,result);
183
+ }
99
184
  const deadlineMs=toolCallDeadlineMs(args),requestId=randomUUID();
100
185
  const res=await talk({contract:CONTRACT,requestId,action:'call',
101
186
  scope:'tool',toolId:routed.toolId,name:routed.name,args,deadlineMs},deadlineMs+2000);
package/lib/release.mjs CHANGED
@@ -1,14 +1,27 @@
1
1
  // Owner-verified stop-and-start upgrade. Failure is reported, never auto-rolled back.
2
2
  import {spawn} from 'node:child_process';
3
- import {randomUUID} from 'node:crypto';
4
- import {existsSync,readFileSync,writeFileSync,openSync,closeSync,unlinkSync,mkdirSync,renameSync} from 'node:fs';
5
- import {homedir} from 'node:os';
3
+ import {randomUUID,createHash} from 'node:crypto';
4
+ import {existsSync,readFileSync,writeFileSync,openSync,closeSync,unlinkSync,mkdirSync,renameSync,lstatSync,rmSync} from 'node:fs';
5
+ import {homedir,userInfo} from 'node:os';
6
6
  import {join,dirname} from 'node:path';
7
7
  import {PACKAGE_VERSION} from './control.mjs';
8
8
 
9
9
  const name='@tomflow/chatloop-tools';
10
10
  const entryIn=prefix=>join(prefix,'node_modules','@tomflow','chatloop-tools','bin','cli.mjs');
11
11
  const runtimeRoot=()=>join(homedir(),'.chat-loop');
12
+ // The local MCP/Desktop Commander process has an intentionally isolated
13
+ // HOME. It must never treat that sandbox as the user's running release root.
14
+ function checkedUpgradeBase(options){
15
+ if(options.base!==undefined)return options.base; // Explicit test/API base.
16
+ try{
17
+ const accountHome=userInfo().homedir;
18
+ if(homedir()!==accountHome)return null;
19
+ const currentState=process.env.CHAT_LOOP_LOCAL_TOOLS_STATE_DIR;
20
+ if(currentState&&currentState!==join(accountHome,'.chat-loop','local-tools'))
21
+ return null;
22
+ return join(accountHome,'.chat-loop');
23
+ }catch{return null}
24
+ }
12
25
  const readJson=path=>JSON.parse(readFileSync(path,'utf8'));
13
26
  const delay=ms=>new Promise(r=>setTimeout(r,ms));
14
27
  const safeVersion=v=>/^[0-9]+\.[0-9]+\.[0-9]+(?:-[a-zA-Z0-9.-]+)?$/.test(v);
@@ -46,7 +59,7 @@ function run(bin,args,opts={}){
46
59
  }
47
60
  async function cli(entry,action,opts={}){
48
61
  let raw;
49
- try{raw=await run(process.execPath,[entry,action],opts);}
62
+ try{raw=await run(process.execPath,[entry,...(Array.isArray(action)?action:[action])],opts);}
50
63
  catch(e){if(!e.stdout)throw e;raw=e.stdout;}
51
64
  try{return JSON.parse(raw.trim());}
52
65
  catch{throw Object.assign(Error('INVALID_CLI_REPLY'),{code:'INVALID_CLI_REPLY'});}
@@ -68,9 +81,150 @@ export function runtimeNeedsUpgrade(base=runtimeRoot(),version=PACKAGE_VERSION){
68
81
  const current=readJson(join(dirname(dirname(p.legacy)),'package.json')).version;
69
82
  return current!==version;
70
83
  }
84
+ // Explicit, offline, stage-only release preparation. Never touches the old
85
+ // Supervisor, Tunnel, runtime.json, MCP profile or any Context Store.
86
+ export async function prepareReleaseCandidate(options={}){
87
+ const base=checkedUpgradeBase(options);
88
+ if(!base)return freshResult('BLOCKED',{code:'RUNTIME_HOME_MISMATCH'});
89
+ const p=upgradeLayout(base,options.version||PACKAGE_VERSION);
90
+ const tarball=options.tarball;
91
+ const expectedSha256=options.sha256;
92
+ if(typeof tarball!=='string'||!tarball.startsWith('/')||
93
+ !tarball.endsWith('.tgz')||!/^[a-f0-9]{64}$/.test(expectedSha256||''))
94
+ return freshResult('BLOCKED',{code:'INVALID_RELEASE_ARTIFACT'});
95
+ let input;
96
+ try{
97
+ const st=lstatSync(tarball);
98
+ if(!st.isFile()||st.isSymbolicLink()||st.size<1024||st.size>8*1024*1024)
99
+ return freshResult('BLOCKED',{code:'RELEASE_ARTIFACT_UNTRUSTED'});
100
+ input=createHash('sha256').update(readFileSync(tarball)).digest('hex');
101
+ if(input!==expectedSha256)
102
+ return freshResult('BLOCKED',{code:'RELEASE_ARTIFACT_HASH_MISMATCH'});
103
+ }catch{return freshResult('BLOCKED',{code:'RELEASE_ARTIFACT_UNAVAILABLE'})}
104
+ try{
105
+ mkdirSync(p.base,{recursive:true,mode:0o700});
106
+ mkdirSync(p.releases,{recursive:true,mode:0o700});
107
+ for(const dir of [p.base,p.releases]){
108
+ const st=lstatSync(dir);
109
+ // Existing runtime parents can be 0755; only foreign *write* access
110
+ // threatens staging. The new private staging directory remains 0700.
111
+ if(!st.isDirectory()||st.isSymbolicLink()||
112
+ (st.mode&0o022)||(process.getuid&&st.uid!==process.getuid()))
113
+ return freshResult('BLOCKED',{code:'RELEASE_DIRECTORY_UNTRUSTED'});
114
+ }
115
+ }catch{return freshResult('BLOCKED',{code:'RELEASE_DIRECTORY_UNTRUSTED'})}
116
+ // Share the exact upgrade lock: a concurrent activate cannot race staging.
117
+ let fd;
118
+ try{fd=openSync(p.lock,'wx',0o600)}
119
+ catch{return freshResult('BLOCKED',{code:'UPGRADE_IN_PROGRESS'})}
120
+ const temporary=join(p.releases,'.prepare-'+p.version+'-'+randomUUID());
121
+ let phase='install';
122
+ try{
123
+ // Never mutate an existing release, even one with the same version.
124
+ if(existsSync(p.stage))
125
+ return freshResult('BLOCKED',{code:'RELEASE_STAGE_EXISTS'});
126
+ mkdirSync(temporary,{mode:0o700});
127
+ // Copy the verified artifact under our private stage root so a changed
128
+ // source path cannot swap its bytes between hash-check and npm install.
129
+ const privateTarball=join(temporary,'validated-release.tgz');
130
+ writeFileSync(privateTarball,readFileSync(tarball),{mode:0o600,flag:'wx'});
131
+ if(createHash('sha256').update(readFileSync(privateTarball)).digest('hex')!==input)
132
+ return freshResult('BLOCKED',{code:'RELEASE_ARTIFACT_CHANGED'});
133
+ const runner=options.run||run;
134
+ await runner(process.platform==='win32'?'npm.cmd':'npm',[
135
+ 'install','--offline','--ignore-scripts','--no-audit','--no-fund',
136
+ '--no-package-lock','--no-save','--prefix',temporary,privateTarball
137
+ ],{env:process.env});
138
+ unlinkSync(privateTarball); // Keep only the installed runtime and hash proof.
139
+ phase='verify';
140
+ const installed=join(temporary,'node_modules','@tomflow','chatloop-tools');
141
+ const actual=readJson(join(installed,'package.json'));
142
+ if(actual.name!==name||actual.version!==p.version)
143
+ return freshResult('BLOCKED',{code:'STAGE_VERSION_MISMATCH'});
144
+ for(const dep of [
145
+ '@tomflow/chatloop-context','@tomflow/chatloop-trace'
146
+ ]){
147
+ const version=actual.dependencies?.[dep];
148
+ const file=join(installed,'node_modules',...dep.split('/'),'package.json');
149
+ if(!safeVersion(version||'')||!actual.bundleDependencies?.includes(dep)||
150
+ !existsSync(file)||readJson(file).name!==dep||
151
+ readJson(file).version!==version)
152
+ return freshResult('BLOCKED',{code:'BUNDLED_SDK_MISMATCH'});
153
+ }
154
+ const proposedEntry=entryIn(temporary);
155
+ const readiness=await cli(proposedEntry,'doctor');
156
+ if(readiness.status!=='LOCAL_READY')
157
+ return freshResult('BLOCKED',{code:'STAGE_DOCTOR_FAILED'});
158
+ const tunnel=await cli(proposedEntry,['tunnel','doctor']);
159
+ if(tunnel.status!=='BUNDLED_READY'||tunnel.verified!==true)
160
+ return freshResult('BLOCKED',{code:'STAGE_TUNNEL_NOT_READY'});
161
+ const files=[
162
+ 'bin/cli.mjs','lib/supervisor.mjs','lib/context-gateway.mjs',
163
+ 'node_modules/@tomflow/chatloop-context/bin/cli.mjs',
164
+ 'node_modules/@tomflow/chatloop-context/lib/operations.mjs',
165
+ 'node_modules/@tomflow/chatloop-trace/lib/trace.mjs'
166
+ ];
167
+ const fingerprints={};
168
+ for(const name of files){
169
+ const file=join(installed,name),st=lstatSync(file);
170
+ if(!st.isFile()||st.isSymbolicLink())
171
+ return freshResult('BLOCKED',{code:'STAGE_FILE_UNTRUSTED'});
172
+ fingerprints[name]=createHash('sha256').update(readFileSync(file)).digest('hex');
173
+ }
174
+ writeFileSync(join(temporary,'release-evidence.json'),JSON.stringify({
175
+ artifactSha256:input,version:p.version,fingerprints
176
+ }),{mode:0o600,flag:'wx'});
177
+ phase='commit';
178
+ if(existsSync(p.stage))
179
+ return freshResult('BLOCKED',{code:'RELEASE_STAGE_EXISTS'});
180
+ renameSync(temporary,p.stage);
181
+ return freshResult('OK',{outcome:'STAGED_ONLY',artifactSha256:input,
182
+ entry:p.entry,ownerStopped:false,productionActivated:false});
183
+ }catch(e){
184
+ return freshResult('BLOCKED',{code:e.code||'RELEASE_PREPARE_FAILED',phase});
185
+ }finally{
186
+ if(existsSync(temporary))rmSync(temporary,{recursive:true,force:true});
187
+ closeSync(fd);
188
+ try{unlinkSync(p.lock)}catch{}
189
+ }
190
+ }
191
+
192
+ export function verifyPreparedRelease(base,version=PACKAGE_VERSION){
193
+ const p=upgradeLayout(base,version);
194
+ const file=join(p.stage,'release-evidence.json');
195
+ try{
196
+ if(!existsSync(file))return {ok:false,code:'PREPARED_RELEASE_NOT_FOUND'};
197
+ const folder=lstatSync(p.stage);
198
+ if(!folder.isDirectory()||folder.isSymbolicLink())
199
+ return {ok:false,code:'PREPARED_RELEASE_UNTRUSTED'};
200
+ const evidence=readJson(file);
201
+ if(evidence.version!==p.version||!/^[a-f0-9]{64}$/.test(
202
+ evidence.artifactSha256||''))
203
+ return {ok:false,code:'PREPARED_RELEASE_UNTRUSTED'};
204
+ const installed=join(p.stage,'node_modules','@tomflow','chatloop-tools');
205
+ const manifest=readJson(join(installed,'package.json'));
206
+ if(manifest.name!==name||manifest.version!==p.version)
207
+ return {ok:false,code:'STAGE_VERSION_MISMATCH'};
208
+ const entries=Object.entries(evidence.fingerprints??{});
209
+ if(entries.length!==6)return {ok:false,code:'PREPARED_RELEASE_UNTRUSTED'};
210
+ for(const [relative,sha] of entries){
211
+ if(!/^[a-f0-9]{64}$/.test(sha)||relative.startsWith('/')||
212
+ relative.split('/').includes('..'))
213
+ return {ok:false,code:'PREPARED_RELEASE_UNTRUSTED'};
214
+ const path=join(installed,relative),st=lstatSync(path);
215
+ if(!st.isFile()||st.isSymbolicLink()||
216
+ createHash('sha256').update(readFileSync(path)).digest('hex')!==sha)
217
+ return {ok:false,code:'PREPARED_RELEASE_TAMPERED'};
218
+ }
219
+ return {ok:true,artifactSha256:evidence.artifactSha256};
220
+ }catch{return {ok:false,code:'PREPARED_RELEASE_UNTRUSTED'}}
221
+ }
222
+
71
223
  export async function upgradeRuntime(options={}){
72
224
  if(options.args?.length)return freshResult('FAILED',{code:'INVALID_ARGUMENT'});
73
- const p=upgradeLayout(options.base,options.version||PACKAGE_VERSION);
225
+ const base=checkedUpgradeBase(options);
226
+ if(!base)return freshResult('BLOCKED',{code:'RUNTIME_HOME_MISMATCH'});
227
+ const p=upgradeLayout(base,options.version||PACKAGE_VERSION);
74
228
  mkdirSync(p.base,{recursive:true,mode:0o700});
75
229
  mkdirSync(p.releases,{recursive:true,mode:0o700});
76
230
  let fd;
@@ -94,6 +248,10 @@ export async function upgradeRuntime(options={}){
94
248
  }
95
249
  // Prepare a new immutable install without touching the running service.
96
250
  phase='prepare';
251
+ if(options.requirePrepared&&!/^[a-f0-9]{64}$/.test(options.expectedArtifactSha256||''))
252
+ return freshResult('BLOCKED',{code:'RELEASE_ARTIFACT_PIN_REQUIRED'});
253
+ if(options.requirePrepared&&!existsSync(p.entry))
254
+ return freshResult('BLOCKED',{code:'PREPARED_RELEASE_NOT_FOUND'});
97
255
  if(!existsSync(p.entry)){
98
256
  await runner(process.platform==='win32'?'npm.cmd':'npm',
99
257
  ['install','--prefix',p.stage,'--save-exact','--ignore-scripts',name+'@'+p.version],
@@ -101,8 +259,19 @@ export async function upgradeRuntime(options={}){
101
259
  }
102
260
  if(!existsSync(p.entry)||readJson(join(dirname(dirname(p.entry)),'package.json')).version!==p.version)
103
261
  return freshResult('BLOCKED',{code:'STAGE_VERSION_MISMATCH'});
262
+ if(options.requirePrepared){
263
+ const evidence=verifyPreparedRelease(p.base,p.version);
264
+ if(!evidence.ok)return freshResult('BLOCKED',{code:evidence.code});
265
+ if(evidence.artifactSha256!==options.expectedArtifactSha256)
266
+ return freshResult('BLOCKED',{code:'RELEASE_ARTIFACT_PIN_MISMATCH'});
267
+ }
104
268
  const ready=await cli(p.entry,'doctor');
105
269
  if(ready.status!=='LOCAL_READY')return freshResult('BLOCKED',{code:'STAGE_DOCTOR_FAILED'});
270
+ if(options.requirePrepared){
271
+ const tunnel=await cli(p.entry,['tunnel','doctor']);
272
+ if(tunnel.status!=='BUNDLED_READY'||tunnel.verified!==true)
273
+ return freshResult('BLOCKED',{code:'STAGE_TUNNEL_NOT_READY'});
274
+ }
106
275
  // The staged Gateway is prepared independently; Tunnel binds only on activation.
107
276
  phase='check-owner';
108
277
  oldStatus=await cli(oldEntry,'status');
@@ -1,17 +1,73 @@
1
1
  import {randomUUID} from 'node:crypto';
2
- import {appendFileSync, closeSync, existsSync, openSync, readFileSync, unlinkSync, writeFileSync, chmodSync} from 'node:fs';
2
+ import {createTraceWriter} from '@tomflow/chatloop-trace';
3
+ import {closeSync, existsSync, openSync, readFileSync, unlinkSync, writeFileSync, chmodSync} from 'node:fs';
3
4
  import {createServer} from 'node:net';
4
5
  import {CONTRACT,VERSION,PACKAGE_VERSION,registry,paths,ensurePrivateDir,ACTIONS} from './control.mjs';
5
6
  import {createAdapter} from './adapters/index.mjs';
7
+ import {loadContextControlSecret} from './context-control-auth.mjs';
8
+ import {handleContextControl} from './context-control-run.mjs';
6
9
 
7
10
  const catalog=registry(), records=new Map(), queues=new Map(), seen=new Map(), receipts=new Map();
8
11
  const p=paths(), nonce=randomUUID();
12
+ const traceWriter=createTraceWriter({
13
+ filePath:p.log,enableRotation:process.env.CHAT_LOOP_TRACE_ROTATE_ENABLE==='1'
14
+ });
9
15
  const desiredTunnel=new Set(), recoveryAttempts=new Map();
10
16
  let lockFd, server, idleTimer;
11
17
  const log=(event,detail={})=>{
12
- try{appendFileSync(p.log,JSON.stringify({time:new Date().toISOString(),event,...detail})+'\n',{mode:0o600});}catch{}
18
+ try{traceWriter.recordLegacy(event,detail);}catch{
19
+ // Observability is never permission to replay an unknown business action.
20
+ // The failure is retained by traceWriter.health and surfaced in __ping.
21
+ }
13
22
  };
14
23
  const error=(code,message=code)=>({code,message});
24
+ const allowedTraceProjects=()=>{
25
+ const entries=(process.env.CHAT_LOOP_TRACE_ALLOWED_PROJECTS||'')
26
+ .split(',').map(x=>x.trim());
27
+ // Apply the same single-project, fail-closed boundary to log submission.
28
+ return new Set(entries.length===1 && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(entries[0])
29
+ ? entries : []);
30
+ };
31
+ const traceEnabled=()=>process.env.CHAT_LOOP_TRACE_API_ENABLE==='1';
32
+ function handleTraceObservation(req){
33
+ if(!traceEnabled()||!allowedTraceProjects().has(req?.projectRef))
34
+ throw error('TRACE_PROJECT_ACCESS_DENIED');
35
+ const intent=/^extension\.(continue|handoff)\.(intent\.queued|receipt\.observed)$/.test(req?.event||'');
36
+ const validEvent=['extension.start.observed','extension.status.observed'].includes(req?.event)
37
+ ||intent;
38
+ if(req?.contract!==CONTRACT||!validEvent
39
+ ||!(intent?(req.event.endsWith('.intent.queued')?req.status==='BEGIN'
40
+ :['CONFIRMED','UNKNOWN'].includes(req.status))
41
+ :['CONFIRMED','UNKNOWN'].includes(req.status))
42
+ ||typeof req.traceId!=='string'
43
+ ||(intent&&(!/^[a-f0-9]{32}$/.test(req.actionId||'')
44
+ ||req.evidenceRef!==req.actionId)))throw error('TRACE_INVALID_ARGUMENT');
45
+ const written=traceWriter.record({
46
+ traceId:req.traceId,sessionRef:req.sessionRef,projectRef:req.projectRef,
47
+ taskRef:req.taskRef??null,generation:req.generation??null,
48
+ requestId:req.requestId,component:'gateway',
49
+ ...(intent?{actionId:req.actionId,evidenceRef:req.evidenceRef}:{}),
50
+ event:req.event,status:req.status
51
+ });
52
+ return {contract:CONTRACT,requestId:req.requestId,status:'OK',eventId:written.eventId};
53
+ }
54
+ function traceNativeReceipt(req){
55
+ if(!traceEnabled())return;
56
+ // This is called ONLY after handleContextControl verifies Native HMAC and
57
+ // successfully executes the Context command; it is not a Browser send proof.
58
+ const command=req?.payload?.command,args=req?.payload?.args;
59
+ if(!command||!args||!allowedTraceProjects().has(args.projectId))return;
60
+ try{
61
+ traceWriter.record({traceId:args.sessionId,sessionRef:args.sessionId,
62
+ projectRef:args.projectId,taskRef:args.taskId,
63
+ generation:args.generation,component:'native',requestId:req.requestId,
64
+ event:'native.context.'+command+'.confirmed',status:'CONFIRMED'});
65
+ }catch{
66
+ // Trace failure is surfaced by health(), never treated as a failed
67
+ // Context mutation; its write result must not be replayed.
68
+ }
69
+ }
70
+
15
71
  const after=rec=>rec ? rec.state : 'STOPPED';
16
72
  function saveReceipt(id,state,result=null,errorCode=null){
17
73
  receipts.delete(id);
@@ -171,6 +227,10 @@ async function shutdown(){
171
227
  }
172
228
  async function main(){
173
229
  ensurePrivateDir();
230
+ // No secret or Context Store is created unless the opt-in adapter is enabled.
231
+ if(process.env.CHAT_LOOP_CONTEXT_API_ENABLE==='1'){
232
+ loadContextControlSecret({create:true});
233
+ }
174
234
  try{lockFd=openSync(p.lock,'wx',0o600);}
175
235
  catch(err){if(err.code==='EEXIST')process.exit(0);throw err;}
176
236
  writeFileSync(lockFd,JSON.stringify({pid:process.pid,nonce,version:VERSION,at:Date.now()}));
@@ -190,7 +250,22 @@ async function main(){
190
250
  handled=true;
191
251
  let req;try{req=JSON.parse(buf.slice(0,n));}catch{socket.end(JSON.stringify(bad({},'INVALID_ARGUMENT'))+'\n');return;}
192
252
  const work=req?.action==='__ping'?
193
- Promise.resolve({contract:CONTRACT,version:VERSION,packageVersion:PACKAGE_VERSION,registrySignature:catalog.map(t=>t.id+':'+t.enabled).join('|'),ownerNonce:nonce,managerPid:process.pid}):req?.action==='call'?executeCall(req):req?.action==='receipt'?Promise.resolve(receipt(req)):execute(req);
253
+ Promise.resolve({contract:CONTRACT,version:VERSION,packageVersion:PACKAGE_VERSION,registrySignature:catalog.map(t=>t.id+':'+t.enabled).join('|'),ownerNonce:nonce,
254
+ managerPid:process.pid,traceHealth:traceWriter.health()}):req?.action==='__trace_health'
255
+ ?Promise.resolve({contract:CONTRACT,requestId:req.requestId,
256
+ status:'OK',traceHealth:traceWriter.health()})
257
+ :req?.action==='__trace_observation'
258
+ ?Promise.resolve().then(()=>handleTraceObservation(req))
259
+ .catch(e=>bad(req,e.code||'TRACE_RECORD_FAILED'))
260
+ :req?.action==='context-control'
261
+ ?handleContextControl(req).then(result=>{
262
+ traceNativeReceipt(req);
263
+ return {contract:CONTRACT,requestId:req.requestId,status:'OK',result};
264
+ }).catch(e=>{
265
+ log('context-control-error',{status:'FAILED',errorCode:e.code||'CONTEXT_CONTROL_FAILED'});
266
+ return bad(req,e.code||'CONTEXT_CONTROL_FAILED');
267
+ })
268
+ :req?.action==='call'?executeCall(req):req?.action==='receipt'?Promise.resolve(receipt(req)):execute(req);
194
269
  work.then(value=>socket.end(JSON.stringify(value)+'\n')).catch(err=>{
195
270
  log('ipc-error',{code:err.code||'INTERNAL_ERROR'});
196
271
  socket.end(JSON.stringify(bad(req,'INTERNAL_ERROR'))+'\n');
@@ -0,0 +1,38 @@
1
+ // Legacy MCP registry compatibility: once the exact physical Registry source
2
+ // is MANAGED_RW, it can never create a second JSON write authority.
3
+ // New edits go through ContextService with epoch + idempotent CAS.
4
+ import {existsSync,lstatSync,readFileSync} from 'node:fs';
5
+ import {createHash} from 'node:crypto';
6
+ const error=code=>Object.assign(new Error(code),{code});
7
+ const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
8
+ const state=(path,expectedHash)=>{
9
+ try{
10
+ const st=lstatSync(path);
11
+ if(!st.isFile()||st.isSymbolicLink()||st.size>512*1024)
12
+ return 'UNVERIFIED';
13
+ const actual=sha(readFileSync(path));
14
+ return actual===expectedHash?'PRESENT':'CHANGED';
15
+ }catch(e){return e.code==='ENOENT'?'MISSING':'UNVERIFIED'}
16
+ };
17
+ const snapshot=task=>{
18
+ const c=task.currentContext;
19
+ return {taskId:task.taskId,projectId:task.projectId,title:c.title,
20
+ taskDocPath:c.taskDocPath,parentTaskId:c.parentTaskId??null,
21
+ revision:task.taskRevision,taskDocumentState:state(c.taskDocPath,c.taskDocumentHash),
22
+ documents:(c.legacyDocuments??[]).map(x=>({...x,sourceStatus:'UNVERIFIED'})),
23
+ migrated:true,sourceOfTruth:'ContextService'};
24
+ };
25
+ export function managedTaskRegistry(db,args){
26
+ if(args.action==='list'){
27
+ return {tasks:db.taskList(args.projectId).filter(t=>t.currentContext?.taskDocPath)
28
+ .map(snapshot)};
29
+ }
30
+ if(args.action==='get'){
31
+ const t=db.get(args.projectId,args.taskId);
32
+ if(!t.currentContext?.taskDocPath)throw error('REGISTRY_NOT_MIGRATED_TASK');
33
+ return snapshot(t);
34
+ }
35
+ // Old calls lack expectedStoreEpoch, writeRequestId, and scoped run cred.
36
+ // A successful JSON write would create two authorities. Never do it.
37
+ throw error('REGISTRY_MANAGED_USE_CONTEXT_MUTATE');
38
+ }