@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
|
@@ -0,0 +1,661 @@
|
|
|
1
|
+
// #1830 S4a: the study and synthesis methods of `Tasks`, moved whole. `Tasks` builds one `StudyDomain` with its deps and an explicit host (the callbacks the moved bodies reach), keeps a one-line
|
|
2
|
+
// delegating method for each member it or the other domain still uses, and stays the only board writer: every board write here runs inside a `Tasks` callback or a host
|
|
3
|
+
// method. No module-level state: the counters and flags live on the instance. Never imported by adapters, tools or the CLI.
|
|
4
|
+
import { instructedExecution } from "./instructed-exact.ts";
|
|
5
|
+
import { checkSynthesis, inventoryBinding, parseSynthesisManifest, type SynthesisManifestV1, type SynthesisCurrent, type SynthesisCurrentClaim, type SynthesisArtifactSnapshot, type SynthesisReadiness } from "./synthesis-readiness.ts";
|
|
6
|
+
import { type EvidenceLinkV1 } from "./research-evidence.ts";
|
|
7
|
+
import { type EvidenceSourceRead } from "./source-read.ts";
|
|
8
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
9
|
+
import { types } from "node:util";
|
|
10
|
+
import { parseResearchHandoff, studyProjection, campaignHash, parseResearchCampaign, type ResearchCampaignContract } from "./research-campaign.ts";
|
|
11
|
+
import type { ResearchCampaignRecord, PreparedResearchUnit } from "./board.ts";
|
|
12
|
+
import { unitId } from "./security-audit.ts";
|
|
13
|
+
import { profileClass } from "./profiles.ts";
|
|
14
|
+
import { latestDeliverables } from "./deliverables.ts";
|
|
15
|
+
import { readGuardedDeliverable, guardedDeliverableCurrent, type GuardedDeliverableRead, type DeliverablePorts } from "./deliverable-files.ts";
|
|
16
|
+
import { resolve } from "node:path";
|
|
17
|
+
import { looksSecret } from "@staix/agent-mem";
|
|
18
|
+
import { taskClaimIdentity, type Board, type Task, type TaskPlan, type TaskRefs, type PlannerBinding } from "./board.ts";
|
|
19
|
+
import { USER, type PeerId, type PeerState } from "./envelope.ts";
|
|
20
|
+
import type { ScreenItem } from "./inference.ts";
|
|
21
|
+
import { detectSignals, type Assignment } from "./routing.ts";
|
|
22
|
+
import { TaskRepositories } from "./task-repository.ts";
|
|
23
|
+
import { PreEffectToolRefusal } from "./tool-refusal.ts";
|
|
24
|
+
import type { TasksDeps, ResearchCampaignReceipt } from "./tasks.ts";
|
|
25
|
+
|
|
26
|
+
interface StudyReferences { parent: Task; adopted: Map<string, Task>; reused: Map<string, Task>; private: boolean; key: string }
|
|
27
|
+
|
|
28
|
+
/** What the moved methods call back into `Tasks` for: each member is the `Tasks` member of that name, unchanged. */
|
|
29
|
+
export interface StudyHost {
|
|
30
|
+
taskShowAllowed(actor: string, task: Pick<Task, "state" | "owner" | "reviewer">, roles: unknown, planner: boolean): boolean;
|
|
31
|
+
cleanRefs(input: unknown): TaskRefs;
|
|
32
|
+
readonly coordinationModes: Map<number, boolean>;
|
|
33
|
+
deliverablePorts(task: Task, policy?: { failClosedOnDiscoveryLimit?: boolean }): DeliverablePorts;
|
|
34
|
+
experimentOutputPrivate(task: Task, path: string): boolean;
|
|
35
|
+
readonly incomingBacklog: Set<number>;
|
|
36
|
+
isConfiguredPlanner(peer: PeerId): boolean;
|
|
37
|
+
readonly isPii: (task: Pick<Task, "signals">) => boolean;
|
|
38
|
+
readonly nameable: (text: string) => boolean;
|
|
39
|
+
need(id: unknown, open?: boolean, preEffect?: boolean, allowBacklog?: boolean): Task;
|
|
40
|
+
places(task: Task): { repositoryKey: string; paths: string[]; symbols: string[] };
|
|
41
|
+
plannerWriteAuthority(by: PeerId, task?: Pick<Task, "planner">): void;
|
|
42
|
+
proposalPlanner(task: Task): PlannerBinding;
|
|
43
|
+
readonly publicMetadataText: (text: string) => boolean;
|
|
44
|
+
readonly publicTitle: (task: Task) => string;
|
|
45
|
+
releaseNotice(line: string, run?: () => unknown): void;
|
|
46
|
+
readonly repositories: TaskRepositories;
|
|
47
|
+
requestCheck(by: PeerId, fence?: () => string | undefined): () => void;
|
|
48
|
+
requireLocalTaskPeer(peer: unknown): void;
|
|
49
|
+
sendTask(task: Task, a: Assignment, context?: string, overlap?: string, contextWithheld?: boolean, currentAuthority?: () => void): Promise<void>;
|
|
50
|
+
signalsFor(task: Pick<Task, "title" | "detail" | "refs"> & { plan?: TaskPlan }, routing?: ReturnType<TasksDeps["routing"]>): ReturnType<typeof detectSignals>;
|
|
51
|
+
states(): Record<PeerId, PeerState>;
|
|
52
|
+
warmRepository(task: Pick<Task, "refs" | "plan">): void;
|
|
53
|
+
withholds(item: ScreenItem, text: unknown, task?: Task): Promise<boolean>;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export class StudyDomain {
|
|
57
|
+
constructor(private readonly d: TasksDeps, private readonly host: StudyHost) {}
|
|
58
|
+
|
|
59
|
+
private studiesRunning = 0;
|
|
60
|
+
|
|
61
|
+
private studyStopped = false;
|
|
62
|
+
|
|
63
|
+
private readonly studyDrainWaiters = new Set<() => void>();
|
|
64
|
+
|
|
65
|
+
studiesPending = (): number => this.studiesRunning;
|
|
66
|
+
|
|
67
|
+
async stopStudies(): Promise<void> {
|
|
68
|
+
this.studyStopped = true;
|
|
69
|
+
if (this.studiesRunning) await new Promise<void>(resolve => this.studyDrainWaiters.add(resolve));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
studyHold(): string | undefined {
|
|
73
|
+
try {
|
|
74
|
+
if (this.studyStopped || this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError)
|
|
75
|
+
return "study writes are held by recovery, shutdown or storage failure";
|
|
76
|
+
} catch { return "study write admission is unavailable"; }
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async studyWrite<T>(write: () => Promise<T>): Promise<T> {
|
|
81
|
+
this.studiesRunning++;
|
|
82
|
+
try { return await write(); } finally {
|
|
83
|
+
if (--this.studiesRunning === 0) { for (const resolve of this.studyDrainWaiters) resolve(); this.studyDrainWaiters.clear(); }
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
studyFields(input: unknown, allowed: readonly string[]): Record<string, unknown> {
|
|
88
|
+
if (!input || typeof input !== "object" || Array.isArray(input) || types.isProxy(input)
|
|
89
|
+
|| ![Object.prototype, null].includes(Object.getPrototypeOf(input)) || Object.getOwnPropertySymbols(input).length)
|
|
90
|
+
throw new PreEffectToolRefusal("study request must be a plain data object");
|
|
91
|
+
const fields = Object.getOwnPropertyDescriptors(input);
|
|
92
|
+
if (Object.entries(fields).some(([key, descriptor]) => !allowed.includes(key) || !Object.hasOwn(descriptor, "value")))
|
|
93
|
+
throw new PreEffectToolRefusal("study request has unknown fields or accessors");
|
|
94
|
+
return Object.fromEntries(Object.entries(fields).map(([key, descriptor]) => [key, descriptor.value]));
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
studyId(value: unknown): string {
|
|
98
|
+
if (typeof value !== "string" || !/^rc-[a-f0-9]{12}$/.test(value)) throw new PreEffectToolRefusal("study id is invalid");
|
|
99
|
+
return value;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
studyNumber(value: unknown, field: string): number {
|
|
103
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) throw new PreEffectToolRefusal(`${field} must be a positive integer`);
|
|
104
|
+
return value;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
private studyContract(value: unknown): ResearchCampaignContract {
|
|
108
|
+
try { return parseResearchCampaign(value); }
|
|
109
|
+
catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid study contract"); }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
studyTime(): number {
|
|
113
|
+
const now = this.d.studyNow?.() ?? Date.now();
|
|
114
|
+
if (!Number.isFinite(now)) throw new PreEffectToolRefusal("study clock is unavailable");
|
|
115
|
+
return now;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
studyRecord(id: string, revision?: number): ResearchCampaignRecord {
|
|
119
|
+
let record: ResearchCampaignRecord | undefined;
|
|
120
|
+
try { record = this.d.board.researchCampaign(id, revision); }
|
|
121
|
+
catch { throw new PreEffectToolRefusal("study record is unavailable or invalid"); }
|
|
122
|
+
if (!record || record.project !== this.d.project) throw new PreEffectToolRefusal("study is unavailable in this project");
|
|
123
|
+
return record;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
studyParent(id: number): Task {
|
|
127
|
+
const parent = this.host.need(id, false, true, true);
|
|
128
|
+
if (this.host.places(parent).repositoryKey !== this.host.repositories.scope({}).key) throw new PreEffectToolRefusal("study parent is outside this project");
|
|
129
|
+
return parent;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Write receipts expose no contract text; only person-only approval returns the unit mapping. */
|
|
133
|
+
private studyReceipt(record: ResearchCampaignRecord, includeMapping = false): ResearchCampaignReceipt {
|
|
134
|
+
const units = this.d.board.researchCampaignBindings(record.id, record.revision);
|
|
135
|
+
return { id: record.id, parentTaskId: record.parentTaskId, revision: record.revision, status: record.status,
|
|
136
|
+
unitCount: units.length, units: includeMapping ? units : [] };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
studySource(id: string): { id: string; sha256: string; private: boolean } | undefined {
|
|
140
|
+
try {
|
|
141
|
+
const source = this.d.studySource?.(id);
|
|
142
|
+
return source && source.id === id && /^[a-f0-9]{64}$/.test(source.sha256) && typeof source.private === "boolean"
|
|
143
|
+
? { id: source.id, sha256: source.sha256, private: source.private } : undefined;
|
|
144
|
+
} catch { return undefined; }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private studyLatest(id: string, revision: number): ResearchCampaignRecord {
|
|
148
|
+
const record = this.studyRecord(id);
|
|
149
|
+
if (record.revision !== revision || record.status === "closed") throw new PreEffectToolRefusal("study revision is stale or closed");
|
|
150
|
+
return record;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
private studyFamily(parent: Task): Set<number> {
|
|
154
|
+
if (!parent.history.some(entry => entry.event === "draft approved")) throw new PreEffectToolRefusal("adoption requires an approved intake family");
|
|
155
|
+
const family = new Set<number>(), pending = [...(parent.deps ?? [])];
|
|
156
|
+
// ponytail: 512 dependency nodes bound intake provenance walks; a larger family needs indexed family identities.
|
|
157
|
+
while (pending.length) {
|
|
158
|
+
const id = pending.pop()!;
|
|
159
|
+
if (family.has(id)) continue;
|
|
160
|
+
if (family.size >= 512) throw new PreEffectToolRefusal("study intake family exceeds its bounded scope");
|
|
161
|
+
const task = this.d.board.get(id);
|
|
162
|
+
if (!task) throw new PreEffectToolRefusal("study intake family is incomplete");
|
|
163
|
+
family.add(id); pending.push(...(task.deps ?? []));
|
|
164
|
+
}
|
|
165
|
+
family.delete(parent.id);
|
|
166
|
+
return family;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
private studyReferences(parentId: number, contract: ResearchCampaignContract, campaignId?: string): StudyReferences {
|
|
170
|
+
const parent = this.studyParent(parentId);
|
|
171
|
+
const profile = parent.profile ?? "dev", storedProfile = profile === (this.d.profile ?? "dev") ? this.d.profileData ?? profile : profile;
|
|
172
|
+
try {
|
|
173
|
+
if (profileClass(parent.profileClass ?? parent.class, storedProfile) !== parent.class) throw new Error("changed class");
|
|
174
|
+
} catch { throw new PreEffectToolRefusal("study parent profile class is unavailable or changed"); }
|
|
175
|
+
const sources = contract.sourceIds.map(id => {
|
|
176
|
+
const source = this.studySource(id);
|
|
177
|
+
if (!source)
|
|
178
|
+
throw new PreEffectToolRefusal("study source is unavailable in this project");
|
|
179
|
+
return source;
|
|
180
|
+
});
|
|
181
|
+
if (contract.budget) {
|
|
182
|
+
const budget = this.d.executionBudget?.status(contract.budget.id);
|
|
183
|
+
if (!budget || Array.isArray(budget)) throw new PreEffectToolRefusal("study budget is unavailable");
|
|
184
|
+
}
|
|
185
|
+
const adopted = new Map<string, Task>();
|
|
186
|
+
const family = contract.units.some(unit => unit.adoptTaskId !== undefined) ? this.studyFamily(parent) : new Set<number>();
|
|
187
|
+
for (const unit of contract.units) if (unit.adoptTaskId !== undefined) {
|
|
188
|
+
const task = this.studyParent(unit.adoptTaskId);
|
|
189
|
+
if (!family.has(task.id) || task.draft || !task.history.some(entry => entry.event === "draft approved"))
|
|
190
|
+
throw new PreEffectToolRefusal("study unit must adopt an approved intake child");
|
|
191
|
+
const binding = this.d.board.researchTaskBinding(task.id);
|
|
192
|
+
if (binding && (binding.campaignId !== campaignId || binding.unitId !== unit.id)) throw new PreEffectToolRefusal("intake child is already bound to another study unit");
|
|
193
|
+
adopted.set(unit.id, task);
|
|
194
|
+
}
|
|
195
|
+
const reused = new Map<string, Task>();
|
|
196
|
+
if (campaignId) for (const unit of contract.units) {
|
|
197
|
+
const previous = this.d.board.researchLatestUnitBinding(campaignId, unit.id);
|
|
198
|
+
if (previous) reused.set(unit.id, this.studyParent(previous.taskId));
|
|
199
|
+
}
|
|
200
|
+
const priv = this.host.isPii(parent) || sources.some(source => source.private) || [...adopted.values(), ...reused.values()].some(task => this.host.isPii(task))
|
|
201
|
+
|| !this.host.nameable(JSON.stringify(contract));
|
|
202
|
+
const flows = (rows: Map<string, Task>) => [...rows].map(([unit, task]) => [unit, task.id, task.history.length]);
|
|
203
|
+
return { parent, adopted, reused, private: priv, key: JSON.stringify([parent.history.length, sources, flows(adopted), flows(reused), priv]) };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Always re-read persisted approval and limits at the dispatch write, including after a metadata await. */
|
|
207
|
+
studyDispatchReason(task: Task, owner?: PeerId): string | undefined {
|
|
208
|
+
try {
|
|
209
|
+
const bound = this.d.board.researchDispatchBinding(task.id);
|
|
210
|
+
if (!bound) return undefined;
|
|
211
|
+
const { campaign, binding } = bound;
|
|
212
|
+
if (campaign.project !== this.d.project || campaign.status !== "approved" || !binding) return "study revision is not approved or its unit was removed";
|
|
213
|
+
const stop = campaign.contract.stopPolicy;
|
|
214
|
+
if (Date.parse(stop.deadline) <= this.studyTime()) return "study deadline has expired";
|
|
215
|
+
const units = this.d.board.researchCampaignBindings(campaign.id, campaign.revision);
|
|
216
|
+
if (units.length > stop.maxUnits || binding.round > stop.maxFollowUpRounds) return "study stop limit exceeded";
|
|
217
|
+
const budget = campaign.contract.budget;
|
|
218
|
+
if (budget?.hardCap.length) {
|
|
219
|
+
const ledger = this.d.executionBudget, current = ledger?.status(budget.id);
|
|
220
|
+
if (!ledger || !current || Array.isArray(current) || !campaign.eligibleOwners?.length ||
|
|
221
|
+
budget.hardCap.some(resource => resource === "tokens" || current.limits[resource] === undefined || resource === "model_calls" && current.limits.tokens !== undefined)) return "study hard-cap budget is unavailable";
|
|
222
|
+
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";
|
|
223
|
+
if (owner && (!campaign.eligibleOwners.includes(owner) || !ledger.covers(budget.id, task.id, owner, budget.hardCap)))
|
|
224
|
+
return "study owner is not covered by its named hard-cap budget";
|
|
225
|
+
}
|
|
226
|
+
return undefined;
|
|
227
|
+
} catch { return "study dispatch evidence is unavailable"; }
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
studyDispatchCheck(task: Task, owner?: PeerId): void {
|
|
231
|
+
const reason = this.studyDispatchReason(task, owner);
|
|
232
|
+
if (reason) throw new PreEffectToolRefusal(reason);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
studyExcludedOwners(task: Task): PeerId[] {
|
|
236
|
+
return Object.keys(this.host.states()).filter(peer => this.studyDispatchReason(task, peer) !== undefined);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
private studyEligibleOwners(contract: ResearchCampaignContract): string[] | undefined {
|
|
240
|
+
if (!contract.budget?.hardCap.length) return undefined;
|
|
241
|
+
const ledger = this.d.executionBudget, budget = ledger?.status(contract.budget.id);
|
|
242
|
+
if (!ledger || !budget || Array.isArray(budget) || contract.budget.hardCap.some(resource => resource === "tokens" || budget.limits[resource] === undefined || resource === "model_calls" && budget.limits.tokens !== undefined))
|
|
243
|
+
throw new PreEffectToolRefusal("study hard-cap requires an enabled budget with supported resource limits");
|
|
244
|
+
const eligible = budget.peers.filter(peer => ledger.instrumented(peer)).sort();
|
|
245
|
+
if (!eligible.length) throw new PreEffectToolRefusal("study hard-cap has no instrumented eligible owner");
|
|
246
|
+
return eligible;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
private studyRoundCheck(original: ResearchCampaignRecord, contract: ResearchCampaignContract): void {
|
|
250
|
+
const added = contract.units.filter(unit => unit.round > 0 && !original.contract.units.some(previous => previous.id === unit.id && previous.round === unit.round));
|
|
251
|
+
if (!added.length) return;
|
|
252
|
+
const stored = this.d.board.researchCampaignBindings(original.id, original.revision), handoffs = this.d.board.researchHandoffs(original.id, original.revision);
|
|
253
|
+
for (const unit of added) {
|
|
254
|
+
// 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.
|
|
255
|
+
const previous = contract.units.filter(value => value.round === unit.round - 1 && value.purpose === "discovery");
|
|
256
|
+
if (!previous.length || previous.some(value => {
|
|
257
|
+
const binding = stored.find(bound => bound.unitId === value.id && bound.round === value.round && bound.purpose === "discovery");
|
|
258
|
+
const handoff = binding && handoffs.find(handoff => handoff.handoff.unitId === value.id);
|
|
259
|
+
return !handoff || !handoff.handoff.insufficientEvidence && value.sourceIds.some(source => !handoff.handoff.evidence.some(item => item.sourceId === source));
|
|
260
|
+
})) throw new PreEffectToolRefusal("follow-up rounds require complete stored discovery handoffs or insufficientEvidence");
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async studyHandoff(by: PeerId, input: unknown): Promise<{ campaignId: string; unitId: string; seq: number }> {
|
|
265
|
+
const requestCheck = this.host.requestCheck(by, () => this.studyHold());
|
|
266
|
+
let handoff: ReturnType<typeof parseResearchHandoff>;
|
|
267
|
+
try { handoff = parseResearchHandoff(input); } catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid study handoff"); }
|
|
268
|
+
return this.studyWrite(async () => {
|
|
269
|
+
const campaign = this.studyRecord(handoff.campaignId, handoff.revision), task = this.studyParent(handoff.taskId);
|
|
270
|
+
if (by !== task.owner || task.state !== "in_progress" || this.d.privateTurn?.(by) && !this.host.isPii(task)) throw new PreEffectToolRefusal("handoff requires the current in-progress unit owner");
|
|
271
|
+
const sources = campaign.contract.sourceIds.map(id => this.studySource(id));
|
|
272
|
+
if (sources.some(source => !source)) throw new PreEffectToolRefusal("study handoff source is unavailable");
|
|
273
|
+
const sourceKey = JSON.stringify(sources);
|
|
274
|
+
const text = JSON.stringify(handoff);
|
|
275
|
+
const withheld = !this.host.nameable(text) || looksSecret(text) || await this.host.withholds("note", text, task);
|
|
276
|
+
requestCheck();
|
|
277
|
+
const current = this.studyParent(task.id);
|
|
278
|
+
if (current.history.length !== task.history.length || current.owner !== by || current.state !== "in_progress") throw new PreEffectToolRefusal("study handoff task changed during screening");
|
|
279
|
+
if (JSON.stringify(campaign.contract.sourceIds.map(id => this.studySource(id))) !== sourceKey) throw new PreEffectToolRefusal("study handoff sources changed during screening");
|
|
280
|
+
if ((withheld || this.studyReplayPrivacy(campaign, this.studyParent(campaign.parentTaskId))) && !this.host.isPii(current)) throw new PreEffectToolRefusal("study handoff privacy requires private task authority");
|
|
281
|
+
requestCheck();
|
|
282
|
+
try {
|
|
283
|
+
const saved = this.d.board.recordResearchHandoff(handoff, this.d.project, by, this.studyTime(), current.history.length);
|
|
284
|
+
return { campaignId: saved.handoff.campaignId, unitId: saved.handoff.unitId, seq: saved.seq };
|
|
285
|
+
} catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study handoff was not saved"); }
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* #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
|
|
291
|
+
* 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.
|
|
292
|
+
*/
|
|
293
|
+
studyList(by: PeerId, input: unknown): { campaigns: ResearchCampaignReceipt[]; next?: string } {
|
|
294
|
+
this.host.requireLocalTaskPeer(by);
|
|
295
|
+
const fields = this.studyFields(input, ["after"]);
|
|
296
|
+
const after = fields.after === undefined ? undefined : this.studyId(fields.after);
|
|
297
|
+
const page = this.d.board.researchCampaignPage(this.d.project, after, 50);
|
|
298
|
+
return { campaigns: page.ids.map(id => this.studyReceipt(this.studyRecord(id))), ...(page.next ? { next: page.next } : {}) };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
studyShow(by: PeerId, input: unknown): ReturnType<typeof studyProjection> {
|
|
302
|
+
this.host.requireLocalTaskPeer(by);
|
|
303
|
+
const fields = this.studyFields(input, ["id"]), campaign = this.studyRecord(this.studyId(fields.id));
|
|
304
|
+
const bindings = this.d.board.researchCampaignBindings(campaign.id, campaign.revision);
|
|
305
|
+
const tasks = bindings.map(unit => this.d.board.get(unit.taskId)).filter((task): task is Task => !!task);
|
|
306
|
+
const ledger = this.d.executionBudget, configured = campaign.contract.budget, budget = configured && ledger?.status(configured.id);
|
|
307
|
+
const instrumentedPeers = tasks.flatMap(task => task.owner && ledger?.instrumented(task.owner) ? [task.owner] : []);
|
|
308
|
+
const projection = studyProjection({ campaign, bindings, tasks, handoffs: this.d.board.researchHandoffs(campaign.id), now: this.studyTime(), instrumentedPeers,
|
|
309
|
+
...(budget && !Array.isArray(budget) ? { budget: { ...budget, coveredTaskIds: tasks.filter(task => task.owner && ledger?.covers(budget.id, task.id, task.owner, [])).map(task => task.id) } } : {}) });
|
|
310
|
+
projection.reasons = [...new Set([...projection.reasons, ...tasks.flatMap(task => { const reason = this.studyDispatchReason(task, task.owner ?? undefined); return reason ? [reason] : []; })])];
|
|
311
|
+
projection.held = projection.reasons.length > 0;
|
|
312
|
+
if (this.studyReplayPrivacy(campaign, this.studyParent(campaign.parentTaskId))) {
|
|
313
|
+
// IDs, counts, states and resource names only. Source references are private view data too.
|
|
314
|
+
for (const unit of projection.units) { unit.sourceIds = []; unit.duplicateSourceIds = []; unit.handoff.coveredSourceIds = []; }
|
|
315
|
+
}
|
|
316
|
+
return projection;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
studyReplayPrivacy(record: ResearchCampaignRecord, parent: Task): boolean {
|
|
320
|
+
return record.private || this.host.isPii(parent) || record.contract.sourceIds.some(id => {
|
|
321
|
+
const source = this.studySource(id);
|
|
322
|
+
return !source || source.private;
|
|
323
|
+
}) || this.d.board.researchCampaignBindings(record.id, record.revision).some(unit => {
|
|
324
|
+
const task = this.d.board.get(unit.taskId); return !task || this.host.isPii(task);
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
async studyDraft(by: PeerId, input: unknown): Promise<ResearchCampaignReceipt> {
|
|
329
|
+
const requestCheck = this.host.requestCheck(by, () => this.studyHold()); this.host.plannerWriteAuthority(by);
|
|
330
|
+
const fields = this.studyFields(input, ["parentTaskId", "contract"]), parentId = this.studyNumber(fields.parentTaskId, "parentTaskId");
|
|
331
|
+
const contract = this.studyContract(fields.contract);
|
|
332
|
+
if (contract.units.some(unit => unit.round !== 0)) throw new PreEffectToolRefusal("an initial study contains only round zero");
|
|
333
|
+
return this.studyWrite(async () => {
|
|
334
|
+
this.host.plannerWriteAuthority(by, this.studyParent(parentId));
|
|
335
|
+
const before = this.studyReferences(parentId, contract);
|
|
336
|
+
const withheld = await this.host.withholds("note", JSON.stringify(contract), before.parent);
|
|
337
|
+
requestCheck();
|
|
338
|
+
const current = this.studyReferences(parentId, contract); this.host.plannerWriteAuthority(by, current.parent);
|
|
339
|
+
if (current.key !== before.key) throw new PreEffectToolRefusal("study references changed during draft screening");
|
|
340
|
+
const record: ResearchCampaignRecord = { id: `rc-${randomBytes(6).toString("hex")}`, project: this.d.project, parentTaskId: parentId,
|
|
341
|
+
revision: 1, status: "draft", contract, hash: campaignHash(contract), private: current.private || withheld, createdBy: by, createdAt: this.studyTime() };
|
|
342
|
+
let saved: ResearchCampaignRecord;
|
|
343
|
+
requestCheck(); this.host.plannerWriteAuthority(by, current.parent);
|
|
344
|
+
try { saved = this.d.board.saveResearchCampaignDraft(record, undefined, current.parent.history.length); }
|
|
345
|
+
catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study draft was not saved"); }
|
|
346
|
+
this.host.releaseNotice(`study ${saved.id} revision ${saved.revision} drafted`);
|
|
347
|
+
return this.studyReceipt(saved);
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
async studyRevise(by: PeerId, input: unknown): Promise<ResearchCampaignReceipt> {
|
|
352
|
+
const requestCheck = this.host.requestCheck(by, () => this.studyHold()); this.host.plannerWriteAuthority(by);
|
|
353
|
+
const fields = this.studyFields(input, ["id", "revision", "contract"]), id = this.studyId(fields.id), revision = this.studyNumber(fields.revision, "revision");
|
|
354
|
+
const contract = this.studyContract(fields.contract);
|
|
355
|
+
return this.studyWrite(async () => {
|
|
356
|
+
const original = this.studyLatest(id, revision);
|
|
357
|
+
this.host.plannerWriteAuthority(by, this.studyParent(original.parentTaskId));
|
|
358
|
+
const before = this.studyReferences(original.parentTaskId, contract, id);
|
|
359
|
+
this.studyRoundCheck(original, contract);
|
|
360
|
+
const withheld = await this.host.withholds("note", JSON.stringify(contract), before.parent);
|
|
361
|
+
requestCheck();
|
|
362
|
+
const latest = this.studyLatest(id, revision), current = this.studyReferences(latest.parentTaskId, contract, id);
|
|
363
|
+
this.host.plannerWriteAuthority(by, current.parent);
|
|
364
|
+
if (latest.hash !== original.hash || current.key !== before.key) throw new PreEffectToolRefusal("study changed during revision screening");
|
|
365
|
+
this.studyRoundCheck(latest, contract);
|
|
366
|
+
const next: ResearchCampaignRecord = { id, project: this.d.project, parentTaskId: latest.parentTaskId, revision: revision + 1, status: "draft",
|
|
367
|
+
contract, hash: campaignHash(contract), private: latest.private || current.private || withheld, createdBy: by, createdAt: this.studyTime() };
|
|
368
|
+
let saved: ResearchCampaignRecord;
|
|
369
|
+
requestCheck(); this.host.plannerWriteAuthority(by, current.parent);
|
|
370
|
+
try { saved = this.d.board.saveResearchCampaignDraft(next, revision, current.parent.history.length); }
|
|
371
|
+
catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study revision was not saved"); }
|
|
372
|
+
this.host.releaseNotice(`study ${id} revision ${saved.revision} drafted`);
|
|
373
|
+
return this.studyReceipt(saved);
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
async studyApprove(by: PeerId, input: unknown): Promise<ResearchCampaignReceipt> {
|
|
378
|
+
const requestCheck = this.host.requestCheck(by, () => this.studyHold());
|
|
379
|
+
if (by !== USER) throw new PreEffectToolRefusal("study approval requires the person");
|
|
380
|
+
const fields = this.studyFields(input, ["id", "revision"]), id = this.studyId(fields.id), revision = this.studyNumber(fields.revision, "revision");
|
|
381
|
+
return this.studyWrite(async () => {
|
|
382
|
+
const original = this.studyRecord(id, revision), parent = this.studyParent(original.parentTaskId);
|
|
383
|
+
if (original.status === "approved") {
|
|
384
|
+
const privacy = this.studyReplayPrivacy(original, parent); requestCheck();
|
|
385
|
+
const replay = this.d.board.activateCampaign(id, revision, this.d.project, by, this.studyTime(), [], parent.history.length, privacy);
|
|
386
|
+
return this.studyReceipt(replay.campaign, true);
|
|
387
|
+
}
|
|
388
|
+
this.studyLatest(id, revision);
|
|
389
|
+
if (original.status !== "draft" || parent.draft) throw new PreEffectToolRefusal("study approval requires a draft and an approved parent input");
|
|
390
|
+
this.studyEligibleOwners(original.contract);
|
|
391
|
+
const before = this.studyReferences(parent.id, original.contract, id);
|
|
392
|
+
let priv = original.private || before.private || await this.host.withholds("note", JSON.stringify(original.contract), parent);
|
|
393
|
+
const prepared: PreparedResearchUnit[] = [];
|
|
394
|
+
for (const unit of original.contract.units) {
|
|
395
|
+
requestCheck();
|
|
396
|
+
const reused = before.reused.get(unit.id);
|
|
397
|
+
if (reused) { prepared.push({ unitId: unit.id, reuse: { taskId: reused.id, flowRevision: reused.history.length } }); continue; }
|
|
398
|
+
const adopted = before.adopted.get(unit.id);
|
|
399
|
+
if (adopted) { prepared.push({ unitId: unit.id, adopt: { taskId: adopted.id, flowRevision: adopted.history.length } }); continue; }
|
|
400
|
+
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(", ")}`;
|
|
401
|
+
priv ||= await this.host.withholds("task", detail, parent);
|
|
402
|
+
const refs = this.host.cleanRefs(parent.refs), signals = [...new Set([...this.host.signalsFor({ title, detail, refs }), ...parent.signals.filter(signal => ["pii", "pii_path", "urgent"].includes(signal))])];
|
|
403
|
+
prepared.push({ unitId: unit.id, create: { title, detail, class: parent.class, refs, signals,
|
|
404
|
+
...(parent.profile ? { profile: parent.profile } : {}), ...(parent.profileClass ? { profileClass: parent.profileClass } : {}),
|
|
405
|
+
} });
|
|
406
|
+
}
|
|
407
|
+
requestCheck();
|
|
408
|
+
const latest = this.studyLatest(id, revision), current = this.studyReferences(parent.id, original.contract, id);
|
|
409
|
+
if (latest.hash !== original.hash || current.key !== before.key) throw new PreEffectToolRefusal("study changed during approval screening");
|
|
410
|
+
const now = this.studyTime(), deadline = Date.parse(original.contract.stopPolicy.deadline);
|
|
411
|
+
if (deadline <= now || deadline - now > 90 * 86_400_000) throw new PreEffectToolRefusal("study deadline must be in the next ninety days at approval");
|
|
412
|
+
priv ||= latest.private || current.private;
|
|
413
|
+
const instruction = instructedExecution.getStore();
|
|
414
|
+
if (instruction?.active) {
|
|
415
|
+
instruction.current();
|
|
416
|
+
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");
|
|
417
|
+
}
|
|
418
|
+
if (priv && [...current.adopted.values(), ...current.reused.values()].some(task => !this.host.isPii(task)))
|
|
419
|
+
throw new PreEffectToolRefusal("a private study cannot retain a public task without changing its authority");
|
|
420
|
+
for (const unit of prepared) if (unit.create) {
|
|
421
|
+
if (priv && !unit.create.signals?.includes("pii")) unit.create.signals = [...(unit.create.signals ?? []), "pii"];
|
|
422
|
+
const planner = this.host.proposalPlanner({ ...parent, ...unit.create, signals: unit.create.signals ?? [], refs: unit.create.refs ?? {}, draft: undefined, state: "backlog", owner: null, reviewer: null });
|
|
423
|
+
unit.create.planner = planner.planner; unit.create.plannerReason = planner.plannerReason;
|
|
424
|
+
this.host.warmRepository({ refs: unit.create.refs ?? {}, plan: unit.create.plan });
|
|
425
|
+
}
|
|
426
|
+
const mode = this.d.coordination?.();
|
|
427
|
+
let result: ReturnType<Board["activateCampaign"]>;
|
|
428
|
+
requestCheck();
|
|
429
|
+
instruction?.beginStudy?.(); // The synchronous board transaction now owns the screened binding.
|
|
430
|
+
try { result = this.d.board.activateCampaign(id, revision, this.d.project, by, now, prepared, current.parent.history.length, priv, { eligibleOwners: this.studyEligibleOwners(original.contract) }); }
|
|
431
|
+
catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study approval was not saved"); }
|
|
432
|
+
for (const child of result.children) {
|
|
433
|
+
this.host.incomingBacklog.add(child.id);
|
|
434
|
+
if (mode !== undefined) this.host.coordinationModes.set(child.id, mode);
|
|
435
|
+
}
|
|
436
|
+
this.host.releaseNotice(`study ${id} revision ${revision} approved; ${result.bindings.length} units`);
|
|
437
|
+
await this.studyReoffer(result.bindings.map(unit => unit.taskId));
|
|
438
|
+
return this.studyReceipt(result.campaign, true);
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* 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
|
|
444
|
+
* 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
|
|
445
|
+
* refusal here is a notice, never a failure of the approval.
|
|
446
|
+
*/
|
|
447
|
+
private async studyReoffer(taskIds: readonly number[]): Promise<void> {
|
|
448
|
+
for (const taskId of taskIds) {
|
|
449
|
+
let owner: PeerId | undefined;
|
|
450
|
+
try { owner = this.d.board.researchDroppedOffer(taskId); } catch (e) { this.host.releaseNotice(`task #${taskId}: study dropped-offer record is unreadable: ${e instanceof Error ? e.message : String(e)}`); continue; }
|
|
451
|
+
if (owner === undefined) continue;
|
|
452
|
+
const task = this.d.board.get(taskId);
|
|
453
|
+
// The record names an owner that no longer holds the unproposed task: it is stale, not a pending offer.
|
|
454
|
+
if (!task || task.owner !== owner || task.state !== "proposed") { this.d.board.clearResearchDroppedOffer(taskId); continue; }
|
|
455
|
+
try {
|
|
456
|
+
await this.host.sendTask(task, { owner, ...(task.reviewer ? { reviewer: task.reviewer } : {}), trace: [] });
|
|
457
|
+
this.d.board.clearResearchDroppedOffer(taskId); // after the offer is published: a refusal keeps the record for the next approval
|
|
458
|
+
} catch (e) { this.host.releaseNotice(`task ${this.host.publicTitle(task)}: could not re-offer after the study was approved: ${e instanceof Error ? e.message : String(e)}`); }
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
async studyClose(by: PeerId, input: unknown): Promise<ResearchCampaignReceipt> {
|
|
463
|
+
const requestCheck = this.host.requestCheck(by, () => this.studyHold()); this.host.plannerWriteAuthority(by);
|
|
464
|
+
const fields = this.studyFields(input, ["id", "revision", "reason"]), id = this.studyId(fields.id), revision = this.studyNumber(fields.revision, "revision");
|
|
465
|
+
if (typeof fields.reason !== "string" || !fields.reason.trim() || Buffer.byteLength(fields.reason, "utf8") > 512) throw new PreEffectToolRefusal("study close needs a bounded reason");
|
|
466
|
+
const reason = fields.reason;
|
|
467
|
+
return this.studyWrite(async () => {
|
|
468
|
+
const original = this.studyLatest(id, revision), parent = this.studyParent(original.parentTaskId);
|
|
469
|
+
this.host.plannerWriteAuthority(by, parent);
|
|
470
|
+
const withheld = await this.host.withholds("note", reason, parent);
|
|
471
|
+
requestCheck();
|
|
472
|
+
const latest = this.studyLatest(id, revision), currentParent = this.studyParent(latest.parentTaskId);
|
|
473
|
+
this.host.plannerWriteAuthority(by, currentParent);
|
|
474
|
+
if (latest.hash !== original.hash || currentParent.history.length !== parent.history.length) throw new PreEffectToolRefusal("study changed during close screening");
|
|
475
|
+
const priv = this.studyReplayPrivacy(latest, currentParent) || withheld || !this.host.nameable(reason);
|
|
476
|
+
let closed: ResearchCampaignRecord;
|
|
477
|
+
requestCheck(); this.host.plannerWriteAuthority(by, currentParent);
|
|
478
|
+
try { closed = this.d.board.closeCampaign(id, revision, this.d.project, by, this.studyTime(), reason, currentParent.history.length, priv); }
|
|
479
|
+
catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study close was not saved"); }
|
|
480
|
+
this.host.releaseNotice(`study ${id} revision ${revision} closed`);
|
|
481
|
+
return this.studyReceipt(closed);
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
private synthesisTask(by: PeerId, id: unknown): Task {
|
|
486
|
+
this.host.requireLocalTaskPeer(by);
|
|
487
|
+
if (this.d.profile !== "research") throw new PreEffectToolRefusal("synthesis evidence is research-only; use a research profile and a visible task");
|
|
488
|
+
const task = this.studyParent(this.studyNumber(id, "taskId"));
|
|
489
|
+
if (task.profile !== "research" || by !== USER && !this.host.taskShowAllowed(by, task, this.d.roles, this.host.isConfiguredPlanner(by)))
|
|
490
|
+
throw new PreEffectToolRefusal("synthesis task unavailable; use a research task visible through hub_task_show");
|
|
491
|
+
return task;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
private synthesisPrivate(task: Task, by: PeerId): boolean {
|
|
495
|
+
try { return !!this.d.privateTurn?.(by) || this.host.isPii(task) || !this.host.publicMetadataText(JSON.stringify(task.plan?.claims ?? [])); }
|
|
496
|
+
catch { return true; }
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
private synthesisPolicy(task: Task): string {
|
|
500
|
+
let root: string | undefined;
|
|
501
|
+
try { root = this.host.deliverablePorts(task).cwd; } catch { /* unknown is part of the fence */ }
|
|
502
|
+
return JSON.stringify([this.d.profile, this.d.routing().signals, this.d.piiPaths, this.d.deny, root]);
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
private synthesisRows(links: readonly EvidenceLinkV1[]) {
|
|
506
|
+
return links.map(link => ({ link, status: link.status === "withdrawn" ? "withdrawn" as const : "active" as const }));
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
private synthesisInventories(task: Task) {
|
|
510
|
+
const claims = task.plan?.claims;
|
|
511
|
+
if (!Array.isArray(claims) || claims.length > 50) throw new PreEffectToolRefusal("synthesis claims unavailable; refresh the task's bounded declared claim list");
|
|
512
|
+
return claims.map((_claim, index) => {
|
|
513
|
+
const identity = taskClaimIdentity(task, index + 1);
|
|
514
|
+
try {
|
|
515
|
+
const inventory = this.d.board.latestEvidenceLinks(this.d.project, task.id, identity.claimId, identity.claimRevision, 128);
|
|
516
|
+
let contradictionHistory: ReturnType<Board["evidenceContradictionHistory"]> = { ids: [], sources: [], members: [], complete: false };
|
|
517
|
+
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. */ }
|
|
518
|
+
if (contradictionHistory.complete && contradictionHistory.sources.some(id => { try { return !this.d.evidenceSourceMeta?.(id); } catch { return true; } })) contradictionHistory.complete = false;
|
|
519
|
+
return { ...identity, inventory, contradictionHistory };
|
|
520
|
+
}
|
|
521
|
+
catch { return { ...identity, inventory: { links: [] as EvidenceLinkV1[], complete: false }, contradictionHistory: { ids: [] as string[], sources: [] as string[], members: [] as string[], complete: false } }; }
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
private synthesisSources(links: readonly Pick<EvidenceLinkV1, "sourceId">[]): { private: boolean; key: string; bytes: number } {
|
|
526
|
+
const meta: unknown[] = [], seen = new Set<string>(); let bytes = 0;
|
|
527
|
+
for (const link of links) {
|
|
528
|
+
if (seen.has(link.sourceId)) continue; seen.add(link.sourceId);
|
|
529
|
+
const source = (() => { try { return this.d.evidenceSourceMeta?.(link.sourceId) ?? this.studySource(link.sourceId); } catch { return undefined; } })();
|
|
530
|
+
if (source?.private || source && !this.host.publicMetadataText(JSON.stringify(source))) return { private: true, key: "", bytes: 0 };
|
|
531
|
+
meta.push([link.sourceId, source]);
|
|
532
|
+
if (source && "bytes" in source && typeof source.bytes === "number") bytes += source.bytes;
|
|
533
|
+
}
|
|
534
|
+
return { private: false, key: createHash("sha256").update(JSON.stringify(meta)).digest("hex"), bytes };
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/** Explicit authoring metadata only: no claim text, source identity, passage, origin or path. */
|
|
538
|
+
async synthesisEvidence(by: PeerId, input: unknown) {
|
|
539
|
+
const fields = this.studyFields(input, ["taskId"]), check = this.host.requestCheck(by, () => this.studyHold());
|
|
540
|
+
return this.studyWrite(async () => {
|
|
541
|
+
check(); const revision = this.d.board.statusRevision(), task = this.synthesisTask(by, fields.taskId);
|
|
542
|
+
if (this.synthesisPrivate(task, by)) return { taskId: task.id, status: "private" as const };
|
|
543
|
+
const claims = this.synthesisInventories(task), links = claims.flatMap(claim => [...claim.inventory.links, ...claim.contradictionHistory.sources.map(sourceId => ({ sourceId }))]);
|
|
544
|
+
if (this.synthesisSources(links).private) return { taskId: task.id, status: "private" as const };
|
|
545
|
+
const delivered = latestDeliverables(task.history) ?? [];
|
|
546
|
+
const artifacts = delivered.filter(record => !record.private && record.path && !this.host.experimentOutputPrivate(task, record.path))
|
|
547
|
+
.map(({ id, sha256, format }) => ({ id, sha256, format }));
|
|
548
|
+
check();
|
|
549
|
+
if (this.d.board.statusRevision() !== revision) return { taskId: task.id, status: "unavailable" as const, cause: "inventory_changed" };
|
|
550
|
+
return { taskId: task.id, taskCreated: task.created, status: "available" as const, scope: "declared_inventory" as const,
|
|
551
|
+
deliverables: artifacts, claims: claims.map(claim => {
|
|
552
|
+
const binding = inventoryBinding(this.synthesisRows(claim.inventory.links), claim.inventory.complete, claim.contradictionHistory);
|
|
553
|
+
return { claimId: claim.claimId, claimRevision: claim.claimRevision, complete: claim.inventory.complete && claim.contradictionHistory.complete,
|
|
554
|
+
...(binding ? { inventory: binding } : {}), evidence: this.synthesisRows(claim.inventory.links).map(({ link, status }) => ({ id: link.id, revision: link.revision, status })) };
|
|
555
|
+
}) };
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** Deterministic, explicit and offline: no caller-supplied current state and no semantic/model judge. */
|
|
560
|
+
async synthesisCheck(by: PeerId, input: unknown): Promise<SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }> {
|
|
561
|
+
return this.synthesisInspect(by, input);
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
synthesisInspect(by: PeerId, input: unknown): Promise<SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }>;
|
|
565
|
+
|
|
566
|
+
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 }>;
|
|
567
|
+
|
|
568
|
+
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 }> {
|
|
569
|
+
const fields = this.studyFields(input, ["taskId", "manifest"]), manifest = parseSynthesisManifest(fields.manifest);
|
|
570
|
+
if (fields.taskId !== manifest.taskId) throw new PreEffectToolRefusal("synthesis manifest names another task; refresh its task binding and retry");
|
|
571
|
+
const check = this.host.requestCheck(by, () => this.studyHold());
|
|
572
|
+
return this.studyWrite(async () => {
|
|
573
|
+
check(); const boardRevision = this.d.board.statusRevision(), task = this.synthesisTask(by, fields.taskId), taskId = task.id;
|
|
574
|
+
if (this.synthesisPrivate(task, by)) return { taskId, status: "private" };
|
|
575
|
+
const before = this.synthesisInventories(task), allLinks = before.flatMap(claim => claim.inventory.links);
|
|
576
|
+
const privacyLinks = [...allLinks, ...before.flatMap(claim => claim.contradictionHistory.sources.map(sourceId => ({ sourceId })))];
|
|
577
|
+
const sources = this.synthesisSources(privacyLinks);
|
|
578
|
+
if (sources.private) return { taskId, status: "private" };
|
|
579
|
+
const activeLinks = allLinks.filter(link => link.status !== "withdrawn");
|
|
580
|
+
if (this.synthesisSources(activeLinks).bytes > 64 * 1024 * 1024) return { taskId, status: "unavailable", cause: "source_input_limit" };
|
|
581
|
+
const delivered = latestDeliverables(task.history) ?? [], policy = this.synthesisPolicy(task);
|
|
582
|
+
// ponytail: any concurrent board write stales this explicit batch. A task-scoped evidence generation narrows the fence later.
|
|
583
|
+
const base = JSON.stringify([task.created, task.owner, task.reviewer, task.history.length, task.plan?.claims, delivered]);
|
|
584
|
+
const current = () => {
|
|
585
|
+
try { check(); const now = this.synthesisTask(by, taskId); return !this.synthesisPrivate(now, by)
|
|
586
|
+
&& this.d.board.statusRevision() === boardRevision && this.synthesisPolicy(now) === policy
|
|
587
|
+
&& JSON.stringify([now.created, now.owner, now.reviewer, now.history.length, now.plan?.claims, latestDeliverables(now.history) ?? []]) === base; }
|
|
588
|
+
catch { return false; }
|
|
589
|
+
};
|
|
590
|
+
const changed = () => {
|
|
591
|
+
check(); const now = this.synthesisTask(by, taskId);
|
|
592
|
+
if (this.synthesisPrivate(now, by) || this.synthesisSources(privacyLinks).private) return { taskId, status: "private" as const };
|
|
593
|
+
return { taskId, status: "stale" as const, cause: "context_changed" };
|
|
594
|
+
};
|
|
595
|
+
try { if (by !== USER) this.d.onReviewObserverInput?.(by); } catch { return { taskId, status: "unavailable", cause: "observer_unavailable" }; }
|
|
596
|
+
const sourceKeys = new Map<string, string | undefined>();
|
|
597
|
+
for (const link of activeLinks) if (!sourceKeys.has(link.sourceId)) {
|
|
598
|
+
let key: string | undefined;
|
|
599
|
+
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 */ }
|
|
600
|
+
sourceKeys.set(link.sourceId, key);
|
|
601
|
+
}
|
|
602
|
+
if (!current()) return changed();
|
|
603
|
+
const reads: { path: string; read: GuardedDeliverableRead }[] = [];
|
|
604
|
+
const artifact = async (reference: { id: string; sha256: string }, limit: number): Promise<SynthesisArtifactSnapshot | "private"> => {
|
|
605
|
+
const record = delivered.find(record => record.id === reference.id);
|
|
606
|
+
if (!record) return { id: reference.id, state: "missing" };
|
|
607
|
+
if (record.private || !record.path || this.host.experimentOutputPrivate(task, record.path)) return "private";
|
|
608
|
+
try {
|
|
609
|
+
const read = await readGuardedDeliverable(record.path, this.host.deliverablePorts(task, { failClosedOnDiscoveryLimit: true }), limit);
|
|
610
|
+
const text = new TextDecoder("utf-8", { fatal: true }).decode(read.data);
|
|
611
|
+
if (!this.host.publicMetadataText(text)) return "private";
|
|
612
|
+
reads.push({ path: record.path, read });
|
|
613
|
+
return { id: record.id, sha256: read.sha256, state: read.sha256 === reference.sha256 && record.sha256 === reference.sha256 ? "unchanged" : "changed", text };
|
|
614
|
+
} catch { return { id: record.id, state: "unknown" }; }
|
|
615
|
+
};
|
|
616
|
+
const doc = await artifact(manifest.deliverable, 256 * 1024); if (doc === "private") return { taskId, status: "private" };
|
|
617
|
+
if (!current()) return changed();
|
|
618
|
+
const bib = await artifact(manifest.bibliography, 4 * 1024 * 1024); if (bib === "private") return { taskId, status: "private" };
|
|
619
|
+
if (!current()) return changed();
|
|
620
|
+
const observed: SynthesisCurrentClaim[] = [];
|
|
621
|
+
for (const claim of before) {
|
|
622
|
+
const resolutions: NonNullable<NonNullable<SynthesisCurrent["claims"]>[number]["resolutions"]>[number][] = [];
|
|
623
|
+
for (const link of claim.inventory.links) {
|
|
624
|
+
if (!current()) return changed();
|
|
625
|
+
const withdrawn = link.status === "withdrawn";
|
|
626
|
+
if (withdrawn) { resolutions.push({ id: link.id, revision: link.revision, status: "withdrawn" }); continue; }
|
|
627
|
+
if (!this.d.evidenceSourceRead || !sourceKeys.get(link.sourceId)) { resolutions.push({ id: link.id, revision: link.revision, status: "unavailable" }); continue; }
|
|
628
|
+
let resolution: EvidenceSourceRead["resolution"];
|
|
629
|
+
try { resolution = (await this.d.evidenceSourceRead(by, link, current, { privacyReadOnly: true })).resolution; }
|
|
630
|
+
catch { resolution = { status: "unavailable", cause: "source_unavailable" }; }
|
|
631
|
+
if (resolution.status === "unavailable" && resolution.cause === "private") return { taskId, status: "private" };
|
|
632
|
+
if (!current()) return changed();
|
|
633
|
+
resolutions.push({ id: link.id, revision: link.revision, status: resolution.status === "resolved" ? "resolved" : resolution.status === "stale" ? "stale" : "unavailable" });
|
|
634
|
+
}
|
|
635
|
+
const entry = task.history.findLast(entry => entry.by === USER && entry.event === "claim verdict" && entry.claim?.slot === claim.slot && entry.claim.list === claim.claimRevision)?.claim;
|
|
636
|
+
const verdict = entry && ["supported", "unsupported", "unclear"].includes(entry.verdict) ? entry.verdict : undefined;
|
|
637
|
+
const synthesis = entry?.synthesis;
|
|
638
|
+
observed.push({ claimId: claim.claimId, claimRevision: claim.claimRevision,
|
|
639
|
+
inventory: { ...claim.inventory, links: this.synthesisRows(claim.inventory.links) },
|
|
640
|
+
contradictionHistory: claim.contradictionHistory,
|
|
641
|
+
resolutions, judgment: { present: !!verdict, ...(verdict ? { verdict } : {}), ...(verdict && synthesis ? synthesis : {}) } });
|
|
642
|
+
}
|
|
643
|
+
const finalCurrent = () => {
|
|
644
|
+
try {
|
|
645
|
+
if (!current() || this.synthesisSources(privacyLinks).key !== sources.key) return false;
|
|
646
|
+
const fencedSources = new Set<string>();
|
|
647
|
+
for (const link of activeLinks) if (!fencedSources.has(link.sourceId)) {
|
|
648
|
+
fencedSources.add(link.sourceId);
|
|
649
|
+
if (sourceKeys.get(link.sourceId) && this.d.evidenceSourceSnapshotKey?.(link) !== sourceKeys.get(link.sourceId)) return false;
|
|
650
|
+
}
|
|
651
|
+
if (reads.some(value => !guardedDeliverableCurrent(value.path, this.host.deliverablePorts(task, { failClosedOnDiscoveryLimit: true }), value.read))) return false;
|
|
652
|
+
return this.synthesisSources(privacyLinks).key === sources.key && current();
|
|
653
|
+
} catch { return false; }
|
|
654
|
+
};
|
|
655
|
+
if (!finalCurrent()) return changed();
|
|
656
|
+
const snapshot: SynthesisCurrent = { taskId, taskCreated: task.created, deliverable: doc, bibliography: bib, claims: observed };
|
|
657
|
+
const report = checkSynthesis(manifest, snapshot);
|
|
658
|
+
return onSnapshot ? onSnapshot(manifest, snapshot, report, finalCurrent) : report;
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
}
|