@tomflow/chatloop-tools 0.4.19 → 0.4.23

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 (32) hide show
  1. package/README.md +93 -3
  2. package/bin/cli.mjs +27 -6
  3. package/lib/adapters/mcp-child.mjs +17 -7
  4. package/lib/context-cli.mjs +2 -0
  5. package/lib/context-control-auth.mjs +40 -0
  6. package/lib/context-control-run.mjs +117 -0
  7. package/lib/context-gateway.mjs +97 -0
  8. package/lib/context-migration.mjs +2 -0
  9. package/lib/context-protocol.mjs +2 -0
  10. package/lib/extension-contract.mjs +16 -0
  11. package/lib/extension-proxy.mjs +11 -2
  12. package/lib/gateway.mjs +93 -4
  13. package/lib/release.mjs +177 -5
  14. package/lib/supervisor.mjs +78 -3
  15. package/lib/task-registry-managed.mjs +38 -0
  16. package/lib/task-registry.mjs +221 -0
  17. package/lib/terminal-app-policy.mjs +18 -0
  18. package/lib/trace-gateway.mjs +99 -0
  19. package/node_modules/@tomflow/chatloop-context/README.md +204 -0
  20. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +236 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +301 -0
  22. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +272 -0
  23. package/node_modules/@tomflow/chatloop-context/lib/context-protocol.mjs +1595 -0
  24. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +264 -0
  25. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +219 -0
  26. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +289 -0
  27. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +159 -0
  28. package/node_modules/@tomflow/chatloop-context/package.json +21 -0
  29. package/node_modules/@tomflow/chatloop-trace/README.md +13 -0
  30. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +259 -0
  31. package/node_modules/@tomflow/chatloop-trace/package.json +11 -0
  32. package/package.json +9 -3
package/lib/gateway.mjs CHANGED
@@ -4,9 +4,41 @@ 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';
12
+ import {isGraphicalTerminalCommand} from './terminal-app-policy.mjs';
8
13
 
9
- const desktopTools=JSON.parse(readFileSync(new URL('./desktop-commander-tools.json',import.meta.url),'utf8'));
14
+ // Keep the pinned Desktop Commander as the implementation, but expose only
15
+ // the file/search/process API useful to Chat Loop. Hidden tools are NOT routable
16
+ // by tools/call either; runtime/admin/onboarding controls are not agent tools.
17
+ const hiddenDesktopTools=new Set([
18
+ 'set_config_value','get_usage_stats','get_recent_tool_calls',
19
+ 'give_feedback_to_desktop_commander','get_prompts'
20
+ ]);
21
+ // The vendor descriptions contain long onboarding instructions and even
22
+ // directives to start unnecessary REPLs. Keep the exact vendor inputSchema,
23
+ // but describe the supported API succinctly at this single MCP boundary.
24
+ const desktopDescriptions={
25
+ 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.',
26
+ read_multiple_files:'Read several authorized absolute file paths in one request. Returns each result with its source path.',
27
+ 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.',
28
+ write_pdf:'Create or modify a PDF with markdown/operations. Use a new outputPath for modifications; never silently overwrite the original.',
29
+ list_directory:'List files and folders under an authorized absolute path; depth limits recursion and output.',
30
+ start_search:'Search filenames (searchType=files) or file contents (searchType=content) from an authorized root. Returns a session for paginated results.',
31
+ get_more_search_results:'Get additional results from an existing search session using sessionId and pagination.',
32
+ 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.',
33
+ start_process:'Run CLI commands through the MCP process, never launch macOS Terminal/iTerm apps. A PID is not completion; read its output.',
34
+ read_process_output:'Read output of an already-started PID with optional offset/length/timeout_ms. Does not start the command again.',
35
+ interact_with_process:'Send input to an existing interactive PID and obtain output. Do not repeat commands with unknown side effects.',
36
+ get_config:'Read Desktop Commander configuration/allowed directories for diagnosis; does not grant or change permissions.'
37
+ };
38
+ const desktopTools=JSON.parse(readFileSync(
39
+ new URL('./desktop-commander-tools.json',import.meta.url),'utf8'))
40
+ .filter(t=>!hiddenDesktopTools.has(t.name))
41
+ .map(t=>({...t,description:desktopDescriptions[t.name]||t.description.trim()}));
10
42
  const fixtureTool={name:'ping',description:'Inert lifecycle test health check',
11
43
  inputSchema:{type:'object',properties:{},additionalProperties:false}};
