inplan 0.1.30 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js CHANGED
@@ -4,12 +4,12 @@
4
4
  import { execFileSync as execFileSync2, spawn as spawn3, spawnSync } from "child_process";
5
5
  import { createHash as createHash4, randomBytes } from "crypto";
6
6
  import { createRequire } from "module";
7
- import { appendFileSync as appendFileSync2, copyFileSync, existsSync as existsSync10, mkdirSync as mkdirSync9, readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync, renameSync as renameSync2, rmSync as rmSync2, statSync as statSync4, writeFileSync as writeFileSync9 } from "fs";
7
+ import { appendFileSync as appendFileSync3, copyFileSync, existsSync as existsSync11, mkdirSync as mkdirSync10, readdirSync as readdirSync2, readFileSync as readFileSync11, realpathSync, renameSync as renameSync4, statSync as statSync5, writeFileSync as writeFileSync10 } from "fs";
8
8
  import { homedir as homedir7 } from "os";
9
- import { basename as basename3, dirname as dirname10, extname, isAbsolute as isAbsolute2, join as join10, relative as relative4, resolve as resolve3 } from "path";
9
+ import { basename as basename3, dirname as dirname11, extname, isAbsolute as isAbsolute2, join as join10, relative as relative4, resolve as resolve3 } from "path";
10
10
  import { fileURLToPath as fileURLToPath2, pathToFileURL as pathToFileURL2 } from "url";
11
11
 
12
- // ../core/dist/chunk-BS76FGIJ.js
12
+ // ../core/dist/chunk-P2QV45YY.js
13
13
  function isReply(c) {
14
14
  return c.parentId !== void 0;
15
15
  }
@@ -234,6 +234,12 @@ function parseLogLine(line) {
234
234
  function parseLog(text) {
235
235
  return text.split("\n").map((l) => l.trim()).filter((l) => l.length > 0).map(parseLogLine);
236
236
  }
237
+ function mintProposalId() {
238
+ const c = globalThis.crypto;
239
+ if (c?.randomUUID) return c.randomUUID();
240
+ const hex = (n) => Math.floor(Math.random() * n).toString(16);
241
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (ch) => ch === "x" ? hex(16) : (Math.floor(Math.random() * 4) + 8).toString(16));
242
+ }
237
243
 
238
244
  // ../core/dist/node.js
239
245
  import { appendFileSync, closeSync, existsSync, openSync, readFileSync, readSync, statSync } from "fs";
@@ -242,6 +248,9 @@ import {
242
248
  mkdirSync,
243
249
  readdirSync,
244
250
  readFileSync as readFileSync2,
251
+ renameSync,
252
+ rmSync,
253
+ statSync as statSync2,
245
254
  unlinkSync,
246
255
  unwatchFile,
247
256
  watch,
@@ -385,7 +394,7 @@ var FsControlChannel = class {
385
394
  return Promise.resolve(false);
386
395
  }
387
396
  };
