From 620bd5a34b0d19b93e4f58f1c8ecb95cb6b17d48 Mon Sep 17 00:00:00 2001 From: Marvin Bitterlich <644950+marvin-bitterlich@users.noreply.github.com> Date: Sat, 11 Jul 2026 18:31:14 +0100 Subject: [PATCH 1/8] feat(pardes-pi): add global frustration feedback channel --- package.json | 4 + plugins/pardes-pi/README.md | 29 +- plugins/pardes-pi/docs/MANAGER.md | 6 + plugins/pardes-pi/docs/NORTH_STAR.md | 29 +- .../extensions/pardes/feedback/cli.ts | 279 ++++++++++++++++++ .../extensions/pardes/feedback/errors.ts | 10 + .../pardes/feedback/feedback.test.ts | 259 ++++++++++++++++ .../extensions/pardes/feedback/index.ts | 43 +++ .../extensions/pardes/feedback/schemas.ts | 75 +++++ .../extensions/pardes/feedback/store.ts | 264 +++++++++++++++++ .../extensions/pardes/feedback/tool.ts | 84 ++++++ .../pardes/manager/activation-safety.test.ts | 14 +- .../pardes/manager/activation-safety.ts | 6 + .../manager/agent-attachment-lifecycle.ts | 6 + .../pardes/manager/controller.test.ts | 6 + .../pardes/manager/guidance/lifecycle.test.ts | 2 + .../pardes/manager/guidance/lifecycle.ts | 1 + .../manager/verification/provisioning.ts | 8 + .../extensions/pardes/tools/feedback.ts | 44 +++ .../extensions/pardes/tools/index.ts | 2 + .../pardes/tools/registration.test.ts | 6 +- .../extensions/pardes/tools/tools.test.ts | 1 + .../worker-runtime/child-extension.test.ts | 8 +- .../pardes/worker-runtime/child-extension.ts | 58 +++- .../pardes/worker-runtime/child-profile.ts | 5 +- .../pardes/worker-runtime/process.test.ts | 37 ++- .../pardes/worker-runtime/process.ts | 9 + .../pardes/worker-runtime/retained-runtime.ts | 4 + plugins/pardes-pi/scripts/pardes-feedback.ts | 5 + 29 files changed, 1282 insertions(+), 22 deletions(-) create mode 100644 plugins/pardes-pi/extensions/pardes/feedback/cli.ts create mode 100644 plugins/pardes-pi/extensions/pardes/feedback/errors.ts create mode 100644 plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts create mode 100644 plugins/pardes-pi/extensions/pardes/feedback/index.ts create mode 100644 plugins/pardes-pi/extensions/pardes/feedback/schemas.ts create mode 100644 plugins/pardes-pi/extensions/pardes/feedback/store.ts create mode 100644 plugins/pardes-pi/extensions/pardes/feedback/tool.ts create mode 100644 plugins/pardes-pi/extensions/pardes/tools/feedback.ts create mode 100755 plugins/pardes-pi/scripts/pardes-feedback.ts diff --git a/package.json b/package.json index 0745b19..ea74e79 100644 --- a/package.json +++ b/package.json @@ -7,10 +7,14 @@ "keywords": [ "pi-package" ], + "bin": { + "pardes-feedback": "./plugins/pardes-pi/scripts/pardes-feedback.ts" + }, "scripts": { "ci": "biome ci .", "format": "biome format --write .", "format:check": "biome format .", + "feedback": "bun plugins/pardes-pi/scripts/pardes-feedback.ts", "lint": "biome check --error-on-warnings .", "lint:fix": "biome check --error-on-warnings --write .", "references:effect": "bash plugins/pardes-pi/scripts/sync-effect-reference.sh", diff --git a/plugins/pardes-pi/README.md b/plugins/pardes-pi/README.md index 0d09c66..5715aa1 100644 --- a/plugins/pardes-pi/README.md +++ b/plugins/pardes-pi/README.md @@ -91,7 +91,7 @@ refresh same-tier numeric counts. The manager-visible tools are grouped by purpose: ```text -question +question · feedback pardes_status · inbox_get · inbox_acknowledge · await_user_feedback workstream_create · workstream_list · workstream_get · workstream_complete report_get @@ -118,6 +118,33 @@ publication. Pardes never merges autonomously. Structured state is written beneath `~/.pi/agent/pardes/`. Override that root for development or tests with `PARDES_PI_STATE_DIR`. +## Frustration feedback + +The model-facing `feedback({ text })` tool is available to managers, writing +workers, and advisory verifiers. It is deliberately broad: use it for anything +about Pardes that is frustrating, confusing, broken, annoying, or wasteful, not +only harness bugs. The tool accepts only free-form text. Pardes adds bounded +provenance (time, id, role and available session/manager/agent/workstream, +repository, verifier, and version identities); it never automatically captures +logs, files, environment values, or secrets. + +Each submission is an immutable atomic JSON record in the global registry. +Addressed state is stored separately so triage never rewrites the submission. +The installed package exposes a human CLI: + +```bash +pardes-feedback help +pardes-feedback list --addressed no +pardes-feedback show +pardes-feedback watch --cursor triage +pardes-feedback address +``` + +From a source checkout, use `bun run feedback -- `. Watch cursors use +atomic per-entry receipts, so concurrent scans and restarted watchers do not log +the same entry twice. CLI rendering treats feedback text as untrusted and +escapes terminal controls. + ## Development validation Hosted GitHub Actions is the normal integration authority. Run relevant diff --git a/plugins/pardes-pi/docs/MANAGER.md b/plugins/pardes-pi/docs/MANAGER.md index f84fa34..865f5d6 100644 --- a/plugins/pardes-pi/docs/MANAGER.md +++ b/plugins/pardes-pi/docs/MANAGER.md @@ -14,6 +14,12 @@ action; omit empty categories. Avoid fluff, repeated narration, excessive headings, pseudo-diagrams, gratuitous code fences, and vertical whitespace. Drill down only for a specific decision. +Use `feedback({ text })` whenever anything about Pardes is frustrating, +confusing, broken, annoying, or wasteful; the channel is not limited to harness +bugs. Describe the friction in bounded free-form words. Do not paste logs, file +contents, environment values, or secrets; Pardes adds only bounded explicit +provenance automatically. + Use the smallest projection needed: - `pardes_status()` for counts, warnings, and pending attention; diff --git a/plugins/pardes-pi/docs/NORTH_STAR.md b/plugins/pardes-pi/docs/NORTH_STAR.md index 06f651b..c957048 100644 --- a/plugins/pardes-pi/docs/NORTH_STAR.md +++ b/plugins/pardes-pi/docs/NORTH_STAR.md @@ -103,6 +103,10 @@ Durable manager state lives beneath: ```text ~/.pi/agent/pardes/ +├── feedback/ +│ ├── submissions/ # one immutable atomic JSON record per submission +│ ├── triage/ # separate addressed-state records +│ └── watch-cursors/ # durable per-entry CLI watch receipts └── projects/ └── / └── managers/ @@ -244,7 +248,7 @@ The manager coordinates work rather than editing source. Its model-visible tools are grouped by purpose: ```text -question +question · feedback pardes_status · inbox_get · inbox_acknowledge · await_user_feedback workstream_create · workstream_list · workstream_get · workstream_complete report_get @@ -260,8 +264,9 @@ is opt-in. ### Writing worker -A writing worker receives ordinary coding tools rooted in one managed worktree. -The extension rejects file-tool paths outside the assigned worktree. Bash is not +A writing worker receives ordinary coding tools rooted in one managed worktree, +plus the global `feedback` frustration channel. The extension rejects file-tool +paths outside the assigned worktree. Bash is not a complete security boundary, so completion, publication, and cleanup paths also audit changed files and Git state. @@ -269,8 +274,8 @@ also audit changed files and Git state. An advisory verifier runs in a fresh detached scratch checkout pinned to the reviewed worker SHA. It has path-rooted read tools, Bash for efficient -inspection, fixed-argv captured-head evidence, structured reporting, and no -`edit` or `write` UI affordances. +inspection, fixed-argv captured-head evidence, structured reporting, the global +`feedback` frustration channel, and no `edit` or `write` UI affordances. Verifier Bash can mutate disposable scratch files and same-user filesystem access is not isolation. Verifier commits are never publication sources. @@ -316,6 +321,20 @@ synchronize an existing review gate after a fresh audit. Terminal merge observation can stop an idle owner and complete its workstream mechanically. Merges remain user-controlled. +## Frustration feedback + +Managers, writing workers, and advisory verifiers have one first-class +`feedback({ text })` tool. Its intentionally minimal schema has one required +free-form text field and covers anything frustrating, confusing, broken, +annoying, or wasteful rather than only harness defects. Each submission is a +separate immutable atomic JSON record in global Pardes state. Pardes adds only +bounded explicit provenance and never automatically captures logs, file +contents, environment values, or secrets. Human addressed-state triage remains +in a separate durable record. The `pardes-feedback` CLI lists, filters, shows, +watches, and marks entries addressed; durable per-entry watch receipts prevent +duplicate logging across races and restarts, and terminal output treats authored +text as untrusted data. + ## External feedback and trust Pull-request comments, submitted reviews, CI logs, child reports, and advisory diff --git a/plugins/pardes-pi/extensions/pardes/feedback/cli.ts b/plugins/pardes-pi/extensions/pardes/feedback/cli.ts new file mode 100644 index 0000000..530b32d --- /dev/null +++ b/plugins/pardes-pi/extensions/pardes/feedback/cli.ts @@ -0,0 +1,279 @@ +import { Effect } from 'effect'; +import { + type FeedbackEntry, + type FeedbackFilter, + type FeedbackRole, + matchesFeedbackFilter, +} from './schemas.ts'; +import { + claimFeedbackForWatch, + getFeedback, + listFeedback, + markFeedbackAddressed, + pardesGlobalStateRoot, + watchCursorExists, +} from './store.ts'; + +const UNSAFE_TERMINAL_CHARACTERS = /[\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu; +const ROLES = new Set(['manager', 'writer', 'advisory_verifier']); + +export interface FeedbackCliIo { + readonly out: (line: string) => void; + readonly error: (line: string) => void; +} + +export interface FeedbackCliOptions { + readonly root?: string; + readonly signal?: AbortSignal; + readonly sleep?: (milliseconds: number) => Promise; +} + +interface ParsedOptions { + readonly filter: FeedbackFilter; + readonly json: boolean; + readonly cursor: string; + readonly includeExisting: boolean; + readonly intervalMs: number; + readonly once: boolean; + readonly positionals: ReadonlyArray; +} + +export const FEEDBACK_CLI_HELP = `Usage: pardes-feedback [options] + +Review the global Pardes feedback registry across manager, writer, and advisory verifier sessions. + +Commands: + list List feedback entries + show Show one entry and its separate triage state + address Mark an entry addressed without changing its submission + watch Watch newly recorded feedback with a durable de-duplication cursor + help Show this help + +Filters (list and watch): + --addressed + --role + --repository --manager --agent + --verification --workstream --since + --text + +Output and watch options: + --json Emit terminal-safe JSON lines + --cursor Durable watch cursor name (default: default) + --include-existing Include entries present when a new cursor starts + --interval Poll interval (default: 1000) + --once Run one watch scan and exit + +Examples: + pardes-feedback list --addressed no + pardes-feedback show feedback-1234 + pardes-feedback watch --role writer --cursor writer-triage + pardes-feedback address feedback-1234 + +Feedback text is untrusted data. Text output escapes terminal controls and directional formatting.`; + +function terminalSafe(value: string): string { + return value.replace( + UNSAFE_TERMINAL_CHARACTERS, + (character) => `\\u${character.codePointAt(0)?.toString(16).padStart(4, '0')}`, + ); +} + +export function terminalSafeJson(value: unknown): string { + return terminalSafe(JSON.stringify(value)); +} + +function quotedPreview(text: string): string { + const characters = Array.from(text); + const preview = characters.length <= 160 ? text : `${characters.slice(0, 159).join('')}…`; + return terminalSafe(JSON.stringify(preview)); +} + +export function formatFeedbackEntry(entry: FeedbackEntry): string { + const { submission, triage } = entry; + const provenance = submission.provenance; + const identities = [ + provenance.repositoryKey && `repo=${terminalSafe(JSON.stringify(provenance.repositoryKey))}`, + provenance.managerId && `manager=${terminalSafe(JSON.stringify(provenance.managerId))}`, + provenance.agentId && `agent=${terminalSafe(JSON.stringify(provenance.agentId))}`, + provenance.verificationId && + `verification=${terminalSafe(JSON.stringify(provenance.verificationId))}`, + provenance.workstreamId && + `workstream=${terminalSafe(JSON.stringify(provenance.workstreamId))}`, + ].filter((value): value is string => value !== undefined); + return [ + triage ? '[addressed]' : '[open]', + submission.id, + submission.createdAt, + `role=${provenance.role}`, + ...identities, + `text=${quotedPreview(submission.text)}`, + ].join(' '); +} + +function requireValue(args: ReadonlyArray, index: number, option: string): string { + const value = args[index + 1]; + if (value === undefined || value.startsWith('--')) throw new Error(`${option} requires a value`); + return value; +} + +function parseOptions(args: ReadonlyArray): ParsedOptions { + const positionals: string[] = []; + const filter: { + addressed?: boolean; + agentId?: string; + managerId?: string; + repositoryKey?: string; + role?: FeedbackRole; + since?: string; + text?: string; + verificationId?: string; + workstreamId?: string; + } = {}; + let json = false; + let cursor = 'default'; + let includeExisting = false; + let intervalMs = 1_000; + let once = false; + for (let index = 0; index < args.length; index += 1) { + const arg = args[index]; + if (!arg?.startsWith('--')) { + if (arg !== undefined) positionals.push(arg); + continue; + } + if (arg === '--json') json = true; + else if (arg === '--include-existing') includeExisting = true; + else if (arg === '--once') once = true; + else if (arg === '--addressed') { + const value = requireValue(args, index, arg); + index += 1; + if (value === 'yes') filter.addressed = true; + else if (value === 'no') filter.addressed = false; + else if (value !== 'all') throw new Error('--addressed must be yes, no, or all'); + } else if (arg === '--role') { + const value = requireValue(args, index, arg); + index += 1; + if (!ROLES.has(value as FeedbackRole)) throw new Error(`unknown feedback role: ${value}`); + filter.role = value as FeedbackRole; + } else if (arg === '--repository') { + filter.repositoryKey = requireValue(args, index, arg); + index += 1; + } else if (arg === '--manager') { + filter.managerId = requireValue(args, index, arg); + index += 1; + } else if (arg === '--agent') { + filter.agentId = requireValue(args, index, arg); + index += 1; + } else if (arg === '--verification') { + filter.verificationId = requireValue(args, index, arg); + index += 1; + } else if (arg === '--workstream') { + filter.workstreamId = requireValue(args, index, arg); + index += 1; + } else if (arg === '--since') { + const value = requireValue(args, index, arg); + index += 1; + if (Number.isNaN(Date.parse(value))) throw new Error('--since must be an ISO timestamp'); + filter.since = new Date(value).toISOString(); + } else if (arg === '--text') { + filter.text = requireValue(args, index, arg); + index += 1; + } else if (arg === '--cursor') { + cursor = requireValue(args, index, arg); + index += 1; + } else if (arg === '--interval') { + const value = Number(requireValue(args, index, arg)); + index += 1; + if (!Number.isInteger(value) || value < 25 || value > 60_000) + throw new Error('--interval must be an integer from 25 to 60000 milliseconds'); + intervalMs = value; + } else throw new Error(`unknown option: ${arg}`); + } + return { cursor, filter, includeExisting, intervalMs, json, once, positionals }; +} + +function outputEntry(entry: FeedbackEntry, json: boolean, io: FeedbackCliIo): void { + io.out(json ? terminalSafeJson(entry) : formatFeedbackEntry(entry)); +} + +async function scanWatch(options: ParsedOptions, io: FeedbackCliIo, root: string): Promise { + const entries = await Effect.runPromise(listFeedback({}, root)); + for (const entry of entries) { + const claimed = await Effect.runPromise( + claimFeedbackForWatch(options.cursor, entry.submission.id, root), + ); + if (claimed && matchesFeedbackFilter(entry, options.filter)) + outputEntry(entry, options.json, io); + } +} + +async function watchFeedback( + options: ParsedOptions, + io: FeedbackCliIo, + configuration: FeedbackCliOptions, +): Promise { + const root = configuration.root ?? pardesGlobalStateRoot(); + const existed = await Effect.runPromise(watchCursorExists(options.cursor, root)); + if (!existed && !options.includeExisting) { + const baseline = await Effect.runPromise(listFeedback({}, root)); + for (const entry of baseline) + await Effect.runPromise(claimFeedbackForWatch(options.cursor, entry.submission.id, root)); + } + const sleep = configuration.sleep ?? ((milliseconds) => Bun.sleep(milliseconds)); + while (!configuration.signal?.aborted) { + await scanWatch(options, io, root); + if (options.once) return; + await sleep(options.intervalMs); + } +} + +export async function runFeedbackCli( + args: ReadonlyArray, + io: FeedbackCliIo = { error: (line) => console.error(line), out: (line) => console.log(line) }, + options: FeedbackCliOptions = {}, +): Promise { + const [command = 'help', ...rest] = args; + if (command === 'help' || command === '--help' || command === '-h') { + io.out(FEEDBACK_CLI_HELP); + return 0; + } + try { + const parsed = parseOptions(rest); + const root = options.root ?? pardesGlobalStateRoot(); + if (command === 'list') { + if (parsed.positionals.length > 0) + throw new Error('list does not accept positional arguments'); + const entries = await Effect.runPromise(listFeedback(parsed.filter, root)); + for (const entry of entries) outputEntry(entry, parsed.json, io); + return 0; + } + if (command === 'show') { + const [feedbackId, ...extra] = parsed.positionals; + if (!feedbackId || extra.length > 0) throw new Error('show requires exactly one feedback id'); + const entry = await Effect.runPromise(getFeedback(feedbackId, root)); + io.out(parsed.json ? terminalSafeJson(entry) : terminalSafeJson(entry)); + return 0; + } + if (command === 'address' || command === 'mark-addressed') { + const [feedbackId, ...extra] = parsed.positionals; + if (!feedbackId || extra.length > 0) + throw new Error('address requires exactly one feedback id'); + const triage = await Effect.runPromise(markFeedbackAddressed(feedbackId, root)); + io.out( + parsed.json ? terminalSafeJson(triage) : `${feedbackId} addressed at ${triage.addressedAt}`, + ); + return 0; + } + if (command === 'watch') { + if (parsed.positionals.length > 0) + throw new Error('watch does not accept positional arguments'); + await watchFeedback(parsed, io, { ...options, root }); + return 0; + } + throw new Error(`unknown command: ${command}`); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + io.error(`pardes-feedback: ${terminalSafe(message)}`); + io.error('Run pardes-feedback help for usage.'); + return 1; + } +} diff --git a/plugins/pardes-pi/extensions/pardes/feedback/errors.ts b/plugins/pardes-pi/extensions/pardes/feedback/errors.ts new file mode 100644 index 0000000..4e75144 --- /dev/null +++ b/plugins/pardes-pi/extensions/pardes/feedback/errors.ts @@ -0,0 +1,10 @@ +import { Data } from 'effect'; + +export class FeedbackStoreError extends Data.TaggedError('FeedbackStoreError')<{ + readonly operation: string; + readonly cause: unknown; +}> {} + +export class FeedbackNotFoundError extends Data.TaggedError('FeedbackNotFoundError')<{ + readonly feedbackId: string; +}> {} diff --git a/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts b/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts new file mode 100644 index 0000000..0e420ac --- /dev/null +++ b/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts @@ -0,0 +1,259 @@ +import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { ExtensionContext } from '@earendil-works/pi-coding-agent'; +import { Effect } from 'effect'; +import { afterEach, describe, expect, test } from 'vitest'; +import { runFeedbackCli, terminalSafeJson } from './cli.ts'; +import { + claimFeedbackForWatch, + feedbackRegistryPaths, + getFeedback, + listFeedback, + markFeedbackAddressed, + submitFeedback, +} from './store.ts'; +import { + childFeedbackSourceFromEnvironment, + executeFeedbackTool, + FEEDBACK_TOOL_DESCRIPTION, + feedbackProvenance, + feedbackToolParameters, +} from './tool.ts'; + +const temporaryDirectories: string[] = []; + +function temporaryRoot(): string { + const root = mkdtempSync(join(tmpdir(), 'pardes-feedback-')); + temporaryDirectories.push(root); + return root; +} + +function provenance(index: number) { + const role: 'writer' | 'advisory_verifier' = index % 2 === 0 ? 'writer' : 'advisory_verifier'; + return { + agentId: `agent-${index}`, + managerId: `manager-${index % 2}`, + pardesVersion: '0.0.0', + repositoryKey: `repo-${index % 3}`, + role, + sessionId: `session-${index}`, + verificationId: `verify-${index}`, + workstreamId: `workstream-${index % 4}`, + }; +} + +function sessionContext(sessionId: string) { + return { + sessionManager: { getSessionId: () => sessionId }, + } as unknown as Pick; +} + +afterEach(() => { + for (const root of temporaryDirectories.splice(0)) rmSync(root, { force: true, recursive: true }); +}); + +describe('global feedback registry', () => { + test('persists concurrent submissions as distinct immutable atomic JSON records', async () => { + const root = temporaryRoot(); + const count = 80; + const submissions = await Effect.runPromise( + Effect.all( + Array.from({ length: count }, (_, index) => + submitFeedback(`feedback ${index}`, provenance(index), root), + ), + { concurrency: 'unbounded' }, + ), + ); + const paths = feedbackRegistryPaths(root); + const names = readdirSync(paths.submissions); + + expect(new Set(submissions.map(({ id }) => id)).size).toBe(count); + expect(names).toHaveLength(count); + expect(names.some((name) => name.endsWith('.tmp'))).toBe(false); + for (const submission of submissions) { + const path = join(paths.submissions, `${submission.id}.json`); + expect(JSON.parse(readFileSync(path, 'utf8'))).toEqual(submission); + expect(statSync(path).mode & 0o222).toBe(0); + } + }); + + test('keeps addressed triage separate, durable, idempotent, and leaves the submission unchanged', async () => { + const root = temporaryRoot(); + const submission = await Effect.runPromise( + submitFeedback('original friction', provenance(1), root), + ); + const path = join(feedbackRegistryPaths(root).submissions, `${submission.id}.json`); + const before = readFileSync(path); + const [left, right] = await Promise.all([ + Effect.runPromise(markFeedbackAddressed(submission.id, root)), + Effect.runPromise(markFeedbackAddressed(submission.id, root)), + ]); + const entry = await Effect.runPromise(getFeedback(submission.id, root)); + + expect(left.feedbackId).toBe(submission.id); + expect(right).toEqual(left); + expect(entry.triage).toEqual(left); + expect(readFileSync(path)).toEqual(before); + expect( + JSON.parse( + readFileSync(join(feedbackRegistryPaths(root).triage, `${submission.id}.json`), 'utf8'), + ), + ).toMatchObject({ + feedbackId: submission.id, + status: 'addressed', + }); + }); + + test('filters globally by addressed state and bounded provenance dimensions', async () => { + const root = temporaryRoot(); + const first = await Effect.runPromise(submitFeedback('needle first', provenance(0), root)); + await Effect.runPromise(submitFeedback('other', provenance(1), root)); + await Effect.runPromise(submitFeedback('needle third', provenance(2), root)); + await Effect.runPromise(markFeedbackAddressed(first.id, root)); + + expect( + (await Effect.runPromise(listFeedback({ addressed: true }, root))).map( + (entry) => entry.submission.id, + ), + ).toEqual([first.id]); + expect( + await Effect.runPromise( + listFeedback( + { + addressed: false, + repositoryKey: 'repo-2', + role: 'writer', + text: 'needle', + workstreamId: 'workstream-2', + }, + root, + ), + ), + ).toHaveLength(1); + expect(await Effect.runPromise(listFeedback({ agentId: 'missing' }, root))).toEqual([]); + }); +}); + +describe('feedback provenance and model schema', () => { + test('uses one required free-form text input and a deliberately broad description', () => { + const parameters = feedbackToolParameters as unknown as { + properties: Record; + required: string[]; + }; + expect(Object.keys(parameters.properties)).toEqual(['text']); + expect(parameters.required).toEqual(['text']); + expect(FEEDBACK_TOOL_DESCRIPTION).toContain('frustrating'); + expect(FEEDBACK_TOOL_DESCRIPTION).toContain('confusing'); + expect(FEEDBACK_TOOL_DESCRIPTION).toContain('broken'); + expect(FEEDBACK_TOOL_DESCRIPTION).toContain('annoying'); + expect(FEEDBACK_TOOL_DESCRIPTION).toContain('wasteful'); + expect(FEEDBACK_TOOL_DESCRIPTION).toContain('not limited to harness bugs'); + }); + + test('attaches only bounded explicit provenance and role-specific child identities', async () => { + const root = temporaryRoot(); + const previous = process.env.PARDES_PI_STATE_DIR; + process.env.PARDES_PI_STATE_DIR = root; + try { + const source = childFeedbackSourceFromEnvironment( + { + PARDES_FEEDBACK_AGENT_ID: 'verifier-agent', + PARDES_FEEDBACK_MANAGER_ID: 'manager-one', + PARDES_FEEDBACK_REPOSITORY_KEY: 'repo-one', + PARDES_FEEDBACK_VERIFICATION_ID: 'verify-one', + PARDES_FEEDBACK_WORKSTREAM_ID: 'stream-one', + SECRET_TOKEN: 'must-not-be-captured', + }, + 'advisory_verifier', + ); + const result = await executeFeedbackTool( + 'review was confusing', + source, + sessionContext('session-one'), + ); + const entry = await Effect.runPromise(getFeedback(result.id, root)); + expect(entry.submission.provenance).toEqual({ + agentId: 'verifier-agent', + managerId: 'manager-one', + pardesVersion: '0.0.0', + repositoryKey: 'repo-one', + role: 'advisory_verifier', + sessionId: 'session-one', + verificationId: 'verify-one', + workstreamId: 'stream-one', + }); + expect(JSON.stringify(entry)).not.toContain('SECRET_TOKEN'); + expect(JSON.stringify(entry)).not.toContain('must-not-be-captured'); + expect( + feedbackProvenance( + { managerId: 'm'.repeat(700), role: 'manager' }, + sessionContext('s'.repeat(700)), + ).managerId, + ).toHaveLength(512); + } finally { + if (previous === undefined) delete process.env.PARDES_PI_STATE_DIR; + else process.env.PARDES_PI_STATE_DIR = previous; + } + }); +}); + +describe('feedback CLI', () => { + test('offers discoverable help, filtering, safe display, and separate addressed-state commands', async () => { + const root = temporaryRoot(); + const dangerous = `line\n\u001b[31mred\u202eoverride`; + const first = await Effect.runPromise(submitFeedback(dangerous, provenance(0), root)); + await Effect.runPromise(submitFeedback('ordinary', provenance(1), root)); + const output: string[] = []; + const errors: string[] = []; + const io = { + error: (line: string) => errors.push(line), + out: (line: string) => output.push(line), + }; + + expect(await runFeedbackCli(['help'], io, { root })).toBe(0); + expect(output.join('\n')).toContain('watch'); + expect(output.join('\n')).toContain('address'); + output.length = 0; + expect(await runFeedbackCli(['list', '--role', 'writer', '--text', 'line'], io, { root })).toBe( + 0, + ); + expect(output).toHaveLength(1); + expect(output[0]).toContain(first.id); + expect(output[0]).not.toContain('\u001b'); + expect(output[0]).not.toContain('\u202e'); + expect(output[0]).toContain('\\u202e'); + output.length = 0; + expect(await runFeedbackCli(['address', first.id], io, { root })).toBe(0); + expect(await runFeedbackCli(['list', '--addressed', 'yes', '--json'], io, { root })).toBe(0); + expect(output.at(-1)).toContain(first.id); + expect(errors).toEqual([]); + expect(terminalSafeJson({ text: dangerous })).not.toContain('\u202e'); + }); + + test('uses durable atomic watch receipts to survive duplicate scans, concurrent watchers, and restarts', async () => { + const root = temporaryRoot(); + const old = await Effect.runPromise(submitFeedback('already present', provenance(0), root)); + const output: string[] = []; + const io = { error: () => {}, out: (line: string) => output.push(line) }; + + await runFeedbackCli(['watch', '--once', '--cursor', 'triage'], io, { root }); + expect(output).toEqual([]); + const fresh = await Effect.runPromise(submitFeedback('new entry', provenance(1), root)); + await Promise.all([ + runFeedbackCli(['watch', '--once', '--cursor', 'triage'], io, { root }), + runFeedbackCli(['watch', '--once', '--cursor', 'triage'], io, { root }), + ]); + expect(output.filter((line) => line.includes(fresh.id))).toHaveLength(1); + expect(output.some((line) => line.includes(old.id))).toBe(false); + + await runFeedbackCli(['watch', '--once', '--cursor', 'triage'], io, { root }); + expect(output.filter((line) => line.includes(fresh.id))).toHaveLength(1); + const claims = await Promise.all( + Array.from({ length: 12 }, () => + Effect.runPromise(claimFeedbackForWatch('other-cursor', fresh.id, root)), + ), + ); + expect(claims.filter(Boolean)).toHaveLength(1); + }); +}); diff --git a/plugins/pardes-pi/extensions/pardes/feedback/index.ts b/plugins/pardes-pi/extensions/pardes/feedback/index.ts new file mode 100644 index 0000000..c60189f --- /dev/null +++ b/plugins/pardes-pi/extensions/pardes/feedback/index.ts @@ -0,0 +1,43 @@ +export { + FEEDBACK_CLI_HELP, + type FeedbackCliIo, + type FeedbackCliOptions, + formatFeedbackEntry, + runFeedbackCli, + terminalSafeJson, +} from './cli.ts'; +export { FeedbackNotFoundError, FeedbackStoreError } from './errors.ts'; +export { + FEEDBACK_SCHEMA_VERSION, + FEEDBACK_TEXT_MAX_BYTES, + type FeedbackEntry, + type FeedbackFilter, + type FeedbackProvenance, + FeedbackProvenanceSchema, + type FeedbackRole, + FeedbackRoleSchema, + type FeedbackSubmission, + FeedbackSubmissionSchema, + type FeedbackTriage, + FeedbackTriageSchema, + matchesFeedbackFilter, + PARDES_VERSION, +} from './schemas.ts'; +export { + claimFeedbackForWatch, + feedbackRegistryPaths, + getFeedback, + listFeedback, + markFeedbackAddressed, + pardesGlobalStateRoot, + submitFeedback, + watchCursorExists, +} from './store.ts'; +export { + childFeedbackSourceFromEnvironment, + executeFeedbackTool, + FEEDBACK_TOOL_DESCRIPTION, + type FeedbackSource, + feedbackProvenance, + feedbackToolParameters, +} from './tool.ts'; diff --git a/plugins/pardes-pi/extensions/pardes/feedback/schemas.ts b/plugins/pardes-pi/extensions/pardes/feedback/schemas.ts new file mode 100644 index 0000000..3025a72 --- /dev/null +++ b/plugins/pardes-pi/extensions/pardes/feedback/schemas.ts @@ -0,0 +1,75 @@ +import { Schema } from 'effect'; + +const NonEmptyString = Schema.String.check(Schema.isMinLength(1)); +const BoundedIdentity = NonEmptyString.check(Schema.isMaxLength(512)); + +export const PARDES_VERSION = '0.0.0'; +export const FEEDBACK_SCHEMA_VERSION = 1; +export const FEEDBACK_TEXT_MAX_BYTES = 4 * 1_024 * 1_024; + +export const FeedbackRoleSchema = Schema.Literals(['manager', 'writer', 'advisory_verifier']); +export type FeedbackRole = typeof FeedbackRoleSchema.Type; + +export const FeedbackProvenanceSchema = Schema.Struct({ + agentId: Schema.optionalKey(BoundedIdentity), + managerId: Schema.optionalKey(BoundedIdentity), + pardesVersion: BoundedIdentity, + repositoryKey: Schema.optionalKey(BoundedIdentity), + role: FeedbackRoleSchema, + sessionId: Schema.optionalKey(BoundedIdentity), + verificationId: Schema.optionalKey(BoundedIdentity), + workstreamId: Schema.optionalKey(BoundedIdentity), +}); +export type FeedbackProvenance = typeof FeedbackProvenanceSchema.Type; + +export const FeedbackSubmissionSchema = Schema.Struct({ + createdAt: NonEmptyString, + id: NonEmptyString.check(Schema.isPattern(/^feedback-[a-f0-9-]+$/)), + provenance: FeedbackProvenanceSchema, + schemaVersion: Schema.Literal(FEEDBACK_SCHEMA_VERSION), + text: NonEmptyString, +}); +export type FeedbackSubmission = typeof FeedbackSubmissionSchema.Type; + +export const FeedbackTriageSchema = Schema.Struct({ + addressedAt: NonEmptyString, + feedbackId: NonEmptyString.check(Schema.isPattern(/^feedback-[a-f0-9-]+$/)), + schemaVersion: Schema.Literal(FEEDBACK_SCHEMA_VERSION), + status: Schema.Literal('addressed'), +}); +export type FeedbackTriage = typeof FeedbackTriageSchema.Type; + +export interface FeedbackEntry { + readonly submission: FeedbackSubmission; + readonly triage?: FeedbackTriage; +} + +export interface FeedbackFilter { + readonly addressed?: boolean; + readonly agentId?: string; + readonly managerId?: string; + readonly repositoryKey?: string; + readonly role?: FeedbackRole; + readonly since?: string; + readonly text?: string; + readonly verificationId?: string; + readonly workstreamId?: string; +} + +export function matchesFeedbackFilter(entry: FeedbackEntry, filter: FeedbackFilter): boolean { + const { provenance } = entry.submission; + if (filter.addressed !== undefined && (entry.triage !== undefined) !== filter.addressed) + return false; + if (filter.agentId !== undefined && provenance.agentId !== filter.agentId) return false; + if (filter.managerId !== undefined && provenance.managerId !== filter.managerId) return false; + if (filter.repositoryKey !== undefined && provenance.repositoryKey !== filter.repositoryKey) + return false; + if (filter.role !== undefined && provenance.role !== filter.role) return false; + if (filter.since !== undefined && entry.submission.createdAt < filter.since) return false; + if (filter.text !== undefined && !entry.submission.text.includes(filter.text)) return false; + if (filter.verificationId !== undefined && provenance.verificationId !== filter.verificationId) + return false; + if (filter.workstreamId !== undefined && provenance.workstreamId !== filter.workstreamId) + return false; + return true; +} diff --git a/plugins/pardes-pi/extensions/pardes/feedback/store.ts b/plugins/pardes-pi/extensions/pardes/feedback/store.ts new file mode 100644 index 0000000..ec6b8cd --- /dev/null +++ b/plugins/pardes-pi/extensions/pardes/feedback/store.ts @@ -0,0 +1,264 @@ +import { randomUUID } from 'node:crypto'; +import { constants } from 'node:fs'; +import { access, link, lstat, mkdir, open, readdir, readFile, rm } from 'node:fs/promises'; +import { homedir } from 'node:os'; +import { basename, dirname, join } from 'node:path'; +import { Effect, Schema } from 'effect'; +import { FeedbackNotFoundError, FeedbackStoreError } from './errors.ts'; +import { + FEEDBACK_SCHEMA_VERSION, + FEEDBACK_TEXT_MAX_BYTES, + type FeedbackEntry, + type FeedbackFilter, + type FeedbackProvenance, + type FeedbackSubmission, + FeedbackSubmissionSchema, + type FeedbackTriage, + FeedbackTriageSchema, + matchesFeedbackFilter, +} from './schemas.ts'; + +const FEEDBACK_ID_PATTERN = /^feedback-[a-f0-9-]+$/; +const CURSOR_PATTERN = /^[a-zA-Z0-9._-]{1,128}$/; +const FEEDBACK_ARTIFACT_MAX_BYTES = FEEDBACK_TEXT_MAX_BYTES + 16 * 1_024; + +export interface FeedbackRegistryPaths { + readonly directory: string; + readonly submissions: string; + readonly triage: string; + readonly watchCursors: string; +} + +export function pardesGlobalStateRoot(): string { + return process.env.PARDES_PI_STATE_DIR || join(homedir(), '.pi', 'agent', 'pardes'); +} + +export function feedbackRegistryPaths(root = pardesGlobalStateRoot()): FeedbackRegistryPaths { + const directory = join(root, 'feedback'); + return { + directory, + submissions: join(directory, 'submissions'), + triage: join(directory, 'triage'), + watchCursors: join(directory, 'watch-cursors'), + }; +} + +function storeError(operation: string, cause: unknown): FeedbackStoreError { + return new FeedbackStoreError({ cause, operation }); +} + +function effectPromise( + operation: string, + run: () => Promise, +): Effect.Effect { + return Effect.tryPromise({ catch: (cause) => storeError(operation, cause), try: run }); +} + +function isCode(error: unknown, code: string): boolean { + return typeof error === 'object' && error !== null && 'code' in error && error.code === code; +} + +async function syncDirectory(directory: string): Promise { + const handle = await open(directory, 'r'); + try { + await handle.sync(); + } finally { + await handle.close(); + } +} + +async function ensureDirectories(paths: FeedbackRegistryPaths): Promise { + await mkdir(paths.submissions, { recursive: true }); + await mkdir(paths.triage, { recursive: true }); + await mkdir(paths.watchCursors, { recursive: true }); +} + +/** Create one immutable, atomically visible artifact without ever replacing an existing target. */ +async function createImmutableArtifact(path: string, source: string): Promise { + const temporary = `${path}.${randomUUID()}.tmp`; + const handle = await open(temporary, 'wx', 0o444); + try { + await handle.writeFile(source, 'utf8'); + await handle.sync(); + } finally { + await handle.close(); + } + try { + await link(temporary, path); + await syncDirectory(dirname(path)); + return true; + } catch (error) { + if (isCode(error, 'EEXIST')) return false; + throw error; + } finally { + await rm(temporary, { force: true }); + } +} + +function validFeedbackId(feedbackId: string): boolean { + return FEEDBACK_ID_PATTERN.test(feedbackId) && basename(feedbackId) === feedbackId; +} + +async function readDecoded( + path: string, + schema: Schema.Codec, +): Promise { + const stats = await lstat(path); + if (!stats.isFile() || stats.isSymbolicLink()) throw new Error('feedback artifact is redirected'); + if (stats.size > FEEDBACK_ARTIFACT_MAX_BYTES) throw new Error('feedback artifact is oversized'); + const source = await readFile(path, 'utf8'); + const parsed = JSON.parse(source) as unknown; + return Effect.runPromise( + Schema.decodeUnknownEffect(schema, { errors: 'all', onExcessProperty: 'error' })(parsed), + ); +} + +async function readTriageIfPresent(paths: FeedbackRegistryPaths, feedbackId: string) { + try { + return await readDecoded(join(paths.triage, `${feedbackId}.json`), FeedbackTriageSchema); + } catch (error) { + if (isCode(error, 'ENOENT')) return undefined; + throw error; + } +} + +export function submitFeedback( + text: string, + provenance: FeedbackProvenance, + root = pardesGlobalStateRoot(), +): Effect.Effect { + return effectPromise('submit feedback', async () => { + if (text.length === 0) throw new Error('feedback text is required'); + if (Buffer.byteLength(text, 'utf8') > FEEDBACK_TEXT_MAX_BYTES) + throw new Error(`feedback text exceeds ${FEEDBACK_TEXT_MAX_BYTES} bytes`); + const paths = feedbackRegistryPaths(root); + await ensureDirectories(paths); + for (let attempt = 0; attempt < 8; attempt += 1) { + const submission: FeedbackSubmission = { + createdAt: new Date().toISOString(), + id: `feedback-${randomUUID()}`, + provenance, + schemaVersion: FEEDBACK_SCHEMA_VERSION, + text, + }; + const encoded = await Effect.runPromise( + Schema.encodeEffect(FeedbackSubmissionSchema)(submission), + ); + const source = `${JSON.stringify(encoded, null, 2)}\n`; + if (await createImmutableArtifact(join(paths.submissions, `${submission.id}.json`), source)) + return submission; + } + throw new Error('could not allocate a unique feedback id'); + }); +} + +export function getFeedback( + feedbackId: string, + root = pardesGlobalStateRoot(), +): Effect.Effect { + if (!validFeedbackId(feedbackId)) return Effect.fail(new FeedbackNotFoundError({ feedbackId })); + const paths = feedbackRegistryPaths(root); + return Effect.tryPromise({ + catch: (cause) => + isCode(cause, 'ENOENT') + ? new FeedbackNotFoundError({ feedbackId }) + : storeError('read feedback', cause), + try: async () => { + const submission = await readDecoded( + join(paths.submissions, `${feedbackId}.json`), + FeedbackSubmissionSchema, + ); + const triage = await readTriageIfPresent(paths, feedbackId); + return { submission, ...(triage === undefined ? {} : { triage }) }; + }, + }); +} + +export function listFeedback( + filter: FeedbackFilter = {}, + root = pardesGlobalStateRoot(), +): Effect.Effect, FeedbackStoreError> { + return effectPromise('list feedback', async () => { + const paths = feedbackRegistryPaths(root); + await ensureDirectories(paths); + const names = (await readdir(paths.submissions, { withFileTypes: true })) + .filter((entry) => entry.isFile() && !entry.isSymbolicLink() && entry.name.endsWith('.json')) + .map((entry) => entry.name) + .sort(); + const entries: FeedbackEntry[] = []; + for (const name of names) { + const feedbackId = name.slice(0, -'.json'.length); + if (!validFeedbackId(feedbackId)) continue; + const submission = await readDecoded(join(paths.submissions, name), FeedbackSubmissionSchema); + const triage = await readTriageIfPresent(paths, feedbackId); + const entry = { submission, ...(triage === undefined ? {} : { triage }) }; + if (matchesFeedbackFilter(entry, filter)) entries.push(entry); + } + return entries.sort( + (left, right) => + left.submission.createdAt.localeCompare(right.submission.createdAt) || + left.submission.id.localeCompare(right.submission.id), + ); + }); +} + +export function markFeedbackAddressed( + feedbackId: string, + root = pardesGlobalStateRoot(), +): Effect.Effect { + return getFeedback(feedbackId, root).pipe( + Effect.flatMap((entry) => { + if (entry.triage) return Effect.succeed(entry.triage); + return effectPromise('mark feedback addressed', async () => { + const paths = feedbackRegistryPaths(root); + await ensureDirectories(paths); + const triage: FeedbackTriage = { + addressedAt: new Date().toISOString(), + feedbackId, + schemaVersion: FEEDBACK_SCHEMA_VERSION, + status: 'addressed', + }; + const encoded = await Effect.runPromise(Schema.encodeEffect(FeedbackTriageSchema)(triage)); + const path = join(paths.triage, `${feedbackId}.json`); + const created = await createImmutableArtifact( + path, + `${JSON.stringify(encoded, null, 2)}\n`, + ); + return created ? triage : readDecoded(path, FeedbackTriageSchema); + }); + }), + ); +} + +/** Atomically claim one entry for a durable named watch cursor. */ +export function claimFeedbackForWatch( + cursor: string, + feedbackId: string, + root = pardesGlobalStateRoot(), +): Effect.Effect { + return effectPromise('claim feedback for watch', async () => { + if (!CURSOR_PATTERN.test(cursor)) throw new Error('invalid watch cursor'); + if (!validFeedbackId(feedbackId)) throw new Error('invalid feedback id'); + const paths = feedbackRegistryPaths(root); + const cursorDirectory = join(paths.watchCursors, cursor); + await mkdir(cursorDirectory, { recursive: true }); + const receipt = `${JSON.stringify({ feedbackId, seenAt: new Date().toISOString() })}\n`; + return createImmutableArtifact(join(cursorDirectory, `${feedbackId}.json`), receipt); + }); +} + +export function watchCursorExists( + cursor: string, + root = pardesGlobalStateRoot(), +): Effect.Effect { + return effectPromise('inspect feedback watch cursor', async () => { + if (!CURSOR_PATTERN.test(cursor)) throw new Error('invalid watch cursor'); + try { + await access(join(feedbackRegistryPaths(root).watchCursors, cursor), constants.F_OK); + return true; + } catch (error) { + if (isCode(error, 'ENOENT')) return false; + throw error; + } + }); +} diff --git a/plugins/pardes-pi/extensions/pardes/feedback/tool.ts b/plugins/pardes-pi/extensions/pardes/feedback/tool.ts new file mode 100644 index 0000000..408d6ea --- /dev/null +++ b/plugins/pardes-pi/extensions/pardes/feedback/tool.ts @@ -0,0 +1,84 @@ +import type { ExtensionContext } from '@earendil-works/pi-coding-agent'; +import { Effect } from 'effect'; +import { Type } from 'typebox'; +import { type FeedbackProvenance, type FeedbackRole, PARDES_VERSION } from './schemas.ts'; +import { submitFeedback } from './store.ts'; + +export const FEEDBACK_TOOL_DESCRIPTION = + 'Record anything about Pardes that is frustrating, confusing, broken, annoying, or wasteful. Use this broad channel for any friction worth preserving; it is not limited to harness bugs.'; + +export const feedbackToolParameters = Type.Object( + { + text: Type.String({ + description: + 'Free-form description of anything frustrating, confusing, broken, annoying, or wasteful.', + minLength: 1, + }), + }, + { additionalProperties: false }, +); + +export interface FeedbackSource { + readonly agentId?: string; + readonly managerId?: string; + readonly repositoryKey?: string; + readonly role: FeedbackRole; + readonly verificationId?: string; + readonly workstreamId?: string; +} + +function boundedIdentity(value: string | undefined): string | undefined { + if (value === undefined || value.length === 0) return undefined; + return Array.from(value).slice(0, 512).join(''); +} + +export function feedbackProvenance( + source: FeedbackSource, + ctx: Pick, +): FeedbackProvenance { + const sessionId = boundedIdentity(ctx.sessionManager.getSessionId()); + const agentId = boundedIdentity(source.agentId); + const managerId = boundedIdentity(source.managerId); + const repositoryKey = boundedIdentity(source.repositoryKey); + const verificationId = boundedIdentity(source.verificationId); + const workstreamId = boundedIdentity(source.workstreamId); + return { + ...(agentId === undefined ? {} : { agentId }), + ...(managerId === undefined ? {} : { managerId }), + pardesVersion: PARDES_VERSION, + ...(repositoryKey === undefined ? {} : { repositoryKey }), + role: source.role, + ...(sessionId === undefined ? {} : { sessionId }), + ...(verificationId === undefined ? {} : { verificationId }), + ...(workstreamId === undefined ? {} : { workstreamId }), + }; +} + +export async function executeFeedbackTool( + text: string, + source: FeedbackSource, + ctx: Pick, +): Promise<{ readonly id: string }> { + const submission = await Effect.runPromise(submitFeedback(text, feedbackProvenance(source, ctx))); + return { id: submission.id }; +} + +/** Read only Pardes-owned provenance variables set explicitly by the parent manager process. */ +export function childFeedbackSourceFromEnvironment( + environment: NodeJS.ProcessEnv, + role: Exclude, +): FeedbackSource { + const agentId = environment.PARDES_FEEDBACK_AGENT_ID; + const managerId = environment.PARDES_FEEDBACK_MANAGER_ID; + const repositoryKey = environment.PARDES_FEEDBACK_REPOSITORY_KEY; + const verificationId = environment.PARDES_FEEDBACK_VERIFICATION_ID; + const workstreamId = environment.PARDES_FEEDBACK_WORKSTREAM_ID; + return { + ...(agentId === undefined ? {} : { agentId }), + ...(managerId === undefined ? {} : { managerId }), + ...(repositoryKey === undefined ? {} : { repositoryKey }), + role, + ...(verificationId === undefined ? {} : { verificationId }), + ...(workstreamId === undefined ? {} : { workstreamId }), + }; +} diff --git a/plugins/pardes-pi/extensions/pardes/manager/activation-safety.test.ts b/plugins/pardes-pi/extensions/pardes/manager/activation-safety.test.ts index 973673a..14dfd1e 100644 --- a/plugins/pardes-pi/extensions/pardes/manager/activation-safety.test.ts +++ b/plugins/pardes-pi/extensions/pardes/manager/activation-safety.test.ts @@ -47,6 +47,12 @@ function fixturePluginSource(): string { join(root, 'worker-runtime', 'child-tool-call-preview.ts'), 'export const previewVersion = 1;\n', ); + mkdirSync(join(root, 'feedback')); + for (const name of ['cli.ts', 'errors.ts', 'index.ts', 'schemas.ts', 'store.ts', 'tool.ts']) + writeFileSync( + join(root, 'feedback', name), + `export const ${name.replace('.ts', '')}Version = 1;\n`, + ); return root; } @@ -64,6 +70,12 @@ describe('loaded child-runtime activation safety', () => { 'worker-runtime/child-extension.ts', 'worker-runtime/child-profile.ts', 'worker-runtime/child-tool-call-preview.ts', + 'feedback/cli.ts', + 'feedback/errors.ts', + 'feedback/index.ts', + 'feedback/schemas.ts', + 'feedback/store.ts', + 'feedback/tool.ts', ]); }); @@ -93,7 +105,7 @@ describe('loaded child-runtime activation safety', () => { expect(materialized).toMatchObject({ lifecycle: 'allowed', reason: 'pinned_snapshot_ready', - snapshot: { inputFileCount: 3, state: 'ready' }, + snapshot: { inputFileCount: CHILD_RUNTIME_INPUTS.length, state: 'ready' }, status: 'aligned', }); const initiallyReady = await Effect.runPromise(safety.requireReady('agent_spawn')); diff --git a/plugins/pardes-pi/extensions/pardes/manager/activation-safety.ts b/plugins/pardes-pi/extensions/pardes/manager/activation-safety.ts index eb273ad..911874d 100644 --- a/plugins/pardes-pi/extensions/pardes/manager/activation-safety.ts +++ b/plugins/pardes-pi/extensions/pardes/manager/activation-safety.ts @@ -14,6 +14,12 @@ export const CHILD_RUNTIME_INPUTS = [ CHILD_EXTENSION_INPUT, 'worker-runtime/child-profile.ts', 'worker-runtime/child-tool-call-preview.ts', + 'feedback/cli.ts', + 'feedback/errors.ts', + 'feedback/index.ts', + 'feedback/schemas.ts', + 'feedback/store.ts', + 'feedback/tool.ts', ] as const; export type PluginTreeIdentityIssue = diff --git a/plugins/pardes-pi/extensions/pardes/manager/agent-attachment-lifecycle.ts b/plugins/pardes-pi/extensions/pardes/manager/agent-attachment-lifecycle.ts index 31dc4da..837b330 100644 --- a/plugins/pardes-pi/extensions/pardes/manager/agent-attachment-lifecycle.ts +++ b/plugins/pardes-pi/extensions/pardes/manager/agent-attachment-lifecycle.ts @@ -381,12 +381,15 @@ export function makeAgentAttachmentLifecycleCoordinator( .spawn({ agentId, cwd: lease.path, + managerId: state.managerId, model, + repositoryKey: state.repo.key, sessionDir, sessionName: agentSessionName(input.workstreamId, agentId, input.title), task: input.task, thinkingLevel, workerExtensionPath, + workstreamId: input.workstreamId, }) .pipe(Effect.exit); if (Exit.isFailure(runtimeResult)) { @@ -478,13 +481,16 @@ export function makeAgentAttachmentLifecycleCoordinator( .spawn({ agentId, cwd: agent.worktree.path, + managerId: namespace.managerId, model: agent.model, + repositoryKey: namespace.repo.key, sessionDir: agent.sessionDir, sessionFile: agent.sessionFile, sessionName: agentSessionName(agent.workstreamId, agentId, agent.title), task: message, thinkingLevel: agent.thinkingLevel, workerExtensionPath, + workstreamId: agent.workstreamId, }) .pipe(Effect.exit); if (Exit.isFailure(runtimeResult)) { diff --git a/plugins/pardes-pi/extensions/pardes/manager/controller.test.ts b/plugins/pardes-pi/extensions/pardes/manager/controller.test.ts index 27ea2aa..2fa4fa7 100644 --- a/plugins/pardes-pi/extensions/pardes/manager/controller.test.ts +++ b/plugins/pardes-pi/extensions/pardes/manager/controller.test.ts @@ -130,6 +130,12 @@ function fixturePluginSource(): string { join(root, 'worker-runtime', 'child-tool-call-preview.ts'), 'export const loadedPreview = true;\n', ); + mkdirSync(join(root, 'feedback')); + for (const name of ['cli.ts', 'errors.ts', 'index.ts', 'schemas.ts', 'store.ts', 'tool.ts']) + writeFileSync( + join(root, 'feedback', name), + `export const ${name.replace('.ts', '')}Version = 1;\n`, + ); return root; } diff --git a/plugins/pardes-pi/extensions/pardes/manager/guidance/lifecycle.test.ts b/plugins/pardes-pi/extensions/pardes/manager/guidance/lifecycle.test.ts index 0a45f9a..9bd9a0e 100644 --- a/plugins/pardes-pi/extensions/pardes/manager/guidance/lifecycle.test.ts +++ b/plugins/pardes-pi/extensions/pardes/manager/guidance/lifecycle.test.ts @@ -179,6 +179,7 @@ Operating model: - Publication: use \`pull_request_create\` only for exact committed worker state, keep the owner attached for CI or review feedback, and leave merges under user control. - Published review feedback: tell the retained worker to make additive descendant commits only; do not amend, rebase, or rewrite published branch history. Pardes exact-SHA publication intentionally never force-pushes. - Inbox has exactly two paths: Autonomous rows may be acknowledged once handled. When a report, external observation, blocker, or attention needs user judgment, do not acknowledge the active cursor first; surface it. Use \`question\` for structured options or \`await_user_feedback\` for free-form feedback, and leave the cursor open until response. +- Friction: use \`feedback({ text })\` for anything about Pardes that is frustrating, confusing, broken, annoying, or wasteful, not only harness bugs. Describe it in your own bounded words; do not dump logs, files, environment values, or secrets. - Communication: state facts, decision needed, blockers, and next action. Skip fluff, repeated narration, excess headings, pseudo-diagrams, gratuitous code fences, and vertical whitespace. First pass: - Inspect bounded \`pardes_status\` for current counts and warnings, then inspect \`pardes_status(view="inbox")\` if attention is pending. @@ -193,6 +194,7 @@ Operating model: - Publication: use \`pull_request_create\` only for exact committed worker state, keep the owner attached for CI or review feedback, and leave merges under user control. - Published review feedback: tell the retained worker to make additive descendant commits only; do not amend, rebase, or rewrite published branch history. Pardes exact-SHA publication intentionally never force-pushes. - Inbox has exactly two paths: Autonomous rows may be acknowledged once handled. When a report, external observation, blocker, or attention needs user judgment, do not acknowledge the active cursor first; surface it. Use \`question\` for structured options or \`await_user_feedback\` for free-form feedback, and leave the cursor open until response. +- Friction: use \`feedback({ text })\` for anything about Pardes that is frustrating, confusing, broken, annoying, or wasteful, not only harness bugs. Describe it in your own bounded words; do not dump logs, files, environment values, or secrets. - Communication: state facts, decision needed, blockers, and next action. Skip fluff, repeated narration, excess headings, pseudo-diagrams, gratuitous code fences, and vertical whitespace. Situational reset: - Persisted manager state and the coordinating suffix are authoritative. Inspect bounded \`pardes_status\`, then \`pardes_status(view="inbox")\`, before deciding what changed. diff --git a/plugins/pardes-pi/extensions/pardes/manager/guidance/lifecycle.ts b/plugins/pardes-pi/extensions/pardes/manager/guidance/lifecycle.ts index 7bf705f..c2e1ef0 100644 --- a/plugins/pardes-pi/extensions/pardes/manager/guidance/lifecycle.ts +++ b/plugins/pardes-pi/extensions/pardes/manager/guidance/lifecycle.ts @@ -31,6 +31,7 @@ Operating model: - Publication: use \`pull_request_create\` only for exact committed worker state, keep the owner attached for CI or review feedback, and leave merges under user control. - ${PUBLISHED_REVIEW_FEEDBACK_ROUTING_GUIDANCE} - Inbox has exactly two paths: ${INBOX_TWO_PATH_GUIDANCE} +- Friction: use \`feedback({ text })\` for anything about Pardes that is frustrating, confusing, broken, annoying, or wasteful, not only harness bugs. Describe it in your own bounded words; do not dump logs, files, environment values, or secrets. - Communication: state facts, decision needed, blockers, and next action. Skip fluff, repeated narration, excess headings, pseudo-diagrams, gratuitous code fences, and vertical whitespace. `.trim(); diff --git a/plugins/pardes-pi/extensions/pardes/manager/verification/provisioning.ts b/plugins/pardes-pi/extensions/pardes/manager/verification/provisioning.ts index b4dd94c..542d9a7 100644 --- a/plugins/pardes-pi/extensions/pardes/manager/verification/provisioning.ts +++ b/plugins/pardes-pi/extensions/pardes/manager/verification/provisioning.ts @@ -169,12 +169,16 @@ export function makeVerificationProvisioner( childProfile: verifierChildProfile(worktree.branchPointSha, inspected.headSha), cwd: reviewCheckout.path, lifecycleGeneration: 1, + managerId: namespace.managerId, model, + repositoryKey: namespace.repo.key, sessionDir, sessionName: `Verifier · ${source.workstreamId} · ${verificationId}`, task: verifierPrompt(task, 1, inspected.headSha, worktree.branchPointSha), thinkingLevel, + verificationId, workerExtensionPath, + workstreamId: source.workstreamId, }) .pipe(Effect.exit); if (Exit.isFailure(runtimeResult)) { @@ -445,7 +449,9 @@ export function makeVerificationProvisioner( childProfile: verifierChildProfile(worktree.branchPointSha, inspected.headSha), cwd: reviewCheckout.path, lifecycleGeneration: attempt, + managerId: namespace.managerId, model: verification.model, + repositoryKey: namespace.repo.key, sessionDir: verifierAgent.sessionDir, sessionFile: verifierAgent.sessionFile, sessionName: `Verifier · ${verification.workstreamId} · ${verificationId}`, @@ -456,7 +462,9 @@ export function makeVerificationProvisioner( worktree.branchPointSha, ), thinkingLevel: verification.thinkingLevel, + verificationId, workerExtensionPath, + workstreamId: verification.workstreamId, }) .pipe(Effect.exit); if (Exit.isFailure(runtimeResult)) { diff --git a/plugins/pardes-pi/extensions/pardes/tools/feedback.ts b/plugins/pardes-pi/extensions/pardes/tools/feedback.ts new file mode 100644 index 0000000..ff16d43 --- /dev/null +++ b/plugins/pardes-pi/extensions/pardes/tools/feedback.ts @@ -0,0 +1,44 @@ +import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'; +import { + executeFeedbackTool, + FEEDBACK_TOOL_DESCRIPTION, + type FeedbackSource, + feedbackToolParameters, +} from '../feedback/index.ts'; +import type { ManagerController } from '../manager/index.ts'; +import { registerPardesTool, textResult } from './registration.ts'; + +export function registerManagerFeedbackTool( + pi: ExtensionAPI, + manager: Pick, +): void { + registerPardesTool(pi, { + description: FEEDBACK_TOOL_DESCRIPTION, + async execute(_toolCallId, params, _signal, _onUpdate, ctx) { + const state = manager.snapshot(); + const source: FeedbackSource = { + ...(state === undefined + ? {} + : { managerId: state.managerId, repositoryKey: state.repo.key }), + role: 'manager', + }; + try { + const recorded = await executeFeedbackTool(params.text, source, ctx); + return textResult(`Feedback recorded as ${recorded.id}.`, { + pardesFeedback: { id: recorded.id, type: 'recorded' }, + }); + } catch { + throw new Error('Pardes could not record feedback in global state.'); + } + }, + label: 'Record Feedback', + name: 'feedback', + parameters: feedbackToolParameters, + preview: (args) => [{ mode: 'length', name: 'text', value: args.text }], + promptGuidelines: [ + 'Use feedback to preserve anything about Pardes that is frustrating, confusing, broken, annoying, or wasteful; do not wait for a harness-specific bug or force a category.', + ], + promptSnippet: + 'Record any frustrating, confusing, broken, annoying, or wasteful Pardes experience', + }); +} diff --git a/plugins/pardes-pi/extensions/pardes/tools/index.ts b/plugins/pardes-pi/extensions/pardes/tools/index.ts index 0cdcbf4..cef5381 100644 --- a/plugins/pardes-pi/extensions/pardes/tools/index.ts +++ b/plugins/pardes-pi/extensions/pardes/tools/index.ts @@ -7,6 +7,7 @@ import { registerInboxGetTool, registerPardesStatusTool, } from './control-plane.ts'; +import { registerManagerFeedbackTool } from './feedback.ts'; import { registerHostedDrilldownTools } from './hosted-drilldown.ts'; import { registerPullRequestTools } from './pull-requests.ts'; import { registerReportTools } from './reports.ts'; @@ -39,6 +40,7 @@ export { registerQuestionTool } from './question.ts'; export { registerPullRequestTools }; export function registerWorkstreamTools(pi: ExtensionAPI, manager: ManagerController): void { + registerManagerFeedbackTool(pi, manager); registerPardesStatusTool(pi, manager); registerWorkstreamDomainTools(pi, manager); registerReportTools(pi, manager); diff --git a/plugins/pardes-pi/extensions/pardes/tools/registration.test.ts b/plugins/pardes-pi/extensions/pardes/tools/registration.test.ts index 0dbcf37..fed1a8d 100644 --- a/plugins/pardes-pi/extensions/pardes/tools/registration.test.ts +++ b/plugins/pardes-pi/extensions/pardes/tools/registration.test.ts @@ -107,7 +107,10 @@ describe('Pardes interactive tool-call previews', () => { registerWorkstreamTools(pi, manager); registerAgentTools(pi, manager); - expect(tools).toHaveLength(26); + expect(tools).toHaveLength(27); + expect(tools.map((tool) => tool.name)).toContain('feedback'); + const feedback = requiredValue(tools.find((tool) => tool.name === 'feedback')); + expect((feedback.parameters as unknown as { required: string[] }).required).toEqual(['text']); for (const tool of tools) { expect(tool.executionMode, tool.name).toBe('sequential'); expect(typeof tool.renderCall, tool.name).toBe('function'); @@ -126,6 +129,7 @@ describe('Pardes interactive tool-call previews', () => { reportId: 'report-123', sourceAgentId: 'agent-123', task: 'private task', + text: 'private frustration', title: 'title', verificationId: 'verify-123', workstreamId: 'ws-123', diff --git a/plugins/pardes-pi/extensions/pardes/tools/tools.test.ts b/plugins/pardes-pi/extensions/pardes/tools/tools.test.ts index 01bf966..6b157ab 100644 --- a/plugins/pardes-pi/extensions/pardes/tools/tools.test.ts +++ b/plugins/pardes-pi/extensions/pardes/tools/tools.test.ts @@ -193,6 +193,7 @@ describe('Pardes model-visible tools', () => { expect([...tools.keys()]).toEqual([ 'question', + 'feedback', 'pardes_status', 'workstream_create', 'workstream_list', diff --git a/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.test.ts b/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.test.ts index 2fd91a3..92f51a0 100644 --- a/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.test.ts +++ b/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.test.ts @@ -243,6 +243,7 @@ describe('verifier child profile', () => { }, } as unknown as ExtensionAPI); expect(tools.map((tool) => tool.name)).toEqual([ + 'feedback', 'verification_evidence', 'report_to_manager', 'ask_manager', @@ -474,6 +475,7 @@ describe('worker child reporting tool rendering', () => { } as unknown as Theme; const argsByTool = { ask_manager: { context: 'private context', question: 'private question' }, + feedback: { text: 'private frustration' }, report_to_manager: { details: 'private details', status: 'progress', @@ -481,7 +483,11 @@ describe('worker child reporting tool rendering', () => { }, } as const; - expect(tools.map((tool) => tool.name)).toEqual(['report_to_manager', 'ask_manager']); + expect(tools.map((tool) => tool.name)).toEqual([ + 'feedback', + 'report_to_manager', + 'ask_manager', + ]); const reportParameters = requiredValue( tools.find((tool) => tool.name === 'report_to_manager'), ).parameters as unknown as ToolParametersPreview; diff --git a/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.ts b/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.ts index d04317b..625b4ee 100644 --- a/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.ts +++ b/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.ts @@ -6,6 +6,12 @@ import { StringDecoder } from 'node:string_decoder'; import { fileURLToPath } from 'node:url'; import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'; import { Type } from 'typebox'; +import { + childFeedbackSourceFromEnvironment, + executeFeedbackTool, + FEEDBACK_TOOL_DESCRIPTION, + feedbackToolParameters, +} from '../feedback/index.ts'; import { CHILD_QUESTION_CONTEXT_MAX_CHARS, CHILD_QUESTION_MAX_CHARS, @@ -379,9 +385,57 @@ export default function pardesWorker(pi: ExtensionAPI): void { if (reason) return { block: true, reason }; }); - if (profile.type === 'verifier') registerVerifierTools(pi, root, profile); - const verifier = profile.type === 'verifier'; + pi.registerTool({ + description: FEEDBACK_TOOL_DESCRIPTION, + async execute(_toolCallId, params, _signal, _onUpdate, ctx) { + try { + const recorded = await executeFeedbackTool( + params.text, + childFeedbackSourceFromEnvironment( + process.env, + verifier ? 'advisory_verifier' : 'writer', + ), + ctx, + ); + return text(`Feedback recorded as ${recorded.id}.`, { + pardesFeedback: { id: recorded.id, type: 'recorded' }, + }); + } catch { + throw new Error('Pardes could not record feedback in global state.'); + } + }, + label: 'Record Feedback', + name: 'feedback', + parameters: feedbackToolParameters, + promptGuidelines: [ + 'Use feedback to preserve anything about Pardes that is frustrating, confusing, broken, annoying, or wasteful; do not wait for a harness-specific bug or force a category.', + ], + promptSnippet: + 'Record any frustrating, confusing, broken, annoying, or wasteful Pardes experience', + renderCall(args, theme, context) { + return renderChildToolCall( + theme, + 'feedback', + [{ mode: 'length', name: 'text', value: args.text }], + !context.isPartial, + ); + }, + renderResult(result, options, theme, context) { + return renderChildToolResult( + theme, + 'feedback', + [{ mode: 'length', name: 'text', value: context.args.text }], + result, + options, + context, + ); + }, + renderShell: 'self', + }); + + if (verifier) registerVerifierTools(pi, root, profile); + const reportStatus = Type.Union( [Type.Literal('progress'), Type.Literal('completed'), Type.Literal('blocked')], { diff --git a/plugins/pardes-pi/extensions/pardes/worker-runtime/child-profile.ts b/plugins/pardes-pi/extensions/pardes/worker-runtime/child-profile.ts index 420a125..d7d46a6 100644 --- a/plugins/pardes-pi/extensions/pardes/worker-runtime/child-profile.ts +++ b/plugins/pardes-pi/extensions/pardes/worker-runtime/child-profile.ts @@ -1,6 +1,7 @@ -export const WORKER_TOOLS = 'read,bash,edit,write,grep,find,ls,report_to_manager,ask_manager'; +export const WORKER_TOOLS = + 'read,bash,edit,write,grep,find,ls,feedback,report_to_manager,ask_manager'; export const VERIFIER_TOOLS = - 'read,bash,grep,find,ls,verification_evidence,report_to_manager,ask_manager'; + 'read,bash,grep,find,ls,feedback,verification_evidence,report_to_manager,ask_manager'; // Calibrated mirror of reporting write policy. Keep these literals inside the // intentionally narrow immutable child-runtime snapshot and cover alignment in tests. diff --git a/plugins/pardes-pi/extensions/pardes/worker-runtime/process.test.ts b/plugins/pardes-pi/extensions/pardes/worker-runtime/process.test.ts index 4589e9e..6aaa011 100644 --- a/plugins/pardes-pi/extensions/pardes/worker-runtime/process.test.ts +++ b/plugins/pardes-pi/extensions/pardes/worker-runtime/process.test.ts @@ -78,6 +78,7 @@ describe('worker process', () => { 'grep', 'find', 'ls', + 'feedback', 'verification_evidence', 'report_to_manager', 'ask_manager', @@ -205,22 +206,35 @@ process.stdout.write(JSON.stringify({ agentProfile: process.env.PARDES_AGENT_PROFILE, verificationBaseline: process.env.PARDES_VERIFICATION_BASELINE_SHA, verificationReviewed: process.env.PARDES_VERIFICATION_REVIEWED_SHA, + feedbackAgentId: process.env.PARDES_FEEDBACK_AGENT_ID, + feedbackManagerId: process.env.PARDES_FEEDBACK_MANAGER_ID, + feedbackRepositoryKey: process.env.PARDES_FEEDBACK_REPOSITORY_KEY, + feedbackVerificationId: process.env.PARDES_FEEDBACK_VERIFICATION_ID, + feedbackWorkstreamId: process.env.PARDES_FEEDBACK_WORKSTREAM_ID, }) + "\\n"); setInterval(() => {}, 1000); `, ); const scope = await Effect.runPromise(Scope.make()); const child = await Effect.runPromise( - spawnWorkerProcess(workerInput(root), { - args: () => [script], - command: process.execPath, - env: { - PARDES_PROCESS_FIXTURE: 'present', - PARDES_VERIFICATION_BASELINE_SHA: 'leaked-baseline', - PARDES_VERIFICATION_REVIEWED_SHA: 'leaked-reviewed-head', - PARDES_WORKTREE_ROOT: '/tmp/incorrect-root', + spawnWorkerProcess( + workerInput(root, { + managerId: 'manager-process-fixture', + repositoryKey: 'repo-process-fixture', + verificationId: 'verify-process-fixture', + workstreamId: 'stream-process-fixture', + }), + { + args: () => [script], + command: process.execPath, + env: { + PARDES_PROCESS_FIXTURE: 'present', + PARDES_VERIFICATION_BASELINE_SHA: 'leaked-baseline', + PARDES_VERIFICATION_REVIEWED_SHA: 'leaked-reviewed-head', + PARDES_WORKTREE_ROOT: '/tmp/incorrect-root', + }, }, - }).pipe(Scope.provide(scope)), + ).pipe(Scope.provide(scope)), ); try { expect(child.stdin.writable).toBe(true); @@ -232,6 +246,11 @@ setInterval(() => {}, 1000); expect(JSON.parse(line) as unknown).toEqual({ agentProfile: 'worker', cwd: realpathSync(root), + feedbackAgentId: 'agent-process-fixture', + feedbackManagerId: 'manager-process-fixture', + feedbackRepositoryKey: 'repo-process-fixture', + feedbackVerificationId: 'verify-process-fixture', + feedbackWorkstreamId: 'stream-process-fixture', fixture: 'present', inheritedPath: process.env.PATH, worktreeRoot: root, diff --git a/plugins/pardes-pi/extensions/pardes/worker-runtime/process.ts b/plugins/pardes-pi/extensions/pardes/worker-runtime/process.ts index 21c9097..a691db9 100644 --- a/plugins/pardes-pi/extensions/pardes/worker-runtime/process.ts +++ b/plugins/pardes-pi/extensions/pardes/worker-runtime/process.ts @@ -19,6 +19,10 @@ export const DEFAULT_WORKER_EXTENSION = fileURLToPath( export interface WorkerProcessInput { readonly agentId: string; + readonly managerId?: string; + readonly repositoryKey?: string; + readonly workstreamId?: string; + readonly verificationId?: string; readonly cwd: string; readonly sessionDir: string; readonly sessionFile?: string; @@ -106,6 +110,11 @@ export function spawnWorkerProcess( const env = gitEnvironmentForExplicitCwd({ ...process.env, ...options.env, + PARDES_FEEDBACK_AGENT_ID: input.agentId, + PARDES_FEEDBACK_MANAGER_ID: input.managerId, + PARDES_FEEDBACK_REPOSITORY_KEY: input.repositoryKey, + PARDES_FEEDBACK_VERIFICATION_ID: input.verificationId, + PARDES_FEEDBACK_WORKSTREAM_ID: input.workstreamId, PARDES_WORKTREE_ROOT: input.cwd, ...childProfileEnvironment(input.childProfile), }); diff --git a/plugins/pardes-pi/extensions/pardes/worker-runtime/retained-runtime.ts b/plugins/pardes-pi/extensions/pardes/worker-runtime/retained-runtime.ts index 3d8fd1b..f9cc5a0 100644 --- a/plugins/pardes-pi/extensions/pardes/worker-runtime/retained-runtime.ts +++ b/plugins/pardes-pi/extensions/pardes/worker-runtime/retained-runtime.ts @@ -33,6 +33,10 @@ export interface WorkerCompactionCompletion { export interface WorkerSpawnInput { readonly agentId: string; + readonly managerId?: string; + readonly repositoryKey?: string; + readonly workstreamId?: string; + readonly verificationId?: string; readonly cwd: string; readonly sessionDir: string; readonly sessionFile?: string; diff --git a/plugins/pardes-pi/scripts/pardes-feedback.ts b/plugins/pardes-pi/scripts/pardes-feedback.ts new file mode 100755 index 0000000..d1fe7b7 --- /dev/null +++ b/plugins/pardes-pi/scripts/pardes-feedback.ts @@ -0,0 +1,5 @@ +#!/usr/bin/env bun + +import { runFeedbackCli } from '../extensions/pardes/feedback/index.ts'; + +process.exitCode = await runFeedbackCli(process.argv.slice(2)); From c419dfe08c6726379fe8352df45a5d16127377ad Mon Sep 17 00:00:00 2001 From: Marvin Bitterlich <644950+marvin-bitterlich@users.noreply.github.com> Date: Sat, 11 Jul 2026 18:52:49 +0100 Subject: [PATCH 2/8] fix(pardes-pi): harden feedback privacy and watch recovery --- plugins/pardes-pi/README.md | 11 +- plugins/pardes-pi/docs/NORTH_STAR.md | 13 +- .../extensions/pardes/feedback/cli.ts | 49 +-- .../pardes/feedback/feedback.test.ts | 226 +++++++++++++- .../extensions/pardes/feedback/index.ts | 6 + .../extensions/pardes/feedback/schemas.ts | 9 + .../extensions/pardes/feedback/store.ts | 292 ++++++++++++++++-- 7 files changed, 560 insertions(+), 46 deletions(-) diff --git a/plugins/pardes-pi/README.md b/plugins/pardes-pi/README.md index 5715aa1..607b5a6 100644 --- a/plugins/pardes-pi/README.md +++ b/plugins/pardes-pi/README.md @@ -128,7 +128,8 @@ provenance (time, id, role and available session/manager/agent/workstream, repository, verifier, and version identities); it never automatically captures logs, files, environment values, or secrets. -Each submission is an immutable atomic JSON record in the global registry. +Each submission is an immutable atomic JSON record in the owner-only global +registry; existing registry directories and artifacts are tightened when read. Addressed state is stored separately so triage never rewrites the submission. The installed package exposes a human CLI: @@ -141,9 +142,11 @@ pardes-feedback address ``` From a source checkout, use `bun run feedback -- `. Watch cursors use -atomic per-entry receipts, so concurrent scans and restarted watchers do not log -the same entry twice. CLI rendering treats feedback text as untrusted and -escapes terminal controls. +one durable initialization boundary, a recoverable cross-process scan lock, and +atomic per-entry receipts written only after output succeeds. Concurrent scans +do not duplicate output; a crash between output and receipt deliberately replays +the entry after restart for at-least-once delivery. CLI rendering treats feedback +text as untrusted and escapes terminal controls. ## Development validation diff --git a/plugins/pardes-pi/docs/NORTH_STAR.md b/plugins/pardes-pi/docs/NORTH_STAR.md index c957048..b023157 100644 --- a/plugins/pardes-pi/docs/NORTH_STAR.md +++ b/plugins/pardes-pi/docs/NORTH_STAR.md @@ -329,11 +329,14 @@ free-form text field and covers anything frustrating, confusing, broken, annoying, or wasteful rather than only harness defects. Each submission is a separate immutable atomic JSON record in global Pardes state. Pardes adds only bounded explicit provenance and never automatically captures logs, file -contents, environment values, or secrets. Human addressed-state triage remains -in a separate durable record. The `pardes-feedback` CLI lists, filters, shows, -watches, and marks entries addressed; durable per-entry watch receipts prevent -duplicate logging across races and restarts, and terminal output treats authored -text as untrusted data. +contents, environment values, or secrets. Registry directories and artifacts +are owner-only, including tightened existing entries. Human addressed-state +triage remains in a separate durable record. The `pardes-feedback` CLI lists, +filters, shows, watches, and marks entries addressed. Watch uses one durable +initialization boundary, a recoverable cross-process scan lock, and output-before- +receipt at-least-once delivery: ordinary concurrent scans do not duplicate, while +a crash between output and receipt safely replays after restart. Terminal output +treats authored text as untrusted data. ## External feedback and trust diff --git a/plugins/pardes-pi/extensions/pardes/feedback/cli.ts b/plugins/pardes-pi/extensions/pardes/feedback/cli.ts index 530b32d..f939891 100644 --- a/plugins/pardes-pi/extensions/pardes/feedback/cli.ts +++ b/plugins/pardes-pi/extensions/pardes/feedback/cli.ts @@ -6,16 +6,19 @@ import { matchesFeedbackFilter, } from './schemas.ts'; import { + acquireFeedbackWatchLock, claimFeedbackForWatch, + ensureFeedbackWatchInitialized, + feedbackWasSeenByWatch, getFeedback, listFeedback, markFeedbackAddressed, pardesGlobalStateRoot, - watchCursorExists, } from './store.ts'; const UNSAFE_TERMINAL_CHARACTERS = /[\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu; const ROLES = new Set(['manager', 'writer', 'advisory_verifier']); +const CANONICAL_ISO_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/; export interface FeedbackCliIo { readonly out: (line: string) => void; @@ -46,14 +49,14 @@ Commands: list List feedback entries show Show one entry and its separate triage state address Mark an entry addressed without changing its submission - watch Watch newly recorded feedback with a durable de-duplication cursor + watch Watch new feedback with a durable at-least-once cursor help Show this help Filters (list and watch): --addressed --role --repository --manager --agent - --verification --workstream --since + --verification --workstream --since --text Output and watch options: @@ -69,7 +72,8 @@ Examples: pardes-feedback watch --role writer --cursor writer-triage pardes-feedback address feedback-1234 -Feedback text is untrusted data. Text output escapes terminal controls and directional formatting.`; +Feedback text is untrusted data. Text output escapes terminal controls and directional formatting. +Watch writes each receipt only after output succeeds. A crash between output and receipt replays the entry on restart (at-least-once delivery).`; function terminalSafe(value: string): string { return value.replace( @@ -172,8 +176,13 @@ function parseOptions(args: ReadonlyArray): ParsedOptions { } else if (arg === '--since') { const value = requireValue(args, index, arg); index += 1; - if (Number.isNaN(Date.parse(value))) throw new Error('--since must be an ISO timestamp'); - filter.since = new Date(value).toISOString(); + if ( + !CANONICAL_ISO_TIMESTAMP.test(value) || + Number.isNaN(Date.parse(value)) || + new Date(value).toISOString() !== value + ) + throw new Error('--since must be a canonical ISO timestamp (YYYY-MM-DDTHH:mm:ss.sssZ)'); + filter.since = value; } else if (arg === '--text') { filter.text = requireValue(args, index, arg); index += 1; @@ -196,13 +205,23 @@ function outputEntry(entry: FeedbackEntry, json: boolean, io: FeedbackCliIo): vo } async function scanWatch(options: ParsedOptions, io: FeedbackCliIo, root: string): Promise { - const entries = await Effect.runPromise(listFeedback({}, root)); - for (const entry of entries) { - const claimed = await Effect.runPromise( - claimFeedbackForWatch(options.cursor, entry.submission.id, root), + const lock = await Effect.runPromise(acquireFeedbackWatchLock(options.cursor, root)); + if (!lock) return; + try { + await Effect.runPromise( + ensureFeedbackWatchInitialized(options.cursor, options.includeExisting, root), ); - if (claimed && matchesFeedbackFilter(entry, options.filter)) - outputEntry(entry, options.json, io); + const entries = await Effect.runPromise(listFeedback({}, root)); + for (const entry of entries) { + if ( + await Effect.runPromise(feedbackWasSeenByWatch(options.cursor, entry.submission.id, root)) + ) + continue; + if (matchesFeedbackFilter(entry, options.filter)) outputEntry(entry, options.json, io); + await Effect.runPromise(claimFeedbackForWatch(options.cursor, entry.submission.id, root)); + } + } finally { + await Effect.runPromise(lock.release()); } } @@ -212,12 +231,6 @@ async function watchFeedback( configuration: FeedbackCliOptions, ): Promise { const root = configuration.root ?? pardesGlobalStateRoot(); - const existed = await Effect.runPromise(watchCursorExists(options.cursor, root)); - if (!existed && !options.includeExisting) { - const baseline = await Effect.runPromise(listFeedback({}, root)); - for (const entry of baseline) - await Effect.runPromise(claimFeedbackForWatch(options.cursor, entry.submission.id, root)); - } const sleep = configuration.sleep ?? ((milliseconds) => Bun.sleep(milliseconds)); while (!configuration.signal?.aborted) { await scanWatch(options, io, root); diff --git a/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts b/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts index 0e420ac..350851f 100644 --- a/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts +++ b/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts @@ -1,6 +1,18 @@ -import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs'; +import { spawn } from 'node:child_process'; +import { + chmodSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + statSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; import type { ExtensionContext } from '@earendil-works/pi-coding-agent'; import { Effect } from 'effect'; import { afterEach, describe, expect, test } from 'vitest'; @@ -49,6 +61,32 @@ function sessionContext(sessionId: string) { } as unknown as Pick; } +function runProcess( + command: string, + args: ReadonlyArray, + options: { readonly cwd?: string; readonly env?: NodeJS.ProcessEnv } = {}, +): Promise<{ readonly code: number | null; readonly stderr: string; readonly stdout: string }> { + return new Promise((resolve, reject) => { + const child = spawn(command, [...args], { + cwd: options.cwd, + env: options.env, + stdio: ['ignore', 'pipe', 'pipe'], + }); + const stdout: Buffer[] = []; + const stderr: Buffer[] = []; + child.stdout.on('data', (chunk: Buffer) => stdout.push(chunk)); + child.stderr.on('data', (chunk: Buffer) => stderr.push(chunk)); + child.once('error', reject); + child.once('close', (code) => + resolve({ + code, + stderr: Buffer.concat(stderr).toString('utf8'), + stdout: Buffer.concat(stdout).toString('utf8'), + }), + ); + }); +} + afterEach(() => { for (const root of temporaryDirectories.splice(0)) rmSync(root, { force: true, recursive: true }); }); @@ -78,6 +116,80 @@ describe('global feedback registry', () => { } }); + test('enforces owner-only modes and tightens existing registry permissions', async () => { + const root = temporaryRoot(); + const submission = await Effect.runPromise( + submitFeedback('private friction', provenance(0), root), + ); + const paths = feedbackRegistryPaths(root); + const submissionPath = join(paths.submissions, `${submission.id}.json`); + + for (const directory of [paths.directory, paths.submissions, paths.triage, paths.watchCursors]) + expect(statSync(directory).mode & 0o777).toBe(0o700); + expect(statSync(submissionPath).mode & 0o777).toBe(0o400); + + chmodSync(paths.directory, 0o755); + chmodSync(paths.submissions, 0o755); + chmodSync(submissionPath, 0o444); + await Effect.runPromise(listFeedback({}, root)); + expect(statSync(paths.directory).mode & 0o777).toBe(0o700); + expect(statSync(paths.submissions).mode & 0o777).toBe(0o700); + expect(statSync(submissionPath).mode & 0o777).toBe(0o400); + }); + + test('persists safely across truly separate concurrent writer processes', async () => { + const root = temporaryRoot(); + const writer = join(root, 'writer.ts'); + const storeUrl = new URL('./store.ts', import.meta.url).href; + const effectUrl = pathToFileURL(join(process.cwd(), 'node_modules/effect/dist/Effect.js')).href; + writeFileSync( + writer, + `import * as Effect from ${JSON.stringify(effectUrl)};\nimport { submitFeedback } from ${JSON.stringify(storeUrl)};\nconst [root, index] = process.argv.slice(2);\nawait Effect.runPromise(submitFeedback('process ' + index, { pardesVersion: '0.0.0', role: 'writer', sessionId: 'session-' + index }, root));\n`, + ); + const results = await Promise.all( + Array.from({ length: 12 }, (_, index) => + runProcess('bun', [writer, root, String(index)], { cwd: process.cwd() }), + ), + ); + expect(results.map(({ code }) => code)).toEqual(Array.from({ length: 12 }, () => 0)); + expect(await Effect.runPromise(listFeedback({}, root))).toHaveLength(12); + expect( + readdirSync(feedbackRegistryPaths(root).submissions).some((name) => name.endsWith('.tmp')), + ).toBe(false); + }); + + test('fails closed on redirected or malformed registry artifacts', async () => { + const symlinkRoot = temporaryRoot(); + await Effect.runPromise(submitFeedback('valid', provenance(0), symlinkRoot)); + const symlinkPaths = feedbackRegistryPaths(symlinkRoot); + const redirected = join(symlinkRoot, 'redirected.json'); + writeFileSync(redirected, '{}\n'); + symlinkSync(redirected, join(symlinkPaths.submissions, 'feedback-deadbeef.json')); + await expect(Effect.runPromise(listFeedback({}, symlinkRoot))).rejects.toMatchObject({ + _tag: 'FeedbackStoreError', + }); + + const malformedRoot = temporaryRoot(); + await Effect.runPromise(submitFeedback('valid', provenance(0), malformedRoot)); + writeFileSync( + join(feedbackRegistryPaths(malformedRoot).submissions, 'feedback-deadbeef.json'), + '{not-json}\n', + ); + await expect(Effect.runPromise(listFeedback({}, malformedRoot))).rejects.toMatchObject({ + _tag: 'FeedbackStoreError', + }); + + const directoryRoot = temporaryRoot(); + await Effect.runPromise(submitFeedback('valid', provenance(0), directoryRoot)); + const directoryPaths = feedbackRegistryPaths(directoryRoot); + rmSync(directoryPaths.triage, { recursive: true }); + mkdirSync(join(directoryRoot, 'redirected-triage')); + symlinkSync(join(directoryRoot, 'redirected-triage'), directoryPaths.triage); + await expect(Effect.runPromise(listFeedback({}, directoryRoot))).rejects.toMatchObject({ + _tag: 'FeedbackStoreError', + }); + }); + test('keeps addressed triage separate, durable, idempotent, and leaves the submission unchanged', async () => { const root = temporaryRoot(); const submission = await Effect.runPromise( @@ -229,6 +341,14 @@ describe('feedback CLI', () => { expect(output.at(-1)).toContain(first.id); expect(errors).toEqual([]); expect(terminalSafeJson({ text: dangerous })).not.toContain('\u202e'); + + errors.length = 0; + expect(await runFeedbackCli(['list', '--since', '2026'], io, { root })).toBe(1); + expect(errors[0]).toContain('canonical ISO timestamp'); + errors.length = 0; + expect( + await runFeedbackCli(['list', '--since', '2026-02-30T00:00:00.000Z'], io, { root }), + ).toBe(1); }); test('uses durable atomic watch receipts to survive duplicate scans, concurrent watchers, and restarts', async () => { @@ -255,5 +375,109 @@ describe('feedback CLI', () => { ), ); expect(claims.filter(Boolean)).toHaveLength(1); + + const cursorDirectory = join(feedbackRegistryPaths(root).watchCursors, 'triage'); + expect(statSync(cursorDirectory).mode & 0o777).toBe(0o700); + for (const name of readdirSync(cursorDirectory).filter((name) => name.endsWith('.json'))) + expect(statSync(join(cursorDirectory, name)).mode & 0o777).toBe(0o400); + }); + + test('resumes an interrupted first-use initialization from one stable boundary', async () => { + const root = temporaryRoot(); + const old = await Effect.runPromise(submitFeedback('old entry', provenance(0), root)); + const paths = feedbackRegistryPaths(root); + const cursorDirectory = join(paths.watchCursors, 'interrupted'); + mkdirSync(cursorDirectory, { mode: 0o700, recursive: true }); + const boundaryAt = new Date().toISOString(); + writeFileSync( + join(cursorDirectory, 'initializing.json'), + `${JSON.stringify({ boundaryAt, cursor: 'interrupted', includeExisting: false, schemaVersion: 1, status: 'initializing' })}\n`, + { mode: 0o400 }, + ); + await new Promise((resolve) => setTimeout(resolve, 2)); + const fresh = await Effect.runPromise(submitFeedback('fresh entry', provenance(1), root)); + const output: string[] = []; + const io = { error: () => {}, out: (line: string) => output.push(line) }; + + expect(await runFeedbackCli(['watch', '--once', '--cursor', 'interrupted'], io, { root })).toBe( + 0, + ); + expect(output.some((line) => line.includes(old.id))).toBe(false); + expect(output.filter((line) => line.includes(fresh.id))).toHaveLength(1); + expect( + JSON.parse(readFileSync(join(cursorDirectory, 'initialized.json'), 'utf8')), + ).toMatchObject({ boundaryAt, status: 'initialized' }); + }); + + test('records delivery after output so output failure and crash-lock recovery replay safely', async () => { + const root = temporaryRoot(); + const first = await Effect.runPromise(submitFeedback('must replay', provenance(0), root)); + const errors: string[] = []; + expect( + await runFeedbackCli( + ['watch', '--once', '--include-existing', '--cursor', 'replay'], + { + error: (line) => errors.push(line), + out: () => { + throw new Error('sink failed'); + }, + }, + { root }, + ), + ).toBe(1); + expect(errors[0]).toContain('sink failed'); + + const output: string[] = []; + const io = { error: () => {}, out: (line: string) => output.push(line) }; + expect(await runFeedbackCli(['watch', '--once', '--cursor', 'replay'], io, { root })).toBe(0); + expect(output.filter((line) => line.includes(first.id))).toHaveLength(1); + + const second = await Effect.runPromise(submitFeedback('after crash', provenance(1), root)); + const lockPath = join(feedbackRegistryPaths(root).watchCursors, 'replay', 'scan.lock'); + writeFileSync( + lockPath, + `${JSON.stringify({ createdAt: new Date().toISOString(), pid: 2_147_483_647, token: 'dead-owner' })}\n`, + { mode: 0o600 }, + ); + expect(await runFeedbackCli(['watch', '--once', '--cursor', 'replay'], io, { root })).toBe(0); + expect(output.filter((line) => line.includes(second.id))).toHaveLength(1); + }); + + test('executes through the installed-bin shape and includes feedback runtime files in the package', async () => { + const root = temporaryRoot(); + const binDirectory = join(root, 'node_modules', '.bin'); + mkdirSync(binDirectory, { recursive: true }); + const sourceBin = join(process.cwd(), 'plugins/pardes-pi/scripts/pardes-feedback.ts'); + const installedBin = join(binDirectory, 'pardes-feedback'); + symlinkSync(sourceBin, installedBin); + const help = await runProcess(installedBin, ['help'], { + cwd: process.cwd(), + env: { ...process.env, PARDES_PI_STATE_DIR: root }, + }); + expect(help).toMatchObject({ code: 0, stderr: '' }); + expect(help.stdout).toContain('Usage: pardes-feedback'); + + const submission = await Effect.runPromise( + submitFeedback('installed watch entry', provenance(0), root), + ); + const watched = await runProcess( + installedBin, + ['watch', '--once', '--include-existing', '--cursor', 'installed-bin'], + { cwd: process.cwd(), env: { ...process.env, PARDES_PI_STATE_DIR: root } }, + ); + expect(watched.code).toBe(0); + expect(watched.stdout).toContain(submission.id); + + const packed = await runProcess('bun', ['pm', 'pack', '--dry-run'], { + cwd: process.cwd(), + env: process.env, + }); + expect(packed.code).toBe(0); + expect(`${packed.stdout}\n${packed.stderr}`).toContain( + 'plugins/pardes-pi/scripts/pardes-feedback.ts', + ); + expect(`${packed.stdout}\n${packed.stderr}`).toContain( + 'plugins/pardes-pi/extensions/pardes/feedback/store.ts', + ); }); }); diff --git a/plugins/pardes-pi/extensions/pardes/feedback/index.ts b/plugins/pardes-pi/extensions/pardes/feedback/index.ts index c60189f..1c9f5a1 100644 --- a/plugins/pardes-pi/extensions/pardes/feedback/index.ts +++ b/plugins/pardes-pi/extensions/pardes/feedback/index.ts @@ -20,12 +20,18 @@ export { FeedbackSubmissionSchema, type FeedbackTriage, FeedbackTriageSchema, + type FeedbackWatchInitialization, + FeedbackWatchInitializationSchema, matchesFeedbackFilter, PARDES_VERSION, } from './schemas.ts'; export { + acquireFeedbackWatchLock, claimFeedbackForWatch, + ensureFeedbackWatchInitialized, + type FeedbackWatchLock, feedbackRegistryPaths, + feedbackWasSeenByWatch, getFeedback, listFeedback, markFeedbackAddressed, diff --git a/plugins/pardes-pi/extensions/pardes/feedback/schemas.ts b/plugins/pardes-pi/extensions/pardes/feedback/schemas.ts index 3025a72..b652504 100644 --- a/plugins/pardes-pi/extensions/pardes/feedback/schemas.ts +++ b/plugins/pardes-pi/extensions/pardes/feedback/schemas.ts @@ -39,6 +39,15 @@ export const FeedbackTriageSchema = Schema.Struct({ }); export type FeedbackTriage = typeof FeedbackTriageSchema.Type; +export const FeedbackWatchInitializationSchema = Schema.Struct({ + boundaryAt: NonEmptyString, + cursor: NonEmptyString.check(Schema.isMaxLength(128)), + includeExisting: Schema.Boolean, + schemaVersion: Schema.Literal(FEEDBACK_SCHEMA_VERSION), + status: Schema.Literals(['initializing', 'initialized']), +}); +export type FeedbackWatchInitialization = typeof FeedbackWatchInitializationSchema.Type; + export interface FeedbackEntry { readonly submission: FeedbackSubmission; readonly triage?: FeedbackTriage; diff --git a/plugins/pardes-pi/extensions/pardes/feedback/store.ts b/plugins/pardes-pi/extensions/pardes/feedback/store.ts index ec6b8cd..90df4ed 100644 --- a/plugins/pardes-pi/extensions/pardes/feedback/store.ts +++ b/plugins/pardes-pi/extensions/pardes/feedback/store.ts @@ -1,6 +1,17 @@ import { randomUUID } from 'node:crypto'; import { constants } from 'node:fs'; -import { access, link, lstat, mkdir, open, readdir, readFile, rm } from 'node:fs/promises'; +import { + access, + chmod, + link, + lstat, + mkdir, + open, + readdir, + readFile, + rename, + rm, +} from 'node:fs/promises'; import { homedir } from 'node:os'; import { basename, dirname, join } from 'node:path'; import { Effect, Schema } from 'effect'; @@ -15,12 +26,17 @@ import { FeedbackSubmissionSchema, type FeedbackTriage, FeedbackTriageSchema, + type FeedbackWatchInitialization, + FeedbackWatchInitializationSchema, matchesFeedbackFilter, } from './schemas.ts'; const FEEDBACK_ID_PATTERN = /^feedback-[a-f0-9-]+$/; const CURSOR_PATTERN = /^[a-zA-Z0-9._-]{1,128}$/; const FEEDBACK_ARTIFACT_MAX_BYTES = FEEDBACK_TEXT_MAX_BYTES + 16 * 1_024; +const PRIVATE_DIRECTORY_MODE = 0o700; +const PRIVATE_IMMUTABLE_FILE_MODE = 0o400; +const WATCH_LOCK_RECOVERY_GRACE_MS = 5_000; export interface FeedbackRegistryPaths { readonly directory: string; @@ -67,16 +83,62 @@ async function syncDirectory(directory: string): Promise { } } +async function validateAndTightenPrivateDirectory(path: string): Promise { + const stats = await lstat(path); + if (!stats.isDirectory() || stats.isSymbolicLink()) + throw new Error('feedback registry directory is redirected'); + await chmod(path, PRIVATE_DIRECTORY_MODE); +} + +async function ensurePrivateDirectory(path: string, recursive = false): Promise { + try { + await mkdir(path, { mode: PRIVATE_DIRECTORY_MODE, recursive }); + } catch (error) { + if (!isCode(error, 'EEXIST')) throw error; + } + await validateAndTightenPrivateDirectory(path); +} + +async function tightenJsonArtifacts(directory: string): Promise { + for (const entry of await readdir(directory, { withFileTypes: true })) { + if (!entry.name.endsWith('.json')) continue; + if (!entry.isFile() || entry.isSymbolicLink()) + throw new Error('feedback registry artifact is redirected'); + await chmod(join(directory, entry.name), PRIVATE_IMMUTABLE_FILE_MODE); + } +} + async function ensureDirectories(paths: FeedbackRegistryPaths): Promise { - await mkdir(paths.submissions, { recursive: true }); - await mkdir(paths.triage, { recursive: true }); - await mkdir(paths.watchCursors, { recursive: true }); + await ensurePrivateDirectory(paths.directory, true); + await ensurePrivateDirectory(paths.submissions); + await ensurePrivateDirectory(paths.triage); + await ensurePrivateDirectory(paths.watchCursors); + await tightenJsonArtifacts(paths.submissions); + await tightenJsonArtifacts(paths.triage); + for (const entry of await readdir(paths.watchCursors, { withFileTypes: true })) { + if (!entry.isDirectory() || entry.isSymbolicLink()) + throw new Error('feedback watch cursor directory is redirected'); + const cursorDirectory = join(paths.watchCursors, entry.name); + await validateAndTightenPrivateDirectory(cursorDirectory); + await tightenJsonArtifacts(cursorDirectory); + } +} + +async function ensureCursorDirectory( + paths: FeedbackRegistryPaths, + cursor: string, +): Promise { + if (!CURSOR_PATTERN.test(cursor)) throw new Error('invalid watch cursor'); + await ensureDirectories(paths); + const cursorDirectory = join(paths.watchCursors, cursor); + await ensurePrivateDirectory(cursorDirectory); + return cursorDirectory; } /** Create one immutable, atomically visible artifact without ever replacing an existing target. */ async function createImmutableArtifact(path: string, source: string): Promise { const temporary = `${path}.${randomUUID()}.tmp`; - const handle = await open(temporary, 'wx', 0o444); + const handle = await open(temporary, 'wx', PRIVATE_IMMUTABLE_FILE_MODE); try { await handle.writeFile(source, 'utf8'); await handle.sync(); @@ -164,6 +226,7 @@ export function getFeedback( ? new FeedbackNotFoundError({ feedbackId }) : storeError('read feedback', cause), try: async () => { + await ensureDirectories(paths); const submission = await readDecoded( join(paths.submissions, `${feedbackId}.json`), FeedbackSubmissionSchema, @@ -181,10 +244,14 @@ export function listFeedback( return effectPromise('list feedback', async () => { const paths = feedbackRegistryPaths(root); await ensureDirectories(paths); - const names = (await readdir(paths.submissions, { withFileTypes: true })) - .filter((entry) => entry.isFile() && !entry.isSymbolicLink() && entry.name.endsWith('.json')) - .map((entry) => entry.name) - .sort(); + const names: string[] = []; + for (const entry of await readdir(paths.submissions, { withFileTypes: true })) { + if (!entry.name.endsWith('.json')) continue; + if (!entry.isFile() || entry.isSymbolicLink()) + throw new Error('feedback submission artifact is redirected'); + names.push(entry.name); + } + names.sort(); const entries: FeedbackEntry[] = []; for (const name of names) { const feedbackId = name.slice(0, -'.json'.length); @@ -230,32 +297,221 @@ export function markFeedbackAddressed( ); } -/** Atomically claim one entry for a durable named watch cursor. */ +interface WatchLockRecord { + readonly createdAt: string; + readonly pid: number; + readonly token: string; +} + +export interface FeedbackWatchLock { + readonly release: () => Effect.Effect; +} + +function watchLockRecord(input: unknown): WatchLockRecord | undefined { + if (typeof input !== 'object' || input === null) return; + const record = input as Partial; + return typeof record.createdAt === 'string' && + typeof record.pid === 'number' && + Number.isInteger(record.pid) && + typeof record.token === 'string' + ? { createdAt: record.createdAt, pid: record.pid, token: record.token } + : undefined; +} + +function processIsAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch (error) { + return isCode(error, 'EPERM'); + } +} + +async function releaseWatchLock(path: string, token: string): Promise { + try { + const owner = watchLockRecord(JSON.parse(await readFile(path, 'utf8')) as unknown); + if (owner?.token !== token) return; + await rm(path); + await syncDirectory(dirname(path)); + } catch (error) { + if (!isCode(error, 'ENOENT')) throw error; + } +} + +/** Serialize one cursor scan across processes; dead owners are recovered before replay. */ +export function acquireFeedbackWatchLock( + cursor: string, + root = pardesGlobalStateRoot(), +): Effect.Effect { + return effectPromise('acquire feedback watch lock', async () => { + const cursorDirectory = await ensureCursorDirectory(feedbackRegistryPaths(root), cursor); + const path = join(cursorDirectory, 'scan.lock'); + for (let attempt = 0; attempt < 4; attempt += 1) { + const token = randomUUID(); + const owner: WatchLockRecord = { + createdAt: new Date().toISOString(), + pid: process.pid, + token, + }; + try { + const handle = await open(path, 'wx', 0o600); + try { + await handle.writeFile(`${JSON.stringify(owner)}\n`, 'utf8'); + await handle.sync(); + } finally { + await handle.close(); + } + await syncDirectory(cursorDirectory); + return { + release: () => + effectPromise('release feedback watch lock', () => releaseWatchLock(path, token)), + }; + } catch (error) { + if (!isCode(error, 'EEXIST')) throw error; + } + + const stats = await lstat(path); + if (!stats.isFile() || stats.isSymbolicLink()) + throw new Error('feedback watch lock is redirected'); + let current: WatchLockRecord | undefined; + try { + current = watchLockRecord(JSON.parse(await readFile(path, 'utf8')) as unknown); + } catch { + current = undefined; + } + const young = Date.now() - stats.mtimeMs <= WATCH_LOCK_RECOVERY_GRACE_MS; + if ((current && processIsAlive(current.pid)) || (!current && young)) return undefined; + const stale = `${path}.stale-${randomUUID()}`; + try { + await rename(path, stale); + await rm(stale, { force: true }); + } catch (error) { + if (!isCode(error, 'ENOENT')) return undefined; + } + } + return undefined; + }); +} + +/** Atomically record delivery after output succeeds. */ export function claimFeedbackForWatch( cursor: string, feedbackId: string, root = pardesGlobalStateRoot(), ): Effect.Effect { - return effectPromise('claim feedback for watch', async () => { - if (!CURSOR_PATTERN.test(cursor)) throw new Error('invalid watch cursor'); + return effectPromise('record feedback watch delivery', async () => { if (!validFeedbackId(feedbackId)) throw new Error('invalid feedback id'); - const paths = feedbackRegistryPaths(root); - const cursorDirectory = join(paths.watchCursors, cursor); - await mkdir(cursorDirectory, { recursive: true }); + const cursorDirectory = await ensureCursorDirectory(feedbackRegistryPaths(root), cursor); const receipt = `${JSON.stringify({ feedbackId, seenAt: new Date().toISOString() })}\n`; return createImmutableArtifact(join(cursorDirectory, `${feedbackId}.json`), receipt); }); } +export function feedbackWasSeenByWatch( + cursor: string, + feedbackId: string, + root = pardesGlobalStateRoot(), +): Effect.Effect { + return effectPromise('inspect feedback watch delivery', async () => { + if (!validFeedbackId(feedbackId)) throw new Error('invalid feedback id'); + const cursorDirectory = await ensureCursorDirectory(feedbackRegistryPaths(root), cursor); + try { + await access(join(cursorDirectory, `${feedbackId}.json`), constants.F_OK); + return true; + } catch (error) { + if (isCode(error, 'ENOENT')) return false; + throw error; + } + }); +} + +async function optionalInitialization( + path: string, +): Promise { + try { + return await readDecoded(path, FeedbackWatchInitializationSchema); + } catch (error) { + if (isCode(error, 'ENOENT')) return undefined; + throw error; + } +} + +/** + * Establish one durable timestamp boundary before baseline enumeration. An + * interrupted initializer is resumed from the immutable boundary on restart. + * Callers hold the cursor scan lock while running this transition. + */ +export function ensureFeedbackWatchInitialized( + cursor: string, + includeExisting: boolean, + root = pardesGlobalStateRoot(), +): Effect.Effect { + return effectPromise('initialize feedback watch cursor', async () => { + const cursorDirectory = await ensureCursorDirectory(feedbackRegistryPaths(root), cursor); + const completedPath = join(cursorDirectory, 'initialized.json'); + const completed = await optionalInitialization(completedPath); + if (completed) { + if (completed.cursor !== cursor || completed.status !== 'initialized') + throw new Error('feedback watch initialization does not match its cursor'); + return completed; + } + + const pendingPath = join(cursorDirectory, 'initializing.json'); + let pending = await optionalInitialization(pendingPath); + if (!pending) { + const proposed: FeedbackWatchInitialization = { + boundaryAt: new Date().toISOString(), + cursor, + includeExisting, + schemaVersion: FEEDBACK_SCHEMA_VERSION, + status: 'initializing', + }; + const encoded = await Effect.runPromise( + Schema.encodeEffect(FeedbackWatchInitializationSchema)(proposed), + ); + const created = await createImmutableArtifact( + pendingPath, + `${JSON.stringify(encoded, null, 2)}\n`, + ); + pending = created + ? proposed + : await readDecoded(pendingPath, FeedbackWatchInitializationSchema); + } + if (pending.cursor !== cursor || pending.status !== 'initializing') + throw new Error('feedback watch initialization does not match its cursor'); + + if (!pending.includeExisting) { + const baseline = await Effect.runPromise(listFeedback({}, root)); + for (const entry of baseline) { + if (entry.submission.createdAt < pending.boundaryAt) + await Effect.runPromise(claimFeedbackForWatch(cursor, entry.submission.id, root)); + } + } + + const initialized: FeedbackWatchInitialization = { ...pending, status: 'initialized' }; + const encoded = await Effect.runPromise( + Schema.encodeEffect(FeedbackWatchInitializationSchema)(initialized), + ); + const created = await createImmutableArtifact( + completedPath, + `${JSON.stringify(encoded, null, 2)}\n`, + ); + return created ? initialized : readDecoded(completedPath, FeedbackWatchInitializationSchema); + }); +} + export function watchCursorExists( cursor: string, root = pardesGlobalStateRoot(), ): Effect.Effect { return effectPromise('inspect feedback watch cursor', async () => { - if (!CURSOR_PATTERN.test(cursor)) throw new Error('invalid watch cursor'); + const cursorDirectory = await ensureCursorDirectory(feedbackRegistryPaths(root), cursor); try { - await access(join(feedbackRegistryPaths(root).watchCursors, cursor), constants.F_OK); - return true; + const initialized = await readDecoded( + join(cursorDirectory, 'initialized.json'), + FeedbackWatchInitializationSchema, + ); + return initialized.cursor === cursor && initialized.status === 'initialized'; } catch (error) { if (isCode(error, 'ENOENT')) return false; throw error; From a825b524005015194f3468a6a15afbb6435d1284 Mon Sep 17 00:00:00 2001 From: Marvin Bitterlich <644950+marvin-bitterlich@users.noreply.github.com> Date: Sat, 11 Jul 2026 19:09:53 +0100 Subject: [PATCH 3/8] fix(pardes-pi): fence feedback watch ownership --- plugins/pardes-pi/README.md | 6 +- plugins/pardes-pi/docs/NORTH_STAR.md | 6 +- .../extensions/pardes/feedback/cli.ts | 3 +- .../pardes/feedback/feedback.test.ts | 52 +++++ .../extensions/pardes/feedback/store.ts | 187 +++++++++++++----- .../extensions/pardes/feedback/tool.ts | 4 +- 6 files changed, 199 insertions(+), 59 deletions(-) diff --git a/plugins/pardes-pi/README.md b/plugins/pardes-pi/README.md index 607b5a6..cae1921 100644 --- a/plugins/pardes-pi/README.md +++ b/plugins/pardes-pi/README.md @@ -145,8 +145,10 @@ From a source checkout, use `bun run feedback -- `. Watch cursors use one durable initialization boundary, a recoverable cross-process scan lock, and atomic per-entry receipts written only after output succeeds. Concurrent scans do not duplicate output; a crash between output and receipt deliberately replays -the entry after restart for at-least-once delivery. CLI rendering treats feedback -text as untrusted and escapes terminal controls. +the entry after restart for at-least-once delivery. A cursor consumes every +observed entry, including filter nonmatches, so use a distinct cursor name when +changing filters or triage purpose. CLI rendering treats feedback text as +untrusted and escapes terminal controls. ## Development validation diff --git a/plugins/pardes-pi/docs/NORTH_STAR.md b/plugins/pardes-pi/docs/NORTH_STAR.md index b023157..b99a4e1 100644 --- a/plugins/pardes-pi/docs/NORTH_STAR.md +++ b/plugins/pardes-pi/docs/NORTH_STAR.md @@ -335,8 +335,10 @@ triage remains in a separate durable record. The `pardes-feedback` CLI lists, filters, shows, watches, and marks entries addressed. Watch uses one durable initialization boundary, a recoverable cross-process scan lock, and output-before- receipt at-least-once delivery: ordinary concurrent scans do not duplicate, while -a crash between output and receipt safely replays after restart. Terminal output -treats authored text as untrusted data. +a crash between output and receipt safely replays after restart. Filters apply at +observation time and every observed entry advances that cursor, including +nonmatches; changing filters requires a distinct cursor. Terminal output treats +authored text as untrusted data. ## External feedback and trust diff --git a/plugins/pardes-pi/extensions/pardes/feedback/cli.ts b/plugins/pardes-pi/extensions/pardes/feedback/cli.ts index f939891..bad04a5 100644 --- a/plugins/pardes-pi/extensions/pardes/feedback/cli.ts +++ b/plugins/pardes-pi/extensions/pardes/feedback/cli.ts @@ -73,7 +73,8 @@ Examples: pardes-feedback address feedback-1234 Feedback text is untrusted data. Text output escapes terminal controls and directional formatting. -Watch writes each receipt only after output succeeds. A crash between output and receipt replays the entry on restart (at-least-once delivery).`; +Watch writes each receipt only after output succeeds. A crash between output and receipt replays the entry on restart (at-least-once delivery). +Each cursor consumes every observed entry, including filter nonmatches. Use a new cursor name when changing filters or triage purpose.`; function terminalSafe(value: string): string { return value.replace( diff --git a/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts b/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts index 350851f..3399519 100644 --- a/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts +++ b/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts @@ -303,6 +303,23 @@ describe('feedback provenance and model schema', () => { sessionContext('s'.repeat(700)), ).managerId, ).toHaveLength(512); + + const emoji = '😀'.repeat(700); + const astral = feedbackProvenance( + { managerId: emoji, role: 'manager' }, + sessionContext(emoji), + ); + expect(astral.managerId?.length).toBe(512); + expect(astral.sessionId?.length).toBe(512); + expect(astral.managerId?.endsWith('\ud83d')).toBe(false); + const astralResult = await executeFeedbackTool( + 'astral provenance remains recordable', + { managerId: emoji, role: 'manager' }, + sessionContext(emoji), + ); + expect( + (await Effect.runPromise(getFeedback(astralResult.id, root))).submission.provenance, + ).toMatchObject({ managerId: astral.managerId, sessionId: astral.sessionId }); } finally { if (previous === undefined) delete process.env.PARDES_PI_STATE_DIR; else process.env.PARDES_PI_STATE_DIR = previous; @@ -326,6 +343,7 @@ describe('feedback CLI', () => { expect(await runFeedbackCli(['help'], io, { root })).toBe(0); expect(output.join('\n')).toContain('watch'); expect(output.join('\n')).toContain('address'); + expect(output.join('\n')).toContain('consumes every observed entry'); output.length = 0; expect(await runFeedbackCli(['list', '--role', 'writer', '--text', 'line'], io, { root })).toBe( 0, @@ -443,6 +461,40 @@ describe('feedback CLI', () => { expect(output.filter((line) => line.includes(second.id))).toHaveLength(1); }); + test('fences stale-lock replacement under high-contention separate-process watchers', async () => { + const root = temporaryRoot(); + await Effect.runPromise(submitFeedback('baseline', provenance(0), root)); + const quietIo = { error: () => {}, out: () => {} }; + expect( + await runFeedbackCli(['watch', '--once', '--cursor', 'contention'], quietIo, { root }), + ).toBe(0); + const lockPath = join(feedbackRegistryPaths(root).watchCursors, 'contention', 'scan.lock'); + const sourceBin = join(process.cwd(), 'plugins/pardes-pi/scripts/pardes-feedback.ts'); + for (let round = 0; round < 4; round += 1) { + const unseen = await Effect.runPromise( + submitFeedback(`contended ${round}`, provenance(round + 1), root), + ); + writeFileSync( + lockPath, + `${JSON.stringify({ createdAt: new Date().toISOString(), pid: 2_147_483_647, token: `legacy-dead-owner-${round}` })}\n`, + { mode: 0o600 }, + ); + const watchers = await Promise.all( + Array.from({ length: 16 }, () => + runProcess('bun', [sourceBin, 'watch', '--once', '--cursor', 'contention'], { + cwd: process.cwd(), + env: { ...process.env, PARDES_PI_STATE_DIR: root }, + }), + ), + ); + expect(watchers.filter(({ code }) => code !== 0)).toEqual([]); + expect(watchers.map(({ stderr }) => stderr)).toEqual(Array.from({ length: 16 }, () => '')); + expect( + watchers.reduce((count, { stdout }) => count + Number(stdout.includes(unseen.id)), 0), + ).toBe(1); + } + }); + test('executes through the installed-bin shape and includes feedback runtime files in the package', async () => { const root = temporaryRoot(); const binDirectory = join(root, 'node_modules', '.bin'); diff --git a/plugins/pardes-pi/extensions/pardes/feedback/store.ts b/plugins/pardes-pi/extensions/pardes/feedback/store.ts index 90df4ed..5bdf129 100644 --- a/plugins/pardes-pi/extensions/pardes/feedback/store.ts +++ b/plugins/pardes-pi/extensions/pardes/feedback/store.ts @@ -1,19 +1,9 @@ import { randomUUID } from 'node:crypto'; import { constants } from 'node:fs'; -import { - access, - chmod, - link, - lstat, - mkdir, - open, - readdir, - readFile, - rename, - rm, -} from 'node:fs/promises'; +import { access, chmod, link, lstat, mkdir, open, readdir, readFile, rm } from 'node:fs/promises'; import { homedir } from 'node:os'; import { basename, dirname, join } from 'node:path'; +import { setTimeout as sleep } from 'node:timers/promises'; import { Effect, Schema } from 'effect'; import { FeedbackNotFoundError, FeedbackStoreError } from './errors.ts'; import { @@ -299,6 +289,7 @@ export function markFeedbackAddressed( interface WatchLockRecord { readonly createdAt: string; + readonly ownerFile?: string; readonly pid: number; readonly token: string; } @@ -310,12 +301,20 @@ export interface FeedbackWatchLock { function watchLockRecord(input: unknown): WatchLockRecord | undefined { if (typeof input !== 'object' || input === null) return; const record = input as Partial; - return typeof record.createdAt === 'string' && - typeof record.pid === 'number' && - Number.isInteger(record.pid) && - typeof record.token === 'string' - ? { createdAt: record.createdAt, pid: record.pid, token: record.token } - : undefined; + if ( + typeof record.createdAt !== 'string' || + typeof record.pid !== 'number' || + !Number.isInteger(record.pid) || + typeof record.token !== 'string' || + (record.ownerFile !== undefined && typeof record.ownerFile !== 'string') + ) + return; + return { + createdAt: record.createdAt, + ...(record.ownerFile === undefined ? {} : { ownerFile: record.ownerFile }), + pid: record.pid, + token: record.token, + }; } function processIsAlive(pid: number): boolean { @@ -327,18 +326,111 @@ function processIsAlive(pid: number): boolean { } } -async function releaseWatchLock(path: string, token: string): Promise { +function sameFile( + left: { readonly dev: number; readonly ino: number }, + right: { readonly dev: number; readonly ino: number }, +): boolean { + return left.dev === right.dev && left.ino === right.ino; +} + +async function optionalStats(path: string) { try { - const owner = watchLockRecord(JSON.parse(await readFile(path, 'utf8')) as unknown); - if (owner?.token !== token) return; - await rm(path); - await syncDirectory(dirname(path)); + return await lstat(path); } catch (error) { - if (!isCode(error, 'ENOENT')) throw error; + if (isCode(error, 'ENOENT')) return undefined; + throw error; + } +} + +async function releaseWatchLock( + cursorDirectory: string, + path: string, + ownerPath: string, +): Promise { + for (let attempt = 0; attempt < 100; attempt += 1) { + const ownerStats = await optionalStats(ownerPath); + if (!ownerStats) return; + if (ownerStats.nlink <= 2) break; + await sleep(2); + } + const ownerStats = await optionalStats(ownerPath); + const currentStats = await optionalStats(path); + if (ownerStats && currentStats && sameFile(ownerStats, currentStats)) await rm(path); + await rm(ownerPath, { force: true }); + await syncDirectory(cursorDirectory); +} + +async function recoverObservedWatchLock( + cursorDirectory: string, + path: string, +): Promise<'retry' | 'busy'> { + const observerPath = join(cursorDirectory, `observer-${process.pid}-${randomUUID()}.lock`); + try { + try { + await link(path, observerPath); + } catch (error) { + if (isCode(error, 'ENOENT')) return 'retry'; + throw error; + } + const observedStats = await lstat(observerPath); + if (!observedStats.isFile() || observedStats.isSymbolicLink()) + throw new Error('feedback watch lock is redirected'); + let observed: WatchLockRecord | undefined; + try { + if (observedStats.size <= 16 * 1_024) + observed = watchLockRecord(JSON.parse(await readFile(observerPath, 'utf8')) as unknown); + } catch { + observed = undefined; + } + const young = Date.now() - observedStats.mtimeMs <= WATCH_LOCK_RECOVERY_GRACE_MS; + if ((observed && processIsAlive(observed.pid)) || (!observed && young)) return 'busy'; + + for (const entry of await readdir(cursorDirectory, { withFileTypes: true })) { + const match = /^observer-(\d+)-[a-f0-9-]+\.lock$/.exec(entry.name); + if (!match || entry.name === basename(observerPath) || !entry.isFile()) continue; + const observerPid = Number(match[1]); + if (Number.isInteger(observerPid) && processIsAlive(observerPid)) continue; + const staleObserverPath = join(cursorDirectory, entry.name); + const staleObserverStats = await optionalStats(staleObserverPath); + if (staleObserverStats && sameFile(observedStats, staleObserverStats)) + await rm(staleObserverPath, { force: true }); + } + + let ownerPath: string | undefined; + let ownerStats: Awaited> | undefined; + if (observed?.ownerFile && /^owner-[a-f0-9-]+\.lock$/.test(observed.ownerFile)) { + ownerPath = join(cursorDirectory, observed.ownerFile); + ownerStats = await optionalStats(ownerPath); + if (ownerStats && !sameFile(observedStats, ownerStats)) ownerStats = undefined; + } + const expectedLinks = ownerStats ? 3 : 2; + const freshObservedStats = await optionalStats(observerPath); + if (!freshObservedStats || freshObservedStats.nlink !== expectedLinks) { + await sleep(Math.floor(Math.random() * 5) + 1); + return 'retry'; + } + + const currentStats = await optionalStats(path); + if (!currentStats || !sameFile(observedStats, currentStats)) return 'retry'; + try { + await rm(path); + } catch (error) { + if (!isCode(error, 'ENOENT')) throw error; + return 'retry'; + } + + if (ownerPath && ownerStats) await rm(ownerPath, { force: true }); + await syncDirectory(cursorDirectory); + return 'retry'; + } finally { + await rm(observerPath, { force: true }); } } -/** Serialize one cursor scan across processes; dead owners are recovered before replay. */ +/** + * Serialize one cursor scan across processes. Unique owner inodes and temporary + * observer hard links fence stale recovery so it can never unlink a successor. + */ export function acquireFeedbackWatchLock( cursor: string, root = pardesGlobalStateRoot(), @@ -346,48 +438,37 @@ export function acquireFeedbackWatchLock( return effectPromise('acquire feedback watch lock', async () => { const cursorDirectory = await ensureCursorDirectory(feedbackRegistryPaths(root), cursor); const path = join(cursorDirectory, 'scan.lock'); - for (let attempt = 0; attempt < 4; attempt += 1) { + for (let attempt = 0; attempt < 8; attempt += 1) { const token = randomUUID(); + const ownerFile = `owner-${token}.lock`; + const ownerPath = join(cursorDirectory, ownerFile); const owner: WatchLockRecord = { createdAt: new Date().toISOString(), + ownerFile, pid: process.pid, token, }; + const handle = await open(ownerPath, 'wx', 0o600); try { - const handle = await open(path, 'wx', 0o600); - try { - await handle.writeFile(`${JSON.stringify(owner)}\n`, 'utf8'); - await handle.sync(); - } finally { - await handle.close(); - } + await handle.writeFile(`${JSON.stringify(owner)}\n`, 'utf8'); + await handle.sync(); + } finally { + await handle.close(); + } + try { + await link(ownerPath, path); await syncDirectory(cursorDirectory); return { release: () => - effectPromise('release feedback watch lock', () => releaseWatchLock(path, token)), + effectPromise('release feedback watch lock', () => + releaseWatchLock(cursorDirectory, path, ownerPath), + ), }; } catch (error) { + await rm(ownerPath, { force: true }); if (!isCode(error, 'EEXIST')) throw error; } - - const stats = await lstat(path); - if (!stats.isFile() || stats.isSymbolicLink()) - throw new Error('feedback watch lock is redirected'); - let current: WatchLockRecord | undefined; - try { - current = watchLockRecord(JSON.parse(await readFile(path, 'utf8')) as unknown); - } catch { - current = undefined; - } - const young = Date.now() - stats.mtimeMs <= WATCH_LOCK_RECOVERY_GRACE_MS; - if ((current && processIsAlive(current.pid)) || (!current && young)) return undefined; - const stale = `${path}.stale-${randomUUID()}`; - try { - await rename(path, stale); - await rm(stale, { force: true }); - } catch (error) { - if (!isCode(error, 'ENOENT')) return undefined; - } + if ((await recoverObservedWatchLock(cursorDirectory, path)) === 'busy') return undefined; } return undefined; }); diff --git a/plugins/pardes-pi/extensions/pardes/feedback/tool.ts b/plugins/pardes-pi/extensions/pardes/feedback/tool.ts index 408d6ea..fdb6b92 100644 --- a/plugins/pardes-pi/extensions/pardes/feedback/tool.ts +++ b/plugins/pardes-pi/extensions/pardes/feedback/tool.ts @@ -29,7 +29,9 @@ export interface FeedbackSource { function boundedIdentity(value: string | undefined): string | undefined { if (value === undefined || value.length === 0) return undefined; - return Array.from(value).slice(0, 512).join(''); + const bounded = value.slice(0, 512); + const finalCodeUnit = bounded.charCodeAt(bounded.length - 1); + return finalCodeUnit >= 0xd800 && finalCodeUnit <= 0xdbff ? bounded.slice(0, -1) : bounded; } export function feedbackProvenance( From b96cf782d46652ee59f50f81020b2b6c617867d3 Mon Sep 17 00:00:00 2001 From: Marvin Bitterlich <644950+marvin-bitterlich@users.noreply.github.com> Date: Sat, 11 Jul 2026 19:26:29 +0100 Subject: [PATCH 4/8] fix(pardes-pi): elect stale feedback lock recovery --- .../extensions/pardes/feedback/cli.ts | 13 +- .../pardes/feedback/feedback.test.ts | 84 +++++++ .../extensions/pardes/feedback/store.ts | 206 +++++++++++++++--- 3 files changed, 275 insertions(+), 28 deletions(-) diff --git a/plugins/pardes-pi/extensions/pardes/feedback/cli.ts b/plugins/pardes-pi/extensions/pardes/feedback/cli.ts index bad04a5..52c482b 100644 --- a/plugins/pardes-pi/extensions/pardes/feedback/cli.ts +++ b/plugins/pardes-pi/extensions/pardes/feedback/cli.ts @@ -1,4 +1,5 @@ import { Effect } from 'effect'; +import { FeedbackNotFoundError, FeedbackStoreError } from './errors.ts'; import { type FeedbackEntry, type FeedbackFilter, @@ -76,6 +77,15 @@ Feedback text is untrusted data. Text output escapes terminal controls and direc Watch writes each receipt only after output succeeds. A crash between output and receipt replays the entry on restart (at-least-once delivery). Each cursor consumes every observed entry, including filter nonmatches. Use a new cursor name when changing filters or triage purpose.`; +function cliErrorMessage(error: unknown): string { + if (error instanceof FeedbackStoreError) { + const cause = error.cause instanceof Error ? error.cause.message : String(error.cause); + return `${error.operation}: ${cause}`; + } + if (error instanceof FeedbackNotFoundError) return `feedback not found: ${error.feedbackId}`; + return error instanceof Error ? error.message : String(error); +} + function terminalSafe(value: string): string { return value.replace( UNSAFE_TERMINAL_CHARACTERS, @@ -285,8 +295,7 @@ export async function runFeedbackCli( } throw new Error(`unknown command: ${command}`); } catch (error) { - const message = error instanceof Error ? error.message : String(error); - io.error(`pardes-feedback: ${terminalSafe(message)}`); + io.error(`pardes-feedback: ${terminalSafe(cliErrorMessage(error))}`); io.error('Run pardes-feedback help for usage.'); return 1; } diff --git a/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts b/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts index 3399519..ec6ff02 100644 --- a/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts +++ b/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts @@ -461,6 +461,90 @@ describe('feedback CLI', () => { expect(output.filter((line) => line.includes(second.id))).toHaveLength(1); }); + test('elects one synchronized in-process stale-lock recovery winner and sweeps dead artifacts', async () => { + const root = temporaryRoot(); + await Effect.runPromise(submitFeedback('baseline', provenance(0), root)); + const quietIo = { error: () => {}, out: () => {} }; + expect( + await runFeedbackCli(['watch', '--once', '--cursor', 'synchronized'], quietIo, { root }), + ).toBe(0); + const unseen = await Effect.runPromise(submitFeedback('synchronized', provenance(1), root)); + const cursorDirectory = join(feedbackRegistryPaths(root).watchCursors, 'synchronized'); + const deadPid = 2_147_483_647; + const token = '00000000-0000-4000-8000-000000000001'; + writeFileSync( + join(cursorDirectory, 'scan.lock'), + `${JSON.stringify({ createdAt: new Date().toISOString(), pid: deadPid, token: 'dead' })}\n`, + { mode: 0o600 }, + ); + writeFileSync( + join(cursorDirectory, `owner-${token}.lock`), + `${JSON.stringify({ createdAt: new Date().toISOString(), pid: deadPid, token })}\n`, + { mode: 0o600 }, + ); + writeFileSync( + join(cursorDirectory, `observer-${deadPid}-${token}.lock`), + `${JSON.stringify({ createdAt: new Date().toISOString(), pid: deadPid, token })}\n`, + { mode: 0o600 }, + ); + writeFileSync( + join(cursorDirectory, `recovery-1-2-ticket-${token}.lock`), + `${JSON.stringify({ createdAt: new Date().toISOString(), pid: deadPid, ticket: 1, token })}\n`, + { mode: 0o600 }, + ); + + const outputs = Array.from({ length: 20 }, () => [] as string[]); + const codes = await Promise.all( + outputs.map((output) => + runFeedbackCli( + ['watch', '--once', '--cursor', 'synchronized'], + { error: () => {}, out: (line) => output.push(line) }, + { root }, + ), + ), + ); + expect(codes).toEqual(Array.from({ length: 20 }, () => 0)); + expect(outputs.flat().filter((line) => line.includes(unseen.id))).toHaveLength(1); + expect(readdirSync(cursorDirectory).filter((entry) => entry.includes(token))).toEqual([]); + }); + + test('returns an explicit retryable failure when stale recovery cannot elect', async () => { + const root = temporaryRoot(); + await Effect.runPromise(submitFeedback('baseline', provenance(0), root)); + const quietIo = { error: () => {}, out: () => {} }; + expect( + await runFeedbackCli(['watch', '--once', '--cursor', 'blocked'], quietIo, { root }), + ).toBe(0); + await Effect.runPromise(submitFeedback('unseen while blocked', provenance(1), root)); + const cursorDirectory = join(feedbackRegistryPaths(root).watchCursors, 'blocked'); + const lockPath = join(cursorDirectory, 'scan.lock'); + writeFileSync( + lockPath, + `${JSON.stringify({ createdAt: new Date().toISOString(), pid: 2_147_483_647, token: 'dead' })}\n`, + { mode: 0o600 }, + ); + const lockStats = statSync(lockPath); + writeFileSync( + join( + cursorDirectory, + `recovery-${lockStats.dev}-${lockStats.ino}-choosing-00000000-0000-4000-8000-000000000002.lock`, + ), + 'incomplete', + { mode: 0o600 }, + ); + const errors: string[] = []; + const output: string[] = []; + expect( + await runFeedbackCli( + ['watch', '--once', '--cursor', 'blocked'], + { error: (line) => errors.push(line), out: (line) => output.push(line) }, + { root }, + ), + ).toBe(1); + expect(errors.join('\n')).toContain('recovery remains contended; retry'); + expect(output).toEqual([]); + }); + test('fences stale-lock replacement under high-contention separate-process watchers', async () => { const root = temporaryRoot(); await Effect.runPromise(submitFeedback('baseline', provenance(0), root)); diff --git a/plugins/pardes-pi/extensions/pardes/feedback/store.ts b/plugins/pardes-pi/extensions/pardes/feedback/store.ts index 5bdf129..5c4373b 100644 --- a/plugins/pardes-pi/extensions/pardes/feedback/store.ts +++ b/plugins/pardes-pi/extensions/pardes/feedback/store.ts @@ -360,6 +360,160 @@ async function releaseWatchLock( await syncDirectory(cursorDirectory); } +interface RecoveryElectionRecord { + readonly createdAt: string; + readonly pid: number; + readonly ticket?: number; + readonly token: string; +} + +function recoveryElectionRecord(input: unknown): RecoveryElectionRecord | undefined { + if (typeof input !== 'object' || input === null) return; + const record = input as Partial; + if ( + typeof record.createdAt !== 'string' || + typeof record.pid !== 'number' || + !Number.isInteger(record.pid) || + typeof record.token !== 'string' || + (record.ticket !== undefined && (!Number.isSafeInteger(record.ticket) || record.ticket < 1)) + ) + return; + return { + createdAt: record.createdAt, + pid: record.pid, + ...(record.ticket === undefined ? {} : { ticket: record.ticket }), + token: record.token, + }; +} + +async function writeEphemeralRecord(path: string, value: unknown): Promise { + const handle = await open(path, 'wx', 0o600); + try { + await handle.writeFile(`${JSON.stringify(value)}\n`, 'utf8'); + await handle.sync(); + } finally { + await handle.close(); + } +} + +async function liveRecoveryRecords( + cursorDirectory: string, + prefix: string, + kind: 'choosing' | 'ticket', +): Promise { + const records: RecoveryElectionRecord[] = []; + for (const entry of await readdir(cursorDirectory, { withFileTypes: true })) { + if (!entry.name.startsWith(`${prefix}-${kind}-`) || !entry.name.endsWith('.lock')) continue; + if (!entry.isFile() || entry.isSymbolicLink()) + throw new Error('feedback recovery election is redirected'); + const path = join(cursorDirectory, entry.name); + const stats = await optionalStats(path); + if (!stats) continue; + let record: RecoveryElectionRecord | undefined; + try { + if (stats.size <= 16 * 1_024) + record = recoveryElectionRecord(JSON.parse(await readFile(path, 'utf8')) as unknown); + } catch { + record = undefined; + } + const young = Date.now() - stats.mtimeMs <= WATCH_LOCK_RECOVERY_GRACE_MS; + if ((!record && !young) || (record && !processIsAlive(record.pid))) { + await rm(path, { force: true }); + continue; + } + if (!record) return undefined; + records.push(record); + } + return records; +} + +async function acquireRecoveryElection( + cursorDirectory: string, + observedStats: { readonly dev: number; readonly ino: number }, +): Promise<(() => Promise) | 'blocked' | 'lost'> { + const prefix = `recovery-${observedStats.dev}-${observedStats.ino}`; + const token = randomUUID(); + const choosingPath = join(cursorDirectory, `${prefix}-choosing-${token}.lock`); + const ticketPath = join(cursorDirectory, `${prefix}-ticket-${token}.lock`); + const base = { createdAt: new Date().toISOString(), pid: process.pid, token }; + let elected = false; + try { + await writeEphemeralRecord(choosingPath, base); + const existingTickets = await liveRecoveryRecords(cursorDirectory, prefix, 'ticket'); + if (!existingTickets) return 'blocked'; + const ticket = + existingTickets.reduce((maximum, record) => Math.max(maximum, record.ticket ?? 0), 0) + 1; + await writeEphemeralRecord(ticketPath, { ...base, ticket }); + await rm(choosingPath, { force: true }); + + for (let attempt = 0; attempt < 100; attempt += 1) { + const choosing = await liveRecoveryRecords(cursorDirectory, prefix, 'choosing'); + if (choosing?.length === 0) break; + if (!choosing) return 'blocked'; + await sleep(2); + } + const choosing = await liveRecoveryRecords(cursorDirectory, prefix, 'choosing'); + if (!choosing) return 'blocked'; + if (choosing.length > 0) return 'lost'; + const tickets = await liveRecoveryRecords(cursorDirectory, prefix, 'ticket'); + if (!tickets) return 'blocked'; + const winner = [...tickets] + .filter((record) => record.ticket !== undefined) + .sort((left, right) => + left.ticket === right.ticket + ? left.token < right.token + ? -1 + : 1 + : (left.ticket ?? 0) - (right.ticket ?? 0), + )[0]; + if (!winner || winner.token !== token) return 'lost'; + elected = true; + return async () => { + await rm(ticketPath, { force: true }); + await syncDirectory(cursorDirectory); + }; + } finally { + await rm(choosingPath, { force: true }); + if (!elected) await rm(ticketPath, { force: true }); + } +} + +async function sweepOrphanWatchArtifacts(cursorDirectory: string): Promise { + for (const entry of await readdir(cursorDirectory, { withFileTypes: true })) { + const managed = + /^owner-[a-f0-9-]+\.lock$/.test(entry.name) || + /^observer-\d+-[a-f0-9-]+\.lock$/.test(entry.name) || + /^recovery-\d+-\d+-(?:choosing|ticket)-[a-f0-9-]+\.lock$/.test(entry.name); + if (!managed) continue; + if (!entry.isFile() || entry.isSymbolicLink()) + throw new Error('feedback watch artifact is redirected'); + const path = join(cursorDirectory, entry.name); + const stats = await optionalStats(path); + if (!stats || (entry.name.startsWith('owner-') && stats.nlink > 1)) continue; + const observer = /^observer-(\d+)-/.exec(entry.name); + if (observer) { + const observerPid = Number(observer[1]); + if (Number.isInteger(observerPid) && processIsAlive(observerPid)) continue; + await rm(path, { force: true }); + continue; + } + let owner: { readonly pid: number } | undefined; + try { + if (stats.size <= 16 * 1_024) { + const parsed = JSON.parse(await readFile(path, 'utf8')) as unknown; + const lock = watchLockRecord(parsed); + const election = recoveryElectionRecord(parsed); + owner = lock ?? election; + } + } catch { + owner = undefined; + } + const young = Date.now() - stats.mtimeMs <= WATCH_LOCK_RECOVERY_GRACE_MS; + if ((!owner && !young) || (owner && !processIsAlive(owner.pid))) + await rm(path, { force: true }); + } +} + async function recoverObservedWatchLock( cursorDirectory: string, path: string, @@ -383,7 +537,8 @@ async function recoverObservedWatchLock( observed = undefined; } const young = Date.now() - observedStats.mtimeMs <= WATCH_LOCK_RECOVERY_GRACE_MS; - if ((observed && processIsAlive(observed.pid)) || (!observed && young)) return 'busy'; + if (observed && processIsAlive(observed.pid)) return 'busy'; + if (!observed && young) return 'retry'; for (const entry of await readdir(cursorDirectory, { withFileTypes: true })) { const match = /^observer-(\d+)-[a-f0-9-]+\.lock$/.exec(entry.name); @@ -396,32 +551,29 @@ async function recoverObservedWatchLock( await rm(staleObserverPath, { force: true }); } - let ownerPath: string | undefined; - let ownerStats: Awaited> | undefined; - if (observed?.ownerFile && /^owner-[a-f0-9-]+\.lock$/.test(observed.ownerFile)) { - ownerPath = join(cursorDirectory, observed.ownerFile); - ownerStats = await optionalStats(ownerPath); - if (ownerStats && !sameFile(observedStats, ownerStats)) ownerStats = undefined; - } - const expectedLinks = ownerStats ? 3 : 2; - const freshObservedStats = await optionalStats(observerPath); - if (!freshObservedStats || freshObservedStats.nlink !== expectedLinks) { - await sleep(Math.floor(Math.random() * 5) + 1); - return 'retry'; - } - - const currentStats = await optionalStats(path); - if (!currentStats || !sameFile(observedStats, currentStats)) return 'retry'; + const election = await acquireRecoveryElection(cursorDirectory, observedStats); + if (election === 'lost') return 'busy'; + if (election === 'blocked') return 'retry'; try { - await rm(path); - } catch (error) { - if (!isCode(error, 'ENOENT')) throw error; + const currentStats = await optionalStats(path); + if (!currentStats || !sameFile(observedStats, currentStats)) return 'retry'; + try { + await rm(path); + } catch (error) { + if (!isCode(error, 'ENOENT')) throw error; + return 'retry'; + } + + if (observed?.ownerFile && /^owner-[a-f0-9-]+\.lock$/.test(observed.ownerFile)) { + const ownerPath = join(cursorDirectory, observed.ownerFile); + const ownerStats = await optionalStats(ownerPath); + if (ownerStats && sameFile(observedStats, ownerStats)) await rm(ownerPath, { force: true }); + } + await syncDirectory(cursorDirectory); return 'retry'; + } finally { + await election(); } - - if (ownerPath && ownerStats) await rm(ownerPath, { force: true }); - await syncDirectory(cursorDirectory); - return 'retry'; } finally { await rm(observerPath, { force: true }); } @@ -429,7 +581,8 @@ async function recoverObservedWatchLock( /** * Serialize one cursor scan across processes. Unique owner inodes and temporary - * observer hard links fence stale recovery so it can never unlink a successor. + * observer hard links fence successors; a choosing/ticket election selects one + * deterministic stale-inode recovery winner. */ export function acquireFeedbackWatchLock( cursor: string, @@ -437,6 +590,7 @@ export function acquireFeedbackWatchLock( ): Effect.Effect { return effectPromise('acquire feedback watch lock', async () => { const cursorDirectory = await ensureCursorDirectory(feedbackRegistryPaths(root), cursor); + await sweepOrphanWatchArtifacts(cursorDirectory); const path = join(cursorDirectory, 'scan.lock'); for (let attempt = 0; attempt < 8; attempt += 1) { const token = randomUUID(); @@ -470,7 +624,7 @@ export function acquireFeedbackWatchLock( } if ((await recoverObservedWatchLock(cursorDirectory, path)) === 'busy') return undefined; } - return undefined; + throw new Error('feedback watch recovery remains contended; retry the scan'); }); } From 259c0fd86a43b3bc16b6b1756076d2fb7fa558dd Mon Sep 17 00:00:00 2001 From: Marvin Bitterlich <644950+marvin-bitterlich@users.noreply.github.com> Date: Sat, 11 Jul 2026 19:36:13 +0100 Subject: [PATCH 5/8] fix(pardes-pi): sanitize feedback CLI diagnostics --- .../extensions/pardes/feedback/cli.ts | 17 ++++++++---- .../pardes/feedback/feedback.test.ts | 27 ++++++++++++++++++- 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/plugins/pardes-pi/extensions/pardes/feedback/cli.ts b/plugins/pardes-pi/extensions/pardes/feedback/cli.ts index 52c482b..76f26c1 100644 --- a/plugins/pardes-pi/extensions/pardes/feedback/cli.ts +++ b/plugins/pardes-pi/extensions/pardes/feedback/cli.ts @@ -17,7 +17,6 @@ import { pardesGlobalStateRoot, } from './store.ts'; -const UNSAFE_TERMINAL_CHARACTERS = /[\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu; const ROLES = new Set(['manager', 'writer', 'advisory_verifier']); const CANONICAL_ISO_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/; @@ -87,10 +86,18 @@ function cliErrorMessage(error: unknown): string { } function terminalSafe(value: string): string { - return value.replace( - UNSAFE_TERMINAL_CHARACTERS, - (character) => `\\u${character.codePointAt(0)?.toString(16).padStart(4, '0')}`, - ); + return Array.from(value, (character) => { + const codePoint = character.codePointAt(0) ?? 0; + const unsafe = + codePoint <= 0x1f || + (codePoint >= 0x7f && codePoint <= 0x9f) || + codePoint === 0x61c || + codePoint === 0x200e || + codePoint === 0x200f || + (codePoint >= 0x202a && codePoint <= 0x202e) || + (codePoint >= 0x2066 && codePoint <= 0x2069); + return unsafe ? `\\u${codePoint.toString(16).padStart(4, '0')}` : character; + }).join(''); } export function terminalSafeJson(value: unknown): string { diff --git a/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts b/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts index ec6ff02..2913ab4 100644 --- a/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts +++ b/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts @@ -369,6 +369,31 @@ describe('feedback CLI', () => { ).toBe(1); }); + test('renders filesystem diagnostics as inert single-line terminal text', async () => { + const parent = temporaryRoot(); + const unsafeRoot = join(parent, 'bad-\u001b[31m\nline-\u0007-root'); + writeFileSync(unsafeRoot, 'not a directory'); + const errors: string[] = []; + expect( + await runFeedbackCli( + ['list'], + { error: (line) => errors.push(line), out: () => {} }, + { root: unsafeRoot }, + ), + ).toBe(1); + expect(errors[0]).toContain('ENOTDIR'); + expect(errors[0]).toContain('\\u001b'); + expect(errors[0]).toContain('\\u000a'); + expect(errors[0]).toContain('\\u0007'); + expect( + Array.from(errors[0]).some((character) => { + const codePoint = character.codePointAt(0) ?? 0; + return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f); + }), + ).toBe(false); + expect(errors[0].split('\n')).toHaveLength(1); + }); + test('uses durable atomic watch receipts to survive duplicate scans, concurrent watchers, and restarts', async () => { const root = temporaryRoot(); const old = await Effect.runPromise(submitFeedback('already present', provenance(0), root)); @@ -577,7 +602,7 @@ describe('feedback CLI', () => { watchers.reduce((count, { stdout }) => count + Number(stdout.includes(unseen.id)), 0), ).toBe(1); } - }); + }, 30_000); test('executes through the installed-bin shape and includes feedback runtime files in the package', async () => { const root = temporaryRoot(); From 8167358cd88f7f241ea970a714b9937d57725084 Mon Sep 17 00:00:00 2001 From: Marvin Bitterlich <644950+marvin-bitterlich@users.noreply.github.com> Date: Sat, 11 Jul 2026 20:03:21 +0100 Subject: [PATCH 6/8] test(pardes-pi): bound large verifier fixture runtime --- .../pardes/worker-runtime/child-extension.test.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.test.ts b/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.test.ts index 92f51a0..9cb1ac1 100644 --- a/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.test.ts +++ b/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.test.ts @@ -60,11 +60,15 @@ if (command === 'rev-parse') { } else if (command === 'status' && process.env.PARDES_TEST_GIT_PATHOLOGICAL === 'true') { process.stdout.write('x'.repeat(${16 * 1_024 * 1_024 + 1})); } else if (command === 'status') { + const rows = []; for (let index = 0; index < 7_000; index += 1) - process.stdout.write(\`?? status/\${String(index).padStart(4, '0')}-\${'s'.repeat(170)}\\n\`); + rows.push(\`?? status/\${String(index).padStart(4, '0')}-\${'s'.repeat(170)}\\n\`); + process.stdout.write(rows.join('')); } else if (command === 'diff') { + const rows = []; for (let index = 0; index < 7_000; index += 1) - process.stdout.write(\`src/\${String(index).padStart(4, '0')}-\${'p'.repeat(170)}.ts\\n\`); + rows.push(\`src/\${String(index).padStart(4, '0')}-\${'p'.repeat(170)}.ts\\n\`); + process.stdout.write(rows.join('')); } else { process.stderr.write('unexpected fake Git command'); process.exitCode = 1; @@ -316,6 +320,8 @@ describe('verifier child profile', () => { } }); + // This intentionally transports more than 18 MiB across several child processes, + // including the breaker boundary, so allow for legitimate shared CI runner load. test('streams large status and changed-path output with complete-row omission metadata', async () => { const { root, worktree } = createFixture(); const previous = { @@ -379,7 +385,7 @@ describe('verifier child profile', () => { if (previous.pathological === undefined) delete process.env.PARDES_TEST_GIT_PATHOLOGICAL; else process.env.PARDES_TEST_GIT_PATHOLOGICAL = previous.pathological; } - }); + }, 20_000); test('executes fixed bounded captured-head evidence', async () => { const { worktree } = createFixture(); From 1adbd47924bf75628a633e8398594859ca556993 Mon Sep 17 00:00:00 2001 From: Marvin Bitterlich <644950+marvin-bitterlich@users.noreply.github.com> Date: Sat, 11 Jul 2026 20:14:16 +0100 Subject: [PATCH 7/8] test(pardes-pi): deterministically stream breaker fixture --- .../worker-runtime/child-extension.test.ts | 47 +++++++++++-------- 1 file changed, 27 insertions(+), 20 deletions(-) diff --git a/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.test.ts b/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.test.ts index 9cb1ac1..dca5111 100644 --- a/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.test.ts +++ b/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.test.ts @@ -50,29 +50,36 @@ function createFixture(parent = tmpdir()) { function installLargeOutputGit(root: string): string { const bin = join(root, 'bin'); mkdirSync(bin); + const rows = (prefix: string, body: string, suffix = '') => + Array.from( + { length: 7_000 }, + (_, index) => `${prefix}${String(index).padStart(4, '0')}-${body}${suffix}\n`, + ).join(''); + writeFileSync(join(bin, 'status.out'), rows('?? status/', 's'.repeat(170))); + writeFileSync(join(bin, 'diff.out'), rows('src/', 'p'.repeat(170), '.ts')); + writeFileSync( + join(bin, 'pathological.out'), + Buffer.alloc(GIT_INSPECTION_STDOUT_MAX_BYTES + 1, 'x'), + ); const executable = join(bin, 'git'); writeFileSync( executable, - `#!/usr/bin/env node -const command = process.argv[2]; -if (command === 'rev-parse') { - process.stdout.write('${'c'.repeat(40)}\\n'); -} else if (command === 'status' && process.env.PARDES_TEST_GIT_PATHOLOGICAL === 'true') { - process.stdout.write('x'.repeat(${16 * 1_024 * 1_024 + 1})); -} else if (command === 'status') { - const rows = []; - for (let index = 0; index < 7_000; index += 1) - rows.push(\`?? status/\${String(index).padStart(4, '0')}-\${'s'.repeat(170)}\\n\`); - process.stdout.write(rows.join('')); -} else if (command === 'diff') { - const rows = []; - for (let index = 0; index < 7_000; index += 1) - rows.push(\`src/\${String(index).padStart(4, '0')}-\${'p'.repeat(170)}.ts\\n\`); - process.stdout.write(rows.join('')); -} else { - process.stderr.write('unexpected fake Git command'); - process.exitCode = 1; -} + `#!/bin/sh +set -eu +fixture_dir="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" +command="\${1:-}" +if [ "$command" = "rev-parse" ]; then + printf '%s\\n' '${'c'.repeat(40)}' +elif [ "$command" = "status" ] && [ "\${PARDES_TEST_GIT_PATHOLOGICAL:-}" = "true" ]; then + exec /bin/cat "$fixture_dir/pathological.out" +elif [ "$command" = "status" ]; then + exec /bin/cat "$fixture_dir/status.out" +elif [ "$command" = "diff" ]; then + exec /bin/cat "$fixture_dir/diff.out" +else + printf '%s' 'unexpected fake Git command' >&2 + exit 1 +fi `, ); chmodSync(executable, 0o755); From d37ccec8e5c8cf4e5ef8bd9f6046a95d2734eb79 Mon Sep 17 00:00:00 2001 From: Marvin Bitterlich <644950+marvin-bitterlich@users.noreply.github.com> Date: Sat, 11 Jul 2026 20:53:58 +0100 Subject: [PATCH 8/8] fix(pardes-pi): generalize frustration feedback guidance --- plugins/pardes-pi/README.md | 6 +++--- plugins/pardes-pi/docs/MANAGER.md | 9 ++++----- plugins/pardes-pi/docs/NORTH_STAR.md | 4 ++-- .../extensions/pardes/feedback/feedback.test.ts | 17 +++++++++++------ .../extensions/pardes/feedback/index.ts | 1 + .../extensions/pardes/feedback/tool.ts | 4 +++- .../pardes/manager/guidance/lifecycle.test.ts | 4 ++-- .../pardes/manager/guidance/lifecycle.ts | 3 ++- .../extensions/pardes/tools/feedback.ts | 8 +++----- .../pardes/tools/registration.test.ts | 4 ++++ .../worker-runtime/child-extension.test.ts | 5 +++++ .../pardes/worker-runtime/child-extension.ts | 8 +++----- 12 files changed, 43 insertions(+), 30 deletions(-) diff --git a/plugins/pardes-pi/README.md b/plugins/pardes-pi/README.md index e18def7..36060b4 100644 --- a/plugins/pardes-pi/README.md +++ b/plugins/pardes-pi/README.md @@ -161,9 +161,9 @@ for development or tests with `PARDES_PI_STATE_DIR`. ## Frustration feedback The model-facing `feedback({ text })` tool is available to managers, writing -workers, and advisory verifiers. It is deliberately broad: use it for anything -about Pardes that is frustrating, confusing, broken, annoying, or wasteful, not -only harness bugs. The tool accepts only free-form text. Pardes adds bounded +workers, and advisory verifiers. It is deliberately general: if anything is +frustrating, confusing, broken, annoying, or wasteful, write it here. The tool +accepts only free-form text. Pardes adds bounded provenance (time, id, role and available session/manager/agent/workstream, repository, verifier, and version identities); it never automatically captures logs, files, environment values, or secrets. diff --git a/plugins/pardes-pi/docs/MANAGER.md b/plugins/pardes-pi/docs/MANAGER.md index cf7511b..ee8de41 100644 --- a/plugins/pardes-pi/docs/MANAGER.md +++ b/plugins/pardes-pi/docs/MANAGER.md @@ -14,11 +14,10 @@ action; omit empty categories. Avoid fluff, repeated narration, excessive headings, pseudo-diagrams, gratuitous code fences, and vertical whitespace. Drill down only for a specific decision. -Use `feedback({ text })` whenever anything about Pardes is frustrating, -confusing, broken, annoying, or wasteful; the channel is not limited to harness -bugs. Describe the friction in bounded free-form words. Do not paste logs, file -contents, environment values, or secrets; Pardes adds only bounded explicit -provenance automatically. +Use `feedback({ text })`: if anything is frustrating, confusing, broken, +annoying, or wasteful, write it here. Describe the friction in bounded free-form +words. Do not paste logs, file contents, environment values, or secrets; Pardes +adds only bounded explicit provenance automatically. Use the smallest projection needed: diff --git a/plugins/pardes-pi/docs/NORTH_STAR.md b/plugins/pardes-pi/docs/NORTH_STAR.md index 34b24aa..71618e2 100644 --- a/plugins/pardes-pi/docs/NORTH_STAR.md +++ b/plugins/pardes-pi/docs/NORTH_STAR.md @@ -366,8 +366,8 @@ Merges remain user-controlled. Managers, writing workers, and advisory verifiers have one first-class `feedback({ text })` tool. Its intentionally minimal schema has one required -free-form text field and covers anything frustrating, confusing, broken, -annoying, or wasteful rather than only harness defects. Each submission is a +free-form text field. If anything is frustrating, confusing, broken, annoying, +or wasteful, write it here. Each submission is a separate immutable atomic JSON record in global Pardes state. Pardes adds only bounded explicit provenance and never automatically captures logs, file contents, environment values, or secrets. Registry directories and artifacts diff --git a/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts b/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts index 2913ab4..365fc6a 100644 --- a/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts +++ b/plugins/pardes-pi/extensions/pardes/feedback/feedback.test.ts @@ -28,6 +28,7 @@ import { import { childFeedbackSourceFromEnvironment, executeFeedbackTool, + FEEDBACK_PROMPT_GUIDANCE, FEEDBACK_TOOL_DESCRIPTION, feedbackProvenance, feedbackToolParameters, @@ -255,12 +256,16 @@ describe('feedback provenance and model schema', () => { }; expect(Object.keys(parameters.properties)).toEqual(['text']); expect(parameters.required).toEqual(['text']); - expect(FEEDBACK_TOOL_DESCRIPTION).toContain('frustrating'); - expect(FEEDBACK_TOOL_DESCRIPTION).toContain('confusing'); - expect(FEEDBACK_TOOL_DESCRIPTION).toContain('broken'); - expect(FEEDBACK_TOOL_DESCRIPTION).toContain('annoying'); - expect(FEEDBACK_TOOL_DESCRIPTION).toContain('wasteful'); - expect(FEEDBACK_TOOL_DESCRIPTION).toContain('not limited to harness bugs'); + expect(FEEDBACK_TOOL_DESCRIPTION).toBe( + 'If anything is frustrating, confusing, broken, annoying, or wasteful, write it here.', + ); + expect(FEEDBACK_PROMPT_GUIDANCE).toBe( + `${FEEDBACK_TOOL_DESCRIPTION} Describe it in your own bounded words; do not dump logs, files, environment values, or secrets.`, + ); + for (const qualifier of ['Pardes', 'harness', 'tooling', 'category']) { + expect(FEEDBACK_TOOL_DESCRIPTION.toLowerCase()).not.toContain(qualifier.toLowerCase()); + expect(FEEDBACK_PROMPT_GUIDANCE.toLowerCase()).not.toContain(qualifier.toLowerCase()); + } }); test('attaches only bounded explicit provenance and role-specific child identities', async () => { diff --git a/plugins/pardes-pi/extensions/pardes/feedback/index.ts b/plugins/pardes-pi/extensions/pardes/feedback/index.ts index 1c9f5a1..b89e39f 100644 --- a/plugins/pardes-pi/extensions/pardes/feedback/index.ts +++ b/plugins/pardes-pi/extensions/pardes/feedback/index.ts @@ -42,6 +42,7 @@ export { export { childFeedbackSourceFromEnvironment, executeFeedbackTool, + FEEDBACK_PROMPT_GUIDANCE, FEEDBACK_TOOL_DESCRIPTION, type FeedbackSource, feedbackProvenance, diff --git a/plugins/pardes-pi/extensions/pardes/feedback/tool.ts b/plugins/pardes-pi/extensions/pardes/feedback/tool.ts index fdb6b92..e35da0d 100644 --- a/plugins/pardes-pi/extensions/pardes/feedback/tool.ts +++ b/plugins/pardes-pi/extensions/pardes/feedback/tool.ts @@ -5,7 +5,9 @@ import { type FeedbackProvenance, type FeedbackRole, PARDES_VERSION } from './sc import { submitFeedback } from './store.ts'; export const FEEDBACK_TOOL_DESCRIPTION = - 'Record anything about Pardes that is frustrating, confusing, broken, annoying, or wasteful. Use this broad channel for any friction worth preserving; it is not limited to harness bugs.'; + 'If anything is frustrating, confusing, broken, annoying, or wasteful, write it here.'; + +export const FEEDBACK_PROMPT_GUIDANCE = `${FEEDBACK_TOOL_DESCRIPTION} Describe it in your own bounded words; do not dump logs, files, environment values, or secrets.`; export const feedbackToolParameters = Type.Object( { diff --git a/plugins/pardes-pi/extensions/pardes/manager/guidance/lifecycle.test.ts b/plugins/pardes-pi/extensions/pardes/manager/guidance/lifecycle.test.ts index 0ae47e8..57b7399 100644 --- a/plugins/pardes-pi/extensions/pardes/manager/guidance/lifecycle.test.ts +++ b/plugins/pardes-pi/extensions/pardes/manager/guidance/lifecycle.test.ts @@ -179,7 +179,7 @@ Operating model: - Publication: use \`pull_request_create\` only for exact committed worker state, keep the owner attached for CI or review feedback, and leave merges under user control. - Published review feedback: tell the retained worker to make additive descendant commits only; do not amend, rebase, or rewrite published branch history. Pardes exact-SHA publication intentionally never force-pushes. - Inbox has exactly two paths: Autonomous rows may be acknowledged once handled. When a report, external observation, blocker, or attention needs user judgment, do not acknowledge the active cursor first; surface it. Use \`question\` with choices or \`options: []\` for free-form feedback (4000-char max); it binds the current cursor and consumes only it after a valid non-blank answer. -- Friction: use \`feedback({ text })\` for anything about Pardes that is frustrating, confusing, broken, annoying, or wasteful, not only harness bugs. Describe it in your own bounded words; do not dump logs, files, environment values, or secrets. +- Friction: use \`feedback({ text })\`. If anything is frustrating, confusing, broken, annoying, or wasteful, write it here. Describe it in your own bounded words; do not dump logs, files, environment values, or secrets. - Communication: state facts, decision needed, blockers, and next action. Skip fluff, repeated narration, excess headings, pseudo-diagrams, gratuitous code fences, and vertical whitespace. First pass: - Inspect bounded \`pardes_status\` for current counts and warnings, then inspect \`pardes_status(view="inbox")\` if attention is pending. @@ -194,7 +194,7 @@ Operating model: - Publication: use \`pull_request_create\` only for exact committed worker state, keep the owner attached for CI or review feedback, and leave merges under user control. - Published review feedback: tell the retained worker to make additive descendant commits only; do not amend, rebase, or rewrite published branch history. Pardes exact-SHA publication intentionally never force-pushes. - Inbox has exactly two paths: Autonomous rows may be acknowledged once handled. When a report, external observation, blocker, or attention needs user judgment, do not acknowledge the active cursor first; surface it. Use \`question\` with choices or \`options: []\` for free-form feedback (4000-char max); it binds the current cursor and consumes only it after a valid non-blank answer. -- Friction: use \`feedback({ text })\` for anything about Pardes that is frustrating, confusing, broken, annoying, or wasteful, not only harness bugs. Describe it in your own bounded words; do not dump logs, files, environment values, or secrets. +- Friction: use \`feedback({ text })\`. If anything is frustrating, confusing, broken, annoying, or wasteful, write it here. Describe it in your own bounded words; do not dump logs, files, environment values, or secrets. - Communication: state facts, decision needed, blockers, and next action. Skip fluff, repeated narration, excess headings, pseudo-diagrams, gratuitous code fences, and vertical whitespace. Situational reset: - Persisted manager state and the coordinating suffix are authoritative. Inspect bounded \`pardes_status\`, then \`pardes_status(view="inbox")\`, before deciding what changed. diff --git a/plugins/pardes-pi/extensions/pardes/manager/guidance/lifecycle.ts b/plugins/pardes-pi/extensions/pardes/manager/guidance/lifecycle.ts index 1d94b81..a6705c2 100644 --- a/plugins/pardes-pi/extensions/pardes/manager/guidance/lifecycle.ts +++ b/plugins/pardes-pi/extensions/pardes/manager/guidance/lifecycle.ts @@ -1,3 +1,4 @@ +import { FEEDBACK_PROMPT_GUIDANCE } from '../../feedback/index.ts'; import { currentSnapshotLines, type ManagerGuidanceProjection, @@ -31,7 +32,7 @@ Operating model: - Publication: use \`pull_request_create\` only for exact committed worker state, keep the owner attached for CI or review feedback, and leave merges under user control. - ${PUBLISHED_REVIEW_FEEDBACK_ROUTING_GUIDANCE} - Inbox has exactly two paths: ${INBOX_TWO_PATH_GUIDANCE} -- Friction: use \`feedback({ text })\` for anything about Pardes that is frustrating, confusing, broken, annoying, or wasteful, not only harness bugs. Describe it in your own bounded words; do not dump logs, files, environment values, or secrets. +- Friction: use \`feedback({ text })\`. ${FEEDBACK_PROMPT_GUIDANCE} - Communication: state facts, decision needed, blockers, and next action. Skip fluff, repeated narration, excess headings, pseudo-diagrams, gratuitous code fences, and vertical whitespace. `.trim(); diff --git a/plugins/pardes-pi/extensions/pardes/tools/feedback.ts b/plugins/pardes-pi/extensions/pardes/tools/feedback.ts index ff16d43..4bfd9ba 100644 --- a/plugins/pardes-pi/extensions/pardes/tools/feedback.ts +++ b/plugins/pardes-pi/extensions/pardes/tools/feedback.ts @@ -1,6 +1,7 @@ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'; import { executeFeedbackTool, + FEEDBACK_PROMPT_GUIDANCE, FEEDBACK_TOOL_DESCRIPTION, type FeedbackSource, feedbackToolParameters, @@ -35,10 +36,7 @@ export function registerManagerFeedbackTool( name: 'feedback', parameters: feedbackToolParameters, preview: (args) => [{ mode: 'length', name: 'text', value: args.text }], - promptGuidelines: [ - 'Use feedback to preserve anything about Pardes that is frustrating, confusing, broken, annoying, or wasteful; do not wait for a harness-specific bug or force a category.', - ], - promptSnippet: - 'Record any frustrating, confusing, broken, annoying, or wasteful Pardes experience', + promptGuidelines: [FEEDBACK_PROMPT_GUIDANCE], + promptSnippet: FEEDBACK_TOOL_DESCRIPTION, }); } diff --git a/plugins/pardes-pi/extensions/pardes/tools/registration.test.ts b/plugins/pardes-pi/extensions/pardes/tools/registration.test.ts index b0e145e..5a94fb6 100644 --- a/plugins/pardes-pi/extensions/pardes/tools/registration.test.ts +++ b/plugins/pardes-pi/extensions/pardes/tools/registration.test.ts @@ -2,6 +2,7 @@ import { stripVTControlCharacters } from 'node:util'; import type { ExtensionAPI, Theme, ToolDefinition } from '@earendil-works/pi-coding-agent'; import { visibleWidth } from '@earendil-works/pi-tui'; import { describe, expect, test } from 'vitest'; +import { FEEDBACK_PROMPT_GUIDANCE, FEEDBACK_TOOL_DESCRIPTION } from '../feedback/index.ts'; import type { ManagerController } from '../manager/index.ts'; import { DEFAULT_PARDES_RENDERER_CONFIG, @@ -111,6 +112,9 @@ describe('Pardes interactive tool-call previews', () => { expect(tools.map((tool) => tool.name)).toContain('feedback'); const feedback = requiredValue(tools.find((tool) => tool.name === 'feedback')); expect((feedback.parameters as unknown as { required: string[] }).required).toEqual(['text']); + expect(feedback.description).toBe(FEEDBACK_TOOL_DESCRIPTION); + expect(feedback.promptGuidelines).toEqual([FEEDBACK_PROMPT_GUIDANCE]); + expect(feedback.promptSnippet).toBe(FEEDBACK_TOOL_DESCRIPTION); for (const tool of tools) { expect(tool.executionMode, tool.name).toBe('sequential'); expect(typeof tool.renderCall, tool.name).toBe('function'); diff --git a/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.test.ts b/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.test.ts index dca5111..39cbe12 100644 --- a/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.test.ts +++ b/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.test.ts @@ -6,6 +6,7 @@ import { stripVTControlCharacters } from 'node:util'; import type { ExtensionAPI, Theme, ToolDefinition } from '@earendil-works/pi-coding-agent'; import { visibleWidth } from '@earendil-works/pi-tui'; import { afterEach, describe, expect, test } from 'vitest'; +import { FEEDBACK_PROMPT_GUIDANCE, FEEDBACK_TOOL_DESCRIPTION } from '../feedback/index.ts'; import { REPORT_DETAILS_MAX_CHARS, REPORT_SUMMARY_MAX_CHARS } from '../reporting/index.ts'; import { requiredValue, runGitFixture } from '../test-support.ts'; import pardesWorker, { @@ -260,6 +261,10 @@ describe('verifier child profile', () => { 'ask_manager', ]); expect(tools.map((tool) => tool.name)).not.toContain('verification_diff'); + const feedback = requiredValue(tools.find((tool) => tool.name === 'feedback')); + expect(feedback.description).toBe(FEEDBACK_TOOL_DESCRIPTION); + expect(feedback.promptGuidelines).toEqual([FEEDBACK_PROMPT_GUIDANCE]); + expect(feedback.promptSnippet).toBe(FEEDBACK_TOOL_DESCRIPTION); const evidence = requiredValue(tools.find((tool) => tool.name === 'verification_evidence')); expect(evidence.renderShell).toBe('self'); expect(typeof evidence.renderCall).toBe('function'); diff --git a/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.ts b/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.ts index 625b4ee..3642677 100644 --- a/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.ts +++ b/plugins/pardes-pi/extensions/pardes/worker-runtime/child-extension.ts @@ -9,6 +9,7 @@ import { Type } from 'typebox'; import { childFeedbackSourceFromEnvironment, executeFeedbackTool, + FEEDBACK_PROMPT_GUIDANCE, FEEDBACK_TOOL_DESCRIPTION, feedbackToolParameters, } from '../feedback/index.ts'; @@ -408,11 +409,8 @@ export default function pardesWorker(pi: ExtensionAPI): void { label: 'Record Feedback', name: 'feedback', parameters: feedbackToolParameters, - promptGuidelines: [ - 'Use feedback to preserve anything about Pardes that is frustrating, confusing, broken, annoying, or wasteful; do not wait for a harness-specific bug or force a category.', - ], - promptSnippet: - 'Record any frustrating, confusing, broken, annoying, or wasteful Pardes experience', + promptGuidelines: [FEEDBACK_PROMPT_GUIDANCE], + promptSnippet: FEEDBACK_TOOL_DESCRIPTION, renderCall(args, theme, context) { return renderChildToolCall( theme,