Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -297,11 +297,11 @@ jobs:
cp phase-loop-runtime/src/phase_loop_runtime/baml_src/*.baml "$raw/baml_src/"
printf '[package]\nname = "bamlraw"\n' > "$raw/baml.toml"
baml-cli --agent-skill-check off check --project "$raw" 2>&1 | tee "$RUNNER_TEMP/raw.log"
grep -q 'Finished checked 9 file(s)' "$RUNNER_TEMP/raw.log"
grep -q 'Finished checked 10 file(s)' "$RUNNER_TEMP/raw.log"
BAMLCHK="$rendered/baml_src" python -c 'import os, pathlib; from phase_loop_runtime import baml_modular as m; d = pathlib.Path(os.environ["BAMLCHK"]); [(d / n).write_text(t, encoding="utf-8") for n, t in m._read_baml_files().items()]'
printf '[package]\nname = "bamlchk"\n' > "$rendered/baml.toml"
baml-cli --agent-skill-check off check --project "$rendered" 2>&1 | tee "$RUNNER_TEMP/rendered.log"
grep -q 'Finished checked 9 file(s)' "$RUNNER_TEMP/rendered.log"
grep -q 'Finished checked 10 file(s)' "$RUNNER_TEMP/rendered.log"


lint:
Expand Down
37 changes: 36 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,42 @@ versioning; the release tag, the package `version`, and this file are kept in lo

## [Unreleased]

### Local T3 typed review host bridge

- Add local request, prepare, register, intake, resume and correction operations
around the frozen review coordinator. Host actions are data for the driving
host; commands do not dispatch providers. Bind original task/thread/run,
recover complete terminal text with bounded UTF-16 pagination, and replay
saved bytes and BAML sources after interruption.
- Document the NON_GATING/HOST_ATTESTED policy, shared pre-bound checkout,
private state requirements, unresolved offered dispatch and one frozen-charter
correction allowance in the [host integration guide](docs/phase-loop/typed-reviews.md).
Add synthetic host fault and standalone CLI conformance coverage. Independent
implementation review and final sealed verification remain pending; no live
route, governed admission or deployment qualification is claimed.

### Typed review coordinator contract

- Add strict review and president intake through the declared BAML worker,
with immutable request/source bindings, saved-map replay, private durable
delivery records and one correction reservation per original lineage.
- Keep valid and invalid-content record, finding and status identities stable across local revalidation,
retain actual invocation history, and require successful current validation
after outages. Stale president ledgers cannot consume reviewer corrections.
- Refuse malformed host evidence before delivery. Oversized reviewer bodies
atomically consume the attempt with digest-only invalid-content records;
oversized corrections exhaust the allowance. Envelope-only overflow permits
host repair with the authentic original body. The envelope limit allows sixfold
JSON escaping plus bounded host framing. Correction prompts explicitly identify
absent over-limit originals by digest and length. Governed provenance now
requires an explicit policy set, empty by default. Publish executable lineage
replay vectors and document the SQLite parsing lock's 60-second busy timeout.
- Separate typed usability, host provenance and existing governed eligibility;
preserve dissent and globally keyed president dispositions. The new
[coordinator contract](docs/phase-loop/typed-review-contract.md) documents the
adapter boundary. Transport integration and live-route qualification remain
downstream work.

### Diagnostic planning skill evaluation (agent-harness#1321)

- Add the opt-in `phase-loop-skill-eval` command for frozen, independent planning
Expand Down Expand Up @@ -38,7 +74,6 @@ versioning; the release tag, the package `version`, and this file are kept in lo

- Add an exact full-secret allowlist match for the synthetic typed-review digest
fixture introduced by agent-harness#1770, leaving other detections unchanged.

### TypeScript publication source classification (agent-harness#1765)

- Normal publication can classify new or existing regular TypeScript implementation
Expand Down
438 changes: 438 additions & 0 deletions docs/phase-loop/typed-review-contract.md

Large diffs are not rendered by default.

377 changes: 377 additions & 0 deletions docs/phase-loop/typed-reviews.md

Large diffs are not rendered by default.

445 changes: 445 additions & 0 deletions docs/proposals/typed-review-contract.md

Large diffs are not rendered by default.

396 changes: 396 additions & 0 deletions docs/proposals/typed-review-roadmap.md

Large diffs are not rendered by default.

349 changes: 349 additions & 0 deletions docs/proposals/typed-review-roadmap_reviews.md

Large diffs are not rendered by default.

17 changes: 17 additions & 0 deletions phase-loop-runtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,23 @@ canonical protocol document ships in the wheel as package data
(from `src/phase_loop_runtime/_contract_docs/phase-loop/protocol.md`); an older copy is also
installed to `share/phase-loop-runtime/protocol/protocol.md`.

## Local T3 typed reviews

`phase-loop typed-review` provides local `request`, `prepare`, `register`,
`intake`, `resume` and `correction` commands. It returns private host-action
files for a trusted driving host to execute, and validates complete original
results through the saved-source BAML coordinator. Commands never dispatch a
provider. The shipped policy is NON_GATING/HOST_ATTESTED; no caller JSON or
environment setting grants governed eligibility or production redispatch.

Use private state outside the pre-bound shared checkout. Same-UID reviewer
exclusion is the host's responsibility; owner-only files alone cannot enforce
it. Unknown offered dispatch remains unresolved, and at most one frozen-charter
correction is available per lineage. See the [T3 host integration guide](https://github.com/Consiliency/agent-harness/blob/main/docs/phase-loop/typed-reviews.md)
for exact grammar, observation schemas, recovery limits and trust assumptions.
Synthetic conformance tests do not establish live-route qualification. Existing
executor closeout and legacy advisory acceptance remain unchanged.

## Offline repository-map artifacts

Legacy `phase-loop fleet-map --repo <path> --json` output remains unchanged.
Expand Down
35 changes: 30 additions & 5 deletions phase-loop-runtime/src/phase_loop_runtime/_baml_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@
Protocol: one JSON object per line, UTF-8 with ``ensure_ascii=True``. Requests
arrive on fd 0; responses leave on a dup of fd 1 taken before fd 1 is pointed
at stderr, so nothing the native runtime prints can corrupt the protocol.
Every request carries an ``id`` that the response echoes. A response has
Every request carries an ``id`` that the response echoes. Legacy responses have
exactly the keys ``{id, fingerprint, <one of ok|error|request|fault>}``.
Review parse replies also carry operation, function_name and runtime_version.

Op table (fixed): ``init``, ``parse_closeout``, ``closeout_request``,
``evidence_request``, plus ``env`` when ``init`` carried ``test_mode``. An op
``evidence_request``, review reply/decision parse and request operations,
plus ``env`` when ``init`` carried ``test_mode``. An op
before ``init`` or a second ``init`` is answered with a ``fault``. Any
exception raised by an op (``BaseException``, including ``BamlPanic``) is
returned as a ``fault``; the client then discards and kills the worker.
Expand All @@ -27,6 +29,10 @@
import sys

_OP_FUNCTIONS = {
"parse_review_reply": ("user.phase_loop_parse_review_reply", ("raw",), ("ok", "error")),
"parse_review_decision": ("user.phase_loop_parse_review_decision", ("raw",), ("ok", "error")),
"review_reply_request": ("user.phase_loop_review_reply_request", ("request_json",), ("request",)),
"review_decision_request": ("user.phase_loop_review_decision_request", ("request_json",), ("request",)),
"parse_closeout": ("user.phase_loop_parse_closeout", ("raw",), ("ok", "error")),
"closeout_request": (
"user.phase_loop_closeout_request",
Expand All @@ -39,6 +45,10 @@
("request",),
),
}
_REVIEW_FUNCTIONS = {
"parse_review_reply": "EmitReviewReply",
"parse_review_decision": "EmitReviewDecision",
}
# The client caps a request frame at 4 MiB + 1 KiB; anything larger here is a
# client bug or a hostile writer, and is refused rather than buffered forever.
_MAX_REQUEST_LINE = 4 * 1024 * 1024 + 1024 + 4096
Expand Down Expand Up @@ -85,6 +95,7 @@ def __init__(self, out_fd: int, no_pdeathsig: bool) -> None:
self.fp: str | None = None
self.fns: dict[str, object] | None = None
self.test_mode = False
self.runtime_version: str | None = None

def send(self, obj: dict) -> None:
data = (json.dumps(obj, separators=(",", ":"), ensure_ascii=True) + "\n").encode("ascii")
Expand All @@ -95,6 +106,7 @@ def send(self, obj: dict) -> None:

def handle(self, line: bytes) -> None:
req_id = None
req = None
try:
req = json.loads(line.decode("ascii"))
if not isinstance(req, dict):
Expand Down Expand Up @@ -122,9 +134,21 @@ def handle(self, line: bytes) -> None:
((key, value),) = out.items()
if key not in keys or not isinstance(value, str):
raise RuntimeError(f"bridge {op} returned key {key!r}")
self.send({"id": req_id, "fingerprint": self.fp, key: value})
metadata = {}
if op in _REVIEW_FUNCTIONS:
metadata = {
"operation": op,
"function_name": _REVIEW_FUNCTIONS[op],
"runtime_version": self.runtime_version,
}
self.send({"id": req_id, "fingerprint": self.fp, **metadata, key: value})
except BaseException as exc: # noqa: BLE001 - every op failure is a typed fault
message = f"{type(exc).__module__}.{type(exc).__qualname__}: {str(exc)[:500]}"
# Review content must never escape in exceptions/telemetry.
message = "review worker fault" if (
isinstance(req, dict) and isinstance(req.get("op"), str) and req["op"] in _REVIEW_FUNCTIONS
) else (
f"{type(exc).__module__}.{type(exc).__qualname__}: {str(exc)[:500]}"
)
self.send({"id": req_id, "fingerprint": self.fp, "fault": message})

def init(self, req: dict) -> dict:
Expand All @@ -145,7 +169,8 @@ def init(self, req: dict) -> dict:
fns = {op: baml_bridge.define_function(name, "sync", list(params)) for op, (name, params, _keys) in _OP_FUNCTIONS.items()}
self.fp = fingerprint(files)
self.fns = fns
return {"version": baml_bridge.get_version(), "pid": os.getpid()}
self.runtime_version = baml_bridge.get_version()
return {"version": self.runtime_version, "pid": os.getpid()}

def serve(self) -> None:
buf = b""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2689,7 +2689,9 @@ def _validate_bootstrap_evidence_root_isolation(
)


def _exclusive_write_at(directory_fd: int, name: str, data: bytes, mode: int) -> None:
def _exclusive_write_at(
directory_fd: int, name: str, data: bytes, mode: int, *, exact_mode: bool = False,
) -> None:
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC
fd = os.open(name, flags, mode, dir_fd=directory_fd)
try:
Expand All @@ -2699,6 +2701,8 @@ def _exclusive_write_at(directory_fd: int, name: str, data: bytes, mode: int) ->
if written <= 0:
raise AgyCanaryEvidenceError(f"short write for {name}")
view = view[written:]
if exact_mode:
os.fchmod(fd, mode)
os.fsync(fd)
finally:
os.close(fd)
Expand Down Expand Up @@ -8134,7 +8138,7 @@ def _finalize_targets_transactionally(plan_target: _FinalTarget, manifest_target
raise AgyCanaryEvidenceError("finalizer target identity or bytes drifted before staging")
for target in targets:
target.temporary = f".phase-loop-agy-finalize-{target.name}.{secrets.token_hex(16)}.tmp"
_exclusive_write_at(target.parent_fd, target.temporary, target.replacement, target.mode)
_exclusive_write_at(target.parent_fd, target.temporary, target.replacement, target.mode, exact_mode=True)
for target in targets:
if not _final_target_matches_preimage(target):
raise AgyCanaryEvidenceError("finalizer target identity or bytes drifted before exchange")
Expand Down
Loading
Loading