Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion plugins/pardes-pi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,18 @@ interruption, but cannot observe or prove termination of a descendant that creat
lifecycle-unsettled, and restart-interrupted checkout ownership is therefore
retained for later inspection rather than declared safe. Use baseline branch
overrides only intentionally. Worker reports are stored under the owning
manager's `reports/` directory; concise summaries wake the manager.
manager's `reports/` directory; concise summaries wake the manager. Retrieve a
known report with `report_get({ reportId })`: Pardes selects `details` when
present, otherwise `summary`, and automatically delivers the complete canonical
body in bounded ordered settlement runs without field or pagination parameters.
Separate runs permit compaction, retire prior raw parts from later model requests,
and replace persisted report bodies with bounded identity metadata in compaction
preparation without rewriting durable session history. A failed manager compaction
is canceled so delivery can resume; unrelated input cancels rather than interleaves.
`/pardes stop` is also a synchronous cancellation boundary: it retires every
scheduled, in-flight, or compaction-held report identity and invalidates permits
held by asynchronous artifact reads before deactivation. Restart issues a fresh
monotonic delivery epoch, so late pre-stop reads cannot create delivery.

`pull_request_create` publishes a clean committed worker state as a
user-controlled review gate. After the exact pushed SHA is verified as the
Expand Down
15 changes: 13 additions & 2 deletions plugins/pardes-pi/docs/MANAGER.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,19 @@ When independent evidence is needed, call
`verification_request({ sourceAgentId, ... })`. Wait for durable inbox delivery;
do not poll. Inspect bounded `verification_status({ verificationId })` and call
`report_get({ reportId })` only when the result or a concrete decision requires
detail. After fixes, call `verification_refresh({ verificationId })` so the same
retained verifier checks the latest clean HEAD. Verification is advisory and
detail. Call it once with only the report ID: Pardes selects `details` when
present, otherwise `summary`, and delivers the complete canonical body in
bounded ordered settlement runs without pagination calls. Let that automatic
sequence finish before unrelated manager work. Pardes permits compaction between
parts, replaces prior persisted report bodies with bounded metadata only in the
compaction request, and resumes delivery if its manager-owned compactor fails;
durable history remains intact. It fails closed on unrelated interruption, and
`/pardes stop` synchronously cancels every active report identity and invalidates
pre-read lifecycle permits before manager deactivation. Restart advances the
permit epoch, so a late pre-stop artifact read cannot create delivery or block a
fresh retrieval. After fixes, call
`verification_refresh({ verificationId })` so the same retained verifier checks
the latest clean HEAD. Verification is advisory and
separate from publication. Use it before publishing meaningful engineering
slices and when a concrete review question remains. Skip trivial documentation
or test-only maintenance unless risk justifies it. Do not recreate verification
Expand Down
45 changes: 33 additions & 12 deletions plugins/pardes-pi/docs/NORTH_STAR.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,13 @@ engineering judgment:
9. **PRs are review gates.** The system may publish and monitor pull requests.
It never merges autonomously.
10. **Manager context is scarce.** Durable reports stay outside the manager
conversation. Model-facing status, inbox rows, diagnostics, and report
excerpts remain bounded and explicit.
conversation until explicitly retrieved. One retrieval selects the canonical
body and delivers it completely through bounded ordered settlement runs so
compaction can occur between parts; prior raw parts leave subsequent model
request context and become bounded identity-only placeholders in compaction
input while durable session entries remain unchanged. Status, inbox rows,
diagnostics, and each transport part
remain bounded and explicit.
11. **Validation is repository-aware.** Managers follow target-repository
instructions, prefer configured hosted checks when present, and leave merges
to the user.
Expand Down Expand Up @@ -239,8 +244,17 @@ handoff markers. Storage and lifecycle services validate namespace ownership,
repository identity, retained session paths, worktree leases, and detached
review checkouts before trusting restored artifacts.

Long child reports remain outside manager context. Manager-visible retrieval is
opt-in by path-free report ID, trust-labelled, JSON-escaped, and bounded.
Long child reports remain outside manager context until explicitly retrieved.
Manager-visible retrieval is opt-in by path-free report ID, automatically selects
`details` when present and otherwise `summary`, and delivers that canonical body
through trust-labelled, JSON-escaped, bounded ordered settlement runs without
model-managed pagination. A delivery never uses Pi's shared follow-up queue:
unrelated input cancels its exact in-memory identity rather than interleaving, and
reload or shutdown cancels every not-yet-dispatched part. Explicit manager stop
synchronously retires the whole delivery identity—including scheduled, in-flight,
and compaction-held phases—and invalidates permits captured before asynchronous
artifact reads. Restart advances a monotonic epoch, preventing late pre-stop reads
from creating delivery after deactivation or competing with fresh retrieval.

Wake handling has three distinct layers:

