@tomflow/chatloop-tools 0.9.64 → 0.9.70
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/node_modules/@tomflow/chatloop-context/README.md +296 -0
- package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +290 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
- package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
- package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +261 -0
- package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
- package/node_modules/@tomflow/chatloop-context/index.mjs +238 -0
- package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
- package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +77 -0
- package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +2036 -0
- package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +69 -0
- package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +338 -0
- package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
- package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +286 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +117 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +134 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +180 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +68 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/run-recovery.mjs +112 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +367 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +398 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +264 -0
- package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
- package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
- package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
- package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +118 -0
- package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +316 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +117 -0
- package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +142 -0
- package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
- package/node_modules/@tomflow/chatloop-context/package.json +38 -0
- package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
- package/node_modules/@tomflow/chatloop-extension/README.md +190 -0
- package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +13 -0
- package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +168 -0
- package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +246 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/entry_test.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +123 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +183 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +390 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/entry_test.js +241 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff-scoped.js +143 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +399 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +60 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +77 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +95 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +329 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +38 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/background.js +33 -0
- package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
- package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
- package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
- package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/entry_test.html +6 -0
- package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +84 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +299 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +172 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +211 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/resource-maintenance.js +159 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +399 -0
- package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +43 -0
- package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
- package/node_modules/@tomflow/chatloop-extension/extension/popup.js +99 -0
- package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/session.html +7 -0
- package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
- package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
- package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +218 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +127 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +296 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +186 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +126 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +287 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +163 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +345 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +209 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +385 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/session-control.js +75 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-action-v2.js +278 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-recovery-v2.js +52 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-v2.js +93 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-continue-recovery-v2.js +78 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-recovery-v2.js +148 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-v2.js +325 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-hold-recovery-v2.js +109 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-dispatch-v2.js +220 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-v2.js +106 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-owner-resolver.js +110 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-recover-v2.js +209 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-routes-v2.js +357 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-run-store.js +400 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-scheduler.js +78 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-start-v2.js +361 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-terminal-v2.js +235 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +205 -0
- package/node_modules/@tomflow/chatloop-extension/index.mjs +78 -0
- package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +19 -0
- package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +82 -0
- package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +378 -0
- package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +89 -0
- package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
- package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +122 -0
- package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +75 -0
- package/node_modules/@tomflow/chatloop-extension/lib/owner-kernel-lock.mjs +106 -0
- package/node_modules/@tomflow/chatloop-extension/lib/owner-ledger.mjs +316 -0
- package/node_modules/@tomflow/chatloop-extension/lib/owner-locked-write.mjs +30 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-cancel-v2.mjs +190 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-continue-v2.mjs +214 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-handoff-v2.mjs +338 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-native-control.mjs +398 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-recovery-v2.mjs +234 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-retire-v2.mjs +70 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-terminal-v2.mjs +143 -0
- package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +228 -0
- package/node_modules/@tomflow/chatloop-extension/package.json +36 -0
- package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +138 -0
- package/node_modules/@tomflow/chatloop-trace/README.md +118 -0
- package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
- package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
- package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
- package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
- package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +308 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +140 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +236 -0
- package/node_modules/@tomflow/chatloop-trace/package.json +28 -0
- package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
- package/node_modules/ps-list/index.d.ts +76 -0
- package/node_modules/ps-list/index.js +366 -0
- package/node_modules/ps-list/license +9 -0
- package/node_modules/ps-list/package.json +44 -0
- package/node_modules/ps-list/readme.md +56 -0
- package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
- package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
- package/package.json +12 -4
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Official Extension/Native owner-evidence contract for Context's reviewed
|
|
2
|
+
// orphan fence. Browser Owner remains Extension's authority, not Context's.
|
|
3
|
+
import {execFileSync} from 'node:child_process';
|
|
4
|
+
import {createHash} from 'node:crypto';
|
|
5
|
+
import {readFileSync,lstatSync} from 'node:fs';
|
|
6
|
+
let readSession,sessionPath,cliPath;
|
|
7
|
+
export function configureOwnerEvidence(api){
|
|
8
|
+
if(readSession)throw Error('EXTENSION_MODULE_ALREADY_COMPOSED');
|
|
9
|
+
for(const name of ['readSession','sessionPath','cliPath'])
|
|
10
|
+
if(typeof api?.[name]!=='function')throw Error('EXTENSION_PORT_MISSING:'+name);
|
|
11
|
+
({readSession,sessionPath,cliPath}=api);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const fail=code=>Object.assign(new Error(code),{code});
|
|
15
|
+
const ensure=(ok,code)=>{if(!ok)throw fail(code)};
|
|
16
|
+
const sha=raw=>createHash('sha256').update(raw).digest('hex');
|
|
17
|
+
const packageVersion=JSON.parse(readFileSync(new URL('../package.json',import.meta.url),'utf8')).version;
|
|
18
|
+
|
|
19
|
+
function checkedNative(){
|
|
20
|
+
const session=readSession();
|
|
21
|
+
ensure(session?.phase==='DONE'&&typeof session.sessionId==='string'
|
|
22
|
+
&&Number.isSafeInteger(session.updatedAt),'NATIVE_NOT_TERMINAL');
|
|
23
|
+
const raw=readFileSync(sessionPath());
|
|
24
|
+
ensure(sha(Buffer.from(JSON.stringify(session)))===
|
|
25
|
+
sha(Buffer.from(JSON.stringify(JSON.parse(raw.toString('utf8'))))),
|
|
26
|
+
'NATIVE_POINTER_UNTRUSTED');
|
|
27
|
+
return {sessionId:session.sessionId,projectId:session.projectId,
|
|
28
|
+
taskId:session.taskId||null,phase:session.phase,
|
|
29
|
+
updatedAt:session.updatedAt,rawHash:sha(raw)};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function checkedExtensionIdle(){
|
|
33
|
+
// This is the Extension-owned CLI, resolved from this installed package.
|
|
34
|
+
// Context never composes an Extension install path or parses its CLI output.
|
|
35
|
+
const cli=cliPath();
|
|
36
|
+
const st=lstatSync(cli);
|
|
37
|
+
ensure(st.isFile()&&!st.isSymbolicLink(),'EXTENSION_CLI_UNTRUSTED');
|
|
38
|
+
const out=execFileSync(process.execPath,[cli,'extension','status'],{
|
|
39
|
+
encoding:'utf8',timeout:14000,maxBuffer:524288,stdio:['ignore','pipe','pipe']});
|
|
40
|
+
const rows=out.trim().split('\n').map(s=>JSON.parse(s));
|
|
41
|
+
const result=rows.findLast(x=>x.event==='RESULT');
|
|
42
|
+
ensure(result?.contract==='chat-loop.extension-cli.v1'
|
|
43
|
+
&&result.command==='extension status'
|
|
44
|
+
&&result.providerVersion===packageVersion
|
|
45
|
+
&&result.ok===true&&result.value?.verified===true
|
|
46
|
+
&&result.value?.truncated===false,'EXTENSION_STATUS_UNVERIFIED');
|
|
47
|
+
const v=JSON.parse(result.value.content||'{}');
|
|
48
|
+
ensure(v.status==='OK'&&v.state==='IDLE'
|
|
49
|
+
&&v.lastSession?.phase==='DONE','EXTENSION_OWNER_NOT_IDLE');
|
|
50
|
+
return v;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Read-only owner proof; NEVER grants execution or signs R/P approval.
|
|
55
|
+
* Re-run before the final Context fence to detect Native/Worker drift.
|
|
56
|
+
*/
|
|
57
|
+
export function verifyOrphanOwnerIdle({oldRunRef,projectId}){
|
|
58
|
+
const native=checkedNative(),extension=checkedExtensionIdle();
|
|
59
|
+
const [oldId,oldTaskId,oldGeneration,...extra]=oldRunRef.split(':');
|
|
60
|
+
ensure(extra.length===0&&oldTaskId&&/^\d+$/.test(oldGeneration),
|
|
61
|
+
'ORPHAN_RUN_REF_INVALID');
|
|
62
|
+
ensure(native.sessionId!==oldId
|
|
63
|
+
&&(native.projectId!==projectId
|
|
64
|
+
||typeof native.taskId==='string'&&native.taskId!==oldTaskId),
|
|
65
|
+
'ORPHAN_OWNER_STILL_CURRENT');
|
|
66
|
+
const live=readSession();
|
|
67
|
+
ensure(live?.phase==='DONE'&&
|
|
68
|
+
extension.lastSession.sessionId===native.sessionId
|
|
69
|
+
&&extension.lastSession.projectId===native.projectId
|
|
70
|
+
&&extension.lastSession.updatedAt===native.updatedAt
|
|
71
|
+
&&extension.lastSession.activeChatId===live.activeChatId
|
|
72
|
+
&&checkedNative().rawHash===native.rawHash,
|
|
73
|
+
'EXTENSION_NATIVE_POINTER_MISMATCH');
|
|
74
|
+
return native;
|
|
75
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// One Native-only V1/V2 Owner mutation lock on macOS.
|
|
2
|
+
// A permanent 0600 marker fences the old O_EXCL writers; lockf -k holds
|
|
3
|
+
// the kernel lock across the entire CAS in a one-shot private subprocess.
|
|
4
|
+
// Never unlink or infer an abandoned legacy lock from its age/PID.
|
|
5
|
+
import {openSync,closeSync,lstatSync,mkdirSync,readFileSync,writeFileSync,
|
|
6
|
+
fsyncSync,unlinkSync} from 'node:fs';
|
|
7
|
+
import {homedir} from 'node:os';
|
|
8
|
+
import {join} from 'node:path';
|
|
9
|
+
import {fileURLToPath} from 'node:url';
|
|
10
|
+
import {spawnSync} from 'node:child_process';
|
|
11
|
+
|
|
12
|
+
const fail=code=>Object.assign(Error(code),{code});
|
|
13
|
+
const marker='CHAT_LOOP_OWNER_KERNEL_LOCK_V1\n';
|
|
14
|
+
const path=()=>join(homedir(),'.chat-loop','session','owner-registry.lock');
|
|
15
|
+
const helper=fileURLToPath(new URL('./owner-locked-write.mjs',import.meta.url));
|
|
16
|
+
const stat=p=>{try{return lstatSync(p)}catch(e){if(e.code==='ENOENT')return null;throw e;}};
|
|
17
|
+
const UUID=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
|
|
18
|
+
const terminal=s=>['DONE','CANCELLED'].includes(s?.phase);
|
|
19
|
+
function checkedOwnerSnapshot(p){
|
|
20
|
+
const st=stat(p);
|
|
21
|
+
if(!st)return null;
|
|
22
|
+
if(!st.isFile()||st.isSymbolicLink()||st.size>128*1024
|
|
23
|
+
||(st.mode&0o077)||(process.getuid&&st.uid!==process.getuid()))
|
|
24
|
+
throw fail('OWNER_LOCK_CUTOVER_UNVERIFIED');
|
|
25
|
+
try{return JSON.parse(readFileSync(p,'utf8'))}
|
|
26
|
+
catch{throw fail('OWNER_LOCK_CUTOVER_UNVERIFIED')}
|
|
27
|
+
}
|
|
28
|
+
function assertLegacyQuiescent(dir){
|
|
29
|
+
// The old O_EXCL lock is held throughout these reads. A live old Writer
|
|
30
|
+
// cannot mutate V1/V2 under us; never strand an ACTIVE legacy Owner by
|
|
31
|
+
// installing a permanent marker before the old session terminates.
|
|
32
|
+
const v1=checkedOwnerSnapshot(join(dir,'active-session.json'));
|
|
33
|
+
if(v1&&(!terminal(v1)||!UUID.test(v1.sessionId||'')
|
|
34
|
+
||typeof v1.projectId!=='string'))
|
|
35
|
+
throw fail('OWNER_LOCK_CUTOVER_ACTIVE');
|
|
36
|
+
const v2=checkedOwnerSnapshot(join(dir,'owner-ledger-v2.json'));
|
|
37
|
+
if(v2&&(v2.schemaVersion!==2||!Number.isSafeInteger(v2.ledgerRevision)
|
|
38
|
+
||!v2.sessions||typeof v2.sessions!=='object'
|
|
39
|
+
||Array.isArray(v2.sessions)
|
|
40
|
+
||Object.values(v2.sessions).some(s=>!terminal(s)
|
|
41
|
+
||!UUID.test(s.sessionId||''))))
|
|
42
|
+
throw fail('OWNER_LOCK_CUTOVER_ACTIVE');
|
|
43
|
+
}
|
|
44
|
+
function ensureMarker(){
|
|
45
|
+
if(process.platform!=='darwin')throw fail('OWNER_KERNEL_LOCK_UNSUPPORTED');
|
|
46
|
+
const file=path(),dir=join(homedir(),'.chat-loop','session');
|
|
47
|
+
// Legacy V1 and V2 both supported a fresh private Session directory.
|
|
48
|
+
if(!stat(dir)){
|
|
49
|
+
try{mkdirSync(dir,{recursive:true,mode:0o700})}
|
|
50
|
+
catch{throw fail('OWNER_LOCK_DIRECTORY_UNTRUSTED')}
|
|
51
|
+
}
|
|
52
|
+
const d=stat(dir);
|
|
53
|
+
if(!d?.isDirectory()||d.isSymbolicLink()||(d.mode&0o077)
|
|
54
|
+
||(process.getuid&&d.uid!==process.getuid()))
|
|
55
|
+
throw fail('OWNER_LOCK_DIRECTORY_UNTRUSTED');
|
|
56
|
+
if(!stat(file)){
|
|
57
|
+
let fd,created=false,promoting=false;
|
|
58
|
+
try{
|
|
59
|
+
// This 'wx' is the LAST use of the old protocol: it excludes every
|
|
60
|
+
// installed V1/V2 writer during both idle checks and marker promotion.
|
|
61
|
+
fd=openSync(file,'wx',0o600);created=true;
|
|
62
|
+
assertLegacyQuiescent(dir);
|
|
63
|
+
// Once promotion begins, never unlink a possibly valid marker:
|
|
64
|
+
// another new process may already be holding a kernel lock on it.
|
|
65
|
+
promoting=true;
|
|
66
|
+
writeFileSync(fd,marker);fsyncSync(fd);
|
|
67
|
+
const parent=openSync(dir,'r');
|
|
68
|
+
try{fsyncSync(parent)}finally{closeSync(parent)}
|
|
69
|
+
}catch(e){
|
|
70
|
+
if(created&&!promoting){try{unlinkSync(file)}catch{}}
|
|
71
|
+
if(e.code!=='EEXIST')
|
|
72
|
+
throw e?.code&&e.code.startsWith('OWNER_')?e
|
|
73
|
+
:fail('OWNER_LOCK_MARKER_WRITE_FAILED');
|
|
74
|
+
}finally{if(fd!==undefined)closeSync(fd)}
|
|
75
|
+
}
|
|
76
|
+
const st=stat(file);
|
|
77
|
+
if(!st?.isFile()||st.isSymbolicLink()||st.size!==Buffer.byteLength(marker)
|
|
78
|
+
||(st.mode&0o077)||(process.getuid&&st.uid!==process.getuid())
|
|
79
|
+
||readFileSync(file,'utf8')!==marker)
|
|
80
|
+
throw fail('OWNER_LOCK_MIGRATION_REQUIRED');
|
|
81
|
+
return file;
|
|
82
|
+
}
|
|
83
|
+
export function withOwnerKernelLock(kind,args){
|
|
84
|
+
if(!['legacy-write','scoped-write','scoped-retire'].includes(kind)
|
|
85
|
+
||!Array.isArray(args))throw fail('OWNER_LOCK_REQUEST_INVALID');
|
|
86
|
+
const file=ensureMarker();
|
|
87
|
+
const result=spawnSync('/usr/bin/lockf',
|
|
88
|
+
['-k','-n','-t','2',file,process.execPath,helper],{
|
|
89
|
+
// Do not kill lockf after acquisition: its child could outlive it
|
|
90
|
+
// and keep writing without the parent-held kernel lock.
|
|
91
|
+
input:JSON.stringify({kind,args}),encoding:'utf8',
|
|
92
|
+
maxBuffer:512*1024
|
|
93
|
+
});
|
|
94
|
+
// A crashed helper may already have committed its atomic rename.
|
|
95
|
+
// Only the kernel's lock-contention exit is a proven no-write result.
|
|
96
|
+
if(result.status===75)throw fail('OWNER_LEDGER_LOCKED');
|
|
97
|
+
if(result.error||result.status!==0||result.signal)
|
|
98
|
+
throw fail('OWNER_WRITE_RECEIPT_UNKNOWN');
|
|
99
|
+
let reply;
|
|
100
|
+
try{reply=JSON.parse(result.stdout)}catch{throw fail('OWNER_WRITE_RECEIPT_UNKNOWN')}
|
|
101
|
+
if(reply?.status==='FAILED'&&typeof reply.code==='string'
|
|
102
|
+
&&/^[A-Z][A-Z0-9_]{1,95}$/.test(reply.code))throw fail(reply.code);
|
|
103
|
+
if(reply?.status!=='OK'||!Object.hasOwn(reply,'result'))
|
|
104
|
+
throw fail('OWNER_WRITE_RECEIPT_UNKNOWN');
|
|
105
|
+
return reply.result;
|
|
106
|
+
}
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
// V2 Native Chat-claim ledger. Data is browser ownership, NOT business Task state.
|
|
2
|
+
import {openSync,closeSync,readFileSync,writeFileSync,renameSync,unlinkSync,
|
|
3
|
+
lstatSync,mkdirSync,fsyncSync} from 'node:fs';
|
|
4
|
+
import {homedir} from 'node:os';
|
|
5
|
+
import {join} from 'node:path';
|
|
6
|
+
import {randomUUID} from 'node:crypto';
|
|
7
|
+
import {withOwnerKernelLock} from './owner-kernel-lock.mjs';
|
|
8
|
+
const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
|
|
9
|
+
const UUID=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
|
|
10
|
+
const CHAT=/^[0-9a-f-]{12,}$/i;
|
|
11
|
+
const URL=/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i;
|
|
12
|
+
const PHASE=new Set(['STARTING','RESERVED','PENDING','WAITING_REPLY','DONE','BLOCKED','CANCELLED']);
|
|
13
|
+
// These are only the phases implemented by the current V2 Start route.
|
|
14
|
+
// Recovery, HANDOFF and terminal fencing require independently reviewed
|
|
15
|
+
// Context proof contracts; no generic backward "resume" is admitted here.
|
|
16
|
+
const NEXT=Object.freeze({
|
|
17
|
+
STARTING:['STARTING','RESERVED','BLOCKED'],
|
|
18
|
+
RESERVED:['RESERVED','PENDING','BLOCKED'],
|
|
19
|
+
PENDING:['PENDING','WAITING_REPLY','BLOCKED'],
|
|
20
|
+
// A new user Turn needs a versioned Context permit + send fence;
|
|
21
|
+
// the current V2 Start-only contract cannot re-enter PENDING.
|
|
22
|
+
WAITING_REPLY:['WAITING_REPLY','BLOCKED','DONE'],
|
|
23
|
+
BLOCKED:['BLOCKED']
|
|
24
|
+
});
|
|
25
|
+
const fail=code=>Object.assign(Error(code),{code});
|
|
26
|
+
const assert=(ok,code)=>{if(!ok)throw fail(code);};
|
|
27
|
+
const directory=()=>join(homedir(),'.chat-loop','session');
|
|
28
|
+
export const ownerLedgerPath=()=>join(directory(),'owner-ledger-v2.json');
|
|
29
|
+
export const ownerLedgerLockPath=()=>join(directory(),'owner-registry.lock');
|
|
30
|
+
export const taskOwnerKey=(projectId,taskId)=>JSON.stringify([projectId,taskId]);
|
|
31
|
+
const terminal=phase=>phase==='DONE'||phase==='CANCELLED';
|
|
32
|
+
const retiredKey=(s)=>JSON.stringify([s.projectId,s.taskId,s.sessionId,s.revision]);
|
|
33
|
+
const RETIRE_HISTORY_LIMIT=256;
|
|
34
|
+
// Small Native-only receipts close the gap when a terminal deletion commits
|
|
35
|
+
// but the one-shot Native ACK is lost before Worker Task Store cleanup.
|
|
36
|
+
const statOrNull=p=>{try{return lstatSync(p);}catch(e){if(e.code==='ENOENT')return null;throw e;}};
|
|
37
|
+
function verifyDir(create=false){
|
|
38
|
+
const dir=directory();
|
|
39
|
+
let st=statOrNull(dir);
|
|
40
|
+
if(!st&&create){mkdirSync(dir,{recursive:true,mode:0o700});st=statOrNull(dir);}
|
|
41
|
+
if(st)assert(st.isDirectory()&&!st.isSymbolicLink()&&
|
|
42
|
+
(!process.getuid||st.uid===process.getuid())&&
|
|
43
|
+
(process.platform==='win32'||!(st.mode&0o077)),'OWNER_DIRECTORY_UNTRUSTED');
|
|
44
|
+
return Boolean(st);
|
|
45
|
+
}
|
|
46
|
+
function checkedFile(file){
|
|
47
|
+
const st=statOrNull(file);
|
|
48
|
+
if(!st)return null;
|
|
49
|
+
assert(st.isFile()&&!st.isSymbolicLink()&&st.size<=128*1024&&
|
|
50
|
+
(!process.getuid||st.uid===process.getuid())&&
|
|
51
|
+
(process.platform==='win32'||!(st.mode&0o077)),'OWNER_FILE_UNTRUSTED');
|
|
52
|
+
return readFileSync(file,'utf8');
|
|
53
|
+
}
|
|
54
|
+
// V1/V2 write wrappers share one Darwin kernel lock; never use the old
|
|
55
|
+
// unlink-on-exit O_EXCL lock or clear a legacy lock based on age/PID.
|
|
56
|
+
function commitOwnerLedger(ledger){
|
|
57
|
+
const encoded=JSON.stringify(ledger)+'\n';
|
|
58
|
+
assert(Buffer.byteLength(encoded)<=128*1024,'OWNER_LEDGER_SIZE_LIMIT');
|
|
59
|
+
const temp=join(directory(),'.owner-ledger-'+randomUUID()+'.tmp');
|
|
60
|
+
try{
|
|
61
|
+
const out=openSync(temp,'wx',0o600);
|
|
62
|
+
try{writeFileSync(out,encoded);fsyncSync(out);}
|
|
63
|
+
finally{closeSync(out);}
|
|
64
|
+
renameSync(temp,ownerLedgerPath());
|
|
65
|
+
const dirFd=openSync(directory(),'r');
|
|
66
|
+
try{fsyncSync(dirFd);}finally{closeSync(dirFd);}
|
|
67
|
+
}finally{try{unlinkSync(temp);}catch{}}
|
|
68
|
+
}
|
|
69
|
+
function validSession(s,persisted=false){
|
|
70
|
+
const names=['projectId','taskId','sessionId','generation','phase',
|
|
71
|
+
'activeChatId','activeChatUrl','updatedAt',...(persisted?['revision']:[])];
|
|
72
|
+
assert(s&&typeof s==='object'&&!Array.isArray(s)&&
|
|
73
|
+
Object.keys(s).length===names.length&&
|
|
74
|
+
names.every(n=>Object.hasOwn(s,n))&&
|
|
75
|
+
ID.test(s.projectId)&&ID.test(s.taskId)&&UUID.test(s.sessionId)&&
|
|
76
|
+
Number.isSafeInteger(s.generation)&&s.generation>=0&&
|
|
77
|
+
PHASE.has(s.phase)&&Number.isSafeInteger(s.updatedAt)&&s.updatedAt>0&&
|
|
78
|
+
(!persisted||Number.isSafeInteger(s.revision)&&s.revision>=1),'OWNER_SESSION_INVALID');
|
|
79
|
+
assert((s.activeChatId===null&&s.activeChatUrl===null)||
|
|
80
|
+
(typeof s.activeChatId==='string'&&CHAT.test(s.activeChatId)&&
|
|
81
|
+
typeof s.activeChatUrl==='string'&&URL.test(s.activeChatUrl)&&
|
|
82
|
+
s.activeChatUrl.endsWith('/'+s.activeChatId)),'OWNER_CHAT_INVALID');
|
|
83
|
+
assert(s.phase!=='WAITING_REPLY'||s.activeChatId!==null,'OWNER_CHAT_INVALID');
|
|
84
|
+
return Object.fromEntries(names.map(n=>[n,s[n]]));
|
|
85
|
+
}
|
|
86
|
+
function validateLedger(obj){
|
|
87
|
+
assert(obj&&typeof obj==='object'&&!Array.isArray(obj)&&
|
|
88
|
+
[3,4].includes(Object.keys(obj).length)
|
|
89
|
+
&&Object.keys(obj).every(k=>['schemaVersion','ledgerRevision',
|
|
90
|
+
'sessions','retired'].includes(k))
|
|
91
|
+
&&obj.schemaVersion===2&&
|
|
92
|
+
Number.isSafeInteger(obj.ledgerRevision)&&obj.ledgerRevision>=0&&
|
|
93
|
+
obj.sessions&&typeof obj.sessions==='object'&&!Array.isArray(obj.sessions),
|
|
94
|
+
'OWNER_LEDGER_INVALID');
|
|
95
|
+
const entries=Object.entries(obj.sessions);
|
|
96
|
+
assert(entries.length<=64,'OWNER_LEDGER_CAPACITY');
|
|
97
|
+
const rawRetired=obj.retired??{};
|
|
98
|
+
assert(rawRetired&&typeof rawRetired==='object'
|
|
99
|
+
&&!Array.isArray(rawRetired)
|
|
100
|
+
&&Object.keys(rawRetired).length<=RETIRE_HISTORY_LIMIT
|
|
101
|
+
&&(obj.retired===undefined||Object.hasOwn(obj,'retired')),
|
|
102
|
+
'OWNER_RETIRE_HISTORY_INVALID');
|
|
103
|
+
const retired=Object.create(null);
|
|
104
|
+
for(const [key,r] of Object.entries(rawRetired)){
|
|
105
|
+
assert(r&&typeof r==='object'&&!Array.isArray(r)
|
|
106
|
+
&&Object.keys(r).length===7
|
|
107
|
+
&&ID.test(r.projectId||'')&&ID.test(r.taskId||'')
|
|
108
|
+
&&UUID.test(r.sessionId||'')
|
|
109
|
+
&&Number.isSafeInteger(r.generation)&&r.generation>=0
|
|
110
|
+
&&Number.isSafeInteger(r.revision)&&r.revision>=1
|
|
111
|
+
&&terminal(r.phase)
|
|
112
|
+
&&Number.isSafeInteger(r.retiredAt)&&r.retiredAt>0
|
|
113
|
+
&&key===retiredKey(r),'OWNER_RETIRE_HISTORY_INVALID');
|
|
114
|
+
retired[key]={...r};
|
|
115
|
+
}
|
|
116
|
+
const sessions=Object.create(null),claims=new Set(),sessionIds=new Set();
|
|
117
|
+
let active=0;
|
|
118
|
+
for(const [key,raw] of entries){
|
|
119
|
+
const s=validSession(raw,true);
|
|
120
|
+
assert(key===taskOwnerKey(s.projectId,s.taskId),'OWNER_TASK_KEY_INVALID');
|
|
121
|
+
const sessionKey=s.sessionId.toLowerCase();
|
|
122
|
+
assert(!sessionIds.has(sessionKey),'OWNER_SESSION_DUPLICATE');
|
|
123
|
+
sessionIds.add(sessionKey);
|
|
124
|
+
if(!terminal(s.phase)){
|
|
125
|
+
active++;
|
|
126
|
+
if(s.activeChatId!==null){
|
|
127
|
+
const claim=s.activeChatId.toLowerCase();
|
|
128
|
+
assert(!claims.has(claim),'OWNER_CHAT_DUPLICATE');
|
|
129
|
+
claims.add(claim);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
sessions[key]=s;
|
|
133
|
+
}
|
|
134
|
+
assert(active<=32,'OWNER_LEDGER_CAPACITY');
|
|
135
|
+
return {schemaVersion:2,ledgerRevision:obj.ledgerRevision,
|
|
136
|
+
sessions,retired};
|
|
137
|
+
}
|
|
138
|
+
export function readOwnerLedger(){
|
|
139
|
+
if(!verifyDir())return null;
|
|
140
|
+
const raw=checkedFile(ownerLedgerPath());
|
|
141
|
+
if(raw===null)return null;
|
|
142
|
+
try{return validateLedger(JSON.parse(raw));}
|
|
143
|
+
catch(e){if(e.code)throw e;throw fail('OWNER_LEDGER_CORRUPT');}
|
|
144
|
+
}
|
|
145
|
+
export function readOwnerLedgerTask(projectId,taskId){
|
|
146
|
+
assert(typeof projectId==='string'&&ID.test(projectId)&&
|
|
147
|
+
typeof taskId==='string'&&ID.test(taskId),'OWNER_TASK_SCOPE_INVALID');
|
|
148
|
+
const ledger=readOwnerLedger();
|
|
149
|
+
return {ledgerRevision:ledger?.ledgerRevision??0,
|
|
150
|
+
session:ledger?.sessions[taskOwnerKey(projectId,taskId)]??null};
|
|
151
|
+
}
|
|
152
|
+
export function hasActiveLedgerOwner(){
|
|
153
|
+
const ledger=readOwnerLedger();
|
|
154
|
+
return Boolean(ledger&&Object.values(ledger.sessions).some(s=>!terminal(s.phase)));
|
|
155
|
+
}
|
|
156
|
+
function assertLegacyInactive(){
|
|
157
|
+
// No V1/V2 split brain: a BLOCKED or UNKNOWN legacy owner stays fenced.
|
|
158
|
+
const raw=checkedFile(join(directory(),'active-session.json'));
|
|
159
|
+
if(raw===null)return;
|
|
160
|
+
let old;
|
|
161
|
+
try{old=JSON.parse(raw);}catch{throw fail('LEGACY_OWNER_UNVERIFIED');}
|
|
162
|
+
assert(old&&terminal(old.phase)&&UUID.test(old.sessionId||''),
|
|
163
|
+
'LEGACY_OWNER_NOT_TERMINAL');
|
|
164
|
+
}
|
|
165
|
+
export function writeOwnerLedgerSession(input,options={}){
|
|
166
|
+
return withOwnerKernelLock('scoped-write',[input,options]);
|
|
167
|
+
}
|
|
168
|
+
export function writeOwnerLedgerSessionLocked(input,{expectedLedgerRevision,
|
|
169
|
+
expectedSessionRevision=null,transitionKind=null}={}){
|
|
170
|
+
const next=validSession(input);
|
|
171
|
+
assert(Number.isSafeInteger(expectedLedgerRevision)&&expectedLedgerRevision>=0,
|
|
172
|
+
'OWNER_LEDGER_CAS_REQUIRED');
|
|
173
|
+
assert(expectedSessionRevision===null||
|
|
174
|
+
Number.isSafeInteger(expectedSessionRevision)&&expectedSessionRevision>=1,
|
|
175
|
+
'OWNER_SESSION_CAS_REQUIRED');
|
|
176
|
+
assert(transitionKind===null
|
|
177
|
+
||['CONTEXT_CONTINUE_PERMITTED','CONTEXT_HANDOFF_PERMITTED',
|
|
178
|
+
'CONTEXT_IDLE_CANCELLED','CONTEXT_HANDOFF_RECOVERED'].includes(transitionKind),
|
|
179
|
+
'OWNER_TRANSITION_AUTHORITY_INVALID');
|
|
180
|
+
verifyDir(true);
|
|
181
|
+
// All Owner transitions still wait only before entering the CAS; a lost
|
|
182
|
+
// post-commit ACK must be investigated, never blindly retried.
|
|
183
|
+
{
|
|
184
|
+
assertLegacyInactive();
|
|
185
|
+
const prior=readOwnerLedger()||{schemaVersion:2,ledgerRevision:0,sessions:{}};
|
|
186
|
+
// The OS-wide lock serializes commits. Global revision is a snapshot
|
|
187
|
+
// watermark, not a reason to reject an unrelated Task's valid Session
|
|
188
|
+
// CAS; cross-Task Chat/Session conflicts are checked against latest data.
|
|
189
|
+
assert(expectedLedgerRevision<=prior.ledgerRevision,'OWNER_LEDGER_CAS_MISMATCH');
|
|
190
|
+
const key=taskOwnerKey(next.projectId,next.taskId),old=prior.sessions[key]||null;
|
|
191
|
+
assert((old?.revision??null)===expectedSessionRevision,
|
|
192
|
+
'OWNER_SESSION_CAS_MISMATCH');
|
|
193
|
+
if(old){
|
|
194
|
+
if(terminal(old.phase)){
|
|
195
|
+
// A later execution Session for this Task must be a fresh, unsent
|
|
196
|
+
// generation-zero reservation. Context must separately approve it.
|
|
197
|
+
assert(old.sessionId.toLowerCase()!==next.sessionId.toLowerCase()
|
|
198
|
+
&&next.generation===0&&
|
|
199
|
+
next.phase==='STARTING'&&next.activeChatId===null,
|
|
200
|
+
'OWNER_RESTART_REQUIRES_PREPERMIT');
|
|
201
|
+
}else{
|
|
202
|
+
const permittedContinue=['CONTEXT_CONTINUE_PERMITTED',
|
|
203
|
+
'CONTEXT_HANDOFF_PERMITTED'].includes(transitionKind)
|
|
204
|
+
&&old.phase==='WAITING_REPLY'&&next.phase==='PENDING'
|
|
205
|
+
&&old.sessionId===next.sessionId
|
|
206
|
+
&&old.generation===next.generation
|
|
207
|
+
&&old.activeChatId===next.activeChatId
|
|
208
|
+
&&old.activeChatUrl===next.activeChatUrl;
|
|
209
|
+
const permittedRecover=transitionKind==='CONTEXT_HANDOFF_RECOVERED'
|
|
210
|
+
&&old.phase==='BLOCKED'&&next.phase==='WAITING_REPLY'
|
|
211
|
+
&&old.sessionId===next.sessionId
|
|
212
|
+
&&old.generation===next.generation
|
|
213
|
+
&&old.activeChatId===next.activeChatId
|
|
214
|
+
&&old.activeChatUrl===next.activeChatUrl;
|
|
215
|
+
const permittedCancel=transitionKind==='CONTEXT_IDLE_CANCELLED'
|
|
216
|
+
&&old.phase==='BLOCKED'&&next.phase==='CANCELLED'
|
|
217
|
+
&&old.sessionId===next.sessionId
|
|
218
|
+
&&old.generation===next.generation
|
|
219
|
+
&&old.activeChatId===next.activeChatId
|
|
220
|
+
&&old.activeChatUrl===next.activeChatUrl;
|
|
221
|
+
assert((transitionKind===null&&NEXT[old.phase]?.includes(next.phase))
|
|
222
|
+
||permittedContinue||permittedCancel||permittedRecover,
|
|
223
|
+
'OWNER_PHASE_TRANSITION_INVALID');
|
|
224
|
+
assert(old.sessionId===next.sessionId,
|
|
225
|
+
'OWNER_SESSION_REPLACEMENT_REQUIRES_FENCE');
|
|
226
|
+
assert(next.generation>=old.generation&&next.generation<=old.generation+1,
|
|
227
|
+
'OWNER_GENERATION_MISMATCH');
|
|
228
|
+
if(next.generation===old.generation)
|
|
229
|
+
assert(old.activeChatId===null||next.activeChatId===old.activeChatId
|
|
230
|
+
&&next.activeChatUrl===old.activeChatUrl,
|
|
231
|
+
'OWNER_CHAT_CHANGED_WITHOUT_HANDOFF');
|
|
232
|
+
else assert(old.activeChatId&&next.activeChatId&&
|
|
233
|
+
old.activeChatId.toLowerCase()!==next.activeChatId.toLowerCase(),
|
|
234
|
+
'OWNER_HANDOFF_UNVERIFIED');
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
for(const [otherKey,owner] of Object.entries(prior.sessions)){
|
|
238
|
+
if(otherKey!==key&&!terminal(owner.phase)&&next.activeChatId&&
|
|
239
|
+
next.activeChatId.toLowerCase()===owner.activeChatId?.toLowerCase()
|
|
240
|
+
&&!terminal(next.phase))
|
|
241
|
+
throw fail('OWNER_CHAT_ALREADY_CLAIMED');
|
|
242
|
+
}
|
|
243
|
+
// Repeated status/projection sync is not a new Native owner CAS event.
|
|
244
|
+
// An unacknowledged changed transition must still re-read exact revision.
|
|
245
|
+
if(old&&['projectId','taskId','sessionId','generation','phase',
|
|
246
|
+
'activeChatId','activeChatUrl'].every(k=>next[k]===old[k]))
|
|
247
|
+
return {ledgerRevision:prior.ledgerRevision,session:old};
|
|
248
|
+
const updated={...next,revision:(old?.revision||0)+1,
|
|
249
|
+
updatedAt:Math.max(next.updatedAt,(old?.updatedAt||0)+1)};
|
|
250
|
+
const sessions={...prior.sessions,[key]:updated};
|
|
251
|
+
const ledger=validateLedger({schemaVersion:2,
|
|
252
|
+
ledgerRevision:prior.ledgerRevision+1,sessions,
|
|
253
|
+
retired:prior.retired??{}});
|
|
254
|
+
commitOwnerLedger(ledger);
|
|
255
|
+
return {ledgerRevision:ledger.ledgerRevision,session:updated};
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// Explicit terminal retirement; called only after Native independently
|
|
260
|
+
// verifies Context's durable delivery/cancel fence. Never prune BLOCKED.
|
|
261
|
+
export function retireOwnerLedgerTerminal(projectId,taskId,options={}){
|
|
262
|
+
return withOwnerKernelLock('scoped-retire',[projectId,taskId,options]);
|
|
263
|
+
}
|
|
264
|
+
export function retireOwnerLedgerTerminalLocked(projectId,taskId,{
|
|
265
|
+
expectedSessionId,expectedGeneration,expectedSessionRevision
|
|
266
|
+
}={}){
|
|
267
|
+
assert(ID.test(projectId||'')&&ID.test(taskId||'')
|
|
268
|
+
&&UUID.test(expectedSessionId||'')
|
|
269
|
+
&&Number.isSafeInteger(expectedGeneration)&&expectedGeneration>=0
|
|
270
|
+
&&Number.isSafeInteger(expectedSessionRevision)
|
|
271
|
+
&&expectedSessionRevision>=1,'OWNER_RETIRE_SCOPE_INVALID');
|
|
272
|
+
verifyDir(true);
|
|
273
|
+
{
|
|
274
|
+
const prior=readOwnerLedger();
|
|
275
|
+
assert(prior,'OWNER_LEDGER_MISSING');
|
|
276
|
+
const key=taskOwnerKey(projectId,taskId),old=prior.sessions[key];
|
|
277
|
+
const receiptKey=retiredKey({projectId,taskId,
|
|
278
|
+
sessionId:expectedSessionId,revision:expectedSessionRevision});
|
|
279
|
+
if(!old){
|
|
280
|
+
// A prior retirement may have committed while its Native reply was
|
|
281
|
+
// lost. An exact in-ledger receipt is read-only, never a new deletion.
|
|
282
|
+
const priorReceipt=prior.retired?.[receiptKey];
|
|
283
|
+
assert(priorReceipt
|
|
284
|
+
&&priorReceipt.generation===expectedGeneration,
|
|
285
|
+
'OWNER_RETIRE_TERMINAL_CAS_MISMATCH');
|
|
286
|
+
return {status:'RETIRED',projectId,taskId,
|
|
287
|
+
sessionId:priorReceipt.sessionId,terminal:priorReceipt.phase,
|
|
288
|
+
ledgerRevision:prior.ledgerRevision,alreadyRetired:true};
|
|
289
|
+
}
|
|
290
|
+
assert(terminal(old.phase)
|
|
291
|
+
&&old.sessionId===expectedSessionId
|
|
292
|
+
&&old.generation===expectedGeneration
|
|
293
|
+
&&old.revision===expectedSessionRevision,
|
|
294
|
+
'OWNER_RETIRE_TERMINAL_CAS_MISMATCH');
|
|
295
|
+
const sessions={...prior.sessions};
|
|
296
|
+
delete sessions[key];
|
|
297
|
+
// A bounded Native receipt outlives one-shot IPC loss. No arbitrary
|
|
298
|
+
// GC of unresolved or in-flight Task sessions.
|
|
299
|
+
const retired={...prior.retired};
|
|
300
|
+
const oldReceipts=Object.entries(retired).filter(([,item])=>
|
|
301
|
+
Date.now()-item.retiredAt>180*24*60*60*1000);
|
|
302
|
+
for(const [key] of oldReceipts)delete retired[key];
|
|
303
|
+
assert(Object.keys(retired).length<RETIRE_HISTORY_LIMIT,
|
|
304
|
+
'OWNER_RETIRE_HISTORY_FULL');
|
|
305
|
+
retired[receiptKey]={projectId,taskId,
|
|
306
|
+
sessionId:old.sessionId,generation:old.generation,
|
|
307
|
+
revision:old.revision,phase:old.phase,retiredAt:Date.now()};
|
|
308
|
+
const ledger=validateLedger({schemaVersion:2,
|
|
309
|
+
ledgerRevision:prior.ledgerRevision+1,sessions,retired});
|
|
310
|
+
commitOwnerLedger(ledger);
|
|
311
|
+
return {status:'RETIRED',projectId,taskId,
|
|
312
|
+
sessionId:old.sessionId,terminal:old.phase,
|
|
313
|
+
ledgerRevision:ledger.ledgerRevision};
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// Private one-shot subprocess, invoked only under macOS lockf -k by
|
|
2
|
+
// owner-kernel-lock.mjs. No independent CLI, MCP tool, service or store.
|
|
3
|
+
// All CAS, legacy exclusion, disk fsync and receipt checks remain in the
|
|
4
|
+
// original V1/V2 domain implementations.
|
|
5
|
+
import {readFileSync} from 'node:fs';
|
|
6
|
+
import {writeSessionLocked} from './session-file.mjs';
|
|
7
|
+
import {writeOwnerLedgerSessionLocked,retireOwnerLedgerTerminalLocked}
|
|
8
|
+
from './owner-ledger.mjs';
|
|
9
|
+
try{
|
|
10
|
+
const raw=readFileSync(0,'utf8');
|
|
11
|
+
if(Buffer.byteLength(raw)>128*1024)throw Error('OWNER_LOCK_REQUEST_TOO_LARGE');
|
|
12
|
+
const request=JSON.parse(raw);
|
|
13
|
+
if(!request||typeof request!=='object'||Array.isArray(request)
|
|
14
|
+
||Object.keys(request).length!==2
|
|
15
|
+
||!Array.isArray(request.args)||request.args.length>8)
|
|
16
|
+
throw Error('OWNER_LOCK_REQUEST_INVALID');
|
|
17
|
+
const fn={
|
|
18
|
+
'legacy-write':writeSessionLocked,
|
|
19
|
+
'scoped-write':writeOwnerLedgerSessionLocked,
|
|
20
|
+
'scoped-retire':retireOwnerLedgerTerminalLocked
|
|
21
|
+
}[request.kind];
|
|
22
|
+
if(typeof fn!=='function')throw Error('OWNER_LOCK_REQUEST_INVALID');
|
|
23
|
+
const result=fn(...request.args);
|
|
24
|
+
process.stdout.write(JSON.stringify({status:'OK',result})+'\n');
|
|
25
|
+
}catch(e){
|
|
26
|
+
const code=/^[A-Z][A-Z0-9_]{1,95}$/.test(e?.code||'')?e.code
|
|
27
|
+
:/^[A-Z][A-Z0-9_]{1,95}$/.test(e?.message||'')?e.message
|
|
28
|
+
:'OWNER_WRITE_FAILED';
|
|
29
|
+
process.stdout.write(JSON.stringify({status:'FAILED',code})+'\n');
|
|
30
|
+
}
|