@tomflow/chatloop-context 0.6.11 → 0.6.13

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.
package/README.md CHANGED
@@ -182,7 +182,7 @@ The npm executable is `chatloop-context`, installed by a fixed dependency
182
182
  or invoked separately through a **pinned, available** npm version:
183
183
 
184
184
  ```sh
185
- npm install --save-exact @tomflow/chatloop-context@0.6.1
185
+ npm install --save-exact "@tomflow/chatloop-context@${VERIFIED_CONTEXT_VERSION:?set-exact-verified-version}"
186
186
  chatloop-context methods groups
187
187
  chatloop-context methods list project
188
188
  chatloop-context methods describe project.open
@@ -223,7 +223,7 @@ ownership boundaries and known coupling risks.
223
223
 
224
224
  ## Deployment is separate from source
225
225
 
226
- Local npm source version `0.6.1` does **not** establish the connected MCP
226
+ The source version declared in [`package.json`](package.json) does **not** establish the connected MCP
227
227
  version. Verify the real `sdk.methods.list` response, Node runtime,
228
228
  pinned Tools dependency, package bytes and Project authority before any
229
229
  separately authorized installation. Source refactoring does **not** migrate
@@ -1,6 +1,6 @@
1
1
  # Context npm package — actual interface, consumer and dependency map
2
2
 
3
- > Applies to the **source** package `@tomflow/chatloop-context@0.6.1`.
3
+ > Applies to the **source** version declared in [`../package.json`](../package.json), not a fixed historical release.
4
4
  > The connected MCP may still be running an earlier installed release.
5
5
  > This document describes source contracts, not production cutover approval.
6
6
 
@@ -262,7 +262,7 @@ fence, R/P approval, UNKNOWN-send or browser Owner guards.
262
262
  CURRENT ownership, old writers and true operator approval have been reviewed,
263
263
  old app/Native/Registry clients fenced, fresh backup plus recovery tested and
264
264
  the release/real Chrome E2E gates passed. See P0-02 in
265
- `docs/research/chat-loop-context-cli-architecture-20261109.md`.
265
+ `docs/CONTEXT.md`(现行)及 `git show 5ec21b33e9e4:docs/research/chat-loop-context-cli-architecture-20261109.md`(历史).
266
266
 
267
267
  ## Safety
268
268
 
package/lib/api-log.mjs CHANGED
@@ -3,7 +3,7 @@
3
3
  // belong to the public @tomflow/chatloop-trace API, not a copied runtime.
4
4
  import {createApiAspect} from '@tomflow/chatloop-trace';
5
5
 
6
- export const API_LOG_CONTRACT='chat-loop.context-api-log.v1';
6
+ const API_LOG_CONTRACT='chat-loop.context-api-log.v1';
7
7
  const API=/^[a-z][A-Za-z0-9._-]{1,89}$/;
8
8
  const REF=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
9
9
  const CODE=/^[A-Z][A-Z0-9_]{1,95}$/;
@@ -1,11 +1,6 @@
1
1
  // Context owns business approval policy. No SQLite, browser, MCP or Session state.
2
- // V1 is intentionally the two genuine R->P soft user Turns already in production.
3
- // A new strong approval requires an explicitly versioned policy and migrations,
4
- // not changing a count scattered through Run/Permit transactions.
5
- export const APPROVAL_POLICY_V1=Object.freeze({
6
- id:'chat-loop.approval.r-p.v1',
7
- requiredKinds:Object.freeze(['R','P'])
8
- });
2
+ // Only these enforced predicates (not an unused second policy descriptor)
3
+ // decide whether R and P have distinct genuine user Turns.
9
4
 
10
5
  const fromUser=a=>Boolean(a&&typeof a==='object'
11
6
  &&(a.sourceRole===undefined||a.sourceRole==='user')
@@ -40,7 +40,9 @@ export function createCapabilityRouter(definitions,capabilities){
40
40
  const source=registry.get(method?.id);
41
41
  if(!source||source.entry.mode!==method.mode)
42
42
  throw fail('CAPABILITY_METHOD_UNKNOWN');
43
- const route=method.route;
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;
44
46
  if(route.kind==='core'){
45
47
  const fn=services?.db?.[route.method];
46
48
  if(typeof fn!=='function')throw fail('CAPABILITY_CORE_PROVIDER_MISSING');
@@ -2,10 +2,15 @@
2
2
  // Only bin/cli.mjs exports a shell command. index.mjs supplies scoped API
3
3
  // dependencies; local admin/SQLite safety gates remain in their owners.
4
4
  import {randomUUID,createHash} from 'node:crypto';
5
- import {existsSync,mkdirSync,mkdtempSync,renameSync,rmSync} from 'node:fs';
5
+ import {lstatSync,mkdirSync,mkdtempSync,renameSync,rmSync} from 'node:fs';
6
6
  import {join} from 'node:path';
7
7
 
8
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
+ };
9
14
  let openContextProtocol,contextRoot,allowedProjects,
10
15
  verifySourceUnit,createProjectDiagnosticBranch,createManagedProjectBranch,
11
16
  fenceLegacyProjectStore,auditLegacyProjectSources,inspectLegacyRegistryReference,
@@ -44,7 +49,7 @@ async function registerProject(projectId,title,workspaces=[],reviewed=false){
44
49
  if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
45
50
  const refs=canonicalWorkspaceRefs(workspaces,{allowEmpty:!reviewed});
46
51
  const root=contextRoot(),final=join(root,projectId);
47
- if(existsSync(final))throw fail('PROJECT_EXISTS');
52
+ if(occupied(final))throw fail('PROJECT_EXISTS');
48
53
  // The user-reviewed entry never creates a Store (or even a directory)
49
54
  // before the local operator confirms the exact canonical roots.
50
55
  if(reviewed)await confirmWorkspaceOperator('REGISTER',projectId,0,refs);
@@ -52,7 +57,7 @@ async function registerProject(projectId,title,workspaces=[],reviewed=false){
52
57
  return withWorkspaceRegistryLock(root,()=>{
53
58
  let tmp;
54
59
  try{
55
- if(existsSync(final))throw fail('PROJECT_EXISTS');
60
+ if(occupied(final))throw fail('PROJECT_EXISTS');
56
61
  if(reviewed){
57
62
  const current=canonicalWorkspaceRefs(workspaces);
58
63
  if(JSON.stringify(current)!==JSON.stringify(refs))throw fail('WORKSPACE_CHANGED');
@@ -2,8 +2,8 @@
2
2
  // Never infer task approvals, Browser Owner, or a runnable checkpoint from
3
3
  // Markdown/legacy Registry. Default mode is read-only SHADOW.
4
4
  import {createHash,randomUUID} from 'node:crypto';
5
- import {readFileSync,writeFileSync,mkdirSync,existsSync,lstatSync,copyFileSync,chmodSync,constants,
6
- realpathSync,renameSync,unlinkSync,openSync,readSync,closeSync} from 'node:fs';
5
+ import {readFileSync,writeFileSync,mkdirSync,lstatSync,copyFileSync,chmodSync,constants,
6
+ realpathSync,linkSync,unlinkSync,openSync,readSync,closeSync} from 'node:fs';
7
7
  import {basename,dirname,join,resolve,isAbsolute} from 'node:path';
8
8
  import {DatabaseSync,backup} from 'node:sqlite';
9
9
  // This module declares ports; index.mjs is the only dependency assembler.
@@ -23,6 +23,11 @@ const fail=code=>Object.assign(new Error(code),{code});
23
23
  const assert=(b,c)=>{if(!b)throw fail(c)};
24
24
  const hash=x=>createHash('sha256').update(x).digest('hex');
25
25
  const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
26
+ // A dangling link is an occupied output path, never an absent artifact.
27
+ const occupied=file=>{
28
+ try{lstatSync(file);return true}
29
+ catch(error){if(error.code==='ENOENT')return false;throw error}
30
+ };
26
31
  // Hash large online backups incrementally; never load a 2 GiB database
27
32
  // into the Agent/CLI process just to check its integrity.
28
33
  const hashLargeFile=(file,max=2*1024*1024*1024)=>{
@@ -60,7 +65,8 @@ const safeOutput=(file,value)=>{
60
65
  const tmp=join(dir,'.'+basename(file)+'.'+randomUUID()+'.tmp');
61
66
  try{
62
67
  writeFileSync(tmp,JSON.stringify(value,null,2)+'\n',{flag:'wx',mode:0o600});
63
- renameSync(tmp,file);
68
+ // Atomic create-if-absent: rename would replace an existing artifact.
69
+ linkSync(tmp,file);
64
70
  }finally{try{unlinkSync(tmp)}catch{}}
65
71
  };
66
72
  export function scanSourceUnit({sourcePath,projectId,kind}){
@@ -131,7 +137,7 @@ export function saveShadowManifest(file,items){
131
137
  status:'SHADOW_RO',sourceUnits:items,permissions:'READ_ONLY',
132
138
  taskApprovalsImported:false,ownerImported:false,
133
139
  knownWritersStopped:false};
134
- assert(!existsSync(file),'MANIFEST_EXISTS');
140
+ assert(!occupied(file),'MANIFEST_EXISTS');
135
141
  safeOutput(file,manifest);
136
142
  return manifest;
137
143
  }
@@ -153,7 +159,7 @@ export function verifyShadowManifest(file){
153
159
  // SQLite online backup: never copy a live database's main file.
154
160
  export async function backupContextDb(dbHandle,targetFile){
155
161
  assert(typeof targetFile==='string'&&isAbsolute(targetFile),'BACKUP_PATH_INVALID');
156
- assert(!existsSync(targetFile),'BACKUP_EXISTS');
162
+ assert(!occupied(targetFile),'BACKUP_EXISTS');
157
163
  privateDirectory(dirname(targetFile));
158
164
  try{
159
165
  await backup(dbHandle,targetFile);
@@ -174,7 +180,7 @@ export function restoreBackupToDiagnosticBranch({
174
180
  &&typeof manifestFile==='string'&&isAbsolute(manifestFile)
175
181
  &&typeof expectedBackupHash==='string'&&/^[a-f0-9]{64}$/.test(expectedBackupHash),
176
182
  'RESTORE_ARGUMENT_INVALID');
177
- assert(!existsSync(targetDb)&&!existsSync(manifestFile),'RESTORE_TARGET_EXISTS');
183
+ assert(!occupied(targetDb)&&!occupied(manifestFile),'RESTORE_TARGET_EXISTS');
178
184
  const source=hashLargeFile(backupFile);
179
185
  assert(source.hash===expectedBackupHash,'BACKUP_HASH_MISMATCH');
180
186
  privateDirectory(dirname(targetDb));
@@ -227,7 +233,7 @@ export function createRecoveryManifest(file,{projectId,taskId,storeEpoch,storeLi
227
233
  storeEpoch,storeLineage,checkpointRef:checkpointRef??null,
228
234
  backupRef,readerVersion,unknownEffects,generatedAt:Date.now(),
229
235
  mode:'DIAGNOSTIC_ONLY',canExecute:false};
230
- assert(!existsSync(file),'RECOVERY_MANIFEST_EXISTS');
236
+ assert(!occupied(file),'RECOVERY_MANIFEST_EXISTS');
231
237
  safeOutput(file,record);
232
238
  return record;
233
239
  }
@@ -1,7 +1,7 @@
1
1
  // Authoritative single-handle Context SQLite Core. Domain methods compose here.
2
2
  // No Chrome Owner, second writer, or independently committed domain transaction.
3
3
  import {DatabaseSync} from 'node:sqlite';
4
- import {createHash, randomBytes, randomUUID} from 'node:crypto';
4
+ import {createHash, randomUUID} from 'node:crypto';
5
5
  import {mkdirSync,lstatSync,existsSync,chmodSync} from 'node:fs';
6
6
  import {dirname} from 'node:path';
7
7
 
@@ -25,7 +25,6 @@ const canonical=x=>x===null||typeof x!=='object'?JSON.stringify(x):
25
25
  Array.isArray(x)?'['+x.map(canonical).join(',')+']':
26
26
  '{'+Object.keys(x).sort().map(k=>JSON.stringify(k)+':'+canonical(x[k])).join(',')+'}';
27
27
  const digest=x=>createHash('sha256').update(typeof x==='string'?x:canonical(x)).digest('hex');
28
- export const issueRunCredential=()=>randomBytes(32).toString('hex');
29
28
  const runDigest=(epoch,projectId,taskId,runRef,credential)=>digest(['context-write-v1',epoch,projectId,taskId,runRef,credential]);
30
29
  const parse=x=>JSON.parse(x);
31
30
 
@@ -44,13 +43,18 @@ export function openContextProtocol(file,{authorizeInternal=()=>false,authorizeD
44
43
  else mkdirSync(dirname(file),{recursive:true,mode:0o700});
45
44
  const dir=lstatSync(dirname(file));
46
45
  assert(dir.isDirectory()&&!dir.isSymbolicLink()&&!(dir.mode&0o077),'STATE_DIRECTORY_UNTRUSTED');
47
- const existed=existsSync(file);
48
- if(!existed)assert(allowCreate===true&&!readOnly,'STORE_MISSING');
49
- else {
50
- const st=lstatSync(file);
51
- assert(st.isFile()&&!st.isSymbolicLink()&&!(st.mode&0o077)
52
- &&(!process.getuid||st.uid===process.getuid()),'STORE_FILE_UNTRUSTED');
46
+ // existsSync follows dangling symlinks. A dangling Store path is not
47
+ // an absent database, even when the operator explicitly allows creation.
48
+ let fileStat=null;
49
+ try{fileStat=lstatSync(file)}
50
+ catch(error){
51
+ if(error.code!=='ENOENT')throw fail('STORE_FILE_UNTRUSTED');
53
52
  }
53
+ const existed=fileStat!==null;
54
+ if(!existed)assert(allowCreate===true&&!readOnly,'STORE_MISSING');
55
+ else assert(fileStat.isFile()&&!fileStat.isSymbolicLink()
56
+ &&!(fileStat.mode&0o077)
57
+ &&(!process.getuid||fileStat.uid===process.getuid()),'STORE_FILE_UNTRUSTED');
54
58
  const db=new DatabaseSync(file,{timeout:3500,readOnly});
55
59
  // Check the existing schema BEFORE creating any application table or changing WAL.
56
60
  // Never silently adopt an unrelated DB or recreate an empty authority.
package/lib/core/task.mjs CHANGED
@@ -125,7 +125,17 @@ export function createTaskMethods(values) {
125
125
  const r=scope(a);expectedBusiness(r,a.expectedTaskRevision);
126
126
  assert(typeof a.userTurn==='string'&&a.userTurn.length>=8,'ACCEPTANCE_SOURCE_REQUIRED');
127
127
  const current=parse(r.context_json);
128
- assert(current.executionOutcome==='DONE','DELIVERY_NOT_DONE');
128
+ // REOPENED still retains the old DONE history but is not a new
129
+ // deliverable for acceptance until the repair is completed.
130
+ assert(current.executionOutcome==='DONE'&&current.stage==='DELIVERED',
131
+ 'DELIVERY_NOT_DONE');
132
+ // The user acceptance follows a committed terminal fence, not merely
133
+ // the model's DONE or an in-flight Context delivery.
134
+ assert(r.writable_ref===null&&r.pending_attempt===null,
135
+ 'TERMINAL_FENCE_REQUIRED');
136
+ // Record one independent decision per delivery. A rejection must
137
+ // proceed through an explicit user-authorized reopen and new delivery.
138
+ assert(current.acceptance==='AWAITING','ACCEPTANCE_ALREADY_RECORDED');
129
139
  const next={...current,acceptance:a.decision==='ACCEPT'?'ACCEPTED':'REJECTED',
130
140
  acceptanceFeedback:{userTurn:a.userTurn,sourceRole:'user',
131
141
  comment:typeof a.comment==='string'?a.comment.slice(0,2000):'',
@@ -140,9 +150,16 @@ export function createTaskMethods(values) {
140
150
  const r=scope(a);written(r,a);
141
151
  assert(typeof a.deliveryRef==='string'&&a.deliveryRef.length>=8,
142
152
  'DELIVERY_REF_REQUIRED');
143
- assert(unresolvedEffects(parse(r.context_json)).length===0,
153
+ const current=parse(r.context_json);
154
+ // A new requestId must not overwrite an already committed delivery.
155
+ // A user-authorized same-scope REOPENED run may deliver a repair.
156
+ assert(current.executionOutcome!=='DONE'
157
+ ||current.stage==='REOPENED'
158
+ &&current.reopenReason==='REPAIR_SAME_SCOPE',
159
+ 'TASK_ALREADY_DELIVERED');
160
+ assert(unresolvedEffects(current).length===0,
144
161
  'UNKNOWN_EFFECTS_UNRESOLVED');
145
- const next={...parse(r.context_json),stage:'DELIVERED',executionOutcome:'DONE',
162
+ const next={...current,stage:'DELIVERED',executionOutcome:'DONE',
146
163
  deliveryRef:a.deliveryRef,acceptance:'AWAITING',deliveredAt:Date.now()};
147
164
  saveTaskContext(a.projectId,a.taskId,next);
148
165
  return {status:'DELIVERED',taskRevision:r.business_revision+1};
@@ -3,7 +3,7 @@
3
3
  // neither path grants Browser Owner or carries forward R/P approvals.
4
4
  import {randomUUID,createHash} from 'node:crypto';
5
5
  import {DatabaseSync} from 'node:sqlite';
6
- import {existsSync,mkdtempSync,renameSync,rmSync,writeFileSync,
6
+ import {lstatSync,mkdtempSync,renameSync,rmSync,writeFileSync,
7
7
  readFileSync} from 'node:fs';
8
8
  import {join,dirname} from 'node:path';
9
9
  // This module declares ports; index.mjs is the only dependency assembler.
@@ -26,6 +26,10 @@ const scopedTables=['checkpoints','documents','issues','artifacts','receipts',
26
26
  'migrations','project_materials','permits','start_leases','tasks','projects'];
27
27
  const allTables=['meta',...scopedTables];
28
28
  const shaFile=file=>createHash('sha256').update(readFileSync(file)).digest('hex');
29
+ const occupied=file=>{
30
+ try{lstatSync(file);return true}
31
+ catch(error){if(error.code==='ENOENT')return false;throw error}
32
+ };
29
33
  function logicalDigest(db){
30
34
  const digest=createHash('sha256');
31
35
  for(const table of allTables){
@@ -74,7 +78,7 @@ async function extractProjectBranch({
74
78
  'PROJECT_VERSION_CONFLICT');
75
79
  privateFile(sourceDb);privateRoot(targetRoot);
76
80
  const target=join(targetRoot,projectId);
77
- ensure(!existsSync(target),'MIGRATION_TARGET_EXISTS');
81
+ ensure(!occupied(target),'MIGRATION_TARGET_EXISTS');
78
82
  // Preflight may not initialize/repair/change the old Store in any way.
79
83
  const source=openContextProtocol(sourceDb,{readOnly:true,principalId:'local-operator',
80
84
  authorizeData:()=>true,authorizeAdmin:()=>true});
@@ -204,7 +208,7 @@ async function extractProjectBranch({
204
208
  writeFileSync(manifest,JSON.stringify(receipt,null,2)+'\n',{flag:'wx',mode:0o600});
205
209
  ensure(readFileSync(manifest,'utf8').includes(receipt.sourceSnapshotHash),
206
210
  'MIGRATION_RECEIPT_UNVERIFIED');
207
- ensure(!existsSync(target),'MIGRATION_TARGET_EXISTS');
211
+ ensure(!occupied(target),'MIGRATION_TARGET_EXISTS');
208
212
  renameSync(stage,target);
209
213
  published=true;
210
214
  return {...receipt,projectDirectory:target};
@@ -233,7 +237,7 @@ export async function fenceLegacyProjectStore({
233
237
  privateFile(sourceDb);
234
238
  privateRoot(dirname(backupPath));
235
239
  privateRoot(dirname(sealManifestPath));
236
- ensure(!existsSync(backupPath)&&!existsSync(sealManifestPath),
240
+ ensure(!occupied(backupPath)&&!occupied(sealManifestPath),
237
241
  'CUTOVER_EVIDENCE_EXISTS');
238
242
  const reader=openContextProtocol(sourceDb,{readOnly:true,principalId:'local-operator',
239
243
  authorizeData:()=>true,authorizeAdmin:()=>true});
@@ -18,6 +18,7 @@ export function configureProjectStore(capabilities){
18
18
 
19
19
  const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
20
20
  const fail=code=>Object.assign(new Error(code),{code});
21
+ const owned=st=>!process.getuid||st.uid===process.getuid();
21
22
  // existsSync follows symlinks and reports a dangling link as absent. Inspect
22
23
  // the actual directory entry so every untrusted root/project/store fails closed.
23
24
  function entryOrMissing(path){
@@ -32,7 +33,7 @@ export function verifiedStoreFile(file,missingCode=null){
32
33
  if(missingCode)throw fail(missingCode);
33
34
  return false;
34
35
  }
35
- if(!st.isFile()||st.isSymbolicLink()||(st.mode&0o077))
36
+ if(!st.isFile()||st.isSymbolicLink()||(st.mode&0o077)||!owned(st))
36
37
  throw fail('STORE_FILE_UNTRUSTED');
37
38
  return true;
38
39
  }
@@ -52,11 +53,12 @@ export function projectDatabase(projectId){
52
53
  const root=contextRoot();
53
54
  const rootEntry=entryOrMissing(root);
54
55
  if(rootEntry&&(!rootEntry.isDirectory()||rootEntry.isSymbolicLink()
55
- ||(rootEntry.mode&0o077)))throw fail('CONTEXT_ROOT_UNTRUSTED');
56
+ ||(rootEntry.mode&0o077)||!owned(rootEntry)))throw fail('CONTEXT_ROOT_UNTRUSTED');
56
57
  const dir=join(root,projectId);
57
58
  const projectEntry=entryOrMissing(dir);
58
59
  if(projectEntry&&(!projectEntry.isDirectory()||projectEntry.isSymbolicLink()
59
- ||(projectEntry.mode&0o077)))throw fail('PROJECT_DIRECTORY_UNTRUSTED');
60
+ ||(projectEntry.mode&0o077)||!owned(projectEntry)))
61
+ throw fail('PROJECT_DIRECTORY_UNTRUSTED');
60
62
  return join(dir,'context.sqlite');
61
63
  }
62
64
  // Real read-only SQLite discovery: never initializes a missing database or turns WAL on.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-context",
3
- "version": "0.6.11",
3
+ "version": "0.6.13",
4
4
  "type": "module",
5
5
  "description": "Independent local Context SDK and short-lived CLI for Chat Loop projects",
6
6
  "publishConfig": {
@@ -34,7 +34,7 @@
34
34
  },
35
35
  "dependencies": {
36
36
  "ps-list": "9.0.0",
37
- "@tomflow/chatloop-extension": "0.4.11",
38
- "@tomflow/chatloop-trace": "0.4.4"
37
+ "@tomflow/chatloop-extension": "0.4.13",
38
+ "@tomflow/chatloop-trace": "0.4.6"
39
39
  }
40
40
  }