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
10 changes: 10 additions & 0 deletions guarantees/agent/golden/scenes/component-boundaries.scene.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
16 changes: 16 additions & 0 deletions guarantees/verifiers/golden.verifiers.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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)) {
Expand Down Expand Up @@ -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 [];
Expand All @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<CapacityWorkdayRunRecord> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<CapacityWorkdayRunRecord, 'id' | 'teamId' | 'parameters' | 'executionMode'>) {
const current = await loadGraphSource('projection', () => readGraph(store, teamId));
const frozenInvalid = new Set<string>();
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)),
Expand All @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<CapacityWorkdayRunRecord, 'id' | 'teamId' | 'parameters' | 'executionMode'>): Promise<TeamGraph> {
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. */
Expand Down
Loading
Loading