@tomflow/chatloop-tools 0.9.62 → 0.9.64

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 (154) hide show
  1. package/README.md +13 -1
  2. package/index.mjs +7 -7
  3. package/lib/context-control-run.mjs +23 -5
  4. package/lib/extension-proxy.mjs +29 -10
  5. package/lib/native-owner-v2.mjs +128 -0
  6. package/lib/release-health-checks.mjs +29 -5
  7. package/lib/trace-gateway.mjs +3 -1
  8. package/package.json +3 -13
  9. package/providers/extension.mjs +59 -16
  10. package/node_modules/@tomflow/chatloop-context/README.md +0 -240
  11. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +0 -48
  12. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +0 -151
  13. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +0 -376
  14. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +0 -266
  15. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +0 -134
  16. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +0 -82
  17. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +0 -349
  18. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +0 -72
  19. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +0 -73
  20. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +0 -507
  21. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +0 -11
  22. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +0 -192
  23. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +0 -277
  24. package/node_modules/@tomflow/chatloop-context/index.mjs +0 -236
  25. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +0 -86
  26. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +0 -77
  27. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +0 -1989
  28. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +0 -69
  29. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +0 -285
  30. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +0 -298
  31. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +0 -286
  32. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +0 -115
  33. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +0 -51
  34. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +0 -75
  35. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +0 -262
  36. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +0 -246
  37. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +0 -147
  38. package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +0 -54
  39. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +0 -375
  40. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +0 -397
  41. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +0 -183
  42. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +0 -13
  43. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +0 -111
  44. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +0 -107
  45. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +0 -118
  46. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +0 -20
  47. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +0 -316
  48. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +0 -153
  49. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +0 -19
  50. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +0 -117
  51. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +0 -97
  52. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +0 -169
  53. package/node_modules/@tomflow/chatloop-context/package.json +0 -40
  54. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +0 -114
  55. package/node_modules/@tomflow/chatloop-extension/README.md +0 -124
  56. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +0 -13
  57. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +0 -153
  58. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +0 -207
  59. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +0 -1
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +0 -1
  61. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +0 -1
  62. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +0 -1
  63. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +0 -1
  64. package/node_modules/@tomflow/chatloop-extension/capabilities/entry_test.mjs +0 -1
  65. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +0 -1
  66. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +0 -1
  67. package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +0 -1
  68. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +0 -1
  69. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +0 -1
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +0 -123
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +0 -183
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +0 -340
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +0 -2
  74. package/node_modules/@tomflow/chatloop-extension/extension/actions/entry_test.js +0 -241
  75. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +0 -393
  76. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +0 -2
  77. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +0 -56
  78. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +0 -9
  79. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +0 -20
  80. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +0 -77
  81. package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +0 -52
  82. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +0 -295
  83. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +0 -24
  84. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +0 -2
  85. package/node_modules/@tomflow/chatloop-extension/extension/background.js +0 -17
  86. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +0 -5
  87. package/node_modules/@tomflow/chatloop-extension/extension/content.js +0 -40
  88. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +0 -9
  89. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +0 -17
  90. package/node_modules/@tomflow/chatloop-extension/extension/entry_test.html +0 -6
  91. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +0 -9
  92. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +0 -2
  93. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +0 -275
  94. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +0 -84
  95. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +0 -107
  96. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +0 -36
  97. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +0 -299
  98. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +0 -144
  99. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +0 -171
  100. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +0 -109
  101. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +0 -154
  102. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +0 -259
  103. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +0 -42
  104. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +0 -25
  105. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +0 -99
  106. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +0 -17
  107. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +0 -17
  108. package/node_modules/@tomflow/chatloop-extension/extension/session.html +0 -6
  109. package/node_modules/@tomflow/chatloop-extension/extension/start.html +0 -6
  110. package/node_modules/@tomflow/chatloop-extension/extension/status.html +0 -6
  111. package/node_modules/@tomflow/chatloop-extension/extension/text.html +0 -17
  112. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +0 -136
  113. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +0 -218
  114. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +0 -124
  115. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +0 -296
  116. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +0 -186
  117. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +0 -126
  118. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +0 -230
  119. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +0 -163
  120. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +0 -345
  121. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +0 -192
  122. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +0 -161
  123. package/node_modules/@tomflow/chatloop-extension/extension/worker/session-control.js +0 -75
  124. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +0 -197
  125. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +0 -205
  126. package/node_modules/@tomflow/chatloop-extension/index.mjs +0 -71
  127. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +0 -19
  128. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +0 -82
  129. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +0 -303
  130. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +0 -83
  131. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +0 -45
  132. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +0 -115
  133. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +0 -75
  134. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +0 -185
  135. package/node_modules/@tomflow/chatloop-extension/package.json +0 -38
  136. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +0 -138
  137. package/node_modules/@tomflow/chatloop-trace/README.md +0 -118
  138. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +0 -23
  139. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +0 -22
  140. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +0 -4
  141. package/node_modules/@tomflow/chatloop-trace/index.mjs +0 -59
  142. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +0 -273
  143. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +0 -308
  144. package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +0 -140
  145. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +0 -236
  146. package/node_modules/@tomflow/chatloop-trace/package.json +0 -30
  147. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +0 -68
  148. package/node_modules/ps-list/index.d.ts +0 -76
  149. package/node_modules/ps-list/index.js +0 -366
  150. package/node_modules/ps-list/license +0 -9
  151. package/node_modules/ps-list/package.json +0 -44
  152. package/node_modules/ps-list/readme.md +0 -56
  153. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  154. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
