@hcflabs/pi-notes 0.0.0-stage → 3.3.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.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Henry Wang
4
+ Copyright (c) 2026 hcflabs
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,42 @@
1
- # Temporary Holding Version
1
+ # `@hcflabs/pi-notes`
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
+ Keep worktree reminders above the Pi editor across sessions.
4
+
5
+ ![Pi showing two persistent notes above the editor](./example.png)
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pi install npm:@hcflabs/pi-notes
11
+ ```
12
+
13
+ ## Use
14
+
15
+ Run `/note Verify the migration rollback.` in a Git worktree or any other directory. The reminder appears immediately and in later sessions.
16
+
17
+ These commands and the widget are for people.
18
+
19
+ | Surface | Type | Purpose |
20
+ | --- | --- | --- |
21
+ | `/note <text>` | command | Add a worktree note. |
22
+ | `/note-rm` | command | Select and remove a note. |
23
+ | `/note-clear` | command | Clear worktree notes. |
24
+ | Notes widget | ui | Show worktree notes. |
25
+
26
+ Each worktree has separate notes. Outside a Git repository, for example in a parent directory that holds many repositories, the notes belong to the real path of the working directory. A subdirectory of that directory has its own notes. The TUI numbers notes and limits each to two lines. Other modes show plain text without that limit. Empty widgets stay hidden.
27
+
28
+ ## State and storage
29
+
30
+ Commands save notes to `~/.pi/agent/config/pi-notes/<worktree-sha256>.json`. Outside a Git repository, the hash is of the real path of the working directory.
31
+
32
+ Session start and note changes silently delete stale files for removed repositories, worktrees, and directories.
33
+
34
+ If a directory with notes becomes a Git repository, the old notes do not apply to it. The widget shows `Worktree notes belong to an old worktree; run /note-clear to reset.`
35
+
36
+ ## Limits and recovery
37
+
38
+ Each worktree or directory holds at most four notes. `/note` trims surrounding whitespace and replaces whitespace sequences with one space. It rejects remaining control characters with `Notes cannot contain terminal control characters.`
39
+
40
+ The extension validates files as untrusted data. Malformed files stay unchanged and block changes for their worktree. Fix the file or reset it with `/note-clear`.
41
+
42
+ Git failures other than "not a Git repository" are errors. Examples are a Git timeout, a missing `git` program, and a bare repository. The commands show the error and change no file. The widget stays empty.
package/example.png ADDED
Binary file
@@ -0,0 +1,314 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFile, readdir, realpath, rm, stat } from "node:fs/promises";
3
+ import { isAbsolute, join } from "node:path";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import {
6
+ type ExtensionAPI,
7
+ type ExtensionContext,
8
+ } from "@earendil-works/pi-coding-agent";
9
+ import { extensionConfigDir, writePrivateTextFileAtomically } from "@hcflabs/pi-config-store";
10
+ import { gitTopLevel } from "@hcflabs/pi-repo";
11
+ import { truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
12
+
13
+ const MAX_NOTES = 4;
14
+ const WIDGET_KEY = "pi-notes";
15
+
16
+ interface WorktreeIdentity {
17
+ repository: string;
18
+ worktree: string;
19
+ gitDir: string;
20
+ generation: string;
21
+ }
22
+
23
+ interface NotesRecord extends WorktreeIdentity {
24
+ notes: string[];
25
+ }
26
+
27
+ const configDir = () => extensionConfigDir("pi-notes");
28
+ const notesPath = (worktree: string) => join(configDir(), `${createHash("sha256").update(worktree).digest("hex")}.json`);
29
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/u;
30
+
31
+ const isSafeNote = (note: unknown): note is string =>
32
+ typeof note === "string" && note.trim().length > 0 && !CONTROL_CHARACTERS.test(note);
33
+
34
+ async function worktreeGeneration(gitDir: string): Promise<string> {
35
+ const metadata = await stat(gitDir, { bigint: true });
36
+ return `${metadata.dev}:${metadata.ino}:${metadata.birthtimeNs}`;
37
+ }
38
+
39
+ /** Notes files are untrusted user data. Invalid records throw so callers preserve them. */
40
+ export function parseNotes(raw: string): NotesRecord {
41
+ const data: unknown = JSON.parse(raw);
42
+ const input = data as Record<string, unknown>;
43
+ if (Object.keys(input).sort().join(",") !== "generation,gitDir,notes,repository,worktree"
44
+ || typeof input.repository !== "string" || !isAbsolute(input.repository)
45
+ || typeof input.worktree !== "string" || !isAbsolute(input.worktree)
46
+ || typeof input.gitDir !== "string" || !isAbsolute(input.gitDir)
47
+ || typeof input.generation !== "string" || !/^\d+:\d+:\d+$/.test(input.generation)
48
+ || !Array.isArray(input.notes)
49
+ || input.notes.length > MAX_NOTES
50
+ || !input.notes.every(isSafeNote)) {
51
+ throw new TypeError(`notes config must identify one worktree and contain at most ${MAX_NOTES} safe non-empty strings`);
52
+ }
53
+ return { ...input, notes: input.notes.map((note) => note.replace(/\s+/g, " ").trim()) } as NotesRecord;
54
+ }
55
+
56
+ function renderNotes(notes: string[]): string[] {
57
+ return notes.map((note, i) => `${i + 1}. ${note}`);
58
+ }
59
+
60
+ export function renderNotesWidget(notes: string[], width: number): string[] {
61
+ const renderWidth = Math.max(1, width);
62
+ return renderNotes(notes).flatMap((note) => {
63
+ const lines = wrapTextWithAnsi(note, renderWidth);
64
+ return lines.length > 2
65
+ ? [lines[0]!, truncateToWidth(`${lines[1]}…`, renderWidth, "…")]
66
+ : lines;
67
+ });
68
+ }
69
+
70
+ function setNotesWidget(ctx: ExtensionContext, notes: string[]): void {
71
+ if (!notes.length) {
72
+ ctx.ui.setWidget(WIDGET_KEY, undefined);
73
+ return;
74
+ }
75
+ if (ctx.mode !== "tui") {
76
+ ctx.ui.setWidget(WIDGET_KEY, renderNotes(notes));
77
+ return;
78
+ }
79
+ ctx.ui.setWidget(WIDGET_KEY, () => ({
80
+ invalidate() {},
81
+ render: (width) => renderNotesWidget(notes, width),
82
+ }));
83
+ }
84
+
85
+ /**
86
+ * Read the identity of the Git worktree that contains `cwd`.
87
+ * Return `undefined` when `cwd` is outside a Git repository.
88
+ * Other Git failures throw, for example a timeout, a missing Git program, or a bare repository.
89
+ */
90
+ async function gitWorktree(pi: ExtensionAPI, cwd: string): Promise<WorktreeIdentity | undefined> {
91
+ const result = await pi.exec(
92
+ "git",
93
+ ["rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir", "--git-dir"],
94
+ { cwd },
95
+ );
96
+ if (result.killed) throw new Error(`git did not finish in ${cwd}`);
97
+ if (result.code !== 0) {
98
+ // gitTopLevel decides without Git messages, so the answer does not depend on the Git locale.
99
+ if (await gitTopLevel(cwd) === undefined) return undefined;
100
+ throw new Error(`git rev-parse failed in ${cwd} with exit ${result.code}`);
101
+ }
102
+ const [worktree, repository, gitDir, ...extra] = result.stdout.trim().split(/\r?\n/);
103
+ if (!worktree || !repository || !gitDir || extra.length) throw new Error("git returned an invalid worktree identity");
104
+ const [canonicalWorktree, canonicalRepository, canonicalGitDir] = await Promise.all([
105
+ realpath(worktree),
106
+ realpath(repository),
107
+ realpath(gitDir),
108
+ ]);
109
+ return {
110
+ worktree: canonicalWorktree,
111
+ repository: canonicalRepository,
112
+ gitDir: canonicalGitDir,
113
+ generation: await worktreeGeneration(canonicalGitDir),
114
+ };
115
+ }
116
+
117
+ /** Outside a Git repository, the real path of the directory names the notes. The three paths are equal. */
118
+ async function directoryIdentity(cwd: string): Promise<WorktreeIdentity> {
119
+ const directory = await realpath(cwd);
120
+ return { worktree: directory, repository: directory, gitDir: directory, generation: await worktreeGeneration(directory) };
121
+ }
122
+
123
+ const isDirectoryIdentity = ({ worktree, repository, gitDir }: WorktreeIdentity) => worktree === repository && repository === gitDir;
124
+
125
+ async function resolveWorktree(pi: ExtensionAPI, cwd: string): Promise<WorktreeIdentity> {
126
+ return await gitWorktree(pi, cwd) ?? await directoryIdentity(cwd);
127
+ }
128
+
129
+ async function loadNotes(identity: WorktreeIdentity): Promise<{ notes: string[]; message?: string }> {
130
+ let raw: string;
131
+ try {
132
+ raw = await readFile(notesPath(identity.worktree), "utf8");
133
+ } catch (error) {
134
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { notes: [] };
135
+ throw error;
136
+ }
137
+ let record: NotesRecord;
138
+ try {
139
+ record = parseNotes(raw);
140
+ } catch {
141
+ return { notes: [], message: "Worktree notes file is malformed; fix it or run /note-clear to reset." };
142
+ }
143
+ const { notes, ...recordIdentity } = record;
144
+ return isDeepStrictEqual(recordIdentity, identity)
145
+ ? { notes }
146
+ : { notes: [], message: "Worktree notes belong to an old worktree; run /note-clear to reset." };
147
+ }
148
+
149
+ async function persist(identity: WorktreeIdentity, notes: string[]): Promise<void> {
150
+ await writePrivateTextFileAtomically(notesPath(identity.worktree), `${JSON.stringify({ ...identity, notes }, null, "\t")}\n`);
151
+ }
152
+
153
+ async function readCurrent(pi: ExtensionAPI, ctx: ExtensionContext): Promise<{ identity: WorktreeIdentity; notes: string[] } | undefined> {
154
+ try {
155
+ const identity = await resolveWorktree(pi, ctx.cwd);
156
+ const { notes, message } = await loadNotes(identity);
157
+ if (message) {
158
+ ctx.ui.notify(message, "error");
159
+ return undefined;
160
+ }
161
+ return { identity, notes };
162
+ } catch (error) {
163
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
164
+ return undefined;
165
+ }
166
+ }
167
+
168
+ async function refresh(pi: ExtensionAPI, ctx: ExtensionContext): Promise<void> {
169
+ try {
170
+ const { notes, message } = await loadNotes(await resolveWorktree(pi, ctx.cwd));
171
+ if (message) ctx.ui.setWidget(WIDGET_KEY, [message]);
172
+ else setNotesWidget(ctx, notes);
173
+ } catch {
174
+ ctx.ui.setWidget(WIDGET_KEY, undefined);
175
+ }
176
+ }
177
+
178
+ async function pruneStale(pi: ExtensionAPI): Promise<void> {
179
+ let entries;
180
+ try {
181
+ entries = await readdir(configDir(), { withFileTypes: true });
182
+ } catch (error) {
183
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
184
+ throw error;
185
+ }
186
+ for (const entry of entries) {
187
+ if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
188
+ const path = join(configDir(), entry.name);
189
+ let record: NotesRecord;
190
+ try {
191
+ record = parseNotes(await readFile(path, "utf8"));
192
+ } catch {
193
+ continue;
194
+ }
195
+ if (path !== notesPath(record.worktree)) continue;
196
+ let stale = false;
197
+ try {
198
+ const [worktree, repository, gitDir] = await Promise.all([
199
+ realpath(record.worktree),
200
+ realpath(record.repository),
201
+ realpath(record.gitDir),
202
+ ]);
203
+ stale = worktree !== record.worktree
204
+ || repository !== record.repository
205
+ || gitDir !== record.gitDir
206
+ || await worktreeGeneration(gitDir) !== record.generation;
207
+ } catch (error) {
208
+ const code = (error as NodeJS.ErrnoException).code;
209
+ if (code === "ENOENT" || code === "ENOTDIR") stale = true;
210
+ else continue;
211
+ }
212
+ // A directory record has no Git identity to compare. If the directory becomes a repository, /note-clear resets it.
213
+ if (!stale && !isDirectoryIdentity(record)) {
214
+ let current: WorktreeIdentity | undefined;
215
+ try {
216
+ current = await gitWorktree(pi, record.worktree);
217
+ } catch {
218
+ continue;
219
+ }
220
+ if (!current) continue;
221
+ const { notes, ...identity } = record;
222
+ stale = !isDeepStrictEqual(current, identity);
223
+ }
224
+ if (stale) await rm(path, { force: true });
225
+ }
226
+ }
227
+
228
+ async function pruneStaleNotes(pi: ExtensionAPI, ctx: ExtensionContext): Promise<void> {
229
+ try {
230
+ await pruneStale(pi);
231
+ } catch (error) {
232
+ ctx.ui.notify(`Failed to prune stale notes: ${error instanceof Error ? error.message : String(error)}`, "error");
233
+ }
234
+ }
235
+
236
+ export default function notesExtension(pi: ExtensionAPI): void {
237
+ pi.on("session_start", async (_event, ctx) => {
238
+ await pruneStaleNotes(pi, ctx);
239
+ await refresh(pi, ctx);
240
+ });
241
+
242
+ pi.registerCommand("note", {
243
+ description: `Add a note to this Git worktree or directory (max ${MAX_NOTES})`,
244
+ handler: async (args, ctx) => {
245
+ const text = args.replace(/\s+/g, " ").trim();
246
+ if (!text) {
247
+ ctx.ui.notify("Usage: /note <text>", "warning");
248
+ return;
249
+ }
250
+ if (!isSafeNote(text)) {
251
+ ctx.ui.notify("Notes cannot contain terminal control characters.", "warning");
252
+ return;
253
+ }
254
+ const current = await readCurrent(pi, ctx);
255
+ if (!current) return;
256
+ if (current.notes.length >= MAX_NOTES) {
257
+ ctx.ui.notify(`Widget full (${MAX_NOTES} notes). Remove one with /note-rm.`, "warning");
258
+ return;
259
+ }
260
+ current.notes.push(text);
261
+ await persist(current.identity, current.notes);
262
+ setNotesWidget(ctx, current.notes);
263
+ await pruneStaleNotes(pi, ctx);
264
+ },
265
+ });
266
+
267
+ pi.registerCommand("note-rm", {
268
+ description: "Remove a note from this Git worktree or directory",
269
+ handler: async (args, ctx) => {
270
+ if (args.trim()) {
271
+ ctx.ui.notify("Usage: /note-rm", "warning");
272
+ return;
273
+ }
274
+ const snapshot = await readCurrent(pi, ctx);
275
+ if (!snapshot) return;
276
+ if (!snapshot.notes.length) {
277
+ ctx.ui.notify("No notes to remove.", "info");
278
+ return;
279
+ }
280
+ const options = renderNotes(snapshot.notes);
281
+ const choice = await ctx.ui.select("Remove note:", options);
282
+ if (!choice) return;
283
+ const current = await readCurrent(pi, ctx);
284
+ if (!current) return;
285
+ const index = options.indexOf(choice);
286
+ if (!isDeepStrictEqual(current, snapshot)) {
287
+ ctx.ui.notify("Notes changed elsewhere; try /note-rm again.", "warning");
288
+ return;
289
+ }
290
+ current.notes.splice(index, 1);
291
+ await persist(current.identity, current.notes);
292
+ setNotesWidget(ctx, current.notes);
293
+ await pruneStaleNotes(pi, ctx);
294
+ },
295
+ });
296
+
297
+ pi.registerCommand("note-clear", {
298
+ description: "Clear notes for this Git worktree or directory",
299
+ handler: async (args, ctx) => {
300
+ if (args.trim()) {
301
+ ctx.ui.notify("Usage: /note-clear", "warning");
302
+ return;
303
+ }
304
+ try {
305
+ const identity = await resolveWorktree(pi, ctx.cwd);
306
+ await rm(notesPath(identity.worktree), { force: true });
307
+ setNotesWidget(ctx, []);
308
+ await pruneStaleNotes(pi, ctx);
309
+ } catch (error) {
310
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
311
+ }
312
+ },
313
+ });
314
+ }
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@hcflabs/pi-notes",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "3.3.0",
4
+ "description": "Persistent notes in a Pi widget, managed with /note commands.",
5
+ "keywords": [
6
+ "pi-package",
7
+ "pi",
8
+ "notes",
9
+ "widget"
10
+ ],
11
+ "type": "module",
12
+ "engines": {
13
+ "node": ">=22.19.0"
14
+ },
15
+ "license": "MIT",
16
+ "files": [
17
+ "LICENSE",
18
+ "extensions",
19
+ "README.md",
20
+ "example.png"
21
+ ],
22
+ "scripts": {
23
+ "test": "node --test test/*.test.ts",
24
+ "typecheck": "tsc --noEmit --allowImportingTsExtensions --target ES2022 --module NodeNext --moduleResolution NodeNext --skipLibCheck extensions/*.ts test/*.test.ts",
25
+ "pack:check": "npm pack --dry-run"
26
+ },
27
+ "peerDependencies": {
28
+ "@earendil-works/pi-coding-agent": "^1.6.0",
29
+ "@earendil-works/pi-tui": "^1.6.0"
30
+ },
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/hcflabs/pi-harness.git",
34
+ "directory": "extensions/pi-notes"
35
+ },
36
+ "bugs": {
37
+ "url": "https://github.com/hcflabs/pi-harness/issues"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "pi": {
43
+ "extensions": [
44
+ "./extensions/notes.ts"
45
+ ],
46
+ "image": "https://raw.githubusercontent.com/hcflabs/pi-harness/main/extensions/pi-notes/example.png"
47
+ },
48
+ "dependencies": {
49
+ "@hcflabs/pi-config-store": "^4.0.0",
50
+ "@hcflabs/pi-repo": "^0.1.0"
51
+ },
52
+ "devDependencies": {
53
+ "@earendil-works/pi-coding-agent": "1.6.0",
54
+ "@earendil-works/pi-tui": "1.6.0"
55
+ }
56
+ }