From 8a1918bd7963320a75d61f4b1a506898735fbbb3 Mon Sep 17 00:00:00 2001 From: Adrian Webb Date: Fri, 30 Oct 2026 03:39:43 -0400 Subject: [PATCH 1/2] test: reproduce unrelated graph progress invalidating selected workday start --- .../workdays/selection-preflight.test.ts | 22 +++++++++++++++++++ 1 file changed, 22 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 3cc790f14..a3fbfce80 100644 --- a/tests/unit/control-plane/capacity/workdays/selection-preflight.test.ts +++ b/tests/unit/control-plane/capacity/workdays/selection-preflight.test.ts @@ -234,6 +234,28 @@ describe('public workday selection custody', () => { expect(receipt.selectedDemands).toEqual([expect.objectContaining({ sourceId: 'actor', actingAuthority: expect.objectContaining({ executionNodeRevision: 5 }) })]); }); + it('starts an unchanged selected root after unrelated team graph progress without rewriting its preflight', async () => { + const f = fixture(true); + let graphRevision = 4; + const actor = { ...executionNodeRow({ id: 'actor', kind: 'acting', agentClass: 'engineer', + digest: 'source', expectedSeconds: 180, nodeRevision: 4, decisionRevision: 1 }), status: 'stale', workday_id: 'closed-parent' }; + 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 execution_nodes node') + ? [{ ...actor, graph_revision: graphRevision }] : 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 }, + }), 'actor'), retained = structuredClone(f.stored()); + expect(receipt.selectedDemands[0].actingAuthority).toMatchObject({ graphRevision: 5, executionNodeRevision: 5 }); + graphRevision = 9; // Another project's progress changes only the team observation cursor. + await expect(f.service.start('team', { preflightId: receipt.id, preflightDigest: receipt.preflightDigest, + idempotencyKey: 'unrelated-project-progress' }, 'actor')).resolves.toMatchObject({ acceptedExecutionNodeIds: ['actor'] }); + expect(f.stored()).toEqual(retained); + expect(actor).toMatchObject({ status: 'stale', node_revision: 4, workday_id: 'closed-parent' }); + expect(f.store.createCapacityWorkdayRun).toHaveBeenCalledTimes(1); + }); it('freezes the admission time when an explicit start is omitted', () => { vi.useFakeTimers(); try { From 6fc27956c64bfe2d8659a0a2b44d1496b4f34d62 Mon Sep 17 00:00:00 2001 From: Adrian Webb Date: Fri, 30 Oct 2026 03:52:47 -0400 Subject: [PATCH 2/2] fix: bind workday freshness to selected authority --- .../scenes/component-boundaries.scene.yaml | 10 ++++ guarantees/verifiers/golden.verifiers.yaml | 16 +++++++ .../scheduling/workday-preflight-service.ts | 9 +++- .../architecture/workday-start-native.test.ts | 48 +++++++++++++++++++ .../workdays/selection-preflight.test.ts | 28 +++++++++++ .../architecture/native-subscriber-inputs.ts | 14 +++++- .../proposal-decision-native.test.ts | 4 +- 7 files changed, 125 insertions(+), 4 deletions(-) diff --git a/guarantees/agent/golden/scenes/component-boundaries.scene.yaml b/guarantees/agent/golden/scenes/component-boundaries.scene.yaml index 5fd714650..e9d80a82e 100644 --- a/guarantees/agent/golden/scenes/component-boundaries.scene.yaml +++ b/guarantees/agent/golden/scenes/component-boundaries.scene.yaml @@ -3421,3 +3421,13 @@ workflow: - id: inbox-comment-summary-unit action: { verifier: api.golden.inbox-comment-summary-unit } expect: { status: passed } + + - id: selected-authority-cursor-unit + action: { verifier: api.golden.selected-authority-cursor-unit } + expect: { status: passed } + - id: selected-authority-freshness-denials + action: { verifier: api.golden.selected-authority-freshness-denials } + expect: { status: passed } + - id: selected-authority-public-start + action: { verifier: api.golden.selected-authority-public-start } + expect: { status: passed } diff --git a/guarantees/verifiers/golden.verifiers.yaml b/guarantees/verifiers/golden.verifiers.yaml index 15c7b8f24..dd746de7b 100644 --- a/guarantees/verifiers/golden.verifiers.yaml +++ b/guarantees/verifiers/golden.verifiers.yaml @@ -5759,3 +5759,19 @@ verifiers: ownerPackage: "@treeseed/api" testFile: tests/unit/control-plane/knowledge/inbox/comment-provenance.test.ts testName: "keeps proposal summaries available without fetching discarded comment history" + + api.golden.selected-authority-cursor-unit: + kind: vitestCase + ownerPackage: "@treeseed/api" + testFile: tests/unit/control-plane/capacity/workdays/selection-preflight.test.ts + testName: "starts an unchanged selected root after unrelated team graph progress without rewriting its preflight" + api.golden.selected-authority-freshness-denials: + kind: vitestCase + ownerPackage: "@treeseed/api" + testFile: tests/unit/control-plane/capacity/workdays/selection-preflight.test.ts + testName: "still denies changed selected authority, effort, ordering, capacity and operator before any start write" + api.golden.selected-authority-public-start: + kind: vitestCase + 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" 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 195f36fb5..6b8b567cc 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 @@ -214,11 +214,18 @@ export class WorkdayPreflightService { 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. + const selectedAuthority = selectedDemands.map(demand => { + if (!demand.actingAuthority) return demand; + const { graphRevision: _cursor, ...authority } = demand.actingAuthority; + return { ...demand, actingAuthority: authority }; + }); const state:WorkdayPreflightObservation={ profileGeneration, profileDigest:digest({profileId:intent.profileId,policy:appliedPlan.policySnapshot,reportingAgentId:appliedPlan.reportingAgentId, projects:(Array.isArray(projection.projects)?projection.projects.map(record):[]).map(project=>({ id:project.id,repositoryId:project.repositoryId,contentRevision:project.contentRevision,agentProfileRevision:project.agentProfileRevision, - }))}), demandSetDigest:digest({selectedDemands,objectives:intent.objectiveFilters??[],proposalIds:intent.proposalIds??[],decisionIds:intent.decisionIds??[]}), + }))}), demandSetDigest:digest({selectedDemands:selectedAuthority,objectives:intent.objectiveFilters??[],proposalIds:intent.proposalIds??[],decisionIds:intent.decisionIds??[]}), providerCapacityDigest:digest({providerId,membershipTeam:teamId,availableSeconds:projection.availableSeconds??null}), authorizationDigest:digest({teamId,requestedById,profileId:intent.profileId}), reservationDigest:digest([]), diff --git a/tests/unit/control-plane/capacity/workdays/scheduling/architecture/workday-start-native.test.ts b/tests/unit/control-plane/capacity/workdays/scheduling/architecture/workday-start-native.test.ts index 4a1415f83..14c36c953 100644 --- a/tests/unit/control-plane/capacity/workdays/scheduling/architecture/workday-start-native.test.ts +++ b/tests/unit/control-plane/capacity/workdays/scheduling/architecture/workday-start-native.test.ts @@ -9,6 +9,54 @@ import { listTeamProjectsMethod } from '../../../../../../../src/api/store/proje // AUTHORING ONLY: no execution receipt. Native SQL/HTTP controls do not prove // separate PostgreSQL connections, actual TreeDX policy or provider consumption. describe('first manual and recurring admission through the same public owning path', () => { + // Controlled projection input; actual public service, SQL and start writer. + it('starts and replays a nonempty selected workday after unrelated graph progress while preserving exact selected authority and receipt bytes', async () => { + const f = await workdayStartDatabase(); + try { + const at = f.intent.startsAt; + const source = { store: 'treedx', model: 'proposal', id: 'controlled-proposal', revision: 1, digest: `sha256:${'a'.repeat(64)}` }; + const authority = [{ store: 'treedx', model: 'decision', id: 'controlled-decision', revision: 1, digest: `sha256:${'b'.repeat(64)}` }]; + await f.query(`INSERT INTO execution_graph_revisions (team_id,revision,rule_revision,changed_source_refs_json,graph_digest,changes_json,created_at) + VALUES (?,?,?,?,?,?,?)`, ['team', 1, 1, '[]', 'controlled-initial', '[]', at]); + await f.query(`INSERT INTO execution_nodes (id,team_id,project_id,work_item_id,kind,pair_role,source_ref_json,authority_refs_json, + rule_revision,node_revision,agent_class,status,estimate_json,required_capabilities_json,requested_permissions_json,workspace,maximum_review_cycles, + graph_revision_created,graph_revision_updated,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, + ['selected-review', 'team', 'project', 'work-item', 'reviewing', 'reviewer', JSON.stringify(source), JSON.stringify(authority), + 1, 1, 'boundary-planner', 'ready', JSON.stringify({ expectedSeconds: 10, maximumSeconds: 20 }), '[]', + JSON.stringify({ content: { read: [], write: [] }, tools: [] }), 'treedx', 2, 1, 1, at, at]); + const body = { ...f.intent, planningOnly: false, allocation: { planningPercent: 0 } }, held = structuredClone(body); + const planned = await f.publicService.preflight(f.principal, 'team', body); + expect(planned.selectedDemands).toEqual([expect.objectContaining({ sourceId: 'selected-review', actingAuthority: { + decisionId: 'controlled-decision', decisionRevision: 1, executionNodeId: 'selected-review', executionNodeRevision: 1, + graphRevision: 1, sourceDigest: source.digest } })]); + const original = (await f.snapshot()).receipts[0]; + // Supplied unrelated-project observation. Selected node bytes stay exact. + await f.query('INSERT INTO projects (id,team_id,slug,name,metadata_json,created_at,updated_at) VALUES (?,?,?,?,?,?,?)', + ['other-project', 'team', 'other-project', 'Other project', '{}', at, at]); + await f.query(`INSERT INTO execution_graph_revisions (team_id,revision,rule_revision,changed_source_refs_json,graph_digest,changes_json,created_at) + VALUES (?,?,?,?,?,?,?)`, ['team', 2, 1, JSON.stringify([{ ...source, id: 'unrelated-source' }]), 'controlled-unrelated', '[]', at]); + const before = await f.snapshot(); + const refreshed = await f.publicService.preflight(f.principal, 'team', body); + expect(refreshed.selectedDemands[0]?.actingAuthority).toMatchObject({ graphRevision: 2, executionNodeRevision: 1 }); + expect(refreshed.demandSetDigest).toBe(planned.demandSetDigest); + expect(refreshed.preflightDigest).not.toBe(planned.preflightDigest); + // A real selected revision change is denied before restoring the original + // controlled input and starting the ORIGINAL immutable receipt. + await f.query('UPDATE execution_nodes SET node_revision=2 WHERE id=?', ['selected-review']); + const changed = await f.snapshot(); + await expect(f.start(planned, 'selected-authority')).rejects.toMatchObject({ code: 'workday_preflight_stale' }); + expect(await f.snapshot()).toEqual(changed); + await f.query('UPDATE execution_nodes SET node_revision=1 WHERE id=?', ['selected-review']); + const started = await f.start(planned, 'selected-authority'), after = await f.snapshot(); + expect(started).toMatchObject({ preflightId: planned.id, preflightDigest: planned.preflightDigest, + acceptedExecutionNodeIds: ['selected-review'], assignmentIds: [], reservationIds: [] }); + expect(after.receipts.find(row => row.id === original?.id)).toEqual(original); + expect(after.workdays).toHaveLength(1); + for (const field of ['assignments', 'reservations', 'usage', 'ledger'] as const) expect(after[field]).toEqual(before[field]); + expect(await f.start(planned, 'selected-authority')).toEqual(started); expect(await f.snapshot()).toEqual(after); + expect(body).toEqual(held); + } finally { await f.close(); } + }); it('native owning workday project inventory retains exact team rows excludes completed deletion and remains immutable across concurrent reads', async () => { const f = await workdayStartDatabase(); try { await f.query('INSERT INTO teams (id,slug,name,metadata_json,created_at,updated_at) VALUES (?,?,?,?,?,?)', 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 a3fbfce80..7a6d03caa 100644 --- a/tests/unit/control-plane/capacity/workdays/selection-preflight.test.ts +++ b/tests/unit/control-plane/capacity/workdays/selection-preflight.test.ts @@ -249,6 +249,11 @@ describe('public workday selection custody', () => { ...input(), executionMode: 'simulation', decisionIds: ['decision'], allocation: { planningPercent: 0 }, }), 'actor'), retained = structuredClone(f.stored()); expect(receipt.selectedDemands[0].actingAuthority).toMatchObject({ graphRevision: 5, executionNodeRevision: 5 }); + f.stored().receipt.selectedDemands[0].actingAuthority.graphRevision = 99; + await expect(f.service.start('team', { preflightId: receipt.id, preflightDigest: receipt.preflightDigest, + idempotencyKey: 'cursor-tamper' }, 'actor')).rejects.toMatchObject({ code: 'workday_preflight_integrity_invalid' }); + expect(f.store.createCapacityWorkdayRun).not.toHaveBeenCalled(); + f.stored().receipt.selectedDemands[0].actingAuthority.graphRevision = 5; graphRevision = 9; // Another project's progress changes only the team observation cursor. await expect(f.service.start('team', { preflightId: receipt.id, preflightDigest: receipt.preflightDigest, idempotencyKey: 'unrelated-project-progress' }, 'actor')).resolves.toMatchObject({ acceptedExecutionNodeIds: ['actor'] }); @@ -256,6 +261,29 @@ describe('public workday selection custody', () => { expect(actor).toMatchObject({ status: 'stale', node_revision: 4, workday_id: 'closed-parent' }); expect(f.store.createCapacityWorkdayRun).toHaveBeenCalledTimes(1); }); + it('still denies changed selected authority, effort, ordering, capacity and operator before any start write', async () => { + for (const change of ['node', 'revision', 'source', 'decision', 'effort', 'priority', 'class', 'removed', 'capacity', 'operator']) { + const f = fixture(true), row = { graph_revision: 5, priority: 0, + ...executionNodeRow({ id: 'actor', kind: 'acting', agentClass: 'engineer', digest: 'source', expectedSeconds: 180, nodeRevision: 4, decisionRevision: 1 }) }; + const projection = { availableSeconds: 7200, projects: [{ id: 'project-sdk', agents: [] }], executionNodeDemands: [row] }; + f.store.preflightCapacityWorkdayRunRequest.mockResolvedValue(projection); + const receipt = await f.service.preflight('team', parsePublicWorkdayIntent('team', { ...input(), + decisionIds: ['decision'], allocation: { planningPercent: 0 } }), 'actor'), retained = structuredClone(f.stored()); + row.graph_revision = 9; + if (change === 'node') row.id = 'replacement'; + if (change === 'revision') row.node_revision++; + if (change === 'source') row.source_ref_json = JSON.stringify({ ...JSON.parse(row.source_ref_json), digest: exactDigest('moved') }); + if (change === 'decision') row.authority_refs_json = JSON.stringify([{ ...JSON.parse(row.authority_refs_json)[0], revision: 2 }]); + if (change === 'effort') row.estimate_json = JSON.stringify({ expectedSeconds: 181, maximumSeconds: 360 }); + if (change === 'priority') row.priority = 1; + if (change === 'class') row.agent_class = 'replacement'; + if (change === 'removed') projection.executionNodeDemands = []; + if (change === 'capacity') projection.availableSeconds--; + await expect(f.service.start('team', { preflightId: receipt.id, preflightDigest: receipt.preflightDigest, + idempotencyKey: `changed-${change}` }, change === 'operator' ? 'another-operator' : 'actor')).rejects.toMatchObject({ code: 'workday_preflight_stale' }); + expect(f.stored()).toEqual(retained); expect(f.store.createCapacityWorkdayRun).not.toHaveBeenCalled(); + } + }); it('freezes the admission time when an explicit start is omitted', () => { vi.useFakeTimers(); try { diff --git a/tests/unit/control-plane/governance/proposals/architecture/native-subscriber-inputs.ts b/tests/unit/control-plane/governance/proposals/architecture/native-subscriber-inputs.ts index 9dc4c7069..5f8f0fc73 100644 --- a/tests/unit/control-plane/governance/proposals/architecture/native-subscriber-inputs.ts +++ b/tests/unit/control-plane/governance/proposals/architecture/native-subscriber-inputs.ts @@ -5,7 +5,8 @@ import { proposalNativeFixture } from './proposal-native-fixture.ts'; import { loadProposalGroupContributions } from '../../../../../../src/api/capacity/services/capacity/execution/proposal-contributions.ts'; import assert from 'node:assert/strict'; import { expect } from 'vitest'; -import { randomUUID } from 'node:crypto'; +import { createHash, randomUUID } from 'node:crypto'; +import { canonicalJson } from '../../../../../../src/api/capacity/security.ts'; import { stringify } from 'yaml'; import { assignmentAttemptSchema, assignmentResultSchema, type ExactEntityReference, type AgentDefinition, type ExecutionNode } from '@treeseed/sdk/agent-capacity'; import { assignment as original } from '../../../capacity/execution/fixtures/assignment.ts'; @@ -182,3 +183,14 @@ export async function subscriberSourceFixture() { return { ...f, store, publishCurrent }; } catch (error) { await f.close(); throw error; } } + +/** The exact selected authority excludes only the team observation cursor. */ +export function expectNativeSelectedDemandDigest(receipt: import('@treeseed/sdk/operator-contracts').WorkdayPreflightReceipt, + actor: ExecutionNode, decisionId: string) { + const selected = { ...receipt.selectedDemands[0]!, actingAuthority: { decisionId, + decisionRevision: actor.authorityRefs!.find(ref => ref.model === 'decision')!.revision, + executionNodeId: actor.id, executionNodeRevision: actor.nodeRevision, sourceDigest: actor.sourceRef.digest } }; + expect(receipt.demandSetDigest).toBe(`sha256:${createHash('sha256').update(canonicalJson({ + selectedDemands: [selected], objectives: [], proposalIds: [], decisionIds: [decisionId], + })).digest('base64url')}`); +} diff --git a/tests/unit/control-plane/governance/proposals/architecture/proposal-decision-native.test.ts b/tests/unit/control-plane/governance/proposals/architecture/proposal-decision-native.test.ts index 1e5fd5873..8bfbe8def 100644 --- a/tests/unit/control-plane/governance/proposals/architecture/proposal-decision-native.test.ts +++ b/tests/unit/control-plane/governance/proposals/architecture/proposal-decision-native.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; import { validateDecisionAuthority, validateExecutionAuthorityReceipt } from '../../../../../../src/api/governance/decision-authority.ts'; import { prepareNativeProposalVoting } from './ready-proposal-fixture.ts'; -import { nativeSubscriberInputs, recordNativeSubscriberInputs, expectNativeSubscriberGraph } from './native-subscriber-inputs.ts'; +import { nativeSubscriberInputs, recordNativeSubscriberInputs, expectNativeSubscriberGraph, expectNativeSelectedDemandDigest } from './native-subscriber-inputs.ts'; import { verifyNativeProposalReconciliation, verifyScopedInboxQuestionGates, verifyNativeAcceptedTeamGrowth, verifyNativeUnissuedDecisionHandoff } from './proposal-reconciliation-fixture.ts'; import { createHash, generateKeyPairSync, randomUUID } from 'node:crypto'; import { stringify } from 'yaml'; @@ -391,7 +391,7 @@ describe('native proposal Decision authority', () => { expect(object(preflightProjection.agentProfilesByProjectId)[projectId]).toMatchObject({ agents: subscriberInputs.subscribers.map(profile => expect.objectContaining({ definition: profile.definition })) }); const hash = (value: unknown) => `sha256:${createHash('sha256').update(canonicalJson(value)).digest('base64url')}`; - expect(receipt.intentDigest).toBe(hash(intent)); expect(storedRows[0]!.request_digest).toBe(receipt.intentDigest); expect(receipt.demandSetDigest).toBe(hash({ selectedDemands: receipt.selectedDemands, objectives: [], proposalIds: [], decisionIds: [decisionId] })); + expect(receipt.intentDigest).toBe(hash(intent)); expect(storedRows[0]!.request_digest).toBe(receipt.intentDigest); expectNativeSelectedDemandDigest(receipt, actorNode, decisionId); const { preflightDigest, ...payload } = receipt; expect(preflightDigest).toBe(hash(payload)); expect(await readerState()).toEqual(preflightBefore); expect(await f.store.all('SELECT * FROM capacity_operation_receipts WHERE resource_id<>? ORDER BY id', [receipt.id])).toEqual(originalReceipts); expect(intent).toEqual(intentBefore); expect(await listReadyExecutionNodes(f.store, run, readyProject)).toEqual(expectedReady); expect(await f.store.all('SELECT * FROM governance_events ORDER BY id')).toEqual(history);