inplan 0.1.31 → 0.2.1

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-JVBKYN5I.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
  }
@@ -941,22 +1156,48 @@ async function reuseCached(auth, skewS = ACCESS_SKEW_S) {
941
1156
  return error || !data.session ? null : { db, session: data.session };
942
1157
  }
943
1158
  var LIVE_REFRESH_SKEW_S = 10 * 60;
944
- async function authedSession(skewS = ACCESS_SKEW_S) {
1159
+ var REJECTING_STATUSES = /* @__PURE__ */ new Set([400, 401, 403]);
1160
+ function isSpentRefreshToken(error) {
1161
+ const e = error ?? {};
1162
+ if (e.code === "refresh_token_already_used") return true;
1163
+ return typeof e.message === "string" && /already used/i.test(e.message);
1164
+ }
1165
+ function authFailureKind(error) {
1166
+ const status = error?.status;
1167
+ const rejected = typeof status === "number" && REJECTING_STATUSES.has(status);
1168
+ if (!rejected) return { reason: "inconclusive", cause: "unspecified" };
1169
+ return { reason: "rejected", cause: isSpentRefreshToken(error) ? "refresh-token-spent" : "unspecified" };
1170
+ }
1171
+ async function authedSession(skewS = ACCESS_SKEW_S, onFailure) {
945
1172
  const cached = loadAuth();
946
- if (!cached) return null;
1173
+ if (!cached) {
1174
+ onFailure?.("inconclusive");
1175
+ return null;
1176
+ }
947
1177
  const reused = await reuseCached(cached, skewS);
948
1178
  if (reused) return reused;
949
1179
  const locked = await withAuthLock(async ({ stillMine }) => {
950
1180
  const auth = loadAuth();
951
- if (!auth) return null;
1181
+ if (!auth) {
1182
+ onFailure?.("inconclusive");
1183
+ return null;
1184
+ }
952
1185
  const fresh = await reuseCached(auth, skewS);
953
1186
  if (fresh) return fresh;
954
- if (!stillMine()) return null;
1187
+ if (!stillMine()) {
1188
+ onFailure?.("inconclusive");
1189
+ return null;
1190
+ }
955
1191
  const db = newClient(auth);
956
1192
  const { data, error } = await db.auth.refreshSession({ refresh_token: auth.refreshToken });
957
- if (error || !data.session) return null;
1193
+ if (error || !data.session) {
1194
+ const graded = error ? authFailureKind(error) : { reason: "inconclusive", cause: "unspecified" };
1195
+ onFailure?.(graded.reason, graded.cause);
1196
+ return null;
1197
+ }
958
1198
  if (!data.session.refresh_token) {
959
1199
  process.stderr.write("inplan: refresh returned no new refresh token; keeping the stored one and retrying rather than persisting a possibly-spent token\n");
1200
+ onFailure?.("inconclusive");
960
1201
  return null;
961
1202
  }
962
1203
  saveAuth({
@@ -969,7 +1210,18 @@ async function authedSession(skewS = ACCESS_SKEW_S) {
969
1210
  return { db, session: data.session };
970
1211
  });
971
1212
  if (locked.acquired) return locked.value;
972
- return reuseCached(loadAuth() ?? cached, 0);
1213
+ const contended = await reuseCached(loadAuth() ?? cached, 0);
1214
+ if (!contended) onFailure?.("inconclusive");
1215
+ return contended;
1216
+ }
1217
+ async function verifyCachedAccessToken() {
1218
+ const auth = loadAuth();
1219
+ if (!auth) return "absent";
1220
+ const bound = await reuseCached(auth);
1221
+ if (!bound) return "absent";
1222
+ const { data, error } = await bound.db.auth.getUser(auth.accessToken);
1223
+ if (!error && data?.user) return "ok";
1224
+ return error ? authFailureKind(error).reason : "inconclusive";
973
1225
  }
974
1226
  async function currentUser() {
975
1227
  const s = await authedSession();
@@ -982,13 +1234,44 @@ async function currentUser() {
982
1234
  ...name ? { name } : {}
983
1235
  };
984
1236
  }
1237
+ var cachedClientId = null;
1238
+ function machineClientId() {
1239
+ if (cachedClientId) return cachedClientId;
1240
+ const home = process.env.INPLAN_HOME || join4(homedir3(), ".inplan");
1241
+ const p = join4(home, "proposer-client-id");
1242
+ try {
1243
+ const v2 = readFileSync4(p, "utf8").trim();
1244
+ if (v2) return cachedClientId = v2;
1245
+ } catch {
1246
+ }
1247
+ const v = mintProposalId();
1248
+ try {
1249
+ mkdirSync3(dirname5(p), { recursive: true });
1250
+ const tmp = `${p}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
1251
+ writeFileSync3(tmp, v);
1252
+ try {
1253
+ linkSync(tmp, p);
1254
+ } finally {
1255
+ rmSync2(tmp, { force: true });
1256
+ }
1257
+ } catch {
1258
+ try {
1259
+ const w = readFileSync4(p, "utf8").trim();
1260
+ if (w) return cachedClientId = w;
1261
+ } catch {
1262
+ }
1263
+ }
1264
+ return cachedClientId = v;
1265
+ }
985
1266
  async function remoteBackend(docId, consumerId = "cli-agent", skewS) {
986
1267
  const s = await authedSession(skewS);
987
1268
  if (!s) return null;
988
1269
  return {
989
1270
  db: s.db,
990
1271
  channel: new SupabaseControlChannel(s.db, docId, consumerId),
991
- store: new SupabaseDocumentStore(s.db, docId),
1272
+ // The CLI proposes as the signed-in USER on this MACHINE: RLS scopes user-kind rows, and the
1273
+ // stable client id keeps two of the same human's machines from superseding each other.
1274
+ store: new SupabaseDocumentStore(s.db, docId, { kind: "user", userId: s.session.user.id, clientId: machineClientId() }),
992
1275
  token: s.session.access_token
993
1276
  };
994
1277
  }
@@ -1048,9 +1331,11 @@ function liveRemoteBackend(docId, consumerId = "cli-agent") {
1048
1331
  saveDoc: async (c) => (await need()).store.saveDoc(c),
1049
1332
  getCanonical: async () => (await need()).store.getCanonical(),
1050
1333
  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(),
1334
+ createProposal: async (i) => (await need()).store.createProposal(i),
1335
+ myPendingProposal: async () => (await need()).store.myPendingProposal(),
1336
+ getProposal: async (id) => (await need()).store.getProposal(id),
1337
+ withdrawProposal: async (id) => (await need()).store.withdrawProposal(id),
1338
+ decideProposal: async (id, st) => (await need()).store.decideProposal(id, st),
1054
1339
  backup: async (c, m) => (await need()).store.backup(c, m)
1055
1340
  };
1056
1341
  return { channel, store, tokenNow: () => inner?.token ?? null };
@@ -1059,7 +1344,7 @@ function liveRemoteBackend(docId, consumerId = "cli-agent") {
1059
1344
  // src/cliLogin.ts
1060
1345
  import { spawn } from "child_process";
1061
1346
  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";
1347
+ 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
1348
  import { homedir as homedir5 } from "os";
1064
1349
  import { dirname as dirname6, join as join7 } from "path";
1065
1350
 
@@ -1141,7 +1426,7 @@ async function withSidecarLock(fn) {
1141
1426
  } catch (e) {
1142
1427
  if (e.code !== "EEXIST") throw e;
1143
1428
  try {
1144
- if (Date.now() - statSync3(lock).mtimeMs > LOCK_STALE_MS2) rmdirSync(lock);
1429
+ if (Date.now() - statSync4(lock).mtimeMs > LOCK_STALE_MS2) rmdirSync(lock);
1145
1430
  } catch {
1146
1431
  }
1147
1432
  if (Date.now() > deadline) throw new Error("could not acquire the login lock \u2014 another inplan process is holding it");
@@ -1228,19 +1513,36 @@ async function createLoginSession(opts = {}) {
1228
1513
  }
1229
1514
  var LoginSessionExpiredError = class extends Error {
1230
1515
  };
1516
+ var BrowserDidNotOpenError = class extends Error {
1517
+ };
1518
+ function pollRequestBudgetMs(nowMs, deadline, openAckDeadline) {
1519
+ const budgets = [REQUEST_TIMEOUT_MS, deadline - nowMs];
1520
+ if (openAckDeadline !== void 0) budgets.push(openAckDeadline - nowMs);
1521
+ return Math.max(1, Math.min(...budgets));
1522
+ }
1523
+ function launchAwareSignal(budgetMs, launchSignal) {
1524
+ const budget = AbortSignal.timeout(budgetMs);
1525
+ return launchSignal ? AbortSignal.any([budget, launchSignal]) : budget;
1526
+ }
1231
1527
  async function pollLoginSession(pending, opts = {}) {
1232
1528
  const fetchImpl = opts.fetchImpl ?? fetch;
1233
1529
  const now = opts.now ?? Date.now;
1234
1530
  const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
1235
1531
  const deadline = now() + (opts.timeoutMs ?? DEFAULT_TIMEOUT_MS);
1236
1532
  const nudgeAt = now() + NUDGE_MS;
1533
+ const openAckDeadline = opts.openAckMs === void 0 ? void 0 : now() + opts.openAckMs;
1237
1534
  let nudged = false;
1238
1535
  let sawOpened = false;
1536
+ const launchDead = () => !sawOpened && Boolean(opts.launchSignal?.aborted);
1239
1537
  while (true) {
1240
1538
  if (!nudged && !sawOpened && now() >= nudgeAt) {
1241
1539
  nudged = true;
1242
1540
  opts.onNudge?.();
1243
1541
  }
1542
+ if (launchDead()) throw new BrowserDidNotOpenError("the browser could not be launched");
1543
+ if (openAckDeadline !== void 0 && !sawOpened && now() >= openAckDeadline) {
1544
+ throw new BrowserDidNotOpenError("the browser did not open");
1545
+ }
1244
1546
  if (now() >= pending.expiresAt) {
1245
1547
  await clearPendingLoginFor(pending.sessionId);
1246
1548
  throw new LoginSessionExpiredError("the sign-in link expired \u2014 run the command again for a fresh one");
@@ -1253,11 +1555,26 @@ async function pollLoginSession(pending, opts = {}) {
1253
1555
  // The poll credential rides a header (never a URL, so never an access log) — see
1254
1556
  // PendingLogin.pollToken: the session id alone must not read or destroy the handoff.
1255
1557
  headers: { "x-inplan-poll-token": pending.pollToken },
1256
- // Capped to the REMAINING deadline: an in-flight request must not let the foreground
1257
- // wait overrun its budget by a whole request-timeout.
1258
- signal: AbortSignal.timeout(Math.max(1, Math.min(REQUEST_TIMEOUT_MS, deadline - now())))
1558
+ // Capped to the REMAINING deadline — and to the openAck deadline when one is set: an
1559
+ // in-flight request must not let either budget overrun by a whole request-timeout. Without
1560
+ // the second cap a stalled poll could burn the full REQUEST_TIMEOUT_MS (plus a POLL_MS
1561
+ // sleep) before the loop ever re-checks a 6-second ack window.
1562
+ // Cut the request short on a launch failure too, not just on the budget: the opener reports
1563
+ // asynchronously, so without this a report landing mid-request would sit behind a stalled
1564
+ // connection for the whole budget before the loop could act on it.
1565
+ // BOTH extra bounds fall away once the page has acked. The ack window has done its job — and
1566
+ // an AbortSignal stays aborted forever, so a launch signal that has already fired would make
1567
+ // AbortSignal.any born-aborted for every remaining request: each one dies before it leaves,
1568
+ // `launchDead()` rightly declines to throw (the page acked), so the loop sleeps and retries
1569
+ // into the same instant abort until the foreground deadline. A login that was about to
1570
+ // complete would end as "login timed out" instead.
1571
+ signal: launchAwareSignal(
1572
+ pollRequestBudgetMs(now(), deadline, sawOpened ? void 0 : openAckDeadline),
1573
+ sawOpened ? void 0 : opts.launchSignal
1574
+ )
1259
1575
  });
1260
1576
  } catch {
1577
+ if (launchDead()) throw new BrowserDidNotOpenError("the browser could not be launched");
1261
1578
  await sleep(POLL_MS);
1262
1579
  continue;
1263
1580
  }
@@ -1295,15 +1612,24 @@ async function rendezvousLogin(opts = {}) {
1295
1612
  (opts.open ?? openInBrowser)(pending.url);
1296
1613
  return pollLoginSession(pending, opts);
1297
1614
  }
1298
- function openInBrowser(url) {
1615
+ function openInBrowser(url, onLaunchFailure) {
1299
1616
  const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
1300
1617
  const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
1618
+ let reported = false;
1619
+ const failed = (kind) => {
1620
+ if (reported) return;
1621
+ reported = true;
1622
+ onLaunchFailure?.(kind);
1623
+ };
1301
1624
  try {
1302
1625
  const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
1303
- child.on("error", () => {
1626
+ child.on("error", () => failed("no-opener"));
1627
+ child.on("exit", (code) => {
1628
+ if (code !== 0) failed("opener-declined");
1304
1629
  });
1305
1630
  child.unref();
1306
1631
  } catch {
1632
+ failed("no-opener");
1307
1633
  }
1308
1634
  }
1309
1635
  async function unsealHandoff(privateKeyPkcs8, sealed) {
@@ -1325,7 +1651,14 @@ async function unsealHandoff(privateKeyPkcs8, sealed) {
1325
1651
  if (typeof parsed.url !== "string" || typeof parsed.anon !== "string" || typeof parsed.refresh !== "string") {
1326
1652
  throw new Error("sign-in handoff was malformed");
1327
1653
  }
1328
- return { url: parsed.url, anonKey: parsed.anon, refreshToken: parsed.refresh, ...parsed.email ? { email: parsed.email } : {} };
1654
+ const cached = typeof parsed.access === "string" && typeof parsed.expiresAt === "number" ? { accessToken: parsed.access, expiresAt: parsed.expiresAt } : {};
1655
+ return {
1656
+ url: parsed.url,
1657
+ anonKey: parsed.anon,
1658
+ refreshToken: parsed.refresh,
1659
+ ...parsed.email ? { email: parsed.email } : {},
1660
+ ...cached
1661
+ };
1329
1662
  }
1330
1663
 
1331
1664
  // src/cliProfile.ts
@@ -1481,6 +1814,191 @@ function runningEditorPid(logPath) {
1481
1814
  return pid !== null && isProcessAlive2(pid) ? pid : null;
1482
1815
  }
1483
1816
 
1817
+ // src/remoteDocState.ts
1818
+ 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";
1819
+ import { dirname as dirname8 } from "path";
1820
+ var utf8Bytes = (text) => Buffer.byteLength(text, "utf8");
1821
+ function isDecidedProposalCorpse(latest, currentContent) {
1822
+ if (!latest || latest.state === "pending_review" || currentContent === null) return false;
1823
+ return hashBody(currentContent) === latest.hash;
1824
+ }
1825
+ var RemoteDocState = class {
1826
+ constructor(workFile, docId) {
1827
+ this.workFile = workFile;
1828
+ this.docId = docId;
1829
+ this.pendingPath = `${workFile}.pending`;
1830
+ this.hashPath = `${workFile}.synced`;
1831
+ this.recordPath = `${workFile}.proposed.json`;
1832
+ this.textPath = `${workFile}.proposed.md`;
1833
+ this.historyPath = `${workFile}.proposals.jsonl`;
1834
+ }
1835
+ workFile;
1836
+ docId;
1837
+ /** Marker: a local fallback edit awaits a hub push (public — liveSync's replay decision reads it). */
1838
+ pendingPath;
1839
+ hashPath;
1840
+ recordPath;
1841
+ textPath;
1842
+ historyPath;
1843
+ ensureDir() {
1844
+ mkdirSync8(dirname8(this.workFile), { recursive: true });
1845
+ }
1846
+ // ── Working copy + canonical-sync hash (legacy formats, unchanged) ────────────────────────────
1847
+ readWorkFile() {
1848
+ return existsSync10(this.workFile) ? readFileSync9(this.workFile, "utf8") : null;
1849
+ }
1850
+ writeWorkFile(content) {
1851
+ writeFileSync8(this.workFile, content);
1852
+ }
1853
+ /** Record that the working copy now equals `content` (our last write/sync). */
1854
+ recordSynced(content) {
1855
+ writeFileSync8(this.hashPath, hashBody(content));
1856
+ }
1857
+ /** Assemble the start-of-turn hydration decision's input (see liveSync.shouldHydrateWorkFile). */
1858
+ hydrateInput() {
1859
+ const current = this.readWorkFile();
1860
+ return {
1861
+ exists: current !== null,
1862
+ pending: this.replayPending(),
1863
+ currentHash: current !== null ? hashBody(current) : null,
1864
+ syncedHash: existsSync10(this.hashPath) ? readFileSync9(this.hashPath, "utf8") : null
1865
+ };
1866
+ }
1867
+ // ── Hub-push replay marker (legacy `.pending`, unchanged) ─────────────────────────────────────
1868
+ replayPending() {
1869
+ return existsSync10(this.pendingPath);
1870
+ }
1871
+ markReplayPending() {
1872
+ writeFileSync8(this.pendingPath, "1");
1873
+ }
1874
+ clearReplayPending() {
1875
+ if (existsSync10(this.pendingPath)) rmSync3(this.pendingPath);
1876
+ }
1877
+ // ── Proposal record: the durable "did my edit land?" signal (#88) ─────────────────────────────
1878
+ /**
1879
+ * Park a proposal: publish the record + its exact text as ONE atomic rename, then refresh the
1880
+ * derived `.proposed.md` copy (best-effort — the JSON is authoritative). A still-pending
1881
+ * previous record about different content is finalized into the history as `superseded` first,
1882
+ * so no record is ever silently lost; re-parking identical content keeps the existing pending
1883
+ * identity (same proposal, re-pushed) instead of minting a new one.
1884
+ */
1885
+ parkProposal(text, at = /* @__PURE__ */ new Date(), id) {
1886
+ const prior = this.pendingProposal();
1887
+ const hash = hashBody(text);
1888
+ if (prior && id !== void 0 && id === prior.id && prior.hash !== hash) {
1889
+ const updated = { ...prior, hash, bytes: utf8Bytes(text) };
1890
+ this.publish({ ...updated, text });
1891
+ return updated;
1892
+ }
1893
+ if (prior && prior.hash === hash && (id === void 0 || id === prior.id)) {
1894
+ this.writeDerivedText(text);
1895
+ return prior;
1896
+ }
1897
+ if (prior) this.finalize(prior, "superseded");
1898
+ const record = {
1899
+ // The id is the CLOUD row's id when the caller passes one (proposals v1 — one identity end
1900
+ // to end); minted locally only for offline/desktop parks.
1901
+ id: id ?? `${at.getTime().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
1902
+ docId: this.docId,
1903
+ hash,
1904
+ bytes: utf8Bytes(text),
1905
+ at: at.toISOString(),
1906
+ state: "pending_review"
1907
+ };
1908
+ this.publish({ ...record, text });
1909
+ return record;
1910
+ }
1911
+ /** The latest record regardless of state, or null — missing, unreadable, or failing the full
1912
+ * shape check (wrong doc, non-numeric bytes, unparseable park time, unknown state). A partial
1913
+ * record must read as absent, or it could be finalized with missing metadata. */
1914
+ latestProposal() {
1915
+ const stored = this.readStored();
1916
+ if (!stored) return null;
1917
+ const { text: _text, ...record } = stored;
1918
+ return record;
1919
+ }
1920
+ /** The latest record only while it awaits the human's decision. */
1921
+ pendingProposal() {
1922
+ const record = this.latestProposal();
1923
+ return record?.state === "pending_review" ? record : null;
1924
+ }
1925
+ /** The latest proposal's exact pushed text (recovery path after the working-copy re-sync). */
1926
+ proposedText() {
1927
+ return this.readStored()?.text ?? null;
1928
+ }
1929
+ /**
1930
+ * Finalize the pending record with the human's decision: append it to the never-pruned history
1931
+ * log FIRST (metadata only — an accepted text's fate is canonical history's job), then
1932
+ * republish the record. A crash between the writes leaves the record pending, so the next
1933
+ * resolution retries — and the retry is idempotent because the history tail already carries
1934
+ * this park's unique id.
1935
+ */
1936
+ resolveProposal(outcome) {
1937
+ const pending = this.pendingProposal();
1938
+ if (!pending) return null;
1939
+ return this.finalize(pending, outcome);
1940
+ }
1941
+ finalize(record, outcome) {
1942
+ const finalized = { ...record, state: outcome };
1943
+ const tail2 = this.historyTail();
1944
+ if (!tail2 || tail2.id !== finalized.id || tail2.state !== finalized.state) appendFileSync2(this.historyPath, `${JSON.stringify(finalized)}
1945
+ `);
1946
+ const stored = this.readStored();
1947
+ this.publish({ ...finalized, text: stored?.id === finalized.id ? stored.text : "" });
1948
+ return finalized;
1949
+ }
1950
+ // ── Persistence primitives ────────────────────────────────────────────────────────────────────
1951
+ /** Atomic publish: the record + text land as one rename, then the derived .md refreshes. */
1952
+ publish(stored) {
1953
+ const tmp = `${this.recordPath}.tmp`;
1954
+ writeFileSync8(tmp, JSON.stringify(stored, null, 2));
1955
+ renameSync3(tmp, this.recordPath);
1956
+ this.writeDerivedText(stored.text);
1957
+ }
1958
+ writeDerivedText(text) {
1959
+ try {
1960
+ writeFileSync8(this.textPath, text);
1961
+ } catch {
1962
+ }
1963
+ }
1964
+ readStored() {
1965
+ if (!existsSync10(this.recordPath)) return null;
1966
+ try {
1967
+ const p = JSON.parse(readFileSync9(this.recordPath, "utf8"));
1968
+ 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";
1969
+ 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;
1970
+ if (p.state === "pending_review" && (hashBody(p.text) !== p.hash || utf8Bytes(p.text) !== p.bytes)) return null;
1971
+ return p;
1972
+ } catch {
1973
+ return null;
1974
+ }
1975
+ }
1976
+ /** The history log's last finalized record, or null (absent/unreadable/invalid). Reads only the
1977
+ * file's tail — the log is never pruned, so a whole-file read would grow without bound. */
1978
+ historyTail() {
1979
+ if (!existsSync10(this.historyPath)) return null;
1980
+ try {
1981
+ const fd = openSync2(this.historyPath, "r");
1982
+ let chunk;
1983
+ try {
1984
+ const size = fstatSync(fd).size;
1985
+ const span = Math.min(size, 16384);
1986
+ const buf = Buffer.alloc(span);
1987
+ readSync2(fd, buf, 0, span, size - span);
1988
+ chunk = buf.toString("utf8");
1989
+ } finally {
1990
+ closeSync2(fd);
1991
+ }
1992
+ const lines = chunk.trim().split("\n");
1993
+ const last = JSON.parse(lines[lines.length - 1]);
1994
+ if (typeof last.id !== "string" || last.docId !== this.docId || typeof last.hash !== "string" || typeof last.state !== "string") return null;
1995
+ return last;
1996
+ } catch {
1997
+ return null;
1998
+ }
1999
+ }
2000
+ };
2001
+
1484
2002
  // src/applyEdit.ts
1485
2003
  async function applyGatedEdit(store, channel, ev, ctx) {
1486
2004
  const { current, canonicalText, quarantine, gate } = ctx;
@@ -1489,21 +2007,57 @@ async function applyGatedEdit(store, channel, ev, ctx) {
1489
2007
  else {
1490
2008
  await store.saveDoc(ev.acceptedText);
1491
2009
  await store.setCanonical(ev.acceptedText);
1492
- await store.clearProposed();
2010
+ await withdrawOwnPending(store);
1493
2011
  }
1494
2012
  await channel.append({ actor: "agent", type: LogEventType.DocumentEdited, payload: { removed: ev.removedIds } });
1495
2013
  } 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 } });
2014
+ let proposalId;
2015
+ try {
2016
+ ({ id: proposalId } = await store.createProposal({ content: current, baseHash: hashBody(canonicalText), baseContent: canonicalText }));
2017
+ } catch {
2018
+ return { proposed: false, parkFailed: true };
2019
+ }
2020
+ if (!gate && !revertWouldWipe(canonicalText, current)) {
2021
+ try {
2022
+ await store.saveDoc(canonicalText);
2023
+ } catch {
2024
+ }
2025
+ }
2026
+ try {
2027
+ await channel.append({
2028
+ actor: "agent",
2029
+ type: LogEventType.AgentRevisionProposed,
2030
+ // proposal_id names WHICH proposal this event parked — the row/record id, the same one
2031
+ // the wait output carries. bytes/hash stay as human-auditable descriptors of the text.
2032
+ payload: { bytes: utf8Bytes(current), hash: hashBody(current), proposal_id: proposalId }
2033
+ });
2034
+ } catch {
2035
+ return { proposed: true, proposalId, eventLogged: false };
2036
+ }
2037
+ return { proposed: true, proposalId };
1499
2038
  } else if (ev.changed) {
1500
2039
  if (gate) await gate.applyRevision(current);
1501
2040
  else {
1502
2041
  await store.setCanonical(current);
1503
- await store.clearProposed();
2042
+ await withdrawOwnPending(store);
1504
2043
  }
1505
- await channel.append({ actor: "agent", type: LogEventType.DocumentEdited, payload: { bytes: current.length } });
2044
+ await channel.append({ actor: "agent", type: LogEventType.DocumentEdited, payload: { bytes: utf8Bytes(current) } });
1506
2045
  }
2046
+ return { proposed: false };
2047
+ }
2048
+ function revertWouldWipe(canonicalText, current) {
2049
+ const blank = (text) => {
2050
+ try {
2051
+ return parse(text).body.trim() === "";
2052
+ } catch {
2053
+ return text.trim() === "";
2054
+ }
2055
+ };
2056
+ return blank(canonicalText) && !blank(current);
2057
+ }
2058
+ async function withdrawOwnPending(store) {
2059
+ const mine = await store.myPendingProposal();
2060
+ if (mine) await store.withdrawProposal(mine.id);
1507
2061
  }
