@tomflow/chatloop-tools 0.4.18 → 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 (32) hide show
  1. package/README.md +93 -3
  2. package/bin/cli.mjs +29 -8
  3. package/lib/approval-form-probe.mjs +55 -0
  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/control.mjs +2 -0
  11. package/lib/extension-contract.mjs +31 -5
  12. package/lib/extension-proxy.mjs +11 -2
  13. package/lib/gateway.mjs +102 -6
  14. package/lib/release.mjs +174 -5
  15. package/lib/supervisor.mjs +78 -3
  16. package/lib/task-registry-managed.mjs +38 -0
  17. package/lib/task-registry.mjs +221 -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
@@ -0,0 +1,221 @@
1
+ // Task identity + document references only. No workflow/approval/Chrome state.
2
+ import {randomUUID} from 'node:crypto';
3
+ import {closeSync,existsSync,openSync,readFileSync,realpathSync,lstatSync,mkdirSync,
4
+ renameSync,unlinkSync,writeFileSync} from 'node:fs';
5
+ import {relative,isAbsolute,join,sep} from 'node:path';
6
+ import {ensurePrivateDir,paths} from './control.mjs';
7
+
8
+ const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
9
+ const goodId=value=>ID.test(value||'')&&!['__proto__','constructor','prototype'].includes(value);
10
+ const ROLE=/^[a-z][a-z0-9_-]{0,63}$/;
11
+ const error=code=>Object.assign(new Error(code),{code});
12
+ const validText=(v,max=200)=>typeof v==='string'&&v.length>0&&v.length<=max
13
+ &&v.trim()===v&&!/[\x00-\x1f]/.test(v);
14
+ const rootOf=p=>{
15
+ if(typeof p!=='string'||!isAbsolute(p))throw error('INVALID_PROJECT_ROOT');
16
+ const st=lstatSync(p);
17
+ if(!st.isDirectory()||st.isSymbolicLink())throw error('INVALID_PROJECT_ROOT');
18
+ return realpathSync(p);
19
+ };
20
+ const authorized=(roots,p)=>{
21
+ if(typeof p!=='string'||!isAbsolute(p)||p.length>4096||/[\x00-\x1f]/.test(p))
22
+ throw error('INVALID_DOCUMENT_PATH');
23
+ let st,real;
24
+ try{st=lstatSync(p);real=realpathSync(p);}catch{throw error('DOCUMENT_MISSING');}
25
+ if(!st.isFile()||st.isSymbolicLink())throw error('DOCUMENT_UNTRUSTED');
26
+ if(!roots.some(root=>{
27
+ const rel=relative(root,real);
28
+ return rel!==''&&rel!=='..'&&!rel.startsWith('..'+sep)&&!isAbsolute(rel);
29
+ }))throw error('DOCUMENT_OUTSIDE_PROJECT');
30
+ return real;
31
+ };
32
+ const taskDoc=(roots,path,taskId)=>{
33
+ const real=authorized(roots,path),st=lstatSync(real);
34
+ if(st.size>512*1024)throw error('TASK_DOCUMENT_TOO_LARGE');
35
+ const text=readFileSync(real,'utf8');
36
+ const ids=[...text.matchAll(/^\s*(?:[-*]\s*)?taskId\s*[::]\s*["'\x60]?([a-zA-Z0-9][a-zA-Z0-9._-]*)/gmi)].map(m=>m[1]);
37
+ if(ids.length!==1||ids[0]!==taskId)throw error('TASK_DOCUMENT_ID_MISMATCH');
38
+ return real;
39
+ };
40
+ const filePath=()=>join(paths().dir,'task-registry.v1.json');
41
+ const initial=()=>({schemaVersion:1,projects:Object.create(null)});
42
+ const ownedFile=file=>{
43
+ const st=lstatSync(file);
44
+ if(!st.isFile()||st.isSymbolicLink()||(process.getuid&&st.uid!==process.getuid())
45
+ ||process.platform!=='win32'&&(st.mode&0o077))throw error('REGISTRY_UNTRUSTED');
46
+ if(st.size>4*1024*1024)throw error('REGISTRY_TOO_LARGE');
47
+ };
48
+ function load(){
49
+ ensurePrivateDir();
50
+ const file=filePath();
51
+ if(!existsSync(file))return initial();
52
+ ownedFile(file);
53
+ let state;
54
+ try{state=JSON.parse(readFileSync(file,'utf8'));}catch{throw error('REGISTRY_CORRUPT');}
55
+ if(state?.schemaVersion!==1||!state.projects||Array.isArray(state.projects)
56
+ ||typeof state.projects!=='object')throw error('REGISTRY_SCHEMA_MISMATCH');
57
+ return state;
58
+ }
59
+ function withMutation(fn){
60
+ ensurePrivateDir();
61
+ const file=filePath(),lock=file+'.lock';
62
+ let fd;
63
+ try{fd=openSync(lock,'wx',0o600);}
64
+ catch{throw error('REGISTRY_BUSY');}
65
+ try{
66
+ const state=load();
67
+ const result=fn(state);
68
+ if(result.changed){
69
+ const temp=file+'.'+randomUUID()+'.tmp';
70
+ try{
71
+ writeFileSync(temp,JSON.stringify(state,null,2)+'\n',{flag:'wx',mode:0o600});
72
+ renameSync(temp,file);
73
+ }finally{if(existsSync(temp))unlinkSync(temp);}
74
+ }
75
+ return result.value;
76
+ }finally{closeSync(fd);unlinkSync(lock);}
77
+ }
78
+ const fields=(args,allow)=>{
79
+ if(!args||typeof args!=='object'||Array.isArray(args)
80
+ ||Object.keys(args).some(k=>!allow.includes(k)))throw error('INVALID_ARGUMENT');
81
+ };
82
+ const project=(state,projectId)=>{
83
+ if(!goodId(projectId))throw error('INVALID_PROJECT_ID');
84
+ const value=Object.hasOwn(state.projects,projectId)?state.projects[projectId]:null;
85
+ if(!value)throw error('PROJECT_NOT_REGISTERED');
86
+ return value;
87
+ };
88
+ const task=(state,projectId,taskId)=>{
89
+ if(!goodId(taskId))throw error('INVALID_TASK_ID');
90
+ const p=project(state,projectId);
91
+ if(!Object.hasOwn(p.tasks,taskId))throw error('TASK_NOT_FOUND');
92
+ return {p,t:p.tasks[taskId]};
93
+ };
94
+ const roots=p=>[p.projectRoot,...(p.contextRoot?[p.contextRoot]:[])];
95
+ const pathState=(r,path,id=null)=>{
96
+ try{id?taskDoc(r,path,id):authorized(r,path);return 'PRESENT';}
97
+ catch(e){return e.code==='DOCUMENT_MISSING'?'MISSING':'UNVERIFIED';}
98
+ };
99
+ const snapshot=(p,t)=>({
100
+ taskId:t.taskId,projectId:t.projectId,title:t.title,
101
+ taskDocPath:t.taskDocPath,parentTaskId:t.parentTaskId,revision:t.revision,
102
+ taskDocumentState:pathState(roots(p),t.taskDocPath,t.taskId),
103
+ documents:t.documents.map(d=>({...d,sourceStatus:pathState(roots(p),d.sourcePath)}))
104
+ });
105
+ export const taskRegistryTool={
106
+ name:'chat_loop_task_registry',
107
+ description:'Register and locate explicitly scoped long-lived tasks and their real files; no workflow/status/approval or browser authority. Actions: register/get/list/link/unlink/update. Register requires task document containing exact taskId; update/unlink require revision.',
108
+ inputSchema:{type:'object',additionalProperties:false,
109
+ properties:{
110
+ action:{type:'string',enum:['register','get','list','link','unlink','update']},
111
+ projectId:{type:'string',minLength:1,maxLength:128},
112
+ taskId:{type:'string',minLength:1,maxLength:128},
113
+ projectRoot:{type:'string',description:'Explicit verified absolute source root, only on register'},
114
+ contextRoot:{type:'string',description:'Optional independent authorized Context directory, only on first registration'},
115
+ title:{type:'string',maxLength:200},
116
+ taskDocPath:{type:'string'},
117
+ parentTaskId:{type:'string'},
118
+ sourcePath:{type:'string'},
119
+ role:{type:'string',description:'Document kind (e.g. requirement, plan, test, report)'},
120
+ versionRef:{type:'string',description:'Optional source version pointer, not approval'},
121
+ expectedRevision:{type:'integer',minimum:1}
122
+ },required:['action','projectId']}
123
+ };
124
+ export function runTaskRegistry(args){
125
+ const action=args?.action;
126
+ if(!['register','get','list','link','unlink','update'].includes(action))
127
+ throw error('INVALID_ACTION');
128
+ if(action==='register'){
129
+ fields(args,['action','projectId','taskId','projectRoot','contextRoot','title','taskDocPath','parentTaskId']);
130
+ if(!goodId(args.projectId)||!goodId(args.taskId)
131
+ ||!validText(args.title)||!validText(args.taskDocPath,4096))
132
+ throw error('INVALID_ARGUMENT');
133
+ const base=rootOf(args.projectRoot),ctx=args.contextRoot===undefined?null:rootOf(args.contextRoot);
134
+ const doc=taskDoc([base,...(ctx?[ctx]:[])],args.taskDocPath,args.taskId);
135
+ return withMutation(state=>{
136
+ let p=Object.hasOwn(state.projects,args.projectId)?state.projects[args.projectId]:null;
137
+ if(p&&(p.projectRoot!==base||p.contextRoot!==ctx))throw error('PROJECT_BINDING_CONFLICT');
138
+ if(!p){
139
+ p={projectRoot:base,contextRoot:ctx,tasks:Object.create(null)};
140
+ state.projects[args.projectId]=p;
141
+ }
142
+ const parent=args.parentTaskId??null;
143
+ if(parent!==null){
144
+ if(!goodId(parent)||parent===args.taskId)throw error('INVALID_PARENT');
145
+ if(!Object.hasOwn(p.tasks,parent))throw error('PARENT_NOT_FOUND');
146
+ }
147
+ const existing=Object.hasOwn(p.tasks,args.taskId)?p.tasks[args.taskId]:null;
148
+ if(existing){
149
+ if(existing.taskDocPath!==doc||existing.title!==args.title||existing.parentTaskId!==parent)
150
+ throw error('TASK_ID_CONFLICT');
151
+ return {changed:false,value:snapshot(p,existing)};
152
+ }
153
+ const entry={projectId:args.projectId,taskId:args.taskId,title:args.title,
154
+ taskDocPath:doc,parentTaskId:parent,revision:1,documents:[]};
155
+ p.tasks[args.taskId]=entry;
156
+ return {changed:true,value:snapshot(p,entry)};
157
+ });
158
+ }
159
+ if(action==='list'){
160
+ fields(args,['action','projectId']);
161
+ const p=project(load(),args.projectId);
162
+ return {tasks:Object.values(p.tasks).map(t=>snapshot(p,t))};
163
+ }
164
+ if(action==='get'){
165
+ fields(args,['action','projectId','taskId']);
166
+ const {p,t}=task(load(),args.projectId,args.taskId);
167
+ return snapshot(p,t);
168
+ }
169
+ if(action==='link'||action==='unlink'){
170
+ fields(args,['action','projectId','taskId','sourcePath','role',
171
+ ...(action==='link'?['versionRef']:['expectedRevision'])]);
172
+ if(!validText(args.sourcePath,4096)||!ROLE.test(args.role??'related')
173
+ ||action==='link'&&args.versionRef!==undefined&&!validText(args.versionRef,128))
174
+ throw error('INVALID_ARGUMENT');
175
+ return withMutation(state=>{
176
+ const {p,t}=task(state,args.projectId,args.taskId),role=args.role??'related';
177
+ let real;
178
+ if(action==='link')real=authorized(roots(p),args.sourcePath);
179
+ else{
180
+ // A removed/moved source is still detachable by its previously registered path.
181
+ if(typeof args.sourcePath!=='string'||!isAbsolute(args.sourcePath))throw error('INVALID_DOCUMENT_PATH');
182
+ real=args.sourcePath;
183
+ }
184
+ const ix=t.documents.findIndex(d=>d.sourcePath===real&&d.role===role);
185
+ if(action==='link'){
186
+ const versionRef=args.versionRef??null;
187
+ if(ix>=0){
188
+ if(t.documents[ix].versionRef!==versionRef)throw error('DOCUMENT_REF_CONFLICT');
189
+ return {changed:false,value:snapshot(p,t)};
190
+ }
191
+ t.documents.push({sourcePath:real,role,versionRef});
192
+ }else{
193
+ if(!Number.isSafeInteger(args.expectedRevision)||args.expectedRevision!==t.revision)
194
+ throw error('REVISION_CONFLICT');
195
+ if(ix<0)throw error('DOCUMENT_REF_NOT_FOUND');
196
+ t.documents.splice(ix,1);
197
+ }
198
+ t.revision++;
199
+ return {changed:true,value:snapshot(p,t)};
200
+ });
201
+ }
202
+ fields(args,['action','projectId','taskId','expectedRevision','title','taskDocPath']);
203
+ if(!Number.isSafeInteger(args.expectedRevision)
204
+ ||args.title===undefined&&args.taskDocPath===undefined
205
+ ||args.title!==undefined&&!validText(args.title)
206
+ ||args.taskDocPath!==undefined&&!validText(args.taskDocPath,4096))
207
+ throw error('INVALID_ARGUMENT');
208
+ return withMutation(state=>{
209
+ const {p,t}=task(state,args.projectId,args.taskId);
210
+ if(t.revision!==args.expectedRevision)throw error('REVISION_CONFLICT');
211
+ const path=args.taskDocPath===undefined?t.taskDocPath
212
+ :taskDoc(roots(p),args.taskDocPath,t.taskId);
213
+ const title=args.title??t.title;
214
+ if(t.taskDocPath===path&&t.title===title)
215
+ return {changed:false,value:snapshot(p,t)};
216
+ t.taskDocPath=path;
217
+ t.title=title;
218
+ t.revision++;
219
+ return {changed:true,value:snapshot(p,t)};
220
+ });
221
+ }
@@ -0,0 +1,99 @@
1
+ // Scoped read-only MCP exposure. Trace SDK is imported, never spawned as a CLI.
2
+ import {createTraceReader} from '@tomflow/chatloop-trace';
3
+ import {randomUUID} from 'node:crypto';
4
+ import {paths,talk,CONTRACT} from './control.mjs';
5
+
6
+ const PROJECT=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
7
+ const UUID='^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89ab][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$';
8
+ const SESSION='^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$';
9
+ const fail=code=>Object.assign(new Error(code),{code});
10
+ // Until the MCP transport supplies authenticated per-caller identity,
11
+ // accept exactly one Project grant in this Gateway instance.
12
+ export const traceGatewayEnabled=()=>process.env.CHAT_LOOP_TRACE_API_ENABLE==='1'
13
+ &&getAllowedProjects().length===1;
14
+ export const traceDiagnoseTool={
15
+ name:'chat_loop_trace_diagnose',
16
+ description:'Read-only local Trace timeline for one explicitly authorized Project and exact traceId/sessionRef. Shows gaps and unknown receipts; cannot replay actions or grant Browser Owner.',
17
+ inputSchema:{
18
+ type:'object',additionalProperties:false,
19
+ required:['projectRef'],
20
+ properties:{
21
+ projectRef:{type:'string',pattern:PROJECT.source},
22
+ traceId:{type:'string',pattern:UUID},
23
+ sessionRef:{type:'string',pattern:SESSION},
24
+ maxEvents:{type:'integer',minimum:1,maximum:200}
25
+ },
26
+ anyOf:[{required:['traceId']},{required:['sessionRef']}]
27
+ },
28
+ annotations:{readOnlyHint:true}
29
+ };
30
+ const getAllowedProjects=()=>{
31
+ const entries=(process.env.CHAT_LOOP_TRACE_ALLOWED_PROJECTS||'')
32
+ .split(',').map(x=>x.trim());
33
+ // Reject the entire grant on duplicates, extra empty entries or invalid
34
+ // syntax; filtering entries could silently broaden a malformed config.
35
+ return entries.length===1&&PROJECT.test(entries[0])?entries:[];
36
+ };
37
+ export async function runTraceDiagnose(args){
38
+ if(!traceGatewayEnabled())throw fail('TRACE_API_DISABLED');
39
+ if(!args||typeof args!=='object'||Array.isArray(args)||
40
+ Object.keys(args).some(k=>!Object.hasOwn(traceDiagnoseTool.inputSchema.properties,k)))
41
+ throw fail('TRACE_INVALID_ARGUMENT');
42
+ if(typeof args.projectRef!=='string'||!getAllowedProjects().includes(args.projectRef))
43
+ throw fail('TRACE_PROJECT_ACCESS_DENIED');
44
+ const result=await createTraceReader({
45
+ filePath:paths().log,allowedProjects:getAllowedProjects()
46
+ }).diagnose(args);
47
+ try{
48
+ const response=await talk({contract:CONTRACT,action:'__trace_health',
49
+ requestId:randomUUID()},1400);
50
+ result.writerHealth=response.status==='OK'?response.traceHealth?.status||'UNKNOWN':'UNAVAILABLE';
51
+ }catch{result.writerHealth='UNAVAILABLE'}
52
+ if(result.writerHealth!=='OK'){
53
+ result.gaps.push('TRACE_WRITER_UNAVAILABLE');
54
+ result.confidence='INCOMPLETE';
55
+ // An offline / unhealthy writer invalidates any claim that the visible
56
+ // timeline is complete, even when every retained event is CONFIRMED.
57
+ // Only the original authoritative receipt can settle an unknown effect.
58
+ result.retryDisposition='VERIFY_AUTHORITATIVE_RECEIPT_FIRST';
59
+ }
60
+ return result;
61
+ }
62
+
63
+
64
+ // Only normalized Extension CLI receipts may create soft observations.
65
+ // Queuing an intent is not sending; an observed Worker send receipt is never
66
+ // promoted to an independent Native/browser Owner proof.
67
+ export async function observeExtensionResult(name,args,result){
68
+ if(!traceGatewayEnabled()||!['start','status','continue','handoff'].includes(name)
69
+ ||result?.isError)return;
70
+ let proof;
71
+ try{proof=JSON.parse(result?.content?.find(x=>x.type==='text')?.text||'null')}
72
+ catch{return}
73
+ if(!proof||!new RegExp(UUID).test(proof.sessionId||''))return;
74
+ const intent=['continue','handoff'].includes(name);
75
+ if(intent&&(!/^[a-f0-9]{32}$/.test(proof.intentId||'')
76
+ ||!['QUEUED','STATUS'].includes(proof.status)))return;
77
+ const projectRef=proof.projectId||(intent?null:args?.projectId);
78
+ if(!getAllowedProjects().includes(projectRef)||
79
+ args?.projectId&&proof.projectId&&args.projectId!==proof.projectId)return;
80
+ const event=intent
81
+ ?'extension.'+name+(proof.status==='QUEUED'?'.intent.queued':'.receipt.observed')
82
+ :'extension.'+name+'.observed';
83
+ const matchingAction=!proof.actualAction
84
+ ||proof.actualAction===name.toUpperCase();
85
+ const status=intent
86
+ ?proof.status==='QUEUED'?'BEGIN'
87
+ :proof.phase==='SENT_CONFIRMED'&&matchingAction?'CONFIRMED':'UNKNOWN'
88
+ :proof.status==='OK'?'CONFIRMED':'UNKNOWN';
89
+ try{
90
+ await talk({contract:CONTRACT,action:'__trace_observation',
91
+ requestId:randomUUID(),traceId:proof.sessionId,
92
+ projectRef,taskRef:proof.taskId||args?.taskId||null,
93
+ sessionRef:proof.sessionId,generation:proof.generation??null,
94
+ ...(intent?{actionId:proof.intentId,evidenceRef:proof.intentId}:{}),
95
+ event,status},1800);
96
+ }catch{
97
+ // Logging failures never cause the model's original intent to be replayed.
98
+ }
99
+ }
@@ -0,0 +1,204 @@
1
+ # @tomflow/chatloop-context — Context SDK and CLI
2
+
3
+ Independent Context SDK. Method Catalog supports Node >=20; CLI/Core require Node >=24. Chat Loop Tools and other explicitly
4
+ authorized local adapters use the same versioned Method Catalog and SQLite Core.
5
+ This package is not a Chrome controller, HTTP service or background process.
6
+
7
+ ## Project data (target layout, not a production cutover)
8
+
9
+ Each explicitly registered project has one SQLite source of truth:
10
+ ~/.chat-loop/context/<projectId>/context.sqlite
11
+
12
+ Optional artifacts/ and backups/ live beside it; no competing project.json,
13
+ current.md, history.md or handoff.md. The user's source repository and AGENTS.md
14
+ are NOT managed or modified by Context. A project may reference authorized
15
+ Workspace roots via Project.sharedContext.workspaceRefs.
16
+
17
+ ## SDK method disclosure
18
+
19
+ Use:
20
+ chatloop-context methods list --json
21
+ chatloop-context methods describe project.open
22
+
23
+ Both use lib/methods.mjs, the same catalog that generates ChatGPT MCP inputSchema.
24
+ No hidden run.bind/fence/permit controls are exposed as ordinary SDK methods.
25
+
26
+ Example after an approved pinned installation (future release, not yet published):
27
+ npx --yes --offline --package=@tomflow/chatloop-context@0.1.0 chatloop-context methods list --json
28
+
29
+ Requests take one bounded JSON object from stdin and emit one JSON object on
30
+ stdout. Never place credentials or sensitive project bodies in CLI args or logs:
31
+ echo '{"operation":"sdk.methods.list","group":"project"}' | chatloop-context request --json
32
+
33
+ A trusted local adapter supplies CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS and, if
34
+ needed, CHAT_LOOP_CONTEXT_ROOT (default ~/.chat-loop/context) or an explicit
35
+ CHAT_LOOP_CONTEXT_DB solely for existing legacy Store compatibility.
36
+ The comma-separated Project grant is parsed atomically: invalid, empty or
37
+ duplicate IDs reject the whole grant, including in MCP and Native adapters.
38
+ Use project.list/task.list with limit (1–100) and cursor for bounded pages;
39
+ omitting both keeps the legacy array return. A page is not a cross-request
40
+ snapshot; verify revisions when resuming after concurrent writes.
41
+
42
+ ## Reviewed Project registration and Workspace ownership (local operator)
43
+
44
+ The local operator must explicitly enable admin scope, choose the permitted
45
+ Project IDs, and use an **interactive terminal**. The user-reviewed entry
46
+ validates real canonical directories and prompts for an exact action+scope
47
+ confirmation BEFORE creating a Store:
48
+
49
+ CHAT_LOOP_CONTEXT_ADMIN_ENABLE=1 \
50
+ CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS=demo \
51
+ chatloop-context project register demo "Demo project" /confirmed/workspace
52
+
53
+ Additional Workspace roots may be supplied to `register` (up to 16).
54
+ Registration uses a global per-Context-root lock, rejects symlink roots,
55
+ nested/overlapping roots and previously claimed roots, and atomically renames
56
+ a newly staged per-Project SQLite. An existing Project is never overwritten.
57
+
58
+ To replace the **whole** Workspace set on an existing Project, first call
59
+ `project.open` and read its projectRevision and storeEpoch, then explicitly
60
+ run the local operator command (with the same admin grant and TTY confirmation):
61
+
62
+ chatloop-context project bind demo <revision> <storeEpoch> <writeRequestId> /root/a /root/b
63
+ chatloop-context project bind demo <revision> <storeEpoch> <writeRequestId> --clear
64
+
65
+ The second command explicitly clears every Workspace binding. A bind checks
66
+ the original Project identity, CAS revision/epoch, global Project ownership,
67
+ path stability, active execution/Handoff writer fences, then writes one durable
68
+ Core receipt. If the CLI result is lost, use the **same** request ID for a
69
+ read-only operator lookup, never repeat the mutation with a different ID:
70
+
71
+ chatloop-context project receipt demo <storeEpoch> <writeRequestId>
72
+
73
+ The older `project init` remains an explicit *local-admin* compatibility
74
+ command for already approved automated setup; it does **not** itself collect
75
+ a real user-review prompt and must not be offered as the normal first-use flow.
76
+ None of these commands are exposed as ordinary model Context MCP mutations.
77
+ A local TTY/OS-UID operator approval is not cryptographic ChatGPT user
78
+ authentication. Until an independently verified ChatGPT→operator approval
79
+ channel exists, do not claim a completed in-Chat self-service onboarding or
80
+ promote this local workflow into production authorization. None of these
81
+ operations grant Chrome Owner or migrate an existing Legacy Store.
82
+
83
+ ## Offline shared Store extraction (diagnostic ONLY, not a cutover)
84
+
85
+ Before a cutover, use the **read-only** source integrity audit with an explicitly
86
+ granted Project and a verified old Store epoch:
87
+
88
+ CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS=demo \
89
+ chatloop-context project audit-sources demo /private/old/shared.sqlite <sourceEpoch>
90
+
91
+ To inspect a Registry task document that changed since shadow scan, point to
92
+ a verified private Recovery Archive copy of the **original** document:
93
+
94
+ chatloop-context project inspect-reference demo /private/old/shared.sqlite \
95
+ <sourceEpoch> <sourceUnitId> <taskId> /private/archive/task-document.md
96
+
97
+ This is a read-only two-version evidence check: exact Registry SHA and
98
+ task identity, archived document SHA, current document SHA, and a bounded
99
+ insertions-only vs changed-content comparison. It outputs a review-required
100
+ receipt (not a stored approval); `canActivate` and `canExecute` remain false.
101
+ Never rewrite the old Registry to suppress drift.
102
+
103
+ **Reviewed local reconciliation (not SourceUnit activation):** after independently
104
+ reviewing the exact original archive, current document, Project scope and old
105
+ writers, a local terminal operator may run:
106
+
107
+ CHAT_LOOP_CONTEXT_ADMIN_ENABLE=1 CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS=demo \
108
+ chatloop-context project reconcile-reference demo /private/old/shared.sqlite \
109
+ <epoch> <sourceUnitId> <migrationRevision> <taskId> <originalArchiveFile> \
110
+ <currentDocSha256> <operatorReviewRef> <writeRequestId>
111
+
112
+ A real TTY is required and the exact source/old/new hashes and review reference
113
+ must be confirmed. Only insertions-only Task document drift is admitted; other
114
+ content changes need separate review. The Core uses epoch, migration revision
115
+ and durable request receipts, keeps original and current SHA plus original
116
+ archive locator in the SourceUnit, leaves the Registry file unchanged and
117
+ keeps the SourceUnit in SHADOW_RO. It cannot create R/P approvals or Browser
118
+ Owner, or assert the independent old-writer / user-authentication gates.
119
+ For an uncertain result, **query** with the same ID, never resubmit with a new ID:
120
+
121
+ chatloop-context project reconcile-receipt demo /private/old/shared.sqlite \
122
+ <epoch> <writeRequestId>
123
+
124
+ This interface is a local-operator candidate; a TTY under one OS UID is not
125
+ proof of a platform-authenticated ChatGPT user approval, so it MUST NOT be used
126
+ by an autonomous agent to authorize production cutover.
127
+ The audit reads source bytes and Registry-linked Task documents, checks exact
128
+ Project Material hash/path coverage, and distinguishes a changed Registry
129
+ file from drift in a linked task document. It reports mixed CURRENT items
130
+ still requiring human classification, without revealing historical document
131
+ bodies or treating a recovered user Turn as fresh approval. Its `BLOCKED`
132
+ status intentionally includes independent old-writer fencing and release/E2E
133
+ gates that a local file scan cannot prove. It never creates a Store or
134
+ modifies SourceUnits, revisions, permissions, Owner or approvals.
135
+
136
+ **Mixed CURRENT EvidenceOnly classification (local operator only):** when
137
+ the complete, exact historical Markdown bytes are already stored as a
138
+ `LEGACY_UNVERIFIED` Project Material under the canonical source path/hash,
139
+ the operator may explicitly classify a mixed source as historical evidence
140
+ without promoting ANY text to a current Project/Task/R/P fact:
141
+
142
+ CHAT_LOOP_CONTEXT_ADMIN_ENABLE=1 CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS=demo \
143
+ chatloop-context project classify-evidence demo /private/old/shared.sqlite \
144
+ <epoch> <sourceUnitId> <migrationRevision> <sourceSha256> \
145
+ <operatorReviewRef> <writeRequestId>
146
+
147
+ The preflight verifies the physical SourceUnit and the complete stored body,
148
+ and requires exact interactive terminal confirmation. Only the Core's
149
+ `migrationClassify` mutates the SourceUnit manifest with
150
+ `taskContexts=[]`, `projectSharedContext={}` and a reference to the
151
+ entire original content as EvidenceOnly/UNKNOWN; the Unit stays SHADOW_RO.
152
+ This is an intentional human-reviewed historical *disposition*, not a
153
+ claim that the historical statements are current or approved. It does not
154
+ activate a Store, release an old writer, or authorize Chrome Owner.
155
+ For an unknown result use `project migration-receipt` with original epoch and
156
+ writeRequestId. Local TTY is not ChatGPT platform user authentication.
157
+
158
+ An older single SQLite may contain several Projects. Never copy or rename it
159
+ directly into the active per-Project location: doing so leaks unrelated data,
160
+ reuses the old epoch and risks reviving stale runs. The local operator can
161
+ first inspect the legacy Store read-only to obtain the **exact** source
162
+ `storeEpoch` and target `projectRevision`, then, on a separate private
163
+ target root and with explicit real TTY confirmation, use:
164
+
165
+ CHAT_LOOP_CONTEXT_ROOT=/private/review-target \\
166
+ CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS=demo \\
167
+ CHAT_LOOP_CONTEXT_ADMIN_ENABLE=1 \\
168
+ chatloop-context project stage-diagnostic demo /private/old/shared.sqlite <sourceEpoch> <projectRevision>
169
+
170
+ This action reads the source through a SQLite online snapshot, selects ONLY
171
+ the named Project and its scoped rows, retains their exact Task/Material/
172
+ SourceUnit history and old-epoch receipts, then strips runnable leases,
173
+ permits and writer credentials. It vacuums foreign Project content from the
174
+ new database and checks the physical row counts, integrity and ownership
175
+ before atomically publishing the result. A private `migration-diagnostic.json`
176
+ receipt names the old/new epochs and counts but is **not** a second active
177
+ Context authority or a retained full-Store backup.
178
+
179
+ The resulting Project is always `DIAGNOSTIC_ONLY`, with a new epoch,
180
+ `canExecute=false` and `approvalsRevalidated=false`. Old receipts cannot
181
+ replay under the new epoch. No SourceUnit becomes `MANAGED_RW`, and no
182
+ Task/Run, browser Owner or previously observed R/P approval gains authority.
183
+ The source is left untouched. An invalid SourceUnit, unexpected schema,
184
+ stale revision, missing operator approval or existing target fails closed;
185
+ incomplete staging is removed. This command is not exposed through MCP.
186
+
187
+ **Production remains BLOCKED** until the physical source hashes, mixed
188
+ CURRENT ownership, old writers and true operator approval have been reviewed,
189
+ old app/Native/Registry clients fenced, fresh backup plus recovery tested and
190
+ the release/real Chrome E2E gates passed. Do not use this diagnostic receipt
191
+ as cutover authorization. See the P0-02 gate in the existing
192
+ `docs/research/chat-loop-context-cli-architecture-20261109.md`.
193
+
194
+ ## Safety
195
+
196
+ Writes use expectedStoreEpoch, revision CAS and durable writeRequestId.
197
+ Unknown results must be checked with the SAME request ID; never blindly
198
+ resubmit with another ID. Active-run holder controls live outside ordinary
199
+ MCP/CLI mutations in the restricted Worker→Native adapter. An SDK business
200
+ checkpoint never grants Browser Owner. One OS UID is not per-Chat isolation.
201
+
202
+ No serve, Socket, HTTP API, second Tunnel or per-project daemon. The real
203
+ legacy Context and UNKNOWN Chrome Owner remain unchanged until explicit
204
+ migration and recovery approval.