-
Notifications
You must be signed in to change notification settings - Fork 163
feat(history): read, ordering, deduplication, and project/global query APIs (slice 2/6) #1392
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
9b56e0b
2b90751
a5ff13d
73c55ff
84c1232
31e7d50
5501d12
ecf148b
892da55
aae37cb
6e27038
f11fdba
d50702d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| # Prompt history | ||
|
|
||
| Slice 1 of the prompt-history extension (#819 split) ships the storage layer only: | ||
| a per-instance JSONL capture store, project identity, and the read/write | ||
| primitives later slices build on. The selector UI, deletion/scope drains, and GC | ||
| arrive in later slices of the chain. | ||
|
|
||
| ## Capture is opt-in | ||
|
|
||
| Recording is **off by default**. Delivered prompts can contain secrets, and the | ||
| deletion UI is not shipped yet, so nothing is stored unless you explicitly opt in: | ||
|
|
||
| ```bash | ||
| GENTLE_PI_HISTORY_CAPTURE=1 pi | ||
| ``` | ||
|
|
||
| - Enabled by `1`, `true`, or `on` (case-insensitive). Unset, empty, or any other | ||
| value means **off** — the same switch is the disable path. | ||
| - The check runs per prompt: unsetting the switch (or setting it to `0`) stops | ||
| new captures immediately, no pi restart needed. | ||
| - With capture off the extension is inert: no registry entry, no files, and | ||
| prompts are never written. | ||
|
|
||
| ## Where the files live | ||
|
|
||
| Everything sits under `~/.pi/agent/history/`: | ||
|
|
||
| - `registry.json` — advisory map of project hash → cwd, used for display | ||
| labels. | ||
| - `projects/<hash>/<instance>.jsonl` — one append-only capture file per pi | ||
| process. | ||
|
|
||
| `<hash>` is the first 16 hex chars of the SHA-256 of the canonicalized project | ||
| cwd; `<instance>` is a per-process UUID. Each line is one delivered prompt: | ||
|
|
||
| ```json | ||
| {"v":1,"text":"the prompt as delivered","ts":1700000000000} | ||
| ``` | ||
|
|
||
| UI command-like prompts (`/name ...`) and empty lines are never stored. Later | ||
| slices add the rebuildable `seed.jsonl`, scope drains/deletes, and GC. | ||
|
|
||
| ## Who can read them | ||
|
|
||
| The store is plain JSONL on your local disk, not encrypted. Files are created by | ||
| the pi process with default umask permissions (typically `0644` files inside | ||
| `0755` directories), so any process running as your OS user can read them, and | ||
| other local accounts can too wherever they can traverse your home directory. | ||
| Treat the store as sensitive: it holds your prompts verbatim. | ||
|
|
||
| ## What disabling capture does | ||
|
|
||
| Turning the switch off only stops **new** captures. Nothing is deleted: files | ||
| already written — and the registry entry — stay on disk until you remove them or | ||
| the deletion UI ships. To erase the store manually while capture is off (or pi | ||
| is not running): | ||
|
|
||
| ```bash | ||
| rm -rf ~/.pi/agent/history # whole store | ||
| rm -rf ~/.pi/agent/history/projects/<hash> # one project (see registry.json) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win Make the project-removal command executable. In a shell, 🤖 Prompt for AI Agents |
||
| ``` | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| import path from "node:path"; | ||
| // SPDX-FileCopyrightText: 2026 ExoPro. Inspired by @jasonish/pi-prompt-history | ||
| // SPDX-License-Identifier: MIT | ||
|
|
||
| import fs from "node:fs"; | ||
|
|
||
| /** | ||
| * Shared atomic JSON writer (design §D3): serialize to a `.tmp` file in the | ||
| * SAME directory as the target, then renameSync it into place — a same-dir | ||
| * rename is atomic on POSIX/APFS, so readers see the old or the new file, | ||
| * never a partial write. Any error returns false and never throws. | ||
| * | ||
| * No fsync: both consumers treat lost writes as derived cache (a lost index | ||
| * rebuilds on the next open; a lost tombstone resurfaces a prompt the user | ||
| * can re-delete), so the per-write fsync cost is not justified — the crash | ||
| * window is documented, not fixed. The staging name is unique per write | ||
| * (`.tmp-<pid>-<ts>`, the same convention as the store.ts writers): the | ||
| * state dir is shared across concurrent pi instances, so a fixed | ||
| * `${filePath}.tmp` would let two writers clobber the same staging file | ||
| * (torn target JSON, spurious rename failures). A failed write unlinks its | ||
| * staging file, so orphaned `.tmp` files do not accumulate. | ||
| */ | ||
| export function writeJsonAtomic(filePath: string, value: unknown): boolean { | ||
| const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`; | ||
| try { | ||
| fs.mkdirSync(path.dirname(filePath), { recursive: true }); | ||
| fs.writeFileSync(tmpPath, JSON.stringify(value), "utf8"); | ||
| fs.renameSync(tmpPath, filePath); | ||
| return true; | ||
| } catch { | ||
| try { | ||
| fs.unlinkSync(tmpPath); | ||
| } catch { | ||
| // staging file never created or already renamed | ||
| } | ||
| return false; | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| // SPDX-FileCopyrightText: 2026 ExoPro. Inspired by @jasonish/pi-prompt-history | ||
| // SPDX-License-Identifier: MIT | ||
|
|
||
| import fs from "node:fs"; | ||
| import path from "node:path"; | ||
| import { writeJsonAtomic } from "./atomic-write.ts"; | ||
| import { promptDedupKey } from "./selector-helpers.ts"; | ||
|
|
||
| /** Name of the tombstone file inside the injected state dir (spec C4). */ | ||
| const HIDE_FILE_NAME = "hidden.json"; | ||
|
|
||
| /** | ||
| * Shared recovery warning for a file that exists but cannot be trusted | ||
| * (spec C4, fail-closed READ half): toast-suitable, names hidden.json, and | ||
| * gives the user the explicit restore-or-delete choice. | ||
| */ | ||
| const RECOVERY_MESSAGE = | ||
| "The prompt-history hide list (hidden.json) is corrupt or unreadable. History is blocked until you restore the file or delete it (hidden prompts may then reappear)."; | ||
|
|
||
| /** | ||
| * Result of one tombstone write (spec C4): `written` on a successful atomic | ||
| * write, or an error object carrying a short, toast-suitable reason. Never | ||
| * throws. | ||
| */ | ||
| export type HideResult = | ||
| | { status: "written" } | ||
| | { status: "error"; message: string }; | ||
|
|
||
| /** | ||
| * Result of one tombstone read (spec C4): `trusted` keys when the file is | ||
| * missing or holds a valid array, or `untrusted` when the file exists but | ||
| * cannot be trusted. History reads FAIL CLOSED on `untrusted`: callers must | ||
| * block the drain instead of emptying the tombstone set, because hidden | ||
| * prompts may contain secrets an empty set would resurface. | ||
| */ | ||
| export type HiddenRead = | ||
| | { status: "trusted"; keys: Set<string> } | ||
| | { | ||
| status: "untrusted"; | ||
| reason: "unreadable" | "corrupt" | "malformed"; | ||
| message: string; | ||
| }; | ||
|
|
||
| /** | ||
| * Read the tombstone key set from `stateDir/hidden.json` — the READ half of | ||
| * the hide-file contract (spec C4). Fail-closed for history: a file that | ||
| * exists but is unreadable, corrupt, or wrong-shaped returns `untrusted` | ||
| * with the recovery warning so callers block the drain; it never degrades | ||
| * to an empty trusted set. A MISSING file — before any deletion — is the | ||
| * safe empty case and reads `trusted` with no keys. A valid array is | ||
| * trusted; junk items inside it are ignored, never trusted. Keys are | ||
| * `promptDedupKey` strings written by `hidePrompt`; the call never throws. | ||
| */ | ||
| export function readHiddenPrompts(stateDir: string): HiddenRead { | ||
| let raw: string; | ||
| try { | ||
| raw = fs.readFileSync(path.join(stateDir, HIDE_FILE_NAME), "utf8"); | ||
| } catch (error) { | ||
| const code = (error as { code?: unknown } | null | undefined)?.code; | ||
| if (code === "ENOENT") { | ||
| // Missing before any deletion: the safe empty tombstone set. | ||
| return { status: "trusted", keys: new Set<string>() }; | ||
| } | ||
| return { | ||
| status: "untrusted", | ||
| reason: "unreadable", | ||
| message: RECOVERY_MESSAGE, | ||
| }; | ||
| } | ||
| let parsed: unknown; | ||
| try { | ||
| parsed = JSON.parse(raw); | ||
| } catch { | ||
| return { status: "untrusted", reason: "corrupt", message: RECOVERY_MESSAGE }; | ||
| } | ||
| const keys = new Set<string>(); | ||
| if (!Array.isArray(parsed)) { | ||
| return { | ||
| status: "untrusted", | ||
| reason: "malformed", | ||
| message: RECOVERY_MESSAGE, | ||
| }; | ||
| } | ||
| for (const item of parsed) { | ||
| if (typeof item === "string" && item !== "") keys.add(item); | ||
| } | ||
| return { status: "trusted", keys }; | ||
| } | ||
|
|
||
| /** | ||
| * Write the tombstone key for `text` into `stateDir/hidden.json` — the | ||
| * WRITE half of the hide-file contract (spec C4). The key is the shared | ||
| * `promptDedupKey` (byte-match normative with the merge filter — never a | ||
| * re-implementation); the set compacts on write and persists as a SORTED | ||
| * array via the shared atomic tmp+rename writer. An untrusted existing file | ||
| * is never silently reset (a clean rewrite would clear the blocked state | ||
| * one hide later): hidePrompt refuses with the recovery warning until the | ||
| * user restores or deletes the file. A missing file is the clean baseline; | ||
| * any write failure returns an error object for the delete-flow toast; the | ||
| * call never throws. | ||
| */ | ||
| export function hidePrompt(stateDir: string, text: string): HideResult { | ||
| const read = readHiddenPrompts(stateDir); | ||
| if (read.status === "untrusted") { | ||
| // Refuse without writing: never reset the untrusted state silently. | ||
| return { status: "error", message: read.message }; | ||
| } | ||
| read.keys.add(promptDedupKey(text)); | ||
| const written = writeJsonAtomic( | ||
| path.join(stateDir, HIDE_FILE_NAME), | ||
| [...read.keys].sort(), | ||
|
Comment on lines
+103
to
+111
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift 🔎 Supported by static analysis🏁 Script executed: sed -n '1,125p' extensions/history/hide-prompts.ts
sed -n '1,42p' extensions/history/atomic-write.ts
git log --format='%h %s' -- extensions/history/hide-prompts.ts | head -15Repository: Gentleman-Programming/gentle-shell Length of output: 6478 🏁 Script executed: #!/bin/bash
set -u
rg -n -S 'hidePrompt|readHiddenPrompts|writeJsonAtomic|lockSync|openSync|flock|mutex|semaphore|withLock|HIDE_FILE_NAME|hidden\.json' extensions README.md docs 2>/dev/null | head -240
printf '%s\n' '--- diff ---'
git diff --stat 777238324bd729a5a9c5817fe00373002ef666a4 5501d12d1ddc39e7efed2c6f5908b23364d6fcef -- extensions/history
git diff --unified=25 777238324bd729a5a9c5817fe00373002ef666a4 5501d12d1ddc39e7efed2c6f5908b23364d6fcef -- extensions/history/hide-prompts.ts extensions/history/atomic-write.ts
printf '%s\n' '--- finding search ---'
rg -n -S 'published-4088537435|4088537435|read-modify-write|lost update|tombstone|concurr' . --glob '!node_modules/**' --glob '!dist/**' --glob '!build/**' 2>/dev/null | head -240Repository: Gentleman-Programming/gentle-shell Length of output: 32166 🏁 Script executed: #!/bin/bash
set -u
printf '%s\n' '--- public history index ---'
cat -n extensions/history/index.ts | sed -n '1,180p'
printf '%s\n' '--- hide-related tests and exports ---'
rg -n -S 'hidePrompt|readHiddenPrompts|hidden\.json|hide' extensions/history tests/history* --glob '*.ts' --glob '*.mjs' | head -260
printf '%s\n' '--- parent-to-head diff ---'
git diff --stat a5ff13d64d 5501d12d1ddc39e7efed2c6f5908b23364d6f5908b23364d6fcef -- extensions/history
git diff --unified=12 a5ff13d64d 5501d12d1ddc39e7efed2c6f5908b23364d6fcef -- extensions/history/hide-prompts.ts extensions/history/atomic-write.ts extensions/history/index.tsRepository: Gentleman-Programming/gentle-shell Length of output: 16687 Serialize the entire When two instances call Re-reading before the rename does not prevent this race because both calls can still read before either rename. Use one shared exclusive lock for the complete read/add/write sequence, with stale-lock handling. 🤖 Prompt for AI Agents |
||
| ); | ||
| return written | ||
| ? { status: "written" } | ||
| : { | ||
| status: "error", | ||
| message: "Could not write the hide file; the prompt may reappear.", | ||
| }; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| // SPDX-FileCopyrightText: 2026 ExoPro. Inspired by @jasonish/pi-prompt-history | ||
| // SPDX-License-Identifier: MIT | ||
|
|
||
| // Prompt-history extension entry (slice 1): identity constants, the | ||
| // per-instance writer lifecycle, and the before_agent_start capture | ||
| // handler. Selector UI, shortcut/command, scope drains, legacy migration | ||
| // and seed bootstrap, and GC arrive in later slices. | ||
| // | ||
| // Capture is OPT-IN while the deletion/privacy behavior is unshipped: | ||
| // nothing is recorded unless GENTLE_PI_HISTORY_CAPTURE=1|true|on. With the | ||
| // switch off the handler is a no-op — no registry entry, no files, and | ||
| // prompts are never written. Unsetting the switch only stops NEW captures; | ||
| // files already written stay on disk (docs/prompt-history.md). | ||
|
|
||
| import { randomUUID } from "node:crypto"; | ||
| import { homedir } from "node:os"; | ||
| import { join } from "node:path"; | ||
| import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; | ||
| import { | ||
| appendSessionCapture, | ||
| ensureRegistryEntry, | ||
| openSessionWriter, | ||
| type SessionWriterState, | ||
| } from "./store.ts"; | ||
|
|
||
| // v2 multi-concurrency store root (design: tmp/multi-concurrency-design.md). | ||
| const PI_HISTORY_ROOT = join(homedir(), ".pi", "agent", "history"); | ||
|
|
||
| export interface HistoryDeps { | ||
| env?: NodeJS.ProcessEnv; | ||
| root?: string; | ||
| cwd?: string; | ||
| instanceId?: string; | ||
| now?: () => number; | ||
| } | ||
|
|
||
| /** | ||
| * Strict opt-in: capture stays off unless GENTLE_PI_HISTORY_CAPTURE is | ||
| * explicitly 1, true, or on (case-insensitive). The same switch is the | ||
| * disable path — unsetting it stops new captures; files already on disk | ||
| * are left untouched until the deletion tooling lands. | ||
| */ | ||
| export function captureEnabled(env: NodeJS.ProcessEnv = process.env): boolean { | ||
| const value = env.GENTLE_PI_HISTORY_CAPTURE?.trim().toLowerCase(); | ||
| return value === "1" || value === "true" || value === "on"; | ||
| } | ||
|
|
||
| export default function promptHistoryExtension( | ||
| pi: ExtensionAPI, | ||
| deps: HistoryDeps = {}, | ||
| ): void { | ||
| const env = deps.env ?? process.env; | ||
| const root = deps.root ?? PI_HISTORY_ROOT; | ||
| const cwd = deps.cwd ?? process.cwd(); | ||
| const instanceId = deps.instanceId ?? randomUUID(); | ||
| const now = deps.now ?? Date.now; | ||
| let writerState: SessionWriterState | null = null; | ||
|
|
||
| /** | ||
| * One-time init per extension load: register the project in the advisory | ||
| * registry, then open this instance's exclusive capture file. Legacy | ||
| * migration and seed bootstrap join this init order in a later slice. | ||
| */ | ||
| const getWriter = (): SessionWriterState => { | ||
| if (!writerState) { | ||
| try { | ||
| ensureRegistryEntry(root, cwd); | ||
| } catch { | ||
| // registry is advisory | ||
| } | ||
| writerState = openSessionWriter(root, cwd, instanceId); | ||
| } | ||
| return writerState; | ||
| }; | ||
|
|
||
| // Persist every delivered user prompt (write-through, append-only JSONL), | ||
| // but only for opted-in sessions — see captureEnabled(). The local | ||
| // ExtensionAPI stub types handler args as unknown; narrow here. | ||
| pi.on("before_agent_start", (...args: unknown[]) => { | ||
| if (!captureEnabled(env)) return; | ||
| try { | ||
| const event = args[0] as { prompt?: string } | undefined; | ||
| appendSessionCapture(getWriter(), event?.prompt ?? "", now()); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔒 Security & Privacy | 🛡️ Detected with Advanced Tier | 🟠 Major | 🏗️ Heavy lift 🧩 Analysis chain🏁 Script executed: sed -n '1,150p' extensions/history/store.ts
sed -n '180,260p' extensions/history/store.tsRepository: Gentleman-Programming/gentle-shell Length of output: 8035 Sensitive Data Exposure Reachability: External Restrict access to captured prompts. When capture is enabled, prompts reach filesystem operations that use default permissions. Set the history directory to Apply private permissions const entry: StoreEntry = { v: 1, text };
if (ts !== undefined) entry.ts = ts;
- fs.mkdirSync(path.dirname(state.filePath), { recursive: true });
- fs.appendFileSync(state.filePath, serializeEntry(entry) + "\n", "utf8");
+ const directory = path.dirname(state.filePath);
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
+ fs.chmodSync(directory, 0o700);
+ fs.appendFileSync(state.filePath, serializeEntry(entry) + "\n", {
+ encoding: "utf8",
+ mode: 0o600,
+ });
+ fs.chmodSync(state.filePath, 0o600);
state.lineCount += 1;🤖 Prompt for AI Agents |
||
| } catch { | ||
| // A capture failure must never break the agent loop or unregister | ||
| // the handler - swallow and keep the next prompt capturable. | ||
| } | ||
|
Comment on lines
+84
to
+87
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win 🔎 Supported by static analysis🏁 Script executed: sed -n '40,89p' extensions/history/index.ts
rg -n 'notify|ui\.|toast|setStatus' extensions --glob '!extensions/history/**' | head -40
rg -n 'notify|toast|warn' extensions/history docs/prompt-history.md | head -40
sed -n '225,250p' extensions/history/store.tsRepository: Gentleman-Programming/gentle-shell Length of output: 8140 🏁 Script executed: set -eu
printf '%s\n' '--- history index ---'
sed -n '1,115p' extensions/history/index.ts
printf '%s\n' '--- history store writer definitions ---'
rg -n -C 8 'interface SessionWriterState|type SessionWriterState|function openSessionWriter|function appendSessionCapture|appendSessionCapture\(' extensions/history
printf '%s\n' '--- API and handler declarations ---'
rg -n -C 6 'before_agent_start|ExtensionAPI|BeforeAgentStart|AgentStart' extensions src test tests . --glob '*.ts' --glob '*.d.ts' --glob '*.md' 2>/dev/null | head -240
printf '%s\n' '--- prompt-history docs ---'
if [ -f docs/prompt-history.md ]; then cat -n docs/prompt-history.md; else echo 'docs/prompt-history.md not present'; fi
printf '%s\n' '--- history tests ---'
fd -i 'history|prompt' . --type f | head -80
rg -n -C 5 'capture|append|unwritable|swallow|failure|error|history' extensions/history . --glob '*test*' --glob '*spec*' --glob '*.md' 2>/dev/null | head -260Repository: Gentleman-Programming/gentle-shell Length of output: 41833 🏁 Script executed: set -eu
printf '%s\n' '--- candidate API/type files ---'
git ls-files | rg '(^|/)(package(-lock)?\.json|.*\.d\.ts|.*pi.*(type|api)|.*extension.*(type|api))$' | head -120
printf '%s\n' '--- package metadata ---'
cat package.json 2>/dev/null || true
printf '%s\n' '--- exact before_agent_start registrations ---'
rg -n -C 12 'pi\.on\("before_agent_start"|before_agent_start' extensions tests --glob '*.ts' --glob '*.tsx' 2>/dev/null
printf '%s\n' '--- prompt-history documentation ---'
cat -n docs/prompt-history.md 2>/dev/null || true
printf '%s\n' '--- history test files ---'
for f in $(git ls-files | rg '(^|/).*history.*\.(test|spec)\.(ts|tsx)$|(^|/).*prompt.*\.(test|spec)\.(ts|tsx)$'); do
echo "--- $f"
sed -n '1,280p' "$f"
done
printf '%s\n' '--- all history source around writes and paths ---'
sed -n '1,280p' extensions/history/store.tsRepository: Gentleman-Programming/gentle-shell Length of output: 42458 🏁 Script executed: set -eu
printf '%s\n' '--- package metadata ---'
if [ -f package.json ]; then sed -n '1,220p' package.json; else echo 'package.json missing'; fi
printf '%s\n' '--- prompt-history documentation ---'
if [ -f docs/prompt-history.md ]; then cat -n docs/prompt-history.md; else echo 'docs/prompt-history.md missing'; fi
printf '%s\n' '--- exact before_agent_start registrations in extensions ---'
rg -n -C 10 'before_agent_start' extensions --glob '*.ts'
printf '%s\n' '--- history test file names ---'
git ls-files | rg 'history.*\.(test|spec)\.(ts|tsx)$|prompt.*\.(test|spec)\.(ts|tsx)$' || true
printf '%s\n' '--- history tests ---'
for f in $(git ls-files | rg 'history.*\.(test|spec)\.(ts|tsx)$|prompt.*\.(test|spec)\.(ts|tsx)$'); do
echo "--- $f"
cat -n "$f"
done
printf '%s\n' '--- writer and append implementation ---'
sed -n '188,255p' extensions/history/store.tsRepository: Gentleman-Programming/gentle-shell Length of output: 42220 Warn when opt-in history capture fails. If the store remains unwritable, each later prompt retries the same failing append and is silently omitted from history. Keep the agent loop running, but use the 🤖 Prompt for AI Agents |
||
| }); | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Correct the no-restart disable instruction.
A shell change to
GENTLE_PI_HISTORY_CAPTUREdoes not change the environment of an already-running Pi process. The handler rechecks its ownprocess.envon each prompt, but the documented shell invocation provides no in-process way to unset it. Tell users to restart Pi with capture disabled, or document a working in-process control. (nodejs.org)🤖 Prompt for AI Agents