@tomflow/chatloop-tools 0.9.63 → 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.
Files changed (83) 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 +16 -7
  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/node_modules/@tomflow/chatloop-context/README.md +56 -0
  9. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +24 -0
  10. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +1 -1
  11. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +2 -2
  12. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +69 -0
  13. package/node_modules/@tomflow/chatloop-context/index.mjs +3 -1
  14. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +50 -3
  15. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +54 -1
  16. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +2 -0
  17. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +61 -2
  18. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +33 -0
  19. package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +14 -0
  20. package/node_modules/@tomflow/chatloop-context/lib/core/run-recovery.mjs +112 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +31 -39
  22. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +6 -5
  23. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +84 -3
  24. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +52 -7
  25. package/node_modules/@tomflow/chatloop-context/package.json +2 -4
  26. package/node_modules/@tomflow/chatloop-extension/README.md +66 -0
  27. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +19 -4
  28. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +40 -1
  29. package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +1 -1
  30. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +54 -4
  31. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff-scoped.js +143 -0
  32. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +9 -3
  33. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +9 -5
  34. package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +53 -10
  35. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +34 -0
  36. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +16 -2
  37. package/node_modules/@tomflow/chatloop-extension/extension/background.js +16 -0
  38. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +1 -1
  39. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +7 -6
  40. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +64 -7
  41. package/node_modules/@tomflow/chatloop-extension/extension/loop/resource-maintenance.js +159 -0
  42. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +235 -95
  43. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +1 -0
  44. package/node_modules/@tomflow/chatloop-extension/extension/session.html +1 -0
  45. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +3 -0
  46. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +73 -16
  47. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +23 -6
  48. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +237 -13
  49. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-action-v2.js +278 -0
  50. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-recovery-v2.js +52 -0
  51. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-v2.js +93 -0
  52. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-continue-recovery-v2.js +78 -0
  53. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-recovery-v2.js +148 -0
  54. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-v2.js +325 -0
  55. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-hold-recovery-v2.js +109 -0
  56. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-dispatch-v2.js +220 -0
  57. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-v2.js +106 -0
  58. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-owner-resolver.js +110 -0
  59. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-recover-v2.js +209 -0
  60. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-routes-v2.js +357 -0
  61. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-run-store.js +400 -0
  62. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-scheduler.js +78 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-start-v2.js +361 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-terminal-v2.js +235 -0
  65. package/node_modules/@tomflow/chatloop-extension/index.mjs +7 -0
  66. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +94 -19
  67. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +3 -3
  68. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +9 -2
  69. package/node_modules/@tomflow/chatloop-extension/lib/owner-kernel-lock.mjs +106 -0
  70. package/node_modules/@tomflow/chatloop-extension/lib/owner-ledger.mjs +316 -0
  71. package/node_modules/@tomflow/chatloop-extension/lib/owner-locked-write.mjs +30 -0
  72. package/node_modules/@tomflow/chatloop-extension/lib/scoped-cancel-v2.mjs +190 -0
  73. package/node_modules/@tomflow/chatloop-extension/lib/scoped-continue-v2.mjs +214 -0
  74. package/node_modules/@tomflow/chatloop-extension/lib/scoped-handoff-v2.mjs +338 -0
  75. package/node_modules/@tomflow/chatloop-extension/lib/scoped-native-control.mjs +398 -0
  76. package/node_modules/@tomflow/chatloop-extension/lib/scoped-recovery-v2.mjs +234 -0
  77. package/node_modules/@tomflow/chatloop-extension/lib/scoped-retire-v2.mjs +70 -0
  78. package/node_modules/@tomflow/chatloop-extension/lib/scoped-terminal-v2.mjs +143 -0
  79. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +50 -7
  80. package/node_modules/@tomflow/chatloop-extension/package.json +1 -3
  81. package/node_modules/@tomflow/chatloop-trace/package.json +1 -3
  82. package/package.json +9 -11
  83. package/providers/extension.mjs +59 -16
package/README.md CHANGED
@@ -57,6 +57,18 @@ Usage: chatloop-tools start [desktop-commander|tunnel]
57
57
  Start all enabled tools or one.
