@christang/keel 5.231.2 → 5.231.4

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.2",
3
+ "version": "5.231.4",
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",
package/README.md CHANGED
@@ -1098,6 +1098,7 @@ keel shift request | check | ready [--wake] | start | resume | status
1098
1098
  keel lock acquire | release | list # see docs/resource-lock.md
1099
1099
  keel lock acquire | release --branch <b> [--break <reason>] [--push] # a branch lock on the remote
1100
1100
  keel worktrees [--repo <path>] [--issues <file>] [--json]
1101
+ keel worktrees add [--repo <path>] --path <path> --branch <new-branch> [--base <ref>] [--json]
1101
1102
  keel sync status [--repo <path>] [--verify] [--remote <name>] [--json] # what exists only on this machine
1102
1103
 
1103
1104
  # Unattended triage — may this issue start work without asking?
package/README.zh-CN.md CHANGED
@@ -924,6 +924,7 @@ keel shift request | check | ready [--wake] | start | resume | status
924
924
  keel lock acquire | release | list # 见 docs/resource-lock.md
925
925
  keel lock acquire | release --branch <b> [--break <reason>] [--push] # 远端上的分支锁
926
926
  keel worktrees [--repo <path>] [--issues <file>] [--json]
927
+ keel worktrees add [--repo <path>] --path <path> --branch <new-branch> [--base <ref>] [--json]
927
928
  keel sync status [--repo <path>] [--verify] [--remote <name>] [--json] # 只在本机的工作
928
929
 
929
930
  # 无人值守 triage —— 这个 issue 能否不经询问就开工?
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.231.2 -->
1
+ <!-- keel:start version=5.231.4 -->
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.
package/bin/keel.js CHANGED
@@ -105,6 +105,7 @@ Usage:
105
105
  keel lock acquire|release|list ... (shared resource leases; see keel lock --help)
106
106
  keel lock acquire|release --branch <b> [--break <reason>] [--push] (a branch lock kept on the remote; device-sync)
107
107
  keel worktrees [--repo <path>] [--issues <file>] [--json] (read-only worktree overview)
108
+ keel worktrees add [--repo <path>] --path <path> --branch <new-branch> [--base <ref>] [--json]
108
109
  keel sync status [--repo <path>] [--verify] [--remote <name>] [--json] (what exists only on this machine; fetches nothing, --verify asks the remote its sha)
109
110
  keel patrol [--issues <file>] [--idle <dur>] [--since-last [--notify]] [--nudge] [--json] [--repo <path>] (the coordinator's patrol; keel patrol task prints its schedule)
110
111
  keel codex status|start|deliver|handover|drain|recover [--repo <path>] [--role <role>] [--socket <path>] [--json] (managed Codex roles; explicit host identity)
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.231.2",
3
+ "version": "5.231.4",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.231.2",
9
+ "version": "5.231.4",
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.2",
5
+ "version": "5.231.4",
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.2",
3
+ "version": "5.231.4",
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.2",
3
+ "version": "5.231.4",
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/);
@@ -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.2"
38
+ PACKAGE_VERSION = "5.231.4"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.231.2"
41
+ PROTOCOL_VERSION = "5.231.4"
42
42
 
43
43
 