@@ -1,69 +0,0 @@
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
- // The capability registry was verified against the build manifest.
44
- // Never dispatch a supplied method object's mutable route instead.
45
- const route=source.entry.route;
46
- if(route.kind==='core'){
47
- const fn=services?.db?.[route.method];
48
- if(typeof fn!=='function')throw fail('CAPABILITY_CORE_PROVIDER_MISSING');
49
- return Reflect.apply(fn,services.db,
50
- route.params.map(param=>value(param,args)));
51
- }
52
- if(route.kind==='module'){
53
- if(method.mode!=='read'||typeof source.cap.execute!=='function'
54
- ||args.projectId!==services?.projectRef)
55
- throw fail('CAPABILITY_PERMISSION_DENIED');
56
- const read=Object.freeze({
57
- projectRef:args.projectId,
58
- // No raw DB handle, credential, CAS mutation or cross-project lookup.
59
- material:(materialId,version)=>
60
- services.db.projectMaterialGet(args.projectId,materialId,version),
61
- document:(taskId,documentId,version)=>
62
- services.db.documentGet(args.projectId,taskId,documentId,version)
63
- });
64
- return source.cap.execute(method.id,args,read);
65
- }
66
- throw fail('CAPABILITY_ADAPTER_ROUTE_REQUIRED');
67
- }
68
- });
69
- }
@@ -1,285 +0,0 @@
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 {lstatSync,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
- // Reject dangling target links as occupied rather than replacing them.
10
- const occupied=path=>{
11
- try{lstatSync(path);return true}
12
- catch(error){if(error.code==='ENOENT')return false;throw error}
13
- };
14
- let openContextProtocol,contextRoot,allowedProjects,
15
- verifySourceUnit,createProjectDiagnosticBranch,createManagedProjectBranch,
16
- fenceLegacyProjectStore,auditLegacyProjectSources,inspectLegacyRegistryReference,
17
- activeLegacyWriters,fenceOrphanRunOperator,canonicalWorkspaceRefs,
18
- confirmWorkspaceOperator,assertWorkspaceUnclaimed,withWorkspaceRegistryLock,
19
- rebindProjectWorkspaces,readOperatorWorkspaceReceipt,runContextCli,
20
- requestContext,listMethods,describeMethod,CONTEXT_PACKAGE_VERSION;
21
- let connected=false;
22
- export function configureCliCommands(api){
23
- if(connected)throw Error('CONTEXT_MODULE_ALREADY_COMPOSED');
24
- const names=['openContextProtocol','contextRoot','allowedProjects',
25
- 'verifySourceUnit','createProjectDiagnosticBranch','createManagedProjectBranch',
26
- 'fenceLegacyProjectStore','auditLegacyProjectSources',
27
- 'inspectLegacyRegistryReference','activeLegacyWriters',
28
- 'fenceOrphanRunOperator','canonicalWorkspaceRefs',
29
- 'confirmWorkspaceOperator','assertWorkspaceUnclaimed','withWorkspaceRegistryLock',
30
- 'rebindProjectWorkspaces','readOperatorWorkspaceReceipt','runContextCli',
31
- 'requestContext','listMethods','describeMethod','CONTEXT_PACKAGE_VERSION'];
32
- for(const name of names)
33
- if(api?.[name]===undefined)throw Error('CONTEXT_MODULE_PORT_MISSING:'+name);
34
- ({openContextProtocol,contextRoot,allowedProjects,
35
- verifySourceUnit,createProjectDiagnosticBranch,createManagedProjectBranch,
36
- fenceLegacyProjectStore,auditLegacyProjectSources,inspectLegacyRegistryReference,
37
- activeLegacyWriters,fenceOrphanRunOperator,canonicalWorkspaceRefs,
38
- confirmWorkspaceOperator,assertWorkspaceUnclaimed,withWorkspaceRegistryLock,
39
- rebindProjectWorkspaces,readOperatorWorkspaceReceipt,runContextCli,
40
- requestContext,listMethods,describeMethod,CONTEXT_PACKAGE_VERSION}=api);
41
- connected=true;
42
- }
43
-
44
- async function registerProject(projectId,title,workspaces=[],reviewed=false){
45
- if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
46
- if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
47
- if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(projectId))throw fail('INVALID_SCOPE');
48
- if(typeof title!=='string'||!title.trim()||title.length>200)throw fail('INVALID_TITLE');
49
- if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
50
- const refs=canonicalWorkspaceRefs(workspaces,{allowEmpty:!reviewed});
51
- const root=contextRoot(),final=join(root,projectId);
52
- if(occupied(final))throw fail('PROJECT_EXISTS');
53
- // The user-reviewed entry never creates a Store (or even a directory)
54
- // before the local operator confirms the exact canonical roots.
55
- if(reviewed)await confirmWorkspaceOperator('REGISTER',projectId,0,refs);
56
- mkdirSync(root,{recursive:true,mode:0o700});
57
- return withWorkspaceRegistryLock(root,()=>{
58
- let tmp;
59
- try{
60
- if(occupied(final))throw fail('PROJECT_EXISTS');
61
- if(reviewed){
62
- const current=canonicalWorkspaceRefs(workspaces);
63
- if(JSON.stringify(current)!==JSON.stringify(refs))throw fail('WORKSPACE_CHANGED');
64
- assertWorkspaceUnclaimed(root,projectId,refs);
65
- }
66
- tmp=mkdtempSync(join(root,'.register-'));
67
- const db=openContextProtocol(join(tmp,'context.sqlite'),{
68
- allowCreate:true,authorizeData:()=>true,principalId:'local-operator'});
69
- let result;
70
- try{
71
- result=db.projectCreate({projectId,title,sharedContext:{workspaceRefs:refs},
72
- expectedStoreEpoch:db.epoch,writeRequestId:randomUUID()});
73
- }finally{db.close()}
74
- renameSync(tmp,final);tmp=null;
75
- return {...result,workspaceRefs:refs,projectDirectory:final};
76
- }finally{
77
- // Incomplete staging is diagnostic only, never silently promoted.
78
- if(tmp)rmSync(tmp,{recursive:true,force:true});
79
- }
80
- });
81
- }
82
- export async function runLocalCliCommand(args,readJson){
83
- const [command,sub,...rest]=args;
84
- let value;
85
- if(command==='methods'&&sub==='list'&&rest.length<=1)
86
- value=await requestContext({operation:'sdk.methods.list',
87
- ...(rest[0]&&rest[0]!=='--json'?{group:rest[0]}:{})});
88
- else if(command==='methods'&&sub==='groups'&&rest.length<=1)
89
- value=await requestContext({operation:'sdk.methods.list',view:'groups',
90
- ...(rest[0]?{group:rest[0]}:{})});
91
- else if(command==='methods'&&sub==='describe'&&rest.length===1)
92
- value=await requestContext({operation:'sdk.methods.describe',methodId:rest[0]});
93
- else if(command==='admin'&&sub){
94
- value=await runContextCli([sub,...rest]);
95
- }
96
- else if(command==='request'&&sub==='--json'&&rest.length===0){
97
- const payload=await readJson();
98
- if(!payload||typeof payload!=='object'||Array.isArray(payload))throw fail('INVALID_ARGUMENT');
99
- value=await requestContext(payload);
100
- }else if(command==='task'&&sub==='fence-orphan'&&rest.length===10){
101
- const [projectId,taskId,expectedRunRef,revision,bindingRevision,
102
- expectedStoreEpoch,evidenceDocumentId,evidenceVersion,evidenceHash,
103
- writeRequestId]=rest;
104
- value=await fenceOrphanRunOperator({projectId,taskId,expectedRunRef,
105
- expectedTaskRevision:Number(revision),
106
- expectedBindingRevision:Number(bindingRevision),
107
- expectedStoreEpoch,evidenceDocumentId,
108
- evidenceVersion:Number(evidenceVersion),evidenceHash,writeRequestId});
109
- }else if(command==='task'&&sub==='orphan-receipt'&&rest.length===3){
110
- const [projectId,storeEpoch,writeRequestId]=rest;
111
- if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
112
- if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
113
- const file=join(contextRoot(),projectId,'context.sqlite');
114
- const db=openContextProtocol(file,{readOnly:true,principalId:'local-operator',
115
- authorizeData:(_mode,p)=>p===projectId});
116
- try{value=db.requestStatus({projectId,storeEpoch,writeRequestId})}
117
- finally{db.close()}
118
- }else if(command==='project'&&sub==='init'&&(rest.length===2||rest.length===3))
119
- value=await registerProject(rest[0],rest[1],rest.slice(2));
120
- else if(command==='project'&&sub==='register'&&rest.length>=3&&rest.length<=18)
121
- value=await registerProject(rest[0],rest[1],rest.slice(2),true);
122
- else if(command==='project'&&sub==='bind'&&rest.length>=4&&rest.length<=20){
123
- const [projectId,revision,epoch,requestId,...paths]=rest;
124
- if(paths.length===1&&paths[0]==='--clear')paths.length=0;
125
- value=await rebindProjectWorkspaces({projectId,
126
- expectedProjectRevision:Number(revision),expectedStoreEpoch:epoch,
127
- writeRequestId:requestId,workspaces:paths});
128
- }else if(command==='project'&&sub==='receipt'&&rest.length===3)
129
- value=await readOperatorWorkspaceReceipt({projectId:rest[0],
130
- storeEpoch:rest[1],writeRequestId:rest[2]});
131
- else if(command==='project'&&sub==='reconcile-reference'&&rest.length===10){
132
- const [projectId,sourceDb,expectedStoreEpoch,sourceUnitId,revision,
133
- taskId,originalArchivePath,expectedCurrentHash,reviewRef,writeRequestId]=rest;
134
- if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
135
- if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
136
- if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
137
- const expectedMigrationRevision=Number(revision);
138
- if(!Number.isSafeInteger(expectedMigrationRevision)||expectedMigrationRevision<1)
139
- throw fail('MIGRATION_VERSION_CONFLICT');
140
- // Fail closed before any writable handle exists. Review is NOT user R/P.
141
- const evidence=inspectLegacyRegistryReference({sourceDb,projectId,
142
- expectedStoreEpoch,sourceUnitId,taskId,archiveFile:originalArchivePath});
143
- if(evidence.changeKind!=='INSERTIONS_ONLY'||
144
- evidence.currentTaskHash!==expectedCurrentHash)
145
- throw fail('REGISTRY_REFERENCE_VERSION_CONFLICT');
146
- await confirmWorkspaceOperator('RECONCILE_REFERENCE',projectId,
147
- expectedMigrationRevision,[sourceDb,sourceUnitId,taskId,
148
- evidence.archivedTaskHash,expectedCurrentHash,reviewRef]);
149
- const db=openContextProtocol(sourceDb,{principalId:'local-operator',
150
- authorizeData:(_mode,p)=>p===projectId,
151
- authorizeAdmin:(op,p)=>p===projectId&&[
152
- 'migration.reference.reconcile',
153
- 'migration.reference.reconcile.reviewed'].includes(op)});
154
- try{
155
- value=db.migrationReconcileReference({projectId,sourceUnitId,
156
- expectedMigrationRevision,expectedStoreEpoch,writeRequestId,
157
- taskId,originalArchivePath,expectedCurrentHash,
158
- sourceHash:evidence.sourceHash,reviewRef});
159
- }finally{db.close()}
160
- }else if(command==='project'&&sub==='migration-receipt'&&rest.length===4){
161
- const [projectId,sourceDb,storeEpoch,writeRequestId]=rest;
162
- if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
163
- const db=openContextProtocol(sourceDb,{readOnly:true,
164
- principalId:'local-operator',
165
- authorizeData:(_mode,p)=>p===projectId});
166
- try{value=db.requestStatus({projectId,storeEpoch,writeRequestId})}
167
- finally{db.close()}
168
- }else if(command==='project'&&sub==='classify-evidence'&&rest.length===8){
169
- const [projectId,sourceDb,expectedStoreEpoch,sourceUnitId,revision,
170
- sourceHash,reviewRef,writeRequestId]=rest;
171
- if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
172
- if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
173
- if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
174
- const expectedMigrationRevision=Number(revision);
175
- if(!Number.isSafeInteger(expectedMigrationRevision)||expectedMigrationRevision<1)
176
- throw fail('MIGRATION_VERSION_CONFLICT');
177
- if(typeof reviewRef!=='string'||reviewRef.length<8||reviewRef.length>256)
178
- throw fail('REVIEW_REFERENCE_REQUIRED');
179
- // The historical body's original bytes must already be a matching
180
- // LEGACY_UNVERIFIED Project Material, never a synthesized current Task.
181
- const reader=openContextProtocol(sourceDb,{readOnly:true,
182
- principalId:'local-operator',authorizeData:(_mode,p)=>p===projectId,
183
- authorizeAdmin:(op,p)=>op==='migration.list'&&p===projectId});
184
- let unit;
185
- try{
186
- if(reader.mode!=='ACTIVE')throw fail('STORE_DIAGNOSTIC_ONLY');
187
- if(reader.epoch!==expectedStoreEpoch)throw fail('STALE_EPOCH');
188
- unit=reader.migrationList(projectId).find(x=>x.sourceUnitId===sourceUnitId);
189
- if(!unit||unit.status!=='SHADOW_RO'||
190
- unit.manifest.sourceKind!=='MIXED_CONTEXT')
191
- throw fail('MIXED_SOURCE_NOT_SHADOW');
192
- if(unit.migrationRevision!==expectedMigrationRevision)
193
- throw fail('MIGRATION_VERSION_CONFLICT');
194
- if(unit.sourceHash!==sourceHash)throw fail('SOURCE_CHANGED');
195
- verifySourceUnit(unit.manifest);
196
- const material=reader.projectMaterialList(projectId).filter(m=>
197
- m.sourcePath===unit.sourcePath&&m.contentHash===sourceHash&&
198
- m.provenance==='LEGACY_UNVERIFIED');
199
- if(!material.some(m=>createHash('sha256').update(
200
- reader.projectMaterialGet(projectId,m.materialId,m.version).body
201
- ).digest('hex')===sourceHash))throw fail('MIGRATION_BODY_NOT_IMPORTED');
202
- }finally{reader.close()}
203
- // Human-reviewed disposition: preserve FULL mixed history as
204
- // EvidenceOnly/UNKNOWN. Do not assert any current Task or R/P fact.
205
- await confirmWorkspaceOperator('CLASSIFY_EVIDENCE_ONLY',projectId,
206
- expectedMigrationRevision,[sourceDb,sourceUnitId,sourceHash,reviewRef]);
207
- const db=openContextProtocol(sourceDb,{principalId:'local-operator',
208
- authorizeData:(_mode,p)=>p===projectId,
209
- authorizeAdmin:(op,p)=>p===projectId&&
210
- ['migration.classify','migration.classify.reviewed'].includes(op)});
211
- try{
212
- value=db.migrationClassify({projectId,sourceUnitId,sourceHash,
213
- expectedStoreEpoch,expectedMigrationRevision,writeRequestId,
214
- classification:{projectId,sourceUnitId,sourceHash,
215
- currentFactsComplete:true,reviewRef,taskContexts:[],
216
- projectSharedContext:{},
217
- unknownHistoryRefs:[{locator:unit.sourcePath,sourceHash}]}});
218
- }finally{db.close()}
219
- }else if(command==='project'&&sub==='inspect-reference'&&rest.length===6){
220
- const [projectId,sourceDb,expectedStoreEpoch,sourceUnitId,taskId,archiveFile]=rest;
221
- if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
222
- value=inspectLegacyRegistryReference({projectId,sourceDb,
223
- expectedStoreEpoch,sourceUnitId,taskId,archiveFile});
224
- }else if(command==='project'&&sub==='audit-sources'&&rest.length===3){
225
- const [projectId,sourceDb,expectedStoreEpoch]=rest;
226
- if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
227
- value=auditLegacyProjectSources({projectId,sourceDb,expectedStoreEpoch});
228
- // Observe known, supported MCP writers without claiming an independent
229
- // old-writer fence. Only PIDs are returned, never process argv or secrets.
230
- let writerObservation;
231
- try{
232
- const pids=await activeLegacyWriters();
233
- writerObservation={status:pids.length?'MATCHED':'NO_SUPPORTED_PROCESS_MATCH',pids};
234
- }catch{writerObservation={status:'UNVERIFIED',pids:[]}}
235
- value={...value,supportedWriterObservation:writerObservation};
236
- }else if(command==='project'&&sub==='seal-source'&&rest.length===6){
237
- const [projectId,sourceDb,epoch,revision,backupPath,sealManifestPath]=rest;
238
- if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
239
- if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
240
- if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
241
- const expectedProjectRevision=Number(revision);
242
- if(!Number.isSafeInteger(expectedProjectRevision)||expectedProjectRevision<1)
243
- throw fail('PROJECT_VERSION_CONFLICT');
244
- await confirmWorkspaceOperator('SEAL_SOURCE',projectId,
245
- expectedProjectRevision,[sourceDb,epoch,backupPath,sealManifestPath]);
246
- value=await fenceLegacyProjectStore({sourceDb,projectId,
247
- expectedStoreEpoch:epoch,expectedProjectRevision,backupPath,sealManifestPath});
248
- }else if(command==='project'&&sub==='publish-managed'&&rest.length===6){
249
- const [projectId,sourceDb,epoch,revision,sealManifest,expectedSealHash]=rest;
250
- if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
251
- if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
252
- if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
253
- const expectedProjectRevision=Number(revision);
254
- if(!Number.isSafeInteger(expectedProjectRevision)||expectedProjectRevision<1)
255
- throw fail('PROJECT_VERSION_CONFLICT');
256
- await confirmWorkspaceOperator('PUBLISH_MANAGED',projectId,
257
- expectedProjectRevision,[sourceDb,epoch,sealManifest,expectedSealHash]);
258
- const root=contextRoot();
259
- mkdirSync(root,{recursive:true,mode:0o700});
260
- value=await withWorkspaceRegistryLock(root,()=>createManagedProjectBranch({
261
- sourceDb,targetRoot:root,projectId,expectedStoreEpoch:epoch,
262
- expectedProjectRevision,sealManifest,expectedSealHash
263
- }));
264
- }else if(command==='project'&&sub==='stage-diagnostic'&&rest.length===4){
265
- const [projectId,sourceDb,expectedStoreEpoch,revision]=rest;
266
- if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
267
- if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
268
- if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
269
- const expectedProjectRevision=Number(revision);
270
- if(!Number.isSafeInteger(expectedProjectRevision)||expectedProjectRevision<1)
271
- throw fail('PROJECT_VERSION_CONFLICT');
272
- // This is an offline diagnostic extract; NEVER a source cutover.
273
- // The operator must review the exact source path and source CAS identity.
274
- await confirmWorkspaceOperator('STAGE_DIAGNOSTIC',projectId,
275
- expectedProjectRevision,[sourceDb,expectedStoreEpoch]);
276
- const root=contextRoot();
277
- mkdirSync(root,{recursive:true,mode:0o700});
278
- value=await withWorkspaceRegistryLock(root,()=>createProjectDiagnosticBranch({
279
- sourceDb,targetRoot:root,projectId,expectedStoreEpoch,expectedProjectRevision
280
- }));
281
- }else if(command==='doctor'&&sub==='--json'&&rest.length===0)
282
- value={status:'READY',packageVersion:CONTEXT_PACKAGE_VERSION,projectRoot:contextRoot()};
283
- else throw fail('UNKNOWN_COMMAND');
284
- return value;
285
- }
@@ -1,298 +0,0 @@
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
- }