diff --git a/plugins/pardes-pi/README.md b/plugins/pardes-pi/README.md index 4a4d125..19a8875 100644 --- a/plugins/pardes-pi/README.md +++ b/plugins/pardes-pi/README.md @@ -142,6 +142,18 @@ 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. +Clean completion audits lead with bounded worker-branch non-merge change +candidates from cooperative first-parent evidence; topology does not prove +authorship or feature semantics. They label merge first-parent diffs separately +as integration context, retain the total branch-point delta, first-parent commit +count, and latest-commit evidence, and do not infer exact conflict-resolution +ownership from parent diffs. The routine-compatible total safety diff is also +subject to explicit Git timeout/output bounds (the provenance defaults, with +independent service overrides); if it cannot complete within them, Pardes +reports the total as unavailable and retains only explicitly known live paths. +Dirty, unsupported, or over-bound histories likewise degrade explicitly instead +of claiming attribution. + `pull_request_create` publishes a clean committed worker state as a user-controlled review gate. After the exact pushed SHA is verified as the hosted head, Pardes makes the retained local worker branch track the managed diff --git a/plugins/pardes-pi/extensions/pardes/git/index.ts b/plugins/pardes-pi/extensions/pardes/git/index.ts index 6beb794..24d47d1 100644 --- a/plugins/pardes-pi/extensions/pardes/git/index.ts +++ b/plugins/pardes-pi/extensions/pardes/git/index.ts @@ -22,6 +22,14 @@ export { RemoteBaselineBranchSchema, type RepoState, RepoStateSchema, + type WorktreeCommitProvenance, + type WorktreeCommitProvenanceBounds, + WorktreeCommitProvenanceBoundsSchema, + WorktreeCommitProvenanceSchema, + type WorktreeCommitProvenanceUnavailableReason, + WorktreeCommitProvenanceUnavailableReasonSchema, + type WorktreeLatestCommitDelta, + WorktreeLatestCommitDeltaSchema, type WorktreeLease, WorktreeLeaseSchema, } from './schemas.ts'; @@ -50,10 +58,6 @@ export { WORKTREE_PROVENANCE_GIT_TIMEOUT_MS, WORKTREE_PROVENANCE_MAX_FIRST_PARENT_COMMITS, WORKTREE_PROVENANCE_MAX_PATHS, - type WorktreeCommitProvenance, - type WorktreeCommitProvenanceBounds, - type WorktreeCommitProvenanceUnavailableReason, type WorktreeInspection, - type WorktreeLatestCommitDelta, type WorktreeServiceError, } from './worktrees.ts'; diff --git a/plugins/pardes-pi/extensions/pardes/git/schemas.ts b/plugins/pardes-pi/extensions/pardes/git/schemas.ts index d43008c..8cf05e7 100644 --- a/plugins/pardes-pi/extensions/pardes/git/schemas.ts +++ b/plugins/pardes-pi/extensions/pardes/git/schemas.ts @@ -31,6 +31,89 @@ export const WorktreeLeaseSchema = Schema.Struct({ }); export type WorktreeLease = typeof WorktreeLeaseSchema.Type; +const FullCommitShaSchema = Schema.String.check(Schema.isPattern(/^[0-9a-f]{40,64}$/)); +const NonNegativeIntegerSchema = Schema.Number.check( + Schema.isInt(), + Schema.isGreaterThanOrEqualTo(0), +); + +export const WorktreeLatestCommitDeltaSchema = Schema.Struct({ + changedPaths: Schema.Array(NonEmptyString), + commitSha: FullCommitShaSchema, + kind: Schema.Literals(['first_parent_non_merge', 'merge_commit']), +}); +export type WorktreeLatestCommitDelta = typeof WorktreeLatestCommitDeltaSchema.Type; + +export const WorktreeCommitProvenanceBoundsSchema = Schema.Struct({ + maxFirstParentCommits: NonNegativeIntegerSchema, + maxPaths: NonNegativeIntegerSchema, +}); +export type WorktreeCommitProvenanceBounds = typeof WorktreeCommitProvenanceBoundsSchema.Type; + +export const WorktreeCommitProvenanceUnavailableReasonSchema = Schema.Literals([ + 'dirty_worktree', + 'worktree_not_registered', + 'branch_mismatch', + 'baseline_not_ancestor', + 'unsupported_graph', + 'bounds_exceeded', + 'total_diff_unavailable', + 'inspection_failed', +]); +export type WorktreeCommitProvenanceUnavailableReason = + typeof WorktreeCommitProvenanceUnavailableReasonSchema.Type; + +/** Bounded cooperative first-parent evidence; merge-parent diffs are context, not authorship proof. */ +export const WorktreeCommitProvenanceSchema = Schema.Union([ + Schema.Struct({ + attribution: Schema.Literal('cooperative_first_parent'), + bounds: WorktreeCommitProvenanceBoundsSchema, + branchPointSha: FullCommitShaSchema, + firstParentNonMergeCommitCount: NonNegativeIntegerSchema, + firstParentNonMergePaths: Schema.Array(NonEmptyString), + headSha: FullCommitShaSchema, + latestDelta: Schema.optionalKey(WorktreeLatestCommitDeltaSchema), + mergeCommitCount: NonNegativeIntegerSchema, + mergePaths: Schema.Array(NonEmptyString), + status: Schema.Literal('available'), + totalBranchCommitCount: NonNegativeIntegerSchema, + totalBranchDeltaPaths: Schema.Array(NonEmptyString), + }), + Schema.Struct({ + bounds: WorktreeCommitProvenanceBoundsSchema, + dirtyPaths: Schema.Array(NonEmptyString), + observedBranch: Schema.optionalKey(NonEmptyString), + reason: WorktreeCommitProvenanceUnavailableReasonSchema, + status: Schema.Literal('unavailable'), + }), +]).check( + Schema.makeFilter((provenance) => { + if (provenance.status === 'unavailable') + return provenance.dirtyPaths.length <= provenance.bounds.maxPaths + ? undefined + : 'dirtyPaths exceeds its declared provenance bound'; + if ( + provenance.firstParentNonMergePaths.length > provenance.bounds.maxPaths || + provenance.mergePaths.length > provenance.bounds.maxPaths || + provenance.totalBranchDeltaPaths.length > provenance.bounds.maxPaths || + (provenance.latestDelta?.changedPaths.length ?? 0) > provenance.bounds.maxPaths + ) + return 'available path evidence exceeds its declared provenance bound'; + if (provenance.totalBranchCommitCount > provenance.bounds.maxFirstParentCommits) + return 'totalBranchCommitCount exceeds its declared provenance bound'; + if ( + provenance.firstParentNonMergeCommitCount + provenance.mergeCommitCount !== + provenance.totalBranchCommitCount + ) + return 'first-parent commit categories do not sum to totalBranchCommitCount'; + return provenance.latestDelta === undefined || + provenance.latestDelta.commitSha === provenance.headSha + ? undefined + : 'latestDelta.commitSha must match headSha'; + }), +); +export type WorktreeCommitProvenance = typeof WorktreeCommitProvenanceSchema.Type; + /** Persisted detached review checkout pinned to one immutable worker head. */ export const DetachedReviewCheckoutLeaseSchema = Schema.Struct({ createdAt: NonEmptyString, diff --git a/plugins/pardes-pi/extensions/pardes/git/worktrees.test.ts b/plugins/pardes-pi/extensions/pardes/git/worktrees.test.ts index 644778e..8860610 100644 --- a/plugins/pardes-pi/extensions/pardes/git/worktrees.test.ts +++ b/plugins/pardes-pi/extensions/pardes/git/worktrees.test.ts @@ -1,4 +1,5 @@ import { + chmodSync, existsSync, mkdirSync, mkdtempSync, @@ -8,7 +9,7 @@ import { writeFileSync, } from 'node:fs'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { delimiter, join } from 'node:path'; import { Effect } from 'effect'; import { afterEach, describe, expect, test } from 'vitest'; import { @@ -39,6 +40,19 @@ function git(cwd: string, ...args: string[]): string { return runGitFixture(cwd, ...args); } +function executableOnPath(name: string): string { + const executable = (process.env.PATH ?? '') + .split(delimiter) + .map((directory) => join(directory, name)) + .find(existsSync); + if (!executable) throw new Error(`Could not resolve ${name} on PATH`); + return realpathSync(executable); +} + +function shellQuote(value: string): string { + return `'${value.replaceAll("'", "'\\''")}'`; +} + const worktreeGit = ( cwd: string, args: ReadonlyArray, @@ -590,7 +604,7 @@ describe('managed worktree service', () => { }); }); - test('refuses stable provenance for dirty worktrees while returning complete dirty paths', async () => { + test('refuses stable provenance for dirty worktrees while retaining total safety-audit paths', async () => { const primary = fixtureRepository(); const repo = await Effect.runPromise(discoverRepository(primary)); const branchPointSha = git(primary, 'rev-parse', 'HEAD'); @@ -608,13 +622,48 @@ describe('managed worktree service', () => { ); expect(inspection).toMatchObject({ - changedPaths: ['dirty.txt'], + changedPaths: ['dirty.txt', 'worker.txt'], dirty: true, provenance: { dirtyPaths: ['dirty.txt'], reason: 'dirty_worktree', status: 'unavailable' }, }); }); - test('returns dirty refusal before committed-range output can exceed the audit circuit breaker', async () => { + test('degrades over-bound dirty provenance without dropping the routine safety-audit path set', async () => { + const primary = fixtureRepository(); + const repo = await Effect.runPromise(discoverRepository(primary)); + const branchPointSha = git(primary, 'rev-parse', 'HEAD'); + const service = makeManagedWorktreeService({ provenanceMaxPaths: 1 }); + const lease = await Effect.runPromise( + service.create({ + agentId: 'agent-dirty-path-bound', + branchPointSha, + managerId: 'manager-1', + repo, + }), + ); + writeFileSync(join(lease.path, 'committed.txt'), 'committed\n'); + git(lease.path, 'add', 'committed.txt'); + git(lease.path, 'commit', '-m', 'committed fixture'); + writeFileSync(join(lease.path, 'dirty-a.txt'), 'dirty a\n'); + writeFileSync(join(lease.path, 'dirty-b.txt'), 'dirty b\n'); + + expect( + await Effect.runPromise( + inspectProvenance(service, owner(repo, 'manager-1', 'agent-dirty-path-bound'), lease), + ), + ).toMatchObject({ + changedPaths: ['committed.txt', 'dirty-a.txt', 'dirty-b.txt'], + dirty: true, + provenance: { + bounds: { maxPaths: 1 }, + dirtyPaths: [], + reason: 'bounds_exceeded', + status: 'unavailable', + }, + }); + }); + + test('degrades honestly when the bounded total safety diff exceeds its output limit', async () => { const primary = fixtureRepository(); const repo = await Effect.runPromise(discoverRepository(primary)); const branchPointSha = git(primary, 'rev-parse', 'HEAD'); @@ -638,7 +687,65 @@ describe('managed worktree service', () => { inspectProvenance(service, owner(repo, 'manager-1', 'agent-dirty-bound'), lease), ), ).toMatchObject({ - provenance: { dirtyPaths: ['dirty.txt'], reason: 'dirty_worktree', status: 'unavailable' }, + changedPaths: ['dirty.txt'], + dirty: true, + provenance: { + dirtyPaths: ['dirty.txt'], + reason: 'total_diff_unavailable', + status: 'unavailable', + }, + }); + }); + + test('degrades deterministically when the bounded total safety diff exceeds its timeout', async () => { + const primary = fixtureRepository(); + const repo = await Effect.runPromise(discoverRepository(primary)); + const branchPointSha = git(primary, 'rev-parse', 'HEAD'); + const service = makeManagedWorktreeService({ provenanceTotalDiffGitTimeoutMs: 100 }); + const lease = await Effect.runPromise( + service.create({ + agentId: 'agent-diff-timeout', + branchPointSha, + managerId: 'manager-1', + repo, + }), + ); + writeFileSync(join(lease.path, 'changed.txt'), 'changed\n'); + git(lease.path, 'add', 'changed.txt'); + git(lease.path, 'commit', '-m', 'timeout fixture'); + + const wrapperRoot = mkdtempSync(join(tmpdir(), 'pardes-slow-git-')); + temporaryDirectories.push(wrapperRoot); + const wrapper = join(wrapperRoot, 'git'); + const marker = join(wrapperRoot, 'diff-started'); + const realGit = executableOnPath('git'); + writeFileSync( + wrapper, + `#!/bin/sh\nif [ "$1" = "diff" ]; then\n : > ${shellQuote(marker)}\n sleep 1\nfi\nexec ${shellQuote(realGit)} "$@"\n`, + ); + chmodSync(wrapper, 0o755); + const originalPath = process.env.PATH; + const inspection = await (async () => { + try { + process.env.PATH = `${wrapperRoot}${delimiter}${originalPath ?? ''}`; + return await Effect.runPromise( + inspectProvenance(service, owner(repo, 'manager-1', 'agent-diff-timeout'), lease), + ); + } finally { + if (originalPath === undefined) delete process.env.PATH; + else process.env.PATH = originalPath; + } + })(); + + expect(existsSync(marker)).toBe(true); + expect(inspection).toMatchObject({ + changedPaths: [], + dirty: false, + provenance: { + dirtyPaths: [], + reason: 'total_diff_unavailable', + status: 'unavailable', + }, }); }); @@ -821,6 +928,7 @@ describe('managed worktree service', () => { inspectProvenance(service, owner(repo, 'manager-1', 'agent-commit-bounds'), lease), ), ).toMatchObject({ + changedPaths: ['first.txt', 'second.txt'], provenance: { bounds: { maxFirstParentCommits: 1 }, dirtyPaths: [], diff --git a/plugins/pardes-pi/extensions/pardes/git/worktrees.ts b/plugins/pardes-pi/extensions/pardes/git/worktrees.ts index dfa7e2b..1ec665c 100644 --- a/plugins/pardes-pi/extensions/pardes/git/worktrees.ts +++ b/plugins/pardes-pi/extensions/pardes/git/worktrees.ts @@ -8,7 +8,14 @@ import { WorktreeError, WorktreeLockError, } from './errors.ts'; -import type { DetachedReviewCheckoutLease, RepoState, WorktreeLease } from './schemas.ts'; +import type { + DetachedReviewCheckoutLease, + RepoState, + WorktreeCommitProvenance, + WorktreeCommitProvenanceBounds, + WorktreeCommitProvenanceUnavailableReason, + WorktreeLease, +} from './schemas.ts'; import { type RunGitOptions, runGit } from './transport.ts'; const MANAGED_EXCLUDE = '/.worktrees/pardes/'; @@ -48,49 +55,6 @@ export const WORKTREE_PROVENANCE_MAX_PATHS = 512; export const WORKTREE_PROVENANCE_GIT_TIMEOUT_MS = 2_000; export const WORKTREE_PROVENANCE_GIT_MAX_BUFFER_BYTES = 256 * 1_024; -export interface WorktreeLatestCommitDelta { - readonly changedPaths: ReadonlyArray; - readonly commitSha: string; - readonly kind: 'first_parent_non_merge' | 'merge_commit'; -} - -export interface WorktreeCommitProvenanceBounds { - readonly maxFirstParentCommits: number; - readonly maxPaths: number; -} - -export type WorktreeCommitProvenanceUnavailableReason = - | 'dirty_worktree' - | 'worktree_not_registered' - | 'branch_mismatch' - | 'baseline_not_ancestor' - | 'unsupported_graph' - | 'bounds_exceeded' - | 'inspection_failed'; - -export type WorktreeCommitProvenance = - | { - readonly status: 'available'; - readonly attribution: 'cooperative_first_parent'; - readonly bounds: WorktreeCommitProvenanceBounds; - readonly branchPointSha: string; - readonly headSha: string; - readonly latestDelta?: WorktreeLatestCommitDelta; - readonly mergeCommitCount: number; - readonly mergePaths: ReadonlyArray; - readonly firstParentNonMergeCommitCount: number; - readonly firstParentNonMergePaths: ReadonlyArray; - readonly totalBranchCommitCount: number; - readonly totalBranchDeltaPaths: ReadonlyArray; - } - | { - readonly status: 'unavailable'; - readonly bounds: WorktreeCommitProvenanceBounds; - readonly dirtyPaths: ReadonlyArray; - readonly observedBranch?: string; - readonly reason: WorktreeCommitProvenanceUnavailableReason; - }; - const WORKTREE_PROVENANCE_BOUNDS: WorktreeCommitProvenanceBounds = { maxFirstParentCommits: WORKTREE_PROVENANCE_MAX_FIRST_PARENT_COMMITS, maxPaths: WORKTREE_PROVENANCE_MAX_PATHS, @@ -201,7 +165,7 @@ export interface ManagedWorktreeShape { lease: WorktreeLease, input: TrackPublishedReviewBranchInput, ) => Effect.Effect; - /** Opt-in richer commit provenance for human/model audit drill-downs, never routine lifecycle checks. */ + /** Bounded richer commit provenance for completion handoffs and explicit audit drill-downs. */ readonly inspectWithProvenance?: ( owner: ManagedLeaseOwner, lease: WorktreeLease, @@ -239,6 +203,9 @@ interface WorktreeServiceOptions { readonly lockRetries?: number; readonly provenanceGitMaxBufferBytes?: number; readonly provenanceGitTimeoutMs?: number; + /** Optional independent bound for the routine-compatible total safety diff. */ + readonly provenanceTotalDiffGitMaxBufferBytes?: number; + readonly provenanceTotalDiffGitTimeoutMs?: number; readonly provenanceMaxFirstParentCommits?: number; readonly provenanceMaxPaths?: number; } @@ -678,6 +645,10 @@ export function makeManagedWorktreeService( maxBuffer: options.provenanceGitMaxBufferBytes ?? WORKTREE_PROVENANCE_GIT_MAX_BUFFER_BYTES, timeoutMs: options.provenanceGitTimeoutMs ?? WORKTREE_PROVENANCE_GIT_TIMEOUT_MS, }; + const totalDiffGitOptions: RunGitOptions = { + maxBuffer: options.provenanceTotalDiffGitMaxBufferBytes ?? provenanceGitOptions.maxBuffer, + timeoutMs: options.provenanceTotalDiffGitTimeoutMs ?? provenanceGitOptions.timeoutMs, + }; const routineLeaseValidationGitOptions: RunGitOptions = { maxBuffer: WORKTREE_PROVENANCE_GIT_MAX_BUFFER_BYTES, timeoutMs: WORKTREE_PROVENANCE_GIT_TIMEOUT_MS, @@ -725,11 +696,6 @@ export function makeManagedWorktreeService( headSha, path: lease.path, }; - if (includeProvenance && dirtyPaths.length > 0) - return { - ...baseInspection, - provenance: provenanceUnavailable('dirty_worktree', dirtyPaths), - }; const range = `${lease.branchPointSha}..${headSha}`; if (!includeProvenance) { const committed = yield* git(lease.path, ['diff', '--name-status', '-z', range]); @@ -749,6 +715,31 @@ export function makeManagedWorktreeService( ...projectionInspection, provenance: provenanceUnavailable(reason, paths, observedBranch), }); + // Preserve the established routine safety-audit path semantics before any + // richer attribution can degrade, but keep this potentially large Git read + // under explicit operational limits. A limit/failure yields known live paths + // only and never presents them as a complete total branch-point delta. + const committed = yield* git( + lease.path, + ['diff', '--name-status', '-z', range], + totalDiffGitOptions, + ).pipe(Effect.exit); + if (Exit.isFailure(committed)) + return unavailable( + 'total_diff_unavailable', + dirtyPaths.length > provenanceBounds.maxPaths ? [] : dirtyPaths, + ); + const totalBranchDeltaPaths = parseCommittedChangedPaths(committed.value.stdout); + projectionInspection = { + ...baseInspection, + changedPaths: [...new Set([...dirtyPaths, ...totalBranchDeltaPaths])].sort(), + }; + if (dirtyPaths.length > 0) + return unavailable( + dirtyPaths.length > provenanceBounds.maxPaths ? 'bounds_exceeded' : 'dirty_worktree', + dirtyPaths.length > provenanceBounds.maxPaths ? [] : dirtyPaths, + ); + if (!(yield* isRegisteredWorktreePath(owner.repo, lease.path, provenanceGitOptions))) return unavailable('worktree_not_registered'); const branchResult = yield* git( @@ -759,6 +750,9 @@ export function makeManagedWorktreeService( if (Exit.isFailure(branchResult)) return unavailable('branch_mismatch'); const observedBranch = branchResult.value.stdout.trim(); if (observedBranch !== lease.branch) return unavailable('branch_mismatch', [], observedBranch); + if (totalBranchDeltaPaths.length > provenanceBounds.maxPaths) + return unavailable('bounds_exceeded'); + const ancestor = yield* git( lease.path, ['merge-base', '--is-ancestor', lease.branchPointSha, headSha], @@ -782,15 +776,6 @@ export function makeManagedWorktreeService( return unavailable('bounds_exceeded'); if (firstParentCommits.some(({ parentCount }) => parentCount < 1 || parentCount > 2)) return unavailable('unsupported_graph'); - const committed = yield* git( - lease.path, - ['diff', '--name-status', '-z', range], - provenanceGitOptions, - ); - const totalBranchDeltaPaths = parseCommittedChangedPaths(committed.stdout); - projectionInspection = { ...baseInspection, changedPaths: totalBranchDeltaPaths }; - if (totalBranchDeltaPaths.length > provenanceBounds.maxPaths) - return unavailable('bounds_exceeded'); const totalBranchCommitCount = firstParentCommits.length; const mergeCommitCount = firstParentCommits.filter( ({ parentCount }) => parentCount === 2, 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 02636fc..38f592f 100644 --- a/plugins/pardes-pi/extensions/pardes/manager/agent-attachment-lifecycle.ts +++ b/plugins/pardes-pi/extensions/pardes/manager/agent-attachment-lifecycle.ts @@ -187,8 +187,12 @@ export function makeAgentAttachmentLifecycleCoordinator( if (!agent.worktree) return undefined; const worktree = agent.worktree; const checkedAt = yield* nowIso; + const inspect = + trigger === 'completion' && worktrees.inspectWithProvenance !== undefined + ? worktrees.inspectWithProvenance + : worktrees.inspect; const result = yield* validateRetainedAgentState(namespace, agent.id, agent).pipe( - Effect.flatMap(() => worktrees.inspect(managedLeaseOwner(namespace, agent.id), worktree)), + Effect.flatMap(() => inspect(managedLeaseOwner(namespace, agent.id), worktree)), Effect.exit, ); return Exit.isSuccess(result) diff --git a/plugins/pardes-pi/extensions/pardes/manager/controller.test.ts b/plugins/pardes-pi/extensions/pardes/manager/controller.test.ts index 70da2a2..284c2f8 100644 --- a/plugins/pardes-pi/extensions/pardes/manager/controller.test.ts +++ b/plugins/pardes-pi/extensions/pardes/manager/controller.test.ts @@ -379,21 +379,29 @@ function toggledInspectionWorktrees() { const service = makeManagedWorktreeService(); let failInspections = false; let inspections = 0; + const inspect = ( + owner: Parameters[0], + lease: Parameters[1], + withProvenance: boolean, + ) => + Effect.sync(() => { + inspections += 1; + if (failInspections) + return Effect.fail( + new WorktreeError({ + cause: 'fixture failure', + operation: 'fixture inspection', + path: lease.path, + }), + ); + return withProvenance && service.inspectWithProvenance + ? service.inspectWithProvenance(owner, lease) + : service.inspect(owner, lease); + }).pipe(Effect.flatten); const worktrees: ManagedWorktreeShape = { ...service, - inspect: (owner, lease) => - Effect.sync(() => { - inspections += 1; - if (failInspections) - return Effect.fail( - new WorktreeError({ - cause: 'fixture failure', - operation: 'fixture inspection', - path: lease.path, - }), - ); - return service.inspect(owner, lease); - }).pipe(Effect.flatten), + inspect: (owner, lease) => inspect(owner, lease, false), + inspectWithProvenance: (owner, lease) => inspect(owner, lease, true), }; return { failInspections: () => { @@ -5880,6 +5888,323 @@ describe('manager controller', () => { expect(fixture.messages).toEqual([]); }); + test('projects merge-heavy completion from the established first-parent evidence without claiming conflict ownership', async () => { + const repo = fixtureRepository(); + const stateRoot = mkdtempSync(join(tmpdir(), 'pardes-state-')); + temporaryDirectories.push(stateRoot); + process.env.PARDES_PI_STATE_DIR = stateRoot; + const fixture = harness(repo); + const workers = stubWorkers(); + const controller = new ManagerController(fixture.pi, { makeWorkers: workers.makeWorkers }); + await Effect.runPromise(controller.activate(fixture.ctx)); + const workstream = await Effect.runPromise( + controller.createWorkstream( + { objective: 'Separate feature work from merge context', title: 'Merge provenance' }, + fixture.ctx, + ), + ); + const agent = await Effect.runPromise( + controller.spawnAgent( + { task: 'Create feature commits around two integrations.', workstreamId: workstream.id }, + fixture.ctx, + ), + ); + const worktreeLease = requiredValue(agent.worktree); + const worktree = worktreeLease.path; + for (const [path, contents, message] of [ + ['feature-a.txt', 'feature a\n', 'feature a'], + ['main-a.txt', 'main a\n', 'main context a'], + ] as const) { + const cwd = path.startsWith('feature') ? worktree : repo; + writeFileSync(join(cwd, path), contents); + git(cwd, 'add', path); + git(cwd, 'commit', '-m', message); + } + git(worktree, 'merge', '--no-edit', 'main'); + writeFileSync(join(worktree, 'feature-b.txt'), 'feature b\n'); + git(worktree, 'add', 'feature-b.txt'); + git(worktree, 'commit', '-m', 'feature b'); + writeFileSync(join(repo, 'main-b.txt'), 'main b\n'); + git(repo, 'add', 'main-b.txt'); + git(repo, 'commit', '-m', 'main context b'); + git(worktree, 'merge', '--no-edit', 'main'); + const headSha = git(worktree, 'rev-parse', 'HEAD'); + expect( + Number(git(worktree, 'rev-list', '--count', `${worktreeLease.branchPointSha}..${headSha}`)), + ).toBe(6); + + await Effect.runPromise( + workers.emit({ + agentId: agent.id, + status: 'completed', + summary: 'Merge-heavy fixture complete.', + type: 'report', + }), + ); + + const persisted = requiredValue(controller.snapshot()?.agents[agent.id]); + expect(persisted.gitAudit).toMatchObject({ + dirty: false, + provenance: { + firstParentNonMergeCommitCount: 2, + firstParentNonMergePaths: ['feature-a.txt', 'feature-b.txt'], + headSha, + latestDelta: { changedPaths: ['main-b.txt'], commitSha: headSha, kind: 'merge_commit' }, + mergeCommitCount: 2, + mergePaths: ['main-a.txt', 'main-b.txt'], + status: 'available', + totalBranchCommitCount: 4, + totalBranchDeltaPaths: ['feature-a.txt', 'feature-b.txt', 'main-a.txt', 'main-b.txt'], + }, + status: 'succeeded', + trigger: 'completion', + }); + expect(persisted.changedPaths).toEqual([ + 'feature-a.txt', + 'feature-b.txt', + 'main-a.txt', + 'main-b.txt', + ]); + const summary = requiredValue(controller.snapshot()?.inbox.at(-1)).summary; + expect(summary).toContain('worker-branch non-merge change candidates: 2 paths/2 commits'); + expect(summary).toContain('Merge context: 2 first-parent-diff paths/2 merge commits'); + expect(summary).toContain('exact conflict-resolution ownership not inferred'); + expect(summary).toContain('Total branch-point delta: 4 paths/4 first-parent commits'); + expect(summary).toContain(`Latest delta: merge_commit ${headSha}; 1 path.`); + expect(summary.length).toBeLessThanOrEqual(900); + }); + + test('degrades over-bound completion provenance while retaining total audited path data', async () => { + const repo = fixtureRepository(); + const stateRoot = mkdtempSync(join(tmpdir(), 'pardes-state-')); + temporaryDirectories.push(stateRoot); + process.env.PARDES_PI_STATE_DIR = stateRoot; + const fixture = harness(repo); + const workers = stubWorkers(); + const controller = new ManagerController(fixture.pi, { + makeWorkers: workers.makeWorkers, + worktrees: makeManagedWorktreeService({ provenanceMaxPaths: 1 }), + }); + await Effect.runPromise(controller.activate(fixture.ctx)); + const workstream = await Effect.runPromise( + controller.createWorkstream( + { objective: 'Degrade bounded provenance explicitly', title: 'Bounded provenance' }, + fixture.ctx, + ), + ); + const agent = await Effect.runPromise( + controller.spawnAgent( + { task: 'Commit two paths beyond the fixture bound.', workstreamId: workstream.id }, + fixture.ctx, + ), + ); + const worktree = requiredValue(agent.worktree).path; + writeFileSync(join(worktree, 'first.txt'), 'first\n'); + writeFileSync(join(worktree, 'second.txt'), 'second\n'); + git(worktree, 'add', 'first.txt', 'second.txt'); + git(worktree, 'commit', '-m', 'over-bound fixture'); + + await Effect.runPromise( + workers.emit({ + agentId: agent.id, + status: 'completed', + summary: `Bounded fixture complete. ${'x'.repeat(2_000)}`, + type: 'report', + }), + ); + + const persisted = requiredValue(controller.snapshot()?.agents[agent.id]); + expect(persisted.changedPaths).toEqual(['first.txt', 'second.txt']); + expect(persisted.gitAudit).toMatchObject({ + provenance: { bounds: { maxPaths: 1 }, reason: 'bounds_exceeded', status: 'unavailable' }, + status: 'succeeded', + trigger: 'completion', + }); + const summary = requiredValue(controller.snapshot()?.inbox.at(-1)).summary; + expect(summary).toContain( + 'worker-branch non-merge change candidates unavailable (bounds_exceeded)', + ); + expect(summary).toContain('Total audited change set: 2 paths'); + expect(summary).toContain('durable report available'); + expect(summary.length).toBeLessThanOrEqual(900); + }); + + test('persists over-bound dirty completion with committed and dirty safety paths intact', async () => { + const repo = fixtureRepository(); + const stateRoot = mkdtempSync(join(tmpdir(), 'pardes-state-')); + temporaryDirectories.push(stateRoot); + process.env.PARDES_PI_STATE_DIR = stateRoot; + const fixture = harness(repo); + const workers = stubWorkers(); + const controller = new ManagerController(fixture.pi, { + makeWorkers: workers.makeWorkers, + worktrees: makeManagedWorktreeService({ provenanceMaxPaths: 1 }), + }); + await Effect.runPromise(controller.activate(fixture.ctx)); + const workstream = await Effect.runPromise( + controller.createWorkstream( + { objective: 'Retain dirty completion safety data', title: 'Dirty bounded provenance' }, + fixture.ctx, + ), + ); + const agent = await Effect.runPromise( + controller.spawnAgent( + { task: 'Commit one path and leave two dirty paths.', workstreamId: workstream.id }, + fixture.ctx, + ), + ); + const worktree = requiredValue(agent.worktree).path; + writeFileSync(join(worktree, 'committed.txt'), 'committed\n'); + git(worktree, 'add', 'committed.txt'); + git(worktree, 'commit', '-m', 'committed fixture'); + writeFileSync(join(worktree, 'dirty-a.txt'), 'dirty a\n'); + writeFileSync(join(worktree, 'dirty-b.txt'), 'dirty b\n'); + + await Effect.runPromise( + workers.emit({ + agentId: agent.id, + status: 'completed', + summary: 'Dirty bounded fixture complete.', + type: 'report', + }), + ); + + const persisted = requiredValue(controller.snapshot()?.agents[agent.id]); + expect(persisted.changedPaths).toEqual(['committed.txt', 'dirty-a.txt', 'dirty-b.txt']); + expect(persisted.latestReport?.status).toBe('completed'); + expect(persisted.gitAudit).toMatchObject({ + dirty: true, + provenance: { + bounds: { maxPaths: 1 }, + dirtyPaths: [], + reason: 'bounds_exceeded', + status: 'unavailable', + }, + status: 'succeeded', + trigger: 'completion', + }); + const attention = requiredValue(controller.snapshot()?.inbox.at(-1)); + expect(attention.type).toBe('agent_report_completed'); + expect(attention.summary).toContain( + 'worker-branch non-merge change candidates unavailable (bounds_exceeded)', + ); + expect(attention.summary).toContain('Total audited change set: 3 paths'); + expect(attention.summary).toContain('Worktree is dirty'); + }); + + test('retains total paths when completion provenance exceeds the first-parent commit bound', async () => { + const repo = fixtureRepository(); + const stateRoot = mkdtempSync(join(tmpdir(), 'pardes-state-')); + temporaryDirectories.push(stateRoot); + process.env.PARDES_PI_STATE_DIR = stateRoot; + const fixture = harness(repo); + const workers = stubWorkers(); + const controller = new ManagerController(fixture.pi, { + makeWorkers: workers.makeWorkers, + worktrees: makeManagedWorktreeService({ provenanceMaxFirstParentCommits: 1 }), + }); + await Effect.runPromise(controller.activate(fixture.ctx)); + const workstream = await Effect.runPromise( + controller.createWorkstream( + { objective: 'Retain total paths after graph bounds', title: 'Commit bounded provenance' }, + fixture.ctx, + ), + ); + const agent = await Effect.runPromise( + controller.spawnAgent( + { task: 'Create two commits beyond the fixture graph bound.', workstreamId: workstream.id }, + fixture.ctx, + ), + ); + const worktree = requiredValue(agent.worktree).path; + for (const path of ['first.txt', 'second.txt']) { + writeFileSync(join(worktree, path), `${path}\n`); + git(worktree, 'add', path); + git(worktree, 'commit', '-m', `${path} fixture`); + } + + await Effect.runPromise( + workers.emit({ + agentId: agent.id, + status: 'completed', + summary: 'Commit-bounded fixture complete.', + type: 'report', + }), + ); + + const persisted = requiredValue(controller.snapshot()?.agents[agent.id]); + expect(persisted.changedPaths).toEqual(['first.txt', 'second.txt']); + expect(persisted.gitAudit).toMatchObject({ + provenance: { + bounds: { maxFirstParentCommits: 1 }, + reason: 'bounds_exceeded', + status: 'unavailable', + }, + status: 'succeeded', + trigger: 'completion', + }); + expect(requiredValue(controller.snapshot()?.inbox.at(-1)).summary).toContain( + 'Total audited change set: 2 paths', + ); + }); + + test('persists an honest incomplete completion audit when the bounded total diff exceeds its buffer', async () => { + const repo = fixtureRepository(); + const stateRoot = mkdtempSync(join(tmpdir(), 'pardes-state-')); + temporaryDirectories.push(stateRoot); + process.env.PARDES_PI_STATE_DIR = stateRoot; + const fixture = harness(repo); + const workers = stubWorkers(); + const controller = new ManagerController(fixture.pi, { + makeWorkers: workers.makeWorkers, + worktrees: makeManagedWorktreeService({ provenanceTotalDiffGitMaxBufferBytes: 65 }), + }); + await Effect.runPromise(controller.activate(fixture.ctx)); + const workstream = await Effect.runPromise( + controller.createWorkstream( + { objective: 'Bound total completion diff', title: 'Total diff buffer' }, + fixture.ctx, + ), + ); + const agent = await Effect.runPromise( + controller.spawnAgent( + { task: 'Exceed the total diff output bound.', workstreamId: workstream.id }, + fixture.ctx, + ), + ); + const worktree = requiredValue(agent.worktree).path; + const committedPath = `${'long-committed-path-'.repeat(8)}.txt`; + writeFileSync(join(worktree, committedPath), 'committed\n'); + git(worktree, 'add', committedPath); + git(worktree, 'commit', '-m', 'long committed fixture'); + writeFileSync(join(worktree, 'dirty.txt'), 'dirty\n'); + + await Effect.runPromise( + workers.emit({ + agentId: agent.id, + status: 'completed', + summary: 'Bounded total diff fixture complete.', + type: 'report', + }), + ); + + const persisted = requiredValue(controller.snapshot()?.agents[agent.id]); + expect(persisted.changedPaths).toEqual(['dirty.txt']); + expect(persisted.latestReport?.status).toBe('completed'); + expect(persisted.gitAudit).toMatchObject({ + dirty: true, + provenance: { reason: 'total_diff_unavailable', status: 'unavailable' }, + status: 'succeeded', + trigger: 'completion', + }); + const attention = requiredValue(controller.snapshot()?.inbox.at(-1)); + expect(attention.type).toBe('agent_report_completed'); + expect(attention.summary).toContain('bounded total diff failed'); + expect(attention.summary).toContain('Total audited change set unavailable'); + expect(attention.summary).toContain('1 known live path'); + expect(attention.summary).not.toContain('Total audited change set: 1 path'); + }); + test('persists a completion audit failure, clears stale paths, and combines bounded report fallback warnings', async () => { const repo = fixtureRepository(); const stateRoot = mkdtempSync(join(tmpdir(), 'pardes-state-')); @@ -6357,6 +6682,8 @@ describe('manager controller', () => { join(requiredValue(agent.worktree).path, 'discovered-change.txt'), 'discovered change fixture\n', ); + git(requiredValue(agent.worktree).path, 'add', 'discovered-change.txt'); + git(requiredValue(agent.worktree).path, 'commit', '-m', 'discovered completion fixture'); const fullReportSummary = `Fixture implementation complete. ${'detail '.repeat(60)}durable-summary-tail`; const durableReportDetails = `Durable fixture details. ${'d'.repeat(2 * 1_024 * 1_024)} durable-details-tail`; await Effect.runPromise( @@ -6372,7 +6699,12 @@ describe('manager controller', () => { 'Fixture implementation complete.', ); expect(controller.snapshot()?.inbox.at(-1)?.summary).not.toContain('durable-summary-tail'); - expect(controller.snapshot()?.inbox.at(-1)?.summary).toContain('Git audit: 1 changed path.'); + expect(controller.snapshot()?.inbox.at(-1)?.summary).toContain( + 'Git audit — worker-branch non-merge change candidates: 1 path/1 commit.', + ); + expect(controller.snapshot()?.inbox.at(-1)?.summary).toContain( + 'Merge context: 0 first-parent-diff paths/0 merge commits', + ); const durableAttention = controller.snapshot()?.inbox.at(-1); expect(durableAttention).toMatchObject({ agentId: agent.id, @@ -6488,7 +6820,9 @@ describe('manager controller', () => { expect(fixture.messages).toHaveLength(1); expect( readFileSync(join(activationStateDir(fixture.entries), 'events.jsonl'), 'utf8'), - ).toContain('Git audit: 1 changed path.'); + ).toContain( + 'Git audit: worker-branch non-merge change candidates unavailable (provenance not captured). Total audited change set: 1 path.', + ); await Effect.runPromise( workers.emit({ agentId: revived.id, diff --git a/plugins/pardes-pi/extensions/pardes/manager/domain.ts b/plugins/pardes-pi/extensions/pardes/manager/domain.ts index e2f0ea0..8329e2b 100644 --- a/plugins/pardes-pi/extensions/pardes/manager/domain.ts +++ b/plugins/pardes-pi/extensions/pardes/manager/domain.ts @@ -3,6 +3,7 @@ import { DetachedReviewCheckoutLeaseSchema, type RepoState, RepoStateSchema, + WorktreeCommitProvenanceSchema, WorktreeLeaseSchema, } from '../git/index.ts'; import { @@ -89,6 +90,7 @@ export type AgentGitAuditTrigger = typeof AgentGitAuditTriggerSchema.Type; const AgentGitAuditSucceededSchema = Schema.Struct({ checkedAt: NonEmptyString, dirty: Schema.Boolean, + provenance: Schema.optionalKey(WorktreeCommitProvenanceSchema), status: Schema.Literal('succeeded'), trigger: AgentGitAuditTriggerSchema, }); diff --git a/plugins/pardes-pi/extensions/pardes/manager/worker-events.test.ts b/plugins/pardes-pi/extensions/pardes/manager/worker-events.test.ts index 6db40a2..d192391 100644 --- a/plugins/pardes-pi/extensions/pardes/manager/worker-events.test.ts +++ b/plugins/pardes-pi/extensions/pardes/manager/worker-events.test.ts @@ -8,6 +8,7 @@ import { } from '../worker-runtime/child-profile.ts'; import type { WorkerSupervisorEvent } from '../worker-runtime/index.ts'; import { + AgentGitAuditSchema, type AgentRecord, currentVerificationTerminalReportStatus, MANAGER_EVENT_DETAILS_MAX_CHARS, @@ -131,6 +132,51 @@ function verification( } describe('manager event schema compatibility', () => { + test('decodes historical Git audits and validates additive bounded provenance consistency', () => { + const historical = { + checkedAt: createdAt, + dirty: false, + status: 'succeeded', + trigger: 'completion', + } as const; + const provenance = { + attribution: 'cooperative_first_parent', + bounds: { maxFirstParentCommits: 2, maxPaths: 2 }, + branchPointSha: 'a'.repeat(40), + firstParentNonMergeCommitCount: 1, + firstParentNonMergePaths: ['feature.ts'], + headSha: 'b'.repeat(40), + latestDelta: { + changedPaths: ['main.ts'], + commitSha: 'b'.repeat(40), + kind: 'merge_commit', + }, + mergeCommitCount: 1, + mergePaths: ['main.ts'], + status: 'available', + totalBranchCommitCount: 2, + totalBranchDeltaPaths: ['feature.ts', 'main.ts'], + } as const; + + expect(Schema.decodeUnknownSync(AgentGitAuditSchema)(historical)).toEqual(historical); + expect(Schema.decodeUnknownSync(AgentGitAuditSchema)({ ...historical, provenance })).toEqual({ + ...historical, + provenance, + }); + expect(() => + Schema.decodeUnknownSync(AgentGitAuditSchema)({ + ...historical, + provenance: { ...provenance, totalBranchCommitCount: 1 }, + }), + ).toThrow(); + expect(() => + Schema.decodeUnknownSync(AgentGitAuditSchema)({ + ...historical, + provenance: { ...provenance, bounds: { ...provenance.bounds, maxPaths: 1 } }, + }), + ).toThrow(); + }); + test('decodes historical schema-v1 events without report pointers and additive structured report associations', () => { const historical: ManagerEvent = { createdAt, @@ -254,7 +300,8 @@ describe('manager handoff-audit policy', () => { { audit: undefined, expected: '' }, { audit: successfulHandoffAudit('completion', laterAt, inspection()), - expected: 'Git audit: 0 changed paths.', + expected: + 'Git audit: worker-branch non-merge change candidates unavailable (provenance not captured). Total audited change set: 0 paths.', }, { audit: successfulHandoffAudit( @@ -262,7 +309,8 @@ describe('manager handoff-audit policy', () => { laterAt, inspection({ changedPaths: ['one.ts'] }), ), - expected: 'Git audit: 1 changed path.', + expected: + 'Git audit: worker-branch non-merge change candidates unavailable (provenance not captured). Total audited change set: 1 path.', }, { audit: successfulHandoffAudit( @@ -270,7 +318,44 @@ describe('manager handoff-audit policy', () => { laterAt, inspection({ changedPaths: ['one.ts', 'two.ts'], dirty: true }), ), - expected: 'Git audit: 2 changed paths. Worktree is dirty.', + expected: + 'Git audit: worker-branch non-merge change candidates unavailable (provenance not captured). Total audited change set: 2 paths. Worktree is dirty.', + }, + { + audit: successfulHandoffAudit( + 'completion', + laterAt, + inspection({ + changedPaths: ['committed.ts', 'dirty.ts'], + dirty: true, + provenance: { + bounds: { maxFirstParentCommits: 200, maxPaths: 512 }, + dirtyPaths: ['dirty.ts'], + reason: 'dirty_worktree', + status: 'unavailable', + }, + }), + ), + expected: + 'Git audit: worker-branch non-merge change candidates unavailable (dirty worktree). Total audited change set: 2 paths; 1 dirty path. Merge context and total branch-point delta were not attributed. Worktree is dirty.', + }, + { + audit: successfulHandoffAudit( + 'completion', + laterAt, + inspection({ + changedPaths: ['dirty.ts'], + dirty: true, + provenance: { + bounds: { maxFirstParentCommits: 200, maxPaths: 512 }, + dirtyPaths: ['dirty.ts'], + reason: 'total_diff_unavailable', + status: 'unavailable', + }, + }), + ), + expected: + 'Git audit: worker-branch non-merge change candidates unavailable (bounded total diff failed). Total audited change set unavailable; 1 known live path. Merge context was not attributed. Worktree is dirty.', }, { audit: failedHandoffAudit('completion', laterAt, new Error('inspection unavailable')), @@ -281,6 +366,119 @@ describe('manager handoff-audit policy', () => { for (const { audit, expected } of cases) expect(handoffAuditSuffix(audit)).toBe(expected); }); + test('leads completion wording with feature evidence while separating merge context, total delta, and latest delta', () => { + const baselineSha = 'a'.repeat(40); + const headSha = 'b'.repeat(40); + const noMerge = successfulHandoffAudit( + 'completion', + laterAt, + inspection({ + changedPaths: ['src/feature-a.ts', 'src/feature-b.ts'], + headSha, + provenance: { + attribution: 'cooperative_first_parent', + bounds: { maxFirstParentCommits: 200, maxPaths: 512 }, + branchPointSha: baselineSha, + firstParentNonMergeCommitCount: 2, + firstParentNonMergePaths: ['src/feature-a.ts', 'src/feature-b.ts'], + headSha, + latestDelta: { + changedPaths: ['src/feature-b.ts'], + commitSha: headSha, + kind: 'first_parent_non_merge', + }, + mergeCommitCount: 0, + mergePaths: [], + status: 'available', + totalBranchCommitCount: 2, + totalBranchDeltaPaths: ['src/feature-a.ts', 'src/feature-b.ts'], + }, + }), + ); + const mergeHeavy = successfulHandoffAudit( + 'completion', + laterAt, + inspection({ + changedPaths: ['src/feature.ts', 'src/main-a.ts', 'src/main-b.ts'], + headSha, + provenance: { + attribution: 'cooperative_first_parent', + bounds: { maxFirstParentCommits: 200, maxPaths: 512 }, + branchPointSha: baselineSha, + firstParentNonMergeCommitCount: 1, + firstParentNonMergePaths: ['src/feature.ts'], + headSha, + latestDelta: { + changedPaths: ['src/main-b.ts'], + commitSha: headSha, + kind: 'merge_commit', + }, + mergeCommitCount: 2, + mergePaths: ['src/main-a.ts', 'src/main-b.ts'], + status: 'available', + totalBranchCommitCount: 3, + totalBranchDeltaPaths: ['src/feature.ts', 'src/main-a.ts', 'src/main-b.ts'], + }, + }), + ); + + const noMergeText = handoffAuditSuffix(noMerge); + expect(noMergeText).toMatch( + /^Git audit — worker-branch non-merge change candidates: 2 paths\/2 commits\./, + ); + expect(noMergeText).toContain('Merge context: 0 first-parent-diff paths/0 merge commits'); + expect(noMergeText).toContain( + `Total branch-point delta: 2 paths/2 first-parent commits ${baselineSha}..${headSha}`, + ); + expect(noMergeText).toContain(`Latest delta: first_parent_non_merge ${headSha}; 1 path.`); + + const mergeText = handoffAuditSuffix(mergeHeavy); + expect(mergeText).toMatch( + /^Git audit — worker-branch non-merge change candidates: 1 path\/1 commit\./, + ); + expect(mergeText).toContain('Merge context: 2 first-parent-diff paths/2 merge commits'); + expect(mergeText).toContain('exact conflict-resolution ownership not inferred'); + expect(mergeText).toContain(`Latest delta: merge_commit ${headSha}; 1 path.`); + expect(`${noMergeText} ${mergeText}`).not.toMatch(/worker feature|worker-authored|authored by/); + }); + + test('degrades bounded provenance explicitly and keeps completion attention bounded', () => { + const audit = successfulHandoffAudit( + 'completion', + laterAt, + inspection({ + changedPaths: Array.from({ length: 513 }, (_, index) => `src/path-${index}.ts`), + provenance: { + bounds: { maxFirstParentCommits: 200, maxPaths: 512 }, + dirtyPaths: [], + reason: 'bounds_exceeded', + status: 'unavailable', + }, + }), + ); + const suffix = handoffAuditSuffix(audit); + const projected = workerEventSummary( + { + agentId: 'agent-one', + status: 'completed', + summary: `Completed bounded fixture. ${'x'.repeat(2_000)}`, + type: 'report', + }, + persistedReport, + audit, + ); + + expect(suffix).toBe( + 'Git audit: worker-branch non-merge change candidates unavailable (bounds_exceeded). Total audited change set: 513 paths. Merge context was not attributed.', + ); + expect(projected?.summary).toContain( + 'worker-branch non-merge change candidates unavailable (bounds_exceeded)', + ); + expect(projected?.summary).toContain('Total audited change set: 513 paths'); + expect(projected?.summary.length).toBeLessThanOrEqual(900); + expect(projected?.summary).toContain('durable report available'); + }); + test('renders only failed report-persistence suffixes', () => { expect(reportPersistenceSuffix(undefined)).toBe(''); expect(reportPersistenceSuffix(persistedReport)).toBe(''); @@ -404,7 +602,8 @@ describe('worker-event summary policy', () => { actionable: true, reportPreviewChars: { omittedChars: 0, originalChars: 5, shownChars: 5 }, reportPreviewTruncated: false, - summary: 'agent-one: Done. Git audit: 2 changed paths. Worktree is dirty.', + summary: + 'agent-one: Done. Git audit: worker-branch non-merge change candidates unavailable (provenance not captured). Total audited change set: 2 paths. Worktree is dirty.', type: 'agent_report_completed', }, persistence: persistedReport, diff --git a/plugins/pardes-pi/extensions/pardes/manager/worker-events.ts b/plugins/pardes-pi/extensions/pardes/manager/worker-events.ts index 6d523c3..94e901c 100644 --- a/plugins/pardes-pi/extensions/pardes/manager/worker-events.ts +++ b/plugins/pardes-pi/extensions/pardes/manager/worker-events.ts @@ -165,7 +165,13 @@ export function successfulHandoffAudit( ): HandoffAuditOutcome { return { changedPaths: inspection.changedPaths, - gitAudit: { checkedAt, dirty: inspection.dirty, status: 'succeeded', trigger }, + gitAudit: { + checkedAt, + dirty: inspection.dirty, + ...(inspection.provenance === undefined ? {} : { provenance: inspection.provenance }), + status: 'succeeded', + trigger, + }, status: 'succeeded', }; } @@ -207,11 +213,33 @@ export function applyHandoffAudit( return { ...withoutStalePaths, gitAudit: audit.gitAudit, updatedAt: audit.gitAudit.checkedAt }; } +function counted(value: number, singular: string, plural = `${singular}s`): string { + return `${value} ${value === 1 ? singular : plural}`; +} + export function handoffAuditSuffix(audit: HandoffAuditOutcome | undefined): string { if (!audit) return ''; if (audit.status === 'failed') return `Git audit failed: ${audit.gitAudit.failureSummary}.`; - const count = audit.changedPaths.length; - return `Git audit: ${count} changed path${count === 1 ? '' : 's'}.${audit.gitAudit.dirty ? ' Worktree is dirty.' : ''}`; + const provenance = audit.gitAudit.provenance; + const dirtySuffix = audit.gitAudit.dirty ? ' Worktree is dirty.' : ''; + if (provenance === undefined) + return `Git audit: worker-branch non-merge change candidates unavailable (provenance not captured). Total audited change set: ${counted(audit.changedPaths.length, 'path')}.${dirtySuffix}`; + if (provenance.status === 'unavailable') { + if (provenance.reason === 'total_diff_unavailable') + return `Git audit: worker-branch non-merge change candidates unavailable (bounded total diff failed). Total audited change set unavailable; ${counted(audit.changedPaths.length, 'known live path')}. Merge context was not attributed.${dirtySuffix}`; + if (provenance.reason === 'dirty_worktree') + return `Git audit: worker-branch non-merge change candidates unavailable (dirty worktree). Total audited change set: ${counted(audit.changedPaths.length, 'path')}; ${counted(provenance.dirtyPaths.length, 'dirty path')}. Merge context and total branch-point delta were not attributed.${dirtySuffix}`; + return `Git audit: worker-branch non-merge change candidates unavailable (${provenance.reason}). Total audited change set: ${counted(audit.changedPaths.length, 'path')}. Merge context was not attributed.${dirtySuffix}`; + } + const latest = provenance.latestDelta; + return [ + `Git audit — worker-branch non-merge change candidates: ${counted(provenance.firstParentNonMergePaths.length, 'path')}/${counted(provenance.firstParentNonMergeCommitCount, 'commit')}.`, + `Merge context: ${counted(provenance.mergePaths.length, 'first-parent-diff path')}/${counted(provenance.mergeCommitCount, 'merge commit')}; exact conflict-resolution ownership not inferred.`, + `Total branch-point delta: ${counted(provenance.totalBranchDeltaPaths.length, 'path')}/${counted(provenance.totalBranchCommitCount, 'first-parent commit')} ${provenance.branchPointSha}..${provenance.headSha}.`, + latest === undefined + ? 'Latest delta: none; branch remains at its immutable baseline.' + : `Latest delta: ${latest.kind} ${latest.commitSha}; ${counted(latest.changedPaths.length, 'path')}.`, + ].join(' '); } export function reportPersistenceSuffix( diff --git a/plugins/pardes-pi/extensions/pardes/tools/projections/agents.ts b/plugins/pardes-pi/extensions/pardes/tools/projections/agents.ts index 0024a09..1f5f393 100644 --- a/plugins/pardes-pi/extensions/pardes/tools/projections/agents.ts +++ b/plugins/pardes-pi/extensions/pardes/tools/projections/agents.ts @@ -41,6 +41,12 @@ export function agentWarnings( ) warnings.push('worktree bootstrap failed'); if (agent.gitAudit?.status === 'failed') warnings.push('git audit failed'); + if ( + agent.gitAudit?.status === 'succeeded' && + agent.gitAudit.provenance?.status === 'unavailable' && + agent.gitAudit.provenance.reason === 'total_diff_unavailable' + ) + warnings.push('git total diff unavailable'); if (agent.gitAudit?.status === 'succeeded' && agent.gitAudit.dirty) warnings.push('dirty worktree'); return warnings; @@ -120,6 +126,11 @@ function latestGitAuditLine(agent: AgentRecord): string { if (!audit) return 'latest git audit: none'; if (audit.status === 'failed') return `latest git audit: failed · ${audit.trigger} · ${completeOrOmittedText(audit.failureSummary, 120)}`; + if ( + audit.provenance?.status === 'unavailable' && + audit.provenance.reason === 'total_diff_unavailable' + ) + return `latest git audit: incomplete · ${audit.trigger} · bounded total diff unavailable · ${audit.dirty ? 'dirty worktree' : 'clean worktree'}`; return `latest git audit: succeeded · ${audit.trigger} · ${audit.dirty ? 'dirty worktree' : 'clean worktree'}`; } @@ -155,37 +166,48 @@ function conciseAgentHeader(status: AgentStatus): string { return `Worker ${structuralValue(agent.id)}${title} is ${effectiveStatus}. Workstream ${structuralValue(agent.workstreamId)}.`; } +function auditProvenance(status: AgentStatus) { + if (status.gitProvenance !== undefined) return status.gitProvenance; + const audit = status.agent.gitAudit; + return audit?.status === 'succeeded' ? audit.provenance : undefined; +} + function auditPathProjection(status: AgentStatus): { readonly label: string; readonly paths: ReadonlyArray; } { - const provenance = status.gitProvenance; + const provenance = auditProvenance(status); if (provenance?.status === 'available') return { - label: 'cooperative first-parent non-merge paths', + label: 'worker-branch non-merge candidate paths', paths: provenance.firstParentNonMergePaths, }; if (provenance?.status === 'unavailable' && provenance.reason === 'dirty_worktree') return { label: 'dirty paths', paths: provenance.dirtyPaths }; - return { label: 'changed paths', paths: status.agent.changedPaths ?? [] }; + if (provenance?.status === 'unavailable' && provenance.reason === 'total_diff_unavailable') + return { label: 'known live paths (total diff unavailable)', paths: provenance.dirtyPaths }; + return { label: 'total audited changed paths', paths: status.agent.changedPaths ?? [] }; } function auditProvenanceLines(status: AgentStatus): ReadonlyArray { - const provenance = status.gitProvenance; + const provenance = auditProvenance(status); if (provenance === undefined) - return ['commit provenance: unavailable · reason:not_requested_or_unsupported_adapter']; + return [ + 'worker-branch non-merge candidate provenance: unavailable · reason:not_captured_or_unsupported_adapter', + ]; if (provenance.status === 'unavailable') return [ - `commit provenance: unavailable · reason:${provenance.reason}${provenance.observedBranch === undefined ? '' : ` · observed branch:${structuralValue(provenance.observedBranch)}`} · bounds:first ${provenance.bounds.maxFirstParentCommits} first-parent commits/${provenance.bounds.maxPaths} paths/category`, + `worker-branch non-merge candidate provenance: unavailable · reason:${provenance.reason}${provenance.observedBranch === undefined ? '' : ` · observed branch:${structuralValue(provenance.observedBranch)}`} · bounds:first ${provenance.bounds.maxFirstParentCommits} first-parent commits/${provenance.bounds.maxPaths} paths/category`, + 'merge context: unavailable · exact conflict-resolution ownership is never inferred from parent diffs', ]; const latest = provenance.latestDelta; return [ - `commit provenance: cooperative first-parent graph · non-merge rows are worker-branch candidates; merge rows are integration context only · bounds:first ${provenance.bounds.maxFirstParentCommits} commits/${provenance.bounds.maxPaths} paths/category`, - `commits: first-parent non-merge:${provenance.firstParentNonMergeCommitCount} · merge-context:${provenance.mergeCommitCount} · total branch:${provenance.totalBranchCommitCount}`, + `worker-branch non-merge change candidates: ${plural(provenance.firstParentNonMergeCommitCount, 'commit')} · ${plural(provenance.firstParentNonMergePaths.length, 'path')} · cooperative first-parent evidence`, + `merge context: ${plural(provenance.mergeCommitCount, 'merge commit')} · ${plural(provenance.mergePaths.length, 'first-parent-diff path')} · exact conflict-resolution ownership not inferred`, + `total branch-point delta: ${plural(provenance.totalBranchCommitCount, 'first-parent commit')} · ${plural(provenance.totalBranchDeltaPaths.length, 'path')} · ${structuralValue(provenance.branchPointSha)}..${structuralValue(provenance.headSha)}`, latest === undefined ? 'latest delta: none · branch still at immutable baseline' - : `latest delta: ${latest.kind} commit:${structuralValue(latest.commitSha)} · ${plural(latest.changedPaths.length, 'changed path')}`, - `total branch delta: ${structuralValue(provenance.branchPointSha)}..${structuralValue(provenance.headSha)} · ${plural(provenance.totalBranchDeltaPaths.length, 'changed path')} · ${plural(provenance.mergePaths.length, 'merge-context path')}`, + : `latest delta: ${latest.kind} commit:${structuralValue(latest.commitSha)} · ${plural(latest.changedPaths.length, 'path')}`, ]; } diff --git a/plugins/pardes-pi/extensions/pardes/tools/tools.test.ts b/plugins/pardes-pi/extensions/pardes/tools/tools.test.ts index e251ff2..c6df454 100644 --- a/plugins/pardes-pi/extensions/pardes/tools/tools.test.ts +++ b/plugins/pardes-pi/extensions/pardes/tools/tools.test.ts @@ -1842,7 +1842,7 @@ describe('Pardes model-visible tools', () => { 'latest git audit: succeeded · completion · dirty worktree', ); expect(audit.content[0]?.text).toContain( - 'changed paths: 2 paths · complete first-N rows follow · omitted:see suffix row if present; otherwise 0', + 'total audited changed paths: 2 paths · complete first-N rows follow · omitted:see suffix row if present; otherwise 0', ); expect(audit.content[0]?.text).toContain('↳ extensions/pardes/tools/index.ts'); expect(audit.content[0]?.text).toContain('↳ extensions/pardes/tools/tools.test.ts'); @@ -1929,18 +1929,21 @@ describe('Pardes model-visible tools', () => { const text = result.content[0]?.text ?? ''; expect(text).toContain( - 'commit provenance: cooperative first-parent graph · non-merge rows are worker-branch candidates; merge rows are integration context only · bounds:first 200 commits/512 paths/category', + 'worker-branch non-merge change candidates: 2 commits · 6 paths · cooperative first-parent evidence', ); - expect(text).toContain('commits: first-parent non-merge:2 · merge-context:1 · total branch:3'); - expect(text).toContain(`latest delta: merge_commit commit:${headSha} · 1 changed path`); expect(text).toContain( - `total branch delta: ${baselineSha}..${headSha} · 7 changed paths · 1 merge-context path`, + 'merge context: 1 merge commit · 1 first-parent-diff path · exact conflict-resolution ownership not inferred', ); expect(text).toContain( - 'cooperative first-parent non-merge paths: 6 paths · complete first-N rows follow · omitted:see suffix row if present; otherwise 0', + `total branch-point delta: 3 first-parent commits · 7 paths · ${baselineSha}..${headSha}`, + ); + expect(text).toContain(`latest delta: merge_commit commit:${headSha} · 1 path`); + expect(text).toContain( + 'worker-branch non-merge candidate paths: 6 paths · complete first-N rows follow · omitted:see suffix row if present; otherwise 0', ); for (const path of authoredPaths.slice(0, 3)) expect(text).toContain(`↳ ${path}`); - expect(text).toContain('… +3 more cooperative first-parent non-merge paths omitted'); + expect(text).toContain('… +3 more worker-branch non-merge candidate paths omitted'); + expect(text).not.toMatch(/worker feature|worker-authored|authored by/); expect(text).not.toContain('src/authored-d.ts'); expect(text).not.toContain('src/main-only.ts'); expect(text.length).toBeLessThanOrEqual(CONTROL_PLANE_MAX_TEXT_LENGTH); @@ -1990,7 +1993,7 @@ describe('Pardes model-visible tools', () => { const text = result.content[0]?.text ?? ''; expect(text).toContain( - 'commit provenance: unavailable · reason:dirty_worktree · bounds:first 200 first-parent commits/512 paths/category', + 'worker-branch non-merge candidate provenance: unavailable · reason:dirty_worktree · bounds:first 200 first-parent commits/512 paths/category', ); expect(text).toContain('dirty paths: 5 paths'); for (const path of dirtyPaths.slice(0, 4)) expect(text).toContain(`↳ ${path}`);