58
58
  ```
59
59
 
60
+ ## Task-first MCP/CLI adapter contract (source-only, NOT_RUN)
61
+
62
+ No additional Gateway, npm export or model-directed browser sender is introduced. The same `extension` MCP Provider has **optional** `taskFirst:true` in the existing `start`, `continue`, `handoff` and `session` schemas, and optional exact `projectId+taskId` in `status`. The provider/CLI validates shape and forwards the signed private Action request to the **same** Extension Worker; neither Provider nor Supervisor selects the latest Task, consumes Context Permits or sends to Chat.
63
+
64
+ - `start`: `taskFirst:true,mode:'adopt',confirmed:true` plus an existing original Chat URL, exact TaskKey and Context `start.reserve` lease/epoch/Task/approval revisions; never a first-message send or replacement of another Task.
65
+ - `continue` / `handoff`: `taskFirst:true` and one previously issued Turn Token. Query `intentId` or `lookup:true` is read-only, not a replay permission. QUEUED/PENDING/SEND_BEGIN/UNKNOWN are not proof of a successful Chat send.
66
+ - `status`: no arguments retains legacy V1 status; only both `projectId` and `taskId` select the new read-only Native/Context Task projection. No partial/fuzzy/latest Task selector.
67
+ - `session`: `operation:cancel` 保持原 `taskFirst:true` 或 V1 的精确取消字段与门禁,只允许没有附加 Permit 的空闲原 Chat Adopt;Context 在同事务核 Start-only Permit 历史。`operation:recover-handoff` 则必须为 `taskFirst:true`,带精确 `projectId/taskId/sessionId/generation/expectedNativeRevision/originalAttemptId` 和 `confirmed:true`;MCP Schema/Provider 均与 Cancel 分支隔离,已有 `session` CLI 固定版本继续调用原 Action,且必须在 `session.html` 由真实用户点击后才进入 Worker。恢复仅针对已证明 `NOT_SENT` 的原 Handoff,绝不创建 Chat 或发送。
68
+ - The authenticated Native and Context receivers independently verify the source, current Task/session/generation/Chat, Project ACL and CAS. Supplied `taskFirst` or a plausible URL is never owner authority. Supervisor now also requires the exact private 0600 `owner-registry.lock` kernel-cutover marker before trusting a V2 Native Owner as Context write authority; absent/old/unknown markers stay `NATIVE_OWNER_LOCK_CUTOVER_UNVERIFIED` instead of silently trusting an O_EXCL-only ledger. V1 read-only status keeps its legacy identity checks. Current source includes a strict same-home Session directory guard to avoid Supervisor and Native verifying different Ledgers.
69
+ - These source declarations impact `providers.generated.mjs`, package pin/lock data and distributed Chrome/Native code. **Generators, tests, builds, npm publish, installation and E2E were deliberately NOT_RUN**. The current installed Gateway cannot be claimed to expose this schema until publication and deployment prove it.
70
+ - The Gateway's optional Continue/Handoff Trace correlation now validates returned `projectId` and `taskId` against the same canonical TaskKey character set as the Extension/Context owner contract. A colon-containing task ID is not silently promoted as a trusted correlation label; absent or invalid optional labels do not authorize or cancel a browser Action. This is source-only and unverified at runtime.
71
+
60
72
  ## Capability composition
61
73
 
62
74
  `providers/<id>.mjs` owns each MCP Provider's tool names, schemas,
@@ -65,7 +77,7 @@ activation condition, scoped call adapter and optional CLI commands.
65
77
  The seven built-in Providers are:
66
78
 
67
79
  - `desktop`: allowlisted Desktop Commander tools and isolated fixtures
68
- - `extension`: nine scoped actions delegated to the official Extension CLI, currently resolved through npm `@latest` per invocation (a mutable dist-tag, not a pinned runtime/Chrome version); the received CLI contract must be verified independently. Timeout, missing/invalid CLI identity, and malformed action results return `EXTENSION_RESULT_UNKNOWN`, never a safe-to-retry send failure; the actual Chrome-loaded Owner/version still require separate verification
80
+ - `extension`: nine scoped actions delegated to the official Extension CLI. Legacy V1 actions retain their original resolution policy; **Task-first** `start/continue/handoff` with `taskFirst:true`, and exact-Task `status` are now routed to the fixed Extension version declared by Context (no `@latest` downgrade). Task-first `start` requires real approved original-Chat Adopt + Context lease, `continue/handoff` require original `turnToken`, and `status` requires an explicit `projectId/taskId`; `session cancel` uses a separate exact Native revision; `session recover-handoff` additionally requires an original Handoff attempt, a new signed request and a real Action-page click. Neither is implicit. This is an **unreleased source contract**, not proof the pinned npm package or Chrome extension already supports it. Timeout, missing CLI identity, malformed receipts or mismatched installed version remain `UNKNOWN/BLOCKED` and must never cause a second send. Native Ledger directory must match the canonical session directory outside isolated fixtures; source-only changes have not been tested, installed or published.
69
81
  - `runtime`: exact-request receipt lookup without replay
70
82
  - `context`: independent Context SDK read/write schemas and fixed CLI
71
83
  - `trace`: Project-scoped diagnosis and SOFT stage observations; an independent `api_system` lookup can correlate an individual Form/Document App using its opaque `traceRef` returned by Prepare/Show. App kind remains `UNVERIFIED` when no matching event is found. Diagnosis separates `writerHealth` (Supervisor Writer status) from `gatewayHealth` (including process-wide App observation loss); loss counters appear under `globalObservationWarnings` and are never assigned to a particular Project/Form/Document as an invented `gap`. Missing actual App parent API spans remain scoped gaps. A rendered but unsubmitted Form has no submit event to expect. Source event timestamps remain ISO UTC; operator reports must label their display timezone. These are soft API/UI observations, not authenticated clicks, user-message identity or business approvals.
package/index.mjs CHANGED
@@ -14,7 +14,7 @@ import {probeLocalWriteCapability,trustedSystemTempRoot} from './lib/local-write
14
14
  let auditPort=null;
15
15
  const auditBacklog=[];
16
16
  let auditDraining=false,auditRetryTimer=null,auditNoOwnerRetries=0,auditLost=0;
17
- let auditLastLossCode=null,mcpAudit=null;
17
+ let auditLastLossCode=null,auditLastLossApi=null,auditLastLossPhase=null,mcpAudit=null;
18
18
  let formObservationLost=0,documentObservationLost=0;
19
19
  const OBSERVER_UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
20
20
  const localError=code=>Object.assign(Error(code),{code});
@@ -34,8 +34,8 @@ async function drainAudit(){
34
34
  }catch(error){
35
35
  if(['ENOENT','ECONNREFUSED'].includes(error?.code)&&
36
36
  auditNoOwnerRetries++<MAX_NO_OWNER_RETRIES)break;
37
- auditBacklog.shift(); // unknown telemetry is dropped, not retried
38
- auditLost++;
37
+ const lost=auditBacklog.shift(); // unknown telemetry is dropped, never replayed
38
+ auditLastLossApi=lost?.api||'UNVERIFIED'; auditLastLossPhase=lost?.phase||'UNVERIFIED'; auditLost++;
39
39
  auditLastLossCode=/^[A-Z][A-Z0-9_]{1,95}$/.test(error?.code||'')?error.code:
40
40
  'TRACE_AUDIT_SINK_FAILED';
41
41
  auditNoOwnerRetries=0;
@@ -54,7 +54,8 @@ async function drainAudit(){
54
54
  }
55
55
  const recordApi=event=>{
56
56
  if(auditBacklog.length>=MAX_AUDIT_BACKLOG){
57
- auditLost++;auditLastLossCode='TRACE_AUDIT_BACKLOG_OVERFLOW';return;
57
+ auditLost++;auditLastLossCode='TRACE_AUDIT_BACKLOG_OVERFLOW';
58
+ auditLastLossApi=event?.api||'UNVERIFIED';auditLastLossPhase=event?.phase||'UNVERIFIED';return;
58
59
  }
59
60
  auditBacklog.push(event);
60
61
  if(auditPort){
@@ -63,8 +64,7 @@ const recordApi=event=>{
63
64
  }
64
65
  };
65
66
  const apiAspect=createApiAspect('@tomflow/chatloop-tools',{sink:recordApi});
66
- // A short-lived CLI may finish producing its reply before its soft audit queue
67
- // is delivered. Drain only *after* that reply; never delay an API or replay it.
67
+ // Short-lived CLIs drain soft audit after replying; never delay or replay business calls.
68
68
  async function drainCliTelemetry(timeoutMs=300){
69
69
  const deadline=Date.now()+Math.max(0,Math.min(timeoutMs,750));
70
70
  // The MCP AOP's separate queue must also drain before EOF exits.
@@ -190,7 +190,7 @@ async function runtime(){
190
190
  writerStatus:result.traceHealth.status,
191
191
  formObservationLost,documentObservationLost,
192
192
  apiObservationLost:auditLost,
193
- ...(auditLost?{apiObservationLastErrorCode:auditLastLossCode}:{})};
193
+ ...(auditLost?{apiObservationLastErrorCode:auditLastLossCode,apiObservationLastApi:auditLastLossApi,apiObservationLastPhase:auditLastLossPhase}:{})};
194
194
  if((formObservationLost>0||documentObservationLost>0||auditLost>0)
195
195
  &&health.status==='OK')health.status='TRACE_DEGRADED';
196
196
  return {...result,traceHealth:health};
@@ -5,6 +5,7 @@ import {existsSync,lstatSync,readFileSync} from 'node:fs';
5
5
  import {homedir} from 'node:os';
6
6
  import {join,dirname} from 'node:path';
7
7
  import {loadTrustedRuntime} from '@tomflow/chatloop-context';
8
+ import {assertLegacyContextOwnerOnly,verifyScopedNativeOwner} from './native-owner-v2.mjs';
8
9
  // All internal dependencies are supplied as API contracts by index.mjs.
9
10
  // Private modules never import or resolve another private implementation.
10
11
  let verifyContextEnvelope;
@@ -21,10 +22,19 @@ export function configureContextControlRun(ports){
21
22
  const fail=code=>Object.assign(new Error(code),{code});
22
23
  const assert=(ok,code)=>{if(!ok)throw fail(code)};
23
24
  const supported=new Set(['permit.consume','run.bind.initial','run.fence',
24
- 'run.bind.handoff','run.restore-same-owner','run.fence.terminal',
25
- 'run.credential.rotate','run.fence.cancel','run.terminalStatus','run.reopenStatus','run.snapshot']);
26
- const sessionPath=()=>join(process.env.CHAT_LOOP_CONTEXT_NATIVE_SESSION_DIR||
27
- join(homedir(),'.chat-loop','session'),'active-session.json');
25
+ 'run.bind.handoff','run.restore-same-owner',
26
+ 'run.restore-fenced-handoff','run.fence.terminal',
27
+ 'run.credential.rotate','run.fence.cancel','run.terminalStatus',
28
+ 'run.reopenStatus','run.snapshot','permit.status',
29
+ 'run.idleStartPermitStatus']);
30
+ const sessionPath=()=>{
31
+ const canonical=join(homedir(),'.chat-loop','session');
32
+ const configured=process.env.CHAT_LOOP_CONTEXT_NATIVE_SESSION_DIR;
33
+ if(configured&&configured!==canonical
34
+ &&process.env.CHAT_LOOP_LOCAL_TOOLS_FIXTURES!=='1')
35
+ throw fail('NATIVE_SESSION_DIRECTORY_MISMATCH');
36
+ return join(configured||canonical,'active-session.json');
37
+ };
28
38
  function readNativePointer(){
29
39
  const file=sessionPath();
30
40
  assert(existsSync(file),'NATIVE_SESSION_MISSING');
@@ -45,11 +55,19 @@ export async function handleContextControl(message){
45
55
  throw fail('CONTEXT_RUNTIME_UNSUPPORTED');
46
56
  const payload=verifyContextEnvelope(message);
47
57
  const {command,args}=payload;
58
+ assert(Object.keys(payload).every(k=>['command','args','ownerProofV2'].includes(k)),
59
+ 'CONTEXT_CONTROL_ENVELOPE_INVALID');
48
60
  assert(supported.has(command)&&args&&typeof args==='object'&&!Array.isArray(args),
49
61
  'CONTEXT_COMMAND_INVALID');
50
62
  assert(!['principal','role','internalAuthorized'].some(k=>Object.hasOwn(args,k)),
51
63
  'CLIENT_AUTH_FIELD_FORBIDDEN');
52
- const native=readNativePointer();
64
+ // Signed v2 requests must name the exact owner revision; never derive
65
+ // Task identity from the most-recent global V1 pointer.
66
+ // No Chrome V2 caller is enabled until Native/Worker routing is verified.
67
+ const scoped=Object.hasOwn(payload,'ownerProofV2');
68
+ if(!scoped)assertLegacyContextOwnerOnly();
69
+ const native=scoped?verifyScopedNativeOwner(payload.ownerProofV2)
70
+ :readNativePointer();
53
71
  const runtime=await loadTrustedRuntime();
54
72
  return runtime.execute(command,args,native);
55
73
  }
@@ -36,6 +36,7 @@ const NPX_COMMAND=process.platform==='win32'?'npx.cmd':'npx';
36
36
  const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
37
37
  const CHAT_URL=/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i;
38
38
  const CHAT_ID=/^[0-9a-f-]{12,}$/i;
39
+ const TASK_ID=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
39
40
  // Match the existing Context child-CLI correlation boundary. Never inherit
40
41
  // an unverified stale parent from the supervisor process environment.
41
42
  function childApiEnvironment(){
@@ -56,10 +57,16 @@ function childApiEnvironment(){
56
57
  }catch{delete env.CHAT_LOOP_API_PARENT}
57
58
  return env;
58
59
  }
59
- export const extensionInvocation=name=>{
60
+ export const extensionInvocation=(name,args={})=>{
60
61
  const command=extensionCommand(name);
61
62
  if(!command)return null;
62
- const packageSpec=name==='session'
63
+ const versionPinned=name==='session'
64
+ ||name==='status'&&args.projectId
65
+ ||['start','continue','handoff'].includes(name)
66
+ &&args.taskFirst===true;
67
+ // Task-first is a versioned cross-package contract, never a mutable
68
+ // @latest CLI that could silently downgrade to the global V1 sender.
69
+ const packageSpec=versionPinned
63
70
  ?'@tomflow/chatloop-extension@'+sessionExtensionPin:EXTENSION_PACKAGE;
64
71
  return {executable:NPX_COMMAND,
65
72
  args:['--yes','--package='+packageSpec,'chatloop-extension',...command]};
@@ -97,15 +104,17 @@ export async function forwardExtensionAction(name,args={}) {
97
104
  ||proof.writeReadVerified!==true||proof.cleaned!==true)
98
105
  return fail('START_LOCAL_PREFLIGHT_BLOCKED');
99
106
  }
100
- const invocation=extensionInvocation(name);
107
+ const invocation=extensionInvocation(name,args);
101
108
  if(!invocation)return fail('EXTENSION_PROVIDER_UNTRUSTED');
102
109
  const control=isControlTool(name);
110
+ const scopedStatus=name==='status'
111
+ &&typeof args.projectId==='string'&&typeof args.taskId==='string';
103
112
  if(name==='clean')invocation.args.push(String(args.tabId));
104
113
  const fixedTemp=name==='start'?trustedTempRoot():null;
105
114
  const env=childApiEnvironment();
106
115
  if(fixedTemp)for(const key of ['TMPDIR','TMP','TEMP'])env[key]=fixedTemp;
107
116
  const response=await new Promise(resolve=>{
108
- const child=spawn(invocation.executable,invocation.args,{stdio:[control?'pipe':'ignore','pipe','pipe'],
117
+ const child=spawn(invocation.executable,invocation.args,{stdio:[control||scopedStatus?'pipe':'ignore','pipe','pipe'],
109
118
  cwd:fixedTemp||tmpdir(),windowsHide:true,env});
110
119
  let stdout='',stdoutBytes=0,finished=false,closed=false,tailTimer=null;
111
120
  const settle=(value,receiptCompleted=false)=>{
@@ -148,7 +157,7 @@ export async function forwardExtensionAction(name,args={}) {
148
157
  // Decode UTF-8 incrementally, and accept the completed RESULT frame
149
158
  // without holding the MCP tool response for the CLI's audit tail.
150
159
  child.stdout.setEncoding('utf8');
151
- if(control){
160
+ if(control||scopedStatus){
152
161
  child.stdin.on('error',()=>{});
153
162
  child.stdin.end(JSON.stringify(args));
154
163
  }
@@ -228,11 +237,11 @@ export function formatExtensionResult(name,response) {
228
237
  // Only verified, bounded identifiers can cross into the optional Trace
229
238
  // correlation contract. Missing identifiers are unverified.
230
239
  const correlated=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(proof.sessionId||'')
231
- &&/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(proof.projectId||'')
240
+ &&TASK_ID.test(proof.projectId||'')
232
241
  &&Number.isSafeInteger(proof.generation)&&proof.generation>=0;
233
242
  const traceRef=correlated?{sessionId:proof.sessionId,
234
243
  projectId:proof.projectId,generation:proof.generation,
235
- ...(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(proof.taskId||'')
244
+ ...(TASK_ID.test(proof.taskId||'')
236
245
  ?{taskId:proof.taskId}:{})}:{};
237
246
  if(proof.status==='STATUS'){
238
247
  if(typeof proof.phase!=='string')return fail('INVALID_MODEL_INTENT_REPLY');
@@ -0,0 +1,128 @@
1
+ // Supervisor-only, read-only projection check. Not an Owner authority.
2
+ import {lstatSync,readFileSync} from 'node:fs';
3
+ import {homedir} from 'node:os';
4
+ import {join,dirname} from 'node:path';
5
+
6
+ const ID=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
7
+ const UUID=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
8
+ const CHAT=/^[0-9a-f-]{12,}$/i;
9
+ const CHAT_URL=/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i;
10
+ const PHASE=new Set(['STARTING','RESERVED','PENDING','WAITING_REPLY',
11
+ 'DONE','BLOCKED','CANCELLED']);
12
+ const fail=code=>Object.assign(Error(code),{code});
13
+ const assert=(ok,code)=>{if(!ok)throw fail(code)};
14
+ const paths=()=>{
15
+ const canonical=join(homedir(),'.chat-loop','session');
16
+ const configured=process.env.CHAT_LOOP_CONTEXT_NATIVE_SESSION_DIR;
17
+ // The Chrome Native Host resolves Owner from the account HOME; an
18
+ // independently configured Supervisor directory must not authenticate
19
+ // a different Ledger as the same browser. Test fixtures are isolated.
20
+ if(configured&&configured!==canonical
21
+ &&process.env.CHAT_LOOP_LOCAL_TOOLS_FIXTURES!=='1')
22
+ throw fail('NATIVE_SESSION_DIRECTORY_MISMATCH');
23
+ const dir=configured||canonical;
24
+ return {dir,file:join(dir,'owner-ledger-v2.json'),
25
+ legacy:join(dir,'active-session.json'),
26
+ lock:join(dir,'owner-registry.lock')};
27
+ };
28
+ function entry(path){
29
+ try{return lstatSync(path)}catch(e){
30
+ if(e.code==='ENOENT')return null;
31
+ throw fail('NATIVE_OWNER_STORAGE_UNVERIFIED');
32
+ }
33
+ }
34
+ function privateDir(dir){
35
+ const st=entry(dir);
36
+ if(st)assert(st.isDirectory()&&!st.isSymbolicLink()&&
37
+ (!process.getuid||st.uid===process.getuid())&&
38
+ (process.platform==='win32'||(st.mode&0o077)===0),
39
+ 'NATIVE_OWNER_STORAGE_UNTRUSTED');
40
+ return Boolean(st);
41
+ }
42
+ function privateData(file){
43
+ if(!privateDir(dirname(file)))return null;
44
+ const st=entry(file);
45
+ if(!st)return null;
46
+ assert(st.isFile()&&!st.isSymbolicLink()&&st.size<=128*1024&&
47
+ (!process.getuid||st.uid===process.getuid())&&
48
+ (process.platform==='win32'||(st.mode&0o077)===0),
49
+ 'NATIVE_OWNER_STORAGE_UNTRUSTED');
50
+ try{return JSON.parse(readFileSync(file,'utf8'))}
51
+ catch{throw fail('NATIVE_OWNER_STORAGE_CORRUPT')}
52
+ }
53
+ function ledger(){
54
+ const data=privateData(paths().file);
55
+ if(!data)return null;
56
+ assert(data.schemaVersion===2&&Number.isSafeInteger(data.ledgerRevision)
57
+ &&data.ledgerRevision>=0&&data.sessions&&
58
+ typeof data.sessions==='object'&&!Array.isArray(data.sessions)&&
59
+ Object.keys(data.sessions).length<=64,'NATIVE_OWNER_LEDGER_INVALID');
60
+ const active=new Set(),sessionIds=new Set();
61
+ for(const [key,s] of Object.entries(data.sessions)){
62
+ assert(s&&typeof s==='object'&&ID.test(s.projectId||'')
63
+ &&ID.test(s.taskId||'')&&UUID.test(s.sessionId||'')
64
+ &&key===JSON.stringify([s.projectId,s.taskId])
65
+ &&Number.isSafeInteger(s.revision)&&s.revision>=1
66
+ &&Number.isSafeInteger(s.generation)&&s.generation>=0
67
+ &&Number.isSafeInteger(s.updatedAt)&&s.updatedAt>0
68
+ &&PHASE.has(s.phase)
69
+ &&(s.activeChatId===null&&s.activeChatUrl===null
70
+ ||typeof s.activeChatId==='string'&&CHAT.test(s.activeChatId)
71
+ &&typeof s.activeChatUrl==='string'&&CHAT_URL.test(s.activeChatUrl)
72
+ &&s.activeChatUrl.endsWith('/'+s.activeChatId))
73
+ &&(s.phase!=='WAITING_REPLY'||s.activeChatId!==null)
74
+ ,'NATIVE_OWNER_LEDGER_INVALID');
75
+ const sessionKey=s.sessionId.toLowerCase();
76
+ assert(!sessionIds.has(sessionKey),'NATIVE_OWNER_DUPLICATE_SESSION');
77
+ sessionIds.add(sessionKey);
78
+ if(s.phase!=='DONE'&&s.phase!=='CANCELLED'&&s.activeChatId){
79
+ const claim=s.activeChatId.toLowerCase();
80
+ assert(!active.has(claim),'NATIVE_OWNER_DUPLICATE_CHAT');
81
+ active.add(claim);
82
+ }
83
+ }
84
+ return data;
85
+ }
86
+ function assertKernelLockCutover(){
87
+ // The new Native V1/V2 writers only operate under this persistent
88
+ // marker plus Darwin lockf. An older O_EXCL-only Native ledger must not
89
+ // be promoted into a new scoped Context write authority by Supervisor.
90
+ const file=paths().lock,st=entry(file);
91
+ assert(st?.isFile()&&!st.isSymbolicLink()
92
+ &&st.size===Buffer.byteLength('CHAT_LOOP_OWNER_KERNEL_LOCK_V1\n')
93
+ &&(st.mode&0o077)===0
94
+ &&(!process.getuid||st.uid===process.getuid()),
95
+ 'NATIVE_OWNER_LOCK_CUTOVER_UNVERIFIED');
96
+ assert(readFileSync(file,'utf8')==='CHAT_LOOP_OWNER_KERNEL_LOCK_V1\n',
97
+ 'NATIVE_OWNER_LOCK_CUTOVER_UNVERIFIED');
98
+ }
99
+ function legacyInactive(){
100
+ const old=privateData(paths().legacy);
101
+ assert(!old||old.phase==='DONE'||old.phase==='CANCELLED',
102
+ 'NATIVE_LEGACY_OWNER_ACTIVE');
103
+ }
104
+ export function assertLegacyContextOwnerOnly(){
105
+ const data=ledger();
106
+ assert(!data||Object.values(data.sessions)
107
+ .every(s=>s.phase==='DONE'||s.phase==='CANCELLED'),
108
+ 'NATIVE_SCOPED_OWNER_ACTIVE');
109
+ }
110
+ export function verifyScopedNativeOwner(proof){
111
+ assert(proof&&typeof proof==='object'&&!Array.isArray(proof)&&
112
+ Object.keys(proof).length===7&&
113
+ ID.test(proof.projectId||'')&&ID.test(proof.taskId||'')
114
+ &&UUID.test(proof.sessionId||'')
115
+ &&Number.isSafeInteger(proof.generation)&&proof.generation>=0
116
+ &&Number.isSafeInteger(proof.revision)&&proof.revision>=1
117
+ &&PHASE.has(proof.phase)
118
+ &&(proof.activeChatId===null||
119
+ typeof proof.activeChatId==='string'&&CHAT.test(proof.activeChatId)),
120
+ 'NATIVE_SCOPED_PROOF_INVALID');
121
+ assertKernelLockCutover();
122
+ legacyInactive();
123
+ const current=ledger()?.sessions[JSON.stringify([proof.projectId,proof.taskId])];
124
+ assert(current&&['projectId','taskId','sessionId','generation',
125
+ 'revision','phase','activeChatId'].every(k=>current[k]===proof[k]),
126
+ 'NATIVE_SCOPED_PROOF_STALE');
127
+ return current;
128
+ }
@@ -25,8 +25,26 @@ export async function verifyTunnelConnection(p,verified,ports={}){
25
25
  ||!existsSync(healthFile))
26
26
  throw Object.assign(Error('NEW_RUNTIME_TUNNEL_PROBE_UNAVAILABLE'),{
27
27
  code:'NEW_RUNTIME_TUNNEL_PROBE_UNAVAILABLE'});
28
+ // A freshly started Tunnel can establish remote control-plane polling
29
+ // after the local readyz comes up. Keep the exact PID and all three hard
30
+ // checks; allow bounded warmup rather than treating the first 30 failures
31
+ // as terminal. The explicit wait port is used only by isolated fixtures.
32
+ const maxAttempts=60;
33
+ const wait=ports.wait??(ms=>new Promise(resolve=>setTimeout(resolve,ms)));
34
+ const safeStatus=value=>{
35
+ let status=value;
36
+ if(typeof value==='string'){
37
+ try{status=JSON.parse(value.trim())}catch{return null}
38
+ }
39
+ if(!status||typeof status!=='object'||Array.isArray(status))return null;
40
+ // Never return raw health JSON; it can contain URLs or credentials.
41
+ return {result:status.result==='ok'?'ok':'not_ready',
42
+ healthz:status.healthz?.ok===true,
43
+ readyz:status.readyz?.ok===true,
44
+ controlPlanePoll:status.control_plane_poll?.ok===true};
45
+ };
28
46
  let last;
29
- for(let attempt=0;attempt<30;attempt++){
47
+ for(let attempt=0;attempt<maxAttempts;attempt++){
30
48
  try{
31
49
  const output=await run(binary,['health','--url-file',healthFile,
32
50
  '--pid',String(tunnel.pid),'--require-control-plane-poll','--json'],
@@ -35,12 +53,18 @@ export async function verifyTunnelConnection(p,verified,ports={}){
35
53
  if(result.result==='ok'&&result.healthz?.ok===true
36
54
  &&result.readyz?.ok===true&&result.control_plane_poll?.ok===true)
37
55
  return {result:'ok',pid:tunnel.pid,controlPlanePoll:true};
38
- last=result;
39
- }catch(error){last={code:error.code||'TUNNEL_HEALTH_FAILED'};}
40
- await new Promise(resolve=>setTimeout(resolve,500));
56
+ last=safeStatus(result)||{code:'TUNNEL_PROBE_UNVERIFIED'};
57
+ }catch(error){
58
+ last={code:/^[A-Z][A-Z0-9_]{1,95}$/.test(error?.code||'')
59
+ ?error.code:'TUNNEL_HEALTH_FAILED',
60
+ ...(Number.isSafeInteger(error?.status)?{exitCode:error.status}:{}),
61
+ ...(safeStatus(error?.stdout)||{})};
62
+ }
63
+ if(attempt+1<maxAttempts)await wait(500);
41
64
  }
42
65
  throw Object.assign(Error('NEW_RUNTIME_TUNNEL_CONNECTION_UNHEALTHY'),{
43
- code:'NEW_RUNTIME_TUNNEL_CONNECTION_UNHEALTHY',tunnelStatus:last});
66
+ code:'NEW_RUNTIME_TUNNEL_CONNECTION_UNHEALTHY',
67
+ attempts:maxAttempts,tunnelStatus:last});
44
68
  }
45
69
  export async function verifyMcpTools(p,ports={}){
46
70
  const {runtimeLaunchEnv}=ports;
@@ -234,7 +234,9 @@ export async function runTraceDiagnose(args){
234
234
  if(health?.apiObservationLost>0){
235
235
  globalWarnings.push('MCP_API_TRACE_OBSERVATION_LOSS');
236
236
  result.globalApiObservationLoss={count:health.apiObservationLost,
237
- lastErrorCode:health.apiObservationLastErrorCode||'UNVERIFIED'};
237
+ lastErrorCode:health.apiObservationLastErrorCode||'UNVERIFIED',
238
+ lastApi:health.apiObservationLastApi||'UNVERIFIED',
239
+ lastPhase:health.apiObservationLastPhase||'UNVERIFIED'};
238
240
  }
239
241
  if(globalWarnings.length)result.globalObservationWarnings=globalWarnings;
240
242
  if(result.writerHealth==='TRACE_DEGRADED'){
@@ -61,6 +61,62 @@ import {
61
61
  action. They organize trusted integrators behind **the same root**; they are
62
62
  not ordinary model/MCP operations.
63
63
 
64
+ **Task-scoped Native Writer read (unreleased source contract):**
65
+ `loadTrustedRuntime().execute('run.terminalStatus',args,native)` uses
66
+ an exact, independently verified `projectId/taskId/sessionId/generation`
67
+ Native owner projection. Its read-only result includes
68
+ `pendingHandoff: boolean` (from the authoritative Task
69
+ `pending_attempt`) and `pendingCheckpointId: string|null` (from
70
+ `pending_checkpoint`) alongside the existing `runRef`,
71
+ `bindingRevision`, `unknownEffectCount` and execution outcome.
72
+ It also reports `writerApprovalCurrent` and `projectRulesDrift`
73
+ from the same authoritative Task/Project snapshot; a later R/P change
74
+ or Project rule drift cannot silently inherit the old Writer.
75
+ A bound `runRef` by itself is **not** a safe Continue permission:
76
+ Native/Worker must reject a pending Handoff, pending Checkpoint,
77
+ an UNKNOWN effect or a stale owner. `run.snapshot` means the latest
78
+ immutable Checkpoint, **not** the live pending-attempt status.
79
+ When a signed Native Owner is already in `PENDING`, this private
80
+ `run.terminalStatus` may additionally accept the exact
81
+ `expectedHandoffAttemptId` (128-bit original signed Handoff request).
82
+ Context compares it with the authoritative `pending_attempt` inside
83
+ its read snapshot and returns only `pendingAttemptMatches: boolean`.
84
+ It never reveals the pending request ID, credential or digest, and never
85
+ releases a fenced Writer. The trusted adapter refuses the probe outside
86
+ Native PENDING except for a positive-revision V2 Native BLOCKED Owner
87
+ with an existing Chat, strictly for the original abort-revocation
88
+ **read-only** receipt; it always rejects a probe combined with Start
89
+ recovery. The Handoff Native consumer requires
90
+ `pendingAttemptMatches===true` before accepting the original
91
+ pending-fence or revoked-abort proof. The BLOCKED read cannot revive a
92
+ Writer, consume a Permit, replay Handoff or change Task data. This is NOT authorization to replay or
93
+ restore a Chat send.
94
+
95
+ A signed, exact V2 Native Task Status may also read
96
+ `run.terminalStatus` while generation zero is `STARTING/RESERVED/PENDING`
97
+ with both `activeChatId` and `activeChatUrl` null. This narrowly
98
+ scoped exception requires a positive V2 Native Session revision and
99
+ does not apply to V1, later generations, writes, Permit consumption
100
+ or `run.bind.initial`. It lets the existing Status Action report the
101
+ pre-Adopt phase instead of failing solely because no Chat has yet
102
+ been claimed.
103
+
104
+ This is an additive **internal trusted read**; it does not add a public
105
+ SDK method, MCP tool, writer, retry capability or browser send. Source
106
+ is not yet rebuilt, deployed or tested.
107
+
108
+ The private `loadTrustedRuntime().execute(command,...)` facade additionally
109
+ accepts `permit.status` (the exact original Task + actionToken, returning
110
+ bounded recorded kind/approval revision) and
111
+ `run.idleStartPermitStatus` (whether the **only** permit in that Task is
112
+ the consumed original START permit). The latter is preliminary evidence:
113
+ `run.fence.cancel` repeats the same original START-only Permit check inside
114
+ **its own SQLite transaction**, so a concurrent CONTINUE/HANDOFF reservation
115
+ cannot slip between the read and cancellation commit. V2 Context reads
116
+ also supply the fixed `storeEpoch` and current Project/R/P writer checks.
117
+ Neither method is an open/public `context.*` capability or additional
118
+ MCP tool. One Task's SQLite revisions never authorize another Task.
119
+
64
120
  See [provider / consumer / dependency matrix](docs/interfaces.md) for the
65
121
  **complete** cross-module reference. For exact method IDs, schemas and
66
122
  semantics, use `sdk.methods.list` / `sdk.methods.describe` on the connected SDK.
@@ -160,6 +160,30 @@ export const capability={
160
160
  "minLength": 8,
161
161
  "maxLength": 128
162
162
  },
163
+ "literalRevision": {
164
+ "type": "object",
165
+ "additionalProperties": false,
166
+ "required": ["baseVersion", "baseContentHash", "replacements"],
167
+ "properties": {
168
+ "baseVersion": {"type": "integer", "minimum": 1},
169
+ "baseContentHash": {"type": "string", "pattern": "^[a-f0-9]{64}$"},
170
+ "replacements": {
171
+ "type": "array",
172
+ "minItems": 1,
173
+ "maxItems": 32,
174
+ "items": {
175
+ "type": "object",
176
+ "additionalProperties": false,
177
+ "required": ["from", "to", "expectedCount"],
178
+ "properties": {
179
+ "from": {"type": "string", "minLength": 1},
180
+ "to": {"type": "string"},
181
+ "expectedCount": {"type": "integer", "minimum": 1, "maximum": 100}
182
+ }
183
+ }
184
+ }
185
+ }
186
+ },
163
187
  "requirementRef": {
164
188
  "type": "object",
165
189
  "additionalProperties": false,
@@ -9,7 +9,7 @@ export const capability={
9
9
  "id": "start.reserve",
10
10
  "group": "start",
11
11
  "mode": "write",
12
- "description": "Reserve a short-lived start lease after both effective R/P approvals.",
12
+ "description": "Reserve a short-lived Start lease after both effective R/P approvals; an explicit Task executionPermission (including review-only or unknown) is a restriction and cannot be overridden by R/P. Legacy tasks without this field retain their prior Start eligibility. No installation or filesystem grants.",
13
13
  "inputSchema": {
14
14
  "type": "object",
15
15
  "required": [
@@ -97,7 +97,7 @@ export const capability={
97
97
  "id": "task.create",
98
98
  "group": "task",
99
99
  "mode": "write",
100
- "description": "Create a project-scoped task with an initial DRAFT state.",
100
+ "description": "Create a project-scoped DRAFT task without durable review-only executionPermission. Current-round R/P limits are not permanent Task scope; R/P approvals and Stage 03 independently guard Start. Existing legacy restrictions remain enforced.",
101
101
  "inputSchema": {
102
102
  "type": "object",
103
103
  "required": [
@@ -437,7 +437,7 @@ export const capability={
437
437
  "id": "task.patch",
438
438
  "group": "task",
439
439
  "mode": "write",
440
- "description": "Patch permitted Task fields with revision and run-holder checks.",
440
+ "description": "Patch permitted Task fields with CAS/run-holder checks; an R/P-approved idle Task may report bounded preflight progress, blockers and nextStep only.",
441
441
  "inputSchema": {
442
442
  "type": "object",
443
443
  "required": [
@@ -66,6 +66,36 @@ contract; this prose document is not a parallel API schema authority.
66
66
  Ordinary MCP **never exposes** `permit.consume`, `run.bind.initial`,
67
67
  `run.fence`, `run.bind.handoff` or other private Run/Permit actions.
68
68
 
69
+ ### Task creation vs. legacy review-only restrictions
70
+
71
+ Public `task.create` creates a DRAFT task without accepting `context.executionPermission` (`TASK_CREATE_REVIEW_SCOPE_FORBIDDEN`). Stage 01/02 review-round restrictions belong to the Workflow and R/P approval flow, not permanent Task execution scope. This change **does not grant execution**: Stage 03 still requires effective R/P approvals and independent authorization for any filesystem, installation or browser operation. Existing Task records carrying review-only/unknown `executionPermission` are not silently migrated or made executable; `start.reserve`, Native START permit and initial run bind remain fail-closed. A clearly requested review-only engagement should finish at its authorized review scope, without manufacturing a future implementation/Start permission.
72
+
73
+ ### Local operator: correct an incorrectly permanent review-only Task
74
+
75
+ `chatloop-context task correct-review-scope <projectId> <taskId> <taskRevision> <approvalRevision> <storeEpoch> <expectedPermission> <operatorEvidenceRef> <writeRequestId>`
76
+
77
+ This is an **independent local operator** action, not an SDK/MCP method
78
+ or a model-executable task mutation. It requires the existing
79
+ `CHAT_LOOP_CONTEXT_ADMIN_ENABLE=1`, exact allowed Project, a real
80
+ interactive TTY confirmation bound to the Task, both revisions, epoch,
81
+ old permission and original-intent evidence reference. Operator must
82
+ independently inspect the original user request and R/P before consenting.
83
+ A normal non-interactive MCP process is rejected. Reconcile an uncertain
84
+ write only with `task scope-correction-receipt <projectId> <storeEpoch> <writeRequestId>`;
85
+ do not repeat the mutation with a new ID.
86
+
87
+ Core rejects mismatched CAS, unapproved or pending R/P, project drift,
88
+ any prior Start lease or permit, active/pending Run, unresolved effects,
89
+ an unknown permission value, or a second correction. It preserves
90
+ original R/P and approved hashes, Project and read-only Workspace bounds,
91
+ Task identity and original objective, and records a durable audit note.
92
+ The receipt `SCOPE_CORRECTED_NOT_OPERATION_AUTHORIZED` **does not authorize**
93
+ installation, download, temporary writes, packing, repository access,
94
+ browser sending or Stage 04; those are independently checked against
95
+ the approved Pn and actual user/operator authorization. The current
96
+ production version may not contain this source-only operator command
97
+ until the Context release is installed and verified.
98
+
69
99
  ## 4. Provider → consumer matrix (actual source paths)
70
100
 
71
101
  | Provider | API / action consumed | Actual consumer | Boundary and result |
@@ -102,6 +132,32 @@ The Tools private handler passes a signed-IPC-verified Native projection into th
102
132
 
103
133
  `run.fence.cancel` is a Native/Worker-only, exact-Session idle Adopt cancellation transaction. It revokes the current writable Run credential, seals permits, records `CANCELLED_NOT_DELIVERED`, and never manufactures Task `DONE` or a `deliveryRef`. A matching Native BLOCKED Owner and verified private `session` Action request are prerequisites; after the Context receipt, Native checks the terminal marker again before allowing the `CANCELLED` Session CAS. Ordinary Context MCP clients cannot invoke this private command. An interrupted or unknown receipt stays BLOCKED pending original-request reconciliation; it is not permission to retry or clear the Owner.
104
134
 
135
+ The new private V2 `permit.consume(kind:RECOVER_HANDOFF)` and
136
+ `run.restore-fenced-handoff` share the existing Task SQLite/receipt
137
+ transactions, not the V1 `RESERVED` restore. The permit is only
138
+ consumable while the exact Native Owner is `BLOCKED`, and the
139
+ transaction checks the original pending attempt, pinned checkpoint,
140
+ successor generation/RunRef, existing USED Handoff permit, current
141
+ approved R/P, zero unresolved effects, unique unused recovery permit,
142
+ CAS and fresh credential before rebinding the original generation.
143
+ The original Extension `session` Action now has a source-only
144
+ `recover-handoff` route through the Native BLOCKED Owner, Worker
145
+ `NOT_SENT` evidence and the signed Tools Supervisor IPC. The original
146
+ private recovery request generates one credential; a lost ACK must
147
+ reconcile the same request's USED permit, Context binding and Native
148
+ CAS, not mint a second permit. **None of this is run, packaged,
149
+ published or E2E-accepted**; a Context method alone never authorizes
150
+ a browser send or proves that the installed Writer was restored.
151
+
152
+ The existing V1 `run.restore-same-owner` is not a V2 Handoff
153
+ recovery contract: it requires the old Native `RESERVED` phase.
154
+ Its Context transaction independently rejects any already delivered,
155
+ cancelled or unresolved-effect Task before rebinding a Writer, even
156
+ when the original Checkpoint and single-use CONTINUE permit match.
157
+ It also requires the pending Handoff to target exactly the same
158
+ Session's next generation and RunRef; a same-attempt receipt alone
159
+ cannot redirect recovery to a different successor.
160
+
105
161
  The Browser Native Host now permits the Worker-used `run.reopenStatus`
106
162
  through the same signed private IPC path; it is not a public MCP method.
107
163
  For first-Start recovery, `run.terminalStatus` accepts the private
@@ -113,6 +169,19 @@ no writer/unknown effect exists, and current approvals remain valid.
113
169
  expired unused initial leases transactionally; the read-only proof does not
114
170
  grant a permit, bind a writer, or replace a Session.
115
171
 
172
+ For V2 Handoff, the same trusted `run.terminalStatus` accepts
173
+ `expectedHandoffAttemptId` with the independently checked Native
174
+ `PENDING` Owner, or with its exact positive-revision `BLOCKED` Owner
175
+ after the original pre-SEND_BEGIN Native abort fence. This remains a
176
+ read-only proof, never a Start recovery lease or a Writer recovery.
177
+ Context compares the signed original attempt to `pending_attempt`
178
+ inside the SQLite read snapshot and exposes only
179
+ `pendingAttemptMatches: boolean` rather than an ID or credential.
180
+ Native requires this match and the original USED Handoff Permit to
181
+ authorize `send-check` while PENDING, or to confirm the revoked
182
+ `handoff-abort-fence-read-v2` receipt once BLOCKED. No probe permits
183
+ replaying a SEND_BEGIN-unknown effect or reviving Context Writer.
184
+
116
185
  ## 5. Context → external dependencies (reverse direction)
117
186
 
118
187
  | External owner / dependency | Context call, file or mechanism | Source | Coupling and scope |
@@ -38,7 +38,7 @@ function sdkRuntime(){
38
38
  if(!sdkPromise)sdkPromise=(async()=>{
39
39
  const [
40
40
  core,health,migrationCore,projectCore,taskCore,reviewCore,
41
- evidenceCore,contextCore,runCore,cancelCore,migration,policy,methods,
41
+ evidenceCore,contextCore,runCore,cancelCore,recoveryCore,migration,policy,methods,
42
42
  projectStore,operations,lineReview
43
43
  ]=await Promise.all([
44
44
  import('./lib/core/store.mjs'),import('./lib/core/health.mjs'),
@@ -46,6 +46,7 @@ function sdkRuntime(){
46
46
  import('./lib/core/task.mjs'),import('./lib/core/review.mjs'),
47
47
  import('./lib/core/evidence.mjs'),import('./lib/core/context.mjs'),
48
48
  import('./lib/core/run.mjs'),import('./lib/core/run-cancel.mjs'),
49
+ import('./lib/core/run-recovery.mjs'),
49
50
  import('./lib/context-migration.mjs'),
50
51
  import('./lib/approval-policy.mjs'),import('./lib/methods.mjs'),
51
52
  import('./lib/project-store.mjs'),import('./lib/operations.mjs'),
@@ -64,6 +65,7 @@ function sdkRuntime(){
64
65
  createContextMethods:contextCore.createContextMethods,
65
66
  createRunMethods:runCore.createRunMethods,
66
67
  createCancelMethods:cancelCore.createCancelMethods,
68
+ createRecoveryMethods:recoveryCore.createRecoveryMethods,
67
69
  verifySourceUnit:migration.verifySourceUnit,
68
70
  inspectRegistryReferenceForReview:migration.inspectRegistryReferenceForReview,
69
71
  hasApprovedPlan:policy.hasApprovedPlan,