From 6a21f01ec484b370cba190631847baad895891f4 Mon Sep 17 00:00:00 2001 From: Alex Date: Sat, 28 Nov 2026 20:11:58 +0200 Subject: [PATCH 01/16] wip: review loops --- docs/plans/2026-11-28-review-loops.md | 97 ++++ platform/src/factory/cli/conductor.py | 17 + platform/src/factory/events/catalog.py | 10 + platform/src/factory/mcp/server.py | 111 +++++ platform/src/factory/model/conductor.py | 18 + platform/src/factory/model/review_loop.py | 82 ++++ platform/src/factory/services/access.py | 5 + platform/src/factory/services/conductor.py | 167 ++++++- .../src/factory/services/modules/retrieval.py | 7 +- platform/src/factory/services/review_loop.py | 323 +++++++++++++ platform/src/factory/services/runner.py | 59 ++- .../src/factory/services/tier_protocol.py | 64 +++ platform/tests/test_conductor_access.py | 2 +- platform/tests/test_review_loop.py | 430 ++++++++++++++++++ plugin/skills/rf-frame-conducted/SKILL.md | 44 ++ plugin/skills/rf-review/SKILL.md | 38 ++ 16 files changed, 1460 insertions(+), 14 deletions(-) create mode 100644 docs/plans/2026-11-28-review-loops.md create mode 100644 platform/src/factory/model/review_loop.py create mode 100644 platform/src/factory/services/review_loop.py create mode 100644 platform/src/factory/services/tier_protocol.py create mode 100644 platform/tests/test_review_loop.py create mode 100644 plugin/skills/rf-frame-conducted/SKILL.md create mode 100644 plugin/skills/rf-review/SKILL.md diff --git a/docs/plans/2026-11-28-review-loops.md b/docs/plans/2026-11-28-review-loops.md new file mode 100644 index 00000000..bef7cd8f --- /dev/null +++ b/docs/plans/2026-11-28-review-loops.md @@ -0,0 +1,97 @@ +# Plan: review loops in the conductor, and a conducted frame + +Date: 2026-11-28. Branch `review-loops`. Scope: slice 9 (tiers and autonomy), conductor C8. + +## Why + +The first live tier run (living-syllabus shakedown `la-brief`, tier brief, autonomous) stopped in +its first step. Four causes, all in the conducted frame: + +1. The `frame` stage runs `rf-frame`, an interactive skill (interview, quote back, wait for the + researcher), while the conducted prompt says nobody answers. Its allow-list also lacks the + reads the skill calls (`briefing_get`, `decision_list`). +2. No tool records the tier's protocol template (`ProtocolTemplate.instantiate` is called only + in tests), so a frame session must write a full `ProtocolSpec` by hand. +3. At brief and deep the conductor waits after frame on two human gates, `protocol.ready` and + `protocol.press_confirm` (the second is declared by no module, so it never closes), although + `rf-brief` says no protocol gate binds in those tiers. +4. The prompt ends a run on any refusal, a refused read included. + +A fifth (a finished CLI-started run was never closed) is fixed in PR #80. + +The researcher also asked that judged outputs be checked by a second session and revised, in a +loop with escapes, rather than in one pass. + +## Design + +### Review loop (steps `frame` and `write`) + +At `supervised` and `autonomous`, a loop step has the roles proposer, verifier and, when an agent +may close one of its gates, auditor. The verifier of a loop step is a reviewer session (stage +`review-frame` or `review-write`, skill `rf-review`) that records one verdict per round with +`review_record`: `accept`, or `revise` with findings. Each finding has a severity (`blocking` or +`minor`), a target, a text, and optionally the id of an earlier finding it repeats. The platform +numbers rounds and findings (`R2.F1`) and fingerprints the step's output when the verdict is +recorded (frame: question, protocol and seeds; write: the drafts). On `revise` the proposer runs +again; it reads the findings with `review_view` and answers each blocking one with `review_reply` +(`addressed` or `declined`, with a note) before the reviewer runs again. + +The loop ends, computed from the log, when: + +- the verdict is `accept` (outcome `accepted`); +- round 5 is reached (`max-rounds`); +- every blocking finding of a round repeats a blocking finding of the round before and there are + no fewer of them (`no-progress`); +- the output's fingerprint equals that of an earlier round (`repeat`: unchanged or reverted); +- the run or time budget is spent (the conductor's existing budget pause). + +A loop that ends with blocking findings still open continues at tiers brief and deep, and the +conductor records `conductor.review_ended` with the open finding ids; the evidence note lists +them. At other tiers it pauses with reason `review-disputed`. A reviewer run that records no +verdict pauses with `review-missing`; `advance --retry` runs the reviewer again. + +Bulk steps (screen, extract) keep their sampled second pass and audit: a loop per record would +cost much and add little. The develop step keeps its own lead/drafter/critic sessions; moving it +onto this loop is a follow-up. + +### Conducted frame + +- Stage `frame` runs skill `rf-frame-conducted`: record the stated goal verbatim as `raw_goal`, + fill the question from it (unknowns as open slots), add the seeds the goal names, and record the + tier's protocol with `protocol_from_template`. No interview and no decisions: they are optional + at `exploratory` and a conducted session has no researcher. +- `protocol_from_template` (new tool): the agent gives criteria and the planned queries; the + platform instantiates the tier's template (`ProtocolTemplate.instantiate`), enforcing its + sources and queries per source, names the project's creator as reviewer of record, and records + the protocol as a draft through `record_protocol`. +- At tiers brief and deep the frame step's protocol gates do not bind in the conductor + (`TIER_UNBOUND_GATES`); the review loop stands in for them, and the note says so. + +### Models + +`frame`, `write`, `review-frame` and `review-write` run on Opus 5.5 (few, short, judged sessions). +Screening and extraction stay on Haiku. A reviewer of another model family (Gemini CLI as an MCP +client) needs a ruling on the rule that judgement comes from Claude: backlog. + +### Prompt + +A refused read is reported and the session continues; a refused write is reported and the +session stops. + +## Events + +- `review.verdict_recorded` (agent): conductor id, step, stage id, round, verdict, findings, + fingerprint, summary. +- `review.reply_recorded` (agent): conductor id, step, round, replies. +- `conductor.review_ended` (system): conductor id, step, stage id, outcome, reason, rounds, open + finding ids. + +No projection table: the loop state is derived from the log, as the conductor's is. + +## Tests (TDD) + +Service: verdict and reply validation (only during the step's reviewer or proposer run, one per +round, `accept` without blocking findings, replies cover every blocking finding), round and +finding numbering, fingerprints. Conductor: accept after one round; revise then accept; each +escape; continue at brief, pause at pilot; missing verdict; frame gates unbound at brief. +Template tool: sources and per-source caps enforced; reviewer of record is the creator. diff --git a/platform/src/factory/cli/conductor.py b/platform/src/factory/cli/conductor.py index 41cd183c..b4fa3bff 100644 --- a/platform/src/factory/cli/conductor.py +++ b/platform/src/factory/cli/conductor.py @@ -76,3 +76,20 @@ def status_cmd(ctx: typer.Context, as_json: Annotated[bool, _JSON] = False) -> N with _reporting_errors(): status = conductor_service.conductor_status(_resolve_project(state)) _echo(status, as_json) + + +@conductor_app.command("release-review") +def release_review_cmd( + ctx: typer.Context, + note: Annotated[str, typer.Option("--note", help="Why the run may go on.")] = "", +) -> None: + """Let the conductor go on past a review loop that ended with blocking findings open (pause + `review-disputed`); the findings stay open and labelled. Your act, recorded as you.""" + from factory.cli.main import _reporting_errors, _resolve_project, _state + from factory.services import review_loop + + state = _state(ctx) + with _reporting_errors(): + project = _resolve_project(state) + released = review_loop.release(project, project.human_actor(), note) + typer.echo(f"released the review of step {released.step}; advance to go on") diff --git a/platform/src/factory/events/catalog.py b/platform/src/factory/events/catalog.py index ed9778ae..9e6c18bf 100644 --- a/platform/src/factory/events/catalog.py +++ b/platform/src/factory/events/catalog.py @@ -27,6 +27,7 @@ from factory.model.conductor import ( ConductorFinished, ConductorPaused, + ConductorReviewEnded, ConductorStarted, ConductorStepFinished, ConductorStepStarted, @@ -203,6 +204,11 @@ RegionReviewed, RegionSnapshotTaken, ) +from factory.model.review_loop import ( + ReviewReleased, + ReviewReplyRecorded, + ReviewVerdictRecorded, +) from factory.model.reviews import ReviewDecided, ReviewRequested from factory.model.runner import PipelineFinished, PipelineStarted, RunnerFinished, RunnerStarted from factory.model.screening import ( @@ -432,6 +438,10 @@ def default_catalog() -> EventCatalog: catalog.register(EventType("conductor.step_finished", ConductorStepFinished, 1)) catalog.register(EventType("conductor.paused", ConductorPaused, 1)) catalog.register(EventType("conductor.finished", ConductorFinished, 1)) + catalog.register(EventType("conductor.review_ended", ConductorReviewEnded, 1)) + catalog.register(EventType("review.verdict_recorded", ReviewVerdictRecorded, 1)) + catalog.register(EventType("review.reply_recorded", ReviewReplyRecorded, 1)) + catalog.register(EventType("review.released", ReviewReleased, 1)) catalog.register(EventType("work.marked_core", WorkMarkedCore, 1)) catalog.register(EventType("work.unmarked_core", WorkUnmarkedCore, 1)) catalog.register(EventType("notice.observed", NoticeObserved, 1)) diff --git a/platform/src/factory/mcp/server.py b/platform/src/factory/mcp/server.py index 6cbb0b77..214fa1e5 100644 --- a/platform/src/factory/mcp/server.py +++ b/platform/src/factory/mcp/server.py @@ -1006,6 +1006,117 @@ def record() -> JsonValue: return _reply(project, record, rename=spec_path) + @server.tool() + def protocol_from_template( + project: str, + criteria: list[dict[str, JsonValue]], + queries: list[dict[str, JsonValue]], + role: str, + model: str, + skill: str, + ) -> dict[str, JsonValue]: + """Record the protocol of the project's tier from its template: you give the criteria and + the planned queries, the platform fills sources, screening, extraction schema and snowball + plan, enforces the template's sources and queries per source, and names the project's + creator as reviewer of record. Recorded as a draft. Gaps are returned.""" + + def record() -> JsonValue: + from factory.model.protocol import Criterion, PlannedQuery + from factory.services import tier_protocol + + opened = open_project(settings, project, session=session, clock=clock) + actor = make_agent_actor(settings, session, role, model, skill) + parsed_criteria = [ + parse_input(Criterion, c, f"criteria.{i}") for i, c in enumerate(criteria) + ] + parsed_queries = [ + parse_input(PlannedQuery, q, f"queries.{i}") for i, q in enumerate(queries) + ] + result = tier_protocol.record_from_template( + opened, actor, parsed_criteria, parsed_queries + ) + data = result.model_dump(mode="json") + data["gaps"] = [ + {"field": spec_path(gap.field), "reason": gap.reason} for gap in result.gaps + ] + return _withheld(opened, data) + + return _reply(project, record, rename=spec_path) + + @server.tool() + def review_view(project: str) -> dict[str, JsonValue]: + """The review loop of the conductor's current step (frame or write): the verdicts so far, + each with its numbered findings, the proposer's replies, the round cap and whether the + loop has ended. Read-only.""" + + def view() -> JsonValue: + from factory.services import review_loop + + opened = open_project(settings, project, session=session, clock=clock) + return review_loop.review_view(opened).model_dump(mode="json") + + return _reply(project, view, include_work_ids=False) + + @server.tool() + def review_record( + project: str, + verdict: str, + summary: str, + role: str, + model: str, + skill: str, + findings: list[dict[str, JsonValue]] | None = None, + ) -> dict[str, JsonValue]: + """Record your verdict on the step's output, once per review run: `accept` (no blocking + finding) or `revise` (at least one). Each finding: `severity` (`blocking` or `minor`), + `target` (the slot, criterion, query, section or sentence), `text` (what is wrong), and + `repeats` (the id of an earlier finding it restates, when it is still open). The platform + numbers the round and findings and fingerprints the output. Only the reviewer role of a + conducted loop step may call it.""" + + def record() -> JsonValue: + from factory.model.review_loop import FindingInput + from factory.services import review_loop + + opened = open_project(settings, project, session=session, clock=clock) + actor = make_agent_actor(settings, session, role, model, skill) + if verdict not in ("accept", "revise"): + raise FactoryValidationError([ValidationIssue("verdict", "accept or revise")]) + parsed = [ + parse_input(FindingInput, f, f"findings.{i}") for i, f in enumerate(findings or []) + ] + payload = review_loop.record_verdict( + opened, actor, "accept" if verdict == "accept" else "revise", parsed, summary + ) + return payload.model_dump(mode="json") + + return _reply(project, record, include_work_ids=False) + + @server.tool() + def review_reply( + project: str, + replies: list[dict[str, JsonValue]], + role: str, + model: str, + skill: str, + ) -> dict[str, JsonValue]: + """Answer the findings of the last `revise` verdict of your step, after revising the + output: one reply per blocking finding (`finding_id`, `action` `addressed` or `declined`, + `note` saying what changed or why not). Minor findings may be answered too. Only the + proposer of a conducted loop step may call it, once per round.""" + + def record() -> JsonValue: + from factory.model.review_loop import Reply + from factory.services import review_loop + + opened = open_project(settings, project, session=session, clock=clock) + actor = make_agent_actor(settings, session, role, model, skill) + parsed = [parse_input(Reply, r, f"replies.{i}") for i, r in enumerate(replies)] + payload = review_loop.record_reply(opened, actor, parsed) + return payload.model_dump(mode="json") + + return _reply(project, record, include_work_ids=False) + @server.tool() def protocol_press_review( project: str, diff --git a/platform/src/factory/model/conductor.py b/platform/src/factory/model/conductor.py index adb5ca20..e35b9b5b 100644 --- a/platform/src/factory/model/conductor.py +++ b/platform/src/factory/model/conductor.py @@ -41,7 +41,11 @@ "trust-pause", "human-gate", "refused", + "review-disputed", + "review-missing", ] +ReviewOutcome = Literal["accepted", "escaped"] +ReviewEndReason = Literal["accepted", "max-rounds", "no-progress", "repeat"] class ConductorStarted(StrictModel): @@ -111,3 +115,17 @@ class ConductorFinished(StrictModel): conductor_id: str = Field(pattern=CONDUCTOR_ID_RE) steps_done: int = Field(ge=1) runs: int = Field(ge=0) + + +class ConductorReviewEnded(StrictModel): + """The review loop of a step ended (plan 2026-11-28-review-loops): computed from the + `review.*` events of the step, never typed by an agent. `open_findings` are the ids of the + blocking findings of the last verdict when the loop escaped; empty when accepted.""" + + conductor_id: str = Field(pattern=CONDUCTOR_ID_RE) + step: int = Field(ge=0) + stage_id: NonBlank + outcome: ReviewOutcome + reason: ReviewEndReason + rounds: int = Field(ge=1) + open_findings: tuple[NonBlank, ...] = () diff --git a/platform/src/factory/model/review_loop.py b/platform/src/factory/model/review_loop.py new file mode 100644 index 00000000..fdc4e125 --- /dev/null +++ b/platform/src/factory/model/review_loop.py @@ -0,0 +1,82 @@ +"""Events of the conductor's review loop (plan 2026-11-28-review-loops): `review.*`. + +A loop step (`frame`, `write`) alternates a proposer session and a reviewer session. The reviewer +records one verdict per round; the proposer answers the blocking findings of a `revise` verdict +before the next round. Both are agent acts with provenance. The platform numbers the rounds and +the findings and fingerprints the step's output; the end of the loop is computed +(`conductor.review_ended`). Pure value types. +""" + +from __future__ import annotations + +from typing import Literal + +from pydantic import Field, model_validator + +from factory.model.base import StrictModel +from factory.model.conductor import CONDUCTOR_ID_RE +from factory.model.screening import NonBlank + +Verdict = Literal["accept", "revise"] +Severity = Literal["blocking", "minor"] +ReplyAction = Literal["addressed", "declined"] +FINDING_ID_RE = r"^R[1-9][0-9]*\.F[1-9][0-9]*$" + + +class FindingInput(StrictModel): + """One finding as the reviewer states it: what is wrong and where. `repeats` names the id of + an earlier finding that this one restates (it is still open).""" + + severity: Severity + target: NonBlank + """Where: a slot, criterion, query, section or sentence of the step's output.""" + text: NonBlank + repeats: str | None = Field(default=None, pattern=FINDING_ID_RE) + + +class Finding(FindingInput): + finding_id: str = Field(pattern=FINDING_ID_RE) + + +class ReviewVerdictRecorded(StrictModel): + conductor_id: str = Field(pattern=CONDUCTOR_ID_RE) + step: int = Field(ge=0) + stage_id: NonBlank + round: int = Field(ge=1) + verdict: Verdict + findings: tuple[Finding, ...] = () + summary: NonBlank + fingerprint: str = Field(pattern=r"^[0-9a-f]{64}$") + """The platform's hash of the step's output as it was reviewed.""" + + @model_validator(mode="after") + def _accept_has_no_blocking(self) -> ReviewVerdictRecorded: + if self.verdict == "accept" and any(f.severity == "blocking" for f in self.findings): + raise ValueError("an accept verdict carries no blocking finding") + if self.verdict == "revise" and not any(f.severity == "blocking" for f in self.findings): + raise ValueError("a revise verdict names at least one blocking finding") + return self + + +class Reply(StrictModel): + finding_id: str = Field(pattern=FINDING_ID_RE) + action: ReplyAction + note: NonBlank + + +class ReviewReplyRecorded(StrictModel): + """The proposer's answers to the blocking findings of round `round`'s verdict.""" + + conductor_id: str = Field(pattern=CONDUCTOR_ID_RE) + step: int = Field(ge=0) + round: int = Field(ge=1) + replies: tuple[Reply, ...] = Field(min_length=1) + + +class ReviewReleased(StrictModel): + """A human let the conductor continue past a loop that escaped with blocking findings open + (pause `review-disputed`, tiers other than brief and deep).""" + + conductor_id: str = Field(pattern=CONDUCTOR_ID_RE) + step: int = Field(ge=0) + note: NonBlank diff --git a/platform/src/factory/services/access.py b/platform/src/factory/services/access.py index 53b9c7ce..fc24314f 100644 --- a/platform/src/factory/services/access.py +++ b/platform/src/factory/services/access.py @@ -272,6 +272,9 @@ class Permission(StrEnum): "review_request": Permission.WORK_RUN, # Refused to an agent on a hosted project (`AGENT_PROPOSES_ONLY`). "protocol_record": Permission.PROTOCOL_CHANGE, + "protocol_from_template": Permission.PROTOCOL_CHANGE, + "review_record": Permission.WORK_RUN, + "review_reply": Permission.WORK_RUN, "protocol_amend": Permission.PROTOCOL_CHANGE, "protocol_deviation": Permission.PROTOCOL_CHANGE, # A person's act relayed over MCP: these tools write a human actor. @@ -308,6 +311,7 @@ class Permission(StrEnum): "lead_list": Permission.PROJECT_READ, "manuscript_read": Permission.PROJECT_READ, "protocol_view": Permission.PROJECT_READ, + "review_view": Permission.PROJECT_READ, "question_view": Permission.PROJECT_READ, "registry_query": Permission.PROJECT_READ, "relation_list": Permission.PROJECT_READ, @@ -395,6 +399,7 @@ class Permission(StrEnum): "cli:queue advance": Permission.WORK_RUN, "cli:conductor start": Permission.WORK_RUN, "cli:conductor advance": Permission.WORK_RUN, + "cli:conductor release-review": Permission.HUMAN_CONFIRM, "cli:queue resume": Permission.WORK_RUN, "cli:resume": Permission.WORK_RUN, "cli:activity": Permission.PROJECT_READ, diff --git a/platform/src/factory/services/conductor.py b/platform/src/factory/services/conductor.py index db0ef44c..9897c569 100644 --- a/platform/src/factory/services/conductor.py +++ b/platform/src/factory/services/conductor.py @@ -38,6 +38,7 @@ from factory.model.conductor import ( ConductorFinished, ConductorPaused, + ConductorReviewEnded, ConductorRole, ConductorStarted, ConductorStepFinished, @@ -47,7 +48,7 @@ ) from factory.model.levels import AutonomyLevel from factory.modules.contract import PolicyKind -from factory.services import runner +from factory.services import review_loop, runner from factory.services.context import Project from factory.services.project import project_levels @@ -57,6 +58,7 @@ "conductor.step_finished", "conductor.paused", "conductor.finished", + "conductor.review_ended", ) STEP_STAGE: Final[Mapping[str, str]] = { @@ -104,6 +106,14 @@ id listed here that does not exist yet (`protocol.press_confirm`) fails safe: the conductor waits.""" +TIER_UNBOUND_GATES: Final[Mapping[str, tuple[str, ...]]] = { + "brief": ("protocol.ready", "protocol.press_confirm"), + "deep": ("protocol.ready", "protocol.press_confirm"), +} +"""Step gates that do not bind the conductor at a tier (plan 2026-11-28-review-loops): a brief or +deep review is exploratory, no protocol gate binds (`rf-brief`), and the frame step's review loop +stands in for them. The output says the protocol was not confirmed by a human.""" + _ROLE_GATES: Final[Mapping[tuple[str, str], tuple[str, ...]]] = { ("develop", "drafter"): ("hypotheses.lead_decide",), } @@ -303,14 +313,76 @@ def _more_to_run(project: Project, trail: _Trail, index: int, step: str) -> bool def _effective_closed(project: Project, trail: _Trail) -> set[tuple[int, str]]: - """`_closed_roles`, minus the proposer of a queue step that must run again (`_more_to_run`).""" + """`_closed_roles`, minus the proposer of a queue step that must run again (`_more_to_run`), + and adjusted for the round of a review loop (`_loop_open`).""" closed = _closed_roles(trail) for index, step in enumerate(trail.meta.steps): if (index, "proposer") in closed and _more_to_run(project, trail, index, step): closed.discard((index, "proposer")) + if review_loop.is_loop_step(step): + closed -= {(index, r) for r in _loop_open(project, trail, index)} return closed +def _loop_runs(trail: _Trail, index: int) -> list[ConductorStepFinished]: + """The complete proposer and verifier runs of a loop step, in order.""" + return [ + f + for f in ( + ConductorStepFinished.model_validate(e.payload) for e in trail.payloads("step_finished") + ) + if f.step == index and f.role in ("proposer", "verifier") and f.outcome == "complete" + ] + + +def _verdict_missing(project: Project, trail: _Trail, index: int) -> bool: + """Whether the latest complete reviewer run of a loop step recorded no verdict.""" + started = [ + e.id + for e in trail.payloads("step_started") + if e.payload["step"] == index and e.payload["role"] == "verifier" + ] + if not started: + return False + recorded = review_loop.verdict_events(project, trail.meta.conductor_id, index) + return not any(event_id > started[-1] for event_id, _ in recorded) + + +def _loop_open(project: Project, trail: _Trail, index: int) -> set[str]: + """The roles of a loop step that are open again: after a reviewer's `revise` the proposer and + the reviewer (a new round); after the proposer's revision the reviewer; after a reviewer run + that recorded no verdict the reviewer (`_decide` pauses on it unless retried).""" + runs = _loop_runs(trail, index) + if not any(f.role == "verifier" for f in runs): + return set() + if runs[-1].role == "proposer": + return {"verifier"} + if _verdict_missing(project, trail, index): + return {"verifier"} + recorded = review_loop.verdicts(project, trail.meta.conductor_id, index) + if review_loop.loop_end(recorded) is None: + return {"proposer", "verifier"} + return set() + + +def _disputed(project: Project, trail: _Trail, upto: int) -> int | None: + """The first loop step up to `upto` whose loop escaped with blocking findings open at a tier + that does not continue past it, and that no human has released (`review.released`).""" + if trail.meta.tier in review_loop.CONTINUE_TIERS: + return None + for index, step in enumerate(trail.meta.steps[: upto + 1]): + if not review_loop.is_loop_step(step): + continue + end = review_loop.loop_end(review_loop.verdicts(project, trail.meta.conductor_id, index)) + if ( + end is not None + and end.outcome == "escaped" + and not review_loop.released(project, trail.meta.conductor_id, index) + ): + return index + return None + + def _open_run(trail: _Trail) -> ConductorStepStarted | None: finished = {e.payload.get("run_id") for e in trail.payloads("step_finished")} for event in reversed(trail.payloads("step_started")): @@ -326,7 +398,9 @@ def _open_run(trail: _Trail) -> ConductorStepStarted | None: def _policy_kinds(project: Project, stage_id: str) -> dict[str, PolicyKind]: from factory.services.gates import effective_policy - gates = STEP_GATES.get(stage_of_step(stage_id), ()) + tier = project_levels(project).tier + unbound = TIER_UNBOUND_GATES.get("" if tier is None else tier.value, ()) + gates = [g for g in STEP_GATES.get(stage_of_step(stage_id), ()) if g not in unbound] return {g: effective_policy(project, g).kind for g in gates} @@ -349,10 +423,11 @@ def roles_of( return ("lead", "drafter", "critic") first: tuple[ConductorRole, ...] = ("proposer", "second-pass") if second_pass else ("proposer",) kinds = _policy_kinds(project, stage_id) - if level is not AutonomyLevel.ATTENDED and any( - k is not PolicyKind.HUMAN for k in kinds.values() - ): + agent_gate = any(k is not PolicyKind.HUMAN for k in kinds.values()) + if level is not AutonomyLevel.ATTENDED and agent_gate: return (*first, "verifier", "auditor") + if level is not AutonomyLevel.ATTENDED and review_loop.is_loop_step(stage_id): + return (*first, "verifier") # the reviewer of the loop, with no gate to audit return first @@ -364,7 +439,7 @@ def _stage_of(stage_id: str, role: ConductorRole) -> str: if role == "second-pass": return SECOND_PASS_STAGE[stage_of_step(stage_id)] if role == "verifier": - return "conduct-verify" + return review_loop.LOOP_STEPS.get(stage_of_step(stage_id), "conduct-verify") if role == "auditor": return "conduct-audit" return STEP_STAGE[stage_id] @@ -508,6 +583,24 @@ def _decide( if waiting_gate is not None: return _Decision("wait", index, stage_id, None, "human-gate", waiting_gate, f"gate {waiting_gate} awaits a human") # fmt: skip + disputed = _disputed(project, trail, index) + if disputed is not None: + return _Decision( + "pause", disputed, meta.steps[disputed], None, "review-disputed", + detail=f"the review loop of {meta.steps[disputed]} ended with blocking findings " + "open; a human releases it with `factory conductor release-review`", + ) # fmt: skip + if ( + role == "verifier" + and review_loop.is_loop_step(stage_id) + and not retry + and _verdict_missing(project, trail, index) + and any(f.role == "verifier" for f in _loop_runs(trail, index)) + ): + return _Decision( + "pause", index, stage_id, role, "review-missing", + detail=f"the reviewer of {stage_id} recorded no verdict; advance with retry", + ) # fmt: skip last = [ e for e in trail.payloads("step_finished") @@ -680,6 +773,64 @@ def begin_conductor(project: Project, plan: PlanLike) -> ConductorRun: return ConductorRun(conductor_id, started.tier, started.autonomy_level, started.steps, budget) +def _end_review(project: Project, conductor_id: str, step: int, stage_id: str) -> None: + """Record `conductor.review_ended` once, when the verdicts so far end the step's loop.""" + end = review_loop.loop_end(review_loop.verdicts(project, conductor_id, step)) + if end is None: + return + ended = read_typed(project.paths.events_dir, project.catalog, ("conductor.review_ended",)) + if any( + e.actor.kind == "system" + and e.payload["conductor_id"] == conductor_id + and e.payload["step"] == step + for e in ended + ): + return + _write( + project, + "review_ended", + ConductorReviewEnded( + conductor_id=conductor_id, + step=step, + stage_id=stage_id, + outcome=end.outcome, + reason=end.reason, + rounds=end.rounds, + open_findings=end.open_findings, + ), + ) + + +@dataclass(frozen=True) +class OpenRoleRun: + """The conductor's open role run: what a review act is checked against.""" + + conductor_id: str + tier: str + step: int + stage_id: str + role: ConductorRole + started_event_id: str + + +def open_role_run(project: Project) -> OpenRoleRun | None: + """The open role run of the project's open conductor run; None when there is none.""" + trail = _load(project) + if trail is None: + return None + run = _open_run(trail) + if run is None: + return None + started = next( + e.id + for e in reversed(trail.payloads("step_started")) + if e.payload.get("run_id") == run.run_id + ) + return OpenRoleRun( + trail.meta.conductor_id, trail.meta.tier, run.step, run.stage_id, run.role, started + ) + + def _write(project: Project, kind: str, payload: StrictModel) -> None: with project.writing(): project.record([project.events.make(f"conductor.{kind}", payload, project.system_actor())]) @@ -736,6 +887,8 @@ def advance( pending=_queue_pending(pend, project, open_run.stage_id) if queue else None, ), ) + if open_run.role == "verifier" and review_loop.is_loop_step(open_run.stage_id): + _end_review(project, meta.conductor_id, open_run.step, open_run.stage_id) trail = _load(project) or trail decision = _decide(project, trail, retry=retry, pending=pend, gate_closed=closer) if decision.kind == "complete-empty": diff --git a/platform/src/factory/services/modules/retrieval.py b/platform/src/factory/services/modules/retrieval.py index b6a6961a..636b841e 100644 --- a/platform/src/factory/services/modules/retrieval.py +++ b/platform/src/factory/services/modules/retrieval.py @@ -123,6 +123,10 @@ "conductor.step_finished", "conductor.paused", "conductor.finished", + "conductor.review_ended", + "review.verdict_recorded", + "review.reply_recorded", + "review.released", ), tables=("runner_runs", "runner_pipelines"), note=( @@ -130,7 +134,8 @@ "`claude` executable for one stage; both events are system acts, and every judgement " "is written through MCP with the agent's provenance. The `conductor.*` events (plan " "tiers-and-autonomy C8) are system acts of the lifecycle conductor, derived from the " - "log without a table." + "log without a table. The `review.*` events are the agent acts of its review loop " + "(plan 2026-11-28-review-loops), also without a table." ), ), ) diff --git a/platform/src/factory/services/review_loop.py b/platform/src/factory/services/review_loop.py new file mode 100644 index 00000000..59cf6880 --- /dev/null +++ b/platform/src/factory/services/review_loop.py @@ -0,0 +1,323 @@ +"""The conductor's review loop (plan 2026-11-28-review-loops). + +A loop step (`LOOP_STEPS`) alternates its proposer and a reviewer session (the step's `verifier` +role). The reviewer records one verdict per round (`record_verdict`); after a `revise` verdict the +proposer runs again and answers each blocking finding (`record_reply`) before the next review. + +Invariants: +- Rounds and finding ids (`R.F`) are numbered by the platform, and the step's output is + fingerprinted by the platform when a verdict is recorded; none of them is typed by an agent. +- A verdict is accepted only while the conductor's open run is the reviewer of a loop step, and + once per reviewer run; a reply only while its open run is that step's proposer, once per round, + and it must answer every blocking finding of the last verdict. Refusals write nothing. +- The end of the loop (`loop_end`) is computed from the verdicts alone: `accept`; round + `MAX_ROUNDS`; no progress (every blocking finding repeats a blocking finding of the round before + and there are no fewer); or a fingerprint equal to an earlier round's (`repeat`). +- No projection table: the state is read from the log, as the conductor's is. +""" + +from __future__ import annotations + +import hashlib +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Final + +from pydantic import JsonValue + +from factory.canonical import canonical_json +from factory.errors import FactoryValidationError, ValidationIssue +from factory.events.envelope import Actor +from factory.events.reader import read_typed +from factory.model.base import StrictModel +from factory.model.conductor import ReviewEndReason, ReviewOutcome +from factory.model.review_loop import ( + Finding, + FindingInput, + Reply, + ReviewReleased, + ReviewReplyRecorded, + ReviewVerdictRecorded, + Verdict, +) +from factory.services.context import Project + +LOOP_STEPS: Final = {"frame": "review-frame", "write": "review-write"} +"""The steps with a review loop and the runner stage of each one's reviewer.""" +MAX_ROUNDS: Final = 5 +CONTINUE_TIERS: Final = ("brief", "deep") +"""Tiers whose conductor continues past a loop that escaped with blocking findings open (they are +labelled in the output); at other tiers the conductor pauses with `review-disputed`.""" +EVENT_TYPES: Final = ("review.verdict_recorded", "review.reply_recorded", "review.released") + + +def is_loop_step(stage_id: str) -> bool: + return stage_id.split(":", 1)[0] in LOOP_STEPS + + +def _refuse(field: str, reason: str) -> FactoryValidationError: + return FactoryValidationError([ValidationIssue(field, reason)]) + + +# ----------------------------------------------------------------------------- fingerprints + + +def _frame_output(project: Project) -> JsonValue: + from factory.services.protocol import current_protocol + from factory.services.question import current_question + from factory.services.seeds import all_seeds + + question = current_question(project) + protocol = current_protocol(project) + return { + "question": None if question is None else question.spec.model_dump(mode="json"), + "protocol": None if protocol is None else protocol.spec.model_dump(mode="json"), + "seeds": [s.model_dump(mode="json") for s in all_seeds(project)], + } + + +def _write_output(project: Project) -> JsonValue: + from factory.services.drafts import list_drafts, live_sentences + + return [ + { + "draft_id": d.draft_id, + "title": d.title, + "sentences": [ + { + "section": r.section_id, + "order": r.order, + "text": r.text, + "supports": list[JsonValue](r.supports), + } + for r in live_sentences(project, d.draft_id) + ], + } + for d in list_drafts(project) + ] + + +def fingerprint(project: Project, stage_id: str) -> str: + """The sha256 of the loop step's output as the platform reads it now.""" + stage = stage_id.split(":", 1)[0] + output = _frame_output(project) if stage == "frame" else _write_output(project) + return hashlib.sha256(canonical_json(output)).hexdigest() + + +# ------------------------------------------------------------------------------- the record + + +def verdict_events( + project: Project, conductor_id: str, step: int +) -> list[tuple[str, ReviewVerdictRecorded]]: + """The verdicts of a step's loop with their event ids, in log order (agent acts only).""" + out = [ + (e.id, ReviewVerdictRecorded.model_validate(e.payload)) + for e in read_typed(project.paths.events_dir, project.catalog, ("review.verdict_recorded",)) + if e.actor.kind == "agent" + ] + return [(i, v) for i, v in out if v.conductor_id == conductor_id and v.step == step] + + +def verdicts(project: Project, conductor_id: str, step: int) -> list[ReviewVerdictRecorded]: + return [v for _, v in verdict_events(project, conductor_id, step)] + + +def released(project: Project, conductor_id: str, step: int) -> bool: + """Whether a human released the step's escaped loop (`review.released`).""" + return any( + e.actor.kind == "human" + and e.payload["conductor_id"] == conductor_id + and e.payload["step"] == step + for e in read_typed(project.paths.events_dir, project.catalog, ("review.released",)) + ) + + +def replies(project: Project, conductor_id: str, step: int) -> list[ReviewReplyRecorded]: + out = [ + ReviewReplyRecorded.model_validate(e.payload) + for e in read_typed(project.paths.events_dir, project.catalog, ("review.reply_recorded",)) + if e.actor.kind == "agent" + ] + return [r for r in out if r.conductor_id == conductor_id and r.step == step] + + +@dataclass(frozen=True) +class LoopEnd: + outcome: ReviewOutcome + reason: ReviewEndReason + rounds: int + open_findings: tuple[str, ...] + + +def _blocking(v: ReviewVerdictRecorded) -> list[Finding]: + return [f for f in v.findings if f.severity == "blocking"] + + +def loop_end(recorded: Sequence[ReviewVerdictRecorded]) -> LoopEnd | None: + """Whether the loop has ended after the verdicts so far; None while it goes on (or before the + first verdict).""" + if not recorded: + return None + last = recorded[-1] + rounds = len(recorded) + if last.verdict == "accept": + return LoopEnd("accepted", "accepted", rounds, ()) + open_ids = tuple(f.finding_id for f in _blocking(last)) + if rounds >= MAX_ROUNDS: + return LoopEnd("escaped", "max-rounds", rounds, open_ids) + if any(v.fingerprint == last.fingerprint for v in recorded[:-1]): + return LoopEnd("escaped", "repeat", rounds, open_ids) + if rounds >= 2: + before = {f.finding_id for f in _blocking(recorded[-2])} + now = _blocking(last) + if len(now) >= len(before) and all(f.repeats in before for f in now): + return LoopEnd("escaped", "no-progress", rounds, open_ids) + return None + + +# ---------------------------------------------------------------------------------- writing + + +def _require_agent(actor: Actor) -> None: + if actor.kind != "agent": + raise _refuse("actor", "only an agent session records a review act") + + +def record_verdict( + project: Project, + actor: Actor, + verdict: Verdict, + findings: Sequence[FindingInput], + summary: str, +) -> ReviewVerdictRecorded: + """Record the reviewer's verdict of the open round. Refused, nothing written, outside a + reviewer run of a loop step, a second time in one run, an ended loop, or a `repeats` naming + no earlier finding.""" + from factory.services import conductor + + _require_agent(actor) + with project.writing(): + run = conductor.open_role_run(project) + if run is None or run.role != "verifier" or not is_loop_step(run.stage_id): + raise _refuse("run", "no reviewer run of a loop step is open") + recorded = verdict_events(project, run.conductor_id, run.step) + if any(event_id > run.started_event_id for event_id, _ in recorded): + raise _refuse("run", "this reviewer run has already recorded its verdict") + done = [v for _, v in recorded] + if loop_end(done) is not None: + raise _refuse("run", "the review loop of this step has ended") + earlier = {f.finding_id for v in done for f in v.findings} + stray = sorted({f.repeats for f in findings if f.repeats and f.repeats not in earlier}) + if stray: + raise _refuse("findings", f"repeats names no earlier finding: {', '.join(stray)}") + number = len(done) + 1 + try: + payload = ReviewVerdictRecorded( + conductor_id=run.conductor_id, + step=run.step, + stage_id=run.stage_id, + round=number, + verdict=verdict, + findings=tuple( + Finding(finding_id=f"R{number}.F{k}", **f.model_dump()) + for k, f in enumerate(findings, start=1) + ), + summary=summary, + fingerprint=fingerprint(project, run.stage_id), + ) + except ValueError as exc: + raise _refuse("verdict", str(exc).splitlines()[-1]) from exc + blob = project.blobs.put_json(payload.model_dump(mode="json")) + project.record( + [project.events.make("review.verdict_recorded", payload, actor, input_blob=blob)] + ) + return payload + + +def record_reply(project: Project, actor: Actor, answers: Sequence[Reply]) -> ReviewReplyRecorded: + """Record the proposer's answers to the last `revise` verdict of its step. Refused, nothing + written, outside a proposer run of a loop step, with no `revise` verdict to answer, a second + time for one round, an id not in that verdict, or a blocking finding left unanswered.""" + from factory.services import conductor + + _require_agent(actor) + with project.writing(): + run = conductor.open_role_run(project) + if run is None or run.role != "proposer" or not is_loop_step(run.stage_id): + raise _refuse("run", "no proposer run of a loop step is open") + done = verdicts(project, run.conductor_id, run.step) + if not done or done[-1].verdict != "revise": + raise _refuse("run", "there is no revise verdict to answer") + last = done[-1] + if any(r.round == last.round for r in replies(project, run.conductor_id, run.step)): + raise _refuse("replies", f"round {last.round} is already answered") + known = {f.finding_id for f in last.findings} + unknown = sorted({a.finding_id for a in answers} - known) + if unknown: + raise _refuse("replies", f"not findings of round {last.round}: {', '.join(unknown)}") + missing = [f.finding_id for f in _blocking(last) if f.finding_id not in + {a.finding_id for a in answers}] # fmt: skip + if missing: + raise _refuse("replies", f"blocking findings unanswered: {', '.join(missing)}") + payload = ReviewReplyRecorded( + conductor_id=run.conductor_id, step=run.step, round=last.round, replies=tuple(answers) + ) + blob = project.blobs.put_json(payload.model_dump(mode="json")) + project.record( + [project.events.make("review.reply_recorded", payload, actor, input_blob=blob)] + ) + return payload + + +# ------------------------------------------------------------------------------------- view + + +class ReviewView(StrictModel): + conductor_id: str | None + step: int | None + stage_id: str | None + max_rounds: int = MAX_ROUNDS + verdicts: tuple[ReviewVerdictRecorded, ...] = () + replies: tuple[ReviewReplyRecorded, ...] = () + ended: str | None = None + """`: ` once the loop has ended.""" + + +def review_view(project: Project) -> ReviewView: + """The review loop of the conductor's current loop step: its verdicts and replies so far.""" + from factory.services import conductor + + run = conductor.open_role_run(project) + if run is None or not is_loop_step(run.stage_id): + return ReviewView(conductor_id=None, step=None, stage_id=None) + done = verdicts(project, run.conductor_id, run.step) + end = loop_end(done) + return ReviewView( + conductor_id=run.conductor_id, + step=run.step, + stage_id=run.stage_id, + verdicts=tuple(done), + replies=tuple(replies(project, run.conductor_id, run.step)), + ended=None if end is None else f"{end.outcome}: {end.reason}", + ) + + +def release(project: Project, actor: Actor, note: str) -> ReviewReleased: + """A human releases the escaped loop at which the conductor paused (`review-disputed`): the + run continues with the findings open and labelled. Refused, nothing written, for a non-human + actor or when the conductor is not paused on a disputed loop.""" + from factory.services import conductor + + if actor.kind != "human": + raise _refuse("actor", "only a human releases a disputed review") + with project.writing(): + status = conductor.conductor_status(project) + if status.state != "paused" or status.reason != "review-disputed": + raise _refuse("conductor", "the conductor is not paused on a disputed review") + step = status.steps.index(status.stage_id or "") + payload = ReviewReleased( + conductor_id=status.conductor_id or "", step=step, note=note.strip() or "released" + ) + project.record([project.events.make("review.released", payload, actor)]) + return payload diff --git a/platform/src/factory/services/runner.py b/platform/src/factory/services/runner.py index d806d85a..24d8e0cc 100644 --- a/platform/src/factory/services/runner.py +++ b/platform/src/factory/services/runner.py @@ -380,6 +380,10 @@ class StageSpec: """The reads the hypothesis engine's skill names for the lead author and the drafter (corpus and selection, the finders, the technique views, quote verification). Every one is a `project:read` tool: none writes an event or closes a gate.""" +OPUS: Final = "claude-opus-5-5" +"""The model of the few, short, judged conducted sessions: frame, write and their reviewers.""" +_REVIEW_REPLY: Final = (f"{_P}review_view", f"{_P}review_reply") +_REVIEW_RECORD: Final = (f"{_P}review_view", f"{_P}review_record") _CONDUCT_READ: Final = ( f"{_P}project_status", f"{_P}gate_status", @@ -393,9 +397,11 @@ class StageSpec: # Lifecycle stages run by the conductor (`services/conductor.py`, plan tiers-and-autonomy # C8). Each allow-list leaves out the gate acts of its stage: a proposer never confirms, # releases or reviews what it proposed. Their pending unit is the conductor's current step. + # A conducted frame has no researcher to interview: `rf-frame-conducted` records the stated + # goal verbatim, fills the question from it and records the tier's protocol template. "frame": StageSpec( - model="claude-sonnet-5-5", - skill="rf-frame", + model=OPUS, + skill="rf-frame-conducted", role="proposer", tools=( f"{_P}project_status", @@ -404,10 +410,12 @@ class StageSpec: f"{_P}seed_add", f"{_P}seed_list", f"{_P}probe_run", + f"{_P}protocol_from_template", f"{_P}protocol_record", f"{_P}protocol_view", f"{_P}term_list", f"{_P}vocabulary_propose", + *_REVIEW_REPLY, ), kinds=(), unit="frame step", @@ -455,7 +463,7 @@ class StageSpec: fixed_cap=1, ), "write": StageSpec( - model="claude-sonnet-5-5", + model=OPUS, skill="rf-write", role="proposer", tools=( @@ -477,6 +485,7 @@ class StageSpec: f"{_P}draft_list", f"{_P}draft_status", f"{_P}draft_render", + *_REVIEW_REPLY, ), kinds=(), unit="write step", @@ -582,6 +591,41 @@ class StageSpec: kinds=(), unit="work extracted (pass B)", ), + # The reviewers of the review loops (plan 2026-11-28-review-loops): read the step's output + # and record one verdict; they change nothing else. + "review-frame": StageSpec( + model=OPUS, + skill="rf-review", + role="verifier", + tools=( + f"{_P}project_status", + f"{_P}question_view", + f"{_P}seed_list", + f"{_P}protocol_view", + f"{_P}term_list", + *_REVIEW_RECORD, + ), + kinds=(), + unit="review round", + fixed_cap=1, + ), + "review-write": StageSpec( + model=OPUS, + skill="rf-review", + role="verifier", + tools=( + *_CONDUCT_READ, + f"{_P}question_view", + f"{_P}draft_list", + f"{_P}draft_status", + f"{_P}draft_render", + f"{_P}chat_verify", + *_REVIEW_RECORD, + ), + kinds=(), + unit="review round", + fixed_cap=1, + ), "conduct-verify": StageSpec( model="claude-sonnet-5-5", skill="rf-conductor", @@ -620,6 +664,8 @@ class StageSpec: "extract-b", "conduct-verify", "conduct-audit", + "review-frame", + "review-write", ) """The stages the conductor starts; their pending unit is its current step (`conductor.pending`). `screen` and `extract` are also conductor steps but keep their own work-queue pending units.""" @@ -945,8 +991,11 @@ def _prompt( "You are one role session of a conducted run (`factory conductor`), in a session of " f"your own: the role is `{spec.role}`. Nobody answers questions during the run: ask " "nothing and wait for nothing. Do only your role; confirm, release or decide no gate " - "that a human or another role closes; if a tool refuses, report the refusal " - "verbatim and stop.\n\n" + "that a human or another role closes. If a tool that writes refuses, report the " + "refusal verbatim and stop; if a read refuses, note it and go on without it. When " + "`review_view` is in your tools and lists a `revise` verdict for this step, this run " + "is a revision: address each blocking finding in the step's output, then answer every " + "blocking finding with `review_reply` (`addressed` or `declined`, with a note).\n\n" ) if stage == "screen-ft": from factory.services.screening import SCREEN_BATCH # screening imports much diff --git a/platform/src/factory/services/tier_protocol.py b/platform/src/factory/services/tier_protocol.py new file mode 100644 index 00000000..af230f53 --- /dev/null +++ b/platform/src/factory/services/tier_protocol.py @@ -0,0 +1,64 @@ +"""The tier's protocol template recorded for a project (plan 2026-11-28-review-loops). + +A conducted frame session gives the criteria and the planned queries; the platform fills the rest +from the tier's `ProtocolTemplate` and records the protocol as a draft through +`protocol.record_protocol`. + +Invariants: +- Refused, nothing written, for a project without a tier or a tier without a template, with no + current question, or with queries the template does not allow (a source it does not name, or + more per source than `queries_per_source`). +- The reviewer of record is the human who created the project (the actor of `project.created`), + never the agent that calls the tool. +- The protocol is recorded as a draft (`ready` false): readiness stays a human's act. +""" + +from __future__ import annotations + +from collections.abc import Sequence + +from factory.errors import FactoryValidationError, ValidationIssue +from factory.events.envelope import Actor +from factory.events.reader import read_typed +from factory.model.protocol import Criterion, PlannedQuery +from factory.services.context import Project +from factory.services.protocol import ProtocolResult, record_protocol +from factory.services.question import current_question + + +def _refuse(field: str, reason: str) -> FactoryValidationError: + return FactoryValidationError([ValidationIssue(field, reason)]) + + +def creator(project: Project) -> str: + """The id of the human who created the project.""" + for event in read_typed(project.paths.events_dir, project.catalog, ("project.created",)): + return event.actor.user or event.actor.id + raise _refuse("project", "the project has no project.created event") + + +def record_from_template( + project: Project, + actor: Actor, + criteria: Sequence[Criterion], + queries: Sequence[PlannedQuery], +) -> ProtocolResult: + from factory.services.project import project_levels + from factory.tiers.plans import PLANS + + tier = project_levels(project).tier + if tier is None: + raise _refuse("project", "the project declares no tier") + template = PLANS[tier].protocol_template + if template is None: + raise _refuse("project", f"tier {tier.value} has no protocol template") + question = current_question(project) + if question is None: + raise _refuse("question", "record the question first") + try: + spec = template.instantiate( + question.question_id, criteria=criteria, queries=queries, reviewer=creator(project) + ) + except ValueError as exc: + raise _refuse("queries", str(exc)) from exc + return record_protocol(project, actor, spec, ready=False) diff --git a/platform/tests/test_conductor_access.py b/platform/tests/test_conductor_access.py index 5b4cb3f6..2750c01f 100644 --- a/platform/tests/test_conductor_access.py +++ b/platform/tests/test_conductor_access.py @@ -21,7 +21,7 @@ def _commands() -> list[str]: def test_every_conductor_command_declares_a_permission() -> None: - assert sorted(_commands()) == ["advance", "start", "status"] + assert sorted(_commands()) == ["advance", "release-review", "start", "status"] for name in _commands(): command_permission(f"cli:conductor {name}") # raises when undeclared diff --git a/platform/tests/test_review_loop.py b/platform/tests/test_review_loop.py new file mode 100644 index 00000000..13e2cd98 --- /dev/null +++ b/platform/tests/test_review_loop.py @@ -0,0 +1,430 @@ +"""The conductor's review loop (plan 2026-11-28-review-loops): verdicts and replies, the rounds of +a loop step, its escapes, and what the conductor does after an escape at each tier.""" + +from __future__ import annotations + +import itertools +from collections.abc import Iterator +from dataclasses import dataclass, field +from typing import Any + +import pytest + +from factory.clock import FixedClock +from factory.config import Settings +from factory.errors import FactoryValidationError +from factory.events.envelope import Actor +from factory.events.reader import read_typed +from factory.model.levels import AutonomyLevel, Tier +from factory.model.review_loop import FindingInput, Reply +from factory.services import conductor, review_loop, runner +from factory.services.context import Project +from factory.services.project import init_project +from tests.helpers import SESSION + + +@dataclass(frozen=True) +class FStage: + stage_id: str + skill: str = "rf-x" + caps: dict[str, int] = field(default_factory=dict) + skipped: bool = False + note: str = "" + + +@dataclass(frozen=True) +class FLimits: + max_papers: int = 30 + max_minutes: int = 600 + max_runs: int = 40 + + +@dataclass(frozen=True) +class FPlan: + tier: Tier + stages: tuple[FStage, ...] + limits: FLimits | None = FLimits() + + +_REAL_FINGERPRINT = review_loop.fingerprint + + +class Runs: + """Stands for `runner.start_run`: starts nothing, every run completes.""" + + def __init__(self) -> None: + self.stages: list[str] = [] + self.ids = itertools.count(1) + + def start(self, project: Project, stage: str, *, unit_cap: int) -> str: + self.stages.append(stage) + return project.ids.new("rnr") + + +def _idle(_p: Project, stage: str) -> dict[str, int]: + return {stage: 0} + + +def _open(_p: Project, _s: str, _g: str) -> bool: + return True + + +def _make(settings: Settings, clock: FixedClock, tier: str, level: str = "autonomous") -> Project: + return init_project( + settings, "demo", None, session=SESSION, clock=clock, tier=tier, autonomy_level=level + ) + + +def _plan(tier: Tier, *ids: str) -> FPlan: + return FPlan(tier, tuple(FStage(i) for i in ids)) + + +def _step(project: Project, runs: Runs, *, retry: bool = False) -> conductor.ConductorStatus: + return conductor.advance( + project, + retry=retry, + start_run=runs.start, + pending=_idle, + gate_closed=_open, + reconcile=lambda _p: [], + ) + + +@pytest.fixture(autouse=True) +def _complete(monkeypatch: pytest.MonkeyPatch) -> None: + """Every role run has ended complete by the next `advance`.""" + monkeypatch.setattr(runner, "run_outcome", lambda _p, _r: "complete") + + +@pytest.fixture(autouse=True) +def _fingerprints(monkeypatch: pytest.MonkeyPatch) -> Iterator[list[str]]: + """Each verdict sees a new output unless a test queues a fingerprint.""" + queued: list[str] = [] + fresh = (f"{n:064x}" for n in itertools.count(1)) + monkeypatch.setattr( + review_loop, "fingerprint", lambda _p, _s: queued.pop(0) if queued else next(fresh) + ) + yield queued + + +@pytest.fixture +def reviewer() -> Actor: + return Actor(kind="agent", id="reviewer", user="obd", session="S" * 26, + model="claude-opus-5-5", skill="rf-review@1a2b3c4d") # fmt: skip + + +@pytest.fixture +def proposer() -> Actor: + return Actor(kind="agent", id="proposer", user="obd", session="P" * 26, + model="claude-opus-5-5", skill="rf-frame-conducted@1a2b3c4d") # fmt: skip + + +def _blocking(text: str = "the queries miss RWKV", repeats: str | None = None) -> FindingInput: + return FindingInput(severity="blocking", target="queries", text=text, repeats=repeats) + + +def _events(project: Project, kind: str) -> list[Any]: + return read_typed(project.paths.events_dir, project.catalog, (kind,)) + + +def _revise(project: Project, actor: Actor, *findings: FindingInput) -> None: + review_loop.record_verdict(project, actor, "revise", findings or (_blocking(),), "checked") + + +def _reply_all(project: Project, actor: Actor) -> None: + last = review_loop.review_view(project).verdicts[-1] + review_loop.record_reply( + project, + actor, + [Reply(finding_id=f.finding_id, action="addressed", note="added") for f in last.findings + if f.severity == "blocking"], + ) # fmt: skip + + +# --------------------------------------------------------------------------------- the roles + + +def test_a_loop_step_has_a_reviewer_and_no_gate_wait_at_brief( + settings: Settings, clock: FixedClock +) -> None: + project = _make(settings, clock, "brief") + level = AutonomyLevel.AUTONOMOUS + assert conductor.roles_of(project, "frame", level) == ("proposer", "verifier") + assert conductor._policy_kinds(project, "frame") == {} # no protocol gate binds a brief + assert conductor._stage_of("frame", "verifier") == "review-frame" + assert conductor._stage_of("write", "verifier") == "review-write" + assert conductor._stage_of("gather", "verifier") == "conduct-verify" + + +def test_attended_has_no_loop(settings: Settings, clock: FixedClock) -> None: + project = _make(settings, clock, "brief", level="attended") + assert conductor.roles_of(project, "frame", AutonomyLevel.ATTENDED) == ("proposer",) + + +def test_the_frame_gates_still_bind_a_pilot(settings: Settings, clock: FixedClock) -> None: + project = _make(settings, clock, "pilot") + assert set(conductor._policy_kinds(project, "frame")) == { + "protocol.ready", + "protocol.press_confirm", + } + + +# ------------------------------------------------------------------------------- the rounds + + +def test_accept_in_round_one_ends_the_loop_and_moves_on( + settings: Settings, clock: FixedClock, reviewer: Actor +) -> None: + project = _make(settings, clock, "brief") + runs = Runs() + conductor.begin_conductor(project, _plan(Tier.BRIEF, "frame", "gather")) + _step(project, runs) # proposer + status = _step(project, runs) # reviewer + assert status.role == "verifier" and runs.stages == ["frame", "review-frame"] + review_loop.record_verdict(project, reviewer, "accept", [], "faithful to the goal") + status = _step(project, runs) + assert runs.stages[-1] == "gather" + ended = [e.payload for e in _events(project, "conductor.review_ended")] + assert ended == [ + { + "conductor_id": ended[0]["conductor_id"], + "step": 0, + "stage_id": "frame", + "outcome": "accepted", + "reason": "accepted", + "rounds": 1, + "open_findings": [], + } + ] + + +def test_revise_runs_the_proposer_again_then_a_new_reviewer( + settings: Settings, clock: FixedClock, reviewer: Actor, proposer: Actor +) -> None: + project = _make(settings, clock, "brief") + runs = Runs() + conductor.begin_conductor(project, _plan(Tier.BRIEF, "frame", "gather")) + _step(project, runs) + _step(project, runs) + _revise(project, reviewer) + status = _step(project, runs) + assert status.role == "proposer" and runs.stages == ["frame", "review-frame", "frame"] + _reply_all(project, proposer) + status = _step(project, runs) + assert status.role == "verifier" and runs.stages[-1] == "review-frame" + review_loop.record_verdict(project, reviewer, "accept", [], "RWKV added") + _step(project, runs) + assert runs.stages == ["frame", "review-frame", "frame", "review-frame", "gather"] + view = [v.round for v in review_loop.verdicts(project, status.conductor_id or "", 0)] + assert view == [1, 2] + + +def test_findings_are_numbered_by_the_platform( + settings: Settings, clock: FixedClock, reviewer: Actor +) -> None: + project = _make(settings, clock, "brief") + runs = Runs() + conductor.begin_conductor(project, _plan(Tier.BRIEF, "frame")) + _step(project, runs) + _step(project, runs) + minor = FindingInput(severity="minor", target="NG01", text="could be sharper") + recorded = review_loop.record_verdict(project, reviewer, "revise", [_blocking(), minor], "s") + assert [f.finding_id for f in recorded.findings] == ["R1.F1", "R1.F2"] + assert recorded.round == 1 and len(recorded.fingerprint) == 64 + + +# ------------------------------------------------------------------------------ refusals + + +def test_a_verdict_outside_a_reviewer_run_is_refused( + settings: Settings, clock: FixedClock, reviewer: Actor +) -> None: + project = _make(settings, clock, "brief") + runs = Runs() + conductor.begin_conductor(project, _plan(Tier.BRIEF, "frame")) + _step(project, runs) # the proposer's run is open + with pytest.raises(FactoryValidationError, match="no reviewer run"): + review_loop.record_verdict(project, reviewer, "accept", [], "s") + assert _events(project, "review.verdict_recorded") == [] + + +def test_one_verdict_per_reviewer_run( + settings: Settings, clock: FixedClock, reviewer: Actor +) -> None: + project = _make(settings, clock, "brief") + runs = Runs() + conductor.begin_conductor(project, _plan(Tier.BRIEF, "frame")) + _step(project, runs) + _step(project, runs) + _revise(project, reviewer) + with pytest.raises(FactoryValidationError, match="already recorded"): + review_loop.record_verdict(project, reviewer, "accept", [], "s") + + +@pytest.mark.parametrize( + ("verdict", "findings"), + [("accept", [FindingInput(severity="blocking", target="q", text="t")]), ("revise", [])], +) +def test_a_verdict_must_match_its_findings( + settings: Settings, clock: FixedClock, reviewer: Actor, verdict: str, findings: list[Any] +) -> None: + project = _make(settings, clock, "brief") + runs = Runs() + conductor.begin_conductor(project, _plan(Tier.BRIEF, "frame")) + _step(project, runs) + _step(project, runs) + with pytest.raises(FactoryValidationError): + review_loop.record_verdict( + project, reviewer, "accept" if verdict == "accept" else "revise", findings, "s" + ) + assert _events(project, "review.verdict_recorded") == [] + + +def test_repeats_must_name_an_earlier_finding( + settings: Settings, clock: FixedClock, reviewer: Actor +) -> None: + project = _make(settings, clock, "brief") + runs = Runs() + conductor.begin_conductor(project, _plan(Tier.BRIEF, "frame")) + _step(project, runs) + _step(project, runs) + with pytest.raises(FactoryValidationError, match="no earlier finding"): + _revise(project, reviewer, _blocking(repeats="R1.F1")) + + +def test_a_reply_must_answer_every_blocking_finding( + settings: Settings, clock: FixedClock, reviewer: Actor, proposer: Actor +) -> None: + project = _make(settings, clock, "brief") + runs = Runs() + conductor.begin_conductor(project, _plan(Tier.BRIEF, "frame")) + _step(project, runs) + _step(project, runs) + _revise(project, reviewer, _blocking("a"), _blocking("b")) + _step(project, runs) # the proposer's revision + one = [Reply(finding_id="R1.F1", action="addressed", note="done")] + with pytest.raises(FactoryValidationError, match="unanswered: R1.F2"): + review_loop.record_reply(project, proposer, one) + stray = [*one, Reply(finding_id="R1.F2", action="declined", note="n"), + Reply(finding_id="R9.F1", action="declined", note="n")] # fmt: skip + with pytest.raises(FactoryValidationError, match="not findings of round 1"): + review_loop.record_reply(project, proposer, stray) + _reply_all(project, proposer) + with pytest.raises(FactoryValidationError, match="already answered"): + _reply_all(project, proposer) + + +def test_a_human_cannot_record_a_verdict( + settings: Settings, clock: FixedClock, human: Actor +) -> None: + project = _make(settings, clock, "brief") + with pytest.raises(FactoryValidationError, match="only an agent"): + review_loop.record_verdict(project, human, "accept", [], "s") + + +# ------------------------------------------------------------------------------- escapes + + +def _loop_to( + project: Project, runs: Runs, reviewer: Actor, proposer: Actor, rounds: int, + finding: Any = None, +) -> None: # fmt: skip + """Run `rounds` rounds that all say revise.""" + _step(project, runs) + for n in range(1, rounds + 1): + _step(project, runs) # reviewer + repeats = f"R{n - 1}.F1" if finding == "repeat" and n > 1 else None + _revise(project, reviewer, _blocking(f"round {n}", repeats=repeats)) + if n < rounds: + _step(project, runs) # proposer revision + _reply_all(project, proposer) + + +def test_the_loop_escapes_at_five_rounds_and_a_brief_goes_on( + settings: Settings, clock: FixedClock, reviewer: Actor, proposer: Actor +) -> None: + project = _make(settings, clock, "brief") + runs = Runs() + conductor.begin_conductor(project, _plan(Tier.BRIEF, "frame", "gather")) + _loop_to(project, runs, reviewer, proposer, review_loop.MAX_ROUNDS) + status = _step(project, runs) + assert status.state == "running" and runs.stages[-1] == "gather" + assert runs.stages.count("review-frame") == 5 + ended = _events(project, "conductor.review_ended")[0].payload + assert (ended["outcome"], ended["reason"], ended["open_findings"]) == ( + "escaped", "max-rounds", ["R5.F1"], + ) # fmt: skip + + +def test_no_progress_ends_the_loop( + settings: Settings, clock: FixedClock, reviewer: Actor, proposer: Actor +) -> None: + project = _make(settings, clock, "brief") + runs = Runs() + conductor.begin_conductor(project, _plan(Tier.BRIEF, "frame", "gather")) + _loop_to(project, runs, reviewer, proposer, 2, finding="repeat") + _step(project, runs) + assert runs.stages[-1] == "gather" + assert _events(project, "conductor.review_ended")[0].payload["reason"] == "no-progress" + + +def test_a_repeated_output_ends_the_loop( + settings: Settings, clock: FixedClock, reviewer: Actor, proposer: Actor, + _fingerprints: list[str], +) -> None: # fmt: skip + project = _make(settings, clock, "brief") + runs = Runs() + _fingerprints.extend(["a" * 64, "a" * 64]) # the revision changed nothing + conductor.begin_conductor(project, _plan(Tier.BRIEF, "frame", "gather")) + _loop_to(project, runs, reviewer, proposer, 2) + _step(project, runs) + assert _events(project, "conductor.review_ended")[0].payload["reason"] == "repeat" + + +def test_an_escaped_loop_pauses_a_pilot_until_a_human_releases_it( + settings: Settings, clock: FixedClock, reviewer: Actor, proposer: Actor, human: Actor +) -> None: + project = _make(settings, clock, "pilot") + runs = Runs() + plan = FPlan(Tier.PILOT, (FStage("frame"), FStage("understand")), None) + conductor.begin_conductor(project, plan) + _loop_to(project, runs, reviewer, proposer, review_loop.MAX_ROUNDS) + status = _step(project, runs) + assert status.state == "paused" and status.reason == "review-disputed" + assert runs.stages[-1] == "review-frame" + with pytest.raises(FactoryValidationError, match="only a human"): + review_loop.release(project, reviewer, "go") + review_loop.release(project, human, "the findings are noted") + status = _step(project, runs) + assert status.state == "running" and runs.stages[-1] == "understand" + + +def test_a_reviewer_without_a_verdict_pauses_and_retry_runs_it_again( + settings: Settings, clock: FixedClock, reviewer: Actor +) -> None: + project = _make(settings, clock, "brief") + runs = Runs() + conductor.begin_conductor(project, _plan(Tier.BRIEF, "frame", "gather")) + _step(project, runs) + _step(project, runs) # the reviewer runs and ends with no verdict + status = _step(project, runs) + assert status.state == "paused" and status.reason == "review-missing" + status = _step(project, runs, retry=True) + assert status.role == "verifier" and runs.stages.count("review-frame") == 2 + review_loop.record_verdict(project, reviewer, "accept", [], "s") + _step(project, runs) + assert runs.stages[-1] == "gather" + + +def test_loop_end_is_computed_from_the_verdicts_alone() -> None: + assert review_loop.loop_end([]) is None + + +# ------------------------------------------------------------------------ the output hash + + +def test_the_frame_fingerprint_is_stable(settings: Settings, clock: FixedClock) -> None: + project = _make(settings, clock, "brief") + first = _REAL_FINGERPRINT(project, "frame") + assert first == _REAL_FINGERPRINT(project, "frame") and len(first) == 64 + assert _REAL_FINGERPRINT(project, "write") != first diff --git a/plugin/skills/rf-frame-conducted/SKILL.md b/plugin/skills/rf-frame-conducted/SKILL.md new file mode 100644 index 00000000..84c9f3d0 --- /dev/null +++ b/plugin/skills/rf-frame-conducted/SKILL.md @@ -0,0 +1,44 @@ +--- +name: rf-frame-conducted +description: Use when the conductor starts the frame step of a project as a headless proposer run (stage frame): nobody answers, so the question, seeds and protocol are recorded from the researcher's stated goal alone. An interactive session with a researcher uses rf-frame. +stage: [frame] +--- + +# rf-frame-conducted + +The conducted form of `rf-frame`. The researcher stated a goal when the project was created; you +turn it into a recorded question, the seeds it names and the tier's protocol. Nobody answers during +the run: no interview, no quote-back, no suggestion set. A reviewer session checks your output +against the goal afterwards and may send it back with findings (the review loop). + +Pass `project`, `role` (`proposer`), `model` (your model id) and the bare skill name +`rf-frame-conducted` as `skill` to every mutating tool. + +## Procedure + +1. `project_status` (tier, rigour mode, stage) and `question_view`. The stated goal is the latest + `goal`. If no goal was stated, stop and say so. +2. If `review_view` lists a `revise` verdict for this step, this run is a revision: read every + finding, change only what the findings call for, then go to step 7. +3. Record the question with `question_record`: the goal verbatim as `raw_goal` (never edited), the + scheme that fits (`TDMBM` for method and ML reviews), and the slots filled from the goal's own + words. Anything the goal does not settle is an open slot with `resolve_in` naming the stage that + will settle it; never guess. Sub-questions (`SQ1`, ...) for each distinct thing the goal asks, + with ids. At least one non-goal (`NG01`) that passes the plausible-paper test: a paper a good + query would return that the goal does not want. State in `rationale` that the question was + recorded from the stated goal without an interview. +4. Seeds: add with `seed_add` only the works the goal names or lists. Never invent one. +5. Protocol: `protocol_from_template` with the criteria and the planned queries. The platform fills + the rest from the tier's template and refuses queries it does not allow (the sources it names, + at most its queries per source; `project_status` and the refusal say which). + - Criteria: `IN01`, ... and `EX01`, ... each with `statement`, an operational `rule` a screener + can apply to a title and abstract, `applies_at` (`title-abstract`, `full-text` or `either`) + and `parent` (the slot, non-goal or sub-question it serves). Cover every sub-question. + - Queries: one `keyword` query per source per allowed slot, each covering every family or + concept the goal names; a query that leaves one out is the first thing a reviewer flags. +6. Do not set the protocol ready, run a PRESS review, or record a decision: in a conducted brief or + deep review those do not bind, and readiness is a human's act. +7. In a revision, answer every blocking finding with `review_reply`: `addressed` with what you + changed, or `declined` with the reason (for example: the goal does not ask for it). +8. End with a short report: the question id, the seeds added, the protocol id and gaps, the + replies, and any refusal verbatim. diff --git a/plugin/skills/rf-review/SKILL.md b/plugin/skills/rf-review/SKILL.md new file mode 100644 index 00000000..3526aaf4 --- /dev/null +++ b/plugin/skills/rf-review/SKILL.md @@ -0,0 +1,38 @@ +--- +name: rf-review +description: Use when the conductor starts the reviewer of a review loop (stage review-frame or review-write): a separate session that checks one step's output against the stated goal and the sources, and records one verdict, accept or revise with findings. +stage: [cross] +--- + +# rf-review + +You are the reviewer of one round of a review loop. A proposer session produced the step's output; +you check it as someone who did not write it and record one verdict with `review_record`. If you +say `revise`, the proposer revises and answers your findings, and a new reviewer session (possibly +you again, without memory) checks the revision. The loop ends at `accept`, at the round cap, when a +round makes no progress, or when a revision repeats an earlier output: so make each finding count. + +Pass `project`, `role` (`verifier`), `model` (your model id) and the bare skill name `rf-review` as +`skill`. You change nothing but your verdict: no record, no gate, no draft. + +## Procedure + +1. `project_status`, then `review_view`: the earlier rounds' findings and the proposer's replies. +2. Read the output whole. + - Frame (`review-frame`): `question_view` (the goal and the question), `seed_list`, + `protocol_view`. Check that the question keeps the goal's meaning (nothing dropped, narrowed or + added); that every family, concept or setting the goal names reaches a sub-question, a + criterion and the queries; that the criteria are operational on a title and abstract; that the + non-goals are plausible papers; that the seeds are only those the goal names. + - Write (`review-write`): `draft_list`, `draft_render`, `claims_digest`, `document_read`. Check + that each evidence sentence is supported by its cited passage (`chat_verify` for a quote), that + no number is typed outside the report, that the note answers the question it states, and that + what was skipped is said. +3. Findings. Each one: `severity` `blocking` (the output is wrong, unsupported or misses what the + goal asks) or `minor` (could be better); `target` (the slot, criterion, query, section or + sentence); `text` (what is wrong and what would fix it, concretely). A finding that restates an + earlier one still open names it in `repeats`. Do not re-raise a finding the proposer declined + with a sound reason; do not raise taste as blocking. +4. Verdict with `review_record`: `accept` when no blocking finding is left (minor ones may be + listed), else `revise`. One short `summary`: what you checked and what holds. +5. End with a short report: the verdict, the findings by id, and any refusal verbatim. From 502a0a57833808fe79683f6925d1a4ffd643f09d Mon Sep 17 00:00:00 2001 From: Alex Date: Sat, 28 Nov 2026 20:52:33 +0200 Subject: [PATCH 02/16] feat(conductor): review loops on frame and write, a conducted frame, tier template tool Plan docs/plans/2026-11-28-review-loops.md. Found by the first live tier run (living-syllabus shakedown la-brief, 2026-11-28). - Review loop: at supervised/autonomous, frame and write alternate an Opus proposer and an Opus reviewer session (stages review-frame, review-write, skill rf-review). The reviewer records one verdict per round (review_record: accept, or revise with blocking/minor findings); the proposer revises and answers each blocking finding (review_reply). Rounds, finding ids and output fingerprints are computed. Escapes: accept, 5 rounds, no progress, repeated output, budget. An escape with open findings continues at brief/deep (listed in the level statement) and pauses elsewhere (review-disputed) until a human runs 'factory conductor release-review'. A reviewer with no verdict pauses (review-missing). Events review.verdict_recorded, review.reply_recorded, review.released, conductor.review_ended; no table. - Conducted frame: skill rf-frame-conducted (no interview; goal verbatim, seeds only as named), new tool protocol_from_template (tier template, its source and per-source caps enforced, creator as reviewer of record, draft only). - Brief and deep: the frame step's protocol gates do not bind the conductor (TIER_UNBOUND_GATES), as rf-brief and the plan state. - Prompt: a refused read is noted and the run goes on. - STAGE_KEY_RE accepts the reviewer stages (a live start would fail). - Backlog IDEA-145 to 147; MAP regenerated. Co-Authored-By: Claude Opus 5.5 --- docs/MAP.md | 53 +++++++----- docs/backlog.md | 24 ++++++ platform/src/factory/model/runner.py | 2 +- platform/src/factory/services/conductor.py | 10 +++ .../src/factory/services/level_statement.py | 3 + platform/src/factory/services/review_loop.py | 48 +++++++++-- platform/src/factory/services/runner.py | 42 +++++----- platform/tests/test_conductor.py | 34 ++++++-- platform/tests/test_review_loop.py | 20 ++++- platform/tests/test_tier_protocol.py | 84 +++++++++++++++++++ platform/tests/test_tiers_walking_skeleton.py | 12 +-- plugin/skills/rf-frame-conducted/SKILL.md | 3 +- 12 files changed, 270 insertions(+), 65 deletions(-) create mode 100644 platform/tests/test_tier_protocol.py diff --git a/docs/MAP.md b/docs/MAP.md index a87c7b6e..1fbc6697 100644 --- a/docs/MAP.md +++ b/docs/MAP.md @@ -2,7 +2,7 @@ -Generated at commit `83dff7ac` · projection version `96` · 52 stage modules · 237 event types · 235 index tables · 350 service modules · 219 MCP tools · 414 CLI commands · 38 skills. +Generated at commit `b57a7078` · projection version `96` · 52 stage modules · 241 event types · 235 index tables · 352 service modules · 223 MCP tools · 415 CLI commands · 40 skills. Read [ARCHITECTURE.md](ARCHITECTURE.md) first. This file answers *where*: for each stage module, the events, models, index files, tables, task kinds, gates and checks it owns, and the services that name its events; then every MCP tool, CLI command, service and skill with what it reaches. Links are found by name (see the script's docstring), so a missing link means the code does not name the thing, not that no relation exists. Paths are relative to `platform/src/factory/` unless they start with `plugin/`. @@ -71,7 +71,7 @@ Declared in `services/modules/.py` against the contract in `modules/contra | [briefing](#module-briefing) | builder | — → report | 1 | 1 | 0 | 0 | 1 | | [manuscripts](#module-manuscripts) | proposal | — → — | 8 | 8 | 1 | 2 | 2 | | [feed](#module-feed) | retrieval | — → — | 6 | 6 | 0 | 0 | 1 | -| [runner](#module-runner) | retrieval | — → — | 9 | 2 | 0 | 0 | 0 | +| [runner](#module-runner) | retrieval | — → — | 13 | 2 | 0 | 0 | 0 | ### Module: core @@ -98,7 +98,7 @@ Declaration: `services/modules/core.py` · kind `core` - **Tables:** `budgets` (budgets.py), `event_refs` (projection.py), `events` (projection.py), `gate_audit_items` (gates.py), `gate_audits` (gates.py), `ledger_confirmations` (ledger.py), `member_events` (members.py), `members` (members.py), `meta` (projection.py), `project` (project.py), `project_hosts` (project.py), `project_visibility` (project.py), `request_starts` (budgets.py), `reviews` (reviews.py), `source_requests` (budgets.py), `sync_state` (projection.py), `task_claims` (budgets.py), `task_usage` (budgets.py), `tasks` (tasks.py) - **Protocol sections:** `gate_policies` - **Check codes:** `broken-link`, `count-source-exploratory`, `missing-provenance`, `gate-below-policy`, `gate-audit-missing`, `gate-audit-error-high`, `gate-audit-unlabelled`, `gate-policy-below-pilot-preset`, `gate-policy-below-systematic-preset`, `host-mismatch`, `host-mismatch-unchecked`, `mcp-code-lines-differ`, `mcp-config-unresolved`, `member-event-unfolded`, `future-dated-event`, `member-missing-reviewer-of-record`, `review-open`, `review-stale`, `ledger-unconfirmed`, `budget-exhausted`, `human-act-relayed` -- **Services naming its events:** `services/access.py`, `services/briefing.py`, `services/budgets.py`, `services/decision_check.py`, `services/draft_verify.py`, `services/drafts.py`, `services/extraction.py`, `services/gate_trust.py`, `services/gates.py`, `services/hosting.py`, `services/human_channel.py`, `services/interpretations.py`, `services/level_statement.py`, `services/manuscript_verify.py`, `services/members.py`, `services/miner_independence.py`, `services/project.py`, `services/reviews.py`, `services/tasks.py` +- **Services naming its events:** `services/access.py`, `services/briefing.py`, `services/budgets.py`, `services/decision_check.py`, `services/draft_verify.py`, `services/drafts.py`, `services/extraction.py`, `services/gate_trust.py`, `services/gates.py`, `services/hosting.py`, `services/human_channel.py`, `services/interpretations.py`, `services/level_statement.py`, `services/manuscript_verify.py`, `services/members.py`, `services/miner_independence.py`, `services/project.py`, `services/reviews.py`, `services/tasks.py`, `services/tier_protocol.py` ### Module: scoping @@ -880,10 +880,14 @@ Declaration: `services/modules/runner.py` · kind `retrieval` | `conductor.step_finished` | `model.conductor.ConductorStepFinished` | not folded | | `conductor.paused` | `model.conductor.ConductorPaused` | not folded | | `conductor.finished` | `model.conductor.ConductorFinished` | not folded | +| `conductor.review_ended` | `model.conductor.ConductorReviewEnded` | not folded | +| `review.verdict_recorded` | `model.review_loop.ReviewVerdictRecorded` | not folded | +| `review.reply_recorded` | `model.review_loop.ReviewReplyRecorded` | not folded | +| `review.released` | `model.review_loop.ReviewReleased` | not folded | - **Tables:** `runner_runs` (runner.py), `runner_pipelines` (runner.py) -- **Note:** Headless runner (plan feed-hub H5, decision 119): the platform starts the installed `claude` executable for one stage; both events are system acts, and every judgement is written through MCP with the agent's provenance. The `conductor.*` events (plan tiers-and-autonomy C8) are system acts of the lifecycle conductor, derived from the log without a table. -- **Services naming its events:** `services/conductor.py`, `services/pipeline.py`, `services/runner.py` +- **Note:** Headless runner (plan feed-hub H5, decision 119): the platform starts the installed `claude` executable for one stage; both events are system acts, and every judgement is written through MCP with the agent's provenance. The `conductor.*` events (plan tiers-and-autonomy C8) are system acts of the lifecycle conductor, derived from the log without a table. The `review.*` events are the agent acts of its review loop (plan 2026-11-28-review-loops), also without a table. +- **Services naming its events:** `services/conductor.py`, `services/pipeline.py`, `services/review_loop.py`, `services/runner.py` ## MCP tools @@ -911,9 +915,9 @@ All in `mcp/server.py`, nested in `build_server`; conventions in `mcp/convention | `chat_request_next` | `chat_requests` | rf-chat | Serve the oldest open chat request (a spar or an ask the researcher ordered) of this headless run's kind, and mark it taken by the run. | | `chat_request_view` | `chat_requests` | — | One chat request with its derived state (open, taken, done, failed) and the sheet or answer that answers it. | | `chat_sections` | `chat_read`, `work_ref` | rf-chat, rf-spar-v2 | The section outline of a work's pinned conversion, in document order: anchor, heading, depth, and the paragraphs and words directly in each… | -| `chat_verify` | `chat_read`, `work_ref` | rf-acquire, rf-brief, rf-chat, rf-deep, rf-hypothesis-engine, rf-spar-v2 | Verify quotes before citing them. | -| `check` | `agent_view` | rf-acquire, rf-appraise, rf-brief, rf-conductor, rf-consolidate, rf-contributions, rf-deep, rf-develop, rf-extract, rf-frame, rf-hypothesis-engine, rf-intuition, rf-lineage, rf-miner-suggest, rf-protocol, rf-references, rf-run, rf-screen, rf-search, rf-spar-v2, rf-synthesize, rf-technique-bounce, rf-verify | Gaps of the project: broken links, missing provenance, unexplained shortfalls, seed, protocol, screening, audit and chase gaps. | -| `claims_digest` | `claims_digest` | rf-brief, rf-chat, rf-conductor, rf-deep, rf-hypothesis-engine, rf-spar-v2 | The claims digest of a selection (spec as in `selection_resolve`): every paper of the selection in work-id order with a stable code P01, P0… | +| `chat_verify` | `chat_read`, `work_ref` | rf-acquire, rf-brief, rf-chat, rf-deep, rf-hypothesis-engine, rf-review, rf-spar-v2 | Verify quotes before citing them. | +| `check` | `agent_view` | rf-acquire, rf-appraise, rf-brief, rf-conductor, rf-consolidate, rf-contributions, rf-deep, rf-develop, rf-extract, rf-frame, rf-hypothesis-engine, rf-intuition, rf-lineage, rf-miner-suggest, rf-protocol, rf-references, rf-review, rf-run, rf-screen, rf-search, rf-spar-v2, rf-synthesize, rf-technique-bounce, rf-verify | Gaps of the project: broken links, missing provenance, unexplained shortfalls, seed, protocol, screening, audit and chase gaps. | +| `claims_digest` | `claims_digest` | rf-brief, rf-chat, rf-conductor, rf-deep, rf-hypothesis-engine, rf-review, rf-spar-v2 | The claims digest of a selection (spec as in `selection_resolve`): every paper of the selection in work-id order with a stable code P01, P0… | | `concept_link` | `agent_view`, `concepts` | rf-intuition | Propose that a paper, a confirmed idea or a concept (`from_node`) uses `concept_id`. | | `concept_list` | `concepts` | rf-run | Background concepts by id, one page at a time, each with `class` and `label` (never evidence), text, source, review state and flags. | | `concept_propose` | `agent_view`, `concepts` | rf-intuition | Propose a background concept named `concept_name`: an outside idea a paper relies on, with an optional `text` (at most 600 characters), a `… | @@ -935,13 +939,13 @@ All in `mcp/server.py`, nested in `build_server`; conventions in `mcp/convention | `dedup_run` | `dedup` | rf-brief, rf-deep, rf-references, rf-run, rf-search, rf-search-run | Find and record duplicate works; merges are reversible. | | `develop_render` | `develop_render` | rf-develop, rf-frame, rf-probe, rf-protocol, rf-run | One level of the develop stage (goal, questions, plan, seeds, probe, protocol) rendered as a formal Markdown document from its decisions: t… | | `digest_get` | `digest` | rf-living | The computed digest of the project since `since` (`last`: the last recorded digest; an event id; null: the start): new candidates with the… | -| `document_read` | `document_read` | rf-acquire, rf-appraise, rf-cards, rf-chat, rf-conductor, rf-contributions, rf-extract, rf-hypothesis-engine, rf-intuition, rf-mine, rf-references, rf-screen, rf-spar-v2, rf-taxonomy, rf-technique-bounce, rf-verify | One page of a promoted work's converted document: its segments in document order, each with its anchor, kind and text (cut and flagged when… | +| `document_read` | `document_read` | rf-acquire, rf-appraise, rf-cards, rf-chat, rf-conductor, rf-contributions, rf-extract, rf-hypothesis-engine, rf-intuition, rf-mine, rf-references, rf-review, rf-screen, rf-spar-v2, rf-taxonomy, rf-technique-bounce, rf-verify | One page of a promoted work's converted document: its segments in document order, each with its anchor, kind and text (cut and flagged when… | | `document_status` | `document_convert` | rf-acquire, rf-run | The conversion state of each live document of a promoted work, one page at a time: converted or not, the converter and version, anchor coun… | | `draft_create` | `agent_view`, `drafts`, `outline` | rf-write | Create a draft pinned to the outline of a scope (see `writing_outline`). | -| `draft_list` | `drafts` | rf-run | Drafts by id, one page at a time: title, kind, pinned outline, sections and the count of live sentences. | +| `draft_list` | `drafts` | rf-review, rf-run | Drafts by id, one page at a time: title, kind, pinned outline, sections and the count of live sentences. | | `draft_next` | `agent_view`, `drafts` | rf-verify, rf-write | The next section of the draft that has no sentence yet (or the named one) as a task: its `content` lists the section's eligible supports (`… | | `draft_release` | `agent_view`, `draft_release` | rf-write | Release the draft through the gate `writing.release`: in exploratory mode any non-empty draft; in pilot mode once the audit the researcher… | -| `draft_render` | `agent_view`, `drafts` | rf-verify | The draft as Markdown text. | +| `draft_render` | `agent_view`, `drafts` | rf-review, rf-verify | The draft as Markdown text. | | `draft_reorder` | `agent_view`, `drafts` | rf-write | Set the order of a section's sentences: `order` lists exactly its live sentences, once each. | | `draft_repin` | `agent_view`, `drafts`, `outline` | rf-write | Pin a draft to a fresh outline, of the same scope unless one is named (see `writing_outline`). | | `draft_status` | `agent_view`, `draft_audit`, `drafts` | rf-run, rf-verify, rf-write | The draft's live sentences in order, each with its class, supports, flags the platform computed (citation-mismatch, quantifier-without-stat… | @@ -1025,14 +1029,15 @@ All in `mcp/server.py`, nested in `build_server`; conventions in `mcp/convention | `paper_profiles` | `paper_profile`, `work_ref` | rf-spar-v2 | One compact profile per work: what every miner listed in the protocol found in it (final rows, else pass A rows marked `pass-a-only`), with… | | `probe_run` | `probe` | rf-develop, rf-probe, rf-run, rf-search-run | Measure queries against the development seeds and the negatives: recall and negative hits per query and per source. | | `progress_status` | `progress` | — | The long operations running now or finished in the last ten minutes (ranking, search paging, snowball and probe queries, deduplication): do… | -| `project_status` | `agent_view` | rf-acquire, rf-brief, rf-conductor, rf-contributions, rf-deep, rf-extract, rf-frame, rf-miner-suggest, rf-run, rf-screen, rf-search, rf-search-run | Report a project's rigor mode, `tier` (null: not declared), `autonomy_level`, event counts, task queue state, derived `stage` (null to a se… | +| `project_status` | `agent_view` | rf-acquire, rf-brief, rf-conductor, rf-contributions, rf-deep, rf-extract, rf-frame, rf-frame-conducted, rf-miner-suggest, rf-review, rf-run, rf-screen, rf-search, rf-search-run | Report a project's rigor mode, `tier` (null: not declared), `autonomy_level`, event counts, task queue state, derived `stage` (null to a se… | | `protocol_amend` | `protocol` | rf-acquire, rf-curate, rf-miner-suggest, rf-protocol, rf-run, rf-search-run | Amend the ready protocol. | | `protocol_deviation` | `protocol` | rf-acquire, rf-protocol, rf-search-run | Record a deviation from the current protocol. | +| `protocol_from_template` | — | rf-frame-conducted | Record the protocol of the project's tier from its template: you give the criteria and the planned queries, the platform fills sources, scr… | | `protocol_press_review` | `protocol` | rf-deep, rf-protocol | Record an agent's PRESS review of the current protocol; a human confirms it next. | | `protocol_record` | `protocol` | rf-brief, rf-deep, rf-develop, rf-miner-suggest, rf-protocol, rf-run | Record the protocol as a draft, or as ready when `ready` is true. | -| `protocol_view` | `protocol` | rf-run, rf-search-run | The current protocol: its id, status, PRESS state, whole spec and amendments, so the spec can be read and passed back to `protocol_amend`. | -| `question_record` | `question` | rf-brief, rf-develop, rf-frame, rf-run | Record the question. | -| `question_view` | `question` | rf-miner-suggest, rf-run, rf-search-run | The current question: its id, spec and the latest raw goal, verbatim. | +| `protocol_view` | `protocol` | rf-review, rf-run, rf-search-run | The current protocol: its id, status, PRESS state, whole spec and amendments, so the spec can be read and passed back to `protocol_amend`. | +| `question_record` | `question` | rf-brief, rf-develop, rf-frame, rf-frame-conducted, rf-run | Record the question. | +| `question_view` | `question` | rf-frame-conducted, rf-miner-suggest, rf-review, rf-run, rf-search-run | The current question: its id, spec and the latest raw goal, verbatim. | | `ranking_compute` | `ranking`, `ranking_model` | rf-brief, rf-deep, rf-protocol | Rank the records still to be screened by similarity to the development seeds, with a local embedding model (decision 116). | | `reference_decide` | `reference_resolve` | rf-references | Propose or record a decision on an unconfirmed or ambiguous reference link. | | `reference_layer_next` | `reference_layers` | rf-reference-layers | Serve the next cited items to assign a relevance layer at `stage`, under the researcher's current scheme (its version and each layer's id,… | @@ -1056,7 +1061,10 @@ All in `mcp/server.py`, nested in `build_server`; conventions in `mcp/convention | `report_search` | `agent_view` | rf-brief, rf-deep, rf-run, rf-search-run | The PRISMA-S search report alone: each registered query and what it retrieved. | | `review_decide` | `reviews` | — | The human's decision on a review request, relayed: `approve`, `reject` or `withdraw`. | | `review_list` | `reviews` | — | Review requests in filing order, or those in `state` (open, approved, rejected, withdrawn, consumed, stale). | +| `review_record` | — | rf-review | Record your verdict on the step's output, once per review run: `accept` (no blocking finding) or `revise` (at least one). | +| `review_reply` | — | rf-frame-conducted | Answer the findings of the last `revise` verdict of your step, after revising the output: one reply per blocking finding (`finding_id`, `ac… | | `review_request` | `reviews` | rf-protocol | File a review request for what you may not apply alone. | +| `review_view` | — | rf-frame-conducted, rf-review | The review loop of the conductor's current step (frame or write): the verdicts so far, each with its numbered findings, the proposer's repl… | | `screen_agreement` | `agreement` | rf-deep, rf-screen, rf-search | The agreement of the two passes at `stage` (`title-abstract` or `full-text`): κ, per-criterion κ, disagreements and cannot-assess rates. | | `screen_check_draw` | `screening_check`, `search` | rf-screen | Draw records for the human to check the screener (H2). | | `screen_check_example` | `screening_check` | rf-screen | Make a disagreement of a tuning batch an example of `criterion` (a protocol amendment). | @@ -1067,8 +1075,8 @@ All in `mcp/server.py`, nested in `build_server`; conventions in `mcp/convention | `search_chase` | `chase` | rf-search | Chase citations from the included works: the platform builds the queries. | | `search_run` | `budgets`, `protocol`, `search` | rf-brief, rf-deep, rf-protocol, rf-references, rf-run, rf-search, rf-search-run | Run a literature query against OpenAlex or arXiv exhaustively; every raw page is archived and counts are recorded. | | `search_slice` | `budgets`, `pubmed_slices` | rf-run, rf-search-run | Split a capped PubMed query (partial, note `esearch-cap`) by publication date. | -| `seed_add` | `results`, `seeds` | rf-brief, rf-develop, rf-probe, rf-run, rf-search-run | Add seeds by identifier (doi, arxiv, openalex or pmid) and look each one up. | -| `seed_list` | `seeds` | rf-probe, rf-search-run | The seeds an agent may use, in id order, one page at a time. | +| `seed_add` | `results`, `seeds` | rf-brief, rf-develop, rf-frame-conducted, rf-probe, rf-run, rf-search-run | Add seeds by identifier (doi, arxiv, openalex or pmid) and look each one up. | +| `seed_list` | `seeds` | rf-probe, rf-review, rf-search-run | The seeds an agent may use, in id order, one page at a time. | | `selection_resolve` | `selection` | rf-chat, rf-hypothesis-engine, rf-spar-v2 | Resolve a selection of papers for the chat: the works of the full-text-included population, restricted to `layers` when given (layer ids of… | | `sheet_argue` | `sheets` | rf-chat, rf-spar-v2 | Record arguments of ONE section of a sheet, all or none. | | `sheet_check` | `spar_v2` | rf-spar-v2 | Record the critic's checks of arguments of this run's sheet (all or none). | @@ -1175,6 +1183,7 @@ Defined in `cli/main.py` (typer); rendering in `cli/render.py` and siblings. | `factory conclusions retire` | `access`, `access_log`, `conclusions`, `human_pass` | Withdraw a conclusion from evaluation (human act); the registration stays in the log. | | `factory conclusions status` | `access`, `access_log`, `conclusions`, `human_pass` | Each active conclusion with your statement and its computed state since the last snapshot. | | `factory conductor advance` | `access`, `access_log`, `conductor`, `human_pass` | Take the conductor one step: close its finished run, check the stop rules, start at most one role run. | +| `factory conductor release-review` | `access`, `access_log`, `human_pass` | Let the conductor go on past a review loop that ended with blocking findings open (pause `review-disputed`); the findings stay open and lab… | | `factory conductor start` | `access`, `access_log`, `conductor`, `human_pass`, `project` | Begin a conductor run of the plan of the project's tier (refused for a legacy project). | | `factory conductor status` | `access`, `access_log`, `conductor`, `human_pass` | Where the conductor is and why it stopped (read-only). | | `factory consolidation complete` | `consolidation` | Complete a pass whose every cluster is decided; the due counts start again. | @@ -1538,8 +1547,8 @@ Defined in `cli/main.py` (typer); rendering in `cli/render.py` and siblings. | Service | Purpose | Modules | MCP tools | CLI commands | | --- | --- | --- | --- | --- | -| `access` | Who may do what (slice 5 rulings 9 and 10; the spec's permissions table). | core | — | `factory activity`, `factory answers export`, `factory answers list`, `factory answers rate`, `factory answers show`, `factory appraisal agreement`, `factory appraisal audit-label`, `factory appraisal audit-report`, `factory appraisal audit-sample`, `factory appraisal judge`, `factory appraisal resolve`, `factory appraisal sheet`, `factory appraisal status`, `factory audit label`, `factory audit report`, `factory audit sample`, `factory bench level`, `factory benchmark-ledger`, `factory briefing`, `factory budget set`, `factory calibrate draw`, `factory calibrate label`, `factory cards assert`, `factory cards confirm`, `factory cards import`, `factory cards list`, `factory cards reject`, `factory cards show`, `factory chat advance`, `factory chat precision`, `factory chat request ask`, `factory chat request spar`, `factory chat requests`, `factory check`, `factory concept-links confirm`, `factory concept-links list`, `factory concept-links reject`, `factory concepts approve`, `factory concepts define`, `factory concepts history`, `factory concepts list`, `factory concepts merge`, `factory concepts reject-source`, `factory concepts review`, `factory concepts show`, `factory concepts source`, `factory concepts unmerge`, `factory conclusions diff`, `factory conclusions register`, `factory conclusions retire`, `factory conclusions status`, `factory conductor advance`, `factory conductor start`, `factory conductor status`, `factory contradictions confirm`, `factory contradictions list`, `factory contradictions reject`, `factory contributions agreement`, `factory contributions audit label`, `factory contributions audit report`, `factory contributions audit sample`, `factory contributions list`, `factory contributions pairs`, `factory contributions resolve`, `factory contributions status`, `factory curation decide`, `factory curation lessons`, `factory curation list`, `factory dashboard export`, `factory dashboard serve`, `factory decide list`, `factory decide select`, `factory decide show`, `factory dedup list`, `factory dedup pair`, `factory dedup pairs`, `factory dedup revert`, `factory dedup run`, `factory develop render`, `factory digest`, `factory directions close`, `factory document convert`, `factory document coverage`, `factory document read`, `factory document reanchor`, `factory document status`, `factory draft audit`, `factory draft create`, `factory draft label`, `factory draft list`, `factory draft release`, `factory draft render`, `factory draft reorder`, `factory draft repin`, `factory draft show`, `factory draft status`, `factory draft verify`, `factory draft withdraw`, `factory draft write`, `factory experiments accept-baseline`, `factory experiments amend`, `factory experiments deviation`, `factory experiments evaluate-baselines`, `factory experiments freeze`, `factory experiments list`, `factory experiments show`, `factory experiments unlock`, `factory export bibtex`, `factory export crate`, `factory export csl`, `factory export nanopub`, `factory export prisma`, `factory export works`, `factory extract agreement`, `factory extract audit-label`, `factory extract audit-report`, `factory extract audit-sample`, `factory extract resolve`, `factory extract status`, `factory feed run`, `factory files list`, `factory files register`, `factory files status`, `factory finders conflicts`, `factory finders gaps`, `factory fulltext fetch`, `factory fulltext import`, `factory fulltext resolve`, `factory fulltext restore`, `factory fulltext status`, `factory gate audit label`, `factory gate audit report`, `factory gate audit sample`, `factory gates`, `factory graph build`, `factory graph export`, `factory graph query`, `factory graph status`, `factory grey capture`, `factory grey contact`, `factory hub build`, `factory hub facets set`, `factory hub facets show`, `factory hypotheses abandon`, `factory hypotheses conclude`, `factory hypotheses evaluate`, `factory hypotheses list`, `factory hypotheses register`, `factory hypotheses show`, `factory ideas candidates`, `factory ideas confirm`, `factory ideas define`, `factory ideas list`, `factory ideas merge`, `factory ideas reject`, `factory ideas unmerge`, `factory import admit`, `factory import attach`, `factory import bib`, `factory import confirm`, `factory import coverage`, `factory import csl`, `factory import describe`, `factory import list`, `factory import pdfs`, `factory import reject`, `factory import resolve`, `factory import ris`, `factory import show`, `factory inbox add`, `factory inbox list`, `factory inbox prioritise`, `factory inbox resolve`, `factory inbox withdraw`, `factory interpretations history`, `factory interpretations list`, `factory interpretations review`, `factory interpretations show`, `factory interpretations supersede`, `factory interpretations write`, `factory layers move`, `factory leads candidates`, `factory leads discard`, `factory leads list`, `factory leads park`, `factory leads promote`, `factory leads queue`, `factory leads stats`, `factory ledger`, `factory library adopt`, `factory library confirm-source`, `factory library consolidate`, `factory library push`, `factory living prisma-update`, `factory living snapshot`, `factory manuscript add`, `factory manuscript audit`, `factory manuscript report`, `factory manuscript resolve`, `factory manuscript status`, `factory match`, `factory member grant`, `factory member list`, `factory member revoke`, `factory mine agreement`, `factory mine audit label`, `factory mine audit report`, `factory mine audit sample`, `factory mine import`, `factory mine request`, `factory mine resolve`, `factory mine status`, `factory miner add`, `factory miner admit`, `factory miner adopt`, `factory miner calibrate draw`, `factory miner calibrate label`, `factory miner calibrate report`, `factory miner list`, `factory miner register`, `factory miner reopen`, `factory miner retire`, `factory models cutoff`, `factory notices assess`, `factory notices check`, `factory notices list`, `factory outline`, `factory pack`, `factory pages brief`, `factory pages list`, `factory pages record`, `factory pages show`, `factory passages embed`, `factory passages status`, `factory performance`, `factory project host`, `factory project visibility`, `factory protocol confirm-press`, `factory protocol show`, `factory question show`, `factory rank compute`, `factory rank show`, `factory rebuild`, `factory references decide`, `factory references extract`, `factory references layers label`, `factory references layers sample`, `factory references layers status`, `factory references list`, `factory references re-resolve`, `factory references scheme record`, `factory references status`, `factory regions add`, `factory regions adopt`, `factory regions define`, `factory regions diff`, `factory regions export`, `factory regions link`, `factory regions links`, `factory regions list`, `factory regions proposals`, `factory regions reject`, `factory regions remove`, `factory regions review`, `factory regions revise`, `factory regions show`, `factory regions snapshot`, `factory registry`, `factory relations confirm`, `factory relations list`, `factory relations reject`, `factory report discovery`, `factory report evidence`, `factory report flow`, `factory report flow-skipped`, `factory report flow-trail`, `factory report flow-works`, `factory report methods`, `factory report prisma`, `factory report search`, `factory resume`, `factory review list`, `factory review show`, `factory runs adopt`, `factory runs list`, `factory runs record`, `factory screen disagreements`, `factory screen join`, `factory screen next`, `factory screen record`, `factory screen resolve`, `factory screen-check band`, `factory screen-check example`, `factory screen-check label`, `factory screen-check list`, `factory screen-check measure`, `factory screen-check report`, `factory screen-check tuning`, `factory search chase`, `factory search slice`, `factory seeds admit`, `factory seeds explain`, `factory seeds split`, `factory sheets balance`, `factory sheets diff`, `factory sheets export`, `factory sheets list`, `factory sheets rate`, `factory sheets show`, `factory site build`, `factory site serve`, `factory site status`, `factory snowball compare`, `factory snowball core list`, `factory snowball core mark`, `factory snowball core unmark`, `factory snowball plan`, `factory snowball run`, `factory status`, `factory suggest`, `factory taxonomy agreement`, `factory taxonomy coverage`, `factory taxonomy derive`, `factory taxonomy diff`, `factory taxonomy list`, `factory taxonomy proposals`, `factory taxonomy register`, `factory taxonomy view`, `factory technique candidates`, `factory technique challenges`, `factory technique combinations`, `factory technique gaps`, `factory technique landscape`, `factory technique neighbors`, `factory technique show`, `factory token issue`, `factory token list`, `factory token revoke`, `factory tour`, `factory trace`, `factory user add`, `factory user deactivate`, `factory user link`, `factory user list`, `factory user reactivate`, `factory versions list`, `factory versions prefer`, `factory view coverage`, `factory view horizon`, `factory view onion`, `factory view timeline`, `factory vocabulary approve`, `factory vocabulary list`, `factory vocabulary merge`, `factory vocabulary reject`, `factory vocabulary unmerge`, `factory watch plan`, `factory watch run`, `factory watch status`, `factory workspace` | -| `access_log` | The server access log (slice 5 ruling 12; plan ruling 5). | — | — | `factory activity`, `factory answers export`, `factory answers list`, `factory answers rate`, `factory answers show`, `factory appraisal agreement`, `factory appraisal audit-label`, `factory appraisal audit-report`, `factory appraisal audit-sample`, `factory appraisal judge`, `factory appraisal resolve`, `factory appraisal sheet`, `factory appraisal status`, `factory audit label`, `factory audit report`, `factory audit sample`, `factory bench level`, `factory benchmark-ledger`, `factory briefing`, `factory budget set`, `factory calibrate draw`, `factory calibrate label`, `factory cards assert`, `factory cards confirm`, `factory cards import`, `factory cards list`, `factory cards reject`, `factory cards show`, `factory chat advance`, `factory chat precision`, `factory chat request ask`, `factory chat request spar`, `factory chat requests`, `factory check`, `factory concept-links confirm`, `factory concept-links list`, `factory concept-links reject`, `factory concepts approve`, `factory concepts define`, `factory concepts history`, `factory concepts list`, `factory concepts merge`, `factory concepts reject-source`, `factory concepts review`, `factory concepts show`, `factory concepts source`, `factory concepts unmerge`, `factory conclusions diff`, `factory conclusions register`, `factory conclusions retire`, `factory conclusions status`, `factory conductor advance`, `factory conductor start`, `factory conductor status`, `factory contradictions confirm`, `factory contradictions list`, `factory contradictions reject`, `factory contributions agreement`, `factory contributions audit label`, `factory contributions audit report`, `factory contributions audit sample`, `factory contributions list`, `factory contributions pairs`, `factory contributions resolve`, `factory contributions status`, `factory curation decide`, `factory curation lessons`, `factory curation list`, `factory dashboard export`, `factory dashboard serve`, `factory decide list`, `factory decide select`, `factory decide show`, `factory dedup list`, `factory dedup pair`, `factory dedup pairs`, `factory dedup revert`, `factory dedup run`, `factory develop render`, `factory digest`, `factory directions close`, `factory document convert`, `factory document coverage`, `factory document read`, `factory document reanchor`, `factory document status`, `factory draft audit`, `factory draft create`, `factory draft label`, `factory draft list`, `factory draft release`, `factory draft render`, `factory draft reorder`, `factory draft repin`, `factory draft show`, `factory draft status`, `factory draft verify`, `factory draft withdraw`, `factory draft write`, `factory experiments accept-baseline`, `factory experiments amend`, `factory experiments deviation`, `factory experiments evaluate-baselines`, `factory experiments freeze`, `factory experiments list`, `factory experiments show`, `factory experiments unlock`, `factory export bibtex`, `factory export crate`, `factory export csl`, `factory export nanopub`, `factory export prisma`, `factory export works`, `factory extract agreement`, `factory extract audit-label`, `factory extract audit-report`, `factory extract audit-sample`, `factory extract resolve`, `factory extract status`, `factory files list`, `factory files register`, `factory files status`, `factory finders conflicts`, `factory finders gaps`, `factory fulltext fetch`, `factory fulltext import`, `factory fulltext resolve`, `factory fulltext restore`, `factory fulltext status`, `factory gate audit label`, `factory gate audit report`, `factory gate audit sample`, `factory gates`, `factory graph build`, `factory graph export`, `factory graph query`, `factory graph status`, `factory grey capture`, `factory grey contact`, `factory hub build`, `factory hub facets set`, `factory hub facets show`, `factory hypotheses abandon`, `factory hypotheses conclude`, `factory hypotheses evaluate`, `factory hypotheses list`, `factory hypotheses register`, `factory hypotheses show`, `factory ideas candidates`, `factory ideas confirm`, `factory ideas define`, `factory ideas list`, `factory ideas merge`, `factory ideas reject`, `factory ideas unmerge`, `factory import admit`, `factory import attach`, `factory import bib`, `factory import confirm`, `factory import coverage`, `factory import csl`, `factory import describe`, `factory import list`, `factory import pdfs`, `factory import reject`, `factory import resolve`, `factory import ris`, `factory import show`, `factory inbox add`, `factory inbox list`, `factory inbox prioritise`, `factory inbox resolve`, `factory inbox withdraw`, `factory interpretations history`, `factory interpretations list`, `factory interpretations review`, `factory interpretations show`, `factory interpretations supersede`, `factory interpretations write`, `factory layers move`, `factory leads candidates`, `factory leads discard`, `factory leads list`, `factory leads park`, `factory leads promote`, `factory leads queue`, `factory leads stats`, `factory ledger`, `factory library adopt`, `factory library confirm-source`, `factory library consolidate`, `factory library push`, `factory living prisma-update`, `factory living snapshot`, `factory manuscript add`, `factory manuscript audit`, `factory manuscript report`, `factory manuscript resolve`, `factory manuscript status`, `factory match`, `factory member grant`, `factory member list`, `factory member revoke`, `factory mine agreement`, `factory mine audit label`, `factory mine audit report`, `factory mine audit sample`, `factory mine import`, `factory mine request`, `factory mine resolve`, `factory mine status`, `factory miner add`, `factory miner admit`, `factory miner adopt`, `factory miner calibrate draw`, `factory miner calibrate label`, `factory miner calibrate report`, `factory miner list`, `factory miner register`, `factory miner reopen`, `factory miner retire`, `factory models cutoff`, `factory notices assess`, `factory notices check`, `factory notices list`, `factory outline`, `factory pack`, `factory pages brief`, `factory pages list`, `factory pages record`, `factory pages show`, `factory passages embed`, `factory passages status`, `factory performance`, `factory project host`, `factory protocol confirm-press`, `factory protocol show`, `factory question show`, `factory rank compute`, `factory rank show`, `factory rebuild`, `factory references decide`, `factory references extract`, `factory references layers label`, `factory references layers sample`, `factory references layers status`, `factory references list`, `factory references re-resolve`, `factory references scheme record`, `factory references status`, `factory regions add`, `factory regions adopt`, `factory regions define`, `factory regions diff`, `factory regions export`, `factory regions link`, `factory regions links`, `factory regions list`, `factory regions proposals`, `factory regions reject`, `factory regions remove`, `factory regions review`, `factory regions revise`, `factory regions show`, `factory regions snapshot`, `factory registry`, `factory relations confirm`, `factory relations list`, `factory relations reject`, `factory report discovery`, `factory report evidence`, `factory report flow`, `factory report flow-skipped`, `factory report flow-trail`, `factory report flow-works`, `factory report methods`, `factory report prisma`, `factory report search`, `factory resume`, `factory runs adopt`, `factory runs list`, `factory runs record`, `factory screen disagreements`, `factory screen join`, `factory screen next`, `factory screen record`, `factory screen resolve`, `factory screen-check band`, `factory screen-check example`, `factory screen-check label`, `factory screen-check list`, `factory screen-check measure`, `factory screen-check report`, `factory screen-check tuning`, `factory search chase`, `factory search slice`, `factory seeds admit`, `factory seeds explain`, `factory seeds split`, `factory server init`, `factory sheets balance`, `factory sheets diff`, `factory sheets export`, `factory sheets list`, `factory sheets rate`, `factory sheets show`, `factory site build`, `factory site serve`, `factory site status`, `factory snowball compare`, `factory snowball core list`, `factory snowball core mark`, `factory snowball core unmark`, `factory snowball plan`, `factory snowball run`, `factory status`, `factory suggest`, `factory taxonomy agreement`, `factory taxonomy coverage`, `factory taxonomy derive`, `factory taxonomy diff`, `factory taxonomy list`, `factory taxonomy proposals`, `factory taxonomy register`, `factory taxonomy view`, `factory technique candidates`, `factory technique challenges`, `factory technique combinations`, `factory technique gaps`, `factory technique landscape`, `factory technique neighbors`, `factory technique show`, `factory token issue`, `factory token list`, `factory token revoke`, `factory tour`, `factory trace`, `factory user add`, `factory user deactivate`, `factory user link`, `factory user list`, `factory user reactivate`, `factory versions list`, `factory versions prefer`, `factory view coverage`, `factory view horizon`, `factory view onion`, `factory view timeline`, `factory vocabulary approve`, `factory vocabulary list`, `factory vocabulary merge`, `factory vocabulary reject`, `factory vocabulary unmerge`, `factory watch plan`, `factory watch run`, `factory watch status` | +| `access` | Who may do what (slice 5 rulings 9 and 10; the spec's permissions table). | core | — | `factory activity`, `factory answers export`, `factory answers list`, `factory answers rate`, `factory answers show`, `factory appraisal agreement`, `factory appraisal audit-label`, `factory appraisal audit-report`, `factory appraisal audit-sample`, `factory appraisal judge`, `factory appraisal resolve`, `factory appraisal sheet`, `factory appraisal status`, `factory audit label`, `factory audit report`, `factory audit sample`, `factory bench level`, `factory benchmark-ledger`, `factory briefing`, `factory budget set`, `factory calibrate draw`, `factory calibrate label`, `factory cards assert`, `factory cards confirm`, `factory cards import`, `factory cards list`, `factory cards reject`, `factory cards show`, `factory chat advance`, `factory chat precision`, `factory chat request ask`, `factory chat request spar`, `factory chat requests`, `factory check`, `factory concept-links confirm`, `factory concept-links list`, `factory concept-links reject`, `factory concepts approve`, `factory concepts define`, `factory concepts history`, `factory concepts list`, `factory concepts merge`, `factory concepts reject-source`, `factory concepts review`, `factory concepts show`, `factory concepts source`, `factory concepts unmerge`, `factory conclusions diff`, `factory conclusions register`, `factory conclusions retire`, `factory conclusions status`, `factory conductor advance`, `factory conductor release-review`, `factory conductor start`, `factory conductor status`, `factory contradictions confirm`, `factory contradictions list`, `factory contradictions reject`, `factory contributions agreement`, `factory contributions audit label`, `factory contributions audit report`, `factory contributions audit sample`, `factory contributions list`, `factory contributions pairs`, `factory contributions resolve`, `factory contributions status`, `factory curation decide`, `factory curation lessons`, `factory curation list`, `factory dashboard export`, `factory dashboard serve`, `factory decide list`, `factory decide select`, `factory decide show`, `factory dedup list`, `factory dedup pair`, `factory dedup pairs`, `factory dedup revert`, `factory dedup run`, `factory develop render`, `factory digest`, `factory directions close`, `factory document convert`, `factory document coverage`, `factory document read`, `factory document reanchor`, `factory document status`, `factory draft audit`, `factory draft create`, `factory draft label`, `factory draft list`, `factory draft release`, `factory draft render`, `factory draft reorder`, `factory draft repin`, `factory draft show`, `factory draft status`, `factory draft verify`, `factory draft withdraw`, `factory draft write`, `factory experiments accept-baseline`, `factory experiments amend`, `factory experiments deviation`, `factory experiments evaluate-baselines`, `factory experiments freeze`, `factory experiments list`, `factory experiments show`, `factory experiments unlock`, `factory export bibtex`, `factory export crate`, `factory export csl`, `factory export nanopub`, `factory export prisma`, `factory export works`, `factory extract agreement`, `factory extract audit-label`, `factory extract audit-report`, `factory extract audit-sample`, `factory extract resolve`, `factory extract status`, `factory feed run`, `factory files list`, `factory files register`, `factory files status`, `factory finders conflicts`, `factory finders gaps`, `factory fulltext fetch`, `factory fulltext import`, `factory fulltext resolve`, `factory fulltext restore`, `factory fulltext status`, `factory gate audit label`, `factory gate audit report`, `factory gate audit sample`, `factory gates`, `factory graph build`, `factory graph export`, `factory graph query`, `factory graph status`, `factory grey capture`, `factory grey contact`, `factory hub build`, `factory hub facets set`, `factory hub facets show`, `factory hypotheses abandon`, `factory hypotheses conclude`, `factory hypotheses evaluate`, `factory hypotheses list`, `factory hypotheses register`, `factory hypotheses show`, `factory ideas candidates`, `factory ideas confirm`, `factory ideas define`, `factory ideas list`, `factory ideas merge`, `factory ideas reject`, `factory ideas unmerge`, `factory import admit`, `factory import attach`, `factory import bib`, `factory import confirm`, `factory import coverage`, `factory import csl`, `factory import describe`, `factory import list`, `factory import pdfs`, `factory import reject`, `factory import resolve`, `factory import ris`, `factory import show`, `factory inbox add`, `factory inbox list`, `factory inbox prioritise`, `factory inbox resolve`, `factory inbox withdraw`, `factory interpretations history`, `factory interpretations list`, `factory interpretations review`, `factory interpretations show`, `factory interpretations supersede`, `factory interpretations write`, `factory layers move`, `factory leads candidates`, `factory leads discard`, `factory leads list`, `factory leads park`, `factory leads promote`, `factory leads queue`, `factory leads stats`, `factory ledger`, `factory library adopt`, `factory library confirm-source`, `factory library consolidate`, `factory library push`, `factory living prisma-update`, `factory living snapshot`, `factory manuscript add`, `factory manuscript audit`, `factory manuscript report`, `factory manuscript resolve`, `factory manuscript status`, `factory match`, `factory member grant`, `factory member list`, `factory member revoke`, `factory mine agreement`, `factory mine audit label`, `factory mine audit report`, `factory mine audit sample`, `factory mine import`, `factory mine request`, `factory mine resolve`, `factory mine status`, `factory miner add`, `factory miner admit`, `factory miner adopt`, `factory miner calibrate draw`, `factory miner calibrate label`, `factory miner calibrate report`, `factory miner list`, `factory miner register`, `factory miner reopen`, `factory miner retire`, `factory models cutoff`, `factory notices assess`, `factory notices check`, `factory notices list`, `factory outline`, `factory pack`, `factory pages brief`, `factory pages list`, `factory pages record`, `factory pages show`, `factory passages embed`, `factory passages status`, `factory performance`, `factory project host`, `factory project visibility`, `factory protocol confirm-press`, `factory protocol show`, `factory question show`, `factory rank compute`, `factory rank show`, `factory rebuild`, `factory references decide`, `factory references extract`, `factory references layers label`, `factory references layers sample`, `factory references layers status`, `factory references list`, `factory references re-resolve`, `factory references scheme record`, `factory references status`, `factory regions add`, `factory regions adopt`, `factory regions define`, `factory regions diff`, `factory regions export`, `factory regions link`, `factory regions links`, `factory regions list`, `factory regions proposals`, `factory regions reject`, `factory regions remove`, `factory regions review`, `factory regions revise`, `factory regions show`, `factory regions snapshot`, `factory registry`, `factory relations confirm`, `factory relations list`, `factory relations reject`, `factory report discovery`, `factory report evidence`, `factory report flow`, `factory report flow-skipped`, `factory report flow-trail`, `factory report flow-works`, `factory report methods`, `factory report prisma`, `factory report search`, `factory resume`, `factory review list`, `factory review show`, `factory runs adopt`, `factory runs list`, `factory runs record`, `factory screen disagreements`, `factory screen join`, `factory screen next`, `factory screen record`, `factory screen resolve`, `factory screen-check band`, `factory screen-check example`, `factory screen-check label`, `factory screen-check list`, `factory screen-check measure`, `factory screen-check report`, `factory screen-check tuning`, `factory search chase`, `factory search slice`, `factory seeds admit`, `factory seeds explain`, `factory seeds split`, `factory sheets balance`, `factory sheets diff`, `factory sheets export`, `factory sheets list`, `factory sheets rate`, `factory sheets show`, `factory site build`, `factory site serve`, `factory site status`, `factory snowball compare`, `factory snowball core list`, `factory snowball core mark`, `factory snowball core unmark`, `factory snowball plan`, `factory snowball run`, `factory status`, `factory suggest`, `factory taxonomy agreement`, `factory taxonomy coverage`, `factory taxonomy derive`, `factory taxonomy diff`, `factory taxonomy list`, `factory taxonomy proposals`, `factory taxonomy register`, `factory taxonomy view`, `factory technique candidates`, `factory technique challenges`, `factory technique combinations`, `factory technique gaps`, `factory technique landscape`, `factory technique neighbors`, `factory technique show`, `factory token issue`, `factory token list`, `factory token revoke`, `factory tour`, `factory trace`, `factory user add`, `factory user deactivate`, `factory user link`, `factory user list`, `factory user reactivate`, `factory versions list`, `factory versions prefer`, `factory view coverage`, `factory view horizon`, `factory view onion`, `factory view timeline`, `factory vocabulary approve`, `factory vocabulary list`, `factory vocabulary merge`, `factory vocabulary reject`, `factory vocabulary unmerge`, `factory watch plan`, `factory watch run`, `factory watch status`, `factory workspace` | +| `access_log` | The server access log (slice 5 ruling 12; plan ruling 5). | — | — | `factory activity`, `factory answers export`, `factory answers list`, `factory answers rate`, `factory answers show`, `factory appraisal agreement`, `factory appraisal audit-label`, `factory appraisal audit-report`, `factory appraisal audit-sample`, `factory appraisal judge`, `factory appraisal resolve`, `factory appraisal sheet`, `factory appraisal status`, `factory audit label`, `factory audit report`, `factory audit sample`, `factory bench level`, `factory benchmark-ledger`, `factory briefing`, `factory budget set`, `factory calibrate draw`, `factory calibrate label`, `factory cards assert`, `factory cards confirm`, `factory cards import`, `factory cards list`, `factory cards reject`, `factory cards show`, `factory chat advance`, `factory chat precision`, `factory chat request ask`, `factory chat request spar`, `factory chat requests`, `factory check`, `factory concept-links confirm`, `factory concept-links list`, `factory concept-links reject`, `factory concepts approve`, `factory concepts define`, `factory concepts history`, `factory concepts list`, `factory concepts merge`, `factory concepts reject-source`, `factory concepts review`, `factory concepts show`, `factory concepts source`, `factory concepts unmerge`, `factory conclusions diff`, `factory conclusions register`, `factory conclusions retire`, `factory conclusions status`, `factory conductor advance`, `factory conductor release-review`, `factory conductor start`, `factory conductor status`, `factory contradictions confirm`, `factory contradictions list`, `factory contradictions reject`, `factory contributions agreement`, `factory contributions audit label`, `factory contributions audit report`, `factory contributions audit sample`, `factory contributions list`, `factory contributions pairs`, `factory contributions resolve`, `factory contributions status`, `factory curation decide`, `factory curation lessons`, `factory curation list`, `factory dashboard export`, `factory dashboard serve`, `factory decide list`, `factory decide select`, `factory decide show`, `factory dedup list`, `factory dedup pair`, `factory dedup pairs`, `factory dedup revert`, `factory dedup run`, `factory develop render`, `factory digest`, `factory directions close`, `factory document convert`, `factory document coverage`, `factory document read`, `factory document reanchor`, `factory document status`, `factory draft audit`, `factory draft create`, `factory draft label`, `factory draft list`, `factory draft release`, `factory draft render`, `factory draft reorder`, `factory draft repin`, `factory draft show`, `factory draft status`, `factory draft verify`, `factory draft withdraw`, `factory draft write`, `factory experiments accept-baseline`, `factory experiments amend`, `factory experiments deviation`, `factory experiments evaluate-baselines`, `factory experiments freeze`, `factory experiments list`, `factory experiments show`, `factory experiments unlock`, `factory export bibtex`, `factory export crate`, `factory export csl`, `factory export nanopub`, `factory export prisma`, `factory export works`, `factory extract agreement`, `factory extract audit-label`, `factory extract audit-report`, `factory extract audit-sample`, `factory extract resolve`, `factory extract status`, `factory files list`, `factory files register`, `factory files status`, `factory finders conflicts`, `factory finders gaps`, `factory fulltext fetch`, `factory fulltext import`, `factory fulltext resolve`, `factory fulltext restore`, `factory fulltext status`, `factory gate audit label`, `factory gate audit report`, `factory gate audit sample`, `factory gates`, `factory graph build`, `factory graph export`, `factory graph query`, `factory graph status`, `factory grey capture`, `factory grey contact`, `factory hub build`, `factory hub facets set`, `factory hub facets show`, `factory hypotheses abandon`, `factory hypotheses conclude`, `factory hypotheses evaluate`, `factory hypotheses list`, `factory hypotheses register`, `factory hypotheses show`, `factory ideas candidates`, `factory ideas confirm`, `factory ideas define`, `factory ideas list`, `factory ideas merge`, `factory ideas reject`, `factory ideas unmerge`, `factory import admit`, `factory import attach`, `factory import bib`, `factory import confirm`, `factory import coverage`, `factory import csl`, `factory import describe`, `factory import list`, `factory import pdfs`, `factory import reject`, `factory import resolve`, `factory import ris`, `factory import show`, `factory inbox add`, `factory inbox list`, `factory inbox prioritise`, `factory inbox resolve`, `factory inbox withdraw`, `factory interpretations history`, `factory interpretations list`, `factory interpretations review`, `factory interpretations show`, `factory interpretations supersede`, `factory interpretations write`, `factory layers move`, `factory leads candidates`, `factory leads discard`, `factory leads list`, `factory leads park`, `factory leads promote`, `factory leads queue`, `factory leads stats`, `factory ledger`, `factory library adopt`, `factory library confirm-source`, `factory library consolidate`, `factory library push`, `factory living prisma-update`, `factory living snapshot`, `factory manuscript add`, `factory manuscript audit`, `factory manuscript report`, `factory manuscript resolve`, `factory manuscript status`, `factory match`, `factory member grant`, `factory member list`, `factory member revoke`, `factory mine agreement`, `factory mine audit label`, `factory mine audit report`, `factory mine audit sample`, `factory mine import`, `factory mine request`, `factory mine resolve`, `factory mine status`, `factory miner add`, `factory miner admit`, `factory miner adopt`, `factory miner calibrate draw`, `factory miner calibrate label`, `factory miner calibrate report`, `factory miner list`, `factory miner register`, `factory miner reopen`, `factory miner retire`, `factory models cutoff`, `factory notices assess`, `factory notices check`, `factory notices list`, `factory outline`, `factory pack`, `factory pages brief`, `factory pages list`, `factory pages record`, `factory pages show`, `factory passages embed`, `factory passages status`, `factory performance`, `factory project host`, `factory protocol confirm-press`, `factory protocol show`, `factory question show`, `factory rank compute`, `factory rank show`, `factory rebuild`, `factory references decide`, `factory references extract`, `factory references layers label`, `factory references layers sample`, `factory references layers status`, `factory references list`, `factory references re-resolve`, `factory references scheme record`, `factory references status`, `factory regions add`, `factory regions adopt`, `factory regions define`, `factory regions diff`, `factory regions export`, `factory regions link`, `factory regions links`, `factory regions list`, `factory regions proposals`, `factory regions reject`, `factory regions remove`, `factory regions review`, `factory regions revise`, `factory regions show`, `factory regions snapshot`, `factory registry`, `factory relations confirm`, `factory relations list`, `factory relations reject`, `factory report discovery`, `factory report evidence`, `factory report flow`, `factory report flow-skipped`, `factory report flow-trail`, `factory report flow-works`, `factory report methods`, `factory report prisma`, `factory report search`, `factory resume`, `factory runs adopt`, `factory runs list`, `factory runs record`, `factory screen disagreements`, `factory screen join`, `factory screen next`, `factory screen record`, `factory screen resolve`, `factory screen-check band`, `factory screen-check example`, `factory screen-check label`, `factory screen-check list`, `factory screen-check measure`, `factory screen-check report`, `factory screen-check tuning`, `factory search chase`, `factory search slice`, `factory seeds admit`, `factory seeds explain`, `factory seeds split`, `factory server init`, `factory sheets balance`, `factory sheets diff`, `factory sheets export`, `factory sheets list`, `factory sheets rate`, `factory sheets show`, `factory site build`, `factory site serve`, `factory site status`, `factory snowball compare`, `factory snowball core list`, `factory snowball core mark`, `factory snowball core unmark`, `factory snowball plan`, `factory snowball run`, `factory status`, `factory suggest`, `factory taxonomy agreement`, `factory taxonomy coverage`, `factory taxonomy derive`, `factory taxonomy diff`, `factory taxonomy list`, `factory taxonomy proposals`, `factory taxonomy register`, `factory taxonomy view`, `factory technique candidates`, `factory technique challenges`, `factory technique combinations`, `factory technique gaps`, `factory technique landscape`, `factory technique neighbors`, `factory technique show`, `factory token issue`, `factory token list`, `factory token revoke`, `factory tour`, `factory trace`, `factory user add`, `factory user deactivate`, `factory user link`, `factory user list`, `factory user reactivate`, `factory versions list`, `factory versions prefer`, `factory view coverage`, `factory view horizon`, `factory view onion`, `factory view timeline`, `factory vocabulary approve`, `factory vocabulary list`, `factory vocabulary merge`, `factory vocabulary reject`, `factory vocabulary unmerge`, `factory watch plan`, `factory watch run`, `factory watch status` | | `activity` | What the agents are working on now (IDEA-98): one reading of the claimed tasks, the open passes, the platform's long op… | — | — | `factory activity` | | `agent_view` | The agent view of the report surfaces, shared by MCP and by the CLI of a person without the full view (slice 5 ruling 2… | experiments | `benchmark_ledger_view`, `card_assert`, `card_create`, `card_view`, `check`, `concept_link`, `concept_propose`, `consolidation_next`, `consolidation_propose`, `contradiction_propose`, `draft_create`, `draft_next`, `draft_release`, `draft_render`, `draft_reorder`, `draft_repin`, `draft_status`, `draft_verify_next`, `draft_verify_record`, `draft_write`, `experiment_design`, `experiment_view`, `finder_contradictions`, `finder_gaps`, `flow_skipped`, `flow_trail`, `flow_works`, `graph_export`, `graph_query`, `graph_status`, `hypothesis_draft`, `hypothesis_register`, `hypothesis_review`, `hypothesis_review_next`, `hypothesis_view`, `interpretation_list`, `interpretation_record`, `intuition_next`, `label_apply`, `lead_decide`, `lead_record`, `manuscript_read`, `manuscript_verify_next`, `manuscript_verify_record`, `match_query`, `mine_disagreements`, `mine_next`, `mine_resolve`, `project_status`, `region_propose`, `region_propose_member`, `region_query`, `region_snapshot`, `region_status`, `registry_query`, `report_discovery`, `report_evidence`, `report_methods`, `report_prisma`, `report_search`, `term_list`, `trace`, `view_coverage`, `view_horizon`, `view_onion`, `view_timeline`, `writing_outline`, `xrun_list`, `xrun_register` | `factory check`, `factory decide list`, `factory decide show`, `factory develop render`, `factory report discovery`, `factory report evidence`, `factory report flow`, `factory report flow-skipped`, `factory report flow-trail`, `factory report flow-works`, `factory report methods`, `factory report prisma`, `factory report search`, `factory review list`, `factory review show`, `factory screen next`, `factory screen record`, `factory status`, `factory trace`, `factory workspace` | | `agreement` | Agreement between the two screening passes, κ per criterion, human resolution, final outcomes (R-36, R-38, ruling 1). | screening | `audit_sample`, `screen_agreement` | `factory audit sample`, `factory screen disagreements`, `factory screen resolve` | @@ -1678,7 +1687,7 @@ Defined in `cli/main.py` (typer); rendering in `cli/render.py` and siblings. | `hub_ui` | Hub UI assets, colour tokens, glossary and labels. | — | — | — | | `hub_write` | The `write` hub payload: synthesis pages, bibliography, PRISMA diagram and wiki vault pointer. | — | — | — | | `human_channel` | Human acts by channel: what is refused, and what is counted (slice 5 ruling 11, R-111). | core, decisions, extraction, living, mining, screening | — | — | -| `human_pass` | What a person may see and run while they screen a pass (slice 5 rulings 15 and 20, R-110). | — | — | `factory activity`, `factory answers export`, `factory answers list`, `factory answers rate`, `factory answers show`, `factory appraisal agreement`, `factory appraisal audit-label`, `factory appraisal audit-report`, `factory appraisal audit-sample`, `factory appraisal judge`, `factory appraisal resolve`, `factory appraisal sheet`, `factory appraisal status`, `factory audit label`, `factory audit report`, `factory audit sample`, `factory bench level`, `factory benchmark-ledger`, `factory briefing`, `factory calibrate draw`, `factory calibrate label`, `factory cards assert`, `factory cards confirm`, `factory cards import`, `factory cards list`, `factory cards reject`, `factory cards show`, `factory chat advance`, `factory chat precision`, `factory chat request ask`, `factory chat request spar`, `factory chat requests`, `factory check`, `factory concept-links confirm`, `factory concept-links list`, `factory concept-links reject`, `factory concepts approve`, `factory concepts define`, `factory concepts history`, `factory concepts list`, `factory concepts merge`, `factory concepts reject-source`, `factory concepts review`, `factory concepts show`, `factory concepts source`, `factory concepts unmerge`, `factory conclusions diff`, `factory conclusions register`, `factory conclusions retire`, `factory conclusions status`, `factory conductor advance`, `factory conductor start`, `factory conductor status`, `factory contradictions confirm`, `factory contradictions list`, `factory contradictions reject`, `factory contributions agreement`, `factory contributions audit label`, `factory contributions audit report`, `factory contributions audit sample`, `factory contributions list`, `factory contributions pairs`, `factory contributions resolve`, `factory contributions status`, `factory curation decide`, `factory curation lessons`, `factory curation list`, `factory dashboard export`, `factory dashboard serve`, `factory decide list`, `factory decide select`, `factory decide show`, `factory dedup list`, `factory dedup pair`, `factory dedup pairs`, `factory dedup revert`, `factory dedup run`, `factory develop render`, `factory digest`, `factory directions close`, `factory document convert`, `factory document coverage`, `factory document read`, `factory document reanchor`, `factory document status`, `factory draft audit`, `factory draft create`, `factory draft label`, `factory draft list`, `factory draft release`, `factory draft render`, `factory draft reorder`, `factory draft repin`, `factory draft show`, `factory draft status`, `factory draft verify`, `factory draft withdraw`, `factory draft write`, `factory experiments accept-baseline`, `factory experiments amend`, `factory experiments deviation`, `factory experiments evaluate-baselines`, `factory experiments freeze`, `factory experiments list`, `factory experiments show`, `factory experiments unlock`, `factory export bibtex`, `factory export crate`, `factory export csl`, `factory export nanopub`, `factory export prisma`, `factory export works`, `factory extract agreement`, `factory extract audit-label`, `factory extract audit-report`, `factory extract audit-sample`, `factory extract resolve`, `factory extract status`, `factory files list`, `factory files register`, `factory files status`, `factory finders conflicts`, `factory finders gaps`, `factory fulltext fetch`, `factory fulltext import`, `factory fulltext resolve`, `factory fulltext restore`, `factory fulltext status`, `factory gate audit label`, `factory gate audit report`, `factory gate audit sample`, `factory gates`, `factory graph build`, `factory graph export`, `factory graph query`, `factory graph status`, `factory grey capture`, `factory grey contact`, `factory hub build`, `factory hub facets set`, `factory hub facets show`, `factory hypotheses abandon`, `factory hypotheses conclude`, `factory hypotheses evaluate`, `factory hypotheses list`, `factory hypotheses register`, `factory hypotheses show`, `factory ideas candidates`, `factory ideas confirm`, `factory ideas define`, `factory ideas list`, `factory ideas merge`, `factory ideas reject`, `factory ideas unmerge`, `factory import admit`, `factory import attach`, `factory import bib`, `factory import confirm`, `factory import coverage`, `factory import csl`, `factory import describe`, `factory import list`, `factory import pdfs`, `factory import reject`, `factory import resolve`, `factory import ris`, `factory import show`, `factory inbox add`, `factory inbox list`, `factory inbox prioritise`, `factory inbox resolve`, `factory inbox withdraw`, `factory interpretations history`, `factory interpretations list`, `factory interpretations review`, `factory interpretations show`, `factory interpretations supersede`, `factory interpretations write`, `factory layers move`, `factory leads candidates`, `factory leads discard`, `factory leads list`, `factory leads park`, `factory leads promote`, `factory leads queue`, `factory leads stats`, `factory living prisma-update`, `factory living snapshot`, `factory manuscript add`, `factory manuscript audit`, `factory manuscript report`, `factory manuscript resolve`, `factory manuscript status`, `factory match`, `factory mine agreement`, `factory mine audit label`, `factory mine audit report`, `factory mine audit sample`, `factory mine import`, `factory mine request`, `factory mine resolve`, `factory mine status`, `factory miner add`, `factory miner admit`, `factory miner adopt`, `factory miner calibrate draw`, `factory miner calibrate label`, `factory miner calibrate report`, `factory miner list`, `factory miner register`, `factory miner reopen`, `factory miner retire`, `factory models cutoff`, `factory notices assess`, `factory notices check`, `factory notices list`, `factory outline`, `factory pack`, `factory pages brief`, `factory pages list`, `factory pages record`, `factory pages show`, `factory passages embed`, `factory passages status`, `factory performance`, `factory protocol confirm-press`, `factory protocol show`, `factory question show`, `factory rank compute`, `factory rank show`, `factory rebuild`, `factory references decide`, `factory references extract`, `factory references layers label`, `factory references layers sample`, `factory references layers status`, `factory references list`, `factory references re-resolve`, `factory references scheme record`, `factory references status`, `factory regions add`, `factory regions adopt`, `factory regions define`, `factory regions diff`, `factory regions export`, `factory regions link`, `factory regions links`, `factory regions list`, `factory regions proposals`, `factory regions reject`, `factory regions remove`, `factory regions review`, `factory regions revise`, `factory regions show`, `factory regions snapshot`, `factory registry`, `factory relations confirm`, `factory relations list`, `factory relations reject`, `factory report discovery`, `factory report evidence`, `factory report flow`, `factory report flow-skipped`, `factory report flow-trail`, `factory report flow-works`, `factory report methods`, `factory report prisma`, `factory report search`, `factory runs adopt`, `factory runs list`, `factory runs record`, `factory screen disagreements`, `factory screen join`, `factory screen next`, `factory screen record`, `factory screen resolve`, `factory screen-check band`, `factory screen-check example`, `factory screen-check label`, `factory screen-check list`, `factory screen-check measure`, `factory screen-check report`, `factory screen-check tuning`, `factory search chase`, `factory search slice`, `factory seeds admit`, `factory seeds explain`, `factory seeds split`, `factory sheets balance`, `factory sheets diff`, `factory sheets export`, `factory sheets list`, `factory sheets rate`, `factory sheets show`, `factory site build`, `factory site serve`, `factory site status`, `factory snowball compare`, `factory snowball core list`, `factory snowball core mark`, `factory snowball core unmark`, `factory snowball plan`, `factory snowball run`, `factory status`, `factory suggest`, `factory taxonomy agreement`, `factory taxonomy coverage`, `factory taxonomy derive`, `factory taxonomy diff`, `factory taxonomy list`, `factory taxonomy proposals`, `factory taxonomy register`, `factory taxonomy view`, `factory technique candidates`, `factory technique challenges`, `factory technique combinations`, `factory technique gaps`, `factory technique landscape`, `factory technique neighbors`, `factory technique show`, `factory tour`, `factory trace`, `factory versions list`, `factory versions prefer`, `factory view coverage`, `factory view horizon`, `factory view onion`, `factory view timeline`, `factory vocabulary approve`, `factory vocabulary list`, `factory vocabulary merge`, `factory vocabulary reject`, `factory vocabulary unmerge`, `factory watch plan`, `factory watch run`, `factory watch status` | +| `human_pass` | What a person may see and run while they screen a pass (slice 5 rulings 15 and 20, R-110). | — | — | `factory activity`, `factory answers export`, `factory answers list`, `factory answers rate`, `factory answers show`, `factory appraisal agreement`, `factory appraisal audit-label`, `factory appraisal audit-report`, `factory appraisal audit-sample`, `factory appraisal judge`, `factory appraisal resolve`, `factory appraisal sheet`, `factory appraisal status`, `factory audit label`, `factory audit report`, `factory audit sample`, `factory bench level`, `factory benchmark-ledger`, `factory briefing`, `factory calibrate draw`, `factory calibrate label`, `factory cards assert`, `factory cards confirm`, `factory cards import`, `factory cards list`, `factory cards reject`, `factory cards show`, `factory chat advance`, `factory chat precision`, `factory chat request ask`, `factory chat request spar`, `factory chat requests`, `factory check`, `factory concept-links confirm`, `factory concept-links list`, `factory concept-links reject`, `factory concepts approve`, `factory concepts define`, `factory concepts history`, `factory concepts list`, `factory concepts merge`, `factory concepts reject-source`, `factory concepts review`, `factory concepts show`, `factory concepts source`, `factory concepts unmerge`, `factory conclusions diff`, `factory conclusions register`, `factory conclusions retire`, `factory conclusions status`, `factory conductor advance`, `factory conductor release-review`, `factory conductor start`, `factory conductor status`, `factory contradictions confirm`, `factory contradictions list`, `factory contradictions reject`, `factory contributions agreement`, `factory contributions audit label`, `factory contributions audit report`, `factory contributions audit sample`, `factory contributions list`, `factory contributions pairs`, `factory contributions resolve`, `factory contributions status`, `factory curation decide`, `factory curation lessons`, `factory curation list`, `factory dashboard export`, `factory dashboard serve`, `factory decide list`, `factory decide select`, `factory decide show`, `factory dedup list`, `factory dedup pair`, `factory dedup pairs`, `factory dedup revert`, `factory dedup run`, `factory develop render`, `factory digest`, `factory directions close`, `factory document convert`, `factory document coverage`, `factory document read`, `factory document reanchor`, `factory document status`, `factory draft audit`, `factory draft create`, `factory draft label`, `factory draft list`, `factory draft release`, `factory draft render`, `factory draft reorder`, `factory draft repin`, `factory draft show`, `factory draft status`, `factory draft verify`, `factory draft withdraw`, `factory draft write`, `factory experiments accept-baseline`, `factory experiments amend`, `factory experiments deviation`, `factory experiments evaluate-baselines`, `factory experiments freeze`, `factory experiments list`, `factory experiments show`, `factory experiments unlock`, `factory export bibtex`, `factory export crate`, `factory export csl`, `factory export nanopub`, `factory export prisma`, `factory export works`, `factory extract agreement`, `factory extract audit-label`, `factory extract audit-report`, `factory extract audit-sample`, `factory extract resolve`, `factory extract status`, `factory files list`, `factory files register`, `factory files status`, `factory finders conflicts`, `factory finders gaps`, `factory fulltext fetch`, `factory fulltext import`, `factory fulltext resolve`, `factory fulltext restore`, `factory fulltext status`, `factory gate audit label`, `factory gate audit report`, `factory gate audit sample`, `factory gates`, `factory graph build`, `factory graph export`, `factory graph query`, `factory graph status`, `factory grey capture`, `factory grey contact`, `factory hub build`, `factory hub facets set`, `factory hub facets show`, `factory hypotheses abandon`, `factory hypotheses conclude`, `factory hypotheses evaluate`, `factory hypotheses list`, `factory hypotheses register`, `factory hypotheses show`, `factory ideas candidates`, `factory ideas confirm`, `factory ideas define`, `factory ideas list`, `factory ideas merge`, `factory ideas reject`, `factory ideas unmerge`, `factory import admit`, `factory import attach`, `factory import bib`, `factory import confirm`, `factory import coverage`, `factory import csl`, `factory import describe`, `factory import list`, `factory import pdfs`, `factory import reject`, `factory import resolve`, `factory import ris`, `factory import show`, `factory inbox add`, `factory inbox list`, `factory inbox prioritise`, `factory inbox resolve`, `factory inbox withdraw`, `factory interpretations history`, `factory interpretations list`, `factory interpretations review`, `factory interpretations show`, `factory interpretations supersede`, `factory interpretations write`, `factory layers move`, `factory leads candidates`, `factory leads discard`, `factory leads list`, `factory leads park`, `factory leads promote`, `factory leads queue`, `factory leads stats`, `factory living prisma-update`, `factory living snapshot`, `factory manuscript add`, `factory manuscript audit`, `factory manuscript report`, `factory manuscript resolve`, `factory manuscript status`, `factory match`, `factory mine agreement`, `factory mine audit label`, `factory mine audit report`, `factory mine audit sample`, `factory mine import`, `factory mine request`, `factory mine resolve`, `factory mine status`, `factory miner add`, `factory miner admit`, `factory miner adopt`, `factory miner calibrate draw`, `factory miner calibrate label`, `factory miner calibrate report`, `factory miner list`, `factory miner register`, `factory miner reopen`, `factory miner retire`, `factory models cutoff`, `factory notices assess`, `factory notices check`, `factory notices list`, `factory outline`, `factory pack`, `factory pages brief`, `factory pages list`, `factory pages record`, `factory pages show`, `factory passages embed`, `factory passages status`, `factory performance`, `factory protocol confirm-press`, `factory protocol show`, `factory question show`, `factory rank compute`, `factory rank show`, `factory rebuild`, `factory references decide`, `factory references extract`, `factory references layers label`, `factory references layers sample`, `factory references layers status`, `factory references list`, `factory references re-resolve`, `factory references scheme record`, `factory references status`, `factory regions add`, `factory regions adopt`, `factory regions define`, `factory regions diff`, `factory regions export`, `factory regions link`, `factory regions links`, `factory regions list`, `factory regions proposals`, `factory regions reject`, `factory regions remove`, `factory regions review`, `factory regions revise`, `factory regions show`, `factory regions snapshot`, `factory registry`, `factory relations confirm`, `factory relations list`, `factory relations reject`, `factory report discovery`, `factory report evidence`, `factory report flow`, `factory report flow-skipped`, `factory report flow-trail`, `factory report flow-works`, `factory report methods`, `factory report prisma`, `factory report search`, `factory runs adopt`, `factory runs list`, `factory runs record`, `factory screen disagreements`, `factory screen join`, `factory screen next`, `factory screen record`, `factory screen resolve`, `factory screen-check band`, `factory screen-check example`, `factory screen-check label`, `factory screen-check list`, `factory screen-check measure`, `factory screen-check report`, `factory screen-check tuning`, `factory search chase`, `factory search slice`, `factory seeds admit`, `factory seeds explain`, `factory seeds split`, `factory sheets balance`, `factory sheets diff`, `factory sheets export`, `factory sheets list`, `factory sheets rate`, `factory sheets show`, `factory site build`, `factory site serve`, `factory site status`, `factory snowball compare`, `factory snowball core list`, `factory snowball core mark`, `factory snowball core unmark`, `factory snowball plan`, `factory snowball run`, `factory status`, `factory suggest`, `factory taxonomy agreement`, `factory taxonomy coverage`, `factory taxonomy derive`, `factory taxonomy diff`, `factory taxonomy list`, `factory taxonomy proposals`, `factory taxonomy register`, `factory taxonomy view`, `factory technique candidates`, `factory technique challenges`, `factory technique combinations`, `factory technique gaps`, `factory technique landscape`, `factory technique neighbors`, `factory technique show`, `factory tour`, `factory trace`, `factory versions list`, `factory versions prefer`, `factory view coverage`, `factory view horizon`, `factory view onion`, `factory view timeline`, `factory vocabulary approve`, `factory vocabulary list`, `factory vocabulary merge`, `factory vocabulary reject`, `factory vocabulary unmerge`, `factory watch plan`, `factory watch run`, `factory watch status` | | `human_queue` | The human queue of one project: where a human is blocking, one count per gate kind. | — | — | — | | `hypotheses` | Hypotheses: drafting, states, the revision rule and abandonment (slice 6, plan H-C; rulings 3, 5, 6 and 12). | hypotheses | `hypothesis_draft`, `hypothesis_list`, `hypothesis_register`, `hypothesis_view` | `factory hypotheses abandon`, `factory hypotheses conclude`, `factory hypotheses list`, `factory hypotheses register`, `factory hypotheses show`, `factory models cutoff` | | `hypothesis_gates` | Who may pass the hypothesis gates (slice 6, plan H-C; slice M ruling 2). | — | — | — | @@ -1778,6 +1787,7 @@ Defined in `cli/main.py` (typer); rendering in `cli/render.py` and siblings. | `reproduction` | Baseline reproduction verdicts, written by the platform as `system` events (slice 6, plan XP-A task 6; spec ruling 24). | experiments | — | `factory experiments evaluate-baselines` | | `results` | | — | `appraisal_record`, `inbox_add`, `label_apply`, `screen_record`, `seed_add` | — | | `resume` | Finding interrupted work (plan restart-and-costs R1, IDEA-59): what a power loss, a killed process or an abandoned sess… | — | — | `factory resume` | +| `review_loop` | The conductor's review loop (plan 2026-11-28-review-loops). | runner | — | — | | `reviews` | Review requests and their decisions (slice 5 ruling 14; plan teams-B). | core | `review_decide`, `review_list`, `review_request` | `factory protocol amend`, `factory protocol deviation`, `factory protocol record`, `factory review decide`, `factory review list`, `factory review request`, `factory review show`, `factory review withdraw`, `factory workspace` | | `run_costs` | Run costs (plan restart-and-costs, task C1): what each headless run cost, read from its log. | — | — | — | | `run_units` | Names shared by the MCP unit cap (`mcp.unit_cap`, the writer) and the cost reader (`services.run_costs`). | — | — | — | @@ -1864,6 +1874,7 @@ Defined in `cli/main.py` (typer); rendering in `cli/render.py` and siblings. | `technique_rank` | Ranking of technique combination and gap candidates (IDEA-78, ranking step). | — | — | — | | `terms` | Terms: promoted label keys with a definition, aliases and a classified set of applications (slice 3d ruling 16, plan Re… | labels | `term_list` | `factory terms list`, `factory terms promote`, `factory terms retire`, `factory terms revise`, `factory terms suggest` | | `tier_caps` | Tier caps as the platform enforces them (lane L14). | — | — | — | +| `tier_protocol` | The tier's protocol template recorded for a project (plan 2026-11-28-review-loops). | core | — | — | | `tolerance` | The protocol's `pending_tolerance` (decision 138): how many works may stay incomplete without blocking a workflow step. | — | — | — | | `tool_source` | The MCP server builder, supplied by an interface instead of imported by the core. | — | — | — | | `trace` | The R-01 chain walked from any identifier, backwards or forwards (plan 5b, task 3). | dedup, imports, retrieval, screening | `trace` | `factory trace` | @@ -1910,6 +1921,7 @@ Defined in `cli/main.py` (typer); rendering in `cli/render.py` and siblings. | `rf-experiment` | Use when a registered or drafted experiment hypothesis needs a pre-registered experiment design, or planned runs must be registered against a frozen design, in… | `experiment_design`, `experiment_view`, `hypothesis_view`, `xrun_list`, `xrun_register` | | `rf-extract` | Use when the included works of a ready protocol must be extracted into schema rows (and, in pass A, claims) from their pinned converted full text, as pass A or… | `check`, `document_read`, `extract_next`, `extract_record`, `project_status`, `trace` | | `rf-frame` | Use when a researcher starts a review or states a goal, and the factory needs a recorded, versioned research question with its framing and non-goals. | `check`, `develop_render`, `project_status`, `question_record` | +| `rf-frame-conducted` | Use when the conductor starts the frame step of a project as a headless proposer run (stage frame): nobody answers, so the question, seeds and protocol are rec… | `project_status`, `protocol_from_template`, `question_record`, `question_view`, `review_reply`, `review_view`, `seed_add` | | `rf-hypothesis-engine` | Use when the researcher wants a guided, step-by-step run of the hypothesis generation engine on the project's corpus products (claims digest, technique candida… | `chat_verify`, `check`, `claims_digest`, `corpus_search`, `document_read`, `finder_contradictions`, `finder_gaps`, `hypothesis_draft`, `hypothesis_list`, `hypothesis_register`, `hypothesis_review`, `hypothesis_review_next`, `hypothesis_view`, `lead_candidates`, `lead_decide`, `lead_list`, `lead_queue`, `lead_record`, `lead_stats`, `match_query`, `selection_resolve`, `technique_challenges`, `technique_combinations`, `technique_gaps`, `technique_neighbors` | | `rf-ideate` | Use when research ideas must be captured as leads tied to triggers in the corpus and turned into pre-registrable hypothesis drafts, in a Claude Code session th… | `contradiction_propose`, `finder_contradictions`, `finder_gaps`, `hypothesis_draft`, `hypothesis_view`, `lead_candidates`, `lead_queue`, `lead_record`, `lead_stats`, `match_query` | | `rf-intuition` | Use when a confirmed idea or a corpus paper needs a short, source-bound interpretation of why it works, to be reviewed by the researcher, in a Claude Code sess… | `check`, `concept_link`, `concept_propose`, `document_read`, `interpretation_list`, `interpretation_record`, `intuition_next` | @@ -1923,6 +1935,7 @@ Defined in `cli/main.py` (typer); rendering in `cli/render.py` and siblings. | `rf-reference-layers` | Assign relevance layers (earth rings) to the cited items of a project's reference lists, from titles, under the researcher's recorded scheme. | `reference_layer_next`, `reference_layer_record` | | `rf-references` | Use when works have been included after full-text screening and converted to Markdown, and their reference lists must be extracted, linked to the corpus, and s… | `check`, `decision_suggest`, `dedup_run`, `document_read`, `reference_decide`, `references_extract`, `references_list`, `references_status`, `search_run`, `snowball_compare`, `snowball_round` | | `rf-regions` | Use when a region or focus of the corpus and the graph must be drafted as typed selection rules, or when a single work, idea or concept should be proposed for… | `region_propose`, `region_propose_member`, `region_query`, `region_snapshot`, `region_status` | +| `rf-review` | Use when the conductor starts the reviewer of a review loop (stage review-frame or review-write): a separate session that checks one step's output against the… | `chat_verify`, `check`, `claims_digest`, `document_read`, `draft_list`, `draft_render`, `project_status`, `protocol_view`, `question_view`, `review_record`, `review_view`, `seed_list` | | `rf-run` | Use when a session starts on a project, or when it is unclear what comes next: states the order of stages, which session runs which pass, which steps are the r… | `card_list`, `check`, `concept_list`, `contribution_status`, `decision_list`, `decision_select`, `decision_view`, `dedup_merges`, `dedup_run`, `develop_render`, `document_status`, `draft_list`, `draft_status`, `experiment_list`, `extraction_status`, `fulltext_fetch`, `fulltext_status`, `graph_query`, `graph_status`, `hypothesis_list`, `idea_list`, `lead_list`, `library_adopt`, `library_adoptable`, `probe_run`, `project_status`, `protocol_amend`, `protocol_record`, `protocol_view`, `question_record`, `question_view`, `region_status`, `relation_list`, `report_discovery`, `report_evidence`, `report_methods`, `report_prisma`, `report_search`, `search_run`, `search_slice`, `seed_add`, `task_release`, `term_list`, `trace`, `view_coverage`, `view_horizon`, `view_onion`, `view_timeline` | | `rf-screen` | Use when records of a ready protocol must be screened, on title and abstract or (full-text mode) on the converted full text, as pass A or pass B of the two-pas… | `check`, `document_read`, `project_status`, `screen_agreement`, `screen_check_draw`, `screen_check_example`, `screen_check_label`, `screen_check_report`, `screen_next`, `screen_record` | | `rf-search` | Use when screening of the corpus has finished and agreement is recorded, and the included works must be chased backward and forward for further candidates. | `check`, `dedup_merges`, `dedup_run`, `grey_search_report`, `inbox_add`, `inbox_resolve`, `merge_revert`, `project_status`, `screen_agreement`, `screen_next`, `search_chase`, `search_run` | diff --git a/docs/backlog.md b/docs/backlog.md index 72b6c90e..d22808d2 100644 --- a/docs/backlog.md +++ b/docs/backlog.md @@ -1298,3 +1298,27 @@ Status: new · Added: 2026-11-24 · Slice: — · Depends on: the search record **Why:** programme runs will make absence claims constantly ("nobody compared compression rates for 3D"), and absence is the hardest claim to support. Today an absence is a sentence in a report; it should be a derived statement from the search record. **Rigour notes:** computed from the recorded searches and screening, never typed; wording is fixed by the platform ("not found in these sources"), so an agent cannot upgrade it to "does not exist"; a claim goes stale when the search record grows (new watch results). **Open questions:** whether it is a report section over existing events (no new event type) or needs its own record; the link to the gap-finder statistics; how a watch run re-checks an open absence claim. + +## Shakedown of the tier runs (added 2026-11-28) + + +### IDEA-145 — Narrative report in the style of a deep-research report, with every sentence verified +Status: new · Added: 2026-11-28 · Slice: — · Depends on: the `write` stage and drafts (rf-write, `draft_*`), anchored passages (`factory/document/`), manuscript verification; Living Syllabus `docs/DESIGN.md` (note pipeline) +**What:** a "complete report" output like Gemini Deep Research's: a narrative across threads (which primitive wins where, and why), with a selection playbook, written from the project's read set, where every evidence sentence cites an anchored paragraph and a short quote and passes an independent claim check. The researcher suggested writing it with Gemini, for its larger context window. +**Why:** deep-research reports are getting good at connecting findings across many papers; the factory's reports (`brief note`, `report evidence`, `answers export`) are organised around extracted rows and do not connect threads. Seen on 2026-11-28: a 73-reference Gemini report on linear attention for vision and medical imaging (about 1 h) read well, but 2 references resolved to the wrong paper, one cited an author's homepage, and about 30 pointed to second-hand sites. +**Rigour notes:** narrative sentences are labelled background, evidence or interpretation; evidence sentences must resolve to an anchored paragraph whose text contains the quote (platform check, no model); the claim check runs in a separate session, preferably another model family; report claims from external tools stay leads, never evidence. Build once and share with Living Syllabus notes (outline → draft → check) rather than as a second writer. +**Open questions:** using Gemini needs a ruling: CLAUDE.md says all judgement comes from Claude through MCP; a Gemini CLI session acting as an MCP client would keep the platform model-free but changes that rule; provenance must name the tool and model. Whether the shakedown runs (`la-brief`, `la-deep`, 2026-11-28) show which parts a report needs before building it. + +### IDEA-146 — `brief new` cannot set the autonomy level (shakedown finding) +Status: new · Added: 2026-11-28 · Slice: 9 · Depends on: decision 164 (autonomy levels), `services/project.py::init_project` +**What:** `factory brief new` records the question but has no `--autonomy-level`; `factory init` takes `--tier` and `--autonomy-level` but records no question. An autonomous `brief` or `deep` project with its goal cannot be created from the CLI. The service accepts both (`init_project(..., tier=, autonomy_level=)` then `state_goal`). Found while setting up the first real tier runs. +**Why:** the faster tier path is meant to run like a deep-research tool; its first step should not need a script. +**Rigour notes:** the level is fixed at init (decision 161), so the option belongs on the creating command, not a later one. +**Open questions:** add `--autonomy-level` to `brief new`, or let `init` take the goal. + +### IDEA-147 — A reviewer of another model family in the review loops +Status: new · Added: 2026-11-28 · Slice: 9 · Depends on: the review loops (plan 2026-11-28-review-loops), a decision on the rule that judgement comes from Claude through MCP +**What:** let the reviewer of a review loop (stages `review-frame`, `review-write`), or an extra auditor after it, be a session of another model family: Gemini CLI first, launched headless by the runner as an MCP client of the factory, with its model named in the provenance. Antigravity only if it can run without its interface. +**Why:** two Opus sessions are independent but share the same blind spots; a reviewer of another family catches the misreadings both would make. The researcher asked for it on 2026-11-28. +**Rigour notes:** the platform stays model-free (the reviewer is an outside process, as `claude -p` is); the verdict is recorded with the same validation as any reviewer's; agreement between families is measured, not assumed. +**Open questions:** the ruling on CLAUDE.md's "All judgement comes from Claude through MCP" (shared with IDEA-145); whether Gemini CLI honours an allow-list as strictly as `--allowedTools`; cost and context per round. diff --git a/platform/src/factory/model/runner.py b/platform/src/factory/model/runner.py index d964cec2..4adbca9d 100644 --- a/platform/src/factory/model/runner.py +++ b/platform/src/factory/model/runner.py @@ -29,7 +29,7 @@ STAGE_KEY_RE = ( r"^(screen|extract|appraise|contributions|intuition|spar|ask" r"|frame|gather|acquire|write|understand|develop-lead|develop-draft|develop-critic|maintain" - r"|screen-ft|extract-b|conduct-verify|conduct-audit" + r"|screen-ft|extract-b|conduct-verify|conduct-audit|review-frame|review-write" r"|spar2-(?:search|read|against|for|critic|cover)" r"|mine:m-[a-z0-9]+(?:-[a-z0-9]+)*)$" ) diff --git a/platform/src/factory/services/conductor.py b/platform/src/factory/services/conductor.py index ace44250..27649efd 100644 --- a/platform/src/factory/services/conductor.py +++ b/platform/src/factory/services/conductor.py @@ -366,6 +366,16 @@ def _loop_open(project: Project, trail: _Trail, index: int) -> set[str]: return set() +def disputed_step(project: Project) -> tuple[str, int] | None: + """The open conductor run's id and the first loop step whose escaped loop holds it + (`review-disputed`), if any.""" + trail = _load(project) + if trail is None: + return None + index = _disputed(project, trail, len(trail.meta.steps) - 1) + return None if index is None else (trail.meta.conductor_id, index) + + def _disputed(project: Project, trail: _Trail, upto: int) -> int | None: """The first loop step up to `upto` whose loop escaped with blocking findings open at a tier that does not continue past it, and that no human has released (`review.released`).""" diff --git a/platform/src/factory/services/level_statement.py b/platform/src/factory/services/level_statement.py index 75dfab90..9a0aeddc 100644 --- a/platform/src/factory/services/level_statement.py +++ b/platform/src/factory/services/level_statement.py @@ -187,6 +187,9 @@ def level_statement(project: Project, *, skipped: SkippedSteps | None = None) -> if levels.tier is not None: validation_label = validation_profile(levels.tier, levels.autonomy_level).label lines.extend(_validation_lines(project, levels.tier, levels.autonomy_level)) + from factory.services.review_loop import review_lines # it reads the conductor + + lines.extend(review_lines(project)) reviewed = _person_reviewed(project) if not reviewed: lines.append("no person has reviewed this output") diff --git a/platform/src/factory/services/review_loop.py b/platform/src/factory/services/review_loop.py index 59cf6880..fd5c7839 100644 --- a/platform/src/factory/services/review_loop.py +++ b/platform/src/factory/services/review_loop.py @@ -306,18 +306,54 @@ def review_view(project: Project) -> ReviewView: def release(project: Project, actor: Actor, note: str) -> ReviewReleased: """A human releases the escaped loop at which the conductor paused (`review-disputed`): the run continues with the findings open and labelled. Refused, nothing written, for a non-human - actor or when the conductor is not paused on a disputed loop.""" + actor or when no escaped loop holds the conductor.""" from factory.services import conductor if actor.kind != "human": raise _refuse("actor", "only a human releases a disputed review") with project.writing(): - status = conductor.conductor_status(project) - if status.state != "paused" or status.reason != "review-disputed": - raise _refuse("conductor", "the conductor is not paused on a disputed review") - step = status.steps.index(status.stage_id or "") + held = conductor.disputed_step(project) + if held is None: + raise _refuse("conductor", "no review loop holds the conductor") payload = ReviewReleased( - conductor_id=status.conductor_id or "", step=step, note=note.strip() or "released" + conductor_id=held[0], step=held[1], note=note.strip() or "released" ) project.record([project.events.make("review.released", payload, actor)]) return payload + + +def review_lines(project: Project) -> list[str]: + """The level-statement lines of the review loops that ended (`conductor.review_ended`): one per + loop, with each open blocking finding and its text, and a line saying the protocol gates did + not bind where the tier unbinds them.""" + from factory.model.conductor import ConductorReviewEnded + from factory.services.conductor import TIER_UNBOUND_GATES + from factory.services.project import project_levels + + lines: list[str] = [] + ended = [ + ConductorReviewEnded.model_validate(e.payload) + for e in read_typed(project.paths.events_dir, project.catalog, ("conductor.review_ended",)) + if e.actor.kind == "system" + ] + for end in ended: + rounds = f"{end.rounds} round{'s' if end.rounds > 1 else ''}" + if end.outcome == "accepted": + lines.append(f"agent review of {end.stage_id}: accepted after {rounds}") + continue + texts = { + f.finding_id: f"{f.target}: {f.text}" + for v in verdicts(project, end.conductor_id, end.step) + for f in v.findings + } + open_text = "; ".join(f"{i} ({texts.get(i, '')})" for i in end.open_findings) + lines.append( + f"agent review of {end.stage_id}: ended without agreement ({end.reason}) after " + f"{rounds}; blocking findings left open: {open_text}" + ) + tier = project_levels(project).tier + if ended and tier is not None and TIER_UNBOUND_GATES.get(tier.value): + lines.append( + f"protocol gates do not bind a {tier.value} review: no person confirmed the protocol" + ) + return lines diff --git a/platform/src/factory/services/runner.py b/platform/src/factory/services/runner.py index 24d8e0cc..1459723b 100644 --- a/platform/src/factory/services/runner.py +++ b/platform/src/factory/services/runner.py @@ -40,10 +40,12 @@ writes `spar.role_started` with `runner.started`. After a run ends, the watcher advances a begun v2 request to its next role; a failed role stops the chain. - The stages `frame`, `gather`, `acquire`, `write`, `understand`, `develop-lead`, `develop-draft`, - `develop-critic`, `maintain`, `conduct-verify` and `conduct-audit` (plan - tiers-and-autonomy C8) are started only by the conductor (`services/conductor.py`): one unit per - run, Sonnet, an allow-list that leaves out the gate acts of the stage (no confirm, release, - amend or PRESS review), and the verifier and auditor read only. Their pending unit is the + `develop-critic`, `maintain`, `conduct-verify`, `conduct-audit`, `review-frame` and + `review-write` (plan tiers-and-autonomy C8; review loops, plan 2026-11-28-review-loops) are + started only by the conductor (`services/conductor.py`): one unit per run, Sonnet (Opus for + `frame`, `write` and their reviewers), an allow-list that leaves out the gate acts of the stage + (no confirm, release, amend or PRESS review), the verifier and auditor read only, and a + reviewer writes only its verdict (`review_record`). Their pending unit is the conductor's current step. The runner records no human act. - Stages: `screen`, `extract`, `appraise`, `contributions`, `intuition` and `mine:`; the derivation of which apply and the pipeline over them are in `factory.services.pipeline`. The @@ -392,6 +394,19 @@ class StageSpec: f"{_P}ledger_view", f"{_P}trace", ) +_REVIEW_TOOLS: Final = ( + *_CONDUCT_READ, + f"{_P}question_view", + f"{_P}seed_list", + f"{_P}protocol_view", + f"{_P}term_list", + f"{_P}draft_list", + f"{_P}draft_status", + f"{_P}draft_render", + f"{_P}chat_verify", + *_REVIEW_RECORD, +) +"""Both reviewers' tools (`rf-review` names the reads of either step): reads, and the verdict.""" STAGES.update( { # Lifecycle stages run by the conductor (`services/conductor.py`, plan tiers-and-autonomy @@ -597,14 +612,7 @@ class StageSpec: model=OPUS, skill="rf-review", role="verifier", - tools=( - f"{_P}project_status", - f"{_P}question_view", - f"{_P}seed_list", - f"{_P}protocol_view", - f"{_P}term_list", - *_REVIEW_RECORD, - ), + tools=_REVIEW_TOOLS, kinds=(), unit="review round", fixed_cap=1, @@ -613,15 +621,7 @@ class StageSpec: model=OPUS, skill="rf-review", role="verifier", - tools=( - *_CONDUCT_READ, - f"{_P}question_view", - f"{_P}draft_list", - f"{_P}draft_status", - f"{_P}draft_render", - f"{_P}chat_verify", - *_REVIEW_RECORD, - ), + tools=_REVIEW_TOOLS, kinds=(), unit="review round", fixed_cap=1, diff --git a/platform/tests/test_conductor.py b/platform/tests/test_conductor.py index eb706669..3f2992ae 100644 --- a/platform/tests/test_conductor.py +++ b/platform/tests/test_conductor.py @@ -94,6 +94,13 @@ def stages(self) -> list[str]: return [c[0] for c in self.calls] +@pytest.fixture(autouse=True) +def _frame_gates_bind(monkeypatch: pytest.MonkeyPatch) -> None: + """These tests exercise the gate mechanics through the frame step's protocol gates; a brief + unbinds them (`TIER_UNBOUND_GATES`, tested in `test_review_loop.py`).""" + monkeypatch.setattr(conductor, "TIER_UNBOUND_GATES", {}) + + @pytest.fixture(autouse=True) def automatic_calls(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, int]]: """Stands for the platform's deterministic step (`default_automatic`): records the calls.""" @@ -497,10 +504,10 @@ def test_roles_are_separate_runs_when_an_agent_closes_the_gate( monkeypatch.setattr(gates, "effective_policy", policy(PolicyKind.AGENT)) project = make(settings, clock, "autonomous") - conductor.begin_conductor(project, plan("write")) + conductor.begin_conductor(project, plan("gather")) # write has a review loop status = drive(project, fake) assert status.state == "finished" - assert fake.stages == ["write", "conduct-verify", "conduct-audit"] + assert fake.stages == ["gather", "conduct-verify", "conduct-audit"] assert len({c[2] for c in fake.calls}) == 3 roles = [e.payload["role"] for e in _events(project, "conductor.step_started")] assert roles == ["proposer", "verifier", "auditor"] @@ -524,9 +531,9 @@ def test_no_role_run_for_a_human_only_gate( monkeypatch.setattr(gates, "effective_policy", policy(PolicyKind.HUMAN)) project = make(settings, clock, "autonomous") - conductor.begin_conductor(project, plan("write")) + conductor.begin_conductor(project, plan("gather")) status = drive(project, fake, gate_closed=lambda *_a: False) - assert status.state == "waiting" and fake.stages == ["write"] + assert status.state == "waiting" and fake.stages == ["gather"] # ------------------------------------------------------------------- the log and the runner @@ -582,7 +589,9 @@ def test_the_stages_are_declared_without_the_gate_acts() -> None: assert re.match(STAGE_KEY_RE, key) and runner.is_stage_key(key) if key == "extract-b": # a work queue of its own: see the second-pass tests continue - assert spec.model == "claude-sonnet-5-5" and spec.fixed_cap == 1 + judged = ("frame", "write", "review-frame", "review-write") + assert spec.model == (runner.OPUS if key in judged else "claude-sonnet-5-5") + assert spec.fixed_cap == 1 assert all(t.startswith("mcp__factory__") for t in spec.tools) assert not [t for t in spec.tools if re.search(r"release|press|amend|confirm|decide", t)] for key in ("conduct-verify", "conduct-audit"): @@ -592,8 +601,15 @@ def test_the_stages_are_declared_without_the_gate_acts() -> None: if t.endswith(("_record", "_write", "_propose", "_create", "_run", "_fetch")) ] assert writes == [] + for key in ("review-frame", "review-write"): # a reviewer writes its verdict alone + writes = [ + t + for t in runner.STAGES[key].tools + if t.endswith(("_record", "_write", "_propose", "_create", "_run", "_fetch", "_reply")) + ] + assert writes == ["mcp__factory__review_record"] assert {runner.STAGES[k].skill for k in ("frame", "gather", "acquire")} == { - "rf-frame", + "rf-frame-conducted", "rf-search-run", "rf-acquire", } @@ -913,10 +929,10 @@ def test_the_conductor_draws_the_platform_audit_before_the_auditor_starts( lambda _p, stage: drawn.append((stage, len(fake.stages))) or [], ) project = make(settings, clock, "autonomous") - conductor.begin_conductor(project, plan("write")) + conductor.begin_conductor(project, plan("gather")) assert drive(project, fake).state == "finished" - assert drawn == [("write", 2)] # after proposer and verifier, before the auditor run - assert fake.stages == ["write", "conduct-verify", "conduct-audit"] + assert drawn == [("gather", 2)] # after proposer and verifier, before the auditor run + assert fake.stages == ["gather", "conduct-verify", "conduct-audit"] # ------------------------------------------- a queue step runs again until its queue is empty diff --git a/platform/tests/test_review_loop.py b/platform/tests/test_review_loop.py index 13e2cd98..b5c7e334 100644 --- a/platform/tests/test_review_loop.py +++ b/platform/tests/test_review_loop.py @@ -303,7 +303,7 @@ def test_a_reply_must_answer_every_blocking_finding( _revise(project, reviewer, _blocking("a"), _blocking("b")) _step(project, runs) # the proposer's revision one = [Reply(finding_id="R1.F1", action="addressed", note="done")] - with pytest.raises(FactoryValidationError, match="unanswered: R1.F2"): + with pytest.raises(FactoryValidationError, match=r"unanswered: R1\.F2"): review_loop.record_reply(project, proposer, one) stray = [*one, Reply(finding_id="R1.F2", action="declined", note="n"), Reply(finding_id="R9.F1", action="declined", note="n")] # fmt: skip @@ -428,3 +428,21 @@ def test_the_frame_fingerprint_is_stable(settings: Settings, clock: FixedClock) first = _REAL_FINGERPRINT(project, "frame") assert first == _REAL_FINGERPRINT(project, "frame") and len(first) == 64 assert _REAL_FINGERPRINT(project, "write") != first + + +def test_the_level_statement_names_the_findings_left_open( + settings: Settings, clock: FixedClock, reviewer: Actor, proposer: Actor +) -> None: + from factory.services.level_statement import level_statement + + project = _make(settings, clock, "brief") + runs = Runs() + conductor.begin_conductor(project, _plan(Tier.BRIEF, "frame", "gather")) + _loop_to(project, runs, reviewer, proposer, review_loop.MAX_ROUNDS) + _step(project, runs) + lines = level_statement(project).lines + assert ( + "agent review of frame: ended without agreement (max-rounds) after 5 rounds; blocking " + "findings left open: R5.F1 (queries: round 5)" in lines + ) + assert "protocol gates do not bind a brief review: no person confirmed the protocol" in lines diff --git a/platform/tests/test_tier_protocol.py b/platform/tests/test_tier_protocol.py new file mode 100644 index 00000000..c99bbe81 --- /dev/null +++ b/platform/tests/test_tier_protocol.py @@ -0,0 +1,84 @@ +"""`protocol_from_template` (plan 2026-11-28-review-loops): the tier's protocol template recorded +from the criteria and queries a conducted frame session gives.""" + +from __future__ import annotations + +import pytest + +from factory.clock import FixedClock +from factory.config import Settings +from factory.errors import FactoryValidationError +from factory.events.envelope import Actor +from factory.model.protocol import Criterion, PlannedQuery, ScreeningStage +from factory.model.search import QueryKind +from factory.services import tier_protocol +from factory.services.context import Project +from factory.services.project import init_project +from factory.services.protocol import current_protocol +from factory.services.question import record_question, state_goal +from tests.helpers import SESSION, pilot_question_spec + + +def _project(settings: Settings, clock: FixedClock, tier: str = "brief") -> Project: + return init_project( + settings, "demo", None, session=SESSION, clock=clock, tier=tier, + autonomy_level="autonomous", + ) # fmt: skip + + +def _criteria() -> list[Criterion]: + return [ + Criterion(id="IN01", statement="linear-time attention for vision", + rule="the title or abstract names a sub-quadratic token mixer used on images", + applies_at=ScreeningStage.EITHER), + Criterion(id="EX01", statement="language only", rule="no image or video data", priority=1, + applies_at=ScreeningStage.EITHER), + ] # fmt: skip + + +def _q(source: str, text: str = "linear attention vision mamba rwkv") -> PlannedQuery: + return PlannedQuery(source=source, kind=QueryKind.KEYWORD, text=text) + + +def _question(project: Project, agent: Actor) -> None: + state_goal(project, agent, "Which linear attention primitive works best for vision?") + record_question(project, agent, pilot_question_spec()) + + +def test_the_brief_template_is_recorded_as_a_draft( + settings: Settings, clock: FixedClock, agent: Actor +) -> None: + project = _project(settings, clock) + _question(project, agent) + result = tier_protocol.record_from_template( + project, agent, _criteria(), [_q("openalex"), _q("arxiv")] + ) + assert result.created and result.status.value == "draft" + spec = current_protocol(project) + assert spec is not None + assert [s.name for s in spec.spec.sources] == ["openalex", "arxiv"] + assert spec.spec.screening.stop_after_consecutive_excludes == 10 + reviewer = spec.spec.screening.reviewers[0] + assert (reviewer.actor, reviewer.kind) == ("obd", "human") # the creator, not the agent + + +@pytest.mark.parametrize( + "queries", + [[_q("openalex"), _q("openalex", "second")], [_q("pubmed")]], +) +def test_queries_the_template_does_not_allow_are_refused( + settings: Settings, clock: FixedClock, agent: Actor, queries: list[PlannedQuery] +) -> None: + project = _project(settings, clock) + _question(project, agent) + with pytest.raises(FactoryValidationError): + tier_protocol.record_from_template(project, agent, _criteria(), queries) + assert current_protocol(project) is None + + +def test_no_question_or_no_template_is_refused( + settings: Settings, clock: FixedClock, agent: Actor +) -> None: + project = _project(settings, clock) + with pytest.raises(FactoryValidationError, match="question first"): + tier_protocol.record_from_template(project, agent, _criteria(), [_q("openalex")]) diff --git a/platform/tests/test_tiers_walking_skeleton.py b/platform/tests/test_tiers_walking_skeleton.py index f9eda8e5..50335c3c 100644 --- a/platform/tests/test_tiers_walking_skeleton.py +++ b/platform/tests/test_tiers_walking_skeleton.py @@ -73,13 +73,12 @@ `screen-ft` the full-text phase after `acquire`, `extract-b` the second-pass run of the extract step (a separate run and session; the plan's `second_pass` data asks for it).""" HUMAN_GATES = { - "protocol.ready", - "protocol.press_confirm", "import.resolution_confirm", "manuscript.citation_confirm", } """The gates the conductor keeps for a person at `attended` (`conductor.STEP_GATES` minus the ones -the exploratory presets already leave to an agent).""" +the exploratory presets already leave to an agent, and minus the protocol gates, which do not bind +a brief: `conductor.TIER_UNBOUND_GATES`).""" TITLES = ( "Linear attention for vision transformers", @@ -417,10 +416,11 @@ def test_the_second_pass_is_a_separate_run_in_a_separate_session(skeleton: Skele def test_a_human_only_gate_made_the_conductor_wait(skeleton: Skeleton) -> None: project = skeleton.project first = skeleton.waits[0] - assert first[0] == "frame" and first[1] in {"protocol.ready", "protocol.press_confirm"} - assert first[2] == 1 # only the frame run had started: no run for a human gate, none after it + # No protocol gate binds a brief (`conductor.TIER_UNBOUND_GATES`): the first wait is gather's. + assert first[0] == "gather" and first[1] == "import.resolution_confirm" + assert first[2] == 2 # frame and gather had started: no run for a human gate, none after it assert {gate for _, gate, _ in skeleton.waits} <= HUMAN_GATES - assert {stage for stage, _, _ in skeleton.waits} <= {"frame", "gather", "write"} + assert {stage for stage, _, _ in skeleton.waits} <= {"gather", "write"} paused = [e for e in _events(project) if e.type == "conductor.paused"] assert len(paused) == len(skeleton.waits) assert {e.payload["reason"] for e in paused} == {"human-gate"} diff --git a/plugin/skills/rf-frame-conducted/SKILL.md b/plugin/skills/rf-frame-conducted/SKILL.md index 84c9f3d0..e238a682 100644 --- a/plugin/skills/rf-frame-conducted/SKILL.md +++ b/plugin/skills/rf-frame-conducted/SKILL.md @@ -33,7 +33,8 @@ Pass `project`, `role` (`proposer`), `model` (your model id) and the bare skill at most its queries per source; `project_status` and the refusal say which). - Criteria: `IN01`, ... and `EX01`, ... each with `statement`, an operational `rule` a screener can apply to a title and abstract, `applies_at` (`title-abstract`, `full-text` or `either`) - and `parent` (the slot, non-goal or sub-question it serves). Cover every sub-question. + and `parent` (the slot, non-goal or sub-question it serves); an exclusion also takes a + `priority` (1 is checked first). Cover every sub-question. - Queries: one `keyword` query per source per allowed slot, each covering every family or concept the goal names; a query that leaves one out is the first thing a reviewer flags. 6. Do not set the protocol ready, run a PRESS review, or record a decision: in a conducted brief or From a08a7c09198a3a8fd869eff3a05429a6875f02b8 Mon Sep 17 00:00:00 2001 From: Alex Date: Sat, 28 Nov 2026 21:30:22 +0200 Subject: [PATCH 03/16] fix(conductor): a brief protocol is ready at once; a blocked queue step pauses Shakedown la-brief-2 finished all 8 steps with no screened, extracted or written output: - screening was refused (R-16: protocol not ready) because protocol_from_template recorded a draft and nobody can make it ready in a conducted brief. At brief and deep (frame gates unbound) it now records the protocol ready; a later call is an amendment with a reason naming the findings and an effect per changed criterion (semantic is computed). Other tiers still record a draft. - the conductor took a queue step whose runs worked off no unit as done, so every later step completed empty. A queue step that never made progress and has units pending now pauses 'blocked'; --retry runs it again. A run that stops making progress after an earlier one did is still a stopping rule. - rf-review: a source without a query, a goal concept missing from the queries, a missing output and an unsupported sentence are always blocking. rf-frame-conducted: a query on every template source; revisions amend the ready protocol. Co-Authored-By: Claude Opus 5.5 --- docs/MAP.md | 2 +- platform/src/factory/mcp/server.py | 17 +++++- platform/src/factory/model/conductor.py | 1 + platform/src/factory/services/conductor.py | 37 +++++++++++- .../src/factory/services/tier_protocol.py | 56 +++++++++++++++++-- platform/tests/test_conductor.py | 30 ++++++++-- platform/tests/test_review_loop.py | 27 +++++++++ platform/tests/test_tier_protocol.py | 43 +++++++++++++- plugin/skills/rf-frame-conducted/SKILL.md | 13 +++-- plugin/skills/rf-review/SKILL.md | 4 ++ 10 files changed, 209 insertions(+), 21 deletions(-) diff --git a/docs/MAP.md b/docs/MAP.md index 1fbc6697..f0d2ea7e 100644 --- a/docs/MAP.md +++ b/docs/MAP.md @@ -2,7 +2,7 @@ -Generated at commit `b57a7078` · projection version `96` · 52 stage modules · 241 event types · 235 index tables · 352 service modules · 223 MCP tools · 415 CLI commands · 40 skills. +Generated at commit `502a0a57` · projection version `96` · 52 stage modules · 241 event types · 235 index tables · 352 service modules · 223 MCP tools · 415 CLI commands · 40 skills. Read [ARCHITECTURE.md](ARCHITECTURE.md) first. This file answers *where*: for each stage module, the events, models, index files, tables, task kinds, gates and checks it owns, and the services that name its events; then every MCP tool, CLI command, service and skill with what it reaches. Links are found by name (see the script's docstring), so a missing link means the code does not name the thing, not that no relation exists. Paths are relative to `platform/src/factory/` unless they start with `plugin/`. diff --git a/platform/src/factory/mcp/server.py b/platform/src/factory/mcp/server.py index 214fa1e5..c462d51c 100644 --- a/platform/src/factory/mcp/server.py +++ b/platform/src/factory/mcp/server.py @@ -1014,14 +1014,19 @@ def protocol_from_template( role: str, model: str, skill: str, + reason: str = "", + effects: dict[str, str] | None = None, ) -> dict[str, JsonValue]: """Record the protocol of the project's tier from its template: you give the criteria and the planned queries, the platform fills sources, screening, extraction schema and snowball plan, enforces the template's sources and queries per source, and names the project's - creator as reviewer of record. Recorded as a draft. Gaps are returned.""" + creator as reviewer of record. At brief and deep (run without a person) it is recorded + ready so screening can start, and a later call is an amendment: give `reason` (the review + finding ids it answers) and `effects`, one of `loosened`, `tightened` or `clarified` per + changed criterion id. At other tiers it is recorded as a draft. Gaps are returned.""" def record() -> JsonValue: - from factory.model.protocol import Criterion, PlannedQuery + from factory.model.protocol import Criterion, CriterionEffect, PlannedQuery from factory.services import tier_protocol opened = open_project(settings, project, session=session, clock=clock) @@ -1032,8 +1037,14 @@ def record() -> JsonValue: parsed_queries = [ parse_input(PlannedQuery, q, f"queries.{i}") for i, q in enumerate(queries) ] + try: + declared = {k: CriterionEffect(v) for k, v in (effects or {}).items()} + except ValueError as exc: + raise FactoryValidationError( + [ValidationIssue("effects", "loosened, tightened or clarified")] + ) from exc result = tier_protocol.record_from_template( - opened, actor, parsed_criteria, parsed_queries + opened, actor, parsed_criteria, parsed_queries, reason=reason, effects=declared ) data = result.model_dump(mode="json") data["gaps"] = [ diff --git a/platform/src/factory/model/conductor.py b/platform/src/factory/model/conductor.py index e35b9b5b..ba66477c 100644 --- a/platform/src/factory/model/conductor.py +++ b/platform/src/factory/model/conductor.py @@ -43,6 +43,7 @@ "refused", "review-disputed", "review-missing", + "blocked", ] ReviewOutcome = Literal["accepted", "escaped"] ReviewEndReason = Literal["accepted", "max-rounds", "no-progress", "repeat"] diff --git a/platform/src/factory/services/conductor.py b/platform/src/factory/services/conductor.py index 27649efd..ecfa6795 100644 --- a/platform/src/factory/services/conductor.py +++ b/platform/src/factory/services/conductor.py @@ -313,12 +313,41 @@ def _more_to_run(project: Project, trail: _Trail, index: int, step: str) -> bool return 0 < last.pending < started.pending and not queue_cap_reached(project, step) +def _blocked(trail: _Trail, index: int, step: str) -> bool: + """Whether a queue step is blocked: its proposer runs are all complete, none of them worked off + a unit, and units are still pending. (A run that makes no progress after an earlier one did is + a stopping rule, and the step is complete; one that never made any is refused work, as a + protocol that is not ready, and must not pass as done.)""" + if step not in _QUEUE_UNITS: + return False + started = { + e.payload.get("run_id"): ConductorStepStarted.model_validate(e.payload) + for e in trail.payloads("step_started") + if e.payload["step"] == index and e.payload["role"] == "proposer" + } + finished = [ + ConductorStepFinished.model_validate(e.payload) + for e in trail.payloads("step_finished") + if e.payload["step"] == index and e.payload["role"] == "proposer" + ] + runs = [f for f in finished if f.run_id is not None and f.run_id in started] + if not runs or any(f.outcome != "complete" for f in runs): + return False + for f in runs: + before = started[f.run_id].pending + if before is None or f.pending is None or f.pending < before: + return False + return (runs[-1].pending or 0) > 0 + + def _effective_closed(project: Project, trail: _Trail) -> set[tuple[int, str]]: """`_closed_roles`, minus the proposer of a queue step that must run again (`_more_to_run`), and adjusted for the round of a review loop (`_loop_open`).""" closed = _closed_roles(trail) for index, step in enumerate(trail.meta.steps): - if (index, "proposer") in closed and _more_to_run(project, trail, index, step): + if (index, "proposer") in closed and ( + _more_to_run(project, trail, index, step) or _blocked(trail, index, step) + ): closed.discard((index, "proposer")) if review_loop.is_loop_step(step): closed -= {(index, r) for r in _loop_open(project, trail, index)} @@ -594,6 +623,12 @@ def _decide( if waiting_gate is not None: return _Decision("wait", index, stage_id, None, "human-gate", waiting_gate, f"gate {waiting_gate} awaits a human") # fmt: skip + if role == "proposer" and not retry and _blocked(trail, index, stage_id): + return _Decision( + "pause", index, stage_id, role, "blocked", + detail=f"the {stage_id} run worked off no unit and units are pending; see its log, " + "fix the cause and advance with retry", + ) # fmt: skip disputed = _disputed(project, trail, index) if disputed is not None: return _Decision( diff --git a/platform/src/factory/services/tier_protocol.py b/platform/src/factory/services/tier_protocol.py index af230f53..a38a9e7e 100644 --- a/platform/src/factory/services/tier_protocol.py +++ b/platform/src/factory/services/tier_protocol.py @@ -10,19 +10,35 @@ more per source than `queries_per_source`). - The reviewer of record is the human who created the project (the actor of `project.created`), never the agent that calls the tool. -- The protocol is recorded as a draft (`ready` false): readiness stays a human's act. +- At a tier whose protocol gates do not bind the conductor (`conductor.TIER_UNBOUND_GATES`: brief + and deep, run without a person), the protocol is recorded ready, so screening can start (R-16); + a later call is an amendment of the ready protocol with a reason naming the review findings it + answers and an effect per changed criterion (`protocol.amend_protocol`; `semantic` is computed, + never typed). At other tiers it is recorded as a draft: readiness stays a human's act. """ from __future__ import annotations -from collections.abc import Sequence +from collections.abc import Mapping, Sequence from factory.errors import FactoryValidationError, ValidationIssue from factory.events.envelope import Actor from factory.events.reader import read_typed -from factory.model.protocol import Criterion, PlannedQuery +from factory.model.protocol import ( + ChangeKind, + Criterion, + CriterionEffect, + PlannedQuery, + ProtocolStatus, +) from factory.services.context import Project -from factory.services.protocol import ProtocolResult, record_protocol +from factory.services.protocol import ( + ProtocolResult, + amend_protocol, + current_protocol, + record_protocol, +) +from factory.services.protocol_rules import criterion_changes, other_changes from factory.services.question import current_question @@ -42,7 +58,11 @@ def record_from_template( actor: Actor, criteria: Sequence[Criterion], queries: Sequence[PlannedQuery], + *, + reason: str = "", + effects: Mapping[str, CriterionEffect] | None = None, ) -> ProtocolResult: + from factory.services.conductor import TIER_UNBOUND_GATES from factory.services.project import project_levels from factory.tiers.plans import PLANS @@ -61,4 +81,30 @@ def record_from_template( ) except ValueError as exc: raise _refuse("queries", str(exc)) from exc - return record_protocol(project, actor, spec, ready=False) + if tier.value not in TIER_UNBOUND_GATES: + return record_protocol(project, actor, spec, ready=False) + current = current_protocol(project) + if current is None or current.status is not ProtocolStatus.READY: + return record_protocol(project, actor, spec, ready=True) + if current.spec == spec: + return ProtocolResult( + protocol_id=current.protocol_id, status=current.status, created=False, gaps=[] + ) + if not reason.strip(): + raise _refuse( + "reason", + "the protocol is ready: a change is an amendment; name the findings it answers", + ) + declared = dict(effects or {}) + changes = criterion_changes(current.spec, spec) + semantic = bool( + other_changes(current.spec, spec) + or any(kind is not ChangeKind.CHANGED for _, kind in changes) + or any(declared.get(cid) is not CriterionEffect.CLARIFIED for cid, _ in changes) + ) + result = amend_protocol( + project, actor, spec, reason=reason, semantic=semantic, effects=declared + ) + return ProtocolResult( + protocol_id=result.to_version, status=ProtocolStatus.READY, created=True, gaps=[] + ) diff --git a/platform/tests/test_conductor.py b/platform/tests/test_conductor.py index 3f2992ae..09fbf6e6 100644 --- a/platform/tests/test_conductor.py +++ b/platform/tests/test_conductor.py @@ -256,8 +256,8 @@ def test_screen_runs_twice_around_acquire_with_its_own_step_keys( asked: list[str] = [] def pending(_p: Project, stage: str) -> dict[str, int]: - asked.append(stage) - return {stage: 1 if stage.startswith("screen") else 0} + asked.append(stage) # one unit for each screen phase until its run has worked it off + return {stage: 1 if stage.startswith("screen") and stage not in fake.stages else 0} for _ in range(12): status = conductor.advance( @@ -837,7 +837,8 @@ def automatic(_p: Project, limit: int) -> None: conductor.begin_conductor(project, plan_) for _ in range(12): status = conductor.advance( - project, start_run=start, pending=_busy, gate_closed=_open, automatic=automatic, + project, start_run=start, gate_closed=_open, automatic=automatic, + pending=lambda _p, stage: {stage: 0 if stage in order else 1}, escalate=lambda *_a: None, ) # fmt: skip if status.state == "finished": @@ -982,11 +983,28 @@ def test_a_queue_step_runs_again_while_units_are_pending_and_progress_is_made( assert queue.left == 0 -def test_a_queue_step_stops_when_a_run_made_no_progress(project: Project, fake: FakeRunner) -> None: +def test_a_queue_step_that_never_made_progress_pauses_as_blocked( + project: Project, fake: FakeRunner +) -> None: + """A first run that works off no unit was refused its work (shakedown la-brief-2: the protocol + was not ready); a stopping rule needs screening first, so it is never this case.""" conductor.begin_conductor(project, plan("screen")) - queue = Queue(fake, 70, per_run=0) # e.g. a stopping rule: units remain, nothing is served + queue = Queue(fake, 70, per_run=0) status = _run_screen(project, fake, queue) - assert status.state == "finished" and fake.stages == ["screen"] + assert status.state == "paused" and status.reason == "blocked" and fake.stages == ["screen"] + + +def test_a_queue_step_stops_when_a_later_run_made_no_progress( + project: Project, fake: FakeRunner +) -> None: + class Stops(Queue): # a stopping rule after the first run: units remain, none is served + def start_run(self, project: Project, stage: str, *, unit_cap: int) -> str: + self.per_run = 30 if self.runs == 0 else 0 + return super().start_run(project, stage, unit_cap=unit_cap) + + conductor.begin_conductor(project, plan("screen")) + status = _run_screen(project, fake, Stops(fake, 70)) + assert status.state == "finished" and fake.stages == ["screen", "screen"] def test_a_queue_step_stops_at_the_tier_cap( diff --git a/platform/tests/test_review_loop.py b/platform/tests/test_review_loop.py index b5c7e334..46a96cde 100644 --- a/platform/tests/test_review_loop.py +++ b/platform/tests/test_review_loop.py @@ -446,3 +446,30 @@ def test_the_level_statement_names_the_findings_left_open( "findings left open: R5.F1 (queries: round 5)" in lines ) assert "protocol gates do not bind a brief review: no person confirmed the protocol" in lines + + +# ------------------------------------------------------------------- a blocked queue step + + +def test_a_queue_step_that_works_off_nothing_pauses_as_blocked( + settings: Settings, clock: FixedClock +) -> None: + """Shakedown la-brief-2: screening was refused (protocol not ready); the run ended with every + record still pending and the conductor took the step as done.""" + project = _make(settings, clock, "brief") + runs = Runs() + conductor.begin_conductor(project, _plan(Tier.BRIEF, "screen", "extract")) + + def busy(_p: Project, stage: str) -> dict[str, int]: + return {stage: 2359} + + def step(retry: bool = False) -> conductor.ConductorStatus: + return conductor.advance(project, retry=retry, start_run=runs.start, pending=busy, + gate_closed=_open, reconcile=lambda _p: []) # fmt: skip + + step() + status = step() + assert status.state == "paused" and status.reason == "blocked" + assert runs.stages == ["screen"] + status = step(retry=True) + assert status.state == "running" and runs.stages == ["screen", "screen"] diff --git a/platform/tests/test_tier_protocol.py b/platform/tests/test_tier_protocol.py index c99bbe81..0c2df91b 100644 --- a/platform/tests/test_tier_protocol.py +++ b/platform/tests/test_tier_protocol.py @@ -53,7 +53,7 @@ def test_the_brief_template_is_recorded_as_a_draft( result = tier_protocol.record_from_template( project, agent, _criteria(), [_q("openalex"), _q("arxiv")] ) - assert result.created and result.status.value == "draft" + assert result.created and result.status.value == "ready" # no person makes it ready (R-16) spec = current_protocol(project) assert spec is not None assert [s.name for s in spec.spec.sources] == ["openalex", "arxiv"] @@ -82,3 +82,44 @@ def test_no_question_or_no_template_is_refused( project = _project(settings, clock) with pytest.raises(FactoryValidationError, match="question first"): tier_protocol.record_from_template(project, agent, _criteria(), [_q("openalex")]) + + +def test_a_revision_of_a_ready_brief_protocol_is_an_amendment( + settings: Settings, clock: FixedClock, agent: Actor +) -> None: + from factory.model.protocol import CriterionEffect, ProtocolStatus + + project = _project(settings, clock) + _question(project, agent) + first = tier_protocol.record_from_template(project, agent, _criteria(), [_q("arxiv")]) + assert first.status is ProtocolStatus.READY # a brief runs without a person: R-16 + both = [_q("openalex"), _q("arxiv")] + with pytest.raises(FactoryValidationError, match="amendment"): + tier_protocol.record_from_template(project, agent, _criteria(), both) + amended = tier_protocol.record_from_template( + project, agent, _criteria(), both, reason="R1.F1: add the OpenAlex query" + ) + assert amended.created and amended.status is ProtocolStatus.READY + current = current_protocol(project) + assert current is not None and [q.source for q in current.spec.queries] == ["openalex", "arxiv"] + criteria = _criteria() + criteria[0] = criteria[0].model_copy(update={"rule": "names a sub-quadratic mixer on images"}) + with pytest.raises(FactoryValidationError, match="effects"): + tier_protocol.record_from_template(project, agent, criteria, both, reason="R2.F1") + tier_protocol.record_from_template( + project, agent, criteria, both, reason="R2.F1", + effects={"IN01": CriterionEffect.CLARIFIED}, + ) # fmt: skip + + +def test_where_the_protocol_gates_bind_it_stays_a_draft( + settings: Settings, clock: FixedClock, agent: Actor, monkeypatch: pytest.MonkeyPatch +) -> None: + from factory.model.protocol import ProtocolStatus + from factory.services import conductor + + monkeypatch.setattr(conductor, "TIER_UNBOUND_GATES", {}) # as at pilot and systematic + project = _project(settings, clock) + _question(project, agent) + result = tier_protocol.record_from_template(project, agent, _criteria(), [_q("openalex")]) + assert result.status is ProtocolStatus.DRAFT diff --git a/plugin/skills/rf-frame-conducted/SKILL.md b/plugin/skills/rf-frame-conducted/SKILL.md index e238a682..272aecaa 100644 --- a/plugin/skills/rf-frame-conducted/SKILL.md +++ b/plugin/skills/rf-frame-conducted/SKILL.md @@ -35,10 +35,15 @@ Pass `project`, `role` (`proposer`), `model` (your model id) and the bare skill can apply to a title and abstract, `applies_at` (`title-abstract`, `full-text` or `either`) and `parent` (the slot, non-goal or sub-question it serves); an exclusion also takes a `priority` (1 is checked first). Cover every sub-question. - - Queries: one `keyword` query per source per allowed slot, each covering every family or - concept the goal names; a query that leaves one out is the first thing a reviewer flags. -6. Do not set the protocol ready, run a PRESS review, or record a decision: in a conducted brief or - deep review those do not bind, and readiness is a human's act. + - Queries: one `keyword` query on **every** source the template names (up to its queries per + source), each covering every family or concept the goal names; a source without a query, or + a query that leaves a concept out, is a blocking finding. + - At brief and deep the protocol is recorded ready (screening needs it). In a revision, call + `protocol_from_template` again with the corrected criteria and queries, a `reason` naming + the finding ids it answers, and `effects` (`loosened`, `tightened` or `clarified`) for each + criterion whose text changed: it is recorded as an amendment. +6. Do not run a PRESS review or record a decision: in a conducted brief or deep review those do + not bind. 7. In a revision, answer every blocking finding with `review_reply`: `addressed` with what you changed, or `declined` with the reason (for example: the goal does not ask for it). 8. End with a short report: the question id, the seeds added, the protocol id and gaps, the diff --git a/plugin/skills/rf-review/SKILL.md b/plugin/skills/rf-review/SKILL.md index 3526aaf4..f2de6eb2 100644 --- a/plugin/skills/rf-review/SKILL.md +++ b/plugin/skills/rf-review/SKILL.md @@ -33,6 +33,10 @@ Pass `project`, `role` (`verifier`), `model` (your model id) and the bare skill sentence); `text` (what is wrong and what would fix it, concretely). A finding that restates an earlier one still open names it in `repeats`. Do not re-raise a finding the proposer declined with a sound reason; do not raise taste as blocking. + Always blocking, whatever else holds: a source the protocol lists with no query on it; a + family, concept or setting the goal names that a query or sub-question leaves out; a step + output that does not exist (no draft, no question); an evidence sentence its passage does not + support. 4. Verdict with `review_record`: `accept` when no blocking finding is left (minor ones may be listed), else `revise`. One short `summary`: what you checked and what holds. 5. End with a short report: the verdict, the findings by id, and any refusal verbatim. From c1e701c0e872faa9cc9eae9fd372edce6e4db5e1 Mon Sep 17 00:00:00 2001 From: Alex Date: Sat, 28 Nov 2026 21:32:47 +0200 Subject: [PATCH 04/16] fix: fingerprint in review_output (writing-import rule); tool list test Co-Authored-By: Claude Opus 5.5 --- docs/MAP.md | 3 +- platform/src/factory/services/review_loop.py | 48 ++-------------- .../src/factory/services/review_output.py | 56 +++++++++++++++++++ platform/tests/test_drafts_cli_mcp.py | 3 + platform/tests/test_mcp_server.py | 4 ++ 5 files changed, 70 insertions(+), 44 deletions(-) create mode 100644 platform/src/factory/services/review_output.py diff --git a/docs/MAP.md b/docs/MAP.md index f0d2ea7e..d165c425 100644 --- a/docs/MAP.md +++ b/docs/MAP.md @@ -2,7 +2,7 @@ -Generated at commit `502a0a57` · projection version `96` · 52 stage modules · 241 event types · 235 index tables · 352 service modules · 223 MCP tools · 415 CLI commands · 40 skills. +Generated at commit `a08a7c09` · projection version `96` · 52 stage modules · 241 event types · 235 index tables · 353 service modules · 223 MCP tools · 415 CLI commands · 40 skills. Read [ARCHITECTURE.md](ARCHITECTURE.md) first. This file answers *where*: for each stage module, the events, models, index files, tables, task kinds, gates and checks it owns, and the services that name its events; then every MCP tool, CLI command, service and skill with what it reaches. Links are found by name (see the script's docstring), so a missing link means the code does not name the thing, not that no relation exists. Paths are relative to `platform/src/factory/` unless they start with `plugin/`. @@ -1788,6 +1788,7 @@ Defined in `cli/main.py` (typer); rendering in `cli/render.py` and siblings. | `results` | | — | `appraisal_record`, `inbox_add`, `label_apply`, `screen_record`, `seed_add` | — | | `resume` | Finding interrupted work (plan restart-and-costs R1, IDEA-59): what a power loss, a killed process or an abandoned sess… | — | — | `factory resume` | | `review_loop` | The conductor's review loop (plan 2026-11-28-review-loops). | runner | — | — | +| `review_output` | The fingerprint of a review-loop step's output (plan 2026-11-28-review-loops): the frame's question, protocol and seeds… | — | — | — | | `reviews` | Review requests and their decisions (slice 5 ruling 14; plan teams-B). | core | `review_decide`, `review_list`, `review_request` | `factory protocol amend`, `factory protocol deviation`, `factory protocol record`, `factory review decide`, `factory review list`, `factory review request`, `factory review show`, `factory review withdraw`, `factory workspace` | | `run_costs` | Run costs (plan restart-and-costs, task C1): what each headless run cost, read from its log. | — | — | — | | `run_units` | Names shared by the MCP unit cap (`mcp.unit_cap`, the writer) and the cost reader (`services.run_costs`). | — | — | — | diff --git a/platform/src/factory/services/review_loop.py b/platform/src/factory/services/review_loop.py index fd5c7839..c973662b 100644 --- a/platform/src/factory/services/review_loop.py +++ b/platform/src/factory/services/review_loop.py @@ -18,14 +18,10 @@ from __future__ import annotations -import hashlib from collections.abc import Sequence from dataclasses import dataclass from typing import Final -from pydantic import JsonValue - -from factory.canonical import canonical_json from factory.errors import FactoryValidationError, ValidationIssue from factory.events.envelope import Actor from factory.events.reader import read_typed @@ -62,46 +58,12 @@ def _refuse(field: str, reason: str) -> FactoryValidationError: # ----------------------------------------------------------------------------- fingerprints -def _frame_output(project: Project) -> JsonValue: - from factory.services.protocol import current_protocol - from factory.services.question import current_question - from factory.services.seeds import all_seeds - - question = current_question(project) - protocol = current_protocol(project) - return { - "question": None if question is None else question.spec.model_dump(mode="json"), - "protocol": None if protocol is None else protocol.spec.model_dump(mode="json"), - "seeds": [s.model_dump(mode="json") for s in all_seeds(project)], - } - - -def _write_output(project: Project) -> JsonValue: - from factory.services.drafts import list_drafts, live_sentences - - return [ - { - "draft_id": d.draft_id, - "title": d.title, - "sentences": [ - { - "section": r.section_id, - "order": r.order, - "text": r.text, - "supports": list[JsonValue](r.supports), - } - for r in live_sentences(project, d.draft_id) - ], - } - for d in list_drafts(project) - ] - - def fingerprint(project: Project, stage_id: str) -> str: - """The sha256 of the loop step's output as the platform reads it now.""" - stage = stage_id.split(":", 1)[0] - output = _frame_output(project) if stage == "frame" else _write_output(project) - return hashlib.sha256(canonical_json(output)).hexdigest() + """The sha256 of the loop step's output as the platform reads it now + (`review_output.output_fingerprint`).""" + from factory.services.review_output import output_fingerprint + + return output_fingerprint(project, stage_id) # ------------------------------------------------------------------------------- the record diff --git a/platform/src/factory/services/review_output.py b/platform/src/factory/services/review_output.py new file mode 100644 index 00000000..e572a628 --- /dev/null +++ b/platform/src/factory/services/review_output.py @@ -0,0 +1,56 @@ +"""The fingerprint of a review-loop step's output (plan 2026-11-28-review-loops): the frame's +question, protocol and seeds, or the write step's drafts, hashed as the platform reads them when a +verdict is recorded. Not an evidence output: it reads the drafts only to tell whether a revision +changed them (`review_loop.loop_end`, escape `repeat`). +""" + +from __future__ import annotations + +import hashlib + +from pydantic import JsonValue + +from factory.canonical import canonical_json +from factory.services.context import Project + + +def _frame_output(project: Project) -> JsonValue: + from factory.services.protocol import current_protocol + from factory.services.question import current_question + from factory.services.seeds import all_seeds + + question = current_question(project) + protocol = current_protocol(project) + return { + "question": None if question is None else question.spec.model_dump(mode="json"), + "protocol": None if protocol is None else protocol.spec.model_dump(mode="json"), + "seeds": [s.model_dump(mode="json") for s in all_seeds(project)], + } + + +def _write_output(project: Project) -> JsonValue: + from factory.services.drafts import list_drafts, live_sentences + + return [ + { + "draft_id": d.draft_id, + "title": d.title, + "sentences": [ + { + "section": r.section_id, + "order": r.order, + "text": r.text, + "supports": list[JsonValue](r.supports), + } + for r in live_sentences(project, d.draft_id) + ], + } + for d in list_drafts(project) + ] + + +def output_fingerprint(project: Project, stage_id: str) -> str: + """The sha256 of the loop step's output as the platform reads it now.""" + stage = stage_id.split(":", 1)[0] + output = _frame_output(project) if stage == "frame" else _write_output(project) + return hashlib.sha256(canonical_json(output)).hexdigest() diff --git a/platform/tests/test_drafts_cli_mcp.py b/platform/tests/test_drafts_cli_mcp.py index 78acc1f3..27a57af9 100644 --- a/platform/tests/test_drafts_cli_mcp.py +++ b/platform/tests/test_drafts_cli_mcp.py @@ -342,6 +342,9 @@ def test_cli_draft_flow_human_author(settings: Settings, project: Project, ww: W # session the drafts it would walk (5941c14). "factory.services.briefing", "factory.services.trace", + # Not an evidence output: the review loop hashes the drafts it reviewed, to tell whether + # a revision changed them (plan 2026-11-28-review-loops). + "factory.services.review_output", "factory.mcp.server", "factory.cli.main", "factory.cli.render", diff --git a/platform/tests/test_mcp_server.py b/platform/tests/test_mcp_server.py index 520f638e..a1236fa7 100644 --- a/platform/tests/test_mcp_server.py +++ b/platform/tests/test_mcp_server.py @@ -48,6 +48,10 @@ async def test_project_status_tool(settings: Settings, project: Project, clock: "seed_list", "probe_run", "protocol_record", + "protocol_from_template", + "review_view", + "review_record", + "review_reply", "protocol_press_review", "protocol_amend", "screen_next", From c9aee89c8e3328ef30443bbd2add85cfadd42014 Mon Sep 17 00:00:00 2001 From: Alex Date: Sat, 28 Nov 2026 22:03:21 +0200 Subject: [PATCH 05/16] fix: refuse at frame a query the source would refuse; pause on a gather with no search Shakedown la-brief-3: frame amended the arXiv query with from_date (arXiv takes only listed_since); gather's search_run was refused, the session stopped, and the conductor took gather as done, so every later step closed empty. protocol_from_template now runs search.query_issues on each planned query; a gather step that left no search run of purpose 'search' in the conductor run pauses 'blocked'. Co-Authored-By: Claude Opus 5.5 --- docs/MAP.md | 6 +-- platform/src/factory/services/conductor.py | 41 +++++++++++++++++-- .../src/factory/services/tier_protocol.py | 19 +++++++++ platform/tests/test_conductor.py | 6 +++ platform/tests/test_review_loop.py | 22 ++++++++++ platform/tests/test_tier_protocol.py | 15 +++++++ 6 files changed, 102 insertions(+), 7 deletions(-) diff --git a/docs/MAP.md b/docs/MAP.md index d165c425..e9c80d74 100644 --- a/docs/MAP.md +++ b/docs/MAP.md @@ -2,7 +2,7 @@ -Generated at commit `a08a7c09` · projection version `96` · 52 stage modules · 241 event types · 235 index tables · 353 service modules · 223 MCP tools · 415 CLI commands · 40 skills. +Generated at commit `c1e701c0` · projection version `96` · 52 stage modules · 241 event types · 235 index tables · 353 service modules · 223 MCP tools · 415 CLI commands · 40 skills. Read [ARCHITECTURE.md](ARCHITECTURE.md) first. This file answers *where*: for each stage module, the events, models, index files, tables, task kinds, gates and checks it owns, and the services that name its events; then every MCP tool, CLI command, service and skill with what it reaches. Links are found by name (see the script's docstring), so a missing link means the code does not name the thing, not that no relation exists. Paths are relative to `platform/src/factory/` unless they start with `plugin/`. @@ -150,7 +150,7 @@ Declaration: `services/modules/retrieval.py` · kind `retrieval` - **Note:** seed.admitted is written by seed admission, so it is owned here (the module whose service writes an event owns it). - **Protocol sections:** `sources`, `queries`, `limits`, `snowball_plan`, `pending_tolerance` - **Check codes:** `shortfall-unexplained`, `seed-admission-pending`, `chase-missing`, `snowball-plan-missing`, `chase-declared-not-run`, `chase-run-unattributed`, `snowball-over-plan`, `snowball-unscreened` -- **Services naming its events:** `services/chase.py`, `services/core_works.py`, `services/search.py`, `services/seeds.py`, `services/snowball.py`, `services/trace.py` +- **Services naming its events:** `services/chase.py`, `services/conductor.py`, `services/core_works.py`, `services/search.py`, `services/seeds.py`, `services/snowball.py`, `services/trace.py` ### Module: dedup @@ -1581,7 +1581,7 @@ Defined in `cli/main.py` (typer); rendering in `cli/render.py` and siblings. | `commit` | The server commit job (slice 5 rulings 4 and 5; `factory commit`). | — | — | `factory commit` | | `concepts` | Background concepts: definition, source approval and definition review (slice 3c, G3-B). | intuition | `concept_link`, `concept_list`, `concept_propose` | `factory concept-links confirm`, `factory concept-links list`, `factory concept-links reject`, `factory concepts approve`, `factory concepts define`, `factory concepts history`, `factory concepts list`, `factory concepts merge`, `factory concepts reject-source`, `factory concepts review`, `factory concepts show`, `factory concepts source`, `factory concepts unmerge` | | `conclusions` | Registered conclusions, their predicates and their basis state (slice 4b, plan living-D). | living | `conclusion_status` | `factory conclusions diff`, `factory conclusions register`, `factory conclusions retire`, `factory conclusions status` | -| `conductor` | The lifecycle conductor (plan tiers-and-autonomy C8, spec slice-9 section 7). | runner, scoping | — | `factory conductor advance`, `factory conductor start`, `factory conductor status` | +| `conductor` | The lifecycle conductor (plan tiers-and-autonomy C8, spec slice-9 section 7). | retrieval, runner, scoping | — | `factory conductor advance`, `factory conductor start`, `factory conductor status` | | `consolidation` | Consolidation: deterministic candidate clusters, agent proposals and human merge decisions (slice 3d rulings 14 and 15,… | labels | `consolidation_next`, `consolidation_propose` | `factory consolidation complete`, `factory consolidation decide`, `factory consolidation list`, `factory consolidation start`, `factory consolidation status` | | `consolidation_due` | When consolidation is due (slice 3d ruling 14, plan Regions-C). | — | — | — | | `context` | | — | — | — | diff --git a/platform/src/factory/services/conductor.py b/platform/src/factory/services/conductor.py index ecfa6795..967f546b 100644 --- a/platform/src/factory/services/conductor.py +++ b/platform/src/factory/services/conductor.py @@ -340,13 +340,38 @@ def _blocked(trail: _Trail, index: int, step: str) -> bool: return (runs[-1].pending or 0) > 0 +def _searched_nothing(project: Project, trail: _Trail, index: int, step: str) -> bool: + """Whether a `gather` step whose proposer has run left no search run of purpose `search` in this + conductor run (a seed lookup is a probe): the gather session stopped on a refusal, and an + empty corpus must not pass as done.""" + if stage_of_step(step) != "gather": + return False + first = trail.started.id + events = read_typed( + project.paths.events_dir, project.catalog, ("query.registered", "search.run_started") + ) + searches = { + str(e.payload["query_id"]) + for e in events + if e.type == "query.registered" + and isinstance(spec := e.payload["spec"], dict) + and spec.get("purpose") == "search" + } + return not any( + e.type == "search.run_started" and e.id > first and str(e.payload["query_id"]) in searches + for e in events + ) + + def _effective_closed(project: Project, trail: _Trail) -> set[tuple[int, str]]: """`_closed_roles`, minus the proposer of a queue step that must run again (`_more_to_run`), and adjusted for the round of a review loop (`_loop_open`).""" closed = _closed_roles(trail) for index, step in enumerate(trail.meta.steps): if (index, "proposer") in closed and ( - _more_to_run(project, trail, index, step) or _blocked(trail, index, step) + _more_to_run(project, trail, index, step) + or _blocked(trail, index, step) + or _searched_nothing(project, trail, index, step) ): closed.discard((index, "proposer")) if review_loop.is_loop_step(step): @@ -623,11 +648,19 @@ def _decide( if waiting_gate is not None: return _Decision("wait", index, stage_id, None, "human-gate", waiting_gate, f"gate {waiting_gate} awaits a human") # fmt: skip - if role == "proposer" and not retry and _blocked(trail, index, stage_id): + if ( + role == "proposer" + and not retry + and (_blocked(trail, index, stage_id) or _searched_nothing(project, trail, index, stage_id)) + and any( + e.payload["step"] == index and e.payload["role"] == "proposer" + for e in trail.payloads("step_finished") + ) + ): return _Decision( "pause", index, stage_id, role, "blocked", - detail=f"the {stage_id} run worked off no unit and units are pending; see its log, " - "fix the cause and advance with retry", + detail=f"the {stage_id} run did no work (no unit worked off, or no search run); see " + "its log, fix the cause and advance with retry", ) # fmt: skip disputed = _disputed(project, trail, index) if disputed is not None: diff --git a/platform/src/factory/services/tier_protocol.py b/platform/src/factory/services/tier_protocol.py index a38a9e7e..77587436 100644 --- a/platform/src/factory/services/tier_protocol.py +++ b/platform/src/factory/services/tier_protocol.py @@ -8,6 +8,8 @@ - Refused, nothing written, for a project without a tier or a tier without a template, with no current question, or with queries the template does not allow (a source it does not name, or more per source than `queries_per_source`). +- A planned query the source would refuse (`search.query_issues`: its kind, filters or text) is + refused here, so the frame session fixes it before gather tries to run it. - The reviewer of record is the human who created the project (the actor of `project.created`), never the agent that calls the tool. - At a tier whose protocol gates do not bind the conductor (`conductor.TIER_UNBOUND_GATES`: brief @@ -75,6 +77,23 @@ def record_from_template( question = current_question(project) if question is None: raise _refuse("question", "record the question first") + from factory.model.search import QueryPurpose, QuerySpec + from factory.services.search import query_issues + from factory.sources.registry import default_sources + + sources = default_sources() + bad = [ + ValidationIssue(f"queries.{i}.{issue.field}", issue.reason) + for i, q in enumerate(queries) + for issue in query_issues( + project, + QuerySpec(source=q.source, kind=q.kind, text=q.text, filters=q.filters, + purpose=QueryPurpose.SEARCH), + sources, + ) + ] # fmt: skip + if bad: # a query the source would refuse at gather is refused here, at frame + raise FactoryValidationError(bad) try: spec = template.instantiate( question.question_id, criteria=criteria, queries=queries, reviewer=creator(project) diff --git a/platform/tests/test_conductor.py b/platform/tests/test_conductor.py index 09fbf6e6..d7d1cb4e 100644 --- a/platform/tests/test_conductor.py +++ b/platform/tests/test_conductor.py @@ -94,6 +94,12 @@ def stages(self) -> list[str]: return [c[0] for c in self.calls] +@pytest.fixture(autouse=True) +def _gather_searched(monkeypatch: pytest.MonkeyPatch) -> None: + """The fake runner runs no search; the empty-gather pause is tested on its own.""" + monkeypatch.setattr(conductor, "_searched_nothing", lambda *_a: False) + + @pytest.fixture(autouse=True) def _frame_gates_bind(monkeypatch: pytest.MonkeyPatch) -> None: """These tests exercise the gate mechanics through the frame step's protocol gates; a brief diff --git a/platform/tests/test_review_loop.py b/platform/tests/test_review_loop.py index 46a96cde..30696df2 100644 --- a/platform/tests/test_review_loop.py +++ b/platform/tests/test_review_loop.py @@ -47,6 +47,7 @@ class FPlan: _REAL_FINGERPRINT = review_loop.fingerprint +_REAL_SEARCHED_NOTHING = conductor._searched_nothing class Runs: @@ -90,6 +91,12 @@ def _step(project: Project, runs: Runs, *, retry: bool = False) -> conductor.Con ) +@pytest.fixture(autouse=True) +def _gather_searched(monkeypatch: pytest.MonkeyPatch) -> None: + """The fake runner runs no search; the empty-gather pause is tested on its own.""" + monkeypatch.setattr(conductor, "_searched_nothing", lambda *_a: False) + + @pytest.fixture(autouse=True) def _complete(monkeypatch: pytest.MonkeyPatch) -> None: """Every role run has ended complete by the next `advance`.""" @@ -473,3 +480,18 @@ def step(retry: bool = False) -> conductor.ConductorStatus: assert runs.stages == ["screen"] status = step(retry=True) assert status.state == "running" and runs.stages == ["screen", "screen"] + + +def test_a_gather_that_ran_no_search_pauses_as_blocked( + settings: Settings, clock: FixedClock, monkeypatch: pytest.MonkeyPatch +) -> None: + """Shakedown la-brief-3: the planned arXiv query had a filter arXiv refuses; gather stopped + before any search and the conductor took the step as done.""" + monkeypatch.setattr(conductor, "_searched_nothing", _REAL_SEARCHED_NOTHING) + project = _make(settings, clock, "brief") + runs = Runs() + conductor.begin_conductor(project, _plan(Tier.BRIEF, "gather", "screen")) + _step(project, runs) + status = _step(project, runs) + assert status.state == "paused" and status.reason == "blocked" + assert runs.stages == ["gather"] diff --git a/platform/tests/test_tier_protocol.py b/platform/tests/test_tier_protocol.py index 0c2df91b..ba18e0fb 100644 --- a/platform/tests/test_tier_protocol.py +++ b/platform/tests/test_tier_protocol.py @@ -123,3 +123,18 @@ def test_where_the_protocol_gates_bind_it_stays_a_draft( _question(project, agent) result = tier_protocol.record_from_template(project, agent, _criteria(), [_q("openalex")]) assert result.status is ProtocolStatus.DRAFT + + +def test_a_query_the_source_would_refuse_is_refused_at_frame( + settings: Settings, clock: FixedClock, agent: Actor +) -> None: + """Shakedown la-brief-3: `from_date` on arXiv was recorded and refused only at gather.""" + project = _project(settings, clock) + _question(project, agent) + dated = PlannedQuery(source="arxiv", kind=QueryKind.KEYWORD, text="mamba vision", + filters={"from_date": "2024-01-01"}) # fmt: skip + with pytest.raises(FactoryValidationError, match="listed_since"): + tier_protocol.record_from_template(project, agent, _criteria(), [dated]) + assert current_protocol(project) is None + ok = dated.model_copy(update={"filters": {"listed_since": "2024-01-01"}}) + assert tier_protocol.record_from_template(project, agent, _criteria(), [ok]).created From 1e0deb56d63c71650d1577a1f34dee1fc393da15 Mon Sep 17 00:00:00 2001 From: Alex Date: Sat, 28 Nov 2026 23:03:56 +0200 Subject: [PATCH 06/16] fix(screening): completed batches count against the tier screen cap; OpenAlex filter keys checked Shakedown la-brief-4: the brief screened 390 records against a cap of 40 and spent its 20 runs on screening. _served_works counted only claimed batch tasks; a completed batch fell out, so screen_cap_reached stayed false. It now counts claimed and completed batches. The planned OpenAlex query carried from_year, which OpenAlex answers with 400; search.query_issues now refuses an OpenAlex filter key outside a documented set, naming the accepted keys, so frame fixes it. Co-Authored-By: Claude Opus 5.5 --- docs/MAP.md | 2 +- platform/src/factory/services/screening.py | 8 +++-- platform/src/factory/services/search.py | 39 +++++++++++++++++++++- platform/tests/test_tier_caps.py | 20 +++++++++++ platform/tests/test_tier_protocol.py | 14 ++++++++ 5 files changed, 78 insertions(+), 5 deletions(-) diff --git a/docs/MAP.md b/docs/MAP.md index e9c80d74..3be324c6 100644 --- a/docs/MAP.md +++ b/docs/MAP.md @@ -2,7 +2,7 @@ -Generated at commit `c1e701c0` · projection version `96` · 52 stage modules · 241 event types · 235 index tables · 353 service modules · 223 MCP tools · 415 CLI commands · 40 skills. +Generated at commit `c9aee89c` · projection version `96` · 52 stage modules · 241 event types · 235 index tables · 353 service modules · 223 MCP tools · 415 CLI commands · 40 skills. Read [ARCHITECTURE.md](ARCHITECTURE.md) first. This file answers *where*: for each stage module, the events, models, index files, tables, task kinds, gates and checks it owns, and the services that name its events; then every MCP tool, CLI command, service and skill with what it reaches. Links are found by name (see the script's docstring), so a missing link means the code does not name the thing, not that no relation exists. Paths are relative to `platform/src/factory/` unless they start with `plugin/`. diff --git a/platform/src/factory/services/screening.py b/platform/src/factory/services/screening.py index 2328f05a..5b91aa19 100644 --- a/platform/src/factory/services/screening.py +++ b/platform/src/factory/services/screening.py @@ -614,12 +614,14 @@ def withheld(self, label: PassLabel) -> set[str]: def _served_works(project: Project, label: PassLabel, stage: ScreeningStage) -> set[str]: - """The works of screening-phase batches of the pass that were claimed (a claim whose lease - lapsed still counts: the batch was shown).""" + """The works of screening-phase batches of the pass that were served: claimed, or claimed and + completed (a claim whose lease lapsed still counts: the batch was shown). A completed batch + once fell out of the count, so the tier's screen cap never closed (shakedown la-brief-4).""" + shown = (TaskStatus.CLAIMED.value, TaskStatus.COMPLETED.value) return { str(record["work_id"]) for _, status, content in _kind_tasks(project, task_kind(stage, label)) - if status == TaskStatus.CLAIMED.value and content.phase is ScreeningPhase.SCREENING + if status in shown and content.phase is ScreeningPhase.SCREENING for record in content.records } diff --git a/platform/src/factory/services/search.py b/platform/src/factory/services/search.py index 43f88d7e..8591ac56 100644 --- a/platform/src/factory/services/search.py +++ b/platform/src/factory/services/search.py @@ -10,7 +10,7 @@ import json from collections.abc import Mapping, Sequence from datetime import date -from typing import Any +from typing import Any, Final from pydantic import Field from sqlalchemy import bindparam, text @@ -531,6 +531,30 @@ def query_issues( return _spec_issues(project, spec, sources) +OPENALEX_FILTERS: Final = frozenset( + { + "listed_since", # the factory's window key, sent as from_created_date + "from_publication_date", + "to_publication_date", + "publication_year", + "from_created_date", + "type", + "language", + "is_oa", + "has_fulltext", + "has_doi", + "cited_by_count", + "primary_topic.id", + "topics.id", + "concepts.id", + "authorships.author.id", + "authorships.institutions.id", + "primary_location.source.id", + } +) +"""The OpenAlex work filters a planned or registered query may carry (a documented subset).""" + + def _window_filter_issues(source: str, filters: Mapping[str, str]) -> list[ValidationIssue]: """arXiv and PubMed take one filter, `listed_since` (YYYY-MM-DD), as the watch does.""" issues: list[ValidationIssue] = [] @@ -578,6 +602,19 @@ def _spec_issues( ) elif spec.filters and spec.source != "openalex": issues.append(ValidationIssue("filters", f"{spec.source} does not take filters")) + unknown = ( # a key with a separator is refused below, once + sorted(k for k in set(spec.filters) - OPENALEX_FILTERS if "," not in k and ":" not in k) + if spec.source == "openalex" + else [] + ) + if unknown: # OpenAlex answers 400 to an unknown key, at gather (shakedown la-brief-4) + issues.append( + ValidationIssue( + "filters", + f"OpenAlex has no filter {', '.join(map(repr, unknown))}; use one of " + + ", ".join(sorted(OPENALEX_FILTERS)), + ) + ) if spec.source == "openalex" and any( sep in part for part in (*spec.filters, *spec.filters.values()) for sep in (",", ":") ): diff --git a/platform/tests/test_tier_caps.py b/platform/tests/test_tier_caps.py index 4f43d568..a4411643 100644 --- a/platform/tests/test_tier_caps.py +++ b/platform/tests/test_tier_caps.py @@ -82,6 +82,26 @@ def test_screening_refuses_past_the_cap( assert len(list(project.paths.events_dir.rglob("*.jsonl"))) == before +def test_a_screened_batch_still_counts_against_the_cap( + project: Project, + agent: Actor, + human: Actor, + mock_sources: SourcesFor, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Shakedown la-brief-4: a batch whose task was completed fell out of the served count, so a + brief screened 390 records against a cap of 40.""" + from factory.services.screening import screen_record + from tests.screening_helpers import _item + + batch = _batch(project, agent, human, mock_sources) + result = screen_record(project, agent, batch.task_id, [_item(r) for r in batch.records]) + assert result.rejected == [] + monkeypatch.setattr(screening_module, "tier_cap", lambda _p, _which: SMALL) + with pytest.raises(FactoryValidationError, match="tier-cap-reached"): + screen_next(project, agent, PassLabel.A) + + def test_screening_without_a_cap_is_unchanged( project: Project, agent: Actor, human: Actor, mock_sources: SourcesFor ) -> None: diff --git a/platform/tests/test_tier_protocol.py b/platform/tests/test_tier_protocol.py index ba18e0fb..15897efb 100644 --- a/platform/tests/test_tier_protocol.py +++ b/platform/tests/test_tier_protocol.py @@ -138,3 +138,17 @@ def test_a_query_the_source_would_refuse_is_refused_at_frame( assert current_protocol(project) is None ok = dated.model_copy(update={"filters": {"listed_since": "2024-01-01"}}) assert tier_protocol.record_from_template(project, agent, _criteria(), [ok]).created + + +def test_an_openalex_filter_it_does_not_have_is_refused_at_frame( + settings: Settings, clock: FixedClock, agent: Actor +) -> None: + """Shakedown la-brief-4: `from_year` on OpenAlex was answered 400 at gather.""" + project = _project(settings, clock) + _question(project, agent) + bad = PlannedQuery(source="openalex", kind=QueryKind.KEYWORD, text="mamba vision", + filters={"from_year": "2024"}) # fmt: skip + with pytest.raises(FactoryValidationError, match="from_publication_date"): + tier_protocol.record_from_template(project, agent, _criteria(), [bad]) + ok = bad.model_copy(update={"filters": {"from_publication_date": "2024-01-01"}}) + assert tier_protocol.record_from_template(project, agent, _criteria(), [ok]).created From e5eefb30fcc1adb6506d0301db8b7e44592ca128 Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 29 Nov 2026 00:38:29 +0200 Subject: [PATCH 07/16] perf(dedup,conductor): title pairs prefiltered in C; one memo scope per advance Shakedown la-brief-5 spent its 60-minute budget mostly idle: each conductor advance took 12-19 minutes on a 13k-work corpus. pending_units ran dedup_current, whose title stage compared every pair in a year window in Python (119M pairs, 100-130 s per call), and advance read the pending units several times outside a memo scope. - dedup: titles get their tokens sorted once; rapidfuzz process.extract with fuzz.ratio and the threshold as cutoff returns only the pairs that can merge, visited in the old order. Same merges on the la-brief-5 corpus (1,104), 6 s instead of 100 s. - conductor: advance and conductor_status run inside call_memo.entering; a recorded event drops the memo, so no read is stale. Co-Authored-By: Claude Opus 5.5 --- platform/src/factory/services/conductor.py | 39 +++++++++++++++++++ .../src/factory/services/dedup_cascade.py | 18 ++++++++- 2 files changed, 55 insertions(+), 2 deletions(-) diff --git a/platform/src/factory/services/conductor.py b/platform/src/factory/services/conductor.py index 967f546b..d1fab4c1 100644 --- a/platform/src/factory/services/conductor.py +++ b/platform/src/factory/services/conductor.py @@ -49,6 +49,7 @@ from factory.model.levels import AutonomyLevel from factory.modules.contract import PolicyKind from factory.services import review_loop, runner +from factory.services.call_memo import entering from factory.services.context import Project from factory.services.project import project_levels @@ -932,6 +933,33 @@ def advance( escalate: Escalate | None = None, automatic: Automatic | None = None, reconcile: Reconcile | None = None, +) -> ConductorStatus: + """`_advance` inside one memo scope (`call_memo`): a step decision reads the pending units + several times, and each read re-ran dedup over the corpus (shakedown la-brief-5: 12-19 min + per advance on 13k works). An event recorded meanwhile drops the memo, so no read is stale.""" + with entering(): + return _advance( + project, + retry=retry, + start_run=start_run, + pending=pending, + gate_closed=gate_closed, + escalate=escalate, + automatic=automatic, + reconcile=reconcile, + ) + + +def _advance( + project: Project, + *, + retry: bool = False, + start_run: StartRun | None = None, + pending: PendingUnits | None = None, + gate_closed: GateClosed | None = None, + escalate: Escalate | None = None, + automatic: Automatic | None = None, + reconcile: Reconcile | None = None, ) -> ConductorStatus: """Take the open conductor run one step further and return its status. First closes the conductor's own open run when the runner has recorded its outcome. A run with no recorded @@ -1123,6 +1151,17 @@ def conductor_status( gate_closed: GateClosed | None = None, ) -> ConductorStatus: """The status of the latest conductor run (read-only): where it is and why it stopped.""" + with entering(): + return _status(project, retry=retry, pending=pending, gate_closed=gate_closed) + + +def _status( + project: Project, + *, + retry: bool = False, + pending: PendingUnits | None = None, + gate_closed: GateClosed | None = None, +) -> ConductorStatus: trail = _load(project) if trail is None: done = [ diff --git a/platform/src/factory/services/dedup_cascade.py b/platform/src/factory/services/dedup_cascade.py index 3a40507c..d7106c9c 100644 --- a/platform/src/factory/services/dedup_cascade.py +++ b/platform/src/factory/services/dedup_cascade.py @@ -26,7 +26,7 @@ from collections.abc import Callable, Mapping, Sequence from dataclasses import dataclass, field -from rapidfuzz import fuzz +from rapidfuzz import fuzz, process from factory.model.dedup_keys import first_surname, strong_keys, title_bucket_key from factory.model.work import Work, WorkType @@ -273,17 +273,31 @@ def dedup( by_year[work.dates.year].append(work) titles = {w.id: normalize_title(w.title) for w in works} + # token_sort_ratio is ratio over the tokens sorted; sorting each title once lets the C + # extractor scan a bucket per title, so only the pairs at or above the threshold reach the + # Python loop below (identical titles score 100, so they are among them). The pairs and their + # order are the same as comparing every pair (shakedown la-brief-5: 13k works took 130 s). + sorted_titles = {key: " ".join(sorted(t.split())) for key, t in titles.items()} compared = 0 for year, bucket in by_year.items(): candidates = list(bucket) if year is not None: for offset in range(1, YEAR_WINDOW + 1): candidates += by_year.get(year + offset, []) + candidate_titles = [sorted_titles[w.id] for w in candidates] for i, left in enumerate(bucket): compared += 1 if progress is not None: progress(compared, len(works)) - for right in candidates[i + 1 :]: + rest = candidates[i + 1 :] + hits = process.extract( + sorted_titles[left.id], + candidate_titles[i + 1 :], + scorer=fuzz.ratio, + score_cutoff=TITLE_SIMILARITY_THRESHOLD, + limit=None, + ) + for right in (rest[index] for index in sorted(hit[2] for hit in hits)): if left.id == right.id or union.find(left.id) == union.find(right.id): continue if ( From d66fa983b536457dfad81a97fce364602b900086 Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 29 Nov 2026 01:16:52 +0200 Subject: [PATCH 08/16] fix(search): drop the deprecated OpenAlex concepts.id filter key (layer table name rule) Co-Authored-By: Claude Opus 5.5 --- platform/src/factory/services/search.py | 1 - 1 file changed, 1 deletion(-) diff --git a/platform/src/factory/services/search.py b/platform/src/factory/services/search.py index 8591ac56..d61e4b45 100644 --- a/platform/src/factory/services/search.py +++ b/platform/src/factory/services/search.py @@ -546,7 +546,6 @@ def query_issues( "cited_by_count", "primary_topic.id", "topics.id", - "concepts.id", "authorships.author.id", "authorships.institutions.id", "primary_location.source.id", From b32c3875ac592b3f843ba33abb5f73428fefb7f9 Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 29 Nov 2026 14:05:57 +0200 Subject: [PATCH 09/16] feat(brief): rank the screening queue before the first run; arXiv-only brief; dated frame Shakedown la-brief-6 screened the 40 records first in work-id order (year, then title) of a 13k corpus: no ranking ran, so none of the 10 check-set papers in the corpus was screened. - services/lexical_rank: a TF-IDF ranker (standard library), the slot of an embedder in ranking.compute_ranking; the ranking records its model id. - conductor: before the first title/abstract screening run the system ranks the queue once (SPECTER2 when FACTORY_RANKER_MODEL is set, the lexical ranker otherwise); ranked serving and the stopping rule use it. - brief template: arXiv only (OpenAlex keyword search brought 10,990 of 13,719 records, mostly conference applications). - rf-frame-conducted: a goal's start date goes on each arXiv query as listed_since, with the reason in the rationale; when a goal compares primitives, papers that only apply one are excluded. Co-Authored-By: Claude Opus 5.5 --- docs/MAP.md | 3 +- platform/src/factory/services/conductor.py | 29 +++++++ platform/src/factory/services/lexical_rank.py | 79 +++++++++++++++++++ platform/src/factory/services/ranking.py | 20 +++-- platform/src/factory/tiers/plans.py | 4 +- platform/tests/test_lexical_rank.py | 74 +++++++++++++++++ platform/tests/test_tier_protocol.py | 23 +++--- platform/tests/test_tiers.py | 2 +- plugin/skills/rf-frame-conducted/SKILL.md | 7 ++ 9 files changed, 221 insertions(+), 20 deletions(-) create mode 100644 platform/src/factory/services/lexical_rank.py create mode 100644 platform/tests/test_lexical_rank.py diff --git a/docs/MAP.md b/docs/MAP.md index 3be324c6..2e46b7e0 100644 --- a/docs/MAP.md +++ b/docs/MAP.md @@ -2,7 +2,7 @@ -Generated at commit `c9aee89c` · projection version `96` · 52 stage modules · 241 event types · 235 index tables · 353 service modules · 223 MCP tools · 415 CLI commands · 40 skills. +Generated at commit `d66fa983` · projection version `96` · 52 stage modules · 241 event types · 235 index tables · 354 service modules · 223 MCP tools · 415 CLI commands · 40 skills. Read [ARCHITECTURE.md](ARCHITECTURE.md) first. This file answers *where*: for each stage module, the events, models, index files, tables, task kinds, gates and checks it owns, and the services that name its events; then every MCP tool, CLI command, service and skill with what it reaches. Links are found by name (see the script's docstring), so a missing link means the code does not name the thing, not that no relation exists. Paths are relative to `platform/src/factory/` unless they start with `plugin/`. @@ -1722,6 +1722,7 @@ Defined in `cli/main.py` (typer); rendering in `cli/render.py` and siblings. | `ledger` | The contribution ledger: who did what, derived from the log (slice 5 ruling 16, R-112). | — | `ledger_view` | `factory ledger` | | `level_bench` | Benchmark metrics of one study, to compare tiers and autonomy levels (plan C9). | — | — | `factory bench level` | | `level_statement` | The level statement: what tier and autonomy level a study ran at, what it skipped and what no human confirmed (plan tie… | core, extraction, mining, screening | — | `factory report discovery`, `factory report evidence`, `factory report flow`, `factory report flow-skipped`, `factory report flow-trail`, `factory report flow-works`, `factory report methods`, `factory report prisma`, `factory report search` | +| `lexical_rank` | A lexical ranker: TF-IDF similarity of each record to the development seeds (shakedown la-brief-6). | — | — | — | | `library_push` | Moving literature to a lab server: the receiving side and the pushing client (deploy-C, Task 4). | — | — | `factory library push` | | `lineage` | Graph reads, queries and exports over the projected lineage graph (slice 3b, plan G2-D). | — | `graph_export`, `graph_query`, `graph_status` | `factory graph build`, `factory graph export`, `factory graph query`, `factory graph status` | | `living_hooks` | Cycle hooks of a living review (living-B): what runs after each watch cycle's searches. | — | `watch_run` | `factory notices check`, `factory watch run` | diff --git a/platform/src/factory/services/conductor.py b/platform/src/factory/services/conductor.py index d1fab4c1..955b01ae 100644 --- a/platform/src/factory/services/conductor.py +++ b/platform/src/factory/services/conductor.py @@ -774,6 +774,33 @@ def _plan_blob(project: Project, plan: PlanLike, steps: Sequence[str]) -> str: return project.blobs.put(canonical_json(view)) +RANKED_STEP: Final = "screen:title-abstract" + + +def rank_before_screening(project: Project) -> None: + """Rank the title/abstract queue once, as the system, before its first screening run (shakedown + la-brief-6: unranked, a capped tier screened the first 40 of 13k records in work-id order). + Ranked serving and the stopping rule then use it. The embedding ranker runs when its weights + are configured (`FACTORY_RANKER_MODEL`), the lexical one otherwise; the ranking records which. + A refusal (no seed with a title, nothing to rank) leaves the queue in its existing order.""" + import os + + from factory.services import ranking + from factory.services.lexical_rank import LexicalScorer + from factory.services.ranked_queue import ranking_positions + from factory.services.ranking_model import MODEL_ENV, Embedder, Specter2Embedder + + if ranking_positions(project): + return + scorer: Embedder | LexicalScorer = ( + Specter2Embedder() if os.environ.get(MODEL_ENV) else LexicalScorer() + ) + try: + ranking.compute_ranking(project, scorer) + except FactoryValidationError: + return + + def default_automatic(project: Project, limit: int) -> None: """The platform's deterministic steps for the works acquired so far, as the system: resolve, fetch (`work_queue.advance`, the same sources and routes as the runner's automatic steps) and @@ -1081,6 +1108,8 @@ def _advance( cap = _unit_cap(meta) if decision.role == "auditor": draw_platform_audits(project, decision.stage_id) + if decision.role == "proposer" and decision.stage_id == RANKED_STEP: + rank_before_screening(project) queue_before = ( _queue_pending(pend, project, decision.stage_id) if decision.role == "proposer" and decision.stage_id in _QUEUE_UNITS diff --git a/platform/src/factory/services/lexical_rank.py b/platform/src/factory/services/lexical_rank.py new file mode 100644 index 00000000..27b0f67d --- /dev/null +++ b/platform/src/factory/services/lexical_rank.py @@ -0,0 +1,79 @@ +"""A lexical ranker: TF-IDF similarity of each record to the development seeds (shakedown +la-brief-6). + +The embedding ranker (decision 116, `ranking_model`) needs the `ranker` extra and supplied weights; +without them a capped tier served its queue in work-id order, so a brief screened the +alphabetically first 40 of 13k records. This scorer needs nothing beyond the standard library and +fills the same slot: `ranking.compute_ranking` takes it in place of an embedder and records its +`model_id`, so a ranking says which method made it. + +Invariants (as for the embedding ranker): it orders and never judges; for fixed inputs the scores +are the same; a work's score is its maximum cosine to any reference text, rounded by the caller. +The vectors are TF-IDF over the reference and candidate texts together (smoothed IDF, sublinear +term frequency, unigrams and bigrams of lowercased words with English stop words removed, +L2-normalised), so a term common to the whole corpus weighs little. +""" + +from __future__ import annotations + +import hashlib +import math +import re +from collections import Counter +from collections.abc import Sequence + +MODEL_ID = "factory-lexical-tfidf" +VERSION = "1" + +_WORD = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*") +STOP_WORDS = frozenset( + ["a", "about", "above", "after", "again", "against", "all", "also", "am", "an", "and", "any", "are", "as", "at", "be", "because", "been", "before", "being", "below", "between", "both", "but", "by", "can", "could", "did", "do", "does", "doing", "down", "during", "each", "few", "for", "from", "further", "had", "has", "have", "having", "he", "her", "here", "hers", "herself", "him", "himself", "his", "how", "i", "if", "in", "into", "is", "it", "its", "itself", "just", "let", "me", "more", "most", "my", "myself", "no", "nor", "not", "now", "of", "off", "on", "once", "only", "or", "other", "our", "ours", "ourselves", "out", "over", "own", "same", "she", "should", "so", "some", "such", "than", "that", "the", "their", "theirs", "them", "themselves", "then", "there", "these", "they", "this", "those", "through", "to", "too", "under", "until", "up", "upon", "very", "via", "was", "we", "were", "what", "when", "where", "which", "while", "who", "whom", "why", "will", "with", "within", "without", "would", "you", "your", "yours", "yourself", "yourselves", "we", "our", "paper", "propose", "proposed", "show", "shows", "method", "methods", "approach", "based", "new", "using", "use", "used", "results", "result"] +) + + +def terms(text: str) -> list[str]: + """The unigrams and bigrams of `text`: lowercased words (hyphenated words kept whole), stop + words and one-character tokens removed before the bigrams are formed.""" + words = [w for w in _WORD.findall(text.lower()) if len(w) > 1 and w not in STOP_WORDS] + return words + [f"{a} {b}" for a, b in zip(words, words[1:], strict=False)] + + +def _vectors(texts: Sequence[str]) -> list[dict[str, float]]: + counts = [Counter(terms(t)) for t in texts] + df: Counter[str] = Counter() + for c in counts: + df.update(c.keys()) + n = len(texts) + idf = {term: math.log((1 + n) / (1 + d)) + 1.0 for term, d in df.items()} + out = [] + for c in counts: + v = {term: (1.0 + math.log(tf)) * idf[term] for term, tf in c.items()} + norm = math.sqrt(math.fsum(x * x for x in v.values())) + out.append({term: x / norm for term, x in v.items()} if norm > 0 else {}) + return out + + +def _cosine(a: dict[str, float], b: dict[str, float]) -> float: + if len(a) > len(b): + a, b = b, a + return math.fsum(x * b[t] for t, x in a.items() if t in b) + + +class LexicalScorer: + """Scores candidates by TF-IDF cosine to the references; the slot of an `Embedder` in + `ranking.compute_ranking`.""" + + model_id = MODEL_ID + software = f"factory lexical ranker v{VERSION} (standard library)" + + @property + def weights_hash(self) -> str: + """No weights: the hash names the version and the stop-word list, which fix the method.""" + spec = f"{VERSION}|{' '.join(sorted(STOP_WORDS))}" + return hashlib.sha256(spec.encode("utf-8")).hexdigest() + + def scores(self, references: Sequence[str], candidates: Sequence[str]) -> list[float]: + """Each candidate's maximum cosine to any reference, in candidate order.""" + vectors = _vectors([*references, *candidates]) + refs, cands = vectors[: len(references)], vectors[len(references) :] + return [max((_cosine(c, r) for r in refs), default=0.0) for c in cands] diff --git a/platform/src/factory/services/ranking.py b/platform/src/factory/services/ranking.py index 701328ea..011414ad 100644 --- a/platform/src/factory/services/ranking.py +++ b/platform/src/factory/services/ranking.py @@ -35,6 +35,7 @@ from factory.model.work import Work from factory.services.calibration import stage_population from factory.services.context import Project +from factory.services.lexical_rank import LexicalScorer from factory.services.progress import Callback, track from factory.services.ranked_queue import ranking_positions as ranking_positions from factory.services.ranking_model import BATCH, Embedder @@ -159,7 +160,7 @@ def max_cosine_scores( } -def compute_ranking(project: Project, embedder: Embedder) -> RankingComputed: +def compute_ranking(project: Project, embedder: Embedder | LexicalScorer) -> RankingComputed: """Rank the works still to be screened and record `ranking.computed` as the system. Refused, with nothing written, when there is nothing to rank or no development seed can be @@ -181,10 +182,19 @@ def compute_ranking(project: Project, embedder: Embedder) -> RankingComputed: [ValidationIssue("corpus", f"{len(missing)} works to rank are not in the corpus")] ) candidates = [by_id[work_id] for work_id in ids] - with track( - project, "ranking", "SPECTER2 embedding", unit="records", total=len(refs) + len(candidates) - ) as reporter: - scores = max_cosine_scores(embedder, refs, candidates, reporter.update) + if isinstance(embedder, LexicalScorer): # no model: TF-IDF over the texts, in one pass + lexical = embedder.scores( + [ranking_text(w) for w in refs], [ranking_text(w) for w in candidates] + ) + scores = { + w.id: round(score, SCORE_DECIMALS) for w, score in zip(candidates, lexical, strict=True) + } + else: + with track( + project, "ranking", "SPECTER2 embedding", unit="records", + total=len(refs) + len(candidates), + ) as reporter: # fmt: skip + scores = max_cosine_scores(embedder, refs, candidates, reporter.update) ordered = order_by_score(scores) parameters = RankingParameters(references=tuple(w.id for w in refs), skipped_seeds=skipped) with project.writing(): diff --git a/platform/src/factory/tiers/plans.py b/platform/src/factory/tiers/plans.py index 5475f173..1f9e3aea 100644 --- a/platform/src/factory/tiers/plans.py +++ b/platform/src/factory/tiers/plans.py @@ -95,7 +95,9 @@ def _uncapped() -> tuple[StagePlan, ...]: _BRIEF_PROTOCOL = ProtocolTemplate( method_profile=MethodProfile.RAPID_REVIEW, - sources=("openalex", "arxiv"), + # arXiv only (shakedown la-brief-6): OpenAlex keyword search brought 10,990 of 13,719 records, + # mostly conference applications, for a brief that screens 40. + sources=("arxiv",), queries_per_source=1, passes=1, stop_after_consecutive_excludes=10, diff --git a/platform/tests/test_lexical_rank.py b/platform/tests/test_lexical_rank.py new file mode 100644 index 00000000..6156db49 --- /dev/null +++ b/platform/tests/test_lexical_rank.py @@ -0,0 +1,74 @@ +"""The lexical ranker (shakedown la-brief-6): TF-IDF similarity to the seeds, no extra needed, and +the conductor ranks the title/abstract queue before its first screening run.""" + +from __future__ import annotations + +import pytest + +from factory.events.envelope import Actor +from factory.services import conductor +from factory.services.context import Project +from factory.services.lexical_rank import MODEL_ID, LexicalScorer, terms +from factory.services.ranking import compute_ranking, ranking_positions, to_rank +from tests.helpers import SourcesFor, _setup + + +def test_terms_drop_stop_words_and_add_bigrams() -> None: + assert terms("The Gated Delta-Rule for linear attention") == [ + "gated", + "delta-rule", + "linear", + "attention", + "gated delta-rule", + "delta-rule linear", + "linear attention", + ] + + +def test_a_candidate_sharing_rare_terms_ranks_above_an_unrelated_one() -> None: + refs = ["Gated delta networks: linear attention with a delta rule for vision"] + near = "A delta rule linear attention backbone for vision" + far = "Pose estimation of cows in barns from video" + generic = "A study of vision" + scores = LexicalScorer().scores(refs, [far, near, generic]) + assert scores[1] > scores[2] > scores[0] == 0.0 + + +def test_scores_are_deterministic() -> None: + refs, cands = ["state space model for images"], ["mamba state space vision", "cows"] + assert LexicalScorer().scores(refs, cands) == LexicalScorer().scores(refs, cands) + + +def test_compute_ranking_records_the_lexical_method( + project: Project, agent: Actor, human: Actor, mock_sources: SourcesFor +) -> None: + _setup(project, agent, human, mock_sources, dual_sample=0.5, random_works=3) + event = compute_ranking(project, LexicalScorer()) + assert event.model_id == MODEL_ID + assert event.count == len(to_rank(project)) + assert set(ranking_positions(project)) == set(to_rank(project)) + + +def test_the_conductor_ranks_once_before_screening( + project: Project, + agent: Actor, + human: Actor, + mock_sources: SourcesFor, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv("FACTORY_RANKER_MODEL", raising=False) + _setup(project, agent, human, mock_sources, dual_sample=0.5, random_works=3) + assert not ranking_positions(project) + conductor.rank_before_screening(project) + first = dict(ranking_positions(project)) + assert first + conductor.rank_before_screening(project) # a ranking exists: nothing is recomputed + events = [p for p in project.paths.events_dir.rglob("*.jsonl")] + computed = sum(f.read_text().count('"ranking.computed"') for f in events) + assert computed == 1 + assert ranking_positions(project) == first + + +def test_a_refused_ranking_leaves_the_queue_unranked(project: Project) -> None: + conductor.rank_before_screening(project) # no seeds, nothing to rank: refused, not raised + assert not ranking_positions(project) diff --git a/platform/tests/test_tier_protocol.py b/platform/tests/test_tier_protocol.py index 15897efb..1fe76886 100644 --- a/platform/tests/test_tier_protocol.py +++ b/platform/tests/test_tier_protocol.py @@ -50,13 +50,11 @@ def test_the_brief_template_is_recorded_as_a_draft( ) -> None: project = _project(settings, clock) _question(project, agent) - result = tier_protocol.record_from_template( - project, agent, _criteria(), [_q("openalex"), _q("arxiv")] - ) + result = tier_protocol.record_from_template(project, agent, _criteria(), [_q("arxiv")]) assert result.created and result.status.value == "ready" # no person makes it ready (R-16) spec = current_protocol(project) assert spec is not None - assert [s.name for s in spec.spec.sources] == ["openalex", "arxiv"] + assert [s.name for s in spec.spec.sources] == ["arxiv"] # la-brief-6: no OpenAlex in a brief assert spec.spec.screening.stop_after_consecutive_excludes == 10 reviewer = spec.spec.screening.reviewers[0] assert (reviewer.actor, reviewer.kind) == ("obd", "human") # the creator, not the agent @@ -64,7 +62,7 @@ def test_the_brief_template_is_recorded_as_a_draft( @pytest.mark.parametrize( "queries", - [[_q("openalex"), _q("openalex", "second")], [_q("pubmed")]], + [[_q("arxiv"), _q("arxiv", "second")], [_q("pubmed")], [_q("openalex")]], ) def test_queries_the_template_does_not_allow_are_refused( settings: Settings, clock: FixedClock, agent: Actor, queries: list[PlannedQuery] @@ -81,7 +79,7 @@ def test_no_question_or_no_template_is_refused( ) -> None: project = _project(settings, clock) with pytest.raises(FactoryValidationError, match="question first"): - tier_protocol.record_from_template(project, agent, _criteria(), [_q("openalex")]) + tier_protocol.record_from_template(project, agent, _criteria(), [_q("arxiv")]) def test_a_revision_of_a_ready_brief_protocol_is_an_amendment( @@ -93,15 +91,15 @@ def test_a_revision_of_a_ready_brief_protocol_is_an_amendment( _question(project, agent) first = tier_protocol.record_from_template(project, agent, _criteria(), [_q("arxiv")]) assert first.status is ProtocolStatus.READY # a brief runs without a person: R-16 - both = [_q("openalex"), _q("arxiv")] + both = [_q("arxiv", "linear attention vision mamba rwkv test-time training")] with pytest.raises(FactoryValidationError, match="amendment"): tier_protocol.record_from_template(project, agent, _criteria(), both) amended = tier_protocol.record_from_template( - project, agent, _criteria(), both, reason="R1.F1: add the OpenAlex query" + project, agent, _criteria(), both, reason="R1.F1: widen the arXiv query" ) assert amended.created and amended.status is ProtocolStatus.READY current = current_protocol(project) - assert current is not None and [q.source for q in current.spec.queries] == ["openalex", "arxiv"] + assert current is not None and "test-time training" in current.spec.queries[0].text criteria = _criteria() criteria[0] = criteria[0].model_copy(update={"rule": "names a sub-quadratic mixer on images"}) with pytest.raises(FactoryValidationError, match="effects"): @@ -121,7 +119,7 @@ def test_where_the_protocol_gates_bind_it_stays_a_draft( monkeypatch.setattr(conductor, "TIER_UNBOUND_GATES", {}) # as at pilot and systematic project = _project(settings, clock) _question(project, agent) - result = tier_protocol.record_from_template(project, agent, _criteria(), [_q("openalex")]) + result = tier_protocol.record_from_template(project, agent, _criteria(), [_q("arxiv")]) assert result.status is ProtocolStatus.DRAFT @@ -143,8 +141,9 @@ def test_a_query_the_source_would_refuse_is_refused_at_frame( def test_an_openalex_filter_it_does_not_have_is_refused_at_frame( settings: Settings, clock: FixedClock, agent: Actor ) -> None: - """Shakedown la-brief-4: `from_year` on OpenAlex was answered 400 at gather.""" - project = _project(settings, clock) + """Shakedown la-brief-4: `from_year` on OpenAlex was answered 400 at gather. (Deep: a brief + no longer searches OpenAlex.)""" + project = _project(settings, clock, "deep") _question(project, agent) bad = PlannedQuery(source="openalex", kind=QueryKind.KEYWORD, text="mamba vision", filters={"from_year": "2024"}) # fmt: skip diff --git a/platform/tests/test_tiers.py b/platform/tests/test_tiers.py index 08709bc8..13ba3206 100644 --- a/platform/tests/test_tiers.py +++ b/platform/tests/test_tiers.py @@ -172,7 +172,7 @@ def test_the_template_refuses_queries_that_break_its_cap() -> None: template = plan_for(Tier.BRIEF).protocol_template assert template is not None two = tuple( - PlannedQuery(source="openalex", kind=QueryKind.KEYWORD, text=t) for t in ("a b", "c d") + PlannedQuery(source="arxiv", kind=QueryKind.KEYWORD, text=t) for t in ("a b", "c d") ) with pytest.raises(ValueError, match="at most 1 query per source"): template.instantiate("q", criteria=_criteria(), queries=two, reviewer="obd") diff --git a/plugin/skills/rf-frame-conducted/SKILL.md b/plugin/skills/rf-frame-conducted/SKILL.md index 272aecaa..33c4856b 100644 --- a/plugin/skills/rf-frame-conducted/SKILL.md +++ b/plugin/skills/rf-frame-conducted/SKILL.md @@ -38,6 +38,13 @@ Pass `project`, `role` (`proposer`), `model` (your model id) and the bare skill - Queries: one `keyword` query on **every** source the template names (up to its queries per source), each covering every family or concept the goal names; a source without a query, or a query that leaves a concept out, is a blocking finding. + - Date window: when the goal names a start (a year, or a month), put it on each arXiv query as + `filters: {"listed_since": "YYYY-MM-01"}` (the first day of the start). The window is a + restriction of the review: say in the protocol's rationale why the goal sets it, as the goal + states it. With no start in the goal, set no filter. + - Include only what the goal asks about. When the goal compares methods or primitives, a paper + that only applies an existing one to a task without changing or analysing it is excluded, + unless the goal asks for applications. - At brief and deep the protocol is recorded ready (screening needs it). In a revision, call `protocol_from_template` again with the corrected criteria and queries, a `reason` naming the finding ids it answers, and `effects` (`loosened`, `tightened` or `clarified`) for each From e52dd57d28ecb54cf11ad44c62f51ff5cabff33f Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 29 Nov 2026 18:44:21 +0200 Subject: [PATCH 10/16] fix(review-loop): tell a revising proposer its round and findings in the prompt Shakedown la-brief-8: the write proposer of round 2 never called review_view, found no slot left and stopped, so the loop ended on an unchanged draft. The conductor now passes a revision brief (round, verdict summary, each finding's id, severity, target and text, and that an empty queue does not end the run) through start_run into the built prompt. Co-Authored-By: Claude Opus 5.5 --- platform/src/factory/services/conductor.py | 10 +- platform/src/factory/services/lexical_rank.py | 155 +++++++++++++++++- platform/src/factory/services/review_loop.py | 28 ++++ platform/src/factory/services/runner.py | 10 +- platform/tests/test_review_loop.py | 27 ++- platform/tests/test_runner.py | 7 + 6 files changed, 231 insertions(+), 6 deletions(-) diff --git a/platform/src/factory/services/conductor.py b/platform/src/factory/services/conductor.py index 955b01ae..337d1876 100644 --- a/platform/src/factory/services/conductor.py +++ b/platform/src/factory/services/conductor.py @@ -1115,9 +1115,17 @@ def _advance( if decision.role == "proposer" and decision.stage_id in _QUEUE_UNITS else None ) + preface = ( + review_loop.revision_brief(project, meta.conductor_id, decision.step) + if decision.role == "proposer" and review_loop.is_loop_step(decision.stage_id) + else None + ) token = _STARTING.set((pend, closer)) try: - run_id = start(project, stage, unit_cap=cap) + if preface is None: + run_id = start(project, stage, unit_cap=cap) + else: + run_id = start(project, stage, unit_cap=cap, preface=preface) except FactoryValidationError as exc: decision = _Decision( "pause", decision.step, decision.stage_id, decision.role, "refused", diff --git a/platform/src/factory/services/lexical_rank.py b/platform/src/factory/services/lexical_rank.py index 27b0f67d..081bad44 100644 --- a/platform/src/factory/services/lexical_rank.py +++ b/platform/src/factory/services/lexical_rank.py @@ -21,13 +21,164 @@ import re from collections import Counter from collections.abc import Sequence +from itertools import pairwise MODEL_ID = "factory-lexical-tfidf" VERSION = "1" _WORD = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*") STOP_WORDS = frozenset( - ["a", "about", "above", "after", "again", "against", "all", "also", "am", "an", "and", "any", "are", "as", "at", "be", "because", "been", "before", "being", "below", "between", "both", "but", "by", "can", "could", "did", "do", "does", "doing", "down", "during", "each", "few", "for", "from", "further", "had", "has", "have", "having", "he", "her", "here", "hers", "herself", "him", "himself", "his", "how", "i", "if", "in", "into", "is", "it", "its", "itself", "just", "let", "me", "more", "most", "my", "myself", "no", "nor", "not", "now", "of", "off", "on", "once", "only", "or", "other", "our", "ours", "ourselves", "out", "over", "own", "same", "she", "should", "so", "some", "such", "than", "that", "the", "their", "theirs", "them", "themselves", "then", "there", "these", "they", "this", "those", "through", "to", "too", "under", "until", "up", "upon", "very", "via", "was", "we", "were", "what", "when", "where", "which", "while", "who", "whom", "why", "will", "with", "within", "without", "would", "you", "your", "yours", "yourself", "yourselves", "we", "our", "paper", "propose", "proposed", "show", "shows", "method", "methods", "approach", "based", "new", "using", "use", "used", "results", "result"] + [ + "a", + "about", + "above", + "after", + "again", + "against", + "all", + "also", + "am", + "an", + "and", + "any", + "are", + "as", + "at", + "be", + "because", + "been", + "before", + "being", + "below", + "between", + "both", + "but", + "by", + "can", + "could", + "did", + "do", + "does", + "doing", + "down", + "during", + "each", + "few", + "for", + "from", + "further", + "had", + "has", + "have", + "having", + "he", + "her", + "here", + "hers", + "herself", + "him", + "himself", + "his", + "how", + "i", + "if", + "in", + "into", + "is", + "it", + "its", + "itself", + "just", + "let", + "me", + "more", + "most", + "my", + "myself", + "no", + "nor", + "not", + "now", + "of", + "off", + "on", + "once", + "only", + "or", + "other", + "our", + "ours", + "ourselves", + "out", + "over", + "own", + "same", + "she", + "should", + "so", + "some", + "such", + "than", + "that", + "the", + "their", + "theirs", + "them", + "themselves", + "then", + "there", + "these", + "they", + "this", + "those", + "through", + "to", + "too", + "under", + "until", + "up", + "upon", + "very", + "via", + "was", + "we", + "were", + "what", + "when", + "where", + "which", + "while", + "who", + "whom", + "why", + "will", + "with", + "within", + "without", + "would", + "you", + "your", + "yours", + "yourself", + "yourselves", + "we", + "our", + "paper", + "propose", + "proposed", + "show", + "shows", + "method", + "methods", + "approach", + "based", + "new", + "using", + "use", + "used", + "results", + "result", + ] ) @@ -35,7 +186,7 @@ def terms(text: str) -> list[str]: """The unigrams and bigrams of `text`: lowercased words (hyphenated words kept whole), stop words and one-character tokens removed before the bigrams are formed.""" words = [w for w in _WORD.findall(text.lower()) if len(w) > 1 and w not in STOP_WORDS] - return words + [f"{a} {b}" for a, b in zip(words, words[1:], strict=False)] + return words + [f"{a} {b}" for a, b in pairwise(words)] def _vectors(texts: Sequence[str]) -> list[dict[str, float]]: diff --git a/platform/src/factory/services/review_loop.py b/platform/src/factory/services/review_loop.py index c973662b..babb7c4a 100644 --- a/platform/src/factory/services/review_loop.py +++ b/platform/src/factory/services/review_loop.py @@ -246,6 +246,34 @@ class ReviewView(StrictModel): """`: ` once the loop has ended.""" +def revision_brief(project: Project, conductor_id: str, step: int) -> str | None: + """The prompt text that tells a loop step's proposer it is revising (shakedown la-brief-8): the + round, the last verdict's findings with ids and text, and what ends the run. None when the last + verdict is not `revise` (a first round, or a loop that ended).""" + done = verdicts(project, conductor_id, step) + if not done or done[-1].verdict != "revise" or loop_end(done) is not None: + return None + last = done[-1] + lines = [ + f"This run is a revision: round {last.round + 1} of the review loop of step " + f"`{last.stage_id}`. The reviewer's round-{last.round} verdict is `revise`: {last.summary}", + "", + "Findings (read them in full with `review_view`):", + ] + lines += [f"- {f.finding_id} [{f.severity}] {f.target}: {f.text}" for f in last.findings] + lines += [ + "", + "Change the step's output to address each blocking finding: revise, add or retract what " + "the finding names with the step's own tools (for a draft: rewrite, add or retract " + "sentences; a section a finding says is missing is added to the outline or written into " + "the nearest section). Address the minor findings where it costs little. An empty work " + "queue does not end this run: the revision is the work. Then answer every blocking " + "finding with `review_reply` (`addressed`, saying what changed, or `declined`, saying " + "why), and stop.", + ] + return "\n".join(lines) + + def review_view(project: Project) -> ReviewView: """The review loop of the conductor's current loop step: its verdicts and replies so far.""" from factory.services import conductor diff --git a/platform/src/factory/services/runner.py b/platform/src/factory/services/runner.py index 1459723b..3229f438 100644 --- a/platform/src/factory/services/runner.py +++ b/platform/src/factory/services/runner.py @@ -968,6 +968,7 @@ def _prompt( spec: StageSpec, unit_cap: int, assignment: RoleAssignment | None = None, + preface: str | None = None, ) -> str: if stage in SPAR2_STAGES: return _spar2_prompt(project, stage, spec, unit_cap, assignment) @@ -1034,6 +1035,7 @@ def _prompt( f"(you are pass `{label}`).\n\n" f"Parameters for every factory call: {parameters}skill `{spec.skill}`.\n\n" f"{extra}" + f"{'' if preface is None else preface + chr(10) * 2}" f"Limit: stop after {unit_cap} units or when the queue is empty, whichever comes first. " f"A unit is one {spec.unit}. The server refuses further units with `cap-reached` once " "the limit is served: then stop. Use no other tools. Finally print " @@ -1077,6 +1079,7 @@ def build_command( run_id: str | None = None, prompt_override: str | None = None, assignment: RoleAssignment | None = None, + preface: str | None = None, ) -> tuple[list[str], dict[str, JsonValue], str]: """`(argv, mcp config, prompt)` for one run of `stage`. Pure: starts and writes nothing. `prompt_override` is used in place of the built prompt (a resumed run's recorded prompt).""" @@ -1088,7 +1091,7 @@ def build_command( prompt = ( prompt_override if prompt_override is not None - else _prompt(project, stage, spec, unit_cap, assignment) + else _prompt(project, stage, spec, unit_cap, assignment, preface) ) argv = [ claude, @@ -1545,6 +1548,7 @@ def start_run( resumes: str | None = None, prompt_override: str | None = None, assignment: RoleAssignment | None = None, + preface: str | None = None, ) -> str: """Start one run of `stage`; returns its `run_id` once the process is started and recorded. @@ -1557,7 +1561,8 @@ def start_run( new run is a new run (the earlier run's events are never edited) that reuses the earlier run's recorded prompt, tools and model, and names it in `runner.started`. `unit_cap` then defaults to the earlier run's. `prompt_override` replaces the built prompt (and is what a - resume passes after reading the blob). + resume passes after reading the blob). `preface` is conductor text set before the limit line + of the built prompt (a review loop's revision brief, `review_loop.revision_brief`). A role stage of the agentic spar (`spar2-*`) is started only with its `assignment`, by the coordinator (`spar_v2.advance`); the assignment must be the request's next role, and the start @@ -1636,6 +1641,7 @@ def start_run( run_id=run_id, prompt_override=prompt_override, assignment=assignment, + preface=preface, ) folder.mkdir(parents=True, exist_ok=True) (folder / "starting").write_text(str(time.time()), encoding="utf-8") diff --git a/platform/tests/test_review_loop.py b/platform/tests/test_review_loop.py index 30696df2..131f0dd5 100644 --- a/platform/tests/test_review_loop.py +++ b/platform/tests/test_review_loop.py @@ -55,10 +55,14 @@ class Runs: def __init__(self) -> None: self.stages: list[str] = [] + self.prefaces: list[str | None] = [] self.ids = itertools.count(1) - def start(self, project: Project, stage: str, *, unit_cap: int) -> str: + def start( + self, project: Project, stage: str, *, unit_cap: int, preface: str | None = None + ) -> str: self.stages.append(stage) + self.prefaces.append(preface) return project.ids.new("rnr") @@ -226,6 +230,27 @@ def test_revise_runs_the_proposer_again_then_a_new_reviewer( assert view == [1, 2] +def test_a_revision_run_is_told_its_findings( + settings: Settings, clock: FixedClock, reviewer: Actor +) -> None: + """Shakedown la-brief-8: the write proposer of round 2 never read the verdict and stopped on an + empty slot queue; the conductor now states the revision and its findings in the prompt.""" + project = _make(settings, clock, "brief") + runs = Runs() + conductor.begin_conductor(project, _plan(Tier.BRIEF, "frame", "gather")) + _step(project, runs) + _step(project, runs) + minor = FindingInput(severity="minor", target="NG01", text="could be sharper") + review_loop.record_verdict(project, reviewer, "revise", [_blocking(), minor], "two issues") + _step(project, runs) + assert runs.prefaces[:2] == [None, None] + preface = runs.prefaces[2] + assert preface is not None + assert "round 2" in preface and "R1.F1" in preface and "R1.F2" in preface + assert _blocking().text in preface and "could be sharper" in preface + assert "review_reply" in preface and "empty" in preface + + def test_findings_are_numbered_by_the_platform( settings: Settings, clock: FixedClock, reviewer: Actor ) -> None: diff --git a/platform/tests/test_runner.py b/platform/tests/test_runner.py index 53c592b2..33c8155c 100644 --- a/platform/tests/test_runner.py +++ b/platform/tests/test_runner.py @@ -111,6 +111,13 @@ def test_build_command_names_model_tools_skill_and_cap(project: Project) -> None assert loaded["mcpServers"]["factory"]["args"] == ["serve"] +def test_a_preface_sits_before_the_limit_line(project: Project) -> None: + _, _, plain = runner.build_command(project, "screen", 7) + _, _, prefaced = runner.build_command(project, "screen", 7, preface="This run is a revision.") + assert "This run is a revision." not in plain + assert prefaced.index("This run is a revision.") < prefaced.index("Limit: stop after 7") + + def test_child_is_denied_the_builtin_tools_and_asks_nothing(project: Project) -> None: argv, _, _ = runner.build_command(project, "screen") start = argv.index("--disallowedTools") + 1 From 7fd6d535222451ad009abd2e7a401c0cae7d6bec Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 29 Nov 2026 18:47:33 +0200 Subject: [PATCH 11/16] feat(brief): cap evidence rows per work at 8 and name the headline results in the prompt Shakedown la-brief-8: uncapped, the brief extractor copied whole results tables (11 to over 184 rows a work, about 35 minutes for 20 works). extract max_rows_per_work is now an enforced tier cap: a new row past it is rejected with tier-cap-reached, a correction is not a new row. The extract prompt states the cap and asks for the main method against its strongest baseline on its main benchmarks, main results table first. Co-Authored-By: Claude Opus 5.5 --- platform/src/factory/services/extraction.py | 12 ++++ platform/src/factory/services/runner.py | 12 ++++ platform/src/factory/services/tier_caps.py | 8 ++- platform/src/factory/tiers/plans.py | 5 +- platform/tests/test_extraction_row_cap.py | 69 +++++++++++++++++++++ platform/tests/test_runner.py | 13 ++++ 6 files changed, 115 insertions(+), 4 deletions(-) create mode 100644 platform/tests/test_extraction_row_cap.py diff --git a/platform/src/factory/services/extraction.py b/platform/src/factory/services/extraction.py index 84d898ea..66870757 100644 --- a/platform/src/factory/services/extraction.py +++ b/platform/src/factory/services/extraction.py @@ -143,6 +143,7 @@ session_served_kind, task_content, ) +from factory.services.tier_caps import EXTRACT_ROW_CAP, cap_refusal, tier_cap from factory.services.work_ref import stored_spelling __all__ = [ @@ -1337,6 +1338,7 @@ def _record( used: set[str] = set() row_errors: list[ItemError] = [] accepted_rows: list[_Row] = [] + row_cap = tier_cap(project, EXTRACT_ROW_CAP) if unit.scope == Scope.EVIDENCE else None for index, row in enumerate(rows): target = row_targets.get(index) issues, verified = _row_issues(pack, schema, row, unit, manifest, corpus) @@ -1356,6 +1358,16 @@ def _record( issues.append( ValidationIssue(f"fields.{VALUE_FIELD}", options.duplicate_reason) ) + if ( + not issues + and row_cap is not None + and target is None + and len(live) - len(used) + sum(a.index not in row_targets for a in accepted_rows) + >= row_cap + ): + issues.append( + cap_refusal(EXTRACT_ROW_CAP, row_cap, "the rows of one work").issues[0] + ) if issues or verified is None: row_errors.append(ItemError(index=index, issues=issues)) continue diff --git a/platform/src/factory/services/runner.py b/platform/src/factory/services/runner.py index 3229f438..338dedb6 100644 --- a/platform/src/factory/services/runner.py +++ b/platform/src/factory/services/runner.py @@ -1023,6 +1023,18 @@ def _prompt( f"{SCREEN_BATCH} records is {SCREEN_BATCH} units. If a stage serves no batch because " "of a `blocked` reason, report it verbatim and go on to the next stage.\n\n" ) + if stage in ("extract", "extract-b"): + from factory.services.tier_caps import EXTRACT_ROW_CAP, tier_cap + + rows = tier_cap(project, EXTRACT_ROW_CAP) + if rows is not None: + extra += ( + f"Row cap for this tier: at most {rows} live rows a work; the platform rejects " + "rows past it (`tier-cap-reached`). Choose the headline results: the work's own " + "main method against its strongest baseline on its main benchmarks, from the " + "main results table first; leave out ablations, per-class breakdowns and " + "repeated settings. A correction that supersedes a row is not a new row.\n\n" + ) if spec.skill == "rf-intuition": extra = ( "Proposing background concepts (`concept_propose`, `concept_link`) is out of scope " diff --git a/platform/src/factory/services/tier_caps.py b/platform/src/factory/services/tier_caps.py index bf05bce4..6417b8ec 100644 --- a/platform/src/factory/services/tier_caps.py +++ b/platform/src/factory/services/tier_caps.py @@ -26,8 +26,12 @@ ACQUIRE_CAP: Final = ("acquire", "max_included") """(stage, cap key): the works full-text fetch may take on.""" -ENFORCED_CAPS: Final = frozenset({SCREEN_CAP, ACQUIRE_CAP}) -"""The (stage, key) caps the platform refuses past (the two above). Every other cap of a plan is +EXTRACT_ROW_CAP: Final = ("extract", "max_rows_per_work") +"""(stage, cap key): the live evidence rows one work may hold in one pass (shakedown la-brief-8: +uncapped, the extractor copied whole results tables, 11 to over 184 rows a work).""" + +ENFORCED_CAPS: Final = frozenset({SCREEN_CAP, ACQUIRE_CAP, EXTRACT_ROW_CAP}) +"""The (stage, key) caps the platform refuses past (the three above). Every other cap of a plan is advisory: the stage's skill tells the agent to stay within it and nothing checks (finding I4).""" CapEnforcement = Literal["enforced", "advisory"] diff --git a/platform/src/factory/tiers/plans.py b/platform/src/factory/tiers/plans.py index 1f9e3aea..8c24c440 100644 --- a/platform/src/factory/tiers/plans.py +++ b/platform/src/factory/tiers/plans.py @@ -162,8 +162,9 @@ def _brief() -> TierPlan: _stage( "extract", skill=s, - caps={"passes": 1, "max_fields": 6}, - note="a template schema; pass A, then pass B opened for the 1% dual sample", + caps={"passes": 1, "max_fields": 6, "max_rows_per_work": 8}, + note="a template schema, at most 8 rows a work (the headline results); pass A, " + "then pass B opened for the 1% dual sample", second_pass=True, ), _stage("understand", skipped=True), diff --git a/platform/tests/test_extraction_row_cap.py b/platform/tests/test_extraction_row_cap.py new file mode 100644 index 00000000..aa334b68 --- /dev/null +++ b/platform/tests/test_extraction_row_cap.py @@ -0,0 +1,69 @@ +"""The per-work row cap of a capped tier (shakedown la-brief-8): uncapped, the brief extractor +copied whole results tables, 11 to over 184 rows a work. Past the cap a row is rejected with +`tier-cap-reached`; a correction (a row that supersedes a live one) is not a new row.""" + +from __future__ import annotations + +import pytest + +from factory.events.envelope import Actor +from factory.model.levels import Tier +from factory.model.screening import PassLabel +from factory.services import extraction +from factory.services.context import Project +from factory.services.extraction import extract_next, extract_record +from factory.services.tier_caps import EXTRACT_ROW_CAP +from factory.tiers.plans import PLANS +from tests.extraction_helpers import ( # noqa: F401 + _r, + ext_a, + screened, + world, +) + + +def _capped(monkeypatch: pytest.MonkeyPatch, cap: int) -> None: + monkeypatch.setattr( + extraction, "tier_cap", lambda _p, which: cap if which == EXTRACT_ROW_CAP else None + ) + + +def test_the_brief_caps_rows_per_work() -> None: + assert PLANS[Tier.BRIEF].stage("extract").caps["max_rows_per_work"] == 8 + + +def test_rows_past_the_cap_are_rejected( + project: Project, ext_a: Actor, world: list[str], monkeypatch: pytest.MonkeyPatch # noqa: F811 +) -> None: + _capped(monkeypatch, 1) + batch = extract_next(project, ext_a, PassLabel.A).batch + assert batch is not None + res = extract_record(project, ext_a, batch.task_id, [_r("1"), _r("2", "t1.r3.c3")]) + assert len(res.rows.written) == 1 + assert [e.index for e in res.rows.rejected] == [1] + assert "tier-cap-reached" in res.rows.rejected[0].issues[0].reason + again = extract_record(project, ext_a, batch.task_id, [_r("2", "t1.r3.c3")]) + assert again.rows.written == [] and len(again.rows.rejected) == 1 + + +def test_a_correction_at_the_cap_is_accepted( + project: Project, ext_a: Actor, world: list[str], monkeypatch: pytest.MonkeyPatch # noqa: F811 +) -> None: + _capped(monkeypatch, 1) + batch = extract_next(project, ext_a, PassLabel.A).batch + assert batch is not None + first = extract_record(project, ext_a, batch.task_id, [_r(value="1")]) + assert len(first.rows.written) == 1 + fixed = extract_record( + project, ext_a, batch.task_id, [_r("2", "t1.r3.c3")], supersedes={0: first.rows.written[0]} + ) + assert len(fixed.rows.written) == 1, fixed.rows.rejected + + +def test_an_uncapped_project_takes_every_row( + project: Project, ext_a: Actor, world: list[str] # noqa: F811 +) -> None: + batch = extract_next(project, ext_a, PassLabel.A).batch + assert batch is not None + rows = [_r("1"), _r("2", "t1.r3.c3")] + assert len(extract_record(project, ext_a, batch.task_id, rows).rows.written) == 2 diff --git a/platform/tests/test_runner.py b/platform/tests/test_runner.py index 33c8155c..49ea2f48 100644 --- a/platform/tests/test_runner.py +++ b/platform/tests/test_runner.py @@ -780,3 +780,16 @@ def test_runner_started_omits_exploratory_when_false() -> None: assert RunnerStarted.model_validate(plain).exploratory is False marked = RunnerStarted.model_validate({**fields, "exploratory": True}).model_dump(mode="json") assert marked["exploratory"] is True + + +def test_the_extract_prompt_names_the_cap( + project: Project, monkeypatch: pytest.MonkeyPatch +) -> None: + from factory.services import tier_caps + + monkeypatch.setattr(tier_caps, "tier_cap", lambda _p, which: 8) + _, _, prompt = runner.build_command(project, "extract", 3) + assert "at most 8 live rows a work" in prompt and "main results table" in prompt + monkeypatch.setattr(tier_caps, "tier_cap", lambda _p, which: None) + _, _, plain = runner.build_command(project, "extract", 3) + assert "Row cap" not in plain From 1b81ed626fb09869f53b8781f004c490b2de7a9d Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 29 Nov 2026 18:47:37 +0200 Subject: [PATCH 12/16] style: format Co-Authored-By: Claude Opus 5.5 --- platform/tests/test_extraction_row_cap.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/platform/tests/test_extraction_row_cap.py b/platform/tests/test_extraction_row_cap.py index aa334b68..1cadb5f8 100644 --- a/platform/tests/test_extraction_row_cap.py +++ b/platform/tests/test_extraction_row_cap.py @@ -33,7 +33,10 @@ def test_the_brief_caps_rows_per_work() -> None: def test_rows_past_the_cap_are_rejected( - project: Project, ext_a: Actor, world: list[str], monkeypatch: pytest.MonkeyPatch # noqa: F811 + project: Project, + ext_a: Actor, + world: list[str], + monkeypatch: pytest.MonkeyPatch, # noqa: F811 ) -> None: _capped(monkeypatch, 1) batch = extract_next(project, ext_a, PassLabel.A).batch @@ -47,7 +50,10 @@ def test_rows_past_the_cap_are_rejected( def test_a_correction_at_the_cap_is_accepted( - project: Project, ext_a: Actor, world: list[str], monkeypatch: pytest.MonkeyPatch # noqa: F811 + project: Project, + ext_a: Actor, + world: list[str], + monkeypatch: pytest.MonkeyPatch, # noqa: F811 ) -> None: _capped(monkeypatch, 1) batch = extract_next(project, ext_a, PassLabel.A).batch @@ -61,7 +67,9 @@ def test_a_correction_at_the_cap_is_accepted( def test_an_uncapped_project_takes_every_row( - project: Project, ext_a: Actor, world: list[str] # noqa: F811 + project: Project, + ext_a: Actor, + world: list[str], # noqa: F811 ) -> None: batch = extract_next(project, ext_a, PassLabel.A).batch assert batch is not None From e385babacf541043c236274c24c2c7fcb5b65e3c Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 29 Nov 2026 18:47:52 +0200 Subject: [PATCH 13/16] style: file-level noqa for imported fixtures Co-Authored-By: Claude Opus 5.5 --- platform/tests/test_extraction_row_cap.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/platform/tests/test_extraction_row_cap.py b/platform/tests/test_extraction_row_cap.py index 1cadb5f8..55dda73d 100644 --- a/platform/tests/test_extraction_row_cap.py +++ b/platform/tests/test_extraction_row_cap.py @@ -1,3 +1,4 @@ +# ruff: noqa: F811 (pytest fixtures imported from extraction_helpers) """The per-work row cap of a capped tier (shakedown la-brief-8): uncapped, the brief extractor copied whole results tables, 11 to over 184 rows a work. Past the cap a row is rejected with `tier-cap-reached`; a correction (a row that supersedes a live one) is not a new row.""" @@ -36,7 +37,7 @@ def test_rows_past_the_cap_are_rejected( project: Project, ext_a: Actor, world: list[str], - monkeypatch: pytest.MonkeyPatch, # noqa: F811 + monkeypatch: pytest.MonkeyPatch, ) -> None: _capped(monkeypatch, 1) batch = extract_next(project, ext_a, PassLabel.A).batch @@ -53,7 +54,7 @@ def test_a_correction_at_the_cap_is_accepted( project: Project, ext_a: Actor, world: list[str], - monkeypatch: pytest.MonkeyPatch, # noqa: F811 + monkeypatch: pytest.MonkeyPatch, ) -> None: _capped(monkeypatch, 1) batch = extract_next(project, ext_a, PassLabel.A).batch @@ -69,7 +70,7 @@ def test_a_correction_at_the_cap_is_accepted( def test_an_uncapped_project_takes_every_row( project: Project, ext_a: Actor, - world: list[str], # noqa: F811 + world: list[str], ) -> None: batch = extract_next(project, ext_a, PassLabel.A).batch assert batch is not None From c5afa773aa9880cea7f0d607afd1f34a6d0c913c Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 29 Nov 2026 18:55:16 +0200 Subject: [PATCH 14/16] feat(brief): screen by yield to 100, acquire 30, rank lexically, 30 runs Shakedown la-brief-8: the top 40 by seed similarity were 55% includes, so the flat cap of 40 ended screening while check-set works sat at ranks 100-960. The brief now screens in ranked order until 20 consecutive excludes (a ranked batch of 20 with no include), at most 100; acquire takes up to 30 included works (the plan's max_papers); the run budget is 30. A brief ranks with the lexical scorer even when SPECTER2 weights are configured: it put the same check-set works in the top 40 in seconds instead of 10 minutes. Co-Authored-By: Claude Opus 5.5 --- platform/src/factory/services/conductor.py | 17 +++++++------ platform/src/factory/tiers/plans.py | 13 ++++++---- platform/tests/test_brief_note.py | 2 +- platform/tests/test_lexical_rank.py | 24 +++++++++++++++++++ platform/tests/test_tier_caps.py | 2 +- platform/tests/test_tier_protocol.py | 2 +- platform/tests/test_tiers.py | 10 ++++---- platform/tests/test_tiers_walking_skeleton.py | 2 +- 8 files changed, 51 insertions(+), 21 deletions(-) diff --git a/platform/src/factory/services/conductor.py b/platform/src/factory/services/conductor.py index 337d1876..2755dfcb 100644 --- a/platform/src/factory/services/conductor.py +++ b/platform/src/factory/services/conductor.py @@ -46,7 +46,7 @@ PauseReason, StepOutcome, ) -from factory.model.levels import AutonomyLevel +from factory.model.levels import AutonomyLevel, Tier from factory.modules.contract import PolicyKind from factory.services import review_loop, runner from factory.services.call_memo import entering @@ -780,9 +780,11 @@ def _plan_blob(project: Project, plan: PlanLike, steps: Sequence[str]) -> str: def rank_before_screening(project: Project) -> None: """Rank the title/abstract queue once, as the system, before its first screening run (shakedown la-brief-6: unranked, a capped tier screened the first 40 of 13k records in work-id order). - Ranked serving and the stopping rule then use it. The embedding ranker runs when its weights - are configured (`FACTORY_RANKER_MODEL`), the lexical one otherwise; the ranking records which. - A refusal (no seed with a title, nothing to rank) leaves the queue in its existing order.""" + Ranked serving and the stopping rule then use it. A brief ranks lexically (shakedown + la-brief-8: SPECTER2 took 10 of 60 minutes on the CPU and put the same check-set works in the + top 40 as TF-IDF); other tiers use the embedding ranker when its weights are configured + (`FACTORY_RANKER_MODEL`), the lexical one otherwise. The ranking records which. A refusal (no + seed with a title, nothing to rank) leaves the queue in its existing order.""" import os from factory.services import ranking @@ -792,9 +794,10 @@ def rank_before_screening(project: Project) -> None: if ranking_positions(project): return - scorer: Embedder | LexicalScorer = ( - Specter2Embedder() if os.environ.get(MODEL_ENV) else LexicalScorer() - ) + from factory.services.project import project_levels + + embed = os.environ.get(MODEL_ENV) and project_levels(project).tier is not Tier.BRIEF + scorer: Embedder | LexicalScorer = Specter2Embedder() if embed else LexicalScorer() try: ranking.compute_ranking(project, scorer) except FactoryValidationError: diff --git a/platform/src/factory/tiers/plans.py b/platform/src/factory/tiers/plans.py index 8c24c440..01c6ec80 100644 --- a/platform/src/factory/tiers/plans.py +++ b/platform/src/factory/tiers/plans.py @@ -100,7 +100,10 @@ def _uncapped() -> tuple[StagePlan, ...]: sources=("arxiv",), queries_per_source=1, passes=1, - stop_after_consecutive_excludes=10, + # 20 (a ranked batch of 20 with no include) with a ceiling of 100, in place of a flat 40 + # (shakedown la-brief-8: the top 40 by seed similarity were 55% includes, and the cap, not + # the yield, ended screening while check-set works sat at ranks 100-960). + stop_after_consecutive_excludes=20, pack="ml-benchmark", pack_version=1, fields=_BRIEF_FIELDS, @@ -150,13 +153,13 @@ def _brief() -> TierPlan: _stage( "screen", skill=s, - caps={"passes": 1, "max_screened": 40}, - note="one pass in ranked order with the stopping rule", + caps={"passes": 1, "max_screened": 100}, + note="one pass in ranked order until 20 consecutive excludes, at most 100", ), _stage( "acquire", skill=s, - caps={"max_included": 20, "open_access_only": 1}, + caps={"max_included": 30, "open_access_only": 1}, note="open-access full texts only", ), _stage( @@ -179,7 +182,7 @@ def _brief() -> TierPlan: ), _full_text(s, caps={"passes": 1}, note="one pass over the acquired works"), ), - limits=Limits(max_papers=30, max_minutes=60, max_runs=20), + limits=Limits(max_papers=30, max_minutes=60, max_runs=30), protocol_template=_BRIEF_PROTOCOL, report_template=ReportTemplate( sections=("question", "search", "screening", "included", "evidence", "quotes", "level"), diff --git a/platform/tests/test_brief_note.py b/platform/tests/test_brief_note.py index 63039af2..352b677d 100644 --- a/platform/tests/test_brief_note.py +++ b/platform/tests/test_brief_note.py @@ -142,4 +142,4 @@ def test_the_note_marks_each_cap_enforced_or_advisory( project = init_project(settings, "demo", None, session=SESSION, clock=clock, tier="brief") text = render_brief_note(brief_note(project)) assert "- cap gather: sources: 2 (advisory)" in text - assert "- cap screen: max_screened: 40 (enforced)" in text + assert "- cap screen: max_screened: 100 (enforced)" in text diff --git a/platform/tests/test_lexical_rank.py b/platform/tests/test_lexical_rank.py index 6156db49..ab5a2af4 100644 --- a/platform/tests/test_lexical_rank.py +++ b/platform/tests/test_lexical_rank.py @@ -72,3 +72,27 @@ def test_the_conductor_ranks_once_before_screening( def test_a_refused_ranking_leaves_the_queue_unranked(project: Project) -> None: conductor.rank_before_screening(project) # no seeds, nothing to rank: refused, not raised assert not ranking_positions(project) + + +def test_a_brief_ranks_lexically_even_with_embedding_weights_configured( + project: Project, + agent: Actor, + human: Actor, + mock_sources: SourcesFor, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Shakedown la-brief-8: SPECTER2 took 10 of a brief's 60 minutes for the same top-40 recall.""" + from types import SimpleNamespace + + from factory.model.levels import Tier + from factory.services import project as project_module + from factory.services.ranking import latest_ranking + + _setup(project, agent, human, mock_sources, dual_sample=0.5, random_works=3) + monkeypatch.setenv("FACTORY_RANKER_MODEL", "/nonexistent/weights") + monkeypatch.setattr( + project_module, "project_levels", lambda _p: SimpleNamespace(tier=Tier.BRIEF) + ) + conductor.rank_before_screening(project) + view = latest_ranking(project) + assert view is not None and view.model_id == MODEL_ID diff --git a/platform/tests/test_tier_caps.py b/platform/tests/test_tier_caps.py index a4411643..f5aed6b4 100644 --- a/platform/tests/test_tier_caps.py +++ b/platform/tests/test_tier_caps.py @@ -165,7 +165,7 @@ def test_cap_lines_name_the_enforcement(settings: Settings, clock: FixedClock) - lines = cap_lines(Tier.BRIEF) assert "cap gather sources: 2 (advisory)" in lines - assert "cap screen max_screened: 40 (enforced)" in lines + assert "cap screen max_screened: 100 (enforced)" in lines assert cap_lines(Tier.PILOT) == () project = _tier_project(settings, clock, "brief", "brief") assert "cap gather sources: 2 (advisory)" in level_statement(project).lines diff --git a/platform/tests/test_tier_protocol.py b/platform/tests/test_tier_protocol.py index 1fe76886..31f22ea6 100644 --- a/platform/tests/test_tier_protocol.py +++ b/platform/tests/test_tier_protocol.py @@ -55,7 +55,7 @@ def test_the_brief_template_is_recorded_as_a_draft( spec = current_protocol(project) assert spec is not None assert [s.name for s in spec.spec.sources] == ["arxiv"] # la-brief-6: no OpenAlex in a brief - assert spec.spec.screening.stop_after_consecutive_excludes == 10 + assert spec.spec.screening.stop_after_consecutive_excludes == 20 reviewer = spec.spec.screening.reviewers[0] assert (reviewer.actor, reviewer.kind) == ("obd", "human") # the creator, not the agent diff --git a/platform/tests/test_tiers.py b/platform/tests/test_tiers.py index 13ba3206..565ae10a 100644 --- a/platform/tests/test_tiers.py +++ b/platform/tests/test_tiers.py @@ -69,14 +69,14 @@ def test_pilot_and_systematic_have_no_caps_and_skip_nothing(tier: Tier) -> None: def test_brief_caps_are_the_ruled_ones() -> None: plan = plan_for(Tier.BRIEF) - assert (plan.limits.max_papers, plan.limits.max_minutes, plan.limits.max_runs) == (30, 60, 20) # type: ignore[union-attr] + assert (plan.limits.max_papers, plan.limits.max_minutes, plan.limits.max_runs) == (30, 60, 30) # type: ignore[union-attr] assert plan.stage("gather").caps == { "sources": 2, "searches_per_source": 1, "snowball_rounds": 0, } - assert plan.stage("screen").caps["max_screened"] == 40 - assert plan.stage("acquire").caps["max_included"] == 20 + assert plan.stage("screen").caps["max_screened"] == 100 + assert plan.stage("acquire").caps["max_included"] == 30 assert plan.stage("extract").caps["max_fields"] == 6 assert [s.stage_id for s in plan.stages if s.skipped] == ["understand", "develop", "maintain"] assert RIGOR_OF_TIER[Tier.BRIEF].value == "exploratory" @@ -108,7 +108,7 @@ def test_skipped_steps_are_computed_from_the_plan() -> None: "develop: skipped", "maintain: skipped", "gather: no snowball rounds", - "screen: max screened capped at 40", + "screen: max screened capped at 100", "frame: no press reviews", ): assert expected in steps @@ -194,7 +194,7 @@ def test_brief_new_plan_and_status(tmp_path: Path) -> None: assert "exploratory" in made.output plan = runner.invoke(app, ["brief", "plan", "lin"], env=env) assert plan.exit_code == 0, plan.output - for line in ("tier brief", "limits: 30 papers, 60 minutes, 20 runs", "rf-brief", "understand"): + for line in ("tier brief", "limits: 30 papers, 60 minutes, 30 runs", "rf-brief", "understand"): assert line in plan.output assert "skipped:" in plan.output and "gather: no snowball rounds" in plan.output status = runner.invoke(app, ["brief", "status", "lin"], env=env) diff --git a/platform/tests/test_tiers_walking_skeleton.py b/platform/tests/test_tiers_walking_skeleton.py index 50335c3c..457233c3 100644 --- a/platform/tests/test_tiers_walking_skeleton.py +++ b/platform/tests/test_tiers_walking_skeleton.py @@ -372,7 +372,7 @@ def test_full_text_is_screened_by_its_own_run_between_acquire_and_extract( ] assert decisions assert {e.actor.session for e in decisions} == scripted.sessions[runs["screen-ft"]] - assert scripted.automatic_calls == [20] # once, bounded by the plan's `acquire.max_included` + assert scripted.automatic_calls == [30] # once, bounded by the plan's `acquire.max_included` order = [e.payload["stage_id"] for e in _events(project) if e.type == "conductor.step_started"] assert ( order.index("acquire") + 1 From 9afb8b8c704a11b9c413987b507435c7ef7ff627 Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 29 Nov 2026 19:54:39 +0200 Subject: [PATCH 15/16] feat(write): coverage in the limits; revision and coverage rules for writer and reviewer Adopted from the deep-research comparison (academic-research-skills seed recall and skew check, GPT-Researcher's reviser). The limits section offers stat:prisma:screened, pending and included, so a note can say how much of the search was screened (la-brief-9: the writer could not write '100 of 1811' for want of a stat). rf-write: the limits name every family, setting or seed the question names that has no included work; a revision run works from review_view even when no slot is served. rf-review: at write, a named seed, family or setting neither covered nor named in the limits, or limits silent on screening coverage, is blocking; a skew to one family must be stated. Co-Authored-By: Claude Opus 5.5 --- platform/src/factory/services/outline.py | 10 +++++++++- platform/tests/test_outline.py | 8 +++++++- plugin/skills/rf-review/SKILL.md | 8 ++++++-- plugin/skills/rf-write/SKILL.md | 15 ++++++++++++++- 4 files changed, 36 insertions(+), 5 deletions(-) diff --git a/platform/src/factory/services/outline.py b/platform/src/factory/services/outline.py index f253d1d8..a7114cc5 100644 --- a/platform/src/factory/services/outline.py +++ b/platform/src/factory/services/outline.py @@ -311,7 +311,15 @@ def _limits_section(project: Project, report: EvidenceReport) -> OutlineSection: kind="limits", title_ref="limits", works=[], - supports=["stat:included-works", "stat:not-stated-count"], + # screening coverage (shakedown la-brief-8: the reviewer asked the note to say that 40 of + # 1,696 records were screened, and the limits offered no stat that holds those numbers) + supports=[ + "stat:included-works", + "stat:not-stated-count", + "stat:prisma:screened", + "stat:prisma:pending", + "stat:prisma:included", + ], conflicts=[], notes=notes, ) diff --git a/platform/tests/test_outline.py b/platform/tests/test_outline.py index ae3d1a4f..6a60ec53 100644 --- a/platform/tests/test_outline.py +++ b/platform/tests/test_outline.py @@ -172,7 +172,13 @@ def test_unattached_claims_by_type(project: Project, ww: WWorld) -> None: def test_limits_section_lists_codes(project: Project, ww: WWorld) -> None: limits = section(build_outline(project), "limits") - assert limits.supports == ["stat:included-works", "stat:not-stated-count"] + assert limits.supports == [ + "stat:included-works", + "stat:not-stated-count", + "stat:prisma:screened", + "stat:prisma:pending", + "stat:prisma:included", + ] assert limits.notes assert all(" " not in n for n in limits.notes) # fixed codes, never prose diff --git a/plugin/skills/rf-review/SKILL.md b/plugin/skills/rf-review/SKILL.md index f2de6eb2..3a33b4a1 100644 --- a/plugin/skills/rf-review/SKILL.md +++ b/plugin/skills/rf-review/SKILL.md @@ -27,7 +27,10 @@ Pass `project`, `role` (`verifier`), `model` (your model id) and the bare skill - Write (`review-write`): `draft_list`, `draft_render`, `claims_digest`, `document_read`. Check that each evidence sentence is supported by its cited passage (`chat_verify` for a quote), that no number is typed outside the report, that the note answers the question it states, and that - what was skipped is said. + what was skipped is said. Check coverage against the question, not only support: list the + families, settings and seeds the question names, and for each find the sentences that cover + it; one with no sentence must be named in the limits. When most included works belong to one + family, the limits must say so, because the comparison then rests on a skewed sample. 3. Findings. Each one: `severity` `blocking` (the output is wrong, unsupported or misses what the goal asks) or `minor` (could be better); `target` (the slot, criterion, query, section or sentence); `text` (what is wrong and what would fix it, concretely). A finding that restates an @@ -36,7 +39,8 @@ Pass `project`, `role` (`verifier`), `model` (your model id) and the bare skill Always blocking, whatever else holds: a source the protocol lists with no query on it; a family, concept or setting the goal names that a query or sub-question leaves out; a step output that does not exist (no draft, no question); an evidence sentence its passage does not - support. + support; at write, a seed, family or setting the question names that the note neither covers nor + names in its limits, and limits that do not say how much of the search was screened. 4. Verdict with `review_record`: `accept` when no blocking finding is left (minor ones may be listed), else `revise`. One short `summary`: what you checked and what holds. 5. End with a short report: the verdict, the findings by id, and any refusal verbatim. diff --git a/plugin/skills/rf-write/SKILL.md b/plugin/skills/rf-write/SKILL.md index 18bd044f..3316fb2f 100644 --- a/plugin/skills/rf-write/SKILL.md +++ b/plugin/skills/rf-write/SKILL.md @@ -47,7 +47,11 @@ citation key. 5. Where the slot lists a disagreement between independent results, state the disagreement; do not average it and do not pick one. 6. Write "the corpus does not support ..." sentences from the limits slot, using its codes and the - `stat:` supports it offers. + `stat:` supports it offers. The limits always say what was not read: how many records the search + found and how many stayed unscreened (`stat:prisma:screened`, `stat:prisma:pending`), and which + family, setting or seed the question names has no included work, by name (a `structural` + sentence with no number). A reader must be able to tell a gap in the literature from a gap in + the screening. 7. Compare across groups only with supports from one group. A comparison that cites cells of two comparability groups is flagged `cross-group`. 8. Read the result of each call. A rejected sentence names the field and the reason; fix that and @@ -60,6 +64,15 @@ citation key. 11. When the outline has changed, pin the draft to the fresh one with `draft_repin` and pull slots again with `draft_next`; the old slot tasks are retired. +## Revision + +When the prompt says the run is a revision, the reviewer's findings are the work, even when +`draft_next` serves no slot: read them with `review_view`, then supersede, add or retract the +sentences each one names (`draft_write` with `supersedes`, in the section the finding targets, or +in the limits when the fix is to say what is missing). Answer every blocking finding with +`review_reply`: `addressed`, with the sentence ids that changed, or `declined`, with the reason (for +example, the material to fix it is not in the corpus, and the limits now say so). + ## Stopping and human steps Verifying, auditing, rendering and releasing a draft (`draft_release`, through the gate From a0d70304d9df1e21f868b27c9a59489eba495b47 Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 29 Nov 2026 20:04:53 +0200 Subject: [PATCH 16/16] feat(brief): screen every record, 100 a run, 3 hours; acquire in ranking order Shakedown la-brief-9: the include rate stayed near 50% to rank 100, so no yield rule fired and the ceiling decided coverage while check-set works sat at ranks 203-1,406. A brief now screens every record at title and abstract (no screening cap, no stopping rule), 100 records a run (screen cap units_per_run, enforced through the run's unit cap), within 180 minutes and 60 runs. Acquire's default selection follows the ranking, so a capped fetch reads the best-ranked includes, not the alphabetically first. Co-Authored-By: Claude Opus 5.5 --- platform/src/factory/services/conductor.py | 11 +++++++ platform/src/factory/services/fulltext.py | 17 +++++++--- platform/src/factory/services/tier_caps.py | 9 +++-- platform/src/factory/tiers/plans.py | 16 +++++---- platform/tests/test_brief_note.py | 2 +- platform/tests/test_review_loop.py | 2 ++ platform/tests/test_tier_caps.py | 38 ++++++++++++++++++++-- platform/tests/test_tier_protocol.py | 2 +- platform/tests/test_tiers.py | 8 ++--- plugin/skills/rf-brief/SKILL.md | 6 ++-- 10 files changed, 86 insertions(+), 25 deletions(-) diff --git a/platform/src/factory/services/conductor.py b/platform/src/factory/services/conductor.py index 2755dfcb..22cba713 100644 --- a/platform/src/factory/services/conductor.py +++ b/platform/src/factory/services/conductor.py @@ -777,6 +777,15 @@ def _plan_blob(project: Project, plan: PlanLike, steps: Sequence[str]) -> str: RANKED_STEP: Final = "screen:title-abstract" +def _screen_units(project: Project) -> int | None: + """The tier's records per title/abstract screening run (`screen` cap `units_per_run`), within + the runner's unit cap; None when the plan sets none.""" + from factory.services.tier_caps import SCREEN_RUN_CAP, tier_cap + + units = tier_cap(project, SCREEN_RUN_CAP) + return None if units is None else max(1, min(units, runner.MAX_UNIT_CAP)) + + def rank_before_screening(project: Project) -> None: """Rank the title/abstract queue once, as the system, before its first screening run (shakedown la-brief-6: unranked, a capped tier screened the first 40 of 13k records in work-id order). @@ -1109,6 +1118,8 @@ def _advance( assert decision.step is not None and decision.stage_id is not None and decision.role stage = _stage_of(decision.stage_id, decision.role) cap = _unit_cap(meta) + if decision.role == "proposer" and decision.stage_id == RANKED_STEP: + cap = _screen_units(project) or cap if decision.role == "auditor": draw_platform_audits(project, decision.stage_id) if decision.role == "proposer" and decision.stage_id == RANKED_STEP: diff --git a/platform/src/factory/services/fulltext.py b/platform/src/factory/services/fulltext.py index a3c3cce2..b0810707 100644 --- a/platform/src/factory/services/fulltext.py +++ b/platform/src/factory/services/fulltext.py @@ -290,17 +290,26 @@ def _targets( limit: int, ) -> list[str]: """The works this call processes. Explicit ids are validated against `limit` beforehand and - returned sorted; the default selection is capped at `limit`. A revisit rotates: works are - ordered by their last attempt, oldest first (never attempted first), then by id, so repeated - calls reach the whole corpus (plan FL, ruling 3).""" + returned sorted; the default selection is capped at `limit`, in ranking order when the project + has a ranking (ranked works first, by position, then the rest by id), else by id (shakedown + la-brief-9: with every record screened, an id-ordered cut read the alphabetically first 30 + includes). A revisit rotates: works are ordered by their last attempt, oldest first (never + attempted first), then by id, so repeated calls reach the whole corpus (plan FL, ruling 3).""" if work_ids is not None: return sorted(set(work_ids)) if revisit: last = _last_attempts(project) chosen = sorted(promoted, key=lambda w: (last.get(w, ""), w)) else: + from factory.services.ranked_queue import ranking_positions + + positions = ranking_positions(project) + unranked = len(positions) + 1 excluded = _documented_works(project) | _attempted_works(project) - chosen = sorted(w for w in promoted if w not in excluded) + chosen = sorted( + (w for w in promoted if w not in excluded), + key=lambda w: (positions.get(w, unranked), w), + ) return chosen[:limit] diff --git a/platform/src/factory/services/tier_caps.py b/platform/src/factory/services/tier_caps.py index 6417b8ec..45aa8013 100644 --- a/platform/src/factory/services/tier_caps.py +++ b/platform/src/factory/services/tier_caps.py @@ -30,8 +30,13 @@ """(stage, cap key): the live evidence rows one work may hold in one pass (shakedown la-brief-8: uncapped, the extractor copied whole results tables, 11 to over 184 rows a work).""" -ENFORCED_CAPS: Final = frozenset({SCREEN_CAP, ACQUIRE_CAP, EXTRACT_ROW_CAP}) -"""The (stage, key) caps the platform refuses past (the three above). Every other cap of a plan is +SCREEN_RUN_CAP: Final = ("screen", "units_per_run") +"""(stage, cap key): the records one title/abstract screening run may serve, in place of the +plan's papers-per-run (a brief screening every record would otherwise take 60 runs of 30).""" + +ENFORCED_CAPS: Final = frozenset({SCREEN_CAP, ACQUIRE_CAP, EXTRACT_ROW_CAP, SCREEN_RUN_CAP}) +"""The (stage, key) caps the platform refuses past (the four above; the last through the run's +unit cap). Every other cap of a plan is advisory: the stage's skill tells the agent to stay within it and nothing checks (finding I4).""" CapEnforcement = Literal["enforced", "advisory"] diff --git a/platform/src/factory/tiers/plans.py b/platform/src/factory/tiers/plans.py index 01c6ec80..b5119213 100644 --- a/platform/src/factory/tiers/plans.py +++ b/platform/src/factory/tiers/plans.py @@ -100,10 +100,11 @@ def _uncapped() -> tuple[StagePlan, ...]: sources=("arxiv",), queries_per_source=1, passes=1, - # 20 (a ranked batch of 20 with no include) with a ceiling of 100, in place of a flat 40 - # (shakedown la-brief-8: the top 40 by seed similarity were 55% includes, and the cap, not - # the yield, ended screening while check-set works sat at ranks 100-960). - stop_after_consecutive_excludes=20, + # No stopping rule: a brief screens every record at title and abstract (shakedown la-brief-9: + # the include rate stayed near 50% to rank 100, so no yield rule fired and a fixed ceiling + # decided coverage; check-set works sat at ranks 203-1,406). Ranking then only orders the + # includes for acquire. + stop_after_consecutive_excludes=None, pack="ml-benchmark", pack_version=1, fields=_BRIEF_FIELDS, @@ -153,8 +154,8 @@ def _brief() -> TierPlan: _stage( "screen", skill=s, - caps={"passes": 1, "max_screened": 100}, - note="one pass in ranked order until 20 consecutive excludes, at most 100", + caps={"passes": 1, "units_per_run": 100}, + note="one pass over every record, 100 records a run", ), _stage( "acquire", @@ -182,7 +183,8 @@ def _brief() -> TierPlan: ), _full_text(s, caps={"passes": 1}, note="one pass over the acquired works"), ), - limits=Limits(max_papers=30, max_minutes=60, max_runs=30), + # 3 hours and 60 runs: screening every record (about 1,800 at 3 s each) takes most of it + limits=Limits(max_papers=30, max_minutes=180, max_runs=60), protocol_template=_BRIEF_PROTOCOL, report_template=ReportTemplate( sections=("question", "search", "screening", "included", "evidence", "quotes", "level"), diff --git a/platform/tests/test_brief_note.py b/platform/tests/test_brief_note.py index 352b677d..7b812fd2 100644 --- a/platform/tests/test_brief_note.py +++ b/platform/tests/test_brief_note.py @@ -142,4 +142,4 @@ def test_the_note_marks_each_cap_enforced_or_advisory( project = init_project(settings, "demo", None, session=SESSION, clock=clock, tier="brief") text = render_brief_note(brief_note(project)) assert "- cap gather: sources: 2 (advisory)" in text - assert "- cap screen: max_screened: 100 (enforced)" in text + assert "- cap screen: units_per_run: 100 (enforced)" in text diff --git a/platform/tests/test_review_loop.py b/platform/tests/test_review_loop.py index 131f0dd5..63674b2d 100644 --- a/platform/tests/test_review_loop.py +++ b/platform/tests/test_review_loop.py @@ -56,6 +56,7 @@ class Runs: def __init__(self) -> None: self.stages: list[str] = [] self.prefaces: list[str | None] = [] + self.caps: list[int] = [] self.ids = itertools.count(1) def start( @@ -63,6 +64,7 @@ def start( ) -> str: self.stages.append(stage) self.prefaces.append(preface) + self.caps.append(unit_cap) return project.ids.new("rnr") diff --git a/platform/tests/test_tier_caps.py b/platform/tests/test_tier_caps.py index f5aed6b4..80f0407b 100644 --- a/platform/tests/test_tier_caps.py +++ b/platform/tests/test_tier_caps.py @@ -47,7 +47,7 @@ def test_caps_come_from_the_plan_for_brief_and_deep_only( for tier in ("brief", "deep"): project = _tier_project(settings, clock, tier, tier) plan = PLANS[Tier(tier)] - assert tier_cap(project, SCREEN_CAP) == plan.stage("screen").caps["max_screened"] + assert tier_cap(project, SCREEN_CAP) == plan.stage("screen").caps.get("max_screened") assert tier_cap(project, ACQUIRE_CAP) == plan.stage("acquire").caps["max_included"] for tier in ("pilot", "systematic", None): project = _tier_project(settings, clock, tier, f"u-{tier or 'legacy'}") @@ -58,7 +58,7 @@ def test_caps_come_from_the_plan_for_brief_and_deep_only( def test_the_level_statement_lists_the_caps(settings: Settings, clock: FixedClock) -> None: project = _tier_project(settings, clock, "brief", "stated") text = "\n".join(level_statement(project).lines) - assert "screen: max screened capped at" in text + assert "screen: units per run capped at 100" in text assert "acquire: max included capped at" in text @@ -132,6 +132,29 @@ def test_fetch_stops_at_the_cap( assert "max_included" in issue.reason +def test_a_capped_fetch_takes_the_best_ranked_works_first( + project: Project, + agent: Actor, + human: Actor, + mock_sources: SourcesFor, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """la-brief-9: with every record screened, an id-ordered cut read the alphabetically first + includes; the default selection now follows the ranking.""" + from factory.services import ranked_queue + + _promoted_corpus(project, agent, human, mock_sources) + stubs = routes_for(arxiv_html=always(retrieved(Route.ARXIV_HTML, b"x"))) + by_id = sorted(_promoted(project)) + assert len(by_id) >= 2 + best = by_id[-1] # last by id, first by rank + monkeypatch.setattr( + ranked_queue, "ranking_positions", lambda _p: {w: i for i, w in enumerate(reversed(by_id))} + ) + monkeypatch.setattr(fulltext_module, "tier_cap", lambda _p, _which: 1) + assert [w.work_id for w in fetch_fulltext(project, routes=stubs, limit=20).works] == [best] + + def test_fetch_without_a_cap_takes_every_promoted_work( project: Project, agent: Actor, @@ -165,7 +188,8 @@ def test_cap_lines_name_the_enforcement(settings: Settings, clock: FixedClock) - lines = cap_lines(Tier.BRIEF) assert "cap gather sources: 2 (advisory)" in lines - assert "cap screen max_screened: 100 (enforced)" in lines + assert "cap screen units_per_run: 100 (enforced)" in lines + assert not any("max_screened" in line for line in lines) # a brief screens every record assert cap_lines(Tier.PILOT) == () project = _tier_project(settings, clock, "brief", "brief") assert "cap gather sources: 2 (advisory)" in level_statement(project).lines @@ -181,3 +205,11 @@ def test_the_brief_gather_stage_has_no_snowball_tool_where_the_plan_allows_no_ro assert snow not in stage_spec(brief, "gather").tools deep = _tier_project(settings, clock, "deep", "deep") assert snow in stage_spec(deep, "gather").tools # the deep plan allows a round + + +def test_a_brief_screening_run_takes_100_records(settings: Settings, clock: FixedClock) -> None: + """la-brief-9: a brief screens every record; at the plan's 30 papers a run that is 60 runs.""" + from factory.services.conductor import _screen_units + + assert _screen_units(_tier_project(settings, clock, "brief", "b100")) == 100 + assert _screen_units(_tier_project(settings, clock, "pilot", "p100")) is None diff --git a/platform/tests/test_tier_protocol.py b/platform/tests/test_tier_protocol.py index 31f22ea6..b554ab04 100644 --- a/platform/tests/test_tier_protocol.py +++ b/platform/tests/test_tier_protocol.py @@ -55,7 +55,7 @@ def test_the_brief_template_is_recorded_as_a_draft( spec = current_protocol(project) assert spec is not None assert [s.name for s in spec.spec.sources] == ["arxiv"] # la-brief-6: no OpenAlex in a brief - assert spec.spec.screening.stop_after_consecutive_excludes == 20 + assert spec.spec.screening.stop_after_consecutive_excludes is None # la-brief-9: screen all reviewer = spec.spec.screening.reviewers[0] assert (reviewer.actor, reviewer.kind) == ("obd", "human") # the creator, not the agent diff --git a/platform/tests/test_tiers.py b/platform/tests/test_tiers.py index 565ae10a..182027de 100644 --- a/platform/tests/test_tiers.py +++ b/platform/tests/test_tiers.py @@ -69,13 +69,13 @@ def test_pilot_and_systematic_have_no_caps_and_skip_nothing(tier: Tier) -> None: def test_brief_caps_are_the_ruled_ones() -> None: plan = plan_for(Tier.BRIEF) - assert (plan.limits.max_papers, plan.limits.max_minutes, plan.limits.max_runs) == (30, 60, 30) # type: ignore[union-attr] + assert (plan.limits.max_papers, plan.limits.max_minutes, plan.limits.max_runs) == (30, 180, 60) # type: ignore[union-attr] assert plan.stage("gather").caps == { "sources": 2, "searches_per_source": 1, "snowball_rounds": 0, } - assert plan.stage("screen").caps["max_screened"] == 100 + assert plan.stage("screen").caps == {"passes": 1, "units_per_run": 100} # no screening cap assert plan.stage("acquire").caps["max_included"] == 30 assert plan.stage("extract").caps["max_fields"] == 6 assert [s.stage_id for s in plan.stages if s.skipped] == ["understand", "develop", "maintain"] @@ -108,7 +108,7 @@ def test_skipped_steps_are_computed_from_the_plan() -> None: "develop: skipped", "maintain: skipped", "gather: no snowball rounds", - "screen: max screened capped at 100", + "screen: units per run capped at 100", "frame: no press reviews", ): assert expected in steps @@ -194,7 +194,7 @@ def test_brief_new_plan_and_status(tmp_path: Path) -> None: assert "exploratory" in made.output plan = runner.invoke(app, ["brief", "plan", "lin"], env=env) assert plan.exit_code == 0, plan.output - for line in ("tier brief", "limits: 30 papers, 60 minutes, 30 runs", "rf-brief", "understand"): + for line in ("tier brief", "limits: 30 papers, 180 minutes, 60 runs", "rf-brief", "understand"): assert line in plan.output assert "skipped:" in plan.output and "gather: no snowball rounds" in plan.output status = runner.invoke(app, ["brief", "status", "lin"], env=env) diff --git a/plugin/skills/rf-brief/SKILL.md b/plugin/skills/rf-brief/SKILL.md index f15c0c74..c4a4db0c 100644 --- a/plugin/skills/rf-brief/SKILL.md +++ b/plugin/skills/rf-brief/SKILL.md @@ -30,8 +30,7 @@ quick review, not a systematic one. researcher's own words as `raw_goal`). The researcher confirms the quoted goal (human gate). - Seeds are optional: add the researcher's own list with `seed_add`; never invent one. - Record the protocol from the template of `factory brief plan` with `protocol_record`: at most 2 - sources, one query per source, screening in one pass with the - stopping rule, an extraction schema of at most 6 fields. Leave `ready` false unless the + sources, one query per source, screening in one pass over every record, an extraction schema of at most 6 fields. Leave `ready` false unless the researcher asks; no PRESS review and no protocol gate bind in a brief. ### 2. Gather @@ -42,7 +41,8 @@ quick review, not a systematic one. ### 3. Screen - `ranking_compute`, then `screen_next` with `pass_label` `A` and `screen_record` in ranked order - with a verbatim quote per decision (`rf-screen` has the rules). Screen at most 40 records and stop earlier when the stopping rule of the protocol stops serving. One pass: no + with a verbatim quote per decision (`rf-screen` has the rules). Screen every record the queue serves (a brief has no screening cap or stopping rule; a tier + cap, where a plan sets one, is refused by the platform). One pass: no pass B in a brief. ### 4. Acquire