From b0a6cecbf8339d12b8f68f315be9a226a84196d5 Mon Sep 17 00:00:00 2001 From: Adrian Webb Date: Fri, 30 Oct 2026 04:03:52 -0400 Subject: [PATCH 1/2] test: reproduce empty continuation after reviewed prefix closes --- .../workdays/selection-preflight.test.ts | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/tests/unit/control-plane/capacity/workdays/selection-preflight.test.ts b/tests/unit/control-plane/capacity/workdays/selection-preflight.test.ts index 7a6d03ca..8d63de76 100644 --- a/tests/unit/control-plane/capacity/workdays/selection-preflight.test.ts +++ b/tests/unit/control-plane/capacity/workdays/selection-preflight.test.ts @@ -284,6 +284,37 @@ describe('public workday selection custody', () => { expect(f.stored()).toEqual(retained); expect(f.store.createCapacityWorkdayRun).not.toHaveBeenCalled(); } }); + it('continues only a failed actor after a completed reviewed prefix closes without rewriting prior work', async () => { + const f = fixture(true), first = f.store.first.getMockImplementation()!; + const parent = { id: 'closed-parent', team_id: 'team', capacity_provider_id: 'provider', status: 'failed', + execution_kind: 'workday', execution_mode: 'simulation', parameters_json: JSON.stringify({ scheduledProjectIds: ['project-sdk'] }) }; + const node = (id: string, kind: string, revision: number) => ({ + ...executionNodeRow({ id, kind, agentClass: 'engineer', digest: 'source', expectedSeconds: 180, nodeRevision: revision, decisionRevision: 1 }), + status: 'stale', workday_id: parent.id, graph_revision: 9, + }); + const rows = [node('completed-actor', 'acting', 6), node('approved-review', 'reviewing', 7), node('failed-writer', 'acting', 6)]; + const history = rows.map((row, index) => ({ id: `attempt-${row.id}`, team_id: 'team', work_day_id: parent.id, + execution_node_id: row.id, execution_node_revision: index === 1 ? 6 : 5, decision_id: 'decision', + status: index === 2 ? 'failed' : 'completed', lease_state: 'released', lease_token: null, + assignment_attempt_json: JSON.stringify({ sourceRef: JSON.parse(row.source_ref_json), authorityRefs: JSON.parse(row.authority_refs_json) }), + assignment_result_json: JSON.stringify({ id: `result-${row.id}`, status: index === 2 ? 'failed' : 'completed', + ...(index === 1 ? { completion: { disposition: 'approved' } } : {}), references: [], verification: [] }) })); + const retained = structuredClone({ parent, rows, history }); + f.store.first.mockImplementation(async (sql, args?: unknown[]) => sql.includes('FROM capacity_workday_runs') && args?.[1] === parent.id ? parent : first(sql)); + f.store.preflightCapacityWorkdayRunRequest.mockResolvedValue({ availableSeconds: 7200, + projects: [{ id: 'project-sdk', agents: [] }], executionNodeDemands: [], appliedPlan: {} }); + f.store.all.mockImplementation(async (sql: string) => sql.includes('capacity_provider_team_memberships') ? [{ capacity_provider_id: 'provider' }] + : sql.includes('FROM capacity_provider_assignments') ? history : sql.includes('FROM execution_nodes node') ? rows + : sql.includes('FROM execution_edges') ? [{ from_node_id: 'completed-actor', to_node_id: 'approved-review' }, + { from_node_id: 'approved-review', to_node_id: 'failed-writer' }] + : sql.includes('SELECT id,slug FROM projects') ? [{ id: 'project-sdk', slug: 'sdk' }] : []); + const receipt = await f.service.preflight('team', parsePublicWorkdayIntent('team', { ...input(), + executionMode: 'simulation', decisionIds: ['decision'], allocation: { planningPercent: 0 }, + continueFromWorkdayId: parent.id }), 'actor'); + expect(receipt.selectedDemands).toEqual([expect.objectContaining({ sourceId: 'failed-writer', mode: 'acting', + actingAuthority: expect.objectContaining({ decisionId: 'decision', executionNodeRevision: 7 }) })]); + expect({ parent, rows, history }).toEqual(retained); expect(f.store.createCapacityWorkdayRun).not.toHaveBeenCalled(); + }); it('freezes the admission time when an explicit start is omitted', () => { vi.useFakeTimers(); try { From 58dc771ffdd5de2addc1a281cc9c55f29389a0c4 Mon Sep 17 00:00:00 2001 From: Adrian Webb Date: Fri, 30 Oct 2026 04:20:32 -0400 Subject: [PATCH 2/2] fix: preview retained acting continuation through canonical graph --- .../scenes/component-boundaries.scene.yaml | 10 +++ guarantees/verifiers/golden.verifiers.yaml | 16 ++++ .../scheduling/workday-preflight-service.ts | 21 +++-- .../scheduling/workday-run-service.ts | 2 +- .../execution/execution-graph-service.ts | 17 +++- .../capacity/workdays/continuation.test.ts | 80 +++++++++++++++++++ .../workdays/selection-preflight.test.ts | 24 ++++++ 7 files changed, 159 insertions(+), 11 deletions(-) diff --git a/guarantees/agent/golden/scenes/component-boundaries.scene.yaml b/guarantees/agent/golden/scenes/component-boundaries.scene.yaml index e9d80a82..09b93bf8 100644 --- a/guarantees/agent/golden/scenes/component-boundaries.scene.yaml +++ b/guarantees/agent/golden/scenes/component-boundaries.scene.yaml @@ -3431,3 +3431,13 @@ workflow: - id: selected-authority-public-start action: { verifier: api.golden.selected-authority-public-start } expect: { status: passed } + + - id: retained-acting-continuation-unit + action: { verifier: api.golden.retained-acting-continuation-unit } + expect: { status: passed } + - id: retained-acting-continuation-production + action: { verifier: api.golden.retained-acting-continuation-production } + expect: { status: passed } + - id: retained-acting-continuation-projection + action: { verifier: api.golden.retained-acting-continuation-projection } + expect: { status: passed } diff --git a/guarantees/verifiers/golden.verifiers.yaml b/guarantees/verifiers/golden.verifiers.yaml index dd746de7..5241354e 100644 --- a/guarantees/verifiers/golden.verifiers.yaml +++ b/guarantees/verifiers/golden.verifiers.yaml @@ -5775,3 +5775,19 @@ verifiers: ownerPackage: "@treeseed/api" testFile: tests/unit/control-plane/capacity/workdays/scheduling/architecture/workday-start-native.test.ts testName: "starts and replays a nonempty selected workday after unrelated graph progress while preserving exact selected authority and receipt bytes" + + api.golden.retained-acting-continuation-unit: + kind: vitestCase + ownerPackage: "@treeseed/api" + testFile: tests/unit/control-plane/capacity/workdays/selection-preflight.test.ts + testName: "continues only a failed actor after a completed reviewed prefix closes without rewriting prior work" + api.golden.retained-acting-continuation-production: + kind: vitestCase + ownerPackage: "@treeseed/api" + testFile: tests/unit/control-plane/capacity/workdays/selection-preflight.test.ts + testName: "preserves production continuation selection without projecting simulation custody" + api.golden.retained-acting-continuation-projection: + kind: vitestCase + ownerPackage: "@treeseed/api" + testFile: tests/unit/control-plane/capacity/workdays/continuation.test.ts + testName: "canonical continuation preview retains the approved corrected prefix and exposes only the failed successor without writing workday graph or result history" diff --git a/src/api/capacity/services/capacity/workdays/scheduling/workday-preflight-service.ts b/src/api/capacity/services/capacity/workdays/scheduling/workday-preflight-service.ts index 6b8b567c..be1215d9 100644 --- a/src/api/capacity/services/capacity/workdays/scheduling/workday-preflight-service.ts +++ b/src/api/capacity/services/capacity/workdays/scheduling/workday-preflight-service.ts @@ -17,6 +17,7 @@ import { CapacityGovernanceError,type CapacityGovernanceDatabase } from '../../. import { canonicalJson,sha256 } from '../../../../security.ts'; import { decodeExecutionNode } from '../../../../../control-plane/repositories/capacity/execution/execution-graph-storage.ts'; import { readTeamWorkdayProfile } from '../../../../../control-plane/repositories/capacity/workdays/profile-service.ts'; +import { previewWorkdayExecutionGraph } from '../../../../../control-plane/repositories/capacity/execution/execution-graph-service.ts'; import { validateWorkdayContinuation } from './workday-continuation.ts'; import { validateDecisionAuthority } from '../../../../../governance/decision-authority.ts'; @@ -145,6 +146,8 @@ export class WorkdayPreflightService { }; const projection=await this.store.preflightCapacityWorkdayRunRequest(teamId,runInput); let nodeRows=Array.isArray(projection.executionNodeDemands)?projection.executionNodeDemands.map(record):[]; + record(runInput.parameters).agentProfilesByProjectId=projection.agentProfilesByProjectId; + record(runInput.parameters).groupIds=projection.groupIds; const selectedDecisions=new Set(intent.decisionIds??[]); const selectedProposals=new Set(intent.proposalIds??[]); if (runInput.executionMode === 'simulation' && (selectedDecisions.size || selectedProposals.size)) { @@ -184,8 +187,16 @@ export class WorkdayPreflightService { (Array.isArray(project.agents)?project.agents.map(record):[]), ])); const planningEnabled=Number(record(runInput.parameters).planningPercent??policy.planningPercent)>0; - const selectedDemands=nodeRows.flatMap((entry)=>{ - const node=decodeExecutionNode(entry) as ExecutionNode; + let demandNodes = nodeRows.map(entry => ({ node: decodeExecutionNode(entry) as ExecutionNode, graphRevision: integer(entry.graph_revision,0) })); + if (runInput.executionMode === 'simulation' && intent.continueFromWorkdayId) { + const graph = await previewWorkdayExecutionGraph(this.store, { id: String(runInput.id), teamId, + executionMode: intent.executionMode ?? 'simulation', parameters: { ...record(runInput.parameters), + appliedPlan: projection.appliedPlan, + scheduledProjectIds: (Array.isArray(projection.projects) ? projection.projects.map(record) : []).map(project => text(project.id)) } }); + demandNodes = graph.nodes.filter(node => node.workdayId === runInput.id && node.status === 'ready') + .map(node => ({ node, graphRevision: graph.revision })); + } + const selectedDemands=demandNodes.flatMap(({node,graphRevision})=>{ const decisionRef=node.authorityRefs?.find((reference)=>reference.model==='decision'); if(selectedProposals.size&&node.sourceRef.model==='proposal'&&!selectedProposals.has(node.sourceRef.id)) return []; if(!node.id||selectedDecisions.size&&(!decisionRef||!selectedDecisions.has(decisionRef.id))) return []; @@ -203,16 +214,12 @@ export class WorkdayPreflightService { return [{id:`execution-node:${node.id}:revision:${node.nodeRevision}`,projectId:node.projectId,sourceType:'execution-node',sourceId:node.id,mode, classSlug:node.agentClass??node.kind,requestedSeconds:integer(node.estimate?.expectedSeconds,1),priority:node.priority??0, ...(decisionRef&&typeof decisionRevision==='number'&&typeof sourceDigest==='string'?{actingAuthority:{ decisionId:decisionRef.id,decisionRevision,executionNodeId:node.id, - executionNodeRevision:node.nodeRevision,graphRevision:integer(entry.graph_revision,0),sourceDigest }}:{})}]; + executionNodeRevision:node.nodeRevision,graphRevision,sourceDigest }}:{})}]; }); const classAccounting=[...new Set(selectedDemands.map((entry)=>entry.classSlug))].sort().map((classSlug)=>({classSlug, allocatedSeconds:selectedDemands.filter((entry)=>entry.classSlug===classSlug).reduce((sum,entry)=>sum+entry.requestedSeconds,0), idleSeconds:0,reservedSeconds:0,activeSeconds:0,releasedSeconds:0,overrunSeconds:0})); const appliedPlan=record(projection.appliedPlan); - // Freeze the existing complete profile authority, including every closeout - // contributor, before creation can observe a changed group or definition. - record(runInput.parameters).agentProfilesByProjectId=projection.agentProfilesByProjectId; - record(runInput.parameters).groupIds=projection.groupIds; const profileGeneration=integer(appliedPlan.policyRevision,1); // The team graph cursor records observation provenance. Other projects may // advance it without changing any selected node or its accepted authority. diff --git a/src/api/capacity/services/capacity/workdays/scheduling/workday-run-service.ts b/src/api/capacity/services/capacity/workdays/scheduling/workday-run-service.ts index d5e392ec..93eb9a6a 100644 --- a/src/api/capacity/services/capacity/workdays/scheduling/workday-run-service.ts +++ b/src/api/capacity/services/capacity/workdays/scheduling/workday-run-service.ts @@ -79,7 +79,7 @@ export class CapacityWorkdayRunService { constructor(private readonly store: WorkdayRunServiceStore) { this.runs = new CapacityWorkdayRunRepository(store); this.writes = new CapacityWorkdayRunWriteRepository(store); } preflight(teamId: string, input: JsonRecord) { - return this.store.preflightCapacityWorkdayRun(compileCapacityWorkdayRunRecord(teamId, { ...input, status: 'running' }, { id: 'preflight' })); + return this.store.preflightCapacityWorkdayRun(compileCapacityWorkdayRunRecord(teamId, { ...input, status: 'running' }, { id: text(input.id, 'preflight') })); } async create(teamId: string, input: JsonRecord): Promise { diff --git a/src/api/control-plane/repositories/capacity/execution/execution-graph-service.ts b/src/api/control-plane/repositories/capacity/execution/execution-graph-service.ts index 7e4abb0f..20708a0e 100644 --- a/src/api/control-plane/repositories/capacity/execution/execution-graph-service.ts +++ b/src/api/control-plane/repositories/capacity/execution/execution-graph-service.ts @@ -3,7 +3,7 @@ export{persistExecutionGraph}; import { applyOperationalState, recoverIncompleteReviewCycles, reviewCycleLimitReached, recoverInterruptedGovernanceReviews, recoverableGovernanceReviewAttemptHistory, stable, digest, record, text, type TeamGraph } from './execution-graph-state.ts'; import { graphRevisionSchema, validateAgentDefinitionModel, - type AgentDefinition, type ExecutionEdge, type ExecutionNode, type GraphRevision } from '@treeseed/sdk/agent-capacity'; + type AgentDefinition, type ExecutionEdge, type ExecutionNode, type GraphRevision, type CapacityWorkdayRunRecord } from '@treeseed/sdk/agent-capacity'; import { projectTeamExecutionGraph } from '../../../../capacity/policy/execution/execution-graph-projector.ts'; import { projectActiveWorkdays } from '../../../../capacity/policy/execution/workday-execution-projector.ts'; import { projectCommunicationInvocations, type CommunicationProjectionSource } from '../../../../capacity/policy/execution/communication-execution-projector.ts'; @@ -203,11 +203,12 @@ function visibleGraph(graph: TeamGraph, query: Row): TeamGraph { return { ...graph, nodes, edges: graph.edges.filter((edge) => ids.has(edge.fromNodeId) && ids.has(edge.toNodeId)) }; } -async function reconcileExecutionGraphOnce(store: any, teamId: string, body: Row = {}, scope: 'team' | 'communication' = 'team') { +async function reconcileExecutionGraphOnce(store: any, teamId: string, body: Row = {}, scope: 'team' | 'communication' = 'team', + prospective?: Pick) { const current = await loadGraphSource('projection', () => readGraph(store, teamId)); const frozenInvalid = new Set(); const assignmentScope = scope === 'communication' ? " AND execution_kind='conversation'" : ''; - const [sources, profiles, workdays, communications, activeAssignmentRows, terminalAssignmentRows, reviewCycleRows] = await Promise.all([ + const [sources, profiles, storedWorkdays, communications, activeAssignmentRows, terminalAssignmentRows, reviewCycleRows] = await Promise.all([ scope === 'communication' ? Promise.resolve([]) : loadGraphSource('governance', () => loadTeamExecutableProposalSources(store, teamId, undefined, (source) => frozenInvalid.add(`${source.id}\u0000${source.digest}`))), loadGraphSource('agent_profiles', () => loadProfiles(store, teamId)), @@ -228,6 +229,7 @@ async function reconcileExecutionGraphOnce(store: any, teamId: string, body: Row AND lifecycle_output_json::jsonb #>> '{activityCompletion,reviewDisposition}'='request-changes' AND execution_node_id IS NOT NULL`, [teamId])), ]); + const workdays = prospective ? [...storedWorkdays, prospective] : storedWorkdays; if (!sources.length && !workdays.length && !communications.length && !current.nodes.length) return body.plan === true ? { teamId, baseRevision: current.revision, desiredRevision: current.revision, desiredDigest: current.digest, changes: { added: [], changed: [], completed: [], blocked: [], stale: [], removedEdges: [], addedEdges: [] } } : current; @@ -371,6 +373,7 @@ async function reconcileExecutionGraphOnce(store: any, teamId: string, body: Row } for (const node of desired.nodes) if (frozenNodeIds.has(node.id) && node.status === 'ready') node.status = 'blocked'; if (frozenNodeIds.size) desired.digest = digest({ teamId, nodes: desired.nodes, edges: desired.edges }); + if (prospective) return desired; // Same projection and lineage rules, without a graph or workday write. const changes = graphChanges(current, desired); if (body.plan === true) return { teamId, baseRevision: current.revision, desiredRevision: desired.revision, desiredDigest: desired.digest, changes }; if (!hasChanges(changes)) return current.revision @@ -399,6 +402,14 @@ async function reconcileGraphScope(store: any, teamId: string, body: Row, scope: throw new CapacityOperationError(409, 'execution_graph_revision_conflict', 'The execution graph changed concurrently; reconcile again.'); } +/** Read-only preview for a validated prospective workday; no caller-supplied graph state. */ +export async function previewWorkdayExecutionGraph(store: any, + run: Pick): Promise { + const graph = await reconcileExecutionGraphOnce(store, run.teamId, {}, 'team', run); + if (!('nodes' in graph)) throw new Error('Prospective workday projection did not return a graph'); + return graph; +} + export async function reconcileExecutionGraph(store: any, teamId: string, body: Row = {}, ..._trace: unknown[]) { return reconcileGraphScope(store, teamId, body, 'team'); } /** Reconcile conversation demand in the same graph without reinterpreting unrelated accepted proposals. */ diff --git a/tests/unit/control-plane/capacity/workdays/continuation.test.ts b/tests/unit/control-plane/capacity/workdays/continuation.test.ts index c4a427ab..9529fb7e 100644 --- a/tests/unit/control-plane/capacity/workdays/continuation.test.ts +++ b/tests/unit/control-plane/capacity/workdays/continuation.test.ts @@ -1,5 +1,12 @@ import { describe, expect, it, vi } from 'vitest'; +const proposalSources = vi.hoisted(() => vi.fn().mockResolvedValue([])); +vi.mock('../../../../../src/api/capacity/services/capacity/execution/executable-proposal-source.ts', async original => ({ + ...await original(), loadTeamExecutableProposalSources: proposalSources, +})); +import { previewWorkdayExecutionGraph, persistExecutionGraph } from '../../../../../src/api/control-plane/repositories/capacity/execution/execution-graph-service.ts'; +import { graphProjection, graphState, graphSource, graphProfiles, graphNode, emptyLivingGraph } from '../execution/graph/architecture/living/living-graph-fixture.ts'; import pg from 'pg'; +import { readFileSync } from 'node:fs'; import { assignmentBelongsToRun, validateWorkdayContinuation, workdayContinuationHistory, workdayLineageSql } from '../../../../../src/api/capacity/services/capacity/workdays/scheduling/workday-continuation.ts'; import { workdayStartDatabase } from './scheduling/architecture/workday-start-fixture.ts'; import { settleCapacityReservationExactlyOnce } from '../../../../../src/api/capacity/services/capacity/accounting/settlement-service.ts'; @@ -14,6 +21,79 @@ const fixture = (rows = [previous]) => ({ all: vi.fn(async () => [{ decision_id: 'decision', assignment_attempt_json: '{}' }]), }); describe('settled workday continuation', () => { + it('canonical continuation preview retains the approved corrected prefix and exposes only the failed successor without writing workday graph or result history', async () => { + const f = await workdayStartDatabase(); + try { + await f.db.exec(readFileSync('drizzle/control-plane/0005_governance_inbox.sql', 'utf8')); + const source = graphSource('project'), profiles = graphProfiles(['project']); + proposalSources.mockResolvedValue([source]); + const projection = graphProjection([source]), current = graphState(projection), at = f.intent.startsAt; + for (const definition of Object.values(profiles)) await f.query(`INSERT INTO project_agent_classes + (id,team_id,project_id,slug,name,handler_refs_json,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?)`, + [definition.id, 'team', 'project', definition.agentClass, definition.name, JSON.stringify({ agents: [definition] }), at, at]); + const parentId = 'reviewed-prefix-parent'; + await f.query(`INSERT INTO capacity_workday_runs (id,team_id,capacity_provider_id,status,execution_kind,execution_mode,trigger_kind,parameters_json,created_at,updated_at) + VALUES (?,'team','provider','failed','workday','simulation','manual',?,?,?)`, [parentId, + JSON.stringify({ scheduledProjectIds: ['project'], decisionIds: [source.decision!.id], planningPercent: 0 }), at, at]); + for (const node of current.nodes) if (node.kind !== 'condition') Object.assign(node, { workdayId: parentId, status: 'stale', nodeRevision: 6 }); + await persistExecutionGraph(f.store, current, emptyLivingGraph(), { ...projection.revision, graphDigest: current.digest }); + const actor = graphNode(current, 'first', 'actor'), reviewer = graphNode(current, 'first', 'reviewer'), writer = graphNode(current, 'next', 'actor'); + const histories = [ + { id: 'original-actor', node: actor, revision: 3, status: 'completed', offset: 5000 }, + { id: 'request-changes', node: reviewer, revision: 3, status: 'completed', offset: 4000, reviewDisposition: 'request-changes' }, + { id: 'corrected-actor', node: actor, revision: 5, status: 'completed', offset: 3000 }, + { id: 'approved-review', node: reviewer, revision: 5, status: 'completed', offset: 2000, reviewDisposition: 'approved' }, + { id: 'failed-writer', node: writer, revision: 5, status: 'failed', offset: 1000 }, + ]; + for (const history of histories) { + const finished = new Date(Date.parse(at) - history.offset).toISOString(); + const frozen = assignmentAttemptSchema.parse({ ...structuredClone(assignment), id: history.id, idempotencyKey: history.id, + teamId: 'team', projectId: 'project', workdayId: parentId, sourceRef: history.node.sourceRef, authorityRefs: history.node.authorityRefs }); + const result = assignmentResultSchema.parse({ schemaVersion: 'treeseed.assignment-result/v1', id: `result-${history.id}`, + assignmentId: history.id, status: history.status, summary: 'Controlled historical input, not a live execution or charge.', + references: [], verification: [], diagnostics: [], usage: { elapsedSeconds: 1 }, completedAt: finished }); + await f.query(`INSERT INTO capacity_provider_assignments (id,membership_id,team_id,project_id,capacity_provider_id,project_agent_class_id,work_day_id, + mode,status,lease_state,attempt_count,decision_id,execution_node_id,execution_node_revision,assignment_attempt_json,assignment_result_json, + lifecycle_output_json,completed_at,failed_at,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, + [history.id, 'membership', 'team', 'project', 'provider', profiles[`project:${history.node.agentClass}`]!.id, parentId, + 'acting', history.status, 'released', 1, source.decision!.id, history.node.id, history.revision, JSON.stringify(frozen), JSON.stringify(result), + JSON.stringify({ activityCompletion: { reviewDisposition: history.reviewDisposition } }), history.status === 'completed' ? finished : null, + history.status === 'failed' ? finished : null, finished, finished]); + } + const preflight = await f.publicService.preflight(f.principal, 'team', { ...f.intent, planningOnly: false, allocation: { planningPercent: 0 } }), + row = (await f.snapshot()).receipts.find(row => row.resource_id === preflight.id)!; + const runInput = JSON.parse(String(row.response_json)).runInput; + const capacity = await f.store.preflightCapacityWorkdayRunRequest('team', runInput); + expect((capacity.appliedPlan as { id: string }).id).toBe(runInput.id); + const run = { id: String(runInput.id), teamId: 'team', executionMode: 'simulation' as const, + parameters: { ...runInput.parameters, appliedPlan: capacity.appliedPlan, scheduledProjectIds: ['project'], + decisionIds: [source.decision!.id], continueFromWorkdayId: parentId, planningPercent: 0 } }; + const before = await f.snapshot(), held = structuredClone({ source, current, run }); + const next = await previewWorkdayExecutionGraph(f.store, run); + expect(next.nodes.filter(node => node.workdayId === run.id && node.status === 'ready').map(node => node.id)).toEqual([writer.id]); + for (const prefix of [actor, reviewer]) expect(next.nodes.find(node => node.id === prefix.id)).toMatchObject({ + status: 'completed', nodeRevision: 5, workdayId: run.id, sourceRef: prefix.sourceRef, authorityRefs: prefix.authorityRefs }); + expect(next.nodes.find(node => node.id === writer.id)).toMatchObject({ status: 'ready', nodeRevision: 7 }); + expect(await Promise.all([previewWorkdayExecutionGraph(f.store, run), previewWorkdayExecutionGraph(f.store, run)])).toEqual([next, next]); + expect(await f.snapshot()).toEqual(before); expect({ source, current, run }).toEqual(held); + await f.query("UPDATE capacity_provider_assignments SET lease_state='leased' WHERE id='failed-writer'"); + const unsettled = await f.snapshot(); + await expect(previewWorkdayExecutionGraph(f.store, run)).rejects.toMatchObject({ code: 'workday_continuation_unsettled' }); + expect(await f.snapshot()).toEqual(unsettled); + await f.query("UPDATE capacity_provider_assignments SET lease_state='released' WHERE id='failed-writer'"); + await f.query(`INSERT INTO inbox_items (id,team_id,project_id,kind,title,markdown,status,author_id,author_label,version, + repository_id,content_path,commit_sha,digest,metadata_json,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, + ['blocking-writer-question', 'team', 'project', 'question', 'Controlled blocker', 'Controlled unresolved input', + 'outstanding', 'operator', 'Operator', 1, source.repository, 'questions/controlled.mdx', source.commit, source.digest, + JSON.stringify({ relatedProposals: [source.frontmatter.id], relatedWorkItems: ['next'] }), at, at]); + const questioned = await f.snapshot(), questions = await f.all('SELECT * FROM inbox_items ORDER BY id'); + const blocked = await previewWorkdayExecutionGraph(f.store, run); + expect(blocked.nodes.find(node => node.id === writer.id)?.status).toBe('blocked'); + expect(blocked.nodes.filter(node => node.workdayId === run.id && node.status === 'ready')).toEqual([]); + expect(await f.snapshot()).toEqual(questioned); expect(await f.all('SELECT * FROM inbox_items ORDER BY id')).toEqual(questions); + + } finally { proposalSources.mockReset().mockResolvedValue([]); await f.close(); } + }); it('preserves canonical omitted node authority without admitting foreign decisions or changed source history', () => { const sourceRef = { store: 'postgresql', model: 'workday', id: 'source-workday' }; const node = executionNodeSchema.parse({ schemaVersion: 'treeseed.execution-node/v1', id: 'planning-node', teamId: 'team', projectId: 'project', diff --git a/tests/unit/control-plane/capacity/workdays/selection-preflight.test.ts b/tests/unit/control-plane/capacity/workdays/selection-preflight.test.ts index 8d63de76..dc5f284d 100644 --- a/tests/unit/control-plane/capacity/workdays/selection-preflight.test.ts +++ b/tests/unit/control-plane/capacity/workdays/selection-preflight.test.ts @@ -2,6 +2,11 @@ import { describe, expect, it, vi } from 'vitest'; import { createHash } from 'node:crypto'; import { stringify } from 'yaml'; const contentRead = vi.hoisted(() => vi.fn()); +const previewGraph = vi.hoisted(() => vi.fn()); +vi.mock('../../../../../src/api/control-plane/repositories/capacity/execution/execution-graph-service.ts', async importOriginal => ({ + ...await importOriginal(), previewWorkdayExecutionGraph: previewGraph, +})); +import { decodeExecutionNode } from '../../../../../src/api/control-plane/repositories/capacity/execution/execution-graph-storage.ts'; vi.mock('../../../../../src/api/knowledge/gateway-treedx-connection.ts', async importOriginal => ({ ...await importOriginal(), resolveKnowledgeGatewayConnection: async () => ({ repositoryId: 'library', client: { readRepositoryFile: contentRead } }), @@ -23,6 +28,7 @@ const executionNodeRow = (value: { id: string; kind: string; agentClass: string; }); function fixture(acceptedDecision = false) { let stored: any; let replay: any; + previewGraph.mockReset().mockResolvedValue({ teamId: 'team', revision: 1, nodes: [], edges: [] }); // Supplied UNIT authority only; native governance is proved separately. const decision = { id: 'decision', team_id: 'team', project_id: 'project-sdk', proposal_id: 'proposal', proposal_version: 1, proposal_content_hash: 'd'.repeat(64), status: 'accepted', superseded_at: null, @@ -300,6 +306,11 @@ describe('public workday selection custody', () => { assignment_result_json: JSON.stringify({ id: `result-${row.id}`, status: index === 2 ? 'failed' : 'completed', ...(index === 1 ? { completion: { disposition: 'approved' } } : {}), references: [], verification: [] }) })); const retained = structuredClone({ parent, rows, history }); + // Supplied UNIT projection output. The native integration must exercise + // the shared canonical projector and exact historical result custody. + previewGraph.mockImplementation(async (_store, run) => ({ teamId: 'team', revision: 10, edges: [], + nodes: rows.map((row, index) => ({ ...decodeExecutionNode(row), workdayId: run.id, + status: index === 2 ? 'ready' : 'completed', nodeRevision: index === 2 ? 7 : index === 1 ? 6 : 5 })) })); f.store.first.mockImplementation(async (sql, args?: unknown[]) => sql.includes('FROM capacity_workday_runs') && args?.[1] === parent.id ? parent : first(sql)); f.store.preflightCapacityWorkdayRunRequest.mockResolvedValue({ availableSeconds: 7200, projects: [{ id: 'project-sdk', agents: [] }], executionNodeDemands: [], appliedPlan: {} }); @@ -314,6 +325,19 @@ describe('public workday selection custody', () => { expect(receipt.selectedDemands).toEqual([expect.objectContaining({ sourceId: 'failed-writer', mode: 'acting', actingAuthority: expect.objectContaining({ decisionId: 'decision', executionNodeRevision: 7 }) })]); expect({ parent, rows, history }).toEqual(retained); expect(f.store.createCapacityWorkdayRun).not.toHaveBeenCalled(); + expect(previewGraph).toHaveBeenCalledWith(f.store, expect.objectContaining({ teamId: 'team', + parameters: expect.objectContaining({ continueFromWorkdayId: parent.id, planningPercent: 0 }) })); + }); + it('preserves production continuation selection without projecting simulation custody', async () => { + const f = fixture(true), first = f.store.first.getMockImplementation()!, all = f.store.all.getMockImplementation()!; + const parent = { id: 'production-parent', team_id: 'team', capacity_provider_id: 'provider', status: 'failed', + execution_kind: 'workday', execution_mode: 'production', parameters_json: JSON.stringify({ scheduledProjectIds: ['project-sdk'] }) }; + f.store.first.mockImplementation(async (sql, args?: unknown[]) => sql.includes('FROM capacity_workday_runs') && args?.[1] === parent.id ? parent : first(sql)); + f.store.all.mockImplementation(async sql => sql.includes('FROM capacity_provider_assignments') ? [{ decision_id: 'decision' }] : all(sql)); + const receipt = await f.service.preflight('team', parsePublicWorkdayIntent('team', { ...input(), + executionMode: 'production', decisionIds: ['decision'], continueFromWorkdayId: parent.id }), 'actor'); + expect(receipt.selectedDemands.map(demand => demand.sourceId)).toEqual(['node-review']); + expect(previewGraph).not.toHaveBeenCalled(); expect(f.store.createCapacityWorkdayRun).not.toHaveBeenCalled(); }); it('freezes the admission time when an explicit start is omitted', () => { vi.useFakeTimers();