Expand Down Expand Up @@ -363,9 +377,11 @@ Pull-request comments, submitted reviews, CI logs, child reports, and advisory
verifier reports are data, not trusted instructions.

Pardes stores durable report artifacts separately, presents bounded summaries,
labels trust boundaries, and requires deliberate routing. `agent_send_report`
hands one bounded provenance-labelled report excerpt to a retained idle agent;
children do not retrieve arbitrary artifacts directly.
and labels trust boundaries. `report_get` deliberately brings one complete
canonical report into manager context through bounded ordered settlement runs
that permit compaction and retire prior raw parts from subsequent model requests.
`agent_send_report` hands one bounded provenance-labelled report excerpt to a
retained idle agent; children do not retrieve arbitrary artifacts directly.

External review feedback remains visible for manager judgment. Pardes does not
execute arbitrary comment bodies or merge because an external system requests
Expand All @@ -374,10 +390,14 @@ it.
## Compaction

Manager compaction reuses Pi compaction with the selected manager model, strips
prior cumulative Pardes and Pi file-operation suffixes, and appends one bounded
deterministic coordination projection. If the custom override cannot complete
safely, it emits a bounded redacted diagnostic and leaves Pi's built-in fallback
in control.
prior cumulative Pardes and Pi file-operation suffixes, replaces persisted
canonical-report bodies in both compaction message arrays with bounded identity
metadata, and appends one bounded deterministic coordination projection. Durable
session history is not rewritten. If the custom override cannot complete safely,
it emits a bounded redacted diagnostic and normally leaves Pi's built-in fallback
in control. During active canonical-report delivery, it instead cancels that
unobservable fallback and explicitly resumes delivery; a later settlement run can
retry compaction without stalling the report sequence.

While manager compaction is unsettled, Pardes holds owned wake injection and
resumes it through generation-checked bounded recovery. Worker automatic
Expand Down Expand Up @@ -429,7 +449,8 @@ The implementation should preserve these mechanically where practical:
- exact-SHA publication fails closed and never force-pushes to conceal an
unexpected remote state;
- no autonomous merge tool exists;
- external feedback and report excerpts are labelled and routed deliberately;
- external feedback, canonical report deliveries, and report handoff excerpts are
labelled and routed deliberately;
- durable reports, watcher metadata, diagnostics, and model-facing projections
remain bounded;
- durable inbox truth is distinct from tokenized presentation cursors;
Expand Down
166 changes: 160 additions & 6 deletions plugins/pardes-pi/extensions/pardes/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,17 @@ import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { ExtensionAPI, ExtensionCommandContext } from '@earendil-works/pi-coding-agent';
import { Effect } from 'effect';
import { afterEach, describe, expect, test } from 'vitest';
import pardesManager, { isNormalUserInputSource } from './index.ts';
import pardesManager, { createPardesCommandHandler, isNormalUserInputSource } from './index.ts';
import type { ManagerController, ManagerState } from './manager/index.ts';
import type { ManagerPresentation } from './presentation/index.ts';
import type { CanonicalReport } from './reporting/index.ts';
import { requiredValue } from './test-support.ts';
import {
ReportDeliveryCoordinator,
type ReportDeliveryScheduler,
} from './tools/report-delivery.ts';

const temporaryDirectories: string[] = [];
const originalStateDir = process.env.PARDES_PI_STATE_DIR;
Expand All @@ -30,17 +38,163 @@ function registeredEvents(factory: (pi: ExtensionAPI) => void): ReadonlyArray<st
return events;
}

const stoppedRun = [{ role: 'assistant', stopReason: 'stop' }] as const;

function commandDeliveryHarness() {
const tasks: Array<{ cancelled: boolean; readonly task: () => void }> = [];
const sent: Array<{ readonly message: unknown; readonly options: unknown }> = [];
const notifications: unknown[] = [];
const scheduler: ReportDeliveryScheduler = {
schedule(_delayMs, task) {
const scheduled = { cancelled: false, task };
tasks.push(scheduled);
return () => {
scheduled.cancelled = true;
};
},
};
const pi = {
sendMessage(message: unknown, options: unknown) {
sent.push({ message, options });
},
} as unknown as ExtensionAPI;
const delivery = new ReportDeliveryCoordinator(pi, scheduler);
const state = {
agents: {},
inbox: [],
managerId: 'manager-fixture',
pullRequests: {},
repo: {
currentCheckout: '/fixture/repository',
gitCommonDir: '/fixture/repository/.git',
key: 'fixture/repository',
primaryCheckout: '/fixture/repository',
},
revision: 0,
schemaVersion: 1,
verifications: {},
workstreamCompletionIntents: {},
workstreams: {},
} as ManagerState;
let active = true;
let deactivatedAfterClear = false;
const manager = {
activate: () =>
Effect.sync(() => {
active = true;
return state;
}),
deactivate: () =>
Effect.sync(() => {
deactivatedAfterClear = !delivery.isActive && delivery.capturePermit() === undefined;
active = false;
}),
runtimeSnapshots: () => new Map(),
snapshot: () => (active ? state : undefined),
} as unknown as ManagerController;
const ctx = {
isIdle: () => true,
ui: { notify: (...args: unknown[]) => notifications.push(args) },
} as unknown as ExtensionCommandContext;
const handler = createPardesCommandHandler(pi, manager, {} as ManagerPresentation, delivery);
const report = (reportId: string): CanonicalReport => ({
agentId: 'agent-fixture',
content: 'x'.repeat(80_000),
field: 'details',
reportId,
status: 'completed',
totalChars: 80_000,
});
const startReport = (reportId: string, toolCallId: string) =>
delivery.start(report(reportId), toolCallId, requiredValue(delivery.capturePermit()));
return {
ctx,
delivery,
handler,
notifications,
report,
sent,
startReport,
tasks,
wasDeactivatedAfterClear: () => deactivatedAfterClear,
};
}

