@tomflow/chatloop-tools 0.9.15 → 0.9.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/README.md +2 -1
  2. package/index.mjs +12 -1
  3. package/lib/gateway.mjs +15 -3
  4. package/lib/mcp-tool-router.mjs +50 -3
  5. package/lib/trace-observation.mjs +19 -0
  6. package/node_modules/@tomflow/chatloop-context/README.md +240 -0
  7. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
  8. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
  9. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
  10. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +266 -0
  11. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
  12. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
  13. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
  14. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
  15. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
  16. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
  17. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
  18. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +182 -0
  19. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
  20. package/node_modules/@tomflow/chatloop-context/index.mjs +233 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
  22. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +24 -0
  23. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +1989 -0
  24. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +67 -0
  25. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +280 -0
  26. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
  27. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +280 -0
  28. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +115 -0
  29. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
  30. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +55 -0
  31. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
  32. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
  33. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +147 -0
  34. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +343 -0
  35. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +391 -0
  36. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +166 -0
  37. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
  38. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
  39. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
  40. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +117 -0
  41. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
  42. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +312 -0
  43. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
  44. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
  45. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +115 -0
  46. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +86 -0
  47. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
  48. package/node_modules/@tomflow/chatloop-context/package.json +40 -0
  49. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
  50. package/node_modules/@tomflow/chatloop-extension/README.md +94 -0
  51. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +11 -0
  52. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +141 -0
  53. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +109 -0
  54. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
  55. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
  56. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
  57. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
  58. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
  59. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
  61. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
  62. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +120 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +180 -0
  65. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +322 -0
  66. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
  67. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +378 -0
  68. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
  69. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +54 -0
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +69 -0
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +287 -0
  74. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +23 -0
  75. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
  76. package/node_modules/@tomflow/chatloop-extension/extension/background.js +16 -0
  77. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
  78. package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
  79. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
  80. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
  81. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
  82. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
  83. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
  84. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +76 -0
  85. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
  86. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
  87. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +227 -0
  88. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
  89. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +171 -0
  90. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
  91. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +154 -0
  92. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +254 -0
  93. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +42 -0
  94. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
  95. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +93 -0
  96. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
  97. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
  98. package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
  99. package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
  100. package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
  101. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
  102. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +220 -0
  103. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +122 -0
  104. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +155 -0
  105. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +185 -0
  106. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +120 -0
  107. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +172 -0
  108. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +165 -0
  109. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +244 -0
  110. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +181 -0
  111. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +147 -0
  112. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
  113. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +200 -0
  114. package/node_modules/@tomflow/chatloop-extension/index.mjs +71 -0
  115. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +18 -0
  116. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +74 -0
  117. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +208 -0
  118. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +40 -0
  119. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
  120. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +111 -0
  121. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +67 -0
  122. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +120 -0
  123. package/node_modules/@tomflow/chatloop-extension/package.json +38 -0
  124. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +133 -0
  125. package/node_modules/@tomflow/chatloop-trace/README.md +105 -0
  126. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
  127. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
  128. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
  129. package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
  130. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
  131. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +265 -0
  132. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +205 -0
  133. package/node_modules/@tomflow/chatloop-trace/package.json +30 -0
  134. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
  135. package/node_modules/ps-list/index.d.ts +76 -0
  136. package/node_modules/ps-list/index.js +366 -0
  137. package/node_modules/ps-list/license +9 -0
  138. package/node_modules/ps-list/package.json +44 -0
  139. package/node_modules/ps-list/readme.md +56 -0
  140. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  141. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
  142. package/package.json +23 -8
  143. package/providers/form.mjs +286 -0
  144. package/providers.generated.mjs +3 -2
  145. package/scripts/build-form-app.mjs +27 -0
  146. package/ui/form/review-app.js +128 -0
  147. package/ui/form/review.html +859 -0
  148. package/ui/form/review.template.html +45 -0
