import { requireConductor } from "./conductor.ts"; import { instructedExecution, instructedHistory } from "./instructed-exact.ts"; import { managedTaskPullRequest } from "./task-pr.ts"; import { parseMilestoneInput, parseMilestonePatch, milestoneId, milestoneRevision, milestoneLinkRef, githubRepo, MILESTONE_STATES, type Milestone, type MilestoneLinkKind, type MilestonePatch, type MilestoneState, type MilestoneSuggestion, type SuggestionItemKind, type DecomposePart, type DecomposeIntake, type MilestoneDecomposition, type DecompositionAccept } from "./roadmap.ts"; import { milestoneViews, type MilestoneView, type RoadmapSnapshot } from "./roadmap-view.ts"; import { readMirrorSnapshot, planRoadmapMirror, recoverMirrorBinding } from "./roadmap-sync.ts"; import { roadmapExport } from "./roadmap-export.ts"; import { checkRoadmap, type DriftMilestone, type RoadmapDrift } from "./roadmap-check.ts"; import type { RoadmapConfig } from "./roadmap.ts"; import { computeUnplaced, withTree, type ReadyToClose, type TreeRollup, type UnplacedResult } from "./roadmap-unplaced.ts"; import { buildTriagePrompt, parseTriage, TRIAGE_BATCH, type TriageItem } from "./roadmap-triage.ts"; import { buildDecomposePrompt, parseDecomposition, planPartPublish, DECOMPOSE_ITEMS, DECOMPOSE_PATHS, type DecomposeItem, type PublishDraft, type PublishPlanPart } from "./roadmap-decompose.ts"; import { pathCandidates } from "@staix/agent-mem"; import { renderGuidanceVariantV1 } from "./guidance-variants.ts"; import { GuidanceProbeFixtureHost, type GuidanceProbeStore } from "./guidance-probe-store.ts"; import { GuidanceProbeError, GUIDANCE_PROBE_STOP_TIMEOUT_MS, GUIDANCE_PROBE_FENCE_INTERVAL_MS, guidanceProbeCanonical, guidanceProbeManifestKey, parseGuidanceProbeRegistration, parseGuidanceProbeReceiptExport, probeHash, probeSha256, probeInteger, probeSessionGeneration, type ProbeChildBinding, type ProbeStoredState, type ProbePublicReceipt, type ProbePublicStatus, type ProbeHostBinding, type ProbeReceiptExport, type ProbeExportSlot, type ProbeReceiptV1, type ProbeRetentionState, type ProbeAdmissionRecheck, type ProbeReservation, type ProbeSlot, type GuidanceProbeFakePorts, type GuidanceProbeManifestV1, type ProbeWorkerFramePreparer } from "./guidance-probes.ts"; import { GuidanceVariantError, GUIDANCE_PAGE_MAX_RECORDS, GUIDANCE_REPLY_MAX_BYTES, guidanceVariantSectionDiff, guidanceProtectedSectionNames, parseGuidancePageResult, parseGuidanceDiffResult, parseGuidanceListQuery, parseGuidanceIdQuery, guidancePageCursor, guidancePageAfter, guidanceVariantMetadata, parseGuidanceVariantV1, validateGuidanceVariantV1, parseGuidanceSelector, type GuidanceVariantV1, type GuidanceStoredRecord, type GuidanceSelector, type GuidanceIdSelector, type GuidanceWriteFence, type GuidanceWriteReceipt, type GuidanceCurrent, type GuidancePublicRecord, type GuidancePageResult, type GuidanceDiffResult, type GuidanceReadResult } from "./guidance-variants.ts"; import { buildEntryDiagnostic } from "./build-entry.ts"; import { taskShowAllowed } from "./conductor.ts"; import { executionOwnerSnapshot, parseOwnerLineageQuery, type ExecutionLineageOwnerPorts } from "./execution-lineage-owner.ts"; import { readExecutionLineage, type LineageResult } from "./execution-lineage.ts"; import { parseExecutionLinkInput, taskExecutionReference, executionLinkActor, executionReferenceDigest, type ExecutionLinkInput } from "./execution-links.ts"; import { executionReferenceKey, executionText, EXECUTION_REFERENCE_LIMITS, type ExecutionReferenceV1 } from "./execution-reference.ts"; import type { JournalDelivery } from "./delivery-journal.ts"; import { checkSynthesis, inventoryBinding, parseSynthesisManifest, synthesisManifestHash, type SynthesisManifestV1, type SynthesisCurrent, type SynthesisCurrentClaim, type SynthesisArtifactSnapshot, type SynthesisReadiness } from "./synthesis-readiness.ts"; import { parseEvidenceRecord, parseEvidenceLink, evidenceLinkId, evidenceLinkCanonical, type EvidenceRecordInput, type EvidenceReceipt, type EvidenceLinkV1 } from "./research-evidence.ts"; import type { ActionMeta, ReviewAnchor } from "@staix/agent-console/contract"; import { parseReviewAnchor, reviewAnchorErrorMessage, anchorStatus, type ReviewAnchorStatus } from "./review-anchor.ts"; import type { ReviewMaterialBatch } from "./review-material.ts"; import { isReviewObserverExcluded } from "./memory-policy.ts"; import { renderFindingAnchor } from "./review-brief.ts"; import { reviewCommentFields, reviewCommentNumber, reviewCommentId, reviewCommentIds, reviewCommentHead, reviewCommentBody, reviewCommentAuthor, privateReviewAnchor, reviewThreadProjection, renderReviewComment, REVIEW_PACKAGE_BYTES, REVIEW_COMMENT_LIMIT, type ReviewCommentRecord, type ReviewCommentFence, type ReviewCommentMutation, type ReviewCommentCounts, type ReviewCommentView } from "./review-comments.ts"; import { evidenceOriginKeys, type EvidenceSourceRead } from "./source-read.ts"; import type { SourceMeta } from "./sources.ts"; import { parseAttemptReceipt, parseResearchRunners, verifyAttemptReceipt } from "./research-runner.ts"; import { approvalBinding, approvalText } from "./task-approval.ts"; import type { InvocationRow } from "./invocations.ts"; import type { ContextAdmission } from "./context-window.ts"; import { queueBackpressure, queueBackpressurePolicy, type QueueBackpressureCode, type QueueBackpressurePolicy, type QueueBackpressureStatus, type QueuePressure } from "./queue-backpressure.ts"; import { generatedRecordAnchors, type GeneratedNoteProof } from "../memory/record-provenance.ts"; import { canonicalMemorySymbolNode, normalizeMemorySymbolInput, MEMORY_SYMBOL_LIMIT, type MemorySymbolNodes } from "./memory-symbols.ts"; import { createHash, randomBytes } from "node:crypto"; import { types } from "node:util"; import { canonicalJson } from "./packs.ts"; import { parseExperimentProtocol, parseExperimentAttempt, parseExperimentEvent, protocolHash, checkRunObservation, deliverableObservation, projectExperimentWithObservations, projectRunnerReceipt, type ExperimentProtocolContract, type ExperimentProtocolRecord, type ExperimentAttemptRecord, type ExperimentWriteFence, type ExperimentHostEvidence, type ExperimentStatus } from "./research-experiments.ts"; import { parseComparisonPlan, comparisonPlanHash, comparisonProjection, evaluatorIdentityHash, protocolApprovalBindingMatches, type ComparisonPlanV1 } from "./research-experiments.ts"; import { parseResearchHandoff, studyProjection, campaignHash, parseResearchCampaign, type ResearchCampaignContract, type ResearchCampaignStatus } from "./research-campaign.ts"; import type { ResearchCampaignRecord, ResearchUnitBinding, PreparedResearchUnit, HandoffOutboundRow } from "./board.ts"; import { HANDOFF_EVENTS, HANDOFF_KEY, HandoffRefusal, handoffRequestDigest, duplicateIssueTasks, duplicateRefusalText, followBackLine, handoffEventFor, parseHandoff, type HandoffEvent } from "./handoff.ts"; import { taskShellBindingValid, type TaskShellBinding } from "./task-shell-command.ts"; import type { ReviewBudgetSnapshot, ReviewGate, ReviewUnknownQuota } from "./review-budget.ts"; import { buildTaskCodeSymbols, publicTaskCodeSymbols, taskCodeSymbolsDisjoint, HOST_CODE_SYMBOLS } from "./task-code-symbols.ts"; import { normalizePlanSymbol, symbolsOverlap } from "./symbol-normalizer.ts"; import { publicTestIntegrity, readTestIntegrity, testIntegrityBlockers, type TestIntegrity } from "./test-integrity.ts"; import { evalAdvice, evalGapBlockers, evalRequiredChecks, readEvalFor } from "./eval-gate.ts"; import { parseSecurityPass, securityPassBlockers, securityPassView, securityRequestLine, SECURITY_CHECKLIST, type SecurityPassRecord, type SecurityPassView } from "./security-pass.ts"; import { AUDIT_PROFILES, applyUnitReports, auditBrief, auditFindingView, auditIsPartial, auditSummary, needsVerification, parseUnitReports, seedLedger, settlementRefusal, SETTLEMENTS, unitId, verificationRefusal, type AuditFinding, type AuditProfile, type AuditSummary, type CarryLookup, type PublicAuditFinding } from "./security-audit.ts"; import type { AuditSource } from "./audit-source.ts"; import { SURVEY_FOCUS, SURVEY_LIMITS, parseSurveyFindings, parseSurveyVetDecisions, publicSurveyFinding, surveyBrief, surveyFindingKey, surveyObject, surveyPath, surveyInputAt, surveyInputProblem, type SurveyFinding, type SurveyFocus, type SurveyPass } from "./advisor-survey.ts"; import { consideredFindingMatch, parseConsideredEntry, type ConsideredEntry } from "./considered-findings.ts"; import type { StoredSurvey, SurveyPreparedCard } from "./board.ts"; import { matchConfigPath } from "./eval-gate.ts"; import { completePlanInventory, planDrift, planConformance, planConformanceBlockers, planFingerprint, type PlanConformance } from "./plan-conformance.ts"; import { RELEASE_TRAIN_HISTORY_LIMIT, releaseTrainData, releaseTrainReadiness, releaseMetrics } from "./sdlc-release.ts"; import { cleanCostPlan, costMetrics, CostScopeError, type CostPlan, type ReviewCost } from "./cost-governance.ts"; import { qualifiedTitleRepos, siblingTitleRefs, specRefs } from "./spec-read.ts"; import { folderDetail, MAX_NEW_PER_POLL, scheduleNext, SOURCE_ID, scheduledDetail, scheduleKeyOf, type FolderEntry, type FolderRunResult, type FolderScan, type FolderStorePort, type ScannedFile, type ScheduleEntry, type ScheduleRunResult, type ScheduleStore } from "./schedules.ts"; import { INTAKE_MAX_SOURCES, INTAKE_MAX_TEXT, intakeDetail, intakeSystemPrompt, intakeUserMessage, parseIntakeDetail, parseIntakeSplit, plannerRequestBody } from "./intake.ts"; import { DEFAULT_BAND, EPISODE_LOOKBACK, sdlcMetrics, type BandMetric, type BandResult, type MetricTask, type MetricsReport, type SeriesPoint } from "./sdlc-metrics.ts"; import { readSecurityScan } from "./security-baseline.ts"; import { cleanMergeCost, mergeCostFrom } from "./cost-governance.ts"; import type { InstancesConfig } from "./instances.ts"; import { composeRememberText } from "./memory-fail.ts"; import { VERSION } from "../version.ts"; import { NoWriteTurns } from "./no-writes.ts"; import { readGitHubImport, readGitHubIssuePages, readGitHubMilestonePages, type GitHubSource, type GitHubImportSelection } from "./github-import.ts"; import { BACKLOG_SPLIT_SCREEN_TIMEOUT_MS, actualTaskDates, planningPatch, type PlanningFields, type Release, type ReleaseState } from "./planning.ts"; import { readMergeQueue, type DeliveryTask, type MergeQueue } from "./sdlc-queue.ts"; import { INLINE_MERGE_READBACK_DEADLINE_MS, MERGE_READBACK_DEADLINE_MS, adoptMergeGates, guardedMerge, mergeModeFor, mergeView, readAdoptMergeEvidence, requiredChecksFor, type MergeView } from "./sdlc-merge.ts"; import { mirrorVerdict as mirrorToGitHub, type MirrorVerdict } from "./sdlc-mirror.ts"; import { CODE_SCOPE_LINE, evidenceOnlyNotice, type ReviewScope } from "./review-scope.ts"; import { DEFAULT_MAX_NITS, parseReviewFindings, findingsForHead, findingHead as resolveFindingHead, findingTally, findingFollowUps, positionalFindingId, type ReviewFinding, type ReviewFindingSet } from "./review-findings.ts"; import { readReleaseReadiness, type ReleaseReportPolicy } from "./sdlc-release.ts"; import { loadRoleCatalog, roleIdentity, taskRole, taskRoleText, type RoleCatalog } from "./roles.ts"; import { matchesPolicy, matchesPolicyLexically, policyRealPath, insideRoot } from "./path-policy.ts"; import { isDenied } from "../local/deny.ts"; import { foldSegment, isHubWritePath } from "./permission-mode.ts"; import { correctionInput, resolveVisibleMemory } from "./memory-candidates.ts"; import type { MemoryScreen } from "./read-tools.ts"; import { withoutPii, mentionsPrivatePath } from "./memory-policy.ts"; import { createMemorySyncPolicy } from "./memory-sync-policy.ts"; import { profileClass, profileData, profileTaskLabel, projectProfile, type ProfileName, type ProfileSelection, type ProjectProfile } from "./profiles.ts"; import { criteriaView, unmetCriteriaIds, workflowHash } from "./workflow.ts"; import { candidateCard, criterionKey, groupUnmetCriteria, LEARNING_DEFAULTS, overridesDiff, parseCandidateCard, selectGroups, type CriterionGroup } from "./learning.ts"; /** #514b: how a closed candidate card says what the person decided; `learnCandidates` reads them back. */ const LEARN_ACCEPTED = "candidate accepted", LEARN_REJECTED = "candidate rejected"; /** What the person decided on a candidate card, read from its cancellation: only an entry the person wrote counts, so no other note can pass for a verdict. Undefined while it is open or closed for another reason. */ const learnVerdict = (card: Pick): "accepted" | "rejected" | undefined => { if (card.state !== "cancelled") return undefined; const closed = card.history.findLast(entry => entry.event === "cancelled"); if (!closed || closed.by !== USER) return undefined; return closed.note?.startsWith(LEARN_ACCEPTED) ? "accepted" : closed.note?.startsWith(LEARN_REJECTED) ? "rejected" : undefined; }; import { approvedDeliverables, latestDeliverables, parseDeliverableClaims, publicDeliverables, type DeliverableRecord, type DeliverableStatus } from "./deliverables.ts"; import { checkDeliverables, DeliverableRefusal, hashDeliverables, vetDeliverables, readGuardedDeliverable, guardedDeliverableCurrent, type GuardedDeliverableRead, type DeliverablePorts } from "./deliverable-files.ts"; import { isAbsolute, relative, resolve } from "node:path"; import type { Briefs, NativeItem } from "../memory/brief.ts"; import type { MemoryClient } from "../memory/client.ts"; import { candidateTargetRevision, type CandidateInput, type CandidateStore, extractNodes, looksSecret, PROMOTED_KINDS, taskKey, type GoalView, type Kind, type MemoryStore, type NoteInput, type Scope, type Tier } from "@staix/agent-mem"; import { HOST_SPEC_ACCEPTANCE_CARRY, HOST_MERGE_ADOPTION, HOST_ROADMAP_DRAFT, parseClaimVerdict, taskClaimIdentity, CLASSES, OUTCOMES_KEPT_MS, ALL_PLAN_KEYS, TASK_MOVE_REASONS, taskCanPlan, taskHasWorkEvidence, taskHasStarted, planningUndoEntry, isClosedTaskState, type TaskStall, type HistoryEntry, type ReviewerHistory, type Board, type Task, type TaskClass, type TaskMoveReason, type TaskPlan, type TaskRefs, type SpecAcceptanceCandidate, type SpecAcceptanceCommit, type PlannerBinding, type SpecAck, type SpecTaskReport } from "./board.ts"; import type { Bus } from "./bus.ts"; import { HUB, newEnvelope, NOTE_KINDS, noteLine, sanitize, USER, type Envelope, type PeerId, type PeerState } from "./envelope.ts"; import type { PiiVerdict, ScreenItem, ScreenRecord } from "./inference.ts"; import { assign, expandClassPeers, isRemotePeerId, detectSignals, peerEntry, predictSplit, relayCandidates, writesRepository, ownerRoleOfClass, type Assignment, type InstanceRoutingOptions, type PeerCapabilities, type Routing, type SplitObservation, type SplitPrediction } from "./routing.ts"; import { ExecutionBudget, type ExecutionBudgetConfig, type ExecutionBudgetDecision, type ExecutionBudgetStatus, type ExecutionUnit } from "./execution-budget.ts"; import { Cohorts, MAX_REQUESTS, type Cohort, type Completion } from "./cohorts.ts"; import { realPath } from "./project.ts"; import { TaskRepositories, githubOriginRepository } from "./task-repository.ts"; import { mainCheckoutWarning } from "./main-checkout.ts"; import { PreEffectToolRefusal } from "./tool-refusal.ts"; import type { TaskWorktreePort } from "./task-worktree.ts"; import { coverageGap, renderReviewBrief, renderSpecTaskReport, type BriefFile, type ReviewBrief } from "./review-brief.ts"; import { DEFAULT_SPECS_CONFIG, type SpecsConfig } from "./specs-config.ts"; import type { SpecsCheckReport, SpecsCoverReport } from "./specs.ts"; import { definitionOf as builtinDefinitionOf } from "../adapters/registry.ts"; import { ADAPTERS, DEFAULT_REVIEW_POOL, definitionOf, familyOf, type ProjectAdapterCatalog } from "../adapters/registry.ts"; import { plannerGrooming, nextSweep, plannedStartPending, taskSweepConfig, taskWait, TASK_WAIT_MAX_MS, TASK_WAIT_REASON_MAX, type TaskSweepConfig, type SweepRecord } from "./task-sweep.ts"; import { CiWatchers, pollCi, type CiOutcome, type CiWatch } from "./ci-watch.ts"; import { planningIssueReceipt, linkedReceipt, openPrFor, readPrCostHistory, readReviewReadiness, reviewReadinessFromEvidence, type PrEvidence, type ReviewReadiness, readPlanIssueMetadata, canonicalStage, checklistOf, readSdlcPr, readSdlcPrHead, readSpecEdit, sdlcConfig, sdlcReceipt, sdlcStatus, specState, SPEC_STATE_TEXT, stageDefinition, lifecycleStage, type SdlcConfig, type MergeRecord, type ReadbackMergeRecord, type PlanIssueMetadata, sdlcGh, type SdlcGh, type SdlcStatus, type SpecEdit, type SpecState, localSupersedingTask, storedSpecAcceptance, carriedSpecAcceptance } from "./sdlc.ts"; /** #1176: refusals for an agent that reaches a person-run card by a path other than the pull gate. */ const PERSON_RUN_SPLIT = "a person-run card is the person's to split: its children would be unmarked cards an agent could take (the person's own split marks every child person-run)"; const PERSON_RUN_ACCEPT = (id: number) => `task #${id} is a person-run leg: no agent accepts it (it waits on the person: live receipts, their accounts or approvals). The person runs it or clears the mark with ahub backlog plan`; function requireLocalTaskPeer(peer: unknown): void { if (isRemotePeerId(peer)) throw new PreEffectToolRefusal("remote peers have no local task authority"); } export type TaskAssignmentRole = "owner" | "reviewer" | "planner"; export type EvidenceReadOrigins = { state: "known"; group: string; groups: number } | { state: "unknown" }; export type EvidenceReadResult = EvidenceReceipt & ({ status: "private" | "stale" | "unavailable" | "withdrawn" } | { status: "resolved"; link: EvidenceLinkV1; excerpt: string; excerptSha256: string; locator: EvidenceLinkV1["locator"]; origins: EvidenceReadOrigins }); /** What `hub_remember` carries (#802: one shape for `remember` and `rememberOutcome`). */ export interface RememberInput { text?: string; title?: string; kind?: string; task?: unknown; horizon?: unknown; scope?: unknown; approach?: unknown; symptom?: unknown; cause?: unknown; evidence?: unknown; retry_when?: unknown } interface SpecGateRead { task: Task; edit?: SpecEdit; carry?: object; } interface SpecCarryProof { by: PeerId; task: number; scope: string; commit: SpecAcceptanceCommit; current: () => boolean; } interface PreparedSpecInspection { report?: SpecTaskReport; policyKey: string; repo?: string; head: string; privateTurn: boolean; pii: boolean; } export interface ReleaseWindow { at: number; host: boolean; quota: boolean; idle: boolean; reasons: string[]; current?: () => boolean; close?: () => Promise; } /** #1403 A4: the audit as a caller reads it. `withheld` counts open important findings whose text the view leaves out. */ export interface AuditView extends AuditSummary { units: { unit: string; state: string; prior?: { audit: number; head: string }; reason?: string }[]; items: PublicAuditFinding[]; withheld?: number; /** Findings in this report that were already verified or rejected, so the hub left them as decided. */ notUpdated?: string[]; } export interface TasksDeps { /** Timing-only owner question evidence for the idle-owner ladder. */ ownerQuestionWait?: (task: number, peer: PeerId) => { open: boolean; settled?: number } | undefined; /** Private host-owned probe ledger and fixture ports. No configuration, wire or model-selected runner. */ guidanceProbes?: { store: GuidanceProbeStore; fakePorts?: GuidanceProbeFakePorts; prepareWorkerFrame?: ProbeWorkerFramePreparer; prepareEditorFrame?: (state: ProbeStoredState, slot: ProbeSlot) => string | Promise; session?: (by: PeerId) => { generation: string | number; nativeSession: string | null; requestConnectionId: string; current: () => void } | undefined; timer?: { set(callback: () => void, ms: number): unknown; clear(handle: unknown): void }; }; adapterCatalog?: ProjectAdapterCatalog; /** Host-bound evidence only; absent/expired observations never admit a release cut. */ releaseWindow?: () => Promise; /** Effective per-peer planner capacity, taken from the existing settings loader. */ wipLimit?: (peer: PeerId) => number; recordPlanning?: (change: { by: string; task?: number; release?: number; fields: string[]; revision: number }) => void; /** The clock of the planner board-changed notice window (#758); tests inject one. Absent: `Date.now`. */ now?: () => number; board: Board; bus: Bus; routing: () => Routing; /** #800: normalized machine-local admission policy; absent or both zero preserve the old queue behaviour. */ queueBackpressure?: () => QueueBackpressurePolicy; /** Host-only native context snapshots, separate from checkpoint notification and quota. */ contextAdmission?: () => ContextAdmission; /** Startup-bound project declarations; routing never discovers instances from peer names. */ instances?: () => InstancesConfig; /** Host proof of each live extra runtime's actual isolated execution root; config paths alone are not proof. */ ownerIsolation?: () => Readonly>; cwd: string; project: string; /** Startup-bound namespace/key and an already-open exact-id journal read; never query-controlled. */ executionLineage?: { projectKey: string; cursorKey: string; readDelivery?(id: string): JournalDelivery | undefined }; profile?: ProfileName; profileData?: ProjectProfile; piiPaths?: string[]; /** The project's secrets denylist (`local.deny`), for the deliverable file reader (#509a). */ deny?: string[]; /** * #509a: the root a peer's files live under: its verified execution root (the daemon's `ownerWriteRoot`), which for a declared worktree * instance is not the project checkout. `undefined` means the root is not proven right now. Absent (library use): the project root. */ executionRoot?: (peer: PeerId) => string | undefined; catalog?: RoleCatalog; /** Role ids whose contract was prepared for the current native session. */ sessionRoles?: (peer: PeerId) => string[]; /** Optional bounded snapshot presentation; never stored in task history or memory. */ projectedReview?: (task: Task) => string | undefined; /** Closed host evidence since the current acceptance: false means proven no writes; undefined is unknown. */ ownerWrites?: (task: Task, since: number) => boolean | undefined; /** Explicit acceptance/self-claim only; implicit done has no pre-work baseline. */ ownerAccepted?: (task: Task) => void; /** #520: the review brief for a task's commit (git only, bounded); undefined when the task names no commit. */ prepareReviewBrief?: (task: Task) => Promise; reviewBrief?: (task: Task) => ReviewBrief | { unavailable: string } | undefined; /** Current public coverage for a task's declared paths; absent when notices are disabled or no specs exist. */ specNotice?: (task: Task) => SpecsCoverReport | undefined; /** Inspect spec metadata at a verified task head; undefined is authoritative quiet (no specs/stamps or review off). */ inspectSpecs?: (task: Task, head: string, changedFiles: readonly BriefFile[] | undefined, acks: readonly SpecAck[]) => Promise; /** Effective shared and machine-local specs policy. */ specsConfig?: () => SpecsConfig; /** Explicit, read-only inspection remains available when task notices are disabled. */ specsRead?: (action: "check" | "covers", paths: readonly string[]) => SpecsCheckReport | SpecsCoverReport; /** R3 (#1481): spec ids with their status, for the unplaced list. Absent or throwing is "unavailable", never "no specs". */ specsList?: () => { specs: { id: string; title: string; status: string | null; type?: string; paths?: string[] }[]; errors: number; truncated: boolean }; /** R3 (#1481): the model for triage. Absent, off or failing is no suggestion; it carries no authority and links nothing. */ roadmapModel?: (system: string, user: string, allowed: () => boolean) => Promise; /** R3 (#1481): host-only `gh` runner for the roadmap's read-only issue and milestone reads (tests); production uses `sdlc.gh`. */ roadmapGh?: SdlcGh; /** Host-only origin proof for tests; production reads the project-local Git origin. */ roadmapOrigin?: () => string | undefined; roadmapConfig?: () => RoadmapConfig; /** Host-verified existing symbols at this task's admitted completion head; never plan guesses. */ memorySymbolNodes?: (task: Task) => MemorySymbolNodes | undefined; /** Host-only release report selector; derives its answer from committed policy and the in-memory authorization ledger. */ sdlc?: { config: () => SdlcConfig; gh?: SdlcGh; reportPolicy?: (head: string, repo: string) => ReleaseReportPolicy | undefined }; /** #1403 A4: read-only git for the security audit (the checkout's head and changed paths); absent means the audit commands are unavailable. */ auditSource?: AuditSource; /** #785 P1b: the per-head CI watcher's bounds; tests shorten them, the defaults are `CI_WATCH_*` in `ci-watch.ts`. */ ciWatch?: { deadlineMs?: number; pollMs?: number }; /** #785 P1c: `tasks.auto_pull`, read for every automatic pull trigger; absent or false pulls nothing. */ autoPull?: () => boolean; briefs?: Briefs; /** Screened live fail notes directly intersecting the task plan or refs; read-only advice. */ planFails?: (task: Task) => NativeItem[]; candidates?: CandidateStore; candidateScreen?: MemoryScreen; /** Authenticated live turn context, not a model-supplied flag. */ privateTurn?: (peer: PeerId) => boolean; /** Host-only observer provenance, separate from task/turn authority. Sample before any operation await. */ observerExcludedTurn?: (peer: PeerId) => boolean; /** #223 R4: the hub's reading of a verdict's context (`fresh` only for a reviewer session started for this review). */ reviewContext?: (by: PeerId, task: number) => "fresh" | "continuing" | undefined; /** Current-turn input carries review material or anchored findings; it expires on the next ordinary input. */ reviewObserverInput?: (peer: PeerId) => boolean; /** Latch an anchor-bearing hub_review input before its first await or effect, even if the verdict is refused. */ onReviewObserverInput?: (peer: PeerId) => void; /** #852: what a reviewer reads. `code` (the fixed sandboxed reviewers by default, or a local `review_scope`) reads the code only; unset or `full` also runs tests and reads CI. */ reviewScope?: (peer: PeerId) => ReviewScope; /** #223 R2: a reviewer-only instance gets review facts, not the builder's done summary. */ reviewOnly?: (peer: PeerId) => boolean; /** #223: captured when a verdict call starts; a non-undefined result refuses the verdict at every later check. */ reviewAuthority?: (by: PeerId, task: number) => (() => string | undefined) | undefined; /** Host-captured current-child authority, rechecked before an admitted async tool first commits effects. */ requestAuthority?: (by: PeerId) => (() => string | undefined) | undefined; /** * #933: whether `by` runs this call inside an admitted, audited conductor operation. The host rechecks the role on every call and throws * its authority refusal when it ended; a peer outside such a call gets `false`. Host-only: never read from configuration or a tool. */ operational?: (by: PeerId) => boolean; memory?: MemoryClient; /** Captured native profile fence at our memory operation boundaries; no board mutation. */ memoryCheck?: () => void; /** #258: the hub's own store, the project name it files entries under (the git chain) and the repo `#N` issues belong to. */ store?: { store: MemoryStore; project: string; repo: string; deny?: string[]; onNote?: (id: string) => void; onGeneratedNote?: (entry: GeneratedNoteProof) => void }; /** a line for the human: console tail and hub.log */ notify: (line: string) => void; /** The completion check configured for a class, if any (local config only; issue #7). */ check?: (cls: TaskClass, task?: Task) => string | undefined; /** #901: the key of the `checks` entry `check` chose for this task (the profile class alias, else the class): the same lookup, so the two cannot disagree. Absent: the key is unknown. */ checkKey?: (cls: TaskClass, task?: Task) => string | undefined; /** Runs one check; the hub runs them one at a time. */ runCheck?: (command: string) => Promise<{ code: number | null; timedOut: boolean; interrupted?: boolean; tail: string }>; /** Hands a saved note to every other peer; it rides on their next delivery. */ share?: (by: PeerId, line: string) => void; /** Hands one peer a line that rides on its next delivery, without a turn of its own (issue #6). */ tell?: (peer: PeerId, line: string) => void; /** Structured overlap records for telemetry (issue #40); the notice line stays for the human. */ /** #1054: a completion check this peer owned just ended (its ownership is already cleared), so a run that waited on it may settle. Advisory: a throw is ignored. */ checkEnded?: (owner: PeerId) => void; recordOverlap?: (task: number, owner: PeerId, others: { task: number; owner: PeerId; paths: string[]; symbols?: string[] }[]) => void; /** Quota per peer from fresh readings (issue #36): routing drains the windows that reset soonest first. */ quota?: () => Record; /** Optional persisted task/run execution limits (issue #102). */ executionBudget?: ExecutionBudget; /** Project-scoped immutable-source metadata, read only before a study transaction. */ /** Host-scoped immutable-head/material batch; supports host-staged completion refs/sdlc, never client-staged Task objects. The shared reader owns file authorization and budgets. */ reviewMaterials?: (task: Task, requests: readonly { path: string; side?: "base" | "head" }[]) => Promise; studySource?: (id: string) => { id: string; sha256: string; private: boolean } | undefined; /** Host-owned screened snapshot read, never a public source-read excerpt reconstructed as a projection. */ /** Opaque host-only current raw/projection/converter token, never client evidence. */ evidenceSourceSnapshotKey?: (link: EvidenceLinkV1) => string | undefined; evidenceSourceRead?: (by: PeerId, link: EvidenceLinkV1, current: () => boolean, mode?: { privacyReadOnly: true }) => Promise; /** Fresh registered metadata for bounded, ephemeral origin grouping; no converter or model call. */ evidenceSourceMeta?: (id: string) => SourceMeta | undefined; /** Host-only fixture clock; never read from model input or project configuration. */ studyNow?: () => number; /** Host-only reader for this project's check-runner receipts; record inputs never supply a receipt. */ experimentCheck?: (run: string) => Promise; /** Fresh trusted machine-local runner registrations. A source-trust failure refuses new receipts. */ researchRunners?: () => unknown; /** Reviewer choice from recorded review outcomes (issue #35); off unless the project config turns it on. */ review?: { adaptive: boolean; min_reviews: number; pool?: readonly string[]; rerotate?: boolean; same_family?: "fallback" | "never"; gate?: ReviewGate; unknown_quota?: ReviewUnknownQuota; max_minutes?: number }; reviewBudget?: () => Pick; /** Peers whose recent deliveries all failed, with the reason (issue #89); routing skips them. */ capabilities?: () => Record; /** #1115: the hub makes, commits and clears the task worktree of a hub-sandboxed peer. Absent: such a peer keeps the #1081 refusal. */ taskWorktree?: TaskWorktreePort; repository?: string; offerRead?: (peer: PeerId, envelopeId: string) => boolean; offerPullOnly?: (peer: PeerId) => boolean; cancellationHeld?: () => boolean; stallNotice?: (stall: TaskStall) => void; failing?: () => Record; /** Peers whose queue a needs_review delivery holds, with the hold detail (issue #90); routing explains the hold, never rejects. */ held?: () => Record; /** Closed host facts only; approval text and quota reasons never enter the grooming projection. */ plannerBlocks?: () => Record; /** Roles from `.agenthub/config.json` (issue #92): peers with the reviewer role join the reviewer candidates. */ roles?: Record; /** Optional: name a class for a task proposed without one. `onCampus` says whether the model call stays on campus. */ triage?: { classify: (title: string, detail: string) => Promise; onCampus: () => Promise }; /** #334: natural-language intake. `split` is the hub model's one call, `partsSchema` the profile's `hub_backlog_split` parts schema, `sourceKnown` the source registry. */ intake?: { split: (system: string, user: string, opts: { campusOnly: boolean }) => Promise; partsSchema: () => unknown; sourceKnown: (id: string) => boolean }; /** The PII screen (issue #198): a closed verdict from a model on this machine or on campus, `unknown` on any failure. */ piiScreen?: (text: string) => Promise; /** Each screen verdict, for the record: item, label, source and category, never the text. */ recordScreen?: (record: ScreenRecord) => void; /** Turn-free coordination (issue #107): configured and no PII task open. Asked at each use. */ turnFree?: () => boolean; /** Coordination preference captured for each newly created task; existing rows keep their initial mode. */ coordination?: () => boolean; /** Whether a peer's context path for facts is verified in its current session (issue #108). */ capable?: (peer: PeerId) => boolean; /** Whether `peer` is between native turns now (issue #107): Codex not busy, Claude stopped since its last tool call. */ idle?: (peer: PeerId) => boolean; /** One hash over these project files as they are now: an integration target (issue #107). */ treeHash?: (paths: string[], windows: { peer: PeerId; since: number; until?: number }[]) => string; /** The facts due for a peer, offered with an integration request; acknowledged by its next done. */ integrationFacts?: (peer: PeerId) => { id: string; text: string } | undefined; ackFacts?: (peer: PeerId, id: string) => void; /** Whether a peer has been shown every change to its files. */ factsCurrent?: (peer: PeerId) => boolean; /** * A peer's split profile now (issue #109): the hub's version, its agent's and the hook profile. Each hand-over is * tagged with it, and only records with a peer's current profile are its observations. Undefined while unknown. */ splitProfile?: (peer: PeerId) => string | undefined; /** * A shadow split prediction, for the record (issue #109): `routing` when routing chose the owner of a task that * overlaps another owner's task not started yet (what calibration reads), `cohort` when an overlap formed a cohort. */ recordSplit?: (task: number, prediction: SplitPrediction, where: "routing" | "cohort") => void; /** A cohort formed, changed or was lifted (issue #107), for the record: the benchmark's treatment check reads it. */ recordCohort?: (cohort: { id: number; event: "formed" | "joined" | "lifted"; silent: boolean; tasks: number[]; owners: PeerId[] }) => void; sweep?: TaskSweepConfig; /** #798 D1: the project's declared submodule paths, project-relative. Absent: none are known, so no notice. */ submodules?: () => string[]; /** Shutdown or coordinator work (recovery) holds task sweeps, and a guarded merge at its dispatch (#491). */ sweepHeld?: () => boolean; /** Consecutive changes_requested verdicts that move a task to another peer (`tasks.escalate_after`, #488). */ escalateAfter?: () => number; /** #489 H1: current host configuration, read at each planner-notice flush; no task/request override. */ groomFyiWindowMin?: () => number; /** #489 H2: current host configuration, read at each use (no cache, no task/request override); absent is the constant each replaces. */ demoteAt?: () => number; demotionHalfLifeH?: () => number; contradictionWindowDays?: () => number; rescreenMax?: () => number; splitMinObservations?: () => number; splitMaxFailureShare?: () => number; } /** The `tasks.escalate_after` default (#488): the third consecutive changes_requested escalates. */ export const ESCALATE_AFTER = 3; // Demotion (issue #36): a failure counts half after a day. A peer is demoted for a class once its decayed failures // reach 1.5 (two within about half a day, three within two days) and outweigh its decayed successes there. // #489 H2: `tasks.demotion_half_life_h` and `tasks.demote_at` set these; unset they are exactly the constants below (pinned in test/operational-settings.test.ts). export const DEMOTION_HALF_LIFE_MS = 24 * 3_600_000; export const DEMOTE_AT = 1.5; /** An approval counts as contradicted when work on the same places fails within this window (issue #35); `tasks.contradiction_window_days` sets it. */ export const CONTRADICTION_WINDOW_MS = 7 * 86_400_000; const OPEN: Task["state"][] = ["proposed", "in_progress", "changes_requested"]; const QUEUE_PRESSURE_CODES: readonly QueueBackpressureCode[] = ["queue-count", "queue-age", "queue-age-unknown"]; const isQueuePressureCode = (code: string): code is QueueBackpressureCode => (QUEUE_PRESSURE_CODES as readonly string[]).includes(code); const QUEUE_RECHECK_PAGE = 32; interface QueuePressurePass { ownerAfter: number; reviewAfter: number; ownerDone: boolean; reviewDone: boolean; retained: boolean; generation: number } /** Board events that leave a task where its completion check found it; any other event means it moved on meanwhile. */ const QUIET_EVENTS = new Set(["answer", "reviewer changed", "idle sweep", "memory reference started"]); QUIET_EVENTS.add("ready held"); // #655: the hub's note that a ready task waits for its reserved owner's WIP slot. QUIET_EVENTS.add("plan observed"); // Host observation does not move the task or replace completion intent. QUIET_EVENTS.add("planner changed"); // Planning authority does not move the execution owner or revoke its handoff. QUIET_EVENTS.add("claim verdict"); // #901: a person's bookkeeping on a plan claim moves nothing, so it must not turn a running check into "check finished late". QUIET_EVENTS.add("invocation"); QUIET_EVENTS.add("check run passed"); // Isolated check bookkeeping does not invalidate an in-flight completion check. QUIET_EVENTS.add("check run failed"); QUIET_EVENTS.add("wait recorded"); // #1454: a recorded wait moves nothing; it only suspends the idle-owner ladder, so it must not turn a running check into "check finished late". QUIET_EVENTS.add("shell branch bound"); // #880: the hub's host-observed branch binding (#845) is bookkeeping; it neither moves nor settles the task. /** The records of the `done (checking)` entry a passed check now completes: what the owner delivered then (#509a). */ const latestPendingDeliverables = (task: Task): DeliverableRecord[] | undefined => { const checking = task.history.findLastIndex(entry => entry.event === "done (checking)"); return checking >= 0 && !task.history.slice(checking + 1).some(entry => entry.event === "done") ? task.history[checking]!.deliverables : undefined; }; /** * Thrown when an assignment's board write is saved but a publish or notify after it failed (#297): the move is * fact, the delivery is unconfirmed. Callers decide by this type, never by comparing owners or reading history. * It stays a plain Error subclass, so the preEffect rule and the #231 ready-offer contract are unchanged. * `task` and `cause` are non-enumerable: a PII task's title and detail must not reach a JSON.stringify of the error. */ export class AssignmentUndeliveredError extends Error { /** The task as the board has it after the write. */ declare readonly task: Task; declare readonly cause: unknown; constructor(task: Task, cause: unknown) { super(`task #${task.id}: the assignment to ${task.owner} is saved, but its delivery is not confirmed: ${cause instanceof Error ? cause.message : String(cause)}`); this.name = "AssignmentUndeliveredError"; Object.defineProperty(this, "task", { value: task, enumerable: false }); Object.defineProperty(this, "cause", { value: cause, enumerable: false }); } } /** A later task-flow event won before the assignment could be published, so the stale envelope is suppressed. */ export class AssignmentSupersededError extends Error { constructor(task: Task) { super(`task #${task.id}: assignment was superseded before publication`); this.name = "AssignmentSupersededError"; } } /** A project path as one spelling (#67): no leading `./`, no repeated or trailing `/`; the root is `.`. */ export const normPath = (p: string) => p.replace(/^(\.\/)+/, "").replace(/\/{2,}/g, "/").replace(/\/+$/, "") || "."; /** Same path, or one is a directory of the other; the project root (`.`) holds everything. */ export const samePlace = (a: string, b: string) => { const [x, y] = [normPath(a), normPath(b)]; return x === "." || y === "." || x === y || x.startsWith(`${y}/`) || y.startsWith(`${x}/`); }; /** Events that hand a task to an owner (or take it away); newer history records that owner on them (#67). */ export const OWNERSHIP_EVENTS = new Set(["assigned", "escalated", "reassigned", "unassigned"]); /** The note on an accept recorded by the done call itself: its stages are unknown to the split prediction (issue #109). */ const WITH_DONE = "with its done"; /** How many times a task changed hands: a cohort member's generation (issue #107). */ const ownerGen = (t: Task) => t.history.filter((h) => OWNERSHIP_EVENTS.has(h.event)).length; /** One hand-over of a task to an owner: a task handed back to a peer that had it before is a new one (#115). */ const handOver = (t: Task, owner: PeerId) => `${t.id}@${owner}#${ownerGen(t)}`; /** When the task was handed to its current owner (its creation, if it never changed hands). */ const handedAt = (t: Task) => [...t.history].reverse().find((h) => OWNERSHIP_EVENTS.has(h.event) && h.event !== "unassigned")?.at ?? t.history[0]?.at ?? Date.now(); /** One line of model-written text: whitespace (newlines included) collapses, so it can never start a forged log line. */ const text = (v: unknown) => (typeof v === "string" && v.trim() ? v.replace(/\s+/g, " ").trim().slice(0, 300) : undefined); /** A list of short strings; a lone string counts as a list of one. */ const textList = (v: unknown) => (Array.isArray(v) ? v : typeof v === "string" ? [v] : []).map(text).filter((p): p is string => !!p).slice(0, 50); const fields = (input: unknown) => (input && typeof input === "object" && !Array.isArray(input) ? input : {}) as Record; /** Tool callers are models: inputSchema is not enforced on the way in, so refs are normalized before they reach the board. */ function cleanRefs(input: unknown): TaskRefs { const r = fields(input); const paths = [...new Set(textList(r.paths).map(normPath))]; const out: TaskRefs = {}; for (const k of ["repo", "branch", "commit"] as const) if (text(r[k])) out[k] = text(r[k])!; if (paths.length) out.paths = paths; return out; } /** Acceptance may correct repository metadata, never file intent or work evidence. */ function acceptRefs(input: unknown): TaskRefs | undefined { if (input == null) return undefined; if (typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => key !== "repo")) throw new PreEffectToolRefusal("accept refs may contain only repo"); const raw = input as Record; if (!Object.hasOwn(raw, "repo")) return undefined; if (typeof raw.repo !== "string" || !raw.repo.trim() || raw.repo.length > 300) throw new PreEffectToolRefusal("accept refs.repo must be a bounded repository slug or path"); return { repo: text(raw.repo)! }; } /** Normalize plan intent at the boundary; lifecycle-off ignores the additive cold-plan fields. */ function cleanPlan(input: unknown, profile: ProfileSelection = "dev", lifecycle = false): TaskPlan { const r = fields(input); const evidence: Pick = {}; for (const key of ["proof", "risks"] as const) { const value = r[key]; if (value === undefined) continue; if (!Array.isArray(value) || value.length > 32 || value.some(item => typeof item !== "string" || item.length > 512)) throw new PreEffectToolRefusal(`plan.${key}: expected at most 32 strings of at most 512 characters`); const items = value.map(item => item.replace(/\s+/g, " ").trim()).filter(Boolean); if (items.length) evidence[key] = items; } const intent: import("./board.ts").ColdPlanIntent = {}; if (lifecycle) { if (r.base !== undefined) { if (typeof r.base !== "string" || !/^[a-f0-9]{40}$/.test(r.base)) throw new PreEffectToolRefusal("plan.base: expected a full lowercase commit SHA"); intent.base = r.base; } for (const key of ["out_of_scope", "stop_if"] as const) { const value = r[key]; if (value === undefined) continue; if (!Array.isArray(value) || value.length > 32 || value.some(item => typeof item !== "string" || item.length > 512)) throw new PreEffectToolRefusal(`plan.${key}: expected at most 32 strings of at most 512 characters`); const items = value.map(item => item.replace(/\s+/g, " ").trim()).filter(Boolean); if (items.length) intent[key] = [...new Set(key === "out_of_scope" ? items.map(normPath) : items)]; } if (r.steps !== undefined) { if (!Array.isArray(r.steps) || r.steps.length > 32) throw new PreEffectToolRefusal("plan.steps: expected at most 32 steps"); intent.steps = r.steps.map(raw => { const row = fields(raw); if (!raw || typeof raw !== "object" || Array.isArray(raw) || Object.keys(row).some(key => key !== "description" && key !== "verify") || typeof row.description !== "string" || !row.description.trim() || row.description.length > 512 || row.verify !== undefined && (typeof row.verify !== "string" || !row.verify.trim() || row.verify.length > 512)) throw new PreEffectToolRefusal("plan.steps: each step needs a bounded description and optional verify command and expected result"); return { description: row.description.replace(/\s+/g, " ").trim(), ...(typeof row.verify === "string" ? { verify: row.verify.replace(/\s+/g, " ").trim() } : {}) }; }); } } let scope: CostPlan; try { scope = cleanCostPlan(r); } catch (error) { throw new PreEffectToolRefusal(error instanceof CostScopeError ? error.message : "invalid review or CI cost scope"); } return { ...Object.fromEntries((profileData(profile).plan_keys as (keyof TaskPlan)[]).map((k) => [k, k === "paths" ? [...new Set(textList(r[k]).map(normPath))] : textList(r[k])] as const).filter(([, v]) => v.length)), ...evidence, ...scope, ...intent }; } /** A plan as one line for other owners; the whole plan is on the board. */ const planText = (plan: TaskPlan = {}) => [ ...ALL_PLAN_KEYS.filter((k) => plan[k]?.length).map((k) => `${k.replace("_", " ")}: ${plan[k]!.join("; ")}`), ...(plan.base ? [`base: ${plan.base}`] : []), ...(["out_of_scope", "stop_if"] as const).filter(key => plan[key]?.length).map(key => `${key}: ${plan[key]!.join("; ")}`), ...(plan.steps?.length ? [`steps: ${plan.steps.map(step => `${step.description}${step.verify ? `; verify: ${step.verify}` : ""}`).join("; ")}`] : []), ].join(" | "); /** What the PII screen reads of a task (#198): the text the patterns are checked against. */ const screenText = (t: { title: string; detail: string; plan?: TaskPlan; external?: Task["external"] }) => [t.title, t.detail, planText(t.plan), t.external?.repo, t.external?.url].filter(value => value !== undefined).join("\n"); /** Re-screens of one task whose verdict was unknown, per hub run (#198). */ export const RESCREEN_MAX = 10; /** #758: the planner "board changed" notice. Its body starts with this, so an unsettled copy is found (and replaced) by the prefix. */ const GROOM_NOTICE_PREFIX = "The board changed"; /** #758: a board change that needs no plan review is recorded at most once per planner in this window. */ export const GROOM_FYI_WINDOW_MS = 10 * 60_000; /** * The task flow. Adapters and tools never touch the board: every change comes through here, where assignment, * PII handling, envelopes, briefs and memory notes are decided in one place. */ /** #694: a PR staged at done with the commit or branch it was read for. */ export interface ResearchCampaignReceipt { id: string; parentTaskId: number; revision: number; status: ResearchCampaignStatus; unitCount: number; units: ResearchUnitBinding[] } interface StudyReferences { parent: Task; adopted: Map; reused: Map; private: boolean; key: string } export interface ExperimentReceipt { kind: "protocol" | "attempt" | "event" | "receipt"; protocolHash: string; attemptId?: string; seq?: number; receiptId?: string } export interface ComparisonPlanReceipt { kind: "plan"; planHash: string } export interface ProtocolApprovalReceipt { protocolHash: string; evaluatorHash: string; approvedBy: string; approvedAt: number } export interface ExperimentAttemptView { id: string; protocolHash: string; taskId: number; phase: "development" | "final"; status: ExperimentStatus; private: boolean; protocol: unknown; events: unknown[]; evidence: Record; eventsComplete: boolean; nextEventCursor?: number; campaignRevision: number; approval: "approved" | "unapproved"; postHoc: "unknown" | "predeclared" | "post-hoc"; retryOf?: string; reproducesAttemptId?: string; independentlyReproduced: false; } export interface ExperimentView { attempts: ExperimentAttemptView[]; counts: { all: number; statuses: Record }; nextCursor?: number; comparison?: { planHash: string; baselineAttemptId: string; variantAttemptId: string; approved: boolean; private: boolean; projection: ReturnType | "[pii]" } } interface ExperimentContext { task: Task; campaign: ResearchCampaignRecord; private: boolean; key: string; fence: ExperimentWriteFence } interface CompletionRefresh { revision: number; commit: string; state: "in_review" | "approved" } interface RefileHeadGuard { recorded?: string } interface IdentityLink { repo: string; pr: number; basis: { commit?: string; branch?: string }; managedRevision?: number } const MANAGED_HANDOFF = Symbol("managed worktree handoff"); type ManagedHandoffRefs = TaskRefs & { [MANAGED_HANDOFF]?: { task: number; owner: PeerId; revision: number; commit: string; branch: string; repo?: string; pr?: number } }; /** What one live check of a task's files says as a whole (#317): `unchanged` only when EVERY file measured unchanged. A change outranks a missing file, which outranks one the hub could not read. */ export type DeliverableResult = "changed" | "missing" | "unknown" | "unchanged"; export const deliverableResult = (states: readonly DeliverableStatus["state"][]): DeliverableResult => states.includes("changed") ? "changed" : states.includes("missing") ? "missing" : states.includes("unknown") || !states.length ? "unknown" : "unchanged"; /** One row of `ahub deliverables` and one card's badge (#317): ids, hashes and sizes always; a path only where `publicDeliverables` allows it. */ export interface DeliverableRow { task: number; title: string; taskState: string; state: "delivered" | "approved"; /** True only when the files were measured for this row. Without it `changedSinceReview` is absent: the board alone cannot know. */ checked: boolean; changedSinceReview?: boolean; /** Present only when `checked`: the whole-row reading of the measurement (never `unchanged` while any file is missing or unreadable). */ result?: DeliverableResult; files: { id: string; path?: string; format: string; version?: string; sha256: string; bytes: number; private?: true; state?: DeliverableStatus["state"] }[]; } /** Detect an own anchor field without invoking model-provided accessors or proxy traps. */ function hasReviewAnchorInput(raw: unknown): boolean { if (raw === undefined || !Array.isArray(raw)) return false; if (types.isProxy(raw)) return true; try { if (Object.getPrototypeOf(raw) !== Array.prototype || Object.getOwnPropertySymbols(raw).length || raw.length > 64) return true; const descriptors = Object.getOwnPropertyDescriptors(raw); for (let index = 0; index < raw.length; index++) { const entry = descriptors[String(index)]; if (!entry || !Object.hasOwn(entry, "value") || !entry.enumerable) return true; const item: unknown = entry.value; if (!item || typeof item !== "object") continue; if (types.isProxy(item)) return true; const prototype = Object.getPrototypeOf(item); if (prototype !== Object.prototype && prototype !== null) return true; if (Object.getOwnPropertyDescriptor(item, "anchor")) return true; } return false; } catch { return true; } } interface GuidanceProbeRuntime { id: string; by: PeerId; controller: AbortController; current: () => ProbeAdmissionRecheck; requestedRevision: number; variantId?: string; reservation?: ProbeReservation; promise?: Promise; stopPromise?: Promise; launched: boolean; launchSettled: boolean; stopSettled: boolean; stopKnown: boolean; stopRequested: boolean; watch?: { handle: unknown }; failure?: Error; } export class Tasks { private guidanceProbeStopping = false; private guidanceProbeAdmissions = 0; private readonly guidanceProbeActive = new Map(); private readonly findingPlacements = new WeakMap; placementOnly: boolean }>(); private findingPlacementBinding(task: Task): string { return JSON.stringify([task.id, task.created, this.reviewHead(task), task.refs.paths, task.plan, this.reviewFindingSets(task)]); } private async prepareFindingPlacements(task: Task, refs: TaskRefs | undefined, guard: () => unknown): Promise> { const staged = { ...task, refs: { ...task.refs, ...cleanRefs(refs) } }, placements = new Map(); const findings = findingsForHead(this.reviewFindingSets(staged), this.findingHead(staged)).filter(item => item.anchor && !this.reviewPathPrivate(item.anchor.path) && this.findingTextAllowed(staged, [item])); if (this.isPii(staged) || !findings.length || !this.d.reviewMaterials) return placements; try { const batch = await this.reviewBatch(staged, findings.map(item => item.anchor!)); guard(); if (batch.head === this.reviewHead(staged)) for (const item of findings) placements.set(item.id, this.reviewPlacement(item.anchor!, batch)); } catch { guard(); } // Optional placement failure is unavailable, never invented coordinates. return placements; } private reviewObserverTurn(by: PeerId, task?: number): boolean { try { if (this.d.reviewObserverInput?.(by) === true || this.d.bus.lastDeliveredTo(by).some(isReviewObserverExcluded)) return true; if (task === undefined) return false; return this.d.board.hasReviewObserverScope(by, task) || this.d.bus.hasUnsettledReviewScope(by, task); } catch { return true; } } async reviewCommentPut(by: PeerId, input: unknown, meta?: ActionMeta): Promise { const author = this.reviewPerson(by, meta), check = this.requestCheck(by, () => this.reviewCommentHold()); const fields = this.reviewInput(input, ["task", "id", "revision", "commit", "anchor", "body"]); let taskId: number, id: string, expected: number | undefined, commit: string, anchor: ReviewAnchor, body: string; try { taskId = reviewCommentNumber(fields.task, "task"); id = fields.id === undefined ? `comment-${crypto.randomUUID()}` : reviewCommentId(fields.id); expected = fields.id === undefined ? undefined : reviewCommentNumber(fields.revision, "revision"); if (fields.id === undefined && fields.revision !== undefined) throw new Error("unexpected revision"); } catch { throw new PreEffectToolRefusal("review task, comment id or revision is invalid; refresh the task review and use its current id and revision, or omit both for a new draft"); } try { commit = reviewCommentHead(fields.commit); } catch { throw new PreEffectToolRefusal("review commit must be a current full lowercase SHA; refresh the task review before saving"); } try { anchor = parseReviewAnchor(fields.anchor); } catch (error) { throw new PreEffectToolRefusal(`${reviewAnchorErrorMessage(error)}; refresh the review and recreate the draft`); } try { body = reviewCommentBody(fields.body); } catch { throw new PreEffectToolRefusal("review comment body must be nonempty and at most 2048 UTF-8 bytes; edit the body before saving"); } return this.commentWrite(async () => { check(); const before = this.reviewContext(taskId), rows = this.d.board.reviewComments(taskId, before.task.created), old = rows.find(row => row.thread.id === id); if (expected !== undefined && (!old || old.lifecycle !== "draft" || old.revision !== expected)) throw new PreEffectToolRefusal("review draft changed or was sent; refresh the draft list before editing"); if (old && old.commit !== commit) throw new PreEffectToolRefusal("draft is anchored to an earlier head; delete it and create a new draft against the current task head"); if (expected === undefined && rows.length >= REVIEW_COMMENT_LIMIT) throw new PreEffectToolRefusal("task review already has 64 comments; remove an unused draft before adding another"); const strip = () => { if (this.reviewPathPrivate(anchor.path)) { try { anchor = privateReviewAnchor(anchor); } catch { throw new PreEffectToolRefusal("private review path needs an existing lineRange or structural selector; select a safe anchor before retrying"); } } }; strip(); const privateRecord = this.reviewTaskPrivate(before.task) || this.reviewPathPrivate(anchor.path), batch = privateRecord ? undefined : await this.reviewBatch(before.task, [anchor]); if (batch && batch.head !== commit) throw new PreEffectToolRefusal("review task head moved; delete this draft and recreate it against the current full commit"); if (!privateRecord) { const material = batch!.materials.find(row => row.path === anchor.path && row.side === (anchor.side ?? "head")); if (!material || material.state !== "available") throw new PreEffectToolRefusal("review anchor material is unavailable; refresh the task review and choose a currently available file before saving"); if (anchor.contentHash !== material.contentHash || JSON.stringify(anchor.projection ?? null) !== JSON.stringify(material.projection ?? null)) throw new PreEffectToolRefusal("review anchor content hash or projection differs from the immutable file; refresh the review and recreate the draft on the current material"); } check(); const current = this.reviewContext(taskId); if (current.key !== before.key || this.reviewHead(current.task) !== commit || batch && batch.head !== commit) throw new PreEffectToolRefusal("review task head changed; delete this draft and recreate it against the current head before saving"); strip(); const record: ReviewCommentRecord = { task: taskId, taskCreated: current.task.created, commit, lifecycle: "draft", revision: (old?.revision ?? 0) + 1, private: false, thread: { id, anchor, body, author, at: new Date(this.d.now?.() ?? Date.now()).toISOString() } }; record.private = this.reviewRecordPrivate(current.task, record); check(); const saved = this.d.board.putReviewComment(record, current.fence, expected); return { task: taskId, id, revision: saved.revision, lifecycle: saved.lifecycle }; }); } async reviewCommentDelete(by: PeerId, input: unknown, meta?: ActionMeta): Promise { this.reviewPerson(by, meta); const check = this.requestCheck(by, () => this.reviewCommentHold()), fields = this.reviewInput(input, ["task", "id", "revision"]); let task: number, id: string, revision: number; try { task = reviewCommentNumber(fields.task, "task"); id = reviewCommentId(fields.id); revision = reviewCommentNumber(fields.revision, "revision"); } catch { throw new PreEffectToolRefusal("review delete identity is invalid; refresh the list and use its current id and revision"); } return this.commentWrite(async () => { check(); const context = this.reviewContext(task), record = this.d.board.reviewComments(task, context.task.created).find(row => row.thread.id === id); if (!record || record.lifecycle !== "dismissed" && record.revision !== revision) throw new PreEffectToolRefusal("review comment changed; refresh its current revision before deleting or dismissing"); const result = this.d.board.deleteReviewComment(id, revision, context.fence); return { task, id, revision: result.record.revision, ...(result.deleted ? { deleted: true as const } : { lifecycle: result.record.lifecycle }) }; }); } async reviewCommentList(by: PeerId, input: unknown): Promise<{ task: number; counts: ReviewCommentCounts; comments: ReviewCommentView[]; packages: import("./review-comments.ts").ReviewCommentPackageView[] }> { if (this.commentsStopped) throw new PreEffectToolRefusal("review comments are stopping; reopen the task review after the hub restarts"); this.reviewPerson(by); const fields = this.reviewInput(input, ["task"]), taskId = reviewCommentNumber(fields.task, "task"), before = this.reviewContext(taskId); const counts = this.d.board.reviewCommentCounts(taskId, before.task.created), records = this.d.board.reviewComments(taskId, before.task.created); const packages = this.d.board.reviewCommentPackages(taskId, before.task.created); if (this.reviewTaskPrivate(before.task)) return { task: taskId, counts, comments: [], packages }; const candidates = records.filter(row => !this.reviewRecordPrivate(before.task, row)); if (!candidates.length) return { task: taskId, counts, comments: [], packages }; let batch: ReviewMaterialBatch; try { batch = await this.reviewBatch(before.task, candidates.map(row => row.thread.anchor)); } catch { batch = { head: "", materials: [] }; } if (this.commentsStopped) return { task: taskId, counts, comments: [], packages }; const current = this.reviewContext(taskId); if (current.key !== before.key) throw new PreEffectToolRefusal("review task changed while reading; refresh the task review"); const latest = this.d.board.reviewComments(taskId, current.task.created); if (latest.length !== records.length || records.some(row => !latest.some(fresh => fresh.thread.id === row.thread.id && fresh.revision === row.revision))) throw new PreEffectToolRefusal("review comments changed while reading; refresh the task review"); const comments = candidates.flatMap(record => { const placement = this.reviewPlacement(record.thread.anchor, batch); if (this.reviewRecordPrivate(current.task, record)) return []; if (placement.status === "unavailable") return [{ thread: reviewThreadProjection(record), task: taskId, commit: record.commit, lifecycle: record.lifecycle, revision: record.revision, ...(record.sentAt ? { sentAt: record.sentAt } : {}), placement: { status: "unavailable" } }]; return [{ thread: reviewThreadProjection(record), task: taskId, commit: record.commit, lifecycle: record.lifecycle, revision: record.revision, ...(record.sentAt ? { sentAt: record.sentAt } : {}), placement }]; }); return { task: taskId, counts, comments, packages }; } async reviewCommentSend(by: PeerId, input: unknown, meta?: ActionMeta): Promise<{ task: number; packageId: string; count: number; delivery: "queued" | "unconfirmed" }> { this.reviewPerson(by, meta); const check = this.requestCheck(by, () => this.reviewCommentHold()), fields = this.reviewInput(input, ["task", "ids", "packageId"]), taskId = reviewCommentNumber(fields.task, "task"); if (fields.packageId !== undefined) { if (fields.ids !== undefined) throw new PreEffectToolRefusal("choose either saved packageId or draft ids; refresh the person review and retry one operation"); let packageId: string; try { if (typeof fields.packageId !== "string" || !/^review-[a-f0-9-]{36}$/.test(fields.packageId)) throw new Error(); packageId = fields.packageId; } catch { throw new PreEffectToolRefusal("review package id is invalid; select a saved package from the current person review list"); } return this.commentWrite(async () => { check(); const context = this.reviewContext(taskId), packet = this.d.board.reviewCommentPackage(packageId); if (!packet || packet.task !== taskId || packet.taskCreated !== context.task.created || packet.owner !== context.task.owner) throw new PreEffectToolRefusal("saved review package is unavailable for this task owner; refresh the task review and inspect the existing package history"); if (!packet.body || !packet.envelopeId || !packet.trace || packet.ts === undefined) throw new PreEffectToolRefusal(`saved review package ${packageId} predates recoverable delivery; inspect the owner's queue and sent comments before drafting a new package`); if (!context.task.owner || context.task.owner === USER || context.task.owner === HUB) throw new PreEffectToolRefusal("saved review package has no current agent owner; assign the open task before retrying"); if (isClosedTaskState(context.task.state)) throw new PreEffectToolRefusal("review package cannot be sent because the task is closed; reopen the task review before sending"); const env = { id: packet.envelopeId, trace: packet.trace, hop: 0, from: HUB, to: [packet.owner], kind: "review" as const, priority: "important" as const, body: packet.body, refs: { task: String(taskId), taskRecipient: "owner" as const, reviewPackage: packageId }, ts: packet.ts }; check(); const status = this.d.bus.reviewEnvelopeStatus(env.id); if (status === "unknown") throw new PreEffectToolRefusal("saved review package delivery history is unavailable; inspect ahub queue list --peer " + packet.owner + " and sent comments before retrying"); if (status === "failed" || status === "discarded") throw new PreEffectToolRefusal(`saved review package delivery is ${status}; inspect ahub queue list --peer ${packet.owner} and ahub queue show before retrying`); if (status === "absent") { if (packet.publicationEvidenceVersion !== 1) throw new PreEffectToolRefusal(`saved review package ${packageId} has no retained delivery proof; inspect the owner's queue and sent comments before retrying`); if (packet.visibleIds === undefined) throw new PreEffectToolRefusal("saved review package has no privacy binding; inspect the owner's queue and sent comments, then dismiss or recreate the package"); const records = this.d.board.reviewComments(taskId, context.task.created); if (packet.ids.some(id => records.find(row => row.thread.id === id)?.lifecycle !== "sent")) throw new PreEffectToolRefusal("saved review package comments are no longer all sent; inspect the owner's queue and dismiss or recreate the package"); if (packet.visibleIds.length && (this.reviewTaskPrivate(context.task) || packet.visibleIds.some(id => { const record = records.find(row => row.thread.id === id); return !record || this.reviewRecordPrivate(context.task, record); }))) { throw new PreEffectToolRefusal("saved review package is private under current policy; inspect the owner's queue, dismiss the old comments, and create a new package only after review privacy is clear"); } } try { const targets = this.d.bus.publishReviewEnvelope(env); if (!targets.includes(packet.owner)) throw new Error("owner not queued"); } catch { const current = this.d.bus.reviewEnvelopeStatus(env.id); if (current === "failed" || current === "discarded") throw new PreEffectToolRefusal(`saved review package delivery is ${current}; inspect ahub queue list --peer ${packet.owner} and ahub queue show before retrying`); throw new PreEffectToolRefusal("saved review package delivery history is unavailable or publication failed; inspect ahub queue list --peer " + packet.owner + " and sent comments before retrying"); } this.d.board.markReviewCommentPackageQueued(packageId); return { task: taskId, packageId, count: packet.ids.length, delivery: "queued" }; }); } let ids: string[] | undefined; try { ids = fields.ids === undefined ? undefined : reviewCommentIds(fields.ids); } catch { throw new PreEffectToolRefusal("review send ids are invalid; select current distinct draft ids"); } return this.commentWrite(async () => { check(); const before = this.reviewContext(taskId), owner = before.task.owner; if (!owner || owner === USER || owner === HUB) throw new PreEffectToolRefusal("review package needs an agent owner; assign the task before sending comments"); if (isClosedTaskState(before.task.state)) throw new PreEffectToolRefusal("review comments can only be sent while the task is open; reopen the task review before sending"); const records = this.d.board.reviewComments(taskId, before.task.created), selected = ids === undefined ? records.filter(row => row.lifecycle === "draft") : ids.map(id => records.find(row => row.thread.id === id)); if (!selected.length || selected.some(row => !row || row.lifecycle !== "draft")) throw new PreEffectToolRefusal("review send needs current draft comments; refresh the list and select draft ids"); const drafts = selected as ReviewCommentRecord[], privateTask = this.reviewTaskPrivate(before.task), publicDrafts = drafts.filter(row => !this.reviewRecordPrivate(before.task, row)); const batch = privateTask || !publicDrafts.length ? undefined : await this.reviewBatch(before.task, publicDrafts.map(row => row.thread.anchor)); check(); const current = this.reviewContext(taskId); if (current.key !== before.key) throw new PreEffectToolRefusal("review task or owner changed; refresh the review before sending"); const latest = this.d.board.reviewComments(taskId, current.task.created); if (drafts.some(row => { const fresh = latest.find(value => value.thread.id === row.thread.id); return !fresh || fresh.lifecycle !== "draft" || fresh.revision !== row.revision; })) throw new PreEffectToolRefusal("review drafts changed; refresh the list before sending"); const unavailable = privateTask ? [] : publicDrafts.filter(row => this.reviewPlacement(row.thread.anchor, batch!).status === "unavailable"); if (unavailable.length) throw new PreEffectToolRefusal(`review material is unavailable for ${unavailable.map(row => row.thread.id).join(", ")}; refresh the task review and retry after the anchored file is available`); const packageId = `review-${crypto.randomUUID()}`, envelopeId = crypto.randomUUID(), trace = crypto.randomUUID(), ts = Date.now(); const body = privateTask ? `Task #${taskId}: ${drafts.length} person review comments are kept on the board; private text is withheld.` : [`Person review comments for task #${taskId} (${drafts.length}). Address these comments; report resolved ids in hub_task_done.`, ...drafts.map(row => { if (this.reviewRecordPrivate(current.task, row)) return renderReviewComment(row, { status: "unavailable" }, false); return renderReviewComment(row, this.reviewPlacement(row.thread.anchor, batch!), true); })].join("\n\n"); if (Buffer.byteLength(body, "utf8") > REVIEW_PACKAGE_BYTES) throw new PreEffectToolRefusal("review package exceeds 12000 presentation bytes; select fewer ids before sending"); let packageHead: string; try { packageHead = reviewCommentHead(batch?.head ?? this.reviewHead(current.task)); } catch { throw new PreEffectToolRefusal("review package has no current immutable head; refresh the task review before sending"); } check(); this.d.board.sendReviewComments(drafts, { id: packageId, task: taskId, taskCreated: current.task.created, ids: drafts.map(row => row.thread.id), visibleIds: privateTask ? [] : publicDrafts.map(row => row.thread.id), owner, head: packageHead, at: new Date(this.d.now?.() ?? Date.now()).toISOString(), body, envelopeId, trace, ts, delivery: "unconfirmed", publicationEvidenceVersion: 1 }, current.fence); let delivery: "queued" | "unconfirmed" = "unconfirmed"; this.releaseNotice(`task #${taskId}: review package ${packageId} publication unconfirmed; inspect ahub queue list --peer ${owner} before any retry`, () => { try { const targets = this.d.bus.publishResult({ id: envelopeId, trace, hop: 0, from: HUB, to: [owner], kind: "review", priority: "important", body, refs: { task: String(taskId), taskRecipient: "owner", reviewPackage: packageId }, ts }); if (!targets.targets.includes(owner)) throw new Error("not queued"); this.d.board.markReviewCommentPackageQueued(packageId); delivery = "queued"; } catch { throw new Error("publication may be unconfirmed; inspect the saved queue before any explicit retry"); } }); return { task: taskId, packageId, count: drafts.length, delivery }; }); } private commentWrites = 0; private commentsStopped = false; private readonly commentDrain = new Set<() => void>(); reviewCommentsPending = (): number => this.commentWrites; async stopReviewComments(): Promise { this.commentsStopped = true; if (this.commentWrites) await new Promise(resolve => this.commentDrain.add(resolve)); } private reviewCommentHold(): string | undefined { try { if (this.commentsStopped || this.d.cancellationHeld?.() || this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) return "review comment writes are held; wait for recovery or shutdown to settle before retrying"; } catch { return "review comment admission is unavailable; inspect ahub status before retrying"; } return undefined; } private async commentWrite(write: () => Promise): Promise { this.commentWrites++; try { return await write(); } finally { if (--this.commentWrites === 0) { for (const resolve of this.commentDrain) resolve(); this.commentDrain.clear(); } } } private reviewPerson(by: PeerId, meta?: ActionMeta): string { if (by !== USER) throw new PreEffectToolRefusal("only the console person may change review comments; use the person's task review surface"); try { return reviewCommentAuthor(meta); } catch { throw new PreEffectToolRefusal("verified person identity is unavailable; reopen the authenticated console review before retrying"); } } private reviewTaskPrivate(task: Task): boolean { try { return task.signals.includes("pii") || task.signals.includes("pii_path") || this.isPii(task); } catch { return true; } } private reviewPathPrivate(path: string): boolean { try { return isDenied(path, this.d.deny) || matchesPolicy(this.d.cwd, path, this.d.piiPaths ?? [], true) || this.publicMetadataText(path) !== true; } catch { return true; } } private reviewRecordPrivate(task: Task, record: ReviewCommentRecord): boolean { try { return record.private || this.reviewTaskPrivate(task) || this.reviewPathPrivate(record.thread.anchor.path) || this.publicMetadataText(JSON.stringify(record.thread)) !== true; } catch { return true; } } private reviewContext(id: unknown): { task: Task; fence: ReviewCommentFence; key: string } { const task = this.need(id, false, true, true), fence: ReviewCommentFence = { task: task.id, taskCreated: task.created, flow: task.history.length, owner: task.owner, ...(this.reviewHead(task) ? { head: this.reviewHead(task) } : {}) }; return { task, fence, key: JSON.stringify([fence, this.reviewTaskPrivate(task)]) }; } private reviewInput(input: unknown, keys: readonly string[]): Record { try { return reviewCommentFields(input, keys); } catch { throw new PreEffectToolRefusal("review comment input is invalid; use only the operation's current task, ids, revision and bounded comment fields"); } } private async reviewBatch(task: Task, anchors: readonly ReviewAnchor[]): Promise { if (!this.d.reviewMaterials) throw new PreEffectToolRefusal("review material reader is unavailable; reopen the task review with the current hub before retrying"); const requests = [...new Map(anchors.map(anchor => [JSON.stringify([anchor.path, anchor.side ?? "head"]), { path: anchor.path, ...(anchor.side ? { side: anchor.side } : {}) }])).values()]; try { const batch = await this.d.reviewMaterials(task, requests); reviewCommentHead(batch.head); return batch; } catch { throw new PreEffectToolRefusal("review material or immutable head is unavailable; refresh the task review before retrying"); } } private reviewPlacement(anchor: ReviewAnchor, batch: ReviewMaterialBatch): ReviewAnchorStatus { const material = batch.materials.find(row => row.path === anchor.path && row.side === (anchor.side ?? "head")); if (!material) return { status: "unavailable" }; try { return anchorStatus(anchor, material); } catch { return { status: "unavailable" }; } } private reviewCommentResolve(by: PeerId, task: Task, input: unknown): string[] | undefined { if (input === undefined) return undefined; try { const ids = reviewCommentIds(input); if (ids.length && by !== task.owner) throw new Error("not owner"); this.d.board.reviewCommentResolution(task, ids); return ids; } catch { throw new PreEffectToolRefusal("comment resolution requires the task owner and sent comment ids; refresh the task review before hub_task_done"); } } private readonly planReviewRequests = new Map(); private readonly repositories: TaskRepositories; private readonly incomingBacklog = new Set(); /** One accept attempt per (answer, part), so two concurrent accepts of one part make one draft (#1480 R2 part 2). */ private readonly decompositionAccepts = new Map>(); /** One apply per milestone while it creates issues, so a retried call cannot POST every planned issue twice (#1480 R2 part 3). */ private readonly roadmapPublishes = new Set(); private readonly plannerBacklog = new Map>(); private readonly plannerBlockedQueue = new Map(); private readonly knownPlanners = new Set(); /** * #758: what the planner board-changed notice has read of the board. `revision` is the board status revision last scanned, `lengths` each task's * history length at that scan (so only entries added since are read), `pending` what each planner has not yet been told (`review`: a planning * revision or dependency change of a card it plans; `other`: a state move, review or assignment) and `sent` when it was last told. * ponytail: a scan lists the whole board once per status revision (at most one per flush); the upgrade is an indexed history read. */ private readonly groomScan = { revision: -1, lengths: new Map(), deps: new Map(), pending: new Map(), sent: new Map() }; /** Turn-free cohorts (issue #107): who works without messages, and who integrates. */ readonly cohorts: Cohorts; private readonly coordinationModes = new Map(); private sweepConfig: TaskSweepConfig; private readonly noWriteTurns = new NoWriteTurns(); private sweeping = false; /** #785 P1b: one bounded CI watcher per exact PR head, and the reviews the hub held as premature, by task id. */ private readonly ciWatchers: CiWatchers; private readonly heldReviews = new Map(); private readonly autoPullAttached = new Set(); constructor(private readonly d: TasksDeps) { this.ciWatchers = new CiWatchers({ ...d.ciWatch, poll: watch => pollCi(watch, watch.head, d.sdlc ? requiredChecksFor(d.sdlc.config(), watch.repo) : [], d.sdlc?.gh ?? sdlcGh), current: watch => this.ciWatchCurrent(watch), finish: (watch, outcome) => this.ciCompleted(watch, outcome), }); d.board.trackPlanRevisions = () => (d.sdlc?.config().mode ?? "off") !== "off"; this.repositories = new TaskRepositories(d.cwd, d.repository); d.board.proposalPlanner = task => this.proposalPlanner(task); for (const task of d.board.list()) this.warmRepository(task); if (d.coordination) { const mode = d.coordination(); for (const task of d.board.list()) this.coordinationModes.set(task.id, mode); } const backlog = d.board.list("backlog"); for (const [peer, roles] of Object.entries(d.roles ?? {})) { if (!roles.includes("planner")) continue; this.knownPlanners.add(peer); const queued = d.bus.queuedBacklogIds(peer); this.addPlannerBacklog(peer, backlog.filter(task => !queued.has(task.id)).map(task => task.id)); } this.sweepConfig = taskSweepConfig(d.sweep); this.cohorts = new Cohorts({ silence: (owners) => this.turnFree() && owners.every((p) => p !== USER && p !== HUB && (this.d.capable?.(p) ?? false)), idle: (peer) => this.d.idle?.(peer) ?? false, }); // What the on-prem worker says about a PII task is private on the bus (console tail and log show a stub), so the // board keeps the text: `ahub task show ` is where the console user reads it, a refusal included. d.bus.onPeerAdded = peer => { this.autoPullAttached.delete(peer); if (d.bus.stateOf(peer) === "idle") this.autoPullForAttachment(peer); }; d.bus.tap((e) => { if (e.t === "state" && e.state === "offline") { this.autoPullAttached.delete(e.peer); this.capacityBackoff.delete(e.peer); } // #1626 A2: the back-off ends at the peer's next idle state, and that idle is a trigger to offer it work (B). if (e.t === "state" && e.state === "idle" && this.capacityBackoff.delete(e.peer) && this.d.autoPull?.() === true && (this.topReservedReady(e.peer, undefined, true) || this.fillPick(e.peer))) this.queueAutoPulls(new Set([e.peer]), "idle after a capacity decline"); if (e.t === "state" && e.state === "idle" && !this.autoPullAttached.has(e.peer) && this.d.autoPull?.() === true) { this.autoPullForAttachment(e.peer); } if (e.t === "overflow" && e.env.from === HUB && e.env.kind === "task" && Array.isArray(e.env.refs?.backlog)) { const ids = e.env.refs.backlog; if (ids.length <= 64 && ids.every(id => Number.isSafeInteger(id) && id > 0)) this.addPlannerBacklog(e.peer, ids); this.plannerBlockedQueue.set(e.peer, JSON.stringify(d.bus.queueIds(e.peer))); } // A turn that ends takes its hand-overs with it: busy later is another turn (#115). The adapter's own state, since a // pause shows as `paused` while the turn goes on. if (e.t === "state" && d.bus.peers.get(e.peer)?.state !== "busy") for (const [k, p] of this.sent) if (p === e.peer) this.sent.delete(k); if (e.t !== "envelope" || !e.env.private || e.env.from === HUB || !e.env.refs?.task) return; try { d.board.update(Number(e.env.refs.task), e.env.from, "answer", {}, e.env.body.slice(0, 4000)); } catch { // the task is gone: nothing to attach the answer to } }); } private autoPullForAttachment(peer: PeerId): void { if (this.autoPullAttached.has(peer) || this.d.autoPull?.() !== true) return; this.autoPullAttached.add(peer); // #1626 B: a ready unowned task also starts a pull, so a reservation is not needed. if (this.topReservedReady(peer, undefined, true) || this.fillPick(peer)) this.queueAutoPulls(new Set([peer]), "peer available"); } isPii = (task: Pick) => task.signals.includes("pii_path") || (task.signals.includes("pii") && this.d.routing().constraints.pii === "local_only"); private signalsFor(task: Pick & { plan?: TaskPlan }, routing = this.d.routing()) { const signals = detectSignals(task, routing, this.d.cwd); const paths = [...(task.refs.paths ?? []), ...(task.plan?.paths ?? []), ...(task.plan?.out_of_scope ?? []), ...(task.plan?.sections ?? []).map(anchor => anchor.split("#")[0]!).filter(Boolean)]; if (paths.some(path => matchesPolicy(this.d.cwd, path, this.d.piiPaths ?? [], true))) { if (!signals.includes("pii")) signals.push("pii"); signals.push("pii_path"); } return signals; } /** `signals.pii_screen = "local"` where the PII constraint applies (issue #198); on without a screener, every verdict is unknown. */ screenOn = (): boolean => { const r = this.d.routing(); return r.signals.pii_screen === "local" && r.constraints.pii === "local_only"; }; /** One bounded screen call. A screener that fails is no verdict, handled as PII (fail closed). */ private requestCheck(by: PeerId, fence?: () => string | undefined): () => void { requireLocalTaskPeer(by); const authority = this.d.requestAuthority?.(by); const check = () => { const reason = authority?.() ?? fence?.(); if (reason) throw new PreEffectToolRefusal(reason); }; check(); return check; } private observerExcluded(by: PeerId): boolean { try { return this.d.observerExcludedTurn?.(by) === true; } catch { return true; } } private async screenCall(text: string): Promise { return (await this.d.piiScreen?.(text).catch(() => undefined)) ?? { label: "unknown", miss: "failed", ms: 0 }; } private recordScreen(task: number | undefined, item: ScreenItem, v: PiiVerdict | undefined, inherited = false): void { const record: ScreenRecord = inherited ? { item, label: "pii", source: "inherited" } : !v ? { item, label: "pii", source: "regex" } : { item, label: v.label === "clear" ? "clear" : "pii", source: v.label === "unknown" ? "unknown" : "screen", ...(v.category ? { category: v.category } : {}), ...(v.miss ? { miss: v.miss } : {}), ms: v.ms }; try { this.d.recordScreen?.({ ...(task === undefined ? {} : { task }), ...record }); } catch { /* telemetry only */ } } /** * Whether the model screen withholds free text about an ordinary task (issue #198): it is on and its verdict is not * `clear`. Text that matches a pattern needs no call (the #69 checks withhold it; only the record says so), and a PII * task's text is private. Tool callers are models: anything but a string is not screened, so `off` stays as it was. */ private async withholds(item: ScreenItem, text: unknown, task?: Task): Promise { if (typeof text !== "string" || !text.trim() || !this.screenOn() || (task && this.isPii(task))) return false; if (!this.nameable(text)) return (this.recordScreen(task?.id, item, undefined), false); const v = await this.screenCall(text); this.recordScreen(task?.id, item, v); return v.label !== "clear"; } /** Why free text is withheld: the pattern check first, as #69 words it. */ private whyWithheld = (text: string) => (this.nameable(text) ? "the PII screen did not clear it" : "it matches a PII pattern"); /** Task-owned, default-off between-turn ladder. Persist before sending so restart cannot repeat a step. */ async sweep(now = Date.now()): Promise<{ task: number; finding: SweepRecord }[]> { const recorded: { task: number; finding: SweepRecord }[] = []; const config = this.sweepConfig; if (!config.enabled || this.sweeping || this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) return recorded; this.sweeping = true; try { for (const task of this.d.board.list()) { if (this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) break; if (!task.owner && this.personUnassigned(task)) continue; const questionWait = task.state === "in_progress" && task.owner ? this.d.ownerQuestionWait?.(task.id, task.owner) : undefined; const finding = nextSweep(task, config, now, this.waitsFor(task).length === 0 && !plannedStartPending(task, now), questionWait); if (!finding || this.waitsFor(task).length || this.isChecking(task.id) || this.silentFor(task.id)) continue; if (finding.kind === "ready-unassigned") { this.d.board.update(task.id, HUB, "idle sweep", {}, undefined, { sweep: finding }); recorded.push({ task: task.id, finding }); const planners = this.taskPlanner(task).filter(peer => this.d.bus.isRostered(peer)); const text = `Task #${task.id}: ready-unassigned, idle escalation ${finding.step}/3.`; if (finding.step === 1 || finding.step === 2) { if (finding.step === 2 || !planners.length) this.releaseNotice(text); for (const peer of planners) this.releaseNotice(`task #${task.id}: sweep notice unavailable`, () => this.sweepNotice(task, peer, `${text} Check the board and assign, re-plan or cancel it.`, "planner")); } else { const admission = this.plannerPullRecord(task)?.pull ? this.plannerAssignment(task, true) : assign(task, this.states(), this.d.routing(), { exclude: this.excluded(task), ...this.weights(task.class, task) }); this.releaseNotice(`${text} Owner reassignment suggestion: ${admission.owner ?? "no eligible peer"}.`); if (admission.owner && config.auto_reassign && this.sweepAvailable(admission.owner) && !this.reservedHold(task)) { try { await this.assignOwner(this.d.board.get(task.id)!, HUB, { candidates: [admission.owner], event: "reassigned", reason: "idle", note: "ready-unassigned idle sweep" }); } catch (e) { if (!(e instanceof AssignmentUndeliveredError)) throw e; } } } continue; } const responsible = finding.kind === "review-pending" ? task.reviewer! : task.owner!; if (responsible !== USER && !this.sweepAvailable(responsible)) continue; if (finding.step === 3 && finding.kind !== "review-pending" && config.auto_reassign && this.plannerPullRecord(task)?.pull && !assign(task, this.states(), this.d.routing(), { exclude: [...this.excluded(task), responsible], excludeOwners: this.plannerFull(task), waitsFor: this.waitsFor(task), ...this.weights(task.class, task) }).owner) continue; const title = this.publicTitle(task); const message = `Task ${title}: ${finding.kind}, idle escalation ${finding.step}/3.`; // Only identifiers, kind and step are kept in the ladder event. A crash after this write and before publish // leaves the notice unpublished or uncertain; the durable-delivery journal owns any delivery retries. this.d.board.update(task.id, HUB, "idle sweep", {}, undefined, { sweep: finding }); recorded.push({ task: task.id, finding }); if (finding.step === 1) { this.sweepNotice(task, responsible, `${message} Check its current state with hub_task_list and accept, complete or review your assigned work.`, finding.kind === "review-pending" ? "reviewer" : "owner"); } else if (finding.step === 2) { this.d.notify(message); for (const peer of this.taskPlanner(task)) { if (peer !== responsible && this.sweepAvailable(peer)) this.sweepNotice(task, peer, `${message} The assigned ${finding.kind === "review-pending" ? "reviewer" : "owner"} has not recorded fresh task activity; check the board before coordinating.`, "planner"); } } else { const reviewer = finding.kind === "review-pending"; const a = assign(task, this.states(), this.d.routing(), { exclude: [...this.excluded(task), responsible], excludeOwners: finding.kind !== "review-pending" && this.plannerPullRecord(task)?.pull ? this.plannerFull(task) : [], waitsFor: this.waitsFor(task), ...(reviewer ? { candidates: [], notReviewer: task.owner ?? undefined } : {}), ...this.weights(task.class, task) }); const candidate = reviewer ? a.reviewer : a.owner; this.passedOver(task, a); this.d.notify(`${message} ${reviewer ? "Reviewer" : "Owner"} reassignment suggestion: ${candidate ?? "no eligible peer"}.`); if (!reviewer && candidate && config.auto_reassign && this.sweepAvailable(candidate)) { try { await this.assignOwner(this.d.board.get(task.id)!, HUB, { candidates: [candidate], exclude: [responsible], event: "reassigned", reason: "idle", note: `idle sweep: ${finding.kind}; from ${responsible}` }); } catch (e) { // A saved move whose delivery failed: the console notice was printed where the error was thrown, and // the sweep goes on (#297). if (!(e instanceof AssignmentUndeliveredError)) throw e; } } } } } finally { this.sweeping = false; } return recorded; } /** * #1454: record a bounded wait on an in_progress task, so the idle-owner ladder is suspended until `until` and restarts from it. * Owner, its planner or the person only. The reason is public text: one the privacy screen would withhold is refused on an * ordinary task (the wait is shown in every board view), and kept withheld on a PII task. Every refusal is pre-effect and * names its cause and the next step. Done, decline, return and reassignment end a wait by moving the task (`taskWait`). */ async wait(by: PeerId, input: { id: unknown; until: unknown; reason: unknown }): Promise { requireLocalTaskPeer(by); const refuse = (text: string): never => { throw new PreEffectToolRefusal(text); }; if (!this.sweepConfig.enabled) refuse("a wait suspends the idle sweep and task_sweep is off, so there is nothing to suspend; just keep working, or ask the person to turn on task_sweep.enabled"); const now = this.d.now?.() ?? Date.now(); const until = typeof input.until === "number" ? input.until : typeof input.until === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/.test(input.until.trim()) ? Date.parse(input.until.trim()) : NaN; if (!Number.isSafeInteger(until)) refuse("until must be an absolute time with a zone, for example 2026-11-18T09:00:00+09:00 (or milliseconds since the epoch); resend with that"); if (until <= now) refuse(`until ${new Date(until).toISOString()} is not in the future (now ${new Date(now).toISOString()}); name a later time, or drop the wait and keep working`); if (until > now + TASK_WAIT_MAX_MS) refuse(`until ${new Date(until).toISOString()} is more than 14 days ahead (latest ${new Date(now + TASK_WAIT_MAX_MS).toISOString()}); name an earlier time and record the wait again when it passes`); const reason = typeof input.reason === "string" ? input.reason.trim() : ""; if (!reason) refuse("reason must be a short public sentence naming what the task waits for; resend with it"); if ([...reason].length > TASK_WAIT_REASON_MAX || /[\u0000-\u001f\u007f]/.test(reason)) refuse(`reason must be one line of at most ${TASK_WAIT_REASON_MAX} characters; shorten it and resend`); const validate = (): Task => { const task = this.need(input.id, false, true); if (task.state !== "in_progress") refuse(`task #${task.id} is ${task.state}: a wait applies only to in_progress work; ${task.state === "proposed" ? "accept the task first with hub_task_accept" : "it needs no wait"}`); if (by !== USER && task.owner !== by && !(this.d.roles?.[by]?.includes("planner") && this.taskPlanner(task).includes(by))) refuse(`task #${task.id}: only its owner (${task.owner ?? "none"}), its planner or the console user can record a wait; ask the owner, or hub_send the planner`); if (by !== USER && this.d.privateTurn?.(by) && !this.isPii(task)) refuse("a wait on ordinary work is unavailable during a private turn; record it from a public turn"); return task; }; const before = validate(), revision = before.history.length; const pii = this.isPii(before); const withheld = looksSecret(reason) || this.aboutPrivatePath("", reason, before) || await this.withholds("note", reason, before); if (withheld && !pii) refuse("the reason would be withheld by the privacy screen and a wait is shown in every board view; restate it without names, paths or personal details"); const task = validate(); if (task.history.length !== revision) refuse(`task #${task.id}: it changed while the reason was screened; read it with hub_task_show and record the wait again`); const next = this.d.board.update(task.id, by, "wait recorded", {}, reason, { wait: { until, owner: task.owner! }, ...(pii || withheld ? { withheld: true as const } : {}) }, revision); this.d.notify(`task ${this.publicTitle(next)}: wait recorded by ${by} until ${new Date(until).toISOString()}`); return next; } /** A validated snapshot takes effect on the next sweep, never halfway through one. */ configureSweep(config: TaskSweepConfig): void { this.sweepConfig = taskSweepConfig(config); if (this.sweepConfig.no_writes_turns === 0) { this.noWriteTurns.retain([]); for (const stall of this.d.board.stalls()) if (stall.cause.kind === "no-writes") this.d.board.clearStall(stall.task); } } /** Host-only acceptance binding, shared by owner-turn evidence and bounded native continuations. */ ownerAcceptance(task: Task, first = false): { index: number; at: number } | undefined { if (!task.owner) return undefined; const boundary = task.history.findLastIndex(entry => OWNERSHIP_EVENTS.has(entry.event) || entry.owner !== undefined && entry.owner !== task.owner); const accepted = (entry: Task["history"][number], index: number) => index > boundary && entry.event === "accepted" && (entry.by === task.owner || entry.by === USER); const index = first ? task.history.findIndex(accepted) : task.history.findLastIndex(accepted); return index > boundary && index >= 0 ? { index, at: task.history[index]!.at } : undefined; } /** Captured at native turn start, not supplied by a model. */ ownerTurnTasks(peer: PeerId): { id: number; acceptance: number }[] { requireLocalTaskPeer(peer); return this.d.board.list("in_progress").flatMap(task => { const accepted = task.owner === peer && ["implement", "bulk_edit"].includes(task.class) ? this.ownerAcceptance(task) : undefined; return accepted ? [{ id: task.id, acceptance: accepted.index }] : []; }); } /** Host-only audit: no tool accepts this record and no task state or notification changes. */ recordInvocation(id: number, row: InvocationRow): void { const task = this.d.board.get(id); if (!task) throw new Error("invocation audit task is unavailable"); if (row.task !== id) throw new Error("invocation audit task mismatch"); if (row.outcome === "queued" && (this.isPii(task) || this.d.privateTurn?.(row.caller) || isClosedTaskState(task.state) || task.state === "backlog" || task.owner !== row.caller && task.reviewer !== row.caller)) throw new Error("invocation audit task scope changed"); if (task.history.some(entry => entry.invocation?.id === row.id && entry.invocation.outcome === row.outcome)) return; const { id: invocationId, caller, target, capability, digest, class: sideEffect, approval, argsSha256, outcome } = row; this.d.board.update(id, HUB, "invocation", {}, undefined, { invocation: { id: invocationId, caller, target, capability, digest, class: sideEffect, approval, argsSha256, outcome } }); } recordOwnerTurn(peer: PeerId, bindings: readonly { id: number; acceptance: number }[], changed: boolean | undefined, effect: boolean): void { requireLocalTaskPeer(peer); this.noWriteTurns.retain(this.d.board.list("in_progress").filter(task => ["implement", "bulk_edit"].includes(task.class)).map(task => task.id)); const current = new Map(this.ownerTurnTasks(peer).map(binding => [binding.id, binding.acceptance])); for (const binding of bindings) { if (current.get(binding.id) !== binding.acceptance) continue; const task = this.d.board.get(binding.id)!; const limit = this.sweepConfig.no_writes_turns ?? 2; if (changed !== false || effect || limit === 0) { if (this.d.board.stalls().some(stall => stall.task === task.id && stall.cause.kind === "no-writes")) this.d.board.clearStall(task.id); } const count = this.noWriteTurns.observe({ task: task.id, generation: `${task.created}:${peer}:${binding.acceptance}`, limit, changed, effect }); if (count === undefined) continue; this.reportStall(task, { kind: "no-writes", code: "no-writes", peer, turns: count, acceptance: binding.acceptance }, Date.now(), `Task ${this.publicTitle(task)} stalled: ${count} consecutive owner turns with no writes or task tool effects recorded.`); } } private captureOwnerAcceptance(task: Task): void { try { this.d.ownerAccepted?.(task); } catch { /* advisory capture cannot fail a saved acceptance */ } } /** Host evidence spans the first acceptance after the latest ownership change, including plan revisions. */ ownerWriteAcceptance(task: Task): { index: number; at: number } | undefined { return this.ownerAcceptance(task, true); } private noWritesRecorded(task: Task): boolean { if (!["implement", "bulk_edit"].includes(task.class) || task.refs.branch || this.reviewHead(task) || task.sdlc?.pr) return false; const accepted = this.ownerWriteAcceptance(task); if (!accepted) return false; try { return this.d.ownerWrites?.(task, accepted.at) === false; } catch { return false; } } private sweepAvailable(peer: PeerId): boolean { const bus = this.d.bus; return bus.stateOf(peer) === "idle" && (this.d.idle?.(peer) ?? true) && !peerEntry(this.d.held?.(), peer) && !bus.queueSummary(peer).heldBy && !bus.queued(peer) && !bus.hasInFlight(peer); } private sweepNotice(task: Task, peer: PeerId, body: string, taskRecipient: "owner" | "reviewer" | "planner"): void { if (peer === USER) this.d.notify(body); else this.d.bus.publish(newEnvelope(HUB, body, { to: [peer], kind: "task", refs: { task: String(task.id), taskRecipient } })); } configureExecutionBudget = (config: ExecutionBudgetConfig, meta: { reason?: string; by?: string } = {}): ExecutionBudgetStatus | undefined => { if (!this.d.executionBudget) return undefined; if (config.kind === "task" && (!config.taskId || !this.d.board.get(config.taskId))) throw new Error(`task #${config.taskId ?? "?"} does not exist`); return this.d.executionBudget.configure(config, meta); }; disableExecutionBudget = (id: string): boolean => this.d.executionBudget?.disable(id) ?? false; executionBudgetStatus = (id?: string): ExecutionBudgetStatus | ExecutionBudgetStatus[] | undefined => this.d.executionBudget?.status(id); /** Charge only budgets matching the task actually delivered to this peer, plus active run budgets. */ admitExecution = (taskId: number | undefined, peer: PeerId, unit: ExecutionUnit, amount = 1): ExecutionBudgetDecision[] => this.d.executionBudget?.admitTask(taskId, peer, unit, amount) ?? []; /** A digest may include several tasks. Charge each matching task budget and each run budget once, atomically. */ admitExecutionEnvelopes = (envs: Envelope[], peer: PeerId, unit: ExecutionUnit, amount = 1): ExecutionBudgetDecision[] => this.d.executionBudget?.admitTasks(this.budgetTaskIds(envs), peer, unit, amount) ?? []; /** Whether an execution budget meters this peer's work on these envelopes; admits nothing. */ budgetApplies = (envs: Envelope[], peer: PeerId): boolean => this.d.executionBudget?.applies(this.budgetTaskIds(envs), peer) ?? false; private budgetTaskIds(envs: Envelope[]): number[] { return [...new Set(envs.flatMap((e) => { const value = e.refs?.task; const id = typeof value === "string" ? Number(value) : NaN; return Number.isSafeInteger(id) && id > 0 ? [id] : []; }))]; } /** What peers other than the owner, the console stream and the log may see of a task. */ publicTitle = (task: Task) => (this.isPii(task) ? `#${task.id} [pii]` : `#${task.id} ${task.title}`); private reviewFindingSets(task: Task): ReviewFindingSet[] { return task.history.flatMap(entry => entry.reviewFindings ? [entry.reviewFindings] : []); } private findingHead(task: Task, reviewedHead?: string): string | undefined { return resolveFindingHead(task.sdlc, reviewedHead ? { head: reviewedHead } : undefined, task.refs.commit); } private findingTextAllowed(task: Task, items: readonly ReviewFinding[]): boolean { return this.candidateTextAllowed(JSON.stringify(items), task) && items.every(item => (!item.path || !matchesPolicy(this.d.cwd, item.path, this.d.piiPaths ?? [], true)) && (!item.anchor || !this.reviewPathPrivate(item.anchor.path))); } /** Host-authored proposals contain only cleared IDs, integer task references and fixed instruction targets. */ /** * #736: how many separate pieces of work the tasks are. Tasks that share a PR, a branch in one repository, or a * supersession (a cancelled task names its replacement) are one piece of work, as an approve-as-step follow-up is: a * finding carried between them is the same finding, not a recurrence. */ private workUnits(rows: readonly Task[]): number { const parent = new Map(); const find = (id: number): number => { let at = id; while (parent.has(at)) at = parent.get(at)!; return at; }; const join = (a: number, b: number) => { const x = find(a), y = find(b); if (x !== y) parent.set(x, y); }; const first = new Map(), ids = new Set(rows.map(row => row.id)); for (const row of rows) { // Repository identity comes from the board's own resolver, so aliases match and an outside path never falls back to this project. const prRepo = row.sdlc?.pr ? this.repositories.scope(row.sdlc.repo ? { repo: row.sdlc.repo, paths: row.refs.paths } : row.refs).key : ""; const branchRepo = row.refs.branch ? this.repositories.scope(row.refs).key : ""; for (const key of [prRepo ? `pr ${prRepo}#${row.sdlc!.pr}` : "", branchRepo ? `branch ${branchRepo} ${row.refs.branch}` : ""]) { if (!key) continue; const seen = first.get(key); if (seen === undefined) first.set(key, row.id); else join(row.id, seen); } // superseded_by is free text ("task #73", "#73" or "73"); the first task number in it names the replacement. const next = Number(/#?(\d+)/.exec(row.cancelled?.supersededBy ?? "")?.[1]); if (ids.has(next)) join(row.id, next); } return new Set(rows.map(row => find(row.id))).size; } /** * #514b: the person's view of the recurring-criterion candidates (`ahub learn list`). The person only: a conductor or an agent gets a refusal, never a list. A card that does not parse as the * hub's own is not listed. Ids, counts and the key parts only: the card's text is never echoed, and a PII row is never reached because the cards are already screened when filed. */ learnCandidates(by: PeerId, opts: { all?: boolean } = {}): Record[] { if (by !== USER) throw new PreEffectToolRefusal("ahub learn is a person's command"); const rows: Record[] = []; for (const card of this.d.board.list()) { const parsed = parseCandidateCard(card); if ("refused" in parsed) continue; const open = card.state === "backlog" || card.state === "proposed"; const closed = card.history.findLast(entry => entry.event === "cancelled"); const verdict = learnVerdict(card) ?? (closed ? "closed" : undefined); if (!open && !opts.all) continue; if (!open && !closed) continue; rows.push({ id: card.id, state: card.state, ...parsed, status: open ? "open" : verdict, tasks: this.learnEvidence(parsed).tasks, line: overridesDiff({ ...parsed, tasks: this.learnEvidence(parsed).tasks }).profile_overrides.review_checklist[0] }); } return rows; } /** The distinct tasks that name this criterion unmet on this profile and class in the window, from the board as it is now: the count the written line states is recomputed, never read from the card. */ private learnEvidence(card: { profile: string; class: string; criterion: string }): { tasks: number[] } { const eligible = this.d.board.list().filter(row => this.candidateTextAllowed(`${row.profile ?? ""} ${row.profileClass ?? ""} ${row.class}`, row)); const group = groupUnmetCriteria(eligible, { windowMs: LEARNING_DEFAULTS.windowMs, now: Date.now() }).find(g => g.profile === card.profile && g.class === card.class && g.criterion === card.criterion); return { tasks: group?.tasks ?? [] }; } /** * #514b: what `ahub learn accept` would write for card `id`, or why not. Person only. It reads ONLY the card's key line (`parseCandidateCard`), requires the card to be open, and builds the * line from the board's own evidence with `overridesDiff`: nothing of the card's text is parsed as a value. The daemon adds the line to the stored checklist and writes it through the settings path. */ learnAcceptPlan(by: PeerId, id: unknown): { id: number; profile: string; class: string; criterion: string; line: string; tasks: number } { if (by !== USER) throw new PreEffectToolRefusal("ahub learn accept is a person's command"); const card = this.learnCard(id); const evidence = this.learnEvidence(card); if (!evidence.tasks.length) throw new PreEffectToolRefusal(`no task in the window still names ${card.criterion} unmet on ${card.profile}/${card.class}: nothing to accept; reject the card to close it`); const line = overridesDiff({ ...card, tasks: evidence.tasks }).profile_overrides.review_checklist[0]!; return { id: card.id, profile: card.profile, class: card.class, criterion: card.criterion, line, tasks: evidence.tasks.length }; } /** * #514b: whether `ahub learn accept` already decided this card. Person only. A card the person accepted answers `"accepted"`, so a repeat accept is a no-write success (the plan's idempotency); * a rejected card, a card closed some other way and an open one answer undefined and take the normal path, which refuses the closed ones. */ learnAccepted(by: PeerId, id: unknown): { id: number; profile: string; class: string; criterion: string } | undefined { if (by !== USER) throw new PreEffectToolRefusal("ahub learn accept is a person's command"); if (typeof id !== "number" || !Number.isSafeInteger(id) || id <= 0) return undefined; const task = this.d.board.get(id); if (!task || learnVerdict(task) !== "accepted") return undefined; const parsed = parseCandidateCard(task); return "refused" in parsed ? undefined : { id, ...parsed }; } /** The card, which must be an open candidate the hub filed. */ private learnCard(id: unknown): { id: number; profile: string; class: string; criterion: string } { if (typeof id !== "number" || !Number.isSafeInteger(id) || id <= 0) throw new PreEffectToolRefusal("id must be a positive task number"); const task = this.d.board.get(id); if (!task) throw new PreEffectToolRefusal(`no task #${id}`); const parsed = parseCandidateCard(task); if ("refused" in parsed) throw new PreEffectToolRefusal(`task #${id}: ${parsed.refused}`); if (task.state !== "backlog" && task.state !== "proposed") throw new PreEffectToolRefusal(`task #${id} is already ${task.state === "cancelled" ? "closed" : task.state}`); return { id, ...parsed }; } /** * #514b: closes a candidate card after the person's verdict, through `cancel` (never a direct board write): the row stays, the verdict is in its history, and because the dedupe key is the card's * detail the same criterion is never filed again. `accepted` is recorded only after the write succeeded (the daemon calls this last); a repeat of either verdict is refused by `learnCard`. */ async learnClose(by: PeerId, id: unknown, verdict: "accepted" | "rejected"): Promise { if (by !== USER) throw new PreEffectToolRefusal("ahub learn is a person's command"); const card = this.learnCard(id); return this.cancel(card.id, USER, { reason: verdict === "accepted" ? `${LEARN_ACCEPTED} by the person: its review checklist line was written to config.local.json` : `${LEARN_REJECTED} by the person` }); } /** * #514a: the same recurrence path for recurring UNMET CRITERIA. A criterion id that reviews keep naming unmet on the same profile and class, on at least * `threshold` tasks that are at least two separate pieces of work (`workUnits`), files one backlog card for a person to review, with the `profile_overrides` * fragment as text. Nothing is applied. A PII task and a withheld or private-turn review are never evidence and never named; the card carries ids and counts only. */ private proposeCriterionCandidates(task: Task, by: PeerId, withheld: boolean): void { if (withheld || this.isPii(task) || this.d.privateTurn?.(by) || !task.history.at(-1)?.unmetCriteria?.length) return; const rows = this.d.board.list(); const keys = new Set(rows.filter(row => row.class === "plan" && row.history[0]?.by === HUB) .flatMap(row => row.detail?.split("\n").filter(line => line.startsWith("Criterion candidate key: ")) ?? [])); // Only the rows that may count: candidateTextAllowed refuses a PII row and one whose text the screen refuses, so those are evidence of nothing. const eligible = rows.filter(row => this.candidateTextAllowed(`${row.profile ?? ""} ${row.profileClass ?? ""} ${row.class}`, row)); const named = new Set(task.history.at(-1)!.unmetCriteria); const created: number[] = []; // No await separates the durable dedupe read from creation; concurrent verdicts see the first card. const groups = groupUnmetCriteria(eligible, { windowMs: LEARNING_DEFAULTS.windowMs, now: Date.now() }); const unitsOf = (group: CriterionGroup) => this.workUnits(eligible.filter(row => group.tasks.includes(row.id))); for (const group of selectGroups(groups, { named, threshold: LEARNING_DEFAULTS.threshold, max: LEARNING_DEFAULTS.maxGroups, has: g => keys.has(criterionKey(g)), units: unitsOf })) { const card = candidateCard(group, Math.round(LEARNING_DEFAULTS.windowMs / 86_400_000), unitsOf(group)); const draft = { title: card.title, detail: card.detail, refs: { paths: ["docs/profiles.md"] } }; const signals = this.signalsFor(draft); if (this.isPii({ signals }) || !this.candidateTextAllowed(`${card.title}\n${card.detail}`)) continue; const proposal = this.d.board.propose(HUB, { ...draft, class: "plan", backlog: true, signals }); this.incomingBacklog.add(proposal.id); keys.add(criterionKey(group)); created.push(proposal.id); } for (const id of created) this.releaseNotice(`task #${id}: recurring unmet criterion candidate proposed in the backlog`); } private proposeRecurringFindings(task: Task, by: PeerId, items: readonly ReviewFinding[], withheld: boolean): void { if (withheld || this.isPii(task) || this.d.privateTurn?.(by) || !items.length || !this.findingTextAllowed(task, items)) return; const rows = this.d.board.list(); const keys = new Set(rows.filter(row => row.class === "plan" && row.history[0]?.by === HUB) .flatMap(row => row.detail?.split("\n").filter(line => line.startsWith("Review finding key: ")) ?? [])); const created: number[] = []; // No await separates the durable dedupe read from creation; concurrent verdicts see the first proposal. // #1436: a positional id (N1, F5, nit-1) is review-local, so it never counts toward a cross-task recurrence; a semantic id does. for (const item of items.filter(item => item.disposition !== "false_positive" && !positionalFindingId(item.id))) { const same = (finding: ReviewFinding) => finding.id === item.id && finding.pass === item.pass; const holders = rows.filter(row => { if (this.isPii(row)) return false; const last = row.history.findLast(entry => entry.reviewFindings?.items.some(value => value.id === item.id)); const finding = last?.reviewFindings?.items.find(value => value.id === item.id); // #328: a follow-up that only records an earlier task's finding as fixed never had it; it counts once seen open. // By id alone: a reclassified finding keeps its id (task note); a withheld review is never evidence. const occurred = row.history.some(entry => !entry.withheld && entry.reviewFindings?.items.some(value => value.id === item.id && (value.disposition === "open" || value.disposition === "accepted"))); return !last?.withheld && finding && same(finding) && occurred && finding.disposition !== "false_positive" && this.findingTextAllowed(row, [finding]); }); if (this.workUnits(holders) < 2) continue; const key = `Review finding key: ${item.pass}:${item.id}`; if (keys.has(key)) continue; const title = `Review policy amendment for recurring finding ${item.pass}:${item.id}`; const detail = `${key}\nFinding ${item.pass}:${item.id} recurred on tasks ${holders.slice(0, 8).map(row => `#${row.id}`).join(", ")}. Inspect their review histories and propose an AGENTS.md or relevant docs/agent-notes/ amendment. This backlog card is a proposal, not authorization to edit instruction files.`; const draft = { title, detail, refs: { paths: ["AGENTS.md", "docs/agent-notes/"] } }; const signals = this.signalsFor(draft); if (this.isPii({ signals }) || !this.candidateTextAllowed(`${title}\n${detail}`)) continue; const proposal = this.d.board.propose(HUB, { ...draft, class: "plan", backlog: true, signals }); this.incomingBacklog.add(proposal.id); keys.add(key); created.push(proposal.id); } for (const id of created) this.releaseNotice(`task #${id}: recurring review finding amendment proposed in the backlog`); } /** * #1403 A1, B4: on approval, one backlog card per open Important finding that did not block it. A `needs_validation` security finding gets one read-only `triage` card that names its blocker * (the missing fact); a `pre_existing` one gets one `plan` card. Marker-deduplicated like the recurring-finding cards and held to the same privacy gates. The card carries the task id, the * finding id and pass, and for a hypothesis its blocker: never the boundary fields or the path, which stay on the task's own review history (the repository is public, and the hub opens no issue). */ private proposeFindingFollowUps(task: Task, by: PeerId, withheld: boolean): void { if (withheld || this.isPii(task) || this.d.privateTurn?.(by)) return; const { validation, preExisting } = findingFollowUps(this.reviewFindingSets(task)); if (!validation.length && !preExisting.length) return; const visible = (item: ReviewFinding) => !task.history.some(entry => entry.withheld && entry.reviewFindings?.items.some(value => value.id === item.id)) && this.findingTextAllowed(task, [item]); const keys = new Set(this.d.board.list().filter(row => (row.class === "plan" || row.class === "triage") && row.history[0]?.by === HUB) .flatMap(row => row.detail?.split("\n").filter(line => line.startsWith("Finding follow-up key: ")) ?? [])); const created: number[] = []; // No await separates the durable dedupe read from creation; a repeated approval sees the first card. for (const [kind, items] of [["validation", validation], ["pre-existing", preExisting]] as const) for (const item of items.filter(visible)) { const key = `Finding follow-up key: ${task.id}:${item.pass}:${item.id}:${kind}`; if (keys.has(key)) continue; const ref = `${item.pass}:${item.id}`; const title = kind === "validation" ? `Validate security finding ${ref} from task #${task.id}: read-only triage` : `Pre-existing finding ${ref} from task #${task.id}: plan a fix`; const detail = kind === "validation" ? `${key}\nTask #${task.id} was approved with the important security finding ${ref} still a hypothesis. Blocker, the fact that settles it: ${item.blocker ?? "not recorded"}\nRead-only triage: settle that fact from source or a sandboxed check and report whether the finding is confirmed or false. Do not edit files, branches or the board, and open no issue: the person decides where a security finding is published. Details are in ahub task show ${task.id}.` : `${key}\nTask #${task.id} was approved with the important finding ${ref} marked pre_existing: that change did not introduce it, so it did not block the approval. Backlog card for the planner: decide whether and how to plan a fix. Details are in ahub task show ${task.id}.`; const draft = { title, detail, refs: {} }; const signals = this.signalsFor(draft); if (this.isPii({ signals }) || !this.candidateTextAllowed(`${title}\n${detail}`)) continue; const proposal = this.d.board.propose(HUB, { ...draft, class: kind === "validation" ? "triage" : "plan", backlog: true, signals }); this.incomingBacklog.add(proposal.id); keys.add(key); created.push(proposal.id); } for (const id of created) this.releaseNotice(`task #${id}: finding follow-up proposed in the backlog`); } private publicClaimBindings(task: Task): ReturnType[] | undefined { const claims = task.plan?.claims; if (task.profile !== "research" || task.signals.includes("pii") || task.signals.includes("pii_path") || !Array.isArray(claims) || !claims.length || claims.length > 50 || claims.some(value => typeof value !== "string")) return undefined; try { return claims.map((_claim, index) => taskClaimIdentity(task, index + 1)); } catch { return undefined; } // Optional public metadata never exposes a partial or malformed binding. } /** A task as a cloud peer may see it. */ publicView(task: Task, fullHistory = false): Record { const { title, detail, history, external, cancelled, codeSymbols, ...taskRest } = task; const plannerBinding = history.findLast(h => h.planner === task.planner && h.plannerReason !== undefined); const ownerBinding = history.findLast(h => h.owner === task.owner && ["assigned", "reassigned", "escalated", "backlog pulled"].includes(h.event)); const reviewerBinding = history.findLast(h => ["assigned", "reassigned", "escalated", "done", "reviewer changed", "reviewer unavailable"].includes(h.event)); const reviewComments = this.d.board.reviewCommentCounts(task.id, task.created); const rest = { ...taskRest, ...(Object.values(reviewComments).some(Boolean) ? { reviewComments } : {}), ...(plannerBinding?.plannerReason && ["rotation", "named", "kept", "none"].includes(plannerBinding.plannerReason) ? { plannerReason: plannerBinding.plannerReason } : {}), ...(ownerBinding?.reason && TASK_MOVE_REASONS.includes(ownerBinding.reason) ? { ownerReason: ownerBinding.reason === "manual" && ownerBinding.event === "reassigned" && ownerBinding.by !== HUB ? "named" : ownerBinding.reason } : {}), ...(reviewerBinding?.reviewerReason && ["rotation", "implementer skip", "unavailable skip", "same-family fallback"].includes(reviewerBinding.reviewerReason) ? { reviewerReason: reviewerBinding.reviewerReason } : reviewerBinding?.event === "reviewer changed" && reviewerBinding.reason === "manual" ? { reviewerReason: "named" } : {}), ...(history.some(h => h.by === USER && h.planDeparture) ? { planDepartureAccepted: true } : {}) }; if (this.isPii(task)) return { ...rest, actualDates: actualTaskDates(task), refs: {}, plan: {}, ...(task.sdlc ? { sdlc: { stage: stageDefinition(this.d.sdlc?.config() ?? sdlcConfig(undefined), task.sdlc.stage)?.base ?? "unknown" } } : {}), title: "[pii]", detail: "[pii]" }; if (rest.sdlc?.redFirst && !this.publicMetadataText(JSON.stringify(rest.sdlc.redFirst))) { const { redFirst: _withheld, ...receipt } = rest.sdlc; rest.sdlc = receipt; } const claimBindings = this.publicClaimBindings(task); const currentSpecReport = this.currentSpecReport(task); const currentSpecEntry = currentSpecReport ? history.findLast(entry => entry.event === "done" || entry.event === "done (checking)") : undefined; const screenHistoryText = (text: string, field: string, withheld = false): string => !withheld && this.nameable(text) ? text : `[history ${field} withheld: ${this.whyWithheld(text)}; ahub task show ${task.id}]`; const publicHistory = (fullHistory ? history : history.slice(-5)).map(h => ({ at: h.at, by: h.by, event: h.event, ...(h.instructed && h.instructedPeer && h.instructionReceipt ? { instructed: true, instructedPeer: h.instructedPeer, instructionReceipt: h.instructionReceipt } : {}), ...(h.note === undefined ? {} : { note: screenHistoryText(h.note, "note", h.withheld) }), ...(h.reviewFindings ? { reviewFindings: !h.withheld && this.findingTextAllowed(task, h.reviewFindings.items) ? h.reviewFindings : { ...(h.reviewFindings.head ? { head: h.reviewFindings.head } : {}), tally: findingTally(h.reviewFindings.items), withheld: true } } : {}), ...(h.supersededBy === undefined ? {} : { supersededBy: screenHistoryText(h.supersededBy, "supersession", h.withheld) }), ...(h.invocation ? { invocation: h.invocation } : {}), ...(h.profile === undefined ? {} : { profile: screenHistoryText(h.profile, "profile") }), ...(h.owner === undefined ? {} : { owner: h.owner }), ...(h.planner === undefined ? {} : { planner: h.planner }), ...(h.plannerReason ? { plannerReason: h.plannerReason } : {}), ...(h.planAuthor === undefined ? {} : { planAuthor: h.planAuthor }), ...(h.selfReview ? { selfReview: true } : {}), ...(h.reviewerFamily ? { reviewerFamily: screenHistoryText(h.reviewerFamily, "reviewer family") } : {}), ...(h.reviewerReason ? { reviewerReason: h.reviewerReason } : {}), ...(h.reviewedHead ? { reviewedHead: h.reviewedHead } : {}), ...(h.reviewScope === "code" ? { reviewScope: "code" as const } : {}), ...(h.evidenceOnly ? { evidenceOnly: true as const } : {}), ...(h.unmetCriteria?.length ? { unmetCriteria: h.unmetCriteria } : {}), ...(h.deliverables?.length ? { deliverables: publicDeliverables(h.deliverables, this.nameable) } : {}), ...(h.reviewBlocked ? { reviewBlocked: true } : {}), ...(h.queueReviewHeld ? { queueReviewHeld: true } : {}), ...(h.reviewerQuotaWait ? { reviewerQuotaWait: { since: h.reviewerQuotaWait.since, deadline: h.reviewerQuotaWait.deadline, resetAt: h.reviewerQuotaWait.resetAt } } : {}), ...(h.reviewerFailure ? { reviewerFailure: { peer: screenHistoryText(h.reviewerFailure.peer, "reviewer"), cause: h.reviewerFailure.cause, ...(h.reviewerFailure.reason === "review time cap" ? { reason: "review time cap" as const } : {}), ...(h.reviewerFailure.head ? { head: screenHistoryText(h.reviewerFailure.head, "review head") } : {}) } } : {}), ...(h.planning ? { planning: { revision: h.planning.revision, fields: h.planning.fields, ...(h.planning.split ? { children: h.planning.split.children.map(child => child.id) } : {}) } } : {}), ...(h.reason && TASK_MOVE_REASONS.includes(h.reason) ? { reason: h.reason } : {}), ...(h.sweep ? { sweep: { kind: h.sweep.kind, activity: h.sweep.activity, step: h.sweep.step, at: h.sweep.at } } : {}), ...(h.wait ? { wait: { until: h.wait.until, owner: h.wait.owner } } : {}), ...(h === currentSpecEntry && currentSpecReport ? { specReport: currentSpecReport } : {}), })); const sets = this.reviewFindingSets(task), current = findingsForHead(sets, this.findingHead(task)); const symbolRepository = codeSymbols && this.codeSymbolsRepository(task); const publicSymbols = codeSymbols && symbolRepository ? publicTaskCodeSymbols(codeSymbols, this.reviewHead(task), symbolRepository.key, this.publicMetadataText) : undefined; const handedOff = this.d.board.handoffOrigin(task.id); // #604: where another project's handoff came from; two ids, never text const wait = taskWait(task), waitEntry = wait ? history.findLast(h => h.wait) : undefined; return { ...rest, ...(wait && waitEntry ? { wait: { until: wait.until, by: wait.by, at: wait.at, passed: wait.until <= (this.d.now?.() ?? Date.now()), ...(waitEntry.note ? { reason: screenHistoryText(waitEntry.note, "wait reason", waitEntry.withheld) } : {}) } } : {}), ...(claimBindings ? { claims: claimBindings } : {}), ...(currentSpecReport ? { specReport: currentSpecReport } : {}), ...(approvalBinding(task) ? { approval: approvalBinding(task) } : {}), ...(handedOff ? { handoffOrigin: { projectId: handedOff.projectId, peer: handedOff.peer, ...(handedOff.originTask === null ? {} : { task: handedOff.originTask }) } } : {}), ...(publicSymbols ? { codeSymbols: publicSymbols } : {}), ...(current.length ? { findings: findingTally(current) } : {}), ...(cancelled ? { cancelled: { ...cancelled, reason: screenHistoryText(cancelled.reason, "cancellation", cancelled.withheld), ...(cancelled.supersededBy ? { supersededBy: screenHistoryText(cancelled.supersededBy, "supersession", cancelled.withheld) } : {}) } } : {}), ...(external && this.nameable(external.url) ? { external } : {}), actualDates: actualTaskDates(task), ...(((this.d.sdlc?.config().mode ?? "off") !== "off" || this.d.sdlc?.config().workflow === "gsd-lite") ? { lifecycle: sdlcStatus(this.d.sdlc?.config() ?? sdlcConfig(undefined), task.sdlc, undefined, this.workflowView(task), undefined, sets, task.refs.commit) } : {}), title, detail, history: publicHistory }; } /** Console results expose direct approval and delivery holds, not just the chosen peer ids. */ specReportText(task: Task, by?: PeerId): string { if (by && this.d.privateTurn?.(by)) return ""; const report = this.currentSpecReport(task); return report ? renderSpecTaskReport(report) : ""; } resultLine(task: Task, by?: PeerId): string { const base = `task #${task.id}: ${task.state}, owner ${task.owner ?? "none"}, reviewer ${task.reviewer ?? "none"}`; const noReview = task.class !== "review" && !task.reviewer && OPEN.includes(task.state) && !this.waitsFor(task).length ? this.noReviewer(assign(task, this.states(), this.d.routing(), { candidates: task.owner ? [task.owner] : [], notReviewer: task.owner ?? undefined, ...this.weights(task.class, task) })) : undefined; const held = task.owner ? peerEntry(this.d.held?.(), task.owner) : undefined; const holdText = held ? `${task.owner}'s queue is held (${held}); it receives the task once the hold is resolved` : undefined; const request = task.history.findLast(entry => ["done", "reviewer changed", "reviewer unavailable"].includes(entry.event)); const quotaWait = this.activeReviewerQuotaWait(task); if (quotaWait) return `${base}; waiting for reviewer quota reset until ${new Date(quotaWait.deadline).toISOString()}`; const poolBlocked = task.state === "in_review" && task.reviewer === USER && request?.reviewBlocked ? "blocked: no reviewer can run" : undefined; const specText = this.specReportText(task, by) || undefined; return [base, noReview, poolBlocked, holdText, specText].filter(Boolean).join("; "); } private currentSpecReport(task: Task): SpecTaskReport | undefined { const config = this.d.specsConfig?.() ?? DEFAULT_SPECS_CONFIG; if (this.isPii(task) || !config.enabled || config.review === "off") return; const head = task.refs.commit && /^[0-9a-f]{40}$/.test(task.refs.commit) ? task.refs.commit : ""; const binding = this.specRefBinding(task); const latest = task.history.findLast(row => row.event === "done" || row.event === "done (checking)"); const report = latest?.specReport; if (!latest || !report || !(report.head === head || report.head === "" && !report.complete) || latest.specRefBinding !== binding) return; return this.publicSpecReport(report); } private specRefBinding(task: Pick): string { return createHash("sha256").update(JSON.stringify([task.refs.repo ?? "", task.refs.branch ?? "", task.refs.commit ?? ""])).digest("hex"); } private publicSpecReport(report: SpecTaskReport): SpecTaskReport | undefined { if (!report || typeof report.head !== "string" || report.head !== "" && !/^[0-9a-f]{40}$/.test(report.head) || report.complete && !/^[0-9a-f]{40}$/.test(report.head) || typeof report.complete !== "boolean" || !Number.isSafeInteger(report.errors) || report.errors < 0 || !Array.isArray(report.unchanged) || !Array.isArray(report.changed)) return; const ref = (value: unknown): SpecTaskReport["unchanged"][number] | undefined => { if (!value || typeof value !== "object" || Array.isArray(value)) return; const row = value as Record; if (typeof row.id !== "string" || typeof row.path !== "string" || typeof row.title !== "string" || !row.id.trim() || row.id.length > 160 || !row.path.trim()) return; // Missing titles are schema diagnostics, not a report-mode completion gate. const title = row.title.trim() ? row.title : row.id; const strings = [row.id, row.path, title, ...(typeof row.reason === "string" ? [row.reason] : [])]; if (strings.some(text => text.length > 1000 || /[\p{Cc}\p{Cf}]/u.test(text) || !this.publicMetadataText(text))) return; return { id: row.id, path: row.path, title, ...(typeof row.reason === "string" ? { reason: row.reason } : {}) }; }; const unchanged = report.unchanged.slice(0, 20).map(ref).filter((row): row is NonNullable => !!row); const changed = report.changed.slice(0, 20).map(ref).filter((row): row is NonNullable => !!row); const privacyFiltered = unchanged.length < Math.min(report.unchanged.length, 20) || changed.length < Math.min(report.changed.length, 20); const reason = privacyFiltered ? "some spec metadata could not be safely shown" : typeof report.reason === "string" && report.reason.length <= 500 && this.publicMetadataText(report.reason) ? report.reason : undefined; return { head: report.head, complete: report.complete && !privacyFiltered, errors: report.errors, unchanged, changed, ...(report.truncated || report.unchanged.length > 20 || report.changed.length > 20 ? { truncated: true } : {}), ...(reason ? { reason } : {}) }; } private parseSpecAcks(value: unknown): SpecAck[] { if (value === undefined) return []; if (!Array.isArray(value) || value.length > 20) throw new PreEffectToolRefusal("spec_ack must contain at most 20 {id, reason} entries"); const seen = new Set(); return value.map(raw => { if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new PreEffectToolRefusal("each spec_ack entry needs an id and reason"); const row = raw as Record; if (Object.keys(row).some(key => key !== "id" && key !== "reason") || typeof row.id !== "string" || !row.id.trim() || row.id.length > 160 || /[\p{Cc}\p{Cf}]/u.test(row.id) || typeof row.reason !== "string" || !row.reason.trim() || row.reason.length > 1000 || /[\p{Cc}\p{Cf}]/u.test(row.reason)) throw new PreEffectToolRefusal("each spec_ack entry needs a bounded id and reason"); const id = row.id.trim(); if (!this.publicMetadataText(id)) throw new PreEffectToolRefusal("spec_ack id is private or sensitive"); if (seen.has(id)) throw new PreEffectToolRefusal(`spec_ack repeats ${id}`); seen.add(id); return { id, reason: row.reason.trim() }; }); } private specsPolicyKey(config = this.d.specsConfig?.() ?? DEFAULT_SPECS_CONFIG): string { return JSON.stringify([config.enabled, config.review, config.roots, config.stamps_file]); } private assertSpecInspection(inspection: PreparedSpecInspection, task: Task, by: PeerId): void { this.assertSpecTaskBinding(inspection, task); if (this.specsPolicyKey() !== inspection.policyKey || (this.d.privateTurn?.(by) === true) !== inspection.privateTurn || this.isPii(task) !== inspection.pii) { throw new PreEffectToolRefusal(`task #${task.id}: specs policy, task head or privacy context changed during inspection; retry hub_task_done`); } } private assertSpecTaskBinding(inspection: PreparedSpecInspection, task: Task): void { const head = task.refs.commit && /^[0-9a-f]{40}$/.test(task.refs.commit) ? task.refs.commit : ""; if (task.refs.repo !== inspection.repo || head !== inspection.head) { throw new PreEffectToolRefusal(`task #${task.id}: task head or repository changed during spec inspection; retry hub_task_done`); } } private refreshAsyncSpecInspection(inspection: PreparedSpecInspection, task: Task, by: PeerId): boolean { this.assertSpecTaskBinding(inspection, task); const config = this.d.specsConfig?.() ?? DEFAULT_SPECS_CONFIG; const privateTurn = this.d.privateTurn?.(by) === true; const policyKey = this.specsPolicyKey(config), pii = this.isPii(task); if (inspection.report && policyKey !== inspection.policyKey && config.enabled && config.review === "require" && !privateTurn && !pii) return true; if (policyKey !== inspection.policyKey || privateTurn !== inspection.privateTurn || pii !== inspection.pii) { delete inspection.report; inspection.policyKey = policyKey; inspection.privateTurn = privateTurn; inspection.pii = pii; } return false; } private requestSpecRefile(task: Task): void { this.tell(task, `Task #${task.id}: its class check passed, but specs policy changed to require while it ran. Refile hub_task_done so coverage is checked under the current policy.`, this.isPii(task)); } private specInspectionReason(cause: string): string { const safe = this.publicMetadataText(cause) ? sanitize(cause).replace(/[\r\n\t]+/g, " ").trim().slice(0, 350) : "verified spec evidence is unavailable"; return `${safe}; split the task scope or ask the person to change specs.review`; } private async inspectTaskSpecs(task: Task, by: PeerId, rawAcks: unknown, validate: () => Task): Promise { const config = this.d.specsConfig?.() ?? DEFAULT_SPECS_CONFIG; const initialPrivate = this.d.privateTurn?.(by) === true, pii = this.isPii(task); const declaredHead = task.refs.commit && /^[0-9a-f]{40}$/.test(task.refs.commit) ? task.refs.commit : ""; const inspection: PreparedSpecInspection = { policyKey: this.specsPolicyKey(config), ...(task.refs.repo ? { repo: task.refs.repo } : {}), head: declaredHead, privateTurn: initialPrivate, pii }; const ackInput = Array.isArray(rawAcks) && rawAcks.length === 0 ? undefined : rawAcks; if (ackInput !== undefined && (pii || initialPrivate)) throw new PreEffectToolRefusal("spec_ack is unavailable for private work"); if (ackInput !== undefined && (!config.enabled || config.review === "off")) throw new PreEffectToolRefusal("spec_ack is unavailable while specs review is disabled"); if (!config.enabled || config.review === "off" || pii || initialPrivate) return inspection; if (!this.d.inspectSpecs) { if (config.review === "require" && declaredHead) throw new PreEffectToolRefusal(`task #${task.id}: spec coverage is unknown because the spec inspector is unavailable at the submitted head; restore specs support or explicitly change specs.review`); if (ackInput !== undefined) throw new PreEffectToolRefusal("spec inspection is unavailable; cannot accept spec_ack"); return inspection; } const acks = this.parseSpecAcks(ackInput); let changedFiles: BriefFile[] | undefined; let changedEvidenceReason: string | undefined; if (declaredHead) { const brief = this.d.reviewBrief?.({ ...task, refs: { ...task.refs, commit: declaredHead } }); if (!brief) changedEvidenceReason = "the verified review brief is unavailable"; else if ("unavailable" in brief) changedEvidenceReason = `review brief unavailable: ${brief.unavailable}`; else if (brief.head !== declaredHead) changedEvidenceReason = "the verified review brief does not match the submitted full head"; else if (brief.withheld > 0) changedEvidenceReason = `the verified review brief withheld ${brief.withheld} changed file(s)`; else if (brief.unlisted.length > 0) changedEvidenceReason = `the verified review brief has ${brief.unlisted.length} unlisted changed file(s)`; else { const files = [...brief.reviewable, ...brief.excluded].flatMap(file => [file, ...(file.oldPath ? [{ path: file.oldPath, status: file.status }] : [])]); if (files.every(file => this.publicMetadataText(file.path))) { const byPath = new Map(); for (const file of files) if (!byPath.has(file.path)) byPath.set(file.path, file); changedFiles = [...byPath.values()]; } else changedEvidenceReason = "the verified changed-file inventory includes private paths"; } } else changedEvidenceReason = "a full task commit head was not supplied"; const screenedAcks: SpecAck[] = []; for (const ack of acks) { if (!this.publicMetadataText(ack.reason)) throw new PreEffectToolRefusal("spec_ack reason is private or sensitive"); if (await this.withholds("note", ack.reason, task)) throw new PreEffectToolRefusal(`spec_ack reason for ${ack.id} was withheld; use a public, non-sensitive rationale`); screenedAcks.push(ack); this.assertSpecInspection(inspection, validate(), by); } this.assertSpecInspection(inspection, validate(), by); const report = await this.d.inspectSpecs(task, declaredHead, changedFiles, screenedAcks); this.assertSpecInspection(inspection, validate(), by); if (!report) { if (acks.length) throw new PreEffectToolRefusal("spec_ack was supplied but no spec requires acknowledgement"); return inspection; } const safe = this.publicSpecReport(report); if (!safe) throw new PreEffectToolRefusal("spec inspection returned invalid or private metadata"); if (safe.unchanged.length < Math.min(report.unchanged.length, 20) || safe.changed.length < Math.min(report.changed.length, 20)) { safe.complete = false; safe.reason = this.specInspectionReason("some spec metadata could not be safely shown"); } if (safe.head !== declaredHead) { safe.complete = false; safe.head = ""; safe.reason = this.specInspectionReason("the spec report does not match the verified task head"); safe.unchanged = []; safe.changed = []; } if (report.truncated) { safe.complete = false; safe.reason = this.specInspectionReason("the submitted spec scan reached its safety limit; narrow specs.roots"); } else if (changedFiles === undefined && changedEvidenceReason && safe.head === declaredHead) { safe.complete = false; safe.reason = this.specInspectionReason(changedEvidenceReason); } else if (!safe.complete && safe.reason) safe.reason = this.specInspectionReason(safe.reason); else if (!safe.complete) safe.reason = this.specInspectionReason(report.reason ?? "spec coverage could not be verified at the submitted task head"); if (config.review === "require" && report.unchanged.length > 20) throw new PreEffectToolRefusal(`task #${task.id}: ${report.unchanged.length} covering specs are unchanged; update the specs or split the task scope so each task covers at most 20 specs`); const pendingIds = new Set(safe.unchanged.map(spec => spec.id)); for (const ack of screenedAcks) if (!pendingIds.has(ack.id)) throw new PreEffectToolRefusal(`spec_ack ${ack.id} does not name a covering spec that is unchanged at this head`); const reasons = new Map(screenedAcks.map(ack => [ack.id, ack.reason])); safe.unchanged = safe.unchanged.map(spec => ({ ...spec, ...(reasons.has(spec.id) ? { reason: reasons.get(spec.id)! } : {}) })); if (config.review === "require") { if (!safe.complete || report.truncated) throw new PreEffectToolRefusal(`task #${task.id}: ${safe.reason ?? this.specInspectionReason("spec coverage is unknown at this submitted task head")}`); const unacknowledged = safe.unchanged.filter(spec => !reasons.has(spec.id)); if (unacknowledged.length) throw new PreEffectToolRefusal(`task #${task.id}: spec not updated: ${unacknowledged.map(spec => spec.id).join(", ")}; update the covering spec or add spec_ack [{id, reason}]`); } inspection.report = safe; return inspection; } /** Narrow public task-path notice used by the tool response after propose/accept. */ specNotice(task: Task, by?: PeerId): string { const config = this.d.specsConfig?.() ?? DEFAULT_SPECS_CONFIG; if (!config.enabled || config.review === "off" || this.isPii(task) || by && this.d.privateTurn?.(by)) return ""; let report: SpecsCoverReport | undefined; try { report = this.d.specNotice?.(task); } catch { return ""; } const current = this.d.board.get(task.id); if (!current || this.isPii(current) || by && this.d.privateTurn?.(by) || current.history.length !== task.history.length || current.owner !== task.owner || current.refs.repo !== task.refs.repo || JSON.stringify(current.refs.paths ?? []) !== JSON.stringify(task.refs.paths ?? [])) return ""; if (!report) return ""; const refs = report.specs.slice(0, 20).filter(spec => [spec.id, spec.path, spec.title].every(value => this.publicMetadataText(value))); const lines = refs.length ? [`Specs covering these paths: ${refs.map(spec => `${spec.id} (${spec.path})`).join(", ")}`] : []; if (report.errors) lines.push(`Spec coverage check reports ${report.errors} error${report.errors === 1 ? "" : "s"}; run ahub specs check.`); if (report.truncated || report.specs.length > 20 || refs.length < Math.min(report.specs.length, 20)) lines.push("Spec coverage list truncated; run ahub specs covers for the full list."); return sanitize(lines.join("\n")); } specsRead(by: PeerId, action: "check" | "covers", rawPaths: unknown = []): Record { if (this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("spec inspection unavailable during a private turn"); if (!this.d.specsRead) throw new PreEffectToolRefusal("spec inspection unavailable"); if (action !== "check" && action !== "covers") throw new PreEffectToolRefusal('hub_specs action must be "check" or "covers"'); if (!Array.isArray(rawPaths) || rawPaths.length > 32 || rawPaths.some(path => typeof path !== "string" || !path.trim() || path.length > 2000 || /[\p{Cc}\p{Cf}]/u.test(path) || path.startsWith("/") || path.includes("\\") || path.split("/").includes("..") || !this.publicMetadataText(path))) throw new PreEffectToolRefusal("hub_specs paths must be bounded, public repository-relative paths using forward slashes"); const paths = rawPaths as string[]; if (action === "check" && paths.length) throw new PreEffectToolRefusal('hub_specs "check" takes no paths'); if (action === "covers" && paths.length === 0) throw new PreEffectToolRefusal('hub_specs "covers" needs at least one repository-relative path'); const safe = (value: string) => sanitize(value); const diagnostic = (raw: SpecsCheckReport["items"][number]): Record | undefined => { const fields = [raw.code, raw.message, raw.cause, raw.nextSteps, ...(raw.path ? [raw.path] : []), ...(raw.id ? [raw.id] : []), ...(raw.field ? [raw.field] : []), ...(raw.relatedId ? [raw.relatedId] : [])]; if (fields.some(value => !this.publicMetadataText(value))) return; return { severity: raw.severity, code: safe(raw.code), message: safe(raw.message), cause: safe(raw.cause), nextSteps: safe(raw.nextSteps), ...(raw.path ? { path: safe(raw.path) } : {}), ...(raw.id ? { id: safe(raw.id) } : {}), ...(raw.field ? { field: safe(raw.field) } : {}), ...(raw.relatedId ? { relatedId: safe(raw.relatedId) } : {}) }; }; let report: SpecsCheckReport | SpecsCoverReport; try { report = this.d.specsRead(action, paths); } catch { throw new PreEffectToolRefusal("spec inspection unavailable; retry ahub specs check"); } if (this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("spec inspection unavailable during a private turn"); try { if ("freshness" in report) { const visibleItems = report.items.map(diagnostic).filter((row): row is Record => !!row); const items = visibleItems.slice(0, 20); const remaining = Math.max(0, 20 - items.length); const visibleFreshness = report.freshness.filter(row => this.publicMetadataText(row.path) && (row.id === undefined || this.publicMetadataText(row.id))); const freshness = visibleFreshness.slice(0, remaining) .map(row => ({ path: safe(row.path), ...(row.id ? { id: safe(row.id) } : {}), state: row.state, commitsSince: row.commitsSince, dirty: row.dirty })); return { specCount: report.specCount, errors: report.errors, warnings: report.warnings, stale: report.stale, truncated: report.truncated || visibleItems.length > 20 || visibleItems.length !== report.items.length || visibleFreshness.length > freshness.length || visibleFreshness.length !== report.freshness.length, freshness, items }; } const visibleSpecs = report.specs.filter(row => [row.id, row.path, row.title].every(value => this.publicMetadataText(value))); const specs = visibleSpecs.slice(0, 20) .map(({ id, path, title }) => ({ id: safe(id), path: safe(path), title: safe(title) })); const visibleItems = report.items.map(diagnostic).filter((row): row is Record => !!row); const remaining = Math.max(0, 20 - specs.length); const items = visibleItems.slice(0, remaining); return { specs, errors: report.errors, truncated: report.truncated || visibleSpecs.length > specs.length || visibleSpecs.length !== report.specs.length || visibleItems.length > remaining || visibleItems.length !== report.items.length, items }; } catch { throw new PreEffectToolRefusal("spec inspection unavailable; retry ahub specs check"); } } private states(): Record { return Object.fromEntries([...this.d.bus.peers.keys()].map((id) => [id, this.d.bus.stateOf(id)])); } /** Dependencies of a task that are not approved yet: while there are any, it is offered to nobody (issue #34). */ waitsFor = (task: Pick): number[] => (task.deps ?? []).filter((id) => this.d.board.get(id)?.state !== "approved"); /** Decayed failure weights of the peers demoted for a class: failures count half after a day (issue #36). */ demoted(cls: TaskClass, now = Date.now()): Record { const sums = new Map(); const halfLifeH = this.d.demotionHalfLifeH?.(), halfLifeMs = halfLifeH === undefined ? DEMOTION_HALF_LIFE_MS : halfLifeH * 3_600_000, demoteAt = this.d.demoteAt?.() ?? DEMOTE_AT; for (const o of this.d.board.outcomes(cls, now - OUTCOMES_KEPT_MS)) { const w = 0.5 ** ((now - o.at) / halfLifeMs); const s = sums.get(o.peer) ?? { bad: 0, good: 0 }; if (o.ok) s.good += w; else s.bad += w; sums.set(o.peer, s); } return Object.fromEntries([...sums].filter(([, s]) => s.bad >= demoteAt && s.bad > s.good).map(([p, s]) => [p, s.bad])); } /** How each reviewer's reviews of each implementer's work in a class held up (issue #35). */ reviewRecord(cls: TaskClass): Record> { // Counted per task: a review that asked for changes and then approved is one review, not two. const c = new Map; contradicted: Set }>(); for (const r of this.d.board.reviews({ class: cls })) { const key = `${r.implementer}\0${r.reviewer}`; const s = c.get(key) ?? { reviewed: new Set(), contradicted: new Set() }; (r.kind === "contradicted" ? s.contradicted : s.reviewed).add(r.task); c.set(key, s); } const out: Record> = {}; for (const [key, s] of c) { const [implementer, reviewer] = key.split("\0") as [PeerId, PeerId]; const n = s.reviewed.size; if (n) (out[implementer] ??= {})[reviewer] = { score: (n - [...s.contradicted].filter((t) => s.reviewed.has(t)).length) / n, n }; } return out; } /** Who asked for changes on the current owner's work: requests made before the task changed hands were about someone else's. */ private requestedChanges(task: Task): Set { // The window starts where the owner last changed. Newer entries carry the owner, so handing a task to the owner it // already had (`ahub task assign `) keeps the window; older ones do not, and any of them starts it. let since = -1; let owner: PeerId | null | undefined = null; task.history.forEach((h, i) => { if (!OWNERSHIP_EVENTS.has(h.event)) return; if (h.owner === undefined || h.owner !== owner) since = i; owner = h.owner; }); return new Set(task.history.slice(since + 1).filter((h) => h.event === "changes_requested" && h.evidenceOnly !== true).map((h) => h.by)); } /** Workload is board/queue data only: wip() never calls health() or weights(). */ private instanceRouting(ownerIsolation?: Readonly>): InstanceRoutingOptions { const instances = this.d.instances?.(); if (!instances || !Object.keys(instances).length) return { adapterCatalog: this.d.adapterCatalog }; const peers = [...new Set([...(this.d.adapterCatalog?.definitions ?? ADAPTERS).map(adapter => adapter.kind), ...Object.keys(instances), ...this.d.bus.peers.keys()])]; return { adapterCatalog: this.d.adapterCatalog, instances, ownerIsolation: ownerIsolation ?? this.d.ownerIsolation?.() ?? {}, wip: Object.fromEntries(peers.map(peer => [peer, this.wip(peer)])), load: Object.fromEntries(peers.map(peer => [peer, this.d.bus.queued(peer)])) }; } private queuePolicy(): QueueBackpressurePolicy | undefined { const policy = queueBackpressurePolicy(this.d.queueBackpressure?.()); return policy.max_queued > 0 || policy.max_oldest_s > 0 ? policy : undefined; } /** Admission is pending metadata only; an unavailable read never invents an empty/fresh queue. */ private queueRouting(peers: readonly PeerId[], policy = this.queuePolicy()): Pick & { now?: number } { if (!policy) return {}; const queues = Object.fromEntries([...new Set(peers)].map(peer => { let value: QueuePressure; try { value = this.d.bus.assignmentQueue(peer); } catch { value = { queued: NaN }; } return [peer, value]; })); return { queueBackpressure: policy, queues, now: this.d.now?.() ?? Date.now() }; } private contextRouting(): Pick & { now?: number } { const admission = this.d.contextAdmission?.(); if (!admission || !Number.isFinite(admission.policy.max_used) || admission.policy.max_used <= 0 || admission.policy.max_used > 1) return {}; return { contextAdmission: admission, now: this.d.now?.() ?? Date.now() }; } /** Public ids/counts/reasons only; no board history, pending envelope body or task text is read. */ queuePressureStatus(peers: readonly string[]): QueueBackpressureStatus | undefined { const policy = this.queuePolicy(); if (!policy) return undefined; const all = [...new Set(peers)].filter(peer => /^[a-z][a-z0-9-]{0,31}$/.test(peer)); const bounded = all.slice(0, 4096), input = this.queueRouting(bounded, policy), now = input.now!; const rows = Object.fromEntries(bounded.map(peer => { const value = peerEntry(input.queues, peer), refusal = queueBackpressure(peer, policy, value, now); const queued = value && Number.isSafeInteger(value.queued) && value.queued >= 0 ? value.queued : null; const at = queued !== null && queued > 0 && typeof value?.oldestQueuedAt === "number" && Number.isSafeInteger(value.oldestQueuedAt) && value.oldestQueuedAt >= 0 && value.oldestQueuedAt <= now ? value.oldestQueuedAt : null; return [peer, { queued, oldestQueuedAt: at, oldestAgeMs: at === null ? null : now - at, blocked: refusal !== undefined, ...(refusal ? { code: refusal.code, reason: refusal.reason } : {}) }]; })); return { policy, peers: rows, ...(all.length > bounded.length ? { truncated: true as const } : {}) }; } /** Peer health and roles the daemon feeds routing (issues #89, #90, #92): failing peers are skipped, held queues explained. */ private health(ownerIsolation?: Readonly>) { const failing = this.d.failing?.(); const held = this.d.held?.(); const workload = this.instanceRouting(ownerIsolation); const peers = workload.instances ? [...new Set([...(this.d.adapterCatalog?.definitions ?? ADAPTERS).map(adapter => adapter.kind), ...Object.keys(workload.instances), ...this.d.bus.peers.keys()])] : (this.d.adapterCatalog?.definitions ?? ADAPTERS).map(adapter => adapter.kind); return { ...workload, ...this.contextRouting(), ...this.queueRouting([...new Set([...peers, ...this.d.bus.peers.keys()])]), reviewPool: { pool: this.d.review?.pool ?? DEFAULT_REVIEW_POOL, rerotate: this.d.review?.rerotate, required: this.d.review?.pool !== undefined, ...(this.d.review?.same_family === "never" ? { sameFamily: "never" as const } : {}) }, ...(this.d.capabilities ? { capabilities: this.d.capabilities(), repository: this.d.repository } : {}), pullOnly: [...this.d.bus.peers.values()].filter(peer => (this.d.adapterCatalog?.definitionOf ?? definitionOf)(peer.id, workload.instances)?.attach?.pullOnlyForms?.length && peer.pullOnly).map(peer => peer.id), offRoster: peers.filter(peer => !this.d.bus.isRostered(peer)), ...(failing ? { failing } : {}), ...(held ? { held } : {}), ...(this.d.roles ? { roles: this.d.roles } : {}) }; } private reviewHead(task: Task): string | undefined { return task.refs.commit ?? task.sdlc?.head ?? task.sdlc?.localHead; } private recordedReviewHead(task: Task): string | undefined { const isFullHead = (value: unknown): value is string => typeof value === "string" && /^[a-f0-9]{40}$/.test(value); const historyHead = task.history.findLast(entry => (entry.event === "approved" || entry.event === "changes_requested") && isFullHead(entry.reviewedHead))?.reviewedHead; return [task.sdlc?.reviewedHead, historyHead].find(isFullHead); } /** An owner ref, when present, outranks host-derived receipt.head values for review identity. */ private ownerReviewHead(task: Task): string | undefined { return /^[a-f0-9]{40}$/.test(task.refs.commit ?? "") ? task.refs.commit : this.recordedReviewHead(task); } private hasReviewHistory(task: Task): boolean { return task.state === "changes_requested" || !!task.sdlc?.reviewedHead || task.history.some(entry => entry.event === "approved" || entry.event === "changes_requested"); } private reviewHeadMoveRefusal(taskId: number, recorded: string | undefined, current?: string): PreEffectToolRefusal { const known = recorded ? `recorded review head ${recorded}` : "a recorded full review head"; const cause = current ? `${known} differs from current head of PR ${current}` : `current PR head could not be verified against ${known}`; const next = current ? `refs.commit set to ${current}` : "refs.commit set to the current full SHA"; return new PreEffectToolRefusal(`task #${taskId}: ${cause}; owner must re-file hub_task_done with ${next} before review`); } private async currentPrHeadForReview(task: Task, validate: () => Task): Promise { const receipt = task.sdlc, gh = this.d.sdlc?.gh; if (this.isPii(task) || !receipt?.repo || !receipt.pr || !gh) return undefined; const identity = (value: Task) => JSON.stringify([value.id, value.state, value.owner, value.reviewer, value.history.length, this.isPii(value), value.refs, value.sdlc]); const before = identity(task), head = await readSdlcPrHead(receipt, gh), current = validate(); if (identity(current) !== before) throw new PreEffectToolRefusal(`task #${task.id}: task or review head changed during PR readback; reload and retry`); return head; } private reviewPoolOptions(task: Task) { const head = this.reviewHead(task); const round = task.state === "in_review" ? task.history.slice(task.history.findLastIndex(entry => entry.event === "done") + 1) : []; const failed = [...new Set(round.flatMap(entry => entry.reviewerFailure?.head === head && entry.reviewerFailure && entry.reviewerFailure.cause !== "quota" ? [entry.reviewerFailure.peer] : []))]; const gate = this.d.review?.gate; const budget: ReviewBudgetSnapshot | undefined = gate === undefined ? undefined : { gate, unknownQuota: this.d.review?.unknown_quota, now: this.d.now?.() ?? Date.now(), readings: this.d.quota?.() ?? {}, paused: {}, ...this.d.reviewBudget?.() }; const wait = this.priorReviewerQuotaWait(task), now = this.d.now?.() ?? Date.now(); return { waitForReset: !wait || now < wait.deadline, pool: this.d.review?.pool ?? DEFAULT_REVIEW_POOL, rerotate: this.d.review?.rerotate, failed, required: this.d.review?.pool !== undefined, ...(budget ? { budget } : {}), ...(this.d.review?.same_family === "never" ? { sameFamily: "never" as const } : {}) }; } private manuallyNamedReviewer(task: Task): boolean { const event = task.history.findLast(entry => ["reviewer changed", "assigned", "reassigned", "escalated"].includes(entry.event)); return event?.event === "reviewer changed" && event.reason === "manual"; } private poolReview(task: Task, refs?: TaskRefs): Assignment | undefined { if (this.manuallyNamedReviewer(task) || this.isPii(task) || task.class === "review") return undefined; const draft = { ...task, refs: { ...task.refs, ...cleanRefs(refs) } }; const weights = this.weights(task.class, draft); const selection = assign(draft, this.states(), this.d.routing(), { ...weights, candidates: [], ...(task.owner ? { notReviewer: task.owner } : {}) }); const heldSelection = task.reviewer === USER && task.history[this.reviewRequestRevision(task) - 1]?.queueReviewHeld === true; const previous = task.reviewer && task.reviewer !== USER ? assign(draft, this.states(), this.d.routing(), { ...weights, candidates: [], namedReviewer: task.reviewer, ...(task.owner ? { notReviewer: task.owner } : {}) }) : undefined; const queueRefused = previous?.refusals?.some(row => row.role === "reviewer" && row.peer === task.reviewer && isQueuePressureCode(row.code)); const newlyBlocked = selection.reviewBlocked && selection.refusals?.some(row => row.role === "reviewer" && isQueuePressureCode(row.code)); return selection.reviewSelection || queueRefused || newlyBlocked || heldSelection ? selection : undefined; } private reviewMetadata(assignment?: Assignment, task?: Task): ReviewerHistory { const choice = assignment?.reviewSelection; const family = choice && assignment?.plannerFallback && assignment.reviewer ? (this.d.adapterCatalog?.familyOf ?? familyOf)(assignment.reviewer, this.d.instances?.()) : choice?.family; const reason = choice && assignment?.plannerFallback ? assignment.sameFamilyFallback ? "same-family fallback" as const : "unavailable skip" as const : choice?.reason; const queueReviewHeld = task !== undefined && !this.isPii(task) && assignment?.reviewer === USER && assignment.reviewBlocked === true && assignment.refusals?.some(row => row.role === "reviewer" && isQueuePressureCode(row.code)); const queueReviewBinding = task ? this.queueReviewBinding(task) : undefined; const quota = choice?.quotaWait; const now = this.d.now?.() ?? Date.now(), prior = task ? this.priorReviewerQuotaWait(task) : undefined; const reviewerQuotaWait = quota && task && !this.isPii(task) && task.state === "in_review" ? { created: task.created, binding: this.queueReviewBinding(task), since: prior?.since ?? now, deadline: prior?.deadline ?? Math.floor(now + this.sweepConfig.review_min * 60_000), resetAt: quota.resetsAt } : undefined; return { ...(reviewerQuotaWait ? { reviewerQuotaWait } : {}), ...(family ? { reviewerFamily: family } : {}), ...(reason ? { reviewerReason: reason } : {}), ...(assignment?.reviewBlocked ? { reviewBlocked: true } : {}), ...(queueReviewHeld ? { queueReviewHeld: true as const, ...(queueReviewBinding !== undefined ? { queueReviewBinding } : {}) } : {}) }; } /** * #1081: a task that declares `needs_network` or `needs_worktree` is refused at accept when its owner cannot meet the need, before any write. Routing * already keeps such a task away from that peer; this covers an offer made before the sandbox network was switched off, and it is what stops a * sandboxed peer from accepting work, failing at `git worktree add` (#270) and leaving an empty branch ref behind (#621, #565). Unknown capability is * not a refusal, and a PII task skips the check as `requireCapabilities` does. */ private declaredNeedCheck(task: Pick & Partial>, peer: PeerId): void { if (!this.d.capabilities || this.isPii(task as Task)) return; // #1129: write-class work needs the hub's worktree whether or not it says so, because a hub-sandboxed owner cannot commit. const declaredWorktree = task.signals?.includes("needs_worktree") === true; const wantsNetwork = task.signals?.includes("needs_network") === true, wantsWorktree = declaredWorktree || (task.class !== undefined && writesRepository(task.class)); if (!wantsNetwork && !wantsWorktree) return; const caps = peerEntry(this.d.capabilities(), peer); if (wantsNetwork && caps?.network === false) { throw new PreEffectToolRefusal(`task #${task.id} needs the network and ${peer} has none: ${caps.networkReason ?? "its shell cannot reach the network"}; decline it so the hub offers it to a peer with network, or ask the person to enable it`); } if (wantsWorktree && caps?.worktree === false) { throw new PreEffectToolRefusal(`task #${task.id} ${declaredWorktree ? "needs its own git worktree" : "changes the repository, so the hub must make its git worktree and commit for it"} and ${peer} cannot create one: ${caps.worktreeReason ?? "it cannot create the task worktree"}; nothing was created, so no branch ref is left behind; decline it so the hub offers it to a peer that can, this will not change by waiting`); } } /** Capability admission precedes explicit assignments/reservations, independent of readiness or transient peer health. */ private requireCapabilities(task: Parameters[0], peer: PeerId, role: Exclude = "owner", preEffect = true): void { requireLocalTaskPeer(peer); const instances = this.d.instances?.(), adapter = (this.d.adapterCatalog?.definitionOf ?? definitionOf)(peer, instances); const declaredExtra = !!adapter && adapter.kind !== peer; if ((!this.d.capabilities || this.isPii(task)) && !declaredExtra) return; const { state: _state, ...draft } = task; // backlog/readiness must not bypass an explicit reservation's admission const admission = assign(draft, this.states(), this.d.routing(), { candidates: role === "owner" ? [peer] : [], ...(role === "owner" ? { namedOwner: peer } : { namedReviewer: peer }), ...this.weights(task.class) }); const missing = (admission.refusals ?? []).filter(row => row.peer === peer && row.role === role && (row.code === "tests" || row.code === "spec" || row.code === "network" || row.code === "worktree" || declaredExtra && role === "owner" && row.code === "owner-admission")).map(row => ` ${role} candidate ${peer}: skipped, ${row.reason}`); if (missing.length) throw new (preEffect ? PreEffectToolRefusal : Error)(`cannot assign ${peer}: ${missing.join("; ")}`); } /** What assignment weighs besides states and policy: quota, demotion and the review record. */ /** * #525-3: the settled planner holders, sorted: the one input of the planner walk. It comes from the same settled role map as planner * authority (`d.roles`), restricted to rostered peers, so assignment, planner notices and `route explain` agree on who the holders are. * Selection stays in assign(); task bindings only keep that selection while the holder remains eligible. */ private plannerHolders(): PeerId[] { return Object.entries(this.d.roles ?? {}).filter(([peer, roles]) => !isRemotePeerId(peer) && Array.isArray(roles) && roles.includes("planner") && this.d.bus.isRostered(peer)).map(([peer]) => peer).sort(); } private weights(cls: TaskClass, task?: Task, projectedHealth?: ReturnType) { const now = Date.now(); const entryDiagnostic = task ? this.entryDiagnostic(task) : undefined; const quota = this.d.quota?.(); const health = projectedHealth ?? this.health(), clock = health.now ?? now; return { ...health, ...(entryDiagnostic ? { entryDiagnostic } : {}), ...(task && this.hasPersonReservation(task) && task.reserved ? { queueReservedHold: task.reserved } : {}), planners: this.plannerHolders(), ...(task ? { reviewPool: this.reviewPoolOptions(task), ...(task.planner ? { keptPlanner: task.planner } : {}) } : {}), now: clock, demoted: this.demoted(cls, clock), reviews: this.reviewRecord(cls), ...(quota ? { quota } : {}), ...(this.d.review?.adaptive ? { adaptive: { min: this.d.review.min_reviews } } : {}) }; } /** * A peer's tasks of a class, across hub runs, as split observations (issue #109): each hand-over to it by someone * else (claims left out) while it had the profile it has now, typed by outcome. Stages are the board's own proxies and * stay unknown when the accept came with the done. * ponytail: the profile is taken at the hand-over; a hub restarted with another version before the done mixes two in * one record. Tag the done as well if that ever shows up in the data. */ splitObservations(cls: TaskClass, peer: PeerId, exclude?: number): SplitObservation[] { const profile = this.d.splitProfile?.(peer); if (!profile) return []; const failed = ["check failed", "changes_requested", "escalated", "released", "declined", "integration unresolved"]; return this.d.board.list().flatMap((t): SplitObservation[] => { if (t.class !== cls || t.id === exclude) return []; // One observation per time the task was handed to `peer` by someone else: what happened from that hand-over up to // and with the next one is that peer's, so an escalation away or a decline counts against the peer that failed, // never against the next owner, and work that ended elsewhere is still counted (no survivors only). return t.history.flatMap((given, i): SplitObservation[] => { if (!OWNERSHIP_EVENTS.has(given.event) || given.event === "unassigned" || given.owner !== peer || given.profile !== profile || given.by === peer) return []; const next = t.history.findIndex((h, j) => j > i && OWNERSHIP_EVENTS.has(h.event)); const span = t.history.slice(i + 1, next < 0 ? undefined : next + 1); if (span.some((h) => failed.includes(h.event) && h.evidenceOnly !== true)) return [{ outcome: "failed" }]; if (next >= 0 || t.state !== "approved") return []; // handed on without a failure (a relay), or still open const accepted = span.find((h) => h.event === "accepted" && h.by === peer); // The work stage ends at its first done call: checks and an integration step are not the work itself. const intent = accepted && span.find((h) => h.at >= accepted.at && ["done", "done (checking)", "integration requested"].includes(h.event)); if (!accepted || !intent || accepted.note === WITH_DONE) return [{ outcome: "approved" }]; return [{ outcome: "approved", orient: accepted.at - given.at, work: intent.at - accepted.at }]; }); }); } /** * The shadow split prediction for routing `task` to `candidate` (issue #109): the pair it would form with the owner of * an open task it overlaps (`unstarted`: one not started yet). Assignment never reads it; `route explain` shows it and * assignment records it. */ splitShadow(task: Task, candidate: PeerId | undefined, unstarted = false): SplitPrediction | undefined { if (!candidate) return undefined; const others = this.overlapHits({ ...task, owner: null }).map((h) => h.task).filter((t) => t.owner && t.owner !== candidate && t.owner !== USER && t.owner !== HUB); // A task not started yet first: the pair the routing record is about, so explain and the record agree on it. const other = others.find((t) => t.state === "proposed") ?? (unstarted ? undefined : others[0]); if (!other) return undefined; const peers: [PeerId, PeerId] = [candidate, other.owner!]; const states = this.states(); const failing = this.d.failing?.() ?? {}; // Other open work, and the overlapping task itself once its owner has started it: either way that owner would not // start from orientation plus two whole units. const open = this.d.board.list().filter((t) => OPEN.includes(t.state) && t.id !== task.id && (t.id !== other.id || t.state !== "proposed")); // One task of a class is one unit: the only normalization the board supports, so another class is unknown. const unit = task.class === other.class ? 1 : undefined; const taking = (p: PeerId) => states[p] === "busy" && (p === candidate ? this.sent.has(handOver(task, p)) : other.state === "proposed" && this.sent.has(handOver(other, p))); return predictSplit({ peers, observations: Object.fromEntries(peers.map((p) => [p, this.splitObservations(task.class, p, task.id)])), units: [unit, unit], ...(this.d.splitMinObservations ? { minObservations: this.d.splitMinObservations() } : {}), ...(this.d.splitMaxFailureShare ? { maxFailureShare: this.d.splitMaxFailureShare() } : {}), profiles: Object.fromEntries(peers.map((p) => [p, this.d.splitProfile?.(p)])), backlog: Object.fromEntries(peers.map((p) => [p, open.filter((t) => t.owner === p).length])), // Busy is taking the task in question only in the turn that task started (an owner goes busy as its task is // delivered) or in which it claimed it: the routed peer this very task, the other owner the overlapped one while it // is not started. Busy otherwise, it is at work on something else (#109, #115; a routing or cohort record is taken // before the task is sent, so a busy candidate is not available then). available: Object.fromEntries(peers.map((p) => [p, !peerEntry(failing, p) && (states[p] === "idle" || taking(p))])), }); } /** * Work on these places failed (a check failure, or changes requested): approvals of other tasks on the same places * within the window were contradicted. Each approval counts once. */ private contradict(failed: Task): void { if (this.isPii(failed)) return; // its places are left out everywhere else too const now = Date.now(); const contradictionDays = this.d.contradictionWindowDays?.(), contradictionWindowMs = contradictionDays === undefined ? CONTRADICTION_WINDOW_MS : contradictionDays * 86_400_000; const mine = this.places(failed); for (const t of this.d.board.list("approved")) { if (t.id === failed.id || !t.owner || this.isPii(t)) continue; const approval = [...t.history].reverse().find((h) => h.event === "approved"); if (!approval || now - approval.at > contradictionWindowMs || approval.by === USER) continue; const theirs = this.places(t); // Blame needs the same file or symbol: a directory or `.` would contradict every approval under it. Older rows // were stored as written, so both sides are compared in one spelling. if (mine.repositoryKey !== theirs.repositoryKey) continue; const file = (p: string) => normPath(p) !== "." && theirs.paths.some((q) => normPath(q) === normPath(p)); const same = mine.paths.some(file) || mine.symbols.some((x) => theirs.symbols.some((y) => symbolsOverlap(x, y))); if (!same || this.d.board.reviews({ task: t.id }).some((r) => r.kind === "contradicted")) continue; this.d.board.recordReview({ implementer: t.owner, reviewer: approval.by, class: t.class, kind: "contradicted", task: t.id }); } } private planningRecorded(change: { by: string; task?: number; release?: number; fields: string[]; revision: number }): void { try { this.d.recordPlanning?.(change); } catch { /* telemetry never changes a durable result */ } } /** A removed/off-roster binding falls back to legacy holders; a busy, paused or offline holder keeps authority. */ taskPlanner(task: Pick): PeerId[] { const holders = Object.keys(this.d.roles ?? {}).filter(peer => !isRemotePeerId(peer) && this.d.roles?.[peer]?.includes("planner")).sort(); return task.planner && holders.includes(task.planner) && this.d.bus.isRostered(task.planner) ? [task.planner] : holders; } /** Current planner rulings amend review context, never person-only plan-departure acceptance. */ plannerRulings(task: Task, recipient: PeerId): { historyIndex: number; by: PeerId; at: number; note: string }[] { requireLocalTaskPeer(recipient); if (this.isPii(task)) return []; const boundary = task.history.findLastIndex(entry => entry.event === "accepted" || entry.event === "claimed"); if (boundary < 0) return []; const planners = new Set(this.taskPlanner(task)); const rulings: { historyIndex: number; by: PeerId; at: number; note: string }[] = []; for (let historyIndex = boundary + 1; historyIndex < task.history.length && rulings.length < 5; historyIndex++) { const entry = task.history[historyIndex]!; if (entry.event !== "plan reviewed" || !planners.has(entry.by) || !this.d.roles?.[entry.by]?.includes("planner") || typeof entry.note !== "string" || !entry.note.trim() || !Number.isFinite(entry.at)) continue; // Screen the entire original note before the display bound, including a sensitive suffix past 1000 characters. const note = sanitize(this.screen(task, entry.note, "planner ruling", recipient, entry.withheld)).slice(0, 1000); rulings.push({ historyIndex, by: entry.by, at: entry.at, note }); } return rulings; } private planningAuthority(by: PeerId, task?: Pick): void { requireLocalTaskPeer(by); if (by !== USER && (!this.d.roles?.[by]?.includes("planner") || task !== undefined && !this.taskPlanner(task).includes(by))) throw new PreEffectToolRefusal(`planning requires a person or configured planner role${task ? "; only the task's effective planner may act" : ""}`); } /** #812 AC5: a peer holding the configured planner role. The conductor's task reads accept it; it grants no write. */ isConfiguredPlanner(peer: PeerId): boolean { return !isRemotePeerId(peer) && peer !== USER && peer !== HUB && !!this.d.roles?.[peer]?.includes("planner"); } private plannerWriteAuthority(by: PeerId, task?: Pick): void { requireLocalTaskPeer(by); if (by !== USER && this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("planner writes are unavailable during a private turn"); this.planningAuthority(by, task); } private studiesRunning = 0; private studyStopped = false; private readonly studyDrainWaiters = new Set<() => void>(); studiesPending = (): number => this.studiesRunning; async stopStudies(): Promise { this.studyStopped = true; if (this.studiesRunning) await new Promise(resolve => this.studyDrainWaiters.add(resolve)); } private studyHold(): string | undefined { try { if (this.studyStopped || this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) return "study writes are held by recovery, shutdown or storage failure"; } catch { return "study write admission is unavailable"; } return undefined; } private async studyWrite(write: () => Promise): Promise { this.studiesRunning++; try { return await write(); } finally { if (--this.studiesRunning === 0) { for (const resolve of this.studyDrainWaiters) resolve(); this.studyDrainWaiters.clear(); } } } private studyFields(input: unknown, allowed: readonly string[]): Record { if (!input || typeof input !== "object" || Array.isArray(input) || types.isProxy(input) || ![Object.prototype, null].includes(Object.getPrototypeOf(input)) || Object.getOwnPropertySymbols(input).length) throw new PreEffectToolRefusal("study request must be a plain data object"); const fields = Object.getOwnPropertyDescriptors(input); if (Object.entries(fields).some(([key, descriptor]) => !allowed.includes(key) || !Object.hasOwn(descriptor, "value"))) throw new PreEffectToolRefusal("study request has unknown fields or accessors"); return Object.fromEntries(Object.entries(fields).map(([key, descriptor]) => [key, descriptor.value])); } private studyId(value: unknown): string { if (typeof value !== "string" || !/^rc-[a-f0-9]{12}$/.test(value)) throw new PreEffectToolRefusal("study id is invalid"); return value; } private studyNumber(value: unknown, field: string): number { if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) throw new PreEffectToolRefusal(`${field} must be a positive integer`); return value; } private studyContract(value: unknown): ResearchCampaignContract { try { return parseResearchCampaign(value); } catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid study contract"); } } private studyTime(): number { const now = this.d.studyNow?.() ?? Date.now(); if (!Number.isFinite(now)) throw new PreEffectToolRefusal("study clock is unavailable"); return now; } private studyRecord(id: string, revision?: number): ResearchCampaignRecord { let record: ResearchCampaignRecord | undefined; try { record = this.d.board.researchCampaign(id, revision); } catch { throw new PreEffectToolRefusal("study record is unavailable or invalid"); } if (!record || record.project !== this.d.project) throw new PreEffectToolRefusal("study is unavailable in this project"); return record; } private studyParent(id: number): Task { const parent = this.need(id, false, true, true); if (this.places(parent).repositoryKey !== this.repositories.scope({}).key) throw new PreEffectToolRefusal("study parent is outside this project"); return parent; } /** Write receipts expose no contract text; only person-only approval returns the unit mapping. */ private studyReceipt(record: ResearchCampaignRecord, includeMapping = false): ResearchCampaignReceipt { const units = this.d.board.researchCampaignBindings(record.id, record.revision); return { id: record.id, parentTaskId: record.parentTaskId, revision: record.revision, status: record.status, unitCount: units.length, units: includeMapping ? units : [] }; } private studySource(id: string): { id: string; sha256: string; private: boolean } | undefined { try { const source = this.d.studySource?.(id); return source && source.id === id && /^[a-f0-9]{64}$/.test(source.sha256) && typeof source.private === "boolean" ? { id: source.id, sha256: source.sha256, private: source.private } : undefined; } catch { return undefined; } } private studyLatest(id: string, revision: number): ResearchCampaignRecord { const record = this.studyRecord(id); if (record.revision !== revision || record.status === "closed") throw new PreEffectToolRefusal("study revision is stale or closed"); return record; } private studyFamily(parent: Task): Set { if (!parent.history.some(entry => entry.event === "draft approved")) throw new PreEffectToolRefusal("adoption requires an approved intake family"); const family = new Set(), pending = [...(parent.deps ?? [])]; // ponytail: 512 dependency nodes bound intake provenance walks; a larger family needs indexed family identities. while (pending.length) { const id = pending.pop()!; if (family.has(id)) continue; if (family.size >= 512) throw new PreEffectToolRefusal("study intake family exceeds its bounded scope"); const task = this.d.board.get(id); if (!task) throw new PreEffectToolRefusal("study intake family is incomplete"); family.add(id); pending.push(...(task.deps ?? [])); } family.delete(parent.id); return family; } private studyReferences(parentId: number, contract: ResearchCampaignContract, campaignId?: string): StudyReferences { const parent = this.studyParent(parentId); const profile = parent.profile ?? "dev", storedProfile = profile === (this.d.profile ?? "dev") ? this.d.profileData ?? profile : profile; try { if (profileClass(parent.profileClass ?? parent.class, storedProfile) !== parent.class) throw new Error("changed class"); } catch { throw new PreEffectToolRefusal("study parent profile class is unavailable or changed"); } const sources = contract.sourceIds.map(id => { const source = this.studySource(id); if (!source) throw new PreEffectToolRefusal("study source is unavailable in this project"); return source; }); if (contract.budget) { const budget = this.d.executionBudget?.status(contract.budget.id); if (!budget || Array.isArray(budget)) throw new PreEffectToolRefusal("study budget is unavailable"); } const adopted = new Map(); const family = contract.units.some(unit => unit.adoptTaskId !== undefined) ? this.studyFamily(parent) : new Set(); for (const unit of contract.units) if (unit.adoptTaskId !== undefined) { const task = this.studyParent(unit.adoptTaskId); if (!family.has(task.id) || task.draft || !task.history.some(entry => entry.event === "draft approved")) throw new PreEffectToolRefusal("study unit must adopt an approved intake child"); const binding = this.d.board.researchTaskBinding(task.id); if (binding && (binding.campaignId !== campaignId || binding.unitId !== unit.id)) throw new PreEffectToolRefusal("intake child is already bound to another study unit"); adopted.set(unit.id, task); } const reused = new Map(); if (campaignId) for (const unit of contract.units) { const previous = this.d.board.researchLatestUnitBinding(campaignId, unit.id); if (previous) reused.set(unit.id, this.studyParent(previous.taskId)); } const priv = this.isPii(parent) || sources.some(source => source.private) || [...adopted.values(), ...reused.values()].some(task => this.isPii(task)) || !this.nameable(JSON.stringify(contract)); const flows = (rows: Map) => [...rows].map(([unit, task]) => [unit, task.id, task.history.length]); return { parent, adopted, reused, private: priv, key: JSON.stringify([parent.history.length, sources, flows(adopted), flows(reused), priv]) }; } /** Always re-read persisted approval and limits at the dispatch write, including after a metadata await. */ private studyDispatchReason(task: Task, owner?: PeerId): string | undefined { try { const bound = this.d.board.researchDispatchBinding(task.id); if (!bound) return undefined; const { campaign, binding } = bound; if (campaign.project !== this.d.project || campaign.status !== "approved" || !binding) return "study revision is not approved or its unit was removed"; const stop = campaign.contract.stopPolicy; if (Date.parse(stop.deadline) <= this.studyTime()) return "study deadline has expired"; const units = this.d.board.researchCampaignBindings(campaign.id, campaign.revision); if (units.length > stop.maxUnits || binding.round > stop.maxFollowUpRounds) return "study stop limit exceeded"; const budget = campaign.contract.budget; if (budget?.hardCap.length) { const ledger = this.d.executionBudget, current = ledger?.status(budget.id); if (!ledger || !current || Array.isArray(current) || !campaign.eligibleOwners?.length || budget.hardCap.some(resource => resource === "tokens" || current.limits[resource] === undefined || resource === "model_calls" && current.limits.tokens !== undefined)) return "study hard-cap budget is unavailable"; if (budget.hardCap.some(resource => !current.units[resource] || current.units[resource]!.remaining <= 0 || current.units[resource]!.reason === "unknown_usage")) return "study hard-cap budget is exhausted or usage is unknown"; if (owner && (!campaign.eligibleOwners.includes(owner) || !ledger.covers(budget.id, task.id, owner, budget.hardCap))) return "study owner is not covered by its named hard-cap budget"; } return undefined; } catch { return "study dispatch evidence is unavailable"; } } private studyDispatchCheck(task: Task, owner?: PeerId): void { const reason = this.studyDispatchReason(task, owner); if (reason) throw new PreEffectToolRefusal(reason); } private studyExcludedOwners(task: Task): PeerId[] { return Object.keys(this.states()).filter(peer => this.studyDispatchReason(task, peer) !== undefined); } private studyEligibleOwners(contract: ResearchCampaignContract): string[] | undefined { if (!contract.budget?.hardCap.length) return undefined; const ledger = this.d.executionBudget, budget = ledger?.status(contract.budget.id); if (!ledger || !budget || Array.isArray(budget) || contract.budget.hardCap.some(resource => resource === "tokens" || budget.limits[resource] === undefined || resource === "model_calls" && budget.limits.tokens !== undefined)) throw new PreEffectToolRefusal("study hard-cap requires an enabled budget with supported resource limits"); const eligible = budget.peers.filter(peer => ledger.instrumented(peer)).sort(); if (!eligible.length) throw new PreEffectToolRefusal("study hard-cap has no instrumented eligible owner"); return eligible; } private studyRoundCheck(original: ResearchCampaignRecord, contract: ResearchCampaignContract): void { const added = contract.units.filter(unit => unit.round > 0 && !original.contract.units.some(previous => previous.id === unit.id && previous.round === unit.round)); if (!added.length) return; const stored = this.d.board.researchCampaignBindings(original.id, original.revision), handoffs = this.d.board.researchHandoffs(original.id, original.revision); for (const unit of added) { // The revised contract decides which discovery units precede this round: a discovery added in the same revision has no stored binding, so it has no handoff and refuses. const previous = contract.units.filter(value => value.round === unit.round - 1 && value.purpose === "discovery"); if (!previous.length || previous.some(value => { const binding = stored.find(bound => bound.unitId === value.id && bound.round === value.round && bound.purpose === "discovery"); const handoff = binding && handoffs.find(handoff => handoff.handoff.unitId === value.id); return !handoff || !handoff.handoff.insufficientEvidence && value.sourceIds.some(source => !handoff.handoff.evidence.some(item => item.sourceId === source)); })) throw new PreEffectToolRefusal("follow-up rounds require complete stored discovery handoffs or insufficientEvidence"); } } async studyHandoff(by: PeerId, input: unknown): Promise<{ campaignId: string; unitId: string; seq: number }> { const requestCheck = this.requestCheck(by, () => this.studyHold()); let handoff: ReturnType; try { handoff = parseResearchHandoff(input); } catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid study handoff"); } return this.studyWrite(async () => { const campaign = this.studyRecord(handoff.campaignId, handoff.revision), task = this.studyParent(handoff.taskId); if (by !== task.owner || task.state !== "in_progress" || this.d.privateTurn?.(by) && !this.isPii(task)) throw new PreEffectToolRefusal("handoff requires the current in-progress unit owner"); const sources = campaign.contract.sourceIds.map(id => this.studySource(id)); if (sources.some(source => !source)) throw new PreEffectToolRefusal("study handoff source is unavailable"); const sourceKey = JSON.stringify(sources); const text = JSON.stringify(handoff); const withheld = !this.nameable(text) || looksSecret(text) || await this.withholds("note", text, task); requestCheck(); const current = this.studyParent(task.id); if (current.history.length !== task.history.length || current.owner !== by || current.state !== "in_progress") throw new PreEffectToolRefusal("study handoff task changed during screening"); if (JSON.stringify(campaign.contract.sourceIds.map(id => this.studySource(id))) !== sourceKey) throw new PreEffectToolRefusal("study handoff sources changed during screening"); if ((withheld || this.studyReplayPrivacy(campaign, this.studyParent(campaign.parentTaskId))) && !this.isPii(current)) throw new PreEffectToolRefusal("study handoff privacy requires private task authority"); requestCheck(); try { const saved = this.d.board.recordResearchHandoff(handoff, this.d.project, by, this.studyTime(), current.history.length); return { campaignId: saved.handoff.campaignId, unitId: saved.handoff.unitId, seq: saved.seq }; } catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study handoff was not saved"); } }); } /** * #601: one page of receipts, one per campaign of this project, newest revision, never its question, scope, sources or unit text. At most 50 rows per call (the spec's readback bound), in id * order, strictly after the optional cursor `after`; `next` names the last id of a page that has more behind it. The bound is in the Board query, not in a slice after loading everything. */ studyList(by: PeerId, input: unknown): { campaigns: ResearchCampaignReceipt[]; next?: string } { requireLocalTaskPeer(by); const fields = this.studyFields(input, ["after"]); const after = fields.after === undefined ? undefined : this.studyId(fields.after); const page = this.d.board.researchCampaignPage(this.d.project, after, 50); return { campaigns: page.ids.map(id => this.studyReceipt(this.studyRecord(id))), ...(page.next ? { next: page.next } : {}) }; } studyShow(by: PeerId, input: unknown): ReturnType { requireLocalTaskPeer(by); const fields = this.studyFields(input, ["id"]), campaign = this.studyRecord(this.studyId(fields.id)); const bindings = this.d.board.researchCampaignBindings(campaign.id, campaign.revision); const tasks = bindings.map(unit => this.d.board.get(unit.taskId)).filter((task): task is Task => !!task); const ledger = this.d.executionBudget, configured = campaign.contract.budget, budget = configured && ledger?.status(configured.id); const instrumentedPeers = tasks.flatMap(task => task.owner && ledger?.instrumented(task.owner) ? [task.owner] : []); const projection = studyProjection({ campaign, bindings, tasks, handoffs: this.d.board.researchHandoffs(campaign.id), now: this.studyTime(), instrumentedPeers, ...(budget && !Array.isArray(budget) ? { budget: { ...budget, coveredTaskIds: tasks.filter(task => task.owner && ledger?.covers(budget.id, task.id, task.owner, [])).map(task => task.id) } } : {}) }); projection.reasons = [...new Set([...projection.reasons, ...tasks.flatMap(task => { const reason = this.studyDispatchReason(task, task.owner ?? undefined); return reason ? [reason] : []; })])]; projection.held = projection.reasons.length > 0; if (this.studyReplayPrivacy(campaign, this.studyParent(campaign.parentTaskId))) { // IDs, counts, states and resource names only. Source references are private view data too. for (const unit of projection.units) { unit.sourceIds = []; unit.duplicateSourceIds = []; unit.handoff.coveredSourceIds = []; } } return projection; } private studyReplayPrivacy(record: ResearchCampaignRecord, parent: Task): boolean { return record.private || this.isPii(parent) || record.contract.sourceIds.some(id => { const source = this.studySource(id); return !source || source.private; }) || this.d.board.researchCampaignBindings(record.id, record.revision).some(unit => { const task = this.d.board.get(unit.taskId); return !task || this.isPii(task); }); } /** * #604 (agent-hub#1030), ORIGIN side. Who may hand work to another project: the person, or a configured planner, or the conductor. The host (the daemon) has already resolved and * checked the target; this is the authority and privacy gate before anything leaves this project, so a refusal here leaves no row in either board. */ handoffOutAuthority(by: PeerId, piiTask?: Task): void { requireLocalTaskPeer(by); if (by !== USER && this.d.privateTurn?.(by)) throw new HandoffRefusal("pii_turn", "a handoff is unavailable during a private turn: nothing from it may leave this project"); if (piiTask && this.isPii(piiTask)) throw new HandoffRefusal("pii_task", "a [pii] task is not handed off: nothing about it leaves this project"); if (by !== USER && !this.d.roles?.[by]?.includes("planner") && this.d.operational?.(by) !== true) throw new HandoffRefusal("no_authority", "a handoff needs the person, a configured planner or the conductor"); } /** * #734 (AC6): who may ask the origin to catch up now (`ahub task handoff --sync`). The person, or the conductor acting on the person's instruction: the same bar as `handoffOutAuthority` * without the planner role, because a sync starts no work and files nothing, but it does ask other projects' hubs, which a planner agent has no need to trigger. */ handoffSyncAuthority(by: PeerId): void { requireLocalTaskPeer(by); if (by !== USER && this.d.operational?.(by) !== true) throw new HandoffRefusal("no_authority", "a handoff sync is the person's or the conductor's: ask them to run `ahub task handoff --sync`"); } /** ORIGIN side: remember what was handed over, once the target answered with its task id. */ handoffSent(by: PeerId, target: { projectId: string }, remoteTask: number, title: string, localTask?: number): void { // #731: a row that already exists is never reset to "proposed": a replayed answer can arrive after the target's own event for the same task was recorded. if (this.d.board.handoffOutboundFor(target.projectId, remoteTask)) return; this.d.board.recordHandoffOutbound({ remoteProject: target.projectId, remoteTask, originPeer: by, ...(localTask === undefined ? {} : { localTask }), title: title.slice(0, 300), state: "proposed" }); } /** * TARGET side. The origin peer gets no identity or authority here: the task is an ownerless proposal made by the hub on the origin's behalf, with the origin recorded in its own table. * The request was parsed closed by the origin and is parsed again here, because a control message is data from another process: the body is bounded, control characters are refused and the * text is sanitized before it is stored. A `[pii]` result is refused whole, and nothing is left behind. */ async handoffIn(origin: { projectId: unknown; peer: unknown; taskId?: unknown }, input: unknown, fence: () => string | undefined = () => undefined): Promise<{ task: number; state: string; note?: string; replayed?: true }> { const request = parseHandoff({ ...(input && typeof input === "object" && !Array.isArray(input) ? input as Record : { invalid: true }), project: "local" }); if (typeof origin.projectId !== "string" || !origin.projectId || origin.projectId.length > 200 || typeof origin.peer !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(origin.peer) || origin.taskId !== undefined && (!Number.isSafeInteger(origin.taskId) || (origin.taskId as number) < 1)) throw new HandoffRefusal("invalid", "handoff origin is malformed"); if (origin.projectId === this.d.project) throw new HandoffRefusal("same_project", "that is this project: a task for this project goes through hub_task_propose"); // The fence is asked right before the board write and after every await: a recovery that began while the PII screen was pending must find nothing written (agent-hub#1030, review). const held = (): void => { const reason = fence(); if (reason) throw new HandoffRefusal("invalid", reason); }; held(); // #731 (agent-hub#1203): a request key this origin already used answers with the task it made, before the duplicate check (which would refuse it as a duplicate of itself) and before any PII screen // or write. The same key for a different request is refused, never answered with a task the caller did not ask for. const key = request.handoffKey, digest = handoffRequestDigest(request, origin.taskId as number | undefined); const replay = (): { task: number; state: string; replayed: true } | undefined => { const existing = key === undefined ? undefined : this.d.board.handoffOriginByKey(origin.projectId as string, key); const task = existing && this.d.board.get(existing.taskId); if (!existing || !task) return undefined; if (existing.digest !== null && existing.digest !== digest) throw new HandoffRefusal("invalid", "that handoff key was already used for a different request: hand the task off again with a new key"); return { task: task.id, state: task.state, replayed: true }; }; const early = replay(); if (early) return early; // The spec issue the caller named is kept in the task itself, as its own line: the target's planner reads it from the detail, and `ahub task show` shows it there. const issueLine = request.issue === undefined ? "" : `spec issue: #${request.issue} in this repository`; const detail = sanitize([request.detail, issueLine, request.duplicate_ok === undefined ? "" : `duplicate acknowledged by the sender: ${request.duplicate_ok}`, `[handed off from project ${origin.projectId} by ${origin.peer}${origin.taskId === undefined ? "" : ` (their task #${origin.taskId})`}]`].filter(Boolean).join("\n\n")); const refs: TaskRefs = { ...(request.paths.length ? { paths: request.paths } : {}) }; const signals = this.signalsFor({ title: request.title, detail, refs, plan: {} }); if (signals.includes("pii")) throw new HandoffRefusal("pii_task", "the handed-off text matches a PII pattern; it is not stored here"); const screening = this.screenOn(); const screened = screening ? await this.screenCall(screenText({ title: request.title, detail: [detail, ...request.paths].join("\n"), plan: {} })) : undefined; held(); if (screening && (!screened || screened.label !== "clear")) throw new HandoffRefusal("pii_task", "the handed-off text could not be cleared by the PII screen; it is not stored here"); // The first attempt may have committed while this one waited for the screen (the origin's timeout does not stop it): ask again, with nothing awaited between here and the write below. const late = replay(); if (late) return late; // #1175: a spec issue that already has open work here is refused before any row exists, so a duplicate is never offered to an owner or escalated by the sweep. This runs after the last // await and writes nothing before it, so the check and the proposal below see one board; a `[pii]` task is left out, so no private task id is named to another project. if (request.issue !== undefined && request.duplicate_ok === undefined) { const open = duplicateIssueTasks(this.d.board.list().filter(row => !this.isPii(row)).map(row => ({ id: row.id, state: row.state, title: row.title, detail: row.detail, refs: row.refs, external: row.external, sdlc: row.sdlc })), request.issue, this.d.repository); if (open.length) throw new HandoffRefusal("duplicate", duplicateRefusalText(request.issue, open)); } // #731 (H9): the proposal and its origin row are one board transaction. A request with no key (an older origin) is written the same way, without a key, so it is never left without its origin either. const made = this.d.board.proposeHandoff(HUB, { title: request.title, detail, class: request.class, refs, plan: {}, signals }, { projectId: origin.projectId, peer: origin.peer, ...(origin.taskId === undefined ? {} : { originTask: origin.taskId as number }), ...(key === undefined ? {} : { key, digest }) }); if (made.replayed) return { task: made.task.id, state: made.task.state, replayed: true }; let task = made.task; // From here the task and its origin are saved, so nothing below may fail the handoff: the origin must learn the task id, or the target keeps work nobody can track. try { task = this.linkOnWrite(task); } catch { /* the lifecycle link is advice */ } try { this.d.notify(`task ${this.publicTitle(task)} handed off from project ${origin.projectId} by ${origin.peer}`); } catch { /* never throw after a board write */ } let note: string | undefined; try { task = await this.assignOwner(task, HUB, {}); } catch (error) { if (error instanceof AssignmentUndeliveredError) { task = error.task; note = "the assignment is saved but its delivery is not confirmed yet; this hub retries it"; } else note = "the task is saved but was not offered to an owner yet; this hub's routing offers it"; // a routing refusal leaves an ordinary proposal for the planner } return { task: task.id, state: task.state, ...(note ? { note } : {}) }; } /** TARGET side: the origin recorded for a task, for `ahub task show` and the board. */ handoffOriginOf(taskId: number): { projectId: string; peer: string; originTask: number | null } | undefined { const origin = this.d.board.handoffOrigin(taskId); return origin ? { projectId: origin.projectId, peer: origin.peer, originTask: origin.originTask } : undefined; } /** * ORIGIN side: the target reported a state change. Records it and tells the origin peer with one `kind: task` envelope. Idempotent: a state already recorded sends nothing. * #733: an event may carry `seq`, the target task's flow revision. One that is not newer than the stored sequence changes nothing and sends nothing (an `in_review` that arrives after * `approved` cannot reopen the row), decided inside the board write; an event without one (an older target) applies as before. */ handoffEvent(input: unknown): { recorded: boolean } { if (!input || typeof input !== "object" || Array.isArray(input)) throw new HandoffRefusal("invalid", "handoff event must be a data object"); const e = input as Record; if (typeof e.projectId !== "string" || !e.projectId || e.projectId.length > 200 || !Number.isSafeInteger(e.remoteTask) || (e.remoteTask as number) < 1 || typeof e.state !== "string" || !(HANDOFF_EVENTS as readonly string[]).includes(e.state) || e.seq !== undefined && (!Number.isSafeInteger(e.seq) || (e.seq as number) < 1)) throw new HandoffRefusal("invalid", "handoff event is malformed"); const row = this.d.board.handoffOutboundFor(e.projectId, e.remoteTask as number); if (!row) throw new HandoffRefusal("invalid", "no handoff of ours is recorded for that task"); const seq = e.seq as number | undefined; const pr = Number.isSafeInteger(e.pr) && (e.pr as number) > 0 ? e.pr as number : undefined, head = typeof e.head === "string" && /^[0-9a-f]{40}$/.test(e.head) ? e.head : undefined; if (seq !== undefined && row.seq !== null && seq <= row.seq) return { recorded: false }; if (row.state === e.state && (pr === undefined || pr === row.pr) && (head === undefined || head === row.head)) { // Nothing to tell the peer, but a newer sequence is still kept, so a later stale event is judged against it. if (seq !== undefined && (row.seq === null || seq > row.seq)) this.d.board.recordHandoffOutbound({ remoteProject: row.remoteProject, remoteTask: row.remoteTask, originPeer: row.originPeer, ...(row.localTask === null ? {} : { localTask: row.localTask }), title: row.title, state: row.state, seq }); return { recorded: false }; } const written = this.d.board.recordHandoffOutbound({ remoteProject: row.remoteProject, remoteTask: row.remoteTask, originPeer: row.originPeer, ...(row.localTask === null ? {} : { localTask: row.localTask }), title: row.title, state: e.state, ...(pr === undefined ? {} : { pr }), ...(head === undefined ? {} : { head }), ...(seq === undefined ? {} : { seq }) }); if (!written.applied) return { recorded: false }; // a newer event won the race between the read above and this write const body = followBackLine(row.remoteTask, e.state as HandoffEvent, { pr, head }); if (row.originPeer !== USER && row.originPeer !== HUB) { // #731 (H3): the envelope names the REMOTE task and no local one. `refs.task` made the bus judge it against whatever local task has that number (or the origin's own task it came from), so a // cancelled or approved local task of the same number dropped a state change that was about another project's task. try { this.d.bus.publish(newEnvelope(HUB, body, { to: [row.originPeer], kind: "task", priority: "important", refs: { handoff: { project: row.remoteProject, task: row.remoteTask } } })); } catch { /* never throw after a board write */ } } return { recorded: true }; } /** * TARGET side, catch-up (#1030 design 4): the origin asks for the current state of the tasks it handed us, by id, after it was down. Answers only for tasks whose recorded origin IS the asking * project, and only with the same fields a live event carries (the event name, a PR number, a full head), so an origin learns nothing it could not have been told live. */ handoffStatesFor(projectId: unknown, taskIds: unknown): { task: number; state: HandoffEvent | "proposed"; pr?: number; head?: string; seq: number }[] { if (typeof projectId !== "string" || !projectId || projectId.length > 200 || !Array.isArray(taskIds) || taskIds.length > 200 || !taskIds.every(id => Number.isSafeInteger(id) && id > 0)) throw new HandoffRefusal("invalid", "handoff state request is malformed"); const out: { task: number; state: HandoffEvent | "proposed"; pr?: number; head?: string; seq: number }[] = []; for (const id of taskIds as number[]) { const origin = this.d.board.handoffOrigin(id), task = origin?.projectId === projectId ? this.d.board.get(id) : undefined; if (!task) continue; const entry = task.history.findLast(h => handoffEventFor(h.event, task.state) !== undefined); const state = entry ? handoffEventFor(entry.event, task.state) ?? "proposed" : "proposed"; const pr = typeof task.sdlc?.pr === "number" && Number.isSafeInteger(task.sdlc.pr) && task.sdlc.pr > 0 ? task.sdlc.pr : undefined; const rawHead = task.refs.commit ?? task.sdlc?.head ?? task.sdlc?.localHead, head = typeof rawHead === "string" && /^[0-9a-f]{40}$/.test(rawHead) ? rawHead : undefined; // the owner's commit, else the receipt's head; only a full SHA crosses // #733: the task's current flow revision (its history length), the same number a live event carries, so a catch-up answer and a late live event are ordered against each other. out.push({ task: id, state, ...(pr === undefined ? {} : { pr }), ...(head === undefined ? {} : { head }), seq: Math.max(1, task.history.length) }); } return out; } /** * TARGET side (#731): where the task a handoff key made stands, for an origin whose request got no answer. Answers only the asking project, and only the fields a live event carries; nothing is * written. `undefined` means this target holds no task for that key. */ handoffStateByKey(projectId: unknown, key: unknown): { task: number; state: HandoffEvent | "proposed"; pr?: number; head?: string; seq: number } | undefined { if (typeof projectId !== "string" || !projectId || projectId.length > 200 || typeof key !== "string" || !HANDOFF_KEY.test(key)) throw new HandoffRefusal("invalid", "handoff key lookup is malformed"); const found = this.d.board.handoffOriginByKey(projectId, key); return found ? this.handoffStatesFor(projectId, [found.taskId])[0] : undefined; } /** ORIGIN side: record what a target answered to the catch-up, and tell the origin peer about a change this project missed while it was down. */ handoffCaughtUp(projectId: string, rows: { task: number; state: string; pr?: number; head?: string; seq?: number }[]): number { let changed = 0; for (const row of rows) { if (!(HANDOFF_EVENTS as readonly string[]).includes(row.state)) continue; try { if (this.handoffEvent({ projectId, remoteTask: row.task, state: row.state, ...(row.pr === undefined ? {} : { pr: row.pr }), ...(row.head === undefined ? {} : { head: row.head }), ...(row.seq === undefined ? {} : { seq: row.seq }) }).recorded) changed++; } catch { /* a row we hold no handoff for is not ours */ } } return changed; } /** ORIGIN side, readback: what this project handed over, with the last state each target reported. */ handoffList(): HandoffOutboundRow[] { return this.d.board.handoffOutbound(); } async studyDraft(by: PeerId, input: unknown): Promise { const requestCheck = this.requestCheck(by, () => this.studyHold()); this.plannerWriteAuthority(by); const fields = this.studyFields(input, ["parentTaskId", "contract"]), parentId = this.studyNumber(fields.parentTaskId, "parentTaskId"); const contract = this.studyContract(fields.contract); if (contract.units.some(unit => unit.round !== 0)) throw new PreEffectToolRefusal("an initial study contains only round zero"); return this.studyWrite(async () => { this.plannerWriteAuthority(by, this.studyParent(parentId)); const before = this.studyReferences(parentId, contract); const withheld = await this.withholds("note", JSON.stringify(contract), before.parent); requestCheck(); const current = this.studyReferences(parentId, contract); this.plannerWriteAuthority(by, current.parent); if (current.key !== before.key) throw new PreEffectToolRefusal("study references changed during draft screening"); const record: ResearchCampaignRecord = { id: `rc-${randomBytes(6).toString("hex")}`, project: this.d.project, parentTaskId: parentId, revision: 1, status: "draft", contract, hash: campaignHash(contract), private: current.private || withheld, createdBy: by, createdAt: this.studyTime() }; let saved: ResearchCampaignRecord; requestCheck(); this.plannerWriteAuthority(by, current.parent); try { saved = this.d.board.saveResearchCampaignDraft(record, undefined, current.parent.history.length); } catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study draft was not saved"); } this.releaseNotice(`study ${saved.id} revision ${saved.revision} drafted`); return this.studyReceipt(saved); }); } async studyRevise(by: PeerId, input: unknown): Promise { const requestCheck = this.requestCheck(by, () => this.studyHold()); this.plannerWriteAuthority(by); const fields = this.studyFields(input, ["id", "revision", "contract"]), id = this.studyId(fields.id), revision = this.studyNumber(fields.revision, "revision"); const contract = this.studyContract(fields.contract); return this.studyWrite(async () => { const original = this.studyLatest(id, revision); this.plannerWriteAuthority(by, this.studyParent(original.parentTaskId)); const before = this.studyReferences(original.parentTaskId, contract, id); this.studyRoundCheck(original, contract); const withheld = await this.withholds("note", JSON.stringify(contract), before.parent); requestCheck(); const latest = this.studyLatest(id, revision), current = this.studyReferences(latest.parentTaskId, contract, id); this.plannerWriteAuthority(by, current.parent); if (latest.hash !== original.hash || current.key !== before.key) throw new PreEffectToolRefusal("study changed during revision screening"); this.studyRoundCheck(latest, contract); const next: ResearchCampaignRecord = { id, project: this.d.project, parentTaskId: latest.parentTaskId, revision: revision + 1, status: "draft", contract, hash: campaignHash(contract), private: latest.private || current.private || withheld, createdBy: by, createdAt: this.studyTime() }; let saved: ResearchCampaignRecord; requestCheck(); this.plannerWriteAuthority(by, current.parent); try { saved = this.d.board.saveResearchCampaignDraft(next, revision, current.parent.history.length); } catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study revision was not saved"); } this.releaseNotice(`study ${id} revision ${saved.revision} drafted`); return this.studyReceipt(saved); }); } async studyApprove(by: PeerId, input: unknown): Promise { const requestCheck = this.requestCheck(by, () => this.studyHold()); if (by !== USER) throw new PreEffectToolRefusal("study approval requires the person"); const fields = this.studyFields(input, ["id", "revision"]), id = this.studyId(fields.id), revision = this.studyNumber(fields.revision, "revision"); return this.studyWrite(async () => { const original = this.studyRecord(id, revision), parent = this.studyParent(original.parentTaskId); if (original.status === "approved") { const privacy = this.studyReplayPrivacy(original, parent); requestCheck(); const replay = this.d.board.activateCampaign(id, revision, this.d.project, by, this.studyTime(), [], parent.history.length, privacy); return this.studyReceipt(replay.campaign, true); } this.studyLatest(id, revision); if (original.status !== "draft" || parent.draft) throw new PreEffectToolRefusal("study approval requires a draft and an approved parent input"); this.studyEligibleOwners(original.contract); const before = this.studyReferences(parent.id, original.contract, id); let priv = original.private || before.private || await this.withholds("note", JSON.stringify(original.contract), parent); const prepared: PreparedResearchUnit[] = []; for (const unit of original.contract.units) { requestCheck(); const reused = before.reused.get(unit.id); if (reused) { prepared.push({ unitId: unit.id, reuse: { taskId: reused.id, flowRevision: reused.history.length } }); continue; } const adopted = before.adopted.get(unit.id); if (adopted) { prepared.push({ unitId: unit.id, adopt: { taskId: adopted.id, flowRevision: adopted.history.length } }); continue; } const title = `Study unit ${unit.id}`, detail = `Study: ${id} unit ${unit.id}\nQuestion: ${unit.question}\nPerspective: ${unit.perspective}\nRequired output: ${unit.requiredOutput}\nSources: ${unit.sourceIds.join(", ")}`; priv ||= await this.withholds("task", detail, parent); const refs = cleanRefs(parent.refs), signals = [...new Set([...this.signalsFor({ title, detail, refs }), ...parent.signals.filter(signal => ["pii", "pii_path", "urgent"].includes(signal))])]; prepared.push({ unitId: unit.id, create: { title, detail, class: parent.class, refs, signals, ...(parent.profile ? { profile: parent.profile } : {}), ...(parent.profileClass ? { profileClass: parent.profileClass } : {}), } }); } requestCheck(); const latest = this.studyLatest(id, revision), current = this.studyReferences(parent.id, original.contract, id); if (latest.hash !== original.hash || current.key !== before.key) throw new PreEffectToolRefusal("study changed during approval screening"); const now = this.studyTime(), deadline = Date.parse(original.contract.stopPolicy.deadline); if (deadline <= now || deadline - now > 90 * 86_400_000) throw new PreEffectToolRefusal("study deadline must be in the next ninety days at approval"); priv ||= latest.private || current.private; const instruction = instructedExecution.getStore(); if (instruction?.active) { instruction.current(); if (priv || prepared.some(unit => unit.create?.signals?.some(signal => signal === "pii" || signal === "pii_path"))) throw new PreEffectToolRefusal("an instructed study approval cannot create private work; run it in a terminal"); } if (priv && [...current.adopted.values(), ...current.reused.values()].some(task => !this.isPii(task))) throw new PreEffectToolRefusal("a private study cannot retain a public task without changing its authority"); for (const unit of prepared) if (unit.create) { if (priv && !unit.create.signals?.includes("pii")) unit.create.signals = [...(unit.create.signals ?? []), "pii"]; const planner = this.proposalPlanner({ ...parent, ...unit.create, signals: unit.create.signals ?? [], refs: unit.create.refs ?? {}, draft: undefined, state: "backlog", owner: null, reviewer: null }); unit.create.planner = planner.planner; unit.create.plannerReason = planner.plannerReason; this.warmRepository({ refs: unit.create.refs ?? {}, plan: unit.create.plan }); } const mode = this.d.coordination?.(); let result: ReturnType; requestCheck(); instruction?.beginStudy?.(); // The synchronous board transaction now owns the screened binding. try { result = this.d.board.activateCampaign(id, revision, this.d.project, by, now, prepared, current.parent.history.length, priv, { eligibleOwners: this.studyEligibleOwners(original.contract) }); } catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study approval was not saved"); } for (const child of result.children) { this.incomingBacklog.add(child.id); if (mode !== undefined) this.coordinationModes.set(child.id, mode); } this.releaseNotice(`study ${id} revision ${revision} approved; ${result.bindings.length} units`); await this.studyReoffer(result.bindings.map(unit => unit.taskId)); return this.studyReceipt(result.campaign, true); }); } /** * A unit held only because a newer draft existed lost its queued offer at delivery. Once a revision is approved, each retained unit task whose offer was dropped, that still has * the same owner and has not been accepted, gets a fresh offer through the one offer path (`sendTask`), which re-runs `studyDispatchCheck`. The approval is already saved: a * refusal here is a notice, never a failure of the approval. */ private async studyReoffer(taskIds: readonly number[]): Promise { for (const taskId of taskIds) { let owner: PeerId | undefined; try { owner = this.d.board.researchDroppedOffer(taskId); } catch (e) { this.releaseNotice(`task #${taskId}: study dropped-offer record is unreadable: ${e instanceof Error ? e.message : String(e)}`); continue; } if (owner === undefined) continue; const task = this.d.board.get(taskId); // The record names an owner that no longer holds the unproposed task: it is stale, not a pending offer. if (!task || task.owner !== owner || task.state !== "proposed") { this.d.board.clearResearchDroppedOffer(taskId); continue; } try { await this.sendTask(task, { owner, ...(task.reviewer ? { reviewer: task.reviewer } : {}), trace: [] }); this.d.board.clearResearchDroppedOffer(taskId); // after the offer is published: a refusal keeps the record for the next approval } catch (e) { this.releaseNotice(`task ${this.publicTitle(task)}: could not re-offer after the study was approved: ${e instanceof Error ? e.message : String(e)}`); } } } async studyClose(by: PeerId, input: unknown): Promise { const requestCheck = this.requestCheck(by, () => this.studyHold()); this.plannerWriteAuthority(by); const fields = this.studyFields(input, ["id", "revision", "reason"]), id = this.studyId(fields.id), revision = this.studyNumber(fields.revision, "revision"); if (typeof fields.reason !== "string" || !fields.reason.trim() || Buffer.byteLength(fields.reason, "utf8") > 512) throw new PreEffectToolRefusal("study close needs a bounded reason"); const reason = fields.reason; return this.studyWrite(async () => { const original = this.studyLatest(id, revision), parent = this.studyParent(original.parentTaskId); this.plannerWriteAuthority(by, parent); const withheld = await this.withholds("note", reason, parent); requestCheck(); const latest = this.studyLatest(id, revision), currentParent = this.studyParent(latest.parentTaskId); this.plannerWriteAuthority(by, currentParent); if (latest.hash !== original.hash || currentParent.history.length !== parent.history.length) throw new PreEffectToolRefusal("study changed during close screening"); const priv = this.studyReplayPrivacy(latest, currentParent) || withheld || !this.nameable(reason); let closed: ResearchCampaignRecord; requestCheck(); this.plannerWriteAuthority(by, currentParent); try { closed = this.d.board.closeCampaign(id, revision, this.d.project, by, this.studyTime(), reason, currentParent.history.length, priv); } catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study close was not saved"); } this.releaseNotice(`study ${id} revision ${revision} closed`); return this.studyReceipt(closed); }); } private experimentHash(input: unknown): string { return createHash("sha256").update(canonicalJson(input)).digest("hex"); } private experimentId(input: unknown): string { if (typeof input !== "string" || !/^ra-[a-f0-9]{12}$/.test(input)) throw new PreEffectToolRefusal("experiment identity is invalid"); return input; } private experimentProtocol(hash: string): ExperimentProtocolRecord { try { const record = this.d.board.experimentProtocol(hash); if (record?.project === this.d.project) return record; } catch { /* damaged records are never returned as evidence */ } throw new PreEffectToolRefusal("experiment protocol is unavailable in this project"); } private experimentAttempt(id: string): ExperimentAttemptRecord { try { const record = this.d.board.experimentAttempt(id); if (record?.project === this.d.project) return record; } catch { /* fail closed without including any stored body */ } throw new PreEffectToolRefusal("experiment attempt is unavailable in this project"); } private experimentContext(by: PeerId, taskId: number, protocol: ExperimentProtocolContract, recordedForTaskId = taskId): ExperimentContext { const task = this.studyParent(taskId), bound = this.d.board.researchDispatchBinding(taskId); if (task.owner !== by || task.state !== "in_progress") throw new PreEffectToolRefusal("experiment records require the current in-progress task owner"); if (this.d.privateTurn?.(by) && !this.isPii(task)) throw new PreEffectToolRefusal("a private turn cannot write experiment records on a public task"); const campaign = bound?.campaign; // ponytail: new attempts against an older revision's protocol are refused; upgrade: explicit membership+source fence. if (!bound?.binding || !campaign || campaign.project !== this.d.project || campaign.id !== protocol.campaignId || campaign.revision !== protocol.campaignRevision || campaign.status !== "approved") throw new PreEffectToolRefusal("experiment task must be a unit of the protocol's current approved campaign revision"); const recording = this.d.board.researchDispatchBinding(recordedForTaskId), origin = this.studyParent(recordedForTaskId); if (!recording?.binding || recording.campaign.id !== campaign.id || recording.campaign.revision !== campaign.revision || recording.campaign.status !== "approved") throw new PreEffectToolRefusal("experiment recording task is no longer a unit of this campaign"); const sources = protocol.inputs.map(input => { const source = this.studySource(input.sourceId); if (!campaign.contract.sourceIds.includes(input.sourceId) || !source || source.sha256 !== input.sha256) throw new PreEffectToolRefusal("experiment input source identity or hash is unavailable in this campaign"); return source; }); let artifactPrivate = false; if ("deliverable" in protocol.code) { const reference = protocol.code.deliverable, artifact = latestDeliverables(origin.history)?.find(value => value.id === reference.id && value.sha256 === reference.sha256); if (!artifact) throw new PreEffectToolRefusal("experiment code deliverable identity is not recorded for its task"); artifactPrivate = artifact.private === true; } const privateRecord = this.studyReplayPrivacy(campaign, this.studyParent(campaign.parentTaskId)) || this.isPii(task) || this.isPii(origin) || artifactPrivate || sources.some(source => source.private); const fence: ExperimentWriteFence = { project: this.d.project, taskId, taskFlowRevision: task.history.length, owner: by, campaignId: campaign.id, campaignRevision: campaign.revision, campaignHash: campaign.hash }; return { task, campaign, private: privateRecord, fence, key: JSON.stringify([fence, sources, privateRecord, origin.history.length, recording.binding]) }; } private experimentFresh(before: ExperimentContext, by: PeerId, protocol: ExperimentProtocolContract, recordedForTaskId?: number): ExperimentContext { const current = this.experimentContext(by, before.task.id, protocol, recordedForTaskId); if (current.key !== before.key) throw new PreEffectToolRefusal("experiment authority, source or campaign changed during admission"); return current; } private async experimentScreen(text: string, task: Task): Promise { if (!this.isPii(task) && (!this.nameable(text) || looksSecret(text) || await this.withholds("note", text, task))) throw new PreEffectToolRefusal("experiment text was not cleared; nothing was recorded"); } private experimentPlanContext(by: PeerId, taskId: number, plan: ComparisonPlanV1): ExperimentContext { const task = this.studyParent(taskId), bound = this.d.board.researchDispatchBinding(taskId), campaign = bound?.campaign; if (task.owner !== by || task.state !== "in_progress" || !bound?.binding || !campaign || campaign.project !== this.d.project || campaign.id !== plan.campaignId || campaign.status !== "approved") throw new PreEffectToolRefusal("comparison plans require the current in-progress campaign unit owner"); if (this.d.privateTurn?.(by) && !this.isPii(task)) throw new PreEffectToolRefusal("a private turn cannot write comparison plans on a public task"); const sources = plan.fixed.inputs.map(input => { const source = this.studySource(input.sourceId); if (!campaign.contract.sourceIds.includes(input.sourceId) || !source || source.sha256 !== input.sha256) throw new PreEffectToolRefusal("comparison input source identity or hash is unavailable in this campaign"); return source; }); const privateRecord = this.studyReplayPrivacy(campaign, this.studyParent(campaign.parentTaskId)) || this.isPii(task) || sources.some(source => source.private); const fence: ExperimentWriteFence = { project: this.d.project, taskId, taskFlowRevision: task.history.length, owner: by, campaignId: campaign.id, campaignRevision: campaign.revision, campaignHash: campaign.hash }; return { task, campaign, private: privateRecord, fence, key: canonicalJson([fence, privateRecord, sources, bound.binding]) }; } private experimentApproved(record: ExperimentProtocolRecord): boolean { const approval = this.d.board.experimentProtocolApproval(record.hash); return protocolApprovalBindingMatches(record.protocol, approval && { protocolHash: approval.protocolHash, evaluatorHash: approval.evaluatorHash }); } /** Approval is an explicit person's decision about immutable bytes, including historical protocols. */ async experimentApproveProtocol(by: PeerId, input: unknown): Promise { const requestCheck = this.requestCheck(by, () => this.studyHold()); if (by !== USER) throw new PreEffectToolRefusal("protocol approval is person only"); const fields = this.studyFields(input, ["hash"]); if (typeof fields.hash !== "string" || fields.hash.length !== 64 || !/^[a-f0-9]{64}$/.test(fields.hash)) throw new PreEffectToolRefusal("protocol approval needs an exact protocol hash"); const hash = fields.hash; return this.studyWrite(async () => { requestCheck(); const record = this.experimentProtocol(hash), evaluatorHash = evaluatorIdentityHash(record.protocol); requestCheck(); let saved; try { saved = this.d.board.approveExperimentProtocol(this.d.project, hash, evaluatorHash, by, this.studyTime()); } catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "protocol approval was not saved"); } return { protocolHash: saved.protocolHash, evaluatorHash: saved.evaluatorHash, approvedBy: saved.approvedBy, approvedAt: saved.at }; }); } /** Record evidence only: this path never runs a check, a shell command or a runner. */ async experimentRecord(by: PeerId, input: { kind: "plan"; [key: string]: unknown }): Promise; async experimentRecord(by: PeerId, input: { kind: "protocol" | "attempt" | "event" | "receipt"; [key: string]: unknown }): Promise; async experimentRecord(by: PeerId, input: unknown): Promise; async experimentRecord(by: PeerId, input: unknown): Promise { const requestCheck = this.requestCheck(by, () => this.studyHold()); const envelope = this.studyFields(input, ["kind", "taskId", "protocol", "attempt", "attemptId", "idempotencyKey", "event", "plan", "receipt", "signature"]); return this.studyWrite(async () => { try { if (envelope.kind === "receipt") { const fields = this.studyFields(input, ["kind", "receipt", "signature"]), receipt = parseAttemptReceipt(fields.receipt); const attempt = this.experimentAttempt(receipt.attemptId), record = this.experimentProtocol(attempt.attempt.protocolHash); const relayOwner = by === USER ? this.studyParent(attempt.attempt.taskId).owner : by; if (!relayOwner) throw new PreEffectToolRefusal("receipt relay requires a current task owner"); const before = this.experimentContext(relayOwner, attempt.attempt.taskId, record.protocol, record.recordedForTaskId); requestCheck(); const proof = (stored: NonNullable>): ExperimentReceipt => ({ kind: "receipt", protocolHash: record.hash, attemptId: attempt.attemptId, seq: stored.seq, receiptId: receipt.receiptId }); const known = this.d.board.runnerReceipt(receipt.receiptId); if (known) { if (canonicalJson(known.receipt) !== canonicalJson(receipt) || known.signature !== fields.signature) throw new PreEffectToolRefusal("receiptId already records different signed bytes"); this.experimentFresh(before, relayOwner, record.protocol, record.recordedForTaskId); requestCheck(); return proof(known); // immutable stored proof: do not re-verify against a revoked/replaced registration or write on replay } const registrations = parseResearchRunners(this.d.researchRunners?.() ?? {}), registrationKey = canonicalJson(registrations); const context = { projectId: this.d.project, attempt: { id: attempt.attemptId, projectId: attempt.project, protocolHash: attempt.attempt.protocolHash, ...("commit" in record.protocol.code ? { codeCommit: record.protocol.code.commit } : {}) } }; verifyAttemptReceipt(receipt, fields.signature, { ...context, runners: registrations }); const lastSeq = this.d.board.experimentLastSeq(attempt.attemptId); await this.experimentScreen(canonicalJson(receipt), before.task); requestCheck(); const current = this.experimentFresh(before, relayOwner, record.protocol, record.recordedForTaskId); const latest = parseResearchRunners(this.d.researchRunners?.() ?? {}); if (canonicalJson(latest) !== registrationKey) throw new PreEffectToolRefusal("runner registration changed during receipt admission"); verifyAttemptReceipt(receipt, fields.signature, { ...context, runners: latest }); requestCheck(); const saved = this.d.board.appendRunnerReceipt({ receipt, signature: fields.signature as string, publicKey: latest[receipt.runner]!.publicKey, by, at: this.studyTime(), private: current.private || record.private || attempt.private }, lastSeq, current.fence); return proof(saved); } if (envelope.kind === "plan") { const fields = this.studyFields(input, ["kind", "taskId", "plan"]), taskId = this.studyNumber(fields.taskId, "taskId"), plan = parseComparisonPlan(fields.plan); const before = this.experimentPlanContext(by, taskId, plan); await this.experimentScreen(canonicalJson(plan), before.task); requestCheck(); const current = this.experimentPlanContext(by, taskId, plan); if (current.key !== before.key) throw new PreEffectToolRefusal("comparison authority, source or campaign changed during admission"); requestCheck(); const saved = this.d.board.saveExperimentComparisonPlan({ hash: comparisonPlanHash(plan), project: this.d.project, recordedForTaskId: taskId, plan, by, at: this.studyTime(), private: current.private }, current.fence); return { kind: "plan", planHash: saved.hash }; } if (envelope.kind === "protocol") { const fields = this.studyFields(input, ["kind", "taskId", "protocol"]), taskId = this.studyNumber(fields.taskId, "taskId"), protocol = parseExperimentProtocol(fields.protocol); const before = this.experimentContext(by, taskId, protocol); for (const reference of [protocol.variantOf, protocol.supersedes]) if (reference) { const previous = this.experimentProtocol(reference); if (previous.protocol.campaignId !== protocol.campaignId || reference === protocol.supersedes && previous.protocol.lineage !== protocol.lineage) throw new PreEffectToolRefusal("experiment protocol reference belongs to another campaign or lineage"); } await this.experimentScreen(canonicalJson(protocol), before.task); requestCheck(); const current = this.experimentFresh(before, by, protocol); requestCheck(); const saved = this.d.board.saveExperimentProtocol({ hash: protocolHash(protocol), project: this.d.project, recordedForTaskId: taskId, protocol, by, at: this.studyTime(), private: current.private }, current.fence); return { kind: "protocol", protocolHash: saved.hash }; } if (envelope.kind === "attempt") { const fields = this.studyFields(input, ["kind", "attempt"]), attempt = parseExperimentAttempt(fields.attempt), record = this.experimentProtocol(attempt.protocolHash); const before = this.experimentContext(by, attempt.taskId, record.protocol, record.recordedForTaskId); for (const reference of [attempt.retryOf, attempt.reproducesAttemptId]) if (reference) { const previous = this.experimentAttempt(reference), protocol = this.experimentProtocol(previous.attempt.protocolHash); if (protocol.protocol.campaignId !== record.protocol.campaignId) throw new PreEffectToolRefusal("attempt reference belongs to another campaign"); } await this.experimentScreen(canonicalJson(attempt), before.task); requestCheck(); const current = this.experimentFresh(before, by, record.protocol, record.recordedForTaskId); requestCheck(); const saved = this.d.board.createExperimentAttempt({ attemptId: `ra-${randomBytes(6).toString("hex")}`, project: this.d.project, attempt, bodyHash: this.experimentHash(attempt), by, at: this.studyTime(), private: current.private || record.private }, current.fence); return { kind: "attempt", protocolHash: saved.attempt.protocolHash, attemptId: saved.attemptId }; } if (envelope.kind === "event") { const fields = this.studyFields(input, ["kind", "attemptId", "idempotencyKey", "event"]), id = this.experimentId(fields.attemptId), key = fields.idempotencyKey; if (typeof key !== "string" || !key.trim() || key.length > 64 || Buffer.byteLength(key, "utf8") > 64 || Buffer.from(key, "utf8").toString("utf8") !== key) throw new PreEffectToolRefusal("event idempotencyKey needs at most 64 UTF-8 bytes"); const attempt = this.experimentAttempt(id), record = this.experimentProtocol(attempt.attempt.protocolHash), event = parseExperimentEvent(fields.event, record.protocol); const before = this.experimentContext(by, attempt.attempt.taskId, record.protocol, record.recordedForTaskId), lastSeq = this.d.board.experimentLastSeq(id); await this.experimentScreen(canonicalJson([key, event]), before.task); requestCheck(); this.experimentFresh(before, by, record.protocol, record.recordedForTaskId); const observations: ExperimentHostEvidence[] = []; let outputPrivate = event.kind === "output" && "path" in event.body ? this.experimentOutputPrivate(before.task, event.body.path) : false; if (event.kind === "end" && event.body.run && this.d.experimentCheck) { let receipt: unknown; try { receipt = await this.d.experimentCheck(event.body.run); } catch { /* unavailable is unknown */ } requestCheck(); this.experimentFresh(before, by, record.protocol, record.recordedForTaskId); const observation = checkRunObservation(receipt, event.body.run, before.task.id, record.protocol); if (observation) observations.push(observation); } else if (event.kind === "output" && "path" in event.body) { try { const measured = await hashDeliverables([event.body], this.deliverablePorts(before.task)); const output = measured[0]; if (output) { observations.push(deliverableObservation(output)); outputPrivate ||= output.private === true; } } catch { /* #509 refusal, missing or unreadable means unknown; never use a declared fallback hash */ } requestCheck(); this.experimentFresh(before, by, record.protocol, record.recordedForTaskId); } const current = this.experimentFresh(before, by, record.protocol, record.recordedForTaskId); requestCheck(); if (event.kind === "output" && "path" in event.body) outputPrivate ||= this.experimentOutputPrivate(current.task, event.body.path); const saved = this.d.board.appendExperimentEvent(id, key, event, observations, by, this.studyTime(), current.private || record.private || attempt.private || outputPrivate, lastSeq, current.fence); return { kind: "event", protocolHash: record.hash, attemptId: id, seq: saved.event.seq }; } throw new PreEffectToolRefusal("unsupported experiment record kind"); } catch (error) { if (error instanceof PreEffectToolRefusal) throw error; throw new PreEffectToolRefusal(error instanceof Error ? error.message : "experiment record was not saved"); } }); } private runnerKeyStatus(stored: NonNullable>): "active" | "revoked" | "replaced" | "unavailable" { try { const runners = parseResearchRunners(this.d.researchRunners?.() ?? {}); if (!Object.hasOwn(runners, stored.receipt.runner)) return "unavailable"; const current = runners[stored.receipt.runner]!; if (current.publicKey !== stored.publicKey) return "replaced"; if (current.revoked) return "revoked"; return current.projects.includes(stored.receipt.projectId) ? "active" : "unavailable"; } catch { return "unavailable"; } } private experimentPrivate(record: ExperimentProtocolRecord, attempt: ExperimentAttemptRecord): boolean { try { const campaign = this.d.board.researchCampaign(record.protocol.campaignId, record.protocol.campaignRevision), task = this.d.board.get(attempt.attempt.taskId); return record.private || attempt.private || !campaign || this.studyReplayPrivacy(campaign, this.studyParent(campaign.parentTaskId)) || !task || this.isPii(task) || record.protocol.inputs.some(input => { const source = this.studySource(input.sourceId); return !source || source.private; }); } catch { return true; } } async experimentShow(by: PeerId, input: unknown): Promise { return this.experimentRead(by, input); } private experimentRead(by: PeerId, input: unknown): ExperimentView { requireLocalTaskPeer(by); const fields = this.studyFields(input, ["attemptId", "campaignId", "after", "eventAfter", "limit", "planHash", "baselineAttemptId", "variantAttemptId"]); const cursor = (value: unknown, name: string) => value === undefined ? 0 : typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : (() => { throw new PreEffectToolRefusal(`${name} must be a nonnegative integer`); })(); const after = cursor(fields.after, "after"), eventAfter = cursor(fields.eventAfter, "eventAfter"), limit = fields.limit === undefined ? 50 : this.studyNumber(fields.limit, "limit"); if (limit > 50) throw new PreEffectToolRefusal("experiment readback is limited to 50 rows"); if (fields.planHash !== undefined || fields.baselineAttemptId !== undefined || fields.variantAttemptId !== undefined) { if (fields.attemptId !== undefined || fields.campaignId !== undefined || fields.after !== undefined || typeof fields.planHash !== "string" || fields.planHash.length !== 64 || !/^[a-f0-9]{64}$/.test(fields.planHash)) throw new PreEffectToolRefusal("comparison readback needs one plan hash and two attempt ids"); const plan = this.d.board.experimentComparisonPlan(fields.planHash); if (!plan || plan.project !== this.d.project) throw new PreEffectToolRefusal("comparison plan is unavailable in this project"); const baseline = this.experimentAttempt(this.experimentId(fields.baselineAttemptId)), variant = this.experimentAttempt(this.experimentId(fields.variantAttemptId)); const first = this.experimentProtocol(baseline.attempt.protocolHash), second = this.experimentProtocol(variant.attempt.protocolHash); if (first.protocol.campaignId !== plan.plan.campaignId || second.protocol.campaignId !== plan.plan.campaignId) throw new PreEffectToolRefusal("comparison attempts must belong to the plan's campaign"); const left = this.experimentRead(by, { attemptId: baseline.attemptId, eventAfter, limit }); const right = this.experimentRead(by, { attemptId: variant.attemptId, eventAfter, limit }); let planPrivate = true; try { const campaign = this.studyRecord(plan.plan.campaignId); planPrivate = plan.private || this.studyReplayPrivacy(campaign, this.studyParent(campaign.parentTaskId)) || plan.plan.fixed.inputs.some(input => { const source = this.studySource(input.sourceId); return !source || source.private; }); } catch { /* an unavailable privacy classification withholds the comparison */ } const privateRecord = planPrivate || left.attempts.some(row => row.private) || right.attempts.some(row => row.private); return { attempts: [...left.attempts, ...right.attempts], counts: left.counts, comparison: { planHash: plan.hash, baselineAttemptId: baseline.attemptId, variantAttemptId: variant.attemptId, approved: this.experimentApproved(first) && this.experimentApproved(second), private: privateRecord, projection: privateRecord ? "[pii]" : comparisonProjection(plan.plan, first.protocol, second.protocol) } }; } let campaignId: string, attempts: ExperimentAttemptRecord[], nextCursor: number | undefined; if (fields.attemptId !== undefined) { if (fields.campaignId !== undefined || fields.after !== undefined) throw new PreEffectToolRefusal("choose one attempt or campaign page"); const attempt = this.experimentAttempt(this.experimentId(fields.attemptId)); campaignId = this.experimentProtocol(attempt.attempt.protocolHash).protocol.campaignId; attempts = [attempt]; } else { campaignId = this.studyId(fields.campaignId); this.studyRecord(campaignId); const page = this.d.board.experimentAttempts(this.d.project, campaignId, after, limit); attempts = page.rows; if (!page.done) nextCursor = page.afterRow; } const summary = this.d.board.experimentSummary(this.d.project, campaignId), views: ExperimentAttemptView[] = []; for (const attempt of attempts) { const record = this.experimentProtocol(attempt.attempt.protocolHash), page = this.d.board.experimentEvents(attempt.attemptId, eventAfter, limit); const runnerReceipts = this.d.board.runnerReceipts(attempt.attemptId); const privateRecord = this.experimentPrivate(record, attempt) || page.rows.some(row => row.private) || runnerReceipts.some(row => row.private || !this.nameable(canonicalJson(row.receipt)) || looksSecret(canonicalJson(row.receipt))); const status = this.d.board.experimentAttemptStatus(attempt.attemptId); const observations = page.rows.flatMap(row => row.observations), events = page.rows.map(row => row.event); const evidence = { ...projectExperimentWithObservations(record.protocol, events, observations), ...(runnerReceipts.length ? { runnerAttested: runnerReceipts.map(row => ({ ...projectRunnerReceipt(record.protocol, row.receipt), key: { hash: row.keyHash, status: this.runnerKeyStatus(row) } })) } : {}) }; views.push({ id: attempt.attemptId, protocolHash: record.hash, taskId: attempt.attempt.taskId, phase: attempt.attempt.phase, status, private: privateRecord, campaignRevision: record.protocol.campaignRevision, approval: this.experimentApproved(record) ? "approved" : "unapproved", postHoc: this.d.board.experimentProtocolContext(record.hash).state, ...(attempt.attempt.retryOf ? { retryOf: attempt.attempt.retryOf } : {}), ...(attempt.attempt.reproducesAttemptId ? { reproducesAttemptId: attempt.attempt.reproducesAttemptId } : {}), independentlyReproduced: false, protocol: { value: privateRecord ? "[pii]" : record.protocol, provenance: "declared" }, events: page.rows.map(row => privateRecord ? { seq: row.event.seq, kind: row.event.kind, at: row.event.at, provenance: row.event.provenance, body: "[pii]" } : row.event), evidence: privateRecord ? { declared: "[pii]", measured: evidence.measured.map(row => ({ eventSeq: row.eventSeq, source: row.source, provenance: "host-observed", values: "[pii]" })), ...(runnerReceipts.length ? { runnerAttested: runnerReceipts.map(() => ({ provenance: "runner-attested", values: "[pii]" })) } : {}) } : evidence, eventsComplete: page.done, ...(!page.done ? { nextEventCursor: page.afterSeq } : {}) }); } return { attempts: views, counts: { all: summary.total, statuses: summary.statuses }, ...(nextCursor === undefined ? {} : { nextCursor }) }; } /** Every new host proposal, including split children, consumes the same pure walk before its first notification. */ private proposalPlanner(task: Task): PlannerBinding { const choice = assign({ ...task, state: "proposed" }, this.states(), this.d.routing(), { ...this.weights(task.class, task), candidates: [] }); return { planner: this.isPii(task) ? null : choice.planner ?? null, plannerReason: this.isPii(task) ? "none" : choice.plannerReason ?? "none" }; } private plannerBinding(task: Task, assignment: Assignment, bindNull = false): PlannerBinding | undefined { if (bindNull && task.planner == null) return { planner: this.isPii(task) ? null : assignment.planner ?? null, plannerReason: assignment.plannerReason ?? "none" }; return task.planner && this.plannerHolders().includes(task.planner) ? { planner: task.planner, plannerReason: "kept" } : undefined; } private planAuthor(task: Task): PeerId | null { // Review scope bookkeeping preserves the existing plan-content author. const authored = task.history.findLast(entry => entry.event !== "plan reviewed" && entry.planRevision !== undefined) ?? task.history.findLast(entry => entry.event !== "plan reviewed" && (entry.planning?.fields as readonly string[] | undefined)?.includes("plan")); if (authored && authored !== task.history[0]) return authored.by; return (ALL_PLAN_KEYS.some(key => !!task.plan?.[key]?.length) || !!task.plan?.base || !!task.plan?.out_of_scope?.length || !!task.plan?.stop_if?.length || !!task.plan?.steps?.length) ? authored?.by ?? task.history[0]?.by ?? null : null; } private planReviewAuthority(by: PeerId, task: Task): { planAuthor: PeerId | null; selfReview?: true } { this.plannerWriteAuthority(by); // Independent settled holders have review authority only, not the task's other planner powers. const author = this.planAuthor(task); const independent = this.plannerHolders().filter(peer => peer !== author && this.d.bus.stateOf(peer) !== "offline"); if (by !== USER && by === author && independent.length) throw new PreEffectToolRefusal("an independent planner reviews this plan"); return { planAuthor: author, ...(by === author ? { selfReview: true as const } : {}) }; } private requestIndependentPlanReview(task: Task): void { const author = this.planAuthor(task); if (!author || !this.taskPlanner(task).includes(author)) return; const planners = this.plannerHolders().filter(peer => peer !== author && this.d.bus.stateOf(peer) !== "offline"); if (!planners.length) return; const selected = assign({ ...task, state: "proposed" }, this.states(), this.d.routing(), { ...this.weights(task.class, task), candidates: [], planners, keptPlanner: undefined }).planner; if (!selected) return; const revision = task.planningRevision ?? 0, signature = `${revision}:${author}:${selected}`; if (this.planReviewRequests.get(task.id) === signature) return; const view = this.publicView(task); const queued = this.d.bus.publish(newEnvelope(HUB, `Independent plan review requested for task #${view.id}, revision ${revision}. Record hub_plan_review for that revision.`, { to: [selected], kind: "task", refs: { task: String(task.id), planReview: revision, planReviewFlow: task.history.length, planAuthor: author }, ...(this.isPii(task) ? { private: true } : {}), })); if (queued.includes(selected)) this.planReviewRequests.set(task.id, signature); } wipLimit(peer: PeerId): number { const limit = this.d.wipLimit?.(peer) ?? 1; if (!Number.isSafeInteger(limit) || limit < 0 || limit > 32) throw new PreEffectToolRefusal("invalid planner WIP capacity"); return limit; } private plannerPullRecord(task: Task): HistoryEntry["planning"] { return task.history.findLast(entry => entry.event === "backlog pulled" || entry.event === "backlog returned")?.planning; } private hasPersonReservation(task: Task): boolean { const reservation = task.history.findLast(entry => entry.event === "reserved" || entry.planning?.fields.includes("reserved") && !["backlog pulled", "backlog returned"].includes(entry.event)) ?? (task.history[0]?.event === "backlogged" ? task.history[0] : undefined); return !!task.reserved && reservation?.by === USER; } wip(peer: PeerId, except?: number): number { return this.d.board.plannerWip(peer, except); } /** Host-observed task branch/root binding (#845), never a tool-call branch claim or an execution grant. */ bindShellBranch(peer: PeerId, id: number, binding: TaskShellBinding & { worktree: string }, current: () => boolean): boolean { requireLocalTaskPeer(peer); try { if (!Number.isSafeInteger(id) || id < 1 || !taskShellBindingValid(binding) || !this.publicMetadataText(binding.branch) || !current() || this.d.privateTurn?.(peer)) return false; const task = this.d.board.get(id), root = this.d.executionRoot?.(peer); if (!task || task.owner !== peer || !["in_progress", "changes_requested"].includes(task.state) || this.isPii(task) || !root || realPath(root) === realPath(this.d.cwd) || realPath(root) !== realPath(binding.worktree)) return false; const worktree = createHash("sha256").update(realPath(root)).digest("hex"); const previous = task.history.findLast(entry => entry.by === HUB && entry.event === "shell branch bound"); if (previous) { const saved: unknown = JSON.parse(previous.note ?? ""); if (!saved || typeof saved !== "object" || Array.isArray(saved)) return false; const record = saved as Record; if (record.branch !== binding.branch || record.worktree !== worktree) return false; } if (task.refs.branch !== undefined && task.refs.branch !== binding.branch) return false; const scope = this.repositories.scope(task.refs); const others = this.d.board.list().filter(row => row.id !== id && !isClosedTaskState(row.state)) .map(row => ({ row, scope: this.repositories.scope(row.refs) })); if (scope.key !== this.repositories.project.key || others.some(other => other.scope.key === scope.key && other.row.refs.branch === binding.branch)) return false; if (!current() || this.d.privateTurn?.(peer) || this.d.board.get(id)?.history.length !== task.history.length) return false; if (previous) return true; let recorded = false; this.releaseNotice(`task #${id}: execution branch binding unavailable`, () => { this.d.board.update(id, HUB, "shell branch bound", { refs: { branch: binding.branch } }, JSON.stringify({ branch: binding.branch, worktree }), {}, task.history.length); recorded = true; }); return recorded; } catch { return false; } } private capacityBefore(task: Task): Map { return new Map([...new Set([task.owner, task.reserved])].filter((peer): peer is PeerId => !!peer).map(peer => [peer, this.wip(peer)])); } /** Write-driven wake-ups (#785): one unsettled ids-only task notice per planner, never a polling pull. */ private writePlannerNotices(task: Task, before: ReadonlyMap, approved = false): void { this.releaseNotice(`task #${task.id}: could not notify planner about ready work`, () => { const now = this.d.now?.() ?? Date.now(); const changes = new Map; ready: Set }>(); const add = (planner: PeerId, peer?: PeerId, id?: number) => { if (!this.d.bus.isRostered(planner)) return; const change = changes.get(planner) ?? { capacity: new Set(), ready: new Set() }; if (peer) change.capacity.add(peer); if (id !== undefined) change.ready.add(id); changes.set(planner, change); }; const released = new Set(); const readied = new Set(); for (const [peer, used] of before) if (this.wip(peer) < used) { released.add(peer); for (const planner of this.taskPlanner(task)) add(planner, peer); } if (approved) for (const card of this.d.board.list("backlog")) { if (card.deps?.includes(task.id) && !this.waitsFor(card).length && !plannedStartPending(card, now)) { for (const planner of this.taskPlanner(card)) add(planner, undefined, card.id); if (card.reserved) readied.add(card.reserved); } } for (const [planner, change] of changes) this.releaseNotice(`could not notify planner ${planner} about ready work`, () => { const pending = this.d.bus.pendingEnvelopes(planner).filter(env => env.from === HUB && env.kind === "task" && env.body.startsWith("Planner work ready:")); // The bus retains these hub-written lines across restart; an in-memory cache would lose unsettled events. for (const env of pending) for (const line of env.body.split("\n")) { const capacity = /^capacity_released: (\S+) WIP \d+; reserved ready (?:#\d+|none)$/.exec(line); if (capacity) change.capacity.add(capacity[1]!); const ready = /^backlog_ready: #(\d+)$/.exec(line); if (ready && Number.isSafeInteger(Number(ready[1]))) change.ready.add(Number(ready[1])); } const lines: string[] = []; for (const peer of change.capacity) { const top = this.topReservedReady(peer, planner); lines.push(`capacity_released: ${peer} WIP ${this.wip(peer)}; reserved ready ${top ? `#${top.id}` : "none"}`); } for (const id of change.ready) { const card = this.d.board.get(id); if (card?.state === "backlog" && this.taskPlanner(card).includes(planner) && !this.waitsFor(card).length && !plannedStartPending(card, now)) lines.push(`backlog_ready: #${id}`); else change.ready.delete(id); } for (const env of pending) this.d.bus.withdraw(env.id); const env = newEnvelope(HUB, sanitize(`Planner work ready:\n${lines.join("\n")}\nRead the current board before planning or pulling work.`), { to: [planner], kind: "task" }); if (!this.d.bus.publish(env).includes(planner)) throw new Error("the notice was not queued"); }); // Only this write's own release or newly ready dependency, never a merged earlier notice. if (this.d.autoPull?.() === true) this.queueAutoPulls(released); if (this.d.autoPull?.() === true) this.queueAutoPulls(new Set([...readied].filter(peer => !released.has(peer))), "backlog ready"); }); } /** The top card explicitly reserved for `peer` that this planner may pull now; the notice and the opt-in pull read the same rule. `pullable` keeps the staged backlog cards only. */ private topReservedReady(peer: PeerId, planner?: PeerId, pullable = false): Task | undefined { const now = this.d.now?.() ?? Date.now(); return this.d.board.list().filter(card => (pullable ? card.state === "backlog" : ["backlog", "proposed"].includes(card.state)) && !card.owner && card.reserved === peer && (planner === undefined || this.taskPlanner(card).includes(planner)) && !plannedStartPending(card, now) && !(pullable && this.isPii(card)) && !card.pinned && !card.needsPerson && !card.draft && taskCanPlan(card) && !this.waitsFor(card).length && !this.excluded(card).includes(peer) && (card.release == null || ["planning", "active"].includes(this.d.board.release(card.release)?.state ?? ""))).sort(this.readyOrder)[0]; } /** * #785 P1c: `tasks.auto_pull`. A trigger pulls the one top backlog card explicitly reserved for a peer, through `pullPlanned` as the hub acting for that card's planner of * record: revision, dependency, reservation, pinned, frozen-release, P0 order and WIP checks all run there unchanged. One card per release. Never an unreserved card, never PII. * Serialized on one chain, so concurrent triggers cannot pick the same card; each job re-reads the board, so a card that moved meanwhile is skipped. */ private autoPulls: Promise = Promise.resolve(); private autoPullsOpen = 0; /** Queued or running auto pulls, so a recovery commit waits for them the way it waits for `checksPending` (#785 P1c): one that is mid-admission would otherwise write after the commit's digest. */ autoPullsPending = (): number => this.autoPullsOpen; private queueAutoPulls(released: ReadonlySet, cause = "capacity released"): void { for (const peer of released) { this.autoPullsOpen++; this.autoPulls = this.autoPulls.then(() => this.autoPull(peer, cause)).catch(() => { /* autoPull reports its own refusals */ }).finally(() => { this.autoPullsOpen--; }); } } /** Whether the hub may still start work on its own: the setting is on, and no recovery, shutdown or storage hold is active. Read at entry and again right before the assignment write. */ private autoPullAdmitted(): boolean { return this.d.autoPull?.() === true && !this.d.sweepHeld?.() && !this.d.bus.isRecoveryHeld && !this.d.bus.storageError; } private async autoPull(peer: PeerId, cause: string): Promise { if (!this.autoPullAdmitted()) return; const card = this.topReservedReady(peer, undefined, true); if (!card) { await this.fillSlot(peer, cause); return; } // The planner of record is the card's own: its bound planner, else the first current holder, and it must be rostered. A private card never gets here (topReservedReady skips it). const planner = this.taskPlanner(card)[0]; if (!planner || !this.d.bus.isRostered(planner)) return; const reason = `auto_pull: ${cause} for ${peer}; hub acted for planner ${planner}`; try { await this.pullPlanned(HUB, { id: card.id, revision: card.planningRevision ?? 0, reason }, { onBehalfOf: planner, guard: () => { if (!this.autoPullAdmitted()) throw new PreEffectToolRefusal("auto pull is no longer admitted: tasks.auto_pull was turned off or a recovery, shutdown or storage hold began"); const current = this.d.board.get(card.id); if (current && plannedStartPending(current, this.d.now?.() ?? Date.now())) throw new PreEffectToolRefusal("auto pull is waiting for the planned start"); } }); } catch (e) { // A guard refusal is the setting or a hold doing its job, not a failure to report. const current = this.d.board.get(card.id); if (!this.autoPullAdmitted() || current && plannedStartPending(current, this.d.now?.() ?? Date.now())) return; this.releaseNotice(`task ${this.publicTitle(card)}: auto_pull for ${peer} refused: ${e instanceof Error ? e.message : String(e)}`); } } /** The first ready unowned task `peer` could be offered now, or undefined. Read-only. */ private fillPick(peer: PeerId): Task | undefined { if (!this.autoPullAdmitted() || this.capacityBackoff.has(peer)) return undefined; const now = this.d.now?.() ?? Date.now(); let routing: Routing; try { routing = this.d.routing(); } catch { return undefined; } return this.d.board.list("proposed").filter(task => this.fillEligible(task, peer, routing, now)).sort(this.readyOrder)[0]; } private fillEligible(task: Task, peer: PeerId, routing: Routing, now: number, mine = false): boolean { if (task.state !== "proposed" || task.owner || (!mine && (this.offered.has(task.id) || this.readyInFlight.has(task.id))) || (task.reserved && task.reserved !== peer)) return false; if (task.pinned || task.draft || task.needsPerson || this.isPii(task) || this.personUnassigned(task) || plannedStartPending(task, now) || this.waitsFor(task).length) return false; if (task.release != null && !["planning", "active"].includes(this.d.board.release(task.release)?.state ?? "")) return false; if (this.excluded(task).includes(peer)) return false; // `candidates: [peer]` replaces the class's peer list inside assign(), so the class list is checked here: a freed slot never takes a class routing keeps the peer out of. A class with no entry offers nothing. const weights = this.weights(task.class, task); if (!expandClassPeers(routing.classes[task.class]?.peers ?? [], this.states(), weights).includes(peer)) return false; return assign(task, this.states(), routing, { candidates: [peer], exclude: this.excluded(task), excludeOwners: this.hubOfferFull(task), waitsFor: this.waitsFor(task), ...weights }).owner === peer; } /** * #1626 B: no reserved card was ready for `peer`, so offer it the first ready, unowned `proposed` task it is an eligible owner for, in the board's ready order, one per trigger. * Runs on the serialized auto-pull chain through `assignOwner` as the hub with `peer` the only candidate, so every routing gate still runs. A task another offer path holds is skipped. */ private async fillSlot(peer: PeerId, cause: string): Promise { const pick = this.fillPick(peer); if (!pick) return; // The check and the slot are one synchronous step, as in offerReady: a second offer must see this one as taking the slot. this.offered.add(pick.id); this.readyInFlight.set(pick.id, peer); try { const fresh = this.d.board.get(pick.id); if (!fresh || !this.autoPullAdmitted() || !this.fillEligible(fresh, peer, this.d.routing(), this.d.now?.() ?? Date.now(), true)) return; const ready = fresh.history.at(-1)?.event === "ready" ? fresh : this.d.board.update(fresh.id, HUB, "ready", {}, `auto_pull: ${cause} for ${peer}`); await this.assignOwner(ready, HUB, { candidates: [peer], current: () => { if (!this.autoPullAdmitted()) throw new PreEffectToolRefusal("auto pull is no longer admitted"); } }); } catch (e) { if (e instanceof PreEffectToolRefusal || e instanceof AssignmentUndeliveredError || !this.autoPullAdmitted()) return; this.releaseNotice(`task ${this.publicTitle(pick)}: auto_pull for ${peer} could not offer it: ${e instanceof Error ? e.message : String(e)}`); } finally { this.readyInFlight.delete(pick.id); if (!this.d.board.get(pick.id)?.owner) this.offered.delete(pick.id); } } /** #784 AC3: the read-only breakdown of `wip` for status, the console and the dashboard: one grouped query for every peer. Admission still reads `wip()`. */ wipBreakdown(peers: readonly PeerId[]): Record { const grouped = this.d.board.plannerWipBreakdown(); return Object.fromEntries(peers.map(peer => { const row = grouped[peer] ?? { active: 0, reviewWait: 0, reserved: 0 }; return [peer, { wip: row.active + row.reviewWait + row.reserved, ...row, wipLimit: this.wipLimit(peer) }]; })); } private prerequisiteOf(task: Task, prerequisite: number): boolean { const pending = [...(task.deps ?? [])], seen = new Set(); while (pending.length) { const id = pending.pop()!; if (id === prerequisite) return true; if (seen.has(id)) continue; seen.add(id); pending.push(...(this.d.board.get(id)?.deps ?? [])); } return false; } /** * Peers that capacity-declined and have not reported idle since (#1626 A2). A TUI or headless agent works one task per turn, so it declines an offer far below its WIP cap while mid-turn. * ponytail: kept in memory, not derived from history. A restart reattaches every peer idle, which is exactly when the back-off ends, so nothing is lost; deriving it from history would need an idle marker the board does not record. */ private readonly capacityBackoff = new Set(); /** #1626 A: peers a hub-initiated offer skips: at the WIP cap (counting offers not yet accepted and in flight, as `reservedHold` does), a held queue, or backing off after a capacity decline. */ private hubOfferFull(task: Task): PeerId[] { const full = new Set(this.plannerFull(task)); for (const peer of Object.keys(this.states())) { if (this.capacityBackoff.has(peer)) { full.add(peer); continue; } const flying = [...this.readyInFlight].filter(([id, p]) => p === peer && id !== task.id && !this.d.board.get(id)?.owner).length; if (this.wip(peer, task.id) + (this.pendingClaims.get(peer) ?? 0) + flying >= this.wipLimit(peer)) full.add(peer); } return [...full]; } private plannerFull(task: Task): PeerId[] { return Object.keys(this.states()).filter(peer => { const queue = this.d.bus.queueSummary(peer); return this.wip(peer, task.id) >= this.wipLimit(peer) || !!queue.heldBy || queue.needsReview > 0; }); } /** * Why a planner pull finds no owner (#531), named from what the assignment saw and never from task text: the peers a * lasting exclusion keeps out, a peer at its WIP limit (with wip/limit), a held queue and needs_review. Peer ids and counts * only, so the text is safe for a PII task too. `route explain` reads the same `excluded()` and `plannerFull` inputs. */ plannerRefusal(task: Task): string { const parts: string[] = []; const excluded = [...new Set(this.excluded(task))]; const pressure = this.queueRouting(Object.keys(this.states())); if (excluded.length) parts.push(`${excluded.join(", ")} declined or was escalated away from this task for good; only a person's ahub task assign lifts that`); for (const peer of Object.keys(this.states())) { if (excluded.includes(peer)) continue; const queue = this.d.bus.queueSummary(peer), wip = this.wip(peer, task.id), limit = this.wipLimit(peer); if (wip >= limit) parts.push(`${peer} WIP full (${wip}/${limit}); no eligible planner WIP capacity`); else if (queue.heldBy) parts.push(`${peer} has a held queue (delivery ${queue.heldBy} is held; ahub queue show ${queue.heldBy} prints the full resolve command for the person)`); else if (queue.needsReview > 0) parts.push(`${peer} has ${queue.needsReview} delivery(ies) in needs_review`); const refusal = queueBackpressure(peer, pressure.queueBackpressure, peerEntry(pressure.queues, peer), pressure.now ?? NaN); if (refusal) parts.push(`${peer} ${refusal.reason}`); } return parts.length ? `no peer can take the planner pull: ${parts.join("; ")}` : "no peer has eligible planner WIP capacity"; } /** * #1430: the owner refusals routing itself recorded, named the way the reserved branch already names its peer: peer id and * reason only, never task text (#531), so the text is safe for a PII task. Undefined when routing recorded none. */ private ownerRefusals(assignment: Assignment): string | undefined { const refused = (assignment.refusals ?? []).filter(row => row.role === "owner"); return refused.length ? `routing refusals: ${refused.map(row => `${row.peer}: ${row.reason}`).join("; ")}` : undefined; } /** Keep routing refusals even when other peers also have known WIP or delivery pressure. */ private pullRefusal(task: Task, assignment: Assignment): string { const known = this.plannerRefusal(task); const routing = this.ownerRefusals(assignment); return routing ? `${known}; ${routing}` : known; } private plannerAssignment(task: Task, reservedOnly = false, routing: Routing = this.d.routing(), queueOverride?: "owner", projectedHealth?: ReturnType): Assignment { const states = this.states(); const full = this.plannerFull(task); // Preview the To Do transition without routing or offering the persisted backlog row. return assign({ ...task, state: "proposed" }, states, routing, { exclude: this.excluded(task), excludeOwners: [...full, ...this.studyExcludedOwners(task)], ...(reservedOnly && task.reserved ? { candidates: [task.reserved], namedOwner: task.reserved } : {}), waitsFor: this.waitsFor(task), ...this.weights(task.class, task, projectedHealth), ...(queueOverride ? { queueOverride, contextOverride: true } : {}) }); } async pullPlanned(by: PeerId, input: { id: number; revision: number; reason: string }, opts: { onBehalfOf?: PeerId; guard?: () => void } = {}): Promise { // #455: one authority check, made before the screen and again after it (a person may move the planner meanwhile). // #785 P1c: `by` is the actor the history records; the hub's opt-in auto pull names the planner it acts for, and that planner's authority is what is checked. if (opts.onBehalfOf !== undefined && by !== HUB) throw new PreEffectToolRefusal("only the hub pulls on a planner's behalf"); const planner = opts.onBehalfOf ?? by; let queueAssignment: { current: () => void } | undefined; // `opts.guard` (the auto pull's own admission, #785 P1c) throws a PreEffectToolRefusal once the pull is no longer wanted; it runs wherever authority is rechecked, so it // also runs after the awaited PII screen and right before the assignment write, where a setting turned off or a recovery that began meanwhile must still stop it. const instructionCheck = this.requestCheck(by); const authorized = () => { instructionCheck(); this.planningAuthority(planner); opts.guard?.(); queueAssignment?.current(); }; authorized(); if (!Number.isSafeInteger(input.id) || input.id <= 0 || !Number.isSafeInteger(input.revision) || input.revision < 0 || typeof input.reason !== "string" || !input.reason.trim() || input.reason.length > 1000) throw new PreEffectToolRefusal("planner pull needs an id, revision and bounded reason"); queueAssignment = by !== HUB && opts.onBehalfOf === undefined && this.d.board.get(input.id)?.reserved ? this.explicitQueueAssignment(by, "owner", true) : undefined; queueAssignment?.current(); const validate = () => { const task = this.d.board.get(input.id); if (task?.draft) throw new PreEffectToolRefusal(`task #${task.id} is an intake draft; the person approves it first`); if (!task || (task.planningRevision ?? 0) !== input.revision || task.state !== "backlog" || task.owner || !taskCanPlan(task) || task.pinned) throw new PreEffectToolRefusal("planner pull changed, pinned or already started"); // #1176: the one gate every agent pull passes (a planner's hub_backlog_pull and the opt-in auto pull alike): a person-run leg is never pulled into an agent's To Do. if (task.needsPerson) throw new PreEffectToolRefusal(`task #${task.id} is a person-run leg: it waits on the person (live receipts, their accounts or approvals), so no agent is offered it; the person runs it or clears the mark with ahub backlog plan`); this.planningAuthority(planner, task); const release = task.release == null ? undefined : this.d.board.release(task.release); if (task.release != null && (!release || ["frozen", "shipped", "dropped"].includes(release.state))) throw new PreEffectToolRefusal("planner pull requires unfrozen release scope"); if (this.waitsFor(task).length) throw new PreEffectToolRefusal("planner pull waits for dependency approval"); const priority = task.priority ?? (task.signals.includes("urgent") ? 0 : 2); if (priority === 0) { const goals = this.d.board.list().filter(goal => !isClosedTaskState(goal.state) && (goal.priority ?? (goal.signals.includes("urgent") ? 0 : 2)) === 0 && goal.rank != null && goal.history.some(entry => entry.by === USER && entry.planning?.fields.includes("rank"))); const effectiveOrder = (candidate: Task) => goals.filter(goal => goal.id === candidate.id || this.prerequisiteOf(goal, candidate.id)).map(goal => ({ rank: goal.rank!, id: goal.id })).sort((a,b) => a.rank-b.rank || a.id-b.id)[0]; const order = effectiveOrder(task) ?? { rank: task.rank ?? Number.MAX_SAFE_INTEGER, id: task.id }; if (this.d.board.list("backlog").some(other => { if (other.id === task.id || this.prerequisiteOf(other, task.id) || (other.priority ?? (other.signals.includes("urgent") ? 0 : 2)) !== 0) return false; const competing = effectiveOrder(other); return !!competing && (competing.rank < order.rank || competing.rank === order.rank && competing.id < order.id); })) throw new PreEffectToolRefusal("a person's P0 backlog order is retained"); } if (task.reserved && this.excluded(task).includes(task.reserved)) throw new PreEffectToolRefusal(this.plannerRefusal(task)); const assignment = this.plannerAssignment(task, !!task.reserved, this.d.routing(), queueAssignment ? "owner" : undefined); if (!assignment.owner) { // #1430: an unreserved card names what routing refused instead of dropping it, and every pull refusal names the route out. const personReserved = this.hasPersonReservation(task); const nextStep = personReserved ? "ask the person to change the reservation" : "reserve a peer with hub_backlog_plan fields.reserved, then pull again"; const refusal = task.reserved ? `reserved peer ${task.reserved} cannot take the planner pull: ${assignment.refusals?.find(row => row.role === "owner" && row.peer === task.reserved)?.reason ?? "not eligible"}; ${this.plannerRefusal(task)}` : this.pullRefusal(task, assignment); throw new PreEffectToolRefusal(`${personReserved ? "a person's reservation is retained; " : ""}${refusal}; ${nextStep}`); } this.studyDispatchCheck(task, assignment.owner); return { task, owner: assignment.owner, assignment }; }; const initial = validate(), withheld = await this.withholds("note", input.reason, initial.task); authorized(); const current = validate(); if (current.task.reserved) { return this.assignOwner(current.task, by, { candidates: [current.owner], namedOwner: current.owner, planner: true, refuseNamed: "pre", ...(queueAssignment ? { queueOverride: "owner" as const, current: queueAssignment.current } : {}), plannerPull: { revision: input.revision, note: input.reason.trim(), withheld, guard: () => { authorized(); const checked = validate(); if (checked.task.history.length !== current.task.history.length || checked.owner !== current.owner) throw new PreEffectToolRefusal("planner pull changed during admission"); } } }); } opts.guard?.(); this.studyDispatchCheck(current.task, current.owner); const pulled = this.d.board.pullPlanned(current.task.id, by, current.owner, input.revision, input.reason.trim(), withheld, this.plannerBinding(current.task, current.assignment, true)); this.planningRecorded({ by, task: pulled.id, fields: ["pull", "reserved"], revision: pulled.planningRevision! }); return pulled; } backlogList(by: PeerId): Record[] { this.planningAuthority(by); return this.d.board.list("backlog").sort((a, b) => (a.rank ?? Number.MAX_SAFE_INTEGER) - (b.rank ?? Number.MAX_SAFE_INTEGER) || a.id - b.id).map(task => this.publicView(task)); } private addPlannerBacklog(peer: PeerId, ids: readonly number[]): void { if (!this.d.roles?.[peer]?.includes("planner")) return; const pending = this.plannerBacklog.get(peer) ?? new Set(); for (const id of ids) { const task = this.d.board.get(id); if (task?.state === "backlog" && !task.draft && this.taskPlanner(task).includes(peer)) pending.add(id); } if (pending.size) this.plannerBacklog.set(peer, pending); } /** * The planner "board changed" notice (#758). Read only what was added to a card's history since the last scan, and tell each attached planner of * what it did not write itself and plans (`taskPlanner`, the #525-2 scoping): a planning revision or dependency change (in or outside a * `planning` entry) or the creation of a card is a task notice, replacing a copy that * is still unsettled so the planner meets the latest revision once; a state move, review or assignment is recorded at `fyi` weight (no turn), * at most once per planner per ten minutes. The hub's own bookkeeping entries tell nobody. A planner with no earlier notice gets one task notice * (a restart, or the first one after it was attached), as before. */ private groomNotices(configured: readonly PeerId[], planners: readonly PeerId[]): void { const scan = this.groomScan, revision = this.d.board.statusRevision(), first = scan.revision < 0; if (scan.revision !== revision) { for (const task of this.d.board.list()) { const seen = scan.lengths.get(task.id), depsKey = JSON.stringify(task.deps ?? []), depsBefore = scan.deps.get(task.id); scan.lengths.set(task.id, task.history.length); scan.deps.set(task.id, depsKey); if (first || seen === task.history.length && depsBefore === depsKey) continue; const holders = this.taskPlanner(task); const tell = (author: string, review: boolean) => { for (const holder of configured) { // every configured planner, so a change made while one was offline is not lost if (holder === author || !holders.includes(holder)) continue; const pending = scan.pending.get(holder) ?? { review: false, other: false }; if (review) pending.review = true; else pending.other = true; scan.pending.set(holder, pending); } }; // A card's creation (a propose, with or without `after`, a split child, a generated card) is new work to consolidate, so it needs a plan review. if (seen === undefined) tell(task.history[0]?.by ?? HUB, true); for (const entry of seen === undefined ? task.history.slice(1) : task.history.slice(seen)) { if (entry.by === HUB && entry.planning === undefined) continue; // the hub's own bookkeeping (lifecycle links, sweeps, holds) is not a board change to tell anyone about tell(entry.by, entry.planning !== undefined); } // Dependencies changed outside a `planning` entry (a propose with `after`, a split, any other write): the same as a planning change. // Its author is the last entry's only when this scan saw a new entry; a write with no entry has no known author, so no planner is skipped. if (depsBefore !== undefined && depsBefore !== depsKey) tell(seen !== undefined && seen < task.history.length ? task.history.at(-1)!.by : "", true); } scan.revision = revision; } const now = this.d.now?.() ?? Date.now(); const configuredFyiMin = this.d.groomFyiWindowMin?.(); const fyiWindowMs = configuredFyiMin === undefined ? GROOM_FYI_WINDOW_MS : configuredFyiMin * 60_000; for (const peer of planners) { const told = scan.sent.get(peer), pending = scan.pending.get(peer); const review = told === undefined || pending?.review === true; if (!review && !pending?.other) continue; if (!review && now - told!.fyiAt < fyiWindowMs) { scan.pending.delete(peer); continue; } this.releaseNotice(`could not notify planner ${peer} about grooming`, () => { if (review) this.sendGroomNotice(peer, revision); else this.d.bus.publish(newEnvelope(HUB, `${GROOM_NOTICE_PREFIX} (revision ${revision}): state moves, reviews or assignments only. No plan review is needed.`, { to: [peer], kind: "task", priority: "fyi" })); scan.pending.delete(peer); scan.sent.set(peer, { fyiAt: review ? told?.fyiAt ?? 0 : now }); }); } } /** The task-weight notice: an unsettled earlier copy for this planner is withdrawn and replaced, never a second one queued. */ private sendGroomNotice(peer: PeerId, revision: number): void { const body = `${GROOM_NOTICE_PREFIX} (revision ${revision}). Before offering or accepting build work, read hub_planner_groom, consolidate dependencies and priorities, and record hub_plan_review against the current planning revision.`; for (const old of this.d.bus.pendingEnvelopes(peer)) if (old.from === HUB && old.kind === "task" && old.body.startsWith(GROOM_NOTICE_PREFIX)) this.d.bus.withdraw(old.id); const recipients = this.d.bus.publish(newEnvelope(HUB, body, { to: [peer], kind: "task" })); if (!recipients.includes(peer)) throw new Error("the notice was not queued"); } /** One bounded ids-only batch per attached planner; failed or evicted copies stay pending. */ flushPlannerNotices(): number { const configured = Object.entries(this.d.roles ?? {}).filter(([peer, roles]) => !isRemotePeerId(peer) && roles.includes("planner")).map(([peer]) => peer); for (const peer of this.knownPlanners) if (!configured.includes(peer)) { this.knownPlanners.delete(peer); this.plannerBacklog.delete(peer); this.plannerBlockedQueue.delete(peer); this.groomScan.pending.delete(peer); this.groomScan.sent.delete(peer); } for (const peer of configured) if (!this.knownPlanners.has(peer)) { this.knownPlanners.add(peer); const retained = this.d.bus.queuedBacklogIds(peer); this.addPlannerBacklog(peer, this.d.board.list("backlog").filter(task => !retained.has(task.id)).map(task => task.id)); } const planners = configured.filter(peer => this.d.bus.isRostered(peer) && this.d.bus.peers.has(peer) && this.d.bus.stateOf(peer) !== "offline"); if (!planners.length) return 0; if ((this.d.sdlc?.config().mode ?? "off") !== "off") this.groomNotices(configured, planners); for (const id of this.incomingBacklog) if (this.d.board.get(id)?.state !== "backlog") this.incomingBacklog.delete(id); const incoming = [...this.incomingBacklog].sort((a, b) => a - b).slice(0, 64); if (incoming.length) { for (const peer of configured) { const queued = this.d.bus.queuedBacklogIds(peer); this.addPlannerBacklog(peer, incoming.filter(id => !queued.has(id))); } } for (const id of incoming) this.incomingBacklog.delete(id); const notified = new Set(); for (const peer of planners) { const pending = this.plannerBacklog.get(peer); if (!pending) continue; for (const id of pending) { const task = this.d.board.get(id); if (task?.state !== "backlog") pending.delete(id); else if (!this.taskPlanner(task).includes(peer)) { pending.delete(id); for (const recipient of this.taskPlanner(task)) this.addPlannerBacklog(recipient, [id]); } } const blockedQueue = this.plannerBlockedQueue.get(peer); if (blockedQueue !== undefined && blockedQueue === JSON.stringify(this.d.bus.queueIds(peer))) continue; this.plannerBlockedQueue.delete(peer); const ids = [...pending].sort((a, b) => a - b).slice(0, 64); if (!ids.length) continue; // Remove before publish: an immediate overflow callback may put this recipient's ids back. for (const id of ids) pending.delete(id); try { const queued = this.d.bus.publish(newEnvelope(HUB, `Backlog items ${ids.map(id => `#${id}`).join(", ")}. Read hub_backlog_list and plan the next work with a reason for each change.`, { to: [peer], kind: "task", refs: { backlog: ids } })); if (!queued.includes(peer)) this.addPlannerBacklog(peer, ids); for (const id of ids) notified.add(id); } catch (error) { this.addPlannerBacklog(peer, ids); throw error; } } return notified.size; } private roadmapReadAuthority(by: PeerId): void { requireLocalTaskPeer(by); if (this.d.privateTurn?.(by) || this.observerExcluded(by) || this.reviewObserverTurn(by)) throw new PreEffectToolRefusal("roadmap is unavailable during private or review-observer input; use ahub roadmap list after that turn"); } private roadmapWriteAuthority(by: PeerId): () => void { const check = this.requestCheck(by, () => this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError ? "roadmap writes are held by recovery, shutdown or storage; retry ahub roadmap list after recovery" : undefined); const current = () => { check(); this.roadmapReadAuthority(by); if (by !== USER && (!this.d.bus.isRostered(by) || !this.isConfiguredPlanner(by) && !this.configuredManualConductor(by))) throw new PreEffectToolRefusal("roadmap writes require a configured planner or the unique conductor; ask the person to run ahub roadmap"); }; current(); return current; } private roadmapParsed(read: () => T): T { try { return read(); } catch (error) { throw new PreEffectToolRefusal(`${error instanceof Error ? error.message : "invalid roadmap input"}; check ahub roadmap show and correct the fields`); } } private roadmapCurrent(id: unknown, state?: MilestoneState): Milestone { const row = this.d.board.milestone(this.roadmapParsed(() => milestoneId(id))); if (!row) throw new PreEffectToolRefusal("roadmap milestone does not exist; use ahub roadmap list"); if (["done", "dropped"].includes(row.state) && state !== row.state) throw new PreEffectToolRefusal("a settled milestone is final; create new work with ahub roadmap new"); return row; } private roadmapStateAuthority(by: PeerId, state: MilestoneState | undefined): void { if (state !== undefined && !(MILESTONE_STATES as readonly string[]).includes(state)) throw new PreEffectToolRefusal("invalid milestone state; use proposed, planned, active, done or dropped with ahub roadmap state"); if (by !== USER && (state === "done" || state === "dropped")) throw new PreEffectToolRefusal("done and dropped require the person; ask them to run ahub roadmap state"); } private roadmapTextCurrent(fields: MilestonePatch): string { const text = [fields.title, fields.outcome].filter((value): value is string => value !== undefined).join("\n"); if (text && !this.publicMetadataText(text)) throw new PreEffectToolRefusal("milestone text was not cleared for public planning; remove private content before ahub roadmap new or edit"); return text; } private async roadmapScreen(fields: MilestonePatch): Promise { const text = this.roadmapTextCurrent(fields); if (text && this.screenOn() && (await this.screenCall(text)).label !== "clear") throw new PreEffectToolRefusal("milestone text was not cleared for public planning; remove private content before ahub roadmap new or edit"); this.roadmapTextCurrent(fields); } private roadmapResult(by: PeerId, id: number): MilestoneView { try { return this.milestoneShow(by, id); } catch { throw new Error("roadmap operation finished but public readback is unavailable; inspect ahub roadmap show before retrying"); } } async milestoneNew(by: PeerId, raw: unknown): Promise { const current = this.roadmapWriteAuthority(by), fields = this.roadmapParsed(() => parseMilestoneInput(raw)); this.roadmapStateAuthority(by, fields.state); await this.roadmapScreen(fields); current(); this.roadmapStateAuthority(by, fields.state); this.roadmapTextCurrent(fields); const row = this.d.board.newMilestone(fields, by, this.d.now?.() ?? Date.now()); return this.roadmapResult(by, row.id); } async milestoneEdit(by: PeerId, id: number, revision: number, raw: unknown): Promise { const current = this.roadmapWriteAuthority(by), fields = this.roadmapParsed(() => parseMilestonePatch(raw)); this.roadmapParsed(() => milestoneRevision(revision)); this.roadmapStateAuthority(by, fields.state); const validate = () => { current(); this.roadmapStateAuthority(by, fields.state); const row = this.roadmapCurrent(id); if (row.revision !== revision) throw new PreEffectToolRefusal("roadmap revision changed; reload ahub roadmap show before editing"); return row; }; validate(); await this.roadmapScreen(fields); const row = validate(); this.roadmapTextCurrent(fields); if (Object.entries(fields).every(([key, value]) => row[key as keyof Milestone] === value)) return this.milestoneShow(by, id); this.d.board.updateMilestone(id, fields, revision, { by, at: this.d.now?.() ?? Date.now(), event: "edited", fields: Object.keys(fields) }); return this.roadmapResult(by, id); } milestoneLink(by: PeerId, id: number, kind: MilestoneLinkKind, raw: string): MilestoneView { this.roadmapWriteAuthority(by); const row = this.roadmapCurrent(id), ref = this.roadmapParsed(() => milestoneLinkRef(kind, raw)); if (!this.publicMetadataText(ref)) throw new PreEffectToolRefusal("roadmap reference is private; use a public reference with ahub roadmap link"); if (kind === "task" && !this.d.board.get(Number(ref)) || kind === "release" && !this.d.board.release(Number(ref))) throw new PreEffectToolRefusal("roadmap target does not exist; inspect ahub board or ahub release list before linking"); this.d.board.linkMilestone(id, kind, ref, by, row.revision, this.d.now?.() ?? Date.now()); return this.roadmapResult(by, id); } milestoneUnlink(by: PeerId, id: number, kind: MilestoneLinkKind, raw: string): MilestoneView { this.roadmapWriteAuthority(by); const row = this.roadmapCurrent(id), ref = this.roadmapParsed(() => milestoneLinkRef(kind, raw)); this.d.board.unlinkMilestone(id, kind, ref, by, row.revision, this.d.now?.() ?? Date.now()); return this.roadmapResult(by, id); } milestoneOrder(by: PeerId, id: number, order: number): MilestoneView { this.roadmapWriteAuthority(by); const row = this.roadmapCurrent(id), fields = this.roadmapParsed(() => parseMilestonePatch({ order })); if (row.order !== order) this.d.board.updateMilestone(id, fields, row.revision, { by, at: this.d.now?.() ?? Date.now(), event: "ordered", fields: ["order"] }); return this.roadmapResult(by, id); } milestoneState(by: PeerId, id: number, state: MilestoneState): MilestoneView { this.roadmapWriteAuthority(by); this.roadmapStateAuthority(by, state); this.roadmapParsed(() => parseMilestonePatch({ state })); const row = this.roadmapCurrent(id, state); // #1622 family 4: an instructed person verdict records the same three provenance keys task history does, for done and dropped only. const instruction = by === USER && (state === "done" || state === "dropped") ? instructedHistory(by) : {}; if (row.state !== state) this.d.board.updateMilestone(id, { state }, row.revision, { by, at: this.d.now?.() ?? Date.now(), event: "state", fields: ["state"], ...instruction }); return this.roadmapResult(by, id); } private roadmapSnapshot(by: PeerId): RoadmapSnapshot { let freshness: SpecsCheckReport["freshness"] | undefined; try { const report = this.d.specsRead?.("check", []); if (report && "freshness" in report && !report.truncated && report.errors === 0) freshness = report.freshness.filter(row => this.publicMetadataText(row.path) && (row.id === undefined || this.publicMetadataText(row.id))); } catch { /* unavailable evidence stays unknown */ } return { milestones: this.d.board.milestones(), links: this.d.board.milestoneLinks(), tasks: this.d.board.list(), releases: this.d.board.releases(), freshness, issueOf: task => { try { const source = this.planIssueIdentity(task); return source ? `${source.repo.toLowerCase()}#${source.issue}` : undefined; } catch { return undefined; } }, privateTask: task => this.isPii(task) || task.signals.includes("pii") || task.state === "backlog" && by !== USER && !this.isConfiguredPlanner(by), publicText: text => this.publicMetadataText(text), }; } milestoneList(by: PeerId): (MilestoneView & { tree: TreeRollup; readyToClose: ReadyToClose })[] { this.roadmapReadAuthority(by); const views = withTree(milestoneViews(this.roadmapSnapshot(by))); this.roadmapReadAuthority(by); return views; } milestoneShow(by: PeerId, id: number): MilestoneView { this.roadmapParsed(() => milestoneId(id)); const row = this.milestoneList(by).find(row => row.id === id); if (!row) throw new PreEffectToolRefusal("roadmap milestone does not exist; use ahub roadmap list"); return row; } /** Host-sampled GitHub authority is never supplied by a tool argument. */ private roadmapRepository(): string { const repo = this.roadmapParsed(() => githubRepo(this.d.repository)); let origin: string | undefined; try { origin = this.d.roadmapOrigin ? this.d.roadmapOrigin() : githubOriginRepository(this.d.cwd); } catch { /* unknown is not a trusted origin */ } if (!origin || origin.toLowerCase() !== repo) throw new PreEffectToolRefusal("roadmap GitHub origin is unavailable or does not match this project; inspect the local origin before retrying"); return repo; } private roadmapApplyAuthority(by: PeerId): void { this.roadmapReadAuthority(by); if (this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) throw new PreEffectToolRefusal("roadmap writes are held; retry after recovery"); if (by !== USER && (!(this.d.roadmapConfig?.().github_write === "conductor") || !this.configuredManualConductor(by) || !this.d.bus.isRostered(by))) throw new PreEffectToolRefusal("GitHub roadmap writes require the person or the configured conductor with roadmap.github_write enabled"); } /** Render only screened views. Issue writes require an exact preview and fresh authority. */ async roadmapExport(by: PeerId, input: { issue?: number; apply?: boolean; confirm?: string } = {}): Promise<{ json: string; markdown: string; fingerprint: string; call?: string[]; applied: boolean }> { const check = this.requestCheck(by, () => this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError ? "roadmap is held by recovery or storage" : undefined); check(); this.roadmapReadAuthority(by); if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => !["issue", "apply", "confirm"].includes(key)) || input.apply !== undefined && typeof input.apply !== "boolean" || input.confirm !== undefined && (typeof input.confirm !== "string" || !/^[a-f0-9]{64}$/.test(input.confirm))) throw new PreEffectToolRefusal("invalid roadmap export options; preview before applying"); if (input.issue !== undefined) this.roadmapParsed(() => milestoneId(input.issue)); if (input.apply && input.issue === undefined) throw new PreEffectToolRefusal("roadmap export --apply needs an issue; preview with --issue first"); if (input.apply) this.roadmapApplyAuthority(by); const rendered = roadmapExport(this.milestoneList(by)); const repo = input.issue === undefined ? undefined : this.roadmapRepository(); const call = repo === undefined ? undefined : ["api", `repos/${repo}/issues/${input.issue}`, "--hostname", "github.com", "--method", "PATCH", "-f", `body=${rendered.markdown}`]; const fingerprint = createHash("sha256").update(JSON.stringify({ repo: repo ?? null, issue: input.issue ?? null, markdown: rendered.markdown })).digest("hex"); if (!input.apply) return { ...rendered, fingerprint, ...(call ? { call } : {}), applied: false }; if (input.confirm !== fingerprint) throw new PreEffectToolRefusal(`roadmap export preview changed; run ahub roadmap export --issue ${input.issue} and retry with --confirm ${fingerprint}`); check(); this.roadmapApplyAuthority(by); if (this.roadmapRepository() !== repo) throw new PreEffectToolRefusal("roadmap GitHub origin changed; preview again"); let result: Awaited>; try { result = await this.roadmapGh()(call!, 10_000, undefined, 64 * 1024); } catch { throw new Error("roadmap issue update outcome is unknown; inspect the issue before retrying"); } if (result.code !== 0) throw new Error("roadmap issue update was not confirmed; inspect the issue before retrying"); try { check(); this.roadmapApplyAuthority(by); if (this.roadmapRepository() !== repo || roadmapExport(this.milestoneList(by)).markdown !== rendered.markdown) throw new Error("changed"); } catch { throw new Error("roadmap or authority changed after issue update; inspect the issue and preview again"); } return { ...rendered, fingerprint, call, applied: true }; } /** Build drift only from the same screened views and host-owned evidence as roadmap reads. */ async roadmapCheck(by: PeerId, include?: (finding: RoadmapDrift) => boolean): Promise> { const check = this.requestCheck(by); check(); this.roadmapReadAuthority(by); const views = this.milestoneList(by), config = this.d.roadmapConfig?.() ?? { github_mirror: false, github_write: "off" as const }, privacy = JSON.stringify([this.d.routing(), this.d.piiPaths, this.d.deny]); const snapshot = (rows: typeof views) => JSON.stringify([rows, rows.flatMap(view => view.tasks.map(member => this.d.board.get(member.id)))]); const evidence = snapshot(views); const current = () => { check(); this.roadmapReadAuthority(by); if (snapshot(this.milestoneList(by)) !== evidence || JSON.stringify(this.d.roadmapConfig?.() ?? { github_mirror: false, github_write: "off" }) !== JSON.stringify(config) || JSON.stringify([this.d.routing(), this.d.piiPaths, this.d.deny]) !== privacy) throw new PreEffectToolRefusal("roadmap or privacy policy changed while checking; retry ahub roadmap check"); }; const rendered = roadmapExport(views), exportStates: (boolean | undefined)[] = []; for (const [path, expected] of [["docs/roadmap.json", rendered.json], ["docs/roadmap.md", rendered.markdown]] as const) { try { const file = await readGuardedDeliverable(path, { cwd: this.d.cwd, deny: this.d.deny ?? [], private: name => matchesPolicy(this.d.cwd, name, this.d.piiPaths ?? [], true) }); current(); exportStates.push(Buffer.from(file.data).toString("utf8") === expected); } catch (error) { if (error instanceof PreEffectToolRefusal) throw error; exportStates.push(error instanceof DeliverableRefusal && error.message.includes("does not exist") ? false : undefined); } } const exportMatches = exportStates.includes(false) ? false : exportStates.every(value => value === true) ? true : undefined; current(); const refs = new Set(); for (const view of views) { for (const issue of view.issues) refs.add(issue.ref); for (const member of view.tasks) { const task = this.d.board.get(member.id); if (!task) continue; try { const source = this.planIssueIdentity(task); if (source && this.publicMetadataText(source.repo)) refs.add(`${source.repo.toLowerCase()}#${source.issue}`); } catch { /* ambiguous identity is unknown */ } } } const issueStates = new Map(), issueDeadline = performance.now() + 20_000; for (const ref of [...refs].sort().slice(0, 100)) { const match = /^([^#]+)#([1-9][0-9]*)$/.exec(ref); if (!match || issueDeadline <= performance.now()) break; const value = await readPlanIssueMetadata(match[1]!, Number(match[2]), async (args, timeout, cwd, cap) => { current(); const remaining = issueDeadline - performance.now(); return remaining > 0 ? this.roadmapGh()([...args.slice(0, 2), "--hostname", "github.com", ...args.slice(2)], Math.min(timeout ?? remaining, remaining), cwd, cap) : { code: 1, stdout: "" }; }); current(); if (value) issueStates.set(ref, value.state === "CLOSED" ? "closed" : "open"); } let mirror: Awaited> | undefined, repo: string | undefined; if (config.github_mirror) { try { repo = this.roadmapRepository(); mirror = await readMirrorSnapshot(repo, this.roadmapGh()); } catch { /* partial or unavailable evidence stays unknown */ } current(); } const milestones: DriftMilestone[] = views.map(view => { const tasks = view.tasks.map(member => { const task = this.d.board.get(member.id)!; let issue: string | null | undefined; try { const source = this.planIssueIdentity(task); issue = source ? `${source.repo.toLowerCase()}#${source.issue}` : null; } catch { issue = undefined; } const issueState: "open" | "closed" | "unknown" = issue ? issueStates.get(issue) ?? "unknown" : "unknown"; const merge = task.sdlc?.merge?.state === "merged" ? task.sdlc.merge : task.sdlc?.mergeReadback; const mergedAt = merge?.state === "merged" ? merge.cost?.mergedAt ?? undefined : task.sdlc?.pr && task.state === "approved" ? undefined : null; const report = merge?.state === "merged" ? this.currentSpecReport(task) : undefined; const unchangedSpecs = mergedAt === null ? [] : report?.complete && report.errors === 0 && !report.truncated && report.head === merge?.head ? report.unchanged.map(row => row.id) : undefined; return { id: task.id, state: task.state, issue, issueState, feature: /^feat(?:\([^)]*\))?:/i.test(task.title), specIssue: !!task.sdlc?.issue, mergedAt, unchangedSpecs }; }); const children = view.children.map(id => views.find(row => row.id === id)); const open = view.tasks.some(row => !["approved", "cancelled"].includes(row.state)) || view.issues.some(row => issueStates.get(row.ref) === "open") || view.releases.some(row => !["shipped", "dropped", "unknown"].includes(row.state)) || children.some(row => row && !["done", "dropped"].includes(row.state)); const uncertain = !!view.withheld || view.issues.some(row => !issueStates.has(row.ref)) || view.releases.some(row => row.state === "unknown") || children.some(row => !row); const merged = view.tasks.some(row => { const task = this.d.board.get(row.id); return task?.sdlc?.merge?.state === "merged" || task?.sdlc?.mergeReadback?.state === "merged"; }); let mirrorDiff: boolean | undefined; if (mirror && repo && !view.withheld && view.title !== "[withheld]") { try { const marker = ``, bound = this.d.board.mirrorMilestone(repo, view.id); const recovered = bound === undefined ? recoverMirrorBinding(marker, view.title, mirror.milestones) : undefined; if (recovered?.kind === "ambiguous" || recovered?.titleConflicts.length) mirrorDiff = true; else { const number = bound ?? (recovered?.kind === "bind" ? recovered.number : undefined), remote = number === undefined ? null : mirror.milestones.find(row => row.number === number); if (number === undefined || remote) mirrorDiff = bound === undefined || planRoadmapMirror(repo, { title: view.title, state: view.state === "done" || view.state === "dropped" ? "closed" : "open", marker, issues: view.issues.filter(row => row.ref.startsWith(`${repo}#`)).map(row => Number(row.ref.slice(repo!.length + 1))) }, remote ?? null, mirror.issues).calls.length > 0; } } catch { /* unknown mirror evidence */ } } return { id: view.id, state: view.state, tasks, openItems: open ? true : uncertain ? undefined : false, mergedCode: merged ? true : tasks.some(row => row.mergedAt === undefined) ? undefined : false, specs: view.specs, mirrorDiff }; }); current(); return checkRoadmap({ milestones, now: this.d.now?.() ?? Date.now(), closeLagMs: 24 * 60 * 60_000, mirrorEnabled: config.github_mirror, exportMatches }, include); } /** Serialize at the host caller. Persist only admitted ids-only notices, so unavailable feeds can retry. */ async roadmapNotify(taskIds: readonly number[], send: (task: number, milestone: number | null, rule: number, marker: string) => boolean): Promise { if (!taskIds.length) return 0; const views = this.milestoneList(HUB); if (!views.some(view => view.tasks.some(task => taskIds.includes(task.id)))) return 0; const select = (finding: RoadmapDrift) => { const referenced = finding.items.filter(item => /^task:[1-9][0-9]*$/.test(item)).map(item => Number(item.slice(5))); const eligible = views.filter(view => finding.milestone === null || view.id === finding.milestone).flatMap(view => view.tasks.map(task => task.id)); const marker = createHash("sha256").update(JSON.stringify([finding.rule, finding.milestone, finding.items, finding.cause])).digest("hex"); return !this.d.board.hasRoadmapNotice(marker) && taskIds.some(id => eligible.includes(id) && (!referenced.length || referenced.includes(id))); }; const checked = await this.roadmapCheck(HUB, select); let sent = 0; for (const finding of checked.findings) { const referenced = finding.items.filter(item => /^task:[1-9][0-9]*$/.test(item)).map(item => Number(item.slice(5))); const eligible = views.filter(view => finding.milestone === null || view.id === finding.milestone).flatMap(view => view.tasks.map(task => task.id)); const task = taskIds.find(id => eligible.includes(id) && (!referenced.length || referenced.includes(id))); if (task === undefined) continue; const marker = createHash("sha256").update(JSON.stringify([finding.rule, finding.milestone, finding.items, finding.cause])).digest("hex"); if (this.d.board.hasRoadmapNotice(marker)) continue; const latest = this.d.board.get(task); if (!latest || this.isPii(latest) || !this.milestoneList(HUB).some(view => (finding.milestone === null || view.id === finding.milestone) && view.tasks.some(row => row.id === task))) continue; if (send(task, finding.milestone, finding.rule, marker) && this.d.board.recordRoadmapNotice(marker)) sent++; } return sent; } /** Preview every fixed GitHub call from a complete inventory; confirmation binds both calls and local bindings. */ async roadmapSync(by: PeerId, input: { apply?: boolean; confirm?: string } = {}): Promise<{ repo: string; calls: string[][]; bindings: { milestone: number; number: number }[]; fingerprint: string; applied: boolean }> { this.roadmapReadAuthority(by); if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => key !== "apply" && key !== "confirm") || typeof input.apply !== "undefined" && typeof input.apply !== "boolean" || input.confirm !== undefined && (typeof input.confirm !== "string" || !/^[a-f0-9]{64}$/.test(input.confirm))) throw new PreEffectToolRefusal("invalid roadmap sync options; preview before applying"); if (input.apply) this.roadmapApplyAuthority(by); const config = this.d.roadmapConfig?.() ?? { github_mirror: false, github_write: "off" as const }; if (!config.github_mirror) throw new PreEffectToolRefusal("roadmap GitHub mirror is off; enable roadmap.github_mirror in trusted configuration before syncing"); const repo = this.roadmapRepository(), views = this.milestoneList(by); if (views.length > 100) throw new PreEffectToolRefusal("roadmap mirror exceeds 100 milestones; narrow the roadmap before syncing"); const deadline = performance.now() + 50_000; const stamp = () => createHash("sha256").update(JSON.stringify([this.d.board.milestones(), this.d.board.milestoneLinks(), this.d.board.list(), views.map(view => [view.id, this.d.board.mirrorMilestone(repo, view.id)]), this.d.roadmapConfig?.(), this.d.routing(), this.d.piiPaths, this.d.deny])).digest("hex"); let before = stamp(); const check = this.requestCheck(by, () => this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError ? "roadmap is held by recovery or storage" : undefined); const current = () => { check(); this.roadmapReadAuthority(by); if (input.apply) this.roadmapApplyAuthority(by); if (this.roadmapRepository() !== repo || stamp() !== before) throw new PreEffectToolRefusal("roadmap, origin or authority changed; preview sync again"); }; const run = this.roadmapGh(); const snapshot = await readMirrorSnapshot(repo, async (...args) => { current(); const result = await run(...args); current(); return result; }); current(); const bindings: { milestone: number; number: number }[] = [], calls: string[][] = [], createIds: (number | undefined)[] = [], issueOwners = new Set(); for (const view of views) for (const issue of view.issues) if (issue.ref.startsWith(`${repo}#`)) { const id = milestoneId(Number(issue.ref.slice(repo.length + 1))); if (issueOwners.has(id)) throw new PreEffectToolRefusal("an issue is linked to multiple roadmap milestones; settle its placement before syncing"); issueOwners.add(id); } for (const view of views) { if (view.withheld || view.title === "[withheld]" || view.outcome === "[withheld]") throw new PreEffectToolRefusal("roadmap mirror contains withheld membership or metadata; inspect privacy before syncing"); const marker = ``, bound = this.d.board.mirrorMilestone(repo, view.id); const matching = bound === undefined ? recoverMirrorBinding(marker, view.title, snapshot.milestones) : undefined; if (matching?.kind === "ambiguous" || matching?.titleConflicts.length) throw new PreEffectToolRefusal("roadmap GitHub milestone identity is ambiguous; inspect matching milestones before syncing"); const remoteId = bound ?? (matching?.kind === "bind" ? matching.number : undefined); if (bound === undefined && remoteId !== undefined) bindings.push({ milestone: view.id, number: remoteId }); const remote = remoteId === undefined ? null : snapshot.milestones.find(row => row.number === remoteId); if (remoteId !== undefined && !remote) throw new PreEffectToolRefusal("recorded GitHub milestone is missing from the complete inventory; inspect the binding"); const issues = view.issues.filter(row => row.ref.startsWith(`${repo}#`)).map(row => Number(row.ref.slice(repo.length + 1))); const planned = planRoadmapMirror(repo, { title: view.title, state: view.state === "done" || view.state === "dropped" ? "closed" : "open", issues, marker }, remote ?? null, snapshot.issues); for (const call of planned.calls) { const detached = /^repos\/[^/]+\/[^/]+\/issues\/([1-9][0-9]*)$/.exec(call[1] ?? ""); if (detached && call.includes("milestone=null") && issueOwners.has(Number(detached[1]))) continue; calls.push(call); createIds.push(remoteId === undefined ? view.id : undefined); if (calls.length > 200) throw new PreEffectToolRefusal("roadmap mirror exceeds 200 writes; narrow the roadmap before syncing"); } } const hiddenIssues = new Set(); for (const task of this.d.board.list()) if (this.isPii(task) || task.signals.includes("pii") || task.signals.includes("pii_path")) { try { const issue = this.planIssueIdentity(task); if (issue?.repo.toLowerCase() === repo) hiddenIssues.add(issue.issue); } catch { throw new PreEffectToolRefusal("private issue placement is unknown; inspect privacy before syncing"); } } if (calls.some(call => { const match = /^repos\/[^/]+\/[^/]+\/issues\/([1-9][0-9]*)$/.exec(call[1] ?? ""); return !!match && hiddenIssues.has(Number(match[1])); })) throw new PreEffectToolRefusal("roadmap mirror would change private issue membership; inspect privacy before syncing"); const fingerprint = createHash("sha256").update(JSON.stringify({ repo, bindings, calls })).digest("hex"); if (!input.apply) return { repo, calls, bindings, fingerprint, applied: false }; if (input.confirm !== fingerprint) throw new PreEffectToolRefusal(`roadmap sync preview changed; run ahub roadmap sync and retry with --confirm ${fingerprint}`); let effects = false; const effectCurrent = () => { try { current(); } catch (error) { if (effects) throw new Error("roadmap sync authority changed after effects; inspect the mirror and preview again before retrying"); throw error; } }; effectCurrent(); for (const binding of bindings) { effectCurrent(); try { this.d.board.bindMirrorMilestone(repo, binding.milestone, binding.number); effects = true; before = stamp(); } catch (error) { if (effects) throw new Error("roadmap binding changed after effects; inspect the mirror and preview again"); throw error; } } for (let index = 0; index < calls.length; index++) { effectCurrent(); let result: Awaited>; const remaining = deadline - performance.now(); if (remaining <= 0) { if (effects) throw new Error("roadmap sync reached its deadline after effects; inspect the mirror and preview again"); throw new PreEffectToolRefusal("roadmap sync deadline expired before writes; preview again"); } effects = true; try { result = await run(calls[index]!, Math.min(10_000, remaining), undefined, 64 * 1024); } catch { throw new Error("roadmap GitHub write outcome is unknown; inspect the mirror and preview again before retrying"); } if (result.code !== 0 || Buffer.byteLength(result.stdout) > 64 * 1024) throw new Error("roadmap GitHub write was not confirmed; inspect the mirror and preview again before retrying"); const local = createIds[index]; if (local !== undefined) { let number: number; try { const created = JSON.parse(result.stdout) as Record, call = calls[index]!; number = milestoneId(created.number); if (created.title !== call.find(value => value.startsWith("title="))?.slice(6) || created.description !== call.find(value => value.startsWith("description="))?.slice(12) || created.state !== call.find(value => value.startsWith("state="))?.slice(6) || typeof created.html_url !== "string" || created.html_url.toLowerCase() !== `https://github.com/${repo}/milestone/${number}`) throw new Error("mismatch"); } catch { throw new Error("roadmap milestone creation was not confirmed; preview again to recover its marker"); } effectCurrent(); try { this.d.board.bindMirrorMilestone(repo, local, number); before = stamp(); } catch { throw new Error("roadmap milestone was created but its binding is uncertain; preview again to recover its marker"); } } effectCurrent(); } return { repo, calls, bindings, fingerprint, applied: true }; } // ---- R3 (#1481): bottom-up placement. Reads are the roadmap read authority; every write below is the R1 writer, never a new one. ---- /** The one repository the roadmap reads from GitHub: the caller's choice, else the project's. Never derived from model text. */ private roadmapRepo(raw: unknown): string | undefined { if (raw === undefined) return undefined; return this.roadmapParsed(() => githubRepo(raw)); } private roadmapGh(run?: SdlcGh): SdlcGh { return run ?? this.d.roadmapGh ?? this.d.sdlc?.gh ?? ((args, timeout, _cwd, bound) => sdlcGh(args, timeout, this.d.cwd, bound)); } /** Issues, tasks and specs that no live milestone places, each with its reason. Private tasks are counted and never named. */ async roadmapUnplaced(by: PeerId, input: { repo?: unknown } = {}, run?: SdlcGh): Promise { this.roadmapReadAuthority(by); const repo = this.roadmapRepo(input.repo); let issues: Awaited> | undefined; try { issues = await readGitHubIssuePages({ ...(repo === undefined ? {} : { repo }) }, this.roadmapGh(run)); } catch { issues = undefined; } this.roadmapReadAuthority(by); let specs: { id: string; title: string; status: string | null }[] | undefined; try { const list = this.d.specsList?.(); if (list && !list.truncated && list.errors === 0) specs = list.specs; } catch { specs = undefined; } const snapshot = this.roadmapSnapshot(by); const result = computeUnplaced({ milestones: snapshot.milestones, links: snapshot.links, tasks: snapshot.tasks, issues, specs, issueOf: snapshot.issueOf, privateTask: snapshot.privateTask, publicText: snapshot.publicText }); return { ...result, repo: issues?.repo ?? repo ?? null }; } /** Pending and settled suggestions as a caller may read them: public text only. */ milestoneSuggestions(by: PeerId, state?: MilestoneSuggestion["state"]): MilestoneSuggestion[] { this.roadmapReadAuthority(by); return this.d.board.suggestions(state).filter(row => this.suggestionPublic(row)); } private suggestionPublic(row: MilestoneSuggestion): boolean { const text = [row.ref, row.citeItem, row.citeMilestone ?? "", row.proposal?.title ?? "", row.proposal?.outcome ?? ""].join("\n"); if (!this.publicMetadataText(text)) return false; if (row.kind !== "task") return true; const task = this.d.board.get(Number(row.ref)); return task !== undefined && !this.isPii(task) && !task.signals.includes("pii"); } /** * Ask the hub's model where unplaced items belong. The model sees only public text, answers are checked against what it was shown * (ids offered, cited words present), saved as pending suggestions, and nothing is linked: that is `roadmapAccept`. */ async roadmapTriage(by: PeerId, input: { repo?: unknown } = {}, run?: SdlcGh): Promise<{ suggestions: MilestoneSuggestion[]; asked: number; dropped: number; partial: boolean; unavailable: string | null }> { const current = this.roadmapWriteAuthority(by); const unplaced = await this.roadmapUnplaced(by, input, run); current(); const snapshot = this.roadmapSnapshot(by), views = milestoneViews(snapshot); const pending = new Set(this.d.board.suggestions("pending").map(row => `${row.kind}:${row.ref}`)); const items: TriageItem[] = [ ...unplaced.tasks.map(row => ({ kind: "task" as const, ref: String(row.id), text: row.title })), ...unplaced.issues.map(row => ({ kind: "issue" as const, ref: row.ref, text: row.title })), ...unplaced.specs.map(row => ({ kind: "spec" as const, ref: row.id, text: row.title })), ].filter(item => !pending.has(`${item.kind}:${item.ref}`)); const live = views.filter(view => view.state !== "done" && view.state !== "dropped" && view.title !== "[withheld]"); const batch = items.slice(0, TRIAGE_BATCH); const done = (suggestions: MilestoneSuggestion[], dropped: number, unavailable: string | null) => ({ suggestions, asked: batch.length, dropped, partial: unplaced.partial || items.length > batch.length, unavailable }); if (!batch.length) return done([], 0, null); if (!this.d.roadmapModel) return done([], 0, "no hub model is configured for roadmap triage"); const prompt = buildTriagePrompt(batch, live.map(view => ({ id: view.id, title: view.title, outcome: view.outcome }))); const answer = await this.d.roadmapModel(prompt.system, prompt.user, () => { try { current(); return true; } catch { return false; } }); current(); if (!answer) return done([], 0, "the hub model gave no answer; retry ahub roadmap triage later"); const parsed = parseTriage(answer, prompt), saved: MilestoneSuggestion[] = [], at = this.d.now?.() ?? Date.now(); for (const row of parsed.suggestions) { // Re-screen at the write: what is stored is public planning text only, and a milestone that has since settled is not a target. if (row.milestone !== null) { const target = this.d.board.milestone(row.milestone); if (!target || ["done", "dropped"].includes(target.state)) continue; } const text = [row.ref, row.citeItem, row.citeMilestone ?? "", row.proposal?.title ?? "", row.proposal?.outcome ?? ""].join("\n"); if (!this.publicMetadataText(text)) continue; if (this.screenOn() && (await this.screenCall(text)).label !== "clear") continue; current(); // A model's answer, attributed to the hub (never to the asker), is advisory data: no ask or memory path reads this table. const made = this.d.board.addSuggestion(row, "hub", at); if (made) saved.push(made); } return done(saved, parsed.dropped + parsed.suggestions.length - saved.length, null); } /** * R2 (#1480) part 1: ask the hub's model how one milestone decomposes. The model sees only the milestone's public text, the * specs it links and the issues it links; each part must cite an id it was shown, and the answer is saved as a hub-attributed * model answer. Nothing is intaken, linked, published or accepted here. */ async roadmapDecompose(by: PeerId, rawId: unknown, run?: SdlcGh): Promise<{ milestone: number; parts: DecomposePart[]; dropped: number; saved: MilestoneDecomposition | null; unavailable: string | null }> { const current = this.roadmapWriteAuthority(by); const id = this.roadmapParsed(() => milestoneId(rawId)), view = this.milestoneShow(by, id); current(); if (view.title === "[withheld]" || view.outcome === "[withheld]") throw new PreEffectToolRefusal("milestone text is not cleared for public planning; remove private content before ahub roadmap decompose"); const done = (parts: DecomposePart[], dropped: number, saved: MilestoneDecomposition | null, unavailable: string | null) => ({ milestone: id, parts, dropped, saved, unavailable }); const publicText = (value: string): boolean => { try { return this.publicMetadataText(value); } catch { return false; } }; let rows: { id: string; title: string; status: string | null; type?: string; paths?: string[] }[] | undefined; try { const list = this.d.specsList?.(); if (list && !list.truncated && list.errors === 0) rows = list.specs; } catch { rows = undefined; } const linked = new Set(view.specs.map(row => row.id)); // Every field that enters the prompt passes the same public screen R3's unplaced list uses; a spec that fails it is not // offered at all, exactly as an unplaced spec is dropped from triage. const summaries = (rows ?? []).filter(row => linked.has(row.id) && [row.id, row.title, ...(row.type ? [row.type] : []), ...(row.status ? [row.status] : []), ...(row.paths ?? []).slice(0, DECOMPOSE_PATHS)].every(publicText)); // The milestone's own context is the goal and architecture specs it links; when it links only other types, those are its context. const top = summaries.filter(row => row.type === "goal" || row.type === "architecture"); const specs: DecomposeItem[] = (top.length ? top : summaries).map(row => ({ ref: row.id, label: `spec ${row.id}`, text: `${row.title} (${row.type || "spec"}${row.status ? `, ${row.status}` : ""})${row.paths?.length ? ` covers: ${row.paths.slice(0, DECOMPOSE_PATHS).join(", ")}` : ""}` })); // Titles for linked issues come from the same bounded page read R3 uses. A ref outside that repository, an unreadable // page, or a title the public screen refuses still offers its id with no text, so a part can cite it; the milestone's own // links are the only source of refs. const refs = view.issues.map(row => row.ref), first = refs.length ? /^([^#]+)#[1-9][0-9]*$/.exec(refs[0]!)![1]! : undefined; const titles = new Map(); if (first !== undefined) { try { const page = await readGitHubIssuePages({ repo: first }, this.roadmapGh(run)); current(); for (const row of page.rows) if (publicText(row.title)) titles.set(`${page.repo}#${row.number}`, row.title); } catch { /* unavailable titles are not an empty list: the ref is still offered */ } } const issues: DecomposeItem[] = refs.map(ref => ({ ref, label: `issue ${ref}`, text: titles.get(ref) ?? "" })); if (!specs.length && !issues.length) return done([], 0, null, "the milestone links no spec or issue to decompose from"); if (!this.d.roadmapModel) return done([], 0, null, "no hub model is configured for roadmap decompose"); const prompt = buildDecomposePrompt({ milestone: { id, title: view.title, outcome: view.outcome }, specs: specs.slice(0, DECOMPOSE_ITEMS), issues: issues.slice(0, DECOMPOSE_ITEMS) }); const answer = await this.d.roadmapModel(prompt.system, prompt.user, () => { try { current(); return true; } catch { return false; } }); current(); if (!answer) return done([], 0, null, "the hub model gave no answer; retry ahub roadmap decompose later"); const parsed = parseDecomposition(answer, prompt), kept: DecomposePart[] = []; for (const part of parsed.parts) { // Re-screen at the write, exactly as triage does: what is stored is public planning text only. const text = [part.title, part.detail, ...part.cites].join("\n"); if (!this.publicMetadataText(text)) continue; if (this.screenOn() && (await this.screenCall(text)).label !== "clear") continue; current(); kept.push(part); } const dropped = parsed.dropped + parsed.parts.length - kept.length; if (!kept.length) return done([], dropped, null, null); const saved = this.d.board.addDecomposition({ milestone: id, parts: kept }, HUB, this.d.now?.() ?? Date.now()); return done(kept, dropped, saved, null); } /** * R2 (#1480) part 2: accept one proposed part as a held intake draft. The draft is the existing intake hold (`draft` and * `backlog`): nothing offers, pulls or routes it until the person approves it with `ahub intake approve`, and this path grants * no new release authority. It carries the milestone link and the part's `spec`/`task` kind, each part is accepted on its own, * and a second accept of the same part returns the draft the first one made. The reply is a public view, so a private draft * reads `[withheld]` and no notice repeats the part's words. One accept per part runs at a time: a concurrent caller waits for * the attempt in flight and then reads the accept row, so two accepts of one part cannot make two drafts. */ async roadmapDecomposePart(by: PeerId, rawId: unknown, rawPart: unknown): Promise<{ milestone: number; part: number; intake: DecomposeIntake; task: Record; created: boolean }> { const current = this.roadmapWriteAuthority(by); const id = this.roadmapParsed(() => milestoneId(rawId)), part = this.roadmapParsed(() => milestoneId(rawPart)); const view = this.milestoneShow(by, id); current(); if (view.title === "[withheld]" || view.outcome === "[withheld]") throw new PreEffectToolRefusal("milestone text is not cleared for public planning; remove private content before accepting a part"); const pending = this.d.board.pendingDecomposition(id); if (!pending) throw new PreEffectToolRefusal(`milestone ${id} has no pending decomposition; run ahub roadmap decompose ${id} first`); if (part > pending.parts.length) throw new PreEffectToolRefusal(`milestone ${id} holds ${pending.parts.length} proposed part${pending.parts.length === 1 ? "" : "s"}; run ahub roadmap decompose ${id} to read them again`); const chosen = pending.parts[part - 1]!; // A retry reads the draft the first accept made, and records the link again if an interrupted tail lost it. const earlier = this.roadmapAcceptedPart(by, id, pending.id, part); if (earlier) return earlier; const taskClass = CLASSES.includes(chosen.class as TaskClass) ? chosen.class as TaskClass : undefined; if (!taskClass) throw new PreEffectToolRefusal(`part ${part} names no hub task class; run ahub roadmap decompose ${id} to replace the answer`); // A milestone settled while its answer was pending refuses here, before any write. The same check runs again where the link // is written, and there it is best-effort: the draft is durable by then. this.roadmapCurrent(id); current(); // One accept per part: a concurrent caller of the same part waits for the attempt in flight and then reads the accept row. const key = `${pending.id}:${part}`, running = this.decompositionAccepts.get(key); if (running) { await running.catch(() => undefined); const after = this.roadmapAcceptedPart(by, id, pending.id, part); if (after) return after; if (this.d.board.pendingDecomposition(id)?.id !== pending.id) throw new PreEffectToolRefusal(`milestone ${id} has a newer decomposition answer; run ahub roadmap decompose ${id} to read it again`); } const attempt = this.acceptDecompositionPartOnce(by, id, part, pending, chosen, taskClass); this.decompositionAccepts.set(key, attempt); try { return await attempt; } finally { if (this.decompositionAccepts.get(key) === attempt) this.decompositionAccepts.delete(key); } } /** The accept row's own draft, while that task exists: the retry's answer, with the milestone link recorded again. */ private roadmapAcceptedPart(by: PeerId, id: number, decomposition: number, part: number): { milestone: number; part: number; intake: DecomposeIntake; task: Record; created: boolean } | undefined { const accepted = this.d.board.decompositionAccept(decomposition, part), earlier = accepted ? this.d.board.get(accepted.task) : undefined; if (!accepted || !earlier) return undefined; // Idempotent, so a missing link heals here; a milestone settled since refuses that as a notice, never as the caller's refusal. this.releaseNotice(`task #${earlier.id}: milestone ${id} part ${part} accepted without its milestone link`, () => { const milestone = this.roadmapCurrent(id); this.d.board.linkMilestone(id, "task", String(earlier.id), by, milestone.revision, this.d.now?.() ?? Date.now()); }); return { milestone: id, part, intake: accepted.intake, task: this.publicView(earlier), created: false }; } /** One accept attempt: the durable draft, then a tail that records the hold and never refuses the caller. */ private async acceptDecompositionPartOnce(by: PeerId, id: number, part: number, pending: MilestoneDecomposition, chosen: DecomposePart, taskClass: TaskClass): Promise<{ milestone: number; part: number; intake: DecomposeIntake; task: Record; created: boolean }> { const draft = await this.propose(by, { [HOST_ROADMAP_DRAFT]: true, title: chosen.title, detail: this.decompositionDraftDetail(chosen, id, part, pending.parts.length), class: taskClass, backlog: true, draft: true }); // The task and its hold are saved, so nothing below may fail the caller: a planner is not told about a held draft, and the // accept row, the milestone link and the notice are best-effort in that order. this.incomingBacklog.delete(draft.id); this.releaseNotice(`task #${draft.id}: milestone ${id} part ${part} accepted without its accept record`, () => { this.d.board.acceptDecompositionPart({ decomposition: pending.id, milestone: id, part, task: draft.id, intake: chosen.intake }, by, this.d.now?.() ?? Date.now()); }); this.releaseNotice(`task #${draft.id}: milestone ${id} part ${part} accepted without its milestone link`, () => { const milestone = this.roadmapCurrent(id); this.d.board.linkMilestone(id, "task", String(draft.id), by, milestone.revision, this.d.now?.() ?? Date.now()); }); this.releaseNotice(`task #${draft.id}: milestone ${id} part ${part} accepted as a held intake draft`); return { milestone: id, part, intake: chosen.intake, task: this.publicView(this.d.board.get(draft.id) ?? draft), created: true }; } /** The held draft's detail: the part's own words, then the one line a person reads before releasing it. */ private decompositionDraftDetail(part: DecomposePart, milestone: number, index: number, total: number): string { const kind = part.intake === "spec" ? "needs its own spec issue before implementation" : "a mechanical chore that goes straight to a task"; return [part.detail, `Milestone ${milestone} part ${index} of ${total}: ${kind}. Cites: ${part.cites.join(", ")}.`, `Held until released: ahub intake approve`].join("\n\n"); } /** * R2 (#1480) part 3: publish the milestone's held drafts to GitHub. `--publish` plans one issue per held `spec` part from a * complete reading of the holds and writes nothing; apply creates each issue through one gh call and links it to the * milestone: R1's own `issue` link, and the R4 membership field the create carries when the mirror has a binding, so this * path adds no second link. A `task` part is its own held draft, a released draft is no longer the hold's work, a private part * is only counted, and a refused or unconfirmed call leaves the draft held and names the failure. */ async roadmapDecomposePublish(by: PeerId, rawId: unknown, input: { apply?: boolean; confirm?: string } = {}): Promise<{ milestone: number; repo: string; githubMilestone: number | null; parts: PublishPlanPart[]; calls: string[][]; skippedPrivate: number; skippedUnknown: number; fingerprint: string; applied: boolean; created: { part: number; task: number; issue: number }[]; }> { const current = this.roadmapWriteAuthority(by); if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => key !== "apply" && key !== "confirm") || input.apply !== undefined && typeof input.apply !== "boolean" || input.confirm !== undefined && (typeof input.confirm !== "string" || !/^[a-f0-9]{64}$/.test(input.confirm))) throw new PreEffectToolRefusal("invalid roadmap publish options; preview with ahub roadmap decompose --publish before applying"); if (input.apply && input.confirm === undefined) throw new PreEffectToolRefusal("roadmap decompose --apply needs its preview fingerprint; preview with ahub roadmap decompose --publish first"); if (input.apply) this.roadmapApplyAuthority(by); const id = this.roadmapParsed(() => milestoneId(rawId)), view = this.milestoneShow(by, id); if (view.title === "[withheld]" || view.outcome === "[withheld]") throw new PreEffectToolRefusal("milestone text is not cleared for public planning; remove private content before publishing a part"); // A milestone settled while its drafts are held refuses here, before any read of GitHub or any write. this.roadmapCurrent(id); current(); const repo = this.roadmapRepository(), config = this.d.roadmapConfig?.() ?? { github_mirror: false, github_write: "off" as const }; // The GitHub milestone comes from the mirror binding, never from an argument; with the mirror off nothing is attached. const githubMilestone = config.github_mirror ? this.d.board.mirrorMilestone(repo, id) ?? null : null; const drafts: PublishDraft[] = [], held = new Map(); let skippedPrivate = 0, skippedUnknown = 0; for (const accept of this.d.board.decompositionAcceptsFor(id)) { const task = this.d.board.get(accept.task); if (!task) continue; const part = this.d.board.decomposition(accept.decomposition)?.parts[accept.part - 1]; // Without the answer a part's own words are gone; the draft stays held and the preview says to propose the parts again. const text = part ? [part.title, part.detail, ...part.cites].join("\n") : ""; let privatePart = true; try { privatePart = this.isPii(task) || !part || !this.publicMetadataText(text); } catch { privatePart = true; } if (part && !privatePart && this.screenOn()) { const label = (await this.screenCall(text)).label; current(); privatePart = label !== "clear"; } if (!part) { skippedUnknown++; continue; } if (privatePart) { skippedPrivate++; continue; } held.set(task.id, accept); drafts.push({ part: accept.part, task: task.id, intake: accept.intake, title: part.title, detail: part.detail, cites: part.cites, published: this.d.board.decompositionPublish(accept.decomposition, accept.part) ?? null, hold: task.draft === true && task.state === "backlog" ? "held" : "released" }); } const planned = planPartPublish({ project: this.d.project, repo, milestone: id, githubMilestone, parts: drafts }); const fingerprint = createHash("sha256").update(JSON.stringify({ repo, milestone: id, githubMilestone, calls: planned.calls })).digest("hex"); const reply = { milestone: id, repo, githubMilestone, ...planned, skippedPrivate, skippedUnknown, fingerprint, applied: false as boolean, created: [] as { part: number; task: number; issue: number }[] }; if (!input.apply) return reply; if (input.confirm !== fingerprint) throw new PreEffectToolRefusal(`roadmap publish preview changed; run ahub roadmap decompose ${id} --publish and retry with --confirm ${fingerprint}`); current(); this.roadmapApplyAuthority(by); if (this.roadmapRepository() !== repo) throw new PreEffectToolRefusal("roadmap GitHub origin changed; preview the publish again"); // A retried call whose first attempt is still creating must not POST every planned issue again: `INSERT OR IGNORE` would keep // the first publish row and GitHub would keep both issues. One apply per milestone, refused with the next step it can take. if (this.roadmapPublishes.has(id)) throw new PreEffectToolRefusal(`a publish for milestone ${id} is already running; wait for it to finish and run ahub roadmap decompose ${id} --publish again`); this.roadmapPublishes.add(id); try { const creating = planned.parts.filter(row => row.action === "create"), created = reply.created; for (const [index, call] of planned.calls.entries()) { const row = creating[index]!, accept = held.get(row.task)!; // A part an earlier attempt already recorded has its issue: never POST it a second time. if (this.d.board.decompositionPublish(accept.decomposition, row.part) !== undefined) continue; const refused = `roadmap publish was refused for milestone ${id} part ${row.part}; the draft stays held and no issue was linked. Inspect ${repo} before retrying`; let result: Awaited>; try { result = await this.roadmapGh()(call, 10_000, undefined, 64 * 1024); } catch { throw new Error(`roadmap publish was not confirmed for milestone ${id} part ${row.part}; the draft stays held and no issue was linked. Inspect ${repo} before retrying`); } if (result.code !== 0 || Buffer.byteLength(result.stdout) > 64 * 1024) throw new Error(refused); let issue: number; try { const made = JSON.parse(result.stdout) as Record; issue = milestoneId(made.number); if (made.title !== call.find(value => value.startsWith("title="))?.slice(6) || typeof made.html_url !== "string" || made.html_url.toLowerCase() !== `https://github.com/${repo}/issues/${issue}`) throw new Error("mismatch"); } catch { throw new Error(`roadmap publish created an issue for milestone ${id} part ${row.part} but its answer was not confirmed; inspect ${repo} before retrying`); } // The issue exists, so nothing below may refuse the caller: the publish record and the milestone link are best effort. this.releaseNotice(`milestone ${id} part ${row.part}: issue ${repo}#${issue} created without its publish record`, () => { this.d.board.recordDecompositionPublish({ decomposition: accept.decomposition, milestone: id, part: row.part, issue }, by, this.d.now?.() ?? Date.now()); }); this.releaseNotice(`milestone ${id} part ${row.part}: issue ${repo}#${issue} created without its milestone link`, () => { const milestone = this.roadmapCurrent(id); this.d.board.linkMilestone(id, "issue", `${repo}#${issue}`, by, milestone.revision, this.d.now?.() ?? Date.now()); }); created.push({ part: row.part, task: row.task, issue }); } reply.applied = true; return reply; } finally { this.roadmapPublishes.delete(id); } } /** Apply one suggestion through R1's own writers. A "new milestone" suggestion creates it first; a retry never creates a second. */ async roadmapAccept(by: PeerId, rawId: unknown): Promise<{ suggestion: MilestoneSuggestion; milestone: MilestoneView }> { const current = this.roadmapWriteAuthority(by); const id = this.roadmapParsed(() => milestoneId(rawId)), row = this.d.board.suggestion(id); if (!row) throw new PreEffectToolRefusal("roadmap suggestion does not exist; use ahub roadmap triage"); if (row.state !== "pending") throw new PreEffectToolRefusal(`roadmap suggestion was already ${row.state}; run ahub roadmap triage for current suggestions`); if (!this.suggestionPublic(row)) throw new PreEffectToolRefusal("roadmap suggestion text is no longer public; reject it with ahub roadmap reject"); let target = row.milestone ?? this.d.board.suggestionCreated(id); if (target === undefined) { const proposal = row.proposal; if (!proposal) throw new PreEffectToolRefusal("roadmap suggestion has no target; reject it with ahub roadmap reject"); const fields = this.roadmapParsed(() => parseMilestoneInput({ title: proposal.title, outcome: proposal.outcome })); await this.roadmapScreen(fields); current(); const made = this.d.board.newMilestone(fields, by, this.d.now?.() ?? Date.now()); this.d.board.setSuggestionCreated(id, made.id); target = made.id; } const milestone = this.roadmapCurrent(target); const ref = this.roadmapParsed(() => milestoneLinkRef(row.kind, row.ref)); if (row.kind === "task" && !this.d.board.get(Number(ref))) throw new PreEffectToolRefusal("roadmap target does not exist; reject the suggestion with ahub roadmap reject"); current(); this.d.board.linkMilestone(target, row.kind, ref, by, milestone.revision, this.d.now?.() ?? Date.now()); const settled = this.d.board.settleSuggestion(id, "accepted", by, this.d.now?.() ?? Date.now()); return { suggestion: settled, milestone: this.roadmapResult(by, target) }; } roadmapReject(by: PeerId, rawId: unknown): MilestoneSuggestion { this.roadmapWriteAuthority(by); const id = this.roadmapParsed(() => milestoneId(rawId)); return this.d.board.settleSuggestion(id, "rejected", by, this.d.now?.() ?? Date.now()); } /** * One-time import of open GitHub milestones as `proposed` milestones, linking their open issues. A dry run unless `apply`. * A repeat finds each milestone's import mark and each link, so a second `apply` changes nothing. Nothing is ever written to GitHub. */ async roadmapImportGitHub(by: PeerId, input: { repo?: unknown; apply?: unknown } = {}, run?: SdlcGh): Promise<{ repo: string; apply: boolean; partial: boolean; milestones: { number: number; title: string; milestone: number | null; action: "create" | "exists"; issues: string[]; newLinks: number }[]; created: number; linked: number; withheld: number; }> { const current = this.roadmapWriteAuthority(by); if (by !== USER) throw new PreEffectToolRefusal("GitHub milestone import is a console command; ask the person to run ahub roadmap import-github"); if (input.apply !== undefined && typeof input.apply !== "boolean") throw new PreEffectToolRefusal("roadmap import apply must be true or false; omit it for a dry run"); const apply = input.apply === true, gh = this.roadmapGh(run), repoInput = this.roadmapRepo(input.repo); const milestonePages = await readGitHubMilestonePages({ ...(repoInput === undefined ? {} : { repo: repoInput }) }, gh); const issuePages = await readGitHubIssuePages({ repo: milestonePages.repo }, gh); current(); const issuesOf = new Map(); for (const row of issuePages.rows) if (row.milestone !== null) issuesOf.set(row.milestone, [...(issuesOf.get(row.milestone) ?? []), `${issuePages.repo}#${row.number}`]); const out: { number: number; title: string; milestone: number | null; action: "create" | "exists"; issues: string[]; newLinks: number }[] = []; let created = 0, linked = 0, withheld = 0; for (const source of milestonePages.rows) { const description = source.description || `Imported from GitHub milestone ${milestonePages.repo}#milestone/${source.number}`; let fields: ReturnType; try { fields = parseMilestoneInput({ title: source.title, outcome: description.slice(0, 4000), ...(source.due ? { target: source.due } : {}) }); } catch { withheld++; continue; } const prior = this.d.board.importedMilestone(milestonePages.repo, source.number), existing = prior === undefined ? undefined : this.d.board.milestone(prior); const refs = (issuesOf.get(source.number) ?? []).filter(ref => this.publicMetadataText(ref)); const have = new Set(existing ? this.d.board.milestoneLinks(existing.id).filter(link => link.kind === "issue").map(link => link.ref) : []); const newRefs = refs.filter(ref => !have.has(ref)); const text = `${fields.title}\n${fields.outcome}`; if (!this.publicMetadataText(text)) { withheld++; continue; } const row = { number: source.number, title: sanitize(fields.title), milestone: existing?.id ?? null, action: existing ? "exists" as const : "create" as const, issues: refs, newLinks: newRefs.length }; if (apply) { // The model screen runs on apply only, for a milestone about to be created; a dry run lists what passes the pattern screen. if (!existing && this.screenOn() && (await this.screenCall(text)).label !== "clear") { withheld++; continue; } current(); const made = this.d.board.importMilestone(milestonePages.repo, source.number, fields, by, this.d.now?.() ?? Date.now()); if (made.created) created++; row.milestone = made.milestone.id; for (const ref of newRefs) { const live = this.d.board.milestone(made.milestone.id)!; // A settled milestone is final: an import never reopens or relinks it. if (["done", "dropped"].includes(live.state)) break; const before = this.d.board.milestoneLinks(made.milestone.id).length; this.d.board.linkMilestone(made.milestone.id, "issue", ref, by, live.revision, this.d.now?.() ?? Date.now()); if (this.d.board.milestoneLinks(made.milestone.id).length > before) linked++; } } out.push(row); } return { repo: milestonePages.repo, apply, partial: milestonePages.partial || issuePages.partial, milestones: out, created, linked, withheld }; } releaseList(by: PeerId): Record[] { this.planningAuthority(by); const scopes = new Map(); type Approval = { id: number; release: Task["release"]; doneAt: number | null }; const approved: Approval[] = [], owned = new Map(); for (const task of this.d.board.list()) { if (typeof task.release === "number") { const scope = scopes.get(task.release) ?? []; scope.push({ id: task.id, state: task.state, deps: task.deps ?? [] }); scopes.set(task.release, scope); } if (task.state !== "approved") continue; const row = { id: task.id, release: task.release, doneAt: actualTaskDates(task).doneAt }; approved.push(row); if (typeof task.release === "number") { const rows = owned.get(task.release) ?? []; rows.push(row); owned.set(task.release, rows); } } const compare = (a: Approval, b: Approval) => a.doneAt! - b.doneAt! || a.id - b.id; const known = approved.filter(task => task.doneAt !== null).sort(compare), unknown = approved.filter(task => task.doneAt === null); const after = (rows: Approval[], cut: number) => { let low = 0, high = rows.length; while (low < high) { const mid = Math.floor((low + high) / 2); if (rows[mid]!.doneAt! <= cut) low = mid + 1; else high = mid; } return low; }; // ponytail: audit previews show 32 ids plus exact counts; add a paginated audit endpoint for exhaustive lists. const outsideIds = (rows: Approval[], start: number, release: number) => { const result: number[] = []; for (let i = start; i < rows.length && result.length < 32; i++) if (rows[i]!.release !== release) result.push(rows[i]!.id); return result; }; return this.d.board.releases().map(release => { const own = owned.get(release.id) ?? [], ownKnown = own.filter(task => task.doneAt !== null).sort(compare); const cutStart = release.cut === null ? known.length : after(known, release.cut); const unknownPool = release.cut === null ? approved : unknown; return { ...this.publicRelease(release), name: this.nameable(release.name) ? release.name : "[withheld]", goal: this.nameable(release.goal) ? release.goal : "[withheld]", tasks: scopes.get(release.id) ?? [], afterCutUnknown: outsideIds(unknownPool, 0, release.id), afterCutUnknownCount: release.cut === null ? approved.length - own.length : unknown.length - (own.length - ownKnown.length), afterCut: release.cut === null ? null : outsideIds(known, cutStart, release.id), afterCutCount: release.cut === null ? null : known.length - cutStart - (ownKnown.length - after(ownKnown, release.cut)), }; }); } async planBacklog(by: PeerId, input: { id: number; revision: number; fields?: unknown; reason: string }): Promise { const instructionCheck = this.requestCheck(by); this.planningAuthority(by); if (!Number.isSafeInteger(input.id) || input.id <= 0 || !Number.isSafeInteger(input.revision) || input.revision < 0) throw new PreEffectToolRefusal("invalid planning identity or revision"); if (typeof input.reason !== "string" || !input.reason.trim() || input.reason.length > 1000) throw new PreEffectToolRefusal("planning needs a bounded reason"); let patch: PlanningFields; try { patch = planningPatch(input.fields); } catch (error) { throw new PreEffectToolRefusal((error as Error).message); } const validate = () => { const task = this.d.board.get(input.id); if (!task || (task.planningRevision ?? 0) !== input.revision) throw new PreEffectToolRefusal("planning revision changed"); this.planningAuthority(by, task); if (patch.sdlc !== undefined) { if (task.state !== "backlog" || task.owner || taskHasStarted(task)) throw new PreEffectToolRefusal("issue identity changes require unstarted backlog work"); if (by !== USER && this.isPii(task)) throw new PreEffectToolRefusal("private issue identity changes require the person"); if (!this.isPii(task) && !this.publicMetadataText(JSON.stringify(patch.sdlc))) throw new PreEffectToolRefusal("planning identity metadata is private or sensitive"); } if (isClosedTaskState(task.state)) throw new PreEffectToolRefusal("closed work is final"); // #1176: marking a card an agent already owns (an offer in its queue, or work it accepted) would leave the agent on it: the offer is not withdrawn by a mark. Refused, with the way out named. if (patch.needsPerson === true && !task.needsPerson && (task.owner || !["backlog", "proposed"].includes(task.state))) throw new PreEffectToolRefusal(`task #${task.id} is already ${task.owner ? `${task.state} with ${task.owner}` : task.state}: take it off the agent first (its owner declines the offer, or ahub task cancel ${task.id} --reason ), then mark it person-run`); if (by !== USER && (task.state !== "backlog" || !taskCanPlan(task) || task.pinned || Object.hasOwn(patch, "pinned"))) throw new PreEffectToolRefusal("planner changes only unpinned backlog work"); // #1176: whether a leg is the person's to run is the person's call, set or cleared: an agent that could clear the mark would put the card back in front of an agent. if (by !== USER && (Object.hasOwn(patch, "needsPerson") || task.needsPerson)) throw new PreEffectToolRefusal("a person-run card is the person's to mark and plan: ask the person (ahub backlog plan '{\"needsPerson\":true|false}' )"); if (by !== USER && patch.rank !== undefined && task.history.some(entry => entry.by === USER && entry.planning?.fields.includes("rank"))) throw new PreEffectToolRefusal("a person's backlog order is retained"); if (by !== USER && Object.hasOwn(patch, "reserved") && this.hasPersonReservation(task)) throw new PreEffectToolRefusal("a person's reservation is retained"); if (Object.hasOwn(patch, "deps") || Object.hasOwn(patch, "reserved")) { const returnedUntouched = task.state === "backlog" && !task.owner && taskHasStarted(task) && taskCanPlan(task); if (!returnedUntouched) { if (task.state !== "backlog" || taskHasStarted(task) || task.owner) throw new PreEffectToolRefusal("dependency and reservation changes require unstarted backlog work"); } const definitionOf = this.d.adapterCatalog?.definitionOf ?? builtinDefinitionOf; if (patch.reserved && !definitionOf(patch.reserved, this.d.instances?.()) && !this.d.bus.knownPeers().includes(patch.reserved) && !this.d.routing().classes[task.class]?.peers.includes(patch.reserved)) throw new PreEffectToolRefusal("reserved owner is not a supported or configured peer"); if (patch.reserved && !this.d.bus.isRostered(patch.reserved)) throw new PreEffectToolRefusal("reserved owner is off roster"); // #531 D3: a reservation for a peer routing leaves out for good could never be honoured. Say so, and who can lift it. if (patch.reserved && this.excluded(task).includes(patch.reserved)) throw new PreEffectToolRefusal(`${patch.reserved} is excluded from this task (it declined it or was escalated away from it for good); a reservation for it can never be honoured. Only a person's ahub task assign lifts the exclusion`); if (patch.reserved) this.requireCapabilities(task, patch.reserved); const rows = new Map(this.d.board.list().map(row => [row.id, row])); const pending = [...(patch.deps ?? task.deps ?? [])], seen = new Set(); while (pending.length) { const id = pending.pop()!; if (id === task.id) throw new PreEffectToolRefusal("planning dependencies would form a cycle"); if (seen.has(id)) continue; seen.add(id); const dependency = rows.get(id); if (!dependency) throw new PreEffectToolRefusal(`no dependency task #${id}`); pending.push(...(dependency.deps ?? [])); } } const target = patch.release === undefined ? task.release : patch.release; if (target != null && !this.d.board.release(target)) throw new PreEffectToolRefusal("no such release"); for (const id of new Set([task.release, target])) { if (id == null) continue; const release = this.d.board.release(id)!; if (Object.hasOwn(patch, "release")) this.planningAuthority(by, release); if (["shipped", "dropped"].includes(release.state)) throw new PreEffectToolRefusal("settled release scope is final"); if (by !== USER && release.state === "frozen") throw new PreEffectToolRefusal("frozen release changes require a person"); } return task; }; const task = validate(), withheld = await this.withholds("note", input.reason, task); instructionCheck(); this.planningAuthority(by); // #455: or moved the planner const latest = validate(); // a person may have changed planning or frozen a release while the screen ran let receipt: Task["sdlc"]; try { receipt = patch.sdlc === undefined ? undefined : planningIssueReceipt(patch.sdlc, latest.sdlc, this.d.sdlc?.config() ?? sdlcConfig(undefined)); } catch (error) { throw new PreEffectToolRefusal((error as Error).message); } const updated = this.d.board.plan(task.id, by, patch, input.revision, input.reason.trim(), withheld, receipt); this.planningRecorded({ by, task: task.id, fields: Object.keys(patch), revision: updated.planningRevision! }); if (updated.state === "backlog" && updated.reserved && ["reserved", "pinned", "deps", "plannedStart", "release", "needsPerson"].some(key => Object.hasOwn(patch, key)) && this.d.autoPull?.() === true) this.queueAutoPulls(new Set([updated.reserved]), "backlog planned"); return updated; // persistence/readback failures must never claim no effect } async undoPlanning(by: PeerId, id: number, revision: number): Promise { this.planningAuthority(by); const task = this.d.board.get(id), entry = task ? planningUndoEntry(task) : undefined; if (!task || !entry?.planning || entry.planning.revision !== revision || (task.planningRevision ?? 0) !== revision || by !== USER && entry.by !== by) throw new PreEffectToolRefusal("planning undo is stale or not owned"); this.planningAuthority(by, task); if (entry.planning.split) { const release = task.release == null ? undefined : this.d.board.release(task.release); if (task.state !== "backlog" || task.owner || taskHasStarted(task) || release && ["shipped", "dropped"].includes(release.state) || by !== USER && (task.pinned || release?.state === "frozen")) throw new PreEffectToolRefusal("split undo is no longer eligible"); if (entry.planning.split.children.some(saved => this.d.board.get(saved.id)?.history.some(item => item.event === "memory reference started"))) throw new PreEffectToolRefusal("split children are referenced by persistent long-term memory"); const childIds = new Set(entry.planning.split.children.map(child => child.id)), budgets = this.d.executionBudget?.status(); if (Array.isArray(budgets) && budgets.some(budget => budget.kind === "task" && budget.taskId !== undefined && childIds.has(budget.taskId))) throw new PreEffectToolRefusal("split children are referenced by execution budgets"); if (this.d.store) { try { this.d.memoryCheck?.(); this.d.store.store.refresh(); } catch { throw new PreEffectToolRefusal("split undo requires current memory link evidence"); } const children = new Set(entry.planning.split.children.map(child => this.d.board.get(child.id)).filter((child): child is Task => !!child).map(child => this.memoryKey(child))); if ([...children].some(key => this.d.store!.store.hasTask(key)) || this.d.store.store.goals().some(goal => goal.links.some(link => children.has(link.task)))) throw new PreEffectToolRefusal("split children are referenced by long-term tasks"); } const restored = this.d.board.undoBacklogSplit(id, by, revision); this.planningRecorded({ by, task: id, fields: ["split", "deps"], revision: restored.planningRevision! }); return restored; } if (entry.planning.pull) { const release = task.release == null ? undefined : this.d.board.release(task.release); if (task.state !== "proposed" || task.owner || taskHasStarted(task) || by !== USER && (task.pinned || release && ["frozen", "shipped", "dropped"].includes(release.state))) throw new PreEffectToolRefusal("planner pull undo is no longer eligible"); const capacity = this.capacityBefore(task); const returned = this.d.board.undoPlannedPull(id, by, revision); this.writePlannerNotices(returned, capacity); this.offered.delete(id); this.incomingBacklog.add(id); this.planningRecorded({ by, task: id, fields: ["pull", "reserved"], revision: returned.planningRevision! }); return returned; } return this.planBacklog(by, { id, revision, fields: entry.planning.previous, reason: `undo planning revision ${revision}` }); } async importGitHub(by: PeerId, input: GitHubImportSelection, run?: SdlcGh): Promise<{ imported: number[]; existing: number[]; partial: boolean; complete: boolean; unconfirmed?: true }> { if (!this.personOrConductor(by)) throw new PreEffectToolRefusal("GitHub import is a person console command"); const deadline = performance.now() + 20_000; const page = await readGitHubImport(input, run ?? ((args, timeout, _cwd, bound) => sdlcGh(args, timeout, this.d.cwd, bound))); const imported: number[] = [], existing: number[] = []; for (const issue of page.issues) { if (performance.now() >= deadline) return { imported, existing, partial: true, complete: false }; let created = false; try { const prior = this.d.board.imported(issue.source.repo, issue.source.issue); if (prior) { existing.push(prior.id); continue; } const classes = profileData(this.d.profileData ?? this.d.profile ?? "dev").classes; const cls = Object.keys(classes).find(name => classes[name] === "implement") ?? Object.keys(classes)[0]; const task = await this.propose(by, { title: issue.title, detail: issue.detail, class: cls, backlog: true }, issue.source, () => { created = true; }); (created ? imported : existing).push(task.id); if (performance.now() >= deadline) return { imported, existing, partial: true, complete: false }; } catch { if (created) { try { const saved = this.d.board.imported(issue.source.repo, issue.source.issue); if (saved) { if (!imported.includes(saved.id)) imported.push(saved.id); if (saved.state === "backlog") this.incomingBacklog.add(saved.id); return { imported, existing, partial: true, complete: false }; } } catch { /* A failed readback leaves the committed identity unconfirmed. */ } } return { imported, existing, partial: true, complete: false, unconfirmed: true }; } } return { imported, existing, partial: page.partial, complete: !page.partial }; } async splitBacklog(by: PeerId, input: { id: number; revision: number; parts: unknown; reason: string }, opts: { intake?: true } = {}): Promise<{ parent: Task; children: Task[] }> { // #334: the hub writes an intake draft's own model split; no other write by the hub passes as a planner. const authority = (task?: Pick) => { if (!(opts.intake && by === HUB)) this.planningAuthority(by, task); }; authority(); const { id, revision } = input; if (!Number.isSafeInteger(id) || id <= 0 || !Number.isSafeInteger(revision) || revision < 0 || typeof input.reason !== "string" || !input.reason.trim() || input.reason.length > 1000) throw new PreEffectToolRefusal("split needs an id, revision and bounded reason"); const reason = input.reason.trim(); let parts: unknown; try { parts = structuredClone(input.parts); } catch { throw new PreEffectToolRefusal("split parts must be cloneable data"); } if (!Array.isArray(parts) || parts.length < 2 || parts.length > 8) throw new PreEffectToolRefusal("split needs two to eight parts"); const rows = parts as Record[]; const validate = () => { const parent = this.d.board.get(id); if (!parent || parent.state !== "backlog" || parent.owner || taskHasStarted(parent) || (parent.planningRevision ?? 0) !== revision || by !== USER && parent.pinned) throw new PreEffectToolRefusal("split changed, pinned or already started"); // #1176: children are unmarked cards an agent could take, so an agent's split would turn person-only work into agent work. Checked here, which runs before the screen and again after it, and in the board's transaction. if (by !== USER && parent.needsPerson) throw new PreEffectToolRefusal(PERSON_RUN_SPLIT); const release = parent.release == null ? undefined : this.d.board.release(parent.release); if (parent.release != null && (!release || ["shipped", "dropped"].includes(release.state) || by !== USER && release.state === "frozen")) throw new PreEffectToolRefusal("split release scope is frozen or final"); authority(parent); // #334: the hub writes a split only into a draft that is still a draft. Both validations run (before and after the awaited screen), and the board asks again in its transaction. if (opts.intake && by === HUB && !parent.draft) throw new PreEffectToolRefusal("split changed, pinned or already started"); const profile = parent.profile ?? "dev"; const drafts = rows.map((part, index) => { if (!part || typeof part !== "object" || Array.isArray(part) || Object.keys(part).some(key => !["title", "detail", "class", "refs", "plan", "after", "afterParts"].includes(key)) || typeof part.title !== "string" || !part.title.trim() || part.title.length > 300 || part.detail !== undefined && (typeof part.detail !== "string" || part.detail.length > 8000) || part.class !== undefined && typeof part.class !== "string") throw new PreEffectToolRefusal("invalid split part"); const given = part.class ?? parent.profileClass ?? parent.class; const storedProfile = !parent.profile ? "dev" : profile === (this.d.profile ?? "dev") ? this.d.profileData ?? profile : profile; let cls: TaskClass; try { cls = part.class === undefined ? parent.class : profileClass(given as string, storedProfile); } catch (error) { throw new PreEffectToolRefusal((error as Error).message); } const after = part.after ?? [], afterParts = part.afterParts ?? []; if (!Array.isArray(after) || after.length > 64 || after.some(dep => !Number.isSafeInteger(dep) || dep <= 0) || new Set(after).size !== after.length || !Array.isArray(afterParts) || afterParts.length > 8 || afterParts.some(dep => !Number.isSafeInteger(dep) || dep < 0 || dep >= index) || new Set(afterParts).size !== afterParts.length) throw new PreEffectToolRefusal("split dependencies must name existing tasks or earlier parts"); const deps = [...new Set([...(parent.deps ?? []), ...after as number[]])], pending = [...deps], seen = new Set(); const direct = afterParts.length ? deps.filter(dep => !parent.deps?.includes(dep)) : deps; if (direct.length + afterParts.length > 64) throw new PreEffectToolRefusal("split child dependencies exceed the 64-edge cap"); while (pending.length) { const dependency = pending.pop()!; if (dependency === id) throw new PreEffectToolRefusal("split dependency reaches its parent"); if (seen.has(dependency)) continue; seen.add(dependency); const task = this.d.board.get(dependency); if (!task) throw new PreEffectToolRefusal("split dependency is missing"); pending.push(...(task.deps ?? [])); } const refs = part.refs === undefined ? parent.refs : cleanRefs(part.refs), plan = cleanPlan(part.plan, storedProfile, (this.d.sdlc?.config().mode ?? "off") !== "off"); // #1161: a part's plan sources are registered ids, as at propose and accept (#1144); refused before any screen or board write. this.validatePlanSources(plan); const draft = { title: part.title.replace(/\s+/g, " ").trim(), detail: part.detail as string | undefined ?? "", class: cls, refs, plan, deps, afterParts: afterParts as number[], ...(parent.role && cls === parent.class ? { role: parent.role } : {}), ...(parent.profile ? { profile: parent.profile, profileClass: given as string, ...(parent.profile === "dev" ? { customProfile: true as const } : {}) } : {}) }; const fields: PlanningFields = {}; for (const key of ["priority", "release", "plannedStart", "due"] as const) if (parent[key] !== undefined) fields[key] = parent[key]; if (parent.needsPerson) fields.needsPerson = true; // #1176: only the person gets here (above), and each child of a person-run leg is a person-run leg until the person says otherwise return { ...draft, fields }; }); return { parent, drafts }; }; const initial = validate(), screening = this.screenOn(); const initialPrivacy = initial.drafts.map(part => this.signalsFor({ ...part, detail: [part.detail, planText(part.plan)].join("\n") }).filter(signal => signal === "pii" || signal === "pii_path")); const initialPrivate = initialPrivacy.map(signals => this.isPii({ signals })), initialParentPrivate = this.isPii(initial.parent); const initialParentPrivacy = initial.parent.signals.filter(signal => signal === "pii" || signal === "pii_path"); const initialReasonPrivate = initialParentPrivate || !this.nameable(reason); let deadline: ReturnType | undefined; const attempt = Promise.all([ Promise.all(initial.drafts.map((part, index) => screening && !initialParentPrivate && !initialPrivate[index] ? this.screenCall(screenText({ title: part.title, detail: part.detail, plan: part.plan })) : undefined)), this.withholds("note", reason, initial.parent), ]); let screened: Awaited; try { screened = await Promise.race([attempt, new Promise((_, reject) => { deadline = setTimeout(() => reject(new PreEffectToolRefusal("split screening request deadline exceeded")), BACKLOG_SPLIT_SCREEN_TIMEOUT_MS); })]); } finally { if (deadline !== undefined) clearTimeout(deadline); } authority(); // #455: a person may have moved the planner while the screen ran const [screenedVerdicts, withheld] = screened, current = validate(); const finalSignals = current.drafts.map(part => this.signalsFor({ ...part, detail: [part.detail, planText(part.plan)].join("\n") })); const deterministicPrivate = finalSignals.map((signals, index) => initialPrivate[index] || this.isPii({ signals })); const verdicts = screenedVerdicts.map((verdict, index) => deterministicPrivate[index] ? undefined : verdict); const inherited = current.drafts.map((_part, index) => (initialParentPrivate || this.isPii(current.parent)) && !deterministicPrivate[index]); const drafts = current.drafts.map((part, index) => ({ ...part, ...(screening ? { screeningNote: inherited[index] ? "pii: inherited" : this.screenNote(verdicts[index]) } : {}), signals: [...new Set([...initialPrivacy[index]!, ...initialParentPrivacy, ...finalSignals[index]!, ...current.parent.signals.filter(signal => ["pii", "pii_path", "urgent"].includes(signal)), ...(verdicts[index] && verdicts[index]!.label !== "clear" ? ["pii"] : [])])] })); for (const draft of drafts) this.warmRepository(draft); // #334: the hub's intake split is only for a draft; the board asks for it again inside its transaction (a flag set for exactly this write, never left on). this.d.board.requireDraftForNextSplit = opts.intake === true && by === HUB; const result = this.d.board.splitBacklog(id, by, revision, drafts, reason, withheld || initialReasonPrivate || this.isPii(current.parent) || !this.nameable(reason)); if (this.d.coordination) { const mode = this.d.coordination(); for (const child of result.children) this.coordinationModes.set(child.id, mode); } for (const [index, child] of result.children.entries()) { this.incomingBacklog.add(child.id); if (screening) { this.recordScreen(child.id, "task", verdicts[index], inherited[index]); if (verdicts[index]?.label === "unknown") this.releaseNotice(`task #${child.id}: the PII screen gave no verdict (${verdicts[index]!.miss}); it is handled as a PII task`); } } this.planningRecorded({ by, task: id, fields: ["split", "deps"], revision: result.parent.planningRevision! }); return result; } /** * The draft and every open draft card split from it, at any depth, parent first. A planner may split an intake child again before approval, and * the grandchildren inherit the mark, so the walk follows `deps` through draft cards only: a dependency on ordinary work is never followed. */ private intakeFamily(id: number): Task[] { const root = this.d.board.get(id); if (!root || !root.draft || root.state !== "backlog") throw new PreEffectToolRefusal(`task #${id} is not an open intake draft`); const family: Task[] = [root], seen = new Set([root.id]); for (let next = 0; next < family.length; next++) { for (const dep of family[next]!.deps ?? []) { if (seen.has(dep)) continue; const child = this.d.board.get(dep); if (!child || !child.draft || child.state !== "backlog") continue; seen.add(dep); family.push(child); } } return family; } /** * #334 (#511a): the person's request becomes one parent draft, a backlog card that nothing offers or pulls. A planner is asked to split it with * `hub_backlog_split`; with none, or for a request that is PII, the hub's model proposes the split and the hub writes it. A split that does not * validate leaves the draft whole, with the reason on its history. */ async intake(by: PeerId, input: { text: unknown; sources?: unknown }): Promise<{ draft: Task; children: Task[]; split: "planner" | "hub" | "unsplit"; reason?: string }> { if (by !== USER) throw new PreEffectToolRefusal("intake is a console command"); const text = typeof input.text === "string" ? input.text.trim() : ""; if (!text || text.length > INTAKE_MAX_TEXT) throw new PreEffectToolRefusal(`intake needs a request of 1 to ${INTAKE_MAX_TEXT} characters`); const given = input.sources ?? []; if (!Array.isArray(given) || given.length > INTAKE_MAX_SOURCES || given.some(id => typeof id !== "string" || !SOURCE_ID.test(id)) || new Set(given).size !== given.length) throw new PreEffectToolRefusal(`sources: at most ${INTAKE_MAX_SOURCES} distinct src:<16 hex> ids`); const sources = given as string[]; for (const id of sources) if (!this.d.intake?.sourceKnown(id)) throw new PreEffectToolRefusal(`unknown source ${id}; register it with ahub source add`); const title = `Intake: ${text.split("\n")[0]!.replace(/\s+/g, " ").trim().slice(0, 80)}`; let draft = await this.propose(USER, { title, detail: intakeDetail(text, sources), class: "plan", backlog: true, draft: true }); this.incomingBacklog.delete(draft.id); const priv = this.isPii(draft); const planner = priv ? undefined : this.taskPlanner(draft).find(peer => this.d.bus.isRostered(peer) && this.d.bus.peers.has(peer) && this.d.bus.stateOf(peer) !== "offline"); if (planner) { const body = plannerRequestBody({ id: draft.id, revision: draft.planningRevision ?? 0, text: parseIntakeDetail(String(this.publicView(draft).detail)).text, sources }); try { if (this.d.bus.publish(newEnvelope(HUB, sanitize(body), { to: [planner], kind: "task", refs: { task: String(draft.id), taskRecipient: "planner" } })).includes(planner)) return { draft, children: [], split: "planner" }; } catch { /* the planner is not reachable: the hub model takes it */ } } return { ...(await this.intakeByHub(draft, text, sources, priv)), draft: this.d.board.get(draft.id) ?? draft }; } /** The hub model's split of a draft, validated against the profile's `hub_backlog_split` parts schema and written through `splitBacklog`. */ private async intakeByHub(draft: Task, text: string, sources: string[], priv: boolean): Promise<{ children: Task[]; split: "hub" | "unsplit"; reason?: string }> { const unsplit = (reason: string) => { this.d.board.update(draft.id, HUB, "intake unsplit", {}, reason); return { children: [], split: "unsplit" as const, reason }; }; if (!this.d.intake) return unsplit("no planner is attached and the hub has no model for a split"); // A request that is PII goes only to a model reached on campus; without one it stays whole for the person. if (priv && !(await this.d.triage?.onCampus().catch(() => false))) return unsplit("the request is PII and no on-prem model was reached"); let raw: string | undefined; try { raw = await this.d.intake.split(intakeSystemPrompt(Object.keys(profileData(this.d.profileData ?? this.d.profile ?? "dev").classes), this.d.intake.partsSchema()), intakeUserMessage(text, sources), { campusOnly: priv }); } catch { raw = undefined; } const parsed = parseIntakeSplit(raw, this.d.intake.partsSchema(), sources); if ("error" in parsed) return unsplit(parsed.error); const current = this.d.board.get(draft.id); if (!current || !current.draft || current.state !== "backlog") return unsplit("the draft changed while the model answered"); try { const result = await this.splitBacklog(HUB, { id: draft.id, revision: current.planningRevision ?? 0, parts: parsed.parts, reason: "intake: split by the hub model" }, { intake: true }); return { children: result.children, split: "hub" }; } catch (error) { return unsplit(`the split was refused: ${error instanceof PreEffectToolRefusal ? sanitize(error.message).slice(0, 200) : "the board refused it"}`); } } /** #334: the person approves a draft; it and its children leave draft and follow the normal backlog pull. */ async approveIntake(by: PeerId, id: unknown): Promise { if (!this.personOrConductor(by)) throw new PreEffectToolRefusal("intake approval is a console command"); if (typeof id !== "number" || !Number.isSafeInteger(id) || id <= 0) throw new PreEffectToolRefusal("id must be a positive task number"); const family = this.intakeFamily(id); let approved: Task[]; try { approved = this.d.board.approveDrafts(family.map(task => task.id), by, by === USER ? "intake approved by the person" : `intake approved by the conductor ${by}`); } catch (error) { throw new PreEffectToolRefusal((error as Error).message); } for (const task of approved) this.incomingBacklog.add(task.id); this.releaseNotice(`intake draft #${id} approved: ${approved.length} backlog card${approved.length === 1 ? "" : "s"}`); return approved; } /** #334: the person discards a draft; it and its children are cancelled through `cancel`. */ async discardIntake(by: PeerId, id: unknown): Promise { if (by !== USER) throw new PreEffectToolRefusal("intake discard is a console command"); if (typeof id !== "number" || !Number.isSafeInteger(id) || id <= 0) throw new PreEffectToolRefusal("id must be a positive task number"); const cancelled: Task[] = []; for (const task of this.intakeFamily(id)) cancelled.push(await this.cancel(task.id, USER, { reason: "intake draft discarded by the person" })); return cancelled; } /** Release assignment changes no execution role, dependency, reservation or state. */ async assignRelease(by: PeerId, input: { id: number; revision: number; release: number | null; reason: string }): Promise { this.plannerWriteAuthority(by); if (typeof input.reason !== "string" || !input.reason.trim() || Buffer.byteLength(input.reason) > 1000) throw new PreEffectToolRefusal("release assignment needs a bounded reason"); if (!Number.isSafeInteger(input.id) || input.id <= 0 || !Number.isSafeInteger(input.revision) || input.revision < 0 || input.release !== null && (!Number.isSafeInteger(input.release) || input.release <= 0)) throw new PreEffectToolRefusal("invalid release assignment"); const validate = () => { this.plannerWriteAuthority(by); const task = this.d.board.get(input.id); if (!task || (task.planningRevision ?? 0) !== input.revision) throw new PreEffectToolRefusal("release assignment changed"); this.plannerWriteAuthority(by, task); if (by !== USER && (this.isPii(task) || task.pinned)) throw new PreEffectToolRefusal("private or pinned release scope requires the person"); for (const id of new Set([task.release, input.release])) if (id != null) { const release = this.d.board.release(id); if (!release || ["frozen", "shipped", "dropped"].includes(release.state)) throw new PreEffectToolRefusal("release scope is frozen or final"); this.plannerWriteAuthority(by, release); } return task; }; const before = validate(), signature = JSON.stringify(before), privateScope = this.isPii(before); if (!privateScope && (!this.nameable(input.reason) || this.screenOn() && (await this.screenCall(input.reason)).label !== "clear")) throw new PreEffectToolRefusal("release reason was not cleared for public planning"); if (JSON.stringify(validate()) !== signature) throw new PreEffectToolRefusal("release assignment changed during screening"); const result = this.d.board.plan(input.id, by, { release: input.release }, input.revision, input.reason.trim(), privateScope); this.planningRecorded({ by, task: input.id, fields: ["release"], revision: result.planningRevision! }); return result; } async configureRelease(by: PeerId, input: { id: number; revision: number; hotfix?: unknown; state?: "active"; cut?: number }): Promise { this.plannerWriteAuthority(by); const validate = () => { this.plannerWriteAuthority(by); if (!Number.isSafeInteger(input.id) || input.id <= 0 || !Number.isSafeInteger(input.revision) || input.revision < 0) throw new PreEffectToolRefusal("invalid release identity or revision"); const release = this.d.board.release(input.id); if (!release || release.revision !== input.revision || !["planning", "active"].includes(release.state)) throw new PreEffectToolRefusal("release revision changed or scope frozen"); this.plannerWriteAuthority(by, release); if (input.state !== undefined && input.state !== "active") throw new PreEffectToolRefusal("invalid train state"); if (input.cut !== undefined && (!Number.isSafeInteger(input.cut) || input.cut <= 0 || input.cut > 8_640_000_000_000_000)) throw new PreEffectToolRefusal("release cut must be a positive safe UTC timestamp"); const dates = [release.plannedStart, input.cut ?? release.cut, release.ship].filter((date): date is number => date !== null); if (dates.some((date, index) => index > 0 && dates[index - 1]! > date)) throw new PreEffectToolRefusal("invalid release planned dates"); if ((input.state ?? release.state) === "active" && this.d.board.releases().some(row => row.id !== input.id && ["active", "frozen"].includes(row.state))) throw new PreEffectToolRefusal("one open release train at a time"); return release; }; const release = validate(); let train; try { train = releaseTrainData({ ...(release.train ?? { history: [] }), ...(input.hotfix === undefined ? {} : { hotfix: input.hotfix }) }); } catch (error) { throw new PreEffectToolRefusal((error as Error).message); } if (train.hotfix && (!this.nameable(train.hotfix.reason) || this.screenOn() && (await this.screenCall(train.hotfix.reason)).label !== "clear")) throw new PreEffectToolRefusal("hotfix reason was not cleared"); const validatedRelease = validate(); if (JSON.stringify(validatedRelease) !== JSON.stringify(release)) throw new PreEffectToolRefusal("release changed during screening"); if (release.train && JSON.stringify(train) === JSON.stringify(release.train) && (input.state ?? release.state) === release.state && (input.cut ?? release.cut) === release.cut) return validatedRelease; if (train.history.length >= RELEASE_TRAIN_HISTORY_LIMIT - 2) throw new PreEffectToolRefusal("release train history full; keep the remaining slots for cut and ship"); train.history.push({ at: Date.now(), by, event: "configured" }); const updated = this.d.board.updateRelease(input.id, { train: releaseTrainData(train), ...(input.state ? { state: input.state } : {}), ...(input.cut === undefined ? {} : { cut: input.cut }) }, input.revision); this.planningRecorded({ by, release: input.id, fields: ["train"], revision: updated.revision }); return updated; } publicRelease(release: Release): Release { return { ...release, name: this.nameable(release.name) ? release.name : "[withheld]", goal: this.nameable(release.goal) ? release.goal : "[withheld]", ...(release.train?.hotfix && !this.nameable(release.train.hotfix.reason) ? { train: { ...release.train, hotfix: { ...release.train.hotfix, reason: "[withheld]" } } } : {}) }; } releaseReport(by: PeerId, id: number) { this.planningAuthority(by); if (by !== USER && this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("release report unavailable during a private turn"); const release = Number.isSafeInteger(id) && id > 0 ? this.d.board.release(id) : undefined; if (!release) throw new PreEffectToolRefusal("no such release"); const all = this.d.board.list(), publicTasks = all.filter(task => !this.isPii(task)); if (all.some(task => task.release === id && this.isPii(task))) throw new PreEffectToolRefusal("release scope contains private work; public readiness unavailable"); return { release: this.publicRelease(release), readiness: releaseTrainReadiness(release, publicTasks), metrics: releaseMetrics(this.d.board.releases().filter(row => !all.some(task => task.release === row.id && this.isPii(task))), publicTasks), native: "unverified" as const }; } /** Scope freeze only. This never tags, publishes, upgrades, or authorizes a release. */ async cutRelease(by: PeerId, input: { id: number; revision: number }): Promise { const validate = () => { this.plannerWriteAuthority(by); if (!Number.isSafeInteger(input.id) || input.id <= 0 || !Number.isSafeInteger(input.revision) || input.revision < 0) throw new PreEffectToolRefusal("invalid release identity or revision"); const release = this.d.board.release(input.id); if (!release || release.revision !== input.revision || release.state !== "active") throw new PreEffectToolRefusal("release revision changed or train is not active"); this.plannerWriteAuthority(by, release); if (this.d.board.releases().some(row => row.id !== input.id && ["active", "frozen"].includes(row.state))) throw new PreEffectToolRefusal("one open release train at a time"); if ((release.train?.history.length ?? 0) > RELEASE_TRAIN_HISTORY_LIMIT - 2) throw new PreEffectToolRefusal("release train history full; cut needs slots for cut and ship, drop this train and create a replacement"); const report = this.releaseReport(by, input.id); if (report.readiness.blockers.length) throw new PreEffectToolRefusal(`release cut blocked: ${report.readiness.blockers.join("; ")}`); return { release, scope: this.d.board.list().filter(task => task.release === input.id) }; }; const before = validate(), signature = JSON.stringify(before); const expected = new Set(before.scope.flatMap(task => task.sdlc?.repo && task.sdlc.pr ? [`${task.sdlc.repo.toLowerCase()}#${task.sdlc.pr}`] : [])); let ciRuns: number | undefined; if (expected.size && before.scope.every(task => task.sdlc?.repo && /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(task.sdlc.repo) && !task.sdlc.repo.startsWith("-") && Number.isSafeInteger(task.sdlc.pr) && task.sdlc.pr! > 0)) { const repositories = [...new Set(before.scope.flatMap(task => task.sdlc?.repo ? [task.sdlc.repo] : []))]; if (repositories.length === 1 && expected.size <= 16) { try { const costs = await this.costReport(by, repositories[0], before.scope.map(task => task.sdlc!.pr!)), rows = costs.rows as import("./cost-governance.ts").CostRow[]; const selected = rows.filter(row => expected.has(`${row.repo.toLowerCase()}#${row.pr}`)); if (!costs.truncated && selected.length === expected.size && selected.every(row => row.ciRuns !== null && row.ciReruns !== null)) ciRuns = selected.reduce((sum, row) => sum + row.ciRuns! + row.ciReruns!, 0); } catch { /* Optional cost evidence stays unknown; validation below still rechecks scope and authority. */ } } } if (JSON.stringify(validate()) !== signature) throw new PreEffectToolRefusal("release scope changed during cost readback"); const window = await this.d.releaseWindow?.(); try { if (JSON.stringify({ release: this.d.board.release(input.id), scope: this.d.board.list().filter(task => task.release === input.id) }) !== signature) throw new PreEffectToolRefusal("release scope changed during admission"); const freshScope = validate(); if (!window || !Number.isFinite(window.at) || Date.now() - window.at > 5000 || window.at > Date.now() || window.host !== true || window.quota !== true || window.current?.() === false) throw new PreEffectToolRefusal(`release cut deferred: ${window?.reasons?.join("; ") || "host or peer quota evidence unavailable"}; inspect ahub budget and ahub budget set <0..1>; stop or resume the paused peer; the person can use ahub release drop or explicitly disable lifecycle mode before retrying`); const scope = freshScope.scope.map(task => task.id).sort((a, b) => a - b), train = releaseTrainData(freshScope.release.train ?? { history: [] }); train.scope = scope; train.history.push({ at: Date.now(), by, event: "cut", scope, reviews: freshScope.scope.reduce((sum, task) => sum + task.history.filter(row => ["approved", "changes_requested"].includes(row.event)).length, 0), ...(ciRuns === undefined ? {} : { ciRuns }) }); const updated = this.d.board.freezeRelease(input.id, input.revision, freshScope.scope, releaseTrainData(train)); this.planningRecorded({ by, release: input.id, fields: ["state", "train"], revision: updated.revision }); return updated; } finally { try { await window?.close?.(); } catch { this.releaseNotice(`release #${input.id}: admission cleanup incomplete; inspect the host lease before retrying`); } } } async newRelease(by: PeerId, input: { name: string; goal: string; order: number }): Promise { this.plannerWriteAuthority(by); if (typeof input.name !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(input.name) || typeof input.goal !== "string" || !input.goal.trim() || input.goal.length > 1000 || !Number.isSafeInteger(input.order) || input.order < 0) throw new PreEffectToolRefusal("invalid release name, goal or order"); const text = input.name + "\n" + input.goal; if (!this.nameable(text) || this.screenOn() && (await this.screenCall(text)).label !== "clear") throw new PreEffectToolRefusal("release text was not cleared for public planning"); this.plannerWriteAuthority(by); // Privacy and planner identity may change while screening. if (this.d.board.releases().some(release => release.name === input.name)) throw new PreEffectToolRefusal("release name already exists"); const release = this.d.board.newRelease(input.name, input.goal.trim(), input.order, by === USER ? null : by); this.planningRecorded({ by, release: release.id, fields: ["created"], revision: release.revision }); return release; } changeRelease(by: PeerId, input: { id: number; revision: number; state?: ReleaseState; plannedStart?: number | null; cut?: number | null; ship?: number | null }): Release { this.planningAuthority(by); const release = this.d.board.release(input.id); if (!Number.isSafeInteger(input.id) || input.id <= 0 || !Number.isSafeInteger(input.revision) || !release || release.revision !== input.revision) throw new PreEffectToolRefusal("release revision changed"); this.planningAuthority(by, release); if (["shipped", "dropped"].includes(release.state)) throw new PreEffectToolRefusal("settled release is final"); if (by !== USER && (release.state === "frozen" || input.state === "frozen" || input.state === "shipped" || input.state === "dropped")) throw new PreEffectToolRefusal("freeze, ship, drop and frozen changes require a person"); if (input.state === "shipped" && this.d.board.list().some(task => task.release === release.id && !isClosedTaskState(task.state))) throw new PreEffectToolRefusal("every release task must be approved, cancelled, or moved out before ship"); if (input.state === "active" && (release.train || (this.d.sdlc?.config().mode ?? "off") !== "off" || this.d.board.releases().some(row => row.train && ["active", "frozen"].includes(row.state))) && this.d.board.releases().some(row => row.id !== release.id && ["active", "frozen"].includes(row.state))) throw new PreEffectToolRefusal("one open release train at a time"); if (input.state === "frozen" && (release.train || (this.d.sdlc?.config().mode ?? "off") !== "off")) throw new PreEffectToolRefusal("use the resource-admitted release cut operation"); if (input.state === "shipped" && release.train) { if (release.train.history.length >= RELEASE_TRAIN_HISTORY_LIMIT) throw new PreEffectToolRefusal("release train history full; ship needs one history slot, drop this train and create a replacement"); const readiness = releaseTrainReadiness(release, this.d.board.list()); if (readiness.blockers.length) throw new PreEffectToolRefusal(`release ship blocked: ${readiness.blockers.join("; ")}`); } const { id, revision, ...patch } = input; if (!Object.keys(patch).length || Object.keys(patch).some(key => !["state", "plannedStart", "cut", "ship"].includes(key))) throw new PreEffectToolRefusal("unknown or empty release fields"); const trained = release.train && input.state === "shipped" ? releaseTrainData({ ...release.train, history: [...release.train.history, { at: Date.now(), by, event: "shipped" }] }) : undefined; const updated = this.d.board.updateRelease(id, { ...patch, ...(trained ? { train: trained } : {}) }, revision); this.planningRecorded({ by, release: id, fields: Object.keys(patch), revision: updated.revision }); return updated; // a failed readback may follow a durable release write } async propose(by: PeerId, input: { title?: string; detail?: string; class?: string; role?: unknown; refs?: TaskRefs; plan?: TaskPlan; owner?: PeerId; after?: unknown; urgent?: unknown; needs_network?: unknown; needs_worktree?: unknown; backlog?: unknown; draft?: unknown; goal?: unknown; [HOST_ROADMAP_DRAFT]?: unknown }, external?: GitHubSource, created?: () => void, fence?: () => string | undefined, hostCreatedHook?: (task: Task) => void): Promise { const requestCheck = this.requestCheck(by, fence); const plan = cleanPlan(input.plan, this.d.profileData ?? this.d.profile ?? "dev", (this.d.sdlc?.config().mode ?? "off") !== "off"); this.validatePlanSources(plan); requireLocalTaskPeer(input.owner); external = external ? { ...external } : undefined; if (external && (!this.personOrConductor(by) || input.backlog !== true)) throw new PreEffectToolRefusal("external intake requires person-owned backlog staging"); if (input.backlog !== undefined && typeof input.backlog !== "boolean") throw new PreEffectToolRefusal("backlog must be a boolean"); const backlog = input.backlog === true; if (input.draft === true && input[HOST_ROADMAP_DRAFT] === true) { // R2 part 2 (#1480): a part the planner or the conductor accepted is held exactly like the person's intake draft. The // capability is a host Symbol, so no tool argument can stage a hidden draft, and the caller is rechecked here as well. if (!backlog) throw new PreEffectToolRefusal("a held roadmap draft is backlog work"); if (by !== USER && (!this.d.bus.isRostered(by) || !this.isConfiguredPlanner(by) && !this.configuredManualConductor(by))) throw new PreEffectToolRefusal("a held roadmap draft needs the configured planner or the unique conductor; ask the person to accept the part with ahub roadmap decompose --accept"); } else if (input.draft !== undefined && (input.draft !== true || !backlog || by !== USER)) throw new PreEffectToolRefusal("only the person's intake stages a backlog draft"); const claiming = !backlog && input.owner === by; if (claiming) { this.acceptanceCapacity({ id: -1, owner: by, state: "proposed" }); this.pendingClaims.set(by, (this.pendingClaims.get(by) ?? 0) + 1); } try { if (backlog && input.owner && !this.d.bus.isRostered(input.owner)) throw new PreEffectToolRefusal(`${input.owner} is off roster; add it before reserving work`); // Callers are models: a title is one line (it is part of console and hub.log lines), not a document. const title = String(input.title ?? "").replace(/\s+/g, " ").trim().slice(0, 300); if (!title) throw new PreEffectToolRefusal("title is required"); const goal = input.goal == null || input.goal === "" ? undefined : this.goalFor(by, input.goal); // Dependencies can only name tasks that exist, so the new task closes no cycle: nothing can depend on it yet. // Callers are models: a missing or null `after` is no dependency, and an id is an integer or a digit string. let afterIds: unknown[] = []; if (Array.isArray(input.after)) afterIds = input.after; else if (input.after != null) afterIds = [input.after]; const deps: number[] = []; for (const v of afterIds) { const id = typeof v === "number" || (typeof v === "string" && /^\s*\d+\s*$/.test(v)) ? Number(v) : NaN; if (!Number.isInteger(id)) throw new PreEffectToolRefusal(`after: ${JSON.stringify(v)} is not a task id`); if (!this.d.board.get(id)) throw new PreEffectToolRefusal(`after: no task #${id}`); if (!deps.includes(id)) deps.push(id); } // An owner for work that waits is reserved (issue #207): routing offers it to that peer first once it is ready. const reserved = backlog || this.waitsFor({ deps }).length ? input.owner : undefined; const given = input.class === undefined || input.class === "" ? undefined : input.class; const profile = this.d.profile ?? "dev"; let baseGiven: TaskClass | undefined; try { if (given !== undefined) baseGiven = profileClass(given, this.d.profileData ?? profile); } catch (error) { throw new PreEffectToolRefusal((error as Error).message); } const text = { title, detail: String(input.detail ?? "").slice(0, 8000), refs: cleanRefs(input.refs) }; // The plan reaches other owners, so a PII pattern in it makes the task a PII task like one in the detail would. const screenDetail = [text.detail, text.refs.repo, external?.repo, external?.url].filter(value => value !== undefined && value !== "").join("\n"); const signals = this.signalsFor({ ...text, detail: [screenDetail, planText(plan)].join("\n"), plan }); // Urgent work is handed over even when its paused owner's window resets soon (issue #36). if (input.urgent === true && !signals.includes("urgent")) signals.push("urgent"); // #1081: a declared need is a signal like urgent, so routing and every later capability check read the same field. Only an explicit true sets it. if (input.needs_network !== undefined && typeof input.needs_network !== "boolean") throw new PreEffectToolRefusal("needs_network must be true or false; omit it when the work needs no network"); if (input.needs_network === true && !signals.includes("needs_network")) signals.push("needs_network"); // #1081 (amended AC1): the same for a task worktree. Only an explicit true sets it. if (input.needs_worktree !== undefined && typeof input.needs_worktree !== "boolean") throw new PreEffectToolRefusal("needs_worktree must be true or false; omit it when the work needs no task worktree"); if (input.needs_worktree === true && !signals.includes("needs_worktree")) signals.push("needs_worktree"); // The PII screen (issue #198) reads the same text before anything else does: until its verdict the task is on no // board, in no envelope and before no other model. A pattern match is PII without a call; no verdict is PII too. const screening = this.screenOn(); const screened = screening && !signals.includes("pii") ? await this.screenCall(screenText({ ...text, detail: screenDetail, plan })) : undefined; requestCheck(); if (screened && screened.label !== "clear") signals.push("pii"); let cls = baseGiven; let triaged = false; let fenced = false; // a PII task off campus: triage is not asked if (!cls && this.d.triage) { // Signals first: a PII task's text may only go to a model that is reached without leaving the campus network. const pii = this.isPii({ signals }); const reached = !pii || await this.d.triage.onCampus().catch(() => false); requestCheck(); if (reached) cls = await this.d.triage.classify(text.title, text.detail).catch(() => undefined); else fenced = true; requestCheck(); triaged = !!cls; } // A claim is work the caller will do itself: without a class and a model to name one, it is implementation (#6). const defaulted = !backlog && !cls && input.owner === by; if (defaulted) cls = "implement"; if (!cls) throw new PreEffectToolRefusal(`class is required (one of ${CLASSES.join(", ")}); ${fenced ? "the task is handled as PII and the hub's model is not reached on campus, so it was not asked to name one" : "the hub could not name one for you"}`); if (claiming) this.acceptanceCapacity({ id: -1, owner: by, state: "proposed" }, 1); let selected; try { selected = taskRole(input.role, cls, this.d.catalog ?? loadRoleCatalog(this.d.cwd)); } catch (error) { throw new PreEffectToolRefusal((error as Error).message); } const draft = { ...text, class: cls, ...(selected ? { role: selected.id } : {}), ...(profile !== "dev" || given !== undefined && given !== cls || this.d.profileData && this.d.profileData !== projectProfile("dev") ? { profile, profileClass: given ?? cls, ...(profile === "dev" ? { customProfile: true as const } : {}) } : {}) }; if (external) { const prior = this.d.board.imported(external.repo, external.issue); if (prior) return prior; } if (reserved) this.requireCapabilities({ ...draft, signals, ...(external ? { external } : {}) }, reserved); this.warmRepository({ refs: draft.refs, plan }); const repositoryMismatch = !this.isPii({ signals }) && this.repositories.mismatch(draft.refs, plan); requestCheck(); let task = this.d.board.propose(by, { ...draft, plan, ...(external ? { external } : {}), ...(deps.length ? { deps } : {}), ...(reserved ? { reserved } : {}), signals, ...(backlog ? { backlog: true } : {}), ...(input.draft === true ? { draft: true } : {}) }, hostCreatedHook); if (repositoryMismatch) this.releaseNotice(`task #${task.id}: refs and plan name different repositories; check refs.repo before editing`); if (this.d.coordination) this.coordinationModes.set(task.id, this.d.coordination()); created?.(); if (screening) task = this.screenedTask(task, screened); task = this.linkOnWrite(task); // #723 if (goal) this.linkNative(task, goal, by); if (triaged) task = this.d.board.update(task.id, "hub", "triaged", {}, `class ${cls} named by the hub's model`); if (defaulted) task = this.d.board.update(task.id, "hub", "class defaulted", {}, "class implement for a claim without one"); if (backlog) { this.incomingBacklog.add(task.id); this.releaseNotice(`task ${this.publicTitle(task)} backlogged by ${by} [${profileTaskLabel(task)}]`); return task; } this.d.notify(`task ${this.publicTitle(task)} proposed by ${by} [${profileTaskLabel(task)}]${task.signals.length ? ` signals: ${task.signals.join(", ")}` : ""}`); // Re-read: a dependency approved while triage was awaited looked for its dependents before this row existed. const still = this.waitsFor(task); if (still.length) { this.d.notify(`task ${this.publicTitle(task)} waits for ${still.map((id) => `#${id}`).join(", ")}; it is offered ${task.reserved ? `to ${task.reserved} first ` : ""}once they are approved`); return this.d.board.update(task.id, HUB, "blocked", {}, `waits for ${still.map((id) => `#${id}`).join(", ")}`); } // Naming yourself is a claim: the work is already yours, so no offer comes back to you (paper: Agensh CLAIM, #68). return await this.assignOwner(task, by, input.owner ? { candidates: [input.owner], namedOwner: input.owner, claim: input.owner === by } : {}); } finally { if (claiming) { const remaining = (this.pendingClaims.get(by) ?? 1) - 1; if (remaining) this.pendingClaims.set(by, remaining); else this.pendingClaims.delete(by); } } } async returnUntouchedToBacklog(by: PeerId, input: { id: number; revision: number; reason: string; fields?: unknown }): Promise { this.plannerWriteAuthority(by); if (!Number.isSafeInteger(input.id) || input.id < 1 || !Number.isSafeInteger(input.revision) || input.revision < 0 || typeof input.reason !== "string" || !input.reason.trim() || input.reason.length > 1000) throw new PreEffectToolRefusal("untouched return needs an id, revision and bounded reason"); let parsed: PlanningFields; try { parsed = planningPatch(input.fields); } catch (error) { throw new PreEffectToolRefusal(`${(error as Error).message}; use fields.reserved with an agent peer id or null, or omit fields`); } if (Object.keys(parsed).some(key => key !== "reserved")) throw new PreEffectToolRefusal("untouched return fields may contain only reserved; remove every other field, or omit fields"); const patch: Pick = Object.hasOwn(parsed, "reserved") ? { reserved: parsed.reserved } : {}; const validate = () => { const task = this.need(input.id, false, true); this.plannerWriteAuthority(by, task); if (!["proposed", "in_progress"].includes(task.state) || (task.planningRevision ?? 0) !== input.revision || taskHasWorkEvidence(task)) throw new PreEffectToolRefusal("work has execution evidence or its planning revision changed"); if (by !== USER && task.pinned) throw new PreEffectToolRefusal("pinned work requires the person"); const release = task.release == null ? undefined : this.d.board.release(task.release); if (release && (["shipped", "dropped"].includes(release.state) || by !== USER && release.state === "frozen")) throw new PreEffectToolRefusal("settled or frozen release scope cannot return"); if (Object.hasOwn(patch, "reserved")) { if (by !== USER && this.hasPersonReservation(task)) throw new PreEffectToolRefusal("a person's reservation is retained; ask the person to change it"); const reserved = patch.reserved, definitionOf = this.d.adapterCatalog?.definitionOf ?? builtinDefinitionOf; if (reserved && !definitionOf(reserved, this.d.instances?.()) && !this.d.bus.knownPeers().includes(reserved) && !this.d.routing().classes[task.class]?.peers.includes(reserved)) throw new PreEffectToolRefusal("reserved owner is not a supported or configured peer; choose a peer from ahub status"); if (reserved && !this.d.bus.isRostered(reserved)) throw new PreEffectToolRefusal("reserved owner is off roster; choose a rostered peer from ahub status or ask the person to update the roster"); if (reserved && this.excluded(task).includes(reserved)) throw new PreEffectToolRefusal(`${reserved} is excluded from this task (it declined it or was escalated away from it for good); a reservation for it can never be honoured. Only a person's ahub task assign lifts the exclusion`); if (reserved) this.requireCapabilities(task, reserved); } return task; }; const task = validate(), flow = task.history.length; const withheld = await this.withholds("note", input.reason, task); this.plannerWriteAuthority(by); const confirmed = validate(); if (confirmed.history.length !== flow) throw new PreEffectToolRefusal("task changed during untouched return"); const capacity = this.capacityBefore(confirmed); const returned = this.d.board.update(confirmed.id, by, "backlog returned untouched", { state: "backlog", owner: null, reviewer: null, ...patch }, input.reason.trim(), { ...(withheld ? { withheld: true } : {}) }, flow); this.writePlannerNotices(returned, capacity); this.offered.delete(confirmed.id); this.cohorts.leave(confirmed.id); this.withdrawRoleRequest(confirmed, returned, "owner"); this.withdrawRoleRequest(confirmed, returned, "reviewer"); this.incomingBacklog.add(confirmed.id); this.planningRecorded({ by, task: confirmed.id, fields: ["return", ...Object.keys(patch)], revision: returned.planningRevision ?? 0 }); await this.releaseHeld(confirmed.owner); // its owner's slot is free (#655) return returned; } /** Person-owned staging only. Flow transitions remain with their existing owners and reviewers. */ async moveBacklog(by: PeerId, id: unknown, pull: boolean): Promise { if (by !== USER) throw new PreEffectToolRefusal("backlog pull/return is a console command"); if (typeof pull !== "boolean") throw new PreEffectToolRefusal("pull must be a boolean"); const n = typeof id === "number" ? id : typeof id === "string" && /^\s*\d+\s*$/.test(id) ? Number(id) : NaN; if (!Number.isSafeInteger(n) || n <= 0) throw new PreEffectToolRefusal("id must be a positive task number"); const task = this.d.board.get(n); if (!task) throw new PreEffectToolRefusal(`no task #${n}`); if (pull && task.draft) throw new PreEffectToolRefusal(`task #${n} is an intake draft; approve it with ahub intake approve ${n} first`); if (task.state !== (pull ? "backlog" : "proposed") || task.owner) throw new PreEffectToolRefusal(`task #${n}: ${pull ? "only backlog may be pulled" : "only ownerless proposed work may return to backlog"}`); if (!pull && taskHasStarted(task)) throw new PreEffectToolRefusal(`task #${n}: started work cannot return to backlog`); const pulled = task.history.findLast(entry => entry.event === "backlog pulled" || entry.event === "backlog returned"); const restoreReservation = !pull && pulled?.planning?.pull && !task.history.slice(task.history.lastIndexOf(pulled) + 1).some(entry => entry.event === "reserved" || entry.planning?.fields.includes("reserved")); const capacity = this.capacityBefore(task); const next = this.d.board.update(n, by, pull ? "backlog pulled" : "backlog returned", { state: pull ? "proposed" : "backlog", owner: null, reviewer: null, ...(restoreReservation ? { reserved: pulled.planning!.previous.reserved ?? null } : {}) }); this.writePlannerNotices(next, capacity); this.offered.delete(n); if (!pull) { this.incomingBacklog.add(n); return next; } const waits = this.waitsFor(next); if (waits.length) return this.d.board.update(n, HUB, "blocked", {}, `waits for ${waits.map(v => `#${v}`).join(", ")}`); // This persisted ready marker also lets a restart offer ownerless work once a peer attaches. const ready = this.d.board.update(n, HUB, "ready", {}, "pulled from backlog"); return this.assignOwner(ready, by); } /** Where a screened task's `pii` signal came from, on its history and in events (issue #198); no verdict is a console line by id. */ private screenNote(v: PiiVerdict | undefined): string { return !v ? "pii: regex" : v.label === "clear" ? "clear" : v.label === "pii" ? `pii: screen, ${v.category}` : `pii: unknown, ${v.miss}`; } private screenedTask(task: Task, v: PiiVerdict | undefined): Task { this.recordScreen(task.id, "task", v); if (v?.label === "unknown") this.d.notify(`task #${task.id}: the PII screen gave no verdict (${v.miss}); it is handled as a PII task`); const note = this.screenNote(v); return this.d.board.update(task.id, HUB, "screened", {}, note); } /** How often each task was screened again in this hub run. ponytail: in memory, so a restart allows another round. */ private readonly rescreens = new Map(); /** * A task whose screen gave no verdict waits as a PII task (#198). While it is proposed and no peer ever owned it, * nothing private was sent anywhere, so the daemon's release timer asks again here: one task per call (the timer runs * one at a time), the least tried first, at most RESCREEN_MAX times each in a hub run; text too long for the screen * never clears. `clear` lifts the pii signal and routes the task as usual (a named owner is not remembered, a reserved * one is offered first as always), `pii` settles it, another unknown changes only the record. A task an owner took * (`local`), even one declined back since, keeps its PII path: its notes, summary and decline reason are not screened. */ async rescreen(): Promise { if (!this.screenOn()) return; const waiting = (t: Task) => { const last = [...t.history].reverse().find((h) => h.event === "screened")?.note ?? ""; return t.state === "proposed" && !t.owner && !t.history.some((h) => h.owner) && t.signals.includes("pii") && last.startsWith("pii: unknown") && last !== "pii: unknown, too long"; }; const tries = (t: Task) => this.rescreens.get(t.id) ?? 0; const rescreenMax = this.d.rescreenMax?.() ?? RESCREEN_MAX; const task = this.d.board.list("proposed").filter((t) => waiting(t) && tries(t) < rescreenMax).sort((a, b) => tries(a) - tries(b))[0]; if (!task) return; this.rescreens.set(task.id, (this.rescreens.get(task.id) ?? 0) + 1); const text = screenText(task); const v = this.nameable(text) ? await this.screenCall(text) : undefined; // a pattern added since settles it const now = this.d.board.get(task.id); if (!now || !waiting(now)) return; // taken or moved meanwhile: its verdict stands this.recordScreen(task.id, "task", v); if (v?.label === "unknown") return; if (v?.label !== "clear") return void this.d.board.update(task.id, HUB, "screened", {}, v ? `pii: screen, ${v.category}` : "pii: regex"); const lifted = this.d.board.update(task.id, HUB, "screened", { signals: now.signals.filter((s) => s !== "pii") }, "clear, screened again"); if (this.personUnassigned(lifted)) return; this.d.notify(`task ${this.publicTitle(lifted)}: the PII screen cleared it on a second look; it is routed as usual`); const still = this.waitsFor(lifted); if (still.length) return void this.d.board.update(lifted.id, HUB, "blocked", {}, `waits for ${still.map((id) => `#${id}`).join(", ")}`); try { await this.assignOwner(lifted, HUB); } catch (e) { // A saved move whose delivery failed: the console notice was printed where the error was thrown (#297). if (!(e instanceof AssignmentUndeliveredError)) throw e; } } /** * Open tasks of other owners whose paths overlap this one's. The later claimant settles it with the other owner, so * only the new owner reads "settle it"; anyone else learns that the owner was told. PII tasks are left out on both * sides: their refs are hidden from cloud peers. */ overlaps(task: Task, forOwner = true, found = this.overlapHits(task)): string { const hits = found.map((h) => `#${h.task.id} (owner ${h.task.owner}) on ${this.where(h)}`); if (!hits.length) return ""; if (this.silentFor(task.id)) { // A silent cohort (issue #107): the plans are what the owner works from, and nobody negotiates by message. const plans = found.map((h) => (planText(h.task.plan) ? `#${h.task.id}'s plan: ${planText(h.task.plan)}` : "")).filter(Boolean); const who = forOwner ? `Do not message ${found.length > 1 ? "those owners" : "that owner"}: you are in one turn-free cohort, the hub shows you their changes as you work and asks the last of you to finish to check the work against the others.${plans.length ? ` ${plans.join(" | ")}` : ""}` : `${task.owner ?? "Whoever takes it"} works alongside without messages (turn-free).`; return `Overlaps ${hits.join("; ")}. ${who}`; } const who = forOwner ? "Settle it with that owner via hub_send before editing those paths." : `${task.owner ?? "Whoever takes it"} is told to settle it.`; return `Overlaps ${hits.join("; ")}. ${who}`; } turnFree = (): boolean => this.d.turnFree?.() ?? false; /** Whether `task` is in a silent cohort: its owner works without messages to the other members (issue #107). */ silentFor = (task: number): boolean => this.turnFree() && !!this.cohorts.of(task)?.silent; /** The live silent cohort that makes a message from `from` to `to` cohort coordination (issue #107). */ silenced = (from: PeerId, to: PeerId) => (this.turnFree() ? this.cohorts.silenced(from, to) : undefined); /** * What `peer`'s turn-free facts cover (issue #108): for each live cohort in which it still has an open task, the paths * every member's task names, the other members' plans, and the task its own writes are reported under. Membership, * not open overlap, so the last member to finish still sees the others' final edits. Undefined without such a task. */ factScope = (peer: PeerId): { paths: string[]; plans: { task: number; owner: PeerId; text: string }[]; task?: { id: number; title: string }; since?: number } | undefined => { const open = (task: number) => OPEN.includes(this.d.board.get(task)?.state ?? "approved"); const members = this.cohorts.list().filter((c) => [...c.members.values()].some((m) => m.owner === peer && open(m.task))).flatMap((c) => [...c.members.values()]); const tasks = members.flatMap((m) => { const t = this.d.board.get(m.task); return t && t.owner === m.owner && !this.isPii(t) ? [t] : []; }); const mine = tasks.filter((t) => t.owner === peer && OPEN.includes(t.state)); if (!mine.length) return undefined; const paths = [...new Set(tasks.flatMap((t) => this.places(t).paths))].filter((p) => p !== "." && this.nameable(p)); const plans = tasks.filter((t) => t.owner !== peer).map((t) => ({ task: t.id, owner: t.owner!, text: planText(t.plan) })).filter((p) => p.text); // When the earliest of its tasks was handed over: work from before facts were tracked is not covered. const since = Math.min(...mine.map(handedAt)); return { paths, plans, task: { id: mine[0]!.id, title: mine[0]!.title }, since }; }; /** The tasks an overlap text for `task` names: their plans are in it (issue #108). */ overlapTasks = (task: Task): number[] => this.overlapHits(task).map((h) => h.task.id); /** Console detail advice only: no pair persistence, and no private task on either side. */ symbolOverlaps(task: Task): { task: number; files: string[]; sameFileDifferentSymbols: boolean }[] { // A routing-locality opt-out does not make symbol metadata for a marked task public. const markedPrivate = (value: Task) => value.signals.includes("pii") || value.signals.includes("pii_path"); if (markedPrivate(task)) return []; return this.overlapHits(task).filter(hit => !markedPrivate(hit.task)).map(hit => ({ task: hit.task.id, files: hit.paths.filter(this.publicMetadataText), sameFileDifferentSymbols: this.sameFileDifferentSymbols(task, hit), })); } /** * Dashboard warning links (#264): the board's overlap pairs and the live cohorts, as task and peer ids only. * Paths, symbols and plans stay out; PII tasks are excluded by the same rules overlapHits applies. * ponytail: O(open²) board reads per call, fine at dashboard board sizes; cache by board revision if it ever shows. */ overlapLinks(): { tasks: [number, number]; peers: string[] }[] { const links: { tasks: [number, number]; peers: string[] }[] = []; const seen = new Set(); for (const task of this.d.board.list()) { if (!OPEN.includes(task.state) || !task.owner || this.isPii(task)) continue; for (const hit of this.overlapHits(task)) { const pair = [task.id, hit.task.id].sort((a, b) => a - b) as [number, number]; const key = pair.join(":"); if (seen.has(key)) continue; seen.add(key); links.push({ tasks: pair, peers: [...new Set([task.owner, hit.task.owner!])].sort() }); } } return links; } /** The live cohorts as dashboard links (#264): member task ids and their owners, nothing else. */ cohortLinks(): { tasks: number[]; peers: string[] }[] { const links: { tasks: number[]; peers: string[] }[] = []; for (const cohort of this.cohorts.list()) { const members = [...cohort.members.values()].filter(member => { const task = this.d.board.get(member.task); return task && !this.isPii(task); }); if (members.length < 2) continue; links.push({ tasks: members.map((m) => m.task).sort((a, b) => a - b), peers: [...new Set(members.map((m) => m.owner))].sort() }); } return links; } /** While a gone owner's tasks move, its other tasks are about to move too: they are no one to settle with. */ private releasing: PeerId | undefined; /** * Notices that only matter while their recipient's task is open (issue #106): envelope id -> recipient and task, the * newest 1024. An envelope without a record (another kind, a restart, an evicted record) is delivered as before: its * purpose is never guessed from its kind. * ponytail: kept in memory, so after a restart such a notice is delivered whatever its task's state; persist the * condition if stale notices after restarts show up. */ private readonly conditional = new Map(); /** * Publish a notice about `task`, which only matters to `to` while that task is in one of `states` for it (issue * #106): open work by default; the conflict notices of #91 count a task in review too. */ /** * #713: the completed-change notice of task `done` for one recipient, about all of its tasks in `about`. It stays relevant while any of them is still open for the * recipient, and carries `completedFor` so the bus replaces an earlier queued notice for the same `done` task and recipient. */ whileOpenFor(to: PeerId, done: number, about: number[], body: string): void { requireLocalTaskPeer(to); const env = newEnvelope(HUB, body, { to: [to], kind: "task", refs: { task: String(about[0]), taskRecipient: "owner", completedFor: done } }); this.conditional.set(env.id, { peer: to, task: about[0]!, tasks: about, states: OPEN }); if (this.conditional.size > 1024) this.conditional.delete(this.conditional.keys().next().value as string); this.d.bus.publish(env); } whileOpen(to: PeerId, task: number, body: string, states: Task["state"][] = OPEN): void { requireLocalTaskPeer(to); const env = newEnvelope(HUB, body, { to: [to], kind: "task", refs: { task: String(task), taskRecipient: "owner" } }); this.conditional.set(env.id, { peer: to, task, states }); if (this.conditional.size > 1024) this.conditional.delete(this.conditional.keys().next().value as string); this.d.bus.publish(env); } /** * Whether a queued envelope still matters to `peer`; the bus asks per recipient at delivery (issue #106). False only * for a recorded notice to this peer whose task is gone, has another owner, or left the states it was about. */ relevant = (peer: PeerId, env: Envelope): boolean => { if (env.from === HUB && env.kind === "task" && env.refs?.backlog) { const ids = env.refs.backlog; if (!Array.isArray(ids) || !ids.length || ids.length > 64 || ids.some(id => !Number.isSafeInteger(id) || id <= 0)) return false; const current = ids.filter(id => { const task = this.d.board.get(id); return task?.state === "backlog" && this.taskPlanner(task).includes(peer); }); if (current.length !== ids.length || !this.d.roles?.[peer]?.includes("planner") || !this.d.bus.isRostered(peer)) { this.addPlannerBacklog(peer, current); for (const id of ids) { const task = this.d.board.get(id); if (task?.state === "backlog" && !this.taskPlanner(task).includes(peer)) { for (const recipient of this.taskPlanner(task)) this.addPlannerBacklog(recipient, [id]); } } return false; } return true; } if (env.from === HUB && env.refs?.task) { const task = this.d.board.get(Number(env.refs.task)); if (env.kind === "task" && env.refs.taskOffer !== undefined && task?.owner === peer && this.studyDispatchReason(task, peer)) { // The bus discards a false verdict for good and cannot hold the envelope. Remember the owner it was for (on the board, so it survives a restart), so approving the study again offers the retained task afresh. try { this.d.board.recordResearchDroppedOffer(task.id, peer); } catch (e) { this.releaseNotice(`task ${this.publicTitle(task)}: could not record the dropped study offer: ${e instanceof Error ? e.message : String(e)}`); } return false; } // #1176: an offer queued before the card was marked is dropped at delivery, not handed to the agent. if (env.kind === "task" && env.refs.taskOffer !== undefined && task?.needsPerson && task.owner === peer) return false; if (task?.state === "cancelled") return env.kind === "task" && typeof env.refs.taskCancelled === "number" && env.refs.taskCancelled === task.cancelled?.flowRevision; if (env.refs.taskRecipient === "planner") return !!task && this.taskPlanner(task).includes(peer); if (env.refs.planReview !== undefined) return !!task && !isClosedTaskState(task.state) && (task.planningRevision ?? 0) === env.refs.planReview && this.plannerHolders().includes(peer) && this.planAuthor(task) !== peer && Number.isSafeInteger(env.refs.planReviewFlow) && !task.history.slice(env.refs.planReviewFlow).some(entry => entry.event === "plan reviewed"); } const c = this.conditional.get(env.id); if (!c || c.peer !== peer) return true; // A notice about several of the recipient's tasks matters while any one of them is still open for it (#713). return (c.tasks ?? [c.task]).some((id) => { const t = this.d.board.get(id); return !!t && t.owner === peer && c.states.includes(t.state); }); }; /** Whether a model-written name may be shown to other peers and in the log: one matching a PII pattern may be PII. */ nameable = (t: string): boolean => !this.isPii({ signals: detectSignals({ title: "", detail: t, refs: {} }, this.d.routing(), this.d.cwd) }); /** * Model-written free text about an ordinary task (a done summary, a review note with its unmet items, a handoff) * that matches a PII pattern stays on this machine (#69): every peer gets a stub, `local` too, which handles an * ordinary task's turn like any other (gateway off campus allowed, memory capture on). The board keeps the text for * `ahub task show`. A PII task's messages are private already. `withheld`: the PII screen did not clear it (#198). */ private screen(task: Task, text: string, what: string, to: PeerId | null | undefined, withheld = false): string { if (!text || this.isPii(task) || to === USER || (!withheld && this.nameable(text))) return text; this.d.notify(`task #${task.id}: the ${what} was withheld from ${to ?? "a peer"} (${this.whyWithheld(text)})`); return `[${what} withheld: ${this.whyWithheld(text)}; ahub task show ${task.id}]`; } /** Where two tasks meet: shared paths, then shared symbols, leaving out any name that matches a PII pattern. */ private where(hit: { paths: string[]; symbols: string[] }): string { const shown = [...hit.paths.filter(this.nameable), ...hit.symbols.filter(this.nameable).map((s) => `symbol ${s}`)]; return shown.length ? shown.join(", ") : "a path whose name is withheld (it matches a PII pattern)"; } /** * Paths from refs and plan, symbols from the plan: the places a task says it touches (issue #31). Models write paths * absolute or relative: one inside the project is compared in its project-relative spelling. */ private warmRepository(task: Pick): void { const scope = this.repositories.scope(task.refs); if (scope !== this.repositories.project) for (const path of [...(task.refs.paths ?? []), ...(task.plan?.paths ?? [])]) this.repositories.relativePath(scope, path); } private places(task: Task): { repositoryKey: string; paths: string[]; symbols: string[] } { const scope = this.repositories.scope(task.refs); const paths = [...(task.refs.paths ?? []), ...(task.plan?.paths ?? [])].map((p) => scope === this.repositories.project ? this.projectPath(p) : normPath(this.repositories.relativePath(scope, p))); const symbols = [ ...(task.plan?.symbols ?? []).map(normalizePlanSymbol), ...(task.plan?.sections ?? []).map(v => `section ${v}`), ...(task.plan?.sources ?? []).map(v => `source ${v}`), ]; return { repositoryKey: scope.key, paths: [...new Set(paths)], symbols: [...new Set(symbols)] }; } private roots?: string[]; private projectPath(p: string): string { if (!isAbsolute(p)) return normPath(p); if (!this.roots) { let real = this.d.cwd; try { real = realPath(this.d.cwd); } catch { /* compared as given */ } this.roots = [...new Set([this.d.cwd, real])]; } for (const root of this.roots) { const r = relative(root, p); if (!r.startsWith("..") && !isAbsolute(r)) return normPath(r || "."); } return p; } private overlapHits(task: Task): { task: Task; paths: string[]; symbols: string[] }[] { const mine = this.places(task); if ((!mine.paths.length && !mine.symbols.length) || this.isPii(task)) return []; return this.d.board.list().flatMap((t) => { if (t.id === task.id || !t.owner || t.owner === task.owner || t.owner === this.releasing || !OPEN.includes(t.state) || this.isPii(t)) return []; const theirs = this.places(t); if (mine.repositoryKey !== theirs.repositoryKey) return []; const paths = task.profile && t.profile && (task.plan?.sections?.length && t.plan?.sections?.length) ? [] : mine.paths.filter((p) => theirs.paths.some((q) => samePlace(p, q))); const symbols = mine.symbols.filter((x) => theirs.symbols.some((y) => symbolsOverlap(x, y))); return paths.length || symbols.length ? [{ task: t, paths, symbols }] : []; }); } /** The console notice and the telemetry record of an overlap; the two are counted against each other (issue #40). */ private announceOverlap(task: Task, hits: ReturnType): void { this.d.notify(`task ${this.publicTitle(task)} (${task.owner}): ${this.overlaps(task, false, hits)}`); this.d.recordOverlap?.(task.id, task.owner!, hits.map((h) => ({ task: h.task.id, owner: h.task.owner!, paths: h.paths.filter(this.nameable), ...(h.symbols.length ? { symbols: h.symbols.filter(this.nameable) } : {}) }))); } /** * The earlier owners hear of an overlap on their next delivery, costing them no turn; the newcomer settles it (#6). * Its plan rides along, so they know what it will touch (issue #31). */ private tellEarlierOwners(task: Task, hits = this.overlapHits(task)): void { if (!task.owner || !this.d.tell) return; const plan = planText(task.plan); for (const hit of hits) { if (hit.task.owner === USER || hit.task.owner === HUB) continue; const how = this.silentFor(task.id) ? `do not message ${task.owner}: you are in one turn-free cohort and the hub shows you its changes as you work` : `${task.owner} is told to settle it`; this.d.tell(hit.task.owner!, noteLine(HUB, "finding", `task #${task.id} (owner ${task.owner}) now overlaps your #${hit.task.id} on ${this.where(hit)}; ${how}${plan ? `. Its plan (full: hub_task_list): ${plan}` : ""}`)); } } /** * An owner offline past the limit loses its open tasks back to routing, through the same path a budget pause uses. * Only when some other peer can take a task: with nobody to hand it to, it stays with its owner. */ async releaseFromGone(peer: PeerId, minutes: number): Promise<{ id: number; title: string; to: PeerId | null }[]> { requireLocalTaskPeer(peer); const moved: { id: number; title: string; to: PeerId | null }[] = []; const why = `owner ${peer} offline for ${minutes} min`; const ids = this.d.board.list().filter((t) => t.owner === peer && OPEN.includes(t.state)).map((t) => t.id); this.releasing = peer; try { for (const id of ids) { // Awaits run between tasks (briefs, memory): re-read, and stop for anything that changed meanwhile. const task = this.d.board.get(id); if (!task || task.owner !== peer || !OPEN.includes(task.state) || this.d.bus.stateOf(peer) !== "offline") continue; if (!assign(task, this.states(), this.d.routing(), { exclude: [...this.excluded(task), peer], excludeOwners: this.plannerPullRecord(task)?.pull ? this.plannerFull(task) : [], ...this.health() }).owner) continue; try { const back = task.state === "in_progress" ? this.d.board.update(task.id, HUB, "released", { state: "proposed" }, why) : task; const next = await this.assignOwner(back, HUB, { exclude: [peer], event: "reassigned", reason: "offline", note: why }); if (this.ownOwnerMove(back, next, HUB, "reassigned")) moved.push({ id: task.id, title: this.publicTitle(task), to: next.owner }); // The gone owner hears it on its next delivery, if it comes back mid-work. if (next.owner && next.owner !== peer) this.d.tell?.(peer, noteLine(HUB, "decision", `task #${task.id} moved to ${next.owner} while you were offline; stop working on it`)); } catch (e) { if (e instanceof AssignmentUndeliveredError) { // The move is fact for the board, so it is fact here too: record it, and tell the gone owner to stop // (the console notice was printed where the error was thrown) (#297). moved.push({ id: task.id, title: this.publicTitle(task), to: e.task.owner }); if (e.task.owner && e.task.owner !== peer) this.d.tell?.(peer, noteLine(HUB, "decision", `task #${task.id} moved to ${e.task.owner} while you were offline; stop working on it`)); } else this.d.notify(`task ${this.publicTitle(task)}: could not be released from ${peer}: ${(e as Error).message}`); } } } finally { this.releasing = undefined; } return moved; } /** Same code as assignment, without doing it. `routing`: a candidate policy to explain under (the settings preview, #269). */ explain(target: number | { title: string; detail?: string; class: TaskClass; refs?: TaskRefs }, routing: Routing = this.d.routing()): string[] { const workflow = this.d.sdlc?.config().workflow === "gsd-lite" ? [`criteria checklist required on every task (retired gsd-lite setting, ${this.d.sdlc.config().mode}); board dependencies authoritative`] : []; if (typeof target === "number") { const task = this.d.board.get(target); if (!task) throw new Error(`no task #${target}`); if (isClosedTaskState(task.state)) return [...workflow, `task ${this.publicTitle(task)} (${task.state}): closed; not routed`]; const planned = task.state === "backlog" && !!task.reserved || this.plannerPullRecord(task)?.pull === true; const a = planned ? this.plannerAssignment(task, true, routing) : assign(task, this.states(), routing, { exclude: this.excluded(task), waitsFor: this.waitsFor(task), ...this.weights(task.class, task) }); // The split trace is for the pair the record is about: the task's owner when it has one (issue #109). return [...workflow, `task ${this.publicTitle(task)} (${task.state}, owner ${task.owner ?? "none"}${task.reserved ? `, reserved for ${task.reserved}` : ""})`, ...(task.profileClass ? [`profile class ${profileTaskLabel(task)}`] : []), ...(task.role ? [`task role ${task.role} (guidance only)`] : []), "if it were assigned now:", ...a.trace, ...(this.splitShadow(task, task.owner ?? a.owner)?.trace ?? [])]; } const draft = { title: target.title, detail: target.detail ?? "", refs: target.refs ?? {} }; const signals = this.signalsFor(draft, routing); const base = profileClass(target.class, this.d.profileData ?? this.d.profile); const trace = [...(this.d.profile && this.d.profile !== "dev" ? [`profile class ${target.class} (base ${base}, ${this.d.profile})`] : []), ...assign({ class: base, signals, ...draft }, this.states(), routing, this.weights(base)).trace]; // A draft is not sent to the PII screen (issue #198): a proposal is, and a pii or unknown verdict adds the pii signal. return [...workflow, ...(this.screenOn() && !signals.includes("pii") ? [...trace, "pii_screen is on: at proposal a pii or unknown verdict adds signal pii (local only)"] : trace)]; } /** Public read path: every generated line is screened, including profile/config-derived trace fields. */ publicExplain(target: number | { title: string; detail?: string; class: TaskClass; refs?: TaskRefs }, routing?: Routing): string[] { const trace = this.explain(target, routing); const holds = Object.entries(this.d.held?.() ?? {}).flatMap(([peer, hold]) => trace.some(line => line.startsWith(` hold: ${peer}'s queue is held:`)) ? [] : [`${peer} queue: ${hold}`]); return [...trace, ...holds].map(line => this.nameable(line) ? line : "[routing explanation withheld: it matches a PII pattern]"); } /** * Peers routing leaves out for good (#207): the owners a task was declined for (the console declines for one; older rows * name only the decliner) and the owners it was escalated away from, so a reservation never hands it back to them. */ private excluded = (task: Task) => task.history.flatMap((h) => (h.event === "declined" && h.capacity !== true ? [h.from ?? h.by] : h.event === "escalated" && h.from ? [h.from] : [])); private checkFlowRevision(task: Task, expected: number | undefined, preEffect = false): void { if (expected !== undefined && (!Number.isSafeInteger(expected) || expected < 0 || task.history.length !== expected)) { throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${task.id}: flow revision changed; reload and retry`); } } /** Authorized manual owner removal sticks until a later explicit assignment/reservation, across hub runs. */ private personUnassigned(task: Task): boolean { const manual = (h: HistoryEntry) => h.by === USER || h.conductorManual === true; const removed = task.history.findLastIndex((h) => h.event === "unassigned" && manual(h)); if (removed < 0) return false; return !task.history.slice(removed + 1).some((h) => manual(h) && ["assigned", "reassigned", "escalated", "reserved", "backlog pulled"].includes(h.event)); } /** * Says on the console and hub.log that routing passed over the reserved owner (#207); returns the history note's suffix. * Only news is said: not when the reserved owner is the one the task moves away from, nor once it refused the task for * good (its decline or escalation said that). */ private passedOver(task: Task, a: Assignment): string { if (!a.unreserved || task.reserved === task.owner || this.excluded(task).includes(task.reserved!)) return ""; // Before the write, but after the caller's own (a decline's, say): a throwing console fails nothing (#297). this.releaseNotice(`task ${this.publicTitle(task)}: its reserved owner ${task.reserved} is passed over (${a.unreserved}); routing proceeds`); return `; reserved owner ${task.reserved} passed over: ${a.unreserved}`; } /** Why the task will approve directly at done: no reviewer could be picked, and who was skipped (issue #92). */ private noReviewer(a: Assignment): string { if (a.reviewBlocked) return "blocked: no reviewer can run"; const skipped = a.trace.flatMap((l) => { const m = /^ {2}reviewer candidate (\S+): skipped, (.*)$/.exec(l); return m ? [`${m[1]} (${m[2]})`] : []; }); return `no reviewer: done will approve directly${skipped.length ? ` (skipped: ${skipped.join("; ")})` : ""}`; } private announceRouting(task: Task, a: Assignment): void { if (task.class !== "review" && !a.reviewer) this.d.notify(`task ${this.publicTitle(task)}: ${this.noReviewer(a)}`); const hold = a.owner ? peerEntry(this.d.held?.(), a.owner) : undefined; if (hold) this.d.notify(`task ${this.publicTitle(task)}: ${a.owner}'s queue is held (${hold}); the task arrives once the hold is resolved`); } private assignmentNote(note: string, assignment: Assignment): string { const tagged = assignment.sameFamilyFallback ? `${note}; sameFamilyFallback=true` : note; const pool = assignment.reviewSelection, metadata = this.reviewMetadata(assignment); const walk = pool?.blocked ? pool.walk.slice(0, 16).map(row => { const reason = this.nameable(row.reason) ? Array.from(sanitize(row.reason).replace(/\s+/g, " ")).slice(0, 160).join("") : "[withheld]"; return `${row.id || row.kind}: ${reason}`; }).join("; ") + (pool.walk.length > 16 ? `; +${pool.walk.length - 16} walk entries` : "") : ""; const admission = pool?.admissionRule ? this.nameable(pool.admissionRule) ? Array.from(sanitize(pool.admissionRule).replace(/\s+/g, " ")).slice(0, 160).join("") : "[withheld]" : undefined; const recorded = pool ? `${tagged}; reviewerFamily=${metadata.reviewerFamily ?? "none"}; reviewerReason=${metadata.reviewerReason ?? pool.blocked}${pool.blocked ? `; pool=${pool.blocked}; walk: ${walk}` : ""}${admission ? `; reviewerQuotaRule=${admission}` : ""}` : tagged; const quota = pool?.quotaWait ? `; quota wait: ${pool.quotaWait.candidates.map(row => `${row.id} ${row.state}, reset ${new Date(row.resetsAt).toISOString()}`).join("; ")}` : ""; return assignment.plannerFallback ? `${recorded}; reviewer=planner (fallback)${quota}` : recorded + quota; } /** A later move to another owner means the caller's assignment was superseded, so its success tail is not authoritative. */ private ownOwnerMove(before: Task, after: Task, by: PeerId, event: string): boolean { const moves = (task: Task) => task.history.filter(entry => ["assigned", "reassigned", "escalated", "unassigned"].includes(entry.event)); const prior = moves(before).length, entries = moves(after).slice(prior), own = entries[0]; if (!own || own.by !== by || own.event !== event) return false; if (own.event === "unassigned") return entries.length === 1; return entries.every(entry => entry.owner === own.owner); } /** `override`: a person's explicit assign, which past refusals do not block and which drops an agent's reservation (#207). */ private async assignOwner(task: Task, by: PeerId, opts: { current?: () => void; conductorManual?: true; queueOverride?: "owner"; candidates?: PeerId[]; namedOwner?: PeerId; event?: string; note?: string; reason?: TaskMoveReason; clearOnFail?: boolean; exclude?: PeerId[]; context?: string; contextWithheld?: boolean; claim?: boolean; override?: boolean; roster?: boolean; planner?: boolean; expectedFlowRevision?: number; refuseNamed?: "pre" | "plain"; plannerPull?: { revision: number; note: string; withheld: boolean; guard: () => void } } = {}): Promise { opts.current?.(); if (by === HUB && !task.owner && ["backlog", "proposed"].includes(task.state) && plannedStartPending(task, this.d.now?.() ?? Date.now())) throw new PreEffectToolRefusal("planned start is in the future"); if (task.state === "backlog" && !opts.plannerPull) throw new PreEffectToolRefusal(`task #${task.id}: pull backlog work before assigning it`); const studyReason = this.studyDispatchReason(task, opts.namedOwner); if (studyReason) { if (opts.refuseNamed || opts.plannerPull || opts.claim) throw new PreEffectToolRefusal(studyReason); if (task.state === "proposed" && !task.owner) this.holdReady(task, "study dispatch", studyReason); return task; } const mode = (this.d.sdlc?.config() ?? sdlcConfig(undefined)).mode; let stagedClaimGap: string | undefined; if (mode !== "off" && this.isBuildTask(task)) { const gap = task.sdlc?.planReview ? await this.planReviewGap(task) : "plan not reviewed since proposal"; opts.current?.(); const current = this.d.board.get(task.id); if (!current || !this.ownerAssignmentCurrent(task, current)) { if (opts.plannerPull) throw new PreEffectToolRefusal("planner pull changed during admission"); return current ?? task; } if (by === HUB && !current.owner && ["backlog", "proposed"].includes(current.state) && plannedStartPending(current, this.d.now?.() ?? Date.now())) throw new PreEffectToolRefusal("planned start is in the future"); task = current; // Reviewer-only and quiet bookkeeping updates do not supersede ownership authority. if (gap) { this.requestIndependentPlanReview(current); const entry = mode === "enforce" ? this.entryDiagnostic(current, gap) ?? `${gap}; planner: hub_plan_review` : `${gap}; planner: call hub_planner_groom then hub_plan_review`; this.releaseNotice(`task ${this.publicTitle(current)}: ${entry}`); if (mode === "enforce") { if (opts.claim && opts.namedOwner === by) stagedClaimGap = gap; else { if (opts.refuseNamed && opts.namedOwner) throw new (opts.refuseNamed === "pre" ? PreEffectToolRefusal : Error)(`cannot assign task #${current.id} to ${opts.namedOwner}: ${entry}`); // #601, before hold bookkeeping this.holdReady(current, "build entry", entry); return this.d.board.get(current.id) ?? current; } } } } const waits = this.waitsFor(task); const plannedMove = opts.planner || this.plannerPullRecord(task)?.pull === true && (by === HUB || opts.roster) && (opts.reason !== "manual" || opts.roster); // #1626 A: an owner choice the hub makes on its own never offers a peer that must refuse it. A person's or conductor's explicit assignment, a claim and a roster move stay as they were. const hubOffer = !opts.roster && !opts.override && !opts.claim && !opts.namedOwner && !opts.conductorManual && !opts.queueOverride && !opts.plannerPull && this.plannerPullRecord(task)?.pull !== true && opts.reason !== "budget" && opts.reason !== "offline" && (by === HUB || !opts.candidates); // a pause or offline relay moves work that already has an owner, so it is not an offer const plannerFull = plannedMove ? this.plannerFull(task) : hubOffer ? this.hubOfferFull(task) : []; const a = assign(opts.plannerPull ? { ...task, state: "proposed" } : task, this.states(), this.d.routing(), { exclude: [...(opts.override ? [] : this.excluded(task)), ...(opts.exclude ?? []), ...(opts.event === "escalated" && task.owner ? [task.owner] : [])], excludeOwners: [...plannerFull, ...this.studyExcludedOwners(task)], ...(opts.candidates ? { candidates: opts.candidates } : {}), waitsFor: waits, ...this.weights(task.class, task), ...(opts.namedOwner ? { namedOwner: opts.namedOwner } : {}), // A self-claim hands over no envelope; reviewer admission remains automatic. contextOverride: !!(opts.queueOverride || opts.claim), ...(opts.queueOverride || opts.claim ? { queueOverride: opts.queueOverride ?? "owner" as const } : {}) }); if (waits.length) { if (opts.plannerPull) throw new PreEffectToolRefusal("planner pull waits for dependency approval"); this.releaseNotice(`task ${this.publicTitle(task)} waits for ${waits.map((id) => `#${id}`).join(", ")}; it is offered once they are approved`); return task; } const passed = this.passedOver(task, a); if (!a.owner) { // An explicit assignment says why the named peer cannot take it, before any write (#601). if (opts.refuseNamed && opts.namedOwner) { const why = a.refusals?.find(row => row.role === "owner" && row.peer === opts.namedOwner)?.reason ?? "not eligible"; throw new (opts.refuseNamed === "pre" ? PreEffectToolRefusal : Error)(`cannot assign task #${task.id} to ${opts.namedOwner}: ${why}${/offline|not attached/.test(why) ? "; assign again once it is attached" : ""}`); } this.releaseNotice(opts.roster ? `task ${this.publicTitle(task)}: ${task.owner} is off roster and no peer can take it; it stays with ${task.owner} in ${task.state}; assign with: ahub task assign ${task.id} ` : `task ${this.publicTitle(task)}: no peer can take it (${a.trace.filter((l) => l.includes("skipped")).length} skipped); assign with: ahub task assign ${task.id} `); // Only a decline takes the task away from its owner; a failed console assign or escalation leaves it where it was. if (opts.clearOnFail && task.owner) { this.cohorts.leave(task.id); task = this.d.board.update(task.id, by, "unassigned", { owner: null }); } if (!task.owner && task.state === "proposed") { const cause = this.ownerStallCause(task, a, !opts.claim); // A named proposal remains bound to that target when pressure clears. this.reportStall(task, cause.kind === "no-eligible-peer" && isQueuePressureCode(cause.code) && opts.namedOwner ? { ...cause, peer: opts.namedOwner } : cause); } return task; } const profile = this.d.splitProfile?.(a.owner); // A person's explicit assign replaces an agent's reservation (#207). Only a refusal keeps the owner it moves away from // out for good: a reviewer's rejections or an escalation by hand, never the hub's own move after a failed delivery. const lasting = opts.event === "escalated" && task.owner && (opts.reason === "rejections" || opts.reason === "manual"); opts.plannerPull?.guard(); const assignmentNote = this.assignmentNote(`${opts.note ?? `to ${a.owner}`}${passed}`, a); const binding = this.plannerBinding(task, a, !!opts.plannerPull); const assignmentExtra = { ...this.reviewMetadata(a, task), ...(binding ? { plannerReason: binding.plannerReason } : {}), ...(profile ? { profile } : {}), ...(opts.reason ? { reason: opts.reason } : {}), ...(lasting ? { from: task.owner! } : {}), ...(opts.conductorManual ? { conductorManual: true as const } : {}) }; opts.current?.(); const current = this.d.board.get(task.id) ?? task; if (by === HUB && !current.owner && ["backlog", "proposed"].includes(current.state) && plannedStartPending(current, this.d.now?.() ?? Date.now())) throw new PreEffectToolRefusal("planned start is in the future"); this.studyDispatchCheck(current, a.owner); const next = opts.plannerPull ? this.d.board.pullAssigned(task.id, by, a.owner, opts.plannerPull.revision, opts.plannerPull.note, opts.plannerPull.withheld, a.reviewer ?? null, assignmentNote, assignmentExtra, task.history.length, binding) : this.d.board.update(task.id, by, opts.event ?? "assigned", { owner: a.owner, reviewer: a.reviewer ?? null, ...(binding ? { planner: binding.planner } : {}), ...(opts.roster && task.state === "in_progress" ? { state: "proposed" as const } : {}), ...(opts.event === "escalated" ? { rejections: 0 } : {}), ...(opts.override && task.reserved ? { reserved: null } : {}) }, assignmentNote, assignmentExtra, opts.expectedFlowRevision); this.queueReviewWritten(next); if (opts.plannerPull) this.planningRecorded({ by, task: next.id, fields: ["pull", "reserved"], revision: next.planningRevision! }); // What calibration reads (issue #109): routing chose the first owner (no single named candidate, no claim; not an // escalation, relay or reassignment of work already begun), and the work overlaps another owner's task not started // yet. For the record only. Work routed back to its proposer is left out, as its observations are (by === owner). if ((opts.event ?? "assigned") === "assigned" && !opts.claim && opts.candidates?.length !== 1 && a.owner !== by) { try { const shadow = this.splitShadow(next, a.owner, true); if (shadow) this.d.recordSplit?.(next.id, shadow, "routing"); } catch { /* shadow only: never between the board write and the delivery */ } } // A claim is its own hand-over: the claimant took the task in the turn it is in, so it is taking it, not busy elsewhere. // The cohort record formed just below reads it, and so does `route explain` while that turn lasts. if (opts.claim && a.owner === by && this.d.bus.peers.get(by)?.state === "busy") this.sent.set(handOver(next, by), by); try { opts.current?.(); if (opts.plannerPull && task.offer) { const prior = { ...task, owner: task.offer.owner }; this.withdrawRoleRequest(prior, next, "owner"); this.releaseNotice(`task #${next.id}: stale offer withdrawal failed`, () => this.d.bus.withdraw(task.offer!.envelopeId)); } if (by === USER && opts.event === "reassigned") this.withdrawRoleRequest(task, next, "owner"); const hits = this.overlapHits(next); this.formCohort(next, hits); if (hits.length) { this.announceOverlap(next, hits); this.tellEarlierOwners(next, hits); } this.announceRouting(next, a); if (!opts.claim || a.owner !== by) await this.sendTask(next, a, opts.context, this.overlaps(next, true, hits), opts.contextWithheld, opts.current); } catch (e) { // Everything between the write and the end of the delivery is in here: the move is fact, and a failure is a // delivery failure (#297). The one console notice is printed here, once, for every caller; callers decide // control flow by the error type. let saved = next; try { saved = this.d.board.get(task.id) ?? next; } catch { /* the write's row is still true */ } // Superseded means a later entry that moves or settles the task: another assignment, an unassign, the // owner's accept, done, approval, close. Entries that do neither (the hub's quiet bookkeeping, a check // result landing during the brief) leave the assignment exactly as undelivered as before: the notice and // the typed error stand (#297 Decisions). const moves = (entries: Task["history"]) => entries.filter((h) => !QUIET_EVENTS.has(h.event) && !h.event.startsWith("check ")); if (moves(saved.history).length !== moves(next.history).length) { if (e instanceof AssignmentSupersededError) return saved; throw e; } this.releaseNotice(this.undeliveredNotice(saved, e)); throw new AssignmentUndeliveredError(saved, e); } // A claim is its own hand-over, with no delivery: its accepted write and its line stay as they were (#297). if (opts.claim && a.owner === by) { // #481 S1: a claim of build work starts it only from an accepted spec. In enforce the claim stays an assignment // (owner set, still proposed); hub_task_accept starts it once the person accepted the spec. if (this.specGated(next) && specState(next.sdlc, undefined) === "missing") { if (this.d.sdlc?.config().mode === "enforce") { this.releaseNotice(`${this.specText(next, "missing", "blocked")}; the claim stays assigned to ${by}`); return next; } this.releaseNotice(this.specText(next, "missing", "advice")); } if (stagedClaimGap) return next; // An explicit claim may reserve its owner, but no offer or acceptance bypasses review. this.studyDispatchCheck(next, by); // #1129: a self-claim of write-class work is an accept too, so a hub-sandboxed claimant gets the hub's worktree here, before the write. When the hub cannot make one the claim stays an assignment, like the missing-spec case above: `hub_task_accept` starts it and refuses with the same cause. let undoWorktree: (() => void) | undefined; try { undoWorktree = this.hubWorktreeFor(next, by); } catch (error) { if (!(error instanceof PreEffectToolRefusal)) throw error; this.releaseNotice(`${error.message}; the claim stays assigned to ${by} and is not started`); return next; } let claimed: Task; try { claimed = this.d.board.update(next.id, by, "accepted", { state: "in_progress" }); } catch (error) { undoWorktree?.(); throw error; } this.captureOwnerAcceptance(claimed); claimed = await this.prepareAcceptedWorktree(claimed, by, opts.current ?? this.requestCheck(by)); this.releaseNotice(`task ${this.publicTitle(claimed)} claimed by ${by}`); return claimed; } return next; } /** #933: the person, or the configured conductor inside an admitted operation (`TasksDeps.operational` rechecks the role). */ private personOrConductor(by: PeerId): boolean { return by === USER || this.d.operational?.(by) === true; } /** Advice changes by the person or, #933, the task's own owner never change ownership, class or authority. */ setRole(by: PeerId, id: unknown, raw: unknown): Task { if (raw === undefined) throw new PreEffectToolRefusal("name a catalog role id or explicit null to clear it"); const task = this.need(id, false, true); if (by !== USER && task.owner !== by) throw new PreEffectToolRefusal(`task #${task.id} is not yours: an agent changes the catalog role of its own task only`); // #933: under review the role is what the reviewer reviews against; only the person changes it then. if (by !== USER && task.state === "in_review") throw new PreEffectToolRefusal(`task #${task.id} is in review: only the person changes its catalog role until the verdict`); if (isClosedTaskState(task.state)) throw new PreEffectToolRefusal("a closed task's role is historical; propose new work instead"); let selected; try { selected = taskRole(raw === null ? undefined : raw, task.class, this.d.catalog ?? loadRoleCatalog(this.d.cwd)); } catch (error) { throw new PreEffectToolRefusal((error as Error).message); } if (task.role === selected?.id) return task; const next = this.d.board.update(task.id, by, "catalog role changed", { role: selected?.id }); for (const peer of new Set([next.owner, next.state === "in_review" ? next.reviewer : null])) { if (!peer || peer === USER) continue; this.releaseNotice(`task ${this.publicTitle(next)}: catalog role update delivery unconfirmed`, () => this.d.bus.publish(newEnvelope(HUB, `Task #${next.id}: catalog role changed by ${by === USER ? "the person" : by}. ${next.role ? this.roleGuidance(next, peer, peer === next.reviewer) : "Catalog guidance cleared; follow the task's existing plan and requirements."}`, { to: [peer], kind: "task", refs: { task: String(next.id), taskRecipient: peer === next.reviewer ? "reviewer" : "owner" }, ...(this.isPii(next) ? { private: true } : {}) }))); } return next; } /** A self-claim has no assignment envelope; its tool result carries the same bounded guidance. */ claimRoleGuidance(task: Task, peer: PeerId): string { requireLocalTaskPeer(peer); // #1129: a claim by a hub-sandboxed peer carries the worktree note as an accept does, since the claim result is all it reads. return task.owner === peer && task.state === "in_progress" ? [this.roleGuidance(task, peer), this.worktreeNote(task, peer)].filter(Boolean).join("\n") : ""; } private roleGuidance(task: Task, peer: PeerId, review = false): string { if (!task.role) return ""; if (!review && this.d.sessionRoles?.(peer).includes(task.role)) return `Task role ${task.role} (already in your session guidance).`; const role = (this.d.catalog ?? loadRoleCatalog(this.d.cwd)).roles.get(task.role); if (role) try { return taskRoleText(role, review); } catch { /* a changed definition cannot break a saved assignment */ } return `Task role ${task.role}: definition unavailable or exceeds the task guidance limit; grants no authority.`; } private ownerAssignmentCurrent(assigned: Task, current: Task): boolean { if (current.owner !== assigned.owner) return false; const moves = (entries: Task["history"]) => entries.filter((h) => !QUIET_EVENTS.has(h.event) && !h.event.startsWith("check ")); return moves(current.history).length === moves(assigned.history).length; } /** `contextWithheld`: the PII screen did not clear a budget hand-off (#198); an escalation's reason is the hub's own words. */ private async sendTask(task: Task, a: Assignment, context?: string, overlap = "", contextWithheld = false, currentAuthority?: () => void): Promise { currentAuthority?.(); const brief = this.isPii(task) ? undefined : await this.d.briefs?.forTask(task.owner!, task, this.planGuardItems(task)).catch(() => undefined); currentAuthority?.(); const current = this.d.board.get(task.id); if (!current || !this.ownerAssignmentCurrent(task, current)) throw new AssignmentSupersededError(current ?? task); this.studyDispatchCheck(current, current.owner ?? undefined); task = current; const pii = this.isPii(task), delivery = { ...a, reviewer: task.reviewer ?? undefined }; const rejected = task.history.filter((h) => h.event === "changes_requested").map((h) => `- ${h.by}: ${this.screen(task, h.note ?? "", "review note", delivery.owner, h.withheld)}`); const handoff = context && !pii ? this.screen(task, context, "handoff", delivery.owner, contextWithheld).slice(0, 3000) : ""; const facts = [`class ${profileTaskLabel(task)}`, delivery.owner && (this.d.adapterCatalog?.definitionOf ?? definitionOf)(delivery.owner, this.d.instances?.())?.routing?.backendLabel ? `backend ${(this.d.adapterCatalog?.definitionOf ?? definitionOf)(delivery.owner, this.d.instances?.())!.routing!.backendLabel}/${delivery.piBackend ?? "dgx"}` : "", task.refs.paths?.length ? `paths ${task.refs.paths.join(", ")}` : "", task.refs.branch ? `branch ${task.refs.branch}` : "", delivery.reviewer ? `reviewer ${delivery.reviewer}` : task.class === "review" ? "no reviewer" : this.noReviewer(delivery)].filter(Boolean).join("; "); const plan = planText(task.plan); const body = [ `Task #${task.id} [${profileTaskLabel(task)}] ${task.title}`, task.detail, `Facts: ${facts}`, this.roleGuidance(task, task.owner!), plan ? `Plan so far: ${plan}` : "", overlap, rejected.length ? `Earlier review notes:\n${rejected.join("\n")}` : "", brief ?? "", // What the previous owner left behind. Peer-written free text: never attached to a PII task. handoff ? `Handoff from the previous owner:\n${handoff}` : "", task.state === "in_review" ? `Ownership moved while this task is already under review. Read it with hub_task_show {id: ${task.id}} and wait for the review verdict; do not accept it or repeat completed work.` : `Take it with hub_task_accept {id: ${task.id}, plan: {paths, symbols, signatures, insertion_points}} (what you will change, before you start${pii ? "" : "; owners of overlapping tasks see it"}) or pass with hub_task_decline. When finished: hub_task_done {id: ${task.id}, summary: what changed, why, and the check you ran with its result, refs}.`, ].filter(Boolean).join("\n\n"); // A hand-over the owner takes in a turn of its own (#109, #115): idle before, busy after and not queued, this envelope // was in the delivery that started its turn. Busy before, it is queued, or steered into a turn about something else // (Codex, Pi); held, it starts no turn yet: neither is taking it. const owner = task.owner!; const idle = this.d.bus.stateOf(owner) === "idle"; const env = newEnvelope(HUB, body, { to: [owner], kind: "task", priority: "important", refs: { ...task.refs, task: String(task.id), taskRecipient: "owner", taskOffer: task.history.length }, ...(pii ? { private: true } : {}) }); currentAuthority?.(); this.studyDispatchCheck(task, owner); this.d.board.recordTaskOffer(task.id, { envelopeId: env.id, owner, assignmentFlowRevision: task.history.length, ...(this.d.offerPullOnly ? { pullOnly: this.d.offerPullOnly(owner) } : {}) }, task.history.length); currentAuthority?.(); this.studyDispatchCheck(task, owner); this.d.bus.publish(env); if (idle && this.d.bus.stateOf(owner) === "busy" && !this.d.bus.queueIds(owner).includes(env.id)) this.sent.set(handOver(task, owner), owner); } /** Nobody, the console user included, works on a task before what it waits for is approved. */ private ready(task: Task, preEffect = false): void { const waits = this.waitsFor(task); if (waits.length) throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${task.id} waits for ${waits.map((id) => `#${id}`).join(", ")}, not approved yet`); } /** Ready offers between their cap check and the owner write (#655): task id -> reserved owner whose slot it takes. */ private readonly readyInFlight = new Map(); /** Offer order for ready work (#655): priority (urgent is P0, none is P2), then rank, then id. */ private readonly readyOrder = (a: Task, b: Task): number => (a.priority ?? (a.signals.includes("urgent") ? 0 : 2)) - (b.priority ?? (b.signals.includes("urgent") ? 0 : 2)) || (a.rank ?? Number.MAX_SAFE_INTEGER) - (b.rank ?? Number.MAX_SAFE_INTEGER) || a.id - b.id; /** Ready work the hub parked on its reserved owner's WIP cap (#655): its latest move-or-hold entry is `ready held`. */ private isHeld(task: Task): boolean { // A planner's priority or rank edit (`planned`) is no move: it must not make held work look released. return task.history.findLast(entry => entry.event === "ready held" || !QUIET_EVENTS.has(entry.event) && entry.event !== "planned")?.event === "ready held"; } /** * Why readiness must not hand `task` to its reserved owner yet (#655): that owner is at its planner WIP cap, the count * `acceptanceCapacity` refuses at. Peer id and counts only, so it is safe for a PII task. A reserved owner the task * excludes is not honoured by routing, and planner-pulled work was admitted by its pull: neither is held. */ private reservedHold(task: Task): string | undefined { const owner = task.reserved; if (!owner || task.owner || this.plannerPullRecord(task)?.pull === true || this.excluded(task).includes(owner)) return undefined; // Offers in flight take a slot before their owner is written; once it is written wip() counts it, so never twice. const flying = [...this.readyInFlight].filter(([id, peer]) => peer === owner && id !== task.id && !this.d.board.get(id)?.owner).length; const limit = this.wipLimit(owner), used = this.wip(owner, task.id) + (this.pendingClaims.get(owner) ?? 0) + flying; return used >= limit ? `reserved owner ${owner} is at its planner WIP cap (${used}/${limit}); stays ready in To Do with its reservation until a slot frees` : undefined; } /** The task is ready but its reserved owner has no room: say so once on the task history, never assign. */ private holdReady(task: Task, why: string, reason: string): void { if (this.isHeld(task)) return; const ready = task.history.at(-1)?.event === "ready" ? task : this.d.board.update(task.id, HUB, "ready", {}, why); this.d.board.update(ready.id, HUB, "ready held", {}, reason); this.releaseNotice(`task ${this.publicTitle(ready)} is ready but held: ${reason}`); } /** An approved task may be the last thing others waited for: those go through assignment now (issue #34). */ private async releaseDependents(approved: Task): Promise { try { // Its dependents and, as its owner's slot just freed (#655), that owner's held ready tasks: one list in priority order. const ready = this.d.board.list("proposed").filter(t => !t.owner && !this.waitsFor(t).length && (t.deps?.includes(approved.id) || !!approved.owner && t.reserved === approved.owner && this.isHeld(t))).sort(this.readyOrder); for (const t of ready) await this.offerReady(t, t.deps?.includes(approved.id) ? `#${approved.id} approved` : "owner slot freed"); } catch (e) { this.releaseNotice(`task #${approved.id}: could not release dependents: ${e instanceof Error ? e.message : String(e)}`); } } /** * The one guard for a publish or notify after a board write (#231, #243): the write took effect, so a failure * never throws back to the caller. A failed publish becomes a console notice naming what was lost; a failed notify * is dropped (a second attempt would fail the same way). A lost publish is not retried here: the delivery * journal's own recovery covers a storage error. */ private releaseNotice(line: string, run?: () => unknown): void { if (!run) { try { this.d.notify(line); } catch { /* best effort; the release timer retries ownerless work */ } return; } try { run(); } catch (e) { try { this.d.notify(`${line}: ${e instanceof Error ? e.message : String(e)}`); } catch { /* best effort */ } } } /** * The one text for a saved assignment whose delivery is unconfirmed (#297), built through publicTitle (a PII task * shows nothing more than it does today): what to check, and how to send it again. No automatic resend: a blind * resend can duplicate a publish that did leave (the #276 decision). */ undeliveredNotice(task: Task, cause: unknown): string { const owner = task.owner ?? "its owner"; return `task ${this.publicTitle(task)}: the move to ${owner} is saved, but its assignment's delivery is not confirmed (${cause instanceof Error ? cause.message : String(cause)}); look for a queued or needs_review delivery with ahub queue list --peer ${owner} (then ahub queue show ), or the accepted entry in ahub task show ${task.id} if the journal is down; send it again with: ahub task assign ${task.id} ${owner}`; } private readonly offered = new Set(); // assignments in this hub run, including offers still in flight private readonly sent = new Map(); // hand-over (`handOver`) -> owner, for the owner's current turn: its task envelope started it, or it claimed the task in it /** * A stop between an approval and the assignment of its dependents (both are saved on their own) leaves them ownerless * with nothing left to wait for, and no later approval to offer them. The daemon calls this on its release timer: * each such task is offered once an attached peer can take it (peers attach one by one). Only an assignment uses * up its offer for this hub run; a failed or ownerless offer stays eligible, after approval and on the timer alike. */ private offerCandidates?: { revision: number; offers: { task: number; peer: PeerId; envelopeId: string; assignmentFlowRevision: number; pullOnly?: boolean }[] }; private stallCandidates?: { revision: number; rows: { stall: TaskStall; task: Task; planned: boolean }[] }; private stallView?: { key: string; stalls: TaskStall[] }; pendingOffers(): { task: number; peer: PeerId; envelopeId: string; assignmentFlowRevision: number; pullOnly?: boolean }[] { const revision = this.d.board.statusRevision(); if (this.offerCandidates?.revision !== revision) this.offerCandidates = { revision, offers: this.d.board.list("proposed").flatMap(task => { const offer = task.offer; if (!offer || task.owner !== offer.owner || task.history.slice(offer.assignmentFlowRevision).some(h => ["accepted", "declined", "assigned", "reassigned", "escalated", "unassigned", "reserved", "backlog returned"].includes(h.event) || h.owner !== undefined && h.owner !== offer.owner)) return []; return [{ task: task.id, peer: offer.owner, envelopeId: offer.envelopeId, assignmentFlowRevision: offer.assignmentFlowRevision, ...(offer.pullOnly === undefined ? {} : { pullOnly: offer.pullOnly }) }]; }) }; return this.offerCandidates.offers.filter(offer => { try { return this.d.offerRead?.(offer.peer, offer.envelopeId) !== true; } catch { return true; } }).map(offer => ({ ...offer })); } /** A status-only snapshot is advisory; all effect/admission callers retain fresh health by default. */ stalled(projection?: { ownerIsolation: Readonly> }): TaskStall[] { const revision = this.d.board.statusRevision(); if (this.stallCandidates?.revision !== revision) this.stallCandidates = { revision, rows: this.d.board.stalls().flatMap(stall => { const task = this.d.board.get(stall.task); if (stall.cause.kind === "no-writes") return (this.sweepConfig.no_writes_turns ?? 2) > 0 && task?.state === "in_progress" && ["implement", "bulk_edit"].includes(task.class) && task.owner === stall.cause.peer && this.ownerAcceptance(task)?.index === stall.cause.acceptance ? [{ stall, task, planned: false }] : []; if (task?.state !== "proposed" || task.owner || (task.planningRevision ?? 0) !== stall.replanRevision) return []; if (stall.cause.kind === "cancelled-dependency") return task.deps?.includes(stall.cause.dependency!) === true && this.d.board.get(stall.cause.dependency!)?.state === "cancelled" ? [{ stall, task, planned: false }] : []; return this.waitsFor(task).length ? [] : [{ stall, task, planned: this.plannerPullRecord(task)?.pull === true }]; }) }; // Eligibility inputs are live; queue journal writes alone do not re-decode board histories. const health = this.health(projection?.ownerIsolation); const key = JSON.stringify([revision, this.states(), this.d.routing(), health, [...this.d.bus.peers.keys()].map(peer => { const queue = this.d.bus.queueSummary(peer); return [peer, this.wipLimit(peer), queue.heldBy, queue.needsReview]; })]); if (this.stallView?.key !== key) this.stallView = { key, stalls: this.stallCandidates.rows.filter(({ stall, task, planned }) => stall.cause.kind === "no-writes" || stall.cause.kind === "cancelled-dependency" || !(planned ? this.plannerAssignment(task, true, this.d.routing(), undefined, health) : assign(task, this.states(), this.d.routing(), { exclude: this.excluded(task), ...this.weights(task.class, task, health), ...(stall.cause.kind === "no-eligible-peer" && isQueuePressureCode(stall.cause.code) && stall.cause.peer ? { candidates: [stall.cause.peer], namedOwner: stall.cause.peer } : {}) })).owner).map(({ stall }) => stall) }; return structuredClone(this.stallView.stalls); } private queuePressureKnown: boolean | undefined; private queuePressureGeneration = 0; private queuePressureQueued = false; private queuePressureRunning = false; private queuePressureDirty = false; private queuePressureStopped = false; private queuePressurePass?: QueuePressurePass; private queuePressureContinuation?: ReturnType; private markQueuePressureCandidate(): void { this.queuePressureKnown = true; this.queuePressureGeneration++; this.scheduleQueuePressureRecheck(); } private queueReviewWritten(task: Task): void { this.reviewQuotaTaskChanged(task); if (task.state === "in_review" && task.reviewer === USER && task.history.at(-1)?.queueReviewHeld) this.markQueuePressureCandidate(); } private queuePressureAdmitted(): boolean { try { return !this.queuePressureStopped && !this.d.sweepHeld?.() && !this.d.bus.isRecoveryHeld && !this.d.bus.storageError; } catch { return false; } } /** Run after the bus's synchronous queue checkpoint, coalescing notifications without polling. */ scheduleQueuePressureRecheck(): void { if (this.queuePressureStopped || this.queuePressureKnown === false) return; this.queuePressureDirty = true; if (this.queuePressureQueued || this.queuePressureRunning || this.queuePressureContinuation) return; this.queuePressureQueued = true; queueMicrotask(() => { this.queuePressureQueued = false; if (!this.queuePressureAdmitted()) return; this.queuePressureDirty = false; const pass = this.queuePressurePass ??= { ownerAfter: 0, reviewAfter: 0, ownerDone: false, reviewDone: false, retained: false, generation: this.queuePressureGeneration }; this.queuePressureRunning = true; let failed = false; void this.recheckQueuePressureBatch(pass).catch(() => { failed = true; // A failed/unknown metadata or authority read never creates an assignment. this.queuePressureKnown = true; this.queuePressurePass = undefined; }).finally(() => { this.queuePressureRunning = false; if (!this.queuePressureAdmitted()) { this.queuePressurePass = undefined; return; } if (failed) return; if (this.queuePressurePass && (!pass.ownerDone || !pass.reviewDone)) { this.queuePressureContinuation = setImmediate(() => { this.queuePressureContinuation = undefined; this.scheduleQueuePressureRecheck(); }); this.queuePressureContinuation.unref?.(); return; } this.queuePressurePass = undefined; const changed = pass.generation !== this.queuePressureGeneration; this.queuePressureKnown = pass.retained || changed; if ((this.queuePressureDirty || changed) && this.queuePressureKnown) this.scheduleQueuePressureRecheck(); }); }); } /** Recovery waits for queued/running host writers; a stop fences a writer already in an await. */ queuePressureRechecksPending = (): number => Number(this.queuePressureQueued || this.queuePressureRunning || this.queuePressureContinuation !== undefined); stopQueuePressureRechecks(): void { this.queuePressureStopped = true; this.queuePressureDirty = false; this.queuePressureQueued = false; if (this.queuePressureContinuation) clearImmediate(this.queuePressureContinuation); this.queuePressureContinuation = undefined; this.queuePressurePass = undefined; } private ordinaryQueueProposal(stall: TaskStall, task: Task | undefined): task is Task { return !!task && task.state === "proposed" && !task.owner && !task.draft && !this.waitsFor(task).length && !this.personUnassigned(task) && !this.plannerPullRecord(task)?.pull; } private queueReviewBinding(task: Task): string { return createHash("sha256").update(JSON.stringify([this.reviewHead(task) ?? null, task.refs.repo ?? null, task.sdlc?.repo ?? null, task.sdlc?.pr ?? null])).digest("hex"); } private queueReviewHeld(task: Task): boolean { if (task.state !== "in_review" || task.reviewer !== USER || this.isPii(task) || this.manuallyNamedReviewer(task)) return false; const role = task.history[this.reviewRequestRevision(task) - 1]; return role?.queueReviewHeld === true && role.queueReviewBinding === this.queueReviewBinding(task); } private async recheckQueuePressureBatch(pass: QueuePressurePass): Promise { if (!this.queuePressureAdmitted()) return; if (!pass.ownerDone) { const page = this.d.board.queuePressureStallPage(pass.ownerAfter, QUEUE_RECHECK_PAGE); pass.ownerAfter = page.afterTask; pass.ownerDone = page.done; for (const stall of page.rows) { if (!this.queuePressureAdmitted()) return; const task = this.d.board.get(stall.task); if (!this.ordinaryQueueProposal(stall, task)) { this.d.board.clearStall(stall.task); continue; } if (plannedStartPending(task, this.d.now?.() ?? Date.now())) { const scheduledOrigin = this.d.board.queuePressureStallPage(task.id - 1, 1).rows.find(row => row.task === task.id); if (scheduledOrigin) this.d.board.recordStall({ ...scheduledOrigin, replanRevision: task.planningRevision ?? 0 }); pass.retained = true; continue; } // A planning revision asks for fresh admission, never erases an automatic offer. const namedOwner = stall.cause.peer; const retry = namedOwner ? { candidates: [namedOwner], namedOwner } : {}; const choice = assign(task, this.states(), this.d.routing(), { exclude: this.excluded(task), waitsFor: this.waitsFor(task), ...this.weights(task.class, task), ...retry }); if (choice.owner) { const current = () => { if (!this.queuePressureAdmitted()) throw new PreEffectToolRefusal("queue-pressure retry is no longer admitted"); }; try { // Reserved ready work shares the existing WIP, in-flight slot and offered fences. if (task.reserved) await this.offerReady(task, "queue pressure cleared", current); else await this.assignOwner(task, HUB, { current, ...retry }); } catch (error) { if (!(error instanceof AssignmentUndeliveredError) && this.queuePressureAdmitted()) pass.retained = true; } if (!this.queuePressureAdmitted()) return; } // Pure transient eligibility reads keep the origin; only a gate that owns retries replaces it. const latest = this.d.board.get(task.id); if (this.ordinaryQueueProposal(stall, latest)) { const origin = this.d.board.queuePressureStallPage(task.id - 1, 1).rows.find(row => row.task === task.id); if (this.isHeld(latest)) this.d.board.clearStall(task.id); // WIP release owns its ready-held task now. else if (origin) { this.d.board.recordStall({ ...origin, replanRevision: latest.planningRevision ?? 0 }); pass.retained = true; } else { const replacing = this.d.board.stall(task.id); const selected = choice.owner; const refusal = replacing && selected ? replacing.cause.peer === selected ? replacing.cause.code : replacing.cause.refusals?.find(row => row.peer === selected)?.code : undefined; const transient = replacing && (replacing.cause.kind === "no-eligible-peer" || replacing.cause.kind === "reservation") && replacing.cause.code !== "policy" && (refusal === "offline" || refusal === "not-attached"); if (transient) { // The initially eligible owner vanished during admission; a policy gate never reaches this restore. this.d.board.recordStall({ ...stall, replanRevision: latest.planningRevision ?? 0 }); pass.retained = true; } } // Other replacing gates keep their stall and own any later retry. } else this.d.board.clearStall(task.id); } } if (!pass.reviewDone && this.queuePressureAdmitted()) { const ids = this.d.board.humanReviewPage(pass.reviewAfter, QUEUE_RECHECK_PAGE); pass.reviewAfter = ids.at(-1) ?? pass.reviewAfter; pass.reviewDone = ids.length < QUEUE_RECHECK_PAGE; for (const id of ids) { if (!this.queuePressureAdmitted()) return; const task = this.d.board.get(id); if (!task || !this.queueReviewHeld(task)) continue; const reviewer = await this.recheckQueueReview(task); if (!this.queuePressureAdmitted()) return; const latest = this.d.board.get(id); if (!reviewer && latest && this.queueReviewHeld(latest)) pass.retained = true; } } } private async recheckQueueReview(before: Task): Promise { const revision = this.reviewRequestRevision(before), head = this.reviewHead(before), owner = before.owner; const valid = () => { if (!this.queuePressureAdmitted()) throw new PreEffectToolRefusal("queue-pressure retry is no longer admitted"); const task = this.need(before.id, false, true); if (!this.queueReviewHeld(task) || this.reviewRequestRevision(task) !== revision || this.reviewHead(task) !== head || task.owner !== owner) throw new PreEffectToolRefusal("queue-held review changed"); return task; }; const choose = (task: Task) => assign(task, this.states(), this.d.routing(), { ...this.weights(task.class, task), candidates: [], ...(task.owner ? { notReviewer: task.owner } : {}) }); const initial = choose(valid()); if (!initial.reviewer || initial.reviewer === USER || initial.reviewBlocked) return undefined; try { const admission = await this.reviewRequestAdmission(before, undefined, true, before.owner ?? USER, undefined, () => { valid(); return true; }); const task = valid(), selection = choose(task), reviewer = selection.reviewer; if (!reviewer || reviewer === USER || selection.reviewBlocked) return undefined; valid(); const next = this.d.board.update(task.id, HUB, "reviewer changed", { reviewer }, this.assignmentNote("queue pressure cleared", selection), this.reviewMetadata(selection), task.history.length); this.heldReviews.delete(next.id); // The current head is unchanged; its watcher reads the live reviewer at completion. this.releaseNotice(`task #${next.id}: queued review request unavailable`, () => this.sendReview(next, reviewer, "", admission)); return reviewer; } catch { return undefined; } } /** Guidance is separate from candidate choice: offers retain their existing plan-only gate. */ private entryDiagnostic(task: Task, planGap?: string): string | undefined { if (this.d.sdlc?.config().mode !== "enforce" || !this.isBuildTask(task) || this.isPii(task)) return undefined; return buildEntryDiagnostic(task, planGap); } /** Proposal entry guidance first; otherwise explain an unassigned named owner from its recorded peer stall (#601). */ namedOwnerNote(task: Task, named: PeerId | undefined, by: PeerId): string | undefined { requireLocalTaskPeer(by); if (task.state !== "proposed") return undefined; const entry = this.entryDiagnostic(task); if (entry) return `task #${task.id}: SDLC build entry blocked: ${entry}`; if (!named || task.owner) return undefined; const stall = this.d.board.stalls().find(row => row.task === task.id); if (!stall) return undefined; const code = stall.cause.refusals?.find(row => row.peer === named)?.code ?? (stall.cause.peer === named ? stall.cause.code : undefined); return `${named} was not assigned${code ? ` (${code})` : ""}: ${stall.cause.kind}; assign it again with hub_task_assign once ${named} can take it`; } private ownerStallCause(task: Task, admission: Assignment, automatic = true): TaskStall["cause"] { const refusal = admission.refusals?.find(row => row.role === "owner" && row.peer === task.reserved); // Persist the existing stall vocabulary; the assignment/explain keeps the precise instance/family refusal. const persisted = (code: NonNullable[number]["code"]): TaskStall["cause"]["code"] => code === "context-headroom" || code === "instance" || code === "family" ? "policy" : code; const pressure = automatic ? admission.refusals?.find(row => row.role === "owner" && isQueuePressureCode(row.code)) : undefined; return refusal && !(automatic && isQueuePressureCode(refusal.code)) ? { kind: "reservation", peer: refusal.peer, code: persisted(refusal.code) } : { kind: "no-eligible-peer", code: pressure ? persisted(pressure.code) : "unavailable", refusals: admission.refusals?.filter(row => row.role === "owner").map(({ peer, code }) => ({ peer, code: persisted(code) })).sort((a, b) => a.peer.localeCompare(b.peer)) ?? [] }; } private reportStall(task: Task, cause: TaskStall["cause"], now = Date.now(), description?: string): void { const stall: TaskStall = { task: task.id, cause, signature: JSON.stringify(cause), replanRevision: task.planningRevision ?? 0, at: now }; if (!this.d.board.recordStall(stall)) return; if (cause.kind === "no-eligible-peer" && isQueuePressureCode(cause.code)) this.markQueuePressureCandidate(); const text = description ?? `Task #${task.id} stalled: ${cause.kind}${cause.peer ? ` ${cause.peer}` : ""}${cause.dependency ? ` #${cause.dependency}` : ""} (${cause.code}); configure the runner or peer, ahub task assign ${task.id} , re-plan dependencies, or cancel it.`; this.releaseNotice(text); try { this.d.stallNotice?.(stall); } catch { /* advisory never changes task authority */ } // Advice joins the planner's next delivery; it must not manufacture a turn beside a withheld backlog batch. for (const peer of this.taskPlanner(task).filter(peer => this.d.bus.isRostered(peer))) this.releaseNotice(`task #${task.id}: stall notice unavailable`, () => this.d.tell?.(peer, noteLine(HUB, "finding", text))); } private synthesisTask(by: PeerId, id: unknown): Task { requireLocalTaskPeer(by); if (this.d.profile !== "research") throw new PreEffectToolRefusal("synthesis evidence is research-only; use a research profile and a visible task"); const task = this.studyParent(this.studyNumber(id, "taskId")); if (task.profile !== "research" || by !== USER && !taskShowAllowed(by, task, this.d.roles, this.isConfiguredPlanner(by))) throw new PreEffectToolRefusal("synthesis task unavailable; use a research task visible through hub_task_show"); return task; } private synthesisPrivate(task: Task, by: PeerId): boolean { try { return !!this.d.privateTurn?.(by) || this.isPii(task) || !this.publicMetadataText(JSON.stringify(task.plan?.claims ?? [])); } catch { return true; } } private synthesisPolicy(task: Task): string { let root: string | undefined; try { root = this.deliverablePorts(task).cwd; } catch { /* unknown is part of the fence */ } return JSON.stringify([this.d.profile, this.d.routing().signals, this.d.piiPaths, this.d.deny, root]); } private synthesisRows(links: readonly EvidenceLinkV1[]) { return links.map(link => ({ link, status: link.status === "withdrawn" ? "withdrawn" as const : "active" as const })); } private synthesisInventories(task: Task) { const claims = task.plan?.claims; if (!Array.isArray(claims) || claims.length > 50) throw new PreEffectToolRefusal("synthesis claims unavailable; refresh the task's bounded declared claim list"); return claims.map((_claim, index) => { const identity = taskClaimIdentity(task, index + 1); try { const inventory = this.d.board.latestEvidenceLinks(this.d.project, task.id, identity.claimId, identity.claimRevision, 128); let contradictionHistory: ReturnType = { ids: [], sources: [], members: [], complete: false }; if (inventory.complete) try { contradictionHistory = this.d.board.evidenceContradictionHistory(this.d.project, task.id, identity.claimId, identity.claimRevision, inventory.links); } catch { /* Unknown immutable history cannot erase a contradiction. */ } if (contradictionHistory.complete && contradictionHistory.sources.some(id => { try { return !this.d.evidenceSourceMeta?.(id); } catch { return true; } })) contradictionHistory.complete = false; return { ...identity, inventory, contradictionHistory }; } catch { return { ...identity, inventory: { links: [] as EvidenceLinkV1[], complete: false }, contradictionHistory: { ids: [] as string[], sources: [] as string[], members: [] as string[], complete: false } }; } }); } private synthesisSources(links: readonly Pick[]): { private: boolean; key: string; bytes: number } { const meta: unknown[] = [], seen = new Set(); let bytes = 0; for (const link of links) { if (seen.has(link.sourceId)) continue; seen.add(link.sourceId); const source = (() => { try { return this.d.evidenceSourceMeta?.(link.sourceId) ?? this.studySource(link.sourceId); } catch { return undefined; } })(); if (source?.private || source && !this.publicMetadataText(JSON.stringify(source))) return { private: true, key: "", bytes: 0 }; meta.push([link.sourceId, source]); if (source && "bytes" in source && typeof source.bytes === "number") bytes += source.bytes; } return { private: false, key: createHash("sha256").update(JSON.stringify(meta)).digest("hex"), bytes }; } /** Explicit authoring metadata only: no claim text, source identity, passage, origin or path. */ async synthesisEvidence(by: PeerId, input: unknown) { const fields = this.studyFields(input, ["taskId"]), check = this.requestCheck(by, () => this.studyHold()); return this.studyWrite(async () => { check(); const revision = this.d.board.statusRevision(), task = this.synthesisTask(by, fields.taskId); if (this.synthesisPrivate(task, by)) return { taskId: task.id, status: "private" as const }; const claims = this.synthesisInventories(task), links = claims.flatMap(claim => [...claim.inventory.links, ...claim.contradictionHistory.sources.map(sourceId => ({ sourceId }))]); if (this.synthesisSources(links).private) return { taskId: task.id, status: "private" as const }; const delivered = latestDeliverables(task.history) ?? []; const artifacts = delivered.filter(record => !record.private && record.path && !this.experimentOutputPrivate(task, record.path)) .map(({ id, sha256, format }) => ({ id, sha256, format })); check(); if (this.d.board.statusRevision() !== revision) return { taskId: task.id, status: "unavailable" as const, cause: "inventory_changed" }; return { taskId: task.id, taskCreated: task.created, status: "available" as const, scope: "declared_inventory" as const, deliverables: artifacts, claims: claims.map(claim => { const binding = inventoryBinding(this.synthesisRows(claim.inventory.links), claim.inventory.complete, claim.contradictionHistory); return { claimId: claim.claimId, claimRevision: claim.claimRevision, complete: claim.inventory.complete && claim.contradictionHistory.complete, ...(binding ? { inventory: binding } : {}), evidence: this.synthesisRows(claim.inventory.links).map(({ link, status }) => ({ id: link.id, revision: link.revision, status })) }; }) }; }); } /** Deterministic, explicit and offline: no caller-supplied current state and no semantic/model judge. */ async synthesisCheck(by: PeerId, input: unknown): Promise { return this.synthesisInspect(by, input); } private synthesisInspect(by: PeerId, input: unknown): Promise; private synthesisInspect(by: PeerId, input: unknown, onSnapshot: (manifest: SynthesisManifestV1, current: SynthesisCurrent, report: SynthesisReadiness, valid: () => boolean) => Task): Promise; private async synthesisInspect(by: PeerId, input: unknown, onSnapshot?: (manifest: SynthesisManifestV1, current: SynthesisCurrent, report: SynthesisReadiness, valid: () => boolean) => Task): Promise { const fields = this.studyFields(input, ["taskId", "manifest"]), manifest = parseSynthesisManifest(fields.manifest); if (fields.taskId !== manifest.taskId) throw new PreEffectToolRefusal("synthesis manifest names another task; refresh its task binding and retry"); const check = this.requestCheck(by, () => this.studyHold()); return this.studyWrite(async () => { check(); const boardRevision = this.d.board.statusRevision(), task = this.synthesisTask(by, fields.taskId), taskId = task.id; if (this.synthesisPrivate(task, by)) return { taskId, status: "private" }; const before = this.synthesisInventories(task), allLinks = before.flatMap(claim => claim.inventory.links); const privacyLinks = [...allLinks, ...before.flatMap(claim => claim.contradictionHistory.sources.map(sourceId => ({ sourceId })))]; const sources = this.synthesisSources(privacyLinks); if (sources.private) return { taskId, status: "private" }; const activeLinks = allLinks.filter(link => link.status !== "withdrawn"); if (this.synthesisSources(activeLinks).bytes > 64 * 1024 * 1024) return { taskId, status: "unavailable", cause: "source_input_limit" }; const delivered = latestDeliverables(task.history) ?? [], policy = this.synthesisPolicy(task); // ponytail: any concurrent board write stales this explicit batch. A task-scoped evidence generation narrows the fence later. const base = JSON.stringify([task.created, task.owner, task.reviewer, task.history.length, task.plan?.claims, delivered]); const current = () => { try { check(); const now = this.synthesisTask(by, taskId); return !this.synthesisPrivate(now, by) && this.d.board.statusRevision() === boardRevision && this.synthesisPolicy(now) === policy && JSON.stringify([now.created, now.owner, now.reviewer, now.history.length, now.plan?.claims, latestDeliverables(now.history) ?? []]) === base; } catch { return false; } }; const changed = () => { check(); const now = this.synthesisTask(by, taskId); if (this.synthesisPrivate(now, by) || this.synthesisSources(privacyLinks).private) return { taskId, status: "private" as const }; return { taskId, status: "stale" as const, cause: "context_changed" }; }; try { if (by !== USER) this.d.onReviewObserverInput?.(by); } catch { return { taskId, status: "unavailable", cause: "observer_unavailable" }; } const sourceKeys = new Map(); for (const link of activeLinks) if (!sourceKeys.has(link.sourceId)) { let key: string | undefined; try { const meta = this.d.evidenceSourceMeta?.(link.sourceId); key = meta && Number.isSafeInteger(meta.bytes) && meta.bytes >= 0 ? this.d.evidenceSourceSnapshotKey?.(link) : undefined; } catch { /* unavailable source cannot verify provenance */ } sourceKeys.set(link.sourceId, key); } if (!current()) return changed(); const reads: { path: string; read: GuardedDeliverableRead }[] = []; const artifact = async (reference: { id: string; sha256: string }, limit: number): Promise => { const record = delivered.find(record => record.id === reference.id); if (!record) return { id: reference.id, state: "missing" }; if (record.private || !record.path || this.experimentOutputPrivate(task, record.path)) return "private"; try { const read = await readGuardedDeliverable(record.path, this.deliverablePorts(task, { failClosedOnDiscoveryLimit: true }), limit); const text = new TextDecoder("utf-8", { fatal: true }).decode(read.data); if (!this.publicMetadataText(text)) return "private"; reads.push({ path: record.path, read }); return { id: record.id, sha256: read.sha256, state: read.sha256 === reference.sha256 && record.sha256 === reference.sha256 ? "unchanged" : "changed", text }; } catch { return { id: record.id, state: "unknown" }; } }; const doc = await artifact(manifest.deliverable, 256 * 1024); if (doc === "private") return { taskId, status: "private" }; if (!current()) return changed(); const bib = await artifact(manifest.bibliography, 4 * 1024 * 1024); if (bib === "private") return { taskId, status: "private" }; if (!current()) return changed(); const observed: SynthesisCurrentClaim[] = []; for (const claim of before) { const resolutions: NonNullable[number]["resolutions"]>[number][] = []; for (const link of claim.inventory.links) { if (!current()) return changed(); const withdrawn = link.status === "withdrawn"; if (withdrawn) { resolutions.push({ id: link.id, revision: link.revision, status: "withdrawn" }); continue; } if (!this.d.evidenceSourceRead || !sourceKeys.get(link.sourceId)) { resolutions.push({ id: link.id, revision: link.revision, status: "unavailable" }); continue; } let resolution: EvidenceSourceRead["resolution"]; try { resolution = (await this.d.evidenceSourceRead(by, link, current, { privacyReadOnly: true })).resolution; } catch { resolution = { status: "unavailable", cause: "source_unavailable" }; } if (resolution.status === "unavailable" && resolution.cause === "private") return { taskId, status: "private" }; if (!current()) return changed(); resolutions.push({ id: link.id, revision: link.revision, status: resolution.status === "resolved" ? "resolved" : resolution.status === "stale" ? "stale" : "unavailable" }); } const entry = task.history.findLast(entry => entry.by === USER && entry.event === "claim verdict" && entry.claim?.slot === claim.slot && entry.claim.list === claim.claimRevision)?.claim; const verdict = entry && ["supported", "unsupported", "unclear"].includes(entry.verdict) ? entry.verdict : undefined; const synthesis = entry?.synthesis; observed.push({ claimId: claim.claimId, claimRevision: claim.claimRevision, inventory: { ...claim.inventory, links: this.synthesisRows(claim.inventory.links) }, contradictionHistory: claim.contradictionHistory, resolutions, judgment: { present: !!verdict, ...(verdict ? { verdict } : {}), ...(verdict && synthesis ? synthesis : {}) } }); } const finalCurrent = () => { try { if (!current() || this.synthesisSources(privacyLinks).key !== sources.key) return false; const fencedSources = new Set(); for (const link of activeLinks) if (!fencedSources.has(link.sourceId)) { fencedSources.add(link.sourceId); if (sourceKeys.get(link.sourceId) && this.d.evidenceSourceSnapshotKey?.(link) !== sourceKeys.get(link.sourceId)) return false; } if (reads.some(value => !guardedDeliverableCurrent(value.path, this.deliverablePorts(task, { failClosedOnDiscoveryLimit: true }), value.read))) return false; return this.synthesisSources(privacyLinks).key === sources.key && current(); } catch { return false; } }; if (!finalCurrent()) return changed(); const snapshot: SynthesisCurrent = { taskId, taskCreated: task.created, deliverable: doc, bibliography: bib, claims: observed }; const report = checkSynthesis(manifest, snapshot); return onSnapshot ? onSnapshot(manifest, snapshot, report, finalCurrent) : report; }); } /** Resolve declared provenance afresh, without manufacturing a #901 judgment or synthesis readiness. */ async evidenceRead(by: PeerId, input: unknown): Promise { const refuse = () => new PreEffectToolRefusal("evidence read unavailable; use a current evidence id on a research task visible through hub_task_show"); try { requireLocalTaskPeer(by); } catch { throw refuse(); } if (this.d.profile !== "research") throw refuse(); const check = this.requestCheck(by, () => this.studyHold()); let id: string, revision: number | undefined; try { const fields = this.studyFields(input, ["id", "revision"]); if (Object.values(Object.getOwnPropertyDescriptors(input)).some(field => !field.enumerable) || typeof fields.id !== "string" || !/^ev:[a-f0-9]{32}$/.test(fields.id) || fields.revision !== undefined && (typeof fields.revision !== "number" || !Number.isSafeInteger(fields.revision) || fields.revision < 1)) throw refuse(); id = fields.id; revision = fields.revision as number | undefined; } catch { throw refuse(); } return this.studyWrite(async () => { check(); const link = this.d.board.evidenceLink(this.d.project, id, revision); if (!link) throw refuse(); const receipt = { id: link.id, revision: link.revision, taskId: link.taskId }; const stub = (status: "private" | "stale" | "unavailable" | "withdrawn"): EvidenceReadResult => ({ ...receipt, status }); const context = () => { check(); let task: Task; try { task = this.studyParent(link.taskId); } catch { throw refuse(); } if (task.profile !== "research" || by !== USER && !taskShowAllowed(by, task, this.d.roles, this.isConfiguredPlanner(by))) throw refuse(); let status: "private" | "stale" | "unavailable" | undefined; try { if (this.d.privateTurn?.(by) || task.signals.includes("pii") || task.signals.includes("pii_path") || this.isPii(task) || this.publicMetadataText(evidenceLinkCanonical(link)) !== true) status = "private"; } catch { status = "private"; } if (!status) { try { const identity = taskClaimIdentity(task, Number(link.claimId.split(":").at(-1))); if (identity.claimId !== link.claimId || identity.claimRevision !== link.claimRevision) status = "stale"; } catch { status = "stale"; } } const source = this.studySource(link.sourceId); if (source?.private) status = "private"; else if (!status && !source) status = "unavailable"; else if (!status && source?.sha256 !== link.rawSha256) status = "stale"; return { task, status, key: JSON.stringify([task.created, task.history.length, task.owner, task.reviewer, task.plan?.claims, source]) }; }; const before = context(); if (before.status) return stub(before.status); if (link.status === "withdrawn") return stub("withdrawn"); if (!this.d.evidenceSourceRead) return stub("unavailable"); const current = () => { try { const next = context(); return !next.status && next.key === before.key; } catch { return false; } }; // A returned passage can be quoted by any later tool or final answer in this input. // Reuse the host review-input exclusion before crossing the async read boundary. try { if (by !== USER) this.d.onReviewObserverInput?.(by); } catch { return stub("unavailable"); } let read: EvidenceSourceRead; try { read = await this.d.evidenceSourceRead(by, link, current); } catch { check(); const after = context(); return stub(after.status ?? "unavailable"); } check(); const after = context(); if (after.status) return stub(after.status); if (after.key !== before.key) return stub("stale"); const resolution = read.resolution; if (resolution.status !== "resolved") return stub(resolution.status === "stale" ? "stale" : resolution.cause === "private" ? "private" : "unavailable"); const result: EvidenceReadResult = { ...receipt, status: "resolved", link, excerpt: resolution.excerpt, excerptSha256: resolution.excerptSha256, locator: resolution.locator, origins: this.evidenceOrigins(link) }; try { if (this.publicMetadataText(JSON.stringify(result)) !== true) return stub("private"); } catch { return stub("private"); } if (!current()) { const final = context(); return stub(final.status ?? "stale"); } return result; }); } private evidenceOrigins(link: EvidenceLinkV1): EvidenceReadOrigins { const unknown: EvidenceReadOrigins = { state: "unknown" }; if (!this.d.evidenceSourceMeta) return unknown; // #931 follow-up: an inventory that changed since the caller read it (a link revision gone between the list and its read) leaves the origins unknown beside the evidence that did resolve; // it never fails the whole read. Any other board error (storage invalid) is not this case and still throws, so a damaged hub.db is not hidden behind an advisory field. let inventory: ReturnType; try { inventory = this.d.board.latestEvidenceLinks(this.d.project, link.taskId, link.claimId, link.claimRevision, 128); } catch (error) { if (error instanceof Error && error.message.startsWith("evidence inventory changed")) return unknown; throw error; } if (!inventory.complete || !inventory.links.some(row => row.id === link.id && row.revision === link.revision)) return unknown; try { const groups: Set[] = [], member: { id: string; keys: readonly string[] }[] = []; for (const row of inventory.links.filter(row => row.status !== "withdrawn")) { const meta = this.d.evidenceSourceMeta(row.sourceId); if (!meta || meta.id !== row.sourceId || meta.private || meta.sha256 !== row.rawSha256 || this.publicMetadataText(JSON.stringify(meta)) !== true) return unknown; const keys = evidenceOriginKeys(meta); if (!keys?.length) return unknown; member.push({ id: row.id, keys }); const matches = groups.filter(group => keys.some(key => group.has(key))); const merged = new Set([...keys, ...matches.flatMap(group => [...group])]); for (const group of matches) groups.splice(groups.indexOf(group), 1); groups.push(merged); } const selected = member.find(row => row.id === link.id), group = selected && groups.find(group => selected.keys.some(key => group.has(key))); if (!group) return unknown; // Connected registered origins express provenance grouping only, never independent corroboration or source quality. return { state: "known", group: `origin:${createHash("sha256").update(JSON.stringify([...group].sort())).digest("hex").slice(0, 32)}`, groups: groups.length }; } catch { return unknown; } } /** Pure read screen: never resolve an address or a path to decide whether to publish it. */ private lineageMetadata(text: string): boolean { try { if (!this.nameable(text) || looksSecret(text)) return false; const policy = [...this.d.piiPaths ?? [], ...this.d.deny ?? []]; if (!policy.length) return true; let parsed: unknown; try { parsed = JSON.parse(text); } catch { return false; } // direct stored paths have no alias proof const strings = (value: unknown): string[] => typeof value === "string" ? [value] : Array.isArray(value) ? value.flatMap(strings) : value && typeof value === "object" ? Object.values(value).flatMap(strings) : []; // ponytail: a path-shaped opaque field has no cached alias proof. Withhold it until owner-maintained // public metadata can prove it without filesystem discovery on this read path. return strings(parsed).every(value => !/[\\/]|\.[a-zA-Z]/.test(value) && !matchesPolicyLexically(this.d.cwd, value, policy)); } catch { return false; } } private lineageVisible(by: PeerId, task: Task): boolean { try { if (this.d.privateTurn?.(by) || this.d.reviewObserverInput?.(by) || this.reviewTaskPrivate(task)) return false; if (this.d.piiPaths?.length && ((task.refs.paths?.length ?? 0) || (task.plan?.paths?.length ?? 0) || (task.plan?.sections?.length ?? 0))) return false; if (this.repositories.cachedScope(task.refs)?.key !== this.repositories.project.key) return false; return by === USER || this.d.bus.isRostered(by) && taskShowAllowed(by, task, this.d.roles, this.isConfiguredPlanner(by)); } catch { return false; } } private lineagePorts(by: PeerId): ExecutionLineageOwnerPorts | undefined { const binding = this.d.executionLineage; if (!binding) return undefined; // Agent-wide roles do not grant diagnostic authority over a hidden or staged source. const diagnostics = by === USER; // ponytail: raw50 event pages cannot prove current field privacy after policy narrowing. // Refuse by policy alone until a privacy-aware page source supplies a complete public projection. let eventProjectionSupported = false; try { eventProjectionSupported = !this.d.piiPaths?.length && !this.d.deny?.length && !this.d.routing().signals.pii_patterns.length; } catch { /* unknown current policy cannot admit event projection */ } return { project: this.d.project, projectKey: binding.projectKey, cursorKey: binding.cursorKey, scope: createHash("sha256").update(by).digest("hex"), diagnostics, eventProjectionSupported, task: id => this.d.board.get(id), visible: task => this.lineageVisible(by, task), metadata: text => this.lineageMetadata(text), links: task => this.d.board.executionReferences(binding.projectKey, task.id, task.created), delivery: binding.readDelivery, attempt: id => this.d.board.experimentAttempt(id), events: (id, after, limit) => this.d.board.experimentEvents(id, after, limit), receipts: id => this.d.board.runnerReceipts(id), attemptStatus: id => this.d.board.experimentAttemptStatus(id) }; } /** Read one explicit owner neighborhood; unauthorized, private and missing roots are indistinguishable. */ executionLineage(by: PeerId, input: unknown): LineageResult { if (!executionLinkActor(by) || by === HUB || by === "admin") return { state: "unavailable" }; try { const check = this.requestCheck(by); if (this.d.privateTurn?.(by) || this.d.reviewObserverInput?.(by)) return { state: "unavailable" }; const ports = this.lineagePorts(by); if (!ports) return { state: "unavailable" }; let query; try { query = parseOwnerLineageQuery(input); } catch { return ports.diagnostics ? { state: "unavailable", reason: "invalid" } : { state: "unavailable" }; } const snapshot = executionOwnerSnapshot(ports, query); check(); if (this.d.privateTurn?.(by) || this.d.reviewObserverInput?.(by)) return { state: "unavailable" }; if (snapshot.task) { const current = this.d.board.get(snapshot.task.id); if (!current || current.created !== snapshot.task.created || current.history.length !== snapshot.task.history.length || !this.lineageVisible(by, current)) return { state: "unavailable" }; } return readExecutionLineage(snapshot.source, snapshot.query); } catch { return { state: "unavailable" }; } } private guidanceProbeTimer(): NonNullable["timer"]> { return this.d.guidanceProbes?.timer ?? { set: (callback, ms) => { const timer = setTimeout(callback, ms); timer.unref?.(); return timer; }, clear: handle => clearTimeout(handle as ReturnType), }; } /** Owned in-process work only, not persisted held lanes or a quiescence assertion. */ guidanceProbesPending = (): number => this.guidanceProbeAdmissions + this.guidanceProbeActive.size; async stopGuidanceProbes(): Promise { this.guidanceProbeStopping = true; const active = [...this.guidanceProbeActive.values()]; for (const entry of active) this.guidanceProbeAbort(entry, "observation", true); if (this.guidanceProbesPending() === 0) return; await this.guidanceProbeDrain(active); if (this.guidanceProbesPending() !== 0) throw new Error("guidance probe admission drain is unconfirmed; retain project storage and explicitly retry after owned callbacks settle"); } private async guidanceProbeDrain(active: GuidanceProbeRuntime[]): Promise { const settled = Promise.allSettled(active.flatMap(entry => [entry.promise, entry.stopPromise].filter((value): value is Promise | Promise => value !== undefined))); let timeout: { handle: unknown } | undefined; try { await Promise.race([settled, new Promise((_resolve, reject) => { timeout = { handle: this.guidanceProbeTimer().set(() => reject(new Error("guidance probe stop is unconfirmed after the owned drain bound; retain the held lane and explicitly drain after its fixture callbacks settle")), GUIDANCE_PROBE_STOP_TIMEOUT_MS) }; })]); if (active.some(entry => this.guidanceProbeActive.get(entry.id) === entry)) throw new Error("guidance probe stop evidence is unknown; retain owned handles and explicitly retry the drain after matching fixture stop evidence"); } finally { if (timeout !== undefined) this.guidanceProbeTimer().clear(timeout.handle); } } private guidanceProbeClearWatch(entry: GuidanceProbeRuntime): void { if (entry.watch !== undefined) { this.guidanceProbeTimer().clear(entry.watch.handle); entry.watch = undefined; } } private guidanceProbeRetire(entry: GuidanceProbeRuntime): void { if (this.guidanceProbeActive.get(entry.id) !== entry || !entry.launchSettled || entry.stopRequested && (!entry.stopSettled || !entry.stopKnown)) return; this.guidanceProbeClearWatch(entry); this.guidanceProbeActive.delete(entry.id); } private guidanceProbeAbort(entry: GuidanceProbeRuntime, reason: "elapsed" | "observation", explicitStop = false): void { if (this.guidanceProbeActive.get(entry.id) !== entry) return; this.guidanceProbeClearWatch(entry); if (entry.reservation) { try { this.d.guidanceProbes!.store.latchHold(entry.reservation, reason); } catch { entry.failure = new Error("guidance probe hold bookkeeping is unconfirmed; inspect retained state before any further work"); } } entry.controller.abort(); if (!entry.launched || !entry.reservation) { this.guidanceProbeRetire(entry); return; } if (entry.stopRequested && (!entry.stopSettled || entry.stopKnown || !explicitStop)) return; const reservation = entry.reservation, ports = this.d.guidanceProbes!.fakePorts!; entry.stopRequested = true; entry.stopSettled = false; entry.stopKnown = false; entry.stopPromise = (async () => { try { const result = await ports.stop({ reservation }, new AbortController().signal); entry.stopKnown = result?.stopped === "known_fixture" && guidanceProbeCanonical(result.reservation) === guidanceProbeCanonical(reservation); if (!entry.stopKnown) entry.failure = new Error("guidance probe stop evidence is unknown; inspect the owned reservation and explicitly drain without replaying it"); } catch { entry.failure = new Error("guidance probe stop failed; retain owned handles and explicitly drain before closing project storage"); } finally { entry.stopSettled = true; this.guidanceProbeRetire(entry); } })(); } private guidanceProbeWatch(entry: GuidanceProbeRuntime): void { if (this.guidanceProbeActive.get(entry.id) !== entry || entry.controller.signal.aborted) return; try { entry.current(); const state = this.d.guidanceProbes!.store.read({ projectKey: this.guidanceProject(), id: entry.id }); if (!state || !entry.reservation || state.firstReservedAt === null) throw new Error("owned probe clock is unavailable"); const now = this.d.now?.() ?? Date.now(), elapsed = now - state.firstReservedAt; if (!probeInteger(elapsed) || elapsed < state.counters.elapsedHighWaterMs || state.admissionHold !== "none") { this.guidanceProbeAbort(entry, "elapsed"); return; } const remaining = state.registration.manifest.limits.elapsedMs - elapsed; if (remaining <= 0) { this.guidanceProbeAbort(entry, "elapsed"); return; } entry.watch = { handle: this.guidanceProbeTimer().set(() => { if (this.guidanceProbeActive.get(entry.id) !== entry || entry.controller.signal.aborted) return; entry.watch = undefined; this.guidanceProbeWatch(entry); }, Math.min(GUIDANCE_PROBE_FENCE_INTERVAL_MS, remaining)) }; } catch { this.guidanceProbeAbort(entry, "observation"); } } private guidanceProbeProjection(state: ProbeStoredState, already = false): ProbePublicStatus { const holds = state.admissionHold !== "none" || state.counters.usageUnknown; const authoring: ProbePublicStatus["authoring"] = state.sessions.some(item => item.child?.authoring === "uncontrolled") ? "uncontrolled" : state.sessions.some(item => item.child?.authoring === "admitted_fixture") ? "admitted_fixture" : "unknown"; const launchedSessions = state.sessions.filter(item => item.coverage.launchExposed); const verifiedCoverage = launchedSessions.length > 0 && launchedSessions.every(item => item.coverage.coverageVerified) && state.sessions.filter(item => item.state === "closed_fixture").every(item => item.coverage.coverageVerified) && state.sessions.every(item => item.state !== "failed_known" || item.coverage.preLaunchFailure || item.coverage.coverageVerified); const evidence: ProbePublicReceipt["evidence"] = state.counters.workerAttempts + state.counters.editorAttempts === 0 ? "declaration" : holds || !verifiedCoverage || state.sessions.some(item => ["reserved", "running", "unknown_held"].includes(item.state)) ? "unknown" : "fixture"; return { ...state.receipt, already, taskId: state.registration.manifest.task.id, experimentId: this.guidancePublicField(state.registration.manifest.experimentId), evidence, counters: { ...state.counters }, cancelRequested: state.cancelRequested, notNeeded: state.notNeeded, authoring, comparable: state.receipt.state === "closed_fixture" && !holds && verifiedCoverage && authoring === "admitted_fixture" }; } private guidanceProbeReceipt(state: ProbeStoredState, already = false): ProbePublicReceipt { const { counters: _counters, cancelRequested: _cancelRequested, notNeeded: _notNeeded, comparable: _comparable, authoring: _authoring, ...result } = this.guidanceProbeProjection(state, already); return result; } private guidanceProbeState(by: PeerId, id: string, check: () => void): ProbeStoredState { check(); if (!probeSha256(id)) throw new PreEffectToolRefusal("guidance probe id is invalid; use the exact registered content id"); if (!this.d.guidanceProbes) throw new PreEffectToolRefusal("guidance probe storage is unavailable; restart a supporting hub before retrying"); const state = this.d.guidanceProbes.store.read({ projectKey: this.guidanceProject(), id }); if (!state) throw new PreEffectToolRefusal("guidance probe is unavailable; inspect a registered declaration in this project"); this.guidanceProbeTask(by, state.registration.manifest.task, false); check(); return state; } private guidanceProbeHost(by: PeerId, manifest: GuidanceProbeManifestV1, request: ReturnType, history?: ProbeHostBinding): ProbeHostBinding { request.check(); const projectKey = this.guidanceProject(); if (projectKey !== manifest.projectKey) throw new PreEffectToolRefusal("guidance probe project changed; register within the current project namespace"); const task = this.guidanceProbeTask(by, manifest.task, history === undefined); const binding = { projectKey, actor: by, task: { id: task.id, created: task.created, flowRevision: task.history.length }, sessionGeneration: request.generation, nativeSession: request.nativeSession, requestConnectionId: request.requestConnectionId }; // A narrowing cancellation carries its original baseline as history, never a new applicability grant. if (history) return { ...binding, role: history.role, baselineGuidance: history.baselineGuidance }; const role = this.guidanceRole(task); return { ...binding, role: { id: role.id, layer: role.layer, baselineSha256: role.hash }, baselineGuidance: taskRoleText(role) }; } private guidanceProbeSnapshotClear(state: ProbeStoredState["registration"]): boolean { return Object.entries(state.snapshots).every(([field, value]) => { const text = field === "dataPolicy" ? guidanceProbeCanonical(value) : value as string; return this.nameable(text) && !looksSecret(text); }); } private guidanceProbeRenderedClear(text: string): boolean { if (!this.nameable(text) || looksSecret(text)) return false; const policy = [...this.d.deny ?? [], ...this.d.piiPaths ?? []]; if ([...pathCandidates(text)].some(candidate => matchesPolicyLexically(this.d.cwd, candidate, policy))) return false; return !policy.some(entry => { const literal = entry.replace(/^\.\//, "").split(/[*?[\]{}]/)[0]!.replace(/\/+$/, ""); return /[/\s]/.test(literal) && text.includes(literal); }); } async guidanceProbeRegister(by: PeerId, value: unknown): Promise { const request = this.guidanceProbeRequest(by), registration = parseGuidanceProbeRegistration(value); if (!registration) throw new PreEffectToolRefusal("guidance probe declaration is invalid or oversized; use the closed V1 envelope without trimming its snapshots"); const binding = this.guidanceProbeHost(by, registration.manifest, request); if (!this.guidanceProbeSnapshotClear(registration)) throw new PreEffectToolRefusal("guidance probe inputs are private; register public task-local inputs in a current public session"); this.guidanceProbeAdmissions++; let wrote = false; try { const saved = this.d.guidanceProbes!.store.register(registration, binding, () => { if (!this.guidanceProbeSnapshotClear(registration)) throw new PreEffectToolRefusal("guidance probe input policy changed; inspect its current public scope before retrying"); return this.guidanceProbeHost(by, registration.manifest, request); }); wrote = !saved.already; const state = this.guidanceProbeState(by, saved.id, request.check); return this.guidanceProbeReceipt(state, saved.already); } catch (error) { if (!wrote && (error instanceof PreEffectToolRefusal || error instanceof GuidanceProbeError && error.reason !== "storage")) throw error; throw new Error("guidance probe registration is unconfirmed; inspect retained state before explicitly retrying"); } finally { this.guidanceProbeAdmissions--; } } async guidanceProbeShow(by: PeerId, id: string): Promise { const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check); request.check(); const status = this.guidanceProbeProjection(state); // T3 (#1226): the sealed receipts can only make the verdict stricter, never grant one the older expression refused. The reasons and the denominator stay in // the store's private status; public show keeps just this flag. A store that cannot be read is not comparable. if (!status.comparable) return status; let sealedComparable = false; try { sealedComparable = this.d.guidanceProbes!.store.outcome({ projectKey: this.guidanceProject(), id: state.receipt.id })?.comparability.comparable === true; } catch { /* fail closed */ } return sealedComparable ? status : { ...status, comparable: false }; } /** * T4 (#1226): the producer receipt reader and export. The same person/conductor, session and task fences as `guidanceProbeShow`, and read-only: it launches, * reserves, writes and prunes nothing. It carries the status, the outcome denominator and the sealed receipts, each re-verified against its own digest by the * Store, so a tampered row refuses the whole read instead of being skipped. Output names are model-written, so each receipt passes the same screen as any * other public field; one that fails is replaced by its digest alone and the slot says `withheld`. A retained directory is a state, never a path. */ async guidanceProbeReceipts(by: PeerId, id: string): Promise { const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check); request.check(); const store = this.d.guidanceProbes!.store, key = { projectKey: this.guidanceProject(), id: state.receipt.id }; const status = await this.guidanceProbeShow(by, id); let receipts: ProbeReceiptV1[], outcome: ReturnType, retention: Map; try { receipts = store.receipts(key); outcome = store.outcome(key); retention = store.retentionStates(key); } catch (error) { if (error instanceof GuidanceProbeError) throw error; throw new GuidanceProbeError("storage"); } if (!outcome) throw new GuidanceProbeError("storage"); request.check(); const bySlot = new Map(receipts.map(item => [item.slotId, item])); const slots: ProbeExportSlot[] = state.registration.manifest.slots.map((slot, index) => { const session = state.sessions[index]!, receipt = bySlot.get(slot.id); const shown = receipt !== undefined && this.guidanceProbeReceiptClear(receipt); return { slotId: slot.id, stage: slot.stage, role: slot.role, arm: slot.arm, state: session.state, receipt: shown ? receipt : null, receiptDigest: receipt?.digest ?? null, withheld: receipt !== undefined && !shown, retention: retention.get(slot.id) ?? "none" }; }); // The sealed verdict can only make the public one stricter, exactly as in `show`: a status that already refused stays refused. const comparable = status.comparable && outcome.comparability.comparable; const result: ProbeReceiptExport = { v: 1, status: { ...status, comparable }, comparable, reasons: outcome.comparability.reasons, counts: outcome.counts, slots }; // What leaves this process is what the consumer's parser will accept: a result that does not round-trip is a storage fault, never a partial answer. const checked = parseGuidanceProbeReceiptExport(JSON.parse(JSON.stringify(result))); if (!checked) throw new GuidanceProbeError("storage"); return checked; } /** Every free-text name a receipt carries (output paths, exclusions, the served model) must pass the public-field screen; the digest alone is kept otherwise. */ private guidanceProbeReceiptClear(receipt: ProbeReceiptV1): boolean { const names = [receipt.experimentId, receipt.slotId, receipt.servedModel ?? "", ...receipt.output.entries.map(item => item.relative), ...receipt.output.excluded.map(item => item.relative)]; return names.every(text => text === "" || this.guidanceFieldAllowed(text)); } async guidanceProbeStart(by: PeerId, id: string, revision: number, variantId?: string): Promise { const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check); const host = this.guidanceProbeHost(by, state.registration.manifest, request); if (!probeInteger(revision) || variantId !== undefined && !probeSha256(variantId)) throw new PreEffectToolRefusal("guidance probe start selector is invalid; use its current CAS revision and exact G1 id"); const dependency = this.d.guidanceProbes!; // No production runner: refuse before original-child selection, G1 raw read, binding, reservation or timer. if (!dependency.fakePorts) throw new PreEffectToolRefusal("guidance probe runner is unavailable in production T1; use fake-only fixtures, not a live launch"); const key = { projectKey: host.projectKey, id }, original = dependency.store.startSelector(key, revision); if (original && (original.actor !== by || original.sessionGeneration !== host.sessionGeneration || original.nativeSession !== host.nativeSession || original.requestConnectionId !== host.requestConnectionId)) throw new PreEffectToolRefusal("guidance probe original start belongs to another request session; inspect its retained id without replaying it"); const slot = original ? state.registration.manifest.slots.find(item => item.id === original.slotId) : state.registration.manifest.slots.find(item => state.sessions.find(session => session.slotId === item.id)?.state === "planned"); if (!slot) throw new PreEffectToolRefusal("guidance probe has no eligible slot; inspect its retained terminal or held state"); if (original && original.variantId !== (variantId ?? null)) throw new PreEffectToolRefusal("guidance probe original selector differs; inspect its original G1 id without rebinding the start"); const needsVariant = slot.role === "worker" && slot.arm !== "baseline"; if (needsVariant !== (variantId !== undefined)) throw new PreEffectToolRefusal("guidance probe next worker needs its existing G1 id only; use --variant for the next non-baseline worker"); const current = (): ProbeAdmissionRecheck => { const fresh = this.guidanceProbeHost(by, state.registration.manifest, request); if (!this.guidanceProbeSnapshotClear(state.registration)) throw new PreEffectToolRefusal("guidance probe input privacy changed; retain its declaration and use current public inputs"); return { host: fresh, ...(variantId === undefined ? {} : { child: this.guidanceProbeVariantBinding(by, this.guidanceProbeTask(by, state.registration.manifest.task, true), variantId) }) }; }; const prepared = current(); const active = this.guidanceProbeActive.get(id); if (active) { if (active.requestedRevision !== revision || active.variantId !== variantId) throw new PreEffectToolRefusal("another owned probe attempt is still settling; inspect its state before explicitly starting the next stage"); const captured = active.current().host; if (captured.actor !== host.actor || captured.sessionGeneration !== host.sessionGeneration || captured.nativeSession !== host.nativeSession || captured.requestConnectionId !== host.requestConnectionId) throw new PreEffectToolRefusal("guidance probe active start belongs to another request session; inspect its retained id without replaying it"); // Frame preparation has not granted a reservation. A duplicate is only a read of truthful current metadata. if (!active.reservation) return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), true); const replay = dependency.store.reserveSession({ key, expectedRevision: revision, ...prepared, now: this.d.now?.() ?? Date.now() }, current); if (replay.kind !== "existing") throw new Error("guidance probe start is unconfirmed; inspect retained state before any further work"); return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), true); } const entry: GuidanceProbeRuntime = { id, by, requestedRevision: revision, ...(variantId === undefined ? {} : { variantId }), controller: new AbortController(), current, launched: false, launchSettled: false, stopRequested: false, stopSettled: false, stopKnown: false }; this.guidanceProbeActive.set(id, entry); const ports: GuidanceProbeFakePorts = { launch: async (input, effects, signal) => { entry.reservation = input.reservation; this.guidanceProbeWatch(entry); if (signal.aborted) throw new Error("owned probe was aborted before launch"); entry.launched = true; return dependency.fakePorts!.launch(input, effects, signal); }, stop: (input, signal) => dependency.fakePorts!.stop(input, signal), ...(dependency.fakePorts.discardRetained ? { discardRetained: record => dependency.fakePorts!.discardRetained!(record) } : {}), }; let reserved = false, returned = false; const runner = new GuidanceProbeFixtureHost(dependency.store, { ports, revalidate: current, now: () => this.d.now?.() ?? Date.now(), prepareWorkerFrame: dependency.prepareWorkerFrame, prepareEditorFrame: dependency.prepareEditorFrame, onReserved: () => { reserved = true; } }); entry.promise = (async () => { try { const saved = await runner.start({ key, expectedRevision: revision, ...prepared, now: this.d.now?.() ?? Date.now() }, entry.controller.signal); returned = true; if (saved.state === "unknown_held" && entry.launched) { this.guidanceProbeAbort(entry, "observation", true); if (!entry.stopPromise) throw new Error("owned probe stop was not recorded; retain the held lane and explicitly inspect its outcome"); await entry.stopPromise; } request.check(); if (entry.failure) throw entry.failure; return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), saved.already); } catch (error) { this.guidanceProbeAbort(entry, "observation"); if (!reserved && !returned && (error instanceof PreEffectToolRefusal || error instanceof GuidanceProbeError && error.reason !== "storage")) throw error; throw new Error("guidance probe attempt outcome is unconfirmed; inspect its retained id without replaying work"); } finally { entry.launchSettled = true; this.guidanceProbeClearWatch(entry); this.guidanceProbeRetire(entry); } })(); return entry.promise; } async guidanceProbeCancel(by: PeerId, id: string, revision: number): Promise { const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check); if (!probeInteger(revision)) throw new PreEffectToolRefusal("guidance probe cancellation revision is invalid; inspect its current CAS revision"); const current = () => this.guidanceProbeHost(by, state.registration.manifest, request, state.binding), host = current(); try { const saved = this.d.guidanceProbes!.store.cancelIntent({ key: { projectKey: host.projectKey, id }, expectedRevision: revision, host }, current); const entry = this.guidanceProbeActive.get(id); if (entry) { this.guidanceProbeAbort(entry, "observation", true); await this.guidanceProbeDrain([entry]); } request.check(); return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), saved.already); } catch { throw new Error("guidance probe cancellation is unconfirmed; inspect its retained intent and owned drain before retrying"); } } private guidanceProbeRequest(by: PeerId): { check: () => void; generation: number | string; nativeSession: string | null; requestConnectionId: string } { const request = this.guidanceRequest(by, "probe"); if (!this.personOrConductor(by)) throw new PreEffectToolRefusal("guidance probes require the person or current configured conductor; use an admitted operational session"); const session = this.d.guidanceProbes?.session?.(by); if (!session || !probeSessionGeneration(session.generation) || !executionText(session.requestConnectionId, EXECUTION_REFERENCE_LIMITS.id) || session.nativeSession !== null && !executionText(session.nativeSession, EXECUTION_REFERENCE_LIMITS.id)) throw new PreEffectToolRefusal("guidance probe request session is unavailable; reconnect through a current authenticated project connection"); const sessionCurrent = session.current; const current = () => { sessionCurrent(); request(); if (this.guidanceProbeStopping) throw new PreEffectToolRefusal("guidance probe admission is stopping; inspect retained work after the owned drain"); if (this.d.reviewOnly?.(by)) throw new PreEffectToolRefusal("guidance probes are unavailable in a review-only context; use a current public operational session"); if (by !== USER) { try { requireConductor(by, this.d.roles); } catch { throw new PreEffectToolRefusal("guidance probe conductor authority changed; refresh the configured role before retrying"); } if (!this.d.bus.isRostered(by)) throw new PreEffectToolRefusal("guidance probe conductor is not currently rostered; restore current membership before retrying"); } }; current(); return { check: current, generation: session.generation, nativeSession: session.nativeSession, requestConnectionId: session.requestConnectionId }; } private guidanceProbeTask(by: PeerId, selected: { id: number; created: number; flowRevision: number }, admission: boolean): Task { const task = this.guidanceTask(by, { taskId: selected.id, taskCreated: selected.created }, false); if (admission && (task.history.length !== selected.flowRevision || !["in_progress", "changes_requested"].includes(task.state))) throw new PreEffectToolRefusal(`guidance probe admission is stale or task state is ${task.state}; accept current work in in_progress or changes_requested and reload its revision`); return task; } /** Actual probe actor only; the source owner validates/hydrates G1, never an impersonated read or separate SQL parser. */ private guidanceProbeVariantBinding(by: PeerId, task: Task, variantId: string): ProbeChildBinding { if (by !== USER) { try { requireConductor(by, this.d.roles); } catch { throw new PreEffectToolRefusal("guidance probe conductor authority changed; reconnect in a current operational session"); } if (!this.d.bus.isRostered(by)) throw new PreEffectToolRefusal("guidance probe conductor membership changed; restore current roster membership before retrying"); } const current = this.guidanceProbeTask(by, { id: task.id, created: task.created, flowRevision: task.history.length }, true); if (!probeSha256(variantId)) throw new PreEffectToolRefusal("guidance probe variant selector is invalid; choose an existing current G1 content id"); const project = this.guidanceProject(), role = this.guidanceRole(current); const experiment = this.guidanceStorage("read", () => this.d.board.guidanceVariantLocation(project, current.id, current.created, variantId)); const record = experiment === undefined ? undefined : this.guidanceStorage("read", () => this.d.board.guidanceVariants(project, current.id, current.created, experiment)).find(item => item.variant.id === variantId); if (!record || record.withdrawn || record.variant.flowRevision !== current.history.length || record.variant.baseline.roleId !== role.id || record.variant.baseline.layer !== role.layer || record.variant.baseline.sha256 !== role.hash) throw new PreEffectToolRefusal("guidance probe G1 is unavailable, withdrawn or stale; separately admit a current owner/person variant before retrying"); const guidance = renderGuidanceVariantV1(record.variant); if (!this.guidanceProbeRenderedClear(guidance)) throw new PreEffectToolRefusal("guidance probe handoff text is private; use a current public G1 before retrying"); return { variantId, candidateSha256: record.variant.candidate.sha256, guidanceSha256: probeHash(guidance), guidance, task: { id: current.id, created: current.created, flowRevision: current.history.length }, role: { id: role.id, layer: role.layer, baselineSha256: role.hash }, authoring: "uncontrolled", sourceSessionId: null }; } private guidanceRequest(by: PeerId, mode: "guidance" | "probe" = "guidance"): () => void { if (!executionText(by, EXECUTION_REFERENCE_LIMITS.id) || !executionLinkActor(by) || by === HUB || by === "admin") throw new PreEffectToolRefusal("guidance requires a current local task actor; ask the task owner or the person"); const request = this.requestCheck(by, () => this.studyHold()); const peer = by === USER ? undefined : this.d.bus.peers.get(by), generation = peer?.sessionGeneration, session = peer?.nativeSession; const delivery = () => this.d.bus.lastDeliveredTo(by).map(item => item.id).join("\n"), delivered = mode === "guidance" ? delivery() : undefined; const check = () => { request(); if (this.d.privateTurn?.(by) || this.reviewObserverTurn(by)) throw new PreEffectToolRefusal("guidance is unavailable during private or review input; retry in a public owner context"); if (by !== USER && (!peer || this.d.bus.peers.get(by) !== peer || "sessionGeneration" in peer && generation === undefined || peer.sessionGeneration !== generation || peer.nativeSession !== session || mode === "guidance" && delivery() !== delivered)) throw new PreEffectToolRefusal("guidance request session changed or is unavailable; reload the task in the current session before retrying"); }; check(); return check; } private guidanceTask(by: PeerId, selector: Pick, write: boolean): Task { const task = this.guidanceStorage("read", () => this.d.board.get(selector.taskId)); if (!task) throw new PreEffectToolRefusal("guidance task is unavailable; read a current task in this project before retrying"); if (task.created !== selector.taskCreated || !this.lineageVisible(by, task) || this.reviewObserverTurn(by, task.id)) throw new PreEffectToolRefusal("guidance task is unavailable; refresh the current public task and privacy context before retrying"); if (write && (isClosedTaskState(task.state) || by !== USER && (task.owner !== by || task.state === "in_review" || !this.d.roles?.[by]?.includes(ownerRoleOfClass(task.class)) || !this.d.bus.isRostered(by)))) throw new PreEffectToolRefusal("guidance changes require the current task owner outside review, or the person, on an open task; refresh the task before retrying"); return task; } private guidanceProject(): string { const key = this.d.executionLineage?.projectKey; if (!key) throw new PreEffectToolRefusal("guidance project storage is unavailable; inspect hub status before retrying"); return key; } private guidanceRole(task: Task) { let role; try { role = taskRole(task.role, task.class, this.d.catalog ?? loadRoleCatalog(this.d.cwd)); } catch { throw new Error("guidance catalog validation is unavailable; inspect the current task role and catalog before retrying"); } if (!role) throw new PreEffectToolRefusal("guidance requires a current catalog task role; select a task role before proposing a variant"); return role; } private guidancePublic(record: GuidanceStoredRecord | { variant: GuidanceVariantV1 }): boolean { const { evidenceRefs, ...text } = record.variant; // Opaque evidence addresses never become filesystem/producer lookup instructions. return this.publicMetadataText(JSON.stringify(text)) && evidenceRefs.every(reference => this.lineageMetadata(JSON.stringify(reference))); } /** Unknown storage/readback failures never certify a pre-effect refusal, even when SQLite rolled back. */ private guidanceStorage(operation: "read" | "write", action: () => T): T { try { return action(); } catch { throw new Error(`guidance storage ${operation} failed; inspect the retained task experiment and its outcome before retrying`); } } private guidanceFence(by: PeerId, task: Task): GuidanceWriteFence { return { by, at: this.d.now?.() ?? Date.now(), taskId: task.id, taskCreated: task.created, flowRevision: task.history.length, owner: task.owner, state: task.state, roleId: task.role }; } private guidanceFieldAllowed(text: string): boolean { try { return this.nameable(text) && !looksSecret(text) && this.lineageMetadata(JSON.stringify(text)); } catch { return false; } } private guidancePublicField(text: string): string { return this.guidanceFieldAllowed(text) ? text : "withheld"; } private guidanceExperimentFor(projectKey: string, task: Task, selector: Pick & { experimentId?: string }): string | undefined { return selector.experimentId ?? (selector.id ? this.guidanceStorage("read", () => this.d.board.guidanceVariantLocation(projectKey, task.id, task.created, selector.id!)) : undefined); } private guidanceCurrent(task: Task): GuidanceCurrent { return { taskId: task.id, taskCreated: task.created, flowRevision: task.history.length }; } private guidanceReadFence(by: PeerId, selector: Pick, task: Task, check: () => void): Task { check(); const current = this.guidanceTask(by, selector, false); if (JSON.stringify([current.created, current.history.length, current.owner, current.reviewer, current.state, current.role]) !== JSON.stringify([task.created, task.history.length, task.owner, task.reviewer, task.state, task.role])) throw new Error("guidance read binding changed"); return current; } private guidanceEvidence(by: PeerId, task: Task, records: readonly GuidanceStoredRecord[]): GuidancePublicRecord["evidence"][] { const ports = this.lineagePorts(by), projectKey = this.guidanceProject(); return records.map(record => record.variant.evidenceRefs.map(reference => { let known = false; if (ports && reference.tool === "ahub" && reference.projectKey === projectKey) { const snapshot = executionOwnerSnapshot(ports, { root: reference, task: { id: task.id, created: task.created } }); known = snapshot.source.health === "ready" && snapshot.source.nodes.some(node => executionReferenceKey(node.ref) === executionReferenceKey(reference)); } return { key: executionReferenceDigest(reference), status: known ? "declared" as const : "unavailable" as const }; })); } private guidanceProjection(by: PeerId, task: Task, record: GuidanceStoredRecord, evidence: GuidancePublicRecord["evidence"]): GuidancePublicRecord { return { ...guidanceVariantMetadata(record.variant), experimentId: this.guidancePublicField(record.variant.experimentId), status: record.withdrawn ? "withdrawn" : "declared", applicable: this.guidanceApplicable(by, task, record), rationale: { problemHypothesis: this.guidancePublicField(record.variant.rationale.problemHypothesis), expectedObservableDifference: this.guidancePublicField(record.variant.rationale.expectedObservableDifference) }, evidence }; } private guidanceReceipt(saved: { record: GuidanceStoredRecord; already: boolean }): GuidanceWriteReceipt { const value = saved.record.variant; return { id: value.id, taskId: value.taskId, experimentId: this.guidancePublicField(value.experimentId), status: saved.record.withdrawn ? "withdrawn" : "declared", already: saved.already }; } /** Immutable declarations only. Neither creation nor readback changes effective role guidance. */ async guidanceVariantCreate(by: PeerId, input: unknown): Promise { const check = this.guidanceRequest(by); let variant: Readonly; try { variant = parseGuidanceVariantV1(input); } catch { throw new PreEffectToolRefusal("invalid guidance variant; use the closed V1 record and current task identity before retrying"); } return this.studyWrite(async () => { const context = () => { check(); const task = this.guidanceTask(by, variant, true), projectKey = this.guidanceProject(), role = this.guidanceRole(task); if (!this.guidancePublic({ variant })) throw new PreEffectToolRefusal("guidance text or evidence metadata is private; use public task-local metadata before retrying"); const experiment = this.guidanceStorage("read", () => this.d.board.guidanceExperiment(projectKey, task.id, task.created, variant.experimentId)); const records = this.guidanceStorage("read", () => this.d.board.guidanceVariants(projectKey, task.id, task.created, variant.experimentId)); try { validateGuidanceVariantV1(variant, { projectKey, taskId: task.id, taskCreated: task.created, flowRevision: task.history.length, experimentId: variant.experimentId, actor: by, baseline: experiment?.baseline ?? variant.baseline, currentBaseline: roleIdentity(role), variantIds: records.map(item => item.variant.id) }); } catch (error) { if (error instanceof GuidanceVariantError) throw new PreEffectToolRefusal("guidance variant or frozen baseline is invalid or changed; reload the task and use a new experiment for a changed baseline"); throw new Error("guidance validation is unavailable; inspect the task experiment before retrying"); } return { task, key: JSON.stringify([task.created, task.history.length, task.owner, task.state, task.role, roleIdentity(role), experiment?.baseline ?? variant.baseline]) }; }; const before = context(); if (this.screenOn() && (await this.screenCall(JSON.stringify(variant))).label !== "clear") throw new PreEffectToolRefusal("guidance privacy screening did not clear the proposal; retry with public metadata when local screening is available"); const current = context(); if (before.key !== current.key) throw new PreEffectToolRefusal("guidance context changed during admission; reload the task and experiment before retrying"); check(); const saved = this.guidanceStorage("write", () => this.d.board.recordGuidanceVariant(variant, this.guidanceFence(by, current.task))); return this.guidanceReceipt(saved); }); } async guidanceVariantWithdraw(by: PeerId, input: unknown): Promise { const check = this.guidanceRequest(by); let selector: GuidanceSelector | GuidanceIdSelector; try { try { selector = parseGuidanceSelector(input, true); } catch { selector = parseGuidanceIdQuery(input, true); } } catch { throw new PreEffectToolRefusal("invalid guidance withdrawal; name a current task epoch, flow revision and existing variant selector"); } return this.studyWrite(async () => { check(); const task = this.guidanceTask(by, selector, true), projectKey = this.guidanceProject(); if (task.history.length !== selector.flowRevision) throw new PreEffectToolRefusal("guidance task revision changed; reload the task before withdrawing"); const experimentId = this.guidanceExperimentFor(projectKey, task, selector); const record = experimentId === undefined ? undefined : this.guidanceStorage("read", () => this.d.board.guidanceVariants(projectKey, task.id, task.created, experimentId)).find(item => item.variant.id === selector.id); if (!record) throw new PreEffectToolRefusal("guidance variant is unavailable; refresh the task experiment before withdrawing"); check(); const saved = this.guidanceStorage("write", () => this.d.board.withdrawGuidanceVariant(projectKey, experimentId!, selector.id!, this.guidanceFence(by, task))); return this.guidanceReceipt(saved); }); } private guidanceApplicable(by: PeerId, task: Task, record: GuidanceStoredRecord): boolean { try { if (record.withdrawn || isClosedTaskState(task.state) || by !== USER && task.owner !== by || by !== USER && task.state === "in_review") return false; const value = record.variant, role = this.guidanceRole(task); return value.flowRevision === task.history.length && value.baseline.roleId === role.id && value.baseline.layer === role.layer && value.baseline.sha256 === role.hash && (by === USER || this.d.roles?.[by]?.includes(ownerRoleOfClass(task.class)) === true); } catch { return false; } } /** Historical data can be visible without being applicable. No model, external resolver or delivery runs here. */ guidanceVariantRead(by: PeerId, input: unknown): GuidanceReadResult { try { const check = this.guidanceRequest(by), selector = parseGuidanceSelector(input); check(); const task = this.guidanceTask(by, selector, false), projectKey = this.guidanceProject(); const experimentId = this.guidanceExperimentFor(projectKey, task, selector); if (experimentId === undefined) return { state: "unavailable" }; const records = this.d.board.guidanceVariants(projectKey, task.id, task.created, experimentId); const selected = selector.id ? records.filter(item => item.variant.id === selector.id) : records; if (!selected.length) return { state: "unavailable" }; const evidence = this.guidanceEvidence(by, task, selected), current = this.guidanceReadFence(by, selector, task, check); if (this.guidanceExperimentFor(projectKey, current, selector) !== experimentId) return { state: "unavailable" }; const fresh = this.d.board.guidanceVariants(projectKey, current.id, current.created, experimentId); const currentSelected = selector.id ? fresh.filter(item => item.variant.id === selector.id) : fresh; if (JSON.stringify(selected) !== JSON.stringify(currentSelected)) return { state: "unavailable" }; const result: GuidanceReadResult = { state: "available", records: currentSelected.map((record, index) => this.guidanceProjection(by, current, record, evidence[index]!)) }; check(); return result; } catch { return { state: "unavailable" }; } } /** Public T3 detail: private selection, screened editable fields, no raw snapshot readback. */ guidanceVariantDiff(by: PeerId, input: unknown): GuidanceDiffResult { try { const check = this.guidanceRequest(by), selector = parseGuidanceIdQuery(input); const task = this.guidanceTask(by, selector, false), projectKey = this.guidanceProject(), experimentId = this.guidanceExperimentFor(projectKey, task, selector); if (experimentId === undefined) return { state: "unavailable" }; const record = this.d.board.guidanceVariants(projectKey, task.id, task.created, experimentId).find(item => item.variant.id === selector.id); if (!record) return { state: "unavailable" }; const evidence = this.guidanceEvidence(by, task, [record]), current = this.guidanceReadFence(by, selector, task, check); if (this.guidanceExperimentFor(projectKey, current, selector) !== experimentId) return { state: "unavailable" }; const fresh = this.d.board.guidanceVariants(projectKey, current.id, current.created, experimentId).find(item => item.variant.id === selector.id); if (!fresh || JSON.stringify(fresh) !== JSON.stringify(record)) return { state: "unavailable" }; const result = parseGuidanceDiffResult({ state: "available", current: this.guidanceCurrent(current), record: this.guidanceProjection(by, current, fresh, evidence[0]!), sections: guidanceVariantSectionDiff(fresh.variant, text => this.guidanceFieldAllowed(text)), protectedSections: guidanceProtectedSectionNames() }); check(); return result; } catch { return { state: "unavailable" }; } } /** Fixed indexed keyset pages; cursor contains only an existing public variant id and authenticated context. */ guidanceVariantList(by: PeerId, input: unknown): GuidancePageResult { try { const check = this.guidanceRequest(by), query = parseGuidanceListQuery(input), task = this.guidanceTask(by, query, false), projectKey = this.guidanceProject(); const key = this.d.executionLineage?.cursorKey; if (!key) return { state: "unavailable" }; const context = { ...this.guidanceCurrent(task), projectKey, actor: by }; const after = query.cursor ? guidancePageAfter(key, context, query.cursor) : ""; if (after && !this.d.board.guidanceVariantLocation(projectKey, task.id, task.created, after)) return { state: "unavailable" }; const page = this.d.board.guidanceVariantPage(projectKey, task.id, task.created, after), selected = page.slice(0, GUIDANCE_PAGE_MAX_RECORDS); const evidence = this.guidanceEvidence(by, task, selected), current = this.guidanceReadFence(by, query, task, check); const fresh = this.d.board.guidanceVariantPage(projectKey, current.id, current.created, after); if (JSON.stringify(page) !== JSON.stringify(fresh)) return { state: "unavailable" }; const records: GuidancePublicRecord[] = []; for (const [index, record] of selected.entries()) { const candidate = this.guidanceProjection(by, current, record, evidence[index]!); const sized = { state: "available", current: this.guidanceCurrent(current), records: [...records, candidate], truncated: true, cursor: guidancePageCursor(key, context, candidate.id) }; if (Buffer.byteLength(JSON.stringify(sized)) > GUIDANCE_REPLY_MAX_BYTES) break; records.push(candidate); } const truncated = records.length < page.length; if (truncated && !records.length) return { state: "unavailable" }; const result = parseGuidancePageResult({ state: "available", current: this.guidanceCurrent(current), records, truncated, ...(truncated ? { cursor: guidancePageCursor(key, context, records.at(-1)!.id) } : {}) }); check(); return result; } catch { return { state: "unavailable" }; } } /** Future probe admission must capture its own current runtime/turn fence; this boolean is no handoff receipt. */ guidanceVariantApplicable(by: PeerId, input: unknown): boolean { try { const selected = parseGuidanceIdQuery(input), read = this.guidanceVariantDiff(by, selected); return read.state === "available" && read.record.applicable; } catch { /* Existing explicit experiment selectors keep the T2 metadata-only path. */ } try { if (parseGuidanceSelector(input).id === undefined) return false; } catch { return false; } const read = this.guidanceVariantRead(by, input); return read.state === "available" && read.records.length === 1 && read.records[0]!.applicable; } /** A declaration carries no resolver, runner attestation, review approval or model-execution authority. */ async linkExecutionReference(by: PeerId, input: unknown): Promise<{ id: string; taskId: number; reference: ExecutionReferenceV1; strength: "declared"; already: boolean }> { if (!executionLinkActor(by) || by === HUB || by === "admin") throw new PreEffectToolRefusal("execution links require a current local task actor; ask the person or the task owner to record the declaration"); const check = this.requestCheck(by, () => this.studyHold() ? "execution links are held; inspect ahub status and retry after recovery or shutdown" : undefined); let proposed: ExecutionLinkInput; try { proposed = parseExecutionLinkInput(input); } catch { throw new PreEffectToolRefusal("execution link fields are invalid; refresh the task identity and use a bounded execution reference"); } return this.studyWrite(async () => { const context = () => { check(); const ports = this.lineagePorts(by); if (!ports) throw new PreEffectToolRefusal("execution reference storage is unavailable; inspect ahub status before retrying"); let task: Task; try { task = this.studyParent(proposed.taskId); } catch { throw new PreEffectToolRefusal("execution link task is unavailable in this project; refresh ahub task show before retrying"); } const role = by === task.owner ? ownerRoleOfClass(task.class) : by === task.reviewer ? "reviewer" : undefined; if (by !== USER && (!role || !this.d.roles?.[by]?.includes(role) || !this.d.bus.isRostered(by))) throw new PreEffectToolRefusal("execution links require the task's current owner or reviewer role; ask that peer or the person to record the declaration"); if (!this.lineageVisible(by, task)) throw new PreEffectToolRefusal("execution links require a public task outside private or review input; refresh the current task policy before retrying"); if (task.created !== proposed.taskCreated || task.history.length !== proposed.flowRevision) throw new PreEffectToolRefusal("execution link task identity or revision changed; refresh ahub task show before retrying"); const from = proposed.from ?? taskExecutionReference(ports.projectKey, task.id, task.created); const scope = { id: task.id, created: task.created }; const origin = executionOwnerSnapshot(ports, { root: from, task: scope }); if (origin.source.health !== "ready" || !origin.source.nodes.some(node => executionReferenceKey(node.ref) === executionReferenceKey(from))) throw new PreEffectToolRefusal("execution link origin is not recorded in this task; select an existing public task-scoped reference"); if (proposed.reference.tool === "ahub") { const target = executionOwnerSnapshot(ports, { root: proposed.reference, task: scope }); if (target.source.health !== "ready" || !target.source.nodes.some(node => executionReferenceKey(node.ref) === executionReferenceKey(proposed.reference))) throw new PreEffectToolRefusal("local execution target is not recorded in this task; select a verified task-scoped reference"); } const metadata = JSON.stringify([from, proposed.reference]); if (!this.publicMetadataText(metadata)) throw new PreEffectToolRefusal("execution reference metadata is private or sensitive; use public metadata before retrying"); return { ports, task, from, metadata, key: JSON.stringify([task.created, task.history.length, task.owner, task.reviewer, task.state, origin.source.revision]) }; }; const before = context(); if (this.screenOn()) { const result = await this.screenCall(before.metadata); if (result.label !== "clear") throw new PreEffectToolRefusal("execution reference privacy screening did not clear the metadata; retry with public metadata when screening is available"); } check(); const current = context(); if (current.key !== before.key) throw new PreEffectToolRefusal("execution link authority or source changed during admission; refresh the task and source references before retrying"); const saved = this.d.board.recordExecutionReference(current.ports.projectKey, { ...proposed, from: current.from }, { by, at: this.d.now?.() ?? Date.now() }); return { id: saved.record.id, taskId: saved.record.taskId, reference: saved.record.reference, strength: "declared", already: saved.already }; }); } /** T1 records declared provenance only; no locator resolution or #901 judgment is manufactured. */ async evidenceRecord(by: PeerId, input: unknown): Promise { try { requireLocalTaskPeer(by); } catch { throw new PreEffectToolRefusal("remote peers cannot record local evidence; ask the current local research task owner to record it"); } const requestCheck = this.requestCheck(by, () => this.studyHold()); let proposed: ReturnType; try { proposed = parseEvidenceRecord(input); } catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid evidence record; check the bounded evidence fields before retrying"); } return this.studyWrite(async () => { const context = () => { requestCheck(); let task: Task; try { task = this.studyParent(proposed.taskId); } catch { throw new PreEffectToolRefusal("evidence task is unavailable or outside this project; refresh ahub task show and select an active research task in this project"); } const personWithdrawal = by === USER && proposed.status === "withdrawn"; if (task.profile === "research" && (task.owner === by || personWithdrawal) && isClosedTaskState(task.state)) throw new PreEffectToolRefusal("a closed research task's evidence records are final; open a follow-up research task to correct evidence and create a new manifest binding"); if (task.profile !== "research" || task.state !== "in_progress" || !task.owner || task.owner !== by && !personWithdrawal) throw new PreEffectToolRefusal("evidence recording requires the current in-progress research task owner; accept an assigned research task before recording evidence"); if (this.d.privateTurn?.(by) || this.isPii(task) || task.signals.includes("pii") || task.signals.includes("pii_path")) throw new PreEffectToolRefusal("private evidence recording is unavailable in T1; use a public research task outside a private turn"); let identity; try { identity = taskClaimIdentity(task, Number(proposed.claimId.split(":").at(-1))); } catch { throw new PreEffectToolRefusal("evidence claim is unavailable; refresh hub_task_show or ahub task show --json and use a current claim binding"); } if (identity.claimId !== proposed.claimId || identity.claimRevision !== proposed.claimRevision) throw new PreEffectToolRefusal("evidence claim revision changed; refresh hub_task_show or ahub task show --json and record the current claim binding"); const source = this.studySource(proposed.sourceId); if (!source || source.sha256 !== proposed.rawSha256) throw new PreEffectToolRefusal("evidence source is unknown or its raw hash changed; use ahub source list and read the registered snapshot before retrying"); if (source.private) throw new PreEffectToolRefusal("private evidence sources are unavailable in T1; select a registered public source"); return { task, key: JSON.stringify([task.created, task.history.length, task.owner, identity, source]) }; }; const before = context(); const link = parseEvidenceLink({ ...proposed, id: proposed.id ?? evidenceLinkId(proposed, by), recordedBy: by }); const canonical = evidenceLinkCanonical(link); const requirePublicMetadata = () => { let nameable = false; try { nameable = this.publicMetadataText(canonical) === true; } catch { /* unknown privacy is refused */ } if (!nameable) throw new PreEffectToolRefusal("evidence metadata is private or sensitive; remove sensitive metadata before recording a public link"); }; requirePublicMetadata(); const requireRevision = () => { const latest = this.d.board.evidenceLink(this.d.project, link.id); const next = (latest?.revision ?? 0) + 1; if (latest && (latest.taskId !== link.taskId || latest.claimId !== link.claimId)) throw new PreEffectToolRefusal("evidence id belongs to another claim; use a new evidence id"); const known = this.d.board.evidenceLink(this.d.project, link.id, link.revision); if (known && evidenceLinkCanonical(known) !== canonical) throw new PreEffectToolRefusal(`evidence revision already records different content; use next revision ${next} or a new evidence id`); if (!known && link.revision !== next) throw new PreEffectToolRefusal(`evidence revision is out of sequence; expected next revision ${next}; use that revision or replay an unchanged recorded revision`); return !!known; }; const replay = requireRevision(); if (!replay && this.screenOn()) { const screen = await this.screenCall(canonical); requestCheck(); if (screen.label !== "clear") throw new PreEffectToolRefusal("evidence privacy screening did not clear the metadata; use public evidence metadata and retry when the screen is available"); } requestCheck(); const current = context(); if (current.key !== before.key) throw new PreEffectToolRefusal("evidence task, claim or source changed during admission; refresh hub_task_show or ahub task show --json and registered source metadata before retrying"); requirePublicMetadata(); requireRevision(); const saved = this.d.board.recordEvidenceLink(this.d.project, link, { taskFlowRevision: current.task.history.length, taskCreated: current.task.created, owner: current.task.owner!, ...(by === USER ? { personWithdrawal: true as const } : {}) }); return { id: saved.id, revision: saved.revision, taskId: saved.taskId }; }); } /** * #901: the person's verdict on one declared claim of a document plan, with the model label they say produced it. Person only (an agent's word on its own claim is no verdict, and task * approval never supplies one). The claim is named by its 1-based slot in the task's current plan; its text is not stored, sent or echoed, so a PII task records the same counters and * its history entry stays a stub. The entry is not a transition and moves nothing; a later verdict for the same slot supersedes the earlier one (the scorecard reads the last). */ recordClaimVerdict(by: PeerId, id: unknown, input: unknown): Task { return this.writeClaimVerdict(by, id, input); } /** Refresh host bindings without changing the person's selected citation mappings or keeping a second manifest store. */ private currentSynthesisManifest(manifest: SynthesisManifestV1, current: SynthesisCurrent): SynthesisManifestV1 | undefined { try { if (!current.deliverable?.sha256 || !current.bibliography?.sha256 || !current.claims) return; const currentClaims = current.claims; const ordered = [...manifest.claims.flatMap(ref => currentClaims.filter(claim => claim.claimId === ref.claimId)), ...currentClaims.filter(claim => !manifest.claims.some(ref => ref.claimId === claim.claimId))]; const claims = ordered.map(claim => { if (!claim.inventory) throw new Error("incomplete inventory"); const inventory = inventoryBinding(claim.inventory.links, claim.inventory.complete, claim.contradictionHistory); if (!inventory) throw new Error("incomplete inventory"); const links = claim.inventory.links.map(row => "link" in row ? row.link : row); const evidence = (manifest.claims.find(row => row.claimId === claim.claimId)?.evidence ?? []).map(ref => { const latest = links.find(link => link.id === ref.id); if (!latest) throw new Error("selected link unavailable"); return { ...ref, revision: latest.revision }; }); return { claimId: claim.claimId, claimRevision: claim.claimRevision, inventory, evidence }; }); return parseSynthesisManifest({ schemaVersion: 1, taskId: current.taskId, taskCreated: current.taskCreated, deliverable: { id: current.deliverable.id, sha256: current.deliverable.sha256 }, bibliography: { id: current.bibliography.id, sha256: current.bibliography.sha256 }, claims }); } catch { return; } } /** Same console claim authority/store; the descriptor is transient and the write stays inside the final snapshot fence. */ async recordSynthesisClaimVerdict(by: PeerId, id: unknown, input: unknown, manifest: unknown): Promise { if (by !== USER) throw new PreEffectToolRefusal("only the console user may record a claim verdict"); const task = this.need(id), claim = parseClaimVerdict(input, task.plan?.claims?.length ?? 0), boardRevision = this.d.board.statusRevision(); if (!claim.synthesis) throw new PreEffectToolRefusal("a synthesis verdict requires a manifest file and resolved or qualified disposition through ahub task claim"); const result = await this.synthesisInspect(by, { taskId: task.id, manifest }, (supplied, current, report, valid) => { const refreshed = this.currentSynthesisManifest(supplied, current); if (!refreshed) throw new PreEffectToolRefusal("current synthesis manifest unavailable; refresh complete inventory, selected evidence and registered artifacts before recording a disposition"); const hash = synthesisManifestHash(refreshed); if (!valid()) throw new PreEffectToolRefusal("synthesis context changed before the claim verdict write; refresh current public inputs and retry"); if (claim.synthesis!.manifestSha256 !== hash || synthesisManifestHash(supplied) !== hash) throw new PreEffectToolRefusal(`synthesis manifest changed; current manifestSha256 ${hash}; refresh the manifest file and explicitly record the disposition again`); if (!("scope" in report) || report.binding !== "current" || report.claimCoverage !== "complete" || report.deliverable !== "unchanged" || report.bibliography !== "unchanged" || report.claims.some(row => row.claim !== "current" || row.inventory !== "current" || row.evidenceLink !== "present" || row.locator !== "resolved" || row.provenance !== "resolved")) throw new PreEffectToolRefusal("current synthesis provenance is unavailable or stale; resolve current source/locator and artifact statuses before recording a disposition"); return this.writeClaimVerdict(by, task.id, claim, { boardRevision, taskCreated: task.created, taskFlowRevision: task.history.length, claimRevision: taskClaimIdentity(task, claim.slot).claimRevision }); }); if (!("history" in result)) { if ("cause" in result && result.cause === "source_input_limit") throw new PreEffectToolRefusal("synthesis source input exceeds the bounded check; split the task into smaller research tasks before recording a disposition"); throw new PreEffectToolRefusal("current synthesis is private, unavailable or changed; refresh public inputs before recording a disposition"); } return result; } private writeClaimVerdict(by: PeerId, id: unknown, input: unknown, verifiedSynthesis?: { boardRevision: number; taskCreated: number; taskFlowRevision: number; claimRevision: string }): Task { if (by !== USER) throw new Error("only the console user may record a claim verdict"); if (this.d.cancellationHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) throw new Error("recovery or shutdown is holding task writes"); const task = this.need(id); const claims = task.plan?.claims?.length ?? 0; if (!claims) throw new Error(`task #${task.id} declares no plan claims: add them to its plan first`); const claim = parseClaimVerdict(input, claims); if (claim.synthesis && !verifiedSynthesis) throw new PreEffectToolRefusal("a synthesis disposition needs current manifest validation; use ahub task claim with --manifest and --disposition"); if (claim.synthesis && (this.d.profile !== "research" || task.profile !== "research")) throw new Error("synthesis dispositions require a research task and profile"); // Bound to the claim list it evaluated: a hash of the plan's claims (never their text), so a later replacement or reorder of the list leaves this verdict naming no claim of the new list. const identity = taskClaimIdentity(task, claim.slot); if (verifiedSynthesis) return this.d.board.recordSynthesisClaimVerdict(task.id, { ...claim, list: identity.claimRevision }, verifiedSynthesis); return this.d.board.update(task.id, USER, "claim verdict", {}, undefined, { claim: { ...claim, list: identity.claimRevision } }); // no note: nothing a person typed beyond the closed fields is kept } async cancel(id: unknown, by: PeerId, input: { reason: string; supersededBy?: string; expectedFlowRevision?: number }): Promise { requireLocalTaskPeer(by); if (typeof input.reason !== "string" || !input.reason.trim() || Buffer.byteLength(input.reason) > 4000 || input.supersededBy !== undefined && (typeof input.supersededBy !== "string" || !input.supersededBy.trim() || Buffer.byteLength(input.supersededBy) > 1000)) throw new PreEffectToolRefusal("cancellation needs a bounded reason and supersession reference"); const validate = () => { if (this.d.cancellationHeld?.() || this.d.bus.isRecoveryHeld) throw new PreEffectToolRefusal("recovery or shutdown is holding cancellation"); const task = this.need(id, false, true, true); this.checkFlowRevision(task, input.expectedFlowRevision, true); if (isClosedTaskState(task.state)) throw new PreEffectToolRefusal(`task #${task.id} is already ${task.state}`); if (by !== USER && this.d.privateTurn?.(by) && !this.isPii(task)) throw new PreEffectToolRefusal("cancellation on ordinary work is unavailable during a private turn"); if (by !== USER && this.conductorHandoffCancel(by, task)) { /* #1175: the receiving conductor's own authority over a handed-off task nobody accepted; the board write below records it as the actor */ } else if (by !== USER) { // The conductor without the planner role is refused with its own rule (#1175): the planner sentence below would point it at a role it does not hold. if (this.configuredManualConductor(by) && !this.d.roles?.[by]?.includes("planner")) throw new PreEffectToolRefusal("the conductor may cancel only a task another project handed off that nobody has accepted (no owner, branch, commit, PR, check, done or verdict) while the conductor is on the roster; for any other task the person runs `ahub task cancel --reason `"); this.planningAuthority(by, task); const proposer = task.history.find(h => h.event === "proposed" || h.event === "backlogged")?.by; // #812 AC5: back in proposed or backlog with no execution evidence (the `hub_backlog_return_untouched` test: no branch, commit, PR, local check, done, verdict or reopen), an accepted-then-declined task is cancellable; any such evidence keeps today's refusal. if (proposer !== by || !["backlog", "proposed"].includes(task.state) || taskHasWorkEvidence(task)) throw new PreEffectToolRefusal(`planner may cancel only its own historically unaccepted backlog or proposed work${proposer === HUB ? `; task #${task.id} was created by the hub, so only the person can cancel it: ahub task cancel ${task.id} --reason (a recurring-finding card that matched unrelated findings is a false recurrence)` : ""}`); } return task; }; const before = validate(), revision = before.history.length; const reasonText = [input.reason, input.supersededBy].filter(Boolean).join("\n"); const withheld = looksSecret(reasonText) || this.aboutPrivatePath("", reasonText, before) || await this.withholds("note", reasonText, before); const task = validate(); if (task.history.length !== revision) throw new PreEffectToolRefusal("task flow revision changed"); const cancelled = { reason: input.reason.trim(), ...(input.supersededBy ? { supersededBy: input.supersededBy.trim() } : {}), flowRevision: revision + 1, ...(withheld ? { withheld: true as const } : {}) }; const capacity = this.capacityBefore(task); this.ciWatchers.cancel(task.id); this.heldReviews.delete(task.id); const next = this.d.board.update(task.id, by, "cancelled", { state: "cancelled", reserved: null, cancelled }, cancelled.reason, { ...(withheld ? { withheld: true as const } : {}) }, revision); this.releaseHubWorktree(task, task.owner); this.writePlannerNotices(next, capacity); this.releaseNotice(`task #${task.id}: cancellation cohort cleanup unavailable`, () => this.cohorts.leave(task.id)); this.offered.delete(task.id); this.releaseNotice(`task #${task.id}: cancellation stall cleanup unavailable`, () => this.d.board.clearStall(task.id)); for (const peer of new Set([task.owner, task.reviewer])) if (peer && peer !== USER) this.releaseNotice(`task #${task.id}: cancellation notice unavailable`, () => this.d.bus.publish(newEnvelope(HUB, sanitize(`Task #${task.id} cancelled. Stop working on it. No native turn or working tree was changed.`), { to: [peer], kind: "task", priority: "important", refs: { task: String(task.id), taskCancelled: cancelled.flowRevision }, ...(this.isPii(next) ? { private: true } : {}) }))); await this.releaseHeld(task.owner); // its owner's slot is free (#655) this.releaseNotice(`task #${task.id}: cancellation dependent advice unavailable`, () => { for (const dependent of this.d.board.list()) if (!isClosedTaskState(dependent.state) && !dependent.owner && dependent.deps?.includes(task.id)) this.releaseNotice(`task #${dependent.id}: cancellation stall advice unavailable`, () => this.reportStall(dependent, { kind: "cancelled-dependency", dependency: task.id, code: "cancelled" })); }); return next; } /** * #1175: the receiving project's configured conductor may cancel a task another project handed it, while nobody has accepted it and it has no execution evidence (the same bar as the * planner's own-work rule, `taskHasStarted` and `taskHasWorkEvidence`). It is re-asked inside both validations of `cancel`, so authority that ended during the privacy screen writes * nothing. The origin hears the cancel through the existing follow-back, which reads the history entry and carries no text. */ private conductorHandoffCancel(by: PeerId, task: Task): boolean { return this.configuredManualConductor(by) && this.d.bus.isRostered(by) && this.d.board.handoffOrigin(task.id) !== undefined && ["proposed", "backlog"].includes(task.state) && !taskHasStarted(task) && !taskHasWorkEvidence(task) && !this.isPii(task); } /** A slot freed for `peer` (cancel, untouched return): its held ready tasks are offered in priority order, and the cap stops the offers (#655). */ private async releaseHeld(peer: PeerId | null | undefined): Promise { if (!peer) return; try { for (const t of this.d.board.list("proposed").filter(t => !t.owner && t.reserved === peer && this.isHeld(t) && !this.waitsFor(t).length).sort(this.readyOrder)) await this.offerReady(t, "owner slot freed"); } catch (e) { this.releaseNotice(`task ${peer}: could not offer held ready work: ${e instanceof Error ? e.message : String(e)}`); } } async releaseReady(): Promise { const now = this.d.now?.() ?? Date.now(); const haveQueueOrigins = this.queuePressureKnown !== false && this.d.board.queuePressureStallPage(0, 1).afterTask > 0; for (const t of [...this.d.board.list("proposed")].sort(this.readyOrder)) { if (t.owner) { this.d.board.clearStall(t.id); continue; } if (t.needsPerson) { this.d.board.clearStall(t.id); continue; } // #1176: waiting on the person is the intent, not a stall: no owner is wanted, so none is reported missing const cancelledDependency = t.deps?.find(id => this.d.board.get(id)?.state === "cancelled"); if (cancelledDependency) { this.reportStall(t, { kind: "cancelled-dependency", dependency: cancelledDependency, code: "cancelled" }); continue; } const last = t.history.findLast(entry => !QUIET_EVENTS.has(entry.event))?.event, planned = this.plannerPullRecord(t)?.pull === true; if (this.personUnassigned(t) || this.offered.has(t.id) || this.waitsFor(t).length) continue; if (haveQueueOrigins) { const origin = this.d.board.queuePressureStallPage(t.id - 1, 1).rows.find(row => row.task === t.id); if (origin && this.ordinaryQueueProposal(origin, t)) { this.scheduleQueuePressureRecheck(); continue; } } if (plannedStartPending(t, now)) continue; const admission = planned ? this.plannerAssignment(t, true) : assign(t, this.states(), this.d.routing(), { exclude: this.excluded(t), ...this.weights(t.class, t) }); if (!admission.owner) { // A diagnostic legacy pass is not evidence that an automatic proposal was attempted. this.reportStall(t, this.ownerStallCause(t, admission, this.hasPersonReservation(t))); continue; } this.d.board.clearStall(t.id); if ((!t.deps?.length && !t.history.some(h => h.event === "backlog pulled")) || (!planned && last !== "blocked" && last !== "ready" && last !== "reserved" && !this.isHeld(t))) continue; // ponytail: a reserved owner (#207) that attaches after another peer that can take the task is passed over here like // an offline one; hold reserved tasks for a grace period if restarts show that up. await this.offerReady(t, "nothing left to wait for"); } } /** Callers hold a list read before an await: re-read, or a task the other caller offered meanwhile is offered twice. */ private async offerReady(stale: Task, why: string, current?: () => void): Promise { current?.(); let offering = false, undelivered: AssignmentUndeliveredError | undefined, slot: PeerId | undefined; try { const t = this.d.board.get(stale.id); if (!t || t.state !== "proposed" || t.owner || this.personUnassigned(t) || this.offered.has(t.id)) return; if (t.needsPerson) return; // #1176: a person-run leg is never offered to an agent, whatever made it ready if (plannedStartPending(t, this.d.now?.() ?? Date.now())) return; const planned = this.plannerPullRecord(t)?.pull === true; const selected = planned ? this.plannerAssignment(t, true).owner : undefined; if (planned && !selected) return; const held = planned ? undefined : this.reservedHold(t); // #655: the cap holds before the ready move is offered if (held) { this.holdReady(t, why, held); return; } // The check and the slot are one synchronous step: assignOwner can yield before it writes the owner, and a second offer // for the same reserved owner must see this one as taking the last slot. if (!planned && t.reserved) { slot = t.reserved; this.readyInFlight.set(t.id, slot); } this.offered.add(t.id); offering = true; const ready = t.history.at(-1)?.event === "ready" ? t : this.d.board.update(t.id, HUB, "ready", {}, why); this.releaseNotice(`task ${this.publicTitle(ready)} is ready: what it waited for is approved`); await this.assignOwner(ready, HUB, { current, ...(planned ? { candidates: [selected!], namedOwner: selected!, planner: true } : {}) }); } catch (e) { // A saved move whose delivery failed is not "could not be assigned" (#297); the console notice was printed // where the error was thrown. The offer stays consumed by the error's own evidence, without the readback. if (e instanceof PreEffectToolRefusal && e.message === "planned start is in the future") return; if (e instanceof AssignmentUndeliveredError) undelivered = e; else this.releaseNotice(`task ${this.publicTitle(stale)}: could not be assigned: ${e instanceof Error ? e.message : String(e)}`); } finally { if (slot) this.readyInFlight.delete(stale.id); if (offering && !undelivered) { try { if (!this.d.board.get(stale.id)?.owner) this.offered.delete(stale.id); } catch (e) { this.offered.delete(stale.id); this.releaseNotice(`task ${this.publicTitle(stale)}: could not verify assignment: ${e instanceof Error ? e.message : String(e)}`); } } } } private mine(task: Task, by: PeerId, role: "owner" | "reviewer", preEffect = false): void { requireLocalTaskPeer(by); if (by !== USER && task[role] !== by) throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${task.id}: only its ${role} (${task[role] ?? "none"}) or the console user can do that`); } /** * #723: link the issue a task names the moment it is proposed or accepted, in advise and enforce, so the lifecycle never * waits for a groom. It is a local parse with no GitHub read, and it never refuses or fails the write it follows. */ private linkOnWrite(task: Task): Task { try { return (this.d.sdlc?.config().mode ?? "off") === "off" ? task : this.linkIssue(task); } catch { return task; } } /** * #723: a title that qualifies another repository (`agent-mem#13`, `owner/repo#N`) while `refs.repo` is absent cannot link * (the identity needs the repository), so the proposer is told to set it. Advice only; a PII task gets none. */ refsRepoHint(task: Task): string | undefined { if (this.isPii(task) || task.refs.repo || task.sdlc?.issue || (this.d.sdlc?.config().mode ?? "off") === "off") return undefined; const names = qualifiedTitleRepos(task.title); return names.length ? `task #${task.id}: the title names ${names.join(", ")}; set refs.repo to that repository (owner/name) so its issue links and the lifecycle shows it` : undefined; } /** * #798 D1: a declared path (refs, plan paths, the file part of a section anchor) inside a git submodule of this project: snapshots, facts, overlap and undo do not observe * inside a submodule. A notice, never a refusal: the task stays valid. Advice only, so a PII task gets none, a path whose name matches a PII pattern is not named, and a * task bound to another repository is judged against that one's layout, which this project's `.gitmodules` does not describe (its scope is not the project's). */ submoduleNotice(task: Task): string | undefined { if (this.isPii(task)) return undefined; let submodules: string[]; try { submodules = this.d.submodules?.() ?? []; } catch { return undefined; } if (!submodules.length) return undefined; if (this.repositories.scope(task.refs) !== this.repositories.project) return undefined; const declared = [...(task.refs.paths ?? []), ...(task.plan?.paths ?? []), ...(task.plan?.sections ?? []).map(anchor => anchor.split("#")[0]!).filter(Boolean)]; const inside = new Set(); for (const path of declared) { let local: string; try { local = this.projectPath(path); } catch { continue; } if (local === ".." || local.startsWith("../") || isAbsolute(local)) continue; const hit = submodules.find(sub => local === sub || local.startsWith(`${sub}/`)); if (hit) inside.add(hit); } const named = [...inside].filter(this.nameable).sort(); if (!named.length) return inside.size ? "inside a submodule (path withheld, it matches a PII pattern): facts, overlap and undo do not observe it" : undefined; return named.map(path => `inside submodule ${path}: facts, overlap and undo do not observe it`).join("\n"); } /** #694: write the one issue the task itself names (the plan-review source) into its lifecycle receipt, once; never relinks. */ private linkIssue(task: Task): Task { if (this.isPii(task) || task.sdlc?.issue) return task; let identity: { repo: string; issue: number } | undefined; try { identity = this.planIssueIdentity(task); } catch { return task; } const next = identity && linkedReceipt(task.sdlc, identity, this.d.sdlc?.config() ?? sdlcConfig(undefined)); return next ? this.d.board.update(task.id, HUB, "lifecycle linked", { sdlc: next }, `issue #${identity!.issue}`) : task; } /** * #694: the PR the hub can verify for a done, without writing it: the one open PR whose head is the done's full commit * (or, with no commit, its branch). The read's basis travels with it, so a task whose commit or branch changed while the * read was awaited never receives a PR found for another head. The done persists it only after its gates admit it, so a * refused done stays effect-free (#254). */ private async identityLink(task: Task, refs?: TaskRefs): Promise { if (this.isPii(task) || task.sdlc?.pr) return undefined; const repository = task.sdlc?.repo ?? task.refs.repo ?? this.d.repository; const commit = refs?.commit ?? task.refs.commit, branch = refs?.branch ?? task.refs.branch; if (!repository || !commit && !branch) return undefined; const pr = await openPrFor(repository, commit ? { commit } : { branch }, this.d.sdlc?.gh ?? sdlcGh); return pr ? { repo: repository, pr, basis: { commit, branch } } : undefined; } /** * The task as the done's gates see it: the issue the current task names (re-resolved now, so a changed title or refs * counts) and the staged PR only while the done's effective commit and branch are still the ones it was read for. */ private withLink(task: Task, link: IdentityLink | undefined, refs?: TaskRefs): Task { if (this.isPii(task) || (this.d.sdlc?.config().mode ?? "off") === "off" && link?.managedRevision === undefined) return task; if (link?.managedRevision !== undefined && task.history.length !== link.managedRevision) throw new PreEffectToolRefusal("managed handoff changed; inspect the task and GitHub before retrying"); const config = this.d.sdlc?.config() ?? sdlcConfig(undefined); let issue: { repo: string; issue: number } | undefined; if ((this.d.sdlc?.config().mode ?? "off") !== "off" && !task.sdlc?.issue) { try { issue = this.planIssueIdentity(task); } catch { issue = undefined; } } const commit = refs?.commit ?? task.refs.commit, branch = refs?.branch ?? task.refs.branch; const repository = task.sdlc?.repo ?? task.refs.repo ?? this.d.repository ?? (link?.managedRevision !== undefined ? link.repo : undefined); const pr = link && !task.sdlc?.pr && repository?.toLowerCase() === link.repo.toLowerCase() && link.basis.commit === commit && (link.managedRevision !== undefined ? link.basis.branch === branch : commit !== undefined || link.basis.branch === branch) ? link : undefined; let next = task.sdlc; if (issue) next = linkedReceipt(next, issue, config) ?? next; if (pr) next = linkedReceipt(next, { repo: pr.repo, pr: pr.pr }, config) ?? next; return next === task.sdlc ? task : { ...task, sdlc: next }; } private planIssueIdentity(task: Task): { repo: string; issue: number } | undefined { const source = task.external ?? task.sdlc; if (source?.repo && source.issue) return { repo: source.repo, issue: source.issue }; const repository = task.refs.repo ?? this.d.repository ?? ""; let issues: number[]; try { issues = specRefs(task, repository); } catch { throw new PreEffectToolRefusal("plan review issue identity unavailable"); } // #723: a title that qualifies the sibling repository `refs.repo` names (`agent-mem#13`) is a local parse, never a read. // A sibling shorthand next to a bare #N is two identities, refused below, never the bare one alone. issues = [...new Set([...issues, ...siblingTitleRefs(task.title, task.refs.repo)])]; if (issues.length > 1) throw new PreEffectToolRefusal("plan review needs one explicit issue identity"); return issues[0] ? { repo: repository, issue: issues[0] } : undefined; } async groomingDigest(by: PeerId): Promise> { this.planningAuthority(by); this.backfillIssueLinks(by); // #723: first, bounded, before the slow reads const included = (task: Task) => !isClosedTaskState(task.state) || task.state === "cancelled" && task.history.some(entry => !!entry.supersededBy); const snapshot = this.d.board.list().filter(included), issues = new Map(), attempted = new Set(); const deadline = performance.now() + 4_000; let reads = 0, incomplete = false; // ponytail: at most eight metadata reads within four seconds; add paginated revision-bound readback for larger boards. for (const listed of snapshot) { this.planningAuthority(by); const task = this.d.board.get(listed.id); if (!task || this.isPii(task) || isClosedTaskState(task.state)) continue; let source: { repo: string; issue: number } | undefined; try { source = this.planIssueIdentity(task); } catch { continue; } if (!source) continue; const key = `${source.repo.toLowerCase()}#${source.issue}`; if (attempted.has(key)) continue; attempted.add(key); if (reads >= 8 || performance.now() >= deadline) { incomplete = true; break; } reads++; const run = this.d.sdlc?.gh ?? sdlcGh; const issue = await readPlanIssueMetadata(source.repo, source.issue, (args, timeout, cwd, cap) => run(args, Math.max(1, Math.min(timeout ?? 10_000, deadline - performance.now())), cwd, cap)); if (issue) issues.set(key, issue); } this.planningAuthority(by); const all = this.d.board.list(), current = all.filter(included), visible = current.filter(task => !this.isPii(task)); // Include only bounded public dependency context, so approved intermediate phases do not disappear from reachability. const indexed = new Map(all.map(task => [task.id, task])), dependencies = new Map(); const pending = visible.slice(0, 500).map(task => task.id).reverse(), visited = new Set(); while (pending.length && visited.size < 500) { const id = pending.pop()!; if (visited.has(id)) continue; visited.add(id); const task = indexed.get(id); if (!task || this.isPii(task)) continue; dependencies.set(id, task.deps ?? []); pending.push(...task.deps ?? []); } const dependencyTruncated = pending.some(id => !visited.has(id)); const peers = [...new Set([...Object.keys(this.states()), ...current.flatMap(task => task.owner ? [task.owner] : [])])]; const reviewedIssues = new Map(visible.flatMap(task => task.sdlc?.planReview?.issue ? [[task.id, task.sdlc.planReview.issue] as const] : [])); const acceptedIssues = new Map(visible.flatMap(task => task.sdlc?.acceptance ? [[task.id, task.sdlc.acceptance] as const] : [])); const currentNoWrites = new Set(this.stalled().filter(stall => stall.cause.kind === "no-writes").map(stall => stall.task)); const blockers: { task: number; code: string }[] = this.d.board.stalls().filter(stall => stall.cause.kind !== "no-writes" || currentNoWrites.has(stall.task)).map(stall => ({ task: stall.task, code: stall.cause.code })); const health = this.health(), states = this.states(), routing = this.d.routing(), hostBlocks = this.d.plannerBlocks?.() ?? {}; for (const task of visible.filter(task => !isClosedTaskState(task.state)).slice(0, 500)) { const owner = task.owner ?? task.reserved; if (owner) for (const code of peerEntry(hostBlocks, owner) ?? []) blockers.push({ task: task.id, code }); const result = assign(task.state === "backlog" ? { ...task, state: "proposed" } : task, states, routing, { ...health, waitsFor: this.waitsFor(task), ...(owner ? { candidates: [owner], namedOwner: owner } : {}) }); if (!result.owner) for (const refusal of result.refusals ?? []) if (refusal.role === "owner") blockers.push({ task: task.id, code: refusal.code === "instance" || refusal.code === "family" ? "policy" : refusal.code }); if (this.waitsFor(task).length) blockers.push({ task: task.id, code: "dependency" }); } const digest = plannerGrooming(visible, { dependencies, dependencyTruncated, repository: this.d.repository ?? `path:${realPath(this.d.cwd)}`, now: this.d.now?.() ?? Date.now(), limits: Object.fromEntries(peers.map(peer => [peer, this.wipLimit(peer)])), wip: Object.fromEntries(peers.map(peer => [peer, this.wip(peer)])), states, issues, reviewedIssues, acceptedIssues, blockers }); return { ...digest, truncated: digest.truncated || incomplete, ...(current.some(task => this.isPii(task)) ? { privateTasks: "withheld" } : {}) }; } /** * #694, #723: backfill lifecycle issue links with their own bounds, run first and apart from the slow metadata reads and * the digest, so a groom that later times out has still linked. Each call links up to 32 open tasks that still lack one * within a one-second budget, so later tasks are reached on later calls. A local parse; a failure skips that task only. */ private backfillCursor = 0; private backfillIssueLinks(by: PeerId): number { if ((this.d.sdlc?.config().mode ?? "off") === "off") return 0; // ponytail: 32 links and 1 s per call; raise both only with a measured groom time on a 400-task board. const deadline = performance.now() + 1_000; let linked = 0, i = 0; const list = this.d.board.list(), n = list.length; // The scan resumes where the last call stopped, so rows that never link cannot hold later ones back. for (; i < n; i++) { if (linked >= 32 || performance.now() >= deadline) break; const task = list[(this.backfillCursor + i) % n]!; if (isClosedTaskState(task.state) || task.sdlc?.issue || this.isPii(task)) continue; this.planningAuthority(by); try { if (this.linkIssue(task) !== task) linked++; } catch { /* one task never stops the rest */ } } this.backfillCursor = n ? (this.backfillCursor + i) % n : 0; return linked; } /** * #481 S7: the SDLC metrics from board history, read-only. Private tasks are counted as withheld and read for nothing else; PR * readbacks are not made here (the cost report owns them), so merge time and same-head reruns read `unknown` unless given. * Detection never calls a model and the report writes nothing. */ sdlcMetrics(by: PeerId, since?: unknown, merged?: { mergedAt?: Record; ciReruns?: Record }): MetricsReport { this.planningAuthority(by); if (by !== USER && this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("metrics unavailable during private work"); let cutoff: number | undefined; if (since !== undefined && since !== null && since !== "") { cutoff = typeof since === "number" ? since : /^\d+$/.test(String(since)) ? Number(since) : Date.parse(String(since)); if (!Number.isFinite(cutoff) || cutoff < 0) throw new PreEffectToolRefusal("since must be a time (YYYY-MM-DD or an ISO timestamp) or milliseconds"); } const rows = this.d.board.list(); const tasks: MetricTask[] = rows.map(task => ({ id: task.id, private: this.isPii(task), history: task.history.map(entry => ({ at: entry.at, event: entry.event, ...(["check run passed", "check run failed"].includes(entry.event) && entry.requestHead ? { requestHead: entry.requestHead } : {}), ...(entry.event === "done" && (entry.requestHead ?? entry.reviewCost?.head ?? entry.specReport?.head) ? { requestHead: entry.requestHead ?? entry.reviewCost?.head ?? entry.specReport?.head } : {}), ...(entry.reviewFindings?.head ? { verdictHead: entry.reviewFindings.head } : {}), ...(entry.evidenceOnly ? { evidenceOnly: true as const } : {}) })) })); const visibleIds = new Set(rows.filter(task => !this.isPii(task)).map(task => task.id)); const byKind: Record = {}; for (const stall of this.stalled()) if (visibleIds.has(stall.task)) byKind[stall.cause.kind] = (byKind[stall.cause.kind] ?? 0) + 1; const stalls = { open: Object.values(byKind).reduce((sum, n) => sum + n, 0), byKind, doneWithoutWrites: rows.filter(task => visibleIds.has(task.id) && task.history.findLast(entry => entry.event === "done")?.noWrites).length }; // #481 S7: the merge-time readback the guarded merge recorded on each merged task's receipt (host-written, never a tool input), and the two series that are not made of tasks. const mergedAt: Record = {}, ciReruns: Record = {}, ciRuns: Record = {}, reviews: Record = {}, firstPass: Record = {}, fullGateRuns: Record = {}, successfulGateRuns: Record = {}, failedGateRuns: Record = {}, cancelledGateRuns: Record = {}, otherGateRuns: Record = {}, macosShardRuns: Record = {}; for (const task of rows) { const guarded = task.sdlc?.merge; const merge = guarded?.state === "merged" ? guarded : task.sdlc?.mergeReadback; if (!visibleIds.has(task.id) || merge?.state !== "merged") continue; const cost = cleanMergeCost(merge.cost); const at = cost?.mergedAt ?? (merge === guarded && Number.isSafeInteger(merge.at) ? merge.at : null); if (at !== null) mergedAt[task.id] = at; if (cost) { ciReruns[task.id] = cost.ciReruns; ciRuns[task.id] = cost.ciRuns; reviews[task.id] = cost.reviews; firstPass[task.id] = cost.firstPass ?? null; fullGateRuns[task.id] = cost.fullGateRuns ?? null; successfulGateRuns[task.id] = cost.successfulGateRuns ?? null; failedGateRuns[task.id] = cost.failedGateRuns ?? null; cancelledGateRuns[task.id] = cost.cancelledGateRuns ?? null; otherGateRuns[task.id] = cost.otherGateRuns ?? null; macosShardRuns[task.id] = cost.macosShardRuns ?? null; } } return { ...sdlcMetrics(tasks, { ...(cutoff !== undefined ? { since: cutoff } : {}), ...(this.d.sdlc?.config().bands ? { bands: this.d.sdlc.config().bands } : {}), stalls, mergedAt, ciReruns, ciRuns, reviews, firstPass, fullGateRuns, successfulGateRuns, failedGateRuns, cancelledGateRuns, otherGateRuns, macosShardRuns, external: this.externalSeries(), ...(merged ?? {}) }), ...(this.securityScanCounts() ? { securityScan: this.securityScanCounts() } : {}) }; } /** Latest configured scan source counts; no repository or alert text is projected. */ securityScanCounts(): Record | undefined { const scan = this.d.sdlc?.config().securityScan, repo = scan?.repo ?? this.d.repository; if (!scan || typeof repo !== "string" || !this.nameable(repo)) return undefined; return this.d.board.latestSecurityScanCounts(repo, scan.sources.join(",")); } /** #481 S7: one point per shipped release (1 for a hotfix, 0 otherwise; a release with no recorded train is skipped, never a 0) and one per recorded security scan whose total is known. */ private externalSeries(): Partial> { const rows = this.d.board.list(), privateRelease = (id: number) => rows.some(task => task.release === id && this.isPii(task)); const hotfix = this.d.board.releases().filter(release => release.state === "shipped" && release.shippedAt !== null && release.train?.history.length && !privateRelease(release.id)) .sort((a, b) => a.shippedAt! - b.shippedAt! || a.id - b.id).map(release => ({ value: release.train!.hotfix ? 1 : 0, task: release.id })); const config = this.d.sdlc?.config().securityScan, repo = config?.repo ?? this.d.repository; // A band needs `window` baseline points plus the newest one, and the episode walk looks back up to EPISODE_LOOKBACK more, so the series loads that many known // totals (unknown ones are filtered in SQL, never counted against the limit). The board caps one read at 1000 rows. const need = (this.d.sdlc?.config().bands?.security_open_alerts?.window ?? DEFAULT_BAND.window) + EPISODE_LOOKBACK + 2; const scans = config && typeof repo === "string" ? this.d.board.securityScans(repo, config.sources.join(","), need, true).map(scan => ({ value: scan.total!, task: scan.id })) : []; return { hotfix_rate: hotfix, security_open_alerts: scans }; } /** * #481 S7: the scheduled security-scan baseline. Reads the open-alert counts GitHub already holds (`security-baseline.ts`), records one row per interval and then runs the * same band path as every other metric, so a breach is one deduplicated card. Held like every host writer; a private repository identity, a mode off, no `[security_scan]` * table and a scan that is not yet due all do nothing. A source GitHub will not read (not enabled, not permitted) records an unknown total, never zero. Returns the scan id. */ async runSecurityScan(now = Date.now()): Promise { const config = this.d.sdlc?.config(), scan = config?.securityScan; if (!config || config.mode === "off" || !scan) return undefined; const repo = scan.repo ?? this.d.repository; if (typeof repo !== "string" || !this.nameable(repo)) return undefined; const held = () => !!this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || !!this.d.bus.storageError; if (held()) return undefined; const sources = scan.sources.join(","), last = this.d.board.securityScans(repo, sources, 1).at(-1); if (last && now - last.at < scan.everyH * 3_600_000) return undefined; const read = await readSecurityScan(repo, scan.sources, this.d.sdlc?.gh ?? sdlcGh); const after = this.d.sdlc?.config(); // The read awaited: the lifecycle, the schedule or a hold may have changed meanwhile, so nothing is written from a stale decision. if (!read || held() || !after || after.mode === "off" || JSON.stringify(after.securityScan) !== JSON.stringify(scan)) return undefined; const id = this.d.board.recordSecurityScan({ repo, sources, counts: read.counts as Record, total: read.total }); this.proposeFromBands(); return id; } /** * #481 S7: act on the band tiers, deterministically and once per breach episode. An episode is a run of non-ok values for one metric * (`BandResult.episode`, derived from history), so a sustained shift is one episode however many tasks finish inside it. `log` is one * hub notice, `diagnose` one read-only `triage` backlog task and `propose` one `plan` backlog card naming the metric and its evidence. * A metric with an open band card (a backlog or open task whose detail carries its key) writes nothing more, so a value that grows * from diagnose to propose inside one episode does not add a second card. Held while the hub is stopping, recovering or has a * storage error, like every host writer. The text is fixed words, numbers and task ids, never task text, and no GitHub issue is * created. Returns the task ids created. */ /** * Whether `proposeFromBands` would run now, and a signature of what it would read. The daemon timer records a board revision only for a * pass that ran, and re-runs when the signature changes (a reload that enables bands or edits them on an idle board). */ bandsState(): { ready: boolean; signature: string } { const config = this.d.sdlc?.config(); const configured = !!config && config.mode !== "off" && !!config.bands && Object.keys(config.bands).length > 0; // The release and scan series do not move the task board's revision, so what they last held is part of the signature: a shipped release or a new scan row is a reason to run again. const external = configured ? this.externalSeries() : {}; return { ready: configured && !this.d.sweepHeld?.() && !this.d.bus.isRecoveryHeld && !this.d.bus.storageError, signature: configured ? JSON.stringify([config!.mode, config!.bands, config!.securityScan ?? null, external.hotfix_rate?.length ?? 0, external.security_open_alerts?.at(-1)?.task ?? 0]) : "" }; } proposeFromBands(by: PeerId = HUB): number[] { requireLocalTaskPeer(by); const config = this.d.sdlc?.config(); if (!config || config.mode === "off" || !config.bands || !Object.keys(config.bands).length) return []; if (this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) return []; if (by !== HUB && by !== USER) this.planningAuthority(by); const report = this.sdlcMetrics(by === HUB ? USER : by); if (report.bands === "off") return []; const rows = this.d.board.list(); const bandRows = rows.filter(row => row.history[0]?.by === HUB && row.detail?.startsWith("Band breach key: ")); const keyOf = (row: Task) => row.detail!.split("\n")[0]!.slice("Band breach key: ".length); const seen = new Set(bandRows.map(keyOf)); // A card counts as open while its task is not closed: the planner has not yet decided on it. const open = new Set(bandRows.filter(row => !isClosedTaskState(row.state)).map(row => keyOf(row).split(":")[0]!)); const created: number[] = []; // Fixed words and a number: a release or a security scan is named by its id, a task by `task #id`. const subjectText = (band: BandResult, id: number) => band.subject === "release" ? `release #${id}` : band.subject === "scan" ? `security scan #${id}` : `task #${id}`; for (const band of report.bands as BandResult[]) { if (band.tier === "ok" || band.lastTask === null || band.episode === null) continue; const key = `${band.metric}:#${band.episode}`; if (band.tier === "log") { const marker = `${key}:log`; if (!open.has(band.metric) && this.d.board.recordBandNotice(marker)) this.releaseNotice(`sdlc band: ${band.metric} is ${band.reason}; last value ${band.last} on ${subjectText(band, band.lastTask)}`); continue; } if (seen.has(`${key}:propose`) || seen.has(`${key}:diagnose`) || open.has(band.metric)) continue; const tier = band.tier === "propose" ? "propose" : "diagnose"; const full = `${key}:${tier}`; const evidence = `metric ${band.metric}; newest value ${band.last} on ${subjectText(band, band.lastTask)}; episode began at ${subjectText(band, band.episode)}; baseline mean ${band.mean}, deviation ${band.sd} over ${band.baseline} ${band.subject === "release" ? "releases" : band.subject === "scan" ? "scans" : "tasks"}; ${band.reason}`; const diagnose = tier === "diagnose"; const title = diagnose ? `Diagnose SDLC metric ${band.metric}: read-only triage` : `Review SDLC metric ${band.metric}: control band breach`; const detail = `Band breach key: ${full}\n${evidence}\n${diagnose ? `Read-only triage for the planner: inspect the recent ${band.subject === "release" ? "releases" : band.subject === "scan" ? "security scans" : "task histories"} behind this metric and report what changed. Do not edit files, branches or the board.` : "Backlog card for the planner: decide whether this breach needs a process change. It names the metric and its evidence; it opens no GitHub issue."}`; const draft = { title, detail, refs: {} }; const signals = this.signalsFor(draft); if (this.isPii({ signals }) || !this.candidateTextAllowed(`${title}\n${detail}`)) continue; const proposal = this.d.board.propose(HUB, { ...draft, class: diagnose ? "triage" : "plan", backlog: true, signals }); this.incomingBacklog.add(proposal.id); seen.add(full); open.add(band.metric); created.push(proposal.id); } for (const id of created) this.releaseNotice(`task #${id}: SDLC control band breach proposed in the backlog`); return created; } /** The open task each schedule made: a hub-written card (first history entry by the hub) whose detail starts with the schedule marker and that is not closed. */ openScheduled(): Map { const open = new Map(); for (const row of this.d.board.list()) { const key = row.history[0]?.by === HUB && !isClosedTaskState(row.state) ? scheduleKeyOf(row.detail) : undefined; if (key !== undefined && !open.has(key)) open.set(key, row.id); } return open; } /** Whether a scheduled run may write now: the same holds as every host writer (stopping or recovering, held by the daemon, a storage error). */ schedulesHeld(): boolean { return !!this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || !!this.d.bus.storageError; } private schedulesRunning = false; /** 1 while a schedules pass is running (its PII screen and triage are awaited), so a recovery commit waits for it like it waits for `checksPending` and `autoPullsPending`: a run mid-admission would write after the commit's digest. */ schedulesPending = (): number => (this.schedulesRunning ? 1 : 0); /** * One due schedule's run: the hold, the open-task rule and the proposal, shared by the timer and `ahub schedule run`, so a manual run can never do what a due * one may not. `propose` asks the fence again right before its board write, so a run admitted and then overtaken by a hold writes nothing and counts as a skip. */ private async runSchedule(store: ScheduleStore, entry: ScheduleEntry, now: number, extraHold: () => boolean, manual = false): Promise { const hold = () => this.schedulesHeld() || extraHold() ? "the hub is held" : undefined; // A skipped tick is counted for the timer only: a person's refused run is not a missed period, so it never feeds the coalescing count. const skip = () => { if (!manual) store.skipped(entry.id); }; if (hold()) { skip(); return { id: entry.id, outcome: "held" }; } const open = this.openScheduled().get(entry.id); if (open !== undefined) { skip(); return { id: entry.id, outcome: "waiting", task: open }; } // The PII screen and triage are awaited inside `propose`, and a hold can begin during them (shutdown, recovery, a storage error). `propose` asks this fence // again right before its board write, so a run that was admitted and then overtaken by a hold writes nothing and counts as a skip, like one held at the start. // The same fence also reads the schedule's pause generation (#335): a person who paused or resumed it after this run was admitted has changed what should happen, // so the run writes nothing. A timer run that finds it paused or resumed meanwhile is dropped (the next pass decides); a person's own run never races its own command. const admitted = store.epoch(entry.id); let overtaken = false, changed = false; const fence = () => { const reason = hold(); if (reason) overtaken = true; if (!reason && !manual && store.epoch(entry.id) !== admitted) { changed = true; return "the schedule was paused or resumed"; } return reason; }; try { const task = await this.propose(HUB, { title: entry.title, detail: scheduledDetail(entry), class: entry.class, backlog: entry.queue === "backlog", ...(entry.owner ? { owner: entry.owner } : {}) }, undefined, undefined, fence); store.ran(entry.id, now, task.id); return { id: entry.id, outcome: "ran", task: task.id }; } catch (error) { if (changed) return { id: entry.id, outcome: "changed" }; if (overtaken) { try { skip(); } catch { /* the store closed with the hub */ } return { id: entry.id, outcome: "held" }; } store.failed(entry.id, sanitize((error as Error).message)); return { id: entry.id, outcome: "failed" }; } } /** * #512a: one pass over the machine-local schedules. A schedule is due once `every` has passed since its period began (first sight, then its last run). * A due schedule proposes at most one task per pass, through `propose` like any proposal (the PII screen, triage, routing and notices all apply), and none * while the task its previous run made is still open. While the hub is held the whole pass skips and every due schedule counts the skip, so a long hold * ends in one run per schedule, never a burst. A run restarts the period at `now`: nothing a restart or a hold missed is replayed. Returns what each due schedule did. */ async proposeFromSchedules(store: ScheduleStore, entries: readonly ScheduleEntry[], now: number, extraHold: () => boolean = () => false): Promise { if (this.schedulesRunning) return []; this.schedulesRunning = true; const out: ScheduleRunResult[] = []; try { store.prune(entries.map(entry => entry.id)); for (const entry of entries) { const row = store.ensure(entry.id, now); if (row.paused) continue; // #335: a person's pause is neither a run nor a skipped tick if (now < scheduleNext(entry, row.anchor)) continue; out.push(await this.runSchedule(store, entry, now, extraHold)); } } finally { this.schedulesRunning = false; } return out; } /** * #335: `ahub schedule run `. The person runs one configured schedule now, whatever its period says. It takes the same pass guard as the timer (so it never * overlaps one), the same hold, open-task and `propose` path (`runSchedule`), and restarts that schedule's period on success like a due run. A paused schedule * runs too: a pause stops the timer, not the person. Only the person may. */ async runScheduleNow(by: PeerId, store: ScheduleStore, entries: readonly ScheduleEntry[], id: unknown, now: number, extraHold: () => boolean = () => false): Promise { if (!this.personOrConductor(by)) throw new PreEffectToolRefusal("schedule run is a console command"); const entry = typeof id === "string" ? entries.find(candidate => candidate.id === id) : undefined; if (!entry) throw new PreEffectToolRefusal(`no schedule ${typeof id === "string" ? JSON.stringify(id.slice(0, 64)) : "named"}; ahub schedule list shows the configured ones`); if (this.schedulesRunning) throw new PreEffectToolRefusal("a schedules pass is running; try again in a moment"); this.schedulesRunning = true; try { store.ensure(entry.id, now); // #933: the board-write fence asks the hold again after the PII screen, so a conductor whose role or connection ended meanwhile writes nothing. const result = await this.runSchedule(store, entry, now, () => extraHold() || !this.personOrConductor(by), true); const reason = result.outcome === "failed" ? store.get(entry.id)?.last_error ?? undefined : undefined; return reason ? { ...result, reason } : result; } finally { this.schedulesRunning = false; } } /** #335: pause or resume one configured schedule. Only the person may; resuming starts a fresh period, so a pause is never replayed as a run. */ setSchedulePaused(by: PeerId, store: ScheduleStore, entries: readonly ScheduleEntry[], id: unknown, paused: boolean, now: number): void { if (!this.personOrConductor(by)) throw new PreEffectToolRefusal(`schedule ${paused ? "pause" : "resume"} is a console command`); const entry = typeof id === "string" ? entries.find(candidate => candidate.id === id) : undefined; if (!entry) throw new PreEffectToolRefusal(`no schedule ${typeof id === "string" ? JSON.stringify(id.slice(0, 64)) : "named"}; ahub schedule list shows the configured ones`); store.setPaused(entry.id, paused, now); } /** * #336 (#512c): one pass over the machine-local folder triggers, on the schedules timer. Each trigger's folder is read once (never watched). The first poll of a trigger * records what is already there and proposes nothing, so adding a trigger to a full inbox does not flood the board; after that a file the trigger has not recorded (by * real path and content hash) is registered as a source through `register` and proposes ONE task through `propose` as the hub, which names the source id and never the * file's name or path. A rename or a touch keeps the hash and proposes nothing. While the hub is held nothing is read or recorded, so the files wait for the next poll. * A file is recorded only after its task exists, so a failure or a hold between the two leaves it to be tried again (a crash in that window can repeat one task; it * never loses a file). At most MAX_NEW_PER_POLL files per trigger per pass. */ async runFolderTriggers(store: FolderStorePort, entries: readonly FolderEntry[], scan: (entry: FolderEntry) => FolderScan, register: (file: ScannedFile) => { id: string; private: boolean }, now: number, extraHold: () => boolean = () => false): Promise { if (this.schedulesRunning) return []; this.schedulesRunning = true; const out: FolderRunResult[] = []; try { store.prune(entries.map(entry => entry.id)); for (const entry of entries) out.push(await this.runFolderTrigger(store, entry, scan, register, now, extraHold)); } finally { this.schedulesRunning = false; } return out; } private async runFolderTrigger(store: FolderStorePort, entry: FolderEntry, scanOf: (entry: FolderEntry) => FolderScan, register: (file: ScannedFile) => { id: string; private: boolean }, now: number, extraHold: () => boolean): Promise { const hold = () => this.schedulesHeld() || extraHold() ? "the hub is held" : undefined; if (hold()) return { id: entry.id, outcome: "held", tasks: [], files: 0 }; const scan = scanOf(entry); // A refused folder never starts the trigger: when it becomes readable, what is in it then is the baseline, not news. if (scan.refused) { store.polled(entry.id, now, scan.refused); return { id: entry.id, outcome: "refused", tasks: [], files: 0, reason: scan.refused }; } // The baseline is every file already in the folder when the trigger starts. A folder too big to hash in one poll (the scan's budget, `truncated`) is baselined over // several polls: each records what it read and proposes nothing, and the poll that reaches the end of the folder completes it. Only then is a file news. if (!store.baselined(entry.id)) { store.begin(entry.id, now); for (const file of scan.files) if (!file.seen) store.record(entry.id, file, null, now); if (!scan.truncated) store.markBaselined(entry.id, now); else store.polled(entry.id, now); return { id: entry.id, outcome: "baseline", tasks: [], files: scan.files.length }; } // A file the trigger already knows by content (a rename, a touch, a copy) proposes nothing, but its new path, size and mtime are recorded, so the next scan finds it with // `known` instead of hashing it again: otherwise such files would spend the hash budget on every poll and starve a genuinely new one behind them. for (const file of scan.files) if (!file.seen && !store.isNew(entry.id, file.sha256)) store.observe(entry.id, file, now); // `isNew` is asked again for each file below, not only here: two files with the same new bytes can arrive before one poll, and the first one's record must suppress the second. const fresh = scan.files.filter(file => !file.seen && store.isNew(entry.id, file.sha256)); const tasks: number[] = []; let error: string | undefined; for (const file of fresh) { if (tasks.length >= MAX_NEW_PER_POLL || hold()) break; if (!store.isNew(entry.id, file.sha256)) { store.observe(entry.id, file, now); continue; } // a duplicate found inside the loop: recorded, never a second task let overtaken = false; const fence = () => { const reason = hold(); if (reason) overtaken = true; return reason; }; try { const source = register(file); const task = await this.propose(HUB, { title: entry.title, detail: folderDetail(entry, source.id), class: entry.class, backlog: entry.queue === "backlog", ...(entry.owner ? { owner: entry.owner } : {}) }, undefined, undefined, fence); store.record(entry.id, file, task.id, now); tasks.push(task.id); } catch (caught) { if (overtaken) break; error = sanitize((caught as Error).message); break; // the next poll tries this file again; later files wait behind it so order is kept } } store.polled(entry.id, now, error); return { id: entry.id, outcome: error ? "failed" : tasks.length ? "ran" : "none", tasks, files: fresh.length, ...(scan.truncated ? { more: true as const } : {}), ...(error ? { reason: error } : {}) }; } /** S10 read-only planner report; S7 owns rolling bands and automatic board proposals. */ async costReport(by: PeerId, repository?: unknown, scopePrs?: readonly number[]): Promise> { const authority = () => { this.planningAuthority(by); if (by !== USER && this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("cost report unavailable during private work"); }; authority(); const repo = repository ?? this.d.repository; if (typeof repo !== "string" || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo) || repo.startsWith("-") || !this.nameable(repo)) throw new PreEffectToolRefusal("cost report requires a public owner/repository identity"); const deadline = performance.now() + 20_000; const bounded = (args: string[], timeout?: number, cwd?: string, cap?: number) => performance.now() < deadline ? (this.d.sdlc?.gh ?? sdlcGh)(args, Math.max(1, Math.min(timeout ?? 10_000, deadline - performance.now())), cwd, cap) : Promise.resolve({ code: 1, stdout: "" }); const requested = scopePrs === undefined ? undefined : new Set(scopePrs); const linked = () => this.d.board.list().filter(task => task.sdlc?.repo?.toLowerCase() === repo.toLowerCase() && Number.isSafeInteger(task.sdlc.pr) && task.sdlc.pr! > 0 && (!requested || requested.has(task.sdlc.pr!))); const ids = [...new Set(linked().filter(task => !this.isPii(task)).map(task => task.sdlc!.pr!))].sort((a, b) => a - b); const observations: import("./cost-governance.ts").CostPr[] = []; let incomplete = ids.length > 16; for (const pr of ids.slice(0, 16)) { authority(); if (linked().some(task => task.sdlc?.pr === pr && this.isPii(task))) continue; if (performance.now() >= deadline) { incomplete = true; break; } const evidence = await readPrCostHistory(repo, pr, (args, timeout, cwd, cap) => { authority(); const fresh = linked().filter(task => task.sdlc?.pr === pr); if (!fresh.length || fresh.some(task => this.isPii(task))) return Promise.resolve({ code: 1, stdout: "" }); return bounded(args, timeout, cwd, cap); }); if (evidence) observations.push(evidence); else incomplete = true; } authority(); const current = linked(); const visiblePrs = new Set(current.filter(task => !this.isPii(task)).map(task => task.sdlc!.pr!)); for (const task of current) if (this.isPii(task)) visiblePrs.delete(task.sdlc!.pr!); if (JSON.stringify([...visiblePrs].sort((a, b) => a - b)) !== JSON.stringify(ids)) incomplete = true; const report = costMetrics(current.map(task => ({ repo, pr: task.sdlc!.pr!, private: this.isPii(task), history: task.history })), observations.filter(pr => visiblePrs.has(pr.pr))); const scoped = current.filter(task => visiblePrs.has(task.sdlc!.pr!) && !this.isPii(task)); const scopedIds = new Set(scoped.map(task => task.id)); const stalls = { noWrites: this.stalled().filter(stall => stall.cause.kind === "no-writes" && scopedIds.has(stall.task)).length, doneWithoutWrites: scoped.filter(task => task.history.findLast(entry => entry.event === "done")?.noWrites).length }; return { ...report, stalls, truncated: report.truncated || incomplete, ...(current.some(task => this.isPii(task)) ? { privateTasks: "withheld" } : {}), bands: "see ahub sdlc metrics" }; } async planReviewGap(task: Task): Promise { const receipt = task.sdlc?.planReview; if (!receipt) return "plan not reviewed since proposal"; if (!receipt.planner || !Number.isFinite(receipt.recordedAt)) return "plan not reviewed since planning revision change"; const revision = task.planningRevision ?? 0; if (receipt.planningRevision !== revision) { const changes = task.history.filter(entry => entry.planning && entry.planning.revision > receipt.planningRevision); if (receipt.planningRevision > revision || changes.length !== revision - receipt.planningRevision || changes.some((entry, index) => entry.event !== "planned" || entry.planning!.revision !== receipt.planningRevision + index + 1 || entry.planning!.fields.length !== 1 || entry.planning!.fields[0] !== "release")) return "plan not reviewed since planning revision change"; } if (receipt.scope && JSON.stringify(receipt.scope) !== JSON.stringify(cleanCostPlan(task.plan ?? {}))) return "plan not reviewed since cost scope change"; const identity = this.planIssueIdentity(task); if (identity?.issue && this.isPii(task)) return "private issue plan review evidence unavailable"; if (!identity?.issue) return receipt.issue ? "plan not reviewed since issue identity change" : undefined; if (!identity.repo || typeof receipt.issue?.repo !== "string" || receipt.issue.repo.toLowerCase() !== identity.repo.toLowerCase() || receipt.issue.issue !== identity.issue) return "plan not reviewed since issue identity change"; const current = await readPlanIssueMetadata(identity.repo, identity.issue, this.d.sdlc?.gh ?? sdlcGh); if (!current) return "plan review issue metadata unavailable"; if (current.state !== "OPEN") return "plan review issue is closed"; return current.editedAt !== receipt.issue.editedAt ? "plan not reviewed since issue edit" : undefined; } /** Planner authority and issue edit evidence are rechecked across every external await. */ async recordPlanReview(by: PeerId, id: unknown, input: unknown): Promise { this.plannerWriteAuthority(by); if (!input || typeof input !== "object" || Array.isArray(input)) throw new PreEffectToolRefusal("plan review needs a revision and reason"); const raw = input as Record; if (Object.keys(raw).some(key => !["revision", "reason", "review", "ci"].includes(key)) || !Number.isSafeInteger(raw.revision) || (raw.revision as number) < 0 || typeof raw.reason !== "string" || !raw.reason.trim() || raw.reason.length > 1000) throw new PreEffectToolRefusal("plan review needs a current revision and bounded reason"); const task = this.need(id, false, true, true), revision = raw.revision as number; this.planReviewAuthority(by, task); if (isClosedTaskState(task.state)) throw new PreEffectToolRefusal("closed work is final"); if ((task.planningRevision ?? 0) !== revision) throw new PreEffectToolRefusal("planning revision changed"); let scope: CostPlan; try { scope = cleanCostPlan({ ...task.plan, ...("review" in raw ? { review: raw.review } : {}), ...("ci" in raw ? { ci: raw.ci } : {}) }, { review: "review" in raw ? "" : "plan", ci: "ci" in raw ? "" : "plan" }); } catch (error) { throw new PreEffectToolRefusal(error instanceof CostScopeError ? error.message : "invalid review or CI cost scope"); } const mode = (this.d.sdlc?.config() ?? sdlcConfig(undefined)).mode; if (!scope.review || !scope.ci) { if (mode === "enforce") throw new PreEffectToolRefusal("review and CI cost scope required for a new plan receipt"); if (mode === "advise") this.releaseNotice(`task ${this.publicTitle(task)}: cost scope unspecified`); } const flow = task.history.length, withheld = await this.withholds("note", raw.reason, task); this.plannerWriteAuthority(by); const observed = this.need(task.id, false, true, true); this.planReviewAuthority(by, observed); if (observed.history.length !== flow || (observed.planningRevision ?? 0) !== revision) throw new PreEffectToolRefusal("plan review changed during readback"); const identity = this.planIssueIdentity(observed); if (identity?.issue && this.isPii(observed)) throw new PreEffectToolRefusal("private issue plan review readback unavailable"); const issue = identity?.repo && identity.issue ? await readPlanIssueMetadata(identity.repo, identity.issue, this.d.sdlc?.gh ?? sdlcGh) : undefined; if (identity?.issue && !issue) throw new PreEffectToolRefusal("plan review issue metadata unavailable"); if (issue && !this.isPii(task) && !this.nameable(JSON.stringify(issue))) throw new PreEffectToolRefusal("plan review metadata matches a PII pattern"); this.plannerWriteAuthority(by); const current = this.need(task.id, false, true, true); const authorship = this.planReviewAuthority(by, current); if (current.history.length !== flow || (current.planningRevision ?? 0) !== revision) throw new PreEffectToolRefusal("plan review changed during readback"); const config = this.d.sdlc?.config() ?? sdlcConfig(undefined); let updated = this.d.board.update(current.id, by, "plan reviewed", { ...(Object.keys(scope).length ? { plan: { ...current.plan, ...scope } } : {}), sdlc: { ...current.sdlc, stage: current.sdlc?.stage ?? lifecycleStage(config, "plan"), planReview: { planner: by, ...authorship, planningRevision: revision, recordedAt: Date.now(), ...(Object.keys(scope).length ? { scope } : {}), ...(issue ? { issue } : {}) } } }, raw.reason.trim(), { ...authorship, ...(withheld ? { withheld: true } : {}) }, flow); this.planReviewRequests.delete(updated.id); if (config.mode !== "off") updated = this.linkIssue(updated); // #694 if (updated.state === "proposed" && !updated.owner) { this.offered.delete(updated.id); try { await this.offerReady(updated, "planner review recorded"); } catch { this.releaseNotice(`task #${updated.id}: plan review saved; inspect its owner delivery before retrying`); } } return this.d.board.get(updated.id) ?? updated; } /** Artifact links and claimed local gates stay on the board; no outside text is accepted. */ /** * `hub_sdlc_record` (#509a): the receipt may also name `deliverables`. They are split off here, claims vetted and the files hashed by the hub, * and only then is the rest recorded as before. A receipt with deliverables and nothing else records just the deliverables. */ async recordSdlc(by: PeerId, id: unknown, input: unknown): Promise { const requestCheck = this.requestCheck(by); const spec = await this.specStageGate(by, id, input); requestCheck(); if (!input || typeof input !== "object" || Array.isArray(input) || !("deliverables" in input)) return this.recordLifecycle(by, id, input, undefined, spec?.carry); const { deliverables, ...receipt } = input as Record; const task = this.need(id, false, true); if (by !== USER && by !== task.owner && by !== task.reviewer) throw new PreEffectToolRefusal("only the task owner, reviewer or console user may record lifecycle evidence"); const claims = this.deliverableClaims(deliverables, task); const records = await this.hashClaims(claims, task, true); requestCheck(); const current = this.need(id, false, true); if (current.history.length !== task.history.length) throw new PreEffectToolRefusal("task changed while its deliverables were hashed; record them again"); return this.recordLifecycle(by, id, receipt, records, spec?.carry); } recordLifecycle(by: PeerId, id: unknown, input: unknown, deliverables?: DeliverableRecord[], specCarry?: object): Task { requireLocalTaskPeer(by); const task = this.stagedSpec(by, this.need(id, false, true), specCarry); const config = this.d.sdlc?.config() ?? sdlcConfig(undefined); const next = sdlcReceipt(input, task.sdlc, config, VERSION); const definition = stageDefinition(config, next.stage); const plannerStage = !!input && typeof input === "object" && !Array.isArray(input) && Object.hasOwn(input, "stage") && Object.keys(input).every(key => ["stage", "repo", "issue"].includes(key)) && (definition?.actor === "planner" || definition?.actor === "owner/planner") && this.taskPlanner(task).includes(by); if (by !== USER && by !== task.owner && by !== task.reviewer && !plannerStage) throw new PreEffectToolRefusal("only the task owner, reviewer or console user may record lifecycle evidence; a stage planner may record stage identity"); // The spec identity is person-owned in enforce. No observation cache or restart can reopen a relink bypass. const specRelink = (task.sdlc?.repo !== undefined && next.repo !== task.sdlc.repo) || (task.sdlc?.issue !== undefined && next.issue !== task.sdlc.issue); if (config.mode === "enforce" && by !== USER && specRelink) throw new PreEffectToolRefusal("only the person may relink an established repository or issue in enforce"); if (next.redFirst && input && typeof input === "object" && "redFirst" in input && !this.isPii(task) && !this.publicMetadataText(JSON.stringify(next.redFirst))) throw new PreEffectToolRefusal("red-first metadata matches a PII pattern; use private work"); // #481 S1: entering a build stage in enforce needs the person's spec acceptance; the person may move any stage. if (config.mode === "enforce" && by !== USER && next.stage !== task.sdlc?.stage && definition && canonicalStage(definition.base) === "build" && specState(next, undefined) === "missing") throw new PreEffectToolRefusal(this.specText(task, "missing", "blocked")); if (config.mode === "enforce" && config.definitions && input && typeof input === "object" && "stage" in input && next.stage !== task.sdlc?.stage && by !== USER) { const actor = definition?.actor; const acts = actor === "owner" ? by === task.owner : actor === "reviewer" ? by === task.reviewer : actor === "planner" ? this.taskPlanner(task).includes(by) : actor === "owner/planner" && (by === task.owner || this.taskPlanner(task).includes(by)); if (!acts) throw new PreEffectToolRefusal(`lifecycle stage requires its ${actor ?? "unknown"} actor or the person`); } if (input && typeof input === "object" && ("criteria" in input || "phase" in input)) { this.mine(task, by, "reviewer", true); // Screen whichever name stored the checklist: off keeps the #257 phase key (#481 S8). const checklist = checklistOf(next); if (checklist && !this.isPii(task) && !this.nameable(JSON.stringify(checklist))) throw new PreEffectToolRefusal("checklist metadata matches a PII pattern; use private work"); } // Recording a head is the reviewer's; a head dropped because the repo or PR changed is not a recording, and a // head supplied with a new PR identity is one even when its value is unchanged (#382). const suppliedHead = !!input && typeof input === "object" && (input as { reviewedHead?: unknown }).reviewedHead !== undefined; const artifactChanged = next.repo !== task.sdlc?.repo || next.pr !== task.sdlc?.pr; if (next.reviewedHead !== undefined && (next.reviewedHead !== task.sdlc?.reviewedHead || (suppliedHead && artifactChanged))) this.mine(task, by, "reviewer", true); const departure = task.history.findLast(h => h.by === USER && h.planDeparture)?.planDeparture; const invalidatesDeparture = !!departure && (artifactChanged || next.localHead !== task.sdlc?.localHead && next.localHead !== undefined && next.localHead !== departure.head || next.reviewedHead !== task.sdlc?.reviewedHead && next.reviewedHead !== undefined && next.reviewedHead !== departure.head); return this.commitSpecCarry(by, specCarry, task.id, by, "lifecycle", { sdlc: next }, undefined, { ...this.planObservation({ ...task, sdlc: next }), ...(invalidatesDeparture ? { planDepartureInvalidated: true } : {}), ...(deliverables ? { deliverables } : {}) }); } /** The board as the merge queue and the guarded merge read it (#786): ids, dependencies, privacy, receipts, findings and plans. */ private deliveryLinks(config: SdlcConfig): DeliveryTask[] { return this.d.board.list().map(t => ({ id: t.id, after: t.deps ?? [], private: this.isPii(t), latestHead: this.reviewHead(t), approval: approvalBinding(t), receipt: t.sdlc, phase: this.isPii(t) ? undefined : this.workflowView(t), findings: this.isPii(t) ? undefined : this.reviewFindingSets(t), ...(config.mode === "off" || !config.security || this.isPii(t) ? {} : { securityPass: t.history.findLast(entry => entry.securityPass && !entry.withheld && (entry.event === "approved" || entry.event === "changes_requested"))?.securityPass }), plan: config.mode === "off" || this.isPii(t) ? undefined : { paths: this.planPaths(t), out_of_scope: this.planPaths(t, "out_of_scope") ?? t.plan?.out_of_scope, revision: t.history.findLast(h => h.planRevision)?.planRevision?.revision ?? 0, fingerprint: planFingerprint(t.plan ?? {}), accepted: this.validPlanDepartures(t) } })); } /** * The board links one `readMergeQueue` read used for a subject (#491): the subject, the holders of the PRs in the open set it read (repository names compare without * case, as the queue does), and the tasks those holders and the subject depend on. Nothing else reaches the queue: a proposal, a plan or finding elsewhere, a holder * of a closed or merged PR that nobody depends on, or a receipt in another repository cannot change what it saw. Pass the queue the decision read: its rows are the * open set. Without one (the read failed) every link counts. */ private queueLinks(links: DeliveryTask[], subject: DeliveryTask, queue: MergeQueue | undefined): DeliveryTask[] { if (!queue) return links; const repo = subject.receipt?.repo?.toLowerCase(), open = new Set(queue.rows.map(row => row.pr)); // The subject's own dependencies are also reached as a holder of its open PR; naming them here keeps the fence right if that PR were ever absent from the rows. const used = new Set([subject.id, ...subject.after]); for (const link of links) { if (repo === undefined || link.receipt?.repo?.toLowerCase() !== repo || link.receipt.pr === undefined || !open.has(link.receipt.pr)) continue; used.add(link.id); for (const id of link.after) used.add(id); } return links.filter(link => used.has(link.id)); } async deliveryQueue(repo: string) { const config = this.d.sdlc?.config() ?? sdlcConfig(undefined); const before = workflowHash(this.d.board.list().map(t => ({ id: t.id, state: t.state, after: t.deps, sdlc: t.sdlc, history: t.history.length }))); const links = this.deliveryLinks(config); const report = await readMergeQueue(repo, config, links, this.d.sdlc?.gh, this.publicMetadataText); // Policy can change across remote awaits without any board write. Never return its stale public projection. const currentPrivacy = this.d.board.list().map(task => ({ id: task.id, private: this.isPii(task) })); if (workflowHash(links.map(({ id, private: hidden }) => ({ id, private: hidden }))) !== workflowHash(currentPrivacy)) { return { ...report, complete: false, rows: [], order: [], unordered: [], conflicts: [] }; } const after = workflowHash(this.d.board.list().map(t => ({ id: t.id, state: t.state, after: t.deps, sdlc: t.sdlc, history: t.history.length }))); if (before !== after) { report.complete = false; report.order = []; if (report.rows.length) report.unordered = report.rows.map(row => row.pr); for (const row of report.rows) { row.ready = false; row.blockers.push("board changed during delivery readback"); } } else if (config.mode !== "off") for (const row of report.rows) if (row.head && !row.private) for (const id of row.tasks) { const task = this.d.board.get(id); if (task?.sdlc?.repo?.toLowerCase() === report.repo.toLowerCase() && task.sdlc.pr === row.pr) { if (this.validPlanDepartures(task).length && row.planConformance?.some(item => item.task === id && item.state !== "unknown" && !item.accepted)) this.invalidatedPlanDepartures.add(id); this.capturePlanHead(task, row.head); } } for (const row of report.rows) if (row.testIntegrity) { row.testIntegrity = row.testIntegrity.map(item => ({ ...publicTestIntegrity(item, this.publicMetadataText), ...(item.task === undefined ? {} : { task: item.task }) })); if (config.mode === "enforce") { row.blockers = [...new Set([...row.blockers, ...row.testIntegrity.flatMap(testIntegrityBlockers)])]; row.ready = row.ready && row.blockers.length === 0; } } return report; } /** #1403 A4: a summary of the newest audit for the release report: ref, profile, partial and unit counts, never a finding or a path. */ auditLine(): AuditSummary | undefined { const audit = this.d.board.audits(1)[0]; return audit ? auditSummary({ audit: audit.id, task: audit.task, ref: audit.ref, profile: audit.profile, scoped: audit.scoped, at: audit.at }, audit.units, this.d.board.auditFindings(audit.id)) : undefined; } private surveyToolInput(command: "start" | "report", field: string, rule: string, read: () => T): T { try { return surveyInputAt(field, rule, read); } catch (error) { const problem = surveyInputProblem(error) ?? { field, rule }; const next = command === "report" ? "fix that field and resend hub_survey_report; tool description lists shape" : "fix that field and resend ahub sdlc survey start; ahub help sdlc survey lists shape"; throw new PreEffectToolRefusal(`${problem.field}: ${problem.rule}; ${next}`); } } private surveyStarting = false; private surveyAdmit(by: PeerId, check: () => void): void { check(); if ((this.d.sdlc?.config().mode ?? "off") === "off") throw new PreEffectToolRefusal("advisor surveys require lifecycle advise or enforce"); if (this.d.privateTurn?.(by) || this.d.reviewOnly?.(by) || this.d.requestAuthority?.(by)) throw new PreEffectToolRefusal("advisor surveys are unavailable in private or child sessions"); const held = this.studyHold(); if (held) throw new PreEffectToolRefusal(held); } private surveyTask(by: PeerId, id: unknown, write = false): { task: Task; survey: StoredSurvey } { const task = this.need(this.studyNumber(id, "survey task")), survey = this.d.board.surveyOfTask(task.id, task.created); if (!survey || survey.repo !== this.repositories.scope({}).key || this.repositories.scope(task.refs).key !== survey.repo) throw new PreEffectToolRefusal("survey is unavailable in this project"); const owner = task.owner === by && this.d.bus.isRostered(by) && this.isConfiguredPlanner(by); const reviewer = task.reviewer === by && this.d.bus.isRostered(by) && !!this.d.roles?.[by]?.includes("reviewer"); if (write ? !owner || task.state !== "in_progress" : by !== USER && !owner && !reviewer && !(this.configuredManualConductor(by) && this.d.bus.isRostered(by))) throw new PreEffectToolRefusal("survey reporting requires its assigned in-progress planner; readback requires its owner, reviewer, person or current conductor"); return { task, survey }; } private surveyPrivate(task: Task, by?: PeerId): boolean { return this.isPii(task) || task.signals.includes("pii") || task.signals.includes("pii_path") || !!(by && this.d.privateTurn?.(by)); } /** The existing task routing chooses one planner; no worker, scanner, issue or fix is launched. */ async surveyStart(by: PeerId, input: unknown = {}, fence?: () => string | undefined): Promise<{ task: number; survey: number; ref: string; focus?: SurveyFocus }> { const fields = this.surveyToolInput("start", "start", "must be a closed object with optional focus", () => surveyObject(input, ["focus"])), focus = fields.focus; if (focus !== undefined && (typeof focus !== "string" || !(SURVEY_FOCUS as readonly string[]).includes(focus))) this.surveyToolInput("start", "focus", "must be bugs, tests, debt, deps, dx or docs", () => { throw new Error("invalid bounded survey data"); }); const check = this.requestCheck(by, fence), authority = () => { this.surveyAdmit(by, check); if (by !== USER && !(this.configuredManualConductor(by) && this.d.bus.isRostered(by))) throw new PreEffectToolRefusal("only the person or current unique conductor may start a survey"); }; authority(); if (this.observerExcluded(by) || this.reviewObserverTurn(by)) throw new PreEffectToolRefusal("survey start is unavailable from observer material"); if (this.surveyStarting) throw new PreEffectToolRefusal("a survey is already starting"); const repo = this.repositories.scope({}).key, source = this.d.auditSource; if (!source) throw new PreEffectToolRefusal("survey source unavailable; start the hub from the project checkout"); const ref = source.head(); if (!ref || !/^[a-f0-9]{40}$/.test(ref) || source.resolve(ref) !== ref) throw new PreEffectToolRefusal("survey commit unavailable; select a checkout with a readable commit"); if (this.d.board.surveyOpen(repo)) throw new PreEffectToolRefusal("a survey is already open; finish or cancel it first"); const brief = `${surveyBrief({ ...(focus === undefined ? {} : { focus: focus as SurveyFocus }) })}\nPinned source commit: ${ref}\nRead this exact commit, including during vetting. Findings are declarations, never host proof of independent source review.\nSubmit candidates with hub_survey_report {id: , findings: [...]}; explicit vet decisions use vet: [...].\n${this.consideredBrief(repo, ref)}`; if (!this.publicMetadataText(brief)) throw new PreEffectToolRefusal("survey brief is not public"); this.surveyStarting = true; try { return await this.studyWrite(async () => { const guard = () => { authority(); if (this.d.auditSource !== source || this.repositories.scope({}).key !== repo || this.d.board.surveyOpen(repo)) throw new PreEffectToolRefusal("survey source or open-survey admission changed"); }; guard(); let surveyID: number | undefined; const task = await this.propose(by, { title: `Advisor survey${focus ? ` (${focus})` : ""} at ${ref.slice(0, 12)}`, detail: brief, class: "plan" }, undefined, undefined, () => { guard(); return undefined; }, created => { if (this.surveyPrivate(created, by)) throw new PreEffectToolRefusal("survey brief privacy was not cleared"); surveyID = this.d.board.surveyCreate({ task: created.id, taskCreated: created.created, repo, ref, ...(focus === undefined ? {} : { focus: focus as SurveyFocus }), by, at: this.d.now?.() ?? Date.now() }); }); return { task: task.id, survey: surveyID!, ref, ...(focus === undefined ? {} : { focus: focus as SurveyFocus }) }; }); } finally { this.surveyStarting = false; } } private consideredChanges(repo: string, ref?: string): (entryRef?: string) => string[] | undefined { // ponytail: distinct refs still use synchronous reads within the existing ledger window per key; batch through an async audit port if histories outgrow interactive readback. const cache = new Map(); let currentKnown: boolean | undefined; return entryRef => { if (!entryRef || !ref || entryRef === ref || repo !== this.repositories.scope({}).key) return undefined; if (cache.has(entryRef)) return cache.get(entryRef); let changed: string[] | undefined; try { currentKnown ??= this.d.auditSource?.resolve(ref) === ref; if (currentKnown && this.d.auditSource?.resolve(entryRef) === entryRef) changed = this.d.auditSource.changed(entryRef, ref); } catch { currentKnown ??= false; /* Per-call unknown evidence stays unknown; no cross-call freshness cache. */ } cache.set(entryRef, changed); return changed; }; } /** Same semantic identity and affected literal paths only; unreadable change evidence never clears suppression. */ consideredBefore(task: Task, finding: Pick | SurveyFinding, ref?: string, readChanges?: (entryRef?: string) => string[] | undefined): { rejectedBefore: boolean; change: "none" | "unchanged" | "changed" | "unknown"; suppressed: boolean } { const neutral = { rejectedBefore: false, change: "none" as const, suppressed: false }; if (positionalFindingId(finding.id) || (this.d.sdlc?.config().mode ?? "off") === "off" || this.surveyPrivate(task)) return neutral; const repo = this.repositories.scope(task.refs).key, ledger = this.d.board.rejectedFindingsFor(repo, finding.pass, finding.id, 1000); if (!ledger.complete) return { rejectedBefore: true, change: "unknown", suppressed: true }; const matched = ledger.rows.filter(row => row.entry.id === finding.id && row.entry.pass === finding.pass); if (!matched.length) return neutral; if (repo !== this.repositories.scope({}).key) return { rejectedBefore: true, change: "unknown", suppressed: true }; const currentRef = ref, paths = "paths" in finding ? finding.paths : finding.path ? (() => { try { return [surveyPath(finding.path)]; } catch { return []; } })() : []; const changes = readChanges ?? this.consideredChanges(repo, ref); let seen = false, unknown = false, unchanged = false; const overlaps = (a: string, b: string) => a === b || a.startsWith(b + "/") || b.startsWith(a + "/"); for (const row of matched) { seen = true; const changed = changes(row.entry.ref); const match = consideredFindingMatch(row.entry, { repo, id: finding.id, pass: finding.pass, currentRef: currentRef ?? "", ...(changed === undefined ? {} : { diff: { repo, base: row.entry.ref!, head: currentRef!, complete: true, paths: changed } }) }); if (match.status === "unknown" || !paths.length) unknown = true; if (match.status === "applicable" && match.applicablePaths.some(path => paths.some(candidate => overlaps(path, candidate)))) unchanged = true; } return !seen ? neutral : { rejectedBefore: true, change: unknown ? "unknown" : unchanged ? "unchanged" : "changed", suppressed: unknown || unchanged }; } private consideredPaths(path: string | undefined): string[] { if (!path) return []; try { let name = path.replace(/:[1-9][0-9]*(?::[1-9][0-9]*)?$/, ""); if (isAbsolute(name)) name = relative(this.d.cwd, name); return [surveyPath(name)]; } catch { return []; } } private consideredPublic(entry: ConsideredEntry): boolean { try { const source = this.d.board.get(entry.source.task); if (entry.withheld || entry.pass === "security" || !source || source.created !== entry.source.created || this.surveyPrivate(source)) return false; const { repo: _scope, ...data } = entry; return this.publicMetadataText(JSON.stringify(data)) && !this.signalsFor({ title: entry.id, detail: entry.reason, refs: { paths: entry.paths } }).some(signal => signal === "pii" || signal === "pii_path"); } catch { return false; } } /** Bounded public historical reasons; never expose internal scope keys, security text or paths. */ consideredDetails(repo: string, id: string, pass: SurveyPass, ref?: string, readChanges?: (entryRef?: string) => string[] | undefined): { complete: boolean; change: "unchanged" | "changed" | "unknown"; items: { id: string; reason?: string; change: "unchanged" | "changed" | "unknown"; withheld?: true }[] } { const publicId = this.publicMetadataText(id) ? id : "withheld"; const ledger = this.d.board.rejectedFindingsFor(repo, pass, id, 1000); if (!ledger.complete) return { complete: false, change: "unknown", items: [{ id: publicId, change: "unknown", withheld: true }] }; const changes = readChanges ?? this.consideredChanges(repo, ref); const items = ledger.rows.slice(0, 16).map(row => { const entry = row.entry; const changed = changes(entry.ref); const match = repo === this.repositories.scope({}).key ? consideredFindingMatch(entry, { repo, id, pass, currentRef: ref ?? "", ...(changed === undefined ? {} : { diff: { repo, base: entry.ref!, head: ref!, complete: true, paths: changed } }) }) : undefined; const change = match?.status === "applicable" ? "unchanged" as const : match?.status === "changed" ? "changed" as const : "unknown" as const; return { id: publicId, change, ...(this.consideredPublic(entry) ? { reason: entry.reason } : { withheld: true as const }) }; }); const change = ledger.rows.length > 16 ? "unknown" : items.some(row => row.change === "unknown") ? "unknown" : items.some(row => row.change === "unchanged") ? "unchanged" : items.length ? "changed" : "unknown"; return { complete: ledger.rows.length <= 16, change, items }; } consideredBrief(repo: string, ref?: string, scope?: readonly string[]): string { const ledger = this.d.board.rejectedFindings(repo, 1000); if (!ledger.complete) return "Previously rejected findings: history incomplete; change is unknown and rejection remains in effect."; const lines = ["Previously rejected findings (unknown change retains rejection; positional ids never match across tasks):"], seen = new Set(), changes = this.consideredChanges(repo, ref); for (const row of ledger.rows) { const entry = row.entry, key = `${entry.pass}:${entry.id}`; if (seen.has(key) || scope?.length && entry.paths.length && !entry.paths.some(path => scope.some(surface => matchConfigPath(surface, path) || path === surface || path.startsWith(surface + "/")))) continue; seen.add(key); const details = this.consideredDetails(repo, entry.id, entry.pass, ref, changes), detail = details.items[0]; const reason = detail?.reason ? `: ${Array.from(detail.reason).slice(0, 160).join("")}${Array.from(detail.reason).length > 160 ? "..." : ""}` : " (details withheld)"; const line = `${entry.pass}:${detail?.id ?? "withheld"}: rejected before; change ${details.change}${reason}`; if (seen.size > 32 || Buffer.byteLength([...lines, line].join("\n")) > 3072) { lines.push("Additional rejection history omitted; consult authorized readback. Unknown change retains rejection."); break; } lines.push(line); } if (lines.length === 1) lines.push("No matching recorded rejections."); return lines.join("\n"); } /** Saved facts stay local. Private/sensitive facts retain a withheld identity stub without a cloud screen. */ async recordConsideredFinding(task: Task, finding: ReviewFinding, reason: string | undefined, kind: "review" | "audit" | "survey", ref?: string): Promise { if ((this.d.sdlc?.config().mode ?? "off") === "off") return; return this.studyWrite(async () => { const revision = this.d.board.statusRevision(), current = this.d.board.get(task.id); if (!current || current.created !== task.created || current.history.length !== task.history.length || this.studyHold()) return; const normalized = typeof reason === "string" ? reason.replace(/[\p{Cc}\p{Cf}]+/gu, " ").replace(/\s+/g, " ").trim() : ""; const safeReason = normalized && Buffer.byteLength(normalized) <= 2048 ? normalized : "reason not recorded"; const paths = this.consideredPaths(finding.path), privateFact = this.surveyPrivate(current) || !!task.history.at(-1)?.withheld; let entry = parseConsideredEntry({ repo: this.repositories.scope(task.refs).key, id: finding.id, pass: finding.pass, paths: privateFact ? [] : paths, reason: privateFact ? "reason not recorded" : safeReason, ...(ref && /^[a-f0-9]{40}$/.test(ref) ? { ref } : {}), source: { task: task.id, created: task.created, kind }, ...(privateFact || finding.pass === "security" ? { withheld: true } : {}) }); const { repo: _internalScope, ...publicEntry } = entry; if (!this.publicMetadataText(JSON.stringify(publicEntry))) entry = { ...entry, paths: [], reason: "reason not recorded", withheld: true }; const now = this.d.board.get(task.id); if (!now || now.created !== task.created || now.history.length !== task.history.length || this.d.board.statusRevision() !== revision || (this.d.sdlc?.config().mode ?? "off") === "off" || this.studyHold() || this.repositories.scope(now.refs).key !== entry.repo) return; return this.d.board.recordRejectedFinding(entry); }); } private recordConsideredAfter(task: Task, findings: readonly ReviewFinding[], kind: "review" | "audit", ref?: string): void { if ((this.d.sdlc?.config().mode ?? "off") === "off" || !findings.length) return; this.releaseNotice(`task #${task.id}: considered rejection ledger unavailable`, () => { void Promise.all(findings.map(finding => this.recordConsideredFinding(task, finding, kind === "audit" ? undefined : finding.rationale, kind, ref))) .then(ids => { if (ids.some(id => id === undefined)) this.releaseNotice(`task #${task.id}: considered rejection ledger admission changed; source decision remains saved`); }) .catch(() => this.releaseNotice(`task #${task.id}: considered rejection ledger unavailable`)); }); } surveyShow(by: PeerId, id: unknown) { const check = this.requestCheck(by); this.surveyAdmit(by, check); const { task, survey } = this.surveyTask(by, id); if (this.surveyPrivate(task, by)) return { task: task.id, status: "private" as const }; const revision = this.d.board.statusRevision(), policy = JSON.stringify([this.d.roles, this.d.routing(), this.d.piiPaths]); const full = by === USER || this.d.bus.isRostered(by) && (task.owner === by && this.isConfiguredPlanner(by) || task.reviewer === by && !!this.d.roles?.[by]?.includes("reviewer")); const stored = this.d.board.surveyFindings(survey.id), changes = this.consideredChanges(survey.repo, survey.ref); if (stored.some(row => !this.publicMetadataText(JSON.stringify(row.finding)) || this.signalsFor({ title: row.finding.id, detail: JSON.stringify(row.finding), refs: { paths: row.finding.paths } }).some(signal => signal === "pii" || signal === "pii_path"))) return { task: task.id, status: "private" as const }; const items = stored.map(row => { const finding = full ? row.finding : publicSurveyFinding(row.finding), before = this.consideredBefore(task, row.finding, survey.ref, changes); const details = this.consideredDetails(survey.repo, row.finding.id, row.finding.pass, survey.ref, changes); return { ...finding, ...(row.decision ? { verdict: row.decision.verdict } : {}), ...before, rejected: details.items, rejectedComplete: details.complete }; }); this.surveyAdmit(by, check); const now = this.surveyTask(by, id); if (this.surveyPrivate(now.task, by)) return { task: task.id, status: "private" as const }; if (this.d.board.statusRevision() !== revision || now.task.history.length !== task.history.length || JSON.stringify([this.d.roles, this.d.routing(), this.d.piiPaths]) !== policy) throw new PreEffectToolRefusal("survey changed during readback; reload before reading"); return { task: task.id, survey: survey.id, ref: survey.ref, ...(survey.focus ? { focus: survey.focus } : {}), status: "available" as const, items }; } async surveyReport(by: PeerId, input: unknown, fence?: () => string | undefined) { const fields = this.surveyToolInput("report", "report", "must be a closed object with id and findings, vet or show", () => surveyObject(input, ["id", "findings", "vet", "show"])); this.surveyToolInput("report", "id", "must be a positive integer survey task id", () => { if (!Number.isSafeInteger(fields.id) || (fields.id as number) < 1) throw new Error("invalid bounded survey data"); }); this.surveyToolInput("report", "show", "must be true for read-only show and cannot include findings or vet decisions", () => { if (fields.show !== undefined && fields.show !== true || fields.show && (fields.findings !== undefined || fields.vet !== undefined)) throw new Error("invalid bounded survey data"); }); if (fields.show) { this.requestCheck(by, fence)(); return this.surveyShow(by, fields.id); } const findings = fields.findings === undefined ? [] : this.surveyToolInput("report", "findings", "must match the documented finding array", () => parseSurveyFindings(fields.findings)); const decisions = fields.vet === undefined ? [] : this.surveyToolInput("report", "vet", "must match the documented vet array", () => parseSurveyVetDecisions(fields.vet)); const check = this.requestCheck(by, fence), guard = () => { this.surveyAdmit(by, check); return this.surveyTask(by, fields.id, true); }; const initial = guard(); if (this.surveyPrivate(initial.task, by) || this.observerExcluded(by) || this.reviewObserverTurn(by)) throw new PreEffectToolRefusal("survey writes unavailable during private or observer work"); if (!findings.length && !decisions.length) throw new PreEffectToolRefusal("report: needs findings or explicit vet decisions; fix that field and resend hub_survey_report; tool description lists shape"); const observerExcluded = this.observerExcluded(by); // Capture before any awaited screen; never forward observer material. if (observerExcluded) throw new PreEffectToolRefusal("survey observer input is unavailable"); return this.studyWrite(async () => { const { task, survey } = guard(), boardRevision = this.d.board.statusRevision(), policy = JSON.stringify([this.d.sdlc?.config().mode, this.d.roles, this.d.routing(), this.d.piiPaths]); const current = () => { const now = guard(); if (now.task.created !== task.created || now.task.history.length !== task.history.length || now.task.owner !== task.owner || this.surveyPrivate(now.task, by) || this.d.board.statusRevision() !== boardRevision || JSON.stringify([this.d.sdlc?.config().mode, this.d.roles, this.d.routing(), this.d.piiPaths]) !== policy) throw new PreEffectToolRefusal("survey authority, privacy or policy changed; reload before reporting"); }; const existing = this.d.board.surveyFindings(survey.id), merged = new Map(existing.map(row => [row.finding.id, row.finding])); for (const finding of findings) { const prior = merged.get(finding.id); if (prior && JSON.stringify(prior) !== JSON.stringify(finding)) throw new PreEffectToolRefusal("findings[].id: survey candidate id already records different content; fix that field and resend hub_survey_report; tool description lists shape"); merged.set(finding.id, finding); } const text = JSON.stringify({ findings: this.surveyToolInput("report", "findings", "combined findings must remain within the documented bounds", () => parseSurveyFindings([...merged.values()])), decisions }); if (!this.publicMetadataText(text)) throw new PreEffectToolRefusal("survey metadata was not cleared as public"); if (this.screenOn() && (await this.screenCall(text)).label !== "clear") throw new PreEffectToolRefusal("survey metadata privacy screening was unavailable or refused"); current(); const changes = this.consideredChanges(survey.repo, survey.ref); const cards: SurveyPreparedCard[] = [], rejections: ConsideredEntry[] = [], reconsiderations: ConsideredEntry[] = []; const items: { id: string; rejectedBefore: boolean; change: "none" | "unchanged" | "changed" | "unknown"; suppressed: boolean }[] = []; for (const decision of decisions) { const finding = merged.get(decision.id); if (!finding) throw new PreEffectToolRefusal("vet[].id: vet decision names an unknown survey candidate; fix that field and resend hub_survey_report; tool description lists shape"); const before = this.consideredBefore(task, finding, survey.ref, changes); items.push({ id: finding.id, ...before }); const entry = (reason: string): ConsideredEntry => ({ repo: survey.repo, id: finding.id, pass: finding.pass, paths: finding.paths, reason, ref: survey.ref, source: { task: task.id, created: task.created, kind: "survey" }, ...(finding.pass === "security" ? { withheld: true } : {}) }); if (decision.verdict === "rejected") { rejections.push(entry(decision.reason!)); continue; } if (before.suppressed && !decision.reason) continue; if (before.rejectedBefore && decision.reason) reconsiderations.push(entry(decision.reason)); const key = surveyFindingKey(survey.repo, finding.pass, finding.id), security = finding.pass === "security"; const history = this.d.board.surveyCardHistory(key), reopens = history.active ? undefined : history.closed; current(); const reopenReason = security ? "explicit current vet; security details remain in the authorized survey" : decision.reason ?? (before.change === "changed" ? "affected paths changed since the recorded rejection" : "explicit current vet; no applicable rejected finding remains"); const reopening = reopens === undefined ? {} : { reopens, reopenReason }; const draft = { title: security ? `Survey security finding ${finding.id}` : `Survey ${finding.confidence}: ${finding.id}`, detail: `${key}\nSource survey task ${task.id} at ${survey.ref}.\n${finding.confidence === "low" ? "Read-only investigation. Do not edit files or execute a fix." : "Prepare a backlog plan. Do not execute a fix."}${security ? "\nSecurity details withheld; read the source survey with authorized task access." : `\nEvidence: ${finding.evidence}\nImpact: ${finding.impact}\nEffort: ${finding.effort}\nRisk: ${finding.risk}\nFix sketch: ${finding.fix_sketch}`}${reopens === undefined ? "" : `\nReopened from hub task ${reopens}: ${reopenReason}`}`, refs: security ? {} : { paths: finding.paths } }; if (Buffer.byteLength(draft.detail) > SURVEY_LIMITS.cardBytes) throw new PreEffectToolRefusal("survey card exceeds its detail bound; shorten the finding or reconsideration reason"); const signals = this.signalsFor(draft); if (this.isPii({ signals }) || signals.includes("pii") || signals.includes("pii_path") || !this.publicMetadataText(JSON.stringify(draft))) throw new PreEffectToolRefusal("survey candidate card is not public"); if (this.screenOn() && (await this.screenCall(JSON.stringify(draft))).label !== "clear") throw new PreEffectToolRefusal("survey card privacy screening was unavailable or refused"); current(); cards.push({ id: finding.id, key, ...draft, class: finding.confidence === "low" ? "triage" : "plan", signals, ...reopening }); } current(); const result = this.d.board.surveyApply(survey.id, { findings, decisions, by, at: this.d.now?.() ?? Date.now(), cards, rejections, reconsiderations }, { boardRevision, taskCreated: task.created, taskFlowRevision: task.history.length, owner: task.owner! }); for (const id of result.createdIDs) this.incomingBacklog.add(id); this.releaseNotice(`survey task ${task.id}: ${result.createdIDs.length} backlog candidates created`); return { task: task.id, survey: survey.id, status: "recorded" as const, ...result, items }; }); } private auditCarry(head: string, source: AuditSource): CarryLookup { const audits = this.d.board.audits(32, true), changed = new Map(); const since = (base: string) => { if (!changed.has(base)) changed.set(base, source.changed(base, head)); return changed.get(base); }; return (surface, companion) => { const id = unitId(surface, companion); for (const audit of audits) { const unit = audit.units.find(row => row.unit === id); // The newest audit that lists the unit decides: a scoped audit that left it out says nothing, but a deferred, out-of-scope or still planned unit plans it again. if (!unit) continue; if (unit.state !== "covered") return undefined; const base = unit.prior?.head ?? audit.ref, origin = unit.prior?.audit ?? audit.id, paths = since(base); // Unknown never carries: an unreadable change list, or a changed path under the surface, plans the unit again. return paths && !paths.some(path => matchConfigPath(surface, path)) ? { audit: origin, head: base } : undefined; } return undefined; }; } /** * #1403 A4: `ahub sdlc audit start`. The person or the one configured conductor files one read-only `review` task whose brief lists the ledger, and the hub seeds the ledger in `hub.db` * (surface x companion, `planned`, or `covered (prior)` for a surface whose paths are unchanged since its last covered state). Nothing is written until every check has passed. */ async auditStart(by: PeerId, input: { profile?: unknown; since?: unknown }, fence?: () => string | undefined): Promise<{ task: number; audit: number; units: number; planned: number; carried: number; partial: boolean; ref: string }> { const check = this.requestCheck(by, fence); if (by !== USER && (!this.configuredManualConductor(by) || !this.d.bus.isRostered(by))) throw new PreEffectToolRefusal("only the person or the current configured conductor may start a security audit; ask the person to run ahub sdlc audit start"); if (this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("a security audit cannot start in a private turn; finish that turn and retry ahub sdlc audit start"); const config = this.d.sdlc?.config() ?? sdlcConfig(undefined); if (config.mode === "off") throw new PreEffectToolRefusal("security audits need the lifecycle on: set sdlc.mode to advise or enforce in .agenthub/sdlc.toml"); if (!config.security) throw new PreEffectToolRefusal("security audits need a [security] table in .agenthub/sdlc.toml (paths and companions)"); const source = this.d.auditSource; if (!source) throw new PreEffectToolRefusal("this hub has no git source to read for an audit; start the hub from a git checkout of the project and retry ahub sdlc audit start"); const profile = input.profile === undefined ? "standard" : input.profile; if (typeof profile !== "string" || !(AUDIT_PROFILES as readonly string[]).includes(profile)) throw new PreEffectToolRefusal(`profile is one of ${AUDIT_PROFILES.join(", ")}`); const head = source.head(); if (!head) throw new PreEffectToolRefusal("the checkout's head commit could not be read; run the audit from a git checkout with a commit"); let scoped: string[] | undefined; if (input.since !== undefined) { if (typeof input.since !== "string" || !input.since.trim() || input.since.length > 200) throw new PreEffectToolRefusal("--since names a commit, tag or branch of this checkout"); const base = source.resolve(input.since.trim()); if (!base) throw new PreEffectToolRefusal("--since does not name a commit in this checkout"); scoped = source.changed(base, head); if (!scoped) throw new PreEffectToolRefusal("the paths changed since that ref could not be listed completely; narrow --since or run an unscoped audit"); } if (this.d.board.list().some(t => t.class === "review" && t.title.startsWith("Security audit (") && !isClosedTaskState(t.state) && t.state !== "approved" && this.d.board.auditOfTask(t.id, t.created))) throw new PreEffectToolRefusal("a security audit is already open; finish or cancel it first"); const units = seedLedger(config.security, profile as AuditProfile, { ...(scoped ? { scoped } : {}), carry: this.auditCarry(head, source) }); if (!units.length) throw new PreEffectToolRefusal("no configured security surface has a changed path in that scope; nothing to audit"); const partial = auditIsPartial(profile as AuditProfile, scoped !== undefined); const inline = units.filter(u => !u.prior).slice(0, 40), cut = units.filter(u => !u.prior).length - inline.length; const brief = auditBrief([...inline, ...units.filter(u => u.prior)], { profile: profile as AuditProfile, partial, checklist: SECURITY_CHECKLIST, ref: head }) + (cut > 0 ? `\n(${cut} more units: hub_audit_report {id: , show: true} lists the ledger)` : "") + "\n" + this.consideredBrief(this.repositories.scope({}).key, head, config.security.paths); check(); const task = await this.propose(by, { title: `Security audit (${profile}${scoped ? ", scoped" : ""}) at ${head.slice(0, 12)}`, detail: brief, class: "review" }, undefined, undefined, fence); let audit: number; try { if (this.isPii(task)) throw new PreEffectToolRefusal("the audit brief matched a private-data pattern; rename the configured surface"); audit = this.d.board.auditCreate({ task: task.id, taskCreated: task.created, ref: head, ...(typeof input.since === "string" ? { since: input.since.trim() } : {}), profile, scoped: scoped !== undefined, by, at: this.d.now?.() ?? Date.now(), units }); } catch (error) { // The ledger is the audit: a task without one would be an empty promise, so it is cancelled rather than left to run. await this.cancel(task.id, by, { reason: "security audit ledger could not be created" }).catch(() => undefined); throw error; } return { task: task.id, audit, units: units.length, planned: units.filter(u => !u.prior).length, carried: units.filter(u => u.prior).length, partial, ref: head }; } private auditView(audit: NonNullable>, full: boolean): AuditView { const findings = this.d.board.auditFindings(audit.id); const summary = auditSummary({ audit: audit.id, task: audit.task, ref: audit.ref, profile: audit.profile, scoped: audit.scoped, at: audit.at }, audit.units, findings); return { ...summary, units: audit.units.map(u => ({ unit: u.unit, state: u.state, ...(u.prior ? { prior: u.prior } : {}), ...(u.reason ? { reason: u.reason } : {}) })), items: findings.map(row => auditFindingView(row, full)), ...(full ? {} : { withheld: findings.filter(row => !!auditFindingView(row, false).withheld).length }) }; } /** `ahub sdlc audit show`: the newest audit, or the one named. The full view (open important boundary text included) is the person's alone; a conductor reads the public one. */ auditShow(by: PeerId, id?: unknown): AuditView | undefined { if (by !== USER && (!this.configuredManualConductor(by) || !this.d.bus.isRostered(by))) throw new PreEffectToolRefusal("the audit readback is for the person or the configured conductor"); if (by !== USER && this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("the audit readback is unavailable in a private turn"); const audit = id === undefined ? this.d.board.audits(1)[0] : Number.isSafeInteger(id) && (id as number) > 0 ? this.d.board.audit(id as number) : undefined; if (id !== undefined && !audit) throw new PreEffectToolRefusal("no such security audit"); return audit ? this.auditView(audit, by === USER) : undefined; } /** * #1403 A4, A5: `hub_audit_report`. The assigned auditor (the audit task's owner) reports a state per unit and its findings; the hub alone writes the ledger. A reviewer-role peer that did * not file a `confirmed` important finding verifies or rejects it; until then it stays a `candidate`. Boundary text of an open important finding is read only through this tool by the * auditor, a reviewer-role peer or the person, and never rides a message to anyone else. */ async auditReport(by: PeerId, input: { id?: unknown; units?: unknown; findings?: unknown; verify?: unknown; settle?: unknown; show?: unknown }, fence?: () => string | undefined): Promise { const check = this.requestCheck(by, fence); const config = this.d.sdlc?.config() ?? sdlcConfig(undefined); if (config.mode === "off" || !config.security) throw new PreEffectToolRefusal("audit reports need the lifecycle on and a [security] table in .agenthub/sdlc.toml"); if (by !== USER && this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("audit reports are unavailable in a private turn: their text must not leave this machine"); if (!Number.isSafeInteger(input.id) || (input.id as number) <= 0) throw new PreEffectToolRefusal("hub_audit_report needs the audit task id"); const task = this.d.board.get(input.id as number), audit = task ? this.d.board.auditOfTask(task.id, task.created) : undefined; if (!task || !audit) throw new PreEffectToolRefusal("no security audit on that task"); if (this.isPii(task)) throw new PreEffectToolRefusal("that task is private"); const isOwner = by !== USER && task.owner === by && task.state === "in_progress"; const reviewerRole = by !== USER && (this.d.roles?.[by] ?? []).includes("reviewer") && this.d.bus.isRostered(by); const writes = input.units !== undefined || input.findings !== undefined, verifies = input.verify !== undefined, settles = input.settle !== undefined; if (!writes && !verifies && !settles && input.show !== true) throw new PreEffectToolRefusal("give units and findings (the auditor), verify or settle (a reviewer other than the finder, or the person) or show: true"); if (writes && !isOwner) throw new PreEffectToolRefusal("only the assigned auditor reports units and findings, while the audit task is in progress"); if (verifies && !(reviewerRole || by === USER)) throw new PreEffectToolRefusal("only a reviewer-role peer or the person verifies a finding"); if (settles && !(reviewerRole || by === USER)) throw new PreEffectToolRefusal("only a reviewer-role peer other than the finder, or the person, settles a verified finding; ask a reviewer or the person to settle it"); if ((verifies || settles) && (task.state === "cancelled" || task.state === "backlog")) throw new PreEffectToolRefusal("the audit task is closed"); if (!isOwner && !reviewerRole && by !== USER) throw new PreEffectToolRefusal("only the auditor, a reviewer-role peer or the person reads an audit report"); const when = this.d.now?.() ?? Date.now(); let units = audit.units, filed: { finding: ReviewFinding; foundBy: string; at: number }[] = []; const decisions: { finding: string; verdict: "verified" | "rejected" }[] = []; const settlements: { finding: string; disposition: "fixed" | "false_positive" }[] = []; if (input.units !== undefined) { try { units = applyUnitReports(audit.units, parseUnitReports(input.units, audit.units), by, when); } catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid units"); } } if (input.findings !== undefined) { let parsed: ReviewFinding[]; try { parsed = parseReviewFindings(input.findings, { person: false, maxNits: this.d.sdlc?.config().maxNits ?? DEFAULT_MAX_NITS, contract: "required" }); } catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid findings"); } if (parsed.some(item => item.pass !== "security")) throw new PreEffectToolRefusal("an audit takes security findings only (pass: security)"); if (parsed.some(item => item.anchor !== undefined)) throw new PreEffectToolRefusal("anchors belong to review verdicts; name the file in path"); const text = JSON.stringify(parsed); if (!this.nameable(text) || this.screenOn() && (await this.screenCall(text)).label !== "clear") throw new PreEffectToolRefusal("finding text was not cleared for the audit ledger: it matches a private-data pattern or the PII screen did not clear it"); filed = parsed.map(finding => ({ finding, foundBy: by, at: when })); } if (input.verify !== undefined) { if (!Array.isArray(input.verify) || !input.verify.length || input.verify.length > 32) throw new PreEffectToolRefusal("verify is a list of 1 to 32 {finding, verdict: verified|rejected}"); const stored = this.d.board.auditFindings(audit.id); for (const item of input.verify as unknown[]) { const record = item && typeof item === "object" && !Array.isArray(item) ? item as Record : undefined; if (!record || Object.keys(record).some(key => key !== "finding" && key !== "verdict") || typeof record.finding !== "string" || (record.verdict !== "verified" && record.verdict !== "rejected")) throw new PreEffectToolRefusal("each verify entry is {finding: , verdict: verified|rejected}"); const refusal = verificationRefusal(stored.find(row => row.finding.id === record.finding), by); if (refusal) throw new PreEffectToolRefusal(`${record.finding.slice(0, 80)}: ${refusal}`); decisions.push({ finding: record.finding, verdict: record.verdict }); } if (new Set(decisions.map(d => d.finding)).size !== decisions.length) throw new PreEffectToolRefusal("a finding is decided once per call"); } if (input.settle !== undefined) { if (!Array.isArray(input.settle) || !input.settle.length || input.settle.length > 32) throw new PreEffectToolRefusal("settle is a list of 1 to 32 {finding, disposition: fixed|false_positive}"); const stored = this.d.board.auditFindings(audit.id); for (const item of input.settle as unknown[]) { const record = item && typeof item === "object" && !Array.isArray(item) ? item as Record : undefined; if (!record || Object.keys(record).some(key => key !== "finding" && key !== "disposition") || typeof record.finding !== "string" || !(SETTLEMENTS as readonly unknown[]).includes(record.disposition)) throw new PreEffectToolRefusal("each settle entry is {finding: , disposition: fixed|false_positive}"); const refusal = settlementRefusal(stored.find(row => row.finding.id === record.finding), by); if (refusal) throw new PreEffectToolRefusal(`${record.finding.slice(0, 80)}: ${refusal}`); settlements.push({ finding: record.finding, disposition: record.disposition as "fixed" | "false_positive" }); } if (new Set(settlements.map(item => item.finding)).size !== settlements.length) throw new PreEffectToolRefusal("a finding is settled once per call"); // A finding verified in this same call is not settled in it: the verification is a separate reader's decision and its result is read before the settlement. if (settlements.some(item => decisions.some(decision => decision.finding === item.finding))) throw new PreEffectToolRefusal("verify a finding and settle it in separate calls"); } check(); const now = this.d.board.audit(audit.id), nowTask = this.d.board.get(task.id); if (!now || !nowTask || nowTask.owner !== task.owner || nowTask.state !== task.state || JSON.stringify(now.units) !== JSON.stringify(audit.units)) throw new PreEffectToolRefusal("the audit changed while the report was checked; read it again and retry"); // One transaction: a unit report, its findings, the verifications and the settlements land together or not at all. const skipped = this.d.board.auditApply(audit.id, { units: writes ? units : undefined, findings: filed, decisions, ...(settlements.length ? { settlements } : {}), by }); if (skipped === undefined) throw new PreEffectToolRefusal("a finding was decided meanwhile; read the audit again and retry"); try { const rejected = new Set(decisions.filter(row => row.verdict === "rejected").map(row => row.finding)); const falsePositives = new Set(settlements.filter(row => row.disposition === "false_positive").map(row => row.finding)); const savedAudit = this.d.board.audit(audit.id); if (savedAudit?.task === nowTask.id && savedAudit.taskCreated === nowTask.created) { const saved = this.d.board.auditFindings(audit.id).filter(row => rejected.has(row.finding.id) && row.rejectedBy === by || falsePositives.has(row.finding.id) && row.settledAs === "false_positive" && row.settledBy === by); this.recordConsideredAfter(nowTask, saved.map(row => row.finding), "audit", savedAudit.ref); } } catch { this.releaseNotice(`task #${task.id}: considered rejection ledger unavailable`); } const full = this.d.board.audit(audit.id)!; return { ...this.auditView(full, true), ...(skipped.length ? { notUpdated: skipped } : {}) }; } /** #1328 T3: approve a merge observed outside the hub, without attributing a verdict to a reviewer. */ async adoptMerge(by: PeerId, id: unknown, pr: unknown, fence?: () => string | undefined): Promise<{ task: number; state: "approved" }> { const check = this.requestCheck(by, fence); const authority = () => { check(); if (by !== USER && (!this.configuredManualConductor(by) || !this.d.bus.isRostered(by))) throw new PreEffectToolRefusal("only the person or the current configured conductor may adopt a merge; ask the person to run ahub sdlc adopt-merge"); if (this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("merge adoption is unavailable in a private turn; finish that turn and retry ahub sdlc adopt-merge"); if (this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) throw new PreEffectToolRefusal("hub recovery, storage or task writes are held; clear the hold before retrying ahub sdlc adopt-merge"); }; authority(); if (!Number.isSafeInteger(pr) || (pr as number) <= 0) throw new PreEffectToolRefusal("merge adoption needs a positive PR number; run ahub sdlc adopt-merge --pr "); if (!Number.isSafeInteger(id) || (id as number) <= 0) throw new PreEffectToolRefusal("merge adoption needs a positive task id; run ahub sdlc adopt-merge --pr "); const task = this.d.board.get(id as number); if (!task) throw new PreEffectToolRefusal("merge adoption task does not exist; inspect ahub task list and choose the task to adopt"); const config = this.d.sdlc?.config() ?? sdlcConfig(undefined), head = this.reviewHead(task); const identity = (row: Task) => JSON.stringify([row, this.isPii(row)]); const before = identity(task), policy = JSON.stringify(config); const current = () => { authority(); const now = this.d.board.get(task.id); if (!now || identity(now) !== before || JSON.stringify(this.d.sdlc?.config() ?? sdlcConfig(undefined)) !== policy) throw new PreEffectToolRefusal("task, privacy or SDLC policy changed during merge adoption; reload the task and retry ahub sdlc adopt-merge"); if (this.isPii(now) || now.signals.includes("pii") || now.signals.includes("pii_path")) throw new PreEffectToolRefusal("a private task cannot send merge evidence to GitHub; keep its approval local through the person's review workflow"); return now; }; current(); if (task.draft) throw new PreEffectToolRefusal(`task #${task.id} is a ${task.state} intake draft; approve the intake through ahub intake approve before retrying ahub sdlc adopt-merge`); if (task.state === "proposed" || task.state === "backlog") throw new PreEffectToolRefusal(`task #${task.id} is ${task.state}; assign and accept it first, then retry ahub sdlc adopt-merge`); if (task.state === "approved" || task.state === "cancelled") throw new PreEffectToolRefusal(`task #${task.id} is ${task.state} and already closed; inspect ahub task show ${task.id} and choose an active task instead`); if (!head || !/^[a-f0-9]{40}$/.test(head)) throw new PreEffectToolRefusal("the task has no recorded full head; record its full commit SHA before retrying ahub sdlc adopt-merge"); const scope = this.repositories.scope(task.refs), repo = task.sdlc?.repo ?? (scope.key.startsWith("repo:") ? scope.key.slice("repo:".length) : undefined); if (!repo || this.repositories.scope({ repo }).key !== scope.key || task.sdlc?.pr !== undefined && task.sdlc.pr !== pr) throw new PreEffectToolRefusal("PR repository or number differs from the task's recorded artifact, or its repository is unknown; record its correct repository and PR before retrying ahub sdlc adopt-merge"); const receipt = { ...task.sdlc, stage: lifecycleStage(config, "merge"), repo, pr: pr as number, head }; const important = () => findingTally(findingsForHead(this.reviewFindingSets(current()), head)).openImportant > 0; if (important()) throw new PreEffectToolRefusal("open Important finding blocks merge adoption; resolve the finding and record its disposition before retrying ahub sdlc adopt-merge"); const deadline = performance.now() + 20_000; const run: SdlcGh = async (args, timeout, cwd, cap) => { current(); const remaining = deadline - performance.now(); if (remaining <= 0) throw new PreEffectToolRefusal("merge evidence read timed out; restore GitHub access and retry ahub sdlc adopt-merge"); const result = await (this.d.sdlc?.gh ?? sdlcGh)(args, Math.min(timeout ?? 10_000, remaining), cwd, cap); current(); return result; }; const evidence = await readAdoptMergeEvidence(receipt, run); current(); const gates = adoptMergeGates(evidence, head, requiredChecksFor(config, repo)); if (gates.length) throw new PreEffectToolRefusal(gates.join("; ")); const costDeadline = performance.now() + INLINE_MERGE_READBACK_DEADLINE_MS; const cost = evidence?.costSnapshot ? await readPrCostHistory(repo, pr as number, (args, timeout, cwd, cap) => { const remaining = costDeadline - performance.now(); current(); return remaining > 0 ? (this.d.sdlc?.gh ?? sdlcGh)(args, Math.min(timeout ?? remaining, remaining), cwd, cap).then(result => { current(); return result; }) : Promise.resolve({ code: 1, stdout: "" }); }, evidence.costSnapshot, head, task.history.find(entry => entry.event === "done")?.requestHead).then(pr => pr?.complete ? mergeCostFrom(pr) : undefined, () => undefined) : undefined; const latest = current(); const merge: ReadbackMergeRecord = { repo, pr: pr as number, head, at: Date.now(), state: "merged", ...(evidence?.mergeCommit ? { mergeCommit: evidence.mergeCommit } : {}), ...(cost ? { cost } : {}) }; const capacity = this.capacityBefore(latest); current(); // No await between the last authority/privacy/flow check and the sole approval write. const next = this.d.board.adoptMerge(latest.id, by, { ...receipt, mergeReadback: merge }, head, latest.history.length, HOST_MERGE_ADOPTION); this.cohorts.closed(next.id); this.ciWatchers.cancel(next.id); this.heldReviews.delete(next.id); this.writePlannerNotices(next, capacity, true); this.releaseNotice(`task #${next.id}: merged outside the hub; approved`); await this.releaseDependents(next); return { task: next.id, state: "approved" }; } private readonly mergesInFlight = new Set(); /** #786: who may ask for a guarded merge. The hub's own approval trigger acts as HUB; a peer must be the one configured conductor. */ private mergeAuthority(by: PeerId): boolean { if (isRemotePeerId(by)) return false; if (by === USER || by === HUB) return true; const holders = Object.entries(this.d.roles ?? {}).filter(([peer, roles]) => !isRemotePeerId(peer) && Array.isArray(roles) && roles.includes("conductor")).map(([actor]) => actor); return holders.length === 1 && holders[0] === by; } /** * #786 T1/T2: the guarded merge of one approved task. `sdlc.auto_merge` (or the repository's table) says whether it only reports (`dry-run`) or acts (`on`); * `opts.dryRun` forces a report. Every gate is re-read right now (`sdlc-merge.ts`); this method owns authority, privacy and the notices, which name the task * and the gates only (a PII task shows its stub and is never merged by the hub). Off/dry-run write nothing to the board; on-mode records gate refusals * and post-run host observations, claiming eligible post-MERGED remote cleanup and owner notices durably. */ async guardedMerge(by: PeerId, id: unknown, opts: { dryRun?: boolean; trigger?: "review" | "command" } = {}): Promise<{ task: number } & MergeView> { if (!this.mergeAuthority(by)) throw new Error("only the console user or the configured conductor may merge"); const task = this.need(id), label = `#${task.id}`; // the number only: a notice about a merge never carries a title (a PII task has none to show) const config = this.d.sdlc?.config() ?? sdlcConfig(undefined); const mode = opts.dryRun ? "dry-run" as const : mergeModeFor(config, task.sdlc?.repo); const refuse = (gate: string) => { if(mode==="on")this.recordMergeRefusal(task.id,by,[gate]); return { task: task.id, ...mergeView({ mode, decision: { refused: [gate] }, ran: false }) }; }; if (this.isPii(task)) return refuse("private task: a person merges"); if (mode === "off") return refuse("auto_merge is off for this repository"); if (this.mergesInFlight.has(task.id)) return refuse("a merge check for this task is already running"); const previous=task.sdlc?.merge; if(previous && !(opts.trigger==="command" && previous.state==="not_merged") && previous.repo===task.sdlc?.repo && previous.pr===task.sdlc.pr && previous.head===task.sdlc.reviewedHead) return refuse("merge attempt already recorded: inspect its result and any uncertain cleanup before acting"); // Ephemeral identity excludes merge progress so our own durable writes cannot rebind the observation. const artifactIdentity=(row:Task)=>JSON.stringify([row.sdlc?.repo,row.sdlc?.pr,row.sdlc?.issue,row.sdlc?.head,row.sdlc?.reviewedHead,row.sdlc?.localHead,row.refs.repo,row.refs.commit]); const initialArtifact=artifactIdentity(task); const artifactCurrent=()=>{const row=this.d.board.get(task.id);return !!row && artifactIdentity(row)===initialArtifact;}; this.mergesInFlight.add(task.id); try { const links = this.deliveryLinks(config), subject = links.find(link => link.id === task.id)!; const outcome = await guardedMerge({ mode, subject, state: task.state, taskState: n => this.d.board.get(n)?.state, config, tasks: links, run: this.d.sdlc?.gh ?? sdlcGh, readableMetadata: this.publicMetadataText, firstSubmittedHead: task.history.find(entry => entry.event === "done")?.requestHead, recordMerge: record=>this.recordMergeResult(task.id,by,record,artifactCurrent), beforeMerge: queue => { if (!this.mergeAuthority(by)) return "merge authority changed during the merge check: nothing was run"; // Only the links this queue read count: a change to one of those (a dependency artifact, an ordering edge, a relink, a new holder of an open PR) invalidates // that remote evidence, and any other task's change does not. Both sides are projected through the same queue, so a new holder of an open PR shows. const currentConfig = this.d.sdlc?.config() ?? sdlcConfig(undefined); const currentLinks = this.deliveryLinks(currentConfig), currentSubject = currentLinks.find(link => link.id === task.id); return currentSubject && workflowHash({ config: currentConfig, links: this.queueLinks(currentLinks, currentSubject, queue) }) === workflowHash({ config, links: this.queueLinks(links, subject, queue) }) ? undefined : "merge queue inputs changed during the merge check: nothing was run"; }, // Read synchronously at dispatch, after the last PR read: the task (state, receipt, privacy, dependencies, findings), the configuration and mode in force, and whether // the asker may still act and the hub may still write. Nothing is awaited between this read and the gh call. fresh: () => { const now = this.d.board.get(task.id), cfg = this.d.sdlc?.config() ?? sdlcConfig(undefined); const current = now && this.deliveryLinks(cfg).find(link => link.id === now.id); return now && current ? { subject: current, state: now.state, config: cfg, mode: opts.dryRun ? "dry-run" : mergeModeFor(cfg, now.sdlc?.repo), allowed: this.mergeAuthority(by) && !this.d.sweepHeld?.() && !this.d.bus.isRecoveryHeld && !this.d.bus.storageError } : undefined; } }); if(mode==="on" && !outcome.ran && "refused" in outcome.decision)this.recordMergeRefusal(task.id,by,outcome.decision.refused); if(outcome.result?.state==="merged") { try {this.mergeOwnerNotice(task.id,by,artifactCurrent);} catch {this.releaseNotice(`task ${label}: merge owner notice unconfirmed`);} } const view = mergeView(outcome); const head = (text?: string) => text ? text.slice(0, 8) : "unknown"; if (outcome.result && (this.isPii(this.d.board.get(task.id) ?? task) || this.d.privateTurn?.(by))) this.releaseNotice(`task ${label}: merge result withheld`); else if (outcome.result) this.releaseNotice(outcome.result.state === "merged" ? `task ${label}: merged (squash, commit ${head(outcome.result.mergeCommit)})` : `task ${label}: gh pr merge exited ${outcome.result.exit}; GitHub reports it ${outcome.result.state === "unknown" ? "unreadable" : "not merged"}`); else if (opts.trigger === "review") this.releaseNotice("action" in outcome.decision ? `task ${label}: auto-merge dry-run: would merge at ${head(outcome.decision.head)}` : `task ${label}: auto-merge refused: ${outcome.decision.refused.join("; ")}`); return { task: task.id, ...view }; } finally { this.mergesInFlight.delete(task.id); } } private recordMergeRefusal(id:number,by:PeerId,gates:string[]):void { const current=this.d.board.get(id); if(!current)return; const note=JSON.stringify({gates:gates.slice(0,32).map(g=>this.publicMetadataText(g)?g.slice(0,256):"merge gate withheld")}); if(!current.history.some(h=>h.by===HUB && h.event==="merge refused" && h.note===note)) this.d.board.update(id,HUB,"merge refused",{},note,{...(this.isPii(current)||this.d.privateTurn?.(by)?{withheld:true}:{})}); } /** Observe one eligible externally merged approved PR without mutating GitHub. */ async captureExternalMerge(id: number): Promise<"merged" | "closed" | "retry" | "skip"> { const task = this.d.board.get(id), config = this.d.sdlc?.config(), receipt = task?.sdlc; const repo = receipt?.repo, pr = receipt?.pr, head = task && this.reviewHead(task); const recorded = receipt?.merge?.state === "merged" ? receipt.merge : receipt?.mergeReadback?.state === "merged" ? receipt.mergeReadback : undefined; if (!task || task.state !== "approved" || this.isPii(task) || (task.owner && this.d.privateTurn?.(task.owner)) || !config || !repo || !pr || !head || !/^[a-f0-9]{40}$/.test(head) || this.repositories.scope(task.refs).key !== this.repositories.scope({ repo }).key || (recorded ? recorded.cost?.ciRuns != null || recorded.repo !== repo || recorded.pr !== pr || recorded.head !== head : mergeModeFor(config, repo) !== "off") || this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) return "skip"; const identity = JSON.stringify([task.history.length, task.updated, task.owner, receipt, config]); const current = () => { const now = this.d.board.get(id), policy = this.d.sdlc?.config(); return !!now && !this.isPii(now) && !(now.owner && this.d.privateTurn?.(now.owner)) && !this.d.sweepHeld?.() && !this.d.bus.isRecoveryHeld && !this.d.bus.storageError && JSON.stringify([now.history.length, now.updated, now.owner, now.sdlc, policy]) === identity; }; const deadline = performance.now() + MERGE_READBACK_DEADLINE_MS; const run: SdlcGh = (args, timeout, cwd, cap) => { const remaining = deadline - performance.now(); return current() && remaining > 0 ? (this.d.sdlc?.gh ?? sdlcGh)(args, Math.min(timeout ?? remaining, remaining), cwd, cap) : Promise.resolve({ code: 1, stdout: "" }); }; const evidence = await readSdlcPr(receipt!, run).catch(() => undefined); if (!current()) return "skip"; if (evidence?.state === "CLOSED") return "closed"; if (evidence?.state !== "MERGED" || evidence.head !== head) return "retry"; const cost = await readPrCostHistory(repo, pr, run, undefined, head, task.history.find(entry => entry.event === "done")?.requestHead).then(value => value?.complete ? mergeCostFrom(value) : undefined, () => undefined); if (!current()) return "skip"; const now = this.d.board.get(id)!; if (recorded) { if (!cost) return "retry"; const key = receipt!.merge === recorded ? "merge" : "mergeReadback"; this.d.board.update(id, HUB, "merge cost observed", { sdlc: { ...now.sdlc!, [key]: { ...recorded, cost } } }, undefined, {}, now.history.length); return "merged"; } const merge: ReadbackMergeRecord = { repo, pr, head, at: Date.now(), state: "merged", ...(evidence.mergeCommit ? { mergeCommit: evidence.mergeCommit } : {}), ...(cost ? { cost } : {}) }; this.d.board.update(id, HUB, "merge observed", { sdlc: { ...now.sdlc!, mergeReadback: merge } }, undefined, {}, now.history.length); return "merged"; } // ponytail: this in-memory schedule is lost on restart; only approvals still within 24 hours are retried. private readonly mergeReadbackSchedule = new Map(); private mergeReadbackRunning = false; async settleMergeReadbacks(now = Date.now()): Promise { if (this.mergeReadbackRunning || this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) return; this.mergeReadbackRunning = true; try { let reads = 0; // Unseen work goes first, then the least recently scheduled read, so a busy backlog cannot starve later tasks. const candidates = this.d.board.list().sort((a, b) => (this.mergeReadbackSchedule.get(a.id)?.next ?? -Infinity) - (this.mergeReadbackSchedule.get(b.id)?.next ?? -Infinity) || a.id - b.id); for (const task of candidates) { if (reads >= 3 || this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) break; const recorded = task.sdlc?.merge?.state === "merged" ? task.sdlc.merge : task.sdlc?.mergeReadback?.state === "merged" ? task.sdlc.mergeReadback : undefined; if (task.state !== "approved" || this.isPii(task) || !task.sdlc?.repo || !task.sdlc.pr || (recorded ? recorded.cost?.ciRuns != null : !!task.sdlc.merge || !!task.sdlc.mergeReadback)) { this.mergeReadbackSchedule.delete(task.id); continue; } const approval = task.history.findLastIndex(entry => entry.event === "approved" || entry.event === "merged outside the hub" || entry.event === "done" && entry.by === task.owner); const at = task.history[approval]?.at; if (approval < 0 || at === undefined || now < at || now - at >= 24 * 60 * 60_000) { this.mergeReadbackSchedule.delete(task.id); continue; } const previous = this.mergeReadbackSchedule.get(task.id); if (previous?.approval === approval && (previous.closed || now < previous.next)) continue; this.mergeReadbackSchedule.set(task.id, { approval, next: now + 10 * 60_000, closed: false }); reads++; const outcome = await this.captureExternalMerge(task.id).catch(() => "retry" as const); if (outcome === "closed") this.mergeReadbackSchedule.set(task.id, { approval, next: now + 10 * 60_000, closed: true }); } } finally { this.mergeReadbackRunning = false; } } private mergeRecordCurrent(id:number,by:PeerId,record:MergeRecord,artifactCurrent:()=>boolean):Task|undefined { const now=this.d.board.get(id); return artifactCurrent() && now && now.sdlc?.repo===record.repo && now.sdlc.pr===record.pr && now.sdlc.reviewedHead===record.head && (!approvalBinding(now) || approvalBinding(now)!.current && approvalBinding(now)!.head === record.head) && (!this.reviewHead(now) || this.reviewHead(now) === record.head) && now.state==="approved" && !this.isPii(now) && !this.d.privateTurn?.(by) && this.mergeAuthority(by) && !this.d.bus.isRecoveryHeld && !this.d.bus.storageError ? now : undefined; } /** Save host facts without ever rebinding an old result to a replacement artifact. */ private recordMergeResult(id: number, by: PeerId, record: MergeRecord,artifactCurrent:()=>boolean): boolean { const now=this.d.board.get(id); if(!now)return false; const allowed=this.mergeRecordCurrent(id,by,record,artifactCurrent)!==undefined; // A bounded old-attempt fact remains history even after a relink or privacy/authority change. No remote prose or branch name is retained. const note=JSON.stringify(record); if(allowed) { if(JSON.stringify(now.sdlc!.merge)!==note)this.d.board.update(id,HUB,"merge result",{sdlc:{...now.sdlc!,merge:record}},note); } else if(!now.history.some(h=>h.by===HUB && h.event==="merge result (detached)" && h.note===note)) { this.d.board.update(id,HUB,"merge result (detached)",{},note,{...(this.isPii(now)||this.d.privateTurn?.(by)?{withheld:true}:{})}); } // Board observers run synchronously. A claim write can itself revoke authority, privacy or artifact identity. return this.mergeRecordCurrent(id,by,record,artifactCurrent)!==undefined && JSON.stringify(this.d.board.get(id)?.sdlc?.merge)===note; } /** Claim before publishing: a lost acknowledgement remains unknown and is never automatically sent twice. */ private mergeOwnerNotice(id:number,by:PeerId,artifactCurrent:()=>boolean):void { const task=this.d.board.get(id),record=task?.sdlc?.merge; if(!task || !record || record.state!=="merged" || !record.mergeCommit || record.ownerNotice!=="not_started")return; const claimed:MergeRecord={...record,ownerNotice:"claimed"}; if(!this.recordMergeResult(id,by,claimed,artifactCurrent))return; const current=this.mergeRecordCurrent(id,by,claimed,artifactCurrent); if(!current)return; const view=this.publicView(current); if(view.title==="[pii]")return; const owner=typeof view.owner==="string"?view.owner:undefined; const body=`Task #${id}: GitHub reports the PR merged (commit ${record.mergeCommit.slice(0,8)}). Remote branch cleanup: ${record.cleanup}. Remove your local worktree and local branch when safe; the hub leaves them in place.`; // Public projection and a synchronous claim observer must not let stale owner text escape. const last=this.mergeRecordCurrent(id,by,claimed,artifactCurrent); if(!last || (last.owner??undefined)!==owner)return; let sent=false; try { if(owner && owner!==USER)sent=this.d.bus.publish(newEnvelope(HUB,body,{to:[owner],kind:"task",refs:{task:String(id),taskRecipient:"owner"}})).includes(owner); else {this.d.notify(body);sent=true;} } catch { /* The durable claim keeps an uncertain publication from being repeated. */ } this.recordMergeResult(id,by,{...claimed,ownerNotice:sent?"sent":"unknown"},artifactCurrent); } /** * #786 T3 (AC1): mirror a saved verdict as ONE `COMMENT` review on the head it was given for (`sdlc-mirror.ts`). Gated by the same `auto_merge` setting as the merge: off posts * nothing, dry-run only reports, on posts. Never awaited by the verdict and never throws: the returned promise always resolves, and a failure is a notice naming the task number. * The note goes out only when it is public: not a PII task, not withheld by the review screen, not in a private turn and matching no private pattern; otherwise the review is its headline alone. */ private mirrorVerdict(task: Task, by: PeerId, verdict: MirrorVerdict, head: string | undefined, note: string | undefined, withheld: boolean): Promise { try { const repo = task.sdlc?.repo, pr = task.sdlc?.pr; if (!repo || !pr || !head) return Promise.resolve(); const mode = mergeModeFor(this.d.sdlc?.config() ?? sdlcConfig(undefined), repo); if (mode === "off") return Promise.resolve(); const text = note && !withheld && !this.isPii(task) && !this.d.privateTurn?.(by) && this.publicMetadataText(note) ? note : undefined; const label = `#${task.id}`; return Promise.resolve().then(() => mirrorToGitHub({ repo, pr, head, verdict, task: task.id, reviewer: by, ...(text !== undefined ? { note: text } : {}), mode, run: this.d.sdlc?.gh ?? sdlcGh })).then(out => { if (out.reason === "posted") this.releaseNotice(`task ${label}: ${verdict} mirrored to GitHub as a comment review`); else if (out.reason === "post failed") this.releaseNotice(`task ${label}: verdict mirror could not be posted`); else if (out.reason === "dry-run") this.releaseNotice(`task ${label}: verdict mirror dry-run: would post one ${verdict} comment review at ${head.slice(0, 8)}`); }).catch(() => this.releaseNotice(`task ${label}: verdict mirror unavailable`)); } catch { return Promise.resolve(); } } /** After an approving verdict, never blocking or failing it: the check runs on a later tick and reports through a notice. `after` (the verdict mirror) settles first, so the review lands before the PR can merge. */ private autoMerge(task: Task, after?: Promise): void { try { if (!task.sdlc?.repo || !task.sdlc.pr || mergeModeFor(this.d.sdlc?.config() ?? sdlcConfig(undefined), task.sdlc.repo) === "off") return; const label = `#${task.id}`; // Promise.resolve().then also catches a synchronous throw, which would otherwise escape a microtask. void Promise.resolve(after).then(() => this.guardedMerge(HUB, task.id, { trigger: "review" })).catch(() => this.releaseNotice(`task ${label}: auto-merge check unavailable`)); } catch { /* an approval never fails because of the merge check */ } } async releaseReadiness(repo: string, liveIssues: number[]) { const report = await readReleaseReadiness(this.d.cwd, repo, liveIssues, { gh: this.d.sdlc?.gh, reportPolicy: this.d.sdlc?.reportPolicy }); if (report.documents) report.documents.documents = report.documents.documents.map(d => { if (d.path && (!this.nameable(d.path) || matchesPolicy(this.d.cwd, d.path, this.d.piiPaths ?? [], true))) { const { path: _privatePath, ...metadata } = d; return metadata; } return d; }); // #481 AC12: release interval, lead time from approval to release and hotfix rate, from the shipped releases' recorded history; unknown stays null (never 0). // Releases whose scope holds private work are left out, like the per-release report does. const rowsNow = this.d.board.list(); const publicShipped = this.d.board.releases().filter(release => !rowsNow.some(task => task.release === release.id && this.isPii(task))); const metrics = publicShipped.some(release => release.state === "shipped") ? releaseMetrics(publicShipped, rowsNow.filter(task => !this.isPii(task))) : undefined; if (metrics) report.releaseMetrics = metrics; const audit = this.auditLine(); if (audit) report.securityAudit = audit; const trains = this.d.board.releases().filter(release => release.train && ["active", "frozen"].includes(release.state)); if (trains.length) { const planned = trains.map(release => { try { return this.releaseReport(USER, release.id); } catch { return { release: { id: release.id }, readiness: { trigger: "waiting", tasks: [], blockers: ["release scope unavailable"] } }; } }); if (planned.some(row => row.readiness.blockers.length)) { report.sourceReady = false; report.blockers.push("planned release scope is not approved or available"); } return { ...report, trains: planned }; } return report; } private workflowView(task: Task) { return criteriaView(this.d.sdlc?.config() ?? sdlcConfig(undefined), task, t => this.isPii(t)); } workflowExport(id: unknown): Record { const task = this.need(id), config = this.d.sdlc?.config() ?? sdlcConfig(undefined), stage = task.sdlc?.stage ?? config.stages[0] ?? "spec"; // Off keeps the #257 export bytes; schema 2 (criteria, no workflow framing) is for an enabled or retired-setting lifecycle. if (config.mode === "off" && !config.workflow) { const legacy = { id: task.id, state: task.state, stage, ...(this.isPii(task) ? { private: true } : { phase: null }) }; return { schema: 1, workflow: "none", state: legacy, stateHash: workflowHash(legacy), sourceHash: workflowHash(config) }; } const state = { id: task.id, state: task.state, stage, ...(this.isPii(task) ? { private: true } : { criteria: this.workflowView(task) ?? null }) }; return { schema: 2, state, stateHash: workflowHash(state), sourceHash: workflowHash(config) }; } private readonly planReads = new Map(); // ponytail: consent expires on restart because a refused readback cannot first mutate the task's history. // A durable host observation journal can retain safe consent across lifetimes without reviving pending invalidations. private readonly departureGeneration = crypto.randomUUID(); private readonly invalidatedPlanDepartures = new Set(); private readonly observedPlans = new Map>(); private planIdentity(task: Task): string { return JSON.stringify([task.refs, task.sdlc, task.plan, task.owner, task.reviewer, task.state, this.isPii(task), this.d.sdlc?.config()]); } private planReadIdentity(task: Task): string { return JSON.stringify([task.sdlc?.repo, task.sdlc?.pr, task.refs.repo, planFingerprint(task.plan ?? {})]); } private planPaths(task: Task, key: "paths" | "out_of_scope" = "paths"): string[] | undefined { if (!task.sdlc?.repo) return; // Resolve the artifact slug first: it may warm the canonical project's previously unnamed identity. const artifact = this.repositories.scope({ repo: task.sdlc.repo, paths: task.refs.paths }); const scope = this.repositories.scope(task.refs); if (scope.key !== artifact.key) return; return task.plan?.[key]?.map(path => scope === this.repositories.project ? this.projectPath(path) : this.repositories.relativePath(scope, path)); } private planScopeIdentity(task: Task): string { const paths = this.planPaths(task); // Warm verified aliases before capturing the scope identity. const scope = this.repositories.scope(task.refs); return planFingerprint({ key: scope.key, root: scope.root ?? null, aliases: [...scope.aliases].sort(), repo: task.refs.repo ?? null, absoluteRefs: (task.refs.paths ?? []).filter(isAbsolute).sort(), paths: paths ?? null }); } private validPlanDepartures(task: Task): NonNullable[] { const invalidated = task.history.findLastIndex(h => h.planDepartureInvalidated && !h.planDeparture); if (this.invalidatedPlanDepartures.has(task.id)) return []; const latest = task.history.findLastIndex(h => h.by === USER && h.event === "plan departure accepted" && h.planDeparture); return latest > invalidated && task.history[latest]!.planDeparture!.generation === this.departureGeneration && task.history[latest]!.planDeparture!.scope === this.planScopeIdentity(task) ? [task.history[latest]!.planDeparture!] : []; } /** * #1403 A2: whether this PR needs a recorded security pass, from the same complete file inventory plan conformance reads. The record is the latest one on a verdict of this task, bound to the head it * reviewed; `proposed` is the pass on the verdict being written (not on the board yet). A PII task and an off lifecycle compute nothing. */ private securityView(task: Task, evidence: PrEvidence | undefined, proposed?: SecurityPassRecord): SecurityPassView | undefined { const config = this.d.sdlc?.config(); if (!config || config.mode === "off" || !config.security || this.isPii(task)) return undefined; const recorded = proposed ?? task.history.findLast(entry => entry.securityPass && !entry.withheld && (entry.event === "approved" || entry.event === "changes_requested"))?.securityPass; return securityPassView(config.security, evidence, recorded); } private planReport(task: Task, evidence?: PrEvidence) { const rawReport = planConformance(this.isPii(task) ? undefined : this.planPaths(task), this.isPii(task) ? undefined : evidence, this.planPaths(task, "out_of_scope") ?? task.plan?.out_of_scope); const safe = [...rawReport.outside, ...rawReport.untouched].every(path => this.publicMetadataText(path)); const report: PlanConformance = safe ? rawReport : { state: "unknown", head: rawReport.head, outside: [], untouched: [] }; const fingerprint = planFingerprint(task.plan ?? {}); const observation = task.history.find(h => h.planObservation?.repo === task.sdlc?.repo && h.planObservation?.pr === task.sdlc?.pr)?.planObservation ?? this.observedPlans.get(task.id); const revision = task.history.findLast(h => h.planRevision)?.planRevision?.revision; const acceptance = evidence && this.validPlanDepartures(task).findLast(item => item.repo === task.sdlc?.repo && item.pr === task.sdlc?.pr && item.head === evidence.head && item.revision === (revision ?? 0) && item.fingerprint === fingerprint && JSON.stringify([...item.paths].sort()) === JSON.stringify([...evidence.paths].sort())); return { ...report, accepted: !!acceptance, earlierPushes: "unknown" as const, ...(observation && observation.repo === task.sdlc?.repo && observation.pr === task.sdlc?.pr ? { revisionsAfterFirstObservedPush: Math.max(0, (revision ?? 0) - observation.revision) } : {}) }; } private capturePlanRead(task: Task, evidence: PrEvidence | undefined): void { if ((this.d.sdlc?.config().mode ?? "off") === "off" || !evidence || this.isPii(task) || !task.sdlc?.repo || !task.sdlc.pr) return; if (this.planReads.size >= 256 && !this.planReads.has(task.id)) this.planReads.delete(this.planReads.keys().next().value!); this.planReads.set(task.id, { identity: this.planReadIdentity(task), evidence }); const accepted = task.history.findLast(h => h.by === USER && h.planDeparture)?.planDeparture; if (accepted && evidence.pathsComplete === true && JSON.stringify([...accepted.paths].sort()) !== JSON.stringify([...evidence.paths].sort())) this.invalidatedPlanDepartures.add(task.id); this.capturePlanHead(task, evidence.head); } private capturePlanHead(task: Task, head: string): void { if ((this.d.sdlc?.config().mode ?? "off") === "off" || this.isPii(task) || !task.sdlc?.repo || !task.sdlc.pr) return; if (this.planReads.get(task.id)?.evidence.head !== head) this.planReads.delete(task.id); const accepted = task.history.findLast(h => h.by === USER && h.planDeparture)?.planDeparture; if (accepted && (accepted.head !== head || accepted.repo !== task.sdlc.repo || accepted.pr !== task.sdlc.pr)) this.invalidatedPlanDepartures.add(task.id); if (!task.history.some(h => h.planObservation?.repo === task.sdlc?.repo && h.planObservation?.pr === task.sdlc?.pr) && (!this.observedPlans.has(task.id) || this.observedPlans.get(task.id)?.repo !== task.sdlc.repo || this.observedPlans.get(task.id)?.pr !== task.sdlc.pr)) { // ponytail: this is first observed push, not a true push event. Earlier pushes stay unknown; upgrade to a webhook/Actions push receipt. if (this.observedPlans.size >= 256) this.observedPlans.delete(this.observedPlans.keys().next().value!); this.observedPlans.set(task.id, { repo: task.sdlc.repo, pr: task.sdlc.pr, head, revision: task.history.findLast(h => h.planRevision)?.planRevision?.revision ?? 0, fingerprint: planFingerprint(task.plan ?? {}) }); } } private planObservation(task: Task): Pick { if ((this.d.sdlc?.config().mode ?? "off") === "off") return {}; const observation = this.observedPlans.get(task.id); const lastAcceptance = task.history.findLastIndex(h => h.by === USER && h.planDeparture); return { ...(observation && observation.repo === task.sdlc?.repo && observation.pr === task.sdlc?.pr && !task.history.some(h => h.planObservation?.repo === observation.repo && h.planObservation.pr === observation.pr) ? { planObservation: observation } : {}), ...(this.invalidatedPlanDepartures.has(task.id) && !task.history.slice(lastAcceptance + 1).some(h => h.planDepartureInvalidated) ? { planDepartureInvalidated: true as const } : {}), }; } async acceptPlanDeparture(by: PeerId, id: unknown, head: unknown, reason: unknown): Promise { if (by !== USER) throw new PreEffectToolRefusal("only the person may accept a plan departure"); if (typeof head !== "string" || !/^[a-f0-9]{40}$/.test(head) || typeof reason !== "string" || !reason.trim() || reason.length > 2048) throw new PreEffectToolRefusal("departure acceptance requires a full head and a bounded reason"); const initial = this.need(id, false, true), identity = this.planIdentity(initial), scope = this.planScopeIdentity(initial), history = initial.history.length; const valid = () => { const now = this.need(id, false, true); if (isClosedTaskState(now.state) || identity !== this.planIdentity(now) || scope !== this.planScopeIdentity(now) || history !== now.history.length) throw new PreEffectToolRefusal("task changed during departure readback"); return now; }; if (this.isPii(initial)) throw new PreEffectToolRefusal("private PR file evidence is unavailable; amend the private plan instead"); const read: SdlcGh = (args, timeout, cwd, cap) => { valid(); return (this.d.sdlc?.gh ?? sdlcGh)(args, timeout, cwd, cap); }; const evidence = initial.sdlc && await readSdlcPr(initial.sdlc, read); valid(); if (!evidence || completePlanInventory(evidence) === undefined) throw new PreEffectToolRefusal("complete PR file inventory unknown"); if (evidence.head !== head) throw new PreEffectToolRefusal("departure acceptance head is not the current PR head"); if (this.planReport(initial, evidence).state !== "departure") throw new PreEffectToolRefusal("current plan conformance is not a known departure; amend unknown scope or coverage first"); const note = sanitize(reason.replace(/\s+/g, " ").trim()); const withheld = await this.withholds("note", note, initial); const current = valid(); this.capturePlanRead(current, evidence); const next = this.d.board.update(current.id, USER, "plan departure accepted", {}, note, { withheld: withheld || undefined, ...this.planObservation(current), planDeparture: { generation: this.departureGeneration, scope, repo: current.sdlc!.repo!, pr: current.sdlc!.pr!, head, revision: current.history.findLast(h => h.planRevision)?.planRevision?.revision ?? 0, fingerprint: planFingerprint(current.plan ?? {}), paths: [...evidence.paths] } }); this.invalidatedPlanDepartures.delete(current.id); return next; } async lifecycleStatus(id: unknown, refresh = true): Promise { const task = this.need(id), config = this.d.sdlc?.config() ?? sdlcConfig(undefined), identity = this.planIdentity(task); const valid = () => { const now = this.need(id, false, true); if (this.planIdentity(now) !== identity || now.history.length !== task.history.length) throw new PreEffectToolRefusal("task changed during lifecycle readback"); return now; }; const deadline = performance.now() + 20_000; const read: SdlcGh = (args, timeout, cwd, cap) => { valid(); const remaining = deadline - performance.now(); return remaining > 0 ? (this.d.sdlc?.gh ?? sdlcGh)(args, Math.min(timeout ?? 10_000, remaining), cwd, cap) : Promise.resolve({ code: 1, stdout: "" }); }; const evidence = task.sdlc && !this.isPii(task) && refresh && config.mode !== "off" ? await readSdlcPr(task.sdlc, read, true) : undefined; valid(); const accepted = task.sdlc?.acceptance; const edit = accepted && !this.isPii(task) && refresh && config.mode !== "off" ? await readSpecEdit(accepted.repo, accepted.issue, read) : undefined; const integrity = config.mode !== "off" ? publicTestIntegrity(task.sdlc && evidence && !this.isPii(task) ? await readTestIntegrity(task.sdlc, evidence, read) : this.unknownTestIntegrity(this.isPii(task)), this.publicMetadataText) : undefined; const evalResult = task.sdlc && !this.isPii(task) ? await readEvalFor(config, evidence, task.sdlc.repo, read) : undefined; const current = valid(); if (this.planIdentity(current) !== this.planIdentity(task) || current.history.length !== task.history.length) throw new PreEffectToolRefusal("task changed during lifecycle readback"); this.capturePlanRead(current, evidence); return sdlcStatus(config, current.sdlc, evidence, this.workflowView(current), edit, this.isPii(current) ? [] : this.reviewFindingSets(current), current.refs.commit, config.mode !== "off" ? this.planReport(this.d.board.get(current.id)!, evidence) : undefined, integrity, evalResult, this.securityView(current, evidence)); } /** #481 S1: only build work starts from an accepted spec. */ private specGated(task: Task): boolean { return (this.d.sdlc?.config().mode ?? "off") !== "off" && (task.class === "implement" || task.class === "bulk_edit"); } private specText(task: Task, state: Exclude, verb: "blocked" | "advice"): string { const issue = task.sdlc?.issue; const diagnostic = verb === "blocked" && !this.isPii(task) && state === "missing" ? buildEntryDiagnostic(task) : undefined; const why = diagnostic ?? (issue ? SPEC_STATE_TEXT[state].replace("", String(task.id)).replace("", String(issue)) : "spec issue unknown: record repo and issue with hub_sdlc_record, then the person accepts it with ahub sdlc accept"); return `task #${task.id}: SDLC build entry ${verb}: ${why}`; } /** The person's acceptance of the task's spec issue at its current body (#481 S1); identity and edit times only. */ acceptSpec(by: PeerId, id: unknown, spec: { repo?: unknown; issue: unknown; edit: SpecEdit }): Task { if (by !== USER) throw new PreEffectToolRefusal("spec acceptance is the person's: run ahub sdlc accept in a terminal"); const task = this.need(id, false, true, true), config = this.d.sdlc?.config() ?? sdlcConfig(undefined); const repo = spec.repo ?? task.sdlc?.repo; if (task.sdlc?.issue !== undefined && task.sdlc.issue !== spec.issue) throw new PreEffectToolRefusal(`task #${task.id} links issue #${task.sdlc.issue}; relink it with hub_sdlc_record before accepting another`); const next = sdlcReceipt({ repo, issue: spec.issue }, task.sdlc, config); if (!next.repo || !next.issue) throw new PreEffectToolRefusal("spec acceptance needs the repository (owner/repository) and the issue number"); next.acceptance = { repo: next.repo, issue: next.issue, lastEditedAt: spec.edit.lastEditedAt, updatedAt: spec.edit.updatedAt, acceptedAt: Date.now() }; return this.d.board.update(task.id, USER, "spec accepted", { sdlc: next }, `issue #${next.issue}, body last edited ${spec.edit.lastEditedAt ?? "never"}`); } private readonly specCarries = new WeakMap(); /** Opaque host proof only: a virtual receipt never changes the stored row or its flow. */ private stagedSpec(by: PeerId, task: Task, token?: object, preEffect = true): Task { if (!token) return task; try { const proof = this.specCarries.get(token); if (!proof || proof.by !== by || proof.task !== task.id) throw new Error("unknown or consumed host spec carry proof"); if (!proof.current() || task.sdlc?.repo !== proof.commit.acceptance.repo || task.sdlc.issue !== proof.commit.acceptance.issue || this.specAcceptanceScope(task.refs) !== proof.scope || !this.specAcceptancePublic(task)) throw new Error("task or source changed during staged spec admission"); return { ...task, sdlc: { ...task.sdlc, acceptance: proof.commit.acceptance } }; } catch (error) { const message = error instanceof Error ? error.message : "staged spec admission changed"; throw new (preEffect ? PreEffectToolRefusal : Error)(`${message}; inspect the current task and held deliveries before repeating this action`); } } /** Called only at an admitted outer write; later failures keep ordinary post-effect error semantics. */ private commitSpecCarry(caller: PeerId, token: object | undefined, ...args: Parameters): Task { if (!token) return this.d.board.update(...args); const [id, by, event, patch, note, extra, revision, codeSymbolsAuthority, adoptionAuthority] = args; const stored = this.need(id, false, false); if (by !== caller && !(by === HUB && ["integration requested", "integration unresolved", "integrated"].includes(event))) throw new Error("spec carry event actor differs from its admitted caller; inspect the current task and held deliveries before repeating this action"); this.stagedSpec(caller, { ...stored, ...patch, refs: { ...stored.refs, ...patch.refs } }, token, false); const proof = this.specCarries.get(token)!; const next = this.d.board.updateWithSpecAcceptance(proof.commit, HOST_SPEC_ACCEPTANCE_CARRY, id, by, event, patch, note, extra, revision ?? stored.history.length, codeSymbolsAuthority, adoptionAuthority); this.specCarries.delete(token); return next; } /** No cold repository probes or source task hydration participate in consent authority. */ private specAcceptanceScope(refs: TaskRefs): string | undefined { return this.repositories.cachedScope(refs)?.key ?? (!refs.repo && !(refs.paths ?? []).some(isAbsolute) ? this.repositories.project.key : undefined); } private specAcceptancePublic(task: Pick): boolean { try { const normalized = cleanRefs(task.refs); if (["repo", "branch", "commit"].some(key => task.refs[key as keyof TaskRefs] !== normalized[key as keyof TaskRefs]) || JSON.stringify(task.refs.paths ?? []) !== JSON.stringify(normalized.paths ?? [])) return false; return !task.signals.includes("pii") && !task.signals.includes("pii_path") && this.publicMetadataText(JSON.stringify(task.refs)) === true && !(task.refs.paths ?? []).some(path => this.reviewPathPrivate(path)); } catch { return false; } } /** Carry uses the existing owner/reviewer/stage-planner authority, without admitting a stage write. */ private specAcceptanceActor(by: PeerId, task: Task, receipt = task.sdlc, stageInput?: Record): boolean { if (by === USER) return true; if (!this.d.bus.isRostered(by)) return false; let role = by === task.owner ? ownerRoleOfClass(task.class) : undefined; if (stageInput) { const config = this.d.sdlc?.config() ?? sdlcConfig(undefined), definition = receipt && stageDefinition(config, receipt.stage); const planners = this.taskPlanner(task), planner = planners.includes(by); const plannerStage = Object.keys(stageInput).every(key => ["stage", "repo", "issue"].includes(key)) && (definition?.actor === "planner" || definition?.actor === "owner/planner") && planner; if (by !== task.owner && by !== task.reviewer && !plannerStage) return false; if (config.mode === "enforce" && config.definitions) { const actor = definition?.actor; const acts = actor === "owner" ? by === task.owner : actor === "reviewer" ? by === task.reviewer : actor === "planner" ? planner : actor === "owner/planner" && (by === task.owner || planner); if (!acts) return false; } role ??= by === task.reviewer ? "reviewer" : "planner"; } return !!role && (!this.d.roles || this.d.roles[by]?.includes(role) === true); } /** One strict host observation serves both the carry decision and the ordinary spec verdict. */ private async readSpecAcceptance(by: PeerId, task: Task, receipt = task.sdlc, allowCarry = true, stageInput?: Record): Promise { const unchanged: SpecGateRead = { task }; const accepted = receipt?.acceptance; if (accepted) return { ...unchanged, edit: !this.isPii(task) ? await readSpecEdit(accepted.repo, accepted.issue, this.d.sdlc?.gh) : undefined }; if (!allowCarry || !receipt?.repo || !receipt.issue || receipt.repo !== task.sdlc?.repo || receipt.issue !== task.sdlc?.issue) return unchanged; const check = this.requestCheck(by), scope = this.specAcceptanceScope(task.refs); const policy = () => { const routing = this.d.routing(); return JSON.stringify([this.d.roles, this.d.deny, this.d.piiPaths, routing.constraints, routing.signals.pii_patterns, this.d.sdlc?.config()]); }; const actorPublic = () => !this.d.privateTurn?.(by) && this.specAcceptanceActor(by, task, receipt, stageInput); if (!scope || isClosedTaskState(task.state) || !actorPublic() || !this.specAcceptancePublic(task) || this.publicMetadataText(receipt.repo) !== true) return unchanged; const eligible = (source: SpecAcceptanceCandidate) => { const consent = storedSpecAcceptance(source.acceptance); return !source.withheld && source.id < task.id && localSupersedingTask(source.supersededBy) === task.id && this.specAcceptancePublic(source) && this.specAcceptanceScope(source.refs) === scope && typeof source.repo === "string" && source.repo.toLowerCase() === receipt.repo!.toLowerCase() && source.issue === receipt.issue && !!consent && consent.repo.toLowerCase() === receipt.repo!.toLowerCase() && consent.issue === receipt.issue; }; const snapshot = (value: Task) => JSON.stringify([value.created, value.state, value.class, value.reviewer, value.planner, value.refs, value.signals]); const beforeTask = snapshot(task), sources = this.d.board.specAcceptanceCandidates(task.id), beforePolicy = policy(); const planners = JSON.stringify(this.taskPlanner(task)); if (!sources.complete || !sources.rows.some(eligible)) return unchanged; const edit = await readSpecEdit(receipt.repo, receipt.issue, this.d.sdlc?.gh); check(); if (this.specMoved(task)) return unchanged; const currentTask = this.need(task.id, false, true); if (snapshot(currentTask) !== beforeTask || !actorPublic() || !this.specAcceptancePublic(currentTask) || policy() !== beforePolicy || JSON.stringify(this.taskPlanner(task)) !== planners || this.specAcceptanceScope(task.refs) !== scope) return unchanged; const current = this.d.board.specAcceptanceCandidates(task.id); if (!current.complete || JSON.stringify(current.rows) !== JSON.stringify(sources.rows)) return unchanged; for (const source of current.rows) { if (!eligible(source)) continue; const acceptance = carriedSpecAcceptance(storedSpecAcceptance(source.acceptance)!, { repo: receipt.repo, issue: receipt.issue }, edit); if (!acceptance) continue; Object.freeze(acceptance); // The virtual receipt must not expose mutable host-consent fields. const token = Object.freeze({}); this.specCarries.set(token, { by, task: task.id, scope, commit: { source: source.id, cancellationRevision: source.cancellationRevision, acceptance }, current: () => { check(); const now = this.need(task.id, false, true), latest = this.d.board.specAcceptanceCandidates(task.id); const donor = latest.rows.find(row => row.id === source.id); return now.history.length === task.history.length && now.owner === task.owner && JSON.stringify(now.sdlc) === JSON.stringify(task.sdlc) && snapshot(now) === beforeTask && actorPublic() && policy() === beforePolicy && JSON.stringify(this.taskPlanner(now)) === planners && latest.complete && JSON.stringify(latest.rows) === JSON.stringify(sources.rows) && !!donor && eligible(donor); } }); return { task: { ...task, sdlc: { ...task.sdlc!, acceptance } }, edit, carry: token }; } return { ...unchanged, edit }; } /** Build entry with a live readback of the spec's body edit time (#481 S1): enforce refuses, advise notifies, off does nothing. */ async specGate(by: PeerId, id: unknown, prospectiveRefs?: TaskRefs): Promise { requireLocalTaskPeer(by); const task = this.need(id, false, true); if (!this.specGated(task) || task.owner !== by && by !== USER) return; // accept reports its own refusals const result = await this.readSpecAcceptance(by, task, task.sdlc, !prospectiveRefs || this.specAcceptanceScope(prospectiveRefs) === this.specAcceptanceScope(task.refs)); if (this.specMoved(task)) return; this.specVerdict(result.task, result.task.sdlc?.issue ? specState(result.task.sdlc, result.edit) : "missing"); return result.carry ? result : undefined; } /** #481 S1: a build stage change by an agent re-reads the body edit time first, as accept does. */ async specStageGate(by: PeerId, id: unknown, input: unknown): Promise { requireLocalTaskPeer(by); const task = this.need(id, false, true), config = this.d.sdlc?.config() ?? sdlcConfig(undefined); if (config.mode === "off" || by === USER || !input || typeof input !== "object" || !("stage" in input)) return; let next: ReturnType; // #509a: `deliverables` ride in the receipt but are not a lifecycle field: recordSdlc splits them off, so the gate reads the same receipt it will record. const { deliverables: _carried, ...lifecycleInput } = input as Record; try { next = sdlcReceipt(lifecycleInput, task.sdlc, config, VERSION); } catch { return; } // recordLifecycle reports an invalid receipt const definition = stageDefinition(config, next.stage); if (next.stage === task.sdlc?.stage || !definition || canonicalStage(definition.base) !== "build") return; const result = await this.readSpecAcceptance(by, task, next, true, lifecycleInput); if (this.specMoved(task)) return; if (result.carry) next.acceptance = result.task.sdlc!.acceptance; this.specVerdict(result.task, next.issue ? specState(next, result.edit) : "missing"); return result.carry ? result : undefined; } /** * The task a spec readback started from changed while it was awaited (flow, link, acceptance, owner or privacy): the * reading belongs to other work. Enforce refuses before any write; advise drops the stale advice. */ private specMoved(before: Task): boolean { const now = this.need(before.id, false, true); if (now.history.length === before.history.length && now.owner === before.owner && this.isPii(now) === this.isPii(before) && JSON.stringify(now.sdlc ?? null) === JSON.stringify(before.sdlc ?? null)) return false; if (this.d.sdlc?.config().mode === "enforce") throw new PreEffectToolRefusal(`task #${before.id}: changed during the spec readback; nothing was recorded, retry on current work`); return true; } private specVerdict(task: Task, state: SpecState): void { if (state === "current") return; if (this.d.sdlc?.config().mode === "enforce") throw new PreEffectToolRefusal(this.specText(task, state, "blocked")); this.d.notify(this.specText(task, state, "advice")); } private unknownTestIntegrity(privateTask = false): TestIntegrity { return { applicability: "unknown", redFirst: "unknown", fileState: "unknown", modifiedTests: [], blockers: [privateTask ? "test integrity: private evidence unavailable" : "test integrity: current evidence unknown"] }; } /** The eval record the last approval-time lifecycle read produced for a task; consumed by the verdict that follows it. */ private readonly evalRecords = new Map(); private async lifecycleGate(task: Task, transition: "review" | "approval", reviewedHead?: string, findings?: readonly ReviewFindingSet[], refileHead?: RefileHeadGuard, securityPass?: SecurityPassRecord): Promise { const config = this.d.sdlc?.config() ?? sdlcConfig(undefined); if (config.mode === "off") return; const receipt = task.sdlc && { ...task.sdlc, ...(reviewedHead ? { reviewedHead } : {}) }; const approvalHead = transition === "approval" ? reviewedHead ?? this.ownerReviewHead(task) ?? this.findingHead(task) : undefined; const guardedHead = !!refileHead || !!approvalHead && !!receipt?.repo && !!receipt.pr && !this.isPii(task); // Compare raw head identity on both sides; `task` may carry an uncommitted identityLink. // Completion state/history races stay with completionCurrent's existing post-readback fence. const identity = (value: Task) => JSON.stringify([value.id, value.owner, value.reviewer, this.isPii(value), value.refs.repo, value.refs.commit, value.refs.branch, value.sdlc?.repo, value.sdlc?.pr, value.sdlc?.head, value.sdlc?.localHead, value.sdlc?.reviewedHead]); const beforeHeadRead = guardedHead ? identity(this.need(task.id, false, true)) : undefined; const deadline = performance.now() + 20_000; const read: SdlcGh = (args, timeout, cwd, cap) => { const current = this.need(task.id, false, true); if (current.history.length !== task.history.length || current.owner !== task.owner || current.reviewer !== task.reviewer || this.isPii(current) !== this.isPii(task)) return Promise.resolve({ code: 1, stdout: "" }); const remaining = deadline - performance.now(); return remaining > 0 ? (this.d.sdlc?.gh ?? sdlcGh)(args, Math.min(timeout ?? 10_000, remaining), cwd, cap) : Promise.resolve({ code: 1, stdout: "" }); }; const evidence = receipt && !this.isPii(task) ? await readSdlcPr(receipt, read, true) : undefined; const currentHead = receipt && !this.isPii(task) && (refileHead || approvalHead) && !evidence?.head ? await readSdlcPrHead(receipt, read) : evidence?.head; if (beforeHeadRead !== undefined) { const current = this.need(task.id, false, true); if (identity(current) !== beforeHeadRead) throw new PreEffectToolRefusal(`task #${task.id}: task or review head changed during PR readback; reload and retry`); } if (refileHead) { if (!refileHead.recorded || !currentHead) throw this.reviewHeadMoveRefusal(task.id, refileHead.recorded); if (currentHead !== refileHead.recorded) throw this.reviewHeadMoveRefusal(task.id, refileHead.recorded, currentHead); } else if (approvalHead && currentHead && currentHead !== approvalHead) throw this.reviewHeadMoveRefusal(task.id, approvalHead, currentHead); const integrity = publicTestIntegrity(receipt && evidence && !this.isPii(task) ? await readTestIntegrity(receipt, evidence, read) : this.unknownTestIntegrity(this.isPii(task)), this.publicMetadataText); const evalResult = receipt && !this.isPii(task) ? await readEvalFor(config, evidence, receipt.repo, read) : undefined; const draftApproval = transition === "approval" && receipt?.repo && receipt.pr && evidence?.draft === true && evidence.review !== "changes_requested" && approvalHead && evidence.head === approvalHead ? await readReviewReadiness(receipt, approvalHead, read, requiredChecksFor(config, receipt.repo)) : undefined; const current = this.need(task.id, false, true); if (config.mode === "enforce" && (current.history.length !== task.history.length || current.owner !== task.owner || current.reviewer !== task.reviewer || current.state !== task.state)) throw new PreEffectToolRefusal(`task #${task.id}: changed during lifecycle readback; retry on current work`); // Advise may continue on the current task, but evidence from its previous link cannot admit that task's review. if (current.history.length !== task.history.length || current.owner !== task.owner || current.reviewer !== task.reviewer || current.state !== task.state || this.isPii(current) !== this.isPii(task)) return; this.capturePlanRead(current, evidence); const planReport = this.planReport(current, evidence); const status = sdlcStatus(config, receipt, evidence, this.workflowView(current), undefined, this.isPii(current) ? [] : findings ?? this.reviewFindingSets(current), current.refs.commit, planReport, integrity, evalResult, this.securityView(current, evidence, transition === "approval" ? securityPass : undefined)); // #481 S5: review entry keeps the eval gate's own blockers (its check, and in enforce its evidence gaps), like the premature-review rule does for the ordinary required checks. const evalNames = evalRequiredChecks(config, evidence).filter(name => !config.requiredChecks.includes(name)); const evalBlocker = (blocker: string) => evalNames.some(name => blocker.startsWith(`required check ${name}:`)) || evalGapBlockers(status.evalGate).includes(blocker); const approvalDeferral = draftApproval?.ready === true && draftApproval.draftApprovalEligible === true && evidence?.unresolved === 0; const blockers = transition === "review" ? [...new Set([...status.blockers.filter(blocker => ["lifecycle stage definition unknown", "issue identity missing", "PR identity missing", "current PR evidence unknown", "PR is not open", "local gate on current head missing or failed"].includes(blocker) || blocker.startsWith("test integrity:") || evalBlocker(blocker)), ...(status.entry ?? []), ...(status.exit ?? [])])] : status.blockers.filter(blocker => !approvalDeferral || !( blocker === "required check check (macos-latest): not successful on current head" || blocker === "GitHub review approval missing or changes requested" && evidence?.review !== "changes_requested" || blocker === "review requests pending or unknown" && evidence?.pendingReviews !== null )); if (config.mode === "enforce" && blockers.length) throw new PreEffectToolRefusal(`task #${task.id}: SDLC ${transition} blocked: ${blockers.join("; ")}`); // #481 S5: the recorded pass rate and suite version ride the approval note; a code-only PR, an unconfigured gate or an unreported value records nothing. const gate = status.evalGate; if (transition === "approval" && gate?.state === "passed" && gate.passRate !== undefined && gate.suite !== undefined && !this.isPii(task)) this.evalRecords.set(task.id, `Eval gate: ${gate.check} passed at ${evidence!.head.slice(0, 12)}, pass rate ${gate.passRate}, suite ${gate.suite}`); else this.evalRecords.delete(task.id); const advice = [...new Set([...blockers, ...planConformanceBlockers(planReport), ...testIntegrityBlockers(integrity), ...evalAdvice(status.evalGate), ...securityPassBlockers(status.securityPass)])]; if (config.mode === "advise" && advice.length) this.d.notify(`task ${this.publicTitle(task)}: SDLC ${transition} advice: ${this.isPii(task) ? "private lifecycle evidence unknown" : advice.join("; ")}`); return evidence; } private need(id: unknown, open = false, preEffect = false, allowBacklog = false): Task { // Callers are models (#70): an id is a whole number or a digit string, never an array that Number() would accept. const n = typeof id === "number" ? id : typeof id === "string" && /^\s*\d+\s*$/.test(id) ? Number(id) : NaN; if (!Number.isInteger(n)) throw new (preEffect ? PreEffectToolRefusal : Error)(`id must be a task number, not ${(typeof id === "number" ? String(id) : JSON.stringify(id ?? null)).slice(0, 60)}`); const task = this.d.board.get(n); if (!task) throw new (preEffect ? PreEffectToolRefusal : Error)(`no task #${n}`); if (task.state === "backlog" && !allowBacklog) throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${n} is in backlog: a planner or person must pull it into To Do first (hub_backlog_pull)`); // Handing a task to someone else only makes sense while there is work left on it. if (open && !OPEN.includes(task.state)) throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${task.id} is ${task.state}: it can no longer change hands`); return task; } private readonly pendingClaims = new Map(); private readonly reviewedAdmissions = new Map(); private isBuildTask(task: Task): boolean { const config = this.d.sdlc?.config() ?? sdlcConfig(undefined); if (["implement", "bulk_edit"].includes(task.class)) return true; const base = task.sdlc ? stageDefinition(config, task.sdlc.stage)?.base : undefined; return base === "build" || base === "implement"; } async acceptReviewed(by: PeerId, id: unknown, plan?: unknown, refs?: unknown): Promise { const requestCheck = this.requestCheck(by); const metadata = acceptRefs(refs); const task = this.need(id, false, true); this.mine(task, by, "owner", true); if (by !== USER && task.needsPerson) throw new PreEffectToolRefusal(PERSON_RUN_ACCEPT(task.id)); // #1176: before any spec or plan-review work is spent on it const proposedPlan = plan == null ? undefined : cleanPlan(plan, (task.profile ?? "dev") === (this.d.profile ?? "dev") ? this.d.profileData ?? task.profile ?? "dev" : task.profile ?? "dev", (this.d.sdlc?.config().mode ?? "off") !== "off"); this.validatePlanSources(proposedPlan && Object.keys(proposedPlan).length ? proposedPlan : task.plan); this.acceptanceCapacity(task, 0, "check"); // #1080: an urgent task may still take unaccepted offers; `accept` does that, after its gates if (metadata && !this.isPii(task) && (!this.nameable(metadata.repo!) || looksSecret(metadata.repo!) || this.aboutPrivatePath("", metadata.repo!, task))) throw new PreEffectToolRefusal("this repository metadata is private or sensitive and is not kept"); let draft = metadata ? { ...task, refs: { ...task.refs, ...metadata } } : task; this.warmRepository(draft); if ((this.d.sdlc?.config() ?? sdlcConfig(undefined)).mode === "off" || !this.isBuildTask(task)) return this.prepareAcceptedWorktree(this.accept(by, id, plan, metadata), by, requestCheck); const spec = await this.specGate(by, id, draft.refs); if (spec?.carry) draft = metadata ? { ...spec.task, refs: { ...spec.task.refs, ...metadata } } : spec.task; await this.planEntryGate(by, draft, spec?.carry); requestCheck(); const current = this.need(id, false, true); this.mine(current, by, "owner", true); if (current.history.length !== task.history.length || current.owner !== task.owner) throw new PreEffectToolRefusal("task changed during build admission"); this.reviewedAdmissions.set(current.id, { flow: current.history.length, owner: current.owner }); try { return await this.prepareAcceptedWorktree(this.accept(by, id, plan, metadata, spec?.carry), by, requestCheck); } finally { this.reviewedAdmissions.delete(current.id); } } /** Spec and plan readbacks share the caller's original task snapshot until the final acceptance write. */ private async planEntryGate(by: PeerId, task: Task, specCarry?: object): Promise { const mode = (this.d.sdlc?.config() ?? sdlcConfig(undefined)).mode; if (mode === "off" || !this.isBuildTask(task)) return; const gap = await this.planReviewGap(task); if (mode === "advise" && !task.sdlc?.planReview?.scope) this.releaseNotice(`task ${this.publicTitle(task)}: cost scope unspecified`); const current = this.stagedSpec(by, this.need(task.id, false, true), specCarry); this.mine(current, by, "owner", true); if (current.history.length !== task.history.length || current.owner !== task.owner) throw new PreEffectToolRefusal("task changed during plan readback"); if (gap && mode === "enforce") throw new PreEffectToolRefusal(this.entryDiagnostic(current, gap) ?? gap); if (gap) this.releaseNotice(`task ${this.publicTitle(current)}: ${gap}`); } /** * What counts toward `owner`'s WIP, split for a refusal and for #1080: `offered` is work handed to the owner that it has not accepted * (state proposed), `reserved` is ownerless planner-pulled work held for it, and `accepted` is everything the owner is actually carrying * (in progress, changes requested, in review). */ private wipSplit(owner: PeerId, except: number): { accepted: Task[]; offered: Task[]; reserved: Task[] } { const open = this.d.board.list().filter(other => other.id !== except && !["backlog", "approved", "cancelled"].includes(other.state) && (other.owner === owner || !other.owner && other.reserved === owner && this.plannerPullRecord(other)?.pull)); return { accepted: open.filter(other => other.owner === owner && other.state !== "proposed"), offered: open.filter(other => other.owner === owner && other.state === "proposed"), reserved: open.filter(other => !other.owner), }; } private static isUrgent(task: Pick): boolean { return (task.priority ?? (task.signals?.includes("urgent") ? 0 : 2)) === 0; } /** #1080: an offer an urgent accept may take back. Never accepted or started work, never another urgent task, never person-pinned work. */ private displaceable(offer: Task): boolean { return offer.state === "proposed" && !!offer.owner && !offer.pinned && !Tasks.isUrgent(offer) && !taskHasStarted(offer); } /** * #1080: the owner is at its limit only because of offers it never accepted, so an urgent task takes the slot. The newest offers go back to * routing (ownerless, in To Do) and the planners are told. Called only from `accept`, immediately before its write. */ private displaceOffers(urgent: Task, owner: PeerId, offers: readonly Task[]): void { for (const offer of offers) { // A planner-pulled offer also holds a counted reservation (`plannerWip` counts an ownerless proposed task reserved for the owner with pull history), so clearing the owner alone frees no slot. `decline` clears it the same way. const pulled = this.plannerPullRecord(offer)?.pull === true; const next = this.d.board.update(offer.id, HUB, "unassigned", { owner: null, reviewer: null, ...(pulled ? { reserved: null } : {}) }, `displaced by urgent task #${urgent.id}: ${owner} was at its WIP limit with this offer unaccepted`, {}, offer.history.length); this.offered.delete(offer.id); this.releaseNotice(`task #${offer.id}: displacement cohort cleanup unavailable`, () => this.cohorts.leave(offer.id)); this.withdrawRoleRequest(offer, next, "owner"); this.withdrawRoleRequest(offer, next, "reviewer"); this.releaseNotice(`task #${offer.id}: displacement notice unavailable`, () => { const body = `Task #${offer.id} was taken back from ${owner}: urgent task #${urgent.id} (priority 0 or marked urgent) needed ${owner}'s WIP slot and #${offer.id} was only offered, never accepted. It is ownerless in To Do and routes again; plan it again if it should wait for ${owner}.`; this.d.notify(body); for (const planner of this.taskPlanner(offer)) this.d.bus.publish(newEnvelope(HUB, sanitize(body), { to: [planner], kind: "task", refs: { task: String(offer.id) }, ...(this.isPii(offer) ? { private: true } : {}) })); }); } } /** * `urgent`: "refuse" (default) never displaces; "check" only tells whether an urgent accept could (a pre-check before a later write); "displace" * performs it. Only `accept` displaces. */ private acceptanceCapacity(task: Pick & Partial>, excludePending = 0, urgent: "refuse" | "check" | "displace" = "refuse"): void { const owner = task.owner ?? task.reserved; if (!owner) return; if ((task.state === "in_progress" || task.state === "changes_requested") && task.history) { let boundary = 0, previous: PeerId | null | undefined; task.history.forEach((entry, index) => { if (entry.owner !== undefined) { if (entry.owner !== previous) boundary = index; previous = entry.owner; } else if (OWNERSHIP_EVENTS.has(entry.event)) { boundary = index; previous = undefined; } }); if (task.history.slice(boundary).some(entry => entry.event === "accepted" && (entry.by === owner || entry.by === USER))) return; } const limit = this.wipLimit(owner), pending = Math.max(0, (this.pendingClaims.get(owner) ?? 0) - excludePending); const used = this.wip(owner, task.id) + pending; if (used < limit) return; const split = this.wipSplit(owner, task.id), ids = (rows: readonly Task[]) => rows.map(row => `#${row.id}`).join(", ") || "none"; // #1080: an urgent task that is the owner's own offer may take back only as many never-accepted offers as it needs, newest first. Anything else refuses. if (urgent !== "refuse" && task.state === "proposed" && task.owner === owner && Tasks.isUrgent(task as Pick)) { const need = used + 1 - limit; const takeable = split.offered.filter(offer => this.displaceable(offer)) .sort((a, b) => handedAt(b) - handedAt(a) || b.id - a.id); if (need > 0 && takeable.length >= need) { if (urgent === "displace") { this.displaceOffers(task as Task, owner, takeable.slice(0, need)); // Defense in depth (#1080): no displacement path may leave the owner over its limit. Clearing the reservation above makes this unreachable today; if it ever fires, the offers are already back in To Do and only the accept is refused. const after = this.wip(owner, task.id) + pending; if (after >= limit) throw new Error(`planner WIP capacity for ${owner}: limit ${limit}; the offers taken back for urgent task #${task.id} are back in To Do but did not free a slot (WIP is now ${after}), so it stays offered; ask the planner to check ${owner}'s reservations, then accept it again`); } return; } } const open = [...split.accepted, ...split.offered, ...split.reserved].sort((a, b) => a.id - b.id); const parts = [`accepted ${ids(split.accepted)}`, `offered, not yet accepted ${ids(split.offered)}`, ...(split.reserved.length ? [`reserved, not yet offered ${ids(split.reserved)}`] : [])]; const next = split.accepted.length >= limit ? `finish or hand back an accepted task first` : `decline an offered task you will not take, or finish an accepted one; an urgent task may take back an offer you have not accepted`; throw new PreEffectToolRefusal(`planner WIP capacity for ${owner}: limit ${limit}; open tasks ${ids(open)} (${parts.join("; ")})${pending ? `; pending claims ${pending}` : ""}; ${next}`); } private validatePlanSources(plan: TaskPlan = {}): void { for (const id of plan.sources ?? []) if (!this.d.intake?.sourceKnown(id)) { throw new PreEffectToolRefusal(`unknown source ${id}; list registered ids with ahub source list`); } } /** * With a plan, the owners of overlapping tasks get it as a ride-along line, and an overlap only the plan reveals is * announced like one found at assignment (issue #31). */ accept(by: PeerId, id: unknown, plan?: unknown, refs?: unknown, specCarry?: object): Task { requireLocalTaskPeer(by); const metadata = acceptRefs(refs); const task = this.stagedSpec(by, this.need(id, false, true), specCarry); this.mine(task, by, "owner", true); this.ready(task, true); // #1176: a person-run leg is never an agent's to accept, whatever offer or owner it carries from before it was marked. if (by !== USER && task.needsPerson) throw new PreEffectToolRefusal(PERSON_RUN_ACCEPT(task.id)); if (task.state !== "proposed" && task.state !== "changes_requested" && task.state !== "in_progress") throw new PreEffectToolRefusal(`task #${task.id} is ${task.state}: cannot move to in_progress`); // Models send null or {} for an optional field they leave empty: neither replaces a plan. const given = plan == null ? undefined : cleanPlan(plan, (task.profile ?? "dev") === (this.d.profile ?? "dev") ? this.d.profileData ?? task.profile ?? "dev" : task.profile ?? "dev", (this.d.sdlc?.config().mode ?? "off") !== "off"); // File-list intent still replaces the old lists; omitted budget keys retain the planner-reviewed scope. const cleaned = given && Object.keys(given).length ? { ...cleanCostPlan(task.plan ?? {}), ...given } : undefined; this.validatePlanSources(cleaned ?? task.plan); this.studyDispatchCheck(task, task.owner ?? undefined); this.declaredNeedCheck(task, task.owner ?? by); // the owner's capability, also when the console user accepts on its behalf (`mine` admits USER) this.acceptanceCapacity(task, 0, "check"); // S1 spec acceptance and S9 plan review are independent prerequisites; retain S1's missing-spec refusal first. if (this.specGated(task) && this.d.sdlc?.config().mode === "enforce" && specState(task.sdlc, undefined) === "missing") throw new PreEffectToolRefusal(this.specText(task, "missing", "blocked")); if ((this.d.sdlc?.config() ?? sdlcConfig(undefined)).mode === "enforce" && this.isBuildTask(task)) { const readback = this.reviewedAdmissions.get(task.id); this.reviewedAdmissions.delete(task.id); if (!readback || readback.flow !== task.history.length || readback.owner !== task.owner) throw new PreEffectToolRefusal("current plan-review readback required before acceptance"); } if (this.d.sdlc?.config().mode === "enforce" && task.sdlc?.planReview && !task.sdlc.planReview.scope && given && Object.keys(cleanCostPlan(given)).length) throw new PreEffectToolRefusal("legacy plan cost scope is unspecified; record a scoped planner review before acceptance"); if (this.d.sdlc?.config().mode === "enforce" && task.sdlc?.planReview?.scope && JSON.stringify(cleanCostPlan(cleaned ?? task.plan ?? {})) !== JSON.stringify(task.sdlc.planReview.scope)) { throw new PreEffectToolRefusal("plan cost scope changed; record a new planner review before acceptance"); } // A task's signals are fixed when it is proposed: text that matches a PII pattern cannot be let in afterwards. if (cleaned && !this.isPii(task) && this.isPii({ signals: this.signalsFor({ title: "", detail: planText(cleaned), refs: {}, plan: cleaned }) })) { throw new PreEffectToolRefusal("this plan matches a PII pattern and is not kept: other owners would see it"); } if (metadata && !this.isPii(task) && (!this.nameable(metadata.repo!) || looksSecret(metadata.repo!) || this.aboutPrivatePath("", metadata.repo!, task))) throw new PreEffectToolRefusal("this repository metadata is private or sensitive and is not kept"); const draft = { ...task, refs: { ...task.refs, ...metadata }, ...(cleaned ? { plan: cleaned } : {}) }; this.warmRepository(draft); const repositoryChanged = this.repositories.scope(task.refs).key !== this.repositories.scope(draft.refs).key; const before = new Set(this.overlapHits(task).map((h) => h.task.id)); this.studyDispatchCheck(task, task.owner ?? undefined); // #1115: a hub-sandboxed peer cannot run `git worktree add`, so for work that declares a worktree the hub makes it here, before any write. Anything that throws below clears it again. const undoWorktree = this.hubWorktreeFor(task, task.owner ?? by); let next: Task; try { this.acceptanceCapacity(task, 0, "displace"); // #1080: every gate has passed; synchronous from here to the accept write next = this.linkOnWrite(this.commitSpecCarry(by, specCarry, task.id, by, "accepted", { state: "in_progress", ...(cleaned ? { plan: cleaned } : {}), ...(metadata ? { refs: metadata } : {}) })); // #723: refs.repo may have just arrived } catch (error) { undoWorktree?.(); throw error; } this.captureOwnerAcceptance(next); this.d.notify(`task ${this.publicTitle(next)} accepted by ${by}`); if (repositoryChanged) this.cohorts.leave(next.id); if (cleaned || metadata) { const hits = this.overlapHits(next); this.formCohort(next, hits); const fresh = hits.filter((h) => !before.has(h.task.id)); if (fresh.length) this.announceOverlap(next, fresh); this.tellEarlierOwners(next, hits); } return next; } /** * Put `task` and the open tasks it overlaps into one cohort (issue #107). A silent cohort that an owner without a * verified context path joins speaks again, and its members hear so. */ private formCohort(task: Task, hits: ReturnType): void { if (!task.owner || this.isPii(task)) return; const coordinate = this.coordinationModes.get(task.id); const coordinated = this.d.coordination ? hits.filter(hit => this.coordinationModes.get(hit.task.id) === coordinate) : hits; const before = this.cohorts.of(task.id)?.revision; const joined = this.cohorts.join(task, coordinated.map((h) => h.task), ownerGen, handedAt, !this.d.coordination || coordinate === true); if (!joined) return; const c = joined.cohort; if (joined.formed || c.revision !== before) { this.d.recordCohort?.({ id: c.id, event: joined.formed ? "formed" : "joined", silent: c.silent, tasks: [...c.members.keys()].sort((a, b) => a - b), owners: [...new Set([...c.members.values()].map((m) => m.owner))].sort() }); // A shadow split prediction for the pair that just overlapped, named owner or not (issue #109): for the record only. const shadow = this.splitShadow(task, task.owner); if (shadow) this.d.recordSplit?.(task.id, shadow, "cohort"); } if (joined.lifted) this.announceLift(c, `${task.owner} cannot be shown the others' changes`); } /** Members of a cohort that is no longer silent may message each other again. */ announceLift(cohort: Cohort, why: string): void { const owners = [...new Set([...cohort.members.values()].map((m) => m.owner))]; this.d.notify(`turn-free cohort #${cohort.id} (${owners.join(", ")}) is no longer silent: ${why}`); this.d.recordCohort?.({ id: cohort.id, event: "lifted", silent: false, tasks: [...cohort.members.keys()].sort((a, b) => a - b), owners: [...owners].sort() }); // Members still at work hear it, with the completed-change notices the silence held (they replace the integration // step that will not run); a member whose task closed is not started on a turn for it (#106). for (const m of cohort.members.values()) { const t = this.d.board.get(m.task); if (m.owner === USER || m.owner === HUB || !t || !OPEN.includes(t.state)) continue; const evidence = this.heldEvidence(cohort, t); this.whileOpen(m.owner, m.task, [`Task #${m.task}: turn-free silence is lifted for the overlapping work of ${owners.filter((o) => o !== m.owner).join(", ")} (${why}). Settle overlaps with them via hub_send, as usual.`, evidence ?? ""].filter(Boolean).join("\n")); } cohort.held.clear(); } /** Text a done result carries besides the board line (issue #107): held notices when no integration ran. */ private readonly doneNotes = new Map(); takeDoneNote = (id: number): string | undefined => { const note = this.doneNotes.get(id); this.doneNotes.delete(id); const task = this.d.board.get(id); return [note, task ? this.planDriftText(task, "done") : ""].filter(Boolean).join("\n") || undefined; }; /** #572 AC3: what the owner's `hub_task_done` result adds while the project root checkout is on a task branch. */ checkoutNote = (): string | undefined => { const warning = mainCheckoutWarning(this.d.cwd, this.publicMetadataText); return warning ? `Note: ${warning}.` : undefined; }; /** * #1115, #1129: the hub makes the worktree of a hub-sandboxed owner for write-class work (`implement`, `bulk_edit`) and for any work that declares `needs_worktree`. Returns a function that clears it again, or * undefined when there is nothing to clear (another peer, a read-only class that did not declare it, a PII task, or a worktree an earlier accept already made). A failure refuses the * accept before any board write and names the cause and the next step; nothing is left behind. */ private hubWorktreeFor(task: Task, peer: PeerId): (() => void) | undefined { const port = this.d.taskWorktree; if (!port || peer === USER || peer === HUB || !port.applies(peer) || this.isPii(task) || !(task.signals.includes("needs_worktree") || writesRepository(task.class))) return undefined; const made = port.create({ peer, task: task.id }); if (!made.ok) throw new PreEffectToolRefusal(`task #${task.id} needs its own git worktree and the hub could not make one for ${peer}: ${made.reason}; nothing was created, so no branch ref is left behind. Decline the task so the hub offers it to a peer that makes its own worktree`); return made.created ? () => { try { port.remove({ peer, task: task.id }); } catch { /* the accept error that got us here is the one reported */ } } : undefined; } /** The hub-made worktree of the task's owner, for the accept answer: where to edit, and what the hub does at `hub_task_done`. */ worktreeNote(task: Task, peer: PeerId): string | undefined { const found = this.d.taskWorktree?.describe(peer, task.id); return found ? [`Worktree: the hub made ${found.path} on branch ${found.branch} for this task. Edit files there only; do not run git. At hub_task_done the hub stages, commits and pushes it for you.`, this.dependencyNote(task, peer)].filter(Boolean).join("\n") : undefined; } private dependencyNote(task: Task, peer: PeerId): string | undefined { const state = this.d.taskWorktree?.dependencyState?.(peer, task.id); return state ? `Task #${task.id} dependencies ${state.ready ? "prepared" : `not prepared: ${state.reason}`}. Full checks stay with CI and the remote runner.` : undefined; } /** Only fixed readiness/cause text for this peer's current public work reaches its next prompt. */ dependencyNotes(peer: PeerId): string | undefined { return this.d.board.list().filter(task => task.owner === peer && task.state === "in_progress" && !this.isPii(task)) .map(task => this.dependencyNote(task, peer)).filter(Boolean).join("\n") || undefined; } private async prepareAcceptedWorktree(task: Task, actor: PeerId, requestCheck: () => void): Promise { const port = this.d.taskWorktree; const peer = task.owner ?? actor; if (!port?.prepareDependencies || !port.preparesDependencies?.(peer) || !port.describe(peer, task.id)) return task; const acceptance = this.ownerAcceptance(task)?.index; const current = () => { try { requestCheck(); const row = this.d.board.get(task.id); return !!row && row.created === task.created && row.owner === peer && row.state === "in_progress" && !this.isPii(row) && this.ownerAcceptance(row)?.index === acceptance; } catch { return false; } }; await port.prepareDependencies({ peer, task: task.id, current }); // Acceptance is already a board effect. Do not describe a lost request as pre-effect. if (!current()) throw new Error(`task #${task.id} changed owner, session or privacy during dependency preparation; read pending notices and call hub_task_list before continuing`); return this.d.board.get(task.id)!; } /** * #1115: at `hub_task_done` the hub commits and pushes a hub-sandboxed peer's worktree and answers the refs the done carries. Undefined when the peer made no * hub worktree for this task (it commits itself). A refused commit or push is a pre-effect refusal that names the cause and the next step: the board is untouched. */ async worktreeHandoff(by: PeerId, id: unknown, refs: unknown): Promise { const port = this.d.taskWorktree; if (!port || by === USER || by === HUB || !port.applies(by)) return undefined; const task = this.need(id, false, true); this.mine(task, by, "owner", true); if (this.isPii(task) || !port.describe(by, task.id)) return undefined; const requestCheck = this.requestCheck(by), revision = task.history.length; const current = () => { try { requestCheck(); const row = this.d.board.get(task.id); return !!row && row.created === task.created && row.owner === by && row.state === task.state && row.history.length === revision && !this.isPii(row) && !this.d.privateTurn?.(by) && !this.observerExcluded(by) && !this.d.sweepHeld?.() && !this.d.bus.isRecoveryHeld && !this.d.bus.storageError && !!port.describe(by, task.id); } catch { return false; } }; if (!current()) throw new PreEffectToolRefusal("managed handoff authority unavailable; inspect the task and retry hub_task_done"); const result = await port.commitAndPush({ peer: by, task: task.id, title: task.title, current }); if (!result.ok) { const message = `hub_task_done for task #${task.id}: ${result.reason}`; if (result.uncertain) throw new Error(message); throw new PreEffectToolRefusal(message); } const stillCurrent = () => { if (!current()) throw new Error("managed handoff authority changed after the commit; inspect the task and GitHub before retrying"); }; stillCurrent(); if (result.note) this.doneNotes.set(task.id, result.note); let repo: string | undefined, pr: number | undefined; if (result.pushed && !task.sdlc?.pr) { repo = githubOriginRepository(this.d.cwd); const named = task.sdlc?.repo ?? task.refs.repo; if (!repo || named && named.toLowerCase() !== repo || this.d.repository && this.d.repository.toLowerCase() !== repo) throw new Error("managed branch was pushed but the project GitHub origin is unavailable or changed; inspect the origin and retry hub_task_done"); let issue: { repo: string; issue: number } | undefined; try { issue = this.planIssueIdentity(task); } catch { throw new Error("managed branch was pushed but its issue identity is ambiguous; inspect the task before retrying hub_task_done"); } if (issue && issue.repo.toLowerCase() !== repo) throw new Error("managed branch was pushed but the spec issue belongs to another repository; inspect the task before retrying hub_task_done"); if (!this.publicMetadataText(JSON.stringify({ repo, branch: result.branch, ...(issue ? { issue: issue.issue } : {}) }))) throw new Error("managed branch was pushed but PR identity is not public; inspect the task before retrying hub_task_done"); const verifiedRepo = repo; const authority = () => { stillCurrent(); if (githubOriginRepository(this.d.cwd) !== verifiedRepo) throw new Error("managed origin changed after the push; inspect GitHub before retrying"); }; try { pr = await managedTaskPullRequest({ repo, branch: result.branch, commit: result.commit, task: task.id, ...(this.publicMetadataText(task.title) ? { title: task.title } : {}), ...(issue ? { issue: issue.issue } : {}), current: authority }, this.d.sdlc?.gh ?? sdlcGh); } catch (error) { throw new Error(`managed branch was pushed; ${error instanceof Error && this.publicMetadataText(error.message) ? error.message : "PR outcome is unavailable; inspect GitHub before retrying hub_task_done"}`); } authority(); } const handed: ManagedHandoffRefs = { ...cleanRefs(refs), commit: result.commit, branch: result.branch }; Object.defineProperty(handed, MANAGED_HANDOFF, { value: { task: task.id, owner: by, revision, commit: result.commit, branch: result.branch, ...(repo && pr ? { repo, pr } : {}) } }); return handed; } /** Commit the managed owner worktree for a check and bind its exact head through the board. */ async worktreeForCheck(by: PeerId, id: number, current: () => boolean): Promise { const port = this.d.taskWorktree; if (!port || !port.applies(by) || !port.describe(by, id)) return undefined; const task = this.need(id, false, true); this.mine(task, by, "owner", true); if (task.state !== "in_progress" || this.isPii(task) || !current()) throw new PreEffectToolRefusal("check unavailable"); const result = await port.commitAndPush({ peer: by, task: id, title: task.title, current }); // A commit or push can have landed even when the request loses authority during an await. if (!result.ok) { const reason = `managed worktree check: ${result.reason.replaceAll("hub_task_done", "hub_check_start")}`; if (result.uncertain) throw new Error(reason); throw new PreEffectToolRefusal(reason); } if (!current()) throw new Error("check unavailable: task authority changed after the worktree commit; read hub_task_show before retrying"); const fresh = this.d.board.get(id); if (!fresh || fresh.history.length !== task.history.length) throw new Error("check unavailable: task changed after the worktree commit; read hub_task_show before retrying"); if (fresh.refs.commit === result.commit && fresh.refs.branch === result.branch) return fresh; return this.d.board.update(id, HUB, "check worktree committed", { refs: { commit: result.commit, branch: result.branch } }, undefined, {}, fresh.history.length); } /** Decline or cancel: clear the hub-made worktree and its empty branch. Uncommitted work is kept and reported, never force-removed. */ private releaseHubWorktree(task: Task, peer: PeerId | null | undefined): void { const port = this.d.taskWorktree; if (!port || !peer || peer === USER || peer === HUB || !port.applies(peer)) return; this.releaseNotice(`task #${task.id}: the hub-made worktree could not be cleared`, () => { const removal = port.remove({ peer, task: task.id }); if (removal.kept) this.d.notify(`task #${task.id}: ${removal.kept}`); }); } /** * `capacity` (#531): the owner has no room right now, so the decline excludes it only from this move's own reroute * (below), never from a later reroute or planner pull. Without it, a decline is a lasting refusal (`excluded()`), and so * is every older row, which has no such field. */ async decline(by: PeerId, id: unknown, reason?: string, capacity?: boolean): Promise { const task = this.need(id, true, true); this.mine(task, by, "owner", true); // The owner it is declined for goes on the entry, also when the console declines for it: `excluded()` keeps it out (#207). const capacityBefore = this.capacityBefore(task); const planned = this.plannerPullRecord(task)?.pull === true; const record = this.plannerPullRecord(task); // #1626 A3: a capacity decline of a pulled card keeps the planner's reservation and returns the card to backlog; any other decline clears it as before. const keep = planned && capacity === true && !!task.owner && ["proposed", "in_progress"].includes(task.state) && !taskHasWorkEvidence(task); // #1626 A2: the decliner is not offered another task by the hub until it next reports idle. A peer already idle gets no back-off: no later idle edge would end it. if (capacity === true && task.owner && this.d.bus.stateOf(task.owner) !== "idle") this.capacityBackoff.add(task.owner); const back = this.d.board.update(task.id, by, "declined", { ...(["in_progress", "changes_requested"].includes(task.state) ? { state: "proposed" as const } : {}), ...(planned && !keep ? { reserved: null } : {}) }, reason, task.owner ? { from: task.owner, ...(capacity === true ? { capacity: true as const } : {}) } : {}); if (planned) this.offered.delete(task.id); if (keep) { this.d.notify(`task ${this.publicTitle(back)} declined (capacity only) by ${by}${reason && !this.isPii(back) ? `: ${reason}` : ""}; back in backlog with its reservation`); this.releaseHubWorktree(task, task.owner ?? by); try { const returned = this.d.board.update(back.id, HUB, "backlog returned untouched", { state: "backlog", owner: null, reviewer: null, reserved: record?.previous.reserved ?? back.reserved ?? null }, "capacity decline: back in backlog with its reservation", {}, back.history.length); this.cohorts.leave(task.id); this.withdrawRoleRequest(task, returned, "owner"); this.incomingBacklog.add(task.id); return returned; } finally { this.writePlannerNotices(this.d.board.get(task.id) ?? back, capacityBefore); } } this.d.notify(`task ${this.publicTitle(back)} declined${capacity === true ? " (capacity only)" : ""} by ${by}${reason && !this.isPii(back) ? `: ${reason}` : ""}`); this.releaseHubWorktree(task, task.owner ?? by); // A capacity decline is not in excluded(), so this move's own reroute leaves the decliner out explicitly. try { return await this.assignOwner(back, HUB, { event: "reassigned", reason: "declined", clearOnFail: true, ...(capacity === true && task.owner ? { exclude: [task.owner] } : {}), ...(planned ? { planner: true } : {}) }); } finally { this.writePlannerNotices(this.d.board.get(task.id) ?? back, capacityBefore); } } /** * #509a: the task's deliverables as they are now against what was delivered and what was approved. `changedSinceReview` is true only for a file * measured to differ from the bytes a reviewer approved (or, before approval, from the bytes delivered); a file the hub cannot read is * `unknown`, never `unchanged`. Ids, hashes and sizes only for a private record. Undefined when the task delivered nothing. */ async deliverableStatus(task: Task): Promise<{ state: "none" | "delivered" | "approved"; changedSinceReview: boolean; files: DeliverableStatus[] } | undefined> { const delivered = latestDeliverables(task.history); if (!delivered) return undefined; const approved = task.state === "approved" ? approvedDeliverables(task.history) : undefined; const basis = approved ?? delivered; const checks = await this.checkRecords(basis, task); const shown = publicDeliverables(basis, this.nameable)!; const files = checks.map((check, i): DeliverableStatus => { const { sha256, id, format, version, path, private: hidden } = shown[i]!; return { id, sha256, state: check.state, ...(path ? { path } : {}), format, ...(version ? { version } : {}), ...(hidden ? { private: true as const } : {}) }; }); const changedSinceReview = files.some(file => file.state === "changed"); this.deliverableSeen.set(task.id, { key: Tasks.deliverableKey(basis), at: Date.now(), result: deliverableResult(files.map(file => file.state)) }); return { state: approved ? "approved" : "delivered", changedSinceReview, files }; } /** The last live check per task (#317): what the dashboard may say about "changed since review" without hashing on its 1 s poll. Keyed by the records it measured. */ private deliverableSeen = new Map(); private static deliverableKey = (records: readonly DeliverableRecord[]) => records.map(record => `${record.id}:${record.sha256}`).join(","); /** * #317: the deliverables of the board's tasks, newest task first, for `ahub deliverables`. `approved` is what a reviewer's approval bound (else what was delivered). * Without `check` this reads the board only: no file is opened, so no row claims `changedSinceReview`. With `check` every file is measured now (one task at a time). * Every path goes through `publicDeliverables`, so a PII task or a path under `pii.paths` shows id, hash and size only. */ async deliverableList(opts: { task?: number; approvedOnly?: boolean; check?: boolean; visible?: (task: Task) => boolean } = {}): Promise { const rows: DeliverableRow[] = []; // #933: `visible` drops a task before anything is read or measured (an agent's list holds only what hub_task_show shows it). const tasks = (opts.task !== undefined ? [this.d.board.get(opts.task)].filter((task): task is Task => !!task) : this.d.board.list()).filter(task => !opts.visible || opts.visible(task)).sort((a, b) => b.id - a.id); for (const task of tasks) { const delivered = latestDeliverables(task.history); if (!delivered) continue; const approved = task.state === "approved" ? approvedDeliverables(task.history) : undefined; if (opts.approvedOnly && !approved) continue; const basis = approved ?? delivered, shown = publicDeliverables(basis, this.nameable)!; const row: DeliverableRow = { task: task.id, title: this.publicTitle(task), taskState: task.state, state: approved ? "approved" : "delivered", checked: false, files: shown.map(({ id, path, format, version, sha256, bytes, private: hidden }) => ({ id, ...(path ? { path } : {}), format, ...(version ? { version } : {}), sha256, bytes, ...(hidden ? { private: true as const } : {}) })) }; if (opts.check) { const status = await this.deliverableStatus(task); if (status) { row.checked = true; row.changedSinceReview = status.changedSinceReview; row.result = deliverableResult(status.files.map(file => file.state)); row.files = row.files.map((file, i) => ({ ...file, state: status.files[i]!.state })); } } rows.push(row); } return rows; } /** What the dashboard card shows: the board's records, plus the last live check when it measured exactly these records. Opens no file. */ deliverableBadge(task: Task): { state: "delivered" | "approved"; files: DeliverableRow["files"]; checked?: { at: number; result: DeliverableResult } } | undefined { const delivered = latestDeliverables(task.history); if (!delivered) return undefined; const approved = task.state === "approved" ? approvedDeliverables(task.history) : undefined; const basis = approved ?? delivered, seen = this.deliverableSeen.get(task.id); return { state: approved ? "approved" : "delivered", files: publicDeliverables(basis, this.nameable)!.map(({ id, path, format, version, sha256, bytes, private: hidden }) => ({ id, ...(path ? { path } : {}), format, ...(version ? { version } : {}), sha256, bytes, ...(hidden ? { private: true as const } : {}) })), ...(seen && seen.key === Tasks.deliverableKey(basis) ? { checked: { at: seen.at, result: seen.result } } : {}) }; } /** Check records against the owner's root; with that root unproven every file is `unknown` (never `unchanged`, never an exception). */ private async checkRecords(records: DeliverableRecord[], task: Task) { try { return await checkDeliverables(records, this.deliverablePorts(task)); } catch (error) { return records.map(record => ({ record, state: "unknown" as const, why: error instanceof Error ? error.message : "unreadable" })); } } /** What the deliverable reader needs from the host: the project root, the secrets denylist, and which files make a record private (#509a). */ private deliverablePorts(task: Task, policy: { failClosedOnDiscoveryLimit?: boolean } = {}): DeliverablePorts { const taskPrivate = this.isPii(task); // The owner's own root: a declared worktree instance writes under its worktree, so its deliverables are hashed there, never in the canonical // checkout (which holds a different file or none). With the root unproven there is nothing safe to hash: refuse rather than guess. const root = !this.d.executionRoot || !task.owner || task.owner === USER ? this.d.cwd : this.d.executionRoot(task.owner); if (root === undefined) throw new DeliverableRefusal(`deliverables: ${task.owner}'s execution root is not verified right now, so its files cannot be hashed`); return { cwd: root, deny: this.d.deny ?? [], private: path => taskPrivate || matchesPolicy(root, path, this.d.piiPaths ?? [], true, policy) }; } /** Path privacy exists even when measurement cannot open the output. Use the #509 policies on both names. */ private experimentOutputPrivate(task: Task, path: string): boolean { try { const ports = this.deliverablePorts(task, { failClosedOnDiscoveryLimit: true }), root = realPath(ports.cwd), deny = [...ports.deny]; const typed = relative(root, resolve(root, path)), actual = relative(root, policyRealPath(resolve(root, path))); return !insideRoot(typed) || !insideRoot(actual) || ports.private(path) || [typed, actual].some(name => isHubWritePath(name) || isDenied(name, deny) || isDenied(foldSegment(name), deny.map(foldSegment))); } catch { return true; } } /** * #509a: parse and vet a call's deliverable claims before any effect. A claimed hash is a refusal (the hub hashes the files itself), and so is a * path outside the project, on the denylist, inside the hub's own state, not a regular file, missing or too large. Nothing is hashed or stored here. */ private deliverableClaims(input: unknown, task: Task, preEffect = true) { try { const claims = parseDeliverableClaims(input); vetDeliverables(claims, this.deliverablePorts(task)); return claims; } catch (error) { throw new (preEffect ? PreEffectToolRefusal : Error)(error instanceof Error ? error.message : "invalid deliverables"); } } /** Hash vetted claims now. A refusal during the read (the file changed while it was read) is still before any write. */ private async hashClaims(claims: ReturnType, task: Task, preEffect = true): Promise { try { return await hashDeliverables(claims, this.deliverablePorts(task)); } catch (error) { throw new (preEffect ? PreEffectToolRefusal : Error)(error instanceof DeliverableRefusal || error instanceof Error ? error.message : "deliverables could not be hashed"); } } /** Tasks whose check is queued or running, and the owner it was started for. */ private readonly checking = new Map(); private checkQueue: Promise = Promise.resolve(); private pendingChecks = 0; /** Checks queued or running, until their result is on the board: a recovery commit waits for them. */ checksPending = () => this.pendingChecks; /** #1054: completion checks queued or running for work this peer owns, so a run is not settled while its own check is still going. */ checksOwnedBy = (peer: PeerId): number => { let n = 0; for (const owner of this.checking.values()) if (owner === peer) n++; return n; }; /** Whether a completion check is still running for this task. */ isChecking = (id: number) => this.checking.has(id); /** Invalidate stale artifact evidence without changing spec acceptance or open findings. */ private completionDraft(task: Task, refresh?: Pick): Task { if (!refresh || !task.sdlc) return task; const sdlc = { ...task.sdlc }; if (sdlc.head !== refresh.commit) { delete sdlc.head; delete sdlc.observed; } if (sdlc.reviewedHead !== refresh.commit) delete sdlc.reviewedHead; if (sdlc.localHead !== refresh.commit) { delete sdlc.localHead; delete sdlc.localResult; } delete sdlc.merge; delete sdlc.mergeReadback; return { ...task, sdlc }; } private completionCurrent(id: unknown, by: PeerId, preEffect: boolean, refresh?: CompletionRefresh): Task { const task = this.need(id, false, preEffect); this.mine(task, by, "owner", preEffect); if (refresh && (task.state !== refresh.state || task.history.length !== refresh.revision)) throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${task.id}: review changed during re-file; retry on current work`); if (preEffect) { if (task.state === "in_review" && !refresh || isClosedTaskState(task.state) && !(task.state === "approved" && refresh)) throw new PreEffectToolRefusal(`task #${task.id} is already ${task.state}`); } else { if (task.state === "in_review" && !refresh || isClosedTaskState(task.state) && !(task.state === "approved" && refresh)) throw new Error(`task #${task.id} is already ${task.state}`); } if (task.sdlc?.merge?.state === "merged") throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${task.id}: PR is merged`); this.ready(task, preEffect); if (task.state === "proposed" || task.state === "changes_requested") this.acceptanceCapacity(task); if (this.checking.has(task.id)) { // The result goes only to the owner the check was started for: anyone who took the task since hears nothing. throw new (preEffect ? PreEffectToolRefusal : Error)(this.checking.get(task.id) === task.owner ? `task #${task.id}: its check is still running; its result comes as a task message` : `task #${task.id}: a check from before it changed hands is still running; call hub_task_done again in a few minutes`); } return this.completionDraft(task, refresh); } /** An approval may reopen only while its linked PR is known not to be merged, even with lifecycle gates off. */ private async unmergedForReopen(task: Task, valid: () => Task): Promise { valid(); if (task.sdlc?.merge?.state === "merged") throw new PreEffectToolRefusal(`task #${task.id}: PR is merged`); const { repo, pr } = task.sdlc ?? {}; if (!repo || !pr) return; if (this.isPii(task)) throw new PreEffectToolRefusal(`task #${task.id}: PR merge state unavailable for private work`); const original = this.need(task.id, false, true); const identity = JSON.stringify([original.sdlc, original.refs, original.history.length]); let state: unknown; try { const reply = await (this.d.sdlc?.gh ?? sdlcGh)(["pr", "view", String(pr), "--repo", repo, "--json", "state"]); if (reply.code === 0) state = JSON.parse(reply.stdout).state; } catch { /* unknown merge state refuses before effects */ } valid(); const current = this.need(task.id, false, true); if (JSON.stringify([current.sdlc, current.refs, current.history.length]) !== identity) throw new PreEffectToolRefusal(`task #${task.id}: task changed during merge-state read`); if (state === "MERGED") throw new PreEffectToolRefusal(`task #${task.id}: PR is merged`); if (state !== "OPEN" && state !== "CLOSED") throw new PreEffectToolRefusal(`task #${task.id}: PR merge state unavailable; cannot reopen approval`); } async done(by: PeerId, id: unknown, summary?: string, refs?: TaskRefs, deliverables?: unknown, specAck?: unknown, resolved?: unknown): Promise { try { return await this.doneWithHandoff(by, id, summary, refs, deliverables, specAck, resolved); } catch (error) { if ((refs as ManagedHandoffRefs | undefined)?.[MANAGED_HANDOFF] && error instanceof PreEffectToolRefusal) throw new Error(`managed worktree was committed before completion was refused: ${error.message}; inspect the task and GitHub before retrying hub_task_done`); throw error; } } private async doneWithHandoff(by: PeerId, id: unknown, summary?: string, refs?: TaskRefs, deliverables?: unknown, specAck?: unknown, resolved?: unknown): Promise { const observerExcluded = this.observerExcluded(by); const requestCheck = this.requestCheck(by); const initial = this.need(id, false, true); this.mine(initial, by, "owner", true); const reviewObserverTurn = observerExcluded || this.reviewObserverTurn(by, initial.id); const resolvedReviewComments = this.reviewCommentResolve(by, initial, resolved); let refresh: CompletionRefresh | undefined; if (initial.state === "in_review" || initial.state === "approved") { const commit = cleanRefs(refs).commit; const recorded = this.ownerReviewHead(initial) ?? this.findingHead(initial); const currentReviewHead = this.ownerReviewHead(initial) ?? this.reviewHead(initial); if (!commit || !/^[a-f0-9]{40}$/.test(commit) || commit === currentReviewHead) { throw new PreEffectToolRefusal(`task #${initial.id} is already ${initial.state}${recorded ? ` with recorded review head ${recorded}` : ""}; re-file requires a different full head SHA. Owner must re-file hub_task_done with refs.commit set to the new full SHA`); } refresh = { revision: initial.history.length, commit, state: initial.state }; } const submittedCommit = cleanRefs(refs).commit; if (submittedCommit && this.hasReviewHistory(initial) && !/^[a-f0-9]{40}$/.test(submittedCommit)) { const recorded = this.ownerReviewHead(initial); throw new PreEffectToolRefusal(`task #${initial.id}: re-file after review needs refs.commit to be a full lowercase SHA${recorded ? ` (recorded review head ${recorded})` : ""}; owner must re-file hub_task_done with the new full SHA in refs.commit`); } const refileHead: RefileHeadGuard | undefined = !submittedCommit && initial.sdlc?.repo && initial.sdlc.pr && this.hasReviewHistory(initial) && !this.isPii(initial) ? { recorded: this.ownerReviewHead(initial) } : undefined; const draft = refresh ?? (submittedCommit && /^[a-f0-9]{40}$/.test(submittedCommit) ? { commit: submittedCommit } : undefined); let specCarry: object | undefined; const write = (...args: Parameters) => { const result = this.commitSpecCarry(by, specCarry, ...args); specCarry = undefined; return result; }; const valid = () => { requestCheck(); const current = this.stagedSpec(by, this.completionDraft(this.completionCurrent(id, by, true, refresh), draft), specCarry); if (resolvedReviewComments !== undefined) this.reviewCommentResolve(by, current, resolvedReviewComments); return current; }; if (initial.state === "approved") { await this.unmergedForReopen(initial, valid); valid(); } // #509a: a bad claim (a claimed hash, an outside or denied path, a missing file) is refused before any effect, with nothing recorded. const claims = deliverables === undefined ? undefined : this.deliverableClaims(deliverables, valid()); // The PII screen reads the summary of a done that passes these checks (issue #198); they run again after it. const withheld = observerExcluded || await this.withholds("summary", summary, valid()); let task = valid(); // The hub hashes the files itself, once, here: what the owner delivered is what this read, whatever the file becomes afterwards. const records = claims ? await this.hashClaims(claims, task, true) : undefined; task = valid(); // #481 S1: done without a separate accept starts build work too: the same live spec check as accept, before any write. if (task.state === "proposed" || task.state === "changes_requested") { const admission = await this.specGate(by, task.id, { ...task.refs, ...cleanRefs(refs) }); specCarry = admission?.carry; await this.planEntryGate(by, admission?.carry ? admission.task : task, specCarry); task = valid(); } // #694: stage the identities the hub can verify; the gates read them, and only the admitted done persists them. const handoff = (refs as ManagedHandoffRefs | undefined)?.[MANAGED_HANDOFF]; const link: IdentityLink | undefined = handoff?.repo && handoff.pr ? { repo: handoff.repo, pr: handoff.pr, basis: { commit: handoff.commit, branch: handoff.branch }, managedRevision: handoff.revision } : !handoff && this.d.sdlc && this.d.sdlc.config().mode !== "off" ? await this.identityLink(task, refs) : undefined; let managedRevision = handoff?.revision; const stageHandoff = (row: Task) => { let staged = row; if (handoff) { if (handoff.task !== staged.id || handoff.owner !== by || managedRevision !== staged.history.length || handoff.commit !== cleanRefs(refs).commit || handoff.branch !== cleanRefs(refs).branch || this.isPii(staged) || this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("managed handoff changed; inspect the task and GitHub before retrying"); if (handoff.repo && handoff.pr && !staged.sdlc?.pr) { const receipt = linkedReceipt(staged.sdlc, { repo: handoff.repo, pr: handoff.pr }, this.d.sdlc?.config() ?? sdlcConfig(undefined)); if (!receipt) throw new PreEffectToolRefusal("managed PR repository no longer matches the task; inspect GitHub before retrying"); staged = { ...staged, sdlc: receipt }; } } return staged; }; const ownWrite = (...args: Parameters) => { current(); const row = write(...args); if (handoff) { managedRevision = row.history.length; if (link) link.managedRevision = managedRevision; } return row; }; const current = () => stageHandoff(this.stagedSpec(by, this.withLink(valid(), link, refs), specCarry)); task = current(); let reviewEvidence: PrEvidence | undefined; if (this.d.sdlc && this.d.sdlc.config().mode !== "off") { reviewEvidence = await this.lifecycleGate(task, "review", undefined, undefined, refileHead); task = current(); } const reviewAdmission = task.reviewer || this.d.prepareReviewBrief ? await this.reviewRequestAdmission(task, refs, true, by, reviewEvidence, undefined, staged => stageHandoff(this.stagedSpec(by, this.withLink(this.completionDraft(staged, draft), link, refs), specCarry)), !task.reviewer, refileHead) : undefined; task = current(); if (refileHead && (this.d.sdlc?.config().mode ?? "off") === "off") { const currentHead = await this.currentPrHeadForReview(task, current); task = current(); if (!refileHead.recorded || !currentHead) throw this.reviewHeadMoveRefusal(task.id, refileHead.recorded); if (currentHead !== refileHead.recorded) throw this.reviewHeadMoveRefusal(task.id, refileHead.recorded, currentHead); } const currentSpecTask = () => { const fresh = current(); return { ...fresh, refs: { ...fresh.refs, ...cleanRefs(refs) } }; }; const specInspection = await this.inspectTaskSpecs(currentSpecTask(), by, specAck, currentSpecTask); task = current(); // the host head and task authority are revalidated after spec inspection this.assertSpecInspection(specInspection, { ...task, refs: { ...task.refs, ...cleanRefs(refs) } }, by); // A member of a silent cohort (issue #107): its done is an intent, and the last of them integrates first. const cohort = this.cohorts.of(task.id); const silentMember = !!cohort?.silent && this.turnFree() && !!task.owner && !this.isPii(task); if (silentMember && by === USER) { // The console finishing a member: its done still counts as an intent, so the last member integrates; what the // silence held goes to the console. this.cohorts.intent(cohort!, task, ownerGen(task)); const evidence = this.heldEvidence(cohort!, task); if (evidence) this.d.notify(`task ${this.publicTitle(task)} done by the console; overlapping work finished meanwhile:\n${evidence}`); } else if (silentMember) { const gen = ownerGen(task); // A retry right after the request: the same request again, nothing acknowledged or counted. if (this.cohorts.isRetry(cohort!, task, gen)) return this.d.board.get(task.id)!; const ig = cohort!.integration; if (ig?.task === task.id && ig.offer) this.d.ackFacts?.(task.owner!, ig.offer); // this call is the proof the request arrived const r = this.cohorts.completion(cohort!, task, { gen, tree: this.tree(cohort!), factsCurrent: this.d.factsCurrent?.(task.owner!) ?? true, handed: handedAt(task) }); if (r.action === "request") return write(task.id, HUB, "integration requested", {}, this.integrationRequest(task, r)); if (r.action === "unresolved") { this.d.notify(`task ${this.publicTitle(task)}: turn-free integration unresolved after ${MAX_REQUESTS} requests (${r.why}); its done is recorded, check the overlapping work by hand`); task = this.withLink(ownWrite(task.id, HUB, "integration unresolved", {}, r.why), link, refs); } else if (r.integrated) task = this.withLink(ownWrite(task.id, HUB, "integrated", {}, `cohort #${cohort!.id}, revision ${cohort!.revision}`), link, refs); } else if (cohort?.held.size && !this.isPii(task)) { // No integration step for this member (silence lifted, a PII task open): the notices the silence held stand in // for it (issue #107, AC4). const evidence = this.heldEvidence(cohort, task); if (evidence && by === USER) this.d.notify(`task ${this.publicTitle(task)} done by the console; overlapping work finished meanwhile:\n${evidence}`); else if (evidence) this.doneNotes.set(task.id, `Overlapping work finished while you worked (no turn-free integration step ran):\n${evidence}`); } if (task.state === "proposed" || task.state === "changes_requested") task = this.withLink(ownWrite(task.id, by, "accepted", { state: "in_progress" }, WITH_DONE), link, refs); // done without a separate accept const command = this.d.runCheck ? this.d.check?.(task.class, task) : undefined; if (!command) return this.complete(task, by, summary, refs, "", withheld, "review", reviewAdmission, link, records, requestCheck, refresh, specInspection, false, resolvedReviewComments, reviewObserverTurn); // The tool call returns now; a check can outlast an agent's tool timeout. The result decides what comes next. if (refresh?.state === "approved") { await this.unmergedForReopen(task, valid); task = current(); } this.checking.set(task.id, task.owner); const checkedRefs = cleanRefs(refs); if (specInspection.report?.head && !checkedRefs.commit) checkedRefs.commit = specInspection.report.head; if (specInspection.report && specInspection.repo && !checkedRefs.repo) checkedRefs.repo = specInspection.repo; const storedRefs = { ...task.refs, ...checkedRefs }; this.warmRepository({ ...task, refs: { ...task.refs, ...checkedRefs } }); this.assertSpecInspection(specInspection, { ...task, refs: storedRefs }, by); const pending = write(task.id, by, "done (checking)", { ...(refresh ? { state: "in_progress" as const } : {}), ...(refresh?.state === "approved" && !task.reviewer ? { reviewer: USER } : {}), codeSymbols: this.observedCodeSymbols({ ...task, refs: storedRefs }), refs: checkedRefs, ...(task.sdlc ? { sdlc: task.sdlc } : {}) }, summary, { withheld: withheld || undefined, ...(records ? { deliverables: records } : {}), ...(specInspection.report ? { specReport: specInspection.report, specRefBinding: this.specRefBinding({ refs: storedRefs }) } : {}) }, task.history.length, HOST_CODE_SYMBOLS); if (refresh) { this.ciWatchers.cancel(pending.id); this.heldReviews.delete(pending.id); } this.releaseNotice(`task ${this.publicTitle(pending)} done by ${by}; its check is queued or running: ${command}`); const seen = { events: pending.history.length, owner: pending.owner }; this.pendingChecks++; this.checkQueue = this.checkQueue .then(() => this.finishChecked(pending.id, by, summary, command, seen, withheld, specInspection, resolvedReviewComments, reviewObserverTurn, observerExcluded)) .catch((e: Error) => { this.releaseNotice(`task #${pending.id}: its check result could not be recorded: ${e.message}`); this.releaseNotice(`task #${pending.id}: its owner retry notice could not be published`, () => { const current = this.d.board.get(pending.id); if (current?.state === "in_progress" && current.owner === seen.owner) this.tell(current, `Task #${current.id}: its check completion was refused. Call hub_task_done again when it is ready.`, this.isPii(current)); }); }) .finally(() => this.pendingChecks--); return pending; } /** * After a restart (issue #107) the cohorts, intents and turn ends are gone, so an integration that was asked for and * not confirmed can never be: it is recorded as unresolved, and the owner's next done is recorded as usual. */ recoverIntegrations(): void { const marks = new Set(["integration requested", "integrated", "integration unresolved", "done", "done (checking)", "reopened", "accepted", "assigned", "reassigned", "escalated"]); for (const t of this.d.board.list()) { if (!OPEN.includes(t.state) || [...t.history].reverse().find((h) => marks.has(h.event))?.event !== "integration requested") continue; this.d.board.update(t.id, HUB, "integration unresolved", {}, "the hub restarted before the integration was confirmed"); this.d.notify(`task ${this.publicTitle(t)}: turn-free integration unresolved (the hub restarted); check the overlapping work by hand`); } } /** * After a restart in a turn-free project (issue #107) the cohorts are gone, and with them what their silence held. When * `peer` first attaches, each of its open tasks that overlaps another owner's work hears that overlaps are settled by * message again, with the completed-change notices of the overlapping tasks finished since it was handed over. A * duplicate notice is the price of never losing one. */ replayHeld(peer: PeerId): void { requireLocalTaskPeer(peer); const finished = this.d.board.list().filter((u) => (u.state === "approved" || u.state === "in_review") && u.owner && !this.isPii(u)); for (const t of this.d.board.list()) { if (!OPEN.includes(t.state) || t.owner !== peer || this.isPii(t)) continue; const open = this.overlapHits(t).filter((h) => h.task.owner !== USER && h.task.owner !== HUB); const mine = this.places(t); const done = finished.flatMap((u) => { const at = [...u.history].reverse().find((h) => h.event === "done"); if (u.owner === t.owner || !at || at.at < handedAt(t)) return []; const theirs = this.places(u); if (mine.repositoryKey !== theirs.repositoryKey) return []; const paths = t.profile && u.profile && (t.plan?.sections?.length && u.plan?.sections?.length) ? [] : mine.paths.filter((p) => theirs.paths.some((q) => samePlace(p, q))); const symbols = mine.symbols.filter((x) => theirs.symbols.some((y) => symbolsOverlap(x, y))); return paths.length || symbols.length ? [this.completedNotice(u, { task: t, paths, symbols }, at.note, at.withheld)] : []; }); if (!open.length && !done.length) continue; const owners = [...new Set(open.map((h) => h.task.owner!))]; const head = owners.length ? `Task #${t.id}: the hub restarted, so overlaps with ${owners.join(", ")} are settled via hub_send again (any turn-free silence is lifted).` : `Task #${t.id}: the hub restarted; overlapping work finished meanwhile.`; this.whileOpen(peer, t.id, [head, ...done].join("\n")); } } /** One hash over the files a cohort's tasks name and its members wrote while at work, as they are now: the integration target (issue #107). */ private tree(cohort: Cohort): string { const paths = [...new Set([...cohort.members.keys()].flatMap((id) => { const t = this.d.board.get(id); return t ? this.places(t).paths : []; }))]; // Each member's writes count from when its owner was handed the task until it settled: settling keeps its files in // the target, and its later writes are its next task's. const windows = [...cohort.members.values()].map((m) => ({ peer: m.owner, since: m.since, ...(m.settledAt !== undefined ? { until: m.settledAt } : {}) })); return this.d.treeHash?.(paths, windows) ?? ""; } /** * What the integrating member reads as its done result (issue #107): what the others finished, the facts it has not * been shown, and what makes the next done count. Its facts offer is acknowledged by that next done. */ private integrationRequest(task: Task, r: Extract): string { const others = [...r.cohort.members.values()].filter((m) => m.task !== task.id).flatMap((m) => { const t = this.d.board.get(m.task); return t ? [t] : []; }); const doneAt = (t: Task) => [...t.history].reverse().find((h) => h.event === "done" || h.event === "done (checking)"); const lines = others.map((t) => { const files = this.places(t).paths.filter(this.nameable); const signatures = (t.plan?.signatures ?? []).filter(this.nameable); const done = doneAt(t); const first = done?.withheld ? undefined : (done?.note ?? "").split("\n").find((l) => l.trim())?.trim().slice(0, 300); return [ `- ${this.publicTitle(t)} (owner ${t.owner}, ${t.state})`, files.length ? ` changed files: ${files.join(", ")}` : "", signatures.length ? ` signatures: ${signatures.join("; ")}` : "", first && this.nameable(first) ? ` summary: ${first}` : "", ].filter(Boolean).join("\n"); }); const facts = task.owner ? this.d.integrationFacts?.(task.owner) : undefined; if (facts && r.cohort.integration) r.cohort.integration.offer = facts.id; const head = r.requests === 1 ? `Before task #${task.id} is recorded as done: you are the last of turn-free cohort #${r.cohort.id} to finish. Check your work against the others' below, fix what conflicts, then call hub_task_done again.` : `Task #${task.id} is not recorded as done yet (integration request ${r.requests} of ${MAX_REQUESTS}): ${r.why}. Check again, then call hub_task_done again.`; return [head, "The done counts once the files did not change between two calls and the others have stopped.", ...lines, facts?.text ?? ""].filter(Boolean).join("\n"); } /** Record an already-admitted isolated run without retaining its output. */ recordCheckResult(receipt: import("./check-runner.ts").RunReceipt): void { const task = this.d.board.get(receipt.task); if (!task || task.state !== "in_progress" || task.owner !== receipt.owner) return; const passed = receipt.exit === 0 && !receipt.timed_out && !receipt.cancelled && !receipt.interrupted; this.d.board.update(task.id, HUB, passed ? "check run passed" : "check run failed", {}, undefined, { checkKey: receipt.check, requestHead: receipt.sha }, task.history.length); } /** * #901: which check key produced this result, and how many citation keys the example citation check said were unresolved. The key is the hub's own selection (`Deps.checkKey`, the lookup * `Deps.check` makes), never read from output; without that dependency it is not recorded. The count is read only from the example check's own last line (`citations: N declared keys, M missing`, scripts/check-citations.ts); * a tail without that exact line, or with a number past the bound, records no count: unknown, never zero. */ private checkProvenance(task: Task, tail: string): Pick { let key: string | undefined; try { key = this.d.checkKey?.(task.class, task); } catch { key = undefined; } const lines = tail.split("\n").map(line => line.trim()).filter(Boolean); const match = /^citations: (\d{1,6}) declared keys, (\d{1,6}) missing$/.exec(lines.at(-1) ?? ""); return { ...(key ? { checkKey: key } : {}), ...(match ? { missingKeys: Number(match[2]) } : {}) }; } private async finishChecked(id: number, by: PeerId, summary: string | undefined, command: string, seen: { events: number; owner: PeerId | null }, withheld: boolean, specInspection: PreparedSpecInspection, resolvedReviewComments?: string[], reviewObserverExcluded = false, evidenceObserverExcluded = false): Promise { const result = await this.d.runCheck!(command).catch((e: Error) => ({ code: null, timedOut: false, interrupted: false, tail: e.message })); const checkOwner = this.checking.get(id); this.checking.delete(id); if (checkOwner) { try { queueMicrotask(() => { try { this.d.checkEnded?.(checkOwner); } catch { /* advisory */ } }); } catch { /* advisory */ } } const task = this.d.board.get(id); if (!task) return; const outcome = `${command} -> ${result.interrupted ? "interrupted by a hub stop" : result.timedOut ? "timed out" : `exit ${result.code ?? "?"}`}`; // Not a verdict on the work, and nobody is listening any more: the owner marks the task done again (spec). if (result.interrupted) return void this.d.board.update(id, HUB, "check interrupted", {}, outcome); const pii = this.isPii(task); // Moved on meanwhile (escalated, reassigned, released, and maybe back again): the result is kept, nothing else changes. if (task.state !== "in_progress" || task.history.slice(seen.events).some((h) => !QUIET_EVENTS.has(h.event))) { this.d.board.update(id, HUB, "check finished late", {}, outcome); if (task.state === "in_progress" && task.owner === seen.owner) this.tell(task, `Task #${id}: the check of your earlier hub_task_done finished after the task changed hands (${outcome}). Call hub_task_done again when it is ready.`, pii); return; } if (result.code === 0 && !result.timedOut) { const refileForSpecs = this.refreshAsyncSpecInspection(specInspection, task, by); // An integrating member's check counts only for the target it confirmed (issue #107). const cohort = this.cohorts.of(id); if (cohort?.silent && !this.cohorts.holds(id, ownerGen(task), this.tree(cohort))) { this.d.board.update(id, HUB, "check finished late", {}, `${outcome}; the integration target changed while it ran`); this.tell(task, `Task #${id}: its check passed, but the overlapping work or the files changed while it ran (turn-free integration). Call hub_task_done again.`, pii); return; } this.d.board.update(id, HUB, "check passed", {}, `${outcome}\n${result.tail}`.trim(), { ...this.checkProvenance(task, result.tail), ...(withheld ? { withheld: true } : {}) }); if (refileForSpecs) { this.requestSpecRefile(task); return; } // The output goes to the reviewer with the done note, not into shared memory: nobody screened it. await this.complete(this.d.board.get(id)!, by, `${summary ?? ""}\nCheck: ${outcome}`.trim(), undefined, result.tail, withheld, undefined, undefined, undefined, undefined, undefined, undefined, specInspection, true, resolvedReviewComments, reviewObserverExcluded); return; } this.d.board.update(id, HUB, "check failed", {}, `${outcome}\n${result.tail}`.trim(), { ...this.checkProvenance(task, result.tail), ...(withheld ? { withheld: true } : {}) }); this.cohorts.withdraw(id); // open again: its done intent no longer counts (issue #107) if (task.owner) this.d.board.recordOutcome(task.owner, task.class, false); this.contradict(task); this.d.notify(`task ${this.publicTitle(task)}: its check failed (${outcome}); it stays with ${task.owner ?? by}`); this.tell(task, `Task #${id}: its check failed.\n$ ${outcome}${!evidenceObserverExcluded && result.tail ? `\n${result.tail}` : ""}\nFix it and call hub_task_done again.`, pii, "owner", this.reviewObserverTurn(by, id)); } /** `gated`: the transition `done()` already gated with no await since, so it is not read back twice (#382). */ private async complete(task: Task, by: PeerId, summary?: string, refs?: TaskRefs, checkOutput = "", withheld = false, gated?: "review", admission?: ReviewReadiness, link?: IdentityLink, records?: DeliverableRecord[], requestCheck: () => void = () => {}, refresh?: CompletionRefresh, specInspection?: PreparedSpecInspection, asyncCheckCompletion = false, resolvedReviewComments?: string[], reviewObserverExcluded = false): Promise { requestCheck(); if (specInspection && asyncCheckCompletion && this.refreshAsyncSpecInspection(specInspection, task, by)) { this.requestSpecRefile(task); return task; } // A check's completion carries the records its `done (checking)` bound: the same bytes the owner delivered, not a later read. records ??= latestPendingDeliverables(task); const submittedCommit = cleanRefs(refs).commit; const draft = refresh ?? (submittedCommit && /^[a-f0-9]{40}$/.test(submittedCommit) ? { commit: submittedCommit } : undefined); task = this.completionDraft(task, draft); let selection = this.poolReview(task, refs); let reviewer = selection?.reviewer ?? task.reviewer ?? (refresh?.state === "approved" ? USER : undefined), reviewEvidence: PrEvidence | undefined; if (this.d.sdlc && this.d.sdlc.config().mode !== "off" && gated !== (reviewer ? "review" : "approval")) { // #1435: the head this done submits is the head the gate compares with the PR. `refs.commit` still holds the earlier head until the done is written, so an approval-path gate (no reviewer after an escalation) would refuse the very head its refusal names. reviewEvidence = await this.lifecycleGate(draft?.commit ? { ...task, refs: { ...task.refs, commit: draft.commit } } : task, reviewer ? "review" : "approval"); requestCheck(); task = this.withLink(this.completionDraft(this.completionCurrent(task.id, by, false, refresh), draft), link, refs); if (specInspection && asyncCheckCompletion && this.refreshAsyncSpecInspection(specInspection, task, by)) { this.requestSpecRefile(task); return task; } selection = this.poolReview(task, refs); reviewer = selection?.reviewer ?? task.reviewer ?? (refresh?.state === "approved" ? USER : undefined); } // A delayed local check needs a new readback; a completion-selected reviewer also needs optional facts in off mode. if (!admission && ((reviewer && (this.d.sdlc?.config().mode ?? "off") !== "off") || this.d.prepareReviewBrief)) { admission = await this.reviewRequestAdmission(task, refs, false, by, reviewEvidence, undefined, staged => this.withLink(this.completionDraft(staged, draft), link, refs), !reviewer); requestCheck(); task = this.withLink(this.completionDraft(this.completionCurrent(task.id, by, false, refresh), draft), link, refs); if (specInspection && asyncCheckCompletion && this.refreshAsyncSpecInspection(specInspection, task, by)) { this.requestSpecRefile(task); return task; } } selection = this.poolReview(task, refs); reviewer = selection?.reviewer ?? task.reviewer ?? (refresh?.state === "approved" ? USER : undefined); const reviewCost: ReviewCost | undefined = reviewer && task.plan && (task.plan.review || task.plan.ci) ? { ...cleanCostPlan(task.plan), ...(admission?.ready && admission.head ? { head: admission.head } : {}) } : undefined; const routedSummary = selection?.reviewSelection && (selection.reviewSelection.blocked || selection.reviewSelection.admissionRule) ? `${summary ?? ""}\nReview routing: ${this.assignmentNote(selection.reviewSelection.blocked ? "pool unavailable" : "pool selected", selection)}`.trim() : summary; if (refresh?.state === "approved") { await this.unmergedForReopen(task, () => { requestCheck(); return this.completionCurrent(task.id, by, true, refresh); }); task = this.withLink(this.completionDraft(this.completionCurrent(task.id, by, true, refresh), draft), link, refs); if (specInspection && asyncCheckCompletion && this.refreshAsyncSpecInspection(specInspection, task, by)) { this.requestSpecRefile(task); return task; } } const completedRefs = cleanRefs(refs); if (specInspection?.report?.head && !completedRefs.commit) completedRefs.commit = specInspection.report.head; if (specInspection?.report && specInspection.repo && !completedRefs.repo) completedRefs.repo = specInspection.repo; const storedRefs = { ...task.refs, ...completedRefs }; const requestedHead = completedRefs.commit ?? admission?.head ?? specInspection?.report?.head; const requestHead = requestedHead && /^[a-f0-9]{40}$/.test(requestedHead) ? requestedHead : undefined; if (specInspection) { if (asyncCheckCompletion) { if (this.refreshAsyncSpecInspection(specInspection, { ...task, refs: storedRefs }, by)) { this.requestSpecRefile(task); return task; } } else this.assertSpecInspection(specInspection, { ...task, refs: storedRefs }, by); } this.warmRepository({ ...task, refs: storedRefs }); const noWrites = this.noWritesRecorded({ ...task, refs: storedRefs }); const capacity = this.capacityBefore(task); reviewObserverExcluded ||= this.reviewObserverTurn(by, task.id); const quotaWaiting = selection?.reviewSelection?.quotaWait !== undefined; const next = this.d.board.update(task.id, by, "done", { codeSymbols: this.observedCodeSymbols({ ...task, refs: storedRefs }), state: reviewer ? "in_review" : "approved", ...(selection || refresh?.state === "approved" ? { reviewer: quotaWaiting ? null : reviewer ?? USER } : {}), ...(task.sdlc ? { sdlc: { ...task.sdlc, stage: lifecycleStage(this.d.sdlc?.config() ?? sdlcConfig(undefined), reviewer ? "review" : "merge") } } : {}), refs: completedRefs }, checkOutput ? `${routedSummary ?? ""}\n${checkOutput}`.trim() : routedSummary, { ...(resolvedReviewComments?.length ? { resolvedReviewComments: this.reviewCommentResolve(by, task, resolvedReviewComments) } : {}), ...this.planObservation(task), withheld: withheld || undefined, ...(specInspection?.report ? { specReport: specInspection.report, specRefBinding: this.specRefBinding({ refs: storedRefs }) } : {}), ...(noWrites ? { noWrites: true as const } : {}), ...this.reviewMetadata(selection, { ...task, state: "in_review", refs: storedRefs }), ...(reviewCost ? { reviewCost } : {}), ...(requestHead ? { requestHead } : {}), ...(records ? { deliverables: records } : {}) }, task.history.length, HOST_CODE_SYMBOLS); this.queueReviewWritten(next); this.writePlannerNotices(next, capacity, next.state === "approved"); this.ciWatchers.cancel(next.id); this.heldReviews.delete(next.id); // a newer head or a move ends the old head's watcher (#785 P1b) this.cohorts.closed(next.id); // its owner's next native turn end settles it in its cohort (issue #107) const memorySymbols = this.completionMemorySymbols(next); this.note(next, by, "finding", `Task #${next.id} done by ${by}: ${next.title}\nChanged-symbol memory anchors: ${memorySymbols.state === "known" ? memorySymbols.nodes.length : "unknown (no complete code facts)"}\n${summary ?? ""}`, withheld || reviewObserverExcluded, memorySymbols); this.tellCompleted(next, summary, withheld || reviewObserverExcluded); if (!reviewer) { this.settleMemory(next); if (next.owner) this.d.board.recordOutcome(next.owner, next.class, true); // approved without a review is a success too this.releaseNotice(`task ${this.publicTitle(next)} done by ${by}, no reviewer: approved`); await this.releaseDependents(next); } else if (quotaWaiting) this.releaseNotice(`task ${this.publicTitle(next)}: waiting for reviewer quota reset`); else if (reviewer === USER) this.releaseNotice(`task ${this.publicTitle(next)} done by ${by}: review it in the ahub console (Tasks, select #${next.id}, press r) or with ahub review ${next.id} approved|changes_requested [note]`); else this.releaseNotice(`task ${this.publicTitle(next)}: could not send the review request to ${reviewer}`, () => this.sendReview(next, reviewer, "", admission)); if (reviewer && !quotaWaiting && !(admission?.ready && admission.head === this.reviewHead(next))) this.watchCi(next); return next; } /** * "Passes alone, fails together": the owners of open tasks on the same places hear what changed under them, once the * work is done (after its check, when one runs), and nobody else does (issue #31). A message of its own, not a * ride-along line: an owner in the middle of those files needs it before its next task arrives. */ private tellCompleted(task: Task, summary?: string, withheld = false): void { const hits = this.overlapHits(task).filter((h) => h.task.owner !== USER && h.task.owner !== HUB); const cohort = this.cohorts.of(task.id); const silent = this.silentFor(task.id); // #713: one notice per recipient per done, naming all of that recipient's overlapping tasks, and only for work the recipient has accepted. An offered or proposed // task has nothing to check yet (its offer, or the accept that follows, already shows the current board), and a repeat done replaces the queued notice (see Bus.enqueue). const byOwner = new Map(); for (const hit of hits) { // A member of the same silent cohort (issue #107): the member that finishes last integrates instead // (Cohorts.completion). The notice is held, so something replaces it if no integration runs. Others hear it. if (silent && cohort?.members.has(hit.task.id)) { cohort.held.add(task.id); continue; } // Accepted by its own owner since it last changed hands (`ownerAcceptance`, the rule the rest of this class uses), and still in work or review: an offered or proposed task is not. if (!["in_progress", "changes_requested", "in_review"].includes(hit.task.state) || !this.ownerAcceptance(hit.task)) continue; byOwner.set(hit.task.owner!, [...(byOwner.get(hit.task.owner!) ?? []), hit]); } for (const [owner, mine] of byOwner) { this.releaseNotice(`task ${this.publicTitle(task)}: could not publish the completed-change notice to ${owner}`, () => this.whileOpenFor(owner, task.id, mine.map((h) => h.task.id), this.completedNotice(task, mine, summary, withheld))); } } /** Share the same screened observation rule between completion notices and read-only console detail. */ private sameFileDifferentSymbols(task: Task, hit: { task: Task; paths: string[] }): boolean { const symbolRepository = task.codeSymbols && !this.isPii(task) ? this.codeSymbolsRepository(task) : undefined; const otherRepository = hit.task.codeSymbols && !this.isPii(hit.task) ? this.codeSymbolsRepository(hit.task) : undefined; return !!symbolRepository && symbolRepository.key === otherRepository?.key && !this.isPii(task) && !this.isPii(hit.task) && taskCodeSymbolsDisjoint( task.codeSymbols, hit.task.codeSymbols, this.reviewHead(task), this.reviewHead(hit.task), symbolRepository.key, hit.paths, false, this.publicMetadataText); } /** * The completed-change notice: files, signatures and the summary are the owner's own words (paths given at done * included), and any item that matches a PII pattern is left out of what other owners get, the summary also when the * PII screen did not clear it (`withheld`, #198). */ private completedNotice(task: Task, hitOrHits: { task: Task; paths: string[]; symbols: string[] } | { task: Task; paths: string[]; symbols: string[] }[], summary?: string, withheld = false): string { const hits = Array.isArray(hitOrHits) ? hitOrHits : [hitOrHits]; const paths = this.places(task).paths.filter(this.nameable); const signatures = (task.plan?.signatures ?? []).filter(this.nameable); const first = (summary ?? "").split("\n").find((l) => l.trim())?.trim().slice(0, 300); const line = first && !withheld && this.nameable(first) ? first : undefined; // One line per overlapping task of the recipient, so a single notice names all of them (#713). const touches = hits.map((hit) => `#${hit.task.id} on ${this.where(hit)}${this.sameFileDifferentSymbols(task, hit) ? " (same file, different symbols; observed names only, deleted definitions may be missing)" : ""}`); const open = hits.length > 1 ? `your open tasks ${touches.join("; ")}` : `your open ${touches[0]}`; return [ `Task #${task.id} (owner ${task.owner}) is done and touches ${open}. Check your work against it before you go on.`, paths.length ? `Changed files: ${paths.join(", ")}` : "", signatures.length ? `New or changed signatures: ${signatures.join("; ")}` : "", line ? `Summary: ${line}` : "", ].filter(Boolean).join("\n"); } /** The held notices of a cohort, as one list for a member that gets no integration step (issue #107). */ private heldEvidence(cohort: Cohort, task: Task): string | undefined { const lines = [...cohort.held].filter((id) => id !== task.id).flatMap((id) => { const t = this.d.board.get(id); if (!t || this.isPii(t)) return []; const done = [...t.history].reverse().find((h) => h.event === "done"); const mine = this.places(task), theirs = this.places(t); if (mine.repositoryKey !== theirs.repositoryKey) return []; return [this.completedNotice(t, { task, paths: mine.paths.filter((p) => theirs.paths.some((q) => samePlace(p, q))), symbols: [] }, done?.note, done?.withheld)]; }); return lines.length ? lines.join("\n") : undefined; } private planGuardItems(task: Task): NativeItem[] { if (this.isPii(task)) return []; try { const items: NativeItem[] = []; for (const item of this.d.planFails?.(task) ?? []) { const line = sanitize(item.line.replace(/\s+/g, " ").trim()); if (item.kind === "fail" && this.nameable(line) && !items.some(existing => existing.id === item.id)) items.push({ ...item, line }); if (items.length === 8) break; } return items; } catch { return []; } // Optional memory cannot refuse an assignment or review. } /** #1403 B1: no checkout-HEAD fallback, foreign repository read or admission effect. */ private planDriftText(task: Task, stage: "accept" | "done"): string { if ((this.d.sdlc?.config().mode ?? "off") === "off" || !task.plan?.base || this.isPii(task) || task.owner && this.d.privateTurn?.(task.owner)) return ""; let report: import("./plan-conformance.ts").PlanDrift = { state: "unknown", paths: [] }; try { const source = this.d.auditSource, base = task.plan.base; if (source?.defaultTip && source.mergeBase && /^[a-f0-9]{40}$/.test(base) && this.repositories.scope(task.refs).key === this.repositories.project.key && (!task.sdlc?.repo || this.repositories.scope({ repo: task.sdlc.repo, paths: task.refs.paths }).key === this.repositories.project.key) && source.resolve(base) === base) { const tip = source.defaultTip(), head = stage === "done" ? this.reviewHead(task) : undefined; const endpoint = tip && /^[a-f0-9]{40}$/.test(tip) && source.resolve(tip) === tip ? stage === "accept" ? tip : head && /^[a-f0-9]{40}$/.test(head) && source.resolve(head) === head ? source.mergeBase(head, tip) : undefined : undefined; if (endpoint && /^[a-f0-9]{40}$/.test(endpoint) && source.resolve(endpoint) === endpoint && source.mergeBase(base, endpoint) === base) { report = planDrift(task.plan.paths?.map(path => this.projectPath(path)), source.changed(base, endpoint)); if (source.defaultTip() !== tip) report = { state: "unknown", paths: [] }; } } if (report.paths.some(path => !this.publicMetadataText(path))) report = { state: "unknown", paths: [] }; } catch { /* Optional local Git evidence is unknown, never a failed task transition. */ } return `Plan drift at ${stage} (upstream advice only): drift: ${report.state}${report.paths.length ? ` (${report.paths.join("; ")})` : ""}`; } /** Current plan advice for an accepted plan's tool result, which has no new assignment envelope. */ planGuardText(task: Task): string { const items = this.planGuardItems(task); return [this.planDriftText(task, "accept"), items.length ? ["Live fail notes for this plan (advice, not a block):", ...items.map(item => item.line)].join("\n") : ""].filter(Boolean).join("\n"); } /** The one place a review request is written: the first reviewer and a replacement get the same text, refs and privacy. */ /** Review admission is separate from brief construction (#228). All refusals precede the requesting done's writes. */ private async reviewRequestAdmission(task: Task, refs?: TaskRefs, preEffect = true, actor: PeerId = task.owner ?? USER, previous?: PrEvidence, sameRequest?: () => boolean, stage: (task: Task) => Task = task => task, prepareOnly = false, refileHead?: RefileHeadGuard): Promise { const mode = (this.d.sdlc?.config() ?? sdlcConfig(undefined)).mode; const anchored = this.reviewFindingSets(task).some(set => set.items.some(item => item.anchor)); if (mode === "off" && !this.d.prepareReviewBrief && !anchored) return undefined; let quietDrift = false; const guard = () => { if (actor !== USER && actor !== task.owner) { const holders = Object.entries(this.d.roles ?? {}).filter(([peer, roles]) => !isRemotePeerId(peer) && Array.isArray(roles) && roles.includes("conductor")).map(([peer]) => peer); if (holders.length !== 1 || holders[0] !== actor) throw new (preEffect ? PreEffectToolRefusal : Error)("review admission authority changed"); } // #694: the board copy seen through the same staged identity link the caller's task carries. const current = stage(this.need(task.id, false, preEffect)); const changed = current.history.length !== task.history.length; const quiet = current.history.length > task.history.length && current.history.slice(task.history.length).every(entry => QUIET_EVENTS.has(entry.event)); const sameHistory = !changed || (mode === "advise" && quiet) || !!sameRequest?.(); if ((this.d.sdlc?.config().mode ?? "off") !== mode || !sameHistory || current.owner !== task.owner || mode !== "advise" && current.reviewer !== task.reviewer || this.isPii(current) !== this.isPii(task) || JSON.stringify(current.sdlc ?? null) !== JSON.stringify(task.sdlc ?? null) || mode === "advise" && (current.state !== task.state || current.refs.commit !== task.refs.commit) || actor !== USER && this.d.privateTurn?.(actor) && !this.isPii(current)) throw new (preEffect ? PreEffectToolRefusal : Error)("task or authority changed during review admission"); quietDrift ||= mode === "advise" && changed && quiet; return current; }; guard(); if (!this.isPii(task) && this.d.prepareReviewBrief) { try { await this.d.prepareReviewBrief({ ...task, refs: { ...task.refs, ...cleanRefs(refs) } }); } catch { /* Optional code facts must not refuse a review. */ } guard(); } if (prepareOnly) return undefined; if (mode === "off") { if (!anchored) return undefined; const placements = await this.prepareFindingPlacements(task, refs, guard); const admission: ReviewReadiness = { ready: false, blockers: [] }; this.findingPlacements.set(admission, { binding: this.findingPlacementBinding({ ...task, refs: { ...task.refs, ...cleanRefs(refs) } }), placements, placementOnly: true }); return admission; } const expected = cleanRefs(refs).commit ?? task.refs.commit ?? task.sdlc?.head ?? task.sdlc?.localHead; const read: SdlcGh = (args, timeout, cwd, cap) => { guard(); if (quietDrift) throw new Error("review readiness unknown: task changed during readback"); return (this.d.sdlc?.gh ?? sdlcGh)(args, timeout, cwd, cap); }; const evidence: ReviewReadiness = this.isPii(task) ? { ready: false, blockers: ["private review readiness unavailable"] } : task.sdlc ? reviewReadinessFromEvidence(previous, expected, this.d.sdlc ? requiredChecksFor(this.d.sdlc.config(), task.sdlc.repo) : [], task.sdlc.repo) ?? await readReviewReadiness(task.sdlc, expected, read, this.d.sdlc ? requiredChecksFor(this.d.sdlc.config(), task.sdlc.repo) : []) : { ready: false, blockers: ["review PR identity missing"] }; const currentHead = refileHead && !evidence.head && task.sdlc ? await readSdlcPrHead(task.sdlc, read) : evidence.head; const current = guard(); const admitted: ReviewReadiness = quietDrift ? { ready: false, blockers: ["review readiness unknown: task changed during readback"] } : evidence; if (refileHead) { if (!refileHead.recorded || !currentHead) throw this.reviewHeadMoveRefusal(task.id, refileHead.recorded); if (currentHead !== refileHead.recorded) throw this.reviewHeadMoveRefusal(task.id, refileHead.recorded, currentHead); } if (!admitted.ready) { const message = `task ${this.publicTitle(current)}: premature review: ${admitted.blockers.join("; ")}`; if (mode === "enforce") throw new (preEffect ? PreEffectToolRefusal : Error)(message); this.releaseNotice(message); } if (anchored) { const placements = await this.prepareFindingPlacements(task, refs, guard); this.findingPlacements.set(admitted, { binding: this.findingPlacementBinding({ ...task, refs: { ...task.refs, ...cleanRefs(refs) } }), placements, placementOnly: false }); } return admitted; } /** * #824: one `Hub-verified at ` line from the review admission, for every reviewer. Ready: the required checks that passed at this exact head (and an identical-tree run when the hub * reused one) and that no bot review thread is waiting for a reply (the readiness rule: an unresolved thread a person already answered does not block, so the line says exactly that). Not ready (advise mode sends anyway): its blockers. No admission (sdlc off, or a request sent without one) and a PII task: no block, the * admission of a PII task being only a stub. Every word comes from the hub's own readiness read; blockers are fixed hub strings, never PR text. */ private hubVerifiedBlock(task: Task, admission?: ReviewReadiness): string { if (!admission || this.isPii(task) || this.findingPlacements.get(admission)?.placementOnly) return ""; const head = admission.head ?? this.reviewHead(task) ?? "unknown head"; if (admission.ready) { const names = admission.checks?.length ? admission.checks.join(", ") : "the required checks"; if (admission.deferred?.length) return `Hub-verified at ${head}: required checks ${names} passed at this exact head; ${admission.deferred.join(", ")} deferred on draft; no bot review thread is waiting for a reply. Full CI is still required before merge.\n`; return `Hub-verified at ${head}: required checks ${names} passed at this exact head${admission.reusedRun !== undefined ? ` via identical-tree run ${admission.reusedRun}` : ""}; no bot review thread is waiting for a reply.\n`; } return `Hub-verified at ${head}: not ready: ${admission.blockers.join("; ")}.\n`; } private sendReview(task: Task, reviewer: PeerId, why = "", admission?: ReviewReadiness): boolean { const mode = (this.d.sdlc?.config() ?? sdlcConfig(undefined)).mode; if (mode === "enforce" && !admission?.ready) { // Background roster/quota role changes are retained, but never invent a remotely admitted review request. this.releaseNotice(`task ${this.publicTitle(task)}: premature review held; retry the reviewer assignment after current CI and bot replies are verified`); this.holdReview(task, reviewer); return false; } const r = task.refs; const last = [...task.history].reverse().find((h) => h.event === "done"); const where = [r.branch ? `branch ${r.branch}` : "", r.commit ? `commit ${r.commit}` : "", r.paths?.length ? `paths ${r.paths.join(", ")}` : ""].filter(Boolean).join("; "); // A checklist that maps the change to its contract (issue #35): reviewers who check against the written plan catch more. const plan = planText(task.plan); const check = [...task.history].reverse().find((h) => h.event === "check passed"); const cachedPlanRead = this.planReads.get(task.id); const planRead = this.planReport(task, cachedPlanRead?.identity === this.planReadIdentity(task) && cachedPlanRead.evidence.head === this.findingHead(task) ? cachedPlanRead.evidence : undefined); const conformanceText = mode !== "off" ? this.screen(task, `Plan conformance: ${JSON.stringify(planRead)}`, "plan conformance", reviewer) + "\n" : ""; // #1403 A2: from the same cached PR read as plan conformance. No cached read is `unknown`, never "not required", so a missing readback still points the reviewer at the checklist. const securityLine = mode !== "off" ? securityRequestLine(this.securityView(task, cachedPlanRead?.identity === this.planReadIdentity(task) && cachedPlanRead.evidence.head === this.findingHead(task) ? cachedPlanRead.evidence : undefined)) : undefined; const securityText = securityLine ? this.screen(task, securityLine, "security pass", reviewer) + "\n" : ""; const profile = (task.profile ?? "dev") === (this.d.profile ?? "dev") ? profileData(this.d.profileData ?? task.profile ?? "dev") : profileData(task.profile); const target = plan ? `the plan (${plan})` : task.detail ? "the task detail above" : "the task title"; const noCheckWording = profile.name === "research" || profile.name === "writing" ? "No check ran for this class: verify the claims and sources yourself." : profile.name === "general" ? "No check ran for this class: verify the outcome yourself." : "No check ran for this class: run the affected tests yourself."; // #824: the hub's own exact-head CI evidence, from the admission this request already carries (no new gh call). Nothing here comes from the builder's summary or a recorded claim. const codeScoped = this.d.reviewScope?.(reviewer) === "code"; const verified = codeScoped ? "" : this.hubVerifiedBlock(task, admission); const ciPassed = admission?.ready === true && !admission.deferred?.length && !this.isPii(task); // #852 AC2: a code-scope reviewer's sandbox cannot run tests or read CI, so its Hub-verified and check lines are replaced by one fixed line. const checkResult = codeScoped ? CODE_SCOPE_LINE : check ? `Check result: ${(check.note ?? "").split("\n")[0]}` : ciPassed ? "CI passed at this exact head (see the Hub-verified line above); do not list test execution or CI evidence as unmet: name the specific missing test or behaviour instead." : noCheckWording; const checklistTemplates = profile.review_checklist ?? [ "Map the changed signatures and call sites to {target}, and name each one that does not match.", "{check}", "List what is unmet in hub_review's unmet, one item each.", ]; const checklistLines = checklistTemplates.map(template => template.replaceAll("{target}", target).replaceAll("{check}", checkResult) ); // #507b: the task's recorded acceptance criteria (the #481 S8 checklist, ids and all). A PII task shows none: its checklist is private. const recorded = this.isPii(task) ? undefined : checklistOf(task.sdlc); const criteriaBlock = recorded?.criteria.length ? ["Acceptance criteria (name an id at the start of an unmet item, such as \"AC1: what is missing\"):", ...recorded.criteria.map(c => `- ${c.id}${c.required ? "" : " (optional)"}: ${c.result}`)].join("\n") + "\n" : ""; // #509a: what was delivered, by id, hash and size. A private record (a PII task, or a path under pii.paths) shows no path. const delivered = publicDeliverables(latestDeliverables(task.history), this.nameable); const deliverablesBlock = delivered?.length ? ["Deliverables (the hub hashed these files when the task was done; approval binds these hashes):", ...delivered.map(d => `- ${d.id}: ${d.path ?? "(path withheld)"} [${d.format}${d.version ? ` ${d.version}` : ""}] sha256 ${d.sha256.slice(0, 16)}, ${d.bytes} bytes`)].join("\n") + "\n" : ""; const rulings = this.plannerRulings(task, reviewer); const rulingsBlock = rulings.length ? rulings.map(ruling => [ `Planner rulings (recorded by the configured planner ${ruling.by}; they amend the plan for this review):`, `- ${new Date(ruling.at).toISOString()}: ${ruling.note.replace(/[\r\n]+/g, " ")}`, ].join("\n")).join("\n") + "\n" : ""; const checklist = deliverablesBlock + criteriaBlock + [ "Checklist:", ...this.planGuardItems(task).map(item => `- Check the plan against this live fail before the remaining checks: ${item.line}`), ...checklistLines.map(line => `- ${line}`), ...(rulings.length ? ["- a departure a listed ruling names is not an unmet item by itself; judge its code."] : []), ].join("\n"); // #223 R2: a reviewer-only instance judges from facts; the builder's narrative stays out, earlier findings go in. const reviewOnly = this.d.reviewOnly?.(reviewer) === true; const summary = reviewOnly ? "(summary withheld from a review-only reviewer; judge the change itself)" : last?.note ? this.screen(task, last.note, "summary", reviewer, last.withheld) : "(no summary)"; const specRepo = task.sdlc?.repo ?? task.external?.repo, specIssue = task.sdlc?.issue ?? task.external?.issue; const spec = reviewOnly && specRepo && specIssue ? `Spec issue: ${specRepo}#${specIssue}\n` : ""; const findings = reviewOnly ? task.history.filter(h => h.event === "changes_requested" && h.note).map(h => `- ${h.by}: ${this.screen(task, h.note!, "review note", reviewer, h.withheld)}`) : []; const carried = findingsForHead(this.reviewFindingSets(task), this.findingHead(task)).filter(item => item.severity === "important" && item.disposition === "open"); const visible = this.isPii(task) ? [] : carried.filter(item => this.findingTextAllowed(task, [item]) && !task.history.some(entry => entry.withheld && entry.reviewFindings?.items.some(value => value.id === item.id))); const prepared = admission && this.findingPlacements.get(admission); const placements = prepared?.binding === this.findingPlacementBinding(task) ? prepared.placements : undefined; // ponytail: rare synchronous role re-offers without an async admission show unavailable until refreshed; no old location is guessed. const carriedText = carried.length ? `Open Important findings carried until explicitly dispositioned: ${carried.length}\n${visible.map(item => { const { id, pass, severity, path } = item, legacy = JSON.stringify({ id, pass, severity, ...(path ? { path } : {}) }); return item.anchor ? legacy + "\n" + renderFindingAnchor(item, this.reviewPathPrivate(item.anchor.path) ? { status: "unavailable" } : placements?.get(id) ?? { status: "unavailable" }) : legacy; }).join("\n")}${visible.length < carried.length ? "\nSome finding details withheld." : ""}\n` : ""; const guidance = this.roleGuidance(task, reviewer, true); let projection = ""; try { const text = this.d.projectedReview?.(task); if (text) projection = this.screen(task, sanitize(text), "document projection", reviewer); } catch { projection = "(document projection unavailable)"; } const brief = this.briefText(task); // #572 AC3: advisory only, from git state never from task text, so it is safe for a PII task too. const checkout = mainCheckoutWarning(this.d.cwd, this.publicMetadataText); const body = `Review task #${task.id} [${profileTaskLabel(task)}] ${task.title}\nDone by ${last?.by ?? task.owner}: ${summary}\n${where ? `Where: ${where}\n` : ""}${last?.noWrites ? "no writes recorded since acceptance\n" : ""}${spec}${why ? `${why}\n` : ""}${!plan && task.detail ? `Task detail:\n${task.detail}\n` : ""}${guidance ? guidance + "\n" : ""}${projection ? projection + "\n" : ""}${brief ? brief + "\n" : ""}${checkout ? `Note: ${checkout}.\n` : ""}${findings.length ? `Earlier findings (set a disposition for each):\n${findings.join("\n")}\n` : ""}${carriedText}${conformanceText}${securityText}${rulingsBlock}${verified}${checklist}\nGive your verdict with hub_review {id: ${task.id}, verdict: "approved" | "changes_requested", note, unmet, findings: [{id, pass: "bugs" | "security" | "compliance", severity: "important" | "nit", path?, disposition: "open" | "fixed" | "false_positive"}]}. Reuse finding ids when updating their disposition; only the person may accept a finding with a rationale.`; const comments = this.d.board.reviewCommentCounts(task.id, task.created); const quoteMaterial = task.history.some(entry => entry.reviewFindings?.items.some(item => item.anchor !== undefined)) || comments.sent + comments.resolved + comments.dismissed > 0; return this.d.bus.publish(newEnvelope(HUB, body, { to: [reviewer], kind: "review", priority: "important", refs: { ...r, ...(quoteMaterial ? { reviewPackage: `reviewer-request-${crypto.randomUUID()}` } : {}), ...(this.reviewHead(task) ? { commit: this.reviewHead(task)! } : {}), task: String(task.id), reviewRevision: String(this.reviewRequestRevision(task)) }, ...(this.isPii(task) ? { private: true } : {}) })).includes(reviewer); } /** #785 P1b: remember a review the hub held as premature, so a green CI at this exact head can re-offer it once. Also watches that head. */ private holdReview(task: Task, reviewer: PeerId): void { try { const head = this.reviewHead(task); if (this.isPii(task) || !head || reviewer === USER) return; this.heldReviews.set(task.id, { head, reviewer, revision: this.reviewRequestRevision(task) }); this.watchCi(task); } catch { /* optional bookkeeping never fails a review path */ } } /** #785 P1b AC3: start the one watcher for this task's exact head. Not for private work, an unlinked PR or a lifecycle that is off; never throws. */ private watchCi(task: Task): void { try { const head = this.reviewHead(task), repo = task.sdlc?.repo, pr = task.sdlc?.pr; if (!this.d.sdlc || this.d.sdlc.config().mode === "off" || this.isPii(task) || task.state !== "in_review" || !head || !/^[0-9a-f]{40}$/.test(head) || !repo || !pr) return; this.ciWatchers.start({ id: task.id, head, repo, pr }); } catch { /* a watcher that cannot start leaves the review path as it was */ } } /** The watcher's own check before every read and every notice: the task must still be in review at this exact head and PR. */ private ciWatchCurrent(watch: CiWatch): boolean { const task = this.d.board.get(watch.id); return !!task && task.state === "in_review" && !this.isPii(task) && this.reviewHead(task) === watch.head && task.sdlc?.repo === watch.repo && task.sdlc?.pr === watch.pr && (this.d.sdlc?.config().mode ?? "off") !== "off"; } /** * #785 P1b: the result of the exact head's CI, told once to the owner and the reviewer (one ids-only task envelope each, `status` weight: `fyi` is recorded but never delivered to the peer), * then a review held as premature is offered once more after a fresh readiness read. A deadline tells the console only. */ private async ciCompleted(watch: CiWatch, outcome: CiOutcome): Promise { const task = this.d.board.get(watch.id); if (!task || !this.ciWatchCurrent(watch)) return; const label = `#${task.id} head ${watch.head.slice(0, 12)}`; if (outcome === "deadline") { this.releaseNotice(`task ${label}: CI did not finish within the watch deadline; no further reads`); return; } const line = `ci_completed: ${label} ${outcome}`; for (const peer of new Set([task.owner, task.reviewer])) { if (!peer || peer === HUB) continue; if (peer === USER) { this.releaseNotice(`task ${label}: CI ${outcome} at its exact head`); continue; } this.releaseNotice(`task ${label}: could not tell ${peer} the CI result`, () => this.d.bus.publish(newEnvelope(HUB, `${line}\nRead hub_task_show for the task before acting.`, { to: [peer], kind: "task", priority: "status", refs: { task: String(task.id), commit: watch.head } }))); } if (outcome === "failed") return; await this.reofferHeldReview(task, watch); } /** The held review of this exact head and request, once: only while it is still the same reviewer, head and revision, and a fresh admission says it is ready. */ private async reofferHeldReview(task: Task, watch: CiWatch): Promise { const held = this.heldReviews.get(task.id); if (!held || held.head !== watch.head || task.reviewer !== held.reviewer || this.reviewRequestRevision(task) !== held.revision) return; this.heldReviews.delete(task.id); // once: a later hold needs a new head or a new request try { const admission = await this.reviewRequestAdmission(task, undefined, false, task.owner ?? USER); const current = this.d.board.get(task.id); if (!admission?.ready || !current || !this.ciWatchCurrent(watch) || current.reviewer !== held.reviewer || this.reviewRequestRevision(current) !== held.revision) return; this.releaseNotice(`task ${this.publicTitle(current)}: could not re-offer the held review to ${held.reviewer}`, () => this.sendReview(current, held.reviewer, "(Held earlier because exact-head CI was not green; it is green now.)", admission)); } catch { /* still not ready: the hold notice already named why; a reviewer reassignment retries it */ } } /** Daemon shutdown: no watcher outlives the hub. */ private readonly reviewerQuotaTimers = new Map }>(); private readonly reviewerQuotaRunning = new Set(); private reviewerQuotaStopped = false; private priorReviewerQuotaWait(task: Task): NonNullable | undefined { const binding = this.queueReviewBinding(task), firstReview = task.history.findIndex(row => row.event === "done"); // Role routing before the first completion never starts a review deadline. return firstReview < 0 ? undefined : task.history.slice(firstReview).findLast(row => row.reviewerQuotaWait?.created === task.created && row.reviewerQuotaWait.binding === binding)?.reviewerQuotaWait; } private activeReviewerQuotaWait(task: Task): NonNullable | undefined { const role = task.history[this.reviewRequestRevision(task) - 1]; return task.state === "in_review" && task.reviewer === null && !this.isPii(task) && !this.manuallyNamedReviewer(task) && role?.reviewerQuotaWait?.created === task.created && role.reviewerQuotaWait.binding === this.queueReviewBinding(task) ? role.reviewerQuotaWait : undefined; } /** Host board-change hook: a changed head/incarnation/privacy/role cancels the old deadline immediately. */ reviewQuotaTaskChanged(task: Task): void { const wait = this.activeReviewerQuotaWait(task), prior = this.reviewerQuotaTimers.get(task.id); const key = wait ? JSON.stringify([task.created, wait.binding, wait.since, wait.deadline, wait.resetAt, this.reviewRequestRevision(task)]) : undefined; if (prior?.key === key) return; if (prior) clearTimeout(prior.timer); this.reviewerQuotaTimers.delete(task.id); if (!wait || this.reviewerQuotaStopped || this.studyHold()) return; const now = this.d.now?.() ?? Date.now(); const wake = wait.resetAt > now ? wait.resetAt : wait.resetAt + 60_000 > now ? wait.resetAt + 60_000 : wait.deadline; const timer = setTimeout(() => { if (this.reviewerQuotaTimers.get(task.id)?.key !== key) return; this.reviewerQuotaTimers.delete(task.id); void this.refreshReviewerQuotaWait(task.id).catch(() => {}); }, Math.min(2_147_483_647, Math.max(0, Math.min(wait.deadline, wake) - now))); timer.unref?.(); this.reviewerQuotaTimers.set(task.id, { key: key!, timer }); } /** Reading/reset signals and recovery release call this; no quota polling or native transport is added. */ refreshReviewerQuotaWaits(): void { if (this.reviewerQuotaStopped || this.studyHold()) return; for (const task of this.d.board.list("in_review")) { this.reviewQuotaTaskChanged(task); if (this.activeReviewerQuotaWait(task)) void this.refreshReviewerQuotaWait(task.id).catch(() => {}); } } private async refreshReviewerQuotaWait(id: number): Promise { if (this.reviewerQuotaStopped || this.reviewerQuotaRunning.has(id) || this.studyHold()) return; this.reviewerQuotaRunning.add(id); try { await this.studyWrite(async () => { const before = this.d.board.get(id), wait = before && this.activeReviewerQuotaWait(before); if (!before || !wait) return; const revision = this.reviewRequestRevision(before), identity = JSON.stringify([before.created, wait.binding, wait.since, wait.deadline]); const valid = () => { const task = this.d.board.get(id), live = task && this.activeReviewerQuotaWait(task); return !this.reviewerQuotaStopped && !this.studyHold() && task && live && this.reviewRequestRevision(task) === revision && JSON.stringify([task.created, live.binding, live.since, live.deadline]) === identity ? task : undefined; }; const choose = (task: Task) => assign(task, this.states(), this.d.routing(), { ...this.weights(task.class, task), candidates: [], ...(task.owner ? { notReviewer: task.owner } : {}) }); let selection = choose(before); if (selection.reviewSelection?.quotaWait) { if (selection.reviewSelection.quotaWait.resetsAt !== wait.resetAt) { const next = this.d.board.update(before.id, HUB, "reviewer changed", { reviewer: null }, this.assignmentNote("reviewer quota reset observation changed", selection), this.reviewMetadata(selection, before), before.history.length); this.queueReviewWritten(next); } else this.reviewQuotaTaskChanged(before); return; } let admission: ReviewReadiness | undefined, admissionFailed = false; // Ending an account wait is not permission to send native review input. A person fallback needs no native admission. if (selection.reviewer && selection.reviewer !== USER) { try { admission = await this.reviewRequestAdmission(before, undefined, true, before.owner ?? USER, undefined, () => !!valid()); } catch { admissionFailed = true; } } const task = valid(); if (!task) return; selection = choose(task); if (selection.reviewSelection?.quotaWait) { this.reviewQuotaTaskChanged(task); return; } // Failed readiness/authority never sends native facts, but cannot extend the original quota deadline. const reviewer = admissionFailed ? USER : selection.reviewer ?? USER; const next = this.d.board.update(task.id, HUB, "reviewer changed", { reviewer }, this.assignmentNote("reviewer quota wait ended", selection), this.reviewMetadata(selection, task), task.history.length); this.queueReviewWritten(next); if (reviewer === USER) this.releaseNotice(`task ${this.publicTitle(next)}: reviewer quota wait ended; the person must review`); else this.releaseNotice(`task ${this.publicTitle(next)}: review request unavailable after quota wait`, () => this.sendReview(next, reviewer, "", admission)); }); } finally { this.reviewerQuotaRunning.delete(id); } } stopCiWatchers(): void { this.ciWatchers.stopAll(); this.heldReviews.clear(); this.reviewerQuotaStopped = true; for (const row of this.reviewerQuotaTimers.values()) clearTimeout(row.timer); this.reviewerQuotaTimers.clear(); } private reviewRequestRevision(task: Task): number { // Role changes fence older requests; bookkeeping appended after the request does not. return task.history.findLastIndex(entry => ["done", "reviewer changed", "reviewer unavailable"].includes(entry.event) || OWNERSHIP_EVENTS.has(entry.event)) + 1; } /** Host-only admission for a queued review after asynchronous native preparation. */ reviewBindingCurrent(by: PeerId, id: number, binding: { head?: string; flowRevision?: number }): boolean { requireLocalTaskPeer(by); const task = this.d.board.get(id); return !!task && task.state === "in_review" && task.reviewer === by && !this.isPii(task) && this.reviewRequestRevision(task) === binding.flowRevision && this.reviewHead(task) === binding.head; } /** Host-only failure report, bound to the exact review request and its still-current child generation. */ async retryReviewer(id: number, failedPeer: PeerId, failure: { head?: string; flowRevision?: number; cause: "start_failed" | "quota" | "no_verdict"; reason?: "review time cap" }, current: () => boolean, onReoffered?: () => void): Promise { requireLocalTaskPeer(failedPeer); if (!failure || !["start_failed", "quota", "no_verdict"].includes(failure.cause) || !/^[a-z][a-z0-9-]{0,63}$/.test(failedPeer) || !Number.isSafeInteger(failure.flowRevision) || failure.flowRevision! < 1 || failure.head !== undefined && (typeof failure.head !== "string" || text(failure.head) !== failure.head || Buffer.byteLength(failure.head) > 1200 || /\p{Cc}/u.test(failure.head))) throw new PreEffectToolRefusal("invalid reviewer failure binding"); const valid = () => { const task = this.need(id, false, true); if (!current() || task.state !== "in_review" || task.reviewer !== failedPeer || this.reviewRequestRevision(task) !== failure.flowRevision || this.reviewHead(task) !== failure.head || this.isPii(task) || this.manuallyNamedReviewer(task) && failure.cause !== "no_verdict") throw new PreEffectToolRefusal("reviewer failure is no longer current"); return task; }; const before = valid(); const admission = await this.reviewRequestAdmission(before, undefined, true, before.owner ?? USER, undefined, () => { valid(); return true; }); const task = valid(); const options = this.reviewPoolOptions(task); // A person-selected reviewer never falls through to an agent the person did not select. const manual = this.manuallyNamedReviewer(task); const selection = manual ? undefined : assign(task, this.states(), this.d.routing(), { ...this.weights(task.class, task), candidates: [], ...(task.owner ? { notReviewer: task.owner } : {}), reviewPool: { ...options, failed: failure.cause === "quota" ? options.failed : [...options.failed, failedPeer] } }); if (!selection?.reviewSelection && failure.cause !== "no_verdict") throw new PreEffectToolRefusal("no declared reviewer pool can receive the fallback"); const quotaWaiting = selection?.reviewSelection?.quotaWait !== undefined; const reviewer = selection?.reviewSelection ? selection.reviewer ?? USER : USER; valid(); const note = manual ? "named reviewer recorded no verdict; the person must review" : selection?.reviewSelection ? this.assignmentNote(`reviewer unavailable: ${failure.reason ?? failure.cause}`, selection) : "no declared reviewer pool can receive the fallback; the person must review"; const next = this.d.board.update(task.id, HUB, "reviewer unavailable", { reviewer: quotaWaiting ? null : reviewer }, note, { ...this.reviewMetadata(selection, task), ...(reviewer === USER ? { reviewBlocked: true } : {}), reviewerFailure: { peer: failedPeer, cause: failure.cause, ...(failure.reason ? { reason: failure.reason } : {}), ...(failure.head ? { head: failure.head } : {}) } }, task.history.length); this.queueReviewWritten(next); this.releaseNotice(`task ${this.publicTitle(next)}: former review request withdrawal incomplete`, () => this.withdrawRoleRequest(task, next, "reviewer")); let offered = quotaWaiting; if (quotaWaiting) { try { onReoffered?.(); } catch { /* The saved wait remains authoritative. */ } } else if (reviewer === USER) { const notice = `task ${this.publicTitle(next)}: blocked: the person must review`; this.releaseNotice(notice, () => { this.d.notify(notice); offered = true; }); } else this.releaseNotice(`task ${this.publicTitle(next)}: fallback review request unavailable`, () => { offered = this.sendReview(next, reviewer, "", admission); }); if (offered && current() && this.reviewBindingCurrent(reviewer, next.id, { head: this.reviewHead(next), flowRevision: this.reviewRequestRevision(next) })) { try { onReoffered?.(); } catch { /* Unconfirmed host settlement retains the delivery hold. */ } } return next; } private codeSymbolsRepository(task: Task) { try { const repository = this.repositories.scope(task.refs); if (task.sdlc?.repo && this.repositories.scope({ repo: task.sdlc.repo }).key !== repository.key) return undefined; return repository; } catch { return undefined; } } /** Read-time code advice uses this project's tree only; declared foreign or inconsistent scope is unknown. */ memoryCodeEligible(task: Task): boolean { if (this.isPii(task)) return false; const repository = this.codeSymbolsRepository(task); return !!repository && repository.key === this.repositories.project.key && !this.repositories.mismatch(task.refs, task.plan); } /** Read-only host input for exists verification; private/foreign/stale observations supply nothing. */ memorySymbolCandidates(task: Task): string[] | undefined { if (this.isPii(task) || !this.d.store) return undefined; const observed = this.observedCodeSymbols(task); return observed?.state === "known" ? observed.symbols.map(symbol => symbol.id) : undefined; } /** Only current host observations and positive exists checks may anchor the completion note. */ private completionMemorySymbols(task: Task): MemorySymbolNodes { const unknown: MemorySymbolNodes = { state: "unknown", nodes: [], unknown: 0, truncated: false }; if (this.isPii(task) || !this.d.store) return unknown; const repository = this.codeSymbolsRepository(task); if (!repository || repository.key !== this.repositories.project.key) return unknown; const observed = publicTaskCodeSymbols(task.codeSymbols, this.reviewHead(task), repository.key, this.publicMetadataText); if (!observed || observed.state !== "known") return unknown; try { const verified = this.d.memorySymbolNodes?.(task); if (!verified) return unknown; const context = { cwd: this.d.cwd, project: this.d.store.project, repo: this.d.store.repo, deny: this.d.store.deny, allowed: this.publicMetadataText }; const actual = new Set(observed.symbols.map(symbol => canonicalMemorySymbolNode(symbol.id, context)).filter(Boolean)); const nodes = [...new Set(verified.nodes)].filter(node => actual.has(node) && canonicalMemorySymbolNode(node, context) === node).slice(0, MEMORY_SYMBOL_LIMIT); const complete = observed.complete && verified.state === "known" && nodes.length === verified.nodes.length; return { state: complete ? "known" : "unknown", nodes, unknown: verified.unknown, truncated: verified.truncated || nodes.length !== verified.nodes.length }; } catch { return unknown; } } /** Host observations are saved only with an admitted transition, never by an optional read. */ private observedCodeSymbols(task: Task) { if (this.isPii(task) || !task.refs.commit) return undefined; const repository = this.codeSymbolsRepository(task); // ponytail: the brief analyzes the validated project execution root. Foreign repositories stay unknown // until the brief carries independent repository provenance; a model's refs.repo cannot supply that proof. if (!repository || repository.key !== this.repositories.project.key) return undefined; try { const brief = this.d.reviewBrief?.(task); const observation = brief && !("unavailable" in brief) ? buildTaskCodeSymbols(brief, repository.key, this.publicMetadataText) : undefined; // A resolved short ref or a stale provider result is unknown advice, never a reason to refuse done. return observation?.head === task.refs.commit ? observation : undefined; } catch { return undefined; } // Optional metadata never costs the admitted result. } /** #520: the rendered review brief of a non-PII task's commit, or why there is none; empty without a commit. */ briefText(task: Task): string { if (this.isPii(task)) return ""; const approval = approvalText(approvalBinding(task)); const spec = this.currentSpecReport(task); const prefix = (brief: string) => [approval, spec ? renderSpecTaskReport(spec) : "", brief].filter(Boolean).join("\n"); if (!task.refs.commit) return prefix(""); try { const brief = this.d.reviewBrief?.(task); if (!brief) return prefix(""); return prefix("unavailable" in brief ? `Review brief unavailable: ${brief.unavailable}.` : sanitize(renderReviewBrief(brief))); } catch { return prefix("Review brief unavailable: it could not be built."); } } async review(by: PeerId, id: unknown, verdict: unknown, note?: string, unmet?: unknown, head?: unknown, coverage?: unknown, findings?: unknown, securityPass?: unknown): Promise { if (by !== USER && hasReviewAnchorInput(findings)) { try { this.d.onReviewObserverInput?.(by); } catch { throw new PreEffectToolRefusal("the anchored review input could not be privately scoped; retry after ordinary new input"); } } const evidenceObserverExcluded = this.observerExcluded(by); const requestCheck = this.requestCheck(by); if (typeof id !== "number" && !(typeof id === "string" && /^\s*\d+\s*$/.test(id))) this.need(id, false, true); const authority = by === USER ? undefined : this.d.reviewAuthority?.(by, Number(id)); let findingGuard: ((task: Task) => void) | undefined; // #520: what the coverage was checked against, pinned through every await: the commit and the lifecycle receipt (the // inherited reviewedHead lives there). let covered: { commit: string | undefined; receipt: string } | undefined; let conformanceIdentity: string | undefined; let reviewRound: number | undefined; let withdrawalRevision: number | undefined; const before = this.need(id, false, true); const reviewObserverTurn = this.reviewObserverTurn(by, before.id); const withdrawing = before.state === "approved" && verdict === "changes_requested"; const valid = (): Task => { requestCheck(); const refused = authority?.(); if (refused) throw new PreEffectToolRefusal(refused); // rechecked after every await, right before each write const t = this.need(id, false, true); if (withdrawalRevision !== undefined && t.history.length !== withdrawalRevision) throw new PreEffectToolRefusal(`task #${t.id}: approval changed during withdrawal`); if (reviewRound !== undefined && this.reviewRequestRevision(t) !== reviewRound) throw new PreEffectToolRefusal(`task #${t.id}: review request changed during the verdict; review the new head`); if (covered && (t.refs.commit !== covered.commit || JSON.stringify(t.sdlc ?? null) !== covered.receipt)) throw new PreEffectToolRefusal(`task #${t.id}'s commit or lifecycle receipt changed during the verdict: review the new head`); this.mine(t, by, "reviewer", true); if (verdict !== "approved" && verdict !== "changes_requested") throw new PreEffectToolRefusal('verdict must be "approved" or "changes_requested"'); if (t.state !== (withdrawing ? "approved" : "in_review")) throw new PreEffectToolRefusal(`task #${t.id} is ${t.state}: cannot move to ${verdict} before its owner calls hub_task_done`); if (conformanceIdentity !== undefined && conformanceIdentity !== this.planIdentity(t)) throw new PreEffectToolRefusal("plan conformance identity changed during verdict"); if (t.sdlc?.merge?.state === "merged") throw new PreEffectToolRefusal(`task #${t.id}: PR is merged`); findingGuard?.(t); return t; }; if ((this.d.sdlc?.config().mode ?? "off") !== "off") conformanceIdentity = this.planIdentity(valid()); const items = textList(unmet); if (items.length) note = `${note ?? ""}\nUnmet: ${items.join("; ")}`.trim(); // #520: an approval accounts for every reviewable path of the brief. enforce refuses before any effect, advise records // the gap in the verdict note, off and a person's own verdict skip it. const mode = this.d.sdlc?.config().mode ?? "off"; const initial = valid(), suppliedFindings = findings !== undefined; reviewRound = this.reviewRequestRevision(initial); if (withdrawing) withdrawalRevision = initial.history.length; if (withdrawing) { await this.unmergedForReopen(initial, valid); valid(); } let parsed: ReviewFinding[]; try { parsed = parseReviewFindings(findings, { person: by === USER, maxNits: this.d.sdlc?.config().maxNits ?? DEFAULT_MAX_NITS, contract: mode === "off" ? "off" : "required" }); } catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid structured findings"); } // #1403 A2: the field exists only under an enabled lifecycle (off neither advertises nor accepts it), and only on a verdict that can carry it. Validated before any board effect. let securityRecord: SecurityPassRecord | undefined; if (securityPass !== undefined) { if (mode === "off") throw new PreEffectToolRefusal("security_pass is not available: the lifecycle is off (set sdlc.mode to advise or enforce in .agenthub/sdlc.toml)"); try { securityRecord = parseSecurityPass(securityPass); } catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid security_pass"); } } const anchorPrivacy = new Map(parsed.flatMap(item => item.anchor ? [[item.anchor.path, this.reviewPathPrivate(item.anchor.path)] as const] : [])); try { parsed = parsed.map(item => item.anchor && anchorPrivacy.get(item.anchor.path) ? { ...item, anchor: privateReviewAnchor(item.anchor) } : item); } catch { throw new PreEffectToolRefusal("private finding path needs an existing lineRange or structural selector; remove quoted selectors and retry"); } const observerExcluded = evidenceObserverExcluded || reviewObserverTurn || parsed.some(item => item.anchor !== undefined); // #852 AC3 (amended): a code-scope reviewer's changes_requested is always recorded, never refused. Without an open structured finding it is // evidence-only: it does not count toward rejections or escalation, the task returns to its owner as usual, and the conductor gets one ids-only // notice. The rule is structural (a finding with disposition open), never a reading of the unmet text. const codeScope = by !== USER && this.d.reviewScope?.(by) === "code"; const evidenceOnly = codeScope && verdict === "changes_requested" && !parsed.some(finding => finding.disposition === "open"); const resolvedHead = this.ownerReviewHead(initial) ?? this.findingHead(initial); let findingHead = resolvedHead; if (head !== undefined) { try { findingHead = sdlcReceipt({ reviewedHead: head }, initial.sdlc, this.d.sdlc?.config() ?? sdlcConfig(undefined)).reviewedHead; } catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid finding head"); } } const report: ReviewFindingSet | undefined = suppliedFindings ? { ...(findingHead ? { head: findingHead } : {}), items: parsed } : undefined; const proposedSets = (task: Task) => [...this.reviewFindingSets(task), ...(report ? [report] : [])]; if (head !== undefined || suppliedFindings || this.reviewFindingSets(initial).length) { const identity = (task: Task) => JSON.stringify({ owner: task.owner, reviewer: task.reviewer, commit: task.refs.commit, receipt: task.sdlc, resolvedHead: this.findingHead(task), private: this.isPii(task), findings: this.reviewFindingSets(task) }); const original = identity(initial); findingGuard = task => { if ([...anchorPrivacy].some(([path, privatePath]) => this.reviewPathPrivate(path) !== privatePath)) throw new PreEffectToolRefusal("review path privacy changed; refresh the task review and retry"); if (identity(task) !== original) throw new PreEffectToolRefusal("task review identity, privacy or findings changed during the verdict; review current work again"); if (by !== USER && suppliedFindings && this.d.privateTurn?.(by) && !this.isPii(task)) throw new PreEffectToolRefusal("structured review of ordinary work is unavailable during a private turn"); if (parsed.filter(item => item.severity === "nit").length > (this.d.sdlc?.config().maxNits ?? DEFAULT_MAX_NITS)) throw new PreEffectToolRefusal("review nit cap exceeded"); if (report?.items.length && !report.head && this.d.sdlc?.config().mode === "enforce") throw new PreEffectToolRefusal("a finding report requires a resolvable full reviewed head in enforce"); const current = findingsForHead(proposedSets(task), findingHead); if (current.length > 64) throw new PreEffectToolRefusal("one reviewed head supports at most 64 distinct finding IDs"); if (verdict === "approved" && this.d.sdlc?.config().mode === "enforce" && findingTally(current).openImportant) throw new PreEffectToolRefusal("approval blocked: open important review findings on this head"); }; findingGuard(initial); } // A Tasks without a brief provider (library use; the daemon always has one) has no coverage gate. if (verdict === "approved" && by !== USER && mode !== "off" && this.d.reviewBrief) { const t = valid(), enforce = mode === "enforce", list = (paths: string[]) => `${paths.slice(0, 20).join(", ")}${paths.length > 20 ? ", ..." : ""}`; // Code work (a commit, branch or PR) needs a brief; work with none of them is exempt and has nothing to account for. const code = !this.isPii(t) && !!(t.refs.commit || t.refs.branch || t.sdlc?.pr); // The commit under review: the task's, else the head the verdict names, else the lifecycle receipt's. const commit = t.refs.commit ?? (typeof head === "string" ? head : undefined) ?? t.sdlc?.reviewedHead ?? t.sdlc?.localHead; const brief: ReviewBrief | { unavailable: string } | undefined = !code ? undefined : !commit ? { unavailable: "the task links a branch or PR but names no commit" } : this.d.reviewBrief({ ...t, refs: { ...t.refs, commit } }) ?? { unavailable: "the review brief could not be built" }; if (brief && "unavailable" in brief) { // An unknown inventory is never an empty one. if (enforce) throw new PreEffectToolRefusal(`coverage: the review brief is unavailable (${brief.unavailable}); an approval needs a complete brief of the task's commit`); note = `${note ?? ""}\nCoverage unknown: the review brief is unavailable (${brief.unavailable})`.trim(); } else if (brief) { // One head: the brief's, the task's commit, and the head the verdict names or inherits from an earlier review (with a // PR, the lifecycle gate binds that head to the PR's). const effective = typeof head === "string" ? head : t.sdlc?.reviewedHead; if (effective !== undefined && effective !== brief.head && enforce) throw new PreEffectToolRefusal(`coverage: the verdict ${typeof head === "string" ? "names" : "inherits"} head ${effective}, but the review brief is for ${brief.head} (the commit under review)`); covered = { commit: t.refs.commit, receipt: JSON.stringify(t.sdlc ?? null) }; const gap = coverageGap(brief, coverage); if (gap.length && enforce) throw new PreEffectToolRefusal(`coverage: ${gap.length} reviewable path(s) of the review brief are not accounted for: ${list(gap)}. Pass coverage {reviewed, skipped: [{path, reason}]}.`); if (gap.length) note = `${note ?? ""}\nCoverage gap (${gap.length}): ${list(gap)}`.trim(); } } if (head !== undefined && resolvedHead && findingHead !== resolvedHead) throw new PreEffectToolRefusal(`task #${initial.id}: supplied review head ${findingHead} differs from recorded task head ${resolvedHead}; owner must re-file hub_task_done with refs.commit set to the supplied full SHA before review`); // The PII screen reads the note of a review that passes these checks (issue #198); they run again after it. // The configured PII screen sees reviewer prose and anchor metadata, but never immutable source selectors or projection content. const screenFindings = parsed.map(({ anchor, ...finding }) => ({ ...finding, ...(anchor ? { anchor: { path: anchor.path, ...(anchor.side ? { side: anchor.side } : {}), ...(anchor.contentHash ? { contentHash: anchor.contentHash } : {}), ...(anchor.projection ? { projection: anchor.projection } : {}), } } : {}) })); const withheld = evidenceObserverExcluded || await this.withholds("review note", parsed.length ? JSON.stringify({ note, findings: screenFindings }) : note, valid()) || parsed.length > 0 && !this.findingTextAllowed(initial, parsed); let task = valid(); let reviewedHead: string | undefined; if (head !== undefined) { const checked = sdlcReceipt({ reviewedHead: head }, task.sdlc, this.d.sdlc?.config() ?? sdlcConfig(undefined)); reviewedHead = checked.reviewedHead; } // #509a: an approval binds the bytes that were delivered. The files are read again now: unchanged, their hashes go on the approval; changed, // missing or unreadable, a reviewer's approval is refused before any write, and the person may approve the files as they are, saying so. let boundDeliverables: DeliverableRecord[] | undefined; if (verdict === "approved") { const delivered = latestDeliverables(task.history); if (delivered) { const identity = JSON.stringify(delivered); const checks = await this.checkRecords(delivered, task); task = valid(); if (JSON.stringify(latestDeliverables(task.history)) !== identity) throw new PreEffectToolRefusal("the task's deliverables changed during the verdict; review the current work again"); const drift = checks.filter(check => check.state !== "unchanged"); if (!drift.length) boundDeliverables = delivered; else { const text = drift.map(check => `${check.record.id} (${check.state})`).join(", "); if (by !== USER) throw new PreEffectToolRefusal(`deliverable changed since it was delivered: ${text}; ask its owner to call hub_task_done again so the current files are reviewed, or a person may approve them as they are`); // The person approves what is on disk now: those bytes are measured and bound, and the verdict says the files had moved. boundDeliverables = await this.hashClaims(delivered.map(record => ({ path: record.path!, format: record.format, ...(record.version !== undefined ? { version: record.version } : {}) })), task, true); task = valid(); note = `${note ?? ""}\nApproved with the deliverable files changed since delivery: ${text}`.trim(); } } } if (verdict === "approved" && this.d.sdlc && this.d.sdlc.config().mode !== "off") { this.evalRecords.delete(task.id); await this.lifecycleGate(task, "approval", reviewedHead, proposedSets(task), undefined, securityRecord && { ...securityRecord, head: reviewedHead ?? findingHead }); task = valid(); const record = this.evalRecords.get(task.id); this.evalRecords.delete(task.id); if (record) note = `${note ?? ""}\n${record}`.trim(); } else if (verdict === "approved" && this.d.sdlc?.config().mode === "off" && this.d.sdlc?.gh && task.sdlc?.repo && task.sdlc.pr && this.ownerReviewHead(task) && !this.isPii(task)) { const expected = reviewedHead ?? this.ownerReviewHead(task) ?? this.findingHead(task); const currentHead = await this.currentPrHeadForReview(task, valid); task = valid(); if (expected && currentHead && currentHead !== expected) throw this.reviewHeadMoveRefusal(task.id, expected, currentHead); } let candidate: Extract | undefined; if (!observerExcluded && verdict === "changes_requested" && !evidenceOnly && items.length && this.d.candidates && !withheld && !this.isPii(task) && !this.d.privateTurn?.(by)) { const input: CandidateInput = { project: this.d.store?.project ?? this.d.project, kind: "fail", approach: this.publicTitle(task), symptom: items.join("\n"), cause: "unknown: review unmet items do not establish a cause", retryWhen: "unknown: a person must review the unmet items before accepting", evidenceRefs: [`task:${task.id}`, `reviewed-head:${reviewedHead ?? task.refs.commit ?? "unknown"}`] }; const context = JSON.stringify({ title: task.title, detail: task.detail, refs: task.refs, plan: task.plan, signals: task.signals }); const payload = JSON.stringify({ input, note, context }); const cleared = this.candidateTextAllowed(payload, task) && !await this.withholds("review note", payload, task); task = valid(); if (cleared && context === JSON.stringify({ title: task.title, detail: task.detail, refs: task.refs, plan: task.plan, signals: task.signals })) candidate = input; // Async screening cannot authorize a verdict under an obsolete role/state. } if (withdrawing) { await this.unmergedForReopen(task, valid); task = valid(); } const pii = this.isPii(task); const reviewContext = by === USER ? undefined : this.d.reviewContext?.(by, task.id); const poolRequest = task.history.findLast(entry => ["done", "reviewer changed", "reviewer unavailable"].includes(entry.event)); const family = by === USER ? undefined : (this.d.adapterCatalog?.familyOf ?? familyOf)(by, this.d.instances?.()); const reviewerFamily = poolRequest?.reviewerFamily === family ? family : undefined; const reviewerReason = reviewerFamily ? poolRequest?.reviewerReason : undefined; // #507b: unmet items that start with a recorded criterion id name that criterion. The ids come from the checklist on the board as it is at this // write (the `task` just rechecked by valid()), never from the caller; a PII task carries none, its checklist being private. const unmetCriteria = pii ? [] : unmetCriteriaIds(items, checklistOf(task.sdlc)); const flag = { ...(findingHead ? { reviewedHead: findingHead } : {}), ...this.planObservation(task), withheld: withheld || undefined, ...(report ? { reviewFindings: report } : {}), ...(securityRecord && !pii ? { securityPass: { ...securityRecord, ...((reviewedHead ?? findingHead) ? { head: (reviewedHead ?? findingHead)! } : {}) } } : {}), ...(unmetCriteria.length ? { unmetCriteria } : {}), ...(boundDeliverables ? { deliverables: boundDeliverables } : {}), ...(reviewContext ? { reviewContext } : {}), ...(codeScope ? { reviewScope: "code" as const } : {}), ...(evidenceOnly ? { evidenceOnly: true as const } : {}), ...(reviewerFamily ? { reviewerFamily } : {}), ...(reviewerReason ? { reviewerReason } : {}) }; if (verdict === "approved") { const capacity = this.capacityBefore(task); this.ciWatchers.cancel(task.id); this.heldReviews.delete(task.id); const next = this.d.board.update(task.id, by, "approved", { state: "approved", rejections: 0, ...(reviewedHead && task.sdlc ? { sdlc: { ...task.sdlc, reviewedHead, stage: lifecycleStage(this.d.sdlc?.config() ?? sdlcConfig(undefined), "merge") } } : {}) }, note, flag); this.recordConsideredAfter(next, parsed.filter(finding => finding.disposition === "false_positive"), "review", findingHead ?? reviewedHead); this.writePlannerNotices(next, capacity, next.state === "approved"); if (next.owner) { this.d.board.recordOutcome(next.owner, next.class, true); this.d.board.recordReview({ implementer: next.owner, reviewer: by, class: next.class, kind: "approved", task: next.id }); // Changes requested on this owner's work and the redo passed: those reviews caught something. for (const r of this.requestedChanges(task)) { this.d.board.recordReview({ implementer: next.owner, reviewer: r, class: next.class, kind: "caught", task: next.id }); } } this.note(next, by, "decision", `Task #${next.id} approved by ${by}: ${next.title}${observerExcluded ? "" : `\n${note ?? ""}`}`, withheld); this.settleMemory(next); this.releaseNotice(`task ${this.publicTitle(next)}: could not tell ${next.owner ?? "its owner"} it was approved`, () => this.tell(next, `Task #${next.id} approved by ${by}.${note ? ` ${this.screen(next, note, "review note", next.owner, withheld)}` : ""}`, pii, "owner", observerExcluded)); await this.releaseDependents(next); this.autoMerge(next, this.mirrorVerdict(next, by, "approved", reviewedHead ?? next.sdlc?.reviewedHead, note, withheld || observerExcluded)); // A proposal storage failure cannot roll back the saved verdict; another matching verdict retries it. this.releaseNotice(`task #${next.id}: review saved but recurring-finding proposal unavailable`, () => this.proposeRecurringFindings(next, by, parsed, withheld)); this.releaseNotice(`task #${next.id}: review saved but finding follow-up proposal unavailable`, () => this.proposeFindingFollowUps(next, by, withheld)); this.releaseNotice(`task #${next.id}: review saved but recurring-criterion proposal unavailable`, () => this.proposeCriterionCandidates(next, by, withheld)); return next; } this.ciWatchers.cancel(task.id); this.heldReviews.delete(task.id); const rejected = this.d.board.update(task.id, by, "changes_requested", { state: "changes_requested", rejections: evidenceOnly ? task.rejections : task.rejections + 1 }, note, flag, task.history.length); this.recordConsideredAfter(rejected, parsed.filter(finding => finding.disposition === "false_positive"), "review", findingHead ?? reviewedHead); void this.mirrorVerdict(rejected, by, "changes_requested", reviewedHead ?? rejected.sdlc?.reviewedHead, note, withheld || observerExcluded); if (!evidenceOnly) this.releaseNotice(`task #${rejected.id}: review saved but recurring-finding proposal unavailable`, () => this.proposeRecurringFindings(rejected, by, parsed, withheld)); if (!evidenceOnly) this.releaseNotice(`task #${rejected.id}: review saved but recurring-criterion proposal unavailable`, () => this.proposeCriterionCandidates(rejected, by, withheld)); if (!observerExcluded && candidate && !pii && !this.d.privateTurn?.(by) && this.candidateTextAllowed(JSON.stringify({ candidate, refs: rejected.refs, plan: rejected.plan }), rejected)) { try { this.d.memoryCheck?.(); this.d.candidates?.put({ ...candidate, evidenceRefs: [...candidate.evidenceRefs, `review:${rejected.id}:${rejected.history.length}`] }, "public"); } catch { /* a saved review remains authoritative if the optional sidecar fails */ } } this.cohorts.withdraw(rejected.id); // open again: its done intent no longer counts (issue #107) // Evidence-only is not a verdict on the owner's work: no failed outcome, no contradiction of an earlier approval, and no escalation count. if (rejected.owner && !evidenceOnly) this.d.board.recordOutcome(rejected.owner, rejected.class, false); if (!evidenceOnly) this.contradict(rejected); this.note(rejected, by, "decision", `Task #${rejected.id} changes requested by ${by}: ${rejected.title}${observerExcluded ? "" : `\n${note ?? ""}`}`, withheld); if (evidenceOnly) this.tellConductorEvidenceOnly(rejected, by); if (withdrawing) { this.releaseNotice(`task ${this.publicTitle(rejected)}: could not tell its owner the approval was withdrawn`, () => this.tell(rejected, `Task #${rejected.id}: ${by} withdrew approval and requests changes. Review the findings, then call hub_task_done with the updated head.`, pii)); return rejected; } if (!evidenceOnly && rejected.rejections >= (this.d.escalateAfter?.() ?? ESCALATE_AFTER)) { let moved: Task; try { moved = await this.escalate(HUB, rejected.id, `${rejected.rejections} consecutive changes_requested`, "rejections"); } catch (e) { // The verdict is saved. If the escalation's move was saved too, only its delivery is unconfirmed, and the // error carries the saved task (#297); the console notice was printed where the error was thrown. The // reviewer gets the saved task back, never a failed tool call (#276). Anything else (the task closed // meanwhile (#254), a failed board write, a superseded move) still throws. assignOwner keeps throwing for // the ready offer's retry (#231). if (!(e instanceof AssignmentUndeliveredError)) throw e; return e.task; } if (moved.owner !== rejected.owner) return moved; // Nobody to escalate to: the owner still has to hear the verdict and the note. this.releaseNotice(`task ${this.publicTitle(moved)}: could not tell ${moved.owner ?? "its owner"} changes were requested again`, () => this.tell(moved, `Task #${moved.id}: ${by} requests changes again.${note ? ` ${this.screen(moved, note, "review note", moved.owner, withheld)}` : ""} Nobody else can take it; fix it and call hub_task_done again.`, pii, "owner", observerExcluded)); return moved; } const reopened = this.d.board.update(rejected.id, HUB, "reopened", { state: "in_progress" }); this.releaseNotice(`task ${this.publicTitle(reopened)}: could not tell ${reopened.owner ?? "its owner"} changes were requested`, () => this.tell(reopened, `Task #${reopened.id}: ${by} requests changes.${note ? ` ${this.screen(reopened, note, "review note", reopened.owner, withheld)}` : ""} Fix it and call hub_task_done again.`, pii, "owner", observerExcluded)); return reopened; } /** * #852 AC3: one task-weight notice to the configured conductor for a verdict recorded as evidence-only. Ids only (task and reviewer), so nothing of * the review or the task reaches it; a PII task's notice is private. With no conductor the person sees one console notice instead. */ private tellConductorEvidenceOnly(task: Task, reviewer: PeerId): void { const conductors = Object.entries(this.d.roles ?? {}).filter(([peer, roles]) => !isRemotePeerId(peer) && Array.isArray(roles) && roles.includes("conductor")).map(([actor]) => actor).filter(actor => actor !== reviewer); const text = evidenceOnlyNotice(task.id, reviewer); if (!conductors.length) { this.releaseNotice(text); return; } this.releaseNotice(`task #${task.id}: could not tell the conductor a code-scope review was evidence-only`, () => { this.d.bus.publish(newEnvelope(HUB, sanitize(text), { to: conductors, kind: "task", refs: { task: String(task.id) }, ...(this.isPii(task) ? { private: true } : {}) })); }); } /** Task-level escalation: the next attached peer in the class's escalate_to takes over, with the history. */ async escalate(by: PeerId, id: unknown, why = "by hand", reason: TaskMoveReason | undefined = by === HUB ? undefined : "manual", preEffect = false): Promise { requireLocalTaskPeer(by); let task = this.need(id, true, preEffect); const list = this.d.routing().classes[task.class]?.escalate_to ?? []; if (task.state === "changes_requested") task = this.d.board.update(task.id, HUB, "reopened", { state: "in_progress" }); const from = task.owner; // The hub's own escalations are not counted: after repeated changes_requested each one already was, and after a // Pi inference failure the backend failed, not the work. An escalation by hand counts on its own. if (from && by !== HUB) this.d.board.recordOutcome(from, task.class, false); // Only a reviewer that asked for changes on this work saw it fail: not an escalation of unreviewed work (a Pi failure). if (from && task.reviewer && task.reviewer !== USER && this.requestedChanges(task).has(task.reviewer)) this.d.board.recordReview({ implementer: from, reviewer: task.reviewer, class: task.class, kind: "escalated", task: task.id }); const stopFormerOwner = (moved: Task) => { if (from && moved.owner && moved.owner !== from) this.releaseNotice(`task ${this.publicTitle(moved)}: could not tell ${from} it moved to ${moved.owner}`, () => this.tell({ ...moved, owner: from }, `Task #${moved.id} moved to ${moved.owner} (${why}). Stop working on it.`, this.isPii(moved), "withdrawal")); }; // Only our landed move authorizes a success notice and decision note. The former owner's stop // message still names the current owner when a later assignment superseded this move. const tail = (moved: Task) => { this.releaseNotice(`task ${this.publicTitle(moved)} escalated from ${from} to ${moved.owner} (${why})`); this.note(moved, by, "decision", `Task #${moved.id} escalated from ${from} to ${moved.owner}: ${why}`); stopFormerOwner(moved); }; let next: Task; try { next = await this.assignOwner(task, by, { candidates: list, event: "escalated", reason, note: `${why}; from ${from ?? "none"}`, context: why }); } catch (e) { // A saved move whose delivery failed arrives as AssignmentUndeliveredError carrying the saved task (#297); // the tail still runs on it (its parts are guarded), and the caller still gets the throw. Anything before // the write gets neither. if (e instanceof AssignmentUndeliveredError && this.ownOwnerMove(task, e.task, by, "escalated")) tail(e.task); throw e; } if (next.owner && next.owner !== from) { // The move is on the board (#243): review() reaches here after its changes_requested write. if (this.ownOwnerMove(task, next, by, "escalated")) tail(next); else stopFormerOwner(next); } else this.releaseNotice(`task ${this.publicTitle(task)}: escalation found nobody in [${list.join(", ")}]; it stays with ${from ?? "nobody"}`); return this.d.board.get(next.id)!; } /** Withdraw only a former role's queued request, then tell it that its authority changed. */ private withdrawRoleRequest(previous: Task, next: Task, role: Exclude): void { const peer = previous[role]; if (!peer || peer === next[role]) return; const kind = role === "owner" ? "task" : "review"; this.releaseNotice(`task ${this.publicTitle(next)}: could not notify previous ${role} ${peer} that its request is withdrawn`, () => { const matches = (env: Envelope) => (role === "reviewer" || env.body.startsWith(`Task #${previous.id} [`)) && env.from === HUB && env.kind === kind && env.refs?.task === String(previous.id); const assignment = previous.history.map(entry => OWNERSHIP_EVENTS.has(entry.event)).lastIndexOf(true); // A self-claim also records accepted, after assigned. State can belong to an earlier owner. const acceptance = previous.history.slice(assignment + 1).some(entry => entry.event === "accepted" && entry.by === peer); const boardEvidence = role === "owner" && acceptance; const mayHaveReceived = boardEvidence || this.d.bus.lastDeliveredTo(peer).some(matches) || this.d.bus.queueList(peer).some(row => ["dispatching", "accepted", "needs_review", "completed"].includes(row.state) && row.originals.some(matches)); for (const env of this.d.bus.pendingEnvelopes(peer)) if (matches(env)) this.d.bus.withdraw(env.id); if (!mayHaveReceived) return; const body = role === "owner" ? `Task ${this.publicTitle(next)} is no longer assigned to you${next.owner ? `; its owner is now ${next.owner}` : "; it is unassigned"}. Do not accept or complete it; late calls under your former assignment are refused.` : `Review request for task #${previous.id} ${this.publicTitle(next)} is withdrawn: ${next.reviewer ? `its reviewer is now ${next.reviewer}` : "the task has no reviewer"}. Do not review this task; a late verdict from the previous reviewer is refused.`; if (peer === USER) this.d.notify(body); // An untagged task notice remains needed by a former role until approval; kind review would look moved already. else this.d.bus.publish(newEnvelope(HUB, body, { to: [peer], kind: "task", priority: "important", refs: { task: String(previous.id) }, ...(this.isPii(next) ? { private: true } : {}) })); }); } /** Preserve explicit intent across a policy reload; recheck conductor authority after every await. */ private explicitQueueAssignment(by: PeerId, role: Exclude, preEffect: boolean): { role: "owner" | "reviewer"; current: () => void } | undefined { if (by === USER) return { role, current: () => {} }; const current = () => { const holders = Object.entries(this.d.roles ?? {}).filter(([, roles]) => Array.isArray(roles) && roles.includes("conductor")).map(([peer]) => peer); return holders.length === 1 && holders[0] === by && this.d.bus.isRostered(by); }; if (!current()) return undefined; return { role, current: () => { if (!current()) throw new (preEffect ? PreEffectToolRefusal : Error)("only the current configured conductor may override assignment admission"); } }; } private configuredManualConductor(by: PeerId): boolean { if (by === USER || by === HUB || isRemotePeerId(by)) return false; const holders = Object.entries(this.d.roles ?? {}).filter(([peer, roles]) => !isRemotePeerId(peer) && Array.isArray(roles) && roles.includes("conductor")).map(([peer]) => peer); return holders.length === 1 && holders[0] === by; } private conductorManualCheck(by: PeerId, preEffect: boolean): () => void { return () => { if (!this.configuredManualConductor(by) || !this.d.bus.isRostered(by)) throw new (preEffect ? PreEffectToolRefusal : Error)("only the console user or the current configured conductor may unassign a task role"); }; } /** Caller authority is checked by the daemon; keep the real actor in task history. */ async assignTo(id: unknown, peer: PeerId, by: PeerId = USER, preEffect = false, role: TaskAssignmentRole = "owner", expectedFlowRevision?: number): Promise { requireLocalTaskPeer(by); requireLocalTaskPeer(peer); const conductorManual = this.configuredManualConductor(by), manualCurrent = conductorManual ? this.conductorManualCheck(by, preEffect) : undefined; manualCurrent?.(); if (role !== "owner" && role !== "reviewer" && role !== "planner") throw new (preEffect ? PreEffectToolRefusal : Error)("role must be owner, reviewer or planner"); if (role === "planner") { if (by !== USER) throw new PreEffectToolRefusal("only the person may name a task planner"); const task = this.need(id, false, preEffect); this.checkFlowRevision(task, expectedFlowRevision, preEffect); if (isClosedTaskState(task.state) || this.isPii(task)) throw new PreEffectToolRefusal("closed or private work cannot name a planner"); const choice = assign({ ...task, state: "proposed" }, this.states(), this.d.routing(), { ...this.weights(task.class, task), candidates: [], namedPlanner: peer }); if (choice.planner !== peer) throw new PreEffectToolRefusal("named planner must be a rostered settled planner holder"); const next = this.d.board.update(task.id, by, "planner changed", { planner: peer }, "named", { plannerReason: "named" }, expectedFlowRevision); if (next.state === "backlog") { this.incomingBacklog.add(next.id); this.addPlannerBacklog(peer, [next.id]); } return next; } if (role === "reviewer" && by !== USER) { const conductors = Object.entries(this.d.roles ?? {}).filter(([peer, roles]) => !isRemotePeerId(peer) && Array.isArray(roles) && roles.includes("conductor")).map(([actor]) => actor); if (conductors.length !== 1 || conductors[0] !== by) throw new (preEffect ? PreEffectToolRefusal : Error)("only the console user or the configured conductor may name a reviewer"); } const queueAssignment = this.explicitQueueAssignment(by, role, preEffect); queueAssignment?.current(); const task = this.need(id, role === "owner", preEffect); this.checkFlowRevision(task, expectedFlowRevision, preEffect); // #1176: routing hands a person-run leg to nobody, so naming an owner would only be a silent no-op plus a stall report. Refused for the conductor and planner (they are agents) and for the person alike: the person clears the mark first. if (role === "owner" && task.needsPerson) throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${task.id} is a person-run leg: no agent is named its owner. Clear the mark first (ahub backlog plan ${task.id} '{"needsPerson":false}' ), then assign it`); if (!this.d.bus.isRostered(peer)) throw new (preEffect ? PreEffectToolRefusal : Error)(`${peer} is off roster; add it to the roster before assigning work`); this.requireCapabilities(task, peer, role, preEffect); if (role === "reviewer") { if (!OPEN.includes(task.state) && task.state !== "in_review") throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${task.id} is ${task.state}: its reviewer can no longer change`); this.ready(task, preEffect); const a = assign(task, this.states(), this.d.routing(), { candidates: [], namedReviewer: peer, ...(task.owner ? { notReviewer: task.owner } : {}), ...this.weights(task.class, task), ...(queueAssignment ? { queueOverride: queueAssignment.role } : {}) }); if (a.reviewer !== peer) throw new (preEffect ? PreEffectToolRefusal : Error)(`cannot name ${peer} as reviewer: ${a.trace.filter(line => line.includes("reviewer") || line.includes("pii")).join("; ")}`); const admission = task.state === "in_review" ? await this.reviewRequestAdmission(task, undefined, preEffect, by) : undefined; // Every runtime authority check precedes the final write, including revocations during the metadata await. manualCurrent?.(); queueAssignment?.current(); const current = this.need(task.id, false, preEffect); if (current.history.length !== task.history.length) throw new (preEffect ? PreEffectToolRefusal : Error)("task changed during reviewer admission"); if (by !== USER) { const holders = Object.entries(this.d.roles ?? {}).filter(([peer, roles]) => !isRemotePeerId(peer) && Array.isArray(roles) && roles.includes("conductor")).map(([actor]) => actor); if (holders.length !== 1 || holders[0] !== by) throw new (preEffect ? PreEffectToolRefusal : Error)("only the console user or the configured conductor may name a reviewer"); } if (!this.d.bus.isRostered(peer)) throw new (preEffect ? PreEffectToolRefusal : Error)(`${peer} is off roster`); this.requireCapabilities(current, peer, role, preEffect); const eligible = assign(current, this.states(), this.d.routing(), { candidates: [], namedReviewer: peer, ...(current.owner ? { notReviewer: current.owner } : {}), ...this.weights(current.class, current), ...(queueAssignment ? { queueOverride: queueAssignment.role } : {}) }); if (eligible.reviewer !== peer) throw new (preEffect ? PreEffectToolRefusal : Error)("reviewer is no longer eligible"); queueAssignment?.current(); const next = this.d.board.update(task.id, by, "reviewer changed", { reviewer: peer }, this.assignmentNote(`named reviewer ${peer}`, a), { reason: "manual" }, expectedFlowRevision); if (next.state === "in_review" && task.reviewer && task.reviewer !== peer) { this.withdrawRoleRequest(task, next, "reviewer"); } if (next.state === "in_review" && peer !== USER) this.releaseNotice(`task ${this.publicTitle(next)}: could not send the review request to ${peer}`, () => this.sendReview(next, peer, "", admission)); return next; } // Work that waits is handed to nobody yet (issue #207): the peer becomes its reserved owner instead. if (!this.waitsFor(task).length) return this.assignOwner(task, by, { candidates: [peer], namedOwner: peer, event: "reassigned", reason: "manual", override: by === USER, expectedFlowRevision, refuseNamed: preEffect ? "pre" : "plain", ...(conductorManual ? { conductorManual: true as const } : {}), ...(queueAssignment ? { queueOverride: "owner" as const } : {}), current: () => { manualCurrent?.(); queueAssignment?.current(); } }); manualCurrent?.(); queueAssignment?.current(); const next = this.d.board.update(task.id, by, "reserved", { reserved: peer }, `for ${peer}`, { reason: "manual", ...(conductorManual ? { conductorManual: true as const } : {}) }, expectedFlowRevision); this.releaseNotice(`task ${this.publicTitle(next)} reserved for ${peer} by ${by}; it is offered to ${peer} first once what it waits for is approved`); return next; } /** Explicit removal without routing a replacement; host history preserves manual intent across role changes. */ async unassign(id: unknown, by: PeerId = USER, preEffect = false, role: TaskAssignmentRole = "owner", expectedFlowRevision?: number): Promise { const authority = by === USER ? undefined : this.conductorManualCheck(by, preEffect); const current = authority && (() => { authority(); if (this.d.privateTurn?.(by)) throw new (preEffect ? PreEffectToolRefusal : Error)("conductor task mutations are unavailable during a private turn"); if (this.d.cancellationHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) throw new (preEffect ? PreEffectToolRefusal : Error)("recovery or shutdown is holding task writes"); }); current?.(); if (role !== "owner" && role !== "reviewer") throw new (preEffect ? PreEffectToolRefusal : Error)("role must be owner or reviewer"); const task = this.need(id, false, preEffect); this.checkFlowRevision(task, expectedFlowRevision, preEffect); if (isClosedTaskState(task.state)) throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${task.id} is ${task.state}: its ${role} is historical`); if (role === "owner") { if (!OPEN.includes(task.state)) throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${task.id} is ${task.state}: its owner cannot be unassigned`); if (!task.owner && !task.reserved) throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${task.id}: no owner or owner reservation to unassign`); current?.(); const next = this.d.board.update(task.id, by, "unassigned", { owner: null, reserved: null, ...(task.state === "proposed" ? {} : { state: "proposed" as const }) }, `${by === USER ? "person" : "conductor"} unassigned ${[task.owner, task.reserved].filter(Boolean).join(" and ")}`, { reason: "manual", ...(current ? { conductorManual: true as const } : {}) }, expectedFlowRevision); this.cohorts.leave(task.id); this.withdrawRoleRequest(task, next, "owner"); return next; } if (!OPEN.includes(task.state) && task.state !== "in_review") throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${task.id} is ${task.state}: its reviewer cannot be unassigned`); if (!task.reviewer) throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${task.id}: no reviewer to unassign`); if (task.reviewer === USER && this.isPii(task)) throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${task.id}: the human reviewer is required for PII work`); current?.(); const next = this.d.board.update(task.id, by, "reviewer changed", { reviewer: null }, `${by === USER ? "person" : "conductor"} unassigned reviewer ${task.reviewer}`, { reason: "manual", ...(current ? { conductorManual: true as const } : {}) }, expectedFlowRevision); this.withdrawRoleRequest(task, next, "reviewer"); return next; } /** * Budget relay: a paused peer's open work moves on. `local` first (it has no quota), then the class list, all through * the usual constraints. Tasks it was reviewing get another reviewer. Moves are reported, never taken back automatically. */ async reassignForPause(peer: PeerId, context: string | undefined, urgentOnly = false): Promise<{ id: number; title: string; to: PeerId | null; role: "owner" | "reviewer" }[]> { requireLocalTaskPeer(peer); return this.reassignWork(peer, context, urgentOnly, false); } /** Read-only preview using the same assignment constraints as the roster relay. */ rosterPreview(peer: PeerId): { id: number; title: string; role: "owner" | "reviewer"; to: PeerId | null }[] { requireLocalTaskPeer(peer); const routing = this.d.routing(); return this.d.board.list().filter(task => !isClosedTaskState(task.state) && (task.owner === peer || task.reviewer === peer)).map(task => { const owner = task.owner === peer; const weights = this.weights(task.class, task); const pii = this.isPii(task); const candidates = owner ? relayCandidates(routing.classes[task.class]?.peers ?? [], pii, { ...this.instanceRouting(), states: this.states() }) : []; const a = assign(task, this.states(), routing, { ...weights, offRoster: [...(weights.offRoster ?? []), peer], exclude: [peer], excludeOwners: owner && this.plannerPullRecord(task)?.pull ? this.plannerFull(task) : [], candidates, ...(owner ? { waitsFor: this.waitsFor(task) } : task.owner ? { notReviewer: task.owner } : {}) }); return { id: task.id, title: this.publicTitle(task), role: owner ? "owner" : "reviewer", to: (owner ? a.owner : a.reviewer) ?? null }; }); } /** A roster removal offers work through the quota relay's constraints, preserving assignments nobody can take. */ async reassignForRoster(peer: PeerId, current?: () => void): Promise<{ id: number; title: string; to: PeerId | null; role: "owner" | "reviewer" }[]> { requireLocalTaskPeer(peer); return this.reassignWork(peer, undefined, false, true, current); } private async reassignWork(peer: PeerId, context: string | undefined, urgentOnly: boolean, roster: boolean, current?: () => void): Promise<{ id: number; title: string; to: PeerId | null; role: "owner" | "reviewer" }[]> { current?.(); const moved: { id: number; title: string; to: PeerId | null; role: "owner" | "reviewer" }[] = []; const routing = this.d.routing(), why = roster ? `roster removal of ${peer}` : `budget pause of ${peer}`; // Budget context is screened exactly as before; a roster removal supplies no agent-written context. const moves = (t: Task) => (!urgentOnly || t.signals.includes("urgent")) && t.owner === peer && OPEN.includes(t.state); const contextWithheld = context && this.d.board.list().some((t) => moves(t) && !this.isPii(t)) ? await this.withholds("handoff", context) : false; current?.(); for (const task of this.d.board.list()) { current?.(); if (urgentOnly && !task.signals.includes("urgent")) continue; if (task.owner === peer && (OPEN.includes(task.state) || roster && task.state === "in_review")) { const pii = this.isPii(task); const candidates = relayCandidates(routing.classes[task.class]?.peers ?? [], pii, { ...this.instanceRouting(), states: this.states() }); if (this.plannerPullRecord(task)?.pull && !assign(task, this.states(), routing, { candidates, exclude: [...this.excluded(task), peer], excludeOwners: this.plannerFull(task), waitsFor: this.waitsFor(task), ...this.weights(task.class, task) }).owner) continue; // Budget keeps its original release/unassign behaviour for ordinary work. Roster changes the state in // assignOwner's same owner write only after routing has found somebody to take it. const back = !roster && task.state === "in_progress" ? this.d.board.update(task.id, HUB, "released", { state: "proposed" }, why) : task; let next: Task; try { next = await this.assignOwner(back, HUB, { current, candidates, exclude: [peer], event: "reassigned", reason: roster ? "manual" : "budget", note: why, ...(roster ? { roster: true } : { clearOnFail: true }), ...(context ? { context, contextWithheld } : {}) }); } catch (e) { // The move is saved and its central #297 notice already spoke; relay the // remaining tasks and run the roster tail on the saved row as on success. if (!(e instanceof AssignmentUndeliveredError)) throw e; next = e.task; } // A saved assignment failure is retained, but never permits a revoked initiating operation to continue. current?.(); if (!this.ownOwnerMove(back, next, HUB, "reassigned") && !this.ownOwnerMove(back, next, HUB, "unassigned")) continue; if (roster) { if (!next.owner || next.owner === peer) continue; this.releaseNotice(`task ${this.publicTitle(next)} moved from ${peer} to ${next.owner} (off roster)`); if (next.state === "in_review" && next.reviewer && next.reviewer !== task.reviewer && next.reviewer !== USER) this.releaseNotice(`task ${this.publicTitle(next)}: could not send the review request to ${next.reviewer}`, () => this.sendReview(next, next.reviewer!, `(${peer} owned this and is off roster.)`)); } current?.(); moved.push({ id: task.id, title: this.publicTitle(task), to: next.owner, role: "owner" }); } else if (task.reviewer === peer && !isClosedTaskState(task.state)) { const a = assign(task, this.states(), routing, { ...(roster ? { exclude: [peer] } : {}), candidates: [], ...(task.owner ? { notReviewer: task.owner } : {}), ...this.weights(task.class, task) }); const reviewer = !a.reviewSelection?.quotaWait && a.reviewer && a.reviewer !== peer && a.reviewer !== task.owner ? a.reviewer : null; if (roster && !reviewer) { this.releaseNotice(`task ${this.publicTitle(task)}: its reviewer ${peer} is off roster and nobody else can review; the reviewer stays ${peer}; use ahub review ${task.id}`); continue; } current?.(); const next = this.d.board.update(task.id, HUB, "reviewer changed", { reviewer }, this.assignmentNote(why, a), this.reviewMetadata(a, task)); this.queueReviewWritten(next); moved.push({ id: task.id, title: this.publicTitle(task), to: reviewer, role: "reviewer" }); current?.(); if (next.state === "in_review" && reviewer && reviewer !== USER) { if (roster) this.releaseNotice(`task ${this.publicTitle(next)}: could not send the review request to ${reviewer}`, () => this.sendReview(next, reviewer, `(${peer} was reviewing this and is off roster.)`)); else this.sendReview(next, reviewer, `(${peer} was reviewing this and is paused for quota.)`); } else if (next.state === "in_review" && !reviewer && !a.reviewSelection?.quotaWait) this.d.notify(`task ${this.publicTitle(next)}: its reviewer ${peer} is paused and nobody else can review; use ahub review ${next.id}`); } } return moved; } /** What the local worker needs to know about the turn it is about to run. */ turnPolicy(envs: Envelope[]): { route?: string; fixedModel?: string; pii: boolean; task?: string } | undefined { const found = envs.map((e) => (e.refs?.task ? this.d.board.get(Number(e.refs.task)) : undefined)).filter((t): t is Task => !!t); // One PII item makes the whole turn a PII turn: a digest can carry a PII task next to ordinary messages. const pii = envs.some((e) => e.private) || found.some((t) => this.isPii(t)); if (!found.length) return pii ? { pii } : undefined; const policy = this.d.routing().classes[found[0]!.class]; const about = found.find((t) => this.isPii(t)) ?? found[0]!; // the answer is filed under the PII task when there is one return { ...(policy?.route ? { route: policy.route } : {}), ...(policy?.fixed_model ? { fixedModel: policy.fixed_model } : {}), pii, task: String(about.id) }; } /** * The whole public-text screen for metadata the hub itself reads from outside the board (a git branch name, #572): a PII * pattern, a secret shape and a path the project marks private. `nameable` alone is the pattern screen only. */ publicMetadataText = (text: string): boolean => this.nameable(text) && !looksSecret(text) && !this.aboutPrivatePath("", text, undefined); private candidateTextAllowed(text: string, task?: Task): boolean { return (!task || !this.isPii(task)) && this.nameable(text) && !looksSecret(text) && !this.aboutPrivatePath("", text, task); } /** Candidate only: the person remains the sole acceptance authority. */ async correct(by: PeerId, input: unknown): Promise { const requestCheck = this.requestCheck(by); const args = correctionInput(input); const st = this.d.store; if (!st || !this.d.candidates) throw new PreEffectToolRefusal("memory correction unavailable"); const screen: MemoryScreen = rows => this.d.candidateScreen?.(rows) ?? withoutPii(rows, this.d.routing(), this.d.cwd, this.d.piiPaths ?? []); const valid = () => { requestCheck(); this.d.memoryCheck?.(); if (this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("memory correction unavailable during a private turn"); if (!this.candidateTextAllowed(JSON.stringify(args))) throw new PreEffectToolRefusal("memory correction withheld by privacy policy"); return resolveVisibleMemory(st.store, st.project, screen, args.id); }; const target = valid(), revision = candidateTargetRevision(target); if (await this.withholds("note", `${args.text}\n${args.reason}`)) throw new PreEffectToolRefusal("memory correction withheld by privacy policy"); const current = valid(); if (current.id !== target.id || candidateTargetRevision(current) !== revision) throw new PreEffectToolRefusal("memory correction target changed; read it again"); const id = this.d.candidates.put({ project: st.project, kind: "correction", target: { id: current.id, revision }, proposedText: args.text, reason: args.reason, ...(current.kind === "decision" || current.kind === "contract" || current.kind === "fail" ? { noteKind: current.kind } : {}) }, "public"); return `candidate:${id}; a person reviews it with amem review; memory was not edited`; } async remember(by: PeerId, input: RememberInput): Promise { return (await this.rememberOutcome(by, input)).message; } /** * #802: what `remember` answered and whether it stored anything, so a caller never decides that from the wording. `saved` is a note in shared memory, `candidate` one held for a person's * review (stored, not yet evidence), `not_saved` a note nothing took. A refusal still throws and never reaches here. */ async rememberOutcome(by: PeerId, input: RememberInput): Promise<{ message: string; outcome: "saved" | "candidate" | "not_saved" }> { const requestCheck = this.requestCheck(by); const text = composeRememberText(input); const task = input.task !== undefined ? this.d.board.get(Number(input.task)) : undefined; if (task && this.isPii(task)) throw new Error("notes about a PII task are not saved: shared memory excludes private data"); // Shared with every other peer as well, so text that matches a PII pattern is refused like a note about a PII task. const title = String(input.title ?? "").trim(); if (by !== USER) { let scoped = false; try { scoped = this.reviewObserverTurn(by, task?.id); } catch { throw new PreEffectToolRefusal("shared memory is held because the open review scope (sent comments, anchored findings, unsettled delivery or current review input) could not be checked; inspect ahub task list after recovery"); } if (scoped) throw new PreEffectToolRefusal(`shared memory is held while an open review scope (sent comments, anchored findings, unsettled delivery or current review input) exists; complete or review the task, ask the person to dismiss comments if appropriate, inspect ahub queue list --peer ${by} and explicitly settle any delivery, then wait for ordinary new input after completion`); } if (this.isPii({ signals: detectSignals({ title, detail: text, refs: {} }, this.d.routing(), this.d.cwd) })) throw new Error("this note matches a PII pattern and is not saved: shared memory excludes private data"); if (input.horizon !== undefined && input.horizon !== "short" && input.horizon !== "long") throw new Error('horizon is "short" or "long"'); if (input.scope !== undefined && input.scope !== "project" && input.scope !== "shared") throw new Error('scope is "project" or "shared"'); if (!this.d.memory && !this.d.store) return { message: "memory is disabled; nothing saved", outcome: "not_saved" }; // Long-term notes can leave the machine (#258); local storage does not relax secret exclusion. if (looksSecret(`${title}\n${text}`)) throw new Error("this note looks like it holds a secret (a key, token or password) and is not saved"); if (this.aboutPrivatePath(title, text, task)) throw new Error("this note is about a path the project keeps private (pii.paths) and is not saved"); if (await this.withholds("note", `${title}\n${text}`, task)) throw new Error("the PII screen did not clear this note, so it is not saved: shared memory excludes private data"); requestCheck(); const kind = (NOTE_KINDS as readonly string[]).includes(String(input.kind)) ? String(input.kind) as Kind : "finding"; const native = this.saveNative(by, kind, text, title, task, input.horizon === "long" || input.horizon === "short" ? input.horizon : undefined, input.scope === "shared" ? "shared" : "project"); if (native && "refused" in native) throw new PreEffectToolRefusal(`${native.refused}; save it with horizon "short" or correct the machine/repository privacy policy, then retry`); if (task && this.d.memory) this.markMemoryReference(task, by); const res = !native && this.d.memory ? await this.d.memory.save({ text, ...(title ? { title } : {}), project: this.d.project, metadata: { peer: by, kind, ...(task ? { task: task.id } : {}) } }) : undefined; if (!res && !native) return { message: "memory store unavailable; nothing saved", outcome: "not_saved" }; if (!native && res && typeof res === "object" && "status" in res && res.status === "candidate") { return { message: "saved as a pending memory candidate; a person must review it before it becomes shared evidence", outcome: "candidate" }; } const line = noteLine(by, kind, title ? `${title}: ${text}` : text); this.d.notify(line); // Display identity only: a queued recall may already contain this saved entry. Stored/captured text stays unchanged. this.d.share?.(by, native ? noteLine(by, kind, `mem:${native.id} ${title ? `${title}: ` : ""}${text}`) : line); return { message: `saved to shared memory${native ? ` (hub memory ${native.id.slice(0, 8)}, ${native.tier}-term)` : ""}; the other agents get it with their next message`, outcome: "saved" }; } /** The task's key in the hub's store: unique across `ahub reset --all`, which restarts the ids. */ private memoryKey(task: Task): string { return taskKey(this.d.store!.project, task); } /** * The long-term task a board task may join (#258). A peer names one of this project's; a person may name any (a link * across projects is a person's). Refused before any board write. */ private goalFor(by: PeerId, ref: unknown): GoalView { if (!this.d.store) throw new PreEffectToolRefusal("goal: hub memory is off for this project"); try { this.d.memoryCheck?.(); } catch { throw new PreEffectToolRefusal("goal: memory profile unavailable; inspect the selector and generation state before linking a long-term task"); } const g = typeof ref === "string" && ref.trim() ? this.d.store.store.goalOf(ref.trim().replace(/^goal:/, "")) : undefined; if (!g) throw new PreEffectToolRefusal(`goal: no long-term task ${JSON.stringify(ref).slice(0, 40)} (ahub goal list shows them)`); if (by !== USER && g.project !== this.d.store.project) throw new PreEffectToolRefusal("goal: that long-term task belongs to another project; linking across projects is a person's"); if (g.state === "done" || g.state === "dropped") throw new PreEffectToolRefusal(`goal: that long-term task is ${g.state}`); return g; } /** Fence deletion before external memory writes; one marker survives store absence. */ private markMemoryReference(task: Task, by: PeerId): void { if (!this.d.board.get(task.id)?.history.some(entry => entry.event === "memory reference started")) this.d.board.update(task.id, by, "memory reference started", {}); } /** Record a long-term link, never for PII; failures remain notices. */ private linkNative(task: Task, goal: GoalView, by: PeerId): string { if (this.isPii(task)) { this.releaseNotice(`task #${task.id} is not linked to a long-term task: nothing about a PII task enters hub memory`); return "not linked (PII task)"; } try { this.d.memoryCheck?.(); this.markMemoryReference(task, by); this.d.store!.store.goalLink(goal.id, this.memoryKey(task), by); return `part of long-term task ${goal.id.slice(0, 8)}`; } catch (e) { this.releaseNotice(`task #${task.id}: the link to long-term task ${goal.id.slice(0, 8)} was not saved (${(e as Error).message})`); return "not linked"; } } /** A person links a board task of this project to a long-term task (`ahub goal link`). */ linkGoal(by: PeerId, id: unknown, ref: unknown): string { requireLocalTaskPeer(by); const task = this.d.board.get(Number(id)); if (!task) throw new Error(`no task #${String(id).slice(0, 12)}`); const goal = this.goalFor(by, ref); return `task #${task.id}: ${this.linkNative(task, goal, by)}`; } /** * One note in the hub's own store (#258). Short-term while its task is open; on an approved task, or with horizon * long, decisions, contracts and fails are long-term. Fail-open: a store that cannot be written costs one notice. * The caller has screened the text for PII; never a PII task's. */ private saveNative(by: PeerId, kind: Kind, text: string, title: string, task: Task | undefined, horizon?: Tier, scope: Scope = "project", symbols?: MemorySymbolNodes): { id: string; tier: Tier; about: string[] } | { refused: string } | undefined { const st = this.d.store; if (!st || (task && this.isPii(task))) return undefined; let longTerm = horizon === "long" || (horizon !== "short" && !!task && task.state === "approved" && PROMOTED_KINDS.includes(kind)); try { // never throws: callers run after a board write this.d.memoryCheck?.(); // Approved, or settled in the store already: the snapshot the caller holds can predate an approval made while it awaited. const approved = !!task && (task.state === "approved" || st.store.settled(this.memoryKey(task))); const tier: Tier = horizon ?? (approved && PROMOTED_KINDS.includes(kind) ? "long" : "short"); longTerm ||= tier === "long"; const about = extractNodes(`${title}\n${text}`, { cwd: this.d.cwd, project: st.project, repo: st.repo, deny: st.deny, paths: [...(task?.refs.paths ?? []), ...(task?.plan?.paths ?? [])], symbols: symbols ? [] : task?.plan?.symbols?.map(normalizeMemorySymbolInput), ...(task ? { task: { id: task.id, created: task.created } } : {}) }); // Existing notes remain immutable; the completion note connects actual symbols through the shared task node. if (symbols && task) { const taskNode = `task:${this.memoryKey(task)}`; about.splice(0, about.length, ...[...new Set([taskNode, ...symbols.nodes, ...about])].slice(0, 64).sort()); } // A short-term note on a task already approved (before hub memory existed, or late): the task is settled first, so // the note gets its own deadline and is never taken for a source waiting for promotion. if (task && approved && tier === "short" && !st.store.settled(this.memoryKey(task))) this.settleMemory(task); const row: NoteInput = { op: "note", project: st.project, scope, tier, kind, peer: by, ...(title ? { title } : {}), text, ...(task ? { task: this.memoryKey(task) } : {}), about, source: by === USER ? "person" : "hub" }; if (tier === "long") { try { const result = this.memorySyncPolicy().screen(row); if (!result.ok) return { refused: `long-term note declined by ${result.rule}` }; } catch { return { refused: "machine privacy policy unavailable" }; } } if (task) this.markMemoryReference(task, by); const id = st.store.note(row, horizon === "short"); try { st.onNote?.(id); } catch { /* The native note is committed; an observer cannot make it fail. */ } return { id, tier, about: [...about] }; } catch (e) { if (longTerm) return { refused: "machine privacy policy unavailable" }; this.releaseNotice(`a ${kind} note was not saved to hub memory (${(e as Error).message})`); return undefined; } } /** An approved task's decision, contract and fail notes move to long-term; its short-term entries start to expire (#258). */ /** * At hub start: an approved task whose settle entry a crash or a failed write cut off is settled now, so its * decisions, contracts and fails still reach long-term memory and its findings get their deadline. */ reconcileMemory(): number { if (!this.d.store) return 0; let n = 0; for (const t of this.d.board.list("approved")) { if (this.isPii(t)) continue; try { this.d.memoryCheck?.(); const key = this.memoryKey(t); if (this.d.store.store.hasTask(key) && !this.d.store.store.settled(key, { includeLegacy: true }) && this.settleMemory(t)) n++; } catch { /* fail-open: tried again at the next start */ } } return n; } private settleMemory(task: Task): boolean { const st = this.d.store; if (!st || this.isPii(task)) return false; try { this.d.memoryCheck?.(); st.store.settle(this.memoryKey(task), task.reviewer ?? task.owner ?? HUB); return true; } catch (e) { this.releaseNotice(`task #${task.id}: hub memory could not settle its notes (${(e as Error).message})`); return false; } } /** Standalone outbound rules plus the hub's current routing and project-private-path policy. */ private memorySyncPolicy() { const st = this.d.store!; const hostScreen = (row: Record) => { const taskKeyValue = typeof row.task === "string" ? row.task : undefined; const match = taskKeyValue ? /#(\d+)@(\d+)$/.exec(taskKeyValue) : null; const task = match ? this.d.board.get(Number(match[1])) : undefined; const taskPaths = task && String(task.created) === match?.[2] ? [...(task.refs.paths ?? []), ...(task.plan?.paths ?? [])] : []; const title = typeof row.title === "string" ? row.title : ""; const text = typeof row.text === "string" ? row.text : ""; const about = Array.isArray(row.about) ? row.about.filter((value): value is string => typeof value === "string") : []; const extraText = JSON.stringify(Object.fromEntries(Object.entries(row).filter(([key]) => !["title", "text", "about", "task", "project"].includes(key)))); const note = { title, text: `${text}\n${extraText}`, about: [...about, ...taskPaths.map(path => `path:${path}`)], ...(typeof row.task === "string" ? { task: row.task } : {}), ...(typeof row.project === "string" ? { project: row.project } : {}) }; const safe = withoutPii([note], this.d.routing(), this.d.cwd, this.d.piiPaths ?? []); const privatePath = mentionsPrivatePath(`${title}\n${text}\n${extraText}`, note.about, this.d.piiPaths ?? [], this.d.cwd); return safe.length && !privatePath ? { ok: true as const } : { ok: false as const, rule: "hub privacy policy: PII pattern or private path" }; }; return createMemorySyncPolicy({ home: st.store.profile.home, cwd: this.d.cwd, denyPaths: st.deny, piiPatterns: this.d.routing().signals.pii_patterns, hostScreen }); } /** * Whether a note names, or its task touches, a path the current `pii.paths` makes private: checked before either memory * backend sees it, whatever the task's signals said when it was proposed. */ private aboutPrivatePath(title: string, text: string, task: Task | undefined): boolean { const st = this.d.store; // No denylist here: a path the graph leaves out is still checked against the privacy policy. const about = extractNodes(`${title}\n${text}`, { cwd: this.d.cwd, project: st?.project ?? this.d.project, repo: st?.repo ?? this.d.project, deny: [], paths: [...(task?.refs.paths ?? []), ...(task?.plan?.paths ?? [])], symbols: task?.plan?.symbols }); return mentionsPrivatePath(`${title}\n${text}`, about, this.d.piiPaths ?? [], this.d.cwd); } /** Auto notes: only transitions that carry content, never for PII. */ private note(task: Task, by: PeerId, kind: Kind, text: string, withheld = false, symbols?: MemorySymbolNodes): void { if (this.isPii(task) || (!this.d.memory && !this.d.store)) return; // Model-written text must clear the host PII screen (#198/#69); long-term memory may sync (#258). No secrets. if (withheld || !this.nameable(text)) return this.releaseNotice(`task #${task.id}: a ${kind} note was not saved to shared memory (${this.whyWithheld(text)})`); if (looksSecret(text)) return this.releaseNotice(`task #${task.id}: a ${kind} note was not saved to shared memory (it looks like it holds a secret)`); const title = `agent-hub task #${task.id}: ${task.title}`.slice(0, 120); if (this.aboutPrivatePath(title, text, task)) return this.releaseNotice(`task #${task.id}: a ${kind} note was not saved to shared memory (it is about a private path)`); const native = this.saveNative(by, kind, text, title, task, undefined, "project", symbols); if (native && "refused" in native) return this.releaseNotice(`task #${task.id}: a ${kind} note was not saved to shared memory (${native.refused})`); if (native && "id" in native && this.d.store?.onGeneratedNote) { try { // Existing repository metadata is warmed by normal task admission/completion, never a new provenance probe. // At the extraction ceiling completeness is unknown. Keep the old bytes rather than a partial proof. if (this.d.privateTurn?.(by) === false && this.memoryCodeEligible(task) && native.about.length < 64 && !symbols?.truncated && !symbols?.unknown) { const anchors = generatedRecordAnchors(native.about); if (anchors && anchors.every(anchor => this.nameable(anchor))) this.d.store.onGeneratedNote({ id: native.id, anchors }); } } catch { /* Callback/privacy uncertainty cannot affect a saved note or the preceding board write. */ } } if (!native && this.d.memory) { try { this.markMemoryReference(task, by); } catch { return this.releaseNotice(`task #${task.id}: memory reference could not be recorded; note was not saved`); } void this.d.memory.save({ text, title, project: this.d.project, metadata: { peer: by, task: task.id, kind } }); } } /** * #1221 T2: one accepted supervision proposal's notice, to the owners of the tasks it names. A delivery through the * same owner path `tell` uses, never a board write: the task's own result stays in its history and a later review of * that result stays a separate record. The person is not told here (the console owns that), and a private task is * refused, so nothing about one leaves the machine. */ supervisionNotice(task: number, other: number | undefined, body: string): { sent: PeerId[]; refused?: string } { const primary = this.d.board.get(task); if (!primary) return { sent: [], refused: `task #${task} is not on the board` }; if (this.isPii(primary)) return { sent: [], refused: "a private task is never proposed on" }; const partner = other === undefined ? undefined : this.d.board.get(other); if (other !== undefined && partner && this.isPii(partner)) return { sent: [], refused: "a private task is never proposed on" }; const targets = [...new Set([primary.owner, partner?.owner].filter((peer): peer is PeerId => !!peer && peer !== USER && peer !== HUB))]; if (!targets.length) return { sent: [], refused: "the task has no owner to tell" }; for (const peer of targets) this.d.bus.publish(newEnvelope(HUB, body, { to: [peer], kind: "task", priority: "important", refs: { task: String(task), taskRecipient: "owner" } })); return { sent: targets }; } private tell(task: Task, body: string, pii: boolean, audience: "owner" | "withdrawal" = "owner", reviewObserverExcluded = false): void { if (!task.owner || task.owner === USER) return; this.d.bus.publish(newEnvelope(HUB, body, { to: [task.owner], kind: reviewObserverExcluded ? "review" : "task", priority: "important", refs: { task: String(task.id), ...(reviewObserverExcluded ? { reviewPackage: `finding-${crypto.randomUUID()}` } : {}), ...(audience === "owner" ? { taskRecipient: "owner" as const } : {}) }, ...(pii ? { private: true } : {}) })); } } export { LOCAL } from "./routing.ts";