pi-todo-ledger 0.7.2 → 0.7.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/README.md CHANGED
@@ -14,7 +14,7 @@ On top of them it publishes a bookkeeping contract, [CONTRACT.md](CONTRACT.md):
14
14
 
15
15
  ## Replaces rpiv-todo
16
16
 
17
- This package registers the tool name `todo`, as rpiv-todo does, so install one or the other.
17
+ Install this package or its predecessor, `@juicesharp/rpiv-todo`, not both. At startup the ledger warns if another extension owns the `todo` tool or registers `/todo` or `/todos`. It also checks personal and project package settings and installation paths for rpiv-todo. The warning names the active tool provider and gives the removal command for a matching package declaration. For an extension loaded with `-e`, omit it on the next launch. Pi does not expose losing tool registrations: a later, unknown extension that only registers `todo` cannot be detected.
18
18
  With both installed, the two `todo` tools clash.
19
19
 
20
20
  Switching keeps your lists.
package/docs/overlay.md CHANGED
@@ -103,7 +103,7 @@ Collapsing the panel, or the run leaving the panel, returns the run to the Subag
103
103
  ## Other workers
104
104
 
105
105
  An agent often sends out a run that belongs to no todo item: a quick scout, a reviewer, a one-off check.
106
- The panel lists this session's runs that no task on the panel is bound to as one group, after the task rows and before the summary row:
106
+ The group follows the task rows. It includes unbound runs and runs whose task is folded away or cut by the row budget. A run from a hidden task carries its task number (`#4 worker-four`). A fully drawn run is claimed here; if there is no room, the summary counts it and the host can still show it.
107
107
 