1508
2062
 
1509
2063
  // src/gate.ts
@@ -1920,19 +2474,19 @@ function waitForActions(opts) {
1920
2474
  }
1921
2475
 
1922
2476
  // src/version.ts
1923
- import { readFileSync as readFileSync9 } from "fs";
1924
- import { dirname as dirname8, join as join9 } from "path";
2477
+ import { readFileSync as readFileSync10 } from "fs";
2478
+ import { dirname as dirname9, join as join9 } from "path";
1925
2479
  import { fileURLToPath } from "url";
1926
2480
  function versionFromDir(moduleDir) {
1927
2481
  try {
1928
- const pkg = JSON.parse(readFileSync9(join9(moduleDir, "..", "package.json"), "utf8"));
2482
+ const pkg = JSON.parse(readFileSync10(join9(moduleDir, "..", "package.json"), "utf8"));
1929
2483
  return typeof pkg.version === "string" ? pkg.version : "0.0.0";
1930
2484
  } catch {
1931
2485
  return "0.0.0";
1932
2486
  }
1933
2487
  }
1934
2488
  function versionFromModule(moduleUrl) {
1935
- return versionFromDir(dirname8(fileURLToPath(moduleUrl)));
2489
+ return versionFromDir(dirname9(fileURLToPath(moduleUrl)));
1936
2490
  }
