@serendevity/pi-gtd 0.0.0-stage → 0.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 pi-gtd contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,71 @@
1
- # Temporary Holding Version
1
+ # pi-gtd
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Capture-first task tracking for [pi](https://github.com/earendil-works/pi-coding-agent).
4
+ One flat list, three states (`current` / `idea` / `done`), exactly one current task.
5
+ GTD capture muscle, no kanban ceremony.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pi install npm:@serendevity/pi-gtd # from npm
11
+ pi install ./pi-gtd # or a local checkout
12
+ ```
13
+
14
+ Ships as TypeScript source — no build step. `pi-gtd` is a [pi package](https://pi.dev/packages) (keyword `pi-package`); the host (`pi-coding-agent`, `pi-tui`, `typebox`) is provided by pi itself via peerDependencies.
15
+
16
+ ## Commands
17
+
18
+ | Command | What it does |
19
+ |---|---|
20
+ | `/gtd` | Interactive panel: current task + inbox. `↑↓` select · `⏎` promote · `d` done · `x` drop · `esc` close |
21
+ | `/gtd-i <text>` | 📥 Capture an idea instantly (`-g` → global inbox) |
22
+ | `/gtd-now` | Show the current task |
23
+ | `/gtd-next` | Promote the next idea to current (old current parks back to inbox), then pick: **Start work** (kicks off the agent on it) or **Discuss first** (agent talks approach, no code). `esc`/timeout = just promote |
24
+ | `/gtd-orient` | Start-of-session ritual on the current task: agent recaps from the last note (with staleness check), proposes the next action, **waits for your confirmation** |
25
+ | `/gtd-done` | Mark the current task done |
26
+ | `/gtd-q` | Save a Q&A note on the current task (question → input box, answer → editor) |
27
+ | `/gtd-list` | Plain-text list |
28
+
29
+ ## Tools (for the agent)
30
+
31
+ - `gtd_idea` — park an idea / off-topic request mid-task
32
+ - `gtd_show` — show current task + inbox
33
+
34
+ ## Notes & handoff
35
+
36
+ Two writers, one reader:
37
+
38
+ - **You** — `/gtd-q` pins a question + answer to the current task (decisions you know matter).
39
+ - **The agent** — after every settled, non-aborted run on a task, pi-gtd calls the session model
40
+ to write a ≤3-sentence handoff (what was done, decisions/files, next action) and pins it to the
41
+ task. Fire-and-forget, silent on failure, never delays a queued run.
42
+
43
+ The reader is the injection: every run's system prompt carries `▶ current: …` plus the last note,
44
+ so a fresh session resumes without re-discovery. One task, one session — the handoff closes the loop.
45
+
46
+ `/gtd-orient` is the session-start ritual (borrowed from the optionswheeling extension's
47
+ `/ow-orient`): it sends the orientation as a real user turn — recap the task from the last note,
48
+ flag staleness via the note's age, propose the next action, and stop. The detailed state lives in
49
+ the store; the prompt is the cue, not the source of truth.
50
+
51
+ ## Status line
52
+
53
+ The footer always shows `▶ <current> · 📥 <n>` for the active store when there's anything to show; it updates on capture, promote, and done, and flashes `📝 writing handoff…` while the resume note is being generated.
54
+
55
+ ## Storage
56
+
57
+ - `<projectRoot>/.pi/gtd.json` — project tasks (auto-gitignored)
58
+ - `~/.pi/agent/gtd/global.json` — project-less ideas
59
+
60
+ Project root = nearest ancestor of cwd containing `.git` or `.pi`.
61
+
62
+ ## Status
63
+
64
+ Phase 1 — store, commands, tools, 4-line system-prompt injection.
65
+ Phase 2 — `/gtd` interactive overlay panel + always-on footer status line.
66
+ Phase 3 — `/gtd-q` saved Q&A + LLM-written resume notes at `agent_settled`.
67
+ Phase 4 — vitest suite (39 tests over store/format/status), package manifest, published to npm.
68
+
69
+ Dev: `npm install && npm test` (vitest) · `npm run typecheck` (strict tsc, no emit).
70
+
71
+ Future work: tests for `index.ts` + `lib/panel.ts` (needs a fake ExtensionAPI / TUI harness).
package/index.ts ADDED
@@ -0,0 +1,384 @@
1
+ /**
2
+ * pi-gtd — capture-first task tracking for pi
3
+ *
4
+ * One flat list, three states (current / idea / done), exactly one current task.
5
+ * Commands: /gtd /gtd-i /gtd-now /gtd-next /gtd-done /gtd-list
6
+ * UI: /gtd panel (overlay), always-on footer status line
7
+ * Tools: gtd_idea, gtd_show
8
+ *
9
+ * Storage: <projectRoot>/.pi/gtd.json (gitignored) or ~/.pi/agent/gtd/global.json
10
+ */
11
+
12
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
13
+ import type { Message } from "@earendil-works/pi-ai";
14
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
15
+ import { convertToLlm, serializeConversation } from "@earendil-works/pi-coding-agent";
16
+ import { Type } from "typebox";
17
+ import { buildInjection, formatList, shortTime, taskLine, timeAgo } from "./lib/format";
18
+ import { GtdPanel } from "./lib/panel";
19
+ import { applyStatus } from "./lib/status";
20
+ import {
21
+ addIdea,
22
+ addNoteToCurrent,
23
+ completeCurrent,
24
+ countDoneToday,
25
+ getCurrent,
26
+ getIdeas,
27
+ loadStore,
28
+ promoteNext,
29
+ saveStore,
30
+ storeLabel,
31
+ storePathFor,
32
+ } from "./lib/store";
33
+
34
+ function cwdOf(ctx: unknown): string {
35
+ const cwd = (ctx as { cwd?: string } | undefined)?.cwd;
36
+ return cwd ?? process.cwd();
37
+ }
38
+
39
+ /** Kick off an agent turn from a command handler; steers instead if a run is already going. */
40
+ function kickOff(pi: ExtensionAPI, text: string): void {
41
+ try {
42
+ pi.sendUserMessage(text);
43
+ } catch {
44
+ // "must specify delivery mode while streaming" → steer into the running turn
45
+ pi.sendUserMessage(text, { deliverAs: "steer" });
46
+ }
47
+ }
48
+
49
+ export default function gtdExtension(pi: ExtensionAPI) {
50
+ // ── commands ─────────────────────────────────────────────────
51
+
52
+ pi.registerCommand("gtd", {
53
+ description: "Open the GTD panel (current task, inbox, actions)",
54
+ handler: async (_args, ctx) => {
55
+ if (ctx.mode !== "tui") {
56
+ ctx.ui.notify("/gtd requires interactive mode — use /gtd-list", "error");
57
+ return;
58
+ }
59
+ const path = storePathFor(cwdOf(ctx));
60
+ const label = storeLabel(path);
61
+ const store = loadStore(path);
62
+ await ctx.ui.custom<string | undefined>(
63
+ (tui, theme, _keybindings, done) =>
64
+ new GtdPanel(theme, store, tui, done, {
65
+ label,
66
+ persist: (mutated) => {
67
+ saveStore(path, mutated);
68
+ applyStatus(ctx, path);
69
+ },
70
+ notify: (message) => ctx.ui.notify(message, "info"),
71
+ }),
72
+ { overlay: true },
73
+ );
74
+ },
75
+ });
76
+
77
+ pi.registerCommand("gtd-i", {
78
+ description: "Capture an idea instantly (use `-g` for the global inbox)",
79
+ handler: async (args, ctx) => {
80
+ const cwd = cwdOf(ctx);
81
+ let text = (args ?? "").trim();
82
+ let forceGlobal = false;
83
+ if (text.startsWith("-g ")) {
84
+ forceGlobal = true;
85
+ text = text.slice(3).trim();
86
+ }
87
+ if (!text) {
88
+ const input = await ctx.ui.input("Capture idea", "What's the idea?");
89
+ if (!input?.trim()) return;
90
+ text = input.trim();
91
+ }
92
+ const path = storePathFor(cwd, forceGlobal);
93
+ const store = loadStore(path);
94
+ const task = addIdea(store, text, forceGlobal ? null : cwd);
95
+ saveStore(path, store);
96
+ applyStatus(ctx, path);
97
+ ctx.ui.notify(`📥 captured (${storeLabel(path)}): ${taskLine(task)}`, "info");
98
+ },
99
+ });
100
+
101
+ pi.registerCommand("gtd-now", {
102
+ description: "Show the current task",
103
+ handler: async (_args, ctx) => {
104
+ const path = storePathFor(cwdOf(ctx));
105
+ const store = loadStore(path);
106
+ const current = getCurrent(store);
107
+ if (!current) {
108
+ const ideas = getIdeas(store).length;
109
+ ctx.ui.notify(`No current task · 📥 ${ideas} idea${ideas === 1 ? "" : "s"} parked — try /gtd-next`, "info");
110
+ return;
111
+ }
112
+ const notes = current.notes.length > 0 ? ` · ${current.notes.length} note${current.notes.length === 1 ? "" : "s"}` : "";
113
+ ctx.ui.notify(`▶ ${taskLine(current)}${notes} (started ${shortTime(current.createdAt)})`, "info");
114
+ },
115
+ });
116
+
117
+ pi.registerCommand("gtd-next", {
118
+ description: "Promote the next idea to current task, then pick: start work or discuss",
119
+ handler: async (_args, ctx) => {
120
+ const path = storePathFor(cwdOf(ctx));
121
+ const store = loadStore(path);
122
+ const result = promoteNext(store);
123
+ if (!result) {
124
+ ctx.ui.notify("📥 inbox empty — capture something with /gtd-i", "info");
125
+ return;
126
+ }
127
+ saveStore(path, store);
128
+ applyStatus(ctx, path);
129
+ const demoted = result.demoted ? ` (parked ${result.demoted.text} back to 📥)` : "";
130
+ ctx.ui.notify(`▶ picked up: ${result.promoted.text}${demoted}`, "info");
131
+
132
+ // Handoff prompt: agent doesn't wake up until the user picks (or esc/timeout).
133
+ if (ctx.mode === "tui") {
134
+ const choice = await ctx.ui.select(`▶ ${result.promoted.text}`, ["Start work", "Discuss first"], {
135
+ timeout: 15000,
136
+ });
137
+ if (choice === "Start work") {
138
+ kickOff(pi, `▶ Start working on: ${result.promoted.text}`);
139
+ } else if (choice === "Discuss first") {
140
+ kickOff(
141
+ pi,
142
+ `▶ I just picked up the task "${result.promoted.text}". Discuss the approach with me before implementing anything.`,
143
+ );
144
+ }
145
+ // esc / timeout → task stays current, no agent turn
146
+ }
147
+ },
148
+ });
149
+
150
+ pi.registerCommand("gtd-orient", {
151
+ description: "Orient the agent on the current task (recap, propose next action, wait)",
152
+ handler: async (_args, ctx) => {
153
+ const path = storePathFor(cwdOf(ctx));
154
+ const store = loadStore(path);
155
+ const current = getCurrent(store);
156
+ if (!current) {
157
+ ctx.ui.notify("Nothing current — /gtd-next picks one first, then /gtd-orient re-runs", "info");
158
+ return;
159
+ }
160
+ // staleness cue: the note's age is the pi-gtd equivalent of ow-orient's
161
+ // `git log -1 -- HANDOFF.md` check — the agent judges freshness from it
162
+ const last = current.notes.at(-1);
163
+ const noteAge = last ? ` (last note ${timeAgo(last.at)})` : " (no notes yet — re-derive from the code)";
164
+ kickOff(
165
+ pi,
166
+ [
167
+ `▶ Orient for this session on "${current.text}"${noteAge} — do this before any work:`,
168
+ "1. Recap in one or two lines where the task stands, from the GTD note in your context. If the note is missing or stale for what you find in the code, say so and re-derive from the repo state.",
169
+ "2. Propose the single next action.",
170
+ "3. WAIT for my confirmation — do not start work yet.",
171
+ "",
172
+ "One task per session; park anything off-topic with gtd_idea.",
173
+ ].join("\n"),
174
+ );
175
+ },
176
+ });
177
+
178
+ pi.registerCommand("gtd-done", {
179
+ description: "Mark the current task done",
180
+ handler: async (_args, ctx) => {
181
+ const path = storePathFor(cwdOf(ctx));
182
+ const store = loadStore(path);
183
+ const done = completeCurrent(store);
184
+ if (!done) {
185
+ ctx.ui.notify("Nothing is current — nothing to done ✓", "info");
186
+ return;
187
+ }
188
+ saveStore(path, store);
189
+ applyStatus(ctx, path);
190
+ const next = getIdeas(store)[0];
191
+ ctx.ui.notify(
192
+ `✓ done: ${done.text}${next ? ` — next up: ${next.text} (/gtd-next)` : " — inbox empty 🎉"}`,
193
+ "info",
194
+ );
195
+ },
196
+ });
197
+
198
+ pi.registerCommand("gtd-q", {
199
+ description: "Save a Q&A note on the current task",
200
+ handler: async (_args, ctx) => {
201
+ if (ctx.mode !== "tui") {
202
+ ctx.ui.notify("/gtd-q requires interactive mode", "error");
203
+ return;
204
+ }
205
+ const path = storePathFor(cwdOf(ctx));
206
+ const store = loadStore(path);
207
+ const current = getCurrent(store);
208
+ if (!current) {
209
+ ctx.ui.notify("Nothing current — /gtd-q attaches to the current task (/gtd-next to pick one)", "info");
210
+ return;
211
+ }
212
+ const q = await ctx.ui.input("Question", `Q for ${current.id}:`);
213
+ if (!q?.trim()) return;
214
+ const a = await ctx.ui.editor("Answer", "");
215
+ if (a === undefined || !a.trim()) return;
216
+ // collapse newlines: notes feed into the ≤4-line injection and the panel
217
+ addNoteToCurrent(store, {
218
+ type: "qa",
219
+ q: q.trim().replace(/\s+/g, " "),
220
+ a: a.trim().replace(/\s+/g, " "),
221
+ at: new Date().toISOString(),
222
+ });
223
+ saveStore(path, store);
224
+ ctx.ui.notify(`💬 saved on ${taskLine(current)}`, "info");
225
+ },
226
+ });
227
+
228
+ pi.registerCommand("gtd-list", {
229
+ description: "List tasks for the current project",
230
+ handler: async (_args, ctx) => {
231
+ const path = storePathFor(cwdOf(ctx));
232
+ const store = loadStore(path);
233
+ ctx.ui.notify(formatList(store, storeLabel(path)), "info");
234
+ },
235
+ });
236
+
237
+ // ── tools (LLM-facing) ───────────────────────────────────────
238
+
239
+ pi.registerTool({
240
+ name: "gtd_idea",
241
+ label: "GTD Idea",
242
+ description:
243
+ "Park an idea or off-topic request without losing it. Use when the user mentions something " +
244
+ "unrelated to the current task mid-conversation, or when work surfaces a follow-up thought. " +
245
+ "Parks it and stays on the current task.",
246
+ promptSnippet: "Park an idea/off-topic thought in the GTD inbox",
247
+ promptGuidelines: [
248
+ "Use gtd_idea when the user mentions a task or idea unrelated to the current work — park it and confirm briefly instead of switching context.",
249
+ ],
250
+ parameters: Type.Object({
251
+ text: Type.String({ description: "The idea, one sentence" }),
252
+ global: Type.Optional(
253
+ Type.Boolean({ description: "true → global inbox instead of the current project's list" }),
254
+ ),
255
+ }),
256
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
257
+ const path = storePathFor(cwdOf(ctx), params.global === true);
258
+ const store = loadStore(path);
259
+ const current = getCurrent(store);
260
+ const task = addIdea(store, params.text.trim(), params.global === true ? null : cwdOf(ctx), current?.id ?? null);
261
+ saveStore(path, store);
262
+ if (ctx?.hasUI) applyStatus(ctx, path);
263
+ return {
264
+ content: [{ type: "text", text: `📥 parked: ${task.text}` }],
265
+ details: { id: task.id, store: storeLabel(path) },
266
+ };
267
+ },
268
+ });
269
+
270
+ pi.registerTool({
271
+ name: "gtd_show",
272
+ label: "GTD Show",
273
+ description: "Show the current task, parked ideas, and done count for the current project. " +
274
+ "Use when the user asks what they were working on or what's next.",
275
+ promptSnippet: "Show current GTD task and inbox",
276
+ parameters: Type.Object({}),
277
+ async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
278
+ const path = storePathFor(cwdOf(ctx));
279
+ const store = loadStore(path);
280
+ return {
281
+ content: [{ type: "text", text: formatList(store, storeLabel(path)) }],
282
+ details: { doneToday: countDoneToday(store) },
283
+ };
284
+ },
285
+ });
286
+
287
+ // ── resume handoff (phase 3) ─────────────────────────────
288
+
289
+ const HANDOFF_SYSTEM = `You write resume handoffs for coding sessions. Given a task and the tail of a session transcript, write a handoff for the next session working on the same task:
290
+ - what was accomplished this run
291
+ - key decisions, files touched, and anything non-obvious
292
+ - the single next action
293
+ Maximum 3 sentences, plain text, no preamble.`;
294
+
295
+ const MAX_TAIL_ENTRIES = 40;
296
+ const MAX_TAIL_CHARS = 20_000;
297
+ const MIN_TAIL_CHARS = 200; // below this the run was a greeting/Q&A, not work
298
+ const NOTE_MAX_CHARS = 500;
299
+
300
+ /** Call the model for the handoff note and store it. Fire-and-forget, silent on failure. */
301
+ async function writeHandoffNote(ctx: ExtensionContext, path: string, taskText: string, transcript: string): Promise<void> {
302
+ try {
303
+ if (ctx.hasUI) ctx.ui.setStatus("gtd-note", "📝 writing handoff…");
304
+ const userMessage: Message = {
305
+ role: "user",
306
+ content: [{ type: "text", text: `Task: ${taskText}\n\n## Session transcript (tail)\n\n${transcript}` }],
307
+ timestamp: Date.now(),
308
+ };
309
+ const response = await ctx.modelRegistry.complete(
310
+ ctx.model!,
311
+ { systemPrompt: HANDOFF_SYSTEM, messages: [userMessage] },
312
+ { cacheRetention: "none" },
313
+ );
314
+ if (response.stopReason === "aborted") return;
315
+ const text = response.content
316
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
317
+ .map((c) => c.text)
318
+ .join(" ")
319
+ .replace(/\s+/g, " ")
320
+ .trim()
321
+ .slice(0, NOTE_MAX_CHARS);
322
+ if (!text) return;
323
+
324
+ // reload: the store may have changed while the model was thinking
325
+ const fresh = loadStore(path);
326
+ const current = getCurrent(fresh);
327
+ if (!current) return;
328
+ const last = current.notes.at(-1);
329
+ if (last?.type === "note" && last.text === text) return; // dedupe
330
+ addNoteToCurrent(fresh, { type: "note", text, at: new Date().toISOString() });
331
+ saveStore(path, fresh);
332
+ if (ctx.hasUI) ctx.ui.notify(`📝 handoff saved: ${text.slice(0, 72)}`, "info");
333
+ } catch {
334
+ /* silent — never break a session over a note */
335
+ } finally {
336
+ if (ctx.hasUI) ctx.ui.setStatus("gtd-note", undefined);
337
+ }
338
+ }
339
+
340
+ pi.on("agent_settled", async (event, ctx) => {
341
+ if (event.aborted || !ctx.model) return;
342
+ const path = storePathFor(cwdOf(ctx));
343
+ const store = loadStore(path);
344
+ const current = getCurrent(store);
345
+ if (!current) return;
346
+
347
+ // transcript tail (compaction entries skipped for now — tail-only is fine for a handoff)
348
+ const messages = ctx.sessionManager
349
+ .getBranch()
350
+ .filter((e) => e.type === "message")
351
+ .slice(-MAX_TAIL_ENTRIES)
352
+ .map((e) => (e as { message: AgentMessage }).message);
353
+ if (messages.length === 0) return;
354
+ let transcript = serializeConversation(convertToLlm(messages));
355
+ if (transcript.length > MAX_TAIL_CHARS) transcript = transcript.slice(-MAX_TAIL_CHARS);
356
+ if (transcript.trim().length < MIN_TAIL_CHARS) return;
357
+
358
+ // not awaited: a queued next run must not wait on the note
359
+ void writeHandoffNote(ctx, path, current.text, transcript);
360
+ });
361
+
362
+ // ── injection ────────────────────────────────────────────────
363
+
364
+ pi.on("before_agent_start", async (event, ctx) => {
365
+ const store = loadStore(storePathFor(cwdOf(ctx)));
366
+ const injection = buildInjection(store);
367
+ if (!injection) return;
368
+ const options = event.systemPromptOptions;
369
+ options.sections ??= {};
370
+ options.sections.gtd = injection;
371
+ });
372
+
373
+ // ── session continuity ───────────────────────────────────────
374
+
375
+ pi.on("session_start", async (_event, ctx) => {
376
+ const path = storePathFor(cwdOf(ctx));
377
+ applyStatus(ctx, path);
378
+ const store = loadStore(path);
379
+ const current = getCurrent(store);
380
+ if (!current) return;
381
+ const ideas = getIdeas(store).length;
382
+ ctx.ui.notify(`▶ on: ${current.text}${ideas > 0 ? ` · 📥 ${ideas} parked` : ""}`, "info");
383
+ });
384
+ }
package/lib/format.ts ADDED
@@ -0,0 +1,66 @@
1
+ /** pi-gtd — formatting */
2
+
3
+ import type { GtdStore, GtdTask } from "./types";
4
+ import { countDoneToday, getCurrent, getIdeas } from "./store";
5
+
6
+ /** Relative age for humans — exported for /gtd-orient staleness framing */
7
+ export function timeAgo(iso: string): string {
8
+ const ms = Date.now() - new Date(iso).getTime();
9
+ const mins = Math.floor(ms / 60000);
10
+ if (mins < 1) return "just now";
11
+ if (mins < 60) return `${mins}m ago`;
12
+ const hours = Math.floor(mins / 60);
13
+ if (hours < 24) return `${hours}h ago`;
14
+ return `${Math.floor(hours / 24)}d ago`;
15
+ }
16
+
17
+ export function shortTime(iso: string): string {
18
+ return new Date(iso).toTimeString().slice(0, 5);
19
+ }
20
+
21
+ /** One-line summary for toasts */
22
+ export function taskLine(task: GtdTask): string {
23
+ return `${task.id} ${task.text}`;
24
+ }
25
+
26
+ /** ≤4-line injection for before_agent_start (as a system prompt section) */
27
+ export function buildInjection(store: GtdStore): string | null {
28
+ const current = getCurrent(store);
29
+ const ideas = getIdeas(store);
30
+ if (!current && ideas.length === 0) return null;
31
+
32
+ const lines: string[] = [];
33
+ if (current) {
34
+ lines.push(`▶ current: ${current.text} (started ${timeAgo(current.createdAt)})`);
35
+ const lastNote = current.notes.at(-1);
36
+ if (lastNote) {
37
+ const raw = lastNote.type === "qa" ? `Q: ${lastNote.q} → ${lastNote.a}` : lastNote.text ?? "";
38
+ lines.push(` last note: ${raw.replace(/\s+/g, " ").trim()}`);
39
+ }
40
+ } else {
41
+ lines.push("▶ no current task");
42
+ }
43
+ lines.push(`📥 ${ideas.length} idea${ideas.length === 1 ? "" : "s"} parked — gtd_idea to park, /gtd-next to start one`);
44
+ return lines.join("\n");
45
+ }
46
+
47
+ /** Multi-line plain-text list for /gtd-list and gtd_show */
48
+ export function formatList(store: GtdStore, title: string): string {
49
+ const current = getCurrent(store);
50
+ const ideas = getIdeas(store);
51
+ const lines: string[] = [`📋 ${title}`];
52
+ if (current) {
53
+ lines.push(`▶ ${taskLine(current)} (${current.notes.length} notes)`);
54
+ } else if (ideas.length > 0) {
55
+ lines.push("▶ (nothing current — /gtd-next to promote an idea)");
56
+ } else {
57
+ lines.push("(empty — /gtd-i <text> to capture your first idea)");
58
+ }
59
+ for (const idea of ideas) {
60
+ lines.push(`📥 ${taskLine(idea)}`);
61
+ }
62
+ const doneToday = countDoneToday(store);
63
+ if (doneToday > 0) lines.push(`✓ ${doneToday} done today`);
64
+ if (lines.length === 1) lines.push("(empty — /gtd-i <text> to capture your first idea)");
65
+ return lines.join("\n");
66
+ }
package/lib/panel.ts ADDED
@@ -0,0 +1,166 @@
1
+ /** pi-gtd — interactive /gtd overlay panel (custom TUI component) */
2
+
3
+ import type { Theme } from "@earendil-works/pi-coding-agent";
4
+ import { matchesKey, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
5
+ import {
6
+ completeCurrent,
7
+ countDoneToday,
8
+ deleteTask,
9
+ getCurrent,
10
+ setState,
11
+ } from "./store";
12
+ import type { GtdStore } from "./types";
13
+
14
+ export interface GtdPanelHooks {
15
+ /** Save the (mutated) store and refresh the status line. */
16
+ persist(store: GtdStore): void;
17
+ /** Non-blocking feedback. */
18
+ notify(message: string): void;
19
+ /** e.g. "project" | "global" — shown in the panel title. */
20
+ label: string;
21
+ }
22
+
23
+ type TuiHandle = { requestRender(): void };
24
+
25
+ export class GtdPanel {
26
+ private theme: Theme;
27
+ private store: GtdStore;
28
+ private done: (result?: string) => void;
29
+ private hooks: GtdPanelHooks;
30
+ private tui: TuiHandle;
31
+ private selected = 0;
32
+ private cachedWidth: number | undefined;
33
+ private cachedLines: string[] | undefined;
34
+
35
+ constructor(
36
+ theme: Theme,
37
+ store: GtdStore,
38
+ tui: TuiHandle,
39
+ done: (result?: string) => void,
40
+ hooks: GtdPanelHooks,
41
+ ) {
42
+ this.theme = theme;
43
+ this.store = store;
44
+ this.tui = tui;
45
+ this.done = done;
46
+ this.hooks = hooks;
47
+ }
48
+
49
+ private ideas() {
50
+ return this.store.tasks.filter((t) => t.state === "idea");
51
+ }
52
+
53
+ /** Invalidate cache + request a fresh frame. */
54
+ private refresh(): void {
55
+ this.cachedWidth = undefined;
56
+ this.cachedLines = undefined;
57
+ this.tui.requestRender();
58
+ }
59
+
60
+ /** Clamp selection after list mutations. */
61
+ private clamp(): void {
62
+ const count = this.ideas().length;
63
+ this.selected = count === 0 ? 0 : Math.min(this.selected, count - 1);
64
+ }
65
+
66
+ handleInput(data: string): void {
67
+ const ideas = this.ideas();
68
+
69
+ if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c") || data === "q") {
70
+ this.done();
71
+ return;
72
+ }
73
+ if (matchesKey(data, "up") || data === "k") {
74
+ if (ideas.length > 0) {
75
+ this.selected = (this.selected - 1 + ideas.length) % ideas.length;
76
+ this.refresh();
77
+ }
78
+ return;
79
+ }
80
+ if (matchesKey(data, "down") || data === "j") {
81
+ if (ideas.length > 0) {
82
+ this.selected = (this.selected + 1) % ideas.length;
83
+ this.refresh();
84
+ }
85
+ return;
86
+ }
87
+ if (matchesKey(data, "return")) {
88
+ const idea = ideas[this.selected];
89
+ if (!idea) {
90
+ this.hooks.notify("📥 inbox empty — capture something with /gtd-i");
91
+ return;
92
+ }
93
+ setState(this.store, idea.id, "current");
94
+ this.clamp();
95
+ this.hooks.persist(this.store);
96
+ this.refresh();
97
+ return;
98
+ }
99
+ if (data === "d") {
100
+ const wasDone = completeCurrent(this.store);
101
+ if (!wasDone) {
102
+ this.hooks.notify("Nothing is current — nothing to done ✓");
103
+ return;
104
+ }
105
+ this.hooks.persist(this.store);
106
+ this.refresh();
107
+ return;
108
+ }
109
+ if (data === "x") {
110
+ const idea = ideas[this.selected];
111
+ if (!idea) return;
112
+ deleteTask(this.store, idea.id);
113
+ this.clamp();
114
+ this.hooks.persist(this.store);
115
+ this.refresh();
116
+ return;
117
+ }
118
+ }
119
+
120
+ invalidate(): void {
121
+ this.cachedWidth = undefined;
122
+ this.cachedLines = undefined;
123
+ }
124
+
125
+ render(width: number): string[] {
126
+ if (this.cachedLines && this.cachedWidth === width) return this.cachedLines;
127
+
128
+ const t = this.theme;
129
+ const current = getCurrent(this.store);
130
+ const ideas = this.ideas();
131
+ const doneToday = countDoneToday(this.store);
132
+ const lines: string[] = [];
133
+
134
+ lines.push(t.fg("accent", `📋 gtd — ${this.hooks.label}`));
135
+ if (current) {
136
+ for (const [i, text] of wrapTextWithAnsi(`${current.id} ${current.text}`, width).entries()) {
137
+ lines.push(t.fg("success", `${i === 0 ? "▶ " : " "}${text}`));
138
+ }
139
+ const lastNote = current.notes.at(-1);
140
+ if (lastNote) {
141
+ const raw = lastNote.type === "qa" ? `Q: ${lastNote.q} → ${lastNote.a}` : lastNote.text ?? "";
142
+ lines.push(t.fg("dim", ` last note: ${raw.replace(/\s+/g, " ").trim()}`));
143
+ }
144
+ } else {
145
+ lines.push(t.fg("dim", "▶ nothing current — select an idea, press ⏎"));
146
+ }
147
+
148
+ lines.push("");
149
+ if (ideas.length === 0) {
150
+ lines.push(t.fg("dim", " 📥 inbox empty — /gtd-i <text> to capture"));
151
+ } else {
152
+ for (const [i, idea] of ideas.entries()) {
153
+ const marker = i === this.selected ? t.fg("accent", "❯ ") : " ";
154
+ lines.push(`${marker}${idea.id} ${idea.text}`);
155
+ }
156
+ }
157
+
158
+ lines.push("");
159
+ lines.push(t.fg("dim", `✓ ${doneToday} done today`));
160
+ lines.push(t.fg("dim", "↑↓ select · ⏎ promote · d done · x drop · esc close"));
161
+
162
+ this.cachedWidth = width;
163
+ this.cachedLines = lines.map((line) => truncateToWidth(line, width));
164
+ return this.cachedLines;
165
+ }
166
+ }
package/lib/status.ts ADDED
@@ -0,0 +1,33 @@
1
+ /** pi-gtd — always-on status line (footer widget via ctx.ui.setStatus) */
2
+
3
+ import type { GtdStore } from "./types";
4
+ import { getCurrent, getIdeas, loadStore } from "./store";
5
+
6
+ function ellipsize(text: string, max: number): string {
7
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
8
+ }
9
+
10
+ /** One compact footer line, or undefined when there's nothing to show. */
11
+ export function statusText(store: GtdStore): string | undefined {
12
+ const current = getCurrent(store);
13
+ const ideas = getIdeas(store);
14
+ if (!current && ideas.length === 0) return undefined;
15
+ const cur = current ? `${current.id} ${ellipsize(current.text, 48)}` : "none";
16
+ return `▶ ${cur} · 📥 ${ideas.length}`;
17
+ }
18
+
19
+ /** Structural subset of the extension UI context we need — keeps this importable everywhere. */
20
+ export interface StatusCtx {
21
+ hasUI: boolean;
22
+ ui: { setStatus(key: string, text?: string): void };
23
+ }
24
+
25
+ /** Load the store and (re)set the footer status. Safe to call after any mutation. */
26
+ export function applyStatus(ctx: StatusCtx, path: string): void {
27
+ if (!ctx.hasUI) return;
28
+ try {
29
+ ctx.ui.setStatus("gtd", statusText(loadStore(path)));
30
+ } catch {
31
+ /* never let status rendering break a task operation */
32
+ }
33
+ }
package/lib/store.ts ADDED
@@ -0,0 +1,183 @@
1
+ /**
2
+ * pi-gtd — storage
3
+ *
4
+ * Two stores:
5
+ * <projectRoot>/.pi/gtd.json — tasks belonging to a project (gitignored by default)
6
+ * ~/.pi/agent/gtd/global.json — project-less ideas
7
+ *
8
+ * Project root = nearest ancestor of cwd containing `.git` or `.pi`.
9
+ */
10
+
11
+ import * as crypto from "node:crypto";
12
+ import * as fs from "node:fs";
13
+ import * as os from "node:os";
14
+ import * as path from "node:path";
15
+ import type { GtdNote, GtdState, GtdStore, GtdTask } from "./types";
16
+
17
+ export const GLOBAL_STORE = path.join(os.homedir(), ".pi", "agent", "gtd", "global.json");
18
+ const GITIGNORE_ENTRY = ".pi/gtd.json";
19
+
20
+ // ── path resolution ──────────────────────────────────────────────
21
+
22
+ export function findProjectRoot(cwd: string): string | null {
23
+ let dir = path.resolve(cwd);
24
+ for (;;) {
25
+ if (fs.existsSync(path.join(dir, ".git")) || fs.existsSync(path.join(dir, ".pi"))) {
26
+ return dir;
27
+ }
28
+ const parent = path.dirname(dir);
29
+ if (parent === dir) return null;
30
+ dir = parent;
31
+ }
32
+ }
33
+
34
+ export function storePathFor(cwd: string, forceGlobal = false): string {
35
+ if (forceGlobal) return GLOBAL_STORE;
36
+ const root = findProjectRoot(cwd);
37
+ return root ? path.join(root, ".pi", "gtd.json") : GLOBAL_STORE;
38
+ }
39
+
40
+ export function storeLabel(filePath: string): string {
41
+ return filePath === GLOBAL_STORE ? "global" : "project";
42
+ }
43
+
44
+ // ── load / save ──────────────────────────────────────────────────
45
+
46
+ export function loadStore(filePath: string): GtdStore {
47
+ try {
48
+ const data = JSON.parse(fs.readFileSync(filePath, "utf8"));
49
+ if (data && data.version === 1 && Array.isArray(data.tasks)) {
50
+ return { version: 1, currentId: data.currentId ?? null, tasks: data.tasks };
51
+ }
52
+ } catch {
53
+ /* missing or corrupt → fresh store (self-heal) */
54
+ }
55
+ return { version: 1, currentId: null, tasks: [] };
56
+ }
57
+
58
+ export function saveStore(filePath: string, store: GtdStore): void {
59
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
60
+ if (filePath !== GLOBAL_STORE) ensureGitignored(filePath);
61
+ const tmp = `${filePath}.tmp`;
62
+ fs.writeFileSync(tmp, `${JSON.stringify(store, null, "\t")}\n`);
63
+ fs.renameSync(tmp, filePath);
64
+ }
65
+
66
+ function ensureGitignored(storePath: string): void {
67
+ // storePath = <root>/.pi/gtd.json → root
68
+ const root = path.dirname(path.dirname(storePath));
69
+ const gitignore = path.join(root, ".gitignore");
70
+ try {
71
+ const existing = fs.existsSync(gitignore) ? fs.readFileSync(gitignore, "utf8") : "";
72
+ if (existing.split("\n").some((line) => line.trim() === GITIGNORE_ENTRY)) return;
73
+ const sep = existing === "" || existing.endsWith("\n") ? "" : "\n";
74
+ fs.writeFileSync(gitignore, `${existing}${sep}${GITIGNORE_ENTRY}\n`);
75
+ } catch {
76
+ /* best effort — never fail a task operation over gitignore */
77
+ }
78
+ }
79
+
80
+ // ── operations (pure-ish: mutate the store object, caller saves) ──
81
+
82
+ export function newId(): string {
83
+ return crypto.randomBytes(2).toString("hex");
84
+ }
85
+
86
+ export function addIdea(
87
+ store: GtdStore,
88
+ text: string,
89
+ project: string | null,
90
+ capturedDuring: string | null = null,
91
+ ): GtdTask {
92
+ const task: GtdTask = {
93
+ id: newId(),
94
+ text,
95
+ state: "idea",
96
+ project,
97
+ createdAt: new Date().toISOString(),
98
+ doneAt: null,
99
+ capturedDuring,
100
+ notes: [],
101
+ };
102
+ store.tasks.push(task);
103
+ return task;
104
+ }
105
+
106
+ export function getCurrent(store: GtdStore): GtdTask | null {
107
+ if (!store.currentId) return null;
108
+ const task = store.tasks.find((t) => t.id === store.currentId);
109
+ if (!task || task.state !== "current") return null; // dangling id → treat as none
110
+ return task;
111
+ }
112
+
113
+ export function getIdeas(store: GtdStore): GtdTask[] {
114
+ return store.tasks.filter((t) => t.state === "idea");
115
+ }
116
+
117
+ export function getDone(store: GtdStore): GtdTask[] {
118
+ return store.tasks.filter((t) => t.state === "done");
119
+ }
120
+
121
+ /** Promote the first idea (capture order) to current; demote the old current back to idea. */
122
+ export function promoteNext(store: GtdStore): { promoted: GtdTask; demoted: GtdTask | null } | null {
123
+ const promoted = getIdeas(store)[0];
124
+ if (!promoted) return null;
125
+ const demoted = getCurrent(store);
126
+ if (demoted) demoted.state = "idea";
127
+ promoted.state = "current";
128
+ store.currentId = promoted.id;
129
+ return { promoted, demoted };
130
+ }
131
+
132
+ /** Mark the current task done. Does not auto-promote — explicit /gtd-next keeps you in control. */
133
+ export function completeCurrent(store: GtdStore): GtdTask | null {
134
+ const current = getCurrent(store);
135
+ if (!current) return null;
136
+ current.state = "done";
137
+ current.doneAt = new Date().toISOString();
138
+ store.currentId = null;
139
+ return current;
140
+ }
141
+
142
+ /** Remove a task entirely (panel "drop"). Returns the removed task or null. */
143
+ export function deleteTask(store: GtdStore, id: string): GtdTask | null {
144
+ const idx = store.tasks.findIndex((t) => t.id === id);
145
+ if (idx === -1) return null;
146
+ const [task] = store.tasks.splice(idx, 1);
147
+ if (store.currentId === id) store.currentId = null;
148
+ return task;
149
+ }
150
+
151
+ /** Local (not UTC) calendar date as YYYY-MM-DD — "today" follows the user's wall clock. */
152
+ export function localDateKey(d: Date): string {
153
+ const m = `${d.getMonth() + 1}`.padStart(2, "0");
154
+ const day = `${d.getDate()}`.padStart(2, "0");
155
+ return `${d.getFullYear()}-${m}-${day}`;
156
+ }
157
+
158
+ export function countDoneToday(store: GtdStore): number {
159
+ const today = localDateKey(new Date());
160
+ return getDone(store).filter((t) => t.doneAt && localDateKey(new Date(t.doneAt)) === today).length;
161
+ }
162
+
163
+ /** Append a note to the current task. Returns the task, or null when nothing is current. */
164
+ export function addNoteToCurrent(store: GtdStore, note: GtdNote): GtdTask | null {
165
+ const current = getCurrent(store);
166
+ if (!current) return null;
167
+ current.notes.push(note);
168
+ return current;
169
+ }
170
+
171
+ export function setState(store: GtdStore, id: string, state: GtdState): GtdTask | null {
172
+ const task = store.tasks.find((t) => t.id === id);
173
+ if (!task) return null;
174
+ if (task.state === "current" && state !== "current") store.currentId = null;
175
+ if (state === "done") task.doneAt = new Date().toISOString();
176
+ if (state === "current") {
177
+ const old = getCurrent(store);
178
+ if (old && old.id !== task.id) old.state = "idea";
179
+ store.currentId = task.id;
180
+ }
181
+ task.state = state;
182
+ return task;
183
+ }
package/lib/types.ts ADDED
@@ -0,0 +1,35 @@
1
+ /** pi-gtd — types */
2
+
3
+ export type GtdState = "current" | "idea" | "done";
4
+
5
+ export interface GtdNote {
6
+ type: "qa" | "note";
7
+ /** for qa notes */
8
+ q?: string;
9
+ a?: string;
10
+ /** for plain notes */
11
+ text?: string;
12
+ /** ISO timestamp */
13
+ at: string;
14
+ }
15
+
16
+ export interface GtdTask {
17
+ /** 4-char hex id, unique within its store */
18
+ id: string;
19
+ text: string;
20
+ state: GtdState;
21
+ /** cwd where the task was captured (null = global / project-less) */
22
+ project: string | null;
23
+ createdAt: string;
24
+ doneAt: string | null;
25
+ /** id of the task that was current when this idea was captured */
26
+ capturedDuring: string | null;
27
+ notes: GtdNote[];
28
+ }
29
+
30
+ export interface GtdStore {
31
+ version: 1;
32
+ /** exactly one current task per store (or null) */
33
+ currentId: string | null;
34
+ tasks: GtdTask[];
35
+ }
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@serendevity/pi-gtd",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "description": "Personal GTD for pi — capture stray ideas, keep exactly one current task, and let every session resume where you left off.",
5
+ "type": "module",
6
+ "keywords": [
7
+ "pi-package",
8
+ "gtd",
9
+ "task-tracking",
10
+ "pi",
11
+ "extension"
12
+ ],
13
+ "license": "MIT",
14
+ "pi": {
15
+ "extensions": [
16
+ "./index.ts"
17
+ ]
18
+ },
19
+ "files": [
20
+ "index.ts",
21
+ "lib/types.ts",
22
+ "lib/store.ts",
23
+ "lib/format.ts",
24
+ "lib/status.ts",
25
+ "lib/panel.ts",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "scripts": {
30
+ "test": "vitest run",
31
+ "typecheck": "tsc -p tsconfig.check.json"
32
+ },
33
+ "peerDependencies": {
34
+ "@earendil-works/pi-agent-core": "*",
35
+ "@earendil-works/pi-ai": "*",
36
+ "@earendil-works/pi-coding-agent": "*",
37
+ "@earendil-works/pi-tui": "*",
38
+ "typebox": "*"
39
+ },
40
+ "devDependencies": {
41
+ "@earendil-works/pi-agent-core": "^1.8.0",
42
+ "@earendil-works/pi-ai": "^1.8.0",
43
+ "@earendil-works/pi-coding-agent": "^1.8.0",
44
+ "@earendil-works/pi-tui": "^1.8.0",
45
+ "@types/node": "^26.6.11",
46
+ "typebox": "^1.4.7",
47
+ "typescript": "^5.9.3",
48
+ "vitest": "^4.0.14"
49
+ },
50
+ "repository": {
51
+ "type": "git",
52
+ "url": "git+https://github.com/khattaksd/pi-gtd.git"
53
+ },
54
+ "bugs": {
55
+ "url": "https://github.com/khattaksd/pi-gtd/issues"
56
+ },
57
+ "homepage": "https://github.com/khattaksd/pi-gtd#readme",
58
+ "publishConfig": {
59
+ "access": "public"
60
+ }
61
+ }