108
108
  ```text
109
109
  ● Todos (0/3)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-todo-ledger",
3
- "version": "0.7.2",
3
+ "version": "0.7.3",
4
4
  "description": "A todo list for pi agents with a public bookkeeping contract: snapshot entries, change events, and namespace validators. Fork of @juicesharp/rpiv-todo",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -0,0 +1,148 @@
1
+ import { readFileSync, realpathSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import type {
6
+ ExtensionAPI,
7
+ ExtensionContext,
8
+ } from "@earendil-works/pi-coding-agent";
9
+ import { t } from "./state/i18n-bridge.ts";
10
+
11
+ const self = realpathSync(fileURLToPath(new URL("../", import.meta.url)));
12
+ const predecessors = ["@juicesharp/rpiv-todo", "rpiv-todo"];
13
+ function real(path: string) {
14
+ try {
15
+ return realpathSync(path);
16
+ } catch {
17
+ return path;
18
+ }
19
+ }
20
+ function json(path: string) {
21
+ try {
22
+ return JSON.parse(readFileSync(path, "utf8"));
23
+ } catch {
24
+ return undefined;
25
+ }
26
+ }
27
+ function owner(path: string) {
28
+ for (let dir = dirname(path); ; dir = dirname(dir)) {
29
+ const name: unknown = json(join(dir, "package.json"))?.name;
30
+ if (typeof name === "string" && name) return { root: dir, name };
31
+ if (dirname(dir) === dir) return { root: path, name: basename(path) };
32
+ }
33
+ }
34
+ const quote = (s: string) =>
35
+ /^[\w@.:/+~-]+$/.test(s) ? s : `'${s.replaceAll("'", "'\\''")}'`;
36
+ interface Rival {
37
+ name: string;
38
+ path: string;
39
+ commands: Set<string>;
40
+ }
41
+ export function conflictWarning(pi: ExtensionAPI, ctx: ExtensionContext) {
42
+ const found = new Map<string, Rival>();
43
+ function add(path: string, name: string, root: string) {
44
+ let item = found.get(root);
45
+ if (!item) {
46
+ item = { name, path, commands: new Set() };
47
+ found.set(root, item);
48
+ }
49
+ return item;
50
+ }
51
+ const tool = pi.getAllTools().find((x) => x.name === "todo");
52
+ const toolPath = tool?.sourceInfo?.path;
53
+ const active = toolPath ? owner(real(toolPath)).name : "—";
54
+ const registrations = new Map<string, Set<string>>();
55
+ for (const info of [
56
+ tool?.sourceInfo,
57
+ ...pi
58
+ .getCommands()
59
+ .filter(
60
+ (c) => c.source === "extension" && /^todos?(?::\d+)?$/.test(c.name),
61
+ )
62
+ .map((c) => c.sourceInfo),
63
+ ]) {
64
+ const path = info?.path;
65
+ if (!path || !isAbsolute(path)) continue;
66
+ const p = real(path),
67
+ pkg = owner(p);
68
+ if (pkg.root === self) continue;
69
+ add(p, pkg.name, pkg.root);
70
+ const sources = registrations.get(pkg.root) ?? new Set<string>();
71
+ sources.add(`${info.scope}:${info.source}`);
72
+ registrations.set(pkg.root, sources);
73
+ }
74
+ const globalDir = resolve(
75
+ (
76
+ process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent")
77
+ ).replace(/^~(?=\/)/, homedir()),
78
+ );
79
+ for (const [dir, local] of [
80
+ [globalDir, false],
81
+ [join(ctx.cwd, ".pi"), true],
82
+ ] as const) {
83
+ const npmRoot = join(dir, "npm", "node_modules");
84
+ const gitRoot = join(dir, "git");
85
+ for (const root of [
86
+ ...predecessors.map((n) => join(npmRoot, n)),
87
+ join(
88
+ gitRoot,
89
+ "github.com",
90
+ "juicesharp",
91
+ "rpiv-mono",
92
+ "packages",
93
+ "rpiv-todo",
94
+ ),
95
+ join(gitRoot, "github.com", "juicesharp", "rpiv-todo"),
96
+ ]) {
97
+ const name = json(join(root, "package.json"))?.name;
98
+ if (predecessors.includes(name)) add(real(root), name, real(root));
99
+ }
100
+ const packages: unknown = json(join(dir, "settings.json"))?.packages;
101
+ if (!Array.isArray(packages)) continue;
102
+ for (const entry of packages) {
103
+ const source = typeof entry === "string" ? entry : entry?.source;
104
+ if (typeof source !== "string" || /[\x00-\x1f\x7f]/.test(source))
105
+ continue;
106
+ const npm = /^npm:((?:@[^/@]+\/)?[^/@]+)(?:@.*)?$/.exec(source)?.[1];
107
+ const git =
108
+ /^(?:git:|https?:\/\/|ssh:\/\/)(?:https?:\/\/)?(?:git@)?([\w.-]+)[/:]([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:@[^\s]+)?$/.exec(
109
+ source,
110
+ );
111
+ const root = real(
112
+ npm
113
+ ? join(npmRoot, npm)
114
+ : git
115
+ ? join(gitRoot, git[1], git[2], git[3])
116
+ : resolve(dir, source.replace(/^~(?=\/)/, homedir())),
117
+ );
118
+ const name = npm ?? json(join(root, "package.json"))?.name;
119
+ if (predecessors.includes(name)) add(root, name, root);
120
+ for (const [key, item] of found)
121
+ if (
122
+ key === root ||
123
+ (git && key.startsWith(root + sep)) ||
124
+ registrations.get(key)?.has(`${local ? "project" : "user"}:${source}`)
125
+ )
126
+ item.commands.add(
127
+ `pi remove ${local ? "--local " : ""}${quote(source)}`,
128
+ );
129
+ }
130
+ }
131
+ if (!found.size) return;
132
+ const rivals = [...found.values()]
133
+ .map((x) => `${x.name} (${x.path})`)
134
+ .join("; ");
135
+ const commands = [
136
+ ...new Set([...found.values()].flatMap((x) => [...x.commands])),
137
+ ];
138
+ return (
139
+ t(
140
+ "conflict.warning",
141
+ "Todo conflict: {rivals}. Active todo tool: {active}.",
142
+ )
143
+ .replace("{rivals}", () => rivals)
144
+ .replace("{active}", () => active) +
145
+ " " +
146
+ [...commands, "/reload"].join(" → ")
147
+ );
148
+ }
package/src/index.ts CHANGED
@@ -23,6 +23,7 @@
23
23
 
24
24
  import type { ExtensionAPI, ExtensionUIContext } from "@earendil-works/pi-coding-agent";
25
25
  import type { KeyId } from "@earendil-works/pi-tui";
26
+ import { conflictWarning } from './conflicts.ts';
26
27
  import { COLLAPSE_KEY_OFF, resolveCollapseKey } from "./config.ts";
27
28
  import {
28
29
  CHANGED_EVENT,
@@ -255,6 +256,7 @@ export default function (
255
256
  if (isForeground) await updateTodoOverlay(true);
256
257
  };
257
258
 
259
+ const warned = new Set<string>();
258
260
  pi.on("session_start", async (_event, ctx) => {
259
261
  let id: string;
260
262
  try {
@@ -268,6 +270,14 @@ export default function (
268
270
  if (!isStaleCtxError(e)) throw e;
269
271
  return;
270
272
  }
273
+ if (!warned.has(id)) {
274
+ const message = conflictWarning(pi, ctx);
275
+ if (message) {
276
+ warned.add(id);
277
+ if (ctx.hasUI) ctx.ui.notify(message, 'warning');
278
+ else console.error(message.replace(/[\r\n]+/g, ' '));
279
+ }
280
+ }
271
281
  if (!ctx.hasUI) return;
272
282
  // First UI-bearing session_start claims the foreground (the interactive
273
283
  // launcher, by spawn-ordering) without eagerly loading the overlay.
@@ -1,4 +1,5 @@
1
1
  {
2
+ "conflict.warning": "Todo-Konflikt: {rivals}. Aktives todo-Werkzeug: {active}.",
2
3
  "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. Unicode box-drawing characters (──) stay untranslated. Note: 'overlay.more' renders as '+5 weitere' which is grammatically loose for plural agreement — accepted for badge brevity.",
3
4
 
4
5
  "status.pending": "ausstehend",
@@ -1,4 +1,5 @@
1
1
  {
2
+ "conflict.warning": "Todo conflict: {rivals}. Active todo tool: {active}.",
2
3
  "status.pending": "pending",
3
4
  "status.in_progress": "in progress",
4
5
  "status.completed": "completed",
@@ -1,4 +1,5 @@
1
1
  {
2
+ "conflict.warning": "Conflicto de tareas: {rivals}. Herramienta todo activa: {active}.",
2
3
  "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. Unicode box-drawing characters (──) stay untranslated.",
3
4
 
4
5
  "status.pending": "pendientes",
@@ -1,4 +1,5 @@
1
1
  {
2
+ "conflict.warning": "Conflit de tâches : {rivals}. Outil todo actif : {active}.",
2
3
  "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. Unicode box-drawing characters (──) stay untranslated.",
3
4
 
4
5
  "status.pending": "en attente",
@@ -1,4 +1,5 @@
1
1
  {
2
+ "conflict.warning": "Conflito de tarefas: {rivals}. Ferramenta todo ativa: {active}.",
2
3
  "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. Unicode box-drawing characters (──) stay untranslated.",
3
4
 
4
5
  "status.pending": "pendentes",
@@ -1,4 +1,5 @@
1
1
  {
2
+ "conflict.warning": "Conflito de tarefas: {rivals}. Ferramenta todo ativa: {active}.",
2
3
  "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. Unicode box-drawing characters (──) stay untranslated.",
3
4
 
4
5
  "status.pending": "pendentes",
@@ -1,4 +1,5 @@
1
1
  {
2
+ "conflict.warning": "Конфликт расширений задач: {rivals}. Активный инструмент todo: {active}.",
2
3
  "_meta.notes": "Автоперевод. Приветствуется проверка носителем языка через PR. Символы юникода (──) не переводятся.",
3
4
 
4
5
  "status.pending": "ожидание",
@@ -1,4 +1,5 @@
1
1
  {
2
+ "conflict.warning": "Конфлікт розширень завдань: {rivals}. Активний інструмент todo: {active}.",
2
3
  "_meta.notes": "Автопереклад. Привітна перевірка носієм мови через PR. Символи юнікоду (──) не перекладаються.",
3
4
 
4
5
  "status.pending": "очікування",
@@ -1,4 +1,5 @@
1
1
  {
2
+ "conflict.warning": "偵測到待辦套件衝突:{rivals}。目前的 todo 工具由 {active} 提供。",
2
3
  "status.pending": "待處理",
3
4
  "status.in_progress": "進行中",
4
5
  "status.completed": "已完成",
@@ -1,4 +1,5 @@
1
1
  {
2
+ "conflict.warning": "检测到待办扩展冲突:{rivals}。当前 todo 工具由 {active} 提供。",
2
3
  "_meta.notes": "中文翻译。欢迎中文母语者通过 PR 审校。",
3
4
 
4
5
  "status.pending": "待处理",
@@ -81,6 +81,7 @@ interface DrawContext {
81
81
  live: ReturnType<typeof liveRows>;
82
82
  /** Live runs of this session bound to no task on the panel, in the host's order. */
83
83
  others: RunRow[];
84
+ runOwners: Map<string, number>;
84
85
  showIds: boolean;
85
86
  now: number;
86
87
  evidence: "inline" | "screen" | undefined;
@@ -403,6 +404,7 @@ export class TodoOverlay {
403
404
  bound,
404
405
  live,
405
406
  others,
407
+ runOwners: new Map([...bound].flatMap(([id, h]) => h.runs.map(r => [r.id, id] as const))),
406
408
  showIds,
407
409
  now: Date.now(),
408
410
  evidence: this.evidence(),
@@ -461,6 +463,7 @@ export class TodoOverlay {
461
463
  const layout = selectOverlayLayout(overlayState, bodyBudget);
462
464
  const overflow = layout.hiddenCompleted + layout.truncatedTail;
463
465
  const hint = this.keyHint();
466
+ draw.others = this.groupCandidates(layout.visible, draw);
464
467
  const others = draw.others.length;
465
468
  // With nothing to summarize, the hint takes its own row only when one is spare.
466
469
  const needed =
@@ -534,23 +537,28 @@ export class TodoOverlay {
534
537
  const completed = overlayTasks.filter((t) => t.status === "completed");
535
538
  const next = pending.slice(0, inProgress.length ? 2 : 3);
536
539
  const total = inProgress.length + pending.length + completed.length;
537
- const others = draw.others.length;
538
540
 
539
541
  // Task rows first, in priority order; runs take the spare rows in display order;
540
542
  // the group and then completed rows get what is left. The summary row is reserved only when needed.
541
543
  const fit = (slots: number) => {
542
544
  const core = [...inProgress, ...next].slice(0, slots);
543
545
  let spare = slots - core.length - this.boundRows(core, slots - core.length, draw);
544
- const group = groupFit(spare, others);
546
+ const candidates = this.groupCandidates([...core, ...completed], draw);
547
+ const initialGroup = groupFit(spare, candidates.length);
548
+ const possibleDone = completed.slice(0, spare - (initialGroup ? 1 + initialGroup : 0));
549
+ const workers = this.groupCandidates([...core, ...possibleDone], draw);
550
+ const group = groupFit(spare, workers.length);
545
551
  spare -= group ? 1 + group : 0;
546
552
  const done = completed.slice(0, spare);
547
553
  const rows = core.length + done.length + (group ? 1 + group : 0);
548
- return { core, done, group, spare: slots - rows, left: spare - done.length };
554
+ return { core, done, group, workers: this.groupCandidates([...core, ...done], draw), spare: slots - rows, left: spare - done.length };
549
555
  };
550
556
  let shown = fit(bodyBudget);
551
557
  const summarized =
552
- shown.core.length + shown.done.length < total || shown.group < others;
558
+ shown.core.length + shown.done.length < total || shown.group < shown.workers.length;
553
559
  if (summarized) shown = fit(bodyBudget - 1);
560
+ draw.others = shown.workers;
561
+ const others = shown.workers.length;
554
562
  // With nothing to summarize, the hint takes its own row only when one is spare;
555
563
  // one row less leaves the same layout then.
556
564
  const hint = this.keyHint();
@@ -598,6 +606,11 @@ export class TodoOverlay {
598
606
  return lines;
599
607
  }
600
608
 
609
+ private groupCandidates(visible: readonly Task[], draw: DrawContext): RunRow[] {
610
+ const ids = new Set(visible.map(task => task.id));
611
+ return [...(draw.live?.values() ?? [])].filter(run => !ids.has(draw.runOwners.get(run.id) ?? -1));
612
+ }
613
+
601
614
  /** Live run rows bound to a task (empty when the host gave no rows). */
602
615
  private children(task: Task, draw: DrawContext): RunRow[] {
603
616
  const { runs } = draw.bound.get(task.id) ?? history(undefined);
@@ -653,7 +666,7 @@ export class TodoOverlay {
653
666
  truncate(`${theme.fg("dim", closed ? "└─" : "├─")} ${theme.fg("muted", t("overlay.others", OVERLAY_OTHERS))}`),
654
667
  ];
655
668
  for (const [j, r] of runs.entries())
656
- this.drawRun(lines, r, `${closed ? " " : "│"} ${j === runs.length - 1 ? "└" : "├"} `, draw, frame);
669
+ this.drawRun(lines, r, `${closed ? " " : "│"} ${j === runs.length - 1 ? "└" : "├"} ${draw.runOwners.has(r.id) ? `#${draw.runOwners.get(r.id)} ` : ''}`, draw, frame);
657
670
  return lines;
658
671
  }
659
672