1937
2491
 
1938
2492
  // src/relayActivity.ts
@@ -1953,12 +2507,12 @@ function toolActivityText(toolName, toolInput) {
1953
2507
  }
1954
2508
 
1955
2509
  // src/ensureDoc.ts
1956
- import { mkdirSync as mkdirSync8, writeFileSync as writeFileSync8 } from "fs";
1957
- import { dirname as dirname9 } from "path";
2510
+ import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync9 } from "fs";
2511
+ import { dirname as dirname10 } from "path";
1958
2512
  function ensureDocFile(file) {
1959
- mkdirSync8(dirname9(file), { recursive: true });
2513
+ mkdirSync9(dirname10(file), { recursive: true });
1960
2514
  try {
1961
- writeFileSync8(file, "", { flag: "wx" });
2515
+ writeFileSync9(file, "", { flag: "wx" });
1962
2516
  return true;
1963
2517
  } catch (err) {
1964
2518
  if (err.code === "EEXIST") return false;
@@ -2031,13 +2585,13 @@ function electronDistRel(platform) {
2031
2585
  }
2032
2586
  function electronBinaryFromDisk(reqUrl) {
2033
2587
  try {
2034
- const pkgDir = dirname10(createRequire(reqUrl).resolve("electron/package.json"));
2588
+ const pkgDir = dirname11(createRequire(reqUrl).resolve("electron/package.json"));
2035
2589
  const rel = electronDistRel(process.platform);
2036
2590
  const bin = join10(pkgDir, "dist", rel);
2037
- if (!existsSync10(bin)) return null;
2591
+ if (!existsSync11(bin)) return null;
2038
2592
  try {
2039
2593
  const pathFile = join10(pkgDir, "path.txt");
2040
- if (!existsSync10(pathFile)) writeFileSync9(pathFile, rel);
2594
+ if (!existsSync11(pathFile)) writeFileSync10(pathFile, rel);
2041
2595
  } catch {
2042
2596
  }
2043
2597
  return bin;
@@ -2057,8 +2611,8 @@ function cachedElectronZip(version, platform, arch) {
2057
2611
  let best = null;
2058
2612
  for (const sub of readdirSync2(root)) {
2059
2613
  const f = join10(root, sub, want);
2060
- if (!existsSync10(f)) continue;
2061
- const mtime = statSync4(f).mtimeMs;
2614
+ if (!existsSync11(f)) continue;
2615
+ const mtime = statSync5(f).mtimeMs;
2062
2616
  if (!best || mtime > best.mtime) best = { file: f, mtime };
2063
2617
  }
2064
2618
  return best?.file ?? null;
@@ -2077,17 +2631,17 @@ function expandArchiveWindows(zipPath, destDir) {
2077
2631
  function autoInstallElectron(reqUrl) {
2078
2632
  if (process.env.INPLAN_NO_ELECTRON_DOWNLOAD === "1") return false;
2079
2633
  try {
2080
- const pkgDir = dirname10(createRequire(reqUrl).resolve("electron/package.json"));
2634
+ const pkgDir = dirname11(createRequire(reqUrl).resolve("electron/package.json"));
2081
2635
  const installJs = join10(pkgDir, "install.js");
2082
- if (!existsSync10(installJs)) return false;
2636
+ if (!existsSync11(installJs)) return false;
2083
2637
  process.stderr.write("[inplan] editor runtime missing \u2014 retrying the download \u2026\n");
2084
2638
  execFileSync2(process.execPath, [installJs], { cwd: pkgDir, stdio: "inherit", env: process.env });
2085
2639
  if (electronBinaryFromDisk(reqUrl) !== null) return true;
2086
2640
  if (process.platform === "win32") {
2087
- const { version } = JSON.parse(readFileSync10(join10(pkgDir, "package.json"), "utf8"));
2641
+ const { version } = JSON.parse(readFileSync11(join10(pkgDir, "package.json"), "utf8"));
2088
2642
  const zip = cachedElectronZip(version, "win32", process.env.npm_config_arch || process.arch);
2089
2643
  if (zip && expandArchiveWindows(zip, join10(pkgDir, "dist"))) {
2090
- writeFileSync9(join10(pkgDir, "path.txt"), "electron.exe");
2644
+ writeFileSync10(join10(pkgDir, "path.txt"), "electron.exe");
2091
2645
  }
2092
2646
  }
2093
2647
  return electronBinaryFromDisk(reqUrl) !== null;
@@ -2096,12 +2650,12 @@ function autoInstallElectron(reqUrl) {
2096
2650
  }
2097
2651
  }
2098
2652
  function resolveBundledApp() {
2099
- const here = dirname10(fileURLToPath2(import.meta.url));
2653
+ const here = dirname11(fileURLToPath2(import.meta.url));
2100
2654
  const appMain = join10(here, "..", "app", "main", "index.cjs");
2101
- if (!existsSync10(appMain)) return { appMain: null };
2655
+ if (!existsSync11(appMain)) return { appMain: null };
2102
2656
  try {
2103
2657
  const electron = createRequire(import.meta.url)("electron");
2104
- if (typeof electron === "string" && electron && existsSync10(electron)) return { electron, appMain };
2658
+ if (typeof electron === "string" && electron && existsSync11(electron)) return { electron, appMain };
2105
2659
  } catch {
2106
2660
  }
2107
2661
  const onDisk = electronBinaryFromDisk(import.meta.url);
@@ -2136,7 +2690,7 @@ function spawnApp(file) {
2136
2690
  process.stderr.write("[inplan] no bundled editor (running from source?) \u2014 set INPLAN_APP_CMD to your editor; running headless\n");
2137
2691
  } else {
2138
2692
  trackCli("editor_launch_failed", telemetryOn, { reason: "electron_unavailable" });
2139
- const root = resolve3(dirname10(bundled.appMain), "..", "..");
2693
+ const root = resolve3(dirname11(bundled.appMain), "..", "..");
2140
2694
  process.stderr.write(
2141
2695
  `[inplan] the bundled editor's Electron runtime is unavailable: ${bundled.error}
2142
2696
  \u2192 re-download the binary: npm rebuild electron --prefix "${root}"
@@ -2167,14 +2721,20 @@ function modeFrom(entries) {
2167
2721
  return { cadence: "turn", wake: "turn-end", locksEditor: true };
2168
2722
  }
2169
2723
  function acceptanceFrom(entries) {
2170
- return settingsFromEntries(entries).acceptance === "auto" ? "auto" : "review";
2724
+ for (let i = entries.length - 1; i >= 0; i--) {
2725
+ const e = entries[i];
2726
+ if (e.type !== LogEventType.ModeChanged && e.type !== LogEventType.SettingsChanged) continue;
2727
+ const a = e.payload?.acceptance;
2728
+ if (a === "auto" || a === "review") return a;
2729
+ }
2730
+ return settingsFromEntries([]).acceptance === "auto" ? "auto" : "review";
2171
2731
  }
2172
2732
  function maxSeqFrom(entries) {
2173
2733
  return entries.length ? entries[entries.length - 1].seq : 0;
2174
2734
  }
2175
2735
  function fsBackend(file) {
2176
2736
  const p = docPaths(file);
2177
- mkdirSync9(p.controlDir, { recursive: true });
2737
+ mkdirSync10(p.controlDir, { recursive: true });
2178
2738
  return {
2179
2739
  channel: new FsControlChannel(p),
2180
2740
  store: new FsDocumentStore(p),
@@ -2184,7 +2744,7 @@ function fsBackend(file) {
2184
2744
  }
2185
2745
  function logWaitExit(p, reason) {
2186
2746
  try {
2187
- appendFileSync2(p.waitDebugPath, `${(/* @__PURE__ */ new Date()).toISOString()} pid=${process.pid} ${reason}
2747
+ appendFileSync3(p.waitDebugPath, `${(/* @__PURE__ */ new Date()).toISOString()} pid=${process.pid} ${reason}
2188
2748
  `);
2189
2749
  } catch {
2190
2750
  }
@@ -2229,10 +2789,34 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
2229
2789
  }
2230
2790
  const acceptance = acceptanceFrom(history);
2231
2791
  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 });
2792
+ const applied = await applyGatedEdit(store, channel, ev, { current, canonicalText, quarantine, gate: usePlugin ? gate : null });
2793
+ if (applied.proposed) {
2794
+ process.stderr.write(
2795
+ 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"
2796
+ );
2797
+ }
2798
+ if (applied.parkFailed) {
2799
+ 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");
2800
+ }
2801
+ const parkFailedId = applied.parkFailed ? backend.localPendingProposalId?.() : void 0;
2802
+ 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) } } : {};
2803
+ try {
2804
+ await channel.append({ actor: "agent", type: LogEventType.AgentRevised });
2805
+ } catch {
2806
+ 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");
2807
+ }
2234
2808
  const lockToken = `${process.pid}-${Date.now()}`;
2235
- await channel.claimLock(lockToken);
2809
+ try {
2810
+ await channel.claimLock(lockToken);
2811
+ } catch (e) {
2812
+ backend.logExit("claim_lock_failed");
2813
+ process.stderr.write(`inplan: could not claim the wait lock (${String(e)}).
2814
+ If your session expired, run \`inplan login\` and re-attach.
2815
+ `);
2816
+ output({ status: "wait_failed", message: `could not claim the wait lock: ${String(e)}`, ...proposalOut });
2817
+ exitAfterFlush(EXIT_WAIT_FAILED);
2818
+ return "exiting";
2819
+ }
2236
2820
  for (const sig of ["SIGTERM", "SIGHUP", "SIGINT"]) {
2237
2821
  process.on(sig, () => {
2238
2822
  backend.logExit(`signal:${sig}`);
@@ -2241,29 +2825,31 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
2241
2825
  }
2242
2826
  const debounceMs = Number(process.env.INPLAN_DEBOUNCE_MS ?? 3e3);
2243
2827
  const pollMs = Number(process.env.INPLAN_POLL_MS ?? 200);
2828
+ const errorGraceParsed = Number(process.env.INPLAN_ERROR_GRACE_MS);
2829
+ const errorGraceMs = process.env.INPLAN_ERROR_GRACE_MS && Number.isFinite(errorGraceParsed) && errorGraceParsed >= 0 ? errorGraceParsed : void 0;
2244
2830
  let waitCursor = cursor;
2245
2831
  let historyForMode = history;
2246
2832
  for (; ; ) {
2247
2833
  const mode = modeFrom(historyForMode);
2248
2834
  const isActionable = wakePredicate(mode.wake);
2249
- const result = await waitForActions({ channel, cursor: waitCursor, debounceMs, pollMs, isActionable, token: lockToken });
2835
+ const result = await waitForActions({ channel, cursor: waitCursor, debounceMs, pollMs, isActionable, token: lockToken, ...errorGraceMs !== void 0 ? { errorGraceMs } : {} });
2250
2836
  if (result.failed) {
2251
2837
  backend.logExit("poll_failed");
2252
2838
  process.stderr.write(`inplan: lost contact with the document (${result.failed.message}).
2253
2839
  If your session expired, run \`inplan login\` and re-attach.
2254
2840
  `);
2255
- output({ status: "wait_failed", message: result.failed.message });
2841
+ output({ status: "wait_failed", message: result.failed.message, ...proposalOut });
2256
2842
  exitAfterFlush(EXIT_WAIT_FAILED);
2257
2843
  return "exiting";
2258
2844
  }
2259
2845
  if (result.superseded) {
2260
2846
  backend.logExit("superseded");
2261
- output({ status: "superseded" });
2847
+ output({ status: "superseded", ...proposalOut });
2262
2848
  return "ok";
2263
2849
  }
2264
2850
  if (backend.onSaveLocally && result.entries.some((e) => e.type === LogEventType.SaveLocallyRequested)) {
2265
2851
  backend.logExit("save_locally");
2266
- await backend.onSaveLocally();
2852
+ await backend.onSaveLocally(proposalOut);
2267
2853
  return "ok";
2268
2854
  }
2269
2855
  await channel.setCursor(result.cursor);
@@ -2271,7 +2857,7 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
2271
2857
  if (navEntry) {
2272
2858
  const path = navEntry.payload?.path;
2273
2859
  backend.logExit("navigated");
2274
- output({ status: "navigated", ...path ? { path } : {}, cursor: result.cursor, closed: false });
2860
+ output({ status: "navigated", ...path ? { path } : {}, ...proposalOut, cursor: result.cursor, closed: false });
2275
2861
  return "ok";
2276
2862
  }
2277
2863
  const closeEntry = [...result.entries].reverse().find((e) => e.type === LogEventType.SessionClosed);
@@ -2286,13 +2872,13 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
2286
2872
  const reopen = await awaitReopen(channel, result.cursor, { token: lockToken });
2287
2873
  if (reopen.kind === "superseded") {
2288
2874
  backend.logExit("superseded");
2289
- output({ status: "superseded" });
2875
+ output({ status: "superseded", ...proposalOut });
2290
2876
  return "ok";
2291
2877
  }
2292
2878
  if (reopen.kind === "completed") {
2293
2879
  await channel.setCursor(reopen.cursor);
2294
2880
  backend.logExit(reopen.reason);
2295
- output({ status: "closed", reason: reopen.reason, cursor: reopen.cursor, closed: true, entries: [...result.entries, ...reopen.entries] });
2881
+ output({ status: "closed", reason: reopen.reason, ...proposalOut, cursor: reopen.cursor, closed: true, entries: [...result.entries, ...reopen.entries] });
2296
2882
  return "ok";
2297
2883
  }
2298
2884
  if (reopen.kind === "reopened") {
@@ -2326,6 +2912,10 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
2326
2912
  // when --model was passed), so presence + authorship stay consistent.
2327
2913
  agentAuthor: agentAuthorFor(model),
2328
2914
  ...reason ? { reason } : {},
2915
+ // The landing signal for a parked Review-mode edit (#88): pending_review means the push
2916
+ // REACHED the store and awaits the human — the canonical is unchanged by design. Absent
2917
+ // when the turn applied directly (or made no body change).
2918
+ ...proposalOut,
2329
2919
  cursor: result.cursor,
2330
2920
  closed: status === "closed",
2331
2921
  entries: result.entries
@@ -2364,6 +2954,7 @@ async function doLogin(args) {
2364
2954
  `);
2365
2955
  const auth = await pollLoginSession(pending, { onNudge: printLoginNudge });
2366
2956
  saveAuth(auth);
2957
+ await primeSessionOrFail();
2367
2958
  await persistCloudIdentity();
2368
2959
  output({ status: "logged_in", url: auth.url, ...auth.email ? { email: auth.email } : {} });
2369
2960
  return;
@@ -2375,6 +2966,38 @@ async function doLogin(args) {
2375
2966
  }
2376
2967
  }
2377
2968
  }
2969
+ if (canAttemptBrowserLaunch()) {
2970
+ let minted;
2971
+ try {
2972
+ minted = await createLoginSession();
2973
+ const launch = new AbortController();
2974
+ openInBrowser(minted.url, (kind) => {
2975
+ if (kind === "no-opener") launch.abort();
2976
+ });
2977
+ const auth = await pollLoginSession(minted, {
2978
+ openAckMs: OPEN_ACK_MS,
2979
+ launchSignal: launch.signal,
2980
+ onNudge: printLoginNudge
2981
+ });
2982
+ saveAuth(auth);
2983
+ await primeSessionOrFail();
2984
+ await persistCloudIdentity();
2985
+ output({ status: "logged_in", url: auth.url, ...auth.email ? { email: auth.email } : {} });
2986
+ return;
2987
+ } catch (e) {
2988
+ if (e instanceof BrowserDidNotOpenError) {
2989
+ await pendingLoginExit(minted);
2990
+ process.exit(1);
2991
+ }
2992
+ if (e instanceof LoginSessionExpiredError) {
2993
+ await pendingLoginExit();
2994
+ process.exit(1);
2995
+ }
2996
+ process.stderr.write(`inplan login: ${e instanceof Error ? e.message : String(e)}
2997
+ `);
2998
+ process.exit(1);
2999
+ }
3000
+ }
2378
3001
  await pendingLoginExit();
2379
3002
  process.exit(1);
2380
3003
  }
@@ -2390,6 +3013,7 @@ async function doLogin(args) {
2390
3013
  // INPLAN_NO_BROWSER: never launch one — the printed URL is the flow
2391
3014
  }) : await defaultRendezvousLogin();
2392
3015
  saveAuth(auth);
3016
+ await primeSessionOrFail();
2393
3017
  await persistCloudIdentity();
2394
3018
  output({ status: "logged_in", url: auth.url, ...auth.email ? { email: auth.email } : {} });
2395
3019
  } catch (e) {
@@ -2398,6 +3022,55 @@ async function doLogin(args) {
2398
3022
  process.exit(1);
2399
3023
  }
2400
3024
  }
3025
+ var OPEN_ACK_MS = 2e4;
3026
+ function canAttemptBrowserLaunch() {
3027
+ return !process.env.CI && !process.env.INPLAN_NO_BROWSER;
3028
+ }
3029
+ async function primeSessionOrFail(retryDelayMs = 750) {
3030
+ const refused = (what) => {
3031
+ clearAuth();
3032
+ process.stderr.write(
3033
+ `inplan login: signed in, but the server rejected the credential the browser handed over \u2014 ${what}
3034
+ Sign in again. If this repeats, the browser session is rotating the token before the CLI
3035
+ can claim it, and the sign-in page needs to hand over an unused token (or an access token).
3036
+ `
3037
+ );
3038
+ process.exit(1);
3039
+ };
3040
+ const unproven = () => {
3041
+ process.stderr.write(
3042
+ "inplan login: signed in, but the credential could not be verified \u2014 the check did not get an\n answer from the server (network, an outage, or another `inplan` holding the refresh lock).\n The credential is KEPT, not discarded: run the command again, or `inplan whoami` to check.\n"
3043
+ );
3044
+ process.exit(1);
3045
+ };
3046
+ const withOneRetry = async (check) => {
3047
+ const first = await check();
3048
+ if (first !== "inconclusive") return first;
3049
+ await new Promise((r) => setTimeout(r, retryDelayMs));
3050
+ return check();
3051
+ };
3052
+ const cached = await withOneRetry(verifyCachedAccessToken);
3053
+ if (cached === "ok") return;
3054
+ if (cached === "rejected") refused("its access token was not accepted.");
3055
+ if (cached === "inconclusive") unproven();
3056
+ const FORCE_REFRESH_SKEW_S = 10 * 365 * 24 * 3600;
3057
+ const forceRefresh = async () => {
3058
+ const before = loadAuth()?.refreshToken;
3059
+ let refusal = "inconclusive";
3060
+ const session = await authedSession(FORCE_REFRESH_SKEW_S, (reason, cause) => {
3061
+ refusal = reason === "inconclusive" ? "inconclusive" : cause === "refresh-token-spent" ? "rejected-spent" : "rejected-other";
3062
+ });
3063
+ if (!session) return refusal;
3064
+ return loadAuth()?.refreshToken !== before ? "ok" : "inconclusive";
3065
+ };
3066
+ const refreshed = await withOneRetry(forceRefresh);
3067
+ if (refreshed === "ok") return;
3068
+ if (refreshed === "rejected-spent") refused("its refresh token had already been spent, so it could never have been used.");
3069
+ if (refreshed === "rejected-other") {
3070
+ refused("the server refused it \u2014 the token may be invalid or revoked, or this deployment's anon key may no longer match.");
3071
+ }
3072
+ unproven();
3073
+ }
2401
3074
  async function persistCloudIdentity() {
2402
3075
  try {
2403
3076
  const user = await currentUser();
@@ -2473,11 +3146,11 @@ function scrubAgentEnv(env) {
2473
3146
  }
2474
3147
  return out;
2475
3148
  }
2476
- async function pendingLoginExit() {
3149
+ async function pendingLoginExit(existing) {
2477
3150
  let url;
2478
3151
  let expiresInSec;
2479
3152
  try {
2480
- const pending = await createLoginSession();
3153
+ const pending = existing ?? await createLoginSession();
2481
3154
  url = pending.url;
2482
3155
  expiresInSec = Math.max(0, Math.floor((pending.expiresAt - Date.now()) / 1e3));
2483
3156
  } catch (e) {
@@ -2522,10 +3195,10 @@ async function pendingLoginExit() {
2522
3195
  function stalenessCache() {
2523
3196
  const path = join10(sidecarRoot(), ".update-check.json");
2524
3197
  return {
2525
- readCache: () => existsSync10(path) ? readFileSync10(path, "utf8") : null,
3198
+ readCache: () => existsSync11(path) ? readFileSync11(path, "utf8") : null,
2526
3199
  writeCache: (v) => {
2527
- mkdirSync9(dirname10(path), { recursive: true });
2528
- writeFileSync9(path, v);
3200
+ mkdirSync10(dirname11(path), { recursive: true });
3201
+ writeFileSync10(path, v);
2529
3202
  }
2530
3203
  };
2531
3204
  }
@@ -2602,18 +3275,15 @@ async function runRemote(cmd, docId, explicitCursor, confirmed, rest, localFile,
2602
3275
  presenceTokenResolver(backend.token, async () => {
2603
3276
  const fresh = await remoteBackend(docId, "cli-agent");
2604
3277
  if (fresh) return fresh;
2605
- if (!existsSync10(authPath())) return null;
3278
+ if (!existsSync11(authPath())) return null;
2606
3279
  throw new Error("transient token refresh failure");
2607
3280
  }),
2608
3281
  model
2609
3282
  );
2610
3283
  try {
2611
3284
  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));
3285
+ const rds = new RemoteDocState(workFile, docId);
3286
+ rds.ensureDir();
2617
3287
  let canonical = "";
2618
3288
  try {
2619
3289
  canonical = await gate.readCanonical();
@@ -2624,33 +3294,121 @@ async function runRemote(cmd, docId, explicitCursor, confirmed, rest, localFile,
2624
3294
  exitAfterFlush(EXIT_PLUGIN_UNAVAILABLE);
2625
3295
  return;
2626
3296
  }
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);
3297
+ let justFinalized = false;
3298
+ const myRow = await live.store.myPendingProposal().catch(() => void 0);
3299
+ if (myRow !== void 0) {
3300
+ try {
3301
+ const pending = rds.pendingProposal();
3302
+ if (myRow && pending?.id !== myRow.id) {
3303
+ let settled = true;
3304
+ if (pending) {
3305
+ const priorRow = await live.store.getProposal(pending.id).catch(() => void 0);
3306
+ if (priorRow === void 0) settled = false;
3307
+ else {
3308
+ const finalized = rds.resolveProposal(priorRow && priorRow.state !== "pending" ? priorRow.state : "superseded");
3309
+ if (finalized && !rds.replayPending() && isDecidedProposalCorpse(finalized, rds.readWorkFile())) {
3310
+ rds.writeWorkFile(canonical);
3311
+ rds.recordSynced(canonical);
3312
+ }
3313
+ }
3314
+ }
3315
+ if (settled) rds.parkProposal(myRow.content, void 0, myRow.id);
3316
+ } else if (myRow && pending && pending.hash !== hashBody(myRow.content)) {
3317
+ rds.parkProposal(myRow.content, void 0, myRow.id);
3318
+ } else if (!myRow && pending) {
3319
+ const row = await live.store.getProposal(pending.id).catch(() => void 0);
3320
+ if (row === null) justFinalized = rds.resolveProposal("decided") !== null;
3321
+ else if (row && row.state !== "pending") justFinalized = rds.resolveProposal(row.state) !== null;
3322
+ }
3323
+ } catch (e) {
3324
+ process.stderr.write(`inplan: could not reconcile the local proposal record (${String(e)}); continuing \u2014 it will retry next run
3325
+ `);
3326
+ }
3327
+ }
3328
+ if (justFinalized && !rds.replayPending() && isDecidedProposalCorpse(rds.latestProposal(), rds.readWorkFile())) {
3329
+ rds.writeWorkFile(canonical);
3330
+ rds.recordSynced(canonical);
3331
+ }
3332
+ if (shouldHydrateWorkFile(rds.hydrateInput())) {
3333
+ rds.writeWorkFile(canonical);
3334
+ rds.recordSynced(canonical);
2636
3335
  }
2637
3336
  const localStore = fsBackend(workFile).store;
3337
+ let hubParkFailed = false;
2638
3338
  const gateStore = {
2639
3339
  loadDoc: () => localStore.loadDoc(),
2640
3340
  saveDoc: (c) => localStore.saveDoc(c),
2641
3341
  getCanonical: () => localStore.getCanonical(),
2642
3342
  setCanonical: (c) => localStore.setCanonical(c),
2643
3343
  backup: (c, m) => localStore.backup(c, m),
2644
- getProposed: () => live.store.getProposed(),
2645
- setProposed: (c) => live.store.setProposed(c),
2646
- clearProposed: () => live.store.clearProposed()
3344
+ myPendingProposal: () => live.store.myPendingProposal(),
3345
+ getProposal: (id) => live.store.getProposal(id),
3346
+ // Cloud-side lifecycle transitions settle the LOCAL record too, or it would stay
3347
+ // pending_review while its cloud row is terminal — and the id-reuse on the next park
3348
+ // would then converge against an immutable row and the content would never land. The
3349
+ // local record mirrors the row's ACTUAL terminal state, not the intended one: our
3350
+ // transition is state-guarded and can lose a race (zero rows updated, no error) to a
3351
+ // human decision that landed first — the decision wins, locally too.
3352
+ withdrawProposal: async (id) => {
3353
+ await live.store.withdrawProposal(id);
3354
+ if (rds.pendingProposal()?.id === id) {
3355
+ const row = await live.store.getProposal(id).catch(() => null);
3356
+ if (row && row.state !== "pending") rds.resolveProposal(row.state);
3357
+ }
3358
+ },
3359
+ decideProposal: async (id, st) => {
3360
+ const result = await live.store.decideProposal(id, st);
3361
+ if (rds.pendingProposal()?.id === id) {
3362
+ const row = await live.store.getProposal(id).catch(() => null);
3363
+ if (row && row.state !== "pending") rds.resolveProposal(row.state);
3364
+ }
3365
+ return result;
3366
+ },
3367
+ createProposal: async (input) => {
3368
+ const prior = rds.pendingProposal();
3369
+ const id = input.id ?? (prior && prior.hash === hashBody(input.content) ? prior.id : void 0);
3370
+ let created;
3371
+ try {
3372
+ created = await live.store.createProposal({ ...input, ...id ? { id } : {} });
3373
+ if (id) {
3374
+ const row = await live.store.getProposal(created.id);
3375
+ if (!row) throw new Error(`park verification found no row for reused id ${created.id}`);
3376
+ if (row.state !== "pending") {
3377
+ if (rds.pendingProposal()?.id === created.id) rds.resolveProposal(row.state);
3378
+ created = await live.store.createProposal({ content: input.content, baseHash: input.baseHash, baseContent: input.baseContent });
3379
+ }
3380
+ }
3381
+ } catch (e) {
3382
+ hubParkFailed = true;
3383
+ throw e;
3384
+ }
3385
+ try {
3386
+ if (prior && prior.id !== created.id) {
3387
+ const priorRow = await live.store.getProposal(prior.id);
3388
+ if (priorRow && priorRow.state !== "pending" && priorRow.state !== "superseded") rds.resolveProposal(priorRow.state);
3389
+ }
3390
+ } catch {
3391
+ }
3392
+ try {
3393
+ rds.parkProposal(input.content, void 0, created.id);
3394
+ } catch (e) {
3395
+ 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
3396
+ `);
3397
+ }
3398
+ return created;
3399
+ }
2647
3400
  };
2648
- const onSaveLocallyGate = localFile ? async () => {
3401
+ const onSaveLocallyGate = localFile ? async (info) => {
2649
3402
  const body = await gate.readCanonical();
2650
- writeFileSync9(localFile, body);
3403
+ const leftover = rds.readWorkFile();
3404
+ if (leftover !== null && hashBody(leftover) !== (rds.hydrateInput().syncedHash ?? "") && parse(leftover).body !== parse(body).body) {
3405
+ 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.
3406
+ `);
3407
+ }
3408
+ writeFileSync10(localFile, body);
2651
3409
  writeStatus(docPaths(localFile).statusPath, { location: "local", originalPath: localFile, lastSyncedHash: hashBody(body) });
2652
3410
  const pid = spawnApp(localFile);
2653
- output({ status: "moved_local", path: localFile, reopened: pid !== null });
3411
+ output({ status: "moved_local", path: localFile, reopened: pid !== null, ...info });
2654
3412
  } : void 0;
2655
3413
  const tracked = trackGateDegradations(
2656
3414
  gate,
@@ -2669,6 +3427,8 @@ async function runRemote(cmd, docId, explicitCursor, confirmed, rest, localFile,
2669
3427
  history: async () => (await live.channel.readSince(0)).entries,
2670
3428
  logExit: () => {
2671
3429
  },
3430
+ localPendingProposalId: () => rds.pendingProposal()?.id,
3431
+ // local file read only — see WaitBackend
2672
3432
  ...onSaveLocallyGate ? { onSaveLocally: onSaveLocallyGate } : {}
2673
3433
  },
2674
3434
  explicitCursor,
@@ -2677,20 +3437,21 @@ async function runRemote(cmd, docId, explicitCursor, confirmed, rest, localFile,
2677
3437
  tracked.gate
2678
3438
  // …and accepted edits apply through the hub, not the store.
2679
3439
  );
2680
- const action = postTurnAction(outcome, { readFailed: tracked.readFailed(), writeFailed: tracked.writeFailed() });
3440
+ const degraded = { readFailed: tracked.readFailed(), writeFailed: tracked.writeFailed() || hubParkFailed };
3441
+ const action = postTurnAction(outcome, degraded);
2681
3442
  if (action === "stop") return;
2682
3443
  if (action === "keep-local") {
2683
- if (pendingRequiresReplay({ readFailed: tracked.readFailed(), writeFailed: tracked.writeFailed() })) {
2684
- writeFileSync9(pendingPath, "1");
3444
+ if (pendingRequiresReplay(degraded)) {
3445
+ rds.markReplayPending();
2685
3446
  }
2686
3447
  process.stderr.write("inplan: hub was unavailable this turn \u2014 keeping local edits (will sync next turn)\n");
2687
3448
  } else {
2688
- if (existsSync10(pendingPath)) rmSync2(pendingPath);
2689
- recordSynced(readFileSync10(workFile, "utf8"));
3449
+ rds.clearReplayPending();
3450
+ rds.recordSynced(rds.readWorkFile() ?? "");
2690
3451
  try {
2691
3452
  const fresh = await gate.readCanonical();
2692
- writeFileSync9(workFile, fresh);
2693
- recordSynced(fresh);
3453
+ rds.writeWorkFile(fresh);
3454
+ rds.recordSynced(fresh);
2694
3455
  } catch {
2695
3456
  }
2696
3457
  }
@@ -2708,7 +3469,7 @@ function doPromote(file, args) {
2708
3469
  process.stderr.write("usage: inplan promote <file> --cloud-doc <docId> [--locator org/repo/path]\n");
2709
3470
  process.exit(64);
2710
3471
  }
2711
- const body = existsSync10(file) ? readFileSync10(file, "utf8") : "";
3472
+ const body = existsSync11(file) ? readFileSync11(file, "utf8") : "";
2712
3473
  const status = { location: "cloud", cloudDocId, originalPath: file, lastSyncedHash: hashBody(body) };
2713
3474
  const locator = getFlag(args, "locator");
2714
3475
  if (locator) {
@@ -2753,7 +3514,7 @@ async function doDemote(file, args) {
2753
3514
  return;
2754
3515
  }
2755
3516
  const body = choice.use === "hub" ? hubBody : await backend.store.loadDoc();
2756
- writeFileSync9(dest, body);
3517
+ writeFileSync10(dest, body);
2757
3518
  writeStatus(p.statusPath, { location: "local", originalPath: dest, lastSyncedHash: hashBody(body) });
2758
3519
  output({ status: "demoted", location: "local", path: dest, source: choice.use });
2759
3520
  }
@@ -2788,16 +3549,16 @@ async function doToken() {
2788
3549
  function bundledSkillPath() {
2789
3550
  try {
2790
3551
  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;
3552
+ if (override) return existsSync11(override) ? override : null;
3553
+ const p = join10(dirname11(fileURLToPath2(import.meta.url)), "..", "skill", "SKILL.md");
3554
+ return existsSync11(p) ? p : null;
2794
3555
  } catch {
2795
3556
  return null;
2796
3557
  }
2797
3558
  }
2798
3559
  function activeDocForCwd(cwd) {
2799
3560
  const root = sidecarRoot();
2800
- if (!existsSync10(root)) return null;
3561
+ if (!existsSync11(root)) return null;
2801
3562
  const real = (p) => {
2802
3563
  try {
2803
3564
  return realpathSync(p);
@@ -2815,7 +3576,7 @@ function activeDocForCwd(cwd) {
2815
3576
  const rel = relative4(base2, real(orig));
2816
3577
  if (rel === "" || rel.startsWith("..") || isAbsolute2(rel)) continue;
2817
3578
  const logPath = join10(dir, "log.jsonl");
2818
- const mtime = existsSync10(logPath) ? statSync4(logPath).mtimeMs : 0;
3579
+ const mtime = existsSync11(logPath) ? statSync5(logPath).mtimeMs : 0;
2819
3580
  if (!best || mtime > best.mtime) best = { file: resolve3(orig), mtime };
2820
3581
  } catch {
2821
3582
  }
@@ -2828,7 +3589,7 @@ function relayCursorPath(sessionKey) {
2828
3589
  }
2829
3590
  function readRelayCursor(sessionKey) {
2830
3591
  try {
2831
- const v = JSON.parse(readFileSync10(relayCursorPath(sessionKey), "utf8"));
3592
+ const v = JSON.parse(readFileSync11(relayCursorPath(sessionKey), "utf8"));
2832
3593
  return typeof v.sent === "number" && v.sent >= 0 ? v.sent : 0;
2833
3594
  } catch {
2834
3595
  return 0;
@@ -2837,8 +3598,8 @@ function readRelayCursor(sessionKey) {
2837
3598
  function writeRelayCursor(sessionKey, sent) {
2838
3599
  try {
2839
3600
  const p = relayCursorPath(sessionKey);
2840
- mkdirSync9(dirname10(p), { recursive: true });
2841
- writeFileSync9(p, JSON.stringify({ sent }) + "\n");
3601
+ mkdirSync10(dirname11(p), { recursive: true });
3602
+ writeFileSync10(p, JSON.stringify({ sent }) + "\n");
2842
3603
  } catch {
2843
3604
  }
2844
3605
  }
@@ -2846,7 +3607,7 @@ function transcriptTextBlocks(path) {
2846
3607
  const out = [];
2847
3608
  let raw;
2848
3609
  try {
2849
- raw = readFileSync10(path, "utf8");
3610
+ raw = readFileSync11(path, "utf8");
2850
3611
  } catch {
2851
3612
  return out;
2852
3613
  }
@@ -2891,7 +3652,7 @@ function notesFromHook(kind, stdin, argv) {
2891
3652
  const p = parse2(stdin);
2892
3653
  const transcript = str(p.transcript_path);
2893
3654
  const sessionKey = str(p.session_id) || transcript;
2894
- const blocks = transcript && existsSync10(transcript) && sessionKey ? transcriptTextBlocks(transcript) : [];
3655
+ const blocks = transcript && existsSync11(transcript) && sessionKey ? transcriptTextBlocks(transcript) : [];
2895
3656
  if (blocks.length > 0) {
2896
3657
  const sent = readRelayCursor(sessionKey);
2897
3658
  for (let i = Math.max(0, sent); i < blocks.length; i++) notes.push(blocks[i]);
@@ -2915,7 +3676,7 @@ async function relayText(file, text) {
2915
3676
  await backend.channel.append({ actor: "agent", type: LogEventType.AgentMessage, payload: { text } });
2916
3677
  } else if (route.kind === "local") {
2917
3678
  const p = docPaths(file);
2918
- mkdirSync9(p.controlDir, { recursive: true });
3679
+ mkdirSync10(p.controlDir, { recursive: true });
2919
3680
  await new FsControlChannel(p).append({ actor: "agent", type: LogEventType.AgentMessage, payload: { text } });
2920
3681
  }
2921
3682
  } catch {
@@ -2933,7 +3694,7 @@ async function doRelay(args) {
2933
3694
  let stdin = "";
2934
3695
  if (hook !== "codex-notify") {
2935
3696
  try {
2936
- stdin = readFileSync10(0, "utf8");
3697
+ stdin = readFileSync11(0, "utf8");
2937
3698
  } catch {
2938
3699
  }
2939
3700
  }
@@ -2965,8 +3726,8 @@ function grantClaudePermissions(claudeRoot) {
2965
3726
  const settingsPath = join10(claudeRoot, "settings.json");
2966
3727
  let settings = {};
2967
3728
  try {
2968
- if (existsSync10(settingsPath)) {
2969
- const parsed = JSON.parse(readFileSync10(settingsPath, "utf8"));
3729
+ if (existsSync11(settingsPath)) {
3730
+ const parsed = JSON.parse(readFileSync11(settingsPath, "utf8"));
2970
3731
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
2971
3732
  settings = parsed;
2972
3733
  }
@@ -2999,8 +3760,8 @@ function grantClaudePermissions(claudeRoot) {
2999
3760
  settings.permissions = perms;
3000
3761
  try {
3001
3762
  const tmp = settingsPath + ".tmp";
3002
- writeFileSync9(tmp, JSON.stringify(settings, null, 2) + "\n");
3003
- renameSync2(tmp, settingsPath);
3763
+ writeFileSync10(tmp, JSON.stringify(settings, null, 2) + "\n");
3764
+ renameSync4(tmp, settingsPath);
3004
3765
  } catch {
3005
3766
  return false;
3006
3767
  }
@@ -3045,8 +3806,8 @@ function mergeRelayHooks(settings, entries) {
3045
3806
  }
3046
3807
  function readJsonObject(path) {
3047
3808
  try {
3048
- if (!existsSync10(path)) return {};
3049
- const parsed = JSON.parse(readFileSync10(path, "utf8"));
3809
+ if (!existsSync11(path)) return {};
3810
+ const parsed = JSON.parse(readFileSync11(path, "utf8"));
3050
3811
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
3051
3812
  return parsed;
3052
3813
  } catch {
@@ -3055,10 +3816,10 @@ function readJsonObject(path) {
3055
3816
  }
3056
3817
  function writeJsonAtomic(path, value) {
3057
3818
  try {
3058
- mkdirSync9(dirname10(path), { recursive: true });
3819
+ mkdirSync10(dirname11(path), { recursive: true });
3059
3820
  const tmp = path + ".tmp";
3060
- writeFileSync9(tmp, JSON.stringify(value, null, 2) + "\n");
3061
- renameSync2(tmp, path);
3821
+ writeFileSync10(tmp, JSON.stringify(value, null, 2) + "\n");
3822
+ renameSync4(tmp, path);
3062
3823
  return true;
3063
3824
  } catch {
3064
3825
  return false;
@@ -3123,15 +3884,15 @@ export default function (pi) {
3123
3884
  function installPiRelayExtension(piAgentRoot) {
3124
3885
  const path = join10(piAgentRoot, "extensions", "inplan-relay.ts");
3125
3886
  try {
3126
- if (existsSync10(path)) {
3127
- const cur = readFileSync10(path, "utf8");
3887
+ if (existsSync11(path)) {
3888
+ const cur = readFileSync11(path, "utf8");
3128
3889
  if (cur === PI_RELAY_EXTENSION) return false;
3129
3890
  if (!cur.startsWith(PI_RELAY_MARKER)) return false;
3130
3891
  }
3131
- mkdirSync9(dirname10(path), { recursive: true });
3892
+ mkdirSync10(dirname11(path), { recursive: true });
3132
3893
  const tmp = path + ".tmp";
3133
- writeFileSync9(tmp, PI_RELAY_EXTENSION);
3134
- renameSync2(tmp, path);
3894
+ writeFileSync10(tmp, PI_RELAY_EXTENSION);
3895
+ renameSync4(tmp, path);
3135
3896
  return true;
3136
3897
  } catch {
3137
3898
  return false;
@@ -3151,9 +3912,9 @@ function doInstallSkill(args) {
3151
3912
  const installed = [];
3152
3913
  for (const a of skillTargets()) {
3153
3914
  try {
3154
- if (!existsSync10(a.root)) continue;
3155
- if (!existsSync10(a.target)) {
3156
- mkdirSync9(dirname10(a.target), { recursive: true });
3915
+ if (!existsSync11(a.root)) continue;
3916
+ if (!existsSync11(a.target)) {
3917
+ mkdirSync10(dirname11(a.target), { recursive: true });
3157
3918
  copyFileSync(src, a.target);
3158
3919
  installed.push(a.name);
3159
3920
  process.stderr.write(`inplan: installed the inplan skill into ${a.name} (${a.target}). Set INPLAN_NO_SKILL_INSTALL=1 to skip.
@@ -3206,7 +3967,7 @@ async function doUpload(file, args) {
3206
3967
  process.exit(1);
3207
3968
  }
3208
3969
  const org = orgOf(pick);
3209
- const body = existsSync10(file) ? readFileSync10(file, "utf8") : "";
3970
+ const body = existsSync11(file) ? readFileSync11(file, "utf8") : "";
3210
3971
  const prov = gitProvenance(file);
3211
3972
  const repo = getFlag(args, "repo") ?? prov.repo;
3212
3973
  const path = getFlag(args, "path") ?? prov.path;
@@ -3248,7 +4009,7 @@ async function doUpload(file, args) {
3248
4009
  let finalBody = body;
3249
4010
  if (out0.status === "created") {
3250
4011
  try {
3251
- const migrated = await migrateLocalImages(body, dirname10(file), s.db, pick.org_id, cloudDocId);
4012
+ const migrated = await migrateLocalImages(body, dirname11(file), s.db, pick.org_id, cloudDocId);
3252
4013
  if (migrated.migrated > 0) {
3253
4014
  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
4015
  if (updateErr) {
@@ -3261,7 +4022,7 @@ async function doUpload(file, args) {
3261
4022
  "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
4023
  );
3263
4024
  }
3264
- const onDiskNow = existsSync10(file) ? readFileSync10(file, "utf8") : null;
4025
+ const onDiskNow = existsSync11(file) ? readFileSync11(file, "utf8") : null;
3265
4026
  if (onDiskNow !== null && onDiskNow !== body) {
3266
4027
  finalBody = onDiskNow;
3267
4028
  throw new Error(
@@ -3269,10 +4030,10 @@ async function doUpload(file, args) {
3269
4030
  );
3270
4031
  }
3271
4032
  try {
3272
- writeFileSync9(file, migrated.body);
4033
+ writeFileSync10(file, migrated.body);
3273
4034
  finalBody = migrated.body;
3274
4035
  } catch (e) {
3275
- finalBody = existsSync10(file) ? readFileSync10(file, "utf8") : body;
4036
+ finalBody = existsSync11(file) ? readFileSync11(file, "utf8") : body;
3276
4037
  throw new Error(
3277
4038
  `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
4039
  );
@@ -3348,7 +4109,7 @@ async function doAssetUpload(file, args) {
3348
4109
  process.exit(1);
3349
4110
  }
3350
4111
  const requestedExt = (getFlag(args, "ext") ?? "png").toLowerCase();
3351
- const bytes = readFileSync10(bytesFile);
4112
+ const bytes = readFileSync11(bytesFile);
3352
4113
  const uploaded = await uploadAssetBytes(s.db, orgId, status.cloudDocId, bytes, requestedExt);
3353
4114
  if (!uploaded) {
3354
4115
  process.stderr.write("inplan asset-upload: upload failed\n");
@@ -3408,7 +4169,7 @@ async function migrateLocalImages(body, docDir, db, orgId, docId) {
3408
4169
  continue;
3409
4170
  }
3410
4171
  const abs = resolve3(docDir, dest);
3411
- if (!existsSync10(abs)) continue;
4172
+ if (!existsSync11(abs)) continue;
3412
4173
  let absReal;
3413
4174
  try {
3414
4175
  absReal = realpathSync(abs);
@@ -3421,7 +4182,7 @@ async function migrateLocalImages(body, docDir, db, orgId, docId) {
3421
4182
  if (!Object.prototype.hasOwnProperty.call(ASSET_MIME_BY_EXT, ext)) continue;
3422
4183
  let bytes;
3423
4184
  try {
3424
- bytes = readFileSync10(abs);
4185
+ bytes = readFileSync11(abs);
3425
4186
  } catch {
3426
4187
  continue;
3427
4188
  }
@@ -3455,8 +4216,8 @@ function routeFor(file, cmd, args) {
3455
4216
  const status = readStatus(p.statusPath);
3456
4217
  if (status.location !== "cloud" || !status.cloudDocId) return { kind: "local" };
3457
4218
  const docId = status.cloudDocId;
3458
- if (cmd === "signal" || cmd === "message" || !existsSync10(file)) return { kind: "cloud", docId };
3459
- const local = readFileSync10(file, "utf8");
4219
+ if (cmd === "signal" || cmd === "message" || !existsSync11(file)) return { kind: "cloud", docId };
4220
+ const local = readFileSync11(file, "utf8");
3460
4221
  const diverged = status.lastSyncedHash !== void 0 && hashBody(local) !== status.lastSyncedHash;
3461
4222
  if (!diverged || hasFlag(args, "use-cloud")) return { kind: "cloud", docId };
3462
4223
  if (hasFlag(args, "continue-locally")) {
@@ -3578,7 +4339,7 @@ async function main() {
3578
4339
  }
3579
4340
  if (cmd === "signal") {
3580
4341
  const p = docPaths(file);
3581
- mkdirSync9(p.controlDir, { recursive: true });
4342
+ mkdirSync10(p.controlDir, { recursive: true });
3582
4343
  const channel = new FsControlChannel(p);
3583
4344
  if (hasFlag(args, "done")) {
3584
4345
  await channel.append({ actor: "agent", type: LogEventType.AgentDoneSuggested });
@@ -3596,13 +4357,13 @@ async function main() {
3596
4357
  process.exit(1);
3597
4358
  }
3598
4359
  const p = docPaths(file);
3599
- mkdirSync9(p.controlDir, { recursive: true });
4360
+ mkdirSync10(p.controlDir, { recursive: true });
3600
4361
  const channel = new FsControlChannel(p);
3601
4362
  await channel.append({ actor: "agent", type: LogEventType.AgentMessage, payload: { text } });
3602
4363
  output({ status: "messaged" });
3603
4364
  return;
3604
4365
  }
3605
- if (cmd !== "open" && !existsSync10(file)) {
4366
+ if (cmd !== "open" && !existsSync11(file)) {
3606
4367
  process.stderr.write(`inplan ${cmd}: file not found: ${file}
3607
4368
  `);
3608
4369
  process.exit(1);
@@ -3628,7 +4389,7 @@ async function main() {
3628
4389
  }
3629
4390
  }
3630
4391
  try {
3631
- const currentText = readFileSync10(file, "utf8");
4392
+ const currentText = readFileSync11(file, "utf8");
3632
4393
  const { text: nextText, comment } = addComment(currentText, {
3633
4394
  text,
3634
4395
  author: agentAuthorFor(model),
@@ -3638,7 +4399,7 @@ async function main() {
3638
4399
  ...question ? { question } : {},
3639
4400
  mayResolve: hasFlag(args, "may-resolve")
3640
4401
  });
3641
- writeFileSync9(file, nextText);
4402
+ writeFileSync10(file, nextText);
3642
4403
  output({ status: "commented", id: comment.id, date: comment.date, author: comment.author });
3643
4404
  } catch (err) {
3644
4405
  if (err instanceof AddCommentError) {
@@ -3653,7 +4414,7 @@ async function main() {
3653
4414
  if (cmd === "open") {
3654
4415
  ensureDocFile(file);
3655
4416
  const p = docPaths(file);
3656
- mkdirSync9(p.controlDir, { recursive: true });
4417
+ mkdirSync10(p.controlDir, { recursive: true });
3657
4418
  const st = readStatus(p.statusPath);
3658
4419
  if (st.location !== "cloud") writeStatus(p.statusPath, { ...st, location: "local", originalPath: file });
3659
4420
  const existing = runningEditorPid(p.logPath);
@@ -3709,6 +4470,7 @@ export {
3709
4470
  EXIT_PLUGIN_UNAVAILABLE,
3710
4471
  EXIT_UPGRADE_REQUIRED,
3711
4472
  EXIT_WAIT_FAILED,
4473
+ acceptanceFrom,
3712
4474
  activeDocForCwd,
3713
4475
  canInteractiveLogin,
3714
4476
  doAssetUpload,
@@ -3718,6 +4480,7 @@ export {
3718
4480
  explainNoGate,
3719
4481
  isKnownAgentEnv,
3720
4482
  notesFromHook,
4483
+ primeSessionOrFail,
3721
4484
  scrubAgentEnv,
3722
4485
  shellQuote,
3723
4486
  transcriptTextBlocks,