describe('Pardes package extension registration', () => {
test('installs coordinating-manager compaction from the package root extension', () => {
test('installs coordinating-manager compaction plus report-delivery settlement observation', () => {
const events = registeredEvents(pardesManager);

expect(events.filter((event) => event === 'session_before_compact')).toEqual([
'session_before_compact',
]);
expect(events).toContain('session_compact');
expect(events.filter((event) => event === 'session_before_compact')).toHaveLength(2);
expect(events.filter((event) => event === 'session_compact')).toHaveLength(2);
expect(events).toContain('input');
});

test('stops a scheduled report delivery synchronously before manager deactivation', async () => {
const fixture = commandDeliveryHarness();
fixture.startReport('report-scheduled', 'tool-scheduled');
fixture.delivery.observeAgentEnd(stoppedRun, fixture.ctx);
const staleDispatch = requiredValue(fixture.tasks[0]);

await fixture.handler('stop', fixture.ctx);
staleDispatch.task();

expect(fixture.wasDeactivatedAfterClear()).toBe(true);
expect(fixture.delivery.isActive).toBe(false);
expect(fixture.sent).toEqual([]);
expect(fixture.notifications).toContainEqual([
'Pardes manager stopped: manager-fixture',
'info',
]);
});

test('stops an acknowledged in-flight report without scheduling another part', async () => {
const fixture = commandDeliveryHarness();
fixture.startReport('report-in-flight', 'tool-in-flight');
fixture.delivery.observeAgentEnd(stoppedRun, fixture.ctx);
requiredValue(fixture.tasks[0]).task();
const dispatched = requiredValue(fixture.sent[0]);
const delivered = { ...(dispatched.message as object), role: 'custom' as const };
fixture.delivery.observeMessageStart(delivered);
fixture.delivery.observeMessageEnd(delivered);

await fixture.handler('stop', fixture.ctx);
fixture.delivery.observeAgentEnd(stoppedRun, fixture.ctx);

expect(fixture.wasDeactivatedAfterClear()).toBe(true);
expect(fixture.delivery.isActive).toBe(false);
expect(fixture.sent).toHaveLength(1);
expect(fixture.tasks).toHaveLength(1);
});

test('stops a compaction-held delivery and restarts without stale identity or timers', async () => {
const fixture = commandDeliveryHarness();
const old = fixture.startReport('report-old', 'tool-old');
fixture.delivery.observeAgentEnd(stoppedRun, fixture.ctx);
fixture.delivery.observeCompactionStart();
const staleTasks = [...fixture.tasks];

await fixture.handler('stop', fixture.ctx);
await fixture.handler('start', fixture.ctx);
const restarted = fixture.startReport('report-new', 'tool-new');
for (const stale of staleTasks) stale.task();

expect(fixture.delivery.activeReportId).toBe('report-new');
expect(restarted.metadata.deliveryId).not.toBe(old.metadata.deliveryId);
expect(
fixture.sent.filter(
({ message }) =>
(message as { customType?: unknown }).customType === 'pardes-canonical-report-delivery',
),
).toEqual([]);

fixture.delivery.observeAgentEnd(stoppedRun, fixture.ctx);
const currentDispatch = requiredValue(fixture.tasks.findLast((task) => !task.cancelled));
currentDispatch.task();
expect(fixture.sent.at(-1)?.message).toMatchObject({
details: { deliveryId: restarted.metadata.deliveryId, reportId: 'report-new' },
});
});

test('uses the supported input source field only for normal user messages', () => {
expect(isNormalUserInputSource('interactive')).toBe(true);
expect(isNormalUserInputSource('rpc')).toBe(true);
Expand Down
Loading
Loading