44
44
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
@@ -535,6 +535,7 @@ SCENARIOS: tuple = (
535
535
  ("chat-direct-participants-json", chat.validate_chat_direct_participants_json_scenario),
536
536
  ("chat-wakes-without-no-wake", chat.validate_chat_wakes_without_no_wake_scenario),
537
537
  ("worktree-overview", shift.validate_worktree_overview_scenario),
538
+ ("project-local-worktree", shift.validate_project_local_worktree_scenario),
538
539
  ("sync-status-lists-local-only", sync.validate_sync_status_lists_local_only_scenario),
539
540
  ("sync-status-read-only-exit-codes", sync.validate_sync_status_read_only_exit_codes_scenario),
540
541
  ("sync-status-verify-classifies", sync.validate_sync_status_verify_classifies_scenario),
@@ -2371,6 +2371,70 @@ def validate_patrol_issue_label_set_unreadable_scenario() -> int:
2371
2371
  return 0
2372
2372
 
2373
2373
 
2374
+ def validate_project_local_worktree_scenario() -> int:
2375
+ """Create and reuse project-local Git worktrees through the public CLI."""
2376
+ with tempfile.TemporaryDirectory(prefix="keel-project-worktree-") as raw:
2377
+ root = Path(raw).resolve()
2378
+ env = os.environ.copy()
2379
+ env.pop("KEEL_CHAT_ROLE", None)
2380
+ env.pop("KEEL_MAIL_ROLE", None)
2381
+
2382
+ def git(cwd: Path, *args: str, check: bool = True):
2383
+ return subprocess.run(["git", *args], cwd=cwd, env=env, check=check,
2384
+ capture_output=True, text=True)
2385
+
2386
+ for project in ("project one", "project two"):
2387
+ repo = root / project / "repo"
2388
+ repo.mkdir(parents=True)
2389
+ git(repo, "init", "-qb", "main")
2390
+ git(repo, "-c", "user.name=Test", "-c", "user.email=test@example.invalid",
2391
+ "commit", "--allow-empty", "-qm", project)
2392
+ first = git(repo, "rev-parse", "HEAD").stdout.strip()
2393
+ git(repo, "-c", "user.name=Test", "-c", "user.email=test@example.invalid",
2394
+ "commit", "--allow-empty", "-qm", "second commit")
2395
+ head = git(repo, "rev-parse", "HEAD").stdout.strip()
2396
+ local = repo / "local-edit"
2397
+ local.write_text(project, encoding="utf-8")
2398
+ review = repo.parent / "worktrees" / "review"
2399
+ other = review.parent / "another"
2400
+
2401
+ def add(*args):
2402
+ return run_keel(root, "worktrees", "add", "--repo", str(repo), "--json", *args, env=env)
2403
+
2404
+ opened = add("--path", "../worktrees/review", "--branch", "codex/review")
2405
+ assert opened.returncode == 0, opened.stderr
2406
+ assert json.loads(opened.stdout) == {"path": str(review), "branch": "codex/review", "base": head}
2407
+ assert not (review / local.name).exists()
2408
+ bound = run_keel(review, "chat", "role", "--set", "review", env=env)
2409
+ assert bound.returncode == 0, bound.stderr
2410
+
2411
+ opened = add("--path", str(other), "--branch", "codex/another", "--base", first)
2412
+ assert opened.returncode == 0, opened.stderr
2413
+ assert json.loads(opened.stdout)["base"] == first
2414
+ assert git(other, "rev-parse", "HEAD").stdout.strip() == first
2415
+ listed = run_keel(repo, "worktrees", "--json", env=env)
2416
+ assert listed.returncode == 0, listed.stderr
2417
+ rows = {row["path"]: row for row in json.loads(listed.stdout)["worktrees"]}
2418
+ assert set(rows) == {str(repo), str(review), str(other)}, rows
2419
+ assert rows[str(review)]["role"] == "review"
2420
+
2421
+ edit = review / "uncommitted"
2422
+ edit.write_text("retain", encoding="utf-8")
2423
+ conflict = add("--path", str(review), "--branch", "codex/occupied")
2424
+ assert conflict.returncode != 0 and str(review) in conflict.stderr, conflict
2425
+ assert not git(repo, "branch", "--list", "codex/occupied").stdout.strip()
2426
+ conflict = add("--path", str(review.parent / "unused"), "--branch", "codex/review")
2427
+ assert conflict.returncode != 0 and "codex/review" in conflict.stderr, conflict
2428
+ assert not (review.parent / "unused").exists()
2429
+ assert git(repo, "worktree", "remove", str(review), check=False).returncode != 0
2430
+ assert edit.read_text(encoding="utf-8") == "retain"
2431
+ assert local.read_text(encoding="utf-8") == project
2432
+ git(repo, "worktree", "remove", str(other))
2433
+ assert git(repo, "rev-parse", "codex/another").stdout.strip() == first
2434
+ report("project-local-worktree scenario passed.")
2435
+ return 0
2436
+
2437
+
2374
2438
  def validate_worktree_overview_scenario() -> int:
2375
2439
  """Read every worktree through the CLI without fetching or changing chat."""
2376
2440
  label = "worktree-overview:"
@@ -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));
@@ -1,8 +1,7 @@
1
1
  "use strict";