12
44
  const toolsFor=t=>t.kind==='mcp-child'?desktopTools:t.kind==='fixture'?[fixtureTool]:[];
@@ -28,7 +60,10 @@ const published=()=>[
28
60
  toolsFor(t).map(({_meta,...x})=>({...x,name:prefix(t.id)+x.name}))),
29
61
  ...(extEnabled()?extensionTools.map(t=>({...t,name:'chat_loop_extension__'+t.name})):[]),
30
62
  ...(formProbeEnabled()?[probeTool]:[]),
31
- receiptTool
63
+ receiptTool,
64
+ taskRegistryTool,
65
+ ...(contextGatewayEnabled()?contextGatewayTools:[]),
66
+ ...(traceGatewayEnabled()?[traceDiagnoseTool]:[])
32
67
  ];
33
68
  function resolveTool(name){
34
69
  if(extEnabled()&&typeof name==='string'&&name.startsWith('chat_loop_extension__')){
@@ -70,6 +105,54 @@ export function runGateway(){
70
105
  if(m.method==='ping')return reply(m.id,{});
71
106
  if(m.method==='tools/list')return reply(m.id,{tools:published()});
72
107
  if(m.method==='tools/call'){
108
+ if(traceGatewayEnabled()&&m.params?.name===traceDiagnoseTool.name){
109
+ try{
110
+ const result=await runTraceDiagnose(m.params.arguments);
111
+ return reply(m.id,{content:[{type:'text',text:JSON.stringify(result)}]});
112
+ }catch(e){return reply(m.id,failure(e.code||'TRACE_DIAGNOSE_FAILED'))}
113
+ }
114
+ if(m.params?.name===taskRegistryTool.name){
115
+ try{
116
+ // Opting into managed Context must never silently revive JSON
117
+ // Registry writes when its SDK, Node runtime or binding is absent.
118
+ if(process.env.CHAT_LOOP_CONTEXT_API_ENABLE==='1'&&!contextGatewayEnabled())
119
+ throw Error('CONTEXT_GATEWAY_UNAVAILABLE');
120
+ let value;
121
+ // Authority is the durable SourceUnit migration record, never a
122
+ // process-local env flag that could go stale after cutover.
123
+ if(contextGatewayEnabled()){
124
+ const args=m.params.arguments||{},projectId=args.projectId;
125
+ const authority=await runContextGateway('chat_loop_context_get',{
126
+ operation:'project.registryAuthority',projectId});
127
+ if(authority==='RESTORED_DIAGNOSTIC')
128
+ throw Error('REGISTRY_RESTORE_READ_ONLY');
129
+ if(authority==='CUTOVER_FENCED')
130
+ throw Error('REGISTRY_CUTOVER_FENCED');
131
+ if(!['LEGACY_RW','MANAGED_RW'].includes(authority))
132
+ throw Error('REGISTRY_AUTHORITY_UNKNOWN');
133
+ if(authority==='MANAGED_RW'){
134
+ // The legacy registry is a read-only projection through the
135
+ // independent Context SDK, not a second SQLite client.
136
+ if(args.action==='list'){
137
+ const tasks=await runContextGateway('chat_loop_context_get',{
138
+ operation:'task.list',projectId});
139
+ value=managedTaskRegistry({taskList:()=>tasks},args);
140
+ }else if(args.action==='get'){
141
+ const task=await runContextGateway('chat_loop_context_get',{
142
+ operation:'task.get',projectId,taskId:args.taskId});
143
+ value=managedTaskRegistry({get:()=>task},args);
144
+ }else throw Error('REGISTRY_MANAGED_USE_CONTEXT_MUTATE');
145
+ }else value=runTaskRegistry(args);
146
+ }else value=runTaskRegistry(m.params.arguments);
147
+ return reply(m.id,{content:[{type:'text',text:JSON.stringify(value)}]});
148
+ }catch(e){return reply(m.id,failure(e.code||e.message||'TASK_REGISTRY_FAILED'));}
149
+ }
150
+ if(contextGatewayEnabled()&&contextGatewayTools.some(t=>t.name===m.params?.name)){
151
+ try{
152
+ const value=await runContextGateway(m.params.name,m.params.arguments);
153
+ return reply(m.id,{content:[{type:'text',text:JSON.stringify(value)}]});
154
+ }catch(e){return reply(m.id,failure(e.code||e.message||'CONTEXT_OPERATION_FAILED'));}
155
+ }
73
156
  if(formProbeEnabled() && m.params?.name===probeTool.name)
74
157
  return reply(m.id,negotiatedVersion==='2026-07-28'
75
158
  ?handleProbeForm(m.params)
@@ -81,6 +164,9 @@ export function runGateway(){
81
164
  const args=m.params?.arguments??{};
82
165
  if(args===null||typeof args!=='object'||Array.isArray(args))
83
166
  return reply(m.id,failure('INVALID_ARGUMENT'));
167
+ if(routed.toolId==='desktop-commander'&&
168
+ isGraphicalTerminalCommand(routed.name,args))
169
+ return reply(m.id,failure('GUI_TERMINAL_LAUNCH_PROHIBITED'));
84
170
  try{
85
171
  if(routed.toolId==='runtime'){
86
172
  if(Object.keys(args).length!==1 || typeof args.requestId!=='string'
@@ -94,8 +180,11 @@ export function runGateway(){
94
180
  !process.env.CHAT_LOOP_LOCAL_TOOLS_STATE_DIR&&
95
181
  !process.env.CHAT_LOOP_LOCAL_TOOLS_FIXTURES&&runtimeNeedsUpgrade())
96
182
  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));
183
+ if(routed.toolId==='chat-loop-extension'){
184
+ const result=await forwardExtensionAction(routed.name,args);
185
+ await observeExtensionResult(routed.name,args,result);
186
+ return reply(m.id,result);
187
+ }
99
188
  const deadlineMs=toolCallDeadlineMs(args),requestId=randomUUID();
100
189
  const res=await talk({contract:CONTRACT,requestId,action:'call',
101
190
  scope:'tool',toolId:routed.toolId,name:routed.name,args,deadlineMs},deadlineMs+2000);
package/lib/release.mjs CHANGED
@@ -1,14 +1,30 @@
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
+ // os.homedir() may be cached in a long-running Node process. Verify
19
+ // the live process HOME as well as the account home, no GUI Terminal needed.
20
+ if(homedir()!==accountHome||process.env.HOME&&process.env.HOME!==accountHome)
21
+ return null;
22
+ const currentState=process.env.CHAT_LOOP_LOCAL_TOOLS_STATE_DIR;
23
+ if(currentState&&currentState!==join(accountHome,'.chat-loop','local-tools'))
24
+ return null;
25
+ return join(accountHome,'.chat-loop');
26
+ }catch{return null}
27
+ }
12
28
  const readJson=path=>JSON.parse(readFileSync(path,'utf8'));
13
29
  const delay=ms=>new Promise(r=>setTimeout(r,ms));
14
30
  const safeVersion=v=>/^[0-9]+\.[0-9]+\.[0-9]+(?:-[a-zA-Z0-9.-]+)?$/.test(v);
@@ -46,7 +62,7 @@ function run(bin,args,opts={}){
46
62
  }
47
63
  async function cli(entry,action,opts={}){
48
64
  let raw;
49
- try{raw=await run(process.execPath,[entry,action],opts);}
65
+ try{raw=await run(process.execPath,[entry,...(Array.isArray(action)?action:[action])],opts);}
50
66
  catch(e){if(!e.stdout)throw e;raw=e.stdout;}
51
67
  try{return JSON.parse(raw.trim());}
52
68
  catch{throw Object.assign(Error('INVALID_CLI_REPLY'),{code:'INVALID_CLI_REPLY'});}
@@ -68,9 +84,150 @@ export function runtimeNeedsUpgrade(base=runtimeRoot(),version=PACKAGE_VERSION){
68
84
  const current=readJson(join(dirname(dirname(p.legacy)),'package.json')).version;
69
85
  return current!==version;
70
86
  }
87
+ // Explicit, offline, stage-only release preparation. Never touches the old
88
+ // Supervisor, Tunnel, runtime.json, MCP profile or any Context Store.
89
+ export async function prepareReleaseCandidate(options={}){
90
+ const base=checkedUpgradeBase(options);
91
+ if(!base)return freshResult('BLOCKED',{code:'RUNTIME_HOME_MISMATCH'});
92
+ const p=upgradeLayout(base,options.version||PACKAGE_VERSION);
93
+ const tarball=options.tarball;
94
+ const expectedSha256=options.sha256;
95
+ if(typeof tarball!=='string'||!tarball.startsWith('/')||
96
+ !tarball.endsWith('.tgz')||!/^[a-f0-9]{64}$/.test(expectedSha256||''))
97
+ return freshResult('BLOCKED',{code:'INVALID_RELEASE_ARTIFACT'});
98
+ let input;
99
+ try{
100
+ const st=lstatSync(tarball);
101
+ if(!st.isFile()||st.isSymbolicLink()||st.size<1024||st.size>8*1024*1024)
102
+ return freshResult('BLOCKED',{code:'RELEASE_ARTIFACT_UNTRUSTED'});
103
+ input=createHash('sha256').update(readFileSync(tarball)).digest('hex');
104
+ if(input!==expectedSha256)
105
+ return freshResult('BLOCKED',{code:'RELEASE_ARTIFACT_HASH_MISMATCH'});
106
+ }catch{return freshResult('BLOCKED',{code:'RELEASE_ARTIFACT_UNAVAILABLE'})}
107
+ try{
108
+ mkdirSync(p.base,{recursive:true,mode:0o700});
109
+ mkdirSync(p.releases,{recursive:true,mode:0o700});
110
+ for(const dir of [p.base,p.releases]){
111
+ const st=lstatSync(dir);
112
+ // Existing runtime parents can be 0755; only foreign *write* access
113
+ // threatens staging. The new private staging directory remains 0700.
114
+ if(!st.isDirectory()||st.isSymbolicLink()||
115
+ (st.mode&0o022)||(process.getuid&&st.uid!==process.getuid()))
116
+ return freshResult('BLOCKED',{code:'RELEASE_DIRECTORY_UNTRUSTED'});
117
+ }
118
+ }catch{return freshResult('BLOCKED',{code:'RELEASE_DIRECTORY_UNTRUSTED'})}
119
+ // Share the exact upgrade lock: a concurrent activate cannot race staging.
120
+ let fd;
121
+ try{fd=openSync(p.lock,'wx',0o600)}
122
+ catch{return freshResult('BLOCKED',{code:'UPGRADE_IN_PROGRESS'})}
123
+ const temporary=join(p.releases,'.prepare-'+p.version+'-'+randomUUID());
124
+ let phase='install';
125
+ try{
126
+ // Never mutate an existing release, even one with the same version.
127
+ if(existsSync(p.stage))
128
+ return freshResult('BLOCKED',{code:'RELEASE_STAGE_EXISTS'});
129
+ mkdirSync(temporary,{mode:0o700});
130
+ // Copy the verified artifact under our private stage root so a changed
131
+ // source path cannot swap its bytes between hash-check and npm install.
132
+ const privateTarball=join(temporary,'validated-release.tgz');
133
+ writeFileSync(privateTarball,readFileSync(tarball),{mode:0o600,flag:'wx'});
134
+ if(createHash('sha256').update(readFileSync(privateTarball)).digest('hex')!==input)
135
+ return freshResult('BLOCKED',{code:'RELEASE_ARTIFACT_CHANGED'});
136
+ const runner=options.run||run;
137
+ await runner(process.platform==='win32'?'npm.cmd':'npm',[
138
+ 'install','--offline','--ignore-scripts','--no-audit','--no-fund',
139
+ '--no-package-lock','--no-save','--prefix',temporary,privateTarball
140
+ ],{env:process.env});
141
+ unlinkSync(privateTarball); // Keep only the installed runtime and hash proof.
142
+ phase='verify';
143
+ const installed=join(temporary,'node_modules','@tomflow','chatloop-tools');
144
+ const actual=readJson(join(installed,'package.json'));
145
+ if(actual.name!==name||actual.version!==p.version)
146
+ return freshResult('BLOCKED',{code:'STAGE_VERSION_MISMATCH'});
147
+ for(const dep of [
148
+ '@tomflow/chatloop-context','@tomflow/chatloop-trace'
149
+ ]){
150
+ const version=actual.dependencies?.[dep];
151
+ const file=join(installed,'node_modules',...dep.split('/'),'package.json');
152
+ if(!safeVersion(version||'')||!actual.bundleDependencies?.includes(dep)||
153
+ !existsSync(file)||readJson(file).name!==dep||
154
+ readJson(file).version!==version)
155
+ return freshResult('BLOCKED',{code:'BUNDLED_SDK_MISMATCH'});
156
+ }
157
+ const proposedEntry=entryIn(temporary);
158
+ const readiness=await cli(proposedEntry,'doctor');
159
+ if(readiness.status!=='LOCAL_READY')
160
+ return freshResult('BLOCKED',{code:'STAGE_DOCTOR_FAILED'});
161
+ const tunnel=await cli(proposedEntry,['tunnel','doctor']);
162
+ if(tunnel.status!=='BUNDLED_READY'||tunnel.verified!==true)
163
+ return freshResult('BLOCKED',{code:'STAGE_TUNNEL_NOT_READY'});
164
+ const files=[
165
+ 'bin/cli.mjs','lib/supervisor.mjs','lib/context-gateway.mjs',
166
+ 'node_modules/@tomflow/chatloop-context/bin/cli.mjs',
167
+ 'node_modules/@tomflow/chatloop-context/lib/operations.mjs',
168
+ 'node_modules/@tomflow/chatloop-trace/lib/trace.mjs'
169
+ ];
170
+ const fingerprints={};
171
+ for(const name of files){
172
+ const file=join(installed,name),st=lstatSync(file);
173
+ if(!st.isFile()||st.isSymbolicLink())
174
+ return freshResult('BLOCKED',{code:'STAGE_FILE_UNTRUSTED'});
175
+ fingerprints[name]=createHash('sha256').update(readFileSync(file)).digest('hex');
176
+ }
177
+ writeFileSync(join(temporary,'release-evidence.json'),JSON.stringify({
178
+ artifactSha256:input,version:p.version,fingerprints
179
+ }),{mode:0o600,flag:'wx'});
180
+ phase='commit';
181
+ if(existsSync(p.stage))
182
+ return freshResult('BLOCKED',{code:'RELEASE_STAGE_EXISTS'});
183
+ renameSync(temporary,p.stage);
184
+ return freshResult('OK',{outcome:'STAGED_ONLY',artifactSha256:input,
185
+ entry:p.entry,ownerStopped:false,productionActivated:false});
186
+ }catch(e){
187
+ return freshResult('BLOCKED',{code:e.code||'RELEASE_PREPARE_FAILED',phase});
188
+ }finally{
189
+ if(existsSync(temporary))rmSync(temporary,{recursive:true,force:true});
190
+ closeSync(fd);
191
+ try{unlinkSync(p.lock)}catch{}
192
+ }
193
+ }
194
+
195
+ export function verifyPreparedRelease(base,version=PACKAGE_VERSION){
196
+ const p=upgradeLayout(base,version);
197
+ const file=join(p.stage,'release-evidence.json');
198
+ try{
199
+ if(!existsSync(file))return {ok:false,code:'PREPARED_RELEASE_NOT_FOUND'};
200
+ const folder=lstatSync(p.stage);
201
+ if(!folder.isDirectory()||folder.isSymbolicLink())
202
+ return {ok:false,code:'PREPARED_RELEASE_UNTRUSTED'};
203
+ const evidence=readJson(file);
204
+ if(evidence.version!==p.version||!/^[a-f0-9]{64}$/.test(
205
+ evidence.artifactSha256||''))
206
+ return {ok:false,code:'PREPARED_RELEASE_UNTRUSTED'};
207
+ const installed=join(p.stage,'node_modules','@tomflow','chatloop-tools');
208
+ const manifest=readJson(join(installed,'package.json'));
209
+ if(manifest.name!==name||manifest.version!==p.version)
210
+ return {ok:false,code:'STAGE_VERSION_MISMATCH'};
211
+ const entries=Object.entries(evidence.fingerprints??{});
212
+ if(entries.length!==6)return {ok:false,code:'PREPARED_RELEASE_UNTRUSTED'};
213
+ for(const [relative,sha] of entries){
214
+ if(!/^[a-f0-9]{64}$/.test(sha)||relative.startsWith('/')||
215
+ relative.split('/').includes('..'))
216
+ return {ok:false,code:'PREPARED_RELEASE_UNTRUSTED'};
217
+ const path=join(installed,relative),st=lstatSync(path);
218
+ if(!st.isFile()||st.isSymbolicLink()||
219
+ createHash('sha256').update(readFileSync(path)).digest('hex')!==sha)
220
+ return {ok:false,code:'PREPARED_RELEASE_TAMPERED'};
221
+ }
222
+ return {ok:true,artifactSha256:evidence.artifactSha256};
223
+ }catch{return {ok:false,code:'PREPARED_RELEASE_UNTRUSTED'}}
224
+ }
225
+
71
226
  export async function upgradeRuntime(options={}){
72
227
  if(options.args?.length)return freshResult('FAILED',{code:'INVALID_ARGUMENT'});
73
- const p=upgradeLayout(options.base,options.version||PACKAGE_VERSION);
228
+ const base=checkedUpgradeBase(options);
229
+ if(!base)return freshResult('BLOCKED',{code:'RUNTIME_HOME_MISMATCH'});
230
+ const p=upgradeLayout(base,options.version||PACKAGE_VERSION);
74
231
  mkdirSync(p.base,{recursive:true,mode:0o700});
75
232
  mkdirSync(p.releases,{recursive:true,mode:0o700});
76
233
  let fd;
@@ -94,6 +251,10 @@ export async function upgradeRuntime(options={}){
94
251
  }
95
252
  // Prepare a new immutable install without touching the running service.
96
253
  phase='prepare';
254
+ if(options.requirePrepared&&!/^[a-f0-9]{64}$/.test(options.expectedArtifactSha256||''))
255
+ return freshResult('BLOCKED',{code:'RELEASE_ARTIFACT_PIN_REQUIRED'});
256
+ if(options.requirePrepared&&!existsSync(p.entry))
257
+ return freshResult('BLOCKED',{code:'PREPARED_RELEASE_NOT_FOUND'});
97
258
  if(!existsSync(p.entry)){
98
259
  await runner(process.platform==='win32'?'npm.cmd':'npm',
99
260
  ['install','--prefix',p.stage,'--save-exact','--ignore-scripts',name+'@'+p.version],
@@ -101,8 +262,19 @@ export async function upgradeRuntime(options={}){
101
262
  }
102
263
  if(!existsSync(p.entry)||readJson(join(dirname(dirname(p.entry)),'package.json')).version!==p.version)
103
264
  return freshResult('BLOCKED',{code:'STAGE_VERSION_MISMATCH'});
265
+ if(options.requirePrepared){
266
+ const evidence=verifyPreparedRelease(p.base,p.version);
267
+ if(!evidence.ok)return freshResult('BLOCKED',{code:evidence.code});
268
+ if(evidence.artifactSha256!==options.expectedArtifactSha256)
269
+ return freshResult('BLOCKED',{code:'RELEASE_ARTIFACT_PIN_MISMATCH'});
270
+ }
104
271
  const ready=await cli(p.entry,'doctor');
105
272
  if(ready.status!=='LOCAL_READY')return freshResult('BLOCKED',{code:'STAGE_DOCTOR_FAILED'});
273
+ if(options.requirePrepared){
274
+ const tunnel=await cli(p.entry,['tunnel','doctor']);
275
+ if(tunnel.status!=='BUNDLED_READY'||tunnel.verified!==true)
276
+ return freshResult('BLOCKED',{code:'STAGE_TUNNEL_NOT_READY'});
277
+ }
106
278
  // The staged Gateway is prepared independently; Tunnel binds only on activation.
107
279
  phase='check-owner';
108
280
  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
+ }