inplan 0.3.0 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js CHANGED
@@ -9,7 +9,7 @@ import { homedir as homedir7 } from "os";
9
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-P2QV45YY.js
12
+ // ../core/dist/chunk-5WMTJCY6.js
13
13
  function isReply(c) {
14
14
  return c.parentId !== void 0;
15
15
  }
@@ -43,10 +43,10 @@ function genId(taken) {
43
43
  throw new Error("genId: failed to generate a unique id after 1000 attempts");
44
44
  }
45
45
  var ANCHOR_LINK_RE = /\]\(#(cmt-[0-9a-z]+)\)/gi;
46
- function stripCode(body) {
46
+ function stripCode(body2) {
47
47
  let inFence = false;
48
48
  const out = [];
49
- for (const line of body.split("\n")) {
49
+ for (const line of body2.split("\n")) {
50
50
  if (/^\s*(```|~~~)/.test(line)) {
51
51
  inFence = !inFence;
52
52
  out.push("");
@@ -58,23 +58,79 @@ function stripCode(body) {
58
58
  }
59
59
  return out.join("\n");
60
60
  }
61
- function extractAnchorIdList(body) {
61
+ function extractAnchorIdList(body2) {
62
62
  const ids = [];
63
- for (const m of stripCode(body).matchAll(ANCHOR_LINK_RE)) {
63
+ for (const m of stripCode(body2).matchAll(ANCHOR_LINK_RE)) {
64
64
  ids.push(m[1].toLowerCase());
65
65
  }
66
66
  return ids;
67
67
  }
68
- function extractAnchorIds(body) {
69
- return new Set(extractAnchorIdList(body));
68
+ function extractAnchorIds(body2) {
69
+ return new Set(extractAnchorIdList(body2));
70
70
  }
71
- function anchorLinkCounts(body) {
71
+ function anchorLinkCounts(body2) {
72
72
  const counts = /* @__PURE__ */ new Map();
73
- for (const id of extractAnchorIdList(body)) {
73
+ for (const id of extractAnchorIdList(body2)) {
74
74
  counts.set(id, (counts.get(id) ?? 0) + 1);
75
75
  }
76
76
  return counts;
77
77
  }
78
+ function codeMask(text) {
79
+ const mask = new Array(text.length).fill(false);
80
+ const fill = (from, len) => {
81
+ for (let k = 0; k < len; k++) mask[from + k] = true;
82
+ };
83
+ let at = 0;
84
+ let inFence = false;
85
+ for (const line of text.split("\n")) {
86
+ if (/^\s*(```|~~~)/.test(line)) {
87
+ inFence = !inFence;
88
+ fill(at, line.length);
89
+ } else if (inFence) {
90
+ fill(at, line.length);
91
+ } else {
92
+ for (const m of line.matchAll(/`[^`]*`/g)) fill(at + m.index, m[0].length);
93
+ }
94
+ at += line.length + 1;
95
+ }
96
+ return mask;
97
+ }
98
+ var ANCHOR_TAIL_RE = /\]\(#(cmt-[0-9a-z]+)\)/gi;
99
+ function findAnchor(text, wanted) {
100
+ const mask = codeMask(text);
101
+ for (const m of text.matchAll(ANCHOR_TAIL_RE)) {
102
+ const close = m.index;
103
+ if (mask[close] || !wanted(m[1].toLowerCase())) continue;
104
+ let depth = 0;
105
+ let open = -1;
106
+ for (let k = close - 1; k >= 0; k--) {
107
+ if (mask[k]) continue;
108
+ const ch = text[k];
109
+ if (ch === "]") depth++;
110
+ else if (ch === "[") {
111
+ if (depth === 0) {
112
+ open = k;
113
+ break;
114
+ }
115
+ depth--;
116
+ }
117
+ }
118
+ if (open === -1) continue;
119
+ return { start: open, end: close + m[0].length, text: text.slice(open + 1, close), id: m[1].toLowerCase() };
120
+ }
121
+ return null;
122
+ }
123
+ function unwrapWhere(text, wanted) {
124
+ let out = text;
125
+ for (; ; ) {
126
+ const found = findAnchor(out, wanted);
127
+ if (!found) return out;
128
+ out = out.slice(0, found.start) + found.text + out.slice(found.end);
129
+ }
130
+ }
131
+ function stripAnchors(text) {
132
+ return unwrapWhere(text, () => true);
133
+ }
78
134
  var BLOCK_OPEN = "<!--inplan";
79
135
  var BLOCK_CLOSE = "-->";
80
136
  var DOC_FORMAT_VERSION = 1;
@@ -121,22 +177,34 @@ function parse(markdown) {
121
177
  if (err instanceof ParseError) throw err;
122
178
  throw new ParseError(`comment data block is not valid JSON: ${err.message}`);
123
179
  }
124
- const body = markdown.slice(0, openIdx).replace(/\s+$/, "");
125
- return { body, comments, version };
180
+ const body2 = markdown.slice(0, openIdx).replace(/\s+$/, "");
181
+ return { body: body2, comments, version };
126
182
  }
127
183
  function serialize(doc) {
128
- const body = doc.body.replace(/\s+$/, "");
184
+ const body2 = doc.body.replace(/\s+$/, "");
129
185
  const json = JSON.stringify(doc.comments, null, 2);
130
186
  const version = doc.version ?? DOC_FORMAT_VERSION;
131
187
  const block = `${BLOCK_OPEN} v${version}
132
188
  ${json}
133
189
  ${BLOCK_CLOSE}
134
190
  `;
135
- return body.length === 0 ? `
136
- ${block}` : `${body}
191
+ return body2.length === 0 ? `
192
+ ${block}` : `${body2}
137
193
 
138
194
  ${block}`;
139
195
  }
196
+ var DATE_SKEW_TOLERANCE_MS = 5 * 6e4;
197
+ function stampImpossibleDates(comments, now = Date.now()) {
198
+ const repaired = [];
199
+ let step = 0;
200
+ const out = comments.map((c) => {
201
+ const t = Date.parse(c.date);
202
+ if (!Number.isNaN(t) && t <= now + DATE_SKEW_TOLERANCE_MS) return c;
203
+ repaired.push(c.id);
204
+ return { ...c, date: new Date(now + step++).toISOString() };
205
+ });
206
+ return { comments: repaired.length ? out : comments, repaired };
207
+ }
140
208
  var ParseError = class extends Error {
141
209
  constructor(message) {
142
210
  super(message);
@@ -223,7 +291,12 @@ var LogEventType = {
223
291
  * Payload `{ path }` is the new doc; the attached agent's `wait` steps down and
224
292
  * the human's agent re-attaches there (the local analogue of save-locally). */
225
293
  NavigatedTo: "navigated_to",
226
- SessionClosed: "session_closed"
294
+ SessionClosed: "session_closed",
295
+ /** `inplan open` created this document on an agent's behalf (it was passed `--model`) and the
296
+ * agent is about to write the first draft. Payload `{ model }`. The editor shows a dismissible
297
+ * "may be writing the first draft" banner while the body is still empty, so the empty page
298
+ * doesn't read as a broken load. Informational only — not a wake signal. */
299
+ DraftPending: "draft_pending"
227
300
  };
228
301
  function serializeLogEntry(entry) {
229
302
  return JSON.stringify(entry);
@@ -271,6 +344,7 @@ import { dirname as dirname4 } from "path";
271
344
  import { createHash as createHash3, createPublicKey, verify } from "crypto";
272
345
  import { existsSync as existsSync7, mkdirSync as mkdirSync5, readFileSync as readFileSync6, writeFileSync as writeFileSync5 } from "fs";
273
346
  import { isAbsolute, join as join5, relative as relative2, resolve as resolve2 } from "path";
347
+ import net from "net";
274
348
  function readLog(path) {
275
349
  if (!existsSync(path)) return [];
276
350
  return parseLog(readFileSync(path, "utf8"));
@@ -673,10 +747,10 @@ function verifyLease(token, publicKeyPem = PLUGIN_PUBLIC_KEY, now = Date.now())
673
747
  if (!publicKeyPem || typeof token !== "string") return null;
674
748
  const dot = token.indexOf(".");
675
749
  if (dot <= 0) return null;
676
- const body = token.slice(0, dot);
750
+ const body2 = token.slice(0, dot);
677
751
  const sig = token.slice(dot + 1);
678
- if (!verify(null, Buffer.from(body), createPublicKey(publicKeyPem), Buffer.from(sig, "base64url"))) return null;
679
- const claims = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
752
+ if (!verify(null, Buffer.from(body2), createPublicKey(publicKeyPem), Buffer.from(sig, "base64url"))) return null;
753
+ const claims = JSON.parse(Buffer.from(body2, "base64url").toString("utf8"));
680
754
  if (typeof claims.sub !== "string" || typeof claims.plan !== "string" || !Array.isArray(claims.features) || typeof claims.iat !== "number" || typeof claims.exp !== "number" || claims.exp <= now)
681
755
  return null;
682
756
  return claims;
@@ -778,6 +852,20 @@ async function resolvePluginOutcome(options) {
778
852
  }
779
853
  return cached();
780
854
  }
855
+ var CONNECT_ATTEMPT_TIMEOUT_MS = 1e3;
856
+ function widenConnectAttemptBudget(ms = CONNECT_ATTEMPT_TIMEOUT_MS) {
857
+ const get = net.getDefaultAutoSelectFamilyAttemptTimeout;
858
+ const set = net.setDefaultAutoSelectFamilyAttemptTimeout;
859
+ if (typeof get !== "function" || typeof set !== "function") return null;
860
+ const current = get();
861
+ if (Number.isFinite(current) && current >= ms) return current;
862
+ try {
863
+ set(ms);
864
+ } catch {
865
+ return Number.isFinite(current) ? current : null;
866
+ }
867
+ return ms;
868
+ }
781
869
 
782
870
  // src/agentAuthor.ts
783
871
  function vendorOf(model) {
@@ -1022,8 +1110,8 @@ var SupabaseDocumentStore = class {
1022
1110
  async getVersion(id) {
1023
1111
  const { data, error } = await this.db.from("doc_versions").select("body").eq("id", id).eq("doc_id", this.docId).maybeSingle();
1024
1112
  if (error) throw new Error(`getVersion failed: ${error.message}`);
1025
- const body = data?.body;
1026
- return typeof body === "string" ? body : null;
1113
+ const body2 = data?.body;
1114
+ return typeof body2 === "string" ? body2 : null;
1027
1115
  }
1028
1116
  async readColumn(name) {
1029
1117
  const { data, error } = await this.db.from("documents").select(name).eq("id", this.docId).maybeSingle();
@@ -1402,6 +1490,33 @@ var REQUEST_TIMEOUT_MS = 15e3;
1402
1490
  function loginApiBase() {
1403
1491
  return hubHttpBase();
1404
1492
  }
1493
+ function transportReason(e) {
1494
+ const seen = /* @__PURE__ */ new Set();
1495
+ const codes = [];
1496
+ const walk = (err) => {
1497
+ if (!err || typeof err !== "object" || seen.has(err)) return;
1498
+ seen.add(err);
1499
+ const code = err.code;
1500
+ if (typeof code === "string" && code && !codes.includes(code)) codes.push(code);
1501
+ const nested = err.errors;
1502
+ if (Array.isArray(nested)) for (const inner of nested) walk(inner);
1503
+ walk(err.cause);
1504
+ };
1505
+ walk(e);
1506
+ return codes.length > 0 ? codes.join(", ") : null;
1507
+ }
1508
+ function unreachable(apiBase, e) {
1509
+ let host = apiBase;
1510
+ try {
1511
+ host = new URL(apiBase).host;
1512
+ } catch {
1513
+ }
1514
+ const named = typeof e === "object" && e !== null ? e.name : void 0;
1515
+ const reason = transportReason(e) ?? // Our own REQUEST_TIMEOUT_MS cap: AbortSignal.timeout rejects with a DOMException that carries
1516
+ // a `name` but no `code`, so the walk above finds nothing to report.
1517
+ (named === "TimeoutError" ? `no response within ${REQUEST_TIMEOUT_MS / 1e3}s` : null) ?? (e instanceof Error && e.message ? e.message : e == null ? "unknown error" : String(e));
1518
+ return new Error(`could not reach ${host} (${reason})`);
1519
+ }
1405
1520
  function pendingLoginPath() {
1406
1521
  const base2 = process.env.INPLAN_HOME || join7(homedir5(), ".inplan");
1407
1522
  return join7(base2, "login-pending.json");
@@ -1481,7 +1596,12 @@ async function createLoginSession(opts = {}) {
1481
1596
  const keys = await subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, ["deriveBits"]);
1482
1597
  const pub = Buffer.from(await subtle.exportKey("spki", keys.publicKey)).toString("base64");
1483
1598
  const priv = Buffer.from(await subtle.exportKey("pkcs8", keys.privateKey)).toString("base64");
1484
- const res = await fetchImpl(`${apiBase}/api/v1/cli-login`, { method: "POST", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
1599
+ let res;
1600
+ try {
1601
+ res = await fetchImpl(`${apiBase}/api/v1/cli-login`, { method: "POST", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
1602
+ } catch (e) {
1603
+ throw unreachable(apiBase, e);
1604
+ }
1485
1605
  if (!res.ok) throw new Error(`could not start a sign-in session (HTTP ${res.status})`);
1486
1606
  const { sessionId, pollToken, expiresInSec } = await res.json();
1487
1607
  if (typeof sessionId !== "string" || !sessionId || typeof pollToken !== "string" || !pollToken) {
@@ -1583,17 +1703,17 @@ async function pollLoginSession(pending, opts = {}) {
1583
1703
  throw new LoginSessionExpiredError("the sign-in link expired \u2014 run the command again for a fresh one");
1584
1704
  }
1585
1705
  if (res.ok) {
1586
- let body;
1706
+ let body2;
1587
1707
  try {
1588
- body = await res.json();
1708
+ body2 = await res.json();
1589
1709
  } catch {
1590
1710
  await sleep(POLL_MS);
1591
1711
  continue;
1592
1712
  }
1593
- if (body.status === "completed" && body.epk && body.iv && body.ct) {
1713
+ if (body2.status === "completed" && body2.epk && body2.iv && body2.ct) {
1594
1714
  let auth;
1595
1715
  try {
1596
- auth = await unsealHandoff(pending.privateKeyPkcs8, { epk: body.epk, iv: body.iv, ct: body.ct });
1716
+ auth = await unsealHandoff(pending.privateKeyPkcs8, { epk: body2.epk, iv: body2.iv, ct: body2.ct });
1597
1717
  } catch {
1598
1718
  await clearPendingLoginFor(pending.sessionId);
1599
1719
  throw new LoginSessionExpiredError("the sign-in handoff could not be read \u2014 run the command again for a fresh link");
@@ -1601,7 +1721,7 @@ async function pollLoginSession(pending, opts = {}) {
1601
1721
  await clearPendingLoginFor(pending.sessionId);
1602
1722
  return auth;
1603
1723
  }
1604
- if (body.status === "opened" || body.status === "completed") sawOpened = true;
1724
+ if (body2.status === "opened" || body2.status === "completed") sawOpened = true;
1605
1725
  }
1606
1726
  await sleep(POLL_MS);
1607
1727
  }
@@ -2001,15 +2121,26 @@ var RemoteDocState = class {
2001
2121
 
2002
2122
  // src/applyEdit.ts
2003
2123
  async function applyGatedEdit(store, channel, ev, ctx) {
2004
- const { current, canonicalText, quarantine, gate } = ctx;
2124
+ const { current, canonicalText, quarantine, gate, onlyIfUnmoved } = ctx;
2125
+ const moved = async () => {
2126
+ if (!onlyIfUnmoved) return false;
2127
+ try {
2128
+ const [doc, canonical] = await Promise.all([store.loadDoc(), store.getCanonical()]);
2129
+ return doc !== current || canonical !== null && canonical !== canonicalText;
2130
+ } catch {
2131
+ return true;
2132
+ }
2133
+ };
2134
+ let withdrew = false;
2005
2135
  if (ev.removedIds.length > 0) {
2006
- if (gate) await gate.applyRevision(ev.acceptedText);
2136
+ let viaPlugin = false;
2137
+ if (gate) viaPlugin = await gate.applyRevision(ev.acceptedText) !== "local";
2007
2138
  else {
2008
2139
  await store.saveDoc(ev.acceptedText);
2009
2140
  await store.setCanonical(ev.acceptedText);
2010
- await withdrawOwnPending(store);
2141
+ withdrew = await withdrawOwnPending(store, canonicalText, ev.acceptedText);
2011
2142
  }
2012
- await channel.append({ actor: "agent", type: LogEventType.DocumentEdited, payload: { removed: ev.removedIds } });
2143
+ if (!await logEdit(channel, { removed: ev.removedIds }, viaPlugin)) return { proposed: false, eventLogged: false, ...withdrew ? { withdrew } : {} };
2013
2144
  } else if (ev.changed && quarantine) {
2014
2145
  let proposalId;
2015
2146
  try {
@@ -2036,28 +2167,61 @@ async function applyGatedEdit(store, channel, ev, ctx) {
2036
2167
  }
2037
2168
  return { proposed: true, proposalId };
2038
2169
  } else if (ev.changed) {
2039
- if (gate) await gate.applyRevision(current);
2170
+ if (await moved()) return { proposed: false, stale: true };
2171
+ let viaPlugin = false;
2172
+ if (gate) viaPlugin = await gate.applyRevision(current) !== "local";
2040
2173
  else {
2041
2174
  await store.setCanonical(current);
2042
- await withdrawOwnPending(store);
2175
+ withdrew = await withdrawOwnPending(store, canonicalText, current);
2043
2176
  }
2044
- await channel.append({ actor: "agent", type: LogEventType.DocumentEdited, payload: { bytes: utf8Bytes(current) } });
2177
+ if (!await logEdit(channel, { bytes: utf8Bytes(current) }, viaPlugin)) return { proposed: false, eventLogged: false, ...withdrew ? { withdrew } : {} };
2178
+ }
2179
+ return { proposed: false, ...withdrew ? { withdrew } : {} };
2180
+ }
2181
+ function shouldQuarantine(acceptance, canonicalText, current) {
2182
+ if (acceptance !== "review") return false;
2183
+ if (emptyDocument(canonicalText)) return false;
2184
+ return body(canonicalText) !== body(current);
2185
+ }
2186
+ function emptyDocument(text) {
2187
+ try {
2188
+ const doc = parse(text);
2189
+ return doc.body.trim() === "" && doc.comments.length === 0;
2190
+ } catch {
2191
+ return false;
2045
2192
  }
2046
- return { proposed: false };
2193
+ }
2194
+ function body(text) {
2195
+ try {
2196
+ return parse(text).body;
2197
+ } catch {
2198
+ return text;
2199
+ }
2200
+ }
2201
+ function emptyBody(text) {
2202
+ return isBlank(text);
2203
+ }
2204
+ function isBlank(text) {
2205
+ return body(text).trim() === "";
2047
2206
  }
2048
2207
  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);
2208
+ return isBlank(canonicalText) && !isBlank(current);
2209
+ }
2210
+ async function logEdit(channel, payload, viaPlugin) {
2211
+ payload = { ...payload, via: viaPlugin ? "plugin" : "file" };
2212
+ try {
2213
+ await channel.append({ actor: "agent", type: LogEventType.DocumentEdited, payload });
2214
+ return true;
2215
+ } catch {
2216
+ return false;
2217
+ }
2057
2218
  }
2058
- async function withdrawOwnPending(store) {
2219
+ async function withdrawOwnPending(store, _canonicalText, landed) {
2059
2220
  const mine = await store.myPendingProposal();
2060
- if (mine) await store.withdrawProposal(mine.id);
2221
+ if (!mine) return false;
2222
+ if (body(landed) !== body(mine.content)) return false;
2223
+ await store.withdrawProposal(mine.id);
2224
+ return true;
2061
2225
  }
2062
2226
 
2063
2227
  // src/gate.ts
@@ -2111,15 +2275,15 @@ function isQuestion(v) {
2111
2275
  const q = v;
2112
2276
  return typeof q.multiSelect === "boolean" && Array.isArray(q.choices) && q.choices.every(isChoice);
2113
2277
  }
2114
- function placeSpanLink(body, span, id) {
2115
- const first = body.indexOf(span);
2278
+ function placeSpanLink(body2, span, id) {
2279
+ const first = body2.indexOf(span);
2116
2280
  if (first === -1) throw new AddCommentError(`comment: --span text not found in the body: ${JSON.stringify(span)}`);
2117
- if (body.indexOf(span, first + span.length) !== -1) {
2281
+ if (body2.indexOf(span, first + span.length) !== -1) {
2118
2282
  throw new AddCommentError(
2119
2283
  `comment: --span text appears more than once in the body, so the target is ambiguous: ${JSON.stringify(span)}. Include more surrounding context to make it unique.`
2120
2284
  );
2121
2285
  }
2122
- return body.slice(0, first) + `[${span}](#${id})` + body.slice(first + span.length);
2286
+ return body2.slice(0, first) + `[${span}](#${id})` + body2.slice(first + span.length);
2123
2287
  }
2124
2288
  function addComment(currentText, input) {
2125
2289
  const targetCount = (input.parentId ? 1 : 0) + (input.doc ? 1 : 0) + (input.span ? 1 : 0);
@@ -2150,8 +2314,8 @@ function addComment(currentText, input) {
2150
2314
  ...input.question ? { question: input.question } : {},
2151
2315
  ...input.mayResolve ? { may_resolve: true } : {}
2152
2316
  };
2153
- const body = input.span ? placeSpanLink(doc.body, input.span, id) : doc.body;
2154
- const next = { body, comments: [...doc.comments, comment], version: doc.version };
2317
+ const body2 = input.span ? placeSpanLink(doc.body, input.span, id) : doc.body;
2318
+ const next = { body: body2, comments: [...doc.comments, comment], version: doc.version };
2155
2319
  const integrity = checkIntegrity(next);
2156
2320
  if (!integrity.ok) {
2157
2321
  throw new AddCommentError(
@@ -2193,6 +2357,7 @@ function trackGateDegradations(gate, localStore, onWriteError) {
2193
2357
  onWriteError?.(String(e));
2194
2358
  await localStore.setCanonical(md);
2195
2359
  await localStore.saveDoc(md);
2360
+ return "local";
2196
2361
  }
2197
2362
  }
2198
2363
  }
@@ -2299,6 +2464,7 @@ function announcePresence(docId, token, model) {
2299
2464
  // src/wait.ts
2300
2465
  var DEFAULT_ERROR_GRACE_MS = 5 * 6e4;
2301
2466
  var DEFAULT_POLL_TIMEOUT_MS = 3e4;
2467
+ var DEFAULT_HOOK_SETTLE_MS = 1e4;
2302
2468
  function inFlightGate() {
2303
2469
  let pending = 0;
2304
2470
  return {
@@ -2327,6 +2493,18 @@ async function withTimeout(p, ms) {
2327
2493
  if (timer) clearTimeout(timer);
2328
2494
  }
2329
2495
  }
2496
+ function onceAtATime(fn) {
2497
+ let busy = false;
2498
+ return async (...args) => {
2499
+ if (busy) return;
2500
+ busy = true;
2501
+ try {
2502
+ await fn(...args);
2503
+ } finally {
2504
+ busy = false;
2505
+ }
2506
+ };
2507
+ }
2330
2508
  var defaultActionable = (e) => e.actor === "user";
2331
2509
  function wakePredicate(wake) {
2332
2510
  return wake === "any-action" ? (e) => e.actor === "user" && e.type !== LogEventType.SettingsChanged : (e) => e.type === LogEventType.TurnEnded || e.type === LogEventType.SessionClosed || e.type === LogEventType.SaveLocallyRequested || e.type === LogEventType.NavigatedTo;
@@ -2402,6 +2580,7 @@ function waitForActions(opts) {
2402
2580
  const reads = inFlightGate();
2403
2581
  const locks = inFlightGate();
2404
2582
  const presences = inFlightGate();
2583
+ let pendingPoll = null;
2405
2584
  const cleanup = () => {
2406
2585
  clearInterval(timer);
2407
2586
  opts.signal?.removeEventListener("abort", onAbort);
@@ -2410,7 +2589,15 @@ function waitForActions(opts) {
2410
2589
  if (done) return;
2411
2590
  done = true;
2412
2591
  cleanup();
2413
- resolve4(r);
2592
+ if (pendingPoll) {
2593
+ let settleTimer;
2594
+ const out = () => {
2595
+ if (settleTimer) clearTimeout(settleTimer);
2596
+ resolve4(r);
2597
+ };
2598
+ settleTimer = setTimeout(out, opts.hookSettleMs ?? DEFAULT_HOOK_SETTLE_MS);
2599
+ void pendingPoll.then(out, out);
2600
+ } else resolve4(r);
2414
2601
  };
2415
2602
  const onAbort = () => {
2416
2603
  if (done) return;
@@ -2457,9 +2644,10 @@ function waitForActions(opts) {
2457
2644
  }
2458
2645
  }
2459
2646
  }
2460
- if (entries.some(isActionable)) {
2461
- if (entries.length !== lastCount) {
2462
- lastCount = entries.length;
2647
+ const actionable = entries.reduce((n, e) => isActionable(e) ? n + 1 : n, 0);
2648
+ if (actionable > 0) {
2649
+ if (actionable !== lastCount) {
2650
+ lastCount = actionable;
2463
2651
  deadline = Date.now() + debounceMs;
2464
2652
  } else if (deadline !== null && Date.now() >= deadline) {
2465
2653
  finish({ entries, cursor });
@@ -2476,9 +2664,26 @@ function waitForActions(opts) {
2476
2664
  busy = false;
2477
2665
  }
2478
2666
  };
2479
- const timer = setInterval(() => void tick(), pollMs);
2667
+ const onPoll = () => {
2668
+ if (pendingPoll || done || !opts.onPoll) return;
2669
+ const run = (async () => {
2670
+ try {
2671
+ await opts.onPoll();
2672
+ } catch {
2673
+ }
2674
+ })();
2675
+ pendingPoll = run;
2676
+ void run.finally(() => {
2677
+ if (pendingPoll === run) pendingPoll = null;
2678
+ });
2679
+ };
2680
+ const timer = setInterval(() => {
2681
+ void tick();
2682
+ onPoll();
2683
+ }, pollMs);
2480
2684
  opts.signal?.addEventListener("abort", onAbort);
2481
2685
  void tick();
2686
+ onPoll();
2482
2687
  });
2483
2688
  }
2484
2689
 
@@ -2714,6 +2919,21 @@ function spawnApp(file) {
2714
2919
  }
2715
2920
  return null;
2716
2921
  }
2922
+ function stampQuietly(text) {
2923
+ const doc = parse(text);
2924
+ const { comments } = stampImpossibleDates(doc.comments);
2925
+ return serialize({ ...doc, comments });
2926
+ }
2927
+ function stampAgentDates(text) {
2928
+ const doc = parse(text);
2929
+ const { comments, repaired } = stampImpossibleDates(doc.comments);
2930
+ if (repaired.length === 0) return text;
2931
+ process.stderr.write(
2932
+ `inplan: ${repaired.length} comment date(s) were absent or in the future and have been stamped from this machine's clock (${repaired.join(", ")}) \u2014 a date in the future sorts a reply after the replies that answered it.
2933
+ `
2934
+ );
2935
+ return serialize({ ...doc, comments });
2936
+ }
2717
2937
  function modeFrom(entries) {
2718
2938
  for (let i = entries.length - 1; i >= 0; i--) {
2719
2939
  if (entries[i].type === LogEventType.ModeChanged) {
@@ -2764,28 +2984,30 @@ function resolveWaitStatus(input) {
2764
2984
  if (input.editorGone) return { status: input.locksEditor ? "your_turn" : "activity", editorGone: true };
2765
2985
  return { status: input.locksEditor ? "your_turn" : "activity" };
2766
2986
  }
2767
- async function waitCycle(backend, explicitCursor, confirmed, model, gate = null) {
2987
+ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null, opts = {}) {
2768
2988
  const { channel, store } = backend;
2769
2989
  const history = await backend.history();
2770
2990
  const cursor = explicitCursor ?? (await channel.getCursor() || maxSeqFrom(history));
2771
- const current = await store.loadDoc();
2772
- let usePlugin = false;
2773
- let canonicalText;
2774
- if (gate) {
2775
- try {
2776
- canonicalText = await gate.readCanonical();
2777
- usePlugin = true;
2778
- } catch {
2779
- canonicalText = await store.getCanonical() ?? current;
2991
+ const rawDoc = await store.loadDoc();
2992
+ const current = stampAgentDates(rawDoc);
2993
+ const resolveCanonical = async (text) => {
2994
+ if (gate) {
2995
+ try {
2996
+ return { canonicalText: await gate.readCanonical(), usePlugin: true };
2997
+ } catch {
2998
+ return { canonicalText: await store.getCanonical() ?? text, usePlugin: false, gateFailed: true };
2999
+ }
2780
3000
  }
2781
- } else {
2782
3001
  const persisted = await store.getCanonical();
2783
- if (persisted === null) {
2784
- canonicalText = current;
2785
- await store.setCanonical(current);
2786
- } else {
2787
- canonicalText = persisted;
2788
- }
3002
+ if (persisted !== null) return { canonicalText: persisted, usePlugin: false };
3003
+ await store.setCanonical(text);
3004
+ return { canonicalText: text, usePlugin: false };
3005
+ };
3006
+ const { canonicalText, usePlugin } = await resolveCanonical(current);
3007
+ if (current !== rawDoc && !usePlugin) {
3008
+ await store.saveDoc(current);
3009
+ const persistedBase = await store.getCanonical();
3010
+ if (persistedBase !== null && stampQuietly(persistedBase) === current) await store.setCanonical(current);
2789
3011
  }
2790
3012
  const ev = evaluateAgentEdit(canonicalText, current, confirmed);
2791
3013
  if (ev.unconfirmed.length > 0) {
@@ -2802,19 +3024,28 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
2802
3024
  exitAfterFlush(2);
2803
3025
  return "exiting";
2804
3026
  }
2805
- const acceptance = acceptanceFrom(history);
2806
- const quarantine = acceptance === "review" && parse(canonicalText).body !== parse(current).body;
3027
+ const suspectEmptyBase = async (viaPlugin, base2) => {
3028
+ if (!viaPlugin || !emptyBody(base2)) return false;
3029
+ const remembered = await store.getCanonical().catch(() => null);
3030
+ return remembered !== null && !emptyBody(remembered);
3031
+ };
3032
+ const quarantine = await suspectEmptyBase(usePlugin, canonicalText) || shouldQuarantine(acceptanceFrom(history), canonicalText, current);
2807
3033
  const applied = await applyGatedEdit(store, channel, ev, { current, canonicalText, quarantine, gate: usePlugin ? gate : null });
2808
- if (applied.proposed) {
2809
- process.stderr.write(
2810
- 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"
2811
- );
2812
- }
2813
- if (applied.parkFailed) {
2814
- 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");
2815
- }
2816
- const parkFailedId = applied.parkFailed ? backend.localPendingProposalId?.() : void 0;
2817
- 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) } } : {};
3034
+ const UNANNOUNCED = "inplan: your edit WAS applied, but its notification event could not be logged (the control log is write-degraded) \u2014 the human's editor may not show it until they reload. The document itself is fine.\n";
3035
+ const reportApplied = (a, text) => {
3036
+ if (!a.proposed && a.eventLogged === false) process.stderr.write(UNANNOUNCED);
3037
+ if (a.proposed) {
3038
+ process.stderr.write(
3039
+ a.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"
3040
+ );
3041
+ }
3042
+ if (a.parkFailed) {
3043
+ 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");
3044
+ }
3045
+ const parkFailedId = a.parkFailed ? backend.localPendingProposalId?.() : void 0;
3046
+ return a.proposed ? { proposal: { state: "pending_review", ...a.proposalId ? { id: a.proposalId } : {}, bytes: utf8Bytes(text), hash: hashBody(text) } } : a.parkFailed ? { proposal: { state: "park_failed", ...parkFailedId ? { id: parkFailedId } : {}, bytes: utf8Bytes(text), hash: hashBody(text) } } : {};
3047
+ };
3048
+ let proposalOut = reportApplied(applied, current);
2818
3049
  try {
2819
3050
  await channel.append({ actor: "agent", type: LogEventType.AgentRevised });
2820
3051
  } catch {
@@ -2842,12 +3073,115 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
2842
3073
  const pollMs = Number(process.env.INPLAN_POLL_MS ?? 200);
2843
3074
  const errorGraceParsed = Number(process.env.INPLAN_ERROR_GRACE_MS);
2844
3075
  const errorGraceMs = process.env.INPLAN_ERROR_GRACE_MS && Number.isFinite(errorGraceParsed) && errorGraceParsed >= 0 ? errorGraceParsed : void 0;
3076
+ let gatedText = current;
3077
+ let gatedDisk = applied.proposed && !usePlugin ? canonicalText : ev.removedIds.length > 0 && !usePlugin ? ev.acceptedText : current;
3078
+ let settling = null;
3079
+ let lastDecline = null;
3080
+ let applyFailures = 0;
3081
+ let retryNotBefore = 0;
3082
+ const markGated = (text, disk = text) => {
3083
+ gatedText = text;
3084
+ gatedDisk = disk;
3085
+ };
3086
+ const liveFill = onceAtATime(async () => {
3087
+ let text;
3088
+ try {
3089
+ text = await store.loadDoc();
3090
+ } catch {
3091
+ return;
3092
+ }
3093
+ if (text === gatedText || text === gatedDisk) {
3094
+ settling = null;
3095
+ return;
3096
+ }
3097
+ if (Date.now() < retryNotBefore) return;
3098
+ if (settling !== text) {
3099
+ settling = text;
3100
+ return;
3101
+ }
3102
+ settling = null;
3103
+ const { canonicalText: base2, usePlugin: viaPlugin, gateFailed } = await resolveCanonical(text);
3104
+ if (gateFailed) return;
3105
+ let liveEv;
3106
+ try {
3107
+ liveEv = evaluateAgentEdit(base2, text, confirmed);
3108
+ } catch (e) {
3109
+ declined(`inplan: your edit's comment block could not be parsed, so it was NOT applied (${e.message}) \u2014 fix the document; the next wait reports it.
3110
+ `, text);
3111
+ return;
3112
+ }
3113
+ if (liveEv.unconfirmed.length > 0 || !liveEv.integrityOk) {
3114
+ declined(
3115
+ liveEv.unconfirmed.length > 0 ? "inplan: your edit removes anchored comment(s), so it was NOT applied while the human's turn is open \u2014 re-run wait with --confirmed-comment-deletion=<ids>.\n" : "inplan: your edit breaks the comment grammar, so it was NOT applied \u2014 fix the document; the next wait reports the errors.\n",
3116
+ text
3117
+ );
3118
+ return;
3119
+ }
3120
+ if (liveEv.removedIds.length > 0) {
3121
+ declined(
3122
+ "inplan: your edit removes anchored comment(s) you confirmed, so it was NOT applied mid-turn \u2014 it stays in the working copy, and the next wait applies it.\n",
3123
+ text
3124
+ );
3125
+ return;
3126
+ }
3127
+ if (await suspectEmptyBase(viaPlugin, base2) || shouldQuarantine(acceptanceFrom(await backend.history()), base2, text)) {
3128
+ declined(
3129
+ "inplan: your body revision is held for review, so it was NOT applied \u2014 it stays in the working copy exactly as you wrote it, and the NEXT `wait` you run (after this turn ends) proposes it to the human. Not a sync failure.\n",
3130
+ text
3131
+ );
3132
+ return;
3133
+ }
3134
+ lastDecline = null;
3135
+ try {
3136
+ if (await channel.isSuperseded(lockToken)) return;
3137
+ } catch {
3138
+ }
3139
+ try {
3140
+ if (await store.loadDoc() !== text) return;
3141
+ } catch {
3142
+ return;
3143
+ }
3144
+ let liveApplied;
3145
+ try {
3146
+ liveApplied = await applyGatedEdit(store, channel, liveEv, { current: text, canonicalText: base2, quarantine: false, gate: viaPlugin ? gate : null, onlyIfUnmoved: true });
3147
+ } catch (e) {
3148
+ applyFailures += 1;
3149
+ retryNotBefore = Date.now() + Math.min(3e4, 500 * 2 ** (applyFailures - 1));
3150
+ sayOnce(`inplan: your edit could not be applied (${e.message}) \u2014 it stays in the working copy and will be retried.
3151
+ `);
3152
+ return;
3153
+ }
3154
+ applyFailures = 0;
3155
+ retryNotBefore = 0;
3156
+ if (liveApplied.stale) return;
3157
+ if (liveApplied.eventLogged === false) process.stderr.write(UNANNOUNCED);
3158
+ if (liveApplied.withdrew) proposalOut = {};
3159
+ markGated(text);
3160
+ });
3161
+ function sayOnce(message) {
3162
+ if (lastDecline === message) return;
3163
+ lastDecline = message;
3164
+ process.stderr.write(message);
3165
+ }
3166
+ function declined(message, text) {
3167
+ sayOnce(message);
3168
+ markGated(text);
3169
+ }
2845
3170
  let waitCursor = cursor;
2846
3171
  let historyForMode = history;
2847
3172
  for (; ; ) {
2848
3173
  const mode = modeFrom(historyForMode);
2849
3174
  const isActionable = wakePredicate(mode.wake);
2850
- const result = await waitForActions({ channel, cursor: waitCursor, debounceMs, pollMs, isActionable, token: lockToken, ...errorGraceMs !== void 0 ? { errorGraceMs } : {} });
3175
+ const result = await waitForActions({
3176
+ channel,
3177
+ cursor: waitCursor,
3178
+ debounceMs,
3179
+ pollMs,
3180
+ isActionable,
3181
+ token: lockToken,
3182
+ ...errorGraceMs !== void 0 ? { errorGraceMs } : {},
3183
+ ...opts.liveFill ? { onPoll: liveFill } : {}
3184
+ });
2851
3185
  if (result.failed) {
2852
3186
  backend.logExit("poll_failed");
2853
3187
  process.stderr.write(`inplan: lost contact with the document (${result.failed.message}).
@@ -3415,14 +3749,14 @@ async function runRemote(cmd, docId, explicitCursor, confirmed, rest, localFile,
3415
3749
  }
3416
3750
  };
3417
3751
  const onSaveLocallyGate = localFile ? async (info) => {
3418
- const body = await gate.readCanonical();
3752
+ const body2 = await gate.readCanonical();
3419
3753
  const leftover = rds.readWorkFile();
3420
- if (leftover !== null && hashBody(leftover) !== (rds.hydrateInput().syncedHash ?? "") && parse(leftover).body !== parse(body).body) {
3754
+ if (leftover !== null && hashBody(leftover) !== (rds.hydrateInput().syncedHash ?? "") && parse(leftover).body !== parse(body2).body) {
3421
3755
  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.
3422
3756
  `);
3423
3757
  }
3424
- writeFileSync10(localFile, body);
3425
- writeStatus(docPaths(localFile).statusPath, { location: "local", originalPath: localFile, lastSyncedHash: hashBody(body) });
3758
+ writeFileSync10(localFile, body2);
3759
+ writeStatus(docPaths(localFile).statusPath, { location: "local", originalPath: localFile, lastSyncedHash: hashBody(body2) });
3426
3760
  const pid = spawnApp(localFile);
3427
3761
  output({ status: "moved_local", path: localFile, reopened: pid !== null, ...info });
3428
3762
  } : void 0;
@@ -3485,8 +3819,8 @@ function doPromote(file, args) {
3485
3819
  process.stderr.write("usage: inplan promote <file> --cloud-doc <docId> [--locator org/repo/path]\n");
3486
3820
  process.exit(64);
3487
3821
  }
3488
- const body = existsSync11(file) ? readFileSync11(file, "utf8") : "";
3489
- const status = { location: "cloud", cloudDocId, originalPath: file, lastSyncedHash: hashBody(body) };
3822
+ const body2 = existsSync11(file) ? readFileSync11(file, "utf8") : "";
3823
+ const status = { location: "cloud", cloudDocId, originalPath: file, lastSyncedHash: hashBody(body2) };
3490
3824
  const locator = getFlag(args, "locator");
3491
3825
  if (locator) {
3492
3826
  const [org, repo, ...rest] = locator.split("/");
@@ -3529,13 +3863,14 @@ async function doDemote(file, args) {
3529
3863
  exitAfterFlush(EXIT_PLUGIN_UNAVAILABLE);
3530
3864
  return;
3531
3865
  }
3532
- const body = choice.use === "hub" ? hubBody : await backend.store.loadDoc();
3533
- writeFileSync10(dest, body);
3534
- writeStatus(p.statusPath, { location: "local", originalPath: dest, lastSyncedHash: hashBody(body) });
3866
+ const body2 = choice.use === "hub" ? hubBody : await backend.store.loadDoc();
3867
+ writeFileSync10(dest, body2);
3868
+ writeStatus(p.statusPath, { location: "local", originalPath: dest, lastSyncedHash: hashBody(body2) });
3535
3869
  output({ status: "demoted", location: "local", path: dest, source: choice.use });
3536
3870
  }
3537
- function firstHeading(body) {
3538
- return body.match(/^#\s+(.+?)\s*$/m)?.[1]?.trim() || null;
3871
+ function firstHeading(body2) {
3872
+ const heading = body2.match(/^#\s+(.+?)\s*$/m)?.[1];
3873
+ return heading ? stripAnchors(heading).trim() || null : null;
3539
3874
  }
3540
3875
  async function doWhoami() {
3541
3876
  const user = await currentUser();
@@ -3983,17 +4318,17 @@ async function doUpload(file, args) {
3983
4318
  process.exit(1);
3984
4319
  }
3985
4320
  const org = orgOf(pick);
3986
- const body = existsSync11(file) ? readFileSync11(file, "utf8") : "";
4321
+ const body2 = existsSync11(file) ? readFileSync11(file, "utf8") : "";
3987
4322
  const prov = gitProvenance(file);
3988
4323
  const repo = getFlag(args, "repo") ?? prov.repo;
3989
4324
  const path = getFlag(args, "path") ?? prov.path;
3990
- const title = firstHeading(body) ?? basename3(path);
4325
+ const title = firstHeading(body2) ?? basename3(path);
3991
4326
  const { data: res, error: de } = await s.db.rpc("create_document", {
3992
4327
  p_org: pick.org_id,
3993
4328
  p_repo: repo,
3994
4329
  p_path: path,
3995
4330
  p_title: title,
3996
- p_body: body,
4331
+ p_body: body2,
3997
4332
  p_draft_pending: false,
3998
4333
  p_evict_lru: hasFlag(args, "evict-lru")
3999
4334
  });
@@ -4022,12 +4357,12 @@ async function doUpload(file, args) {
4022
4357
  process.stderr.write("inplan upload: could not create the cloud document\n");
4023
4358
  process.exit(1);
4024
4359
  }
4025
- let finalBody = body;
4360
+ let finalBody = body2;
4026
4361
  if (out0.status === "created") {
4027
4362
  try {
4028
- const migrated = await migrateLocalImages(body, dirname11(file), s.db, pick.org_id, cloudDocId);
4363
+ const migrated = await migrateLocalImages(body2, dirname11(file), s.db, pick.org_id, cloudDocId);
4029
4364
  if (migrated.migrated > 0) {
4030
- 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");
4365
+ 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", body2).select("id");
4031
4366
  if (updateErr) {
4032
4367
  await cleanupOrphanedUploads(s.db, migrated.uploadedPaths);
4033
4368
  throw new Error(`cloud write failed: ${updateErr.message}`);
@@ -4039,7 +4374,7 @@ async function doUpload(file, args) {
4039
4374
  );
4040
4375
  }
4041
4376
  const onDiskNow = existsSync11(file) ? readFileSync11(file, "utf8") : null;
4042
- if (onDiskNow !== null && onDiskNow !== body) {
4377
+ if (onDiskNow !== null && onDiskNow !== body2) {
4043
4378
  finalBody = onDiskNow;
4044
4379
  throw new Error(
4045
4380
  "the local file changed while migrating images, so it was left untouched to avoid discarding those edits \u2014 the cloud copy already has the migrated image links; open this doc in the editor to reconcile"
@@ -4049,7 +4384,7 @@ async function doUpload(file, args) {
4049
4384
  writeFileSync10(file, migrated.body);
4050
4385
  finalBody = migrated.body;
4051
4386
  } catch (e) {
4052
- finalBody = existsSync11(file) ? readFileSync11(file, "utf8") : body;
4387
+ finalBody = existsSync11(file) ? readFileSync11(file, "utf8") : body2;
4053
4388
  throw new Error(
4054
4389
  `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`
4055
4390
  );
@@ -4148,14 +4483,14 @@ var IMAGE_REF_RE = /!\[([^\]]*)\]\(\s*(?:<([^>]+)>|([^()\s]+))\s*\)/g;
4148
4483
  function isLocalRelativePath(dest) {
4149
4484
  return !/^[a-z][a-z0-9+.-]*:/i.test(dest) && !dest.startsWith("//") && !dest.startsWith("/");
4150
4485
  }
4151
- function codeRanges(body) {
4486
+ function codeRanges(body2) {
4152
4487
  const ranges = [];
4153
4488
  const fenceRe = /^(`{3,}|~{3,})/;
4154
4489
  let offset = 0;
4155
4490
  let fenceChar = null;
4156
4491
  let fenceLen = 0;
4157
4492
  let fenceStart = 0;
4158
- for (const line of body.split("\n")) {
4493
+ for (const line of body2.split("\n")) {
4159
4494
  const m = fenceRe.exec(line.trimStart());
4160
4495
  if (fenceChar) {
4161
4496
  if (m && m[1][0] === fenceChar && m[1].length >= fenceLen) {
@@ -4169,8 +4504,8 @@ function codeRanges(body) {
4169
4504
  }
4170
4505
  offset += line.length + 1;
4171
4506
  }
4172
- if (fenceChar) ranges.push([fenceStart, body.length]);
4173
- for (const m of body.matchAll(/`[^`\n]*`/g)) ranges.push([m.index, m.index + m[0].length]);
4507
+ if (fenceChar) ranges.push([fenceStart, body2.length]);
4508
+ for (const m of body2.matchAll(/`[^`\n]*`/g)) ranges.push([m.index, m.index + m[0].length]);
4174
4509
  return ranges;
4175
4510
  }
4176
4511
  function inRange(ranges, index) {
@@ -4192,8 +4527,8 @@ async function rememberAsset(db, docId, sha256, ext, objectPath) {
4192
4527
  } catch {
4193
4528
  }
4194
4529
  }
4195
- async function migrateLocalImages(body, docDir, db, orgId, docId) {
4196
- const excluded = codeRanges(body);
4530
+ async function migrateLocalImages(body2, docDir, db, orgId, docId) {
4531
+ const excluded = codeRanges(body2);
4197
4532
  const migrations = /* @__PURE__ */ new Map();
4198
4533
  const uploadedByDest = /* @__PURE__ */ new Map();
4199
4534
  const uploadedByHash = /* @__PURE__ */ new Map();
@@ -4202,9 +4537,9 @@ async function migrateLocalImages(body, docDir, db, orgId, docId) {
4202
4537
  try {
4203
4538
  docDirReal = realpathSync(docDir);
4204
4539
  } catch {
4205
- return { body, migrated: 0, uploadedPaths };
4540
+ return { body: body2, migrated: 0, uploadedPaths };
4206
4541
  }
4207
- for (const m of body.matchAll(IMAGE_REF_RE)) {
4542
+ for (const m of body2.matchAll(IMAGE_REF_RE)) {
4208
4543
  const dest = m[2] ?? m[3] ?? "";
4209
4544
  if (!dest || inRange(excluded, m.index) || !isLocalRelativePath(dest)) continue;
4210
4545
  const cached = uploadedByDest.get(dest);
@@ -4254,16 +4589,16 @@ async function migrateLocalImages(body, docDir, db, orgId, docId) {
4254
4589
  uploadedPaths.push(uploaded.path);
4255
4590
  migrations.set(m.index, { dest, url: uploaded.url });
4256
4591
  }
4257
- if (migrations.size === 0) return { body, migrated: 0, uploadedPaths };
4592
+ if (migrations.size === 0) return { body: body2, migrated: 0, uploadedPaths };
4258
4593
  let newBody = "";
4259
4594
  let cursor = 0;
4260
- for (const m of body.matchAll(IMAGE_REF_RE)) {
4595
+ for (const m of body2.matchAll(IMAGE_REF_RE)) {
4261
4596
  const hit = migrations.get(m.index);
4262
- newBody += body.slice(cursor, m.index);
4597
+ newBody += body2.slice(cursor, m.index);
4263
4598
  newBody += hit ? `![${m[1]}](${hit.url})` : m[0];
4264
4599
  cursor = m.index + m[0].length;
4265
4600
  }
4266
- newBody += body.slice(cursor);
4601
+ newBody += body2.slice(cursor);
4267
4602
  return { body: newBody, migrated: migrations.size, uploadedPaths };
4268
4603
  }
4269
4604
  function rejectCommentOnCloud(cmd, hasLocalFile) {
@@ -4478,9 +4813,10 @@ async function main() {
4478
4813
  return;
4479
4814
  }
4480
4815
  if (cmd === "open") {
4481
- ensureDocFile(file);
4816
+ const created = ensureDocFile(file);
4482
4817
  const p = docPaths(file);
4483
4818
  mkdirSync10(p.controlDir, { recursive: true });
4819
+ if (created && model) await new FsControlChannel(p).append({ actor: "agent", type: LogEventType.DraftPending, payload: { model } });
4484
4820
  const st = readStatus(p.statusPath);
4485
4821
  if (st.location !== "cloud") writeStatus(p.statusPath, { ...st, location: "local", originalPath: file });
4486
4822
  const existing = runningEditorPid(p.logPath);
@@ -4500,7 +4836,7 @@ async function main() {
4500
4836
  const session = await authedSession();
4501
4837
  gate = await loadPluginGate(pluginSession, { token: session?.session.access_token ?? null });
4502
4838
  }
4503
- await waitCycle(fsBackend(file), explicitCursor, confirmed, model, gate);
4839
+ await waitCycle(fsBackend(file), explicitCursor, confirmed, model, gate, { liveFill: true });
4504
4840
  }
4505
4841
  function isProgramEntry() {
4506
4842
  const argv1 = process.argv[1];
@@ -4512,6 +4848,7 @@ function isProgramEntry() {
4512
4848
  }
4513
4849
  }
4514
4850
  if (isProgramEntry()) {
4851
+ widenConnectAttemptBudget();
4515
4852
  let exitingForUnhandledRejection = false;
4516
4853
  process.on("unhandledRejection", (reason) => {
4517
4854
  if (exitingForUnhandledRejection) return;
@@ -4545,6 +4882,7 @@ export {
4545
4882
  ensureLoggedIn,
4546
4883
  exitAfterFlush,
4547
4884
  explainNoGate,
4885
+ firstHeading,
4548
4886
  isKnownAgentEnv,
4549
4887
  main,
4550
4888
  notesFromHook,