@staix/agent-hub 0.51.0 → 0.52.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +35 -0
- package/README.md +1 -1
- package/docs/adding-an-ai-tool.md +24 -2
- package/docs/agent-notes/adapters.md +1 -0
- package/docs/agent-notes/budget.md +8 -2
- package/docs/agent-notes/daemon.md +13 -8
- package/docs/agent-notes/security-review.md +6 -5
- package/docs/agent-notes/tasks.md +5 -2
- package/docs/agent-notes/tests.md +4 -3
- package/docs/cooperbench.md +1 -1
- package/docs/design/adapters.md +4 -0
- package/docs/design/cli-output-inventory.md +162 -152
- package/docs/design/cli-output.md +4 -3
- package/docs/design/guidance-probes.md +1 -0
- package/docs/design/roadmap.md +2 -0
- package/docs/design/task-board.md +1 -0
- package/docs/dogfood.md +14 -0
- package/docs/events.md +4 -2
- package/docs/memory.md +5 -3
- package/docs/operations.md +210 -16
- package/docs/quickstart.md +12 -2
- package/docs/roles.md +1 -1
- package/docs/sdlc.md +26 -3
- package/docs/security.md +11 -5
- package/docs/specs/2026-09-19-agent-hub-design.md +43 -0
- package/docs/specs/2026-09-19-multi-project-design.md +4 -0
- package/docs/specs/2026-09-20-upgrade-recovery-design.md +17 -0
- package/docs/specs/mcp-endpoint.md +63 -0
- package/docs/verification/2026-11-30-capability-listing-shape-1808.md +45 -0
- package/docs/verification/2026-11-30-upgrade-keep-1807.md +174 -0
- package/docs/verification/2026-12-01-1811-confirmation-receipt.md +19 -0
- package/docs/verification/2026-12-01-1811-orca-agent-list.md +20 -0
- package/docs/verification/2026-12-01-1811-orca-pane-key.md +21 -0
- package/docs/verification/2026-12-02-1819-claude-process-after-renewal.md +54 -0
- package/docs/verification/2026-12-02-agy-1.5.21.md +74 -0
- package/docs/verification/2026-12-02-claude-implementer-2.1.334.md +44 -0
- package/docs/verification/2026-12-02-cli-import-graph.md +33 -0
- package/docs/verification/2026-12-03-0.52.0.md +150 -0
- package/docs/verification/2026-12-03-codex-0173-reviewer-isolation.md +53 -0
- package/docs/verification/2026-12-03-codex-0173-reviewer-tool-call.md +34 -0
- package/docs/verification/2026-12-03-jcode-1.3.0.md +25 -0
- package/docs/verification/agy/README.md +17 -0
- package/docs/verification/agy/cli-surface.ts +68 -0
- package/docs/verification/agy/interactive-bridge.ts +92 -0
- package/docs/verification/agy/interactive-session.ts +131 -0
- package/docs/verification/agy/launcher-nonce.ts +215 -0
- package/docs/verification/agy/native-hooks.ts +210 -0
- package/docs/verification/agy/originals/agent-hub-681/cli-surface.ts +87 -0
- package/docs/verification/agy/originals/agent-hub-681/native-hooks-adapted.ts +91 -0
- package/docs/verification/agy/originals/agent-hub-681/tui-actual.ts +200 -0
- package/docs/verification/agy/originals/agent-hub-684/probe.ts +107 -0
- package/docs/verification/agy/originals.json +25 -0
- package/docs/verification/agy/permission-new-functions.ts +128 -0
- package/docs/verification/agy/run-probe.py +108 -0
- package/docs/verification/agy/runtime.ts +171 -0
- package/docs/verification/agy/tmux-helper-control.ts +6 -0
- package/docs/verification/agy/tmux-session.ts +235 -0
- package/docs/verified.json +82 -41
- package/package.json +3 -3
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/compat.json +157 -0
- package/plugins/agent-hub/kimi-hook.js +621 -865
- package/plugins/agent-hub/server.js +17423 -32962
- package/src/adapters/agy/definition.ts +7 -24
- package/src/adapters/channel-peer.ts +3 -1
- package/src/adapters/claude-channel.ts +38 -257
- package/src/adapters/claude-implementer.ts +3 -1
- package/src/adapters/codex-appserver.ts +77 -15
- package/src/adapters/compat.ts +74 -11
- package/src/adapters/configured-acp.ts +23 -163
- package/src/adapters/configured-adapter-policy.ts +160 -0
- package/src/adapters/configured-pull-entry.ts +53 -0
- package/src/adapters/configured-pull.ts +38 -0
- package/src/adapters/conformance/fakes/app-server.ts +9 -2
- package/src/adapters/declaration-catalog.ts +25 -0
- package/src/adapters/declaration-data.ts +342 -0
- package/src/adapters/declaration-resolution.ts +53 -0
- package/src/adapters/definitions/builtin-metadata.ts +61 -83
- package/src/adapters/definitions/jcode-launch.ts +13 -0
- package/src/adapters/definitions/native-adapter-policy.ts +390 -0
- package/src/adapters/definitions/native-cli-claude-launch.ts +3 -2
- package/src/adapters/definitions/native-cli-codex-launch.ts +2 -1
- package/src/adapters/definitions/native-cli-entry-jcode.ts +4 -2
- package/src/adapters/definitions/native-cli-entry-types.ts +9 -2
- package/src/adapters/definitions/native-cli-launch-common.ts +2 -2
- package/src/adapters/definitions/native-cli-retained.ts +1 -1
- package/src/adapters/definitions/native-configuration.ts +18 -0
- package/src/adapters/definitions/native-help.ts +24 -0
- package/src/adapters/definitions/native-launch-declarations.ts +34 -0
- package/src/adapters/definitions/native-launch-policy.ts +4 -0
- package/src/adapters/definitions/native-launch-settings.ts +72 -0
- package/src/adapters/definitions/native-light-cli.ts +18 -0
- package/src/adapters/definitions/native-light-preview.ts +10 -0
- package/src/adapters/definitions/native-wrapper-launch.ts +10 -0
- package/src/adapters/definitions/qwen.ts +6 -29
- package/src/adapters/definitions/reviewer-variants.ts +7 -8
- package/src/adapters/external-declarations.ts +31 -0
- package/src/adapters/external-modules.ts +4 -29
- package/src/adapters/jcode.ts +3 -12
- package/src/adapters/native-capabilities.ts +18 -8
- package/src/adapters/native-proof-ports.ts +1 -1
- package/src/adapters/presets.ts +136 -0
- package/src/adapters/qwen-dual.ts +2 -2
- package/src/adapters/registry-types.ts +3 -0
- package/src/adapters/registry.ts +20 -81
- package/src/adapters/reviewer-print.ts +26 -9
- package/src/adapters/role-eligibility.ts +2 -1
- package/src/cli/accounts-import.ts +72 -0
- package/src/cli/agents-latest-table.ts +88 -0
- package/src/cli/agents-latest.ts +22 -0
- package/src/cli/agents-output.ts +10 -0
- package/src/cli/agents-presets.ts +100 -0
- package/src/cli/agents.ts +1 -1
- package/src/cli/attention.ts +3 -2
- package/src/cli/autonomy-homes.ts +7 -2
- package/src/cli/budget-renew-guidance.ts +129 -0
- package/src/cli/claude-homes.ts +9 -5
- package/src/cli/command-context.ts +3 -0
- package/src/cli/command-table.ts +123 -0
- package/src/cli/commands/accounts.ts +8 -0
- package/src/cli/commands/agents.ts +18 -0
- package/src/cli/commands/answer.ts +28 -0
- package/src/cli/commands/ask.ts +17 -0
- package/src/cli/commands/autonomy.ts +83 -0
- package/src/cli/commands/backlog.ts +46 -0
- package/src/cli/commands/bench.ts +60 -0
- package/src/cli/commands/board.ts +48 -0
- package/src/cli/commands/broker.ts +9 -0
- package/src/cli/commands/budget.ts +96 -0
- package/src/cli/commands/capabilities.ts +12 -0
- package/src/cli/commands/check-path.ts +55 -0
- package/src/cli/commands/completion.ts +8 -0
- package/src/cli/commands/console.ts +12 -0
- package/src/cli/commands/daemon.ts +8 -0
- package/src/cli/commands/deliverables.ts +25 -0
- package/src/cli/commands/doctor.ts +249 -0
- package/src/cli/commands/down.ts +3 -0
- package/src/cli/commands/export.ts +15 -0
- package/src/cli/commands/facts.ts +15 -0
- package/src/cli/commands/goal.ts +22 -0
- package/src/cli/commands/guidance.ts +102 -0
- package/src/cli/commands/help.ts +17 -0
- package/src/cli/commands/host.ts +45 -0
- package/src/cli/commands/init.ts +121 -0
- package/src/cli/commands/instructed.ts +19 -0
- package/src/cli/commands/instruction-hook.ts +15 -0
- package/src/cli/commands/intake.ts +24 -0
- package/src/cli/commands/kill.ts +15 -0
- package/src/cli/commands/learn.ts +23 -0
- package/src/cli/commands/lineage.ts +30 -0
- package/src/cli/commands/logs.ts +21 -0
- package/src/cli/commands/manager.ts +15 -0
- package/src/cli/commands/memory.ts +21 -0
- package/src/cli/commands/model.ts +25 -0
- package/src/cli/commands/models.ts +40 -0
- package/src/cli/commands/native.ts +39 -0
- package/src/cli/commands/pause.ts +5 -0
- package/src/cli/commands/peer.ts +32 -0
- package/src/cli/commands/permission.ts +26 -0
- package/src/cli/commands/permit.ts +12 -0
- package/src/cli/commands/pet.ts +24 -0
- package/src/cli/commands/projects.ts +49 -0
- package/src/cli/commands/queue.ts +70 -0
- package/src/cli/commands/recovery-run.ts +13 -0
- package/src/cli/commands/recovery.ts +130 -0
- package/src/cli/commands/release.ts +23 -0
- package/src/cli/commands/releases.ts +9 -0
- package/src/cli/commands/remember.ts +6 -0
- package/src/cli/commands/report.ts +27 -0
- package/src/cli/commands/research.ts +53 -0
- package/src/cli/commands/reset.ts +89 -0
- package/src/cli/commands/restart.ts +5 -0
- package/src/cli/commands/results.ts +31 -0
- package/src/cli/commands/resume.ts +5 -0
- package/src/cli/commands/review.ts +24 -0
- package/src/cli/commands/roadmap.ts +21 -0
- package/src/cli/commands/role.ts +34 -0
- package/src/cli/commands/roles.ts +30 -0
- package/src/cli/commands/room.ts +14 -0
- package/src/cli/commands/roster.ts +48 -0
- package/src/cli/commands/route.ts +9 -0
- package/src/cli/commands/say.ts +21 -0
- package/src/cli/commands/schedule.ts +17 -0
- package/src/cli/commands/sdlc.ts +321 -0
- package/src/cli/commands/settings.ts +148 -0
- package/src/cli/commands/setup.ts +89 -0
- package/src/cli/commands/shared-refusals.ts +25 -0
- package/src/cli/commands/smoke.ts +44 -0
- package/src/cli/commands/source.ts +64 -0
- package/src/cli/commands/specs.ts +13 -0
- package/src/cli/commands/status.ts +28 -0
- package/src/cli/commands/stop.ts +17 -0
- package/src/cli/commands/structure.ts +60 -0
- package/src/cli/commands/study.ts +39 -0
- package/src/cli/commands/tail.ts +19 -0
- package/src/cli/commands/task.ts +114 -0
- package/src/cli/commands/title.ts +17 -0
- package/src/cli/commands/turns.ts +10 -0
- package/src/cli/commands/ui.ts +47 -0
- package/src/cli/commands/undo.ts +77 -0
- package/src/cli/commands/up.ts +39 -0
- package/src/cli/commands/upgrade.ts +5 -0
- package/src/cli/commands/usage.ts +33 -0
- package/src/cli/commands/version.ts +5 -0
- package/src/cli/commands/watch.ts +30 -0
- package/src/cli/commands/worktrees.ts +31 -0
- package/src/cli/console-state.ts +5 -138
- package/src/cli/console-versions.ts +1 -1
- package/src/cli/help.ts +37 -15
- package/src/cli/identity.ts +23 -4
- package/src/cli/launch-check.ts +1 -2
- package/src/cli/launch.ts +13 -82
- package/src/cli/light-dispatch.ts +29 -0
- package/src/cli/main.js +8 -1
- package/src/cli/main.ts +233 -2816
- package/src/cli/orca-probe.ts +119 -0
- package/src/cli/output.ts +31 -2
- package/src/cli/preview.ts +10 -5
- package/src/cli/recovery-version-preflight.ts +28 -9
- package/src/cli/replace-process.ts +22 -0
- package/src/cli/report-layout.ts +142 -0
- package/src/cli/roadmap-usage.ts +16 -0
- package/src/cli/roadmap.ts +3 -16
- package/src/cli/sdlc-doctor.ts +27 -0
- package/src/cli/sdlc-output.ts +55 -1
- package/src/cli/setup-homes.ts +1 -1
- package/src/cli/start-agents-run.ts +1 -1
- package/src/cli/statusline-tee.ts +25 -4
- package/src/cli/terminal-recovery.ts +53 -10
- package/src/cli/upgrade-interactive.ts +1 -0
- package/src/cli/upgrade-runtime.ts +11 -0
- package/src/cli/upgrade.ts +4 -15
- package/src/hub/accounts.ts +148 -0
- package/src/hub/addons.ts +20 -0
- package/src/hub/agent-drift.ts +2 -1
- package/src/hub/budget-projection.ts +39 -7
- package/src/hub/budget.ts +231 -16
- package/src/hub/channel-project.ts +3 -3
- package/src/hub/conductor-peer.ts +24 -0
- package/src/hub/conductor.ts +2 -21
- package/src/hub/config-apply.ts +24 -13
- package/src/hub/config-edit.ts +1 -1
- package/src/hub/config-tier.ts +2 -0
- package/src/hub/config.ts +31 -14
- package/src/hub/control-client.ts +48 -0
- package/src/hub/daemon.ts +421 -61
- package/src/hub/events.ts +3 -0
- package/src/hub/home-tag.ts +12 -0
- package/src/hub/host.ts +217 -0
- package/src/hub/hub-tools.ts +2 -1
- package/src/hub/instance-budget.ts +2 -2
- package/src/hub/instance-config.ts +15 -126
- package/src/hub/instances.ts +22 -6
- package/src/hub/instruction-receipt.ts +2 -2
- package/src/hub/kimi-usage.ts +38 -11
- package/src/hub/lifecycle.ts +86 -4
- package/src/hub/mcp-bridge-core.ts +98 -0
- package/src/hub/mcp-channel-push.ts +20 -0
- package/src/hub/mcp-endpoint-serve.ts +178 -0
- package/src/hub/mcp-endpoint.ts +226 -0
- package/src/hub/mcp-tool-call.ts +181 -0
- package/src/hub/operational-settings.ts +2 -0
- package/src/hub/orca-env.ts +6 -0
- package/src/hub/orca-state.ts +84 -0
- package/src/hub/peers.ts +5 -1
- package/src/hub/permission-mode.ts +2 -1
- package/src/hub/project.ts +20 -0
- package/src/hub/protocol-window.ts +58 -0
- package/src/hub/quota-origin.ts +20 -0
- package/src/hub/registry.ts +36 -2
- package/src/hub/report.ts +1 -1
- package/src/hub/research.ts +1 -1
- package/src/hub/review-brief.ts +47 -2
- package/src/hub/roster.ts +6 -3
- package/src/hub/routing.ts +9 -2
- package/src/hub/sdlc-check.ts +205 -0
- package/src/hub/sdlc-sync.ts +146 -0
- package/src/hub/sdlc.ts +33 -4
- package/src/hub/settings.ts +7 -4
- package/src/hub/start-agents.ts +1 -1
- package/src/hub/start-mode.ts +11 -4
- package/src/hub/structure-budget.ts +131 -0
- package/src/hub/structure-scan.ts +149 -0
- package/src/hub/tasks-experiment.ts +455 -0
- package/src/hub/tasks-guidance.ts +606 -0
- package/src/hub/tasks-roadmap-plan.ts +419 -0
- package/src/hub/tasks-roadmap.ts +491 -0
- package/src/hub/tasks-study.ts +661 -0
- package/src/hub/tasks-survey.ts +192 -0
- package/src/hub/tasks.ts +319 -2548
- package/src/hub/terminal-open.ts +5 -3
- package/src/hub/tooling.ts +3 -19
- package/src/hub/usage-rollup.ts +9 -3
- package/src/local/tools.ts +5 -0
- package/src/ui/index.html +1 -1
- package/src/ui/needs.ts +17 -5
- package/src/ui/peer-palette.ts +2 -4
- package/templates/presets/agents.json +60 -0
- package/templates/presets/confirmation-matrix.json +8 -8
package/src/hub/tasks.ts
CHANGED
|
@@ -1,33 +1,19 @@
|
|
|
1
|
+
import { ESCALATE_AFTER } from "./operational-settings.ts";
|
|
1
2
|
import { conductorPeer, requireConductor } from "./conductor.ts";
|
|
2
|
-
import { instructedExecution, instructedHistory } from "./instructed-exact.ts";
|
|
3
3
|
import { managedTaskPullRequest } from "./task-pr.ts";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { readMirrorSnapshot, planRoadmapMirror, recoverMirrorBinding } from "./roadmap-sync.ts";
|
|
4
|
+
import { type Milestone, type MilestoneLinkKind, type MilestonePatch, type MilestoneState, type MilestoneSuggestion, type DecomposePart, type DecomposeIntake, type MilestoneDecomposition } from "./roadmap.ts";
|
|
5
|
+
import { type MilestoneView, type RoadmapSnapshot } from "./roadmap-view.ts";
|
|
7
6
|
import { roadmapExport } from "./roadmap-export.ts";
|
|
8
|
-
import {
|
|
9
|
-
import { checkRoadmap, type DriftMilestone, type RoadmapDrift } from "./roadmap-check.ts";
|
|
7
|
+
import { checkRoadmap, type RoadmapDrift } from "./roadmap-check.ts";
|
|
10
8
|
import type { RoadmapConfig } from "./roadmap.ts";
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import { renderGuidanceVariantV1 } from "./guidance-variants.ts";
|
|
16
|
-
import { GuidanceProbeFixtureHost, type GuidanceProbeStore } from "./guidance-probe-store.ts";
|
|
17
|
-
import { GuidanceProbeError, GUIDANCE_PROBE_STOP_TIMEOUT_MS, GUIDANCE_PROBE_FENCE_INTERVAL_MS, GUIDANCE_PROBE_LIVE_LIMITS, isLiveGuidanceProbeManifest, guidanceProbeCanonical, guidanceProbeManifestKey,
|
|
18
|
-
parseGuidanceProbeRegistration, parseGuidanceProbeReceiptExport, probeHash, probeSha256, probeInteger, probeSessionGeneration,
|
|
19
|
-
type ProbeChildBinding, type ProbeStoredState, type ProbePublicReceipt, type ProbePublicStatus, type ProbeHostBinding,
|
|
20
|
-
type ProbeReceiptExport, type ProbeExportSlot, type ProbeReceiptV1, type ProbeRetentionState,
|
|
21
|
-
type ProbeAdmissionRecheck, type ProbeReservation, type ProbeSlot, type GuidanceProbeFakePorts, type GuidanceProbeManifestV1, type ProbeWorkerFramePreparer } from "./guidance-probes.ts";
|
|
22
|
-
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";
|
|
9
|
+
import { type ReadyToClose, type TreeRollup, type UnplacedResult } from "./roadmap-unplaced.ts";
|
|
10
|
+
import { type PublishPlanPart } from "./roadmap-decompose.ts";
|
|
11
|
+
import { type GuidanceProbeStore } from "./guidance-probe-store.ts";
|
|
12
|
+
import { type ProbeStoredState, type ProbeSlot, type GuidanceProbeFakePorts, type ProbeWorkerFramePreparer } from "./guidance-probes.ts";
|
|
23
13
|
import { buildEntryDiagnostic } from "./build-entry.ts";
|
|
24
14
|
import { taskShowAllowed } from "./conductor.ts";
|
|
25
|
-
import { executionOwnerSnapshot, parseOwnerLineageQuery, type ExecutionLineageOwnerPorts } from "./execution-lineage-owner.ts";
|
|
26
|
-
import { readExecutionLineage, type LineageResult } from "./execution-lineage.ts";
|
|
27
|
-
import { parseExecutionLinkInput, taskExecutionReference, executionLinkActor, executionReferenceDigest, type ExecutionLinkInput } from "./execution-links.ts";
|
|
28
|
-
import { executionReferenceKey, executionText, EXECUTION_REFERENCE_LIMITS, type ExecutionReferenceV1 } from "./execution-reference.ts";
|
|
29
15
|
import type { JournalDelivery } from "./delivery-journal.ts";
|
|
30
|
-
import {
|
|
16
|
+
import { inventoryBinding, parseSynthesisManifest, synthesisManifestHash, type SynthesisManifestV1, type SynthesisCurrent, type SynthesisReadiness } from "./synthesis-readiness.ts";
|
|
31
17
|
import { parseEvidenceRecord, parseEvidenceLink, evidenceLinkId, evidenceLinkCanonical, type EvidenceRecordInput, type EvidenceReceipt, type EvidenceLinkV1 } from "./research-evidence.ts";
|
|
32
18
|
import type { ActionMeta, ReviewAnchor } from "@staix/agent-console/contract";
|
|
33
19
|
import { parseReviewAnchor, reviewAnchorErrorMessage, anchorStatus, type ReviewAnchorStatus } from "./review-anchor.ts";
|
|
@@ -38,21 +24,16 @@ import { reviewCommentFields, reviewCommentNumber, reviewCommentId, reviewCommen
|
|
|
38
24
|
type ReviewCommentRecord, type ReviewCommentFence, type ReviewCommentMutation, type ReviewCommentCounts, type ReviewCommentView } from "./review-comments.ts";
|
|
39
25
|
import { evidenceOriginKeys, type EvidenceSourceRead } from "./source-read.ts";
|
|
40
26
|
import type { SourceMeta } from "./sources.ts";
|
|
41
|
-
import { parseAttemptReceipt, parseResearchRunners, verifyAttemptReceipt } from "./research-runner.ts";
|
|
42
27
|
import { approvalBinding, approvalText } from "./task-approval.ts";
|
|
43
28
|
import type { InvocationRow } from "./invocations.ts";
|
|
44
29
|
import type { ContextAdmission } from "./context-window.ts";
|
|
45
30
|
import { queueBackpressure, queueBackpressurePolicy, type QueueBackpressureCode, type QueueBackpressurePolicy, type QueueBackpressureStatus, type QueuePressure } from "./queue-backpressure.ts";
|
|
46
31
|
import { generatedRecordAnchors, type GeneratedNoteProof } from "../memory/record-provenance.ts";
|
|
47
32
|
import { canonicalMemorySymbolNode, normalizeMemorySymbolInput, MEMORY_SYMBOL_LIMIT, type MemorySymbolNodes } from "./memory-symbols.ts";
|
|
48
|
-
import { createHash
|
|
33
|
+
import { createHash } from "node:crypto";
|
|
49
34
|
import { types } from "node:util";
|
|
50
|
-
import {
|
|
51
|
-
import {
|
|
52
|
-
type ExperimentProtocolContract, type ExperimentProtocolRecord, type ExperimentAttemptRecord, type ExperimentWriteFence, type ExperimentHostEvidence, type ExperimentStatus } from "./research-experiments.ts";
|
|
53
|
-
import { parseComparisonPlan, comparisonPlanHash, comparisonProjection, evaluatorIdentityHash, protocolApprovalBindingMatches, type ComparisonPlanV1 } from "./research-experiments.ts";
|
|
54
|
-
import { parseResearchHandoff, studyProjection, campaignHash, parseResearchCampaign, type ResearchCampaignContract, type ResearchCampaignStatus } from "./research-campaign.ts";
|
|
55
|
-
import type { ResearchCampaignRecord, ResearchUnitBinding, PreparedResearchUnit, HandoffOutboundRow } from "./board.ts";
|
|
35
|
+
import { studyProjection, type ResearchCampaignStatus } from "./research-campaign.ts";
|
|
36
|
+
import type { ResearchCampaignRecord, ResearchUnitBinding, HandoffOutboundRow } from "./board.ts";
|
|
56
37
|
import { HANDOFF_EVENTS, HANDOFF_KEY, HandoffRefusal, handoffRequestDigest, duplicateIssueTasks, duplicateRefusalText, followBackLine, handoffEventFor, parseHandoff, type HandoffEvent } from "./handoff.ts";
|
|
57
38
|
import { taskShellBindingValid, type TaskShellBinding } from "./task-shell-command.ts";
|
|
58
39
|
import type { ReviewBudgetSnapshot, ReviewGate, ReviewUnknownQuota } from "./review-budget.ts";
|
|
@@ -62,12 +43,10 @@ import { publicTestIntegrity, readTestIntegrity, testIntegrityBlockers, type Tes
|
|
|
62
43
|
import { evalAdvice, evalGapBlockers, evalRequiredChecks, readEvalFor } from "./eval-gate.ts";
|
|
63
44
|
import { parseSecurityPass, securityPassBlockers, securityPassView, securityRequestLine, SECURITY_CHECKLIST, type SecurityPassRecord, type SecurityPassView } from "./security-pass.ts";
|
|
64
45
|
import { deriveRiskTier, riskLine, riskPlanFloor, riskView, withoutRisk, type RiskCard, type RiskRecord, type RiskView } from "./risk-tier.ts";
|
|
65
|
-
import { AUDIT_PROFILES, applyUnitReports, auditBrief, auditFindingView, auditIsPartial, auditSummary, needsVerification, parseUnitReports, seedLedger, settlementRefusal, SETTLEMENTS, unitId, verificationRefusal, type
|
|
46
|
+
import { AUDIT_PROFILES, applyUnitReports, auditBrief, auditFindingView, auditIsPartial, auditSummary, needsVerification, parseUnitReports, seedLedger, settlementRefusal, SETTLEMENTS, unitId, verificationRefusal, type AuditProfile, type AuditSummary, type CarryLookup, type PublicAuditFinding } from "./security-audit.ts";
|
|
66
47
|
import type { AuditSource } from "./audit-source.ts";
|
|
67
|
-
import {
|
|
68
|
-
type SurveyFinding, type SurveyFocus, type SurveyPass } from "./advisor-survey.ts";
|
|
48
|
+
import { surveyPath, surveyInputProblem, type SurveyFinding, type SurveyFocus, type SurveyPass } from "./advisor-survey.ts";
|
|
69
49
|
import { consideredFindingMatch, parseConsideredEntry, type ConsideredEntry } from "./considered-findings.ts";
|
|
70
|
-
import type { StoredSurvey, SurveyPreparedCard } from "./board.ts";
|
|
71
50
|
import { matchConfigPath } from "./eval-gate.ts";
|
|
72
51
|
import { completePlanInventory, planDrift, planConformance, planConformanceBlockers, planFingerprint, type PlanConformance } from "./plan-conformance.ts";
|
|
73
52
|
import { RELEASE_TRAIN_HISTORY_LIMIT, releaseTrainData, releaseTrainReadiness, releaseMetrics } from "./sdlc-release.ts";
|
|
@@ -83,7 +62,7 @@ import type { InstancesConfig } from "./instances.ts";
|
|
|
83
62
|
import { composeRememberText } from "./memory-fail.ts";
|
|
84
63
|
import { VERSION } from "../version.ts";
|
|
85
64
|
import { NoWriteTurns } from "./no-writes.ts";
|
|
86
|
-
import { readGitHubImport,
|
|
65
|
+
import { readGitHubImport, type GitHubSource, type GitHubImportSelection } from "./github-import.ts";
|
|
87
66
|
import { BACKLOG_SPLIT_SCREEN_TIMEOUT_MS, actualTaskDates, planningPatch, type PlanningFields, type Release, type ReleaseState } from "./planning.ts";
|
|
88
67
|
import { readMergeQueue, type DeliveryTask, type MergeQueue } from "./sdlc-queue.ts";
|
|
89
68
|
import { INLINE_MERGE_READBACK_DEADLINE_MS, MERGE_READBACK_DEADLINE_MS, adoptMergeGates, guardedMerge, mergeModeFor, mergeView, readAdoptMergeEvidence, requiredChecksFor, type MergeView } from "./sdlc-merge.ts";
|
|
@@ -91,8 +70,8 @@ import { mirrorVerdict as mirrorToGitHub, type MirrorVerdict } from "./sdlc-mirr
|
|
|
91
70
|
import { CODE_SCOPE_LINE, evidenceOnlyNotice, type ReviewScope } from "./review-scope.ts";
|
|
92
71
|
import { DEFAULT_MAX_NITS, parseReviewFindings, findingsForHead, findingHead as resolveFindingHead, findingTally, findingFollowUps, positionalFindingId, type ReviewFinding, type ReviewFindingSet } from "./review-findings.ts";
|
|
93
72
|
import { readReleaseReadiness, type ReleaseReportPolicy } from "./sdlc-release.ts";
|
|
94
|
-
import { loadRoleCatalog,
|
|
95
|
-
import { matchesPolicy,
|
|
73
|
+
import { loadRoleCatalog, taskRole, taskRoleText, type RoleCatalog } from "./roles.ts";
|
|
74
|
+
import { matchesPolicy, policyRealPath, insideRoot } from "./path-policy.ts";
|
|
96
75
|
import { isDenied } from "../local/deny.ts";
|
|
97
76
|
import { foldSegment, isHubWritePath } from "./permission-mode.ts";
|
|
98
77
|
import { correctionInput, resolveVisibleMemory } from "./memory-candidates.ts";
|
|
@@ -102,7 +81,7 @@ import { withoutPii, mentionsPrivatePath } from "./memory-policy.ts";
|
|
|
102
81
|
import { createMemorySyncPolicy } from "./memory-sync-policy.ts";
|
|
103
82
|
import { profileClass, profileData, profileTaskLabel, projectProfile, type ProfileName, type ProfileSelection, type ProjectProfile } from "./profiles.ts";
|
|
104
83
|
import { criteriaView, unmetCriteriaIds, workflowHash } from "./workflow.ts";
|
|
105
|
-
import { candidateCard, CHECKLIST_MAX_LINES, checklistLineMarker, criterionKey, groupUnmetCriteria, LEARNING_DEFAULTS, overridesDiff, parseCandidateCard, parseRemovalCard, removalCard, removalKey, selectGroups,
|
|
84
|
+
import { candidateCard, CHECKLIST_MAX_LINES, checklistLineMarker, criterionKey, groupUnmetCriteria, LEARNING_DEFAULTS, overridesDiff, parseCandidateCard, parseRemovalCard, removalCard, removalKey, selectGroups, type CriterionGroup } from "./learning.ts";
|
|
106
85
|
import { acceptanceSuffix, FOLLOWUP_DEFAULTS, outcomeOf, rateIn, readAcceptance, removalDue, weakest, type AcceptanceRecord, type OutcomeView, type Rate } from "./learn-followup.ts";
|
|
107
86
|
/** #514b: how a closed candidate card says what the person decided; `learnCandidates` reads them back. */
|
|
108
87
|
const LEARN_ACCEPTED = "candidate accepted", LEARN_REJECTED = "candidate rejected";
|
|
@@ -114,12 +93,12 @@ const learnVerdict = (card: Pick<Task, "state" | "history">): "accepted" | "reje
|
|
|
114
93
|
return closed.note?.startsWith(LEARN_ACCEPTED) ? "accepted" : closed.note?.startsWith(LEARN_REJECTED) ? "rejected" : undefined;
|
|
115
94
|
};
|
|
116
95
|
import { approvedDeliverables, latestDeliverables, parseDeliverableClaims, publicDeliverables, type DeliverableRecord, type DeliverableStatus } from "./deliverables.ts";
|
|
117
|
-
import { checkDeliverables, DeliverableRefusal, hashDeliverables, vetDeliverables,
|
|
96
|
+
import { checkDeliverables, DeliverableRefusal, hashDeliverables, vetDeliverables, type DeliverablePorts } from "./deliverable-files.ts";
|
|
118
97
|
import { isAbsolute, relative, resolve } from "node:path";
|
|
119
98
|
import type { Briefs, NativeItem } from "../memory/brief.ts";
|
|
120
99
|
import type { MemoryClient } from "../memory/client.ts";
|
|
121
|
-
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";
|
|
122
|
-
import { HOST_SPEC_ACCEPTANCE_CARRY, HOST_MERGE_ADOPTION, HOST_ROADMAP_DRAFT, parseClaimVerdict, taskClaimIdentity, CLASSES, OUTCOMES_KEPT_MS, ALL_PLAN_KEYS, TASK_MOVE_REASONS,
|
|
100
|
+
import { captureSessionKey, 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";
|
|
101
|
+
import { HOST_SPEC_ACCEPTANCE_CARRY, HOST_MERGE_ADOPTION, HOST_ROADMAP_DRAFT, parseClaimVerdict, taskClaimIdentity, CLASSES, OUTCOMES_KEPT_MS, ALL_PLAN_KEYS, TASK_MOVE_REASONS, type TaskReason, 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";
|
|
123
102
|
import type { Bus } from "./bus.ts";
|
|
124
103
|
import { HUB, newEnvelope, NOTE_KINDS, noteLine, sanitize, USER, type Envelope, type PeerId, type PeerState } from "./envelope.ts";
|
|
125
104
|
import type { PiiVerdict, ScreenItem, ScreenRecord } from "./inference.ts";
|
|
@@ -141,6 +120,12 @@ import { plannerGrooming, nextSweep, plannedStartPending, taskSweepConfig, taskW
|
|
|
141
120
|
import { CiWatchers, pollCi, type CiOutcome, type CiRetryDecision, type CiShardRetry, type CiSnapshot, type CiWatch } from "./ci-watch.ts";
|
|
142
121
|
import { acceptedSpecEdit, 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";
|
|
143
122
|
import { missingReadbackRefs, parseSpecReadbackReport, type ReadbackView, type SpecReadbackReport } from "./spec-readback.ts";
|
|
123
|
+
import { StudyDomain, type StudyHost } from "./tasks-study.ts";
|
|
124
|
+
import { RoadmapDomain, type RoadmapHost } from "./tasks-roadmap.ts";
|
|
125
|
+
import { RoadmapPlanDomain, type RoadmapPlanHost } from "./tasks-roadmap-plan.ts";
|
|
126
|
+
import { GuidanceDomain, type GuidanceHost } from "./tasks-guidance.ts";
|
|
127
|
+
import { ExperimentDomain, type ExperimentHost, type ComparisonPlanReceipt, type ExperimentReceipt } from "./tasks-experiment.ts";
|
|
128
|
+
import { SurveyDomain, type SurveyHost } from "./tasks-survey.ts";
|
|
144
129
|
|
|
145
130
|
/** #1176: refusals for an agent that reaches a person-run card by a path other than the pull gate. */
|
|
146
131
|
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)";
|
|
@@ -180,9 +165,6 @@ export interface AuditView extends AuditSummary {
|
|
|
180
165
|
/** Findings in this report that were already verified or rejected, so the hub left them as decided. */
|
|
181
166
|
notUpdated?: string[];
|
|
182
167
|
}
|
|
183
|
-
/** #1738: how long one working-tree spec check serves the roadmap snapshot. */
|
|
184
|
-
const ROADMAP_SPECS_REUSE_MS = 60_000;
|
|
185
|
-
|
|
186
168
|
export interface TasksDeps {
|
|
187
169
|
/** #1647 AC4: the hub's own token increments per task (a task id to its count, null when unknown), for the metrics grouped by reason. Read-only; absent means no reading. */
|
|
188
170
|
taskTokens?: () => Readonly<Record<number, number | null>>;
|
|
@@ -422,7 +404,7 @@ export interface TasksDeps {
|
|
|
422
404
|
}
|
|
423
405
|
|
|
424
406
|
/** The `tasks.escalate_after` default (#488): the third consecutive changes_requested escalates. */
|
|
425
|
-
export
|
|
407
|
+
export { ESCALATE_AFTER } from "./operational-settings.ts";
|
|
426
408
|
// Demotion (issue #36): a failure counts half after a day. A peer is demoted for a class once its decayed failures
|
|
427
409
|
// reach 1.5 (two within about half a day, three within two days) and outweigh its decayed successes there.
|
|
428
410
|
// #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).
|
|
@@ -482,9 +464,6 @@ export class AssignmentSupersededError extends Error {
|
|
|
482
464
|
export const normPath = (p: string) => p.replace(/^(\.\/)+/, "").replace(/\/{2,}/g, "/").replace(/\/+$/, "") || ".";
|
|
483
465
|
|
|
484
466
|
/** Same path, or one is a directory of the other; the project root (`.`) holds everything. */
|
|
485
|
-
/** #1647: how many overlapping paths a parallel-sibling refusal names, so the text stays one line. */
|
|
486
|
-
const PARALLEL_PATHS_NAMED = 5;
|
|
487
|
-
|
|
488
467
|
export const samePlace = (a: string, b: string) => {
|
|
489
468
|
const [x, y] = [normPath(a), normPath(b)];
|
|
490
469
|
return x === "." || y === "." || x === y || x.startsWith(`${y}/`) || y.startsWith(`${x}/`);
|
|
@@ -589,19 +568,7 @@ export const GROOM_FYI_WINDOW_MS = 10 * 60_000;
|
|
|
589
568
|
*/
|
|
590
569
|
/** #694: a PR staged at done with the commit or branch it was read for. */
|
|
591
570
|
export interface ResearchCampaignReceipt { id: string; parentTaskId: number; revision: number; status: ResearchCampaignStatus; unitCount: number; units: ResearchUnitBinding[] }
|
|
592
|
-
|
|
593
|
-
export interface ExperimentReceipt { kind: "protocol" | "attempt" | "event" | "receipt"; protocolHash: string; attemptId?: string; seq?: number; receiptId?: string }
|
|
594
|
-
export interface ComparisonPlanReceipt { kind: "plan"; planHash: string }
|
|
595
|
-
export interface ProtocolApprovalReceipt { protocolHash: string; evaluatorHash: string; approvedBy: string; approvedAt: number }
|
|
596
|
-
export interface ExperimentAttemptView {
|
|
597
|
-
id: string; protocolHash: string; taskId: number; phase: "development" | "final"; status: ExperimentStatus; private: boolean;
|
|
598
|
-
protocol: unknown; events: unknown[]; evidence: Record<string, unknown>; eventsComplete: boolean; nextEventCursor?: number;
|
|
599
|
-
campaignRevision: number; approval: "approved" | "unapproved"; postHoc: "unknown" | "predeclared" | "post-hoc";
|
|
600
|
-
retryOf?: string; reproducesAttemptId?: string; independentlyReproduced: false;
|
|
601
|
-
}
|
|
602
|
-
export interface ExperimentView { attempts: ExperimentAttemptView[]; counts: { all: number; statuses: Record<ExperimentStatus, number> }; nextCursor?: number;
|
|
603
|
-
comparison?: { planHash: string; baselineAttemptId: string; variantAttemptId: string; approved: boolean; private: boolean; projection: ReturnType<typeof comparisonProjection> | "[pii]" } }
|
|
604
|
-
interface ExperimentContext { task: Task; campaign: ResearchCampaignRecord; private: boolean; key: string; fence: ExperimentWriteFence }
|
|
571
|
+
export type { ExperimentReceipt, ComparisonPlanReceipt, ProtocolApprovalReceipt, ExperimentAttemptView, ExperimentView } from "./tasks-experiment.ts";
|
|
605
572
|
interface CompletionRefresh { revision: number; commit: string; state: "in_review" | "approved" }
|
|
606
573
|
interface RefileHeadGuard { recorded?: string }
|
|
607
574
|
interface IdentityLink { repo: string; pr: number; basis: { commit?: string; branch?: string }; managedRevision?: number }
|
|
@@ -644,18 +611,7 @@ function hasReviewAnchorInput(raw: unknown): boolean {
|
|
|
644
611
|
} catch { return true; }
|
|
645
612
|
}
|
|
646
613
|
|
|
647
|
-
interface GuidanceProbeRuntime {
|
|
648
|
-
id: string; by: PeerId; controller: AbortController; current: () => ProbeAdmissionRecheck;
|
|
649
|
-
requestedRevision: number; variantId?: string;
|
|
650
|
-
ports: GuidanceProbeFakePorts;
|
|
651
|
-
reservation?: ProbeReservation; promise?: Promise<ProbePublicReceipt>; stopPromise?: Promise<void>;
|
|
652
|
-
launched: boolean; launchSettled: boolean; stopSettled: boolean; stopKnown: boolean; stopRequested: boolean;
|
|
653
|
-
watch?: { handle: unknown }; failure?: Error;
|
|
654
|
-
}
|
|
655
614
|
export class Tasks {
|
|
656
|
-
private guidanceProbeStopping = false;
|
|
657
|
-
private guidanceProbeAdmissions = 0;
|
|
658
|
-
private readonly guidanceProbeActive = new Map<string, GuidanceProbeRuntime>();
|
|
659
615
|
private readonly findingPlacements = new WeakMap<ReviewReadiness, { binding: string; placements: Map<string, ReviewAnchorStatus>; placementOnly: boolean }>();
|
|
660
616
|
private findingPlacementBinding(task: Task): string {
|
|
661
617
|
return JSON.stringify([task.id, task.created, this.reviewHead(task), task.refs.paths, task.plan, this.reviewFindingSets(task)]);
|
|
@@ -909,9 +865,7 @@ export class Tasks {
|
|
|
909
865
|
private readonly repositories: TaskRepositories;
|
|
910
866
|
private readonly incomingBacklog = new Set<number>();
|
|
911
867
|
/** One accept attempt per (answer, part), so two concurrent accepts of one part make one draft (#1480 R2 part 2). */
|
|
912
|
-
private readonly decompositionAccepts = new Map<string, Promise<unknown>>();
|
|
913
868
|
/** One apply per milestone while it creates issues, so a retried call cannot POST every planned issue twice (#1480 R2 part 3). */
|
|
914
|
-
private readonly roadmapPublishes = new Set<number>();
|
|
915
869
|
private readonly plannerBacklog = new Map<PeerId, Set<number>>();
|
|
916
870
|
private readonly plannerBlockedQueue = new Map<PeerId, string>();
|
|
917
871
|
private readonly knownPlanners = new Set<PeerId>();
|
|
@@ -933,7 +887,145 @@ export class Tasks {
|
|
|
933
887
|
private readonly heldReviews = new Map<number, { head: string; reviewer: PeerId; revision: number }>();
|
|
934
888
|
private readonly autoPullAttached = new Set<PeerId>();
|
|
935
889
|
|
|
890
|
+
private readonly study: StudyDomain;
|
|
891
|
+
private readonly survey: SurveyDomain;
|
|
892
|
+
private readonly roadmap: RoadmapDomain;
|
|
893
|
+
private readonly roadmapPlan: RoadmapPlanDomain;
|
|
894
|
+
private readonly guidance: GuidanceDomain;
|
|
895
|
+
private readonly experiment: ExperimentDomain;
|
|
896
|
+
|
|
936
897
|
constructor(private readonly d: TasksDeps) {
|
|
898
|
+
// #1830 S4a: a host property is read through a getter so it is the value at the call, never one captured here.
|
|
899
|
+
const host = this;
|
|
900
|
+
this.study = new StudyDomain(d, {
|
|
901
|
+
cleanRefs: input => cleanRefs(input),
|
|
902
|
+
taskShowAllowed: (actor, task, roles, planner) => taskShowAllowed(actor, task, roles, planner),
|
|
903
|
+
get coordinationModes() { return host.coordinationModes; },
|
|
904
|
+
deliverablePorts: (...args: Parameters<StudyHost["deliverablePorts"]>) => host.deliverablePorts(...args),
|
|
905
|
+
experimentOutputPrivate: (...args: Parameters<StudyHost["experimentOutputPrivate"]>) => host.experimentOutputPrivate(...args),
|
|
906
|
+
get incomingBacklog() { return host.incomingBacklog; },
|
|
907
|
+
isConfiguredPlanner: (...args: Parameters<StudyHost["isConfiguredPlanner"]>) => host.isConfiguredPlanner(...args),
|
|
908
|
+
get isPii() { return host.isPii; },
|
|
909
|
+
get nameable() { return host.nameable; },
|
|
910
|
+
need: (...args: Parameters<StudyHost["need"]>) => host.need(...args),
|
|
911
|
+
places: (...args: Parameters<StudyHost["places"]>) => host.places(...args),
|
|
912
|
+
plannerWriteAuthority: (...args: Parameters<StudyHost["plannerWriteAuthority"]>) => host.plannerWriteAuthority(...args),
|
|
913
|
+
proposalPlanner: (...args: Parameters<StudyHost["proposalPlanner"]>) => host.proposalPlanner(...args),
|
|
914
|
+
get publicMetadataText() { return host.publicMetadataText; },
|
|
915
|
+
get publicTitle() { return host.publicTitle; },
|
|
916
|
+
releaseNotice: (...args: Parameters<StudyHost["releaseNotice"]>) => host.releaseNotice(...args),
|
|
917
|
+
get repositories() { return host.repositories; },
|
|
918
|
+
requestCheck: (...args: Parameters<StudyHost["requestCheck"]>) => host.requestCheck(...args),
|
|
919
|
+
requireLocalTaskPeer: peer => requireLocalTaskPeer(peer),
|
|
920
|
+
sendTask: (...args: Parameters<StudyHost["sendTask"]>) => host.sendTask(...args),
|
|
921
|
+
signalsFor: (...args: Parameters<StudyHost["signalsFor"]>) => host.signalsFor(...args),
|
|
922
|
+
states: (...args: Parameters<StudyHost["states"]>) => host.states(...args),
|
|
923
|
+
warmRepository: (...args: Parameters<StudyHost["warmRepository"]>) => host.warmRepository(...args),
|
|
924
|
+
withholds: (...args: Parameters<StudyHost["withholds"]>) => host.withholds(...args),
|
|
925
|
+
});
|
|
926
|
+
this.survey = new SurveyDomain(d, {
|
|
927
|
+
configuredManualConductor: (...args: Parameters<SurveyHost["configuredManualConductor"]>) => host.configuredManualConductor(...args),
|
|
928
|
+
consideredBefore: (...args: Parameters<SurveyHost["consideredBefore"]>) => host.consideredBefore(...args),
|
|
929
|
+
consideredBrief: (...args: Parameters<SurveyHost["consideredBrief"]>) => host.consideredBrief(...args),
|
|
930
|
+
consideredChanges: (...args: Parameters<SurveyHost["consideredChanges"]>) => host.consideredChanges(...args),
|
|
931
|
+
consideredDetails: (...args: Parameters<SurveyHost["consideredDetails"]>) => host.consideredDetails(...args),
|
|
932
|
+
get incomingBacklog() { return host.incomingBacklog; },
|
|
933
|
+
isConfiguredPlanner: (...args: Parameters<SurveyHost["isConfiguredPlanner"]>) => host.isConfiguredPlanner(...args),
|
|
934
|
+
get isPii() { return host.isPii; },
|
|
935
|
+
need: (...args: Parameters<SurveyHost["need"]>) => host.need(...args),
|
|
936
|
+
observerExcluded: (...args: Parameters<SurveyHost["observerExcluded"]>) => host.observerExcluded(...args),
|
|
937
|
+
propose: (...args: Parameters<SurveyHost["propose"]>) => host.propose(...args),
|
|
938
|
+
get publicMetadataText() { return host.publicMetadataText; },
|
|
939
|
+
releaseNotice: (...args: Parameters<SurveyHost["releaseNotice"]>) => host.releaseNotice(...args),
|
|
940
|
+
get repositories() { return host.repositories; },
|
|
941
|
+
requestCheck: (...args: Parameters<SurveyHost["requestCheck"]>) => host.requestCheck(...args),
|
|
942
|
+
reviewObserverTurn: (...args: Parameters<SurveyHost["reviewObserverTurn"]>) => host.reviewObserverTurn(...args),
|
|
943
|
+
screenCall: (...args: Parameters<SurveyHost["screenCall"]>) => host.screenCall(...args),
|
|
944
|
+
get screenOn() { return host.screenOn; },
|
|
945
|
+
signalsFor: (...args: Parameters<SurveyHost["signalsFor"]>) => host.signalsFor(...args),
|
|
946
|
+
studyHold: (...args: Parameters<SurveyHost["studyHold"]>) => host.studyHold(...args),
|
|
947
|
+
studyNumber: (...args: Parameters<SurveyHost["studyNumber"]>) => host.studyNumber(...args),
|
|
948
|
+
studyWrite: <T>(write: () => Promise<T>) => host.studyWrite(write),
|
|
949
|
+
});
|
|
950
|
+
this.roadmap = new RoadmapDomain(d, {
|
|
951
|
+
configuredManualConductor: (...args: Parameters<RoadmapHost["configuredManualConductor"]>) => host.configuredManualConductor(...args),
|
|
952
|
+
currentSpecReport: (...args: Parameters<RoadmapHost["currentSpecReport"]>) => host.currentSpecReport(...args),
|
|
953
|
+
isConfiguredPlanner: (...args: Parameters<RoadmapHost["isConfiguredPlanner"]>) => host.isConfiguredPlanner(...args),
|
|
954
|
+
get isPii() { return host.isPii; },
|
|
955
|
+
observerExcluded: (...args: Parameters<RoadmapHost["observerExcluded"]>) => host.observerExcluded(...args),
|
|
956
|
+
planIssueIdentity: (...args: Parameters<RoadmapHost["planIssueIdentity"]>) => host.planIssueIdentity(...args),
|
|
957
|
+
get publicMetadataText() { return host.publicMetadataText; },
|
|
958
|
+
get repositories() { return host.repositories; },
|
|
959
|
+
requestCheck: (...args: Parameters<RoadmapHost["requestCheck"]>) => host.requestCheck(...args),
|
|
960
|
+
requireLocalTaskPeer: peer => requireLocalTaskPeer(peer),
|
|
961
|
+
reviewObserverTurn: (...args: Parameters<RoadmapHost["reviewObserverTurn"]>) => host.reviewObserverTurn(...args),
|
|
962
|
+
samePlace: (a, b) => samePlace(a, b),
|
|
963
|
+
screenCall: (...args: Parameters<RoadmapHost["screenCall"]>) => host.screenCall(...args),
|
|
964
|
+
get screenOn() { return host.screenOn; },
|
|
965
|
+
});
|
|
966
|
+
this.roadmapPlan = new RoadmapPlanDomain(d, {
|
|
967
|
+
get incomingBacklog() { return host.incomingBacklog; },
|
|
968
|
+
get isPii() { return host.isPii; },
|
|
969
|
+
milestoneShow: (...args: Parameters<RoadmapPlanHost["milestoneShow"]>) => host.milestoneShow(...args),
|
|
970
|
+
propose: (...args: Parameters<RoadmapPlanHost["propose"]>) => host.propose(...args),
|
|
971
|
+
get publicMetadataText() { return host.publicMetadataText; },
|
|
972
|
+
publicView: (...args: Parameters<RoadmapPlanHost["publicView"]>) => host.publicView(...args),
|
|
973
|
+
releaseNotice: (...args: Parameters<RoadmapPlanHost["releaseNotice"]>) => host.releaseNotice(...args),
|
|
974
|
+
roadmapApplyAuthority: (...args: Parameters<RoadmapPlanHost["roadmapApplyAuthority"]>) => host.roadmapApplyAuthority(...args),
|
|
975
|
+
roadmapCurrent: (...args: Parameters<RoadmapPlanHost["roadmapCurrent"]>) => host.roadmapCurrent(...args),
|
|
976
|
+
roadmapGh: (...args: Parameters<RoadmapPlanHost["roadmapGh"]>) => host.roadmapGh(...args),
|
|
977
|
+
roadmapParsed: <T>(read: () => T): T => host.roadmapParsed(read),
|
|
978
|
+
roadmapReadAuthority: (...args: Parameters<RoadmapPlanHost["roadmapReadAuthority"]>) => host.roadmapReadAuthority(...args),
|
|
979
|
+
roadmapRepo: (...args: Parameters<RoadmapPlanHost["roadmapRepo"]>) => host.roadmapRepo(...args),
|
|
980
|
+
roadmapRepository: (...args: Parameters<RoadmapPlanHost["roadmapRepository"]>) => host.roadmapRepository(...args),
|
|
981
|
+
roadmapResult: (...args: Parameters<RoadmapPlanHost["roadmapResult"]>) => host.roadmapResult(...args),
|
|
982
|
+
roadmapScreen: (...args: Parameters<RoadmapPlanHost["roadmapScreen"]>) => host.roadmapScreen(...args),
|
|
983
|
+
roadmapSnapshot: (...args: Parameters<RoadmapPlanHost["roadmapSnapshot"]>) => host.roadmapSnapshot(...args),
|
|
984
|
+
roadmapWriteAuthority: (...args: Parameters<RoadmapPlanHost["roadmapWriteAuthority"]>) => host.roadmapWriteAuthority(...args),
|
|
985
|
+
screenCall: (...args: Parameters<RoadmapPlanHost["screenCall"]>) => host.screenCall(...args),
|
|
986
|
+
get screenOn() { return host.screenOn; },
|
|
987
|
+
});
|
|
988
|
+
this.guidance = new GuidanceDomain(d, {
|
|
989
|
+
requireConductor: (peer, roles) => requireConductor(peer, roles),
|
|
990
|
+
lineageMetadata: (...args: Parameters<GuidanceHost["lineageMetadata"]>) => host.lineageMetadata(...args),
|
|
991
|
+
lineagePorts: (...args: Parameters<GuidanceHost["lineagePorts"]>) => host.lineagePorts(...args),
|
|
992
|
+
lineageVisible: (...args: Parameters<GuidanceHost["lineageVisible"]>) => host.lineageVisible(...args),
|
|
993
|
+
get nameable() { return host.nameable; },
|
|
994
|
+
personOrConductor: (...args: Parameters<GuidanceHost["personOrConductor"]>) => host.personOrConductor(...args),
|
|
995
|
+
get publicMetadataText() { return host.publicMetadataText; },
|
|
996
|
+
requestCheck: (...args: Parameters<GuidanceHost["requestCheck"]>) => host.requestCheck(...args),
|
|
997
|
+
reviewObserverTurn: (...args: Parameters<GuidanceHost["reviewObserverTurn"]>) => host.reviewObserverTurn(...args),
|
|
998
|
+
screenCall: (...args: Parameters<GuidanceHost["screenCall"]>) => host.screenCall(...args),
|
|
999
|
+
get screenOn() { return host.screenOn; },
|
|
1000
|
+
studyHold: (...args: Parameters<GuidanceHost["studyHold"]>) => host.studyHold(...args),
|
|
1001
|
+
studyWrite: <T>(write: () => Promise<T>) => host.studyWrite(write),
|
|
1002
|
+
});
|
|
1003
|
+
this.experiment = new ExperimentDomain(d, {
|
|
1004
|
+
taskShowAllowed: (actor, task, roles, planner) => taskShowAllowed(actor, task, roles, planner),
|
|
1005
|
+
deliverablePorts: (...args: Parameters<ExperimentHost["deliverablePorts"]>) => host.deliverablePorts(...args),
|
|
1006
|
+
experimentOutputPrivate: (...args: Parameters<ExperimentHost["experimentOutputPrivate"]>) => host.experimentOutputPrivate(...args),
|
|
1007
|
+
isConfiguredPlanner: (...args: Parameters<ExperimentHost["isConfiguredPlanner"]>) => host.isConfiguredPlanner(...args),
|
|
1008
|
+
get isPii() { return host.isPii; },
|
|
1009
|
+
get nameable() { return host.nameable; },
|
|
1010
|
+
get publicMetadataText() { return host.publicMetadataText; },
|
|
1011
|
+
get repositories() { return host.repositories; },
|
|
1012
|
+
requireLocalTaskPeer: peer => requireLocalTaskPeer(peer),
|
|
1013
|
+
requestCheck: (...args: Parameters<ExperimentHost["requestCheck"]>) => host.requestCheck(...args),
|
|
1014
|
+
reviewTaskPrivate: (...args: Parameters<ExperimentHost["reviewTaskPrivate"]>) => host.reviewTaskPrivate(...args),
|
|
1015
|
+
screenCall: (...args: Parameters<ExperimentHost["screenCall"]>) => host.screenCall(...args),
|
|
1016
|
+
get screenOn() { return host.screenOn; },
|
|
1017
|
+
studyFields: (...args: Parameters<ExperimentHost["studyFields"]>) => host.studyFields(...args),
|
|
1018
|
+
studyHold: (...args: Parameters<ExperimentHost["studyHold"]>) => host.studyHold(...args),
|
|
1019
|
+
studyId: (...args: Parameters<ExperimentHost["studyId"]>) => host.studyId(...args),
|
|
1020
|
+
studyNumber: (...args: Parameters<ExperimentHost["studyNumber"]>) => host.studyNumber(...args),
|
|
1021
|
+
studyParent: (...args: Parameters<ExperimentHost["studyParent"]>) => host.studyParent(...args),
|
|
1022
|
+
studyRecord: (...args: Parameters<ExperimentHost["studyRecord"]>) => host.studyRecord(...args),
|
|
1023
|
+
studyReplayPrivacy: (...args: Parameters<ExperimentHost["studyReplayPrivacy"]>) => host.studyReplayPrivacy(...args),
|
|
1024
|
+
studySource: (...args: Parameters<ExperimentHost["studySource"]>) => host.studySource(...args),
|
|
1025
|
+
studyTime: (...args: Parameters<ExperimentHost["studyTime"]>) => host.studyTime(...args),
|
|
1026
|
+
studyWrite: <T>(write: () => Promise<T>) => host.studyWrite(write),
|
|
1027
|
+
withholds: (...args: Parameters<ExperimentHost["withholds"]>) => host.withholds(...args),
|
|
1028
|
+
});
|
|
937
1029
|
this.ciWatchers = new CiWatchers({
|
|
938
1030
|
...d.ciWatch,
|
|
939
1031
|
poll: watch => pollCi(watch, watch.head, d.sdlc ? requiredChecksFor(d.sdlc.config(), watch.repo) : [], d.sdlc?.gh ?? sdlcGh, true),
|
|
@@ -2283,271 +2375,62 @@ export class Tasks {
|
|
|
2283
2375
|
this.planningAuthority(by, task);
|
|
2284
2376
|
}
|
|
2285
2377
|
|
|
2286
|
-
|
|
2287
|
-
|
|
2288
|
-
private
|
|
2289
|
-
|
|
2378
|
+
async stopStudies(): Promise<void> { await this.study.stopStudies(); }
|
|
2379
|
+
studiesPending = (): number => this.study.studiesPending();
|
|
2380
|
+
private studyHold(): string | undefined { return this.study.studyHold(); }
|
|
2381
|
+
private async studyWrite<T>(write: () => Promise<T>): Promise<T> { return this.study.studyWrite(write); }
|
|
2382
|
+
private studyFields(input: unknown, allowed: readonly string[]): Record<string, unknown> { return this.study.studyFields(input, allowed); }
|
|
2383
|
+
private studyId(value: unknown): string { return this.study.studyId(value); }
|
|
2384
|
+
private studyNumber(value: unknown, field: string): number { return this.study.studyNumber(value, field); }
|
|
2385
|
+
private studyTime(): number { return this.study.studyTime(); }
|
|
2386
|
+
private studyRecord(id: string, revision?: number): ResearchCampaignRecord { return this.study.studyRecord(id, revision); }
|
|
2387
|
+
private studyParent(id: number): Task { return this.study.studyParent(id); }
|
|
2388
|
+
private studySource(id: string): { id: string; sha256: string; private: boolean } | undefined { return this.study.studySource(id); }
|
|
2389
|
+
private studyDispatchReason(task: Task, owner?: PeerId): string | undefined { return this.study.studyDispatchReason(task, owner); }
|
|
2390
|
+
private studyDispatchCheck(task: Task, owner?: PeerId): void { return this.study.studyDispatchCheck(task, owner); }
|
|
2391
|
+
private studyExcludedOwners(task: Task): PeerId[] { return this.study.studyExcludedOwners(task); }
|
|
2392
|
+
async studyHandoff(by: PeerId, input: unknown): Promise<{ campaignId: string; unitId: string; seq: number }> { return this.study.studyHandoff(by, input); }
|
|
2393
|
+
studyList(by: PeerId, input: unknown): { campaigns: ResearchCampaignReceipt[]; next?: string } { return this.study.studyList(by, input); }
|
|
2394
|
+
studyShow(by: PeerId, input: unknown): ReturnType<typeof studyProjection> { return this.study.studyShow(by, input); }
|
|
2395
|
+
private studyReplayPrivacy(record: ResearchCampaignRecord, parent: Task): boolean { return this.study.studyReplayPrivacy(record, parent); }
|
|
2396
|
+
async studyDraft(by: PeerId, input: unknown): Promise<ResearchCampaignReceipt> { return this.study.studyDraft(by, input); }
|
|
2397
|
+
async studyRevise(by: PeerId, input: unknown): Promise<ResearchCampaignReceipt> { return this.study.studyRevise(by, input); }
|
|
2398
|
+
async studyApprove(by: PeerId, input: unknown): Promise<ResearchCampaignReceipt> { return this.study.studyApprove(by, input); }
|
|
2399
|
+
async studyClose(by: PeerId, input: unknown): Promise<ResearchCampaignReceipt> { return this.study.studyClose(by, input); }
|
|
2400
|
+
async synthesisEvidence(by: PeerId, input: unknown) { return this.study.synthesisEvidence(by, input); }
|
|
2401
|
+
async synthesisCheck(by: PeerId, input: unknown): Promise<SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }> { return this.study.synthesisCheck(by, input); }
|
|
2402
|
+
private synthesisInspect(by: PeerId, input: unknown): Promise<SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }>;
|
|
2403
|
+
private synthesisInspect(by: PeerId, input: unknown, onSnapshot: (manifest: SynthesisManifestV1, current: SynthesisCurrent, report: SynthesisReadiness, valid: () => boolean) => Task): Promise<Task | SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }>;
|
|
2404
|
+
private async synthesisInspect(by: PeerId, input: unknown, onSnapshot?: (manifest: SynthesisManifestV1, current: SynthesisCurrent, report: SynthesisReadiness, valid: () => boolean) => Task): Promise<Task | SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }> { return onSnapshot ? this.study.synthesisInspect(by, input, onSnapshot) : this.study.synthesisInspect(by, input); }
|
|
2405
|
+
private surveyPrivate(task: Task, by?: PeerId): boolean { return this.survey.surveyPrivate(task, by); }
|
|
2406
|
+
async surveyStart(by: PeerId, input: unknown = {}, fence?: () => string | undefined): Promise<{ task: number; survey: number; ref: string; focus?: SurveyFocus }> { return this.survey.surveyStart(by, input, fence); }
|
|
2407
|
+
surveyShow(by: PeerId, id: unknown) { return this.survey.surveyShow(by, id); }
|
|
2408
|
+
async surveyReport(by: PeerId, input: unknown, fence?: () => string | undefined) { return this.survey.surveyReport(by, input, fence); }
|
|
2409
|
+
|
|
2410
|
+
|
|
2411
|
+
|
|
2290
2412
|
|
|
2291
|
-
async stopStudies(): Promise<void> {
|
|
2292
|
-
this.studyStopped = true;
|
|
2293
|
-
if (this.studiesRunning) await new Promise<void>(resolve => this.studyDrainWaiters.add(resolve));
|
|
2294
|
-
}
|
|
2295
2413
|
|
|
2296
|
-
private studyHold(): string | undefined {
|
|
2297
|
-
try {
|
|
2298
|
-
if (this.studyStopped || this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError)
|
|
2299
|
-
return "study writes are held by recovery, shutdown or storage failure";
|
|
2300
|
-
} catch { return "study write admission is unavailable"; }
|
|
2301
|
-
return undefined;
|
|
2302
|
-
}
|
|
2303
2414
|
|
|
2304
|
-
private async studyWrite<T>(write: () => Promise<T>): Promise<T> {
|
|
2305
|
-
this.studiesRunning++;
|
|
2306
|
-
try { return await write(); } finally {
|
|
2307
|
-
if (--this.studiesRunning === 0) { for (const resolve of this.studyDrainWaiters) resolve(); this.studyDrainWaiters.clear(); }
|
|
2308
|
-
}
|
|
2309
|
-
}
|
|
2310
2415
|
|
|
2311
|
-
private studyFields(input: unknown, allowed: readonly string[]): Record<string, unknown> {
|
|
2312
|
-
if (!input || typeof input !== "object" || Array.isArray(input) || types.isProxy(input)
|
|
2313
|
-
|| ![Object.prototype, null].includes(Object.getPrototypeOf(input)) || Object.getOwnPropertySymbols(input).length)
|
|
2314
|
-
throw new PreEffectToolRefusal("study request must be a plain data object");
|
|
2315
|
-
const fields = Object.getOwnPropertyDescriptors(input);
|
|
2316
|
-
if (Object.entries(fields).some(([key, descriptor]) => !allowed.includes(key) || !Object.hasOwn(descriptor, "value")))
|
|
2317
|
-
throw new PreEffectToolRefusal("study request has unknown fields or accessors");
|
|
2318
|
-
return Object.fromEntries(Object.entries(fields).map(([key, descriptor]) => [key, descriptor.value]));
|
|
2319
|
-
}
|
|
2320
2416
|
|
|
2321
|
-
private studyId(value: unknown): string {
|
|
2322
|
-
if (typeof value !== "string" || !/^rc-[a-f0-9]{12}$/.test(value)) throw new PreEffectToolRefusal("study id is invalid");
|
|
2323
|
-
return value;
|
|
2324
|
-
}
|
|
2325
2417
|
|
|
2326
|
-
private studyNumber(value: unknown, field: string): number {
|
|
2327
|
-
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) throw new PreEffectToolRefusal(`${field} must be a positive integer`);
|
|
2328
|
-
return value;
|
|
2329
|
-
}
|
|
2330
2418
|
|
|
2331
|
-
private studyContract(value: unknown): ResearchCampaignContract {
|
|
2332
|
-
try { return parseResearchCampaign(value); }
|
|
2333
|
-
catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid study contract"); }
|
|
2334
|
-
}
|
|
2335
2419
|
|
|
2336
|
-
private studyTime(): number {
|
|
2337
|
-
const now = this.d.studyNow?.() ?? Date.now();
|
|
2338
|
-
if (!Number.isFinite(now)) throw new PreEffectToolRefusal("study clock is unavailable");
|
|
2339
|
-
return now;
|
|
2340
|
-
}
|
|
2341
2420
|
|
|
2342
|
-
private studyRecord(id: string, revision?: number): ResearchCampaignRecord {
|
|
2343
|
-
let record: ResearchCampaignRecord | undefined;
|
|
2344
|
-
try { record = this.d.board.researchCampaign(id, revision); }
|
|
2345
|
-
catch { throw new PreEffectToolRefusal("study record is unavailable or invalid"); }
|
|
2346
|
-
if (!record || record.project !== this.d.project) throw new PreEffectToolRefusal("study is unavailable in this project");
|
|
2347
|
-
return record;
|
|
2348
|
-
}
|
|
2349
2421
|
|
|
2350
|
-
private studyParent(id: number): Task {
|
|
2351
|
-
const parent = this.need(id, false, true, true);
|
|
2352
|
-
if (this.places(parent).repositoryKey !== this.repositories.scope({}).key) throw new PreEffectToolRefusal("study parent is outside this project");
|
|
2353
|
-
return parent;
|
|
2354
|
-
}
|
|
2355
2422
|
|
|
2356
|
-
/** Write receipts expose no contract text; only person-only approval returns the unit mapping. */
|
|
2357
|
-
private studyReceipt(record: ResearchCampaignRecord, includeMapping = false): ResearchCampaignReceipt {
|
|
2358
|
-
const units = this.d.board.researchCampaignBindings(record.id, record.revision);
|
|
2359
|
-
return { id: record.id, parentTaskId: record.parentTaskId, revision: record.revision, status: record.status,
|
|
2360
|
-
unitCount: units.length, units: includeMapping ? units : [] };
|
|
2361
|
-
}
|
|
2362
2423
|
|
|
2363
|
-
private studySource(id: string): { id: string; sha256: string; private: boolean } | undefined {
|
|
2364
|
-
try {
|
|
2365
|
-
const source = this.d.studySource?.(id);
|
|
2366
|
-
return source && source.id === id && /^[a-f0-9]{64}$/.test(source.sha256) && typeof source.private === "boolean"
|
|
2367
|
-
? { id: source.id, sha256: source.sha256, private: source.private } : undefined;
|
|
2368
|
-
} catch { return undefined; }
|
|
2369
|
-
}
|
|
2370
2424
|
|
|
2371
|
-
private studyLatest(id: string, revision: number): ResearchCampaignRecord {
|
|
2372
|
-
const record = this.studyRecord(id);
|
|
2373
|
-
if (record.revision !== revision || record.status === "closed") throw new PreEffectToolRefusal("study revision is stale or closed");
|
|
2374
|
-
return record;
|
|
2375
|
-
}
|
|
2376
2425
|
|
|
2377
|
-
private studyFamily(parent: Task): Set<number> {
|
|
2378
|
-
if (!parent.history.some(entry => entry.event === "draft approved")) throw new PreEffectToolRefusal("adoption requires an approved intake family");
|
|
2379
|
-
const family = new Set<number>(), pending = [...(parent.deps ?? [])];
|
|
2380
|
-
// ponytail: 512 dependency nodes bound intake provenance walks; a larger family needs indexed family identities.
|
|
2381
|
-
while (pending.length) {
|
|
2382
|
-
const id = pending.pop()!;
|
|
2383
|
-
if (family.has(id)) continue;
|
|
2384
|
-
if (family.size >= 512) throw new PreEffectToolRefusal("study intake family exceeds its bounded scope");
|
|
2385
|
-
const task = this.d.board.get(id);
|
|
2386
|
-
if (!task) throw new PreEffectToolRefusal("study intake family is incomplete");
|
|
2387
|
-
family.add(id); pending.push(...(task.deps ?? []));
|
|
2388
|
-
}
|
|
2389
|
-
family.delete(parent.id);
|
|
2390
|
-
return family;
|
|
2391
|
-
}
|
|
2392
2426
|
|
|
2393
|
-
private studyReferences(parentId: number, contract: ResearchCampaignContract, campaignId?: string): StudyReferences {
|
|
2394
|
-
const parent = this.studyParent(parentId);
|
|
2395
|
-
const profile = parent.profile ?? "dev", storedProfile = profile === (this.d.profile ?? "dev") ? this.d.profileData ?? profile : profile;
|
|
2396
|
-
try {
|
|
2397
|
-
if (profileClass(parent.profileClass ?? parent.class, storedProfile) !== parent.class) throw new Error("changed class");
|
|
2398
|
-
} catch { throw new PreEffectToolRefusal("study parent profile class is unavailable or changed"); }
|
|
2399
|
-
const sources = contract.sourceIds.map(id => {
|
|
2400
|
-
const source = this.studySource(id);
|
|
2401
|
-
if (!source)
|
|
2402
|
-
throw new PreEffectToolRefusal("study source is unavailable in this project");
|
|
2403
|
-
return source;
|
|
2404
|
-
});
|
|
2405
|
-
if (contract.budget) {
|
|
2406
|
-
const budget = this.d.executionBudget?.status(contract.budget.id);
|
|
2407
|
-
if (!budget || Array.isArray(budget)) throw new PreEffectToolRefusal("study budget is unavailable");
|
|
2408
|
-
}
|
|
2409
|
-
const adopted = new Map<string, Task>();
|
|
2410
|
-
const family = contract.units.some(unit => unit.adoptTaskId !== undefined) ? this.studyFamily(parent) : new Set<number>();
|
|
2411
|
-
for (const unit of contract.units) if (unit.adoptTaskId !== undefined) {
|
|
2412
|
-
const task = this.studyParent(unit.adoptTaskId);
|
|
2413
|
-
if (!family.has(task.id) || task.draft || !task.history.some(entry => entry.event === "draft approved"))
|
|
2414
|
-
throw new PreEffectToolRefusal("study unit must adopt an approved intake child");
|
|
2415
|
-
const binding = this.d.board.researchTaskBinding(task.id);
|
|
2416
|
-
if (binding && (binding.campaignId !== campaignId || binding.unitId !== unit.id)) throw new PreEffectToolRefusal("intake child is already bound to another study unit");
|
|
2417
|
-
adopted.set(unit.id, task);
|
|
2418
|
-
}
|
|
2419
|
-
const reused = new Map<string, Task>();
|
|
2420
|
-
if (campaignId) for (const unit of contract.units) {
|
|
2421
|
-
const previous = this.d.board.researchLatestUnitBinding(campaignId, unit.id);
|
|
2422
|
-
if (previous) reused.set(unit.id, this.studyParent(previous.taskId));
|
|
2423
|
-
}
|
|
2424
|
-
const priv = this.isPii(parent) || sources.some(source => source.private) || [...adopted.values(), ...reused.values()].some(task => this.isPii(task))
|
|
2425
|
-
|| !this.nameable(JSON.stringify(contract));
|
|
2426
|
-
const flows = (rows: Map<string, Task>) => [...rows].map(([unit, task]) => [unit, task.id, task.history.length]);
|
|
2427
|
-
return { parent, adopted, reused, private: priv, key: JSON.stringify([parent.history.length, sources, flows(adopted), flows(reused), priv]) };
|
|
2428
|
-
}
|
|
2429
|
-
|
|
2430
|
-
/** Always re-read persisted approval and limits at the dispatch write, including after a metadata await. */
|
|
2431
|
-
private studyDispatchReason(task: Task, owner?: PeerId): string | undefined {
|
|
2432
|
-
try {
|
|
2433
|
-
const bound = this.d.board.researchDispatchBinding(task.id);
|
|
2434
|
-
if (!bound) return undefined;
|
|
2435
|
-
const { campaign, binding } = bound;
|
|
2436
|
-
if (campaign.project !== this.d.project || campaign.status !== "approved" || !binding) return "study revision is not approved or its unit was removed";
|
|
2437
|
-
const stop = campaign.contract.stopPolicy;
|
|
2438
|
-
if (Date.parse(stop.deadline) <= this.studyTime()) return "study deadline has expired";
|
|
2439
|
-
const units = this.d.board.researchCampaignBindings(campaign.id, campaign.revision);
|
|
2440
|
-
if (units.length > stop.maxUnits || binding.round > stop.maxFollowUpRounds) return "study stop limit exceeded";
|
|
2441
|
-
const budget = campaign.contract.budget;
|
|
2442
|
-
if (budget?.hardCap.length) {
|
|
2443
|
-
const ledger = this.d.executionBudget, current = ledger?.status(budget.id);
|
|
2444
|
-
if (!ledger || !current || Array.isArray(current) || !campaign.eligibleOwners?.length ||
|
|
2445
|
-
budget.hardCap.some(resource => resource === "tokens" || current.limits[resource] === undefined || resource === "model_calls" && current.limits.tokens !== undefined)) return "study hard-cap budget is unavailable";
|
|
2446
|
-
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";
|
|
2447
|
-
if (owner && (!campaign.eligibleOwners.includes(owner) || !ledger.covers(budget.id, task.id, owner, budget.hardCap)))
|
|
2448
|
-
return "study owner is not covered by its named hard-cap budget";
|
|
2449
|
-
}
|
|
2450
|
-
return undefined;
|
|
2451
|
-
} catch { return "study dispatch evidence is unavailable"; }
|
|
2452
|
-
}
|
|
2453
2427
|
|
|
2454
|
-
private studyDispatchCheck(task: Task, owner?: PeerId): void {
|
|
2455
|
-
const reason = this.studyDispatchReason(task, owner);
|
|
2456
|
-
if (reason) throw new PreEffectToolRefusal(reason);
|
|
2457
|
-
}
|
|
2458
2428
|
|
|
2459
|
-
private studyExcludedOwners(task: Task): PeerId[] {
|
|
2460
|
-
return Object.keys(this.states()).filter(peer => this.studyDispatchReason(task, peer) !== undefined);
|
|
2461
|
-
}
|
|
2462
2429
|
|
|
2463
|
-
private studyEligibleOwners(contract: ResearchCampaignContract): string[] | undefined {
|
|
2464
|
-
if (!contract.budget?.hardCap.length) return undefined;
|
|
2465
|
-
const ledger = this.d.executionBudget, budget = ledger?.status(contract.budget.id);
|
|
2466
|
-
if (!ledger || !budget || Array.isArray(budget) || contract.budget.hardCap.some(resource => resource === "tokens" || budget.limits[resource] === undefined || resource === "model_calls" && budget.limits.tokens !== undefined))
|
|
2467
|
-
throw new PreEffectToolRefusal("study hard-cap requires an enabled budget with supported resource limits");
|
|
2468
|
-
const eligible = budget.peers.filter(peer => ledger.instrumented(peer)).sort();
|
|
2469
|
-
if (!eligible.length) throw new PreEffectToolRefusal("study hard-cap has no instrumented eligible owner");
|
|
2470
|
-
return eligible;
|
|
2471
|
-
}
|
|
2472
2430
|
|
|
2473
|
-
private studyRoundCheck(original: ResearchCampaignRecord, contract: ResearchCampaignContract): void {
|
|
2474
|
-
const added = contract.units.filter(unit => unit.round > 0 && !original.contract.units.some(previous => previous.id === unit.id && previous.round === unit.round));
|
|
2475
|
-
if (!added.length) return;
|
|
2476
|
-
const stored = this.d.board.researchCampaignBindings(original.id, original.revision), handoffs = this.d.board.researchHandoffs(original.id, original.revision);
|
|
2477
|
-
for (const unit of added) {
|
|
2478
|
-
// 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.
|
|
2479
|
-
const previous = contract.units.filter(value => value.round === unit.round - 1 && value.purpose === "discovery");
|
|
2480
|
-
if (!previous.length || previous.some(value => {
|
|
2481
|
-
const binding = stored.find(bound => bound.unitId === value.id && bound.round === value.round && bound.purpose === "discovery");
|
|
2482
|
-
const handoff = binding && handoffs.find(handoff => handoff.handoff.unitId === value.id);
|
|
2483
|
-
return !handoff || !handoff.handoff.insufficientEvidence && value.sourceIds.some(source => !handoff.handoff.evidence.some(item => item.sourceId === source));
|
|
2484
|
-
})) throw new PreEffectToolRefusal("follow-up rounds require complete stored discovery handoffs or insufficientEvidence");
|
|
2485
|
-
}
|
|
2486
|
-
}
|
|
2487
2431
|
|
|
2488
|
-
async studyHandoff(by: PeerId, input: unknown): Promise<{ campaignId: string; unitId: string; seq: number }> {
|
|
2489
|
-
const requestCheck = this.requestCheck(by, () => this.studyHold());
|
|
2490
|
-
let handoff: ReturnType<typeof parseResearchHandoff>;
|
|
2491
|
-
try { handoff = parseResearchHandoff(input); } catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid study handoff"); }
|
|
2492
|
-
return this.studyWrite(async () => {
|
|
2493
|
-
const campaign = this.studyRecord(handoff.campaignId, handoff.revision), task = this.studyParent(handoff.taskId);
|
|
2494
|
-
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");
|
|
2495
|
-
const sources = campaign.contract.sourceIds.map(id => this.studySource(id));
|
|
2496
|
-
if (sources.some(source => !source)) throw new PreEffectToolRefusal("study handoff source is unavailable");
|
|
2497
|
-
const sourceKey = JSON.stringify(sources);
|
|
2498
|
-
const text = JSON.stringify(handoff);
|
|
2499
|
-
const withheld = !this.nameable(text) || looksSecret(text) || await this.withholds("note", text, task);
|
|
2500
|
-
requestCheck();
|
|
2501
|
-
const current = this.studyParent(task.id);
|
|
2502
|
-
if (current.history.length !== task.history.length || current.owner !== by || current.state !== "in_progress") throw new PreEffectToolRefusal("study handoff task changed during screening");
|
|
2503
|
-
if (JSON.stringify(campaign.contract.sourceIds.map(id => this.studySource(id))) !== sourceKey) throw new PreEffectToolRefusal("study handoff sources changed during screening");
|
|
2504
|
-
if ((withheld || this.studyReplayPrivacy(campaign, this.studyParent(campaign.parentTaskId))) && !this.isPii(current)) throw new PreEffectToolRefusal("study handoff privacy requires private task authority");
|
|
2505
|
-
requestCheck();
|
|
2506
|
-
try {
|
|
2507
|
-
const saved = this.d.board.recordResearchHandoff(handoff, this.d.project, by, this.studyTime(), current.history.length);
|
|
2508
|
-
return { campaignId: saved.handoff.campaignId, unitId: saved.handoff.unitId, seq: saved.seq };
|
|
2509
|
-
} catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study handoff was not saved"); }
|
|
2510
|
-
});
|
|
2511
|
-
}
|
|
2512
2432
|
|
|
2513
|
-
/**
|
|
2514
|
-
* #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
|
|
2515
|
-
* 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.
|
|
2516
|
-
*/
|
|
2517
|
-
studyList(by: PeerId, input: unknown): { campaigns: ResearchCampaignReceipt[]; next?: string } {
|
|
2518
|
-
requireLocalTaskPeer(by);
|
|
2519
|
-
const fields = this.studyFields(input, ["after"]);
|
|
2520
|
-
const after = fields.after === undefined ? undefined : this.studyId(fields.after);
|
|
2521
|
-
const page = this.d.board.researchCampaignPage(this.d.project, after, 50);
|
|
2522
|
-
return { campaigns: page.ids.map(id => this.studyReceipt(this.studyRecord(id))), ...(page.next ? { next: page.next } : {}) };
|
|
2523
|
-
}
|
|
2524
2433
|
|
|
2525
|
-
studyShow(by: PeerId, input: unknown): ReturnType<typeof studyProjection> {
|
|
2526
|
-
requireLocalTaskPeer(by);
|
|
2527
|
-
const fields = this.studyFields(input, ["id"]), campaign = this.studyRecord(this.studyId(fields.id));
|
|
2528
|
-
const bindings = this.d.board.researchCampaignBindings(campaign.id, campaign.revision);
|
|
2529
|
-
const tasks = bindings.map(unit => this.d.board.get(unit.taskId)).filter((task): task is Task => !!task);
|
|
2530
|
-
const ledger = this.d.executionBudget, configured = campaign.contract.budget, budget = configured && ledger?.status(configured.id);
|
|
2531
|
-
const instrumentedPeers = tasks.flatMap(task => task.owner && ledger?.instrumented(task.owner) ? [task.owner] : []);
|
|
2532
|
-
const projection = studyProjection({ campaign, bindings, tasks, handoffs: this.d.board.researchHandoffs(campaign.id), now: this.studyTime(), instrumentedPeers,
|
|
2533
|
-
...(budget && !Array.isArray(budget) ? { budget: { ...budget, coveredTaskIds: tasks.filter(task => task.owner && ledger?.covers(budget.id, task.id, task.owner, [])).map(task => task.id) } } : {}) });
|
|
2534
|
-
projection.reasons = [...new Set([...projection.reasons, ...tasks.flatMap(task => { const reason = this.studyDispatchReason(task, task.owner ?? undefined); return reason ? [reason] : []; })])];
|
|
2535
|
-
projection.held = projection.reasons.length > 0;
|
|
2536
|
-
if (this.studyReplayPrivacy(campaign, this.studyParent(campaign.parentTaskId))) {
|
|
2537
|
-
// IDs, counts, states and resource names only. Source references are private view data too.
|
|
2538
|
-
for (const unit of projection.units) { unit.sourceIds = []; unit.duplicateSourceIds = []; unit.handoff.coveredSourceIds = []; }
|
|
2539
|
-
}
|
|
2540
|
-
return projection;
|
|
2541
|
-
}
|
|
2542
|
-
|
|
2543
|
-
private studyReplayPrivacy(record: ResearchCampaignRecord, parent: Task): boolean {
|
|
2544
|
-
return record.private || this.isPii(parent) || record.contract.sourceIds.some(id => {
|
|
2545
|
-
const source = this.studySource(id);
|
|
2546
|
-
return !source || source.private;
|
|
2547
|
-
}) || this.d.board.researchCampaignBindings(record.id, record.revision).some(unit => {
|
|
2548
|
-
const task = this.d.board.get(unit.taskId); return !task || this.isPii(task);
|
|
2549
|
-
});
|
|
2550
|
-
}
|
|
2551
2434
|
|
|
2552
2435
|
/**
|
|
2553
2436
|
* #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
|
|
@@ -2719,462 +2602,15 @@ export class Tasks {
|
|
|
2719
2602
|
|
|
2720
2603
|
/** ORIGIN side, readback: what this project handed over, with the last state each target reported. */
|
|
2721
2604
|
handoffList(): HandoffOutboundRow[] { return this.d.board.handoffOutbound(); }
|
|
2605
|
+
experimentApproveProtocol(...args: Parameters<ExperimentDomain["experimentApproveProtocol"]>): ReturnType<ExperimentDomain["experimentApproveProtocol"]> { return this.experiment.experimentApproveProtocol(...args); }
|
|
2722
2606
|
|
|
2723
|
-
async studyDraft(by: PeerId, input: unknown): Promise<ResearchCampaignReceipt> {
|
|
2724
|
-
const requestCheck = this.requestCheck(by, () => this.studyHold()); this.plannerWriteAuthority(by);
|
|
2725
|
-
const fields = this.studyFields(input, ["parentTaskId", "contract"]), parentId = this.studyNumber(fields.parentTaskId, "parentTaskId");
|
|
2726
|
-
const contract = this.studyContract(fields.contract);
|
|
2727
|
-
if (contract.units.some(unit => unit.round !== 0)) throw new PreEffectToolRefusal("an initial study contains only round zero");
|
|
2728
|
-
return this.studyWrite(async () => {
|
|
2729
|
-
this.plannerWriteAuthority(by, this.studyParent(parentId));
|
|
2730
|
-
const before = this.studyReferences(parentId, contract);
|
|
2731
|
-
const withheld = await this.withholds("note", JSON.stringify(contract), before.parent);
|
|
2732
|
-
requestCheck();
|
|
2733
|
-
const current = this.studyReferences(parentId, contract); this.plannerWriteAuthority(by, current.parent);
|
|
2734
|
-
if (current.key !== before.key) throw new PreEffectToolRefusal("study references changed during draft screening");
|
|
2735
|
-
const record: ResearchCampaignRecord = { id: `rc-${randomBytes(6).toString("hex")}`, project: this.d.project, parentTaskId: parentId,
|
|
2736
|
-
revision: 1, status: "draft", contract, hash: campaignHash(contract), private: current.private || withheld, createdBy: by, createdAt: this.studyTime() };
|
|
2737
|
-
let saved: ResearchCampaignRecord;
|
|
2738
|
-
requestCheck(); this.plannerWriteAuthority(by, current.parent);
|
|
2739
|
-
try { saved = this.d.board.saveResearchCampaignDraft(record, undefined, current.parent.history.length); }
|
|
2740
|
-
catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study draft was not saved"); }
|
|
2741
|
-
this.releaseNotice(`study ${saved.id} revision ${saved.revision} drafted`);
|
|
2742
|
-
return this.studyReceipt(saved);
|
|
2743
|
-
});
|
|
2744
|
-
}
|
|
2745
|
-
|
|
2746
|
-
async studyRevise(by: PeerId, input: unknown): Promise<ResearchCampaignReceipt> {
|
|
2747
|
-
const requestCheck = this.requestCheck(by, () => this.studyHold()); this.plannerWriteAuthority(by);
|
|
2748
|
-
const fields = this.studyFields(input, ["id", "revision", "contract"]), id = this.studyId(fields.id), revision = this.studyNumber(fields.revision, "revision");
|
|
2749
|
-
const contract = this.studyContract(fields.contract);
|
|
2750
|
-
return this.studyWrite(async () => {
|
|
2751
|
-
const original = this.studyLatest(id, revision);
|
|
2752
|
-
this.plannerWriteAuthority(by, this.studyParent(original.parentTaskId));
|
|
2753
|
-
const before = this.studyReferences(original.parentTaskId, contract, id);
|
|
2754
|
-
this.studyRoundCheck(original, contract);
|
|
2755
|
-
const withheld = await this.withholds("note", JSON.stringify(contract), before.parent);
|
|
2756
|
-
requestCheck();
|
|
2757
|
-
const latest = this.studyLatest(id, revision), current = this.studyReferences(latest.parentTaskId, contract, id);
|
|
2758
|
-
this.plannerWriteAuthority(by, current.parent);
|
|
2759
|
-
if (latest.hash !== original.hash || current.key !== before.key) throw new PreEffectToolRefusal("study changed during revision screening");
|
|
2760
|
-
this.studyRoundCheck(latest, contract);
|
|
2761
|
-
const next: ResearchCampaignRecord = { id, project: this.d.project, parentTaskId: latest.parentTaskId, revision: revision + 1, status: "draft",
|
|
2762
|
-
contract, hash: campaignHash(contract), private: latest.private || current.private || withheld, createdBy: by, createdAt: this.studyTime() };
|
|
2763
|
-
let saved: ResearchCampaignRecord;
|
|
2764
|
-
requestCheck(); this.plannerWriteAuthority(by, current.parent);
|
|
2765
|
-
try { saved = this.d.board.saveResearchCampaignDraft(next, revision, current.parent.history.length); }
|
|
2766
|
-
catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study revision was not saved"); }
|
|
2767
|
-
this.releaseNotice(`study ${id} revision ${saved.revision} drafted`);
|
|
2768
|
-
return this.studyReceipt(saved);
|
|
2769
|
-
});
|
|
2770
|
-
}
|
|
2771
|
-
|
|
2772
|
-
async studyApprove(by: PeerId, input: unknown): Promise<ResearchCampaignReceipt> {
|
|
2773
|
-
const requestCheck = this.requestCheck(by, () => this.studyHold());
|
|
2774
|
-
if (by !== USER) throw new PreEffectToolRefusal("study approval requires the person");
|
|
2775
|
-
const fields = this.studyFields(input, ["id", "revision"]), id = this.studyId(fields.id), revision = this.studyNumber(fields.revision, "revision");
|
|
2776
|
-
return this.studyWrite(async () => {
|
|
2777
|
-
const original = this.studyRecord(id, revision), parent = this.studyParent(original.parentTaskId);
|
|
2778
|
-
if (original.status === "approved") {
|
|
2779
|
-
const privacy = this.studyReplayPrivacy(original, parent); requestCheck();
|
|
2780
|
-
const replay = this.d.board.activateCampaign(id, revision, this.d.project, by, this.studyTime(), [], parent.history.length, privacy);
|
|
2781
|
-
return this.studyReceipt(replay.campaign, true);
|
|
2782
|
-
}
|
|
2783
|
-
this.studyLatest(id, revision);
|
|
2784
|
-
if (original.status !== "draft" || parent.draft) throw new PreEffectToolRefusal("study approval requires a draft and an approved parent input");
|
|
2785
|
-
this.studyEligibleOwners(original.contract);
|
|
2786
|
-
const before = this.studyReferences(parent.id, original.contract, id);
|
|
2787
|
-
let priv = original.private || before.private || await this.withholds("note", JSON.stringify(original.contract), parent);
|
|
2788
|
-
const prepared: PreparedResearchUnit[] = [];
|
|
2789
|
-
for (const unit of original.contract.units) {
|
|
2790
|
-
requestCheck();
|
|
2791
|
-
const reused = before.reused.get(unit.id);
|
|
2792
|
-
if (reused) { prepared.push({ unitId: unit.id, reuse: { taskId: reused.id, flowRevision: reused.history.length } }); continue; }
|
|
2793
|
-
const adopted = before.adopted.get(unit.id);
|
|
2794
|
-
if (adopted) { prepared.push({ unitId: unit.id, adopt: { taskId: adopted.id, flowRevision: adopted.history.length } }); continue; }
|
|
2795
|
-
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(", ")}`;
|
|
2796
|
-
priv ||= await this.withholds("task", detail, parent);
|
|
2797
|
-
const refs = cleanRefs(parent.refs), signals = [...new Set([...this.signalsFor({ title, detail, refs }), ...parent.signals.filter(signal => ["pii", "pii_path", "urgent"].includes(signal))])];
|
|
2798
|
-
prepared.push({ unitId: unit.id, create: { title, detail, class: parent.class, refs, signals,
|
|
2799
|
-
...(parent.profile ? { profile: parent.profile } : {}), ...(parent.profileClass ? { profileClass: parent.profileClass } : {}),
|
|
2800
|
-
} });
|
|
2801
|
-
}
|
|
2802
|
-
requestCheck();
|
|
2803
|
-
const latest = this.studyLatest(id, revision), current = this.studyReferences(parent.id, original.contract, id);
|
|
2804
|
-
if (latest.hash !== original.hash || current.key !== before.key) throw new PreEffectToolRefusal("study changed during approval screening");
|
|
2805
|
-
const now = this.studyTime(), deadline = Date.parse(original.contract.stopPolicy.deadline);
|
|
2806
|
-
if (deadline <= now || deadline - now > 90 * 86_400_000) throw new PreEffectToolRefusal("study deadline must be in the next ninety days at approval");
|
|
2807
|
-
priv ||= latest.private || current.private;
|
|
2808
|
-
const instruction = instructedExecution.getStore();
|
|
2809
|
-
if (instruction?.active) {
|
|
2810
|
-
instruction.current();
|
|
2811
|
-
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");
|
|
2812
|
-
}
|
|
2813
|
-
if (priv && [...current.adopted.values(), ...current.reused.values()].some(task => !this.isPii(task)))
|
|
2814
|
-
throw new PreEffectToolRefusal("a private study cannot retain a public task without changing its authority");
|
|
2815
|
-
for (const unit of prepared) if (unit.create) {
|
|
2816
|
-
if (priv && !unit.create.signals?.includes("pii")) unit.create.signals = [...(unit.create.signals ?? []), "pii"];
|
|
2817
|
-
const planner = this.proposalPlanner({ ...parent, ...unit.create, signals: unit.create.signals ?? [], refs: unit.create.refs ?? {}, draft: undefined, state: "backlog", owner: null, reviewer: null });
|
|
2818
|
-
unit.create.planner = planner.planner; unit.create.plannerReason = planner.plannerReason;
|
|
2819
|
-
this.warmRepository({ refs: unit.create.refs ?? {}, plan: unit.create.plan });
|
|
2820
|
-
}
|
|
2821
|
-
const mode = this.d.coordination?.();
|
|
2822
|
-
let result: ReturnType<Board["activateCampaign"]>;
|
|
2823
|
-
requestCheck();
|
|
2824
|
-
instruction?.beginStudy?.(); // The synchronous board transaction now owns the screened binding.
|
|
2825
|
-
try { result = this.d.board.activateCampaign(id, revision, this.d.project, by, now, prepared, current.parent.history.length, priv, { eligibleOwners: this.studyEligibleOwners(original.contract) }); }
|
|
2826
|
-
catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study approval was not saved"); }
|
|
2827
|
-
for (const child of result.children) {
|
|
2828
|
-
this.incomingBacklog.add(child.id);
|
|
2829
|
-
if (mode !== undefined) this.coordinationModes.set(child.id, mode);
|
|
2830
|
-
}
|
|
2831
|
-
this.releaseNotice(`study ${id} revision ${revision} approved; ${result.bindings.length} units`);
|
|
2832
|
-
await this.studyReoffer(result.bindings.map(unit => unit.taskId));
|
|
2833
|
-
return this.studyReceipt(result.campaign, true);
|
|
2834
|
-
});
|
|
2835
|
-
}
|
|
2836
|
-
|
|
2837
|
-
/**
|
|
2838
|
-
* 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
|
|
2839
|
-
* 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
|
|
2840
|
-
* refusal here is a notice, never a failure of the approval.
|
|
2841
|
-
*/
|
|
2842
|
-
private async studyReoffer(taskIds: readonly number[]): Promise<void> {
|
|
2843
|
-
for (const taskId of taskIds) {
|
|
2844
|
-
let owner: PeerId | undefined;
|
|
2845
|
-
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; }
|
|
2846
|
-
if (owner === undefined) continue;
|
|
2847
|
-
const task = this.d.board.get(taskId);
|
|
2848
|
-
// The record names an owner that no longer holds the unproposed task: it is stale, not a pending offer.
|
|
2849
|
-
if (!task || task.owner !== owner || task.state !== "proposed") { this.d.board.clearResearchDroppedOffer(taskId); continue; }
|
|
2850
|
-
try {
|
|
2851
|
-
await this.sendTask(task, { owner, ...(task.reviewer ? { reviewer: task.reviewer } : {}), trace: [] });
|
|
2852
|
-
this.d.board.clearResearchDroppedOffer(taskId); // after the offer is published: a refusal keeps the record for the next approval
|
|
2853
|
-
} catch (e) { this.releaseNotice(`task ${this.publicTitle(task)}: could not re-offer after the study was approved: ${e instanceof Error ? e.message : String(e)}`); }
|
|
2854
|
-
}
|
|
2855
|
-
}
|
|
2856
|
-
|
|
2857
|
-
async studyClose(by: PeerId, input: unknown): Promise<ResearchCampaignReceipt> {
|
|
2858
|
-
const requestCheck = this.requestCheck(by, () => this.studyHold()); this.plannerWriteAuthority(by);
|
|
2859
|
-
const fields = this.studyFields(input, ["id", "revision", "reason"]), id = this.studyId(fields.id), revision = this.studyNumber(fields.revision, "revision");
|
|
2860
|
-
if (typeof fields.reason !== "string" || !fields.reason.trim() || Buffer.byteLength(fields.reason, "utf8") > 512) throw new PreEffectToolRefusal("study close needs a bounded reason");
|
|
2861
|
-
const reason = fields.reason;
|
|
2862
|
-
return this.studyWrite(async () => {
|
|
2863
|
-
const original = this.studyLatest(id, revision), parent = this.studyParent(original.parentTaskId);
|
|
2864
|
-
this.plannerWriteAuthority(by, parent);
|
|
2865
|
-
const withheld = await this.withholds("note", reason, parent);
|
|
2866
|
-
requestCheck();
|
|
2867
|
-
const latest = this.studyLatest(id, revision), currentParent = this.studyParent(latest.parentTaskId);
|
|
2868
|
-
this.plannerWriteAuthority(by, currentParent);
|
|
2869
|
-
if (latest.hash !== original.hash || currentParent.history.length !== parent.history.length) throw new PreEffectToolRefusal("study changed during close screening");
|
|
2870
|
-
const priv = this.studyReplayPrivacy(latest, currentParent) || withheld || !this.nameable(reason);
|
|
2871
|
-
let closed: ResearchCampaignRecord;
|
|
2872
|
-
requestCheck(); this.plannerWriteAuthority(by, currentParent);
|
|
2873
|
-
try { closed = this.d.board.closeCampaign(id, revision, this.d.project, by, this.studyTime(), reason, currentParent.history.length, priv); }
|
|
2874
|
-
catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study close was not saved"); }
|
|
2875
|
-
this.releaseNotice(`study ${id} revision ${revision} closed`);
|
|
2876
|
-
return this.studyReceipt(closed);
|
|
2877
|
-
});
|
|
2878
|
-
}
|
|
2879
|
-
|
|
2880
|
-
private experimentHash(input: unknown): string { return createHash("sha256").update(canonicalJson(input)).digest("hex"); }
|
|
2881
|
-
|
|
2882
|
-
private experimentId(input: unknown): string {
|
|
2883
|
-
if (typeof input !== "string" || !/^ra-[a-f0-9]{12}$/.test(input)) throw new PreEffectToolRefusal("experiment identity is invalid");
|
|
2884
|
-
return input;
|
|
2885
|
-
}
|
|
2886
|
-
|
|
2887
|
-
private experimentProtocol(hash: string): ExperimentProtocolRecord {
|
|
2888
|
-
try {
|
|
2889
|
-
const record = this.d.board.experimentProtocol(hash);
|
|
2890
|
-
if (record?.project === this.d.project) return record;
|
|
2891
|
-
} catch { /* damaged records are never returned as evidence */ }
|
|
2892
|
-
throw new PreEffectToolRefusal("experiment protocol is unavailable in this project");
|
|
2893
|
-
}
|
|
2894
|
-
|
|
2895
|
-
private experimentAttempt(id: string): ExperimentAttemptRecord {
|
|
2896
|
-
try {
|
|
2897
|
-
const record = this.d.board.experimentAttempt(id);
|
|
2898
|
-
if (record?.project === this.d.project) return record;
|
|
2899
|
-
} catch { /* fail closed without including any stored body */ }
|
|
2900
|
-
throw new PreEffectToolRefusal("experiment attempt is unavailable in this project");
|
|
2901
|
-
}
|
|
2902
|
-
|
|
2903
|
-
private experimentContext(by: PeerId, taskId: number, protocol: ExperimentProtocolContract, recordedForTaskId = taskId): ExperimentContext {
|
|
2904
|
-
const task = this.studyParent(taskId), bound = this.d.board.researchDispatchBinding(taskId);
|
|
2905
|
-
if (task.owner !== by || task.state !== "in_progress") throw new PreEffectToolRefusal("experiment records require the current in-progress task owner");
|
|
2906
|
-
if (this.d.privateTurn?.(by) && !this.isPii(task)) throw new PreEffectToolRefusal("a private turn cannot write experiment records on a public task");
|
|
2907
|
-
const campaign = bound?.campaign;
|
|
2908
|
-
// ponytail: new attempts against an older revision's protocol are refused; upgrade: explicit membership+source fence.
|
|
2909
|
-
if (!bound?.binding || !campaign || campaign.project !== this.d.project || campaign.id !== protocol.campaignId || campaign.revision !== protocol.campaignRevision || campaign.status !== "approved")
|
|
2910
|
-
throw new PreEffectToolRefusal("experiment task must be a unit of the protocol's current approved campaign revision");
|
|
2911
|
-
const recording = this.d.board.researchDispatchBinding(recordedForTaskId), origin = this.studyParent(recordedForTaskId);
|
|
2912
|
-
if (!recording?.binding || recording.campaign.id !== campaign.id || recording.campaign.revision !== campaign.revision || recording.campaign.status !== "approved")
|
|
2913
|
-
throw new PreEffectToolRefusal("experiment recording task is no longer a unit of this campaign");
|
|
2914
|
-
const sources = protocol.inputs.map(input => {
|
|
2915
|
-
const source = this.studySource(input.sourceId);
|
|
2916
|
-
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");
|
|
2917
|
-
return source;
|
|
2918
|
-
});
|
|
2919
|
-
let artifactPrivate = false;
|
|
2920
|
-
if ("deliverable" in protocol.code) {
|
|
2921
|
-
const reference = protocol.code.deliverable, artifact = latestDeliverables(origin.history)?.find(value => value.id === reference.id && value.sha256 === reference.sha256);
|
|
2922
|
-
if (!artifact) throw new PreEffectToolRefusal("experiment code deliverable identity is not recorded for its task");
|
|
2923
|
-
artifactPrivate = artifact.private === true;
|
|
2924
|
-
}
|
|
2925
|
-
const privateRecord = this.studyReplayPrivacy(campaign, this.studyParent(campaign.parentTaskId)) || this.isPii(task) || this.isPii(origin) || artifactPrivate || sources.some(source => source.private);
|
|
2926
|
-
const fence: ExperimentWriteFence = { project: this.d.project, taskId, taskFlowRevision: task.history.length, owner: by,
|
|
2927
|
-
campaignId: campaign.id, campaignRevision: campaign.revision, campaignHash: campaign.hash };
|
|
2928
|
-
return { task, campaign, private: privateRecord, fence, key: JSON.stringify([fence, sources, privateRecord, origin.history.length, recording.binding]) };
|
|
2929
|
-
}
|
|
2930
|
-
|
|
2931
|
-
private experimentFresh(before: ExperimentContext, by: PeerId, protocol: ExperimentProtocolContract, recordedForTaskId?: number): ExperimentContext {
|
|
2932
|
-
const current = this.experimentContext(by, before.task.id, protocol, recordedForTaskId);
|
|
2933
|
-
if (current.key !== before.key) throw new PreEffectToolRefusal("experiment authority, source or campaign changed during admission");
|
|
2934
|
-
return current;
|
|
2935
|
-
}
|
|
2936
|
-
|
|
2937
|
-
private async experimentScreen(text: string, task: Task): Promise<void> {
|
|
2938
|
-
if (!this.isPii(task) && (!this.nameable(text) || looksSecret(text) || await this.withholds("note", text, task)))
|
|
2939
|
-
throw new PreEffectToolRefusal("experiment text was not cleared; nothing was recorded");
|
|
2940
|
-
}
|
|
2941
|
-
|
|
2942
|
-
private experimentPlanContext(by: PeerId, taskId: number, plan: ComparisonPlanV1): ExperimentContext {
|
|
2943
|
-
const task = this.studyParent(taskId), bound = this.d.board.researchDispatchBinding(taskId), campaign = bound?.campaign;
|
|
2944
|
-
if (task.owner !== by || task.state !== "in_progress" || !bound?.binding || !campaign || campaign.project !== this.d.project
|
|
2945
|
-
|| campaign.id !== plan.campaignId || campaign.status !== "approved")
|
|
2946
|
-
throw new PreEffectToolRefusal("comparison plans require the current in-progress campaign unit owner");
|
|
2947
|
-
if (this.d.privateTurn?.(by) && !this.isPii(task)) throw new PreEffectToolRefusal("a private turn cannot write comparison plans on a public task");
|
|
2948
|
-
const sources = plan.fixed.inputs.map(input => {
|
|
2949
|
-
const source = this.studySource(input.sourceId);
|
|
2950
|
-
if (!campaign.contract.sourceIds.includes(input.sourceId) || !source || source.sha256 !== input.sha256)
|
|
2951
|
-
throw new PreEffectToolRefusal("comparison input source identity or hash is unavailable in this campaign");
|
|
2952
|
-
return source;
|
|
2953
|
-
});
|
|
2954
|
-
const privateRecord = this.studyReplayPrivacy(campaign, this.studyParent(campaign.parentTaskId)) || this.isPii(task) || sources.some(source => source.private);
|
|
2955
|
-
const fence: ExperimentWriteFence = { project: this.d.project, taskId, taskFlowRevision: task.history.length, owner: by,
|
|
2956
|
-
campaignId: campaign.id, campaignRevision: campaign.revision, campaignHash: campaign.hash };
|
|
2957
|
-
return { task, campaign, private: privateRecord, fence, key: canonicalJson([fence, privateRecord, sources, bound.binding]) };
|
|
2958
|
-
}
|
|
2959
|
-
|
|
2960
|
-
private experimentApproved(record: ExperimentProtocolRecord): boolean {
|
|
2961
|
-
const approval = this.d.board.experimentProtocolApproval(record.hash);
|
|
2962
|
-
return protocolApprovalBindingMatches(record.protocol, approval && { protocolHash: approval.protocolHash, evaluatorHash: approval.evaluatorHash });
|
|
2963
|
-
}
|
|
2964
|
-
|
|
2965
|
-
/** Approval is an explicit person's decision about immutable bytes, including historical protocols. */
|
|
2966
|
-
async experimentApproveProtocol(by: PeerId, input: unknown): Promise<ProtocolApprovalReceipt> {
|
|
2967
|
-
const requestCheck = this.requestCheck(by, () => this.studyHold());
|
|
2968
|
-
if (by !== USER) throw new PreEffectToolRefusal("protocol approval is person only");
|
|
2969
|
-
const fields = this.studyFields(input, ["hash"]);
|
|
2970
|
-
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");
|
|
2971
|
-
const hash = fields.hash;
|
|
2972
|
-
return this.studyWrite(async () => {
|
|
2973
|
-
requestCheck();
|
|
2974
|
-
const record = this.experimentProtocol(hash), evaluatorHash = evaluatorIdentityHash(record.protocol);
|
|
2975
|
-
requestCheck();
|
|
2976
|
-
let saved;
|
|
2977
|
-
try { saved = this.d.board.approveExperimentProtocol(this.d.project, hash, evaluatorHash, by, this.studyTime()); }
|
|
2978
|
-
catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "protocol approval was not saved"); }
|
|
2979
|
-
return { protocolHash: saved.protocolHash, evaluatorHash: saved.evaluatorHash, approvedBy: saved.approvedBy, approvedAt: saved.at };
|
|
2980
|
-
});
|
|
2981
|
-
}
|
|
2982
|
-
|
|
2983
|
-
/** Record evidence only: this path never runs a check, a shell command or a runner. */
|
|
2984
2607
|
async experimentRecord(by: PeerId, input: { kind: "plan"; [key: string]: unknown }): Promise<ComparisonPlanReceipt>;
|
|
2985
2608
|
async experimentRecord(by: PeerId, input: { kind: "protocol" | "attempt" | "event" | "receipt"; [key: string]: unknown }): Promise<ExperimentReceipt>;
|
|
2986
2609
|
async experimentRecord(by: PeerId, input: unknown): Promise<ExperimentReceipt | ComparisonPlanReceipt>;
|
|
2987
|
-
async experimentRecord(by: PeerId, input: unknown): Promise<ExperimentReceipt | ComparisonPlanReceipt> {
|
|
2988
|
-
const requestCheck = this.requestCheck(by, () => this.studyHold());
|
|
2989
|
-
const envelope = this.studyFields(input, ["kind", "taskId", "protocol", "attempt", "attemptId", "idempotencyKey", "event", "plan", "receipt", "signature"]);
|
|
2990
|
-
return this.studyWrite(async () => {
|
|
2991
|
-
try {
|
|
2992
|
-
if (envelope.kind === "receipt") {
|
|
2993
|
-
const fields = this.studyFields(input, ["kind", "receipt", "signature"]), receipt = parseAttemptReceipt(fields.receipt);
|
|
2994
|
-
const attempt = this.experimentAttempt(receipt.attemptId), record = this.experimentProtocol(attempt.attempt.protocolHash);
|
|
2995
|
-
const relayOwner = by === USER ? this.studyParent(attempt.attempt.taskId).owner : by;
|
|
2996
|
-
if (!relayOwner) throw new PreEffectToolRefusal("receipt relay requires a current task owner");
|
|
2997
|
-
const before = this.experimentContext(relayOwner, attempt.attempt.taskId, record.protocol, record.recordedForTaskId);
|
|
2998
|
-
requestCheck();
|
|
2999
|
-
const proof = (stored: NonNullable<ReturnType<Board["runnerReceipt"]>>): ExperimentReceipt => ({ kind: "receipt", protocolHash: record.hash,
|
|
3000
|
-
attemptId: attempt.attemptId, seq: stored.seq, receiptId: receipt.receiptId });
|
|
3001
|
-
const known = this.d.board.runnerReceipt(receipt.receiptId);
|
|
3002
|
-
if (known) {
|
|
3003
|
-
if (canonicalJson(known.receipt) !== canonicalJson(receipt) || known.signature !== fields.signature)
|
|
3004
|
-
throw new PreEffectToolRefusal("receiptId already records different signed bytes");
|
|
3005
|
-
this.experimentFresh(before, relayOwner, record.protocol, record.recordedForTaskId); requestCheck();
|
|
3006
|
-
return proof(known); // immutable stored proof: do not re-verify against a revoked/replaced registration or write on replay
|
|
3007
|
-
}
|
|
3008
|
-
const registrations = parseResearchRunners(this.d.researchRunners?.() ?? {}), registrationKey = canonicalJson(registrations);
|
|
3009
|
-
const context = { projectId: this.d.project, attempt: { id: attempt.attemptId, projectId: attempt.project, protocolHash: attempt.attempt.protocolHash,
|
|
3010
|
-
...("commit" in record.protocol.code ? { codeCommit: record.protocol.code.commit } : {}) } };
|
|
3011
|
-
verifyAttemptReceipt(receipt, fields.signature, { ...context, runners: registrations });
|
|
3012
|
-
const lastSeq = this.d.board.experimentLastSeq(attempt.attemptId);
|
|
3013
|
-
await this.experimentScreen(canonicalJson(receipt), before.task); requestCheck();
|
|
3014
|
-
const current = this.experimentFresh(before, relayOwner, record.protocol, record.recordedForTaskId);
|
|
3015
|
-
const latest = parseResearchRunners(this.d.researchRunners?.() ?? {});
|
|
3016
|
-
if (canonicalJson(latest) !== registrationKey) throw new PreEffectToolRefusal("runner registration changed during receipt admission");
|
|
3017
|
-
verifyAttemptReceipt(receipt, fields.signature, { ...context, runners: latest }); requestCheck();
|
|
3018
|
-
const saved = this.d.board.appendRunnerReceipt({ receipt, signature: fields.signature as string, publicKey: latest[receipt.runner]!.publicKey,
|
|
3019
|
-
by, at: this.studyTime(), private: current.private || record.private || attempt.private }, lastSeq, current.fence);
|
|
3020
|
-
return proof(saved);
|
|
3021
|
-
}
|
|
3022
|
-
if (envelope.kind === "plan") {
|
|
3023
|
-
const fields = this.studyFields(input, ["kind", "taskId", "plan"]), taskId = this.studyNumber(fields.taskId, "taskId"), plan = parseComparisonPlan(fields.plan);
|
|
3024
|
-
const before = this.experimentPlanContext(by, taskId, plan);
|
|
3025
|
-
await this.experimentScreen(canonicalJson(plan), before.task); requestCheck();
|
|
3026
|
-
const current = this.experimentPlanContext(by, taskId, plan);
|
|
3027
|
-
if (current.key !== before.key) throw new PreEffectToolRefusal("comparison authority, source or campaign changed during admission");
|
|
3028
|
-
requestCheck();
|
|
3029
|
-
const saved = this.d.board.saveExperimentComparisonPlan({ hash: comparisonPlanHash(plan), project: this.d.project, recordedForTaskId: taskId,
|
|
3030
|
-
plan, by, at: this.studyTime(), private: current.private }, current.fence);
|
|
3031
|
-
return { kind: "plan", planHash: saved.hash };
|
|
3032
|
-
}
|
|
3033
|
-
if (envelope.kind === "protocol") {
|
|
3034
|
-
const fields = this.studyFields(input, ["kind", "taskId", "protocol"]), taskId = this.studyNumber(fields.taskId, "taskId"), protocol = parseExperimentProtocol(fields.protocol);
|
|
3035
|
-
const before = this.experimentContext(by, taskId, protocol);
|
|
3036
|
-
for (const reference of [protocol.variantOf, protocol.supersedes]) if (reference) {
|
|
3037
|
-
const previous = this.experimentProtocol(reference);
|
|
3038
|
-
if (previous.protocol.campaignId !== protocol.campaignId || reference === protocol.supersedes && previous.protocol.lineage !== protocol.lineage)
|
|
3039
|
-
throw new PreEffectToolRefusal("experiment protocol reference belongs to another campaign or lineage");
|
|
3040
|
-
}
|
|
3041
|
-
await this.experimentScreen(canonicalJson(protocol), before.task); requestCheck();
|
|
3042
|
-
const current = this.experimentFresh(before, by, protocol); requestCheck();
|
|
3043
|
-
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);
|
|
3044
|
-
return { kind: "protocol", protocolHash: saved.hash };
|
|
3045
|
-
}
|
|
3046
|
-
if (envelope.kind === "attempt") {
|
|
3047
|
-
const fields = this.studyFields(input, ["kind", "attempt"]), attempt = parseExperimentAttempt(fields.attempt), record = this.experimentProtocol(attempt.protocolHash);
|
|
3048
|
-
const before = this.experimentContext(by, attempt.taskId, record.protocol, record.recordedForTaskId);
|
|
3049
|
-
for (const reference of [attempt.retryOf, attempt.reproducesAttemptId]) if (reference) {
|
|
3050
|
-
const previous = this.experimentAttempt(reference), protocol = this.experimentProtocol(previous.attempt.protocolHash);
|
|
3051
|
-
if (protocol.protocol.campaignId !== record.protocol.campaignId) throw new PreEffectToolRefusal("attempt reference belongs to another campaign");
|
|
3052
|
-
}
|
|
3053
|
-
await this.experimentScreen(canonicalJson(attempt), before.task); requestCheck();
|
|
3054
|
-
const current = this.experimentFresh(before, by, record.protocol, record.recordedForTaskId); requestCheck();
|
|
3055
|
-
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);
|
|
3056
|
-
return { kind: "attempt", protocolHash: saved.attempt.protocolHash, attemptId: saved.attemptId };
|
|
3057
|
-
}
|
|
3058
|
-
if (envelope.kind === "event") {
|
|
3059
|
-
const fields = this.studyFields(input, ["kind", "attemptId", "idempotencyKey", "event"]), id = this.experimentId(fields.attemptId), key = fields.idempotencyKey;
|
|
3060
|
-
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");
|
|
3061
|
-
const attempt = this.experimentAttempt(id), record = this.experimentProtocol(attempt.attempt.protocolHash), event = parseExperimentEvent(fields.event, record.protocol);
|
|
3062
|
-
const before = this.experimentContext(by, attempt.attempt.taskId, record.protocol, record.recordedForTaskId), lastSeq = this.d.board.experimentLastSeq(id);
|
|
3063
|
-
await this.experimentScreen(canonicalJson([key, event]), before.task); requestCheck();
|
|
3064
|
-
this.experimentFresh(before, by, record.protocol, record.recordedForTaskId);
|
|
3065
|
-
const observations: ExperimentHostEvidence[] = [];
|
|
3066
|
-
let outputPrivate = event.kind === "output" && "path" in event.body ? this.experimentOutputPrivate(before.task, event.body.path) : false;
|
|
3067
|
-
if (event.kind === "end" && event.body.run && this.d.experimentCheck) {
|
|
3068
|
-
let receipt: unknown;
|
|
3069
|
-
try { receipt = await this.d.experimentCheck(event.body.run); } catch { /* unavailable is unknown */ }
|
|
3070
|
-
requestCheck(); this.experimentFresh(before, by, record.protocol, record.recordedForTaskId);
|
|
3071
|
-
const observation = checkRunObservation(receipt, event.body.run, before.task.id, record.protocol);
|
|
3072
|
-
if (observation) observations.push(observation);
|
|
3073
|
-
} else if (event.kind === "output" && "path" in event.body) {
|
|
3074
|
-
try {
|
|
3075
|
-
const measured = await hashDeliverables([event.body], this.deliverablePorts(before.task));
|
|
3076
|
-
const output = measured[0];
|
|
3077
|
-
if (output) { observations.push(deliverableObservation(output)); outputPrivate ||= output.private === true; }
|
|
3078
|
-
} catch { /* #509 refusal, missing or unreadable means unknown; never use a declared fallback hash */ }
|
|
3079
|
-
requestCheck(); this.experimentFresh(before, by, record.protocol, record.recordedForTaskId);
|
|
3080
|
-
}
|
|
3081
|
-
const current = this.experimentFresh(before, by, record.protocol, record.recordedForTaskId); requestCheck();
|
|
3082
|
-
if (event.kind === "output" && "path" in event.body) outputPrivate ||= this.experimentOutputPrivate(current.task, event.body.path);
|
|
3083
|
-
const saved = this.d.board.appendExperimentEvent(id, key, event, observations, by, this.studyTime(), current.private || record.private || attempt.private || outputPrivate, lastSeq, current.fence);
|
|
3084
|
-
return { kind: "event", protocolHash: record.hash, attemptId: id, seq: saved.event.seq };
|
|
3085
|
-
}
|
|
3086
|
-
throw new PreEffectToolRefusal("unsupported experiment record kind");
|
|
3087
|
-
} catch (error) {
|
|
3088
|
-
if (error instanceof PreEffectToolRefusal) throw error;
|
|
3089
|
-
throw new PreEffectToolRefusal(error instanceof Error ? error.message : "experiment record was not saved");
|
|
3090
|
-
}
|
|
3091
|
-
});
|
|
3092
|
-
}
|
|
3093
|
-
|
|
3094
|
-
private runnerKeyStatus(stored: NonNullable<ReturnType<Board["runnerReceipt"]>>): "active" | "revoked" | "replaced" | "unavailable" {
|
|
3095
|
-
try {
|
|
3096
|
-
const runners = parseResearchRunners(this.d.researchRunners?.() ?? {});
|
|
3097
|
-
if (!Object.hasOwn(runners, stored.receipt.runner)) return "unavailable";
|
|
3098
|
-
const current = runners[stored.receipt.runner]!;
|
|
3099
|
-
if (current.publicKey !== stored.publicKey) return "replaced";
|
|
3100
|
-
if (current.revoked) return "revoked";
|
|
3101
|
-
return current.projects.includes(stored.receipt.projectId) ? "active" : "unavailable";
|
|
3102
|
-
} catch { return "unavailable"; }
|
|
3103
|
-
}
|
|
2610
|
+
async experimentRecord(by: PeerId, input: unknown): Promise<ExperimentReceipt | ComparisonPlanReceipt> { return this.experiment.experimentRecord(by, input); }
|
|
3104
2611
|
|
|
3105
|
-
|
|
3106
|
-
try {
|
|
3107
|
-
const campaign = this.d.board.researchCampaign(record.protocol.campaignId, record.protocol.campaignRevision), task = this.d.board.get(attempt.attempt.taskId);
|
|
3108
|
-
return record.private || attempt.private || !campaign || this.studyReplayPrivacy(campaign, this.studyParent(campaign.parentTaskId)) || !task || this.isPii(task)
|
|
3109
|
-
|| record.protocol.inputs.some(input => { const source = this.studySource(input.sourceId); return !source || source.private; });
|
|
3110
|
-
} catch { return true; }
|
|
3111
|
-
}
|
|
2612
|
+
experimentShow(...args: Parameters<ExperimentDomain["experimentShow"]>): ReturnType<ExperimentDomain["experimentShow"]> { return this.experiment.experimentShow(...args); }
|
|
3112
2613
|
|
|
3113
|
-
async experimentShow(by: PeerId, input: unknown): Promise<ExperimentView> {
|
|
3114
|
-
return this.experimentRead(by, input);
|
|
3115
|
-
}
|
|
3116
|
-
|
|
3117
|
-
private experimentRead(by: PeerId, input: unknown): ExperimentView {
|
|
3118
|
-
requireLocalTaskPeer(by);
|
|
3119
|
-
const fields = this.studyFields(input, ["attemptId", "campaignId", "after", "eventAfter", "limit", "planHash", "baselineAttemptId", "variantAttemptId"]);
|
|
3120
|
-
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`); })();
|
|
3121
|
-
const after = cursor(fields.after, "after"), eventAfter = cursor(fields.eventAfter, "eventAfter"), limit = fields.limit === undefined ? 50 : this.studyNumber(fields.limit, "limit");
|
|
3122
|
-
if (limit > 50) throw new PreEffectToolRefusal("experiment readback is limited to 50 rows");
|
|
3123
|
-
if (fields.planHash !== undefined || fields.baselineAttemptId !== undefined || fields.variantAttemptId !== undefined) {
|
|
3124
|
-
if (fields.attemptId !== undefined || fields.campaignId !== undefined || fields.after !== undefined
|
|
3125
|
-
|| typeof fields.planHash !== "string" || fields.planHash.length !== 64 || !/^[a-f0-9]{64}$/.test(fields.planHash))
|
|
3126
|
-
throw new PreEffectToolRefusal("comparison readback needs one plan hash and two attempt ids");
|
|
3127
|
-
const plan = this.d.board.experimentComparisonPlan(fields.planHash);
|
|
3128
|
-
if (!plan || plan.project !== this.d.project) throw new PreEffectToolRefusal("comparison plan is unavailable in this project");
|
|
3129
|
-
const baseline = this.experimentAttempt(this.experimentId(fields.baselineAttemptId)), variant = this.experimentAttempt(this.experimentId(fields.variantAttemptId));
|
|
3130
|
-
const first = this.experimentProtocol(baseline.attempt.protocolHash), second = this.experimentProtocol(variant.attempt.protocolHash);
|
|
3131
|
-
if (first.protocol.campaignId !== plan.plan.campaignId || second.protocol.campaignId !== plan.plan.campaignId)
|
|
3132
|
-
throw new PreEffectToolRefusal("comparison attempts must belong to the plan's campaign");
|
|
3133
|
-
const left = this.experimentRead(by, { attemptId: baseline.attemptId, eventAfter, limit });
|
|
3134
|
-
const right = this.experimentRead(by, { attemptId: variant.attemptId, eventAfter, limit });
|
|
3135
|
-
let planPrivate = true;
|
|
3136
|
-
try {
|
|
3137
|
-
const campaign = this.studyRecord(plan.plan.campaignId);
|
|
3138
|
-
planPrivate = plan.private || this.studyReplayPrivacy(campaign, this.studyParent(campaign.parentTaskId))
|
|
3139
|
-
|| plan.plan.fixed.inputs.some(input => { const source = this.studySource(input.sourceId); return !source || source.private; });
|
|
3140
|
-
} catch { /* an unavailable privacy classification withholds the comparison */ }
|
|
3141
|
-
const privateRecord = planPrivate || left.attempts.some(row => row.private) || right.attempts.some(row => row.private);
|
|
3142
|
-
return { attempts: [...left.attempts, ...right.attempts], counts: left.counts,
|
|
3143
|
-
comparison: { planHash: plan.hash, baselineAttemptId: baseline.attemptId, variantAttemptId: variant.attemptId,
|
|
3144
|
-
approved: this.experimentApproved(first) && this.experimentApproved(second), private: privateRecord,
|
|
3145
|
-
projection: privateRecord ? "[pii]" : comparisonProjection(plan.plan, first.protocol, second.protocol) } };
|
|
3146
|
-
}
|
|
3147
|
-
let campaignId: string, attempts: ExperimentAttemptRecord[], nextCursor: number | undefined;
|
|
3148
|
-
if (fields.attemptId !== undefined) {
|
|
3149
|
-
if (fields.campaignId !== undefined || fields.after !== undefined) throw new PreEffectToolRefusal("choose one attempt or campaign page");
|
|
3150
|
-
const attempt = this.experimentAttempt(this.experimentId(fields.attemptId));
|
|
3151
|
-
campaignId = this.experimentProtocol(attempt.attempt.protocolHash).protocol.campaignId; attempts = [attempt];
|
|
3152
|
-
} else {
|
|
3153
|
-
campaignId = this.studyId(fields.campaignId); this.studyRecord(campaignId);
|
|
3154
|
-
const page = this.d.board.experimentAttempts(this.d.project, campaignId, after, limit); attempts = page.rows;
|
|
3155
|
-
if (!page.done) nextCursor = page.afterRow;
|
|
3156
|
-
}
|
|
3157
|
-
const summary = this.d.board.experimentSummary(this.d.project, campaignId), views: ExperimentAttemptView[] = [];
|
|
3158
|
-
for (const attempt of attempts) {
|
|
3159
|
-
const record = this.experimentProtocol(attempt.attempt.protocolHash), page = this.d.board.experimentEvents(attempt.attemptId, eventAfter, limit);
|
|
3160
|
-
const runnerReceipts = this.d.board.runnerReceipts(attempt.attemptId);
|
|
3161
|
-
const privateRecord = this.experimentPrivate(record, attempt) || page.rows.some(row => row.private)
|
|
3162
|
-
|| runnerReceipts.some(row => row.private || !this.nameable(canonicalJson(row.receipt)) || looksSecret(canonicalJson(row.receipt)));
|
|
3163
|
-
const status = this.d.board.experimentAttemptStatus(attempt.attemptId);
|
|
3164
|
-
const observations = page.rows.flatMap(row => row.observations), events = page.rows.map(row => row.event);
|
|
3165
|
-
const evidence = { ...projectExperimentWithObservations(record.protocol, events, observations),
|
|
3166
|
-
...(runnerReceipts.length ? { runnerAttested: runnerReceipts.map(row => ({ ...projectRunnerReceipt(record.protocol, row.receipt), key: { hash: row.keyHash, status: this.runnerKeyStatus(row) } })) } : {}) };
|
|
3167
|
-
views.push({ id: attempt.attemptId, protocolHash: record.hash, taskId: attempt.attempt.taskId, phase: attempt.attempt.phase, status, private: privateRecord,
|
|
3168
|
-
campaignRevision: record.protocol.campaignRevision, approval: this.experimentApproved(record) ? "approved" : "unapproved",
|
|
3169
|
-
postHoc: this.d.board.experimentProtocolContext(record.hash).state,
|
|
3170
|
-
...(attempt.attempt.retryOf ? { retryOf: attempt.attempt.retryOf } : {}), ...(attempt.attempt.reproducesAttemptId ? { reproducesAttemptId: attempt.attempt.reproducesAttemptId } : {}), independentlyReproduced: false,
|
|
3171
|
-
protocol: { value: privateRecord ? "[pii]" : record.protocol, provenance: "declared" },
|
|
3172
|
-
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),
|
|
3173
|
-
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,
|
|
3174
|
-
eventsComplete: page.done, ...(!page.done ? { nextEventCursor: page.afterSeq } : {}) });
|
|
3175
|
-
}
|
|
3176
|
-
return { attempts: views, counts: { all: summary.total, statuses: summary.statuses }, ...(nextCursor === undefined ? {} : { nextCursor }) };
|
|
3177
|
-
}
|
|
3178
2614
|
|
|
3179
2615
|
/** Every new host proposal, including split children, consumes the same pure walk before its first notification. */
|
|
3180
2616
|
private proposalPlanner(task: Task): PlannerBinding {
|
|
@@ -3697,812 +3133,40 @@ export class Tasks {
|
|
|
3697
3133
|
}
|
|
3698
3134
|
return notified.size;
|
|
3699
3135
|
}
|
|
3700
|
-
private roadmapReadAuthority(by: PeerId): void {
|
|
3701
|
-
|
|
3702
|
-
|
|
3703
|
-
}
|
|
3704
|
-
|
|
3705
|
-
private
|
|
3706
|
-
|
|
3707
|
-
|
|
3708
|
-
|
|
3709
|
-
|
|
3710
|
-
|
|
3711
|
-
|
|
3712
|
-
|
|
3713
|
-
}
|
|
3714
|
-
|
|
3715
|
-
private
|
|
3716
|
-
|
|
3717
|
-
|
|
3718
|
-
}
|
|
3719
|
-
|
|
3720
|
-
private
|
|
3721
|
-
|
|
3722
|
-
|
|
3723
|
-
|
|
3724
|
-
|
|
3725
|
-
}
|
|
3726
|
-
|
|
3727
|
-
|
|
3728
|
-
|
|
3729
|
-
|
|
3730
|
-
}
|
|
3731
|
-
|
|
3732
|
-
|
|
3733
|
-
|
|
3734
|
-
if (text && !this.publicMetadataText(text))
|
|
3735
|
-
throw new PreEffectToolRefusal("milestone text was not cleared for public planning; remove private content before ahub roadmap new or edit");
|
|
3736
|
-
return text;
|
|
3737
|
-
}
|
|
3738
|
-
|
|
3739
|
-
private async roadmapScreen(fields: MilestonePatch): Promise<void> {
|
|
3740
|
-
const text = this.roadmapTextCurrent(fields);
|
|
3741
|
-
if (text && this.screenOn() && (await this.screenCall(text)).label !== "clear")
|
|
3742
|
-
throw new PreEffectToolRefusal("milestone text was not cleared for public planning; remove private content before ahub roadmap new or edit");
|
|
3743
|
-
this.roadmapTextCurrent(fields);
|
|
3744
|
-
}
|
|
3745
|
-
|
|
3746
|
-
private roadmapResult(by: PeerId, id: number): MilestoneView {
|
|
3747
|
-
try { return this.milestoneShow(by, id); }
|
|
3748
|
-
catch { throw new Error("roadmap operation finished but public readback is unavailable; inspect ahub roadmap show before retrying"); }
|
|
3749
|
-
}
|
|
3750
|
-
|
|
3751
|
-
async milestoneNew(by: PeerId, raw: unknown): Promise<MilestoneView> {
|
|
3752
|
-
const current = this.roadmapWriteAuthority(by), fields = this.roadmapParsed(() => parseMilestoneInput(raw));
|
|
3753
|
-
this.roadmapStateAuthority(by, fields.state);
|
|
3754
|
-
await this.roadmapScreen(fields); current(); this.roadmapStateAuthority(by, fields.state); this.roadmapTextCurrent(fields);
|
|
3755
|
-
const row = this.d.board.newMilestone(fields, by, this.d.now?.() ?? Date.now());
|
|
3756
|
-
return this.roadmapResult(by, row.id);
|
|
3757
|
-
}
|
|
3758
|
-
|
|
3759
|
-
async milestoneEdit(by: PeerId, id: number, revision: number, raw: unknown): Promise<MilestoneView> {
|
|
3760
|
-
const current = this.roadmapWriteAuthority(by), fields = this.roadmapParsed(() => parseMilestonePatch(raw));
|
|
3761
|
-
this.roadmapParsed(() => milestoneRevision(revision)); this.roadmapStateAuthority(by, fields.state);
|
|
3762
|
-
const validate = () => {
|
|
3763
|
-
current(); this.roadmapStateAuthority(by, fields.state);
|
|
3764
|
-
const row = this.roadmapCurrent(id);
|
|
3765
|
-
if (row.revision !== revision) throw new PreEffectToolRefusal("roadmap revision changed; reload ahub roadmap show before editing");
|
|
3766
|
-
return row;
|
|
3767
|
-
};
|
|
3768
|
-
validate(); await this.roadmapScreen(fields); const row = validate(); this.roadmapTextCurrent(fields);
|
|
3769
|
-
if (Object.entries(fields).every(([key, value]) => row[key as keyof Milestone] === value)) return this.milestoneShow(by, id);
|
|
3770
|
-
this.d.board.updateMilestone(id, fields, revision, { by, at: this.d.now?.() ?? Date.now(), event: "edited", fields: Object.keys(fields) });
|
|
3771
|
-
return this.roadmapResult(by, id);
|
|
3772
|
-
}
|
|
3773
|
-
|
|
3774
|
-
milestoneLink(by: PeerId, id: number, kind: MilestoneLinkKind, raw: string): MilestoneView {
|
|
3775
|
-
this.roadmapWriteAuthority(by);
|
|
3776
|
-
const row = this.roadmapCurrent(id), ref = this.roadmapParsed(() => milestoneLinkRef(kind, raw));
|
|
3777
|
-
if (!this.publicMetadataText(ref)) throw new PreEffectToolRefusal("roadmap reference is private; use a public reference with ahub roadmap link");
|
|
3778
|
-
if (kind === "task" && !this.d.board.get(Number(ref)) || kind === "release" && !this.d.board.release(Number(ref)))
|
|
3779
|
-
throw new PreEffectToolRefusal("roadmap target does not exist; inspect ahub board or ahub release list before linking");
|
|
3780
|
-
this.d.board.linkMilestone(id, kind, ref, by, row.revision, this.d.now?.() ?? Date.now());
|
|
3781
|
-
return this.roadmapResult(by, id);
|
|
3782
|
-
}
|
|
3783
|
-
|
|
3784
|
-
milestoneUnlink(by: PeerId, id: number, kind: MilestoneLinkKind, raw: string): MilestoneView {
|
|
3785
|
-
this.roadmapWriteAuthority(by);
|
|
3786
|
-
const row = this.roadmapCurrent(id), ref = this.roadmapParsed(() => milestoneLinkRef(kind, raw));
|
|
3787
|
-
this.d.board.unlinkMilestone(id, kind, ref, by, row.revision, this.d.now?.() ?? Date.now());
|
|
3788
|
-
return this.roadmapResult(by, id);
|
|
3789
|
-
}
|
|
3790
|
-
|
|
3791
|
-
milestoneOrder(by: PeerId, id: number, order: number): MilestoneView {
|
|
3792
|
-
this.roadmapWriteAuthority(by);
|
|
3793
|
-
const row = this.roadmapCurrent(id), fields = this.roadmapParsed(() => parseMilestonePatch({ order }));
|
|
3794
|
-
if (row.order !== order) this.d.board.updateMilestone(id, fields, row.revision, { by, at: this.d.now?.() ?? Date.now(), event: "ordered", fields: ["order"] });
|
|
3795
|
-
return this.roadmapResult(by, id);
|
|
3796
|
-
}
|
|
3797
|
-
|
|
3798
|
-
milestoneState(by: PeerId, id: number, state: MilestoneState): MilestoneView {
|
|
3799
|
-
this.roadmapWriteAuthority(by); this.roadmapStateAuthority(by, state);
|
|
3800
|
-
this.roadmapParsed(() => parseMilestonePatch({ state }));
|
|
3801
|
-
const row = this.roadmapCurrent(id, state);
|
|
3802
|
-
// #1622 family 4: an instructed person verdict records the same three provenance keys task history does, for done and dropped only.
|
|
3803
|
-
const instruction = by === USER && (state === "done" || state === "dropped") ? instructedHistory(by) : {};
|
|
3804
|
-
if (row.state !== state) this.d.board.updateMilestone(id, { state }, row.revision, { by, at: this.d.now?.() ?? Date.now(), event: "state", fields: ["state"], ...instruction });
|
|
3805
|
-
return this.roadmapResult(by, id);
|
|
3806
|
-
}
|
|
3807
|
-
|
|
3808
|
-
/** #1738: the hub's own roadmap pass (the five-minute sweep and each task change's notice) runs milestoneList several times (the sweep, roadmapNotify, roadmapCheck and each
|
|
3809
|
-
* finding's recheck), and a working-tree spec check runs one synchronous git per spec path, so hub reads reuse one check for ROADMAP_SPECS_REUSE_MS. A thrown check is not
|
|
3810
|
-
* kept. Reads by the person and peers, and explicit `specs check`, stay uncached.
|
|
3811
|
-
* ponytail: a time window, not a repository key; key it on HEAD and index state, or run the check off the event loop, if a minute of stale freshness ever matters. */
|
|
3812
|
-
private roadmapSpecs: { at: number; report: SpecsCheckReport | SpecsCoverReport | undefined } | undefined;
|
|
3813
|
-
private roadmapSpecsCheck(): SpecsCheckReport | SpecsCoverReport | undefined {
|
|
3814
|
-
const now = this.d.now?.() ?? Date.now(), kept = this.roadmapSpecs;
|
|
3815
|
-
if (kept && now >= kept.at && now - kept.at < ROADMAP_SPECS_REUSE_MS) return kept.report;
|
|
3816
|
-
const report = this.d.specsRead?.("check", []);
|
|
3817
|
-
this.roadmapSpecs = { at: now, report };
|
|
3818
|
-
return report;
|
|
3819
|
-
}
|
|
3820
|
-
|
|
3821
|
-
private roadmapSpecsFor(by: PeerId): SpecsCheckReport | SpecsCoverReport | undefined {
|
|
3822
|
-
return by === HUB ? this.roadmapSpecsCheck() : this.d.specsRead?.("check", []);
|
|
3823
|
-
}
|
|
3824
|
-
|
|
3825
|
-
private roadmapSnapshot(by: PeerId, specs = () => this.roadmapSpecsFor(by)): RoadmapSnapshot {
|
|
3826
|
-
let freshness: SpecsCheckReport["freshness"] | undefined;
|
|
3827
|
-
try { const report = specs(); if (report && "freshness" in report && !report.truncated && report.errors === 0)
|
|
3828
|
-
freshness = report.freshness.filter(row => this.publicMetadataText(row.path) && (row.id === undefined || this.publicMetadataText(row.id))); } catch { /* unavailable evidence stays unknown */ }
|
|
3829
|
-
return { milestones: this.d.board.milestones(), links: this.d.board.milestoneLinks(), tasks: this.d.board.list(), releases: this.d.board.releases(), freshness,
|
|
3830
|
-
issueOf: task => { try { const source = this.planIssueIdentity(task); return source ? `${source.repo.toLowerCase()}#${source.issue}` : undefined; } catch { return undefined; } },
|
|
3831
|
-
privateTask: task => this.isPii(task) || task.signals.includes("pii") || task.state === "backlog" && by !== USER && !this.isConfiguredPlanner(by),
|
|
3832
|
-
publicText: text => this.publicMetadataText(text),
|
|
3833
|
-
};
|
|
3834
|
-
}
|
|
3835
|
-
|
|
3836
|
-
milestoneList(by: PeerId, specs?: () => SpecsCheckReport | SpecsCoverReport | undefined): (MilestoneView & { tree: TreeRollup; readyToClose: ReadyToClose })[] {
|
|
3837
|
-
this.roadmapReadAuthority(by);
|
|
3838
|
-
const views = withTree(milestoneViews(this.roadmapSnapshot(by, specs)));
|
|
3839
|
-
this.roadmapReadAuthority(by); return views;
|
|
3840
|
-
}
|
|
3841
|
-
|
|
3842
|
-
milestoneShow(by: PeerId, id: number): MilestoneView {
|
|
3843
|
-
this.roadmapParsed(() => milestoneId(id));
|
|
3844
|
-
const row = this.milestoneList(by).find(row => row.id === id);
|
|
3845
|
-
if (!row) throw new PreEffectToolRefusal("roadmap milestone does not exist; use ahub roadmap list");
|
|
3846
|
-
return row;
|
|
3847
|
-
}
|
|
3848
|
-
|
|
3849
|
-
/** Host-sampled GitHub authority is never supplied by a tool argument. */
|
|
3850
|
-
private roadmapRepository(): string {
|
|
3851
|
-
const repo = this.roadmapParsed(() => githubRepo(this.d.repository));
|
|
3852
|
-
let origin: string | undefined;
|
|
3853
|
-
try { origin = this.d.roadmapOrigin ? this.d.roadmapOrigin() : githubOriginRepository(this.d.cwd); } catch { /* unknown is not a trusted origin */ }
|
|
3854
|
-
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");
|
|
3855
|
-
return repo;
|
|
3856
|
-
}
|
|
3857
|
-
private roadmapApplyAuthority(by: PeerId): void {
|
|
3858
|
-
this.roadmapReadAuthority(by);
|
|
3859
|
-
if (this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) throw new PreEffectToolRefusal("roadmap writes are held; retry after recovery");
|
|
3860
|
-
if (by !== USER && (!(this.d.roadmapConfig?.().github_write === "conductor") || !this.configuredManualConductor(by) || !this.d.bus.isRostered(by)))
|
|
3861
|
-
throw new PreEffectToolRefusal("GitHub roadmap writes require the person or the configured conductor with roadmap.github_write enabled");
|
|
3862
|
-
}
|
|
3863
|
-
|
|
3864
|
-
private roadmapIssueRefs(views: ReturnType<Tasks["milestoneList"]>): Set<string> {
|
|
3865
|
-
const refs = new Set<string>();
|
|
3866
|
-
for (const view of views) {
|
|
3867
|
-
for (const issue of view.issues) refs.add(issue.ref);
|
|
3868
|
-
for (const member of view.tasks) {
|
|
3869
|
-
const task = this.d.board.get(member.id); if (!task) continue;
|
|
3870
|
-
try { const source = this.planIssueIdentity(task); if (source && this.publicMetadataText(source.repo)) refs.add(`${source.repo.toLowerCase()}#${source.issue}`); } catch { /* ambiguous identity is unknown */ }
|
|
3871
|
-
}
|
|
3872
|
-
}
|
|
3873
|
-
return refs;
|
|
3874
|
-
}
|
|
3875
|
-
|
|
3876
|
-
/** Render only screened views. Issue writes require an exact preview and fresh authority. */
|
|
3877
|
-
async roadmapExport(by: PeerId, input: { issue?: number; apply?: boolean; confirm?: string } = {}): Promise<{ json: string; markdown: string; fingerprint: string; call?: string[]; applied: boolean }> {
|
|
3878
|
-
const check = this.requestCheck(by, () => this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError ? "roadmap is held by recovery or storage" : undefined);
|
|
3879
|
-
check(); this.roadmapReadAuthority(by);
|
|
3880
|
-
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");
|
|
3881
|
-
if (input.issue !== undefined) this.roadmapParsed(() => milestoneId(input.issue));
|
|
3882
|
-
if (input.apply && input.issue === undefined) throw new PreEffectToolRefusal("roadmap export --apply needs an issue; preview with --issue first");
|
|
3883
|
-
if (input.apply) this.roadmapApplyAuthority(by);
|
|
3884
|
-
let pinned: { report: SpecsCheckReport | SpecsCoverReport | undefined } | undefined;
|
|
3885
|
-
const specs = () => { if (!pinned) { pinned = { report: undefined }; pinned.report = this.roadmapSpecsFor(by); } return pinned.report; };
|
|
3886
|
-
let checkedKey = this.roadmapBoardKey(by);
|
|
3887
|
-
const views = this.milestoneList(by, specs), refs = this.roadmapIssueRefs(views);
|
|
3888
|
-
const evidence = JSON.stringify([views, [...refs]]);
|
|
3889
|
-
const privacy = JSON.stringify([this.d.routing(), this.d.piiPaths, this.d.deny]);
|
|
3890
|
-
const current = () => {
|
|
3891
|
-
check(); this.roadmapReadAuthority(by);
|
|
3892
|
-
const key = this.roadmapBoardKey(by);
|
|
3893
|
-
const sameViews = () => {
|
|
3894
|
-
if (key === checkedKey) return true;
|
|
3895
|
-
const latest = this.milestoneList(by, specs);
|
|
3896
|
-
return JSON.stringify([latest, [...this.roadmapIssueRefs(latest)]]) === evidence;
|
|
3897
|
-
};
|
|
3898
|
-
if (JSON.stringify([this.d.routing(), this.d.piiPaths, this.d.deny]) !== privacy || !sameViews())
|
|
3899
|
-
throw new PreEffectToolRefusal("roadmap or privacy policy changed while exporting; retry ahub roadmap export");
|
|
3900
|
-
checkedKey = key;
|
|
3901
|
-
};
|
|
3902
|
-
const issueStates = await roadmapIssueStates(refs, this.roadmapGh(), current);
|
|
3903
|
-
current();
|
|
3904
|
-
const rendered = roadmapExport(views, issueStates);
|
|
3905
|
-
const repo = input.issue === undefined ? undefined : this.roadmapRepository();
|
|
3906
|
-
const call = repo === undefined ? undefined : ["api", `repos/${repo}/issues/${input.issue}`, "--hostname", "github.com", "--method", "PATCH", "-f", `body=${rendered.markdown}`];
|
|
3907
|
-
const fingerprint = createHash("sha256").update(JSON.stringify({ repo: repo ?? null, issue: input.issue ?? null, markdown: rendered.markdown })).digest("hex");
|
|
3908
|
-
if (!input.apply) return { ...rendered, fingerprint, ...(call ? { call } : {}), applied: false };
|
|
3909
|
-
if (input.confirm !== fingerprint) throw new PreEffectToolRefusal(`roadmap export preview changed; run ahub roadmap export --issue ${input.issue} and retry with --confirm ${fingerprint}`);
|
|
3910
|
-
check(); this.roadmapApplyAuthority(by); if (this.roadmapRepository() !== repo) throw new PreEffectToolRefusal("roadmap GitHub origin changed; preview again");
|
|
3911
|
-
let result: Awaited<ReturnType<SdlcGh>>;
|
|
3912
|
-
try { result = await this.roadmapGh()(call!, 10_000, undefined, 64 * 1024); }
|
|
3913
|
-
catch { throw new Error("roadmap issue update outcome is unknown; inspect the issue before retrying"); }
|
|
3914
|
-
if (result.code !== 0) throw new Error("roadmap issue update was not confirmed; inspect the issue before retrying");
|
|
3915
|
-
try { current(); this.roadmapApplyAuthority(by); if (this.roadmapRepository() !== repo) throw new Error("changed"); }
|
|
3916
|
-
catch { throw new Error("roadmap or authority changed after issue update; inspect the issue and preview again"); }
|
|
3917
|
-
return { ...rendered, fingerprint, call, applied: true };
|
|
3918
|
-
}
|
|
3919
|
-
|
|
3920
|
-
/** Build drift only from the same screened views and host-owned evidence as roadmap reads. */
|
|
3921
|
-
async roadmapCheck(by: PeerId, include?: (finding: RoadmapDrift) => boolean): Promise<ReturnType<typeof checkRoadmap>> {
|
|
3922
|
-
const check = this.requestCheck(by); check(); this.roadmapReadAuthority(by);
|
|
3923
|
-
// #1741: one spec check per roadmap check. current() rebuilds the views before and after every issue read, and an uncached working-tree check is a
|
|
3924
|
-
// synchronous git per spec path (about a second on this repository), so it ran up to 200 times per call. A thrown check is kept as unavailable.
|
|
3925
|
-
let pinned: { report: SpecsCheckReport | SpecsCoverReport | undefined } | undefined;
|
|
3926
|
-
const specs = () => { if (!pinned) { pinned = { report: undefined }; pinned.report = this.roadmapSpecsFor(by); } return pinned.report; };
|
|
3927
|
-
const boardKey = () => this.roadmapBoardKey(by);
|
|
3928
|
-
let checkedKey = boardKey(); // taken before the views, so a write between the two is compared, not skipped
|
|
3929
|
-
const views = this.milestoneList(by, specs), config = this.d.roadmapConfig?.() ?? { github_mirror: false, github_write: "off" as const }, privacy = JSON.stringify([this.d.routing(), this.d.piiPaths, this.d.deny]);
|
|
3930
|
-
const snapshot = (rows: typeof views) => JSON.stringify([rows, rows.flatMap(view => view.tasks.map(member => this.d.board.get(member.id)))]);
|
|
3931
|
-
const evidence = snapshot(views);
|
|
3932
|
-
// #1741: building the views runs issueOf over every board task (a regex scan of its text), about 140 ms on a 1156-task board, and current() runs before
|
|
3933
|
-
// and after each issue read. Rebuild only when a task write (statusRevision), a milestone, link or release row, or the caller's planner role (it screens backlog tasks) says the views can differ; config and privacy are compared on every call below.
|
|
3934
|
-
const sameViews = () => { const key = boardKey(); if (key === checkedKey) return true; if (snapshot(this.milestoneList(by, specs)) !== evidence) return false; checkedKey = key; return true; };
|
|
3935
|
-
const current = () => { check(); this.roadmapReadAuthority(by); if (!sameViews() || 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"); };
|
|
3936
|
-
const issueStates = await roadmapIssueStates(this.roadmapIssueRefs(views), this.roadmapGh(), current);
|
|
3937
|
-
const rendered = roadmapExport(views, issueStates), exportStates: (boolean | undefined)[] = [];
|
|
3938
|
-
for (const [path, expected] of [["docs/roadmap.json", rendered.json], ["docs/roadmap.md", rendered.markdown]] as const) {
|
|
3939
|
-
try {
|
|
3940
|
-
const file = await readGuardedDeliverable(path, { cwd: this.d.cwd, deny: this.d.deny ?? [], private: name => matchesPolicy(this.d.cwd, name, this.d.piiPaths ?? [], true) });
|
|
3941
|
-
current(); exportStates.push(Buffer.from(file.data).toString("utf8") === expected);
|
|
3942
|
-
} catch (error) { if (error instanceof PreEffectToolRefusal) throw error; exportStates.push(error instanceof DeliverableRefusal && error.message.includes("does not exist") ? false : undefined); }
|
|
3943
|
-
}
|
|
3944
|
-
const exportMatches = exportStates.includes(false) ? false : exportStates.every(value => value === true) ? true : undefined;
|
|
3945
|
-
current();
|
|
3946
|
-
let mirror: Awaited<ReturnType<typeof readMirrorSnapshot>> | undefined, repo: string | undefined;
|
|
3947
|
-
if (config.github_mirror) {
|
|
3948
|
-
try { repo = this.roadmapRepository(); mirror = await readMirrorSnapshot(repo, this.roadmapGh()); }
|
|
3949
|
-
catch { /* partial or unavailable evidence stays unknown */ }
|
|
3950
|
-
current();
|
|
3951
|
-
}
|
|
3952
|
-
const milestones: DriftMilestone[] = views.map(view => {
|
|
3953
|
-
const tasks = view.tasks.map(member => {
|
|
3954
|
-
const task = this.d.board.get(member.id)!;
|
|
3955
|
-
let issue: string | null | undefined;
|
|
3956
|
-
try { const source = this.planIssueIdentity(task); issue = source ? `${source.repo.toLowerCase()}#${source.issue}` : null; } catch { issue = undefined; }
|
|
3957
|
-
const issueState: "open" | "closed" | "unknown" = issue ? issueStates.get(issue) ?? "unknown" : "unknown";
|
|
3958
|
-
const merge = task.sdlc?.merge?.state === "merged" ? task.sdlc.merge : task.sdlc?.mergeReadback;
|
|
3959
|
-
const mergedAt = merge?.state === "merged" ? merge.cost?.mergedAt ?? undefined : task.sdlc?.pr && task.state === "approved" ? undefined : null;
|
|
3960
|
-
const report = merge?.state === "merged" ? this.currentSpecReport(task) : undefined;
|
|
3961
|
-
const unchangedSpecs = mergedAt === null ? [] : report?.complete && report.errors === 0 && !report.truncated && report.head === merge?.head
|
|
3962
|
-
? report.unchanged.filter(row => !row.reason?.trim()).map(row => row.id) : undefined;
|
|
3963
|
-
return { id: task.id, state: task.state, issue, issueState, feature: /^feat(?:\([^)]*\))?:/i.test(task.title), specIssue: !!task.sdlc?.issue, mergedAt, unchangedSpecs };
|
|
3964
|
-
});
|
|
3965
|
-
const children = view.children.map(id => views.find(row => row.id === id));
|
|
3966
|
-
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));
|
|
3967
|
-
const uncertain = !!view.withheld || view.issues.some(row => !issueStates.has(row.ref)) || view.releases.some(row => row.state === "unknown") || children.some(row => !row);
|
|
3968
|
-
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"; });
|
|
3969
|
-
let mirrorDiff: boolean | undefined;
|
|
3970
|
-
if (mirror && repo && !view.withheld && view.title !== "[withheld]") {
|
|
3971
|
-
try {
|
|
3972
|
-
const marker = `<!-- ahub-roadmap:${this.d.project}:${view.id} -->`, bound = this.d.board.mirrorMilestone(repo, view.id);
|
|
3973
|
-
const recovered = bound === undefined ? recoverMirrorBinding(marker, view.title, mirror.milestones) : undefined;
|
|
3974
|
-
if (recovered?.kind === "ambiguous" || recovered?.titleConflicts.length) mirrorDiff = true;
|
|
3975
|
-
else {
|
|
3976
|
-
const number = bound ?? (recovered?.kind === "bind" ? recovered.number : undefined), remote = number === undefined ? null : mirror.milestones.find(row => row.number === number);
|
|
3977
|
-
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;
|
|
3978
|
-
}
|
|
3979
|
-
} catch { /* unknown mirror evidence */ }
|
|
3980
|
-
}
|
|
3981
|
-
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 };
|
|
3982
|
-
});
|
|
3983
|
-
current(); return checkRoadmap({ milestones, now: this.d.now?.() ?? Date.now(), closeLagMs: 24 * 60 * 60_000, mirrorEnabled: config.github_mirror, exportMatches }, include);
|
|
3984
|
-
}
|
|
3985
|
-
|
|
3986
|
-
/** #1741: what the milestone views are built from, apart from config, privacy and the spec report: equal keys build equal views. */
|
|
3987
|
-
private roadmapBoardKey(by: PeerId): string {
|
|
3988
|
-
return JSON.stringify([this.d.board.statusRevision(), this.d.board.milestones(), this.d.board.milestoneLinks(), this.d.board.releases(), this.isConfiguredPlanner(by)]);
|
|
3989
|
-
}
|
|
3990
|
-
|
|
3991
|
-
/** Serialize at the host caller. Persist only admitted ids-only notices, so unavailable feeds can retry. */
|
|
3992
|
-
async roadmapNotify(taskIds: readonly number[], send: (task: number, milestone: number | null, rule: number, marker: string) => boolean): Promise<number> {
|
|
3993
|
-
if (!taskIds.length) return 0;
|
|
3994
|
-
const views = this.milestoneList(HUB);
|
|
3995
|
-
if (!views.some(view => view.tasks.some(task => taskIds.includes(task.id)))) return 0;
|
|
3996
|
-
const select = (finding: RoadmapDrift) => {
|
|
3997
|
-
const referenced = finding.items.filter(item => /^task:[1-9][0-9]*$/.test(item)).map(item => Number(item.slice(5)));
|
|
3998
|
-
const eligible = views.filter(view => finding.milestone === null || view.id === finding.milestone).flatMap(view => view.tasks.map(task => task.id));
|
|
3999
|
-
const marker = createHash("sha256").update(JSON.stringify([finding.rule, finding.milestone, finding.items, finding.cause])).digest("hex");
|
|
4000
|
-
return !this.d.board.hasRoadmapNotice(marker) && taskIds.some(id => eligible.includes(id) && (!referenced.length || referenced.includes(id)));
|
|
4001
|
-
};
|
|
4002
|
-
const checked = await this.roadmapCheck(HUB, select);
|
|
4003
|
-
// #1741: each finding rechecks membership against the current views; rebuild them only when the board key moved (a build is ~140 ms on a 1156-task board, once per finding before).
|
|
4004
|
-
let latestViews: ReturnType<Tasks["milestoneList"]> | undefined, latestKey: string | undefined;
|
|
4005
|
-
const currentViews = () => { const key = this.roadmapBoardKey(HUB); if (key !== latestKey || !latestViews) { latestKey = key; latestViews = this.milestoneList(HUB); } return latestViews; };
|
|
4006
|
-
let sent = 0;
|
|
4007
|
-
for (const finding of checked.findings) {
|
|
4008
|
-
const referenced = finding.items.filter(item => /^task:[1-9][0-9]*$/.test(item)).map(item => Number(item.slice(5)));
|
|
4009
|
-
const eligible = views.filter(view => finding.milestone === null || view.id === finding.milestone).flatMap(view => view.tasks.map(task => task.id));
|
|
4010
|
-
const task = taskIds.find(id => eligible.includes(id) && (!referenced.length || referenced.includes(id)));
|
|
4011
|
-
if (task === undefined) continue;
|
|
4012
|
-
const marker = createHash("sha256").update(JSON.stringify([finding.rule, finding.milestone, finding.items, finding.cause])).digest("hex");
|
|
4013
|
-
if (this.d.board.hasRoadmapNotice(marker)) continue;
|
|
4014
|
-
const latest = this.d.board.get(task);
|
|
4015
|
-
if (!latest || this.isPii(latest) || !currentViews().some(view => (finding.milestone === null || view.id === finding.milestone) && view.tasks.some(row => row.id === task))) continue;
|
|
4016
|
-
if (send(task, finding.milestone, finding.rule, marker) && this.d.board.recordRoadmapNotice(marker)) sent++;
|
|
4017
|
-
}
|
|
4018
|
-
return sent;
|
|
4019
|
-
}
|
|
4020
|
-
|
|
4021
|
-
/** #1647: the optional reason a task was split off. Absent stays legal; anything outside the closed set is refused before any effect, naming the allowed values. */
|
|
4022
|
-
private proposalReason(value: unknown): TaskReason | undefined {
|
|
4023
|
-
if (value === undefined || value === null || value === "") return undefined;
|
|
4024
|
-
if (typeof value !== "string" || !(TASK_REASONS as readonly string[]).includes(value)) throw new PreEffectToolRefusal(`reason must be one of ${TASK_REASONS.join(", ")}; omit it when no reason applies, then call hub_task_propose again`);
|
|
4025
|
-
return value as TaskReason;
|
|
4026
|
-
}
|
|
4027
|
-
|
|
4028
|
-
/**
|
|
4029
|
-
* #1647 AC2: siblings proposed for one plan, by one planner with the same dependencies and `reason: "parallel"`, must touch disjoint `refs.paths` (prefix overlap, `samePlace`).
|
|
4030
|
-
* Refused before the new task exists, naming both tasks and the paths.
|
|
4031
|
-
* ponytail: the board has no plan-revision id on a task, so "one plan" is the same proposer, the same `after` set, the same repository and an open state; ceiling: two unrelated
|
|
4032
|
-
* parallel batches by one planner with equal dependencies read as siblings; upgrade: record the planning revision on the task and compare within it.
|
|
4033
|
-
*/
|
|
4034
|
-
private parallelSiblingsDisjoint(by: PeerId, title: string, refs: TaskRefs, deps: number[]): void {
|
|
4035
|
-
const mine = refs.paths ?? [];
|
|
4036
|
-
if (!mine.length) return;
|
|
4037
|
-
const scope = this.repositories.scope(refs), key = [...deps].sort((a, b) => a - b).join(",");
|
|
4038
|
-
for (const other of this.d.board.list()) {
|
|
4039
|
-
if (other.reason !== "parallel" || isClosedTaskState(other.state) || other.history[0]?.by !== by || this.isPii(other)) continue;
|
|
4040
|
-
if ([...(other.deps ?? [])].sort((a, b) => a - b).join(",") !== key || this.repositories.scope(other.refs).key !== scope.key) continue;
|
|
4041
|
-
const shared = mine.filter(path => (other.refs.paths ?? []).some(theirs => samePlace(path, theirs)));
|
|
4042
|
-
if (shared.length) throw new PreEffectToolRefusal(`parallel siblings must touch disjoint paths: "${title}" and task #${other.id} both touch ${shared.slice(0, PARALLEL_PATHS_NAMED).join(", ")}; call hub_task_propose again with disjoint refs.paths, or without reason parallel, or keep the work as one task you own`);
|
|
4043
|
-
}
|
|
4044
|
-
}
|
|
4045
|
-
|
|
4046
|
-
/** Preview every fixed GitHub call from a complete inventory; confirmation binds both calls and local bindings. */
|
|
4047
|
-
async roadmapSync(by: PeerId, input: { apply?: boolean; confirm?: string } = {}): Promise<{ repo: string; calls: string[][]; bindings: { milestone: number; number: number }[]; fingerprint: string; applied: boolean }> {
|
|
4048
|
-
this.roadmapReadAuthority(by);
|
|
4049
|
-
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");
|
|
4050
|
-
if (input.apply) this.roadmapApplyAuthority(by);
|
|
4051
|
-
const config = this.d.roadmapConfig?.() ?? { github_mirror: false, github_write: "off" as const };
|
|
4052
|
-
if (!config.github_mirror) throw new PreEffectToolRefusal("roadmap GitHub mirror is off; enable roadmap.github_mirror in trusted configuration before syncing");
|
|
4053
|
-
const repo = this.roadmapRepository(), views = this.milestoneList(by);
|
|
4054
|
-
if (views.length > 100) throw new PreEffectToolRefusal("roadmap mirror exceeds 100 milestones; narrow the roadmap before syncing");
|
|
4055
|
-
const deadline = performance.now() + 50_000;
|
|
4056
|
-
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");
|
|
4057
|
-
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);
|
|
4058
|
-
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"); };
|
|
4059
|
-
const run = this.roadmapGh();
|
|
4060
|
-
const snapshot = await readMirrorSnapshot(repo, async (...args) => { current(); const result = await run(...args); current(); return result; });
|
|
4061
|
-
current();
|
|
4062
|
-
const bindings: { milestone: number; number: number }[] = [], calls: string[][] = [], createIds: (number | undefined)[] = [], issueOwners = new Set<number>();
|
|
4063
|
-
for (const view of views) for (const issue of view.issues) if (issue.ref.startsWith(`${repo}#`)) {
|
|
4064
|
-
const id = milestoneId(Number(issue.ref.slice(repo.length + 1)));
|
|
4065
|
-
if (issueOwners.has(id)) throw new PreEffectToolRefusal("an issue is linked to multiple roadmap milestones; settle its placement before syncing");
|
|
4066
|
-
issueOwners.add(id);
|
|
4067
|
-
}
|
|
4068
|
-
for (const view of views) {
|
|
4069
|
-
if (view.withheld || view.title === "[withheld]" || view.outcome === "[withheld]") throw new PreEffectToolRefusal("roadmap mirror contains withheld membership or metadata; inspect privacy before syncing");
|
|
4070
|
-
const marker = `<!-- ahub-roadmap:${this.d.project}:${view.id} -->`, bound = this.d.board.mirrorMilestone(repo, view.id);
|
|
4071
|
-
const matching = bound === undefined ? recoverMirrorBinding(marker, view.title, snapshot.milestones) : undefined;
|
|
4072
|
-
if (matching?.kind === "ambiguous" || matching?.titleConflicts.length) throw new PreEffectToolRefusal("roadmap GitHub milestone identity is ambiguous; inspect matching milestones before syncing");
|
|
4073
|
-
const remoteId = bound ?? (matching?.kind === "bind" ? matching.number : undefined);
|
|
4074
|
-
if (bound === undefined && remoteId !== undefined) bindings.push({ milestone: view.id, number: remoteId });
|
|
4075
|
-
const remote = remoteId === undefined ? null : snapshot.milestones.find(row => row.number === remoteId);
|
|
4076
|
-
if (remoteId !== undefined && !remote) throw new PreEffectToolRefusal("recorded GitHub milestone is missing from the complete inventory; inspect the binding");
|
|
4077
|
-
const issues = view.issues.filter(row => row.ref.startsWith(`${repo}#`)).map(row => Number(row.ref.slice(repo.length + 1)));
|
|
4078
|
-
const planned = planRoadmapMirror(repo, { title: view.title, state: view.state === "done" || view.state === "dropped" ? "closed" : "open", issues, marker }, remote ?? null, snapshot.issues);
|
|
4079
|
-
for (const call of planned.calls) {
|
|
4080
|
-
const detached = /^repos\/[^/]+\/[^/]+\/issues\/([1-9][0-9]*)$/.exec(call[1] ?? "");
|
|
4081
|
-
if (detached && call.includes("milestone=null") && issueOwners.has(Number(detached[1]))) continue;
|
|
4082
|
-
calls.push(call); createIds.push(remoteId === undefined ? view.id : undefined);
|
|
4083
|
-
if (calls.length > 200) throw new PreEffectToolRefusal("roadmap mirror exceeds 200 writes; narrow the roadmap before syncing");
|
|
4084
|
-
}
|
|
4085
|
-
}
|
|
4086
|
-
const hiddenIssues = new Set<number>();
|
|
4087
|
-
for (const task of this.d.board.list()) if (this.isPii(task) || task.signals.includes("pii") || task.signals.includes("pii_path")) {
|
|
4088
|
-
try { const issue = this.planIssueIdentity(task); if (issue?.repo.toLowerCase() === repo) hiddenIssues.add(issue.issue); }
|
|
4089
|
-
catch { throw new PreEffectToolRefusal("private issue placement is unknown; inspect privacy before syncing"); }
|
|
4090
|
-
}
|
|
4091
|
-
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");
|
|
4092
|
-
const fingerprint = createHash("sha256").update(JSON.stringify({ repo, bindings, calls })).digest("hex");
|
|
4093
|
-
if (!input.apply) return { repo, calls, bindings, fingerprint, applied: false };
|
|
4094
|
-
if (input.confirm !== fingerprint) throw new PreEffectToolRefusal(`roadmap sync preview changed; run ahub roadmap sync and retry with --confirm ${fingerprint}`);
|
|
4095
|
-
let effects = false;
|
|
4096
|
-
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; } };
|
|
4097
|
-
effectCurrent();
|
|
4098
|
-
for (const binding of bindings) {
|
|
4099
|
-
effectCurrent();
|
|
4100
|
-
try { this.d.board.bindMirrorMilestone(repo, binding.milestone, binding.number); effects = true; before = stamp(); }
|
|
4101
|
-
catch (error) { if (effects) throw new Error("roadmap binding changed after effects; inspect the mirror and preview again"); throw error; }
|
|
4102
|
-
}
|
|
4103
|
-
for (let index = 0; index < calls.length; index++) {
|
|
4104
|
-
effectCurrent();
|
|
4105
|
-
let result: Awaited<ReturnType<SdlcGh>>;
|
|
4106
|
-
const remaining = deadline - performance.now();
|
|
4107
|
-
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"); }
|
|
4108
|
-
effects = true;
|
|
4109
|
-
try { result = await run(calls[index]!, Math.min(10_000, remaining), undefined, 64 * 1024); }
|
|
4110
|
-
catch { throw new Error("roadmap GitHub write outcome is unknown; inspect the mirror and preview again before retrying"); }
|
|
4111
|
-
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");
|
|
4112
|
-
const local = createIds[index];
|
|
4113
|
-
if (local !== undefined) {
|
|
4114
|
-
let number: number;
|
|
4115
|
-
try {
|
|
4116
|
-
const created = JSON.parse(result.stdout) as Record<string, unknown>, call = calls[index]!;
|
|
4117
|
-
number = milestoneId(created.number);
|
|
4118
|
-
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");
|
|
4119
|
-
} catch { throw new Error("roadmap milestone creation was not confirmed; preview again to recover its marker"); }
|
|
4120
|
-
effectCurrent();
|
|
4121
|
-
try { this.d.board.bindMirrorMilestone(repo, local, number); before = stamp(); }
|
|
4122
|
-
catch { throw new Error("roadmap milestone was created but its binding is uncertain; preview again to recover its marker"); }
|
|
4123
|
-
}
|
|
4124
|
-
effectCurrent();
|
|
4125
|
-
}
|
|
4126
|
-
return { repo, calls, bindings, fingerprint, applied: true };
|
|
4127
|
-
}
|
|
4128
|
-
|
|
4129
|
-
// ---- R3 (#1481): bottom-up placement. Reads are the roadmap read authority; every write below is the R1 writer, never a new one. ----
|
|
4130
|
-
|
|
4131
|
-
/** The one repository the roadmap reads from GitHub: the caller's choice, else the project's. Never derived from model text. */
|
|
4132
|
-
private roadmapRepo(raw: unknown): string | undefined {
|
|
4133
|
-
if (raw === undefined) return undefined;
|
|
4134
|
-
return this.roadmapParsed(() => githubRepo(raw));
|
|
4135
|
-
}
|
|
4136
|
-
|
|
4137
|
-
private roadmapGh(run?: SdlcGh): SdlcGh {
|
|
4138
|
-
return run ?? this.d.roadmapGh ?? this.d.sdlc?.gh ?? ((args, timeout, _cwd, bound) => sdlcGh(args, timeout, this.d.cwd, bound));
|
|
4139
|
-
}
|
|
4140
|
-
|
|
4141
|
-
/** Issues, tasks and specs that no live milestone places, each with its reason. Private tasks are counted and never named. */
|
|
4142
|
-
async roadmapUnplaced(by: PeerId, input: { repo?: unknown } = {}, run?: SdlcGh): Promise<UnplacedResult & { repo: string | null }> {
|
|
4143
|
-
this.roadmapReadAuthority(by);
|
|
4144
|
-
const repo = this.roadmapRepo(input.repo);
|
|
4145
|
-
let issues: Awaited<ReturnType<typeof readGitHubIssuePages>> | undefined;
|
|
4146
|
-
try { issues = await readGitHubIssuePages({ ...(repo === undefined ? {} : { repo }) }, this.roadmapGh(run)); } catch { issues = undefined; }
|
|
4147
|
-
this.roadmapReadAuthority(by);
|
|
4148
|
-
let specs: { id: string; title: string; status: string | null }[] | undefined;
|
|
4149
|
-
try { const list = this.d.specsList?.(); if (list && !list.truncated && list.errors === 0) specs = list.specs; } catch { specs = undefined; }
|
|
4150
|
-
const snapshot = this.roadmapSnapshot(by);
|
|
4151
|
-
const result = computeUnplaced({ milestones: snapshot.milestones, links: snapshot.links, tasks: snapshot.tasks, issues, specs, issueOf: snapshot.issueOf, privateTask: snapshot.privateTask, publicText: snapshot.publicText });
|
|
4152
|
-
return { ...result, repo: issues?.repo ?? repo ?? null };
|
|
4153
|
-
}
|
|
4154
|
-
|
|
4155
|
-
/** Pending and settled suggestions as a caller may read them: public text only. */
|
|
4156
|
-
milestoneSuggestions(by: PeerId, state?: MilestoneSuggestion["state"]): MilestoneSuggestion[] {
|
|
4157
|
-
this.roadmapReadAuthority(by);
|
|
4158
|
-
return this.d.board.suggestions(state).filter(row => this.suggestionPublic(row));
|
|
4159
|
-
}
|
|
4160
|
-
|
|
4161
|
-
private suggestionPublic(row: MilestoneSuggestion): boolean {
|
|
4162
|
-
const text = [row.ref, row.citeItem, row.citeMilestone ?? "", row.proposal?.title ?? "", row.proposal?.outcome ?? ""].join("\n");
|
|
4163
|
-
if (!this.publicMetadataText(text)) return false;
|
|
4164
|
-
if (row.kind !== "task") return true;
|
|
4165
|
-
const task = this.d.board.get(Number(row.ref));
|
|
4166
|
-
return task !== undefined && !this.isPii(task) && !task.signals.includes("pii");
|
|
4167
|
-
}
|
|
4168
|
-
|
|
4169
|
-
/**
|
|
4170
|
-
* Ask the hub's model where unplaced items belong. The model sees only public text, answers are checked against what it was shown
|
|
4171
|
-
* (ids offered, cited words present), saved as pending suggestions, and nothing is linked: that is `roadmapAccept`.
|
|
4172
|
-
*/
|
|
4173
|
-
async roadmapTriage(by: PeerId, input: { repo?: unknown } = {}, run?: SdlcGh): Promise<{ suggestions: MilestoneSuggestion[]; asked: number; dropped: number; partial: boolean; unavailable: string | null }> {
|
|
4174
|
-
const current = this.roadmapWriteAuthority(by);
|
|
4175
|
-
const unplaced = await this.roadmapUnplaced(by, input, run);
|
|
4176
|
-
current();
|
|
4177
|
-
const snapshot = this.roadmapSnapshot(by), views = milestoneViews(snapshot);
|
|
4178
|
-
const pending = new Set(this.d.board.suggestions("pending").map(row => `${row.kind}:${row.ref}`));
|
|
4179
|
-
const items: TriageItem[] = [
|
|
4180
|
-
...unplaced.tasks.map(row => ({ kind: "task" as const, ref: String(row.id), text: row.title })),
|
|
4181
|
-
...unplaced.issues.map(row => ({ kind: "issue" as const, ref: row.ref, text: row.title })),
|
|
4182
|
-
...unplaced.specs.map(row => ({ kind: "spec" as const, ref: row.id, text: row.title })),
|
|
4183
|
-
].filter(item => !pending.has(`${item.kind}:${item.ref}`));
|
|
4184
|
-
const live = views.filter(view => view.state !== "done" && view.state !== "dropped" && view.title !== "[withheld]");
|
|
4185
|
-
const batch = items.slice(0, TRIAGE_BATCH);
|
|
4186
|
-
const done = (suggestions: MilestoneSuggestion[], dropped: number, unavailable: string | null) => ({ suggestions, asked: batch.length, dropped, partial: unplaced.partial || items.length > batch.length, unavailable });
|
|
4187
|
-
if (!batch.length) return done([], 0, null);
|
|
4188
|
-
if (!this.d.roadmapModel) return done([], 0, "no hub model is configured for roadmap triage");
|
|
4189
|
-
const prompt = buildTriagePrompt(batch, live.map(view => ({ id: view.id, title: view.title, outcome: view.outcome })));
|
|
4190
|
-
const answer = await this.d.roadmapModel(prompt.system, prompt.user, () => { try { current(); return true; } catch { return false; } });
|
|
4191
|
-
current();
|
|
4192
|
-
if (!answer) return done([], 0, "the hub model gave no answer; retry ahub roadmap triage later");
|
|
4193
|
-
const parsed = parseTriage(answer, prompt), saved: MilestoneSuggestion[] = [], at = this.d.now?.() ?? Date.now();
|
|
4194
|
-
for (const row of parsed.suggestions) {
|
|
4195
|
-
// Re-screen at the write: what is stored is public planning text only, and a milestone that has since settled is not a target.
|
|
4196
|
-
if (row.milestone !== null) { const target = this.d.board.milestone(row.milestone); if (!target || ["done", "dropped"].includes(target.state)) continue; }
|
|
4197
|
-
const text = [row.ref, row.citeItem, row.citeMilestone ?? "", row.proposal?.title ?? "", row.proposal?.outcome ?? ""].join("\n");
|
|
4198
|
-
if (!this.publicMetadataText(text)) continue;
|
|
4199
|
-
if (this.screenOn() && (await this.screenCall(text)).label !== "clear") continue;
|
|
4200
|
-
current();
|
|
4201
|
-
// A model's answer, attributed to the hub (never to the asker), is advisory data: no ask or memory path reads this table.
|
|
4202
|
-
const made = this.d.board.addSuggestion(row, "hub", at);
|
|
4203
|
-
if (made) saved.push(made);
|
|
4204
|
-
}
|
|
4205
|
-
return done(saved, parsed.dropped + parsed.suggestions.length - saved.length, null);
|
|
4206
|
-
}
|
|
4207
|
-
|
|
4208
|
-
/**
|
|
4209
|
-
* R2 (#1480) part 1: ask the hub's model how one milestone decomposes. The model sees only the milestone's public text, the
|
|
4210
|
-
* 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
|
|
4211
|
-
* model answer. Nothing is intaken, linked, published or accepted here.
|
|
4212
|
-
*/
|
|
4213
|
-
async roadmapDecompose(by: PeerId, rawId: unknown, run?: SdlcGh): Promise<{ milestone: number; parts: DecomposePart[]; dropped: number; saved: MilestoneDecomposition | null; unavailable: string | null }> {
|
|
4214
|
-
const current = this.roadmapWriteAuthority(by);
|
|
4215
|
-
const id = this.roadmapParsed(() => milestoneId(rawId)), view = this.milestoneShow(by, id);
|
|
4216
|
-
current();
|
|
4217
|
-
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");
|
|
4218
|
-
const done = (parts: DecomposePart[], dropped: number, saved: MilestoneDecomposition | null, unavailable: string | null) => ({ milestone: id, parts, dropped, saved, unavailable });
|
|
4219
|
-
const publicText = (value: string): boolean => { try { return this.publicMetadataText(value); } catch { return false; } };
|
|
4220
|
-
let rows: { id: string; title: string; status: string | null; type?: string; paths?: string[] }[] | undefined;
|
|
4221
|
-
try { const list = this.d.specsList?.(); if (list && !list.truncated && list.errors === 0) rows = list.specs; } catch { rows = undefined; }
|
|
4222
|
-
const linked = new Set(view.specs.map(row => row.id));
|
|
4223
|
-
// Every field that enters the prompt passes the same public screen R3's unplaced list uses; a spec that fails it is not
|
|
4224
|
-
// offered at all, exactly as an unplaced spec is dropped from triage.
|
|
4225
|
-
const summaries = (rows ?? []).filter(row => linked.has(row.id)
|
|
4226
|
-
&& [row.id, row.title, ...(row.type ? [row.type] : []), ...(row.status ? [row.status] : []), ...(row.paths ?? []).slice(0, DECOMPOSE_PATHS)].every(publicText));
|
|
4227
|
-
// The milestone's own context is the goal and architecture specs it links; when it links only other types, those are its context.
|
|
4228
|
-
const top = summaries.filter(row => row.type === "goal" || row.type === "architecture");
|
|
4229
|
-
const specs: DecomposeItem[] = (top.length ? top : summaries).map(row => ({ ref: row.id, label: `spec ${row.id}`,
|
|
4230
|
-
text: `${row.title} (${row.type || "spec"}${row.status ? `, ${row.status}` : ""})${row.paths?.length ? ` covers: ${row.paths.slice(0, DECOMPOSE_PATHS).join(", ")}` : ""}` }));
|
|
4231
|
-
// Titles for linked issues come from the same bounded page read R3 uses. A ref outside that repository, an unreadable
|
|
4232
|
-
// 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
|
|
4233
|
-
// links are the only source of refs.
|
|
4234
|
-
const refs = view.issues.map(row => row.ref), first = refs.length ? /^([^#]+)#[1-9][0-9]*$/.exec(refs[0]!)![1]! : undefined;
|
|
4235
|
-
const titles = new Map<string, string>();
|
|
4236
|
-
if (first !== undefined) {
|
|
4237
|
-
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); }
|
|
4238
|
-
catch { /* unavailable titles are not an empty list: the ref is still offered */ }
|
|
4239
|
-
}
|
|
4240
|
-
const issues: DecomposeItem[] = refs.map(ref => ({ ref, label: `issue ${ref}`, text: titles.get(ref) ?? "" }));
|
|
4241
|
-
if (!specs.length && !issues.length) return done([], 0, null, "the milestone links no spec or issue to decompose from");
|
|
4242
|
-
if (!this.d.roadmapModel) return done([], 0, null, "no hub model is configured for roadmap decompose");
|
|
4243
|
-
const prompt = buildDecomposePrompt({ milestone: { id, title: view.title, outcome: view.outcome }, specs: specs.slice(0, DECOMPOSE_ITEMS), issues: issues.slice(0, DECOMPOSE_ITEMS) });
|
|
4244
|
-
const answer = await this.d.roadmapModel(prompt.system, prompt.user, () => { try { current(); return true; } catch { return false; } });
|
|
4245
|
-
current();
|
|
4246
|
-
if (!answer) return done([], 0, null, "the hub model gave no answer; retry ahub roadmap decompose later");
|
|
4247
|
-
const parsed = parseDecomposition(answer, prompt), kept: DecomposePart[] = [];
|
|
4248
|
-
for (const part of parsed.parts) {
|
|
4249
|
-
// Re-screen at the write, exactly as triage does: what is stored is public planning text only.
|
|
4250
|
-
const text = [part.title, part.detail, ...part.cites].join("\n");
|
|
4251
|
-
if (!this.publicMetadataText(text)) continue;
|
|
4252
|
-
if (this.screenOn() && (await this.screenCall(text)).label !== "clear") continue;
|
|
4253
|
-
current(); kept.push(part);
|
|
4254
|
-
}
|
|
4255
|
-
const dropped = parsed.dropped + parsed.parts.length - kept.length;
|
|
4256
|
-
if (!kept.length) return done([], dropped, null, null);
|
|
4257
|
-
const saved = this.d.board.addDecomposition({ milestone: id, parts: kept }, HUB, this.d.now?.() ?? Date.now());
|
|
4258
|
-
return done(kept, dropped, saved, null);
|
|
4259
|
-
}
|
|
4260
|
-
|
|
4261
|
-
/**
|
|
4262
|
-
* R2 (#1480) part 2: accept one proposed part as a held intake draft. The draft is the existing intake hold (`draft` and
|
|
4263
|
-
* `backlog`): nothing offers, pulls or routes it until the person approves it with `ahub intake approve`, and this path grants
|
|
4264
|
-
* no new release authority. It carries the milestone link and the part's `spec`/`task` kind, each part is accepted on its own,
|
|
4265
|
-
* 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
|
|
4266
|
-
* reads `[withheld]` and no notice repeats the part's words. One accept per part runs at a time: a concurrent caller waits for
|
|
4267
|
-
* the attempt in flight and then reads the accept row, so two accepts of one part cannot make two drafts.
|
|
4268
|
-
*/
|
|
4269
|
-
async roadmapDecomposePart(by: PeerId, rawId: unknown, rawPart: unknown): Promise<{ milestone: number; part: number; intake: DecomposeIntake; task: Record<string, unknown>; created: boolean }> {
|
|
4270
|
-
const current = this.roadmapWriteAuthority(by);
|
|
4271
|
-
const id = this.roadmapParsed(() => milestoneId(rawId)), part = this.roadmapParsed(() => milestoneId(rawPart));
|
|
4272
|
-
const view = this.milestoneShow(by, id);
|
|
4273
|
-
current();
|
|
4274
|
-
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");
|
|
4275
|
-
const pending = this.d.board.pendingDecomposition(id);
|
|
4276
|
-
if (!pending) throw new PreEffectToolRefusal(`milestone ${id} has no pending decomposition; run ahub roadmap decompose ${id} first`);
|
|
4277
|
-
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`);
|
|
4278
|
-
const chosen = pending.parts[part - 1]!;
|
|
4279
|
-
// A retry reads the draft the first accept made, and records the link again if an interrupted tail lost it.
|
|
4280
|
-
const earlier = this.roadmapAcceptedPart(by, id, pending.id, part);
|
|
4281
|
-
if (earlier) return earlier;
|
|
4282
|
-
const taskClass = CLASSES.includes(chosen.class as TaskClass) ? chosen.class as TaskClass : undefined;
|
|
4283
|
-
if (!taskClass) throw new PreEffectToolRefusal(`part ${part} names no hub task class; run ahub roadmap decompose ${id} to replace the answer`);
|
|
4284
|
-
// A milestone settled while its answer was pending refuses here, before any write. The same check runs again where the link
|
|
4285
|
-
// is written, and there it is best-effort: the draft is durable by then.
|
|
4286
|
-
this.roadmapCurrent(id);
|
|
4287
|
-
current();
|
|
4288
|
-
// One accept per part: a concurrent caller of the same part waits for the attempt in flight and then reads the accept row.
|
|
4289
|
-
const key = `${pending.id}:${part}`, running = this.decompositionAccepts.get(key);
|
|
4290
|
-
if (running) {
|
|
4291
|
-
await running.catch(() => undefined);
|
|
4292
|
-
const after = this.roadmapAcceptedPart(by, id, pending.id, part);
|
|
4293
|
-
if (after) return after;
|
|
4294
|
-
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`);
|
|
4295
|
-
}
|
|
4296
|
-
const attempt = this.acceptDecompositionPartOnce(by, id, part, pending, chosen, taskClass);
|
|
4297
|
-
this.decompositionAccepts.set(key, attempt);
|
|
4298
|
-
try { return await attempt; } finally { if (this.decompositionAccepts.get(key) === attempt) this.decompositionAccepts.delete(key); }
|
|
4299
|
-
}
|
|
4300
|
-
|
|
4301
|
-
/** The accept row's own draft, while that task exists: the retry's answer, with the milestone link recorded again. */
|
|
4302
|
-
private roadmapAcceptedPart(by: PeerId, id: number, decomposition: number, part: number): { milestone: number; part: number; intake: DecomposeIntake; task: Record<string, unknown>; created: boolean } | undefined {
|
|
4303
|
-
const accepted = this.d.board.decompositionAccept(decomposition, part), earlier = accepted ? this.d.board.get(accepted.task) : undefined;
|
|
4304
|
-
if (!accepted || !earlier) return undefined;
|
|
4305
|
-
// Idempotent, so a missing link heals here; a milestone settled since refuses that as a notice, never as the caller's refusal.
|
|
4306
|
-
this.releaseNotice(`task #${earlier.id}: milestone ${id} part ${part} accepted without its milestone link`, () => {
|
|
4307
|
-
const milestone = this.roadmapCurrent(id);
|
|
4308
|
-
this.d.board.linkMilestone(id, "task", String(earlier.id), by, milestone.revision, this.d.now?.() ?? Date.now());
|
|
4309
|
-
});
|
|
4310
|
-
return { milestone: id, part, intake: accepted.intake, task: this.publicView(earlier), created: false };
|
|
4311
|
-
}
|
|
4312
|
-
|
|
4313
|
-
/** One accept attempt: the durable draft, then a tail that records the hold and never refuses the caller. */
|
|
4314
|
-
private async acceptDecompositionPartOnce(by: PeerId, id: number, part: number, pending: MilestoneDecomposition, chosen: DecomposePart, taskClass: TaskClass): Promise<{ milestone: number; part: number; intake: DecomposeIntake; task: Record<string, unknown>; created: boolean }> {
|
|
4315
|
-
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 });
|
|
4316
|
-
// 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
|
|
4317
|
-
// accept row, the milestone link and the notice are best-effort in that order.
|
|
4318
|
-
this.incomingBacklog.delete(draft.id);
|
|
4319
|
-
this.releaseNotice(`task #${draft.id}: milestone ${id} part ${part} accepted without its accept record`, () => {
|
|
4320
|
-
this.d.board.acceptDecompositionPart({ decomposition: pending.id, milestone: id, part, task: draft.id, intake: chosen.intake }, by, this.d.now?.() ?? Date.now());
|
|
4321
|
-
});
|
|
4322
|
-
this.releaseNotice(`task #${draft.id}: milestone ${id} part ${part} accepted without its milestone link`, () => {
|
|
4323
|
-
const milestone = this.roadmapCurrent(id);
|
|
4324
|
-
this.d.board.linkMilestone(id, "task", String(draft.id), by, milestone.revision, this.d.now?.() ?? Date.now());
|
|
4325
|
-
});
|
|
4326
|
-
this.releaseNotice(`task #${draft.id}: milestone ${id} part ${part} accepted as a held intake draft`);
|
|
4327
|
-
return { milestone: id, part, intake: chosen.intake, task: this.publicView(this.d.board.get(draft.id) ?? draft), created: true };
|
|
4328
|
-
}
|
|
4329
|
-
|
|
4330
|
-
/** The held draft's detail: the part's own words, then the one line a person reads before releasing it. */
|
|
4331
|
-
private decompositionDraftDetail(part: DecomposePart, milestone: number, index: number, total: number): string {
|
|
4332
|
-
const kind = part.intake === "spec" ? "needs its own spec issue before implementation" : "a mechanical chore that goes straight to a task";
|
|
4333
|
-
return [part.detail, `Milestone ${milestone} part ${index} of ${total}: ${kind}. Cites: ${part.cites.join(", ")}.`, `Held until released: ahub intake approve`].join("\n\n");
|
|
4334
|
-
}
|
|
4335
|
-
|
|
4336
|
-
/**
|
|
4337
|
-
* R2 (#1480) part 3: publish the milestone's held drafts to GitHub. `--publish` plans one issue per held `spec` part from a
|
|
4338
|
-
* complete reading of the holds and writes nothing; apply creates each issue through one gh call and links it to the
|
|
4339
|
-
* milestone: R1's own `issue` link, and the R4 membership field the create carries when the mirror has a binding, so this
|
|
4340
|
-
* 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
|
|
4341
|
-
* is only counted, and a refused or unconfirmed call leaves the draft held and names the failure.
|
|
4342
|
-
*/
|
|
4343
|
-
async roadmapDecomposePublish(by: PeerId, rawId: unknown, input: { apply?: boolean; confirm?: string } = {}): Promise<{
|
|
4344
|
-
milestone: number; repo: string; githubMilestone: number | null; parts: PublishPlanPart[]; calls: string[][];
|
|
4345
|
-
skippedPrivate: number; skippedUnknown: number; fingerprint: string; applied: boolean; created: { part: number; task: number; issue: number }[];
|
|
4346
|
-
}> {
|
|
4347
|
-
const current = this.roadmapWriteAuthority(by);
|
|
4348
|
-
if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => key !== "apply" && key !== "confirm")
|
|
4349
|
-
|| input.apply !== undefined && typeof input.apply !== "boolean"
|
|
4350
|
-
|| input.confirm !== undefined && (typeof input.confirm !== "string" || !/^[a-f0-9]{64}$/.test(input.confirm)))
|
|
4351
|
-
throw new PreEffectToolRefusal("invalid roadmap publish options; preview with ahub roadmap decompose <id> --publish before applying");
|
|
4352
|
-
if (input.apply && input.confirm === undefined) throw new PreEffectToolRefusal("roadmap decompose --apply needs its preview fingerprint; preview with ahub roadmap decompose <id> --publish first");
|
|
4353
|
-
if (input.apply) this.roadmapApplyAuthority(by);
|
|
4354
|
-
const id = this.roadmapParsed(() => milestoneId(rawId)), view = this.milestoneShow(by, id);
|
|
4355
|
-
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");
|
|
4356
|
-
// A milestone settled while its drafts are held refuses here, before any read of GitHub or any write.
|
|
4357
|
-
this.roadmapCurrent(id);
|
|
4358
|
-
current();
|
|
4359
|
-
const repo = this.roadmapRepository(), config = this.d.roadmapConfig?.() ?? { github_mirror: false, github_write: "off" as const };
|
|
4360
|
-
// The GitHub milestone comes from the mirror binding, never from an argument; with the mirror off nothing is attached.
|
|
4361
|
-
const githubMilestone = config.github_mirror ? this.d.board.mirrorMilestone(repo, id) ?? null : null;
|
|
4362
|
-
const drafts: PublishDraft[] = [], held = new Map<number, DecompositionAccept>();
|
|
4363
|
-
let skippedPrivate = 0, skippedUnknown = 0;
|
|
4364
|
-
for (const accept of this.d.board.decompositionAcceptsFor(id)) {
|
|
4365
|
-
const task = this.d.board.get(accept.task);
|
|
4366
|
-
if (!task) continue;
|
|
4367
|
-
const part = this.d.board.decomposition(accept.decomposition)?.parts[accept.part - 1];
|
|
4368
|
-
// Without the answer a part's own words are gone; the draft stays held and the preview says to propose the parts again.
|
|
4369
|
-
const text = part ? [part.title, part.detail, ...part.cites].join("\n") : "";
|
|
4370
|
-
let privatePart = true;
|
|
4371
|
-
try { privatePart = this.isPii(task) || !part || !this.publicMetadataText(text); } catch { privatePart = true; }
|
|
4372
|
-
if (part && !privatePart && this.screenOn()) { const label = (await this.screenCall(text)).label; current(); privatePart = label !== "clear"; }
|
|
4373
|
-
if (!part) { skippedUnknown++; continue; }
|
|
4374
|
-
if (privatePart) { skippedPrivate++; continue; }
|
|
4375
|
-
held.set(task.id, accept);
|
|
4376
|
-
drafts.push({ part: accept.part, task: task.id, intake: accept.intake, title: part.title, detail: part.detail, cites: part.cites,
|
|
4377
|
-
published: this.d.board.decompositionPublish(accept.decomposition, accept.part) ?? null,
|
|
4378
|
-
hold: task.draft === true && task.state === "backlog" ? "held" : "released" });
|
|
4379
|
-
}
|
|
4380
|
-
const planned = planPartPublish({ project: this.d.project, repo, milestone: id, githubMilestone, parts: drafts });
|
|
4381
|
-
const fingerprint = createHash("sha256").update(JSON.stringify({ repo, milestone: id, githubMilestone, calls: planned.calls })).digest("hex");
|
|
4382
|
-
const reply = { milestone: id, repo, githubMilestone, ...planned, skippedPrivate, skippedUnknown, fingerprint, applied: false as boolean, created: [] as { part: number; task: number; issue: number }[] };
|
|
4383
|
-
if (!input.apply) return reply;
|
|
4384
|
-
if (input.confirm !== fingerprint) throw new PreEffectToolRefusal(`roadmap publish preview changed; run ahub roadmap decompose ${id} --publish and retry with --confirm ${fingerprint}`);
|
|
4385
|
-
current(); this.roadmapApplyAuthority(by); if (this.roadmapRepository() !== repo) throw new PreEffectToolRefusal("roadmap GitHub origin changed; preview the publish again");
|
|
4386
|
-
// A retried call whose first attempt is still creating must not POST every planned issue again: `INSERT OR IGNORE` would keep
|
|
4387
|
-
// the first publish row and GitHub would keep both issues. One apply per milestone, refused with the next step it can take.
|
|
4388
|
-
if (this.roadmapPublishes.has(id))
|
|
4389
|
-
throw new PreEffectToolRefusal(`a publish for milestone ${id} is already running; wait for it to finish and run ahub roadmap decompose ${id} --publish again`);
|
|
4390
|
-
this.roadmapPublishes.add(id);
|
|
4391
|
-
try {
|
|
4392
|
-
const creating = planned.parts.filter(row => row.action === "create"), created = reply.created;
|
|
4393
|
-
for (const [index, call] of planned.calls.entries()) {
|
|
4394
|
-
const row = creating[index]!, accept = held.get(row.task)!;
|
|
4395
|
-
// A part an earlier attempt already recorded has its issue: never POST it a second time.
|
|
4396
|
-
if (this.d.board.decompositionPublish(accept.decomposition, row.part) !== undefined) continue;
|
|
4397
|
-
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`;
|
|
4398
|
-
let result: Awaited<ReturnType<SdlcGh>>;
|
|
4399
|
-
try { result = await this.roadmapGh()(call, 10_000, undefined, 64 * 1024); }
|
|
4400
|
-
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`); }
|
|
4401
|
-
if (result.code !== 0 || Buffer.byteLength(result.stdout) > 64 * 1024) throw new Error(refused);
|
|
4402
|
-
let issue: number;
|
|
4403
|
-
try {
|
|
4404
|
-
const made = JSON.parse(result.stdout) as Record<string, unknown>;
|
|
4405
|
-
issue = milestoneId(made.number);
|
|
4406
|
-
if (made.title !== call.find(value => value.startsWith("title="))?.slice(6)
|
|
4407
|
-
|| typeof made.html_url !== "string" || made.html_url.toLowerCase() !== `https://github.com/${repo}/issues/${issue}`) throw new Error("mismatch");
|
|
4408
|
-
} 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`); }
|
|
4409
|
-
// The issue exists, so nothing below may refuse the caller: the publish record and the milestone link are best effort.
|
|
4410
|
-
this.releaseNotice(`milestone ${id} part ${row.part}: issue ${repo}#${issue} created without its publish record`, () => {
|
|
4411
|
-
this.d.board.recordDecompositionPublish({ decomposition: accept.decomposition, milestone: id, part: row.part, issue }, by, this.d.now?.() ?? Date.now());
|
|
4412
|
-
});
|
|
4413
|
-
this.releaseNotice(`milestone ${id} part ${row.part}: issue ${repo}#${issue} created without its milestone link`, () => {
|
|
4414
|
-
const milestone = this.roadmapCurrent(id);
|
|
4415
|
-
this.d.board.linkMilestone(id, "issue", `${repo}#${issue}`, by, milestone.revision, this.d.now?.() ?? Date.now());
|
|
4416
|
-
});
|
|
4417
|
-
created.push({ part: row.part, task: row.task, issue });
|
|
4418
|
-
}
|
|
4419
|
-
reply.applied = true;
|
|
4420
|
-
return reply;
|
|
4421
|
-
} finally { this.roadmapPublishes.delete(id); }
|
|
4422
|
-
}
|
|
4423
|
-
|
|
4424
|
-
/** Apply one suggestion through R1's own writers. A "new milestone" suggestion creates it first; a retry never creates a second. */
|
|
4425
|
-
async roadmapAccept(by: PeerId, rawId: unknown): Promise<{ suggestion: MilestoneSuggestion; milestone: MilestoneView }> {
|
|
4426
|
-
const current = this.roadmapWriteAuthority(by);
|
|
4427
|
-
const id = this.roadmapParsed(() => milestoneId(rawId)), row = this.d.board.suggestion(id);
|
|
4428
|
-
if (!row) throw new PreEffectToolRefusal("roadmap suggestion does not exist; use ahub roadmap triage");
|
|
4429
|
-
if (row.state !== "pending") throw new PreEffectToolRefusal(`roadmap suggestion was already ${row.state}; run ahub roadmap triage for current suggestions`);
|
|
4430
|
-
if (!this.suggestionPublic(row)) throw new PreEffectToolRefusal("roadmap suggestion text is no longer public; reject it with ahub roadmap reject");
|
|
4431
|
-
let target = row.milestone ?? this.d.board.suggestionCreated(id);
|
|
4432
|
-
if (target === undefined) {
|
|
4433
|
-
const proposal = row.proposal;
|
|
4434
|
-
if (!proposal) throw new PreEffectToolRefusal("roadmap suggestion has no target; reject it with ahub roadmap reject");
|
|
4435
|
-
const fields = this.roadmapParsed(() => parseMilestoneInput({ title: proposal.title, outcome: proposal.outcome }));
|
|
4436
|
-
await this.roadmapScreen(fields); current();
|
|
4437
|
-
const made = this.d.board.newMilestone(fields, by, this.d.now?.() ?? Date.now());
|
|
4438
|
-
this.d.board.setSuggestionCreated(id, made.id); target = made.id;
|
|
4439
|
-
}
|
|
4440
|
-
const milestone = this.roadmapCurrent(target);
|
|
4441
|
-
const ref = this.roadmapParsed(() => milestoneLinkRef(row.kind, row.ref));
|
|
4442
|
-
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");
|
|
4443
|
-
current();
|
|
4444
|
-
this.d.board.linkMilestone(target, row.kind, ref, by, milestone.revision, this.d.now?.() ?? Date.now());
|
|
4445
|
-
const settled = this.d.board.settleSuggestion(id, "accepted", by, this.d.now?.() ?? Date.now());
|
|
4446
|
-
return { suggestion: settled, milestone: this.roadmapResult(by, target) };
|
|
4447
|
-
}
|
|
4448
|
-
|
|
4449
|
-
roadmapReject(by: PeerId, rawId: unknown): MilestoneSuggestion {
|
|
4450
|
-
this.roadmapWriteAuthority(by);
|
|
4451
|
-
const id = this.roadmapParsed(() => milestoneId(rawId));
|
|
4452
|
-
return this.d.board.settleSuggestion(id, "rejected", by, this.d.now?.() ?? Date.now());
|
|
4453
|
-
}
|
|
4454
|
-
|
|
4455
|
-
/**
|
|
4456
|
-
* One-time import of open GitHub milestones as `proposed` milestones, linking their open issues. A dry run unless `apply`.
|
|
4457
|
-
* A repeat finds each milestone's import mark and each link, so a second `apply` changes nothing. Nothing is ever written to GitHub.
|
|
4458
|
-
*/
|
|
4459
|
-
async roadmapImportGitHub(by: PeerId, input: { repo?: unknown; apply?: unknown } = {}, run?: SdlcGh): Promise<{
|
|
4460
|
-
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;
|
|
4461
|
-
}> {
|
|
4462
|
-
const current = this.roadmapWriteAuthority(by);
|
|
4463
|
-
if (by !== USER) throw new PreEffectToolRefusal("GitHub milestone import is a console command; ask the person to run ahub roadmap import-github");
|
|
4464
|
-
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");
|
|
4465
|
-
const apply = input.apply === true, gh = this.roadmapGh(run), repoInput = this.roadmapRepo(input.repo);
|
|
4466
|
-
const milestonePages = await readGitHubMilestonePages({ ...(repoInput === undefined ? {} : { repo: repoInput }) }, gh);
|
|
4467
|
-
const issuePages = await readGitHubIssuePages({ repo: milestonePages.repo }, gh);
|
|
4468
|
-
current();
|
|
4469
|
-
const issuesOf = new Map<number, string[]>();
|
|
4470
|
-
for (const row of issuePages.rows) if (row.milestone !== null) issuesOf.set(row.milestone, [...(issuesOf.get(row.milestone) ?? []), `${issuePages.repo}#${row.number}`]);
|
|
4471
|
-
const out: { number: number; title: string; milestone: number | null; action: "create" | "exists"; issues: string[]; newLinks: number }[] = [];
|
|
4472
|
-
let created = 0, linked = 0, withheld = 0;
|
|
4473
|
-
for (const source of milestonePages.rows) {
|
|
4474
|
-
const description = source.description || `Imported from GitHub milestone ${milestonePages.repo}#milestone/${source.number}`;
|
|
4475
|
-
let fields: ReturnType<typeof parseMilestoneInput>;
|
|
4476
|
-
try { fields = parseMilestoneInput({ title: source.title, outcome: description.slice(0, 4000), ...(source.due ? { target: source.due } : {}) }); }
|
|
4477
|
-
catch { withheld++; continue; }
|
|
4478
|
-
const prior = this.d.board.importedMilestone(milestonePages.repo, source.number), existing = prior === undefined ? undefined : this.d.board.milestone(prior);
|
|
4479
|
-
const refs = (issuesOf.get(source.number) ?? []).filter(ref => this.publicMetadataText(ref));
|
|
4480
|
-
const have = new Set(existing ? this.d.board.milestoneLinks(existing.id).filter(link => link.kind === "issue").map(link => link.ref) : []);
|
|
4481
|
-
const newRefs = refs.filter(ref => !have.has(ref));
|
|
4482
|
-
const text = `${fields.title}\n${fields.outcome}`;
|
|
4483
|
-
if (!this.publicMetadataText(text)) { withheld++; continue; }
|
|
4484
|
-
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 };
|
|
4485
|
-
if (apply) {
|
|
4486
|
-
// The model screen runs on apply only, for a milestone about to be created; a dry run lists what passes the pattern screen.
|
|
4487
|
-
if (!existing && this.screenOn() && (await this.screenCall(text)).label !== "clear") { withheld++; continue; }
|
|
4488
|
-
current();
|
|
4489
|
-
const made = this.d.board.importMilestone(milestonePages.repo, source.number, fields, by, this.d.now?.() ?? Date.now());
|
|
4490
|
-
if (made.created) created++;
|
|
4491
|
-
row.milestone = made.milestone.id;
|
|
4492
|
-
for (const ref of newRefs) {
|
|
4493
|
-
const live = this.d.board.milestone(made.milestone.id)!;
|
|
4494
|
-
// A settled milestone is final: an import never reopens or relinks it.
|
|
4495
|
-
if (["done", "dropped"].includes(live.state)) break;
|
|
4496
|
-
const before = this.d.board.milestoneLinks(made.milestone.id).length;
|
|
4497
|
-
this.d.board.linkMilestone(made.milestone.id, "issue", ref, by, live.revision, this.d.now?.() ?? Date.now());
|
|
4498
|
-
if (this.d.board.milestoneLinks(made.milestone.id).length > before) linked++;
|
|
4499
|
-
}
|
|
4500
|
-
}
|
|
4501
|
-
out.push(row);
|
|
4502
|
-
}
|
|
4503
|
-
return { repo: milestonePages.repo, apply, partial: milestonePages.partial || issuePages.partial, milestones: out, created, linked, withheld };
|
|
4504
|
-
}
|
|
4505
|
-
|
|
3136
|
+
private roadmapReadAuthority(by: PeerId): void { return this.roadmap.roadmapReadAuthority(by); }
|
|
3137
|
+
private roadmapWriteAuthority(by: PeerId): () => void { return this.roadmap.roadmapWriteAuthority(by); }
|
|
3138
|
+
private roadmapParsed<T>(read: () => T): T { return this.roadmap.roadmapParsed(read); }
|
|
3139
|
+
private roadmapCurrent(id: unknown, state?: MilestoneState): Milestone { return this.roadmap.roadmapCurrent(id, state); }
|
|
3140
|
+
private async roadmapScreen(fields: MilestonePatch): Promise<void> { return this.roadmap.roadmapScreen(fields); }
|
|
3141
|
+
private roadmapResult(by: PeerId, id: number): MilestoneView { return this.roadmap.roadmapResult(by, id); }
|
|
3142
|
+
async milestoneNew(by: PeerId, raw: unknown): Promise<MilestoneView> { return this.roadmap.milestoneNew(by, raw); }
|
|
3143
|
+
async milestoneEdit(by: PeerId, id: number, revision: number, raw: unknown): Promise<MilestoneView> { return this.roadmap.milestoneEdit(by, id, revision, raw); }
|
|
3144
|
+
milestoneLink(by: PeerId, id: number, kind: MilestoneLinkKind, raw: string): MilestoneView { return this.roadmap.milestoneLink(by, id, kind, raw); }
|
|
3145
|
+
milestoneUnlink(by: PeerId, id: number, kind: MilestoneLinkKind, raw: string): MilestoneView { return this.roadmap.milestoneUnlink(by, id, kind, raw); }
|
|
3146
|
+
milestoneOrder(by: PeerId, id: number, order: number): MilestoneView { return this.roadmap.milestoneOrder(by, id, order); }
|
|
3147
|
+
milestoneState(by: PeerId, id: number, state: MilestoneState): MilestoneView { return this.roadmap.milestoneState(by, id, state); }
|
|
3148
|
+
private roadmapSnapshot(by: PeerId, specs?: () => SpecsCheckReport | SpecsCoverReport | undefined): RoadmapSnapshot { return this.roadmap.roadmapSnapshot(by, specs); }
|
|
3149
|
+
milestoneList(by: PeerId, specs?: () => SpecsCheckReport | SpecsCoverReport | undefined): (MilestoneView & { tree: TreeRollup; readyToClose: ReadyToClose })[] { return this.roadmap.milestoneList(by, specs); }
|
|
3150
|
+
milestoneShow(by: PeerId, id: number): MilestoneView { return this.roadmap.milestoneShow(by, id); }
|
|
3151
|
+
private roadmapRepository(): string { return this.roadmap.roadmapRepository(); }
|
|
3152
|
+
private roadmapApplyAuthority(by: PeerId): void { return this.roadmap.roadmapApplyAuthority(by); }
|
|
3153
|
+
async roadmapExport(by: PeerId, input: { issue?: number; apply?: boolean; confirm?: string } = {}): Promise<{ json: string; markdown: string; fingerprint: string; call?: string[]; applied: boolean }> { return this.roadmap.roadmapExport(by, input); }
|
|
3154
|
+
async roadmapCheck(by: PeerId, include?: (finding: RoadmapDrift) => boolean): Promise<ReturnType<typeof checkRoadmap>> { return this.roadmap.roadmapCheck(by, include); }
|
|
3155
|
+
async roadmapNotify(taskIds: readonly number[], send: (task: number, milestone: number | null, rule: number, marker: string) => boolean): Promise<number> { return this.roadmap.roadmapNotify(taskIds, send); }
|
|
3156
|
+
private proposalReason(value: unknown): TaskReason | undefined { return this.roadmap.proposalReason(value); }
|
|
3157
|
+
private parallelSiblingsDisjoint(by: PeerId, title: string, refs: TaskRefs, deps: number[]): void { return this.roadmap.parallelSiblingsDisjoint(by, title, refs, deps); }
|
|
3158
|
+
async roadmapSync(by: PeerId, input: { apply?: boolean; confirm?: string } = {}): Promise<{ repo: string; calls: string[][]; bindings: { milestone: number; number: number }[]; fingerprint: string; applied: boolean }> { return this.roadmap.roadmapSync(by, input); }
|
|
3159
|
+
private roadmapRepo(raw: unknown): string | undefined { return this.roadmap.roadmapRepo(raw); }
|
|
3160
|
+
private roadmapGh(run?: SdlcGh): SdlcGh { return this.roadmap.roadmapGh(run); }
|
|
3161
|
+
async roadmapUnplaced(by: PeerId, input: { repo?: unknown } = {}, run?: SdlcGh): Promise<UnplacedResult & { repo: string | null }> { return this.roadmapPlan.roadmapUnplaced(by, input, run); }
|
|
3162
|
+
milestoneSuggestions(by: PeerId, state?: MilestoneSuggestion["state"]): MilestoneSuggestion[] { return this.roadmapPlan.milestoneSuggestions(by, state); }
|
|
3163
|
+
async roadmapTriage(by: PeerId, input: { repo?: unknown } = {}, run?: SdlcGh): Promise<{ suggestions: MilestoneSuggestion[]; asked: number; dropped: number; partial: boolean; unavailable: string | null }> { return this.roadmapPlan.roadmapTriage(by, input, run); }
|
|
3164
|
+
async roadmapDecompose(by: PeerId, rawId: unknown, run?: SdlcGh): Promise<{ milestone: number; parts: DecomposePart[]; dropped: number; saved: MilestoneDecomposition | null; unavailable: string | null }> { return this.roadmapPlan.roadmapDecompose(by, rawId, run); }
|
|
3165
|
+
async roadmapDecomposePart(by: PeerId, rawId: unknown, rawPart: unknown): Promise<{ milestone: number; part: number; intake: DecomposeIntake; task: Record<string, unknown>; created: boolean }> { return this.roadmapPlan.roadmapDecomposePart(by, rawId, rawPart); }
|
|
3166
|
+
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 }[]; }> { return this.roadmapPlan.roadmapDecomposePublish(by, rawId, input); }
|
|
3167
|
+
async roadmapAccept(by: PeerId, rawId: unknown): Promise<{ suggestion: MilestoneSuggestion; milestone: MilestoneView }> { return this.roadmapPlan.roadmapAccept(by, rawId); }
|
|
3168
|
+
roadmapReject(by: PeerId, rawId: unknown): MilestoneSuggestion { return this.roadmapPlan.roadmapReject(by, rawId); }
|
|
3169
|
+
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; }> { return this.roadmapPlan.roadmapImportGitHub(by, input, run); }
|
|
4506
3170
|
releaseList(by: PeerId): Record<string, unknown>[] {
|
|
4507
3171
|
this.planningAuthority(by);
|
|
4508
3172
|
const scopes = new Map<number, { id: number; state: Task["state"]; deps: number[] }[]>();
|
|
@@ -6230,180 +4894,14 @@ export class Tasks {
|
|
|
6230
4894
|
// Advice joins the planner's next delivery; it must not manufacture a turn beside a withheld backlog batch.
|
|
6231
4895
|
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)));
|
|
6232
4896
|
}
|
|
6233
|
-
private synthesisTask(by: PeerId, id: unknown): Task {
|
|
6234
|
-
requireLocalTaskPeer(by);
|
|
6235
|
-
if (this.d.profile !== "research") throw new PreEffectToolRefusal("synthesis evidence is research-only; use a research profile and a visible task");
|
|
6236
|
-
const task = this.studyParent(this.studyNumber(id, "taskId"));
|
|
6237
|
-
if (task.profile !== "research" || by !== USER && !taskShowAllowed(by, task, this.d.roles, this.isConfiguredPlanner(by)))
|
|
6238
|
-
throw new PreEffectToolRefusal("synthesis task unavailable; use a research task visible through hub_task_show");
|
|
6239
|
-
return task;
|
|
6240
|
-
}
|
|
6241
4897
|
|
|
6242
|
-
private synthesisPrivate(task: Task, by: PeerId): boolean {
|
|
6243
|
-
try { return !!this.d.privateTurn?.(by) || this.isPii(task) || !this.publicMetadataText(JSON.stringify(task.plan?.claims ?? [])); }
|
|
6244
|
-
catch { return true; }
|
|
6245
|
-
}
|
|
6246
4898
|
|
|
6247
|
-
private synthesisPolicy(task: Task): string {
|
|
6248
|
-
let root: string | undefined;
|
|
6249
|
-
try { root = this.deliverablePorts(task).cwd; } catch { /* unknown is part of the fence */ }
|
|
6250
|
-
return JSON.stringify([this.d.profile, this.d.routing().signals, this.d.piiPaths, this.d.deny, root]);
|
|
6251
|
-
}
|
|
6252
4899
|
|
|
6253
|
-
private synthesisRows(links: readonly EvidenceLinkV1[]) {
|
|
6254
|
-
return links.map(link => ({ link, status: link.status === "withdrawn" ? "withdrawn" as const : "active" as const }));
|
|
6255
|
-
}
|
|
6256
4900
|
|
|
6257
|
-
private synthesisInventories(task: Task) {
|
|
6258
|
-
const claims = task.plan?.claims;
|
|
6259
|
-
if (!Array.isArray(claims) || claims.length > 50) throw new PreEffectToolRefusal("synthesis claims unavailable; refresh the task's bounded declared claim list");
|
|
6260
|
-
return claims.map((_claim, index) => {
|
|
6261
|
-
const identity = taskClaimIdentity(task, index + 1);
|
|
6262
|
-
try {
|
|
6263
|
-
const inventory = this.d.board.latestEvidenceLinks(this.d.project, task.id, identity.claimId, identity.claimRevision, 128);
|
|
6264
|
-
let contradictionHistory: ReturnType<Board["evidenceContradictionHistory"]> = { ids: [], sources: [], members: [], complete: false };
|
|
6265
|
-
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. */ }
|
|
6266
|
-
if (contradictionHistory.complete && contradictionHistory.sources.some(id => { try { return !this.d.evidenceSourceMeta?.(id); } catch { return true; } })) contradictionHistory.complete = false;
|
|
6267
|
-
return { ...identity, inventory, contradictionHistory };
|
|
6268
|
-
}
|
|
6269
|
-
catch { return { ...identity, inventory: { links: [] as EvidenceLinkV1[], complete: false }, contradictionHistory: { ids: [] as string[], sources: [] as string[], members: [] as string[], complete: false } }; }
|
|
6270
|
-
});
|
|
6271
|
-
}
|
|
6272
4901
|
|
|
6273
|
-
private synthesisSources(links: readonly Pick<EvidenceLinkV1, "sourceId">[]): { private: boolean; key: string; bytes: number } {
|
|
6274
|
-
const meta: unknown[] = [], seen = new Set<string>(); let bytes = 0;
|
|
6275
|
-
for (const link of links) {
|
|
6276
|
-
if (seen.has(link.sourceId)) continue; seen.add(link.sourceId);
|
|
6277
|
-
const source = (() => { try { return this.d.evidenceSourceMeta?.(link.sourceId) ?? this.studySource(link.sourceId); } catch { return undefined; } })();
|
|
6278
|
-
if (source?.private || source && !this.publicMetadataText(JSON.stringify(source))) return { private: true, key: "", bytes: 0 };
|
|
6279
|
-
meta.push([link.sourceId, source]);
|
|
6280
|
-
if (source && "bytes" in source && typeof source.bytes === "number") bytes += source.bytes;
|
|
6281
|
-
}
|
|
6282
|
-
return { private: false, key: createHash("sha256").update(JSON.stringify(meta)).digest("hex"), bytes };
|
|
6283
|
-
}
|
|
6284
4902
|
|
|
6285
|
-
/** Explicit authoring metadata only: no claim text, source identity, passage, origin or path. */
|
|
6286
|
-
async synthesisEvidence(by: PeerId, input: unknown) {
|
|
6287
|
-
const fields = this.studyFields(input, ["taskId"]), check = this.requestCheck(by, () => this.studyHold());
|
|
6288
|
-
return this.studyWrite(async () => {
|
|
6289
|
-
check(); const revision = this.d.board.statusRevision(), task = this.synthesisTask(by, fields.taskId);
|
|
6290
|
-
if (this.synthesisPrivate(task, by)) return { taskId: task.id, status: "private" as const };
|
|
6291
|
-
const claims = this.synthesisInventories(task), links = claims.flatMap(claim => [...claim.inventory.links, ...claim.contradictionHistory.sources.map(sourceId => ({ sourceId }))]);
|
|
6292
|
-
if (this.synthesisSources(links).private) return { taskId: task.id, status: "private" as const };
|
|
6293
|
-
const delivered = latestDeliverables(task.history) ?? [];
|
|
6294
|
-
const artifacts = delivered.filter(record => !record.private && record.path && !this.experimentOutputPrivate(task, record.path))
|
|
6295
|
-
.map(({ id, sha256, format }) => ({ id, sha256, format }));
|
|
6296
|
-
check();
|
|
6297
|
-
if (this.d.board.statusRevision() !== revision) return { taskId: task.id, status: "unavailable" as const, cause: "inventory_changed" };
|
|
6298
|
-
return { taskId: task.id, taskCreated: task.created, status: "available" as const, scope: "declared_inventory" as const,
|
|
6299
|
-
deliverables: artifacts, claims: claims.map(claim => {
|
|
6300
|
-
const binding = inventoryBinding(this.synthesisRows(claim.inventory.links), claim.inventory.complete, claim.contradictionHistory);
|
|
6301
|
-
return { claimId: claim.claimId, claimRevision: claim.claimRevision, complete: claim.inventory.complete && claim.contradictionHistory.complete,
|
|
6302
|
-
...(binding ? { inventory: binding } : {}), evidence: this.synthesisRows(claim.inventory.links).map(({ link, status }) => ({ id: link.id, revision: link.revision, status })) };
|
|
6303
|
-
}) };
|
|
6304
|
-
});
|
|
6305
|
-
}
|
|
6306
4903
|
|
|
6307
|
-
/** Deterministic, explicit and offline: no caller-supplied current state and no semantic/model judge. */
|
|
6308
|
-
async synthesisCheck(by: PeerId, input: unknown): Promise<SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }> {
|
|
6309
|
-
return this.synthesisInspect(by, input);
|
|
6310
|
-
}
|
|
6311
4904
|
|
|
6312
|
-
private synthesisInspect(by: PeerId, input: unknown): Promise<SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }>;
|
|
6313
|
-
private synthesisInspect(by: PeerId, input: unknown, onSnapshot: (manifest: SynthesisManifestV1, current: SynthesisCurrent, report: SynthesisReadiness, valid: () => boolean) => Task): Promise<Task | SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }>;
|
|
6314
|
-
private async synthesisInspect(by: PeerId, input: unknown, onSnapshot?: (manifest: SynthesisManifestV1, current: SynthesisCurrent, report: SynthesisReadiness, valid: () => boolean) => Task): Promise<Task | SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }> {
|
|
6315
|
-
const fields = this.studyFields(input, ["taskId", "manifest"]), manifest = parseSynthesisManifest(fields.manifest);
|
|
6316
|
-
if (fields.taskId !== manifest.taskId) throw new PreEffectToolRefusal("synthesis manifest names another task; refresh its task binding and retry");
|
|
6317
|
-
const check = this.requestCheck(by, () => this.studyHold());
|
|
6318
|
-
return this.studyWrite(async () => {
|
|
6319
|
-
check(); const boardRevision = this.d.board.statusRevision(), task = this.synthesisTask(by, fields.taskId), taskId = task.id;
|
|
6320
|
-
if (this.synthesisPrivate(task, by)) return { taskId, status: "private" };
|
|
6321
|
-
const before = this.synthesisInventories(task), allLinks = before.flatMap(claim => claim.inventory.links);
|
|
6322
|
-
const privacyLinks = [...allLinks, ...before.flatMap(claim => claim.contradictionHistory.sources.map(sourceId => ({ sourceId })))];
|
|
6323
|
-
const sources = this.synthesisSources(privacyLinks);
|
|
6324
|
-
if (sources.private) return { taskId, status: "private" };
|
|
6325
|
-
const activeLinks = allLinks.filter(link => link.status !== "withdrawn");
|
|
6326
|
-
if (this.synthesisSources(activeLinks).bytes > 64 * 1024 * 1024) return { taskId, status: "unavailable", cause: "source_input_limit" };
|
|
6327
|
-
const delivered = latestDeliverables(task.history) ?? [], policy = this.synthesisPolicy(task);
|
|
6328
|
-
// ponytail: any concurrent board write stales this explicit batch. A task-scoped evidence generation narrows the fence later.
|
|
6329
|
-
const base = JSON.stringify([task.created, task.owner, task.reviewer, task.history.length, task.plan?.claims, delivered]);
|
|
6330
|
-
const current = () => {
|
|
6331
|
-
try { check(); const now = this.synthesisTask(by, taskId); return !this.synthesisPrivate(now, by)
|
|
6332
|
-
&& this.d.board.statusRevision() === boardRevision && this.synthesisPolicy(now) === policy
|
|
6333
|
-
&& JSON.stringify([now.created, now.owner, now.reviewer, now.history.length, now.plan?.claims, latestDeliverables(now.history) ?? []]) === base; }
|
|
6334
|
-
catch { return false; }
|
|
6335
|
-
};
|
|
6336
|
-
const changed = () => {
|
|
6337
|
-
check(); const now = this.synthesisTask(by, taskId);
|
|
6338
|
-
if (this.synthesisPrivate(now, by) || this.synthesisSources(privacyLinks).private) return { taskId, status: "private" as const };
|
|
6339
|
-
return { taskId, status: "stale" as const, cause: "context_changed" };
|
|
6340
|
-
};
|
|
6341
|
-
try { if (by !== USER) this.d.onReviewObserverInput?.(by); } catch { return { taskId, status: "unavailable", cause: "observer_unavailable" }; }
|
|
6342
|
-
const sourceKeys = new Map<string, string | undefined>();
|
|
6343
|
-
for (const link of activeLinks) if (!sourceKeys.has(link.sourceId)) {
|
|
6344
|
-
let key: string | undefined;
|
|
6345
|
-
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 */ }
|
|
6346
|
-
sourceKeys.set(link.sourceId, key);
|
|
6347
|
-
}
|
|
6348
|
-
if (!current()) return changed();
|
|
6349
|
-
const reads: { path: string; read: GuardedDeliverableRead }[] = [];
|
|
6350
|
-
const artifact = async (reference: { id: string; sha256: string }, limit: number): Promise<SynthesisArtifactSnapshot | "private"> => {
|
|
6351
|
-
const record = delivered.find(record => record.id === reference.id);
|
|
6352
|
-
if (!record) return { id: reference.id, state: "missing" };
|
|
6353
|
-
if (record.private || !record.path || this.experimentOutputPrivate(task, record.path)) return "private";
|
|
6354
|
-
try {
|
|
6355
|
-
const read = await readGuardedDeliverable(record.path, this.deliverablePorts(task, { failClosedOnDiscoveryLimit: true }), limit);
|
|
6356
|
-
const text = new TextDecoder("utf-8", { fatal: true }).decode(read.data);
|
|
6357
|
-
if (!this.publicMetadataText(text)) return "private";
|
|
6358
|
-
reads.push({ path: record.path, read });
|
|
6359
|
-
return { id: record.id, sha256: read.sha256, state: read.sha256 === reference.sha256 && record.sha256 === reference.sha256 ? "unchanged" : "changed", text };
|
|
6360
|
-
} catch { return { id: record.id, state: "unknown" }; }
|
|
6361
|
-
};
|
|
6362
|
-
const doc = await artifact(manifest.deliverable, 256 * 1024); if (doc === "private") return { taskId, status: "private" };
|
|
6363
|
-
if (!current()) return changed();
|
|
6364
|
-
const bib = await artifact(manifest.bibliography, 4 * 1024 * 1024); if (bib === "private") return { taskId, status: "private" };
|
|
6365
|
-
if (!current()) return changed();
|
|
6366
|
-
const observed: SynthesisCurrentClaim[] = [];
|
|
6367
|
-
for (const claim of before) {
|
|
6368
|
-
const resolutions: NonNullable<NonNullable<SynthesisCurrent["claims"]>[number]["resolutions"]>[number][] = [];
|
|
6369
|
-
for (const link of claim.inventory.links) {
|
|
6370
|
-
if (!current()) return changed();
|
|
6371
|
-
const withdrawn = link.status === "withdrawn";
|
|
6372
|
-
if (withdrawn) { resolutions.push({ id: link.id, revision: link.revision, status: "withdrawn" }); continue; }
|
|
6373
|
-
if (!this.d.evidenceSourceRead || !sourceKeys.get(link.sourceId)) { resolutions.push({ id: link.id, revision: link.revision, status: "unavailable" }); continue; }
|
|
6374
|
-
let resolution: EvidenceSourceRead["resolution"];
|
|
6375
|
-
try { resolution = (await this.d.evidenceSourceRead(by, link, current, { privacyReadOnly: true })).resolution; }
|
|
6376
|
-
catch { resolution = { status: "unavailable", cause: "source_unavailable" }; }
|
|
6377
|
-
if (resolution.status === "unavailable" && resolution.cause === "private") return { taskId, status: "private" };
|
|
6378
|
-
if (!current()) return changed();
|
|
6379
|
-
resolutions.push({ id: link.id, revision: link.revision, status: resolution.status === "resolved" ? "resolved" : resolution.status === "stale" ? "stale" : "unavailable" });
|
|
6380
|
-
}
|
|
6381
|
-
const entry = task.history.findLast(entry => entry.by === USER && entry.event === "claim verdict" && entry.claim?.slot === claim.slot && entry.claim.list === claim.claimRevision)?.claim;
|
|
6382
|
-
const verdict = entry && ["supported", "unsupported", "unclear"].includes(entry.verdict) ? entry.verdict : undefined;
|
|
6383
|
-
const synthesis = entry?.synthesis;
|
|
6384
|
-
observed.push({ claimId: claim.claimId, claimRevision: claim.claimRevision,
|
|
6385
|
-
inventory: { ...claim.inventory, links: this.synthesisRows(claim.inventory.links) },
|
|
6386
|
-
contradictionHistory: claim.contradictionHistory,
|
|
6387
|
-
resolutions, judgment: { present: !!verdict, ...(verdict ? { verdict } : {}), ...(verdict && synthesis ? synthesis : {}) } });
|
|
6388
|
-
}
|
|
6389
|
-
const finalCurrent = () => {
|
|
6390
|
-
try {
|
|
6391
|
-
if (!current() || this.synthesisSources(privacyLinks).key !== sources.key) return false;
|
|
6392
|
-
const fencedSources = new Set<string>();
|
|
6393
|
-
for (const link of activeLinks) if (!fencedSources.has(link.sourceId)) {
|
|
6394
|
-
fencedSources.add(link.sourceId);
|
|
6395
|
-
if (sourceKeys.get(link.sourceId) && this.d.evidenceSourceSnapshotKey?.(link) !== sourceKeys.get(link.sourceId)) return false;
|
|
6396
|
-
}
|
|
6397
|
-
if (reads.some(value => !guardedDeliverableCurrent(value.path, this.deliverablePorts(task, { failClosedOnDiscoveryLimit: true }), value.read))) return false;
|
|
6398
|
-
return this.synthesisSources(privacyLinks).key === sources.key && current();
|
|
6399
|
-
} catch { return false; }
|
|
6400
|
-
};
|
|
6401
|
-
if (!finalCurrent()) return changed();
|
|
6402
|
-
const snapshot: SynthesisCurrent = { taskId, taskCreated: task.created, deliverable: doc, bibliography: bib, claims: observed };
|
|
6403
|
-
const report = checkSynthesis(manifest, snapshot);
|
|
6404
|
-
return onSnapshot ? onSnapshot(manifest, snapshot, report, finalCurrent) : report;
|
|
6405
|
-
});
|
|
6406
|
-
}
|
|
6407
4905
|
|
|
6408
4906
|
/** Resolve declared provenance afresh, without manufacturing a #901 judgment or synthesis readiness. */
|
|
6409
4907
|
async evidenceRead(by: PeerId, input: unknown): Promise<EvidenceReadResult> {
|
|
@@ -6492,668 +4990,42 @@ export class Tasks {
|
|
|
6492
4990
|
return { state: "known", group: `origin:${createHash("sha256").update(JSON.stringify([...group].sort())).digest("hex").slice(0, 32)}`, groups: groups.length };
|
|
6493
4991
|
} catch { return unknown; }
|
|
6494
4992
|
}
|
|
4993
|
+
private lineageMetadata(...args: Parameters<ExperimentDomain["lineageMetadata"]>): ReturnType<ExperimentDomain["lineageMetadata"]> { return this.experiment.lineageMetadata(...args); }
|
|
6495
4994
|
|
|
6496
|
-
|
|
6497
|
-
private lineageMetadata(text: string): boolean {
|
|
6498
|
-
try {
|
|
6499
|
-
if (!this.nameable(text) || looksSecret(text)) return false;
|
|
6500
|
-
const policy = [...this.d.piiPaths ?? [], ...this.d.deny ?? []];
|
|
6501
|
-
if (!policy.length) return true;
|
|
6502
|
-
let parsed: unknown;
|
|
6503
|
-
try { parsed = JSON.parse(text); } catch { return false; } // direct stored paths have no alias proof
|
|
6504
|
-
const strings = (value: unknown): string[] => typeof value === "string" ? [value] : Array.isArray(value) ? value.flatMap(strings) : value && typeof value === "object" ? Object.values(value).flatMap(strings) : [];
|
|
6505
|
-
// ponytail: a path-shaped opaque field has no cached alias proof. Withhold it until owner-maintained
|
|
6506
|
-
// public metadata can prove it without filesystem discovery on this read path.
|
|
6507
|
-
return strings(parsed).every(value => !/[\\/]|\.[a-zA-Z]/.test(value) && !matchesPolicyLexically(this.d.cwd, value, policy));
|
|
6508
|
-
} catch { return false; }
|
|
6509
|
-
}
|
|
4995
|
+
private lineageVisible(...args: Parameters<ExperimentDomain["lineageVisible"]>): ReturnType<ExperimentDomain["lineageVisible"]> { return this.experiment.lineageVisible(...args); }
|
|
6510
4996
|
|
|
6511
|
-
private
|
|
6512
|
-
try {
|
|
6513
|
-
if (this.d.privateTurn?.(by) || this.d.reviewObserverInput?.(by) || this.reviewTaskPrivate(task)) return false;
|
|
6514
|
-
if (this.d.piiPaths?.length && ((task.refs.paths?.length ?? 0) || (task.plan?.paths?.length ?? 0) || (task.plan?.sections?.length ?? 0))) return false;
|
|
6515
|
-
if (this.repositories.cachedScope(task.refs)?.key !== this.repositories.project.key) return false;
|
|
6516
|
-
return by === USER || this.d.bus.isRostered(by) && taskShowAllowed(by, task, this.d.roles, this.isConfiguredPlanner(by));
|
|
6517
|
-
} catch { return false; }
|
|
6518
|
-
}
|
|
4997
|
+
private lineagePorts(...args: Parameters<ExperimentDomain["lineagePorts"]>): ReturnType<ExperimentDomain["lineagePorts"]> { return this.experiment.lineagePorts(...args); }
|
|
6519
4998
|
|
|
6520
|
-
|
|
6521
|
-
const binding = this.d.executionLineage;
|
|
6522
|
-
if (!binding) return undefined;
|
|
6523
|
-
// Agent-wide roles do not grant diagnostic authority over a hidden or staged source.
|
|
6524
|
-
const diagnostics = by === USER;
|
|
6525
|
-
// ponytail: raw50 event pages cannot prove current field privacy after policy narrowing.
|
|
6526
|
-
// Refuse by policy alone until a privacy-aware page source supplies a complete public projection.
|
|
6527
|
-
let eventProjectionSupported = false;
|
|
6528
|
-
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 */ }
|
|
6529
|
-
return { project: this.d.project, projectKey: binding.projectKey, cursorKey: binding.cursorKey,
|
|
6530
|
-
scope: createHash("sha256").update(by).digest("hex"), diagnostics, eventProjectionSupported,
|
|
6531
|
-
task: id => this.d.board.get(id), visible: task => this.lineageVisible(by, task), metadata: text => this.lineageMetadata(text),
|
|
6532
|
-
links: task => this.d.board.executionReferences(binding.projectKey, task.id, task.created),
|
|
6533
|
-
delivery: binding.readDelivery,
|
|
6534
|
-
attempt: id => this.d.board.experimentAttempt(id), events: (id, after, limit) => this.d.board.experimentEvents(id, after, limit),
|
|
6535
|
-
receipts: id => this.d.board.runnerReceipts(id), attemptStatus: id => this.d.board.experimentAttemptStatus(id) };
|
|
6536
|
-
}
|
|
6537
|
-
|
|
6538
|
-
/** Read one explicit owner neighborhood; unauthorized, private and missing roots are indistinguishable. */
|
|
6539
|
-
executionLineage(by: PeerId, input: unknown): LineageResult {
|
|
6540
|
-
if (!executionLinkActor(by) || by === HUB || by === "admin") return { state: "unavailable" };
|
|
6541
|
-
try {
|
|
6542
|
-
const check = this.requestCheck(by);
|
|
6543
|
-
if (this.d.privateTurn?.(by) || this.d.reviewObserverInput?.(by)) return { state: "unavailable" };
|
|
6544
|
-
const ports = this.lineagePorts(by);
|
|
6545
|
-
if (!ports) return { state: "unavailable" };
|
|
6546
|
-
let query;
|
|
6547
|
-
try { query = parseOwnerLineageQuery(input); }
|
|
6548
|
-
catch { return ports.diagnostics ? { state: "unavailable", reason: "invalid" } : { state: "unavailable" }; }
|
|
6549
|
-
const snapshot = executionOwnerSnapshot(ports, query);
|
|
6550
|
-
check();
|
|
6551
|
-
if (this.d.privateTurn?.(by) || this.d.reviewObserverInput?.(by)) return { state: "unavailable" };
|
|
6552
|
-
if (snapshot.task) {
|
|
6553
|
-
const current = this.d.board.get(snapshot.task.id);
|
|
6554
|
-
if (!current || current.created !== snapshot.task.created || current.history.length !== snapshot.task.history.length || !this.lineageVisible(by, current)) return { state: "unavailable" };
|
|
6555
|
-
}
|
|
6556
|
-
return readExecutionLineage(snapshot.source, snapshot.query);
|
|
6557
|
-
} catch { return { state: "unavailable" }; }
|
|
6558
|
-
}
|
|
4999
|
+
executionLineage(...args: Parameters<ExperimentDomain["executionLineage"]>): ReturnType<ExperimentDomain["executionLineage"]> { return this.experiment.executionLineage(...args); }
|
|
6559
5000
|
|
|
6560
|
-
|
|
6561
|
-
|
|
6562
|
-
|
|
6563
|
-
|
|
6564
|
-
|
|
6565
|
-
|
|
6566
|
-
|
|
6567
|
-
|
|
6568
|
-
|
|
6569
|
-
|
|
6570
|
-
|
|
6571
|
-
|
|
6572
|
-
|
|
6573
|
-
|
|
6574
|
-
|
|
6575
|
-
|
|
6576
|
-
|
|
6577
|
-
|
|
6578
|
-
|
|
6579
|
-
|
|
6580
|
-
|
|
6581
|
-
|
|
6582
|
-
|
|
6583
|
-
|
|
6584
|
-
|
|
6585
|
-
|
|
6586
|
-
|
|
6587
|
-
if (entry.watch !== undefined) { this.guidanceProbeTimer().clear(entry.watch.handle); entry.watch = undefined; }
|
|
6588
|
-
}
|
|
6589
|
-
private guidanceProbeRetire(entry: GuidanceProbeRuntime): void {
|
|
6590
|
-
if (this.guidanceProbeActive.get(entry.id) !== entry || !entry.launchSettled || entry.stopRequested && (!entry.stopSettled || !entry.stopKnown)) return;
|
|
6591
|
-
this.guidanceProbeClearWatch(entry); this.guidanceProbeActive.delete(entry.id);
|
|
6592
|
-
}
|
|
6593
|
-
private guidanceProbeAbort(entry: GuidanceProbeRuntime, reason: "elapsed" | "observation", explicitStop = false): void {
|
|
6594
|
-
if (this.guidanceProbeActive.get(entry.id) !== entry) return;
|
|
6595
|
-
this.guidanceProbeClearWatch(entry);
|
|
6596
|
-
if (entry.reservation) {
|
|
6597
|
-
try { this.d.guidanceProbes!.store.latchHold(entry.reservation, reason); }
|
|
6598
|
-
catch { entry.failure = new Error("guidance probe hold bookkeeping is unconfirmed; inspect retained state before any further work"); }
|
|
6599
|
-
}
|
|
6600
|
-
entry.controller.abort();
|
|
6601
|
-
if (!entry.launched || !entry.reservation) { this.guidanceProbeRetire(entry); return; }
|
|
6602
|
-
if (entry.stopRequested && (!entry.stopSettled || entry.stopKnown || !explicitStop)) return;
|
|
6603
|
-
const reservation = entry.reservation, ports = entry.ports;
|
|
6604
|
-
entry.stopRequested = true; entry.stopSettled = false; entry.stopKnown = false;
|
|
6605
|
-
entry.stopPromise = (async () => {
|
|
6606
|
-
try {
|
|
6607
|
-
const result = await ports.stop({ reservation }, new AbortController().signal);
|
|
6608
|
-
entry.stopKnown = result?.stopped === "known_fixture" && guidanceProbeCanonical(result.reservation) === guidanceProbeCanonical(reservation);
|
|
6609
|
-
if (!entry.stopKnown) entry.failure = new Error("guidance probe stop evidence is unknown; inspect the owned reservation and explicitly drain without replaying it");
|
|
6610
|
-
} catch { entry.failure = new Error("guidance probe stop failed; retain owned handles and explicitly drain before closing project storage"); }
|
|
6611
|
-
finally { entry.stopSettled = true; this.guidanceProbeRetire(entry); }
|
|
6612
|
-
})();
|
|
6613
|
-
}
|
|
6614
|
-
private guidanceProbeWatch(entry: GuidanceProbeRuntime): void {
|
|
6615
|
-
if (this.guidanceProbeActive.get(entry.id) !== entry || entry.controller.signal.aborted) return;
|
|
6616
|
-
try {
|
|
6617
|
-
entry.current();
|
|
6618
|
-
const state = this.d.guidanceProbes!.store.read({ projectKey: this.guidanceProject(), id: entry.id });
|
|
6619
|
-
if (!state || !entry.reservation || state.firstReservedAt === null) throw new Error("owned probe clock is unavailable");
|
|
6620
|
-
const now = this.d.now?.() ?? Date.now(), elapsed = now - state.firstReservedAt;
|
|
6621
|
-
if (!probeInteger(elapsed) || elapsed < state.counters.elapsedHighWaterMs || state.admissionHold !== "none") { this.guidanceProbeAbort(entry, "elapsed"); return; }
|
|
6622
|
-
const live = state.sessions.find(session => session.slotId === entry.reservation!.slotId)?.live;
|
|
6623
|
-
const remaining = Math.min(state.registration.manifest.limits.elapsedMs - elapsed,
|
|
6624
|
-
live === undefined ? Infinity : GUIDANCE_PROBE_LIVE_LIMITS.elapsedMs - (now - live.reservedAt));
|
|
6625
|
-
if (remaining <= 0) { this.guidanceProbeAbort(entry, "elapsed"); return; }
|
|
6626
|
-
entry.watch = { handle: this.guidanceProbeTimer().set(() => {
|
|
6627
|
-
if (this.guidanceProbeActive.get(entry.id) !== entry || entry.controller.signal.aborted) return;
|
|
6628
|
-
entry.watch = undefined; this.guidanceProbeWatch(entry);
|
|
6629
|
-
}, Math.min(GUIDANCE_PROBE_FENCE_INTERVAL_MS, remaining)) };
|
|
6630
|
-
} catch { this.guidanceProbeAbort(entry, "observation"); }
|
|
6631
|
-
}
|
|
6632
|
-
private guidanceProbeProjection(state: ProbeStoredState, already = false): ProbePublicStatus {
|
|
6633
|
-
const holds = state.admissionHold !== "none" || state.counters.usageUnknown;
|
|
6634
|
-
const authoring: ProbePublicStatus["authoring"] = state.sessions.some(item => item.child?.authoring === "uncontrolled") ? "uncontrolled"
|
|
6635
|
-
: state.sessions.some(item => item.child?.authoring === "admitted_fixture") ? "admitted_fixture" : "unknown";
|
|
6636
|
-
const launchedSessions = state.sessions.filter(item => item.coverage.launchExposed);
|
|
6637
|
-
const verifiedCoverage = launchedSessions.length > 0 && launchedSessions.every(item => item.coverage.coverageVerified)
|
|
6638
|
-
&& state.sessions.filter(item => item.state === "closed_fixture").every(item => item.coverage.coverageVerified)
|
|
6639
|
-
&& state.sessions.every(item => item.state !== "failed_known" || item.coverage.preLaunchFailure || item.coverage.coverageVerified);
|
|
6640
|
-
const evidence: ProbePublicReceipt["evidence"] = state.counters.workerAttempts + state.counters.editorAttempts === 0 ? "declaration"
|
|
6641
|
-
: holds || !verifiedCoverage || state.sessions.some(item => ["reserved", "running", "unknown_held"].includes(item.state)) ? "unknown" : launchedSessions.every(item => item.live !== undefined) ? "live" : "fixture";
|
|
6642
|
-
return { ...state.receipt, already, taskId: state.registration.manifest.task.id,
|
|
6643
|
-
experimentId: this.guidancePublicField(state.registration.manifest.experimentId), evidence,
|
|
6644
|
-
counters: { ...state.counters }, cancelRequested: state.cancelRequested, notNeeded: state.notNeeded, authoring,
|
|
6645
|
-
comparable: state.receipt.state === "closed_fixture" && !holds && verifiedCoverage && authoring === "admitted_fixture" };
|
|
6646
|
-
}
|
|
6647
|
-
private guidanceProbeReceipt(state: ProbeStoredState, already = false): ProbePublicReceipt {
|
|
6648
|
-
const { counters: _counters, cancelRequested: _cancelRequested, notNeeded: _notNeeded, comparable: _comparable, authoring: _authoring, ...result } = this.guidanceProbeProjection(state, already);
|
|
6649
|
-
return result;
|
|
6650
|
-
}
|
|
6651
|
-
private guidanceProbeState(by: PeerId, id: string, check: () => void): ProbeStoredState {
|
|
6652
|
-
check();
|
|
6653
|
-
if (!probeSha256(id)) throw new PreEffectToolRefusal("guidance probe id is invalid; use the exact registered content id");
|
|
6654
|
-
if (!this.d.guidanceProbes) throw new PreEffectToolRefusal("guidance probe storage is unavailable; restart a supporting hub before retrying");
|
|
6655
|
-
const state = this.d.guidanceProbes.store.read({ projectKey: this.guidanceProject(), id });
|
|
6656
|
-
if (!state) throw new PreEffectToolRefusal("guidance probe is unavailable; inspect a registered declaration in this project");
|
|
6657
|
-
this.guidanceProbeTask(by, state.registration.manifest.task, false); check(); return state;
|
|
6658
|
-
}
|
|
6659
|
-
private guidanceProbeHost(by: PeerId, manifest: GuidanceProbeManifestV1, request: ReturnType<Tasks["guidanceProbeRequest"]>, history?: ProbeHostBinding): ProbeHostBinding {
|
|
6660
|
-
request.check();
|
|
6661
|
-
const projectKey = this.guidanceProject();
|
|
6662
|
-
if (projectKey !== manifest.projectKey) throw new PreEffectToolRefusal("guidance probe project changed; register within the current project namespace");
|
|
6663
|
-
const task = this.guidanceProbeTask(by, manifest.task, history === undefined);
|
|
6664
|
-
const binding = { projectKey, actor: by, task: { id: task.id, created: task.created, flowRevision: task.history.length },
|
|
6665
|
-
sessionGeneration: request.generation, nativeSession: request.nativeSession, requestConnectionId: request.requestConnectionId };
|
|
6666
|
-
// A narrowing cancellation carries its original baseline as history, never a new applicability grant.
|
|
6667
|
-
if (history) return { ...binding, role: history.role, baselineGuidance: history.baselineGuidance };
|
|
6668
|
-
const role = this.guidanceRole(task);
|
|
6669
|
-
return { ...binding, role: { id: role.id, layer: role.layer, baselineSha256: role.hash }, baselineGuidance: taskRoleText(role) };
|
|
6670
|
-
}
|
|
6671
|
-
private guidanceProbeSnapshotClear(state: ProbeStoredState["registration"]): boolean {
|
|
6672
|
-
return Object.entries(state.snapshots).every(([field, value]) => {
|
|
6673
|
-
const text = field === "dataPolicy" ? guidanceProbeCanonical(value) : value as string;
|
|
6674
|
-
return this.nameable(text) && !looksSecret(text);
|
|
6675
|
-
});
|
|
6676
|
-
}
|
|
6677
|
-
private guidanceProbeRenderedClear(text: string): boolean {
|
|
6678
|
-
if (!this.nameable(text) || looksSecret(text)) return false;
|
|
6679
|
-
const policy = [...this.d.deny ?? [], ...this.d.piiPaths ?? []];
|
|
6680
|
-
if ([...pathCandidates(text)].some(candidate => matchesPolicyLexically(this.d.cwd, candidate, policy))) return false;
|
|
6681
|
-
return !policy.some(entry => {
|
|
6682
|
-
const literal = entry.replace(/^\.\//, "").split(/[*?[\]{}]/)[0]!.replace(/\/+$/, "");
|
|
6683
|
-
return /[/\s]/.test(literal) && text.includes(literal);
|
|
6684
|
-
});
|
|
6685
|
-
}
|
|
6686
|
-
async guidanceProbeRegister(by: PeerId, value: unknown): Promise<ProbePublicReceipt> {
|
|
6687
|
-
const request = this.guidanceProbeRequest(by), registration = parseGuidanceProbeRegistration(value);
|
|
6688
|
-
if (!registration) throw new PreEffectToolRefusal("guidance probe declaration is invalid or oversized; use the closed V1 envelope without trimming its snapshots");
|
|
6689
|
-
const binding = this.guidanceProbeHost(by, registration.manifest, request);
|
|
6690
|
-
if (!this.guidanceProbeSnapshotClear(registration)) throw new PreEffectToolRefusal("guidance probe inputs are private; register public task-local inputs in a current public session");
|
|
6691
|
-
this.guidanceProbeAdmissions++;
|
|
6692
|
-
let wrote = false;
|
|
6693
|
-
try {
|
|
6694
|
-
const saved = this.d.guidanceProbes!.store.register(registration, binding, () => {
|
|
6695
|
-
if (!this.guidanceProbeSnapshotClear(registration)) throw new PreEffectToolRefusal("guidance probe input policy changed; inspect its current public scope before retrying");
|
|
6696
|
-
return this.guidanceProbeHost(by, registration.manifest, request);
|
|
6697
|
-
});
|
|
6698
|
-
wrote = !saved.already;
|
|
6699
|
-
const state = this.guidanceProbeState(by, saved.id, request.check);
|
|
6700
|
-
return this.guidanceProbeReceipt(state, saved.already);
|
|
6701
|
-
} catch (error) {
|
|
6702
|
-
if (!wrote && (error instanceof PreEffectToolRefusal || error instanceof GuidanceProbeError && error.reason !== "storage")) throw error;
|
|
6703
|
-
throw new Error("guidance probe registration is unconfirmed; inspect retained state before explicitly retrying");
|
|
6704
|
-
}
|
|
6705
|
-
finally { this.guidanceProbeAdmissions--; }
|
|
6706
|
-
}
|
|
6707
|
-
async guidanceProbeShow(by: PeerId, id: string): Promise<ProbePublicStatus> {
|
|
6708
|
-
const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check);
|
|
6709
|
-
request.check();
|
|
6710
|
-
const status = this.guidanceProbeProjection(state);
|
|
6711
|
-
// 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
|
|
6712
|
-
// the store's private status; public show keeps just this flag. A store that cannot be read is not comparable.
|
|
6713
|
-
if (!status.comparable) return status;
|
|
6714
|
-
let sealedComparable = false;
|
|
6715
|
-
try { sealedComparable = this.d.guidanceProbes!.store.outcome({ projectKey: this.guidanceProject(), id: state.receipt.id })?.comparability.comparable === true; } catch { /* fail closed */ }
|
|
6716
|
-
return sealedComparable ? status : { ...status, comparable: false };
|
|
6717
|
-
}
|
|
6718
|
-
/**
|
|
6719
|
-
* T4 (#1226): the producer receipt reader and export. The same person/conductor, session and task fences as `guidanceProbeShow`, and read-only: it launches,
|
|
6720
|
-
* 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
|
|
6721
|
-
* 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
|
|
6722
|
-
* 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.
|
|
6723
|
-
*/
|
|
6724
|
-
async guidanceProbeReceipts(by: PeerId, id: string): Promise<ProbeReceiptExport> {
|
|
6725
|
-
const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check);
|
|
6726
|
-
request.check();
|
|
6727
|
-
const store = this.d.guidanceProbes!.store, key = { projectKey: this.guidanceProject(), id: state.receipt.id };
|
|
6728
|
-
const status = await this.guidanceProbeShow(by, id);
|
|
6729
|
-
let receipts: ProbeReceiptV1[], outcome: ReturnType<GuidanceProbeStore["outcome"]>, retention: Map<string, ProbeRetentionState>;
|
|
6730
|
-
try { receipts = store.receipts(key); outcome = store.outcome(key); retention = store.retentionStates(key); }
|
|
6731
|
-
catch (error) { if (error instanceof GuidanceProbeError) throw error; throw new GuidanceProbeError("storage"); }
|
|
6732
|
-
if (!outcome) throw new GuidanceProbeError("storage");
|
|
6733
|
-
request.check();
|
|
6734
|
-
const bySlot = new Map(receipts.map(item => [item.slotId, item]));
|
|
6735
|
-
const slots: ProbeExportSlot[] = state.registration.manifest.slots.map((slot, index) => {
|
|
6736
|
-
const session = state.sessions[index]!, receipt = bySlot.get(slot.id);
|
|
6737
|
-
const shown = receipt !== undefined && this.guidanceProbeReceiptClear(receipt);
|
|
6738
|
-
return { slotId: slot.id, stage: slot.stage, role: slot.role, arm: slot.arm, state: session.state, receipt: shown ? receipt : null,
|
|
6739
|
-
receiptDigest: receipt?.digest ?? null, withheld: receipt !== undefined && !shown, retention: retention.get(slot.id) ?? "none" };
|
|
6740
|
-
});
|
|
6741
|
-
// The sealed verdict can only make the public one stricter, exactly as in `show`: a status that already refused stays refused.
|
|
6742
|
-
const comparable = status.comparable && outcome.comparability.comparable;
|
|
6743
|
-
const result: ProbeReceiptExport = { v: 1, status: { ...status, comparable }, comparable, reasons: outcome.comparability.reasons, counts: outcome.counts, slots };
|
|
6744
|
-
// 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.
|
|
6745
|
-
const checked = parseGuidanceProbeReceiptExport(JSON.parse(JSON.stringify(result)));
|
|
6746
|
-
if (!checked) throw new GuidanceProbeError("storage");
|
|
6747
|
-
return checked;
|
|
6748
|
-
}
|
|
6749
|
-
/** 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. */
|
|
6750
|
-
private guidanceProbeReceiptClear(receipt: ProbeReceiptV1): boolean {
|
|
6751
|
-
const names = [receipt.experimentId, receipt.slotId, receipt.servedModel ?? "", ...receipt.output.entries.map(item => item.relative), ...receipt.output.excluded.map(item => item.relative)];
|
|
6752
|
-
return names.every(text => text === "" || this.guidanceFieldAllowed(text));
|
|
6753
|
-
}
|
|
6754
|
-
async guidanceProbeStart(by: PeerId, id: string, revision: number, variantId?: string): Promise<ProbePublicReceipt> {
|
|
6755
|
-
const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check);
|
|
6756
|
-
const host = this.guidanceProbeHost(by, state.registration.manifest, request);
|
|
6757
|
-
if (!probeInteger(revision) || variantId !== undefined && !probeSha256(variantId))
|
|
6758
|
-
throw new PreEffectToolRefusal("guidance probe start selector is invalid; use its current CAS revision and exact G1 id");
|
|
6759
|
-
const dependency = this.d.guidanceProbes!;
|
|
6760
|
-
// Match a host-configured content ID, never a mode requested by the caller or carried by imported evidence.
|
|
6761
|
-
const live = dependency.live?.id === id ? dependency.live.adapter : undefined;
|
|
6762
|
-
if (live && (by === USER || request.nativeSession === null))
|
|
6763
|
-
// refusal:by-design human-authority: live starts require an authenticated conductor session
|
|
6764
|
-
throw new PreEffectToolRefusal("live guidance probes require the current authenticated conductor native session");
|
|
6765
|
-
if (live && !isLiveGuidanceProbeManifest(state.registration.manifest))
|
|
6766
|
-
// refusal:by-design operator-knowledge: the operator must supply the preregistered bounded declaration
|
|
6767
|
-
throw new PreEffectToolRefusal("live guidance probe requires a bounded baseline and candidate declaration");
|
|
6768
|
-
const selectedPorts = live?.ports ?? dependency.fakePorts;
|
|
6769
|
-
// refusal:by-design human-authority: only the host operator can select a live registration
|
|
6770
|
-
if (!selectedPorts) throw new PreEffectToolRefusal("guidance probe runner is unavailable in production T1 for this registration");
|
|
6771
|
-
const key = { projectKey: host.projectKey, id }, original = dependency.store.startSelector(key, revision);
|
|
6772
|
-
if (original && (original.actor !== by || original.sessionGeneration !== host.sessionGeneration || original.nativeSession !== host.nativeSession
|
|
6773
|
-
|| original.requestConnectionId !== host.requestConnectionId)) throw new PreEffectToolRefusal("guidance probe original start belongs to another request session; inspect its retained id without replaying it");
|
|
6774
|
-
const slot = original ? state.registration.manifest.slots.find(item => item.id === original.slotId)
|
|
6775
|
-
: state.registration.manifest.slots.find(item => state.sessions.find(session => session.slotId === item.id)?.state === "planned");
|
|
6776
|
-
if (!slot) throw new PreEffectToolRefusal("guidance probe has no eligible slot; inspect its retained terminal or held state");
|
|
6777
|
-
if (original && original.variantId !== (variantId ?? null)) throw new PreEffectToolRefusal("guidance probe original selector differs; inspect its original G1 id without rebinding the start");
|
|
6778
|
-
const needsVariant = slot.role === "worker" && slot.arm !== "baseline";
|
|
6779
|
-
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");
|
|
6780
|
-
const current = (): ProbeAdmissionRecheck => {
|
|
6781
|
-
const fresh = this.guidanceProbeHost(by, state.registration.manifest, request);
|
|
6782
|
-
if (!this.guidanceProbeSnapshotClear(state.registration)) throw new PreEffectToolRefusal("guidance probe input privacy changed; retain its declaration and use current public inputs");
|
|
6783
|
-
return { host: fresh, ...(variantId === undefined ? {} : { child: this.guidanceProbeVariantBinding(by, this.guidanceProbeTask(by, state.registration.manifest.task, true), variantId) }) };
|
|
6784
|
-
};
|
|
6785
|
-
const prepared = current();
|
|
6786
|
-
const active = this.guidanceProbeActive.get(id);
|
|
6787
|
-
if (active) {
|
|
6788
|
-
if (active.requestedRevision !== revision || active.variantId !== variantId)
|
|
6789
|
-
throw new PreEffectToolRefusal("another owned probe attempt is still settling; inspect its state before explicitly starting the next stage");
|
|
6790
|
-
const captured = active.current().host;
|
|
6791
|
-
if (captured.actor !== host.actor || captured.sessionGeneration !== host.sessionGeneration || captured.nativeSession !== host.nativeSession
|
|
6792
|
-
|| captured.requestConnectionId !== host.requestConnectionId)
|
|
6793
|
-
throw new PreEffectToolRefusal("guidance probe active start belongs to another request session; inspect its retained id without replaying it");
|
|
6794
|
-
// Frame preparation has not granted a reservation. A duplicate is only a read of truthful current metadata.
|
|
6795
|
-
if (!active.reservation) return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), true);
|
|
6796
|
-
const replay = dependency.store.reserveSession({ key, expectedRevision: revision, ...prepared, ...(live ? { mode: "live" as const } : {}), now: this.d.now?.() ?? Date.now() }, current);
|
|
6797
|
-
if (replay.kind !== "existing") throw new Error("guidance probe start is unconfirmed; inspect retained state before any further work");
|
|
6798
|
-
return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), true);
|
|
6799
|
-
}
|
|
6800
|
-
const entry: GuidanceProbeRuntime = { id, by, requestedRevision: revision, ...(variantId === undefined ? {} : { variantId }), controller: new AbortController(), current, ports: selectedPorts, launched: false, launchSettled: false,
|
|
6801
|
-
stopRequested: false, stopSettled: false, stopKnown: false };
|
|
6802
|
-
this.guidanceProbeActive.set(id, entry);
|
|
6803
|
-
const ports: GuidanceProbeFakePorts = {
|
|
6804
|
-
launch: async (input, effects, signal) => {
|
|
6805
|
-
entry.reservation = input.reservation;
|
|
6806
|
-
this.guidanceProbeWatch(entry);
|
|
6807
|
-
if (signal.aborted) throw new Error("owned probe was aborted before launch");
|
|
6808
|
-
entry.launched = true;
|
|
6809
|
-
return selectedPorts.launch(input, effects, signal);
|
|
6810
|
-
},
|
|
6811
|
-
stop: (input, signal) => selectedPorts.stop(input, signal),
|
|
6812
|
-
...(selectedPorts.discardRetained ? { discardRetained: record => selectedPorts.discardRetained!(record) } : {}),
|
|
6813
|
-
};
|
|
6814
|
-
let reserved = false, returned = false;
|
|
6815
|
-
const runner = new GuidanceProbeFixtureHost(dependency.store, { ports, ...(live ? { mode: "live" as const } : {}), revalidate: current, now: () => this.d.now?.() ?? Date.now(),
|
|
6816
|
-
prepareWorkerFrame: live?.prepareWorkerFrame ?? dependency.prepareWorkerFrame, prepareEditorFrame: dependency.prepareEditorFrame, onReserved: () => { reserved = true; } });
|
|
6817
|
-
entry.promise = (async () => {
|
|
6818
|
-
try {
|
|
6819
|
-
const saved = await runner.start({ key, expectedRevision: revision, ...prepared, ...(live ? { mode: "live" as const } : {}), now: this.d.now?.() ?? Date.now() }, entry.controller.signal);
|
|
6820
|
-
returned = true;
|
|
6821
|
-
if (saved.state === "unknown_held" && entry.launched) {
|
|
6822
|
-
this.guidanceProbeAbort(entry, "observation", true);
|
|
6823
|
-
if (!entry.stopPromise) throw new Error("owned probe stop was not recorded; retain the held lane and explicitly inspect its outcome");
|
|
6824
|
-
await entry.stopPromise;
|
|
6825
|
-
}
|
|
6826
|
-
request.check();
|
|
6827
|
-
if (entry.failure) throw entry.failure;
|
|
6828
|
-
return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), saved.already);
|
|
6829
|
-
} catch (error) {
|
|
6830
|
-
this.guidanceProbeAbort(entry, "observation");
|
|
6831
|
-
if (!reserved && !returned && (error instanceof PreEffectToolRefusal || error instanceof GuidanceProbeError && error.reason !== "storage")) throw error;
|
|
6832
|
-
throw new Error("guidance probe attempt outcome is unconfirmed; inspect its retained id without replaying work");
|
|
6833
|
-
} finally { entry.launchSettled = true; this.guidanceProbeClearWatch(entry); this.guidanceProbeRetire(entry); }
|
|
6834
|
-
})();
|
|
6835
|
-
return entry.promise;
|
|
6836
|
-
}
|
|
6837
|
-
async guidanceProbeCancel(by: PeerId, id: string, revision: number): Promise<ProbePublicReceipt> {
|
|
6838
|
-
const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check);
|
|
6839
|
-
if (!probeInteger(revision)) throw new PreEffectToolRefusal("guidance probe cancellation revision is invalid; inspect its current CAS revision");
|
|
6840
|
-
const current = () => this.guidanceProbeHost(by, state.registration.manifest, request, state.binding), host = current();
|
|
6841
|
-
try {
|
|
6842
|
-
const saved = this.d.guidanceProbes!.store.cancelIntent({ key: { projectKey: host.projectKey, id }, expectedRevision: revision, host }, current);
|
|
6843
|
-
const entry = this.guidanceProbeActive.get(id);
|
|
6844
|
-
if (entry) { this.guidanceProbeAbort(entry, "observation", true); await this.guidanceProbeDrain([entry]); }
|
|
6845
|
-
request.check();
|
|
6846
|
-
return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), saved.already);
|
|
6847
|
-
} catch { throw new Error("guidance probe cancellation is unconfirmed; inspect its retained intent and owned drain before retrying"); }
|
|
6848
|
-
}
|
|
6849
|
-
private guidanceProbeRequest(by: PeerId): { check: () => void; generation: number | string; nativeSession: string | null; requestConnectionId: string } {
|
|
6850
|
-
const request = this.guidanceRequest(by, "probe");
|
|
6851
|
-
if (!this.personOrConductor(by)) throw new PreEffectToolRefusal("guidance probes require the person or current configured conductor; use an admitted operational session");
|
|
6852
|
-
const session = this.d.guidanceProbes?.session?.(by);
|
|
6853
|
-
if (!session || !probeSessionGeneration(session.generation) || !executionText(session.requestConnectionId, EXECUTION_REFERENCE_LIMITS.id)
|
|
6854
|
-
|| session.nativeSession !== null && !executionText(session.nativeSession, EXECUTION_REFERENCE_LIMITS.id))
|
|
6855
|
-
throw new PreEffectToolRefusal("guidance probe request session is unavailable; reconnect through a current authenticated project connection");
|
|
6856
|
-
const sessionCurrent = session.current;
|
|
6857
|
-
const current = () => {
|
|
6858
|
-
sessionCurrent(); request();
|
|
6859
|
-
if (this.guidanceProbeStopping) throw new PreEffectToolRefusal("guidance probe admission is stopping; inspect retained work after the owned drain");
|
|
6860
|
-
if (this.d.reviewOnly?.(by)) throw new PreEffectToolRefusal("guidance probes are unavailable in a review-only context; use a current public operational session");
|
|
6861
|
-
if (by !== USER) {
|
|
6862
|
-
try { requireConductor(by, this.d.roles); }
|
|
6863
|
-
catch { throw new PreEffectToolRefusal("guidance probe conductor authority changed; refresh the configured role before retrying"); }
|
|
6864
|
-
if (!this.d.bus.isRostered(by)) throw new PreEffectToolRefusal("guidance probe conductor is not currently rostered; restore current membership before retrying");
|
|
6865
|
-
}
|
|
6866
|
-
};
|
|
6867
|
-
current(); return { check: current, generation: session.generation, nativeSession: session.nativeSession, requestConnectionId: session.requestConnectionId };
|
|
6868
|
-
}
|
|
6869
|
-
private guidanceProbeTask(by: PeerId, selected: { id: number; created: number; flowRevision: number }, admission: boolean): Task {
|
|
6870
|
-
const task = this.guidanceTask(by, { taskId: selected.id, taskCreated: selected.created }, false);
|
|
6871
|
-
if (admission && (task.history.length !== selected.flowRevision || !["in_progress", "changes_requested"].includes(task.state)))
|
|
6872
|
-
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`);
|
|
6873
|
-
return task;
|
|
6874
|
-
}
|
|
6875
|
-
/** Actual probe actor only; the source owner validates/hydrates G1, never an impersonated read or separate SQL parser. */
|
|
6876
|
-
private guidanceProbeVariantBinding(by: PeerId, task: Task, variantId: string): ProbeChildBinding {
|
|
6877
|
-
if (by !== USER) {
|
|
6878
|
-
try { requireConductor(by, this.d.roles); }
|
|
6879
|
-
catch { throw new PreEffectToolRefusal("guidance probe conductor authority changed; reconnect in a current operational session"); }
|
|
6880
|
-
if (!this.d.bus.isRostered(by)) throw new PreEffectToolRefusal("guidance probe conductor membership changed; restore current roster membership before retrying");
|
|
6881
|
-
}
|
|
6882
|
-
const current = this.guidanceProbeTask(by, { id: task.id, created: task.created, flowRevision: task.history.length }, true);
|
|
6883
|
-
if (!probeSha256(variantId)) throw new PreEffectToolRefusal("guidance probe variant selector is invalid; choose an existing current G1 content id");
|
|
6884
|
-
const project = this.guidanceProject(), role = this.guidanceRole(current);
|
|
6885
|
-
const experiment = this.guidanceStorage("read", () => this.d.board.guidanceVariantLocation(project, current.id, current.created, variantId));
|
|
6886
|
-
const record = experiment === undefined ? undefined : this.guidanceStorage("read", () => this.d.board.guidanceVariants(project, current.id, current.created, experiment)).find(item => item.variant.id === variantId);
|
|
6887
|
-
if (!record || record.withdrawn || record.variant.flowRevision !== current.history.length || record.variant.baseline.roleId !== role.id
|
|
6888
|
-
|| record.variant.baseline.layer !== role.layer || record.variant.baseline.sha256 !== role.hash)
|
|
6889
|
-
throw new PreEffectToolRefusal("guidance probe G1 is unavailable, withdrawn or stale; separately admit a current owner/person variant before retrying");
|
|
6890
|
-
const guidance = renderGuidanceVariantV1(record.variant);
|
|
6891
|
-
if (!this.guidanceProbeRenderedClear(guidance))
|
|
6892
|
-
throw new PreEffectToolRefusal("guidance probe handoff text is private; use a current public G1 before retrying");
|
|
6893
|
-
return { variantId, candidateSha256: record.variant.candidate.sha256, guidanceSha256: probeHash(guidance), guidance,
|
|
6894
|
-
task: { id: current.id, created: current.created, flowRevision: current.history.length },
|
|
6895
|
-
role: { id: role.id, layer: role.layer, baselineSha256: role.hash }, authoring: "uncontrolled", sourceSessionId: null };
|
|
6896
|
-
}
|
|
6897
|
-
|
|
6898
|
-
private guidanceRequest(by: PeerId, mode: "guidance" | "probe" = "guidance"): () => void {
|
|
6899
|
-
if (!executionText(by, EXECUTION_REFERENCE_LIMITS.id) || !executionLinkActor(by) || by === HUB || by === "admin")
|
|
6900
|
-
throw new PreEffectToolRefusal("guidance requires a current local task actor; ask the task owner or the person");
|
|
6901
|
-
const request = this.requestCheck(by, () => this.studyHold());
|
|
6902
|
-
const peer = by === USER ? undefined : this.d.bus.peers.get(by), generation = peer?.sessionGeneration, session = peer?.nativeSession;
|
|
6903
|
-
const delivery = () => this.d.bus.lastDeliveredTo(by).map(item => item.id).join("\n"), delivered = mode === "guidance" ? delivery() : undefined;
|
|
6904
|
-
const check = () => {
|
|
6905
|
-
request();
|
|
6906
|
-
if (this.d.privateTurn?.(by) || this.reviewObserverTurn(by))
|
|
6907
|
-
throw new PreEffectToolRefusal("guidance is unavailable during private or review input; retry in a public owner context");
|
|
6908
|
-
if (by !== USER && (!peer || this.d.bus.peers.get(by) !== peer || "sessionGeneration" in peer && generation === undefined
|
|
6909
|
-
|| peer.sessionGeneration !== generation || peer.nativeSession !== session || mode === "guidance" && delivery() !== delivered))
|
|
6910
|
-
throw new PreEffectToolRefusal("guidance request session changed or is unavailable; reload the task in the current session before retrying");
|
|
6911
|
-
};
|
|
6912
|
-
check(); return check;
|
|
6913
|
-
}
|
|
6914
|
-
private guidanceTask(by: PeerId, selector: Pick<GuidanceSelector, "taskId" | "taskCreated">, write: boolean): Task {
|
|
6915
|
-
const task = this.guidanceStorage("read", () => this.d.board.get(selector.taskId));
|
|
6916
|
-
if (!task) throw new PreEffectToolRefusal("guidance task is unavailable; read a current task in this project before retrying");
|
|
6917
|
-
if (task.created !== selector.taskCreated || !this.lineageVisible(by, task) || this.reviewObserverTurn(by, task.id))
|
|
6918
|
-
throw new PreEffectToolRefusal("guidance task is unavailable; refresh the current public task and privacy context before retrying");
|
|
6919
|
-
if (write && (isClosedTaskState(task.state) || by !== USER && (task.owner !== by || task.state === "in_review"
|
|
6920
|
-
|| !this.d.roles?.[by]?.includes(ownerRoleOfClass(task.class)) || !this.d.bus.isRostered(by))))
|
|
6921
|
-
throw new PreEffectToolRefusal("guidance changes require the current task owner outside review, or the person, on an open task; refresh the task before retrying");
|
|
6922
|
-
return task;
|
|
6923
|
-
}
|
|
6924
|
-
private guidanceProject(): string {
|
|
6925
|
-
const key = this.d.executionLineage?.projectKey;
|
|
6926
|
-
if (!key) throw new PreEffectToolRefusal("guidance project storage is unavailable; inspect hub status before retrying");
|
|
6927
|
-
return key;
|
|
6928
|
-
}
|
|
6929
|
-
private guidanceRole(task: Task) {
|
|
6930
|
-
let role;
|
|
6931
|
-
try { role = taskRole(task.role, task.class, this.d.catalog ?? loadRoleCatalog(this.d.cwd)); }
|
|
6932
|
-
catch { throw new Error("guidance catalog validation is unavailable; inspect the current task role and catalog before retrying"); }
|
|
6933
|
-
if (!role) throw new PreEffectToolRefusal("guidance requires a current catalog task role; select a task role before proposing a variant");
|
|
6934
|
-
return role;
|
|
6935
|
-
}
|
|
6936
|
-
private guidancePublic(record: GuidanceStoredRecord | { variant: GuidanceVariantV1 }): boolean {
|
|
6937
|
-
const { evidenceRefs, ...text } = record.variant;
|
|
6938
|
-
// Opaque evidence addresses never become filesystem/producer lookup instructions.
|
|
6939
|
-
return this.publicMetadataText(JSON.stringify(text)) && evidenceRefs.every(reference => this.lineageMetadata(JSON.stringify(reference)));
|
|
6940
|
-
}
|
|
6941
|
-
/** Unknown storage/readback failures never certify a pre-effect refusal, even when SQLite rolled back. */
|
|
6942
|
-
private guidanceStorage<T>(operation: "read" | "write", action: () => T): T {
|
|
6943
|
-
try { return action(); }
|
|
6944
|
-
catch { throw new Error(`guidance storage ${operation} failed; inspect the retained task experiment and its outcome before retrying`); }
|
|
6945
|
-
}
|
|
6946
|
-
private guidanceFence(by: PeerId, task: Task): GuidanceWriteFence {
|
|
6947
|
-
return { by, at: this.d.now?.() ?? Date.now(), taskId: task.id, taskCreated: task.created, flowRevision: task.history.length,
|
|
6948
|
-
owner: task.owner, state: task.state, roleId: task.role };
|
|
6949
|
-
}
|
|
6950
|
-
private guidanceFieldAllowed(text: string): boolean {
|
|
6951
|
-
try { return this.nameable(text) && !looksSecret(text) && this.lineageMetadata(JSON.stringify(text)); }
|
|
6952
|
-
catch { return false; }
|
|
6953
|
-
}
|
|
6954
|
-
private guidancePublicField(text: string): string { return this.guidanceFieldAllowed(text) ? text : "withheld"; }
|
|
6955
|
-
private guidanceExperimentFor(projectKey: string, task: Task, selector: Pick<GuidanceSelector, "taskId" | "taskCreated" | "id"> & { experimentId?: string }): string | undefined {
|
|
6956
|
-
return selector.experimentId ?? (selector.id ? this.guidanceStorage("read", () => this.d.board.guidanceVariantLocation(projectKey, task.id, task.created, selector.id!)) : undefined);
|
|
6957
|
-
}
|
|
6958
|
-
private guidanceCurrent(task: Task): GuidanceCurrent { return { taskId: task.id, taskCreated: task.created, flowRevision: task.history.length }; }
|
|
6959
|
-
private guidanceReadFence(by: PeerId, selector: Pick<GuidanceSelector, "taskId" | "taskCreated">, task: Task, check: () => void): Task {
|
|
6960
|
-
check(); const current = this.guidanceTask(by, selector, false);
|
|
6961
|
-
if (JSON.stringify([current.created, current.history.length, current.owner, current.reviewer, current.state, current.role])
|
|
6962
|
-
!== JSON.stringify([task.created, task.history.length, task.owner, task.reviewer, task.state, task.role])) throw new Error("guidance read binding changed");
|
|
6963
|
-
return current;
|
|
6964
|
-
}
|
|
6965
|
-
private guidanceEvidence(by: PeerId, task: Task, records: readonly GuidanceStoredRecord[]): GuidancePublicRecord["evidence"][] {
|
|
6966
|
-
const ports = this.lineagePorts(by), projectKey = this.guidanceProject();
|
|
6967
|
-
return records.map(record => record.variant.evidenceRefs.map(reference => {
|
|
6968
|
-
let known = false;
|
|
6969
|
-
if (ports && reference.tool === "ahub" && reference.projectKey === projectKey) {
|
|
6970
|
-
const snapshot = executionOwnerSnapshot(ports, { root: reference, task: { id: task.id, created: task.created } });
|
|
6971
|
-
known = snapshot.source.health === "ready" && snapshot.source.nodes.some(node => executionReferenceKey(node.ref) === executionReferenceKey(reference));
|
|
6972
|
-
}
|
|
6973
|
-
return { key: executionReferenceDigest(reference), status: known ? "declared" as const : "unavailable" as const };
|
|
6974
|
-
}));
|
|
6975
|
-
}
|
|
6976
|
-
private guidanceProjection(by: PeerId, task: Task, record: GuidanceStoredRecord, evidence: GuidancePublicRecord["evidence"]): GuidancePublicRecord {
|
|
6977
|
-
return { ...guidanceVariantMetadata(record.variant), experimentId: this.guidancePublicField(record.variant.experimentId),
|
|
6978
|
-
status: record.withdrawn ? "withdrawn" : "declared", applicable: this.guidanceApplicable(by, task, record),
|
|
6979
|
-
rationale: { problemHypothesis: this.guidancePublicField(record.variant.rationale.problemHypothesis), expectedObservableDifference: this.guidancePublicField(record.variant.rationale.expectedObservableDifference) }, evidence };
|
|
6980
|
-
}
|
|
6981
|
-
private guidanceReceipt(saved: { record: GuidanceStoredRecord; already: boolean }): GuidanceWriteReceipt {
|
|
6982
|
-
const value = saved.record.variant;
|
|
6983
|
-
return { id: value.id, taskId: value.taskId, experimentId: this.guidancePublicField(value.experimentId), status: saved.record.withdrawn ? "withdrawn" : "declared", already: saved.already };
|
|
6984
|
-
}
|
|
6985
|
-
/** Immutable declarations only. Neither creation nor readback changes effective role guidance. */
|
|
6986
|
-
async guidanceVariantCreate(by: PeerId, input: unknown): Promise<GuidanceWriteReceipt> {
|
|
6987
|
-
const check = this.guidanceRequest(by);
|
|
6988
|
-
let variant: Readonly<GuidanceVariantV1>;
|
|
6989
|
-
try { variant = parseGuidanceVariantV1(input); } catch { throw new PreEffectToolRefusal("invalid guidance variant; use the closed V1 record and current task identity before retrying"); }
|
|
6990
|
-
return this.studyWrite(async () => {
|
|
6991
|
-
const context = () => {
|
|
6992
|
-
check();
|
|
6993
|
-
const task = this.guidanceTask(by, variant, true), projectKey = this.guidanceProject(), role = this.guidanceRole(task);
|
|
6994
|
-
if (!this.guidancePublic({ variant })) throw new PreEffectToolRefusal("guidance text or evidence metadata is private; use public task-local metadata before retrying");
|
|
6995
|
-
const experiment = this.guidanceStorage("read", () => this.d.board.guidanceExperiment(projectKey, task.id, task.created, variant.experimentId));
|
|
6996
|
-
const records = this.guidanceStorage("read", () => this.d.board.guidanceVariants(projectKey, task.id, task.created, variant.experimentId));
|
|
6997
|
-
try {
|
|
6998
|
-
validateGuidanceVariantV1(variant, { projectKey, taskId: task.id, taskCreated: task.created, flowRevision: task.history.length,
|
|
6999
|
-
experimentId: variant.experimentId, actor: by, baseline: experiment?.baseline ?? variant.baseline,
|
|
7000
|
-
currentBaseline: roleIdentity(role), variantIds: records.map(item => item.variant.id) });
|
|
7001
|
-
} catch (error) {
|
|
7002
|
-
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");
|
|
7003
|
-
throw new Error("guidance validation is unavailable; inspect the task experiment before retrying");
|
|
7004
|
-
}
|
|
7005
|
-
return { task, key: JSON.stringify([task.created, task.history.length, task.owner, task.state, task.role, roleIdentity(role), experiment?.baseline ?? variant.baseline]) };
|
|
7006
|
-
};
|
|
7007
|
-
const before = context();
|
|
7008
|
-
if (this.screenOn() && (await this.screenCall(JSON.stringify(variant))).label !== "clear")
|
|
7009
|
-
throw new PreEffectToolRefusal("guidance privacy screening did not clear the proposal; retry with public metadata when local screening is available");
|
|
7010
|
-
const current = context();
|
|
7011
|
-
if (before.key !== current.key) throw new PreEffectToolRefusal("guidance context changed during admission; reload the task and experiment before retrying");
|
|
7012
|
-
check();
|
|
7013
|
-
const saved = this.guidanceStorage("write", () => this.d.board.recordGuidanceVariant(variant, this.guidanceFence(by, current.task)));
|
|
7014
|
-
return this.guidanceReceipt(saved);
|
|
7015
|
-
});
|
|
7016
|
-
}
|
|
7017
|
-
async guidanceVariantWithdraw(by: PeerId, input: unknown): Promise<GuidanceWriteReceipt> {
|
|
7018
|
-
const check = this.guidanceRequest(by);
|
|
7019
|
-
let selector: GuidanceSelector | GuidanceIdSelector;
|
|
7020
|
-
try { try { selector = parseGuidanceSelector(input, true); } catch { selector = parseGuidanceIdQuery(input, true); } }
|
|
7021
|
-
catch { throw new PreEffectToolRefusal("invalid guidance withdrawal; name a current task epoch, flow revision and existing variant selector"); }
|
|
7022
|
-
return this.studyWrite(async () => {
|
|
7023
|
-
check(); const task = this.guidanceTask(by, selector, true), projectKey = this.guidanceProject();
|
|
7024
|
-
if (task.history.length !== selector.flowRevision) throw new PreEffectToolRefusal("guidance task revision changed; reload the task before withdrawing");
|
|
7025
|
-
const experimentId = this.guidanceExperimentFor(projectKey, task, selector);
|
|
7026
|
-
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);
|
|
7027
|
-
if (!record) throw new PreEffectToolRefusal("guidance variant is unavailable; refresh the task experiment before withdrawing");
|
|
7028
|
-
check();
|
|
7029
|
-
const saved = this.guidanceStorage("write", () => this.d.board.withdrawGuidanceVariant(projectKey, experimentId!, selector.id!, this.guidanceFence(by, task)));
|
|
7030
|
-
return this.guidanceReceipt(saved);
|
|
7031
|
-
});
|
|
7032
|
-
}
|
|
7033
|
-
private guidanceApplicable(by: PeerId, task: Task, record: GuidanceStoredRecord): boolean {
|
|
7034
|
-
try {
|
|
7035
|
-
if (record.withdrawn || isClosedTaskState(task.state) || by !== USER && task.owner !== by || by !== USER && task.state === "in_review") return false;
|
|
7036
|
-
const value = record.variant, role = this.guidanceRole(task);
|
|
7037
|
-
return value.flowRevision === task.history.length && value.baseline.roleId === role.id && value.baseline.layer === role.layer
|
|
7038
|
-
&& value.baseline.sha256 === role.hash && (by === USER || this.d.roles?.[by]?.includes(ownerRoleOfClass(task.class)) === true);
|
|
7039
|
-
} catch { return false; }
|
|
7040
|
-
}
|
|
7041
|
-
/** Historical data can be visible without being applicable. No model, external resolver or delivery runs here. */
|
|
7042
|
-
guidanceVariantRead(by: PeerId, input: unknown): GuidanceReadResult {
|
|
7043
|
-
try {
|
|
7044
|
-
const check = this.guidanceRequest(by), selector = parseGuidanceSelector(input);
|
|
7045
|
-
check(); const task = this.guidanceTask(by, selector, false), projectKey = this.guidanceProject();
|
|
7046
|
-
const experimentId = this.guidanceExperimentFor(projectKey, task, selector);
|
|
7047
|
-
if (experimentId === undefined) return { state: "unavailable" };
|
|
7048
|
-
const records = this.d.board.guidanceVariants(projectKey, task.id, task.created, experimentId);
|
|
7049
|
-
const selected = selector.id ? records.filter(item => item.variant.id === selector.id) : records;
|
|
7050
|
-
if (!selected.length) return { state: "unavailable" };
|
|
7051
|
-
const evidence = this.guidanceEvidence(by, task, selected), current = this.guidanceReadFence(by, selector, task, check);
|
|
7052
|
-
if (this.guidanceExperimentFor(projectKey, current, selector) !== experimentId) return { state: "unavailable" };
|
|
7053
|
-
const fresh = this.d.board.guidanceVariants(projectKey, current.id, current.created, experimentId);
|
|
7054
|
-
const currentSelected = selector.id ? fresh.filter(item => item.variant.id === selector.id) : fresh;
|
|
7055
|
-
if (JSON.stringify(selected) !== JSON.stringify(currentSelected)) return { state: "unavailable" };
|
|
7056
|
-
const result: GuidanceReadResult = { state: "available", records: currentSelected.map((record, index) => this.guidanceProjection(by, current, record, evidence[index]!)) };
|
|
7057
|
-
check();
|
|
7058
|
-
return result;
|
|
7059
|
-
} catch { return { state: "unavailable" }; }
|
|
7060
|
-
}
|
|
7061
|
-
/** Public T3 detail: private selection, screened editable fields, no raw snapshot readback. */
|
|
7062
|
-
guidanceVariantDiff(by: PeerId, input: unknown): GuidanceDiffResult {
|
|
7063
|
-
try {
|
|
7064
|
-
const check = this.guidanceRequest(by), selector = parseGuidanceIdQuery(input);
|
|
7065
|
-
const task = this.guidanceTask(by, selector, false), projectKey = this.guidanceProject(), experimentId = this.guidanceExperimentFor(projectKey, task, selector);
|
|
7066
|
-
if (experimentId === undefined) return { state: "unavailable" };
|
|
7067
|
-
const record = this.d.board.guidanceVariants(projectKey, task.id, task.created, experimentId).find(item => item.variant.id === selector.id);
|
|
7068
|
-
if (!record) return { state: "unavailable" };
|
|
7069
|
-
const evidence = this.guidanceEvidence(by, task, [record]), current = this.guidanceReadFence(by, selector, task, check);
|
|
7070
|
-
if (this.guidanceExperimentFor(projectKey, current, selector) !== experimentId) return { state: "unavailable" };
|
|
7071
|
-
const fresh = this.d.board.guidanceVariants(projectKey, current.id, current.created, experimentId).find(item => item.variant.id === selector.id);
|
|
7072
|
-
if (!fresh || JSON.stringify(fresh) !== JSON.stringify(record)) return { state: "unavailable" };
|
|
7073
|
-
const result = parseGuidanceDiffResult({ state: "available", current: this.guidanceCurrent(current), record: this.guidanceProjection(by, current, fresh, evidence[0]!),
|
|
7074
|
-
sections: guidanceVariantSectionDiff(fresh.variant, text => this.guidanceFieldAllowed(text)), protectedSections: guidanceProtectedSectionNames() });
|
|
7075
|
-
check(); return result;
|
|
7076
|
-
} catch { return { state: "unavailable" }; }
|
|
7077
|
-
}
|
|
7078
|
-
/** Fixed indexed keyset pages; cursor contains only an existing public variant id and authenticated context. */
|
|
7079
|
-
guidanceVariantList(by: PeerId, input: unknown): GuidancePageResult {
|
|
7080
|
-
try {
|
|
7081
|
-
const check = this.guidanceRequest(by), query = parseGuidanceListQuery(input), task = this.guidanceTask(by, query, false), projectKey = this.guidanceProject();
|
|
7082
|
-
const key = this.d.executionLineage?.cursorKey; if (!key) return { state: "unavailable" };
|
|
7083
|
-
const context = { ...this.guidanceCurrent(task), projectKey, actor: by };
|
|
7084
|
-
const after = query.cursor ? guidancePageAfter(key, context, query.cursor) : "";
|
|
7085
|
-
if (after && !this.d.board.guidanceVariantLocation(projectKey, task.id, task.created, after)) return { state: "unavailable" };
|
|
7086
|
-
const page = this.d.board.guidanceVariantPage(projectKey, task.id, task.created, after), selected = page.slice(0, GUIDANCE_PAGE_MAX_RECORDS);
|
|
7087
|
-
const evidence = this.guidanceEvidence(by, task, selected), current = this.guidanceReadFence(by, query, task, check);
|
|
7088
|
-
const fresh = this.d.board.guidanceVariantPage(projectKey, current.id, current.created, after);
|
|
7089
|
-
if (JSON.stringify(page) !== JSON.stringify(fresh)) return { state: "unavailable" };
|
|
7090
|
-
const records: GuidancePublicRecord[] = [];
|
|
7091
|
-
for (const [index, record] of selected.entries()) {
|
|
7092
|
-
const candidate = this.guidanceProjection(by, current, record, evidence[index]!);
|
|
7093
|
-
const sized = { state: "available", current: this.guidanceCurrent(current), records: [...records, candidate], truncated: true, cursor: guidancePageCursor(key, context, candidate.id) };
|
|
7094
|
-
if (Buffer.byteLength(JSON.stringify(sized)) > GUIDANCE_REPLY_MAX_BYTES) break;
|
|
7095
|
-
records.push(candidate);
|
|
7096
|
-
}
|
|
7097
|
-
const truncated = records.length < page.length;
|
|
7098
|
-
if (truncated && !records.length) return { state: "unavailable" };
|
|
7099
|
-
const result = parseGuidancePageResult({ state: "available", current: this.guidanceCurrent(current), records, truncated,
|
|
7100
|
-
...(truncated ? { cursor: guidancePageCursor(key, context, records.at(-1)!.id) } : {}) });
|
|
7101
|
-
check(); return result;
|
|
7102
|
-
} catch { return { state: "unavailable" }; }
|
|
7103
|
-
}
|
|
5001
|
+
guidanceProbesPending = (): number => this.guidance.guidanceProbesPending();
|
|
5002
|
+
|
|
5003
|
+
stopGuidanceProbes(...args: Parameters<GuidanceDomain["stopGuidanceProbes"]>): ReturnType<GuidanceDomain["stopGuidanceProbes"]> { return this.guidance.stopGuidanceProbes(...args); }
|
|
5004
|
+
|
|
5005
|
+
guidanceProbeRegister(...args: Parameters<GuidanceDomain["guidanceProbeRegister"]>): ReturnType<GuidanceDomain["guidanceProbeRegister"]> { return this.guidance.guidanceProbeRegister(...args); }
|
|
5006
|
+
|
|
5007
|
+
guidanceProbeShow(...args: Parameters<GuidanceDomain["guidanceProbeShow"]>): ReturnType<GuidanceDomain["guidanceProbeShow"]> { return this.guidance.guidanceProbeShow(...args); }
|
|
5008
|
+
|
|
5009
|
+
guidanceProbeReceipts(...args: Parameters<GuidanceDomain["guidanceProbeReceipts"]>): ReturnType<GuidanceDomain["guidanceProbeReceipts"]> { return this.guidance.guidanceProbeReceipts(...args); }
|
|
5010
|
+
|
|
5011
|
+
guidanceProbeStart(...args: Parameters<GuidanceDomain["guidanceProbeStart"]>): ReturnType<GuidanceDomain["guidanceProbeStart"]> { return this.guidance.guidanceProbeStart(...args); }
|
|
5012
|
+
|
|
5013
|
+
guidanceProbeCancel(...args: Parameters<GuidanceDomain["guidanceProbeCancel"]>): ReturnType<GuidanceDomain["guidanceProbeCancel"]> { return this.guidance.guidanceProbeCancel(...args); }
|
|
5014
|
+
|
|
5015
|
+
guidanceVariantCreate(...args: Parameters<GuidanceDomain["guidanceVariantCreate"]>): ReturnType<GuidanceDomain["guidanceVariantCreate"]> { return this.guidance.guidanceVariantCreate(...args); }
|
|
5016
|
+
|
|
5017
|
+
guidanceVariantWithdraw(...args: Parameters<GuidanceDomain["guidanceVariantWithdraw"]>): ReturnType<GuidanceDomain["guidanceVariantWithdraw"]> { return this.guidance.guidanceVariantWithdraw(...args); }
|
|
5018
|
+
|
|
5019
|
+
guidanceVariantRead(...args: Parameters<GuidanceDomain["guidanceVariantRead"]>): ReturnType<GuidanceDomain["guidanceVariantRead"]> { return this.guidance.guidanceVariantRead(...args); }
|
|
5020
|
+
|
|
5021
|
+
guidanceVariantDiff(...args: Parameters<GuidanceDomain["guidanceVariantDiff"]>): ReturnType<GuidanceDomain["guidanceVariantDiff"]> { return this.guidance.guidanceVariantDiff(...args); }
|
|
5022
|
+
|
|
5023
|
+
guidanceVariantList(...args: Parameters<GuidanceDomain["guidanceVariantList"]>): ReturnType<GuidanceDomain["guidanceVariantList"]> { return this.guidance.guidanceVariantList(...args); }
|
|
5024
|
+
|
|
5025
|
+
guidanceVariantApplicable(...args: Parameters<GuidanceDomain["guidanceVariantApplicable"]>): ReturnType<GuidanceDomain["guidanceVariantApplicable"]> { return this.guidance.guidanceVariantApplicable(...args); }
|
|
5026
|
+
|
|
5027
|
+
linkExecutionReference(...args: Parameters<ExperimentDomain["linkExecutionReference"]>): ReturnType<ExperimentDomain["linkExecutionReference"]> { return this.experiment.linkExecutionReference(...args); }
|
|
7104
5028
|
|
|
7105
|
-
/** Future probe admission must capture its own current runtime/turn fence; this boolean is no handoff receipt. */
|
|
7106
|
-
guidanceVariantApplicable(by: PeerId, input: unknown): boolean {
|
|
7107
|
-
try {
|
|
7108
|
-
const selected = parseGuidanceIdQuery(input), read = this.guidanceVariantDiff(by, selected);
|
|
7109
|
-
return read.state === "available" && read.record.applicable;
|
|
7110
|
-
} catch { /* Existing explicit experiment selectors keep the T2 metadata-only path. */ }
|
|
7111
|
-
try { if (parseGuidanceSelector(input).id === undefined) return false; } catch { return false; }
|
|
7112
|
-
const read = this.guidanceVariantRead(by, input);
|
|
7113
|
-
return read.state === "available" && read.records.length === 1 && read.records[0]!.applicable;
|
|
7114
|
-
}
|
|
7115
|
-
|
|
7116
|
-
/** A declaration carries no resolver, runner attestation, review approval or model-execution authority. */
|
|
7117
|
-
async linkExecutionReference(by: PeerId, input: unknown): Promise<{ id: string; taskId: number; reference: ExecutionReferenceV1; strength: "declared"; already: boolean }> {
|
|
7118
|
-
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");
|
|
7119
|
-
const check = this.requestCheck(by, () => this.studyHold() ? "execution links are held; inspect ahub status and retry after recovery or shutdown" : undefined);
|
|
7120
|
-
let proposed: ExecutionLinkInput;
|
|
7121
|
-
try { proposed = parseExecutionLinkInput(input); } catch { throw new PreEffectToolRefusal("execution link fields are invalid; refresh the task identity and use a bounded execution reference"); }
|
|
7122
|
-
return this.studyWrite(async () => {
|
|
7123
|
-
const context = () => {
|
|
7124
|
-
check();
|
|
7125
|
-
const ports = this.lineagePorts(by);
|
|
7126
|
-
if (!ports) throw new PreEffectToolRefusal("execution reference storage is unavailable; inspect ahub status before retrying");
|
|
7127
|
-
let task: Task;
|
|
7128
|
-
try { task = this.studyParent(proposed.taskId); } catch { throw new PreEffectToolRefusal("execution link task is unavailable in this project; refresh ahub task show before retrying"); }
|
|
7129
|
-
const role = by === task.owner ? ownerRoleOfClass(task.class) : by === task.reviewer ? "reviewer" : undefined;
|
|
7130
|
-
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");
|
|
7131
|
-
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");
|
|
7132
|
-
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");
|
|
7133
|
-
const from = proposed.from ?? taskExecutionReference(ports.projectKey, task.id, task.created);
|
|
7134
|
-
const scope = { id: task.id, created: task.created };
|
|
7135
|
-
const origin = executionOwnerSnapshot(ports, { root: from, task: scope });
|
|
7136
|
-
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");
|
|
7137
|
-
if (proposed.reference.tool === "ahub") {
|
|
7138
|
-
const target = executionOwnerSnapshot(ports, { root: proposed.reference, task: scope });
|
|
7139
|
-
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");
|
|
7140
|
-
}
|
|
7141
|
-
const metadata = JSON.stringify([from, proposed.reference]);
|
|
7142
|
-
if (!this.publicMetadataText(metadata)) throw new PreEffectToolRefusal("execution reference metadata is private or sensitive; use public metadata before retrying");
|
|
7143
|
-
return { ports, task, from, metadata, key: JSON.stringify([task.created, task.history.length, task.owner, task.reviewer, task.state, origin.source.revision]) };
|
|
7144
|
-
};
|
|
7145
|
-
const before = context();
|
|
7146
|
-
if (this.screenOn()) {
|
|
7147
|
-
const result = await this.screenCall(before.metadata);
|
|
7148
|
-
if (result.label !== "clear") throw new PreEffectToolRefusal("execution reference privacy screening did not clear the metadata; retry with public metadata when screening is available");
|
|
7149
|
-
}
|
|
7150
|
-
check();
|
|
7151
|
-
const current = context();
|
|
7152
|
-
if (current.key !== before.key) throw new PreEffectToolRefusal("execution link authority or source changed during admission; refresh the task and source references before retrying");
|
|
7153
|
-
const saved = this.d.board.recordExecutionReference(current.ports.projectKey, { ...proposed, from: current.from }, { by, at: this.d.now?.() ?? Date.now() });
|
|
7154
|
-
return { id: saved.record.id, taskId: saved.record.taskId, reference: saved.record.reference, strength: "declared", already: saved.already };
|
|
7155
|
-
});
|
|
7156
|
-
}
|
|
7157
5029
|
|
|
7158
5030
|
/** T1 records declared provenance only; no locator resolution or #901 judgment is manufactured. */
|
|
7159
5031
|
async evidenceRecord(by: PeerId, input: unknown): Promise<EvidenceReceipt> {
|
|
@@ -8083,7 +5955,7 @@ export class Tasks {
|
|
|
8083
5955
|
return this.recordLifecycle(by, id, receipt, records, spec?.carry);
|
|
8084
5956
|
}
|
|
8085
5957
|
|
|
8086
|
-
recordLifecycle(by: PeerId, id: unknown, input: unknown, deliverables?: DeliverableRecord[], specCarry?: object): Task {
|
|
5958
|
+
recordLifecycle(by: PeerId, id: unknown, input: unknown, deliverables?: DeliverableRecord[], specCarry?: object, syncRepair = false): Task {
|
|
8087
5959
|
requireLocalTaskPeer(by);
|
|
8088
5960
|
const task = this.stagedSpec(by, this.need(id, false, true), specCarry);
|
|
8089
5961
|
const config = this.d.sdlc?.config() ?? sdlcConfig(undefined);
|
|
@@ -8092,7 +5964,7 @@ export class Tasks {
|
|
|
8092
5964
|
const plannerStage = !!input && typeof input === "object" && !Array.isArray(input) && Object.hasOwn(input, "stage")
|
|
8093
5965
|
&& Object.keys(input).every(key => ["stage", "repo", "issue"].includes(key))
|
|
8094
5966
|
&& (definition?.actor === "planner" || definition?.actor === "owner/planner") && this.taskPlanner(task).includes(by);
|
|
8095
|
-
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");
|
|
5967
|
+
if (by !== USER && by !== task.owner && by !== task.reviewer && !plannerStage && !syncRepair) throw new PreEffectToolRefusal("only the task owner, reviewer or console user may record lifecycle evidence; a stage planner may record stage identity");
|
|
8096
5968
|
// The spec identity is person-owned in enforce. No observation cache or restart can reopen a relink bypass.
|
|
8097
5969
|
const specRelink = (task.sdlc?.repo !== undefined && next.repo !== task.sdlc.repo) || (task.sdlc?.issue !== undefined && next.issue !== task.sdlc.issue);
|
|
8098
5970
|
if (config.mode === "enforce" && by !== USER && specRelink) throw new PreEffectToolRefusal("only the person may relink an established repository or issue in enforce");
|
|
@@ -8182,14 +6054,6 @@ export class Tasks {
|
|
|
8182
6054
|
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;
|
|
8183
6055
|
}
|
|
8184
6056
|
|
|
8185
|
-
private surveyToolInput<T>(command: "start" | "report", field: string, rule: string, read: () => T): T {
|
|
8186
|
-
try { return surveyInputAt(field, rule, read); } catch (error) {
|
|
8187
|
-
const problem = surveyInputProblem(error) ?? { field, rule };
|
|
8188
|
-
const next = command === "report" ? "fix that field and resend hub_survey_report; tool description lists shape"
|
|
8189
|
-
: "fix that field and resend ahub sdlc survey start; ahub help sdlc survey lists shape";
|
|
8190
|
-
throw new PreEffectToolRefusal(`${problem.field}: ${problem.rule}; ${next}`);
|
|
8191
|
-
}
|
|
8192
|
-
}
|
|
8193
6057
|
/** #1658: an over-limit or malformed report is refused before any effect, naming the field and its limit as a survey is. */
|
|
8194
6058
|
private readbackToolInput(input: unknown): SpecReadbackReport {
|
|
8195
6059
|
try { return parseSpecReadbackReport(input); } catch (error) {
|
|
@@ -8197,56 +6061,6 @@ export class Tasks {
|
|
|
8197
6061
|
throw new PreEffectToolRefusal(`${problem.field}: ${problem.rule}; fix that field and resend hub_readback_report`);
|
|
8198
6062
|
}
|
|
8199
6063
|
}
|
|
8200
|
-
private surveyStarting = false;
|
|
8201
|
-
private surveyAdmit(by: PeerId, check: () => void): void {
|
|
8202
|
-
check();
|
|
8203
|
-
if ((this.d.sdlc?.config().mode ?? "off") === "off") throw new PreEffectToolRefusal("advisor surveys require lifecycle advise or enforce");
|
|
8204
|
-
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");
|
|
8205
|
-
const held = this.studyHold(); if (held) throw new PreEffectToolRefusal(held);
|
|
8206
|
-
}
|
|
8207
|
-
private surveyTask(by: PeerId, id: unknown, write = false): { task: Task; survey: StoredSurvey } {
|
|
8208
|
-
const task = this.need(this.studyNumber(id, "survey task")), survey = this.d.board.surveyOfTask(task.id, task.created);
|
|
8209
|
-
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");
|
|
8210
|
-
const owner = task.owner === by && this.d.bus.isRostered(by) && this.isConfiguredPlanner(by);
|
|
8211
|
-
const reviewer = task.reviewer === by && this.d.bus.isRostered(by) && !!this.d.roles?.[by]?.includes("reviewer");
|
|
8212
|
-
if (write ? !owner || task.state !== "in_progress" : by !== USER && !owner && !reviewer && !(this.configuredManualConductor(by) && this.d.bus.isRostered(by)))
|
|
8213
|
-
throw new PreEffectToolRefusal("survey reporting requires its assigned in-progress planner; readback requires its owner, reviewer, person or current conductor");
|
|
8214
|
-
return { task, survey };
|
|
8215
|
-
}
|
|
8216
|
-
private surveyPrivate(task: Task, by?: PeerId): boolean {
|
|
8217
|
-
return this.isPii(task) || task.signals.includes("pii") || task.signals.includes("pii_path") || !!(by && this.d.privateTurn?.(by));
|
|
8218
|
-
}
|
|
8219
|
-
/** The existing task routing chooses one planner; no worker, scanner, issue or fix is launched. */
|
|
8220
|
-
async surveyStart(by: PeerId, input: unknown = {}, fence?: () => string | undefined): Promise<{ task: number; survey: number; ref: string; focus?: SurveyFocus }> {
|
|
8221
|
-
const fields = this.surveyToolInput("start", "start", "must be a closed object with optional focus", () => surveyObject(input, ["focus"])), focus = fields.focus;
|
|
8222
|
-
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"); });
|
|
8223
|
-
const check = this.requestCheck(by, fence), authority = () => {
|
|
8224
|
-
this.surveyAdmit(by, check);
|
|
8225
|
-
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");
|
|
8226
|
-
};
|
|
8227
|
-
authority();
|
|
8228
|
-
if (this.observerExcluded(by) || this.reviewObserverTurn(by)) throw new PreEffectToolRefusal("survey start is unavailable from observer material");
|
|
8229
|
-
if (this.surveyStarting) throw new PreEffectToolRefusal("a survey is already starting");
|
|
8230
|
-
const repo = this.repositories.scope({}).key, source = this.d.auditSource;
|
|
8231
|
-
if (!source) throw new PreEffectToolRefusal("survey source unavailable; start the hub from the project checkout");
|
|
8232
|
-
const ref = source.head();
|
|
8233
|
-
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");
|
|
8234
|
-
if (this.d.board.surveyOpen(repo)) throw new PreEffectToolRefusal("a survey is already open; finish or cancel it first");
|
|
8235
|
-
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: <this task>, findings: [...]}; explicit vet decisions use vet: [...].\n${this.consideredBrief(repo, ref)}`;
|
|
8236
|
-
if (!this.publicMetadataText(brief)) throw new PreEffectToolRefusal("survey brief is not public");
|
|
8237
|
-
this.surveyStarting = true;
|
|
8238
|
-
try { return await this.studyWrite(async () => {
|
|
8239
|
-
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"); };
|
|
8240
|
-
guard();
|
|
8241
|
-
let surveyID: number | undefined;
|
|
8242
|
-
const task = await this.propose(by, { title: `Advisor survey${focus ? ` (${focus})` : ""} at ${ref.slice(0, 12)}`, detail: brief, class: "plan" }, undefined, undefined,
|
|
8243
|
-
() => { guard(); return undefined; }, created => {
|
|
8244
|
-
if (this.surveyPrivate(created, by)) throw new PreEffectToolRefusal("survey brief privacy was not cleared");
|
|
8245
|
-
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() });
|
|
8246
|
-
});
|
|
8247
|
-
return { task: task.id, survey: surveyID!, ref, ...(focus === undefined ? {} : { focus: focus as SurveyFocus }) };
|
|
8248
|
-
}); } finally { this.surveyStarting = false; }
|
|
8249
|
-
}
|
|
8250
6064
|
private consideredChanges(repo: string, ref?: string): (entryRef?: string) => string[] | undefined {
|
|
8251
6065
|
// 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.
|
|
8252
6066
|
const cache = new Map<string, string[] | undefined>(); let currentKnown: boolean | undefined;
|
|
@@ -8359,87 +6173,6 @@ export class Tasks {
|
|
|
8359
6173
|
.catch(() => this.releaseNotice(`task #${task.id}: considered rejection ledger unavailable`));
|
|
8360
6174
|
});
|
|
8361
6175
|
}
|
|
8362
|
-
surveyShow(by: PeerId, id: unknown) {
|
|
8363
|
-
const check = this.requestCheck(by); this.surveyAdmit(by, check);
|
|
8364
|
-
const { task, survey } = this.surveyTask(by, id);
|
|
8365
|
-
if (this.surveyPrivate(task, by)) return { task: task.id, status: "private" as const };
|
|
8366
|
-
const revision = this.d.board.statusRevision(), policy = JSON.stringify([this.d.roles, this.d.routing(), this.d.piiPaths]);
|
|
8367
|
-
const full = by === USER || this.d.bus.isRostered(by) && (task.owner === by && this.isConfiguredPlanner(by) || task.reviewer === by && !!this.d.roles?.[by]?.includes("reviewer"));
|
|
8368
|
-
const stored = this.d.board.surveyFindings(survey.id), changes = this.consideredChanges(survey.repo, survey.ref);
|
|
8369
|
-
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 };
|
|
8370
|
-
const items = stored.map(row => {
|
|
8371
|
-
const finding = full ? row.finding : publicSurveyFinding(row.finding), before = this.consideredBefore(task, row.finding, survey.ref, changes);
|
|
8372
|
-
const details = this.consideredDetails(survey.repo, row.finding.id, row.finding.pass, survey.ref, changes);
|
|
8373
|
-
return { ...finding, ...(row.decision ? { verdict: row.decision.verdict } : {}), ...before, rejected: details.items, rejectedComplete: details.complete };
|
|
8374
|
-
});
|
|
8375
|
-
this.surveyAdmit(by, check);
|
|
8376
|
-
const now = this.surveyTask(by, id);
|
|
8377
|
-
if (this.surveyPrivate(now.task, by)) return { task: task.id, status: "private" as const };
|
|
8378
|
-
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");
|
|
8379
|
-
return { task: task.id, survey: survey.id, ref: survey.ref, ...(survey.focus ? { focus: survey.focus } : {}), status: "available" as const, items };
|
|
8380
|
-
}
|
|
8381
|
-
async surveyReport(by: PeerId, input: unknown, fence?: () => string | undefined) {
|
|
8382
|
-
const fields = this.surveyToolInput("report", "report", "must be a closed object with id and findings, vet or show", () => surveyObject(input, ["id", "findings", "vet", "show"]));
|
|
8383
|
-
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"); });
|
|
8384
|
-
this.surveyToolInput("report", "show", "must be true for read-only show and cannot include findings or vet decisions", () => {
|
|
8385
|
-
if (fields.show !== undefined && fields.show !== true || fields.show && (fields.findings !== undefined || fields.vet !== undefined)) throw new Error("invalid bounded survey data");
|
|
8386
|
-
});
|
|
8387
|
-
if (fields.show) { this.requestCheck(by, fence)(); return this.surveyShow(by, fields.id); }
|
|
8388
|
-
const findings = fields.findings === undefined ? [] : this.surveyToolInput("report", "findings", "must match the documented finding array", () => parseSurveyFindings(fields.findings));
|
|
8389
|
-
const decisions = fields.vet === undefined ? [] : this.surveyToolInput("report", "vet", "must match the documented vet array", () => parseSurveyVetDecisions(fields.vet));
|
|
8390
|
-
const check = this.requestCheck(by, fence), guard = () => { this.surveyAdmit(by, check); return this.surveyTask(by, fields.id, true); };
|
|
8391
|
-
const initial = guard();
|
|
8392
|
-
if (this.surveyPrivate(initial.task, by) || this.observerExcluded(by) || this.reviewObserverTurn(by)) throw new PreEffectToolRefusal("survey writes unavailable during private or observer work");
|
|
8393
|
-
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");
|
|
8394
|
-
const observerExcluded = this.observerExcluded(by); // Capture before any awaited screen; never forward observer material.
|
|
8395
|
-
if (observerExcluded) throw new PreEffectToolRefusal("survey observer input is unavailable");
|
|
8396
|
-
return this.studyWrite(async () => {
|
|
8397
|
-
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]);
|
|
8398
|
-
const current = () => {
|
|
8399
|
-
const now = guard();
|
|
8400
|
-
if (now.task.created !== task.created || now.task.history.length !== task.history.length || now.task.owner !== task.owner || this.surveyPrivate(now.task, by)
|
|
8401
|
-
|| 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");
|
|
8402
|
-
};
|
|
8403
|
-
const existing = this.d.board.surveyFindings(survey.id), merged = new Map(existing.map(row => [row.finding.id, row.finding]));
|
|
8404
|
-
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); }
|
|
8405
|
-
const text = JSON.stringify({ findings: this.surveyToolInput("report", "findings", "combined findings must remain within the documented bounds", () => parseSurveyFindings([...merged.values()])), decisions });
|
|
8406
|
-
if (!this.publicMetadataText(text)) throw new PreEffectToolRefusal("survey metadata was not cleared as public");
|
|
8407
|
-
if (this.screenOn() && (await this.screenCall(text)).label !== "clear") throw new PreEffectToolRefusal("survey metadata privacy screening was unavailable or refused");
|
|
8408
|
-
current();
|
|
8409
|
-
const changes = this.consideredChanges(survey.repo, survey.ref);
|
|
8410
|
-
const cards: SurveyPreparedCard[] = [], rejections: ConsideredEntry[] = [], reconsiderations: ConsideredEntry[] = [];
|
|
8411
|
-
const items: { id: string; rejectedBefore: boolean; change: "none" | "unchanged" | "changed" | "unknown"; suppressed: boolean }[] = [];
|
|
8412
|
-
for (const decision of decisions) {
|
|
8413
|
-
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");
|
|
8414
|
-
const before = this.consideredBefore(task, finding, survey.ref, changes); items.push({ id: finding.id, ...before });
|
|
8415
|
-
const entry = (reason: string): ConsideredEntry => ({ repo: survey.repo, id: finding.id, pass: finding.pass, paths: finding.paths, reason, ref: survey.ref,
|
|
8416
|
-
source: { task: task.id, created: task.created, kind: "survey" }, ...(finding.pass === "security" ? { withheld: true } : {}) });
|
|
8417
|
-
if (decision.verdict === "rejected") { rejections.push(entry(decision.reason!)); continue; }
|
|
8418
|
-
if (before.suppressed && !decision.reason) continue;
|
|
8419
|
-
if (before.rejectedBefore && decision.reason) reconsiderations.push(entry(decision.reason));
|
|
8420
|
-
const key = surveyFindingKey(survey.repo, finding.pass, finding.id), security = finding.pass === "security";
|
|
8421
|
-
const history = this.d.board.surveyCardHistory(key), reopens = history.active ? undefined : history.closed;
|
|
8422
|
-
current();
|
|
8423
|
-
const reopenReason = security ? "explicit current vet; security details remain in the authorized survey"
|
|
8424
|
-
: decision.reason ?? (before.change === "changed" ? "affected paths changed since the recorded rejection" : "explicit current vet; no applicable rejected finding remains");
|
|
8425
|
-
const reopening = reopens === undefined ? {} : { reopens, reopenReason };
|
|
8426
|
-
const draft = { title: security ? `Survey security finding ${finding.id}` : `Survey ${finding.confidence}: ${finding.id}`,
|
|
8427
|
-
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}`}`,
|
|
8428
|
-
refs: security ? {} : { paths: finding.paths } };
|
|
8429
|
-
if (Buffer.byteLength(draft.detail) > SURVEY_LIMITS.cardBytes) throw new PreEffectToolRefusal("survey card exceeds its detail bound; shorten the finding or reconsideration reason");
|
|
8430
|
-
const signals = this.signalsFor(draft);
|
|
8431
|
-
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");
|
|
8432
|
-
if (this.screenOn() && (await this.screenCall(JSON.stringify(draft))).label !== "clear") throw new PreEffectToolRefusal("survey card privacy screening was unavailable or refused");
|
|
8433
|
-
current(); cards.push({ id: finding.id, key, ...draft, class: finding.confidence === "low" ? "triage" : "plan", signals, ...reopening });
|
|
8434
|
-
}
|
|
8435
|
-
current();
|
|
8436
|
-
const result = this.d.board.surveyApply(survey.id, { findings, decisions, by, at: this.d.now?.() ?? Date.now(), cards, rejections, reconsiderations },
|
|
8437
|
-
{ boardRevision, taskCreated: task.created, taskFlowRevision: task.history.length, owner: task.owner! });
|
|
8438
|
-
for (const id of result.createdIDs) this.incomingBacklog.add(id);
|
|
8439
|
-
this.releaseNotice(`survey task ${task.id}: ${result.createdIDs.length} backlog candidates created`);
|
|
8440
|
-
return { task: task.id, survey: survey.id, status: "recorded" as const, ...result, items };
|
|
8441
|
-
});
|
|
8442
|
-
}
|
|
8443
6176
|
|
|
8444
6177
|
/** #1658: a read-back is a report for the person, so it is unavailable wherever a private or child session could carry text out. */
|
|
8445
6178
|
private readbackAdmit(by: PeerId, check: () => void): void {
|
|
@@ -8753,6 +6486,44 @@ export class Tasks {
|
|
|
8753
6486
|
return { ...this.auditView(full, true), ...(skipped.length ? { notUpdated: skipped } : {}) };
|
|
8754
6487
|
}
|
|
8755
6488
|
|
|
6489
|
+
/**
|
|
6490
|
+
* #1856 T4: `ahub sdlc sync --close-settled-issues` runs only under roadmap apply authority (the person, or the unique conductor with roadmap.github_write = "conductor").
|
|
6491
|
+
* Returns the host-sampled repository; the refusal names the person's own command.
|
|
6492
|
+
*/
|
|
6493
|
+
closeSettledGate(by: PeerId): string {
|
|
6494
|
+
try { this.roadmapApplyAuthority(by); return this.roadmapRepository(); }
|
|
6495
|
+
catch (error) {
|
|
6496
|
+
if (error instanceof PreEffectToolRefusal) throw new PreEffectToolRefusal(`${error.message}; the person runs ahub sdlc sync --close-settled-issues, then the same command with --apply --confirm <fingerprint>`);
|
|
6497
|
+
throw error;
|
|
6498
|
+
}
|
|
6499
|
+
}
|
|
6500
|
+
|
|
6501
|
+
/** One `gh issue close` of a settled issue, after the authority and origin are re-checked. Never touches a milestone. */
|
|
6502
|
+
async closeSettledIssue(by: PeerId, repo: string, issue: number): Promise<void> {
|
|
6503
|
+
if (this.closeSettledGate(by).toLowerCase() !== repo.toLowerCase() || !Number.isSafeInteger(issue) || issue <= 0) throw new PreEffectToolRefusal("roadmap GitHub origin changed; preview again with ahub sdlc sync --close-settled-issues");
|
|
6504
|
+
let result: Awaited<ReturnType<SdlcGh>>;
|
|
6505
|
+
try { result = await this.roadmapGh()(["issue", "close", String(issue), "--repo", repo, "--reason", "completed"], 10_000, undefined, 64 * 1024); }
|
|
6506
|
+
catch { throw new Error("issue close outcome is unknown; inspect the issue before retrying"); }
|
|
6507
|
+
if (result.code !== 0) throw new Error("issue close was not confirmed; inspect the issue before retrying");
|
|
6508
|
+
}
|
|
6509
|
+
|
|
6510
|
+
/**
|
|
6511
|
+
* #1856 T3: one sync repair written under the real actor. Only the person or the one configured conductor on the roster; the entry names that actor.
|
|
6512
|
+
* The writer is admitted past the owner and reviewer rule for exactly a link ({repo, issue}) or a bind ({repo, pr, localHead}), never a relink and never deliverables.
|
|
6513
|
+
*/
|
|
6514
|
+
recordSyncRepair(by: PeerId, id: number, input: { repo: string; issue?: number; pr?: number; localHead?: string }): Task {
|
|
6515
|
+
if (by !== USER && (!this.configuredManualConductor(by) || !this.d.bus.isRostered(by)))
|
|
6516
|
+
throw new PreEffectToolRefusal("only the person or the current configured conductor may apply a sync; ask the person to run ahub sdlc sync --apply --confirm <fingerprint>");
|
|
6517
|
+
if (this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("sync is unavailable in a private turn; finish that turn and retry ahub sdlc sync");
|
|
6518
|
+
const keys = Object.keys(input).sort().join(",");
|
|
6519
|
+
if (keys !== "issue,repo" && keys !== "localHead,pr,repo") throw new PreEffectToolRefusal("a sync repair is a link {repo, issue} or a bind {repo, pr, localHead}; record anything else with ahub sdlc record");
|
|
6520
|
+
const task = this.need(id, false, true), had = task.sdlc;
|
|
6521
|
+
if (had?.repo !== undefined && had.repo.toLowerCase() !== input.repo.toLowerCase() || input.issue !== undefined && had?.issue !== undefined)
|
|
6522
|
+
throw new PreEffectToolRefusal("a sync repair never relinks an established repository or issue; record the change with ahub sdlc record");
|
|
6523
|
+
if (input.pr !== undefined && had?.pr !== undefined && had.pr !== input.pr) throw new PreEffectToolRefusal("a sync repair never replaces a recorded PR; record the change with ahub sdlc record");
|
|
6524
|
+
return this.recordLifecycle(by, id, input, undefined, undefined, true);
|
|
6525
|
+
}
|
|
6526
|
+
|
|
8756
6527
|
/** #1328 T3: approve a merge observed outside the hub, without attributing a verdict to a reviewer. */
|
|
8757
6528
|
async adoptMerge(by: PeerId, id: unknown, pr: unknown, fence?: () => string | undefined): Promise<{ task: number; state: "approved" }> {
|
|
8758
6529
|
const check = this.requestCheck(by, fence);
|
|
@@ -11571,9 +9342,9 @@ export class Tasks {
|
|
|
11571
9342
|
* Budget relay: a paused peer's open work moves on. `local` first (it has no quota), then the class list, all through
|
|
11572
9343
|
* the usual constraints. Tasks it was reviewing get another reviewer. Moves are reported, never taken back automatically.
|
|
11573
9344
|
*/
|
|
11574
|
-
async reassignForPause(peer: PeerId, context: string | undefined, urgentOnly = false): Promise<{ id: number; title: string; to: PeerId | null; role: "owner" | "reviewer" }[]> {
|
|
9345
|
+
async reassignForPause(peer: PeerId, context: string | undefined, urgentOnly = false, also: readonly PeerId[] = []): Promise<{ id: number; title: string; to: PeerId | null; role: "owner" | "reviewer" }[]> {
|
|
11575
9346
|
requireLocalTaskPeer(peer);
|
|
11576
|
-
return this.reassignWork(peer, context, urgentOnly, false);
|
|
9347
|
+
return this.reassignWork(peer, context, urgentOnly, false, undefined, also);
|
|
11577
9348
|
}
|
|
11578
9349
|
|
|
11579
9350
|
/** Read-only preview using the same assignment constraints as the roster relay. */
|
|
@@ -11596,7 +9367,7 @@ export class Tasks {
|
|
|
11596
9367
|
return this.reassignWork(peer, undefined, false, true, current);
|
|
11597
9368
|
}
|
|
11598
9369
|
|
|
11599
|
-
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" }[]> {
|
|
9370
|
+
private async reassignWork(peer: PeerId, context: string | undefined, urgentOnly: boolean, roster: boolean, current?: () => void, also: readonly PeerId[] = []): Promise<{ id: number; title: string; to: PeerId | null; role: "owner" | "reviewer" }[]> {
|
|
11600
9371
|
current?.();
|
|
11601
9372
|
const moved: { id: number; title: string; to: PeerId | null; role: "owner" | "reviewer" }[] = [];
|
|
11602
9373
|
const routing = this.d.routing(), why = roster ? `roster removal of ${peer}` : `budget pause of ${peer}`;
|
|
@@ -11610,13 +9381,13 @@ export class Tasks {
|
|
|
11610
9381
|
if (task.owner === peer && (OPEN.includes(task.state) || roster && task.state === "in_review")) {
|
|
11611
9382
|
const pii = this.isPii(task);
|
|
11612
9383
|
const candidates = relayCandidates(routing.classes[task.class]?.peers ?? [], pii, { ...this.instanceRouting(), states: this.states() });
|
|
11613
|
-
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;
|
|
9384
|
+
if (this.plannerPullRecord(task)?.pull && !assign(task, this.states(), routing, { candidates, exclude: [...this.excluded(task), peer, ...also], excludeOwners: this.plannerFull(task), waitsFor: this.waitsFor(task), ...this.weights(task.class, task) }).owner) continue;
|
|
11614
9385
|
// Budget keeps its original release/unassign behaviour for ordinary work. Roster changes the state in
|
|
11615
9386
|
// assignOwner's same owner write only after routing has found somebody to take it.
|
|
11616
9387
|
const back = !roster && task.state === "in_progress" ? this.d.board.update(task.id, HUB, "released", { state: "proposed" }, why) : task;
|
|
11617
9388
|
let next: Task;
|
|
11618
9389
|
try {
|
|
11619
|
-
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 } : {}) });
|
|
9390
|
+
next = await this.assignOwner(back, HUB, { current, candidates, exclude: [peer, ...also], event: "reassigned", reason: roster ? "manual" : "budget", note: why, ...(roster ? { roster: true } : { clearOnFail: true }), ...(context ? { context, contextWithheld } : {}) });
|
|
11620
9391
|
} catch (e) {
|
|
11621
9392
|
// The move is saved and its central #297 notice already spoke; relay the
|
|
11622
9393
|
// remaining tasks and run the roster tail on the saved row as on success.
|
|
@@ -11634,7 +9405,7 @@ export class Tasks {
|
|
|
11634
9405
|
current?.();
|
|
11635
9406
|
moved.push({ id: task.id, title: this.publicTitle(task), to: next.owner, role: "owner" });
|
|
11636
9407
|
} else if (task.reviewer === peer && !isClosedTaskState(task.state)) {
|
|
11637
|
-
const a = assign(task, this.states(), routing, { ...(roster ? { exclude: [peer] } : {}), candidates: [], ...(task.owner ? { notReviewer: task.owner } : {}), ...this.weights(task.class, task) });
|
|
9408
|
+
const a = assign(task, this.states(), routing, { ...(roster ? { exclude: [peer] } : also.length ? { exclude: [peer, ...also] } : {}), candidates: [], ...(task.owner ? { notReviewer: task.owner } : {}), ...this.weights(task.class, task) });
|
|
11638
9409
|
const reviewer = !a.reviewSelection?.quotaWait && a.reviewer && a.reviewer !== peer && a.reviewer !== task.owner ? a.reviewer : null;
|
|
11639
9410
|
if (roster && !reviewer) {
|
|
11640
9411
|
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}`);
|
|
@@ -11704,7 +9475,7 @@ export class Tasks {
|
|
|
11704
9475
|
* #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
|
|
11705
9476
|
* review (stored, not yet evidence), `not_saved` a note nothing took. A refusal still throws and never reaches here.
|
|
11706
9477
|
*/
|
|
11707
|
-
async rememberOutcome(by: PeerId, input: RememberInput, review?: Task): Promise<{ message: string; outcome: "saved" | "candidate" | "not_saved" }> {
|
|
9478
|
+
async rememberOutcome(by: PeerId, input: RememberInput, review?: Task, writerSession?: string): Promise<{ message: string; outcome: "saved" | "candidate" | "not_saved" }> {
|
|
11708
9479
|
const requestCheck = this.requestCheck(by);
|
|
11709
9480
|
const text = composeRememberText(input);
|
|
11710
9481
|
const task = input.task !== undefined ? this.d.board.get(Number(input.task)) : undefined;
|
|
@@ -11735,7 +9506,7 @@ export class Tasks {
|
|
|
11735
9506
|
const id = this.d.candidates.put({ project: this.d.store.project, ...proposal.input }, "public", proposal.origin);
|
|
11736
9507
|
return { message: `candidate:${id}; a memory review proposes only, and a person accepts it with amem review; task #${review.id} changed no note`, outcome: "candidate" };
|
|
11737
9508
|
}
|
|
11738
|
-
const native = this.saveNative(by, kind, text, title, task, input.horizon === "long" || input.horizon === "short" ? input.horizon : undefined, input.scope === "shared" ? "shared" : "project");
|
|
9509
|
+
const native = this.saveNative(by, kind, text, title, task, input.horizon === "long" || input.horizon === "short" ? input.horizon : undefined, input.scope === "shared" ? "shared" : "project", undefined, captureSessionKey(writerSession));
|
|
11739
9510
|
if (native && "refused" in native) throw new PreEffectToolRefusal(`${native.refused}; save it with horizon "short" or correct the machine/repository privacy policy, then retry`);
|
|
11740
9511
|
if (task && this.d.memory) this.markMemoryReference(task, by);
|
|
11741
9512
|
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;
|
|
@@ -11791,7 +9562,7 @@ export class Tasks {
|
|
|
11791
9562
|
* long, decisions, contracts and fails are long-term. Fail-open: a store that cannot be written costs one notice.
|
|
11792
9563
|
* The caller has screened the text for PII; never a PII task's.
|
|
11793
9564
|
*/
|
|
11794
|
-
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 {
|
|
9565
|
+
private saveNative(by: PeerId, kind: Kind, text: string, title: string, task: Task | undefined, horizon?: Tier, scope: Scope = "project", symbols?: MemorySymbolNodes, session?: string): { id: string; tier: Tier; about: string[] } | { refused: string } | undefined {
|
|
11795
9566
|
const st = this.d.store;
|
|
11796
9567
|
if (!st || (task && this.isPii(task))) return undefined;
|
|
11797
9568
|
let longTerm = horizon === "long" || (horizon !== "short" && !!task && task.state === "approved" && PROMOTED_KINDS.includes(kind));
|
|
@@ -11818,7 +9589,7 @@ export class Tasks {
|
|
|
11818
9589
|
} catch { return { refused: "machine privacy policy unavailable" }; }
|
|
11819
9590
|
}
|
|
11820
9591
|
if (task) this.markMemoryReference(task, by);
|
|
11821
|
-
const id = st.store.note(row, horizon === "short");
|
|
9592
|
+
const id = st.store.note(row, { ownClock: horizon === "short", ...(session === undefined ? {} : { session }) });
|
|
11822
9593
|
try { st.onNote?.(id); } catch { /* The native note is committed; an observer cannot make it fail. */ }
|
|
11823
9594
|
return { id, tier, about: [...about] };
|
|
11824
9595
|
} catch (e) {
|