@@ -0,0 +1,67 @@
1
+ // Composes capabilities declared in the build manifest, never scans at runtime.
2
+ // Domain methods stay behind the existing Store's authority/CAS/receipt gates.
3
+ // New capability routes use a restricted, project-scoped read-only service port.
4
+ const fail=code=>Object.assign(new Error(code),{code});
5
+ const isObject=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
6
+ const value=(spec,args)=>{
7
+ if(spec==='$args')return args;
8
+ if(typeof spec==='string')return args[spec];
9
+ if(isObject(spec)&&isObject(spec.$object))
10
+ return Object.fromEntries(Object.entries(spec.$object).map(([key,x])=>
11
+ [key,isObject(x)&&typeof x.$field==='string'
12
+ ?args[x.$field]??x.$default
13
+ :x]));
14
+ throw fail('CAPABILITY_ROUTE_PARAMETER_INVALID');
15
+ };
16
+
17
+ export function createCapabilityRouter(definitions,capabilities){
18
+ if(!Array.isArray(definitions)||!Array.isArray(capabilities))
19
+ throw fail('CAPABILITY_REGISTRY_INVALID');
20
+ const registry=new Map();
21
+ for(const cap of capabilities){
22
+ if(!cap||typeof cap.id!=='string'||!Array.isArray(cap.methods))
23
+ throw fail('CAPABILITY_REGISTRY_INVALID');
24
+ for(const entry of cap.methods){
25
+ if(registry.has(entry.id))throw fail('CAPABILITY_METHOD_CONFLICT');
26
+ registry.set(entry.id,{cap,entry});
27
+ }
28
+ }
29
+ if(registry.size!==definitions.length)throw fail('CAPABILITY_MANIFEST_MISMATCH');
30
+ for(const def of definitions){
31
+ const source=registry.get(def.id);
32
+ if(!source||JSON.stringify(source.entry.route)!==JSON.stringify(def.route)
33
+ ||JSON.stringify(source.entry.inputSchema)!==JSON.stringify(def.inputSchema)
34
+ ||source.entry.description!==def.description
35
+ ||source.entry.mode!==def.mode||source.entry.group!==def.group)
36
+ throw fail('CAPABILITY_MANIFEST_MISMATCH');
37
+ }
38
+ return Object.freeze({
39
+ execute(method,args,services){
40
+ const source=registry.get(method?.id);
41
+ if(!source||source.entry.mode!==method.mode)
42
+ throw fail('CAPABILITY_METHOD_UNKNOWN');
43
+ const route=method.route;
44
+ if(route.kind==='core'){
45
+ const fn=services?.db?.[route.method];
46
+ if(typeof fn!=='function')throw fail('CAPABILITY_CORE_PROVIDER_MISSING');
47
+ return Reflect.apply(fn,services.db,
48
+ route.params.map(param=>value(param,args)));
49
+ }
50
+ if(route.kind==='module'){
51
+ if(method.mode!=='read'||typeof source.cap.execute!=='function'
52
+ ||args.projectId!==services?.projectRef)
53
+ throw fail('CAPABILITY_PERMISSION_DENIED');
54
+ const read=Object.freeze({
55
+ projectRef:args.projectId,
56
+ // No raw DB handle, credential, CAS mutation or cross-project lookup.
57
+ material:(materialId,version)=>
58
+ services.db.projectMaterialGet(args.projectId,materialId,version),
59
+ document:(taskId,documentId,version)=>
60
+ services.db.documentGet(args.projectId,taskId,documentId,version)
61
+ });
62
+ return source.cap.execute(method.id,args,read);
63
+ }
64
+ throw fail('CAPABILITY_ADAPTER_ROUTE_REQUIRED');
65
+ }
66
+ });
67
+ }
@@ -0,0 +1,280 @@
1
+ // CLI command implementation: no imports from other internal modules.
2
+ // Only bin/cli.mjs exports a shell command. index.mjs supplies scoped API
3
+ // dependencies; local admin/SQLite safety gates remain in their owners.
4
+ import {randomUUID,createHash} from 'node:crypto';
5
+ import {existsSync,mkdirSync,mkdtempSync,renameSync,rmSync} from 'node:fs';
6
+ import {join} from 'node:path';
7
+
8
+ const fail=code=>Object.assign(new Error(code),{code});
9
+ let openContextProtocol,contextRoot,allowedProjects,
10
+ verifySourceUnit,createProjectDiagnosticBranch,createManagedProjectBranch,
11
+ fenceLegacyProjectStore,auditLegacyProjectSources,inspectLegacyRegistryReference,
12
+ activeLegacyWriters,fenceOrphanRunOperator,canonicalWorkspaceRefs,
13
+ confirmWorkspaceOperator,assertWorkspaceUnclaimed,withWorkspaceRegistryLock,
14
+ rebindProjectWorkspaces,readOperatorWorkspaceReceipt,runContextCli,
15
+ requestContext,listMethods,describeMethod,CONTEXT_PACKAGE_VERSION;
16
+ let connected=false;
17
+ export function configureCliCommands(api){
18
+ if(connected)throw Error('CONTEXT_MODULE_ALREADY_COMPOSED');
19
+ const names=['openContextProtocol','contextRoot','allowedProjects',
20
+ 'verifySourceUnit','createProjectDiagnosticBranch','createManagedProjectBranch',
21
+ 'fenceLegacyProjectStore','auditLegacyProjectSources',
22
+ 'inspectLegacyRegistryReference','activeLegacyWriters',
23
+ 'fenceOrphanRunOperator','canonicalWorkspaceRefs',
24
+ 'confirmWorkspaceOperator','assertWorkspaceUnclaimed','withWorkspaceRegistryLock',
25
+ 'rebindProjectWorkspaces','readOperatorWorkspaceReceipt','runContextCli',
26
+ 'requestContext','listMethods','describeMethod','CONTEXT_PACKAGE_VERSION'];
27
+ for(const name of names)
28
+ if(api?.[name]===undefined)throw Error('CONTEXT_MODULE_PORT_MISSING:'+name);
29
+ ({openContextProtocol,contextRoot,allowedProjects,
30
+ verifySourceUnit,createProjectDiagnosticBranch,createManagedProjectBranch,
31
+ fenceLegacyProjectStore,auditLegacyProjectSources,inspectLegacyRegistryReference,
32
+ activeLegacyWriters,fenceOrphanRunOperator,canonicalWorkspaceRefs,
33
+ confirmWorkspaceOperator,assertWorkspaceUnclaimed,withWorkspaceRegistryLock,
34
+ rebindProjectWorkspaces,readOperatorWorkspaceReceipt,runContextCli,
35
+ requestContext,listMethods,describeMethod,CONTEXT_PACKAGE_VERSION}=api);
36
+ connected=true;
37
+ }
38
+
39
+ async function registerProject(projectId,title,workspaces=[],reviewed=false){
40
+ if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
41
+ if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
42
+ if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(projectId))throw fail('INVALID_SCOPE');
43
+ if(typeof title!=='string'||!title.trim()||title.length>200)throw fail('INVALID_TITLE');
44
+ if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
45
+ const refs=canonicalWorkspaceRefs(workspaces,{allowEmpty:!reviewed});
46
+ const root=contextRoot(),final=join(root,projectId);
47
+ if(existsSync(final))throw fail('PROJECT_EXISTS');
48
+ // The user-reviewed entry never creates a Store (or even a directory)
49
+ // before the local operator confirms the exact canonical roots.
50
+ if(reviewed)await confirmWorkspaceOperator('REGISTER',projectId,0,refs);
51
+ mkdirSync(root,{recursive:true,mode:0o700});
52
+ return withWorkspaceRegistryLock(root,()=>{
53
+ let tmp;
54
+ try{
55
+ if(existsSync(final))throw fail('PROJECT_EXISTS');
56
+ if(reviewed){
57
+ const current=canonicalWorkspaceRefs(workspaces);
58
+ if(JSON.stringify(current)!==JSON.stringify(refs))throw fail('WORKSPACE_CHANGED');
59
+ assertWorkspaceUnclaimed(root,projectId,refs);
60
+ }
61
+ tmp=mkdtempSync(join(root,'.register-'));
62
+ const db=openContextProtocol(join(tmp,'context.sqlite'),{
63
+ allowCreate:true,authorizeData:()=>true,principalId:'local-operator'});
64
+ let result;
65
+ try{
66
+ result=db.projectCreate({projectId,title,sharedContext:{workspaceRefs:refs},
67
+ expectedStoreEpoch:db.epoch,writeRequestId:randomUUID()});
68
+ }finally{db.close()}
69
+ renameSync(tmp,final);tmp=null;
70
+ return {...result,workspaceRefs:refs,projectDirectory:final};
71
+ }finally{
72
+ // Incomplete staging is diagnostic only, never silently promoted.
73
+ if(tmp)rmSync(tmp,{recursive:true,force:true});
74
+ }
75
+ });
76
+ }
77
+ export async function runLocalCliCommand(args,readJson){
78
+ const [command,sub,...rest]=args;
79
+ let value;
80
+ if(command==='methods'&&sub==='list'&&rest.length<=1)
81
+ value=await requestContext({operation:'sdk.methods.list',
82
+ ...(rest[0]&&rest[0]!=='--json'?{group:rest[0]}:{})});
83
+ else if(command==='methods'&&sub==='groups'&&rest.length<=1)
84
+ value=await requestContext({operation:'sdk.methods.list',view:'groups',
85
+ ...(rest[0]?{group:rest[0]}:{})});
86
+ else if(command==='methods'&&sub==='describe'&&rest.length===1)
87
+ value=await requestContext({operation:'sdk.methods.describe',methodId:rest[0]});
88
+ else if(command==='admin'&&sub){
89
+ value=await runContextCli([sub,...rest]);
90
+ }
91
+ else if(command==='request'&&sub==='--json'&&rest.length===0){
92
+ const payload=await readJson();
93
+ if(!payload||typeof payload!=='object'||Array.isArray(payload))throw fail('INVALID_ARGUMENT');
94
+ value=await requestContext(payload);
95
+ }else if(command==='task'&&sub==='fence-orphan'&&rest.length===10){
96
+ const [projectId,taskId,expectedRunRef,revision,bindingRevision,
97
+ expectedStoreEpoch,evidenceDocumentId,evidenceVersion,evidenceHash,
98
+ writeRequestId]=rest;
99
+ value=await fenceOrphanRunOperator({projectId,taskId,expectedRunRef,
100
+ expectedTaskRevision:Number(revision),
101
+ expectedBindingRevision:Number(bindingRevision),
102
+ expectedStoreEpoch,evidenceDocumentId,
103
+ evidenceVersion:Number(evidenceVersion),evidenceHash,writeRequestId});
104
+ }else if(command==='task'&&sub==='orphan-receipt'&&rest.length===3){
105
+ const [projectId,storeEpoch,writeRequestId]=rest;
106
+ if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
107
+ if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
108
+ const file=join(contextRoot(),projectId,'context.sqlite');
109
+ const db=openContextProtocol(file,{readOnly:true,principalId:'local-operator',
110
+ authorizeData:(_mode,p)=>p===projectId});
111
+ try{value=db.requestStatus({projectId,storeEpoch,writeRequestId})}
112
+ finally{db.close()}
113
+ }else if(command==='project'&&sub==='init'&&(rest.length===2||rest.length===3))
114
+ value=await registerProject(rest[0],rest[1],rest.slice(2));
115
+ else if(command==='project'&&sub==='register'&&rest.length>=3&&rest.length<=18)
116
+ value=await registerProject(rest[0],rest[1],rest.slice(2),true);
117
+ else if(command==='project'&&sub==='bind'&&rest.length>=4&&rest.length<=20){
118
+ const [projectId,revision,epoch,requestId,...paths]=rest;
119
+ if(paths.length===1&&paths[0]==='--clear')paths.length=0;
120
+ value=await rebindProjectWorkspaces({projectId,
121
+ expectedProjectRevision:Number(revision),expectedStoreEpoch:epoch,
122
+ writeRequestId:requestId,workspaces:paths});
123
+ }else if(command==='project'&&sub==='receipt'&&rest.length===3)
124
+ value=await readOperatorWorkspaceReceipt({projectId:rest[0],
125
+ storeEpoch:rest[1],writeRequestId:rest[2]});
126
+ else if(command==='project'&&sub==='reconcile-reference'&&rest.length===10){
127
+ const [projectId,sourceDb,expectedStoreEpoch,sourceUnitId,revision,
128
+ taskId,originalArchivePath,expectedCurrentHash,reviewRef,writeRequestId]=rest;
129
+ if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
130
+ if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
131
+ if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
132
+ const expectedMigrationRevision=Number(revision);
133
+ if(!Number.isSafeInteger(expectedMigrationRevision)||expectedMigrationRevision<1)
134
+ throw fail('MIGRATION_VERSION_CONFLICT');
135
+ // Fail closed before any writable handle exists. Review is NOT user R/P.
136
+ const evidence=inspectLegacyRegistryReference({sourceDb,projectId,
137
+ expectedStoreEpoch,sourceUnitId,taskId,archiveFile:originalArchivePath});
138
+ if(evidence.changeKind!=='INSERTIONS_ONLY'||
139
+ evidence.currentTaskHash!==expectedCurrentHash)
140
+ throw fail('REGISTRY_REFERENCE_VERSION_CONFLICT');
141
+ await confirmWorkspaceOperator('RECONCILE_REFERENCE',projectId,
142
+ expectedMigrationRevision,[sourceDb,sourceUnitId,taskId,
143
+ evidence.archivedTaskHash,expectedCurrentHash,reviewRef]);
144
+ const db=openContextProtocol(sourceDb,{principalId:'local-operator',
145
+ authorizeData:(_mode,p)=>p===projectId,
146
+ authorizeAdmin:(op,p)=>p===projectId&&[
147
+ 'migration.reference.reconcile',
148
+ 'migration.reference.reconcile.reviewed'].includes(op)});
149
+ try{
150
+ value=db.migrationReconcileReference({projectId,sourceUnitId,
151
+ expectedMigrationRevision,expectedStoreEpoch,writeRequestId,
152
+ taskId,originalArchivePath,expectedCurrentHash,
153
+ sourceHash:evidence.sourceHash,reviewRef});
154
+ }finally{db.close()}
155
+ }else if(command==='project'&&sub==='migration-receipt'&&rest.length===4){
156
+ const [projectId,sourceDb,storeEpoch,writeRequestId]=rest;
157
+ if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
158
+ const db=openContextProtocol(sourceDb,{readOnly:true,
159
+ principalId:'local-operator',
160
+ authorizeData:(_mode,p)=>p===projectId});
161
+ try{value=db.requestStatus({projectId,storeEpoch,writeRequestId})}
162
+ finally{db.close()}
163
+ }else if(command==='project'&&sub==='classify-evidence'&&rest.length===8){
164
+ const [projectId,sourceDb,expectedStoreEpoch,sourceUnitId,revision,
165
+ sourceHash,reviewRef,writeRequestId]=rest;
166
+ if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
167
+ if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
168
+ if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
169
+ const expectedMigrationRevision=Number(revision);
170
+ if(!Number.isSafeInteger(expectedMigrationRevision)||expectedMigrationRevision<1)
171
+ throw fail('MIGRATION_VERSION_CONFLICT');
172
+ if(typeof reviewRef!=='string'||reviewRef.length<8||reviewRef.length>256)
173
+ throw fail('REVIEW_REFERENCE_REQUIRED');
174
+ // The historical body's original bytes must already be a matching
175
+ // LEGACY_UNVERIFIED Project Material, never a synthesized current Task.
176
+ const reader=openContextProtocol(sourceDb,{readOnly:true,
177
+ principalId:'local-operator',authorizeData:(_mode,p)=>p===projectId,
178
+ authorizeAdmin:(op,p)=>op==='migration.list'&&p===projectId});
179
+ let unit;
180
+ try{
181
+ if(reader.mode!=='ACTIVE')throw fail('STORE_DIAGNOSTIC_ONLY');
182
+ if(reader.epoch!==expectedStoreEpoch)throw fail('STALE_EPOCH');
183
+ unit=reader.migrationList(projectId).find(x=>x.sourceUnitId===sourceUnitId);
184
+ if(!unit||unit.status!=='SHADOW_RO'||
185
+ unit.manifest.sourceKind!=='MIXED_CONTEXT')
186
+ throw fail('MIXED_SOURCE_NOT_SHADOW');
187
+ if(unit.migrationRevision!==expectedMigrationRevision)
188
+ throw fail('MIGRATION_VERSION_CONFLICT');
189
+ if(unit.sourceHash!==sourceHash)throw fail('SOURCE_CHANGED');
190
+ verifySourceUnit(unit.manifest);
191
+ const material=reader.projectMaterialList(projectId).filter(m=>
192
+ m.sourcePath===unit.sourcePath&&m.contentHash===sourceHash&&
193
+ m.provenance==='LEGACY_UNVERIFIED');
194
+ if(!material.some(m=>createHash('sha256').update(
195
+ reader.projectMaterialGet(projectId,m.materialId,m.version).body
196
+ ).digest('hex')===sourceHash))throw fail('MIGRATION_BODY_NOT_IMPORTED');
197
+ }finally{reader.close()}
198
+ // Human-reviewed disposition: preserve FULL mixed history as
199
+ // EvidenceOnly/UNKNOWN. Do not assert any current Task or R/P fact.
200
+ await confirmWorkspaceOperator('CLASSIFY_EVIDENCE_ONLY',projectId,
201
+ expectedMigrationRevision,[sourceDb,sourceUnitId,sourceHash,reviewRef]);
202
+ const db=openContextProtocol(sourceDb,{principalId:'local-operator',
203
+ authorizeData:(_mode,p)=>p===projectId,
204
+ authorizeAdmin:(op,p)=>p===projectId&&
205
+ ['migration.classify','migration.classify.reviewed'].includes(op)});
206
+ try{
207
+ value=db.migrationClassify({projectId,sourceUnitId,sourceHash,
208
+ expectedStoreEpoch,expectedMigrationRevision,writeRequestId,
209
+ classification:{projectId,sourceUnitId,sourceHash,
210
+ currentFactsComplete:true,reviewRef,taskContexts:[],
211
+ projectSharedContext:{},
212
+ unknownHistoryRefs:[{locator:unit.sourcePath,sourceHash}]}});
213
+ }finally{db.close()}
214
+ }else if(command==='project'&&sub==='inspect-reference'&&rest.length===6){
215
+ const [projectId,sourceDb,expectedStoreEpoch,sourceUnitId,taskId,archiveFile]=rest;
216
+ if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
217
+ value=inspectLegacyRegistryReference({projectId,sourceDb,
218
+ expectedStoreEpoch,sourceUnitId,taskId,archiveFile});
219
+ }else if(command==='project'&&sub==='audit-sources'&&rest.length===3){
220
+ const [projectId,sourceDb,expectedStoreEpoch]=rest;
221
+ if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
222
+ value=auditLegacyProjectSources({projectId,sourceDb,expectedStoreEpoch});
223
+ // Observe known, supported MCP writers without claiming an independent
224
+ // old-writer fence. Only PIDs are returned, never process argv or secrets.
225
+ let writerObservation;
226
+ try{
227
+ const pids=await activeLegacyWriters();
228
+ writerObservation={status:pids.length?'MATCHED':'NO_SUPPORTED_PROCESS_MATCH',pids};
229
+ }catch{writerObservation={status:'UNVERIFIED',pids:[]}}
230
+ value={...value,supportedWriterObservation:writerObservation};
231
+ }else if(command==='project'&&sub==='seal-source'&&rest.length===6){
232
+ const [projectId,sourceDb,epoch,revision,backupPath,sealManifestPath]=rest;
233
+ if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
234
+ if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
235
+ if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
236
+ const expectedProjectRevision=Number(revision);
237
+ if(!Number.isSafeInteger(expectedProjectRevision)||expectedProjectRevision<1)
238
+ throw fail('PROJECT_VERSION_CONFLICT');
239
+ await confirmWorkspaceOperator('SEAL_SOURCE',projectId,
240
+ expectedProjectRevision,[sourceDb,epoch,backupPath,sealManifestPath]);
241
+ value=await fenceLegacyProjectStore({sourceDb,projectId,
242
+ expectedStoreEpoch:epoch,expectedProjectRevision,backupPath,sealManifestPath});
243
+ }else if(command==='project'&&sub==='publish-managed'&&rest.length===6){
244
+ const [projectId,sourceDb,epoch,revision,sealManifest,expectedSealHash]=rest;
245
+ if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
246
+ if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
247
+ if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
248
+ const expectedProjectRevision=Number(revision);
249
+ if(!Number.isSafeInteger(expectedProjectRevision)||expectedProjectRevision<1)
250
+ throw fail('PROJECT_VERSION_CONFLICT');
251
+ await confirmWorkspaceOperator('PUBLISH_MANAGED',projectId,
252
+ expectedProjectRevision,[sourceDb,epoch,sealManifest,expectedSealHash]);
253
+ const root=contextRoot();
254
+ mkdirSync(root,{recursive:true,mode:0o700});
255
+ value=await withWorkspaceRegistryLock(root,()=>createManagedProjectBranch({
256
+ sourceDb,targetRoot:root,projectId,expectedStoreEpoch:epoch,
257
+ expectedProjectRevision,sealManifest,expectedSealHash
258
+ }));
259
+ }else if(command==='project'&&sub==='stage-diagnostic'&&rest.length===4){
260
+ const [projectId,sourceDb,expectedStoreEpoch,revision]=rest;
261
+ if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
262
+ if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
263
+ if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
264
+ const expectedProjectRevision=Number(revision);
265
+ if(!Number.isSafeInteger(expectedProjectRevision)||expectedProjectRevision<1)
266
+ throw fail('PROJECT_VERSION_CONFLICT');
267
+ // This is an offline diagnostic extract; NEVER a source cutover.
268
+ // The operator must review the exact source path and source CAS identity.
269
+ await confirmWorkspaceOperator('STAGE_DIAGNOSTIC',projectId,
270
+ expectedProjectRevision,[sourceDb,expectedStoreEpoch]);
271
+ const root=contextRoot();
272
+ mkdirSync(root,{recursive:true,mode:0o700});
273
+ value=await withWorkspaceRegistryLock(root,()=>createProjectDiagnosticBranch({
274
+ sourceDb,targetRoot:root,projectId,expectedStoreEpoch,expectedProjectRevision
275
+ }));
276
+ }else if(command==='doctor'&&sub==='--json'&&rest.length===0)
277
+ value={status:'READY',packageVersion:CONTEXT_PACKAGE_VERSION,projectRoot:contextRoot()};
278
+ else throw fail('UNKNOWN_COMMAND');
279
+ return value;
280
+ }
@@ -0,0 +1,298 @@
1
+ // Local-only Context Manager administration. Never exposed through MCP tools.
2
+ // Activation requires explicit terminal operator consent and known-writer check.
3
+ // This is a SAME-UID trust boundary, not a proof of ChatGPT user identity.
4
+ import {realpathSync,existsSync,lstatSync,readFileSync} from 'node:fs';
5
+ import {randomUUID,createHash} from 'node:crypto';
6
+ import {createInterface} from 'node:readline/promises';
7
+ import {isAbsolute,resolve} from 'node:path';
8
+ import {DatabaseSync} from 'node:sqlite';
9
+ // This module declares ports; index.mjs is the only dependency assembler.
10
+ // No implementation module imports another implementation module.
11
+ let activeLegacyWriters, openContextProtocol, parseContextAllowedProjects, scanSourceUnit, saveShadowManifest, readShadowManifest, verifyShadowManifest, backupContextDb, createRecoveryManifest, restoreBackupToDiagnosticBranch;
12
+ let connected=false;
13
+ export function configureContextAdmin(capabilities){
14
+ if(connected)throw Error('CONTEXT_MODULE_ALREADY_COMPOSED');
15
+ for(const name of ['activeLegacyWriters', 'openContextProtocol', 'parseContextAllowedProjects', 'scanSourceUnit', 'saveShadowManifest', 'readShadowManifest', 'verifyShadowManifest', 'backupContextDb', 'createRecoveryManifest', 'restoreBackupToDiagnosticBranch']){
16
+ if(capabilities?.[name]===undefined)throw Error('CONTEXT_MODULE_PORT_MISSING:'+name);
17
+ }
18
+ ({activeLegacyWriters, openContextProtocol, parseContextAllowedProjects, scanSourceUnit, saveShadowManifest, readShadowManifest, verifyShadowManifest, backupContextDb, createRecoveryManifest, restoreBackupToDiagnosticBranch}=capabilities);
19
+ connected=true;
20
+ }
21
+
22
+ const fail=code=>Object.assign(new Error(code),{code});
23
+ const hash=x=>createHash('sha256').update(x).digest('hex');
24
+ const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
25
+ const allowed=()=>parseContextAllowedProjects(process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS);
26
+ const verified=(projectId)=>{if(!allowed().has(projectId)||!ID.test(projectId||''))
27
+ throw fail('PROJECT_NOT_AUTHORIZED')};
28
+ async function operatorConfirm(expected){
29
+ if(!process.stdin.isTTY||!process.stdout.isTTY)throw fail('OPERATOR_TTY_REQUIRED');
30
+ const rl=createInterface({input:process.stdin,output:process.stdout});
31
+ try{
32
+ const answer=await rl.question('Confirm local Context cutover by typing '+expected+': ');
33
+ if(answer!==expected)throw fail('OPERATOR_CONFIRMATION_MISMATCH');
34
+ }finally{rl.close()}
35
+ }
36
+
37
+ const open=(allowCreate=false)=>openContextProtocol(process.env.CHAT_LOOP_CONTEXT_DB,{
38
+ allowCreate,
39
+ principalId:'local-operator',
40
+ authorizeData:(_,p)=>allowed().has(p),
41
+ authorizeAdmin:()=>true
42
+ });
43
+ const readBytes=(file)=>{
44
+ const st=lstatSync(file);
45
+ if(!st.isFile()||st.isSymbolicLink())throw fail('SOURCE_UNTRUSTED');
46
+ return readFileSync(file);
47
+ };
48
+ const readOperatorReview=(file)=>{
49
+ if(!isAbsolute(file))throw fail('REVIEW_PATH_INVALID');
50
+ const st=lstatSync(file);
51
+ if(!st.isFile()||st.isSymbolicLink()||(st.mode&0o077)
52
+ ||(process.getuid&&st.uid!==process.getuid())
53
+ ||st.size===0||st.size>1024*1024)throw fail('REVIEW_FILE_UNTRUSTED');
54
+ let reviewed;
55
+ try{reviewed=JSON.parse(readFileSync(file,'utf8'))}
56
+ catch{throw fail('REVIEW_FILE_INVALID')}
57
+ return reviewed;
58
+ };
59
+ const write=(a,o={})=>({projectId:a.projectId,expectedStoreEpoch:o.epoch,
60
+ writeRequestId:randomUUID(),...a});
61
+ export async function runContextCli(argv,{confirm=operatorConfirm}={}){
62
+ if(Number(process.versions.node.split('.')[0])<24)throw fail('CONTEXT_RUNTIME_UNSUPPORTED');
63
+ if(!process.env.CHAT_LOOP_CONTEXT_DB||!isAbsolute(process.env.CHAT_LOOP_CONTEXT_DB))
64
+ throw fail('CONTEXT_DB_NOT_CONFIGURED');
65
+ allowed(); // Reject malformed or ambiguous grants before all admin actions.
66
+ const [action,...params]=argv;
67
+ if(action==='doctor'){
68
+ if(params.length)throw fail('INVALID_ARGUMENT');
69
+ const db=open();
70
+ try{return {status:'INSPECTED',...db.integrity(),pragmas:db.pragmas()}}
71
+ finally{db.close()}
72
+ }
73
+ if(action==='init'){
74
+ if(params.length)throw fail('INVALID_ARGUMENT');
75
+ const db=open(true);
76
+ try{return {status:'READY',storeEpoch:db.epoch,pragmas:db.pragmas()}}
77
+ finally{db.close()}
78
+ }
79
+ if(action==='scan'){
80
+ if(params.length!==4)throw fail('INVALID_ARGUMENT');
81
+ const [projectId,kind,path,manifestPath]=params;
82
+ verified(projectId);
83
+ const source=scanSourceUnit({projectId,kind,sourcePath:path});
84
+ const manifest=saveShadowManifest(manifestPath,[source]);
85
+ return {status:'SHADOW_RO',sourceUnit:source,manifestPath,
86
+ manifestId:manifest.instanceLineage};
87
+ }
88
+ if(action==='backup'){
89
+ if(params.length!==1)throw fail('INVALID_ARGUMENT');
90
+ const db=open(),target=params[0];db.close();
91
+ const raw=new DatabaseSync(process.env.CHAT_LOOP_CONTEXT_DB);
92
+ try{return await backupContextDb(raw,target)}
93
+ finally{raw.close()}
94
+ }
95
+ if(action==='restore-branch'){
96
+ if(params.length!==4)throw fail('INVALID_ARGUMENT');
97
+ const [backupFile,targetDb,expectedBackupHash,manifestFile]=params;
98
+ // Recovery branch creation never imports Browser Owner and never opens
99
+ // this branch for business writes until reauthorization/reconciliation.
100
+ await confirm('RESTORE_DIAGNOSTIC '+targetDb);
101
+ return restoreBackupToDiagnosticBranch({
102
+ backupFile,targetDb,expectedBackupHash,manifestFile});
103
+ }
104
+ if(action==='project-create'){
105
+ if(params.length!==2)throw fail('INVALID_ARGUMENT');
106
+ const [projectId,title]=params;verified(projectId);
107
+ const db=open();
108
+ try{return db.projectCreate(write({projectId,title},{epoch:db.epoch}))}
109
+ finally{db.close()}
110
+ }
111
+ if(action==='shadow'){
112
+ if(params.length!==2)throw fail('INVALID_ARGUMENT');
113
+ const [projectId,manifestPath]=params;verified(projectId);
114
+ const manifest=readShadowManifest(manifestPath);
115
+ if(manifest.sourceUnits.length!==1)throw fail('ONE_SOURCE_UNIT_REQUIRED');
116
+ const one=manifest.sourceUnits[0];
117
+ if(one.projectId!==projectId)throw fail('PROJECT_MISMATCH');
118
+ verifyShadowManifest(manifestPath);
119
+ const db=open();
120
+ try{return db.migrationShadow(write({projectId,...one,manifest:one},{epoch:db.epoch}))}
121
+ finally{db.close()}
122
+ }
123
+ if(action==='status'){
124
+ if(params.length!==1)throw fail('INVALID_ARGUMENT');
125
+ const projectId=params[0];verified(projectId);
126
+ const db=open();
127
+ try{
128
+ const sourceUnits=db.migrationList(projectId);
129
+ const materials=db.projectMaterialList(projectId);
130
+ const project=db.projectGet(projectId);
131
+ const tasks=db.taskList(projectId);
132
+ return {status:'OK',projectId,storeMode:db.mode,
133
+ projectRevision:project.projectRevision,
134
+ authority:db.registryAuthority(projectId),
135
+ businessAuthority:db.projectBusinessAuthority(projectId),
136
+ // Registry authority is NOT the authority of every physical SourceUnit.
137
+ sourceUnits,materialCount:materials.length,materials,
138
+ taskCount:tasks.length,taskRefs:tasks.map(t=>({taskId:t.taskId,
139
+ taskRevision:t.taskRevision}))};
140
+ }
141
+ finally{db.close()}
142
+ }
143
+ if(action==='classify'){
144
+ if(params.length!==3)throw fail('INVALID_ARGUMENT');
145
+ const [projectId,manifestPath,reviewPath]=params;verified(projectId);
146
+ verifyShadowManifest(manifestPath);
147
+ const manifest=readShadowManifest(manifestPath);
148
+ if(manifest.sourceUnits.length!==1)throw fail('ONE_SOURCE_UNIT_REQUIRED');
149
+ const unit=manifest.sourceUnits[0];
150
+ if(unit.projectId!==projectId||unit.sourceKind!=='MIXED_CONTEXT')
151
+ throw fail('MIXED_SOURCE_REQUIRED');
152
+ const classification=readOperatorReview(reviewPath);
153
+ const db=open();
154
+ try{
155
+ const stage=db.migrationList(projectId).find(r=>r.sourceUnitId===unit.sourceUnitId);
156
+ if(stage?.status!=='SHADOW_RO')throw fail('MIGRATION_STAGE_MISMATCH');
157
+ if(stage.sourceHash!==unit.sourceHash)throw fail('SOURCE_CHANGED');
158
+ // The operator reviews exactly one physical source and its full
159
+ // EvidenceOnly reference; this does NOT certify historical authorship.
160
+ await confirm('CLASSIFY '+projectId+' '+unit.sourceUnitId);
161
+ verifyShadowManifest(manifestPath);
162
+ return db.migrationClassify(write({
163
+ projectId,sourceUnitId:unit.sourceUnitId,sourceHash:unit.sourceHash,
164
+ expectedMigrationRevision:stage.migrationRevision,classification
165
+ },{epoch:db.epoch}));
166
+ }finally{db.close()}
167
+ }
168
+ if(action==='import-sources'){
169
+ if(params.length!==2)throw fail('INVALID_ARGUMENT');
170
+ const [projectId,reviewPath]=params;verified(projectId);
171
+ const review=readOperatorReview(reviewPath);
172
+ if(review?.projectId!==projectId||!Array.isArray(review.materials)
173
+ ||review.materials.length<1||review.materials.length>128)
174
+ throw fail('SOURCE_IMPORT_REVIEW_INVALID');
175
+ const root=realpathSync(review.sourceRoot);
176
+ const seen=new Set();
177
+ // Hash-check the FULL bytes before prompting. Never infer R/P approvals,
178
+ // task identities or an active checkpoint from legacy Markdown.
179
+ const materials=review.materials.map(item=>{
180
+ if(typeof item.materialId!=='string'||!ID.test(item.materialId)
181
+ ||seen.has(item.materialId)||!['INSTRUCTIONS','HISTORY','LEGACY_EVIDENCE','REFERENCE'].includes(item.kind)
182
+ ||typeof item.path!=='string'||!isAbsolute(item.path)
183
+ ||typeof item.sha256!=='string'||!/^[a-f0-9]{64}$/.test(item.sha256))
184
+ throw fail('SOURCE_IMPORT_REVIEW_INVALID');
185
+ seen.add(item.materialId);
186
+ const original=realpathSync(item.path);
187
+ if(!original.startsWith(root+'/'))throw fail('SOURCE_OUTSIDE_ROOT');
188
+ const bytes=readBytes(item.path);
189
+ if(bytes.length>4*1024*1024)throw fail('SOURCE_TOO_LARGE');
190
+ if(hash(bytes)!==item.sha256)throw fail('SOURCE_CHANGED');
191
+ const body=bytes.toString('utf8');
192
+ if(!Buffer.from(body,'utf8').equals(bytes))throw fail('SOURCE_NOT_UTF8');
193
+ return {materialId:item.materialId,kind:item.kind,body,
194
+ contentHash:item.sha256,sourcePath:original};
195
+ });
196
+ const db=open();
197
+ try{
198
+ const before=db.projectMaterialList(projectId);
199
+ for(const item of materials){
200
+ const prev=before.find(v=>v.materialId===item.materialId&&v.version===1);
201
+ if(prev && (prev.contentHash!==item.contentHash||prev.kind!==item.kind
202
+ ||prev.sourcePath!==item.sourcePath))
203
+ throw fail('IMPORTED_SOURCE_CONFLICT');
204
+ }
205
+ await confirm('IMPORT_SOURCES '+projectId);
206
+ // The operator may spend time reviewing the manifest. Ensure no source
207
+ // changed between preflight and the first durable Store mutation.
208
+ for(const item of materials)
209
+ if(hash(readBytes(item.sourcePath))!==item.contentHash)
210
+ throw fail('SOURCE_CHANGED');
211
+ const imported=[];
212
+ for(const item of materials){
213
+ const prior=db.projectMaterialList(projectId)
214
+ .find(v=>v.materialId===item.materialId&&v.version===1);
215
+ if(!prior){
216
+ const version=db.projectGet(projectId).projectRevision;
217
+ db.projectMaterialPut(write({...item,projectId,version:1,
218
+ expectedProjectRevision:version,provenance:'LEGACY_UNVERIFIED'},
219
+ {epoch:db.epoch}));
220
+ }
221
+ const readBack=db.projectMaterialGet(projectId,item.materialId,1);
222
+ if(hash(Buffer.from(readBack.body,'utf8'))!==item.contentHash)
223
+ throw fail('SOURCE_IMPORT_VERIFY_FAILED');
224
+ imported.push({materialId:item.materialId,sha256:item.contentHash,
225
+ provenance:'LEGACY_UNVERIFIED'});
226
+ }
227
+ return {status:'EVIDENCE_STAGED_NOT_CUTOVER',projectId,imported,
228
+ approvalsImported:false,ownerImported:false,checkpointImported:false,
229
+ currentAuthority:'LEGACY_RW'};
230
+ }finally{db.close()}
231
+ }
232
+ if(action==='prepare'){
233
+ if(params.length!==5)throw fail('INVALID_ARGUMENT');
234
+ const [projectId,sourceUnitId,manifestPath,backupPath,recoveryPath]=params;
235
+ verified(projectId);
236
+ verifyShadowManifest(manifestPath);
237
+ const manifest=readShadowManifest(manifestPath);
238
+ const unit=manifest.sourceUnits.find(x=>x.sourceUnitId===sourceUnitId
239
+ &&x.projectId===projectId);
240
+ if(!unit)throw fail('SOURCE_UNIT_NOT_FOUND');
241
+ // Fail BEFORE creating backup/recovery artifacts if classification or
242
+ // revision is already known to be ineligible for a write cutover.
243
+ const preflight=open();
244
+ try{
245
+ const stage=preflight.migrationList(projectId).find(r=>r.sourceUnitId===sourceUnitId);
246
+ if(stage?.status!=='SHADOW_RO')throw fail('MIGRATION_STAGE_MISMATCH');
247
+ if(stage.sourceHash!==unit.sourceHash)throw fail('SOURCE_CHANGED');
248
+ if(unit.sourceKind==='MIXED_CONTEXT' &&
249
+ stage.manifest.classification?.currentFactsComplete!==true)
250
+ throw fail('MIXED_SOURCE_UNCLASSIFIED');
251
+ }finally{preflight.close()}
252
+ await confirm('PREPARE '+projectId+' '+sourceUnitId);
253
+ const raw=new DatabaseSync(process.env.CHAT_LOOP_CONTEXT_DB);
254
+ let backup;
255
+ try{backup=await backupContextDb(raw,backupPath)}
256
+ finally{raw.close()}
257
+ const db=open();
258
+ try{
259
+ const stage=db.migrationList(projectId).find(r=>r.sourceUnitId===sourceUnitId);
260
+ if(stage?.status!=='SHADOW_RO')throw fail('MIGRATION_STAGE_MISMATCH');
261
+ if(stage.sourceHash!==unit.sourceHash)throw fail('SOURCE_CHANGED');
262
+ const recovery=createRecoveryManifest(recoveryPath,{
263
+ projectId,taskId:'migration-meta',storeEpoch:db.epoch,
264
+ storeLineage:manifest.instanceLineage,
265
+ checkpointRef:null,backupRef:backup,
266
+ unknownEffects:unit.unknownItems??[]});
267
+ return db.migrationPrepare(write({projectId,sourceUnitId,
268
+ expectedMigrationRevision:stage.migrationRevision,sourceHash:unit.sourceHash,
269
+ backupHash:backup.hash,recoveryManifestHash:hash(readBytes(recoveryPath))},
270
+ {epoch:db.epoch}));
271
+ }finally{db.close()}
272
+ }
273
+ if(action==='activate'){
274
+ if(params.length!==3)throw fail('INVALID_ARGUMENT');
275
+ const [projectId,sourceUnitId,manifestPath]=params;verified(projectId);
276
+ verifyShadowManifest(manifestPath);
277
+ const manifest=readShadowManifest(manifestPath);
278
+ const unit=manifest.sourceUnits.find(x=>x.sourceUnitId===sourceUnitId
279
+ &&x.projectId===projectId);
280
+ if(!unit)throw fail('SOURCE_UNIT_NOT_FOUND');
281
+ const writers=await activeLegacyWriters();
282
+ if(writers.length)throw Object.assign(fail('KNOWN_LEGACY_WRITER_ACTIVE'),{writers});
283
+ const db=open();
284
+ try{
285
+ const stage=db.migrationList(projectId).find(r=>r.sourceUnitId===sourceUnitId);
286
+ if(stage?.status!=='CUTOVER_FENCED')throw fail('MIGRATION_STAGE_MISMATCH');
287
+ if(stage?.sourceHash!==unit.sourceHash)throw fail('SOURCE_CHANGED');
288
+ // No model payload grants authorization; operator confirms exact physical
289
+ // unit after inspecting old clients/caches and the private backup.
290
+ await confirm('ACTIVATE '+projectId+' '+sourceUnitId);
291
+ if((await activeLegacyWriters()).length)throw fail('KNOWN_LEGACY_WRITER_ACTIVE');
292
+ return db.migrationActivate(write({projectId,sourceUnitId,
293
+ expectedMigrationRevision:stage.migrationRevision,sourceHash:unit.sourceHash},
294
+ {epoch:db.epoch}));
295
+ }finally{db.close()}
296
+ }
297
+ throw fail('CONTEXT_ADMIN_OPERATION_UNKNOWN');
298
+ }