2
2
 
3
- // Worktree-overview D1-D5: local Git and chat reads only. In particular,
4
- // status must not refresh the index, and role overrides belong to the caller,
5
- // not to every worktree it is inspecting.
3
+ // The overview only reads Git and chat state. Status must not refresh the
4
+ // index, and role overrides belong to the caller rather than every worktree.
6
5
  const fs = require("fs");
7
6
  const path = require("path");
8
7
  const { spawnSync } = require("child_process");
@@ -10,6 +9,7 @@ const store = require("./chat/store");
10
9
  const notice = require("./chat/notice");
11
10
 
12
11
  const USAGE = "keel worktrees [--repo <path>] [--issues <file>] [--json]";
12
+ const ADD_USAGE = "keel worktrees add [--repo <path>] --path <path> --branch <new-branch> [--base <ref>] [--json]";
13
13
  class WorktreesError extends Error {}
14
14
 
15
15
  function git(cwd, args, optional = false) {
@@ -146,25 +146,44 @@ function render(result) {
146
146
  return lines.join("\n");
147
147
  }
148
148
 
149
+ function addWorktree(where, options) {
150
+ if (!options.path || !options.branch) throw new WorktreesError(ADD_USAGE);
151
+ const target = path.resolve(where.worktree, options.path);
152
+ if (fs.lstatSync(target, { throwIfNoEntry: false })) {
153
+ throw new WorktreesError(`Worktree destination already exists: ${target}`);
154
+ }
155
+ const base = git(where.worktree, ["rev-parse", "--verify", "--end-of-options", `${options.base || "HEAD"}^{commit}`]);
156
+ git(where.worktree, ["worktree", "add", "-b", options.branch, "--", target, base]);
157
+ const created = fs.realpathSync(target);
158
+ process.stdout.write(options.json
159
+ ? JSON.stringify({ path: created, branch: options.branch, base }) + "\n"
160
+ : `Created worktree ${created} on ${options.branch} at ${base}\n`);
161
+ return 0;
162
+ }
163
+
149
164
  function runWorktrees(argv) {
165
+ const add = argv[0] === "add";
166
+ const optionNames = add ? ["--repo", "--path", "--branch", "--base"] : ["--repo", "--issues"];
150
167
  const options = { repo: process.cwd(), issues: null, json: false };
151
168
  try {
152
- for (let index = 0; index < argv.length; index += 1) {
169
+ for (let index = add ? 1 : 0; index < argv.length; index += 1) {
153
170
  const arg = argv[index];
154
171
  if (arg === "--json") options.json = true;
155
172
  else if (arg === "--help" || arg === "-h") {
156
- process.stdout.write(`${USAGE}\nIssue times come only from --issues (a JSON array with number and updatedAt).\n`);
173
+ process.stdout.write(add ? `${ADD_USAGE}\n`
174
+ : `${USAGE}\n${ADD_USAGE}\nIssue times come only from --issues (a JSON array with number and updatedAt).\n`);
157
175
  return 0;
158
- } else if (arg === "--repo" || arg === "--issues") {
176
+ } else if (optionNames.includes(arg)) {
159
177
  const value = argv[++index];
160
178
  if (!value || value.startsWith("--")) throw new WorktreesError(`${arg} needs a value.`);
161
- options[arg === "--repo" ? "repo" : "issues"] = value;
162
- } else throw new WorktreesError(`Unknown argument ${arg}. ${USAGE}`);
179
+ options[arg.slice(2)] = value;
180
+ } else throw new WorktreesError(`Unknown argument ${arg}. ${add ? ADD_USAGE : USAGE}`);
163
181
  }
164
182
  // Refuse a bad file before collecting or printing any repository state.
165
183
  const times = readIssues(options.issues);
166
184
  const where = store.locate(options.repo);
167
185
  if (!where) throw new WorktreesError(`Not a git repository: ${options.repo}`);
186
+ if (add) return addWorktree(where, options);
168
187
  const base = defaultBranch(where.worktree);
169
188
  const roles = store.readJsonFile(path.join(where.root, "roles.json"));
170
189
  const result = {