inplan 0.1.30 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -109,6 +109,12 @@ function parseLogLine(line) {
109
109
  function parseLog(text) {
110
110
  return text.split("\n").map((l) => l.trim()).filter((l) => l.length > 0).map(parseLogLine);
111
111
  }
112
+ function mintProposalId() {
113
+ const c = globalThis.crypto;
114
+ if (c?.randomUUID) return c.randomUUID();
115
+ const hex = (n) => Math.floor(Math.random() * n).toString(16);
116
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (ch) => ch === "x" ? hex(16) : (Math.floor(Math.random() * 4) + 8).toString(16));
117
+ }
112
118
  function readLog(path2) {
113
119
  if (!fs.existsSync(path2)) return [];
114
120
  return parseLog(fs.readFileSync(path2, "utf8"));
@@ -145,6 +151,7 @@ function appendLog(path2, entry) {
145
151
  fs.appendFileSync(path2, serializeLogEntry(full) + "\n");
146
152
  return full;
147
153
  }
154
+ var MAX_BACKUPS$1 = 25;
148
155
  function isProcessAlive(pid) {
149
156
  try {
150
157
  process.kill(pid, 0);
@@ -231,6 +238,201 @@ var FsControlChannel = class {
231
238
  return Promise.resolve(false);
232
239
  }
233
240
  };
241
+ var FsDocumentStore = class _FsDocumentStore {
242
+ constructor(paths) {
243
+ this.paths = paths;
244
+ }
245
+ paths;
246
+ readOrNull(path2) {
247
+ return fs.existsSync(path2) ? fs.readFileSync(path2, "utf8") : null;
248
+ }
249
+ loadDoc() {
250
+ return Promise.resolve(fs.readFileSync(this.paths.file, "utf8"));
251
+ }
252
+ saveDoc(content) {
253
+ fs.writeFileSync(this.paths.file, content);
254
+ return Promise.resolve();
255
+ }
256
+ getCanonical() {
257
+ return Promise.resolve(this.readOrNull(this.paths.canonicalPath));
258
+ }
259
+ setCanonical(content) {
260
+ fs.writeFileSync(this.paths.canonicalPath, content);
261
+ return Promise.resolve();
262
+ }
263
+ // Proposal rows live in a JSON file beside the other sidecars; `proposedPath` stays as a
264
+ // derived copy of the CURRENT pending content (readable at a glance, and what pre-rows code
265
+ // wrote). A single local proposer, so "mine" is unqualified.
266
+ proposalsPath() {
267
+ return `${this.paths.proposedPath}.rows.json`;
268
+ }
269
+ /** Whether row-backed proposal state exists for this doc at all (vs the legacy content file). */
270
+ hasProposalHistory() {
271
+ return fs.existsSync(this.proposalsPath());
272
+ }
273
+ static STATES = /* @__PURE__ */ new Set(["pending", "accepted", "partially_accepted", "rejected", "superseded", "withdrawn"]);
274
+ static isValidRow(r) {
275
+ const x = r;
276
+ 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";
277
+ }
278
+ readRows() {
279
+ const raw = this.readOrNull(this.proposalsPath());
280
+ if (raw === null) return [];
281
+ try {
282
+ const rows = JSON.parse(raw);
283
+ if (Array.isArray(rows) && rows.every((r) => _FsDocumentStore.isValidRow(r))) return rows;
284
+ } catch {
285
+ }
286
+ fs.renameSync(this.proposalsPath(), `${this.proposalsPath()}.corrupt-${Date.now()}`);
287
+ return [];
288
+ }
289
+ /**
290
+ * Advisory per-doc lock around every read-modify-publish of the rows file: the desktop editor
291
+ * (main process) and a CLI can share one sidecar, and interleaved mutations would lose a
292
+ * lifecycle update. mkdir is the atomic primitive; a stale lock (a crashed holder) is broken
293
+ * after 2s. Mutations here are a few file ops — well under the staleness window.
294
+ *
295
+ * Async: contention waits are AWAITED sleeps, never a synchronous spin — the desktop editor
296
+ * calls this on Electron's main thread, where a sync busy-wait under a held lock froze the
297
+ * whole UI for up to the 2s deadline. The semantics are unchanged (owner token, ~2s deadline,
298
+ * atomic take-by-rename release, quarantine behavior); only the wait yields the event loop.
299
+ */
300
+ async withRowsLock(run) {
301
+ const lockDir = `${this.proposalsPath()}.lock`;
302
+ const ownerPath = path.join(lockDir, "owner");
303
+ const token = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
304
+ const deadline = Date.now() + 2e3;
305
+ for (; ; ) {
306
+ try {
307
+ fs.mkdirSync(lockDir);
308
+ fs.writeFileSync(ownerPath, token);
309
+ break;
310
+ } catch {
311
+ let stale = false;
312
+ try {
313
+ stale = Date.now() - fs.statSync(lockDir).mtime.getTime() > 2e3;
314
+ } catch {
315
+ continue;
316
+ }
317
+ if (stale) {
318
+ try {
319
+ fs.rmSync(lockDir, { recursive: true, force: true });
320
+ } catch {
321
+ }
322
+ continue;
323
+ }
324
+ if (Date.now() > deadline) throw new Error(`proposal rows lock is held: ${lockDir}`);
325
+ await new Promise((resolve3) => setTimeout(resolve3, 25));
326
+ }
327
+ }
328
+ try {
329
+ return run();
330
+ } finally {
331
+ const releasing = `${lockDir}.releasing-${token}`;
332
+ try {
333
+ fs.renameSync(lockDir, releasing);
334
+ if (fs.readFileSync(path.join(releasing, "owner"), "utf8") === token) {
335
+ fs.rmSync(releasing, { recursive: true, force: true });
336
+ } else {
337
+ try {
338
+ fs.renameSync(releasing, lockDir);
339
+ } catch {
340
+ fs.rmSync(releasing, { recursive: true, force: true });
341
+ }
342
+ }
343
+ } catch {
344
+ }
345
+ }
346
+ }
347
+ writeRows(rows) {
348
+ const tmp = `${this.proposalsPath()}.tmp`;
349
+ fs.writeFileSync(tmp, JSON.stringify(rows, null, 2));
350
+ fs.renameSync(tmp, this.proposalsPath());
351
+ const pending = rows.find((r) => r.state === "pending");
352
+ try {
353
+ if (pending) fs.writeFileSync(this.paths.proposedPath, pending.content);
354
+ else if (fs.existsSync(this.paths.proposedPath)) fs.unlinkSync(this.paths.proposedPath);
355
+ } catch {
356
+ }
357
+ }
358
+ async createProposal(input) {
359
+ return this.withRowsLock(() => {
360
+ const rows = this.readRowsAdoptingLegacy();
361
+ const pendingSame = input.id ? void 0 : rows.find((r) => r.state === "pending" && r.content === input.content);
362
+ const id = input.id ?? pendingSame?.id ?? mintProposalId();
363
+ const existing = rows.find((r) => r.id === id);
364
+ if (existing) {
365
+ if (existing.state === "pending") Object.assign(existing, { content: input.content, baseHash: input.baseHash, baseContent: input.baseContent });
366
+ } else {
367
+ for (const r of rows) if (r.state === "pending") r.state = "superseded";
368
+ rows.push({ id, content: input.content, baseHash: input.baseHash, baseContent: input.baseContent, state: "pending", createdAt: (/* @__PURE__ */ new Date()).toISOString() });
369
+ }
370
+ this.writeRows(rows);
371
+ return { id };
372
+ });
373
+ }
374
+ /** Rows, adopting a legacy pre-rows sidecar exactly once: a `proposedPath` content file with no
375
+ * rows file is an old park — it becomes a real pending row (minted id) so the full lifecycle
376
+ * (withdraw/decide/supersede) applies to it instead of the file lingering forever. */
377
+ readRowsAdoptingLegacy() {
378
+ const rows = this.readRows();
379
+ if (rows.length > 0 || this.hasProposalHistory()) return rows;
380
+ const legacy = this.readOrNull(this.paths.proposedPath);
381
+ if (legacy === null) return rows;
382
+ return [{ id: mintProposalId(), content: legacy, baseHash: "", baseContent: "", state: "pending", createdAt: (/* @__PURE__ */ new Date()).toISOString() }];
383
+ }
384
+ async myPendingProposal() {
385
+ return this.withRowsLock(() => {
386
+ const rows = this.readRowsAdoptingLegacy();
387
+ const pending = rows.find((r) => r.state === "pending") ?? null;
388
+ if (pending && !this.hasProposalHistory()) this.writeRows(rows);
389
+ return pending;
390
+ });
391
+ }
392
+ async getProposal(id) {
393
+ return this.withRowsLock(() => this.readRows().find((r) => r.id === id) ?? null);
394
+ }
395
+ async withdrawProposal(id) {
396
+ await this.withRowsLock(() => {
397
+ const rows = this.readRowsAdoptingLegacy();
398
+ const r = rows.find((x) => x.id === id);
399
+ if (r && r.state === "pending") {
400
+ r.state = "withdrawn";
401
+ this.writeRows(rows);
402
+ }
403
+ });
404
+ }
405
+ async decideProposal(id, state2) {
406
+ return this.withRowsLock(() => {
407
+ const rows = this.readRowsAdoptingLegacy();
408
+ const r = rows.find((x) => x.id === id);
409
+ if (r && r.state === "pending") {
410
+ r.state = state2;
411
+ r.decidedAt = (/* @__PURE__ */ new Date()).toISOString();
412
+ this.writeRows(rows);
413
+ return { transitioned: true };
414
+ }
415
+ return { transitioned: false };
416
+ });
417
+ }
418
+ backup(content) {
419
+ fs.mkdirSync(this.paths.backupsDir, { recursive: true });
420
+ const seqs = this.backupSeqs();
421
+ const next = (seqs.at(-1) ?? 0) + 1;
422
+ fs.writeFileSync(path.join(this.paths.backupsDir, `autosave-${next}.md`), content);
423
+ for (const n of seqs.slice(0, Math.max(0, seqs.length + 1 - MAX_BACKUPS$1))) {
424
+ try {
425
+ fs.unlinkSync(path.join(this.paths.backupsDir, `autosave-${n}.md`));
426
+ } catch {
427
+ }
428
+ }
429
+ return Promise.resolve();
430
+ }
431
+ backupSeqs() {
432
+ if (!fs.existsSync(this.paths.backupsDir)) return [];
433
+ return fs.readdirSync(this.paths.backupsDir).map((name) => /^autosave-(\d+)\.md$/.exec(name)?.[1]).filter((n) => n != null).map(Number).sort((a, b) => a - b);
434
+ }
435
+ };
234
436
  function sidecarRoot() {
235
437
  if (process.env.INPLAN_SIDECAR_DIR) return process.env.INPLAN_SIDECAR_DIR;
236
438
  const home = process.env.INPLAN_HOME || path.join(os.homedir(), ".inplan");
@@ -477,12 +679,23 @@ class Session {
477
679
  }
478
680
  }
479
681
  }
480
- load() {
682
+ async load() {
481
683
  const content = node_fs.readFileSync(this.paths.file, "utf8");
482
684
  if (!node_fs.existsSync(this.paths.canonicalPath)) {
483
685
  node_fs.writeFileSync(this.paths.canonicalPath, content);
686
+ return { path: this.paths.file, content };
687
+ }
688
+ let pending;
689
+ try {
690
+ pending = await this.pendingProposal();
691
+ } catch {
692
+ pending = null;
693
+ }
694
+ const current = node_fs.readFileSync(this.paths.file, "utf8");
695
+ if (pending !== null && pending.content === current) {
696
+ return { path: this.paths.file, content: node_fs.readFileSync(this.paths.canonicalPath, "utf8") };
484
697
  }
485
- return { path: this.paths.file, content };
698
+ return { path: this.paths.file, content: current };
486
699
  }
487
700
  save(content, options) {
488
701
  if (options.kind === "backup") {
@@ -527,13 +740,45 @@ class Session {
527
740
  this.pendingDirty = false;
528
741
  this.pendingContent = content;
529
742
  }
530
- /** The parked Review-mode proposal, if one is pending (the file exists ⇔ undecided). */
531
- pendingProposal() {
532
- return node_fs.existsSync(this.paths.proposedPath) ? node_fs.readFileSync(this.paths.proposedPath, "utf8") : null;
533
- }
534
- /** Discard the parked proposal once the human has accepted/rejected it. */
535
- clearProposal() {
536
- if (node_fs.existsSync(this.paths.proposedPath)) node_fs.unlinkSync(this.paths.proposedPath);
743
+ /** An ADOPTED legacy row (a pre-rows proposed.md, baseHash "" sentinel) has no real base:
744
+ * surfacing its empty baseContent would read as "written against an empty document" and put
745
+ * the renderer on a false stale-merge path — omit the queue fields and let review degrade to
746
+ * the documented legacy single-proposal flow. */
747
+ proposalPayload(row) {
748
+ return row.baseHash === "" ? { id: row.id, content: row.content } : { id: row.id, content: row.content, baseContent: row.baseContent, pending: 1 };
749
+ }
750
+ /** The parked Review-mode proposal, if one is pending. Row-backed (proposals v1) with a
751
+ * legacy fallback to the derived content file (a pre-rows sidecar). The base rides along for
752
+ * stale-proposal review (3-way merge); the desktop queue is the single local agent's own
753
+ * pending row, so `pending` is 1 whenever a proposal exists. */
754
+ async pendingProposal() {
755
+ const store = new FsDocumentStore(this.paths);
756
+ const mine = await store.myPendingProposal();
757
+ if (mine) return this.proposalPayload(mine);
758
+ if (store.hasProposalHistory()) return null;
759
+ if (!node_fs.existsSync(this.paths.proposedPath)) return null;
760
+ const raced = await store.myPendingProposal();
761
+ if (raced) return this.proposalPayload(raced);
762
+ return node_fs.existsSync(this.paths.proposedPath) ? { content: node_fs.readFileSync(this.paths.proposedPath, "utf8") } : null;
763
+ }
764
+ /** Settle the parked proposal once the human has decided — the outcome lands on the proposal
765
+ * row (proposals v1); the derived proposedPath file is cleared by the store. Legacy fallback:
766
+ * a stray content file with no row is simply removed. */
767
+ async clearProposal(outcome = "accepted", id) {
768
+ if (outcome !== "accepted" && outcome !== "partially_accepted" && outcome !== "rejected") {
769
+ throw new Error(`invalid proposal outcome: ${String(outcome)}`);
770
+ }
771
+ const store = new FsDocumentStore(this.paths);
772
+ const mine = await store.myPendingProposal();
773
+ const target = id ?? mine?.id;
774
+ if (target) {
775
+ const { transitioned } = await store.decideProposal(target, outcome);
776
+ if (!transitioned) throw new Error(`proposal ${target} was decided elsewhere`);
777
+ } else if (!store.hasProposalHistory() && node_fs.existsSync(this.paths.proposedPath)) {
778
+ node_fs.unlinkSync(this.paths.proposedPath);
779
+ } else {
780
+ throw new Error("no pending proposal to settle (it was decided or withdrawn elsewhere)");
781
+ }
537
782
  }
538
783
  /** Record why the session ended (logged at most once) so the agent's `wait` can report it. */
539
784
  logClose(reason) {
@@ -579,8 +824,11 @@ class Session {
579
824
  }
580
825
  }
581
826
  if (entries.some((e) => e.type === LogEventType.AgentRevisionProposed)) {
582
- const proposed = this.pendingProposal();
583
- if (proposed != null) handlers.onProposal(proposed);
827
+ void this.pendingProposal().then((proposed) => {
828
+ if (proposed != null) handlers.onProposal(proposed.content, proposed.id, proposed.baseContent, proposed.pending, this.paths.file);
829
+ }).catch((e) => {
830
+ console.warn("inplan: could not read the pending proposal for review dispatch:", e);
831
+ });
584
832
  }
585
833
  if (entries.some((e) => e.actor === "agent" && e.type === LogEventType.DocumentEdited) && node_fs.existsSync(this.paths.file)) {
586
834
  try {
@@ -1054,7 +1302,7 @@ function watchSession() {
1054
1302
  onExternalChange: (content) => win?.webContents.send("doc:external-change", { path: s.paths.file, content }),
1055
1303
  onAgentDone: () => win?.webContents.send("agent:done"),
1056
1304
  onAgentActive: () => win?.webContents.send("agent:active"),
1057
- onProposal: (content) => win?.webContents.send("doc:proposal", { content }),
1305
+ onProposal: (content, id, baseContent, pending, path2) => win?.webContents.send("doc:proposal", { content, ...id ? { id } : {}, ...baseContent !== void 0 ? { baseContent } : {}, ...pending !== void 0 ? { pending } : {}, ...path2 !== void 0 ? { path: path2 } : {} }),
1058
1306
  onReload: () => win?.webContents.send("agent:reload"),
1059
1307
  onAgentMessage: (text, ts) => win?.webContents.send("agent:message", { text, ts })
1060
1308
  });
@@ -1087,11 +1335,16 @@ function navigateTo(file) {
1087
1335
  return true;
1088
1336
  }
1089
1337
  async function refreshPluginAndView(file) {
1338
+ const forSession = session;
1090
1339
  await stopDesktopPlugin();
1091
1340
  await startDesktopPlugin(file, pluginToken);
1092
- if (!win || !session) return;
1341
+ if (!win || !session || session !== forSession) return;
1093
1342
  if (pluginInfo()) win.webContents.send("plugin:reactivate");
1094
- else win.webContents.send("doc:navigated", session.load());
1343
+ else {
1344
+ const payload = await session.load();
1345
+ if (!win || session !== forSession) return;
1346
+ win.webContents.send("doc:navigated", payload);
1347
+ }
1095
1348
  }
1096
1349
  function quitNow(reason) {
1097
1350
  if (session?.hasUnsaved) session.complete(session.pending);
@@ -1200,10 +1453,8 @@ function registerIpc() {
1200
1453
  quitConfirmed = true;
1201
1454
  win?.close();
1202
1455
  });
1203
- electron.ipcMain.handle("proposal:get", () => session?.pendingProposal() ?? null);
1204
- electron.ipcMain.handle("proposal:clear", () => {
1205
- session?.clearProposal();
1206
- });
1456
+ electron.ipcMain.handle("proposal:get", async () => await session?.pendingProposal() ?? null);
1457
+ electron.ipcMain.handle("proposal:clear", (_e, outcome, id) => session?.clearProposal(outcome, id));
1207
1458
  const toPosix = (s) => s.replace(/\\/g, "/");
1208
1459
  electron.ipcMain.handle("newdoc:pick", async (_e, suggestedName) => {
1209
1460
  if (!session || !win) return null;
@@ -93,7 +93,7 @@ const api = {
93
93
  },
94
94
  closeWindow: () => ipcRenderer.invoke("window:close"),
95
95
  getProposal: () => ipcRenderer.invoke("proposal:get"),
96
- clearProposal: () => ipcRenderer.invoke("proposal:clear"),
96
+ clearProposal: (outcome, id) => ipcRenderer.invoke("proposal:clear", outcome, id),
97
97
  onProposal: (cb) => {
98
98
  const h = (_e, payload) => cb(payload);
99
99
  ipcRenderer.on("doc:proposal", h);
@@ -233,6 +233,16 @@ body {
233
233
  @media (prefers-reduced-motion: reduce) { .ap-sidepanel, .ap-sidepanel.ap-sidepanel--closing { animation: none; } }
234
234
  .ap-preview { flex: 1; min-width: 0; overflow: auto; padding: 28px 36px; border-right: 1px solid var(--line); background: var(--bg); }
235
235
  .ap-rendered { max-width: 760px; }
236
+ /* Show a paragraph the way its author typed it. Markdown keeps the author's newlines inside a
237
+ paragraph and markdown-it emits them inside the <p>, but HTML's default whitespace processing
238
+ collapses each newline — and each run of alignment spaces — to a single space, so a directory
239
+ tree or any hand-aligned block pasted into a plan arrived as one run-on line with its columns
240
+ gone. `pre-wrap` honors both, and still wraps a long line at the pane width (unlike `pre`).
241
+ Deliberately scoped to paragraph content: markdown-it also emits cosmetic newlines BETWEEN
242
+ block tags (inside <li>, <blockquote>, <ul>, around a loose list item's <p>), and preserving
243
+ those would open a blank line before every nested list. Tradeoff: prose whose source is
244
+ hand-wrapped now shows those line breaks in the preview, matching the source pane. */
245
+ .ap-rendered p { white-space: pre-wrap; }
236
246
  .ap-rendered img { max-width: 100%; height: auto; } /* a pasted/picked image is embedded at its native pixel size otherwise */
237
247
  .ap-rendered:focus { outline: none; } /* tabIndex={-1}: click-focusable (to receive a native paste event) but not Tab-reachable, so there's no keyboard focus ring to suppress here */
238
248
  .ap-rendered h1, .ap-rendered h2, .ap-rendered h3 { font-family: var(--serif); font-weight: 500; letter-spacing: -0.01em; line-height: 1.15; }
@@ -462,6 +472,11 @@ input[type="checkbox"]:focus-visible, input[type="radio"]:focus-visible { outlin
462
472
  ::highlight(ap-comment-target) { background: #bcd5cc; color: inherit; }
463
473
  /* Preview right-click context menu. */
464
474
  .ap-ctxmenu { position: fixed; z-index: 40; display: flex; flex-direction: column; min-width: 168px; padding: 4px; background: var(--bg); border: 1px solid var(--line); border-radius: 8px; box-shadow: var(--shadow); }
475
+ .ap-mention-dropdown { position: absolute; top: 100%; left: 0; z-index: 45; margin-top: 4px; width: 260px; max-height: 180px; overflow-y: auto; display: flex; flex-direction: column; padding: 4px; background: var(--bg); border: 1px solid var(--line); border-radius: 8px; box-shadow: var(--shadow); }
476
+ .ap-mention-item { display: flex; flex-direction: column; align-items: flex-start; gap: 1px; font: inherit; text-align: left; background: none; border: 0; border-radius: 6px; padding: 5px 9px; cursor: pointer; color: var(--fg); }
477
+ .ap-mention-item:hover, .ap-mention-item.active { background: var(--accent-soft); color: var(--accent); }
478
+ .ap-mention-email { font-size: 12.5px; }
479
+ .ap-mention-name { font-size: 11px; opacity: 0.7; }
465
480
  .ap-ctxmenu-item { font: inherit; text-align: left; background: none; border: 0; border-radius: 6px; padding: 6px 10px; cursor: pointer; color: var(--fg); }
466
481
  .ap-ctxmenu-item:hover:not(:disabled) { background: var(--accent-soft); color: var(--accent); }
467
482
  .ap-ctxmenu-item:disabled { opacity: 0.4; cursor: default; }