@christang/keel 5.231.1 → 5.231.3

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.231.1",
3
+ "version": "5.231.3",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.231.1 -->
1
+ <!-- keel:start version=5.231.3 -->
2
2
  ## Keel Bootstrap
3
3
 
4
4
  - Start every session with `keel context`; OpenSpec artifacts and Git are the durable authority, and memory or transcripts may only inform.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.231.1",
3
+ "version": "5.231.3",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.231.1",
9
+ "version": "5.231.3",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@fission-ai/openspec": "1.14.0"
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@christang/keel",
3
3
  "displayName": "Keel",
4
4
  "description": "Keel OpenSpec execution discipline CLI for Claude Code, Codex, and OpenCode.",
5
- "version": "5.231.1",
5
+ "version": "5.231.3",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.231.1",
3
+ "version": "5.231.3",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.231.1",
3
+ "version": "5.231.3",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -19,7 +19,9 @@ async function fixture(){
19
19
  const requests=[],peers=[],servers=[],controls={};
20
20
  async function host(name){
21
21
  const sock=path.join(dir,name+'.sock'),server=http.createServer();servers.push(server);
22
- server.on('upgrade',(req,s)=>{peers.push(s);s.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: '+crypto.createHash('sha1').update(req.headers['sec-websocket-key']+'258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64')+'\r\n\r\n');let buf=Buffer.alloc(0);
22
+ server.on('upgrade',(req,s)=>{peers.push(s);
23
+ s.on('error',error=>{if(error.code!=='ECONNRESET')throw error;});
24
+ s.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: '+crypto.createHash('sha1').update(req.headers['sec-websocket-key']+'258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64')+'\r\n\r\n');let buf=Buffer.alloc(0);
23
25
  s.on('data',chunk=>{buf=Buffer.concat([buf,chunk]);while(buf.length>=6){let len=buf[1]&127,offset=2;if(len===126){if(buf.length<8)return;len=buf.readUInt16BE(2);offset=4;}else if(len===127){if(buf.length<14)return;len=Number(buf.readBigUInt64BE(2));offset=10;}if(buf.length<offset+4+len)return;const mask=buf.subarray(offset,offset+4),body=Buffer.from(buf.subarray(offset+4,offset+4+len));buf=buf.subarray(offset+4+len);for(let i=0;i<body.length;i++)body[i]^=mask[i%4];const x=JSON.parse(body);requests.push({host:name,...x});if(!x.id)continue;
24
26
  const p=x.params||{};let result={},error;
25
27
  const metadata=()=>({id:(controls.wrongId||(name==='target'&&controls.targetWrongId))?'wrong-id':native.id,cwd:(controls.wrongCwd||(name==='target'&&controls.targetWrongCwd))?'/wrong-cwd':native.cwd,status:{type:native.loaded===name?native.status:'notLoaded'},turns:p.includeTurns?native.turns:[]});
@@ -29,7 +31,15 @@ async function fixture(){
29
31
  else if(x.method==='thread/resume'){
30
32
  if(native.loaded&&native.loaded!==name)error='original has an active writer';
31
33
  else {native.loaded=name;result={thread:metadata(),...structuredClone(native.policy)};if(controls.badPolicy||(name==='target'&&controls.targetBadPolicy))result.sandbox={type:'workspaceWrite'};}
32
- }else if(x.method==='thread/turns/list'){const start=Number(p.cursor||0);result={data:native.turns.slice(start,start+1),nextCursor:start+1<native.turns.length?String(start+1):null};if(name==='target'&&controls.missingHistory)result={data:[],nextCursor:null};}
34
+ }else if(x.method==='thread/turns/list'){
35
+ const start=Number(p.cursor||0);
36
+ result={data:native.turns.slice(start,start+1),nextCursor:start+1<native.turns.length?String(start+1):null};
37
+ if(name==='target'&&controls.missingHistory)result={data:[],nextCursor:null};
38
+ if(name==='target'&&controls.oldHistoryView&&start===1){
39
+ result.data=structuredClone(result.data);
40
+ delete result.data[0].environmentId;
41
+ }
42
+ }
33
43
  else if(x.method==='thread/queue/list')result={data:controls.queued?[{id:'queued-input'}]:[],nextCursor:null};
34
44
  else if(x.method==='thread/goal/get')result={goal:controls.goal?{objective:'original goal'}:null};
35
45
  else if(x.method==='thread/backgroundTerminals/list')result={data:controls.terminal?[{id:'running-tool'}]:[],nextCursor:null};
@@ -124,6 +134,81 @@ test('registered policy drift and uncertain claim never start work',async()=>{
124
134
 
125
135
  async function managed(h){const plan=h.savePlan(await run('inspect-registration',h.args));const r=await run('register',['--plan',plan]);assert.equal(r.code,0,r.err);const entry=JSON.parse(fs.readFileSync(h.record));entry.history=[{thread:'older-owned-thread',note:'original handover'}];entry.custom={preserved:true};entry.deliveries={[crypto.createHash('sha256').update('uncertain').digest('hex')]:{record:'uncertain',state:'pending'},[crypto.createHash('sha256').update('already').digest('hex')]:{record:'already',state:'delivered',turn:'previous-turn'}};fs.writeFileSync(h.record,JSON.stringify(entry));return entry;}
126
136
  function migrationArgs(h){return ['--repo',h.dir,'--role',h.role,'--to-socket',h.target,'--authority','https://example.com/owner/approved-migration'];}
137
+ test('target cold preflight detects second-page metadata loss before planning or release',async()=>{
138
+ const h=await fixture();try{
139
+ await managed(h);
140
+ h.native.turns.push({id:'next-turn',status:'completed',environmentId:'native-env',items:[]});
141
+ const original=fs.readFileSync(h.record);
142
+ h.controls.oldHistoryView=true;
143
+ const failedInspect=await run('inspect-migration',migrationArgs(h));
144
+ assert.notEqual(failedInspect.code,0);
145
+ assert.match(failedInspect.err,/target original persistent history mismatch/);
146
+ assert.equal(failedInspect.out,'');
147
+ h.controls.oldHistoryView=false;
148
+ const plan=h.savePlan(await run('inspect-migration',migrationArgs(h)));
149
+ const journal=path.join(h.root,'codex-transitions',JSON.parse(fs.readFileSync(plan)).id+'.json');
150
+ for(const [flag,error] of [
151
+ ['oldHistoryView',/target original persistent history mismatch/],
152
+ ['targetWrongId',/identity/],
153
+ ['targetWrongCwd',/worktree/],
154
+ ]){
155
+ h.controls[flag]=true;
156
+ const failed=await run('migrate',['--plan',plan]);
157
+ assert.notEqual(failed.code,0,flag);
158
+ assert.match(failed.err,error);
159
+ assert.doesNotMatch(failed.err,/outcome unknown/);
160
+ assert.ok(!fs.existsSync(journal));
161
+ h.controls[flag]=false;
162
+ }
163
+ assert.ok(h.requests.some(x=>x.host==='target'&&x.method==='thread/turns/list'&&x.params.cursor==='1'&&x.params.itemsView==='full'));
164
+ assert.ok(!h.requests.some(x=>x.method==='thread/unsubscribe'||(x.host==='target'&&x.method==='thread/resume')));
165
+ assert.deepEqual(fs.readFileSync(h.record),original);
166
+ }finally{await h.close();}
167
+ });
168
+ test('source unload is observed before the single target acquisition',async()=>{
169
+ const h=await fixture();try{
170
+ await managed(h);
171
+ const plan=h.savePlan(await run('inspect-migration',migrationArgs(h)));
172
+ let releaseIssued=false, readsAfterRelease=0;
173
+ h.controls.retainWriter=true;
174
+ h.controls.beforeReply=(request,host)=>{
175
+ if(host!=='source')return;
176
+ if(request.method==='thread/unsubscribe')releaseIssued=true;
177
+ if(releaseIssued&&request.method==='thread/read'&&++readsAfterRelease===2)h.native.loaded=null;
178
+ };
179
+ const migrated=await run('migrate',['--plan',plan]);
180
+ assert.equal(migrated.code,0,migrated.err);
181
+ const afterRelease=h.requests.slice(h.requests.findIndex(x=>x.method==='thread/unsubscribe')+1);
182
+ const acquired=afterRelease.findIndex(x=>x.host==='target'&&x.method==='thread/resume');
183
+ assert.equal(afterRelease.filter(x=>x.host==='target'&&x.method==='thread/resume').length,1);
184
+ assert.equal(afterRelease.slice(0,acquired).filter(x=>x.host==='source'&&x.method==='thread/read').length,2);
185
+ assert.equal(h.native.loaded,'target');
186
+ }finally{await h.close();}
187
+ });
188
+ test('source unload timeout never tries target acquisition and writer races still refuse',async()=>{
189
+ for(const race of [false,true]){
190
+ const h=await fixture();try{
191
+ await managed(h);
192
+ const plan=h.savePlan(await run('inspect-migration',migrationArgs(h)));
193
+ const original=fs.readFileSync(h.record);
194
+ h.controls.retainWriter=!race;
195
+ if(race)h.controls.beforeReply=(request,host)=>{
196
+ if(host==='target'&&request.method==='thread/resume')h.native.loaded='source';
197
+ };
198
+ const failed=await run('migrate',['--plan',plan,'--timeout','600']);
199
+ assert.notEqual(failed.code,0);
200
+ assert.match(failed.err,race?/native writer|active writer/:/source unload timed out/);
201
+ assert.match(failed.err,/outcome unknown/);
202
+ const status=JSON.parse((await run('migration-status',['--plan',plan])).out);
203
+ assert.equal(status.state,'unknown');
204
+ assert.equal(status.phase,race?'acquiring':'releasing');
205
+ assert.deepEqual(fs.readFileSync(h.record),original);
206
+ assert.match((await run('migrate',['--plan',plan])).err,/explicitly reconcile/);
207
+ assert.equal(h.requests.filter(x=>x.method==='thread/unsubscribe').length,1);
208
+ assert.equal(h.requests.filter(x=>x.host==='target'&&x.method==='thread/resume').length,race?1:0);
209
+ }finally{await h.close();}
210
+ }
211
+ });
127
212
  test('migrate original native endpoint preserving full history and all claims',async()=>{
128
213
  const h=await fixture();try{
129
214
  const entry=await managed(h);h.native.turns.push({id:'previous-two',status:'completed',items:[{id:'result-two',type:'agentMessage',text:'retain paginated second result'}]});
@@ -184,7 +269,8 @@ test('migration failure journals preserve writer, identity, history and policy b
184
269
  for(const flag of ['retainWriter','missingHistory','targetBadPolicy','targetWrongId','targetWrongCwd']){
185
270
  const h=await fixture();try{
186
271
  await managed(h);const plan=h.savePlan(await run('inspect-migration',migrationArgs(h))),p=JSON.parse(fs.readFileSync(plan)),original=fs.readFileSync(h.record);
187
- h.controls[flag]=true;const failed=await run('migrate',['--plan',plan]);assert.notEqual(failed.code,0,flag);assert.match(failed.err,/outcome unknown/);
272
+ h.controls.beforeReply=x=>{if(x.method==='thread/unsubscribe')h.controls[flag]=true;};
273
+ const failed=await run('migrate',['--plan',plan,'--timeout','600']);assert.notEqual(failed.code,0,flag);assert.match(failed.err,/outcome unknown/);
188
274
  assert.deepEqual(fs.readFileSync(h.record),original);assert.equal(JSON.parse(fs.readFileSync(path.join(h.root,'codex-transitions',p.id+'.json'))).state,'unknown');
189
275
  const releaseCount=h.requests.filter(x=>x.method==='thread/unsubscribe').length,resumeCount=h.requests.filter(x=>x.method==='thread/resume').length;
190
276
  assert.match((await run('migrate',['--plan',plan])).err,/explicitly reconcile/);
@@ -1394,6 +1394,67 @@ def validate_chat_no_wake_dm_scenario() -> int:
1394
1394
  return 0
1395
1395
 
1396
1396
 
1397
+ def validate_chat_direct_participants_json_scenario() -> int:
1398
+ """Expose direct participants without needing a role rename (#552)."""
1399
+ with tempfile.TemporaryDirectory(prefix="keel-direct-json-") as raw:
1400
+ sender, receiver, env = chat_scratch_group(Path(raw))
1401
+ store = mailbox_common_dir(sender) / "keel-chat"
1402
+ direct_group = "dm-rtl--verify"
1403
+
1404
+ def chat(worktree: Path, *args: str):
1405
+ result = run_keel(worktree, "chat", *args, env=env)
1406
+ assert result.returncode == 0, result.stderr
1407
+ return result
1408
+
1409
+ def snapshot():
1410
+ return {
1411
+ file.relative_to(store): file.read_bytes()
1412
+ for directory in (store / "groups", store / "cursors")
1413
+ for file in directory.rglob("*") if file.is_file()
1414
+ }
1415
+
1416
+ def send(*args: str) -> str:
1417
+ return chat_json(chat(sender, *args, "--json"))["id"]
1418
+
1419
+ send("post", "soc", "initial cursor")
1420
+ chat(receiver, "read", "soc")
1421
+ silent = send("dm", "verify", "--no-wake", "silent direct record")
1422
+ plain = send("post", "soc", "ordinary group record")
1423
+ assert would_wake(receiver, env) == 1, "silent DM or plain group record woke receiver"
1424
+ ordinary = send("dm", "verify", "ordinary direct record")
1425
+ assert would_wake(receiver, env) == 0, "ordinary DM did not wake receiver"
1426
+ assert not (store / "renames.json").exists(), "initial reads must have no rename map"
1427
+
1428
+ def assert_reads(role: str):
1429
+ before = snapshot()
1430
+ assert before, "expected stored history and a read cursor"
1431
+ unread = {r["id"]: r for r in chat_json(chat(receiver, "unread", "--json"))["unread"]}
1432
+ direct = {r["id"]: r for r in chat_json(chat(receiver, direct_group, "--peek", "--json"))["records"]}
1433
+ group = {r["id"]: r for r in chat_json(chat(receiver, "soc", "--peek", "--json"))["records"]}
1434
+ for record_id in (ordinary, silent, plain):
1435
+ shown = chat_json(chat(receiver, "show", record_id, "--json"))
1436
+ assert shown["readers"] == [], "peek/show must not mark a record as read"
1437
+ peeked = group[record_id] if record_id == plain else direct[record_id]
1438
+ for surface, record in (("unread", unread[record_id]), ("peek", peeked), ("show", shown["record"])):
1439
+ assert record["id"] == record_id
1440
+ assert not record.get("mentions"), f"{surface} must not rely on mentions"
1441
+ if record_id == plain:
1442
+ assert "direct" not in record, f"{surface} gave a plain group record direct participants"
1443
+ else:
1444
+ assert record.get("direct") == ["rtl", role], f"{surface} lost canonical DM participants: {record.get('direct')!r}"
1445
+ assert bool(record.get("no_wake")) == (record_id == silent), f"{surface} changed no-wake"
1446
+ assert snapshot() == before, "JSON projections rewrote history or cursors"
1447
+
1448
+ assert_reads("verify")
1449
+ original_records = {file: data for file, data in snapshot().items() if file.parts[0] == "groups" and "log" in file.parts}
1450
+ chat(receiver, "role", "--rename", "verify", "check")
1451
+ assert_reads("check")
1452
+ assert all((store / file).read_bytes() == data for file, data in original_records.items()), "rename rewrote original records"
1453
+
1454
+ report("chat-direct-participants-json scenario passed.")
1455
+ return 0
1456
+
1457
+
1397
1458
  def validate_chat_wakes_without_no_wake_scenario() -> int:
1398
1459
  """Issue #502: without the option a mention still wakes, as before."""
1399
1460
  label = "chat-wakes-without-no-wake:"
@@ -35,10 +35,10 @@ os.environ["KEEL_UPDATE_CLAUDE"] = str(Path(tempfile.gettempdir()) / "keel-suite
35
35
  os.environ["KEEL_UPDATE_CODEX"] = str(Path(tempfile.gettempdir()) / "keel-suite-has-no-codex")
36
36
 
37
37
 
38
- PACKAGE_VERSION = "5.231.1"
38
+ PACKAGE_VERSION = "5.231.3"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.231.1"
41
+ PROTOCOL_VERSION = "5.231.3"
42
42
 
43
43
 
44
44
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
@@ -532,6 +532,7 @@ SCENARIOS: tuple = (
532
532
  ("chat-summary", chat.validate_chat_summary_scenario),
533
533
  ("chat-no-wake-post", chat.validate_chat_no_wake_post_scenario),
534
534
  ("chat-no-wake-dm", chat.validate_chat_no_wake_dm_scenario),
535
+ ("chat-direct-participants-json", chat.validate_chat_direct_participants_json_scenario),
535
536
  ("chat-wakes-without-no-wake", chat.validate_chat_wakes_without_no_wake_scenario),
536
537
  ("worktree-overview", shift.validate_worktree_overview_scenario),
537
538
  ("sync-status-lists-local-only", sync.validate_sync_status_lists_local_only_scenario),
@@ -228,15 +228,16 @@ function canonicalRole(root, name, renames = readRenames(root)) {
228
228
  // Every role field a record carries, read through the renames (D2); a direct
229
229
  // group's members come from its name, so they are given as `direct`.
230
230
  function mapRecord(record, renames) {
231
- if (!record || !Object.keys(renames).length) return record;
231
+ if (!record) return record;
232
232
  const map = (name) => (validName(name) ? canonicalRole(null, name, renames) : name);
233
+ if (record.group && isDirect(record.group)) record.direct = [...new Set(directMembers(record.group).map(map))];
234
+ if (!Object.keys(renames).length) return record;
233
235
  record.from = map(record.from);
234
236
  if (record.assignee) record.assignee = map(record.assignee);
235
237
  if (Array.isArray(record.mentions)) record.mentions = [...new Set(record.mentions.map(map))];
236
238
  // A join or leave keeps the name it was written for; `member` is the role
237
239
  // it now means, applied once membership is computed (groupState).
238
240
  if ((record.kind === "join" || record.kind === "leave") && record.target) record.member = map(record.target);
239
- if (record.group && isDirect(record.group)) record.direct = [...new Set(directMembers(record.group).map(map))];
240
241
  return record;
241
242
  }
242
243
 
@@ -2,6 +2,7 @@
2
2
  const fs = require('node:fs');
3
3
  const path = require('node:path');
4
4
  const crypto = require('node:crypto');
5
+ const {setTimeout: delay} = require('node:timers/promises');
5
6
  const store = require('./chat/store');
6
7
  const actions = ['inspect-registration', 'register', 'inspect-migration', 'migrate', 'migration-status'];
7
8
  const canonical = value => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value;
@@ -76,7 +77,7 @@ async function history(client, thread) {
76
77
  async function run(args, {connect}) {
77
78
  const clients = [], locks = [];
78
79
  try {
79
- const action = args.shift(), options = {timeout: 15000};
80
+ const action = args.shift(), options = {};
80
81
  while (args.length) {
81
82
  const flag = args.shift();
82
83
  if (flag === '--json') continue;
@@ -87,7 +88,7 @@ async function run(args, {connect}) {
87
88
  if (options[flag.slice(2)] !== undefined && flag !== '--timeout') throw Error(`duplicate ${flag}`);
88
89
  options[flag.slice(2)] = value;
89
90
  }
90
- const timeout = Number(options.timeout);
91
+ const timeout = Number(options.timeout ?? 15000);
91
92
  if (!Number.isInteger(timeout) || timeout < 50 || timeout > 60000) throw Error('timeout must be 50–60000 milliseconds');
92
93
  if (['inspect-migration', 'migrate', 'migration-status'].includes(action)) return await migration(action, options, {connect, timeout, clients, locks});
93
94
  if (options.reconcile || options['to-socket']) throw Error('migration-only option used for registration');
@@ -175,6 +176,26 @@ async function inspectSource(client, plan, recorded) {
175
176
  await quiescent(client, plan, native.thread, turns);
176
177
  return {nativePolicy, historyDigest: digest(turns), historyCount: turns.length};
177
178
  }
179
+ function matchesHistory(turns, snapshot, allowLaterTurns = false) {
180
+ const {historyCount, historyDigest} = snapshot;
181
+ if (!allowLaterTurns) return turns.length === historyCount && digest(turns) === historyDigest;
182
+ return turns.length >= historyCount && digest(turns.slice(0, historyCount)) === historyDigest;
183
+ }
184
+ async function waitForSourceUnload(source, plan, rpcTimeout, waitTimeout) {
185
+ const deadline = performance.now() + waitTimeout;
186
+ let remaining = waitTimeout;
187
+ while (remaining > 0) {
188
+ const {thread} = await source.call('thread/read', {threadId: plan.thread, includeTurns: false}, Math.min(rpcTimeout, Math.ceil(remaining)));
189
+ verifyThread(thread, plan);
190
+ if (thread.status.type === 'active') throw Error('source became active while waiting for unload');
191
+ remaining = deadline - performance.now();
192
+ if (remaining <= 0) break;
193
+ if (thread.status.type === 'notLoaded') return;
194
+ await delay(Math.min(250, Math.ceil(remaining)));
195
+ remaining = deadline - performance.now();
196
+ }
197
+ throw Error('source unload timed out before target acquisition');
198
+ }
178
199
  async function migration(action, options, context) {
179
200
  const {clients, locks} = context;
180
201
  const applying = action !== 'inspect-migration';
@@ -238,12 +259,22 @@ async function migration(action, options, context) {
238
259
  if (journal && !options.reconcile) throw Error('migration outcome unknown; inspect migration-status and explicitly reconcile, no automatic retry');
239
260
  if (options.reconcile && !journal) throw Error('no transition exists to reconcile');
240
261
  const source = await openHost(plan.fromSocket, context);
262
+ let target;
241
263
  if (!options.reconcile) {
242
264
  const snapshot = await inspectSource(source, plan, recorded);
265
+ if (applying && (!same(snapshot.nativePolicy, plan.nativePolicy) || snapshot.historyDigest !== plan.historyDigest || snapshot.historyCount !== plan.historyCount)) throw Error('native source policy or history changed since inspection');
266
+ target = await openHost(plan.toSocket, context);
267
+ const targetThread = (await target.call('thread/read', {threadId: plan.thread, includeTurns: false})).thread;
268
+ verifyThread(targetThread, plan);
269
+ if (!matchesHistory(await history(target, plan.thread), snapshot)) throw Error('target original persistent history mismatch before source release');
243
270
  if (!applying) {
244
271
  process.stdout.write(JSON.stringify(savePlan({...plan, ...snapshot})) + '\n'); return 0;
245
272
  }
246
- if (!same(snapshot.nativePolicy, plan.nativePolicy) || snapshot.historyDigest !== plan.historyDigest || snapshot.historyCount !== plan.historyCount) throw Error('native source policy or history changed since inspection');
273
+ const current = (await source.call('thread/read', {threadId: plan.thread, includeTurns: false})).thread;
274
+ verifyThread(current, plan);
275
+ const latest = await history(source, plan.thread);
276
+ await quiescent(source, plan, current, latest);
277
+ if (!matchesHistory(latest, plan)) throw Error('native source history changed before release');
247
278
  unchanged();
248
279
  journal = {schema: 'keel-codex-migration/v1', state: 'pending', phase: 'intent', plan, originalRegistry: bytes.toString('utf8')};
249
280
  store.writeJsonAtomic(where, journalFile, journal);
@@ -252,14 +283,13 @@ async function migration(action, options, context) {
252
283
  if (!options.reconcile) {
253
284
  // Only release our own source subscription, never cancel a tool/turn or
254
285
  // remove another frontend's subscription. Native writer refusal rules.
255
- const current = (await source.call('thread/read', {threadId: plan.thread, includeTurns: false})).thread;
256
- verifyThread(current, plan);
257
- await quiescent(source, plan, current, await history(source, plan.thread));
258
286
  journal.phase = 'releasing'; store.writeJsonAtomic(where, journalFile, journal);
259
287
  const released = await source.call('thread/unsubscribe', {threadId: plan.thread});
260
288
  if (released.status !== 'unsubscribed') throw Error('source subscription release not verified');
289
+ const unloadTimeout = options.timeout === undefined ? 75000 : context.timeout;
290
+ await waitForSourceUnload(source, plan, context.timeout, unloadTimeout);
261
291
  }
262
- const target = await openHost(plan.toSocket, context);
292
+ target ??= await openHost(plan.toSocket, context);
263
293
  const targetThread = (await target.call('thread/read', {threadId: plan.thread, includeTurns: false})).thread;
264
294
  verifyThread(targetThread, plan);
265
295
  if (options.reconcile) {
@@ -269,13 +299,13 @@ async function migration(action, options, context) {
269
299
  if (!['idle', 'active'].includes(targetThread.status.type)) throw Error('target is not already loaded; reconciliation will not retry native acquisition');
270
300
  }
271
301
  const prior = await history(target, plan.thread);
272
- if (prior.length < plan.historyCount || digest(prior.slice(0, plan.historyCount)) !== plan.historyDigest || (!options.reconcile && prior.length !== plan.historyCount)) throw Error('target original persistent history mismatch');
302
+ if (!matchesHistory(prior, plan, options.reconcile)) throw Error('target original persistent history mismatch');
273
303
  journal.phase = options.reconcile ? 'reconciling' : 'acquiring'; store.writeJsonAtomic(where, journalFile, journal);
274
304
  const native = await target.call('thread/resume', {threadId: plan.thread});
275
305
  verifyThread(native.thread, plan); verifyPolicy(native, plan.nativePolicy);
276
306
  if (!['idle', ...(options.reconcile ? ['active'] : [])].includes(native.thread.status.type)) throw Error('target native state changed; registration retained');
277
307
  const after = await history(target, plan.thread);
278
- if (after.length < plan.historyCount || digest(after.slice(0, plan.historyCount)) !== plan.historyDigest || (!options.reconcile && after.length !== plan.historyCount)) throw Error('resumed target original persistent history mismatch');
308
+ if (!matchesHistory(after, plan, options.reconcile)) throw Error('resumed target original persistent history mismatch');
279
309
  journal.phase = 'verified'; store.writeJsonAtomic(where, journalFile, journal);
280
310
  unchanged();
281
311
  if (!registryAlreadyApplied) store.writeJsonAtomic(where, file, nextRegistry(recorded));