388
- var FsDocumentStore = class {
397
+ var FsDocumentStore = class _FsDocumentStore {
389
398
  constructor(paths) {
390
399
  this.paths = paths;
391
400
  }
@@ -407,16 +416,160 @@ var FsDocumentStore = class {
407
416
  writeFileSync(this.paths.canonicalPath, content);
408
417
  return Promise.resolve();
409
418
  }
410
- getProposed() {
411
- return Promise.resolve(this.readOrNull(this.paths.proposedPath));
419
+ // Proposal rows live in a JSON file beside the other sidecars; `proposedPath` stays as a
420
+ // derived copy of the CURRENT pending content (readable at a glance, and what pre-rows code
421
+ // wrote). A single local proposer, so "mine" is unqualified.
422
+ proposalsPath() {
423
+ return `${this.paths.proposedPath}.rows.json`;
412
424
  }
413
- setProposed(content) {
414
- writeFileSync(this.paths.proposedPath, content);
415
- return Promise.resolve();
425
+ /** Whether row-backed proposal state exists for this doc at all (vs the legacy content file). */
426
+ hasProposalHistory() {
427
+ return existsSync2(this.proposalsPath());
416
428
  }
417
- clearProposed() {
418
- if (existsSync2(this.paths.proposedPath)) unlinkSync(this.paths.proposedPath);
419
- return Promise.resolve();
429
+ static STATES = /* @__PURE__ */ new Set(["pending", "accepted", "partially_accepted", "rejected", "superseded", "withdrawn"]);
430
+ static isValidRow(r) {
431
+ const x = r;
432
+ return !!x && typeof x.id === "string" && typeof x.content === "string" && typeof x.baseHash === "string" && typeof x.baseContent === "string" && typeof x.state === "string" && _FsDocumentStore.STATES.has(x.state) && typeof x.createdAt === "string";
433
+ }
434
+ readRows() {
435
+ const raw = this.readOrNull(this.proposalsPath());
436
+ if (raw === null) return [];
437
+ try {
438
+ const rows = JSON.parse(raw);
439
+ if (Array.isArray(rows) && rows.every((r) => _FsDocumentStore.isValidRow(r))) return rows;
440
+ } catch {
441
+ }
442
+ renameSync(this.proposalsPath(), `${this.proposalsPath()}.corrupt-${Date.now()}`);
443
+ return [];
444
+ }
445
+ /**
446
+ * Advisory per-doc lock around every read-modify-publish of the rows file: the desktop editor
447
+ * (main process) and a CLI can share one sidecar, and interleaved mutations would lose a
448
+ * lifecycle update. mkdir is the atomic primitive; a stale lock (a crashed holder) is broken
449
+ * after 2s. Mutations here are a few file ops — well under the staleness window.
450
+ *
451
+ * Async: contention waits are AWAITED sleeps, never a synchronous spin — the desktop editor
452
+ * calls this on Electron's main thread, where a sync busy-wait under a held lock froze the
453
+ * whole UI for up to the 2s deadline. The semantics are unchanged (owner token, ~2s deadline,
454
+ * atomic take-by-rename release, quarantine behavior); only the wait yields the event loop.
455
+ */
456
+ async withRowsLock(run) {
457
+ const lockDir2 = `${this.proposalsPath()}.lock`;
458
+ const ownerPath = join(lockDir2, "owner");
459
+ const token = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
460
+ const deadline = Date.now() + 2e3;
461
+ for (; ; ) {
462
+ try {
463
+ mkdirSync(lockDir2);
464
+ writeFileSync(ownerPath, token);
465
+ break;
466
+ } catch {
467
+ let stale = false;
468
+ try {
469
+ stale = Date.now() - statSync2(lockDir2).mtime.getTime() > 2e3;
470
+ } catch {
471
+ continue;
472
+ }
473
+ if (stale) {
474
+ try {
475
+ rmSync(lockDir2, { recursive: true, force: true });
476
+ } catch {
477
+ }
478
+ continue;
479
+ }
480
+ if (Date.now() > deadline) throw new Error(`proposal rows lock is held: ${lockDir2}`);
481
+ await new Promise((resolve32) => setTimeout(resolve32, 25));
482
+ }
483
+ }
484
+ try {
485
+ return run();
486
+ } finally {
487
+ const releasing = `${lockDir2}.releasing-${token}`;
488
+ try {
489
+ renameSync(lockDir2, releasing);
490
+ if (readFileSync2(join(releasing, "owner"), "utf8") === token) {
491
+ rmSync(releasing, { recursive: true, force: true });
492
+ } else {
493
+ try {
494
+ renameSync(releasing, lockDir2);
495
+ } catch {
496
+ rmSync(releasing, { recursive: true, force: true });
497
+ }
498
+ }
499
+ } catch {
500
+ }
501
+ }
502
+ }
503
+ writeRows(rows) {
504
+ const tmp = `${this.proposalsPath()}.tmp`;
505
+ writeFileSync(tmp, JSON.stringify(rows, null, 2));
506
+ renameSync(tmp, this.proposalsPath());
507
+ const pending = rows.find((r) => r.state === "pending");
508
+ try {
509
+ if (pending) writeFileSync(this.paths.proposedPath, pending.content);
510
+ else if (existsSync2(this.paths.proposedPath)) unlinkSync(this.paths.proposedPath);
511
+ } catch {
512
+ }
513
+ }
514
+ async createProposal(input) {
515
+ return this.withRowsLock(() => {
516
+ const rows = this.readRowsAdoptingLegacy();
517
+ const pendingSame = input.id ? void 0 : rows.find((r) => r.state === "pending" && r.content === input.content);
518
+ const id = input.id ?? pendingSame?.id ?? mintProposalId();
519
+ const existing = rows.find((r) => r.id === id);
520
+ if (existing) {
521
+ if (existing.state === "pending") Object.assign(existing, { content: input.content, baseHash: input.baseHash, baseContent: input.baseContent });
522
+ } else {
523
+ for (const r of rows) if (r.state === "pending") r.state = "superseded";
524
+ rows.push({ id, content: input.content, baseHash: input.baseHash, baseContent: input.baseContent, state: "pending", createdAt: (/* @__PURE__ */ new Date()).toISOString() });
525
+ }
526
+ this.writeRows(rows);
527
+ return { id };
528
+ });
529
+ }
530
+ /** Rows, adopting a legacy pre-rows sidecar exactly once: a `proposedPath` content file with no
531
+ * rows file is an old park — it becomes a real pending row (minted id) so the full lifecycle
532
+ * (withdraw/decide/supersede) applies to it instead of the file lingering forever. */
533
+ readRowsAdoptingLegacy() {
534
+ const rows = this.readRows();
535
+ if (rows.length > 0 || this.hasProposalHistory()) return rows;
536
+ const legacy = this.readOrNull(this.paths.proposedPath);
537
+ if (legacy === null) return rows;
538
+ return [{ id: mintProposalId(), content: legacy, baseHash: "", baseContent: "", state: "pending", createdAt: (/* @__PURE__ */ new Date()).toISOString() }];
539
+ }
540
+ async myPendingProposal() {
541
+ return this.withRowsLock(() => {
542
+ const rows = this.readRowsAdoptingLegacy();
543
+ const pending = rows.find((r) => r.state === "pending") ?? null;
544
+ if (pending && !this.hasProposalHistory()) this.writeRows(rows);
545
+ return pending;
546
+ });
547
+ }
548
+ async getProposal(id) {
549
+ return this.withRowsLock(() => this.readRows().find((r) => r.id === id) ?? null);
550
+ }
551
+ async withdrawProposal(id) {
552
+ await this.withRowsLock(() => {
553
+ const rows = this.readRowsAdoptingLegacy();
554
+ const r = rows.find((x) => x.id === id);
555
+ if (r && r.state === "pending") {
556
+ r.state = "withdrawn";
557
+ this.writeRows(rows);
558
+ }
559
+ });
560
+ }
561
+ async decideProposal(id, state) {
562
+ return this.withRowsLock(() => {
563
+ const rows = this.readRowsAdoptingLegacy();
564
+ const r = rows.find((x) => x.id === id);
565
+ if (r && r.state === "pending") {
566
+ r.state = state;
567
+ r.decidedAt = (/* @__PURE__ */ new Date()).toISOString();
568
+ this.writeRows(rows);
569
+ return { transitioned: true };
570
+ }
571
+ return { transitioned: false };
572
+ });
420
573
  }
421
574
  backup(content) {
422
575
  mkdirSync(this.paths.backupsDir, { recursive: true });
@@ -678,7 +831,7 @@ function gitIdentity(dir, run = defaultRun) {
678
831
  }
679
832
 
680
833
  // src/cliAuth.ts
681
- import { chmodSync, existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync4, renameSync, rmSync, statSync as statSync2, utimesSync, writeFileSync as writeFileSync3 } from "fs";
834
+ import { chmodSync, existsSync as existsSync5, linkSync, mkdirSync as mkdirSync3, readFileSync as readFileSync4, renameSync as renameSync2, rmSync as rmSync2, statSync as statSync3, utimesSync, writeFileSync as writeFileSync3 } from "fs";
682
835
  import { homedir as homedir3 } from "os";
683
836
  import { dirname as dirname5, join as join4 } from "path";
684
837
  import { createClient as createClient2 } from "@supabase/supabase-js";
@@ -759,13 +912,33 @@ var SupabaseControlChannel = class {
759
912
  function rowToEntry(r) {
760
913
  return { seq: r.seq, ts: r.ts, actor: r.actor, type: r.type, payload: r.payload ?? void 0 };
761
914
  }
915
+ var toRow = (r) => ({
916
+ id: r.id,
917
+ content: r.content,
918
+ baseHash: r.base_hash,
919
+ baseContent: r.base_content,
920
+ state: r.state,
921
+ createdAt: r.created_at,
922
+ ...r.decided_at ? { decidedAt: r.decided_at } : {}
923
+ });
762
924
  var SupabaseDocumentStore = class {
763
- constructor(db, docId) {
925
+ constructor(db, docId, proposer) {
764
926
  this.db = db;
765
927
  this.docId = docId;
928
+ this.proposer = proposer;
766
929
  }
767
930
  db;
768
931
  docId;
932
+ proposer;
933
+ /** Filter for the caller's own proposal rows. */
934
+ mineFilter() {
935
+ if (this.proposer.kind === "user" && this.proposer.userId === void 0) {
936
+ throw new Error("proposer identity of kind 'user' requires a userId");
937
+ }
938
+ const f = { proposer_kind: this.proposer.kind, client_id: this.proposer.clientId };
939
+ if (this.proposer.userId !== void 0) f.proposer_user_id = this.proposer.userId;
940
+ return f;
941
+ }
769
942
  async loadDoc() {
770
943
  return await this.readColumn("body") ?? "";
771
944
  }
@@ -778,14 +951,56 @@ var SupabaseDocumentStore = class {
778
951
  async setCanonical(content) {
779
952
  await this.writeColumns({ canonical: content });
780
953
  }
781
- async getProposed() {
782
- return this.readColumn("proposed");
954
+ async createProposal(input) {
955
+ const reuse = input.id ? null : await this.myPendingProposal();
956
+ const id = input.id ?? (reuse && reuse.content === input.content ? reuse.id : mintProposalId());
957
+ const existing = await this.getProposal(id);
958
+ if (existing) {
959
+ if (existing.state !== "pending") return { id };
960
+ const { error: error2 } = await this.db.from("proposals").update({ content: input.content, base_hash: input.baseHash, base_content: input.baseContent }).match({ doc_id: this.docId, id, state: "pending", ...this.mineFilter() });
961
+ if (error2) throw new Error(`createProposal failed: ${error2.message}`);
962
+ return { id };
963
+ }
964
+ const { error: supersedeErr } = await this.db.from("proposals").update({ state: "superseded" }).match({ doc_id: this.docId, state: "pending", ...this.mineFilter() }).neq("id", id);
965
+ if (supersedeErr) throw new Error(`createProposal failed: ${supersedeErr.message}`);
966
+ const { error } = await this.db.from("proposals").insert({
967
+ id,
968
+ doc_id: this.docId,
969
+ proposer_kind: this.proposer.kind,
970
+ proposer_user_id: this.proposer.userId ?? null,
971
+ client_id: this.proposer.clientId,
972
+ content: input.content,
973
+ base_hash: input.baseHash,
974
+ base_content: input.baseContent,
975
+ state: "pending"
976
+ });
977
+ if (error) {
978
+ if (error.code === "23505") {
979
+ const { error: convergeErr } = await this.db.from("proposals").update({ content: input.content, base_hash: input.baseHash, base_content: input.baseContent }).match({ doc_id: this.docId, id, state: "pending", ...this.mineFilter() });
980
+ if (!convergeErr && await this.getProposal(id)) return { id };
981
+ }
982
+ throw new Error(`createProposal failed: ${error.message}`);
983
+ }
984
+ return { id };
985
+ }
986
+ async myPendingProposal() {
987
+ const { data, error } = await this.db.from("proposals").select("id, content, base_hash, base_content, state, created_at, decided_at").match({ doc_id: this.docId, state: "pending", ...this.mineFilter() }).order("created_at", { ascending: false }).limit(1).maybeSingle();
988
+ if (error) throw new Error(`myPendingProposal failed: ${error.message}`);
989
+ return data ? toRow(data) : null;
783
990
  }
784
- async setProposed(content) {
785
- await this.writeColumns({ proposed: content });
991
+ async getProposal(id) {
992
+ const { data, error } = await this.db.from("proposals").select("id, content, base_hash, base_content, state, created_at, decided_at").match({ doc_id: this.docId, id }).maybeSingle();
993
+ if (error) throw new Error(`getProposal failed: ${error.message}`);
994
+ return data ? toRow(data) : null;
786
995
  }
787
- async clearProposed() {
788
- await this.writeColumns({ proposed: null });
996
+ async withdrawProposal(id) {
997
+ const { error } = await this.db.from("proposals").update({ state: "withdrawn" }).match({ doc_id: this.docId, id, state: "pending", ...this.mineFilter() });
998
+ if (error) throw new Error(`withdrawProposal failed: ${error.message}`);
999
+ }
1000
+ async decideProposal(id, state) {
1001
+ const { data, error } = await this.db.from("proposals").update({ state, decided_at: (/* @__PURE__ */ new Date()).toISOString() }).match({ doc_id: this.docId, id, state: "pending" }).select("id");
1002
+ if (error) throw new Error(`decideProposal failed: ${error.message}`);
1003
+ return { transitioned: (data ?? []).length > 0 };
789
1004
  }
790
1005
  async backup(content, meta) {
791
1006
  const { data: latest } = await this.db.from("doc_versions").select("body").eq("doc_id", this.docId).order("created_at", { ascending: false }).order("id", { ascending: false }).limit(1).maybeSingle();
@@ -858,11 +1073,11 @@ function saveAuth(auth) {
858
1073
  chmodSync(tmp, 384);
859
1074
  } catch {
860
1075
  }
861
- renameSync(tmp, path);
1076
+ renameSync2(tmp, path);
862
1077
  }
863
1078
  function clearAuth() {
864
1079
  const path = authPath();
865
- if (existsSync5(path)) rmSync(path, { force: true });
1080
+ if (existsSync5(path)) rmSync2(path, { force: true });
866
1081
  }
867
1082
  var LOCK_WAIT_MS = 1e4;
868
1083
  var LOCK_STALE_MS = 6e4;
@@ -889,10 +1104,10 @@ async function withAuthLock(fn, opts = {}) {
889
1104
  } catch (e) {
890
1105
  if (e.code !== "EEXIST") throw e;
891
1106
  try {
892
- if (Date.now() - statSync2(lock).mtimeMs > staleMs) {
1107
+ if (Date.now() - statSync3(lock).mtimeMs > staleMs) {
893
1108
  const aside = `${lock}.stale-${token}`;
894
- renameSync(lock, aside);
895
- rmSync(aside, { recursive: true, force: true });
1109
+ renameSync2(lock, aside);
1110
+ rmSync2(aside, { recursive: true, force: true });
896
1111
  continue;
897
1112
  }
898
1113
  } catch {
@@ -921,7 +1136,7 @@ async function withAuthLock(fn, opts = {}) {
921
1136
  } finally {
922
1137
  clearInterval(beat);
923
1138
  try {
924
- if (readFileSync4(lockOwnerPath(), "utf8") === token) rmSync(lock, { recursive: true, force: true });
1139
+ if (readFileSync4(lockOwnerPath(), "utf8") === token) rmSync2(lock, { recursive: true, force: true });
925
1140
  } catch {
926
1141
  }
927
1142
  }
@@ -982,13 +1197,44 @@ async function currentUser() {
982
1197
  ...name ? { name } : {}
983
1198
  };
984
1199
  }
1200
+ var cachedClientId = null;
1201
+ function machineClientId() {
1202
+ if (cachedClientId) return cachedClientId;
1203
+ const home = process.env.INPLAN_HOME || join4(homedir3(), ".inplan");
1204
+ const p = join4(home, "proposer-client-id");
1205
+ try {
1206
+ const v2 = readFileSync4(p, "utf8").trim();
1207
+ if (v2) return cachedClientId = v2;
1208
+ } catch {
1209
+ }
1210
+ const v = mintProposalId();
1211
+ try {
1212
+ mkdirSync3(dirname5(p), { recursive: true });
1213
+ const tmp = `${p}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
1214
+ writeFileSync3(tmp, v);
1215
+ try {
1216
+ linkSync(tmp, p);
1217
+ } finally {
1218
+ rmSync2(tmp, { force: true });
1219
+ }
1220
+ } catch {
1221
+ try {
1222
+ const w = readFileSync4(p, "utf8").trim();
1223
+ if (w) return cachedClientId = w;
1224
+ } catch {
1225
+ }
1226
+ }
1227
+ return cachedClientId = v;
1228
+ }
985
1229
  async function remoteBackend(docId, consumerId = "cli-agent", skewS) {
986
1230
  const s = await authedSession(skewS);
987
1231
  if (!s) return null;
988
1232
  return {
989
1233
  db: s.db,
990
1234
  channel: new SupabaseControlChannel(s.db, docId, consumerId),
991
- store: new SupabaseDocumentStore(s.db, docId),
1235
+ // The CLI proposes as the signed-in USER on this MACHINE: RLS scopes user-kind rows, and the
1236
+ // stable client id keeps two of the same human's machines from superseding each other.
1237
+ store: new SupabaseDocumentStore(s.db, docId, { kind: "user", userId: s.session.user.id, clientId: machineClientId() }),
992
1238
  token: s.session.access_token
993
1239
  };
994
1240
  }
@@ -1048,9 +1294,11 @@ function liveRemoteBackend(docId, consumerId = "cli-agent") {
1048
1294
  saveDoc: async (c) => (await need()).store.saveDoc(c),
1049
1295
  getCanonical: async () => (await need()).store.getCanonical(),
1050
1296
  setCanonical: async (c) => (await need()).store.setCanonical(c),
1051
- getProposed: async () => (await need()).store.getProposed(),
1052
- setProposed: async (c) => (await need()).store.setProposed(c),
1053
- clearProposed: async () => (await need()).store.clearProposed(),
1297
+ createProposal: async (i) => (await need()).store.createProposal(i),
1298
+ myPendingProposal: async () => (await need()).store.myPendingProposal(),
1299
+ getProposal: async (id) => (await need()).store.getProposal(id),
1300
+ withdrawProposal: async (id) => (await need()).store.withdrawProposal(id),
1301
+ decideProposal: async (id, st) => (await need()).store.decideProposal(id, st),
1054
1302
  backup: async (c, m) => (await need()).store.backup(c, m)
1055
1303
  };
1056
1304
  return { channel, store, tokenNow: () => inner?.token ?? null };
@@ -1059,7 +1307,7 @@ function liveRemoteBackend(docId, consumerId = "cli-agent") {
1059
1307
  // src/cliLogin.ts
1060
1308
  import { spawn } from "child_process";
1061
1309
  import { webcrypto } from "crypto";
1062
- import { chmodSync as chmodSync2, existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync7, rmdirSync, statSync as statSync3, unlinkSync as unlinkSync2, writeFileSync as writeFileSync6 } from "fs";
1310
+ import { chmodSync as chmodSync2, existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync7, rmdirSync, statSync as statSync4, unlinkSync as unlinkSync2, writeFileSync as writeFileSync6 } from "fs";
1063
1311
  import { homedir as homedir5 } from "os";
1064
1312
  import { dirname as dirname6, join as join7 } from "path";
1065
1313
 
@@ -1141,7 +1389,7 @@ async function withSidecarLock(fn) {
1141
1389
  } catch (e) {
1142
1390
  if (e.code !== "EEXIST") throw e;
1143
1391
  try {
1144
- if (Date.now() - statSync3(lock).mtimeMs > LOCK_STALE_MS2) rmdirSync(lock);
1392
+ if (Date.now() - statSync4(lock).mtimeMs > LOCK_STALE_MS2) rmdirSync(lock);
1145
1393
  } catch {
1146
1394
  }
1147
1395
  if (Date.now() > deadline) throw new Error("could not acquire the login lock \u2014 another inplan process is holding it");
@@ -1481,6 +1729,191 @@ function runningEditorPid(logPath) {
1481
1729
  return pid !== null && isProcessAlive2(pid) ? pid : null;
1482
1730
  }
1483
1731
 
1732
+ // src/remoteDocState.ts
1733
+ import { appendFileSync as appendFileSync2, closeSync as closeSync2, existsSync as existsSync10, fstatSync, mkdirSync as mkdirSync8, openSync as openSync2, readFileSync as readFileSync9, readSync as readSync2, renameSync as renameSync3, rmSync as rmSync3, writeFileSync as writeFileSync8 } from "fs";
1734
+ import { dirname as dirname8 } from "path";
1735
+ var utf8Bytes = (text) => Buffer.byteLength(text, "utf8");
1736
+ function isDecidedProposalCorpse(latest, currentContent) {
1737
+ if (!latest || latest.state === "pending_review" || currentContent === null) return false;
1738
+ return hashBody(currentContent) === latest.hash;
1739
+ }
1740
+ var RemoteDocState = class {
1741
+ constructor(workFile, docId) {
1742
+ this.workFile = workFile;
1743
+ this.docId = docId;
1744
+ this.pendingPath = `${workFile}.pending`;
1745
+ this.hashPath = `${workFile}.synced`;
1746
+ this.recordPath = `${workFile}.proposed.json`;
1747
+ this.textPath = `${workFile}.proposed.md`;
1748
+ this.historyPath = `${workFile}.proposals.jsonl`;
1749
+ }
1750
+ workFile;
1751
+ docId;
1752
+ /** Marker: a local fallback edit awaits a hub push (public — liveSync's replay decision reads it). */
1753
+ pendingPath;
1754
+ hashPath;
1755
+ recordPath;
1756
+ textPath;
1757
+ historyPath;
1758
+ ensureDir() {
1759
+ mkdirSync8(dirname8(this.workFile), { recursive: true });
1760
+ }
1761
+ // ── Working copy + canonical-sync hash (legacy formats, unchanged) ────────────────────────────
1762
+ readWorkFile() {
1763
+ return existsSync10(this.workFile) ? readFileSync9(this.workFile, "utf8") : null;
1764
+ }
1765
+ writeWorkFile(content) {
1766
+ writeFileSync8(this.workFile, content);
1767
+ }
1768
+ /** Record that the working copy now equals `content` (our last write/sync). */
1769
+ recordSynced(content) {
1770
+ writeFileSync8(this.hashPath, hashBody(content));
1771
+ }
1772
+ /** Assemble the start-of-turn hydration decision's input (see liveSync.shouldHydrateWorkFile). */
1773
+ hydrateInput() {
1774
+ const current = this.readWorkFile();
1775
+ return {
1776
+ exists: current !== null,
1777
+ pending: this.replayPending(),
1778
+ currentHash: current !== null ? hashBody(current) : null,
1779
+ syncedHash: existsSync10(this.hashPath) ? readFileSync9(this.hashPath, "utf8") : null
1780
+ };
1781
+ }
1782
+ // ── Hub-push replay marker (legacy `.pending`, unchanged) ─────────────────────────────────────
1783
+ replayPending() {
1784
+ return existsSync10(this.pendingPath);
1785
+ }
1786
+ markReplayPending() {
1787
+ writeFileSync8(this.pendingPath, "1");
1788
+ }
1789
+ clearReplayPending() {
1790
+ if (existsSync10(this.pendingPath)) rmSync3(this.pendingPath);
1791
+ }
1792
+ // ── Proposal record: the durable "did my edit land?" signal (#88) ─────────────────────────────
1793
+ /**
1794
+ * Park a proposal: publish the record + its exact text as ONE atomic rename, then refresh the
1795
+ * derived `.proposed.md` copy (best-effort — the JSON is authoritative). A still-pending
1796
+ * previous record about different content is finalized into the history as `superseded` first,
1797
+ * so no record is ever silently lost; re-parking identical content keeps the existing pending
1798
+ * identity (same proposal, re-pushed) instead of minting a new one.
1799
+ */
1800
+ parkProposal(text, at = /* @__PURE__ */ new Date(), id) {
1801
+ const prior = this.pendingProposal();
1802
+ const hash = hashBody(text);
1803
+ if (prior && id !== void 0 && id === prior.id && prior.hash !== hash) {
1804
+ const updated = { ...prior, hash, bytes: utf8Bytes(text) };
1805
+ this.publish({ ...updated, text });
1806
+ return updated;
1807
+ }
1808
+ if (prior && prior.hash === hash && (id === void 0 || id === prior.id)) {
1809
+ this.writeDerivedText(text);
1810
+ return prior;
1811
+ }
1812
+ if (prior) this.finalize(prior, "superseded");
1813
+ const record = {
1814
+ // The id is the CLOUD row's id when the caller passes one (proposals v1 — one identity end
1815
+ // to end); minted locally only for offline/desktop parks.
1816
+ id: id ?? `${at.getTime().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
1817
+ docId: this.docId,
1818
+ hash,
1819
+ bytes: utf8Bytes(text),
1820
+ at: at.toISOString(),
1821
+ state: "pending_review"
1822
+ };
1823
+ this.publish({ ...record, text });
1824
+ return record;
1825
+ }
1826
+ /** The latest record regardless of state, or null — missing, unreadable, or failing the full
1827
+ * shape check (wrong doc, non-numeric bytes, unparseable park time, unknown state). A partial
1828
+ * record must read as absent, or it could be finalized with missing metadata. */
1829
+ latestProposal() {
1830
+ const stored = this.readStored();
1831
+ if (!stored) return null;
1832
+ const { text: _text, ...record } = stored;
1833
+ return record;
1834
+ }
1835
+ /** The latest record only while it awaits the human's decision. */
1836
+ pendingProposal() {
1837
+ const record = this.latestProposal();
1838
+ return record?.state === "pending_review" ? record : null;
1839
+ }
1840
+ /** The latest proposal's exact pushed text (recovery path after the working-copy re-sync). */
1841
+ proposedText() {
1842
+ return this.readStored()?.text ?? null;
1843
+ }
1844
+ /**
1845
+ * Finalize the pending record with the human's decision: append it to the never-pruned history
1846
+ * log FIRST (metadata only — an accepted text's fate is canonical history's job), then
1847
+ * republish the record. A crash between the writes leaves the record pending, so the next
1848
+ * resolution retries — and the retry is idempotent because the history tail already carries
1849
+ * this park's unique id.
1850
+ */
1851
+ resolveProposal(outcome) {
1852
+ const pending = this.pendingProposal();
1853
+ if (!pending) return null;
1854
+ return this.finalize(pending, outcome);
1855
+ }
1856
+ finalize(record, outcome) {
1857
+ const finalized = { ...record, state: outcome };
1858
+ const tail2 = this.historyTail();
1859
+ if (!tail2 || tail2.id !== finalized.id || tail2.state !== finalized.state) appendFileSync2(this.historyPath, `${JSON.stringify(finalized)}
1860
+ `);
1861
+ const stored = this.readStored();
1862
+ this.publish({ ...finalized, text: stored?.id === finalized.id ? stored.text : "" });
1863
+ return finalized;
1864
+ }
1865
+ // ── Persistence primitives ────────────────────────────────────────────────────────────────────
1866
+ /** Atomic publish: the record + text land as one rename, then the derived .md refreshes. */
1867
+ publish(stored) {
1868
+ const tmp = `${this.recordPath}.tmp`;
1869
+ writeFileSync8(tmp, JSON.stringify(stored, null, 2));
1870
+ renameSync3(tmp, this.recordPath);
1871
+ this.writeDerivedText(stored.text);
1872
+ }
1873
+ writeDerivedText(text) {
1874
+ try {
1875
+ writeFileSync8(this.textPath, text);
1876
+ } catch {
1877
+ }
1878
+ }
1879
+ readStored() {
1880
+ if (!existsSync10(this.recordPath)) return null;
1881
+ try {
1882
+ const p = JSON.parse(readFileSync9(this.recordPath, "utf8"));
1883
+ const validState = p.state === "pending_review" || p.state === "accepted" || p.state === "partially_accepted" || p.state === "rejected" || p.state === "decided" || p.state === "superseded" || p.state === "withdrawn";
1884
+ if (typeof p.id !== "string" || p.docId !== this.docId || typeof p.hash !== "string" || !Number.isInteger(p.bytes) || p.bytes < 0 || !Number.isFinite(Date.parse(p.at ?? "")) || !validState || typeof p.text !== "string") return null;
1885
+ if (p.state === "pending_review" && (hashBody(p.text) !== p.hash || utf8Bytes(p.text) !== p.bytes)) return null;
1886
+ return p;
1887
+ } catch {
1888
+ return null;
1889
+ }
1890
+ }
1891
+ /** The history log's last finalized record, or null (absent/unreadable/invalid). Reads only the
1892
+ * file's tail — the log is never pruned, so a whole-file read would grow without bound. */
1893
+ historyTail() {
1894
+ if (!existsSync10(this.historyPath)) return null;
1895
+ try {
1896
+ const fd = openSync2(this.historyPath, "r");
1897
+ let chunk;
1898
+ try {
1899
+ const size = fstatSync(fd).size;
1900
+ const span = Math.min(size, 16384);
1901
+ const buf = Buffer.alloc(span);
1902
+ readSync2(fd, buf, 0, span, size - span);
1903
+ chunk = buf.toString("utf8");
1904
+ } finally {
1905
+ closeSync2(fd);
1906
+ }
1907
+ const lines = chunk.trim().split("\n");
1908
+ const last = JSON.parse(lines[lines.length - 1]);
1909
+ if (typeof last.id !== "string" || last.docId !== this.docId || typeof last.hash !== "string" || typeof last.state !== "string") return null;
1910
+ return last;
1911
+ } catch {
1912
+ return null;
1913
+ }
1914
+ }
1915
+ };
1916
+
1484
1917
  // src/applyEdit.ts
1485
1918
  async function applyGatedEdit(store, channel, ev, ctx) {
1486
1919
  const { current, canonicalText, quarantine, gate } = ctx;
@@ -1489,21 +1922,57 @@ async function applyGatedEdit(store, channel, ev, ctx) {
1489
1922
  else {
1490
1923
  await store.saveDoc(ev.acceptedText);
1491
1924
  await store.setCanonical(ev.acceptedText);
1492
- await store.clearProposed();
1925
+ await withdrawOwnPending(store);
1493
1926
  }
1494
1927
  await channel.append({ actor: "agent", type: LogEventType.DocumentEdited, payload: { removed: ev.removedIds } });
1495
1928
  } else if (ev.changed && quarantine) {
1496
- await store.setProposed(current);
1497
- if (!gate) await store.saveDoc(canonicalText);
1498
- await channel.append({ actor: "agent", type: LogEventType.AgentRevisionProposed, payload: { bytes: current.length } });
1929
+ let proposalId;
1930
+ try {
1931
+ ({ id: proposalId } = await store.createProposal({ content: current, baseHash: hashBody(canonicalText), baseContent: canonicalText }));
1932
+ } catch {
1933
+ return { proposed: false, parkFailed: true };
1934
+ }
1935
+ if (!gate && !revertWouldWipe(canonicalText, current)) {
1936
+ try {
1937
+ await store.saveDoc(canonicalText);
1938
+ } catch {
1939
+ }
1940
+ }
1941
+ try {
1942
+ await channel.append({
1943
+ actor: "agent",
1944
+ type: LogEventType.AgentRevisionProposed,
1945
+ // proposal_id names WHICH proposal this event parked — the row/record id, the same one
1946
+ // the wait output carries. bytes/hash stay as human-auditable descriptors of the text.
1947
+ payload: { bytes: utf8Bytes(current), hash: hashBody(current), proposal_id: proposalId }
1948
+ });
1949
+ } catch {
1950
+ return { proposed: true, proposalId, eventLogged: false };
1951
+ }
1952
+ return { proposed: true, proposalId };
1499
1953
  } else if (ev.changed) {
1500
1954
  if (gate) await gate.applyRevision(current);
1501
1955
  else {
1502
1956
  await store.setCanonical(current);
1503
- await store.clearProposed();
1957
+ await withdrawOwnPending(store);
1504
1958
  }
1505
- await channel.append({ actor: "agent", type: LogEventType.DocumentEdited, payload: { bytes: current.length } });
1959
+ await channel.append({ actor: "agent", type: LogEventType.DocumentEdited, payload: { bytes: utf8Bytes(current) } });
1506
1960
  }
1961
+ return { proposed: false };
1962
+ }
1963
+ function revertWouldWipe(canonicalText, current) {
1964
+ const blank = (text) => {
1965
+ try {
1966
+ return parse(text).body.trim() === "";
1967
+ } catch {
1968
+ return text.trim() === "";
1969
+ }
1970
+ };
1971
+ return blank(canonicalText) && !blank(current);
1972
+ }
1973
+ async function withdrawOwnPending(store) {
1974
+ const mine = await store.myPendingProposal();
1975
+ if (mine) await store.withdrawProposal(mine.id);
1507
1976
  }
1508
1977
 
1509
1978
  // src/gate.ts
@@ -1920,19 +2389,19 @@ function waitForActions(opts) {
1920
2389
  }
1921
2390
 
1922
2391
  // src/version.ts
1923
- import { readFileSync as readFileSync9 } from "fs";
1924
- import { dirname as dirname8, join as join9 } from "path";
2392
+ import { readFileSync as readFileSync10 } from "fs";
2393
+ import { dirname as dirname9, join as join9 } from "path";
1925
2394
  import { fileURLToPath } from "url";
1926
2395
  function versionFromDir(moduleDir) {
1927
2396
  try {
1928
- const pkg = JSON.parse(readFileSync9(join9(moduleDir, "..", "package.json"), "utf8"));
2397
+ const pkg = JSON.parse(readFileSync10(join9(moduleDir, "..", "package.json"), "utf8"));
1929
2398
  return typeof pkg.version === "string" ? pkg.version : "0.0.0";
1930
2399
  } catch {
1931
2400
  return "0.0.0";
1932
2401
  }
1933
2402
  }
1934
2403
  function versionFromModule(moduleUrl) {
1935
- return versionFromDir(dirname8(fileURLToPath(moduleUrl)));
2404
+ return versionFromDir(dirname9(fileURLToPath(moduleUrl)));
1936
2405
  }
1937
2406
 
1938
2407
  // src/relayActivity.ts
@@ -1953,12 +2422,12 @@ function toolActivityText(toolName, toolInput) {
1953
2422
  }
1954
2423
 
1955
2424
  // src/ensureDoc.ts
1956
- import { mkdirSync as mkdirSync8, writeFileSync as writeFileSync8 } from "fs";
1957
- import { dirname as dirname9 } from "path";
2425
+ import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync9 } from "fs";
2426
+ import { dirname as dirname10 } from "path";
1958
2427
  function ensureDocFile(file) {
1959
- mkdirSync8(dirname9(file), { recursive: true });
2428
+ mkdirSync9(dirname10(file), { recursive: true });
1960
2429
  try {
1961
- writeFileSync8(file, "", { flag: "wx" });
2430
+ writeFileSync9(file, "", { flag: "wx" });
1962
2431
  return true;
1963
2432
  } catch (err) {
1964
2433
  if (err.code === "EEXIST") return false;
@@ -2031,13 +2500,13 @@ function electronDistRel(platform) {
2031
2500
  }
2032
2501
  function electronBinaryFromDisk(reqUrl) {
2033
2502
  try {
2034
- const pkgDir = dirname10(createRequire(reqUrl).resolve("electron/package.json"));
2503
+ const pkgDir = dirname11(createRequire(reqUrl).resolve("electron/package.json"));
2035
2504
  const rel = electronDistRel(process.platform);
2036
2505
  const bin = join10(pkgDir, "dist", rel);
2037
- if (!existsSync10(bin)) return null;
2506
+ if (!existsSync11(bin)) return null;
2038
2507
  try {
2039
2508
  const pathFile = join10(pkgDir, "path.txt");
2040
- if (!existsSync10(pathFile)) writeFileSync9(pathFile, rel);
2509
+ if (!existsSync11(pathFile)) writeFileSync10(pathFile, rel);
2041
2510
  } catch {
2042
2511
  }
2043
2512
  return bin;
@@ -2057,8 +2526,8 @@ function cachedElectronZip(version, platform, arch) {
2057
2526
  let best = null;
2058
2527
  for (const sub of readdirSync2(root)) {
2059
2528
  const f = join10(root, sub, want);
2060
- if (!existsSync10(f)) continue;
2061
- const mtime = statSync4(f).mtimeMs;
2529
+ if (!existsSync11(f)) continue;
2530
+ const mtime = statSync5(f).mtimeMs;
2062
2531
  if (!best || mtime > best.mtime) best = { file: f, mtime };
2063
2532
  }
2064
2533
  return best?.file ?? null;
@@ -2077,17 +2546,17 @@ function expandArchiveWindows(zipPath, destDir) {
2077
2546
  function autoInstallElectron(reqUrl) {
2078
2547
  if (process.env.INPLAN_NO_ELECTRON_DOWNLOAD === "1") return false;
2079
2548
  try {
2080
- const pkgDir = dirname10(createRequire(reqUrl).resolve("electron/package.json"));
2549
+ const pkgDir = dirname11(createRequire(reqUrl).resolve("electron/package.json"));
2081
2550
  const installJs = join10(pkgDir, "install.js");
2082
- if (!existsSync10(installJs)) return false;
2551
+ if (!existsSync11(installJs)) return false;
2083
2552
  process.stderr.write("[inplan] editor runtime missing \u2014 retrying the download \u2026\n");
2084
2553
  execFileSync2(process.execPath, [installJs], { cwd: pkgDir, stdio: "inherit", env: process.env });
2085
2554
  if (electronBinaryFromDisk(reqUrl) !== null) return true;
2086
2555
  if (process.platform === "win32") {
2087
- const { version } = JSON.parse(readFileSync10(join10(pkgDir, "package.json"), "utf8"));
2556
+ const { version } = JSON.parse(readFileSync11(join10(pkgDir, "package.json"), "utf8"));
2088
2557
  const zip = cachedElectronZip(version, "win32", process.env.npm_config_arch || process.arch);
2089
2558
  if (zip && expandArchiveWindows(zip, join10(pkgDir, "dist"))) {
2090
- writeFileSync9(join10(pkgDir, "path.txt"), "electron.exe");
2559
+ writeFileSync10(join10(pkgDir, "path.txt"), "electron.exe");
2091
2560
  }
2092
2561
  }
2093
2562
  return electronBinaryFromDisk(reqUrl) !== null;
@@ -2096,12 +2565,12 @@ function autoInstallElectron(reqUrl) {
2096
2565
  }
2097
2566
  }
2098
2567
  function resolveBundledApp() {
2099
- const here = dirname10(fileURLToPath2(import.meta.url));
2568
+ const here = dirname11(fileURLToPath2(import.meta.url));
2100
2569
  const appMain = join10(here, "..", "app", "main", "index.cjs");
2101
- if (!existsSync10(appMain)) return { appMain: null };
2570
+ if (!existsSync11(appMain)) return { appMain: null };
2102
2571
  try {
2103
2572
  const electron = createRequire(import.meta.url)("electron");
2104
- if (typeof electron === "string" && electron && existsSync10(electron)) return { electron, appMain };
2573
+ if (typeof electron === "string" && electron && existsSync11(electron)) return { electron, appMain };
2105
2574
  } catch {
2106
2575
  }
2107
2576
  const onDisk = electronBinaryFromDisk(import.meta.url);
@@ -2136,7 +2605,7 @@ function spawnApp(file) {
2136
2605
  process.stderr.write("[inplan] no bundled editor (running from source?) \u2014 set INPLAN_APP_CMD to your editor; running headless\n");
2137
2606
  } else {
2138
2607
  trackCli("editor_launch_failed", telemetryOn, { reason: "electron_unavailable" });
2139
- const root = resolve3(dirname10(bundled.appMain), "..", "..");
2608
+ const root = resolve3(dirname11(bundled.appMain), "..", "..");
2140
2609
  process.stderr.write(
2141
2610
  `[inplan] the bundled editor's Electron runtime is unavailable: ${bundled.error}
2142
2611
  \u2192 re-download the binary: npm rebuild electron --prefix "${root}"
@@ -2167,14 +2636,20 @@ function modeFrom(entries) {
2167
2636
  return { cadence: "turn", wake: "turn-end", locksEditor: true };
2168
2637
  }
2169
2638
  function acceptanceFrom(entries) {
2170
- return settingsFromEntries(entries).acceptance === "auto" ? "auto" : "review";
2639
+ for (let i = entries.length - 1; i >= 0; i--) {
2640
+ const e = entries[i];
2641
+ if (e.type !== LogEventType.ModeChanged && e.type !== LogEventType.SettingsChanged) continue;
2642
+ const a = e.payload?.acceptance;
2643
+ if (a === "auto" || a === "review") return a;
2644
+ }
2645
+ return settingsFromEntries([]).acceptance === "auto" ? "auto" : "review";
2171
2646
  }
2172
2647
  function maxSeqFrom(entries) {
2173
2648
  return entries.length ? entries[entries.length - 1].seq : 0;
2174
2649
  }
2175
2650
  function fsBackend(file) {
2176
2651
  const p = docPaths(file);
2177
- mkdirSync9(p.controlDir, { recursive: true });
2652
+ mkdirSync10(p.controlDir, { recursive: true });
2178
2653
  return {
2179
2654
  channel: new FsControlChannel(p),
2180
2655
  store: new FsDocumentStore(p),
@@ -2184,7 +2659,7 @@ function fsBackend(file) {
2184
2659
  }
2185
2660
  function logWaitExit(p, reason) {
2186
2661
  try {
2187
- appendFileSync2(p.waitDebugPath, `${(/* @__PURE__ */ new Date()).toISOString()} pid=${process.pid} ${reason}
2662
+ appendFileSync3(p.waitDebugPath, `${(/* @__PURE__ */ new Date()).toISOString()} pid=${process.pid} ${reason}
2188
2663
  `);
2189
2664
  } catch {
2190
2665
  }
@@ -2229,10 +2704,34 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
2229
2704
  }
2230
2705
  const acceptance = acceptanceFrom(history);
2231
2706
  const quarantine = acceptance === "review" && parse(canonicalText).body !== parse(current).body;
2232
- await applyGatedEdit(store, channel, ev, { current, canonicalText, quarantine, gate: usePlugin ? gate : null });
2233
- await channel.append({ actor: "agent", type: LogEventType.AgentRevised });
2707
+ const applied = await applyGatedEdit(store, channel, ev, { current, canonicalText, quarantine, gate: usePlugin ? gate : null });
2708
+ if (applied.proposed) {
2709
+ process.stderr.write(
2710
+ applied.eventLogged === false ? "inplan: review mode \u2014 your edit was parked as a proposal, but its notification event could NOT be logged: the proposal is safely stored, and the human's editor may not show it until they reload. Not a sync failure.\n" : "inplan: review mode \u2014 your edit was parked as a proposal (agent_revision_proposed); the canonical body is unchanged until the human accepts. This is normal, not a sync failure.\n"
2711
+ );
2712
+ }
2713
+ if (applied.parkFailed) {
2714
+ process.stderr.write("inplan: pushing your edit as a review proposal FAILED \u2014 the edit is kept in the working copy and will be re-pushed on the next run.\n");
2715
+ }
2716
+ const parkFailedId = applied.parkFailed ? backend.localPendingProposalId?.() : void 0;
2717
+ const proposalOut = applied.proposed ? { proposal: { state: "pending_review", ...applied.proposalId ? { id: applied.proposalId } : {}, bytes: utf8Bytes(current), hash: hashBody(current) } } : applied.parkFailed ? { proposal: { state: "park_failed", ...parkFailedId ? { id: parkFailedId } : {}, bytes: utf8Bytes(current), hash: hashBody(current) } } : {};
2718
+ try {
2719
+ await channel.append({ actor: "agent", type: LogEventType.AgentRevised });
2720
+ } catch {
2721
+ process.stderr.write("inplan: could not log the turn marker (control log write failed) \u2014 the editor may keep showing 'Agent is thinking' until it reloads.\n");
2722
+ }
2234
2723
  const lockToken = `${process.pid}-${Date.now()}`;
2235
- await channel.claimLock(lockToken);
2724
+ try {
2725
+ await channel.claimLock(lockToken);
2726
+ } catch (e) {
2727
+ backend.logExit("claim_lock_failed");
2728
+ process.stderr.write(`inplan: could not claim the wait lock (${String(e)}).
2729
+ If your session expired, run \`inplan login\` and re-attach.
2730
+ `);
2731
+ output({ status: "wait_failed", message: `could not claim the wait lock: ${String(e)}`, ...proposalOut });
2732
+ exitAfterFlush(EXIT_WAIT_FAILED);
2733
+ return "exiting";
2734
+ }
2236
2735
  for (const sig of ["SIGTERM", "SIGHUP", "SIGINT"]) {
2237
2736
  process.on(sig, () => {
2238
2737
  backend.logExit(`signal:${sig}`);
@@ -2241,29 +2740,31 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
2241
2740
  }
2242
2741
  const debounceMs = Number(process.env.INPLAN_DEBOUNCE_MS ?? 3e3);
2243
2742
  const pollMs = Number(process.env.INPLAN_POLL_MS ?? 200);
2743
+ const errorGraceParsed = Number(process.env.INPLAN_ERROR_GRACE_MS);
2744
+ const errorGraceMs = process.env.INPLAN_ERROR_GRACE_MS && Number.isFinite(errorGraceParsed) && errorGraceParsed >= 0 ? errorGraceParsed : void 0;
2244
2745
  let waitCursor = cursor;
2245
2746
  let historyForMode = history;
2246
2747
  for (; ; ) {
2247
2748
  const mode = modeFrom(historyForMode);
2248
2749
  const isActionable = wakePredicate(mode.wake);
2249
- const result = await waitForActions({ channel, cursor: waitCursor, debounceMs, pollMs, isActionable, token: lockToken });
2750
+ const result = await waitForActions({ channel, cursor: waitCursor, debounceMs, pollMs, isActionable, token: lockToken, ...errorGraceMs !== void 0 ? { errorGraceMs } : {} });
2250
2751
  if (result.failed) {
2251
2752
  backend.logExit("poll_failed");
2252
2753
  process.stderr.write(`inplan: lost contact with the document (${result.failed.message}).
2253
2754
  If your session expired, run \`inplan login\` and re-attach.
2254
2755
  `);
2255
- output({ status: "wait_failed", message: result.failed.message });
2756
+ output({ status: "wait_failed", message: result.failed.message, ...proposalOut });
2256
2757
  exitAfterFlush(EXIT_WAIT_FAILED);
2257
2758
  return "exiting";
2258
2759
  }
2259
2760
  if (result.superseded) {
2260
2761
  backend.logExit("superseded");
2261
- output({ status: "superseded" });
2762
+ output({ status: "superseded", ...proposalOut });
2262
2763
  return "ok";
2263
2764
  }
2264
2765
  if (backend.onSaveLocally && result.entries.some((e) => e.type === LogEventType.SaveLocallyRequested)) {
2265
2766
  backend.logExit("save_locally");
2266
- await backend.onSaveLocally();
2767
+ await backend.onSaveLocally(proposalOut);
2267
2768
  return "ok";
2268
2769
  }
2269
2770
  await channel.setCursor(result.cursor);
@@ -2271,7 +2772,7 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
2271
2772
  if (navEntry) {
2272
2773
  const path = navEntry.payload?.path;
2273
2774
  backend.logExit("navigated");
2274
- output({ status: "navigated", ...path ? { path } : {}, cursor: result.cursor, closed: false });
2775
+ output({ status: "navigated", ...path ? { path } : {}, ...proposalOut, cursor: result.cursor, closed: false });
2275
2776
  return "ok";
2276
2777
  }
2277
2778
  const closeEntry = [...result.entries].reverse().find((e) => e.type === LogEventType.SessionClosed);
@@ -2286,13 +2787,13 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
2286
2787
  const reopen = await awaitReopen(channel, result.cursor, { token: lockToken });
2287
2788
  if (reopen.kind === "superseded") {
2288
2789
  backend.logExit("superseded");
2289
- output({ status: "superseded" });
2790
+ output({ status: "superseded", ...proposalOut });
2290
2791
  return "ok";
2291
2792
  }
2292
2793
  if (reopen.kind === "completed") {
2293
2794
  await channel.setCursor(reopen.cursor);
2294
2795
  backend.logExit(reopen.reason);
2295
- output({ status: "closed", reason: reopen.reason, cursor: reopen.cursor, closed: true, entries: [...result.entries, ...reopen.entries] });
2796
+ output({ status: "closed", reason: reopen.reason, ...proposalOut, cursor: reopen.cursor, closed: true, entries: [...result.entries, ...reopen.entries] });
2296
2797
  return "ok";
2297
2798
  }
2298
2799
  if (reopen.kind === "reopened") {
@@ -2326,6 +2827,10 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
2326
2827
  // when --model was passed), so presence + authorship stay consistent.
2327
2828
  agentAuthor: agentAuthorFor(model),
2328
2829
  ...reason ? { reason } : {},
2830
+ // The landing signal for a parked Review-mode edit (#88): pending_review means the push
2831
+ // REACHED the store and awaits the human — the canonical is unchanged by design. Absent
2832
+ // when the turn applied directly (or made no body change).
2833
+ ...proposalOut,
2329
2834
  cursor: result.cursor,
2330
2835
  closed: status === "closed",
2331
2836
  entries: result.entries
@@ -2522,10 +3027,10 @@ async function pendingLoginExit() {
2522
3027
  function stalenessCache() {
2523
3028
  const path = join10(sidecarRoot(), ".update-check.json");
2524
3029
  return {
2525
- readCache: () => existsSync10(path) ? readFileSync10(path, "utf8") : null,
3030
+ readCache: () => existsSync11(path) ? readFileSync11(path, "utf8") : null,
2526
3031
  writeCache: (v) => {
2527
- mkdirSync9(dirname10(path), { recursive: true });
2528
- writeFileSync9(path, v);
3032
+ mkdirSync10(dirname11(path), { recursive: true });
3033
+ writeFileSync10(path, v);
2529
3034
  }
2530
3035
  };
2531
3036
  }
@@ -2602,18 +3107,15 @@ async function runRemote(cmd, docId, explicitCursor, confirmed, rest, localFile,
2602
3107
  presenceTokenResolver(backend.token, async () => {
2603
3108
  const fresh = await remoteBackend(docId, "cli-agent");
2604
3109
  if (fresh) return fresh;
2605
- if (!existsSync10(authPath())) return null;
3110
+ if (!existsSync11(authPath())) return null;
2606
3111
  throw new Error("transient token refresh failure");
2607
3112
  }),
2608
3113
  model
2609
3114
  );
2610
3115
  try {
2611
3116
  const workFile = join10(sidecarRoot(), "remote", `${docId}.plan.md`);
2612
- const pendingPath = `${workFile}.pending`;
2613
- const hashPath = `${workFile}.synced`;
2614
- mkdirSync9(dirname10(workFile), { recursive: true });
2615
- const readIf = (p) => existsSync10(p) ? readFileSync10(p, "utf8") : null;
2616
- const recordSynced = (content) => writeFileSync9(hashPath, hashBody(content));
3117
+ const rds = new RemoteDocState(workFile, docId);
3118
+ rds.ensureDir();
2617
3119
  let canonical = "";
2618
3120
  try {
2619
3121
  canonical = await gate.readCanonical();
@@ -2624,33 +3126,121 @@ async function runRemote(cmd, docId, explicitCursor, confirmed, rest, localFile,
2624
3126
  exitAfterFlush(EXIT_PLUGIN_UNAVAILABLE);
2625
3127
  return;
2626
3128
  }
2627
- const exists = existsSync10(workFile);
2628
- if (shouldHydrateWorkFile({
2629
- exists,
2630
- pending: existsSync10(pendingPath),
2631
- currentHash: exists ? hashBody(readFileSync10(workFile, "utf8")) : null,
2632
- syncedHash: readIf(hashPath)
2633
- })) {
2634
- writeFileSync9(workFile, canonical);
2635
- recordSynced(canonical);
3129
+ let justFinalized = false;
3130
+ const myRow = await live.store.myPendingProposal().catch(() => void 0);
3131
+ if (myRow !== void 0) {
3132
+ try {
3133
+ const pending = rds.pendingProposal();
3134
+ if (myRow && pending?.id !== myRow.id) {
3135
+ let settled = true;
3136
+ if (pending) {
3137
+ const priorRow = await live.store.getProposal(pending.id).catch(() => void 0);
3138
+ if (priorRow === void 0) settled = false;
3139
+ else {
3140
+ const finalized = rds.resolveProposal(priorRow && priorRow.state !== "pending" ? priorRow.state : "superseded");
3141
+ if (finalized && !rds.replayPending() && isDecidedProposalCorpse(finalized, rds.readWorkFile())) {
3142
+ rds.writeWorkFile(canonical);
3143
+ rds.recordSynced(canonical);
3144
+ }
3145
+ }
3146
+ }
3147
+ if (settled) rds.parkProposal(myRow.content, void 0, myRow.id);
3148
+ } else if (myRow && pending && pending.hash !== hashBody(myRow.content)) {
3149
+ rds.parkProposal(myRow.content, void 0, myRow.id);
3150
+ } else if (!myRow && pending) {
3151
+ const row = await live.store.getProposal(pending.id).catch(() => void 0);
3152
+ if (row === null) justFinalized = rds.resolveProposal("decided") !== null;
3153
+ else if (row && row.state !== "pending") justFinalized = rds.resolveProposal(row.state) !== null;
3154
+ }
3155
+ } catch (e) {
3156
+ process.stderr.write(`inplan: could not reconcile the local proposal record (${String(e)}); continuing \u2014 it will retry next run
3157
+ `);
3158
+ }
3159
+ }
3160
+ if (justFinalized && !rds.replayPending() && isDecidedProposalCorpse(rds.latestProposal(), rds.readWorkFile())) {
3161
+ rds.writeWorkFile(canonical);
3162
+ rds.recordSynced(canonical);
3163
+ }
3164
+ if (shouldHydrateWorkFile(rds.hydrateInput())) {
3165
+ rds.writeWorkFile(canonical);
3166
+ rds.recordSynced(canonical);
2636
3167
  }
2637
3168
  const localStore = fsBackend(workFile).store;
3169
+ let hubParkFailed = false;
2638
3170
  const gateStore = {
2639
3171
  loadDoc: () => localStore.loadDoc(),
2640
3172
  saveDoc: (c) => localStore.saveDoc(c),
2641
3173
  getCanonical: () => localStore.getCanonical(),
2642
3174
  setCanonical: (c) => localStore.setCanonical(c),
2643
3175
  backup: (c, m) => localStore.backup(c, m),
2644
- getProposed: () => live.store.getProposed(),
2645
- setProposed: (c) => live.store.setProposed(c),
2646
- clearProposed: () => live.store.clearProposed()
3176
+ myPendingProposal: () => live.store.myPendingProposal(),
3177
+ getProposal: (id) => live.store.getProposal(id),
3178
+ // Cloud-side lifecycle transitions settle the LOCAL record too, or it would stay
3179
+ // pending_review while its cloud row is terminal — and the id-reuse on the next park
3180
+ // would then converge against an immutable row and the content would never land. The
3181
+ // local record mirrors the row's ACTUAL terminal state, not the intended one: our
3182
+ // transition is state-guarded and can lose a race (zero rows updated, no error) to a
3183
+ // human decision that landed first — the decision wins, locally too.
3184
+ withdrawProposal: async (id) => {
3185
+ await live.store.withdrawProposal(id);
3186
+ if (rds.pendingProposal()?.id === id) {
3187
+ const row = await live.store.getProposal(id).catch(() => null);
3188
+ if (row && row.state !== "pending") rds.resolveProposal(row.state);
3189
+ }
3190
+ },
3191
+ decideProposal: async (id, st) => {
3192
+ const result = await live.store.decideProposal(id, st);
3193
+ if (rds.pendingProposal()?.id === id) {
3194
+ const row = await live.store.getProposal(id).catch(() => null);
3195
+ if (row && row.state !== "pending") rds.resolveProposal(row.state);
3196
+ }
3197
+ return result;
3198
+ },
3199
+ createProposal: async (input) => {
3200
+ const prior = rds.pendingProposal();
3201
+ const id = input.id ?? (prior && prior.hash === hashBody(input.content) ? prior.id : void 0);
3202
+ let created;
3203
+ try {
3204
+ created = await live.store.createProposal({ ...input, ...id ? { id } : {} });
3205
+ if (id) {
3206
+ const row = await live.store.getProposal(created.id);
3207
+ if (!row) throw new Error(`park verification found no row for reused id ${created.id}`);
3208
+ if (row.state !== "pending") {
3209
+ if (rds.pendingProposal()?.id === created.id) rds.resolveProposal(row.state);
3210
+ created = await live.store.createProposal({ content: input.content, baseHash: input.baseHash, baseContent: input.baseContent });
3211
+ }
3212
+ }
3213
+ } catch (e) {
3214
+ hubParkFailed = true;
3215
+ throw e;
3216
+ }
3217
+ try {
3218
+ if (prior && prior.id !== created.id) {
3219
+ const priorRow = await live.store.getProposal(prior.id);
3220
+ if (priorRow && priorRow.state !== "pending" && priorRow.state !== "superseded") rds.resolveProposal(priorRow.state);
3221
+ }
3222
+ } catch {
3223
+ }
3224
+ try {
3225
+ rds.parkProposal(input.content, void 0, created.id);
3226
+ } catch (e) {
3227
+ process.stderr.write(`inplan: could not write the local proposal record (${String(e)}); the proposal is live in the cloud and the record will be reconciled on the next run
3228
+ `);
3229
+ }
3230
+ return created;
3231
+ }
2647
3232
  };
2648
- const onSaveLocallyGate = localFile ? async () => {
3233
+ const onSaveLocallyGate = localFile ? async (info) => {
2649
3234
  const body = await gate.readCanonical();
2650
- writeFileSync9(localFile, body);
3235
+ const leftover = rds.readWorkFile();
3236
+ if (leftover !== null && hashBody(leftover) !== (rds.hydrateInput().syncedHash ?? "") && parse(leftover).body !== parse(body).body) {
3237
+ process.stderr.write(`inplan: the doc moved local, but an unpushed edit remains at ${workFile} \u2014 merge it into ${localFile} by hand if you still want it.
3238
+ `);
3239
+ }
3240
+ writeFileSync10(localFile, body);
2651
3241
  writeStatus(docPaths(localFile).statusPath, { location: "local", originalPath: localFile, lastSyncedHash: hashBody(body) });
2652
3242
  const pid = spawnApp(localFile);
2653
- output({ status: "moved_local", path: localFile, reopened: pid !== null });
3243
+ output({ status: "moved_local", path: localFile, reopened: pid !== null, ...info });
2654
3244
  } : void 0;
2655
3245
  const tracked = trackGateDegradations(
2656
3246
  gate,
@@ -2669,6 +3259,8 @@ async function runRemote(cmd, docId, explicitCursor, confirmed, rest, localFile,
2669
3259
  history: async () => (await live.channel.readSince(0)).entries,
2670
3260
  logExit: () => {
2671
3261
  },
3262
+ localPendingProposalId: () => rds.pendingProposal()?.id,
3263
+ // local file read only — see WaitBackend
2672
3264
  ...onSaveLocallyGate ? { onSaveLocally: onSaveLocallyGate } : {}
2673
3265
  },
2674
3266
  explicitCursor,
@@ -2677,20 +3269,21 @@ async function runRemote(cmd, docId, explicitCursor, confirmed, rest, localFile,
2677
3269
  tracked.gate
2678
3270
  // …and accepted edits apply through the hub, not the store.
2679
3271
  );
2680
- const action = postTurnAction(outcome, { readFailed: tracked.readFailed(), writeFailed: tracked.writeFailed() });
3272
+ const degraded = { readFailed: tracked.readFailed(), writeFailed: tracked.writeFailed() || hubParkFailed };
3273
+ const action = postTurnAction(outcome, degraded);
2681
3274
  if (action === "stop") return;
2682
3275
  if (action === "keep-local") {
2683
- if (pendingRequiresReplay({ readFailed: tracked.readFailed(), writeFailed: tracked.writeFailed() })) {
2684
- writeFileSync9(pendingPath, "1");
3276
+ if (pendingRequiresReplay(degraded)) {
3277
+ rds.markReplayPending();
2685
3278
  }
2686
3279
  process.stderr.write("inplan: hub was unavailable this turn \u2014 keeping local edits (will sync next turn)\n");
2687
3280
  } else {
2688
- if (existsSync10(pendingPath)) rmSync2(pendingPath);
2689
- recordSynced(readFileSync10(workFile, "utf8"));
3281
+ rds.clearReplayPending();
3282
+ rds.recordSynced(rds.readWorkFile() ?? "");
2690
3283
  try {
2691
3284
  const fresh = await gate.readCanonical();
2692
- writeFileSync9(workFile, fresh);
2693
- recordSynced(fresh);
3285
+ rds.writeWorkFile(fresh);
3286
+ rds.recordSynced(fresh);
2694
3287
  } catch {
2695
3288
  }
2696
3289
  }
@@ -2708,7 +3301,7 @@ function doPromote(file, args) {
2708
3301
  process.stderr.write("usage: inplan promote <file> --cloud-doc <docId> [--locator org/repo/path]\n");
2709
3302
  process.exit(64);
2710
3303
  }
2711
- const body = existsSync10(file) ? readFileSync10(file, "utf8") : "";
3304
+ const body = existsSync11(file) ? readFileSync11(file, "utf8") : "";
2712
3305
  const status = { location: "cloud", cloudDocId, originalPath: file, lastSyncedHash: hashBody(body) };
2713
3306
  const locator = getFlag(args, "locator");
2714
3307
  if (locator) {
@@ -2753,7 +3346,7 @@ async function doDemote(file, args) {
2753
3346
  return;
2754
3347
  }
2755
3348
  const body = choice.use === "hub" ? hubBody : await backend.store.loadDoc();
2756
- writeFileSync9(dest, body);
3349
+ writeFileSync10(dest, body);
2757
3350
  writeStatus(p.statusPath, { location: "local", originalPath: dest, lastSyncedHash: hashBody(body) });
2758
3351
  output({ status: "demoted", location: "local", path: dest, source: choice.use });
2759
3352
  }
@@ -2788,16 +3381,16 @@ async function doToken() {
2788
3381
  function bundledSkillPath() {
2789
3382
  try {
2790
3383
  const override = process.env.INPLAN_SKILL_SRC;
2791
- if (override) return existsSync10(override) ? override : null;
2792
- const p = join10(dirname10(fileURLToPath2(import.meta.url)), "..", "skill", "SKILL.md");
2793
- return existsSync10(p) ? p : null;
3384
+ if (override) return existsSync11(override) ? override : null;
3385
+ const p = join10(dirname11(fileURLToPath2(import.meta.url)), "..", "skill", "SKILL.md");
3386
+ return existsSync11(p) ? p : null;
2794
3387
  } catch {
2795
3388
  return null;
2796
3389
  }
2797
3390
  }
2798
3391
  function activeDocForCwd(cwd) {
2799
3392
  const root = sidecarRoot();
2800
- if (!existsSync10(root)) return null;
3393
+ if (!existsSync11(root)) return null;
2801
3394
  const real = (p) => {
2802
3395
  try {
2803
3396
  return realpathSync(p);
@@ -2815,7 +3408,7 @@ function activeDocForCwd(cwd) {
2815
3408
  const rel = relative4(base2, real(orig));
2816
3409
  if (rel === "" || rel.startsWith("..") || isAbsolute2(rel)) continue;
2817
3410
  const logPath = join10(dir, "log.jsonl");
2818
- const mtime = existsSync10(logPath) ? statSync4(logPath).mtimeMs : 0;
3411
+ const mtime = existsSync11(logPath) ? statSync5(logPath).mtimeMs : 0;
2819
3412
  if (!best || mtime > best.mtime) best = { file: resolve3(orig), mtime };
2820
3413
  } catch {
2821
3414
  }
@@ -2828,7 +3421,7 @@ function relayCursorPath(sessionKey) {
2828
3421
  }
2829
3422
  function readRelayCursor(sessionKey) {
2830
3423
  try {
2831
- const v = JSON.parse(readFileSync10(relayCursorPath(sessionKey), "utf8"));
3424
+ const v = JSON.parse(readFileSync11(relayCursorPath(sessionKey), "utf8"));
2832
3425
  return typeof v.sent === "number" && v.sent >= 0 ? v.sent : 0;
2833
3426
  } catch {
2834
3427
  return 0;
@@ -2837,8 +3430,8 @@ function readRelayCursor(sessionKey) {
2837
3430
  function writeRelayCursor(sessionKey, sent) {
2838
3431
  try {
2839
3432
  const p = relayCursorPath(sessionKey);
2840
- mkdirSync9(dirname10(p), { recursive: true });
2841
- writeFileSync9(p, JSON.stringify({ sent }) + "\n");
3433
+ mkdirSync10(dirname11(p), { recursive: true });
3434
+ writeFileSync10(p, JSON.stringify({ sent }) + "\n");
2842
3435
  } catch {
2843
3436
  }
2844
3437
  }
@@ -2846,7 +3439,7 @@ function transcriptTextBlocks(path) {
2846
3439
  const out = [];
2847
3440
  let raw;
2848
3441
  try {
2849
- raw = readFileSync10(path, "utf8");
3442
+ raw = readFileSync11(path, "utf8");
2850
3443
  } catch {
2851
3444
  return out;
2852
3445
  }
@@ -2891,7 +3484,7 @@ function notesFromHook(kind, stdin, argv) {
2891
3484
  const p = parse2(stdin);
2892
3485
  const transcript = str(p.transcript_path);
2893
3486
  const sessionKey = str(p.session_id) || transcript;
2894
- const blocks = transcript && existsSync10(transcript) && sessionKey ? transcriptTextBlocks(transcript) : [];
3487
+ const blocks = transcript && existsSync11(transcript) && sessionKey ? transcriptTextBlocks(transcript) : [];
2895
3488
  if (blocks.length > 0) {
2896
3489
  const sent = readRelayCursor(sessionKey);
2897
3490
  for (let i = Math.max(0, sent); i < blocks.length; i++) notes.push(blocks[i]);
@@ -2915,7 +3508,7 @@ async function relayText(file, text) {
2915
3508
  await backend.channel.append({ actor: "agent", type: LogEventType.AgentMessage, payload: { text } });
2916
3509
  } else if (route.kind === "local") {
2917
3510
  const p = docPaths(file);
2918
- mkdirSync9(p.controlDir, { recursive: true });
3511
+ mkdirSync10(p.controlDir, { recursive: true });
2919
3512
  await new FsControlChannel(p).append({ actor: "agent", type: LogEventType.AgentMessage, payload: { text } });
2920
3513
  }
2921
3514
  } catch {
@@ -2933,7 +3526,7 @@ async function doRelay(args) {
2933
3526
  let stdin = "";
2934
3527
  if (hook !== "codex-notify") {
2935
3528
  try {
2936
- stdin = readFileSync10(0, "utf8");
3529
+ stdin = readFileSync11(0, "utf8");
2937
3530
  } catch {
2938
3531
  }
2939
3532
  }
@@ -2965,8 +3558,8 @@ function grantClaudePermissions(claudeRoot) {
2965
3558
  const settingsPath = join10(claudeRoot, "settings.json");
2966
3559
  let settings = {};
2967
3560
  try {
2968
- if (existsSync10(settingsPath)) {
2969
- const parsed = JSON.parse(readFileSync10(settingsPath, "utf8"));
3561
+ if (existsSync11(settingsPath)) {
3562
+ const parsed = JSON.parse(readFileSync11(settingsPath, "utf8"));
2970
3563
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
2971
3564
  settings = parsed;
2972
3565
  }
@@ -2999,8 +3592,8 @@ function grantClaudePermissions(claudeRoot) {
2999
3592
  settings.permissions = perms;
3000
3593
  try {
3001
3594
  const tmp = settingsPath + ".tmp";
3002
- writeFileSync9(tmp, JSON.stringify(settings, null, 2) + "\n");
3003
- renameSync2(tmp, settingsPath);
3595
+ writeFileSync10(tmp, JSON.stringify(settings, null, 2) + "\n");
3596
+ renameSync4(tmp, settingsPath);
3004
3597
  } catch {
3005
3598
  return false;
3006
3599
  }
@@ -3045,8 +3638,8 @@ function mergeRelayHooks(settings, entries) {
3045
3638
  }
3046
3639
  function readJsonObject(path) {
3047
3640
  try {
3048
- if (!existsSync10(path)) return {};
3049
- const parsed = JSON.parse(readFileSync10(path, "utf8"));
3641
+ if (!existsSync11(path)) return {};
3642
+ const parsed = JSON.parse(readFileSync11(path, "utf8"));
3050
3643
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
3051
3644
  return parsed;
3052
3645
  } catch {
@@ -3055,10 +3648,10 @@ function readJsonObject(path) {
3055
3648
  }
3056
3649
  function writeJsonAtomic(path, value) {
3057
3650
  try {
3058
- mkdirSync9(dirname10(path), { recursive: true });
3651
+ mkdirSync10(dirname11(path), { recursive: true });
3059
3652
  const tmp = path + ".tmp";
3060
- writeFileSync9(tmp, JSON.stringify(value, null, 2) + "\n");
3061
- renameSync2(tmp, path);
3653
+ writeFileSync10(tmp, JSON.stringify(value, null, 2) + "\n");
3654
+ renameSync4(tmp, path);
3062
3655
  return true;
3063
3656
  } catch {
3064
3657
  return false;
@@ -3123,15 +3716,15 @@ export default function (pi) {
3123
3716
  function installPiRelayExtension(piAgentRoot) {
3124
3717
  const path = join10(piAgentRoot, "extensions", "inplan-relay.ts");
3125
3718
  try {
3126
- if (existsSync10(path)) {
3127
- const cur = readFileSync10(path, "utf8");
3719
+ if (existsSync11(path)) {
3720
+ const cur = readFileSync11(path, "utf8");
3128
3721
  if (cur === PI_RELAY_EXTENSION) return false;
3129
3722
  if (!cur.startsWith(PI_RELAY_MARKER)) return false;
3130
3723
  }
3131
- mkdirSync9(dirname10(path), { recursive: true });
3724
+ mkdirSync10(dirname11(path), { recursive: true });
3132
3725
  const tmp = path + ".tmp";
3133
- writeFileSync9(tmp, PI_RELAY_EXTENSION);
3134
- renameSync2(tmp, path);
3726
+ writeFileSync10(tmp, PI_RELAY_EXTENSION);
3727
+ renameSync4(tmp, path);
3135
3728
  return true;
3136
3729
  } catch {
3137
3730
  return false;
@@ -3151,9 +3744,9 @@ function doInstallSkill(args) {
3151
3744
  const installed = [];
3152
3745
  for (const a of skillTargets()) {
3153
3746
  try {
3154
- if (!existsSync10(a.root)) continue;
3155
- if (!existsSync10(a.target)) {
3156
- mkdirSync9(dirname10(a.target), { recursive: true });
3747
+ if (!existsSync11(a.root)) continue;
3748
+ if (!existsSync11(a.target)) {
3749
+ mkdirSync10(dirname11(a.target), { recursive: true });
3157
3750
  copyFileSync(src, a.target);
3158
3751
  installed.push(a.name);
3159
3752
  process.stderr.write(`inplan: installed the inplan skill into ${a.name} (${a.target}). Set INPLAN_NO_SKILL_INSTALL=1 to skip.
@@ -3206,7 +3799,7 @@ async function doUpload(file, args) {
3206
3799
  process.exit(1);
3207
3800
  }
3208
3801
  const org = orgOf(pick);
3209
- const body = existsSync10(file) ? readFileSync10(file, "utf8") : "";
3802
+ const body = existsSync11(file) ? readFileSync11(file, "utf8") : "";
3210
3803
  const prov = gitProvenance(file);
3211
3804
  const repo = getFlag(args, "repo") ?? prov.repo;
3212
3805
  const path = getFlag(args, "path") ?? prov.path;
@@ -3248,7 +3841,7 @@ async function doUpload(file, args) {
3248
3841
  let finalBody = body;
3249
3842
  if (out0.status === "created") {
3250
3843
  try {
3251
- const migrated = await migrateLocalImages(body, dirname10(file), s.db, pick.org_id, cloudDocId);
3844
+ const migrated = await migrateLocalImages(body, dirname11(file), s.db, pick.org_id, cloudDocId);
3252
3845
  if (migrated.migrated > 0) {
3253
3846
  const { data: updatedRows, error: updateErr } = await s.db.from("documents").update({ body: migrated.body, updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", cloudDocId).eq("body", body).select("id");
3254
3847
  if (updateErr) {
@@ -3261,7 +3854,7 @@ async function doUpload(file, args) {
3261
3854
  "the document changed in the cloud while migrating images (a live session attached first) \u2014 not overwriting it; the local images were not migrated, re-paste them once you're collaborating on this doc in the cloud"
3262
3855
  );
3263
3856
  }
3264
- const onDiskNow = existsSync10(file) ? readFileSync10(file, "utf8") : null;
3857
+ const onDiskNow = existsSync11(file) ? readFileSync11(file, "utf8") : null;
3265
3858
  if (onDiskNow !== null && onDiskNow !== body) {
3266
3859
  finalBody = onDiskNow;
3267
3860
  throw new Error(
@@ -3269,10 +3862,10 @@ async function doUpload(file, args) {
3269
3862
  );
3270
3863
  }
3271
3864
  try {
3272
- writeFileSync9(file, migrated.body);
3865
+ writeFileSync10(file, migrated.body);
3273
3866
  finalBody = migrated.body;
3274
3867
  } catch (e) {
3275
- finalBody = existsSync10(file) ? readFileSync10(file, "utf8") : body;
3868
+ finalBody = existsSync11(file) ? readFileSync11(file, "utf8") : body;
3276
3869
  throw new Error(
3277
3870
  `the cloud copy was updated, but writing it back to the local file failed (${e instanceof Error ? e.message : String(e)}) \u2014 the local file is now stale; open this doc in the editor (or re-run \`inplan wait\`) to pull the migrated body back down`
3278
3871
  );
@@ -3348,7 +3941,7 @@ async function doAssetUpload(file, args) {
3348
3941
  process.exit(1);
3349
3942
  }
3350
3943
  const requestedExt = (getFlag(args, "ext") ?? "png").toLowerCase();
3351
- const bytes = readFileSync10(bytesFile);
3944
+ const bytes = readFileSync11(bytesFile);
3352
3945
  const uploaded = await uploadAssetBytes(s.db, orgId, status.cloudDocId, bytes, requestedExt);
3353
3946
  if (!uploaded) {
3354
3947
  process.stderr.write("inplan asset-upload: upload failed\n");
@@ -3408,7 +4001,7 @@ async function migrateLocalImages(body, docDir, db, orgId, docId) {
3408
4001
  continue;
3409
4002
  }
3410
4003
  const abs = resolve3(docDir, dest);
3411
- if (!existsSync10(abs)) continue;
4004
+ if (!existsSync11(abs)) continue;
3412
4005
  let absReal;
3413
4006
  try {
3414
4007
  absReal = realpathSync(abs);
@@ -3421,7 +4014,7 @@ async function migrateLocalImages(body, docDir, db, orgId, docId) {
3421
4014
  if (!Object.prototype.hasOwnProperty.call(ASSET_MIME_BY_EXT, ext)) continue;
3422
4015
  let bytes;
3423
4016
  try {
3424
- bytes = readFileSync10(abs);
4017
+ bytes = readFileSync11(abs);
3425
4018
  } catch {
3426
4019
  continue;
3427
4020
  }
@@ -3455,8 +4048,8 @@ function routeFor(file, cmd, args) {
3455
4048
  const status = readStatus(p.statusPath);
3456
4049
  if (status.location !== "cloud" || !status.cloudDocId) return { kind: "local" };
3457
4050
  const docId = status.cloudDocId;
3458
- if (cmd === "signal" || cmd === "message" || !existsSync10(file)) return { kind: "cloud", docId };
3459
- const local = readFileSync10(file, "utf8");
4051
+ if (cmd === "signal" || cmd === "message" || !existsSync11(file)) return { kind: "cloud", docId };
4052
+ const local = readFileSync11(file, "utf8");
3460
4053
  const diverged = status.lastSyncedHash !== void 0 && hashBody(local) !== status.lastSyncedHash;
3461
4054
  if (!diverged || hasFlag(args, "use-cloud")) return { kind: "cloud", docId };
3462
4055
  if (hasFlag(args, "continue-locally")) {
@@ -3578,7 +4171,7 @@ async function main() {
3578
4171
  }
3579
4172
  if (cmd === "signal") {
3580
4173
  const p = docPaths(file);
3581
- mkdirSync9(p.controlDir, { recursive: true });
4174
+ mkdirSync10(p.controlDir, { recursive: true });
3582
4175
  const channel = new FsControlChannel(p);
3583
4176
  if (hasFlag(args, "done")) {
3584
4177
  await channel.append({ actor: "agent", type: LogEventType.AgentDoneSuggested });
@@ -3596,13 +4189,13 @@ async function main() {
3596
4189
  process.exit(1);
3597
4190
  }
3598
4191
  const p = docPaths(file);
3599
- mkdirSync9(p.controlDir, { recursive: true });
4192
+ mkdirSync10(p.controlDir, { recursive: true });
3600
4193
  const channel = new FsControlChannel(p);
3601
4194
  await channel.append({ actor: "agent", type: LogEventType.AgentMessage, payload: { text } });
3602
4195
  output({ status: "messaged" });
3603
4196
  return;
3604
4197
  }
3605
- if (cmd !== "open" && !existsSync10(file)) {
4198
+ if (cmd !== "open" && !existsSync11(file)) {
3606
4199
  process.stderr.write(`inplan ${cmd}: file not found: ${file}
3607
4200
  `);
3608
4201
  process.exit(1);
@@ -3628,7 +4221,7 @@ async function main() {
3628
4221
  }
3629
4222
  }
3630
4223
  try {
3631
- const currentText = readFileSync10(file, "utf8");
4224
+ const currentText = readFileSync11(file, "utf8");
3632
4225
  const { text: nextText, comment } = addComment(currentText, {
3633
4226
  text,
3634
4227
  author: agentAuthorFor(model),
@@ -3638,7 +4231,7 @@ async function main() {
3638
4231
  ...question ? { question } : {},
3639
4232
  mayResolve: hasFlag(args, "may-resolve")
3640
4233
  });
3641
- writeFileSync9(file, nextText);
4234
+ writeFileSync10(file, nextText);
3642
4235
  output({ status: "commented", id: comment.id, date: comment.date, author: comment.author });
3643
4236
  } catch (err) {
3644
4237
  if (err instanceof AddCommentError) {
@@ -3653,7 +4246,7 @@ async function main() {
3653
4246
  if (cmd === "open") {
3654
4247
  ensureDocFile(file);
3655
4248
  const p = docPaths(file);
3656
- mkdirSync9(p.controlDir, { recursive: true });
4249
+ mkdirSync10(p.controlDir, { recursive: true });
3657
4250
  const st = readStatus(p.statusPath);
3658
4251
  if (st.location !== "cloud") writeStatus(p.statusPath, { ...st, location: "local", originalPath: file });
3659
4252
  const existing = runningEditorPid(p.logPath);
@@ -3709,6 +4302,7 @@ export {
3709
4302
  EXIT_PLUGIN_UNAVAILABLE,
3710
4303
  EXIT_UPGRADE_REQUIRED,
3711
4304
  EXIT_WAIT_FAILED,
4305
+ acceptanceFrom,
3712
4306
  activeDocForCwd,
3713
4307
  canInteractiveLogin,
3714
4308
  doAssetUpload,