From d4744d8220dbc5c869dd0895744103799288539f Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 12:43:58 -0800 Subject: [PATCH 01/23] Restore ratified spec bytes and carry #24's text as candidate amendment 005 PR #24 edited architecture.md, verification.md and cli.md in place, so their digests stopped matching ratification-manifest.json and every acceptance run refused with INVALID_HARNESS. The three files go back to their ratified bytes; the same text, verbatim, becomes candidate amendment 005. The allow_non_loopback behaviour itself is unchanged. Spec: amendment-005-managed-deployment-bind.md (candidate) --- spec/amendment-005-managed-deployment-bind.md | 84 +++++++++++++++++++ spec/architecture.md | 26 +----- spec/cli.md | 3 +- spec/verification.md | 9 +- 4 files changed, 91 insertions(+), 31 deletions(-) create mode 100644 spec/amendment-005-managed-deployment-bind.md diff --git a/spec/amendment-005-managed-deployment-bind.md b/spec/amendment-005-managed-deployment-bind.md new file mode 100644 index 0000000..a22fa70 --- /dev/null +++ b/spec/amendment-005-managed-deployment-bind.md @@ -0,0 +1,84 @@ +# Candidate Amendment 005 — A managed deployment may bind beyond loopback + +Status: **candidate; not authority until the founder and a distinct Validator +ratify its exact digest.** + +## Why this file exists + +PR #24 (`9fb7fa4`, "Let a managed deployment bind somewhere other than +loopback") wrote its spec changes directly into three ratified artifacts: +`architecture.md`, `verification.md` and `cli.md`. Their bytes then no longer +matched `ratification-manifest.json`, and the acceptance suite refused every run +with `INVALID_HARNESS`. Those three files are restored to their ratified bytes, +and the same text is carried here, word for word, as a candidate overlay. The +product behaviour (`allow_non_loopback`, default off) is unchanged. + +## Supersessions + +Each item names the ratified passage and the text that replaces or follows it. + +### `architecture.md`, Company / Kinbase + +1. In "Every endpoint, including reads, requires a per-instance bearer token + loaded from a mode-0600 file, exact loopback Host validation, absent Origin + header, and JSON content type for bodies", replace "exact loopback Host + validation" with "loopback Host validation unless opted out". + +2. After the paragraph ending "the security claim against a local same-UID + process rests on scoped token plus client-key request signature, not those + headers.", add: + + > A deployment may set `allow_non_loopback`, which lifts the bind, Host and + > client endpoint rules together so the service can be reached through a + > cluster Service name. Doing so moves the peer set from the operator's own + > processes to everything the network permits, and the transport is + > cleartext: the endpoint parser accepts `http://` only, so TLS is + > unreachable rather than merely absent, and the bearer token crosses the + > network on every request. The signature does not narrow this. A request + > supplies its own client key, and while a token and key pair is recorded the + > first-use binding that would pin them is not yet enforced, so an observer + > of one request can mint a fresh key and sign for the same token. On a + > routable bind the token is therefore the whole credential. + > + > Isolation for such a deployment comes from the network, not from the + > service: ingress denied by default, and no workload admitted to the port + > that is not meant to read the store. That is an accepted risk of the + > managed shape rather than a property of the proof, and it is recorded here + > so it is not inherited silently. A transport option for operators wanting + > defence in depth, and enforcement of the first-use client-key binding, + > remain open. + +### `architecture.md`, host SessionStart budget + +3. Replace "launches asynchronous Company refresh with a 250-millisecond + connection budget; a blackholed endpoint cannot hold the host open" with + "launches asynchronous Company refresh with a 250-millisecond connection + budget and, where the endpoint names a host rather than a literal, a separate + 250-millisecond resolution budget ahead of it, so a refresh that must resolve + is bounded at 500 milliseconds; a blackholed endpoint cannot hold the host + open". + +### `verification.md` + +4. Replace "Company connect budget is 250 ms, cold/degraded projection is empty" + with "Company connect budget is 250 ms, with a separate 250 ms resolution + budget where the endpoint names a host, cold/degraded projection is empty". + +5. Replace "Kinbase HTTP rejects unauthenticated reads, non-loopback Host, + Origin-bearing requests, and non-JSON writes; all receive typed + remediation-safe errors." with "Kinbase HTTP rejects unauthenticated reads, + Origin-bearing requests, and non-JSON writes; all receive typed + remediation-safe errors. A non-loopback Host is rejected unless + `allow_non_loopback` is set, which a managed deployment sets because it is + reached through a cluster Service name rather than a literal." + +### `cli.md` + +6. In the service config sentence, replace "bind address (loopback only in the + PoC)" with "bind address (loopback unless `allow_non_loopback` is set)". + +## What does not change + +Every other ratified passage. With `allow_non_loopback` unset, which is the +default, the service, Host checks and client endpoint behave exactly as the +ratified text says. diff --git a/spec/architecture.md b/spec/architecture.md index 2859d1b..5867620 100644 --- a/spec/architecture.md +++ b/spec/architecture.md @@ -479,7 +479,7 @@ startup failure even when path access remains denied. table, authority registry, source observations, current-view cache, Unknown queue, and monotonic change cursor. The proof runs service and client as separate processes. Every endpoint, including reads, requires a per-instance bearer token loaded from a -mode-0600 file, loopback Host validation unless opted out, absent Origin header, and JSON content +mode-0600 file, exact loopback Host validation, absent Origin header, and JSON content type for bodies. Tokens are capability-scoped (`facts:read`, `questions:write`, `directory:read`, or administrative issuance), compared in constant time, bound to a client-instance public key, rotated by the Company owner, and throttled by a serialized @@ -498,24 +498,6 @@ refusal. Host/Origin checks are anti-CSRF hardening only; the security claim aga local same-UID process rests on scoped token plus client-key request signature, not those headers. -A deployment may set `allow_non_loopback`, which lifts the bind, Host and client -endpoint rules together so the service can be reached through a cluster Service -name. Doing so moves the peer set from the operator's own processes to everything -the network permits, and the transport is cleartext: the endpoint parser accepts -`http://` only, so TLS is unreachable rather than merely absent, and the bearer -token crosses the network on every request. The signature does not narrow this. -A request supplies its own client key, and while a token and key pair is recorded -the first-use binding that would pin them is not yet enforced, so an observer of -one request can mint a fresh key and sign for the same token. On a routable bind -the token is therefore the whole credential. - -Isolation for such a deployment comes from the network, not from the service: -ingress denied by default, and no workload admitted to the port that is not meant -to read the store. That is an accepted risk of the managed shape rather than a -property of the proof, and it is recorded here so it is not inherited silently. A -transport option for operators wanting defence in depth, and enforcement of the -first-use client-key binding, remain open. - A client cache binds company ID, cursor, authority snapshot, separate short revocation-valid-until, fact-valid-until, and the root/signature chain. Both clocks are rechecked at every projection, not only SessionStart. Every decision trace and @@ -761,10 +743,8 @@ temporary homes by invoking installed hook commands and config, not by passing native envelope samples; `doctor` rejects unsupported ranges. SessionStart has a two-second p95 proof budget. It uses a previously verified cache -and launches asynchronous Company refresh with a 250-millisecond connection budget -and, where the endpoint names a host rather than a literal, a separate -250-millisecond resolution budget ahead of it, so a refresh that must resolve is -bounded at 500 milliseconds; a blackholed endpoint cannot hold the +and launches asynchronous Company refresh with a 250-millisecond connection budget; +a blackholed endpoint cannot hold the host open. Fail-closed means affected facts are withheld with a loud degraded/Unknown status, never that an ordinary editor session is prevented from starting. Warm, cold, cache-invalid, and full-fsck-required starts all return the hook response diff --git a/spec/cli.md b/spec/cli.md index 97fe70c..d1c8467 100644 --- a/spec/cli.md +++ b/spec/cli.md @@ -47,8 +47,7 @@ without `.kin/` starts with no Codebase facts and offers `kinbase repo init`; ordinary coding remains available. Service config is an explicit `kinbased.toml` (0600) naming Company ID, SQLite -path, bind address (loopback unless `allow_non_loopback` is set), bearer-token -file, root key file, +path, bind address (loopback only in the PoC), bearer-token file, root key file, retention, freshness, and rate ceilings. Malformed or unsafe config fails startup. ```toml diff --git a/spec/verification.md b/spec/verification.md index ee3bf20..d6d27ee 100644 --- a/spec/verification.md +++ b/spec/verification.md @@ -492,8 +492,7 @@ cluster sizes and source dependence reported rather than manufactured. - Measure warm, cold, invalid-cache, and full-fsck-required SessionStart separately; run at least 200 invocations per host/state on the recorded proof machine, report CPU/RAM/filesystem, and require every state's p95 under two seconds. Company connect - budget is 250 ms, with a separate 250 ms resolution budget where the endpoint - names a host, cold/degraded projection is empty, and background full fsck at + budget is 250 ms, cold/degraded projection is empty, and background full fsck at the 10,000-event ceiling finishes within 120 seconds. Across the 20-session private soak, at least 90% of starts must take the warm verified path and deliver nonempty trusted context when eligible facts exist; after the first cold start, at most 5% @@ -783,10 +782,8 @@ pass. - `fsck`, `doctor`, corpus status, question status, and experiment status are executable and useful after restart. `explain ` shows each reducer admission/rejection step and the evidence needed to flip the result. -- Kinbase HTTP rejects unauthenticated reads, Origin-bearing requests, and - non-JSON writes; all receive typed remediation-safe errors. A non-loopback Host - is rejected unless `allow_non_loopback` is set, which a managed deployment sets - because it is reached through a cluster Service name rather than a literal. +- Kinbase HTTP rejects unauthenticated reads, non-loopback Host, Origin-bearing + requests, and non-JSON writes; all receive typed remediation-safe errors. - Static analysis, formatting, type checks, dependency audit, and full test suite run without undeclared network access. - [`leak-runbook.md`](leak-runbook.md) is exercised as a tabletop against one seeded From 11867768499a2b5b9fbf0587ca3f946cef064ca9 Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 12:50:35 -0800 Subject: [PATCH 02/23] Refuse a malformed kinbase .kin/config instead of skipping it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A `.kin/config` that names the kinbase-repo schema but carries malformed bytes (a raw NUL, invalid UTF-8) was silently ignored: since the config moved to `.kin/kinbase.toml`, discovery read only the new file when it existed, and otherwise fell back to `.kin/config` only when it parsed. So `status` against a hostile kinbase config exited 0 instead of the first-run table's exit 5, and NF.exit-boundary's config probe failed. A `.kin/config` that names `kinbase-repo/` is now treated as kinbase's own: it is read when `kinbase.toml` is absent, and whenever it fails to parse, so the malformed bytes reach RepoConfig parsing and refuse with DIGEST_MISMATCH (exit 5). Kindex's YAML never names that schema, so it is still left alone, which keeps the sharing that `kinbase.toml` was added for. Spec: spec/cli.md NONFUNCTIONAL first-run-failures ("malformed certificate/config | exit 5 and quarantine") Spec: spec/architecture.md §11 ("Existing `.kin/config` ... with an incompatible schema block and preserve bytes") --- crates/kinbase/src/codebase.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/crates/kinbase/src/codebase.rs b/crates/kinbase/src/codebase.rs index c70ba2d..769650d 100644 --- a/crates/kinbase/src/codebase.rs +++ b/crates/kinbase/src/codebase.rs @@ -316,18 +316,21 @@ pub const CONFIG_FILE: &str = "kinbase.toml"; /// only when it is genuinely a kinbase config. fn config_path_for(kin: &std::path::Path) -> Option { let ours = kin.join(CONFIG_FILE); - if ours.exists() { - return Some(ours); - } let legacy = kin.join("config"); - if legacy.exists() - && std::fs::read_to_string(&legacy) + // A `.kin/config` naming our schema is kinbase's own, so malformed bytes there + // must refuse with exit 5 (spec/cli.md first-run table), not be skipped as + // Kindex's; Kindex's YAML never names `kinbase-repo/`. + let legacy_names_ours = std::fs::read(&legacy) + .is_ok_and(|bytes| bytes.windows(13).any(|window| window == b"kinbase-repo/")); + let legacy_parses = || { + std::fs::read_to_string(&legacy) .ok() .is_some_and(|text| RepoConfig::parse(&text).is_ok()) - { + }; + if legacy_names_ours && (!ours.exists() || !legacy_parses()) { return Some(legacy); } - None + ours.exists().then_some(ours) } impl Repository { From 332ae669157a782a44a32b2c5ea4276761695d8d Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 13:09:44 -0800 Subject: [PATCH 03/23] Add candidate spec amendment 006 for the .kin/kinbase.toml rename e970ae5 moved kinbase's tracked config from .kin/config, which Kindex owns, to .kin/kinbase.toml, but the ratified spec still names .kin/config in cli.md, architecture.md and threat-model.md. The amendment records the rename and the lookup rule: Kindex's file is ignored, a pre-rename kinbase TOML at .kin/config is still read, and a .kin/config naming kinbase's schema that does not parse refuses with exit 5. Ratified files are unchanged. Spec: amendment-006-kinbase-config-filename.md (candidate) --- spec/amendment-006-kinbase-config-filename.md | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 spec/amendment-006-kinbase-config-filename.md diff --git a/spec/amendment-006-kinbase-config-filename.md b/spec/amendment-006-kinbase-config-filename.md new file mode 100644 index 0000000..1d81087 --- /dev/null +++ b/spec/amendment-006-kinbase-config-filename.md @@ -0,0 +1,58 @@ +# Candidate Amendment 006 — Kinbase's tracked config is `.kin/kinbase.toml` + +Status: **candidate; not authority until the founder and a distinct Validator +ratify its exact digest.** + +## Why + +The ratified artifacts name kinbase's tracked repository config `.kin/config`. +Kindex already owns that path, in YAML, and most Wander repositories carry one. +Kinbase read Kindex's YAML as a malformed kinbase config and refused with +`DIGEST_MISMATCH`, so it could not be initialised in those repositories. Commit +`e970ae5` ("Give kinbase its own config filename so it can share .kin/ with +kindex", 2026-09-10) moved kinbase to `.kin/kinbase.toml`. The spec was not +updated. This amendment records the rename. + +## Supersessions + +In each passage below, kinbase's tracked config is `.kin/kinbase.toml` where the +ratified text says `.kin/config`: + +1. `cli.md`, "Tracked `.kin/config` contains only schema version, repository + UUID hint, safe name, domains, and local policy hints." +2. `cli.md`, first-run step 5: "commit only `.kin/config`, `.kin/events/`, + `.kin/manifests/`, and the required `.gitattributes`." +3. `architecture.md`: "A tracked `.kin/config` contains only repository metadata + and safe client hints." +4. `architecture.md`: "Existing `.kin/config` or Kinbase event paths with an + incompatible schema block and preserve bytes." +5. `threat-model.md`, adversary item 11: "malicious `.kin/config` fields" covers + `.kin/kinbase.toml`, and a `.kin/config` that names kinbase's schema (below). + +The content rules are unchanged: the file still holds only schema version, +repository UUID hint, safe name, domains and local policy hints, and still +cannot name roots, keys, authorities or Company endpoints. + +## Requirements + +1. `repo init` writes `.kin/kinbase.toml`. It never writes, edits or removes + `.kin/config`. +2. A `.kin/config` is Kindex's unless its bytes name kinbase's schema + (`kinbase-repo/`). Kinbase ignores Kindex's file and never reports it as a + kinbase error. +3. A repository initialised before the rename may still hold kinbase's TOML at + `.kin/config`. Kinbase reads it when `.kin/kinbase.toml` is absent. +4. A `.kin/config` that names kinbase's schema but does not parse is kinbase's + malformed config. It refuses with the integrity error and exit 5 that + `cli.md` requires for malformed config, even when `.kin/kinbase.toml` is + present. It is never silently skipped. +5. When both files are valid, `.kin/kinbase.toml` governs. + +## Verification + +- `tests/acceptance/test_nonfunctional.py::test_hostile_bytes_never_escape_the_exception_boundary` + writes a hostile kinbase config to `.kin/config`; requirement 4 makes it + refuse with exit 5. +- Requirements 1 and 2 (`repo init` in a repository whose `.kin/config` is + Kindex YAML succeeds and leaves that file byte-identical) have no automated + test yet; one should be added before ratification. From 1b1e5c64da4c34bc9fd20f9ece6fa0313ab7a60e Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 12:57:33 -0800 Subject: [PATCH 04/23] Resolve an omitted --as-of to the recorded proof clock 214567a made the shared as-of resolver advance to the cached authority snapshot's issued_at whenever that was later, so status, fsck, explain, corpus rebuild and recall echoed as_of_source authority-snapshot:issued_at for an omitted --as-of. Ruling R-1/C12 says an omitted --as-of uses the recorded proof clock and echoes it. The input also moves whenever the cache is refreshed, so two consecutive corpus rebuilds with no --as-of gave different current_view_digest values and V-4's rebuild and restart stages could not preserve the view. The resolver returns the recorded proof clock again. The projector (after its refresh) and the session-start hook still advance to the signed snapshot, so the brief keeps seeing rulings published after the repository's clock. Spec: spec/architecture.md Reduction algorithm (as_of is explicit, never ambient) Refs: evidence/factory-run/validator-rulings-C1-C28.md C12, validator-rulings-2026-09-07.md R-1 --- crates/kinbase/src/cli.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/kinbase/src/cli.rs b/crates/kinbase/src/cli.rs index e1ebccf..ffd8811 100644 --- a/crates/kinbase/src/cli.rs +++ b/crates/kinbase/src/cli.rs @@ -487,8 +487,9 @@ fn resolve_as_of( } } }; - // The verified authority snapshot is recorded proof of a later instant. - Ok(crate::repository::advance_as_of(launcher, &recorded)) + // Omitted --as-of is the recorded proof clock (ruling R-1/C12). The + // projector and hook advance to the signed snapshot on their own. + Ok(recorded) } fn store_to_kind(store: Store) -> crate::StoreKind { From 2a09239d71205e6b8efb4f49836792321038310f Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 12:57:33 -0800 Subject: [PATCH 05/23] Order GitHub exports by one clock V-1's github_export approve/request-change cell recorded pull:42 as absent the moment it was ingested. 9d3a454 dated an export with no header or dated records by its file time, but kept ordering dated exports by their record times, so the two clocks were compared directly: two undated issue exports written today outranked a later export whose pull was last updated in March, and the newest snapshot was taken to be one that lacks the pull. An export's own time and a file time are now never compared. When any export carries no own time, all are ordered by file time; otherwise by their own time as before. An undated newest export still wins, and a checkout's identical file times still defer to the exports' own dates. Spec: spec/verification.md V-1 lifecycle matrix --- crates/kinbase/src/lifecycle.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/crates/kinbase/src/lifecycle.rs b/crates/kinbase/src/lifecycle.rs index c4c9465..5bee306 100644 --- a/crates/kinbase/src/lifecycle.rs +++ b/crates/kinbase/src/lifecycle.rs @@ -2332,7 +2332,7 @@ fn scan_github_export(source: &Path, repo: &Repository) -> Result)> = Vec::new(); + let mut exports: Vec<(Option, i64, PathBuf, Map)> = Vec::new(); for (mtime, path) in files { let bytes = read_bounded(&path)?; check_budget(&mut scan, bytes.len())?; @@ -2365,12 +2365,17 @@ fn scan_github_export(source: &Path, repo: &Repository) -> Result = BTreeMap::new(); let mut newest_ids: BTreeSet = BTreeSet::new(); @@ -2513,12 +2518,6 @@ fn export_time(map: &Map) -> Option { .max() } -fn mtime_rfc3339(seconds: i64) -> String { - chrono::DateTime::from_timestamp(seconds, 0) - .map(crate::time::format_rfc3339_millis) - .unwrap_or_default() -} - // -------------------------------------------------------------------------- // kindex: SQLite exports (nodes and edges) or a `.kin/` event tree // -------------------------------------------------------------------------- From 2d333ecb824bb3d52e86acadc664cbe26086cf15 Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 13:20:35 -0800 Subject: [PATCH 06/23] Record agent-trailer commits as ai_generated and report provenance on ingest test_git_authorship_survives_ingestion_without_inventing_human_review failed for both parametrisations: `ingest git_history` observation rows carried no `provenance` or `standing` at all, and a commit with an agent `Co-authored-by:` trailer under a person's author name was classified `human_review`. That provenance caps at `prevalent`, so trailer-marked commits could climb exactly where amendment 003 says they never may; a name in the author field is whoever ran the tool, not evidence of review. An agent marker now yields `ai_generated` regardless of the author identity. A ref record inherits the provenance of the commit it names instead of the `unknown` default. Ingest reports each observation's provenance and the standing it is admitted at, computed by the same helper corpus admission signs with (`model::observation_standing`), so the two cannot disagree. Spec: amendment-003-ruling-contract.md requirements 4 (provenance) and 6 (unlabelled) --- crates/kinbase/src/corpus.rs | 10 ++++------ crates/kinbase/src/ingest.rs | 2 ++ crates/kinbase/src/lifecycle.rs | 35 ++++++++++++++++++++++----------- crates/kinbase/src/model.rs | 11 +++++++++++ 4 files changed, 41 insertions(+), 17 deletions(-) diff --git a/crates/kinbase/src/corpus.rs b/crates/kinbase/src/corpus.rs index 18958f6..5311335 100644 --- a/crates/kinbase/src/corpus.rs +++ b/crates/kinbase/src/corpus.rs @@ -1209,12 +1209,10 @@ pub fn admit( // document would arrive with exactly the weight of the commits it is // meant to outrank. Provenance still clamps this, so an agent-written // document claiming `north_star` cannot reach `ratified`. - standing: match observation.atom_kind.as_deref() { - Some("north_star") | Some("invariant") | Some("directional") => { - "ratified".to_owned() - } - _ => "present".to_owned(), - }, + standing: crate::model::observation_standing( + observation.atom_kind.as_deref(), + &observation.provenance, + ), provenance: observation.provenance.clone(), governs_paths: observation.governs_paths.clone(), anchors: observation.anchors.clone(), diff --git a/crates/kinbase/src/ingest.rs b/crates/kinbase/src/ingest.rs index b3cee47..236e5bf 100644 --- a/crates/kinbase/src/ingest.rs +++ b/crates/kinbase/src/ingest.rs @@ -1200,6 +1200,8 @@ pub fn observation_result( "repository_id": observation.repository_id, "revision": observation.revision, "branch": observation.branch, + "provenance": observation.provenance, + "standing": crate::model::observation_standing(observation.atom_kind.as_deref(), &observation.provenance), "disposition": disposition, "state": state, "observation_state": state, diff --git a/crates/kinbase/src/lifecycle.rs b/crates/kinbase/src/lifecycle.rs index 5bee306..d19b26f 100644 --- a/crates/kinbase/src/lifecycle.rs +++ b/crates/kinbase/src/lifecycle.rs @@ -1951,17 +1951,11 @@ fn commit_provenance(author: &str, email: &str, trailers: &str, subject: &str) - let agent = AGENT_MARKERS .iter() .any(|marker| attributed.contains(marker) || identity.contains(marker)); - if !agent { - return "unknown".to_owned(); - } - // An agent is named. If a person's identity is on the commit as well, they - // reviewed and took ownership of the output; that is weaker than authorship - // but stronger than an unattended write. - if AGENT_MARKERS.iter().any(|marker| identity.contains(marker)) { - "ai_generated".to_owned() - } else { - "human_review".to_owned() - } + // A person's name in the author field beside an agent trailer is not evidence + // that anyone reviewed the output: it is whoever ran the tool. Reading it as + // `human_review` let trailer-marked commits climb to `prevalent`, which the + // provenance ceiling forbids end to end for agent `Co-authored-by:` commits. + if agent { "ai_generated" } else { "unknown" }.to_owned() } /// A sweeping refactor touches hundreds of files and says very little about any @@ -2297,6 +2291,12 @@ fn scan_git_history( } else { "unreviewed-branch".to_owned() }; + // A ref is evidence about the commit it names, so it carries that + // commit's authorship; left at the default it reported an agent + // commit's revision as `unknown`. + if let Some(commit) = by_sha.get(sha) { + record.provenance = commit.provenance.clone(); + } record.revision = Some(sha.to_owned()); record.branch = Some(name.trim_start_matches("refs/heads/").to_owned()); scan.unit_ids.insert(native_id); @@ -4462,6 +4462,19 @@ fn derive_answers(builder: &mut FactBuilder<'_>, _key: &str, rows: &[&Observatio mod tests { use super::*; + #[test] + fn an_agent_trailer_beside_a_human_author_is_not_human_review() { + let trailer = "Claude "; + assert_eq!( + commit_provenance("Ada", "ada@example.invalid", trailer, "Fix"), + "ai_generated" + ); + assert_eq!( + commit_provenance("Ada", "ada@example.invalid", "", "Fix"), + "unknown" + ); + } + fn git_repo() -> (tempfile::TempDir, Repository) { let dir = tempfile::tempdir().expect("temp dir"); let run = |args: &[&str]| { diff --git a/crates/kinbase/src/model.rs b/crates/kinbase/src/model.rs index 075e658..8b67779 100644 --- a/crates/kinbase/src/model.rs +++ b/crates/kinbase/src/model.rs @@ -209,6 +209,17 @@ pub fn effective_standing(standing: &str, provenance: &str) -> String { } } +/// The standing an ingested observation is admitted at: `present`, except a +/// direction-bearing kind, and always clamped by provenance. Ingest reports it +/// and corpus admission signs it, so the two cannot disagree. +pub fn observation_standing(atom_kind: Option<&str>, provenance: &str) -> String { + let claimed = match atom_kind { + Some("north_star") | Some("invariant") | Some("directional") => "ratified", + _ => "present", + }; + effective_standing(claimed, provenance) +} + pub fn default_standing_pub() -> String { default_standing() } From 2ad65bbf83ff71ec99046772caf01b00f50bd2f9 Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 13:20:35 -0800 Subject: [PATCH 07/23] Ask about contested keys and let a shrug close the question it settles test_conflicting_evidence_without_answering_authority_opens_question and test_shrug_is_terminal_while_unruled_remains_actionable failed because a two-head conflict never raised a question. The conflict Unknown blocks "use of logical key K", which matches neither the projected task nor the decision, so `has_blocking_unknown` was false and the question stage was skipped outright. The "a contested key always asks" branch inside it (bd9502f, kept by c76147d) was unreachable. The stage now also runs when an open conflict exists; the stopping reason reports a raised question only when an Unknown actually blocked this projection. With questions raised, the shrug case then failed: the reducer drops a shrugged key's derived Unknowns, but the question already raised and its persisted Unknown stayed open on every later read. A recording projection that sees a current `shrug` now closes that key's still-open questions, appending a closed question record and a signed Unknown closure naming the shrug fact. Already-closed questions are untouched, so repeated projections append nothing. `find_unknown` gains a repo-explicit variant so closure reads the repository being projected rather than the working directory. Spec: amendment-003-ruling-contract.md requirements 2 (unknown) and 5 (shrug) --- crates/kinbase/src/projector.rs | 28 ++++++++++++++++++++-- crates/kinbase/src/questions.rs | 41 ++++++++++++++++++++++++++++++--- 2 files changed, 64 insertions(+), 5 deletions(-) diff --git a/crates/kinbase/src/projector.rs b/crates/kinbase/src/projector.rs index 6133b11..7fa6d35 100644 --- a/crates/kinbase/src/projector.rs +++ b/crates/kinbase/src/projector.rs @@ -352,6 +352,21 @@ pub fn project_with( ingested_events.extend(store_view.events); references.extend(store_view.references); } + // A `shrug` ruled after a question was raised settles that question too. + // The reducer drops the key's derived Unknowns, but a question already + // raised and its persisted Unknown stayed open for every later read, so the + // shrug never became terminal (amendment 003, `shrug`). Closed before the + // closure set is read, so this projection already honours it. + if recording == Recording::Full { + let shrugs: BTreeMap<&str, &str> = facts + .iter() + .filter(|fact| fact.atom_kind == "shrug" && fact.status == "current") + .map(|fact| (fact.logical_key.as_str(), fact.fact_id.as_str())) + .collect(); + if !shrugs.is_empty() { + crate::questions::close_shrugged(repo, &shrugs)?; + } + } // A closure record is authoritative across stores: the original Unknown // remains in append-only history, but no later projection may treat it as // still blocking after the signed answer. @@ -616,7 +631,15 @@ pub fn project_with( )); } - let question_id = if !has_blocking_unknown || recording == Recording::ReadOnly { + // A contested key asks even when it blocks nothing this projection decides. + // Gating the question stage on a blocker alone left the conflict branch + // below unreachable, so a conflict on a key nobody named as blocked was + // never asked about (amendment 003, `unknown`). + let has_open_conflict = open_unknowns + .iter() + .any(|unknown| unknown.kind == "conflict"); + let may_ask = has_blocking_unknown || has_open_conflict; + let question_id = if !may_ask || recording == Recording::ReadOnly { None } else { let evidence: Vec = context @@ -689,7 +712,8 @@ pub fn project_with( && evaluate_cached(fact, &context, &cache).marginal_value > 0 })); let stopping_reason = stopping_reason( - question_id.is_some(), + // A question about a conflict elsewhere did not stop this projection. + question_id.is_some() && has_blocking_unknown, sufficiency, residents_filled, item_ceiling_hit, diff --git a/crates/kinbase/src/questions.rs b/crates/kinbase/src/questions.rs index b799a5b..e86d583 100644 --- a/crates/kinbase/src/questions.rs +++ b/crates/kinbase/src/questions.rs @@ -86,9 +86,12 @@ fn find_question(question_id: &str) -> Result { } fn find_unknown(question_id: &str) -> Result { - let repo = repo()?; + find_unknown_in(&repo()?, question_id) +} + +fn find_unknown_in(repo: &Path, question_id: &str) -> Result { for store in [crate::StoreKind::Company, crate::StoreKind::Codebase] { - if let Ok(records) = crate::store::read_records(store, &repo, "unknowns.jsonl") { + if let Ok(records) = crate::store::read_records(store, repo, "unknowns.jsonl") { if let Some(record) = records.into_iter().rev().find(|record| { ["unknown_id", "fact_id", "event_id"] .iter() @@ -1096,7 +1099,7 @@ fn close_unknown(repo: &Path, question: &Value, answer_id: &str) -> Result Result, +) -> Result<(), ContractError> { + for question in latest_questions(repo).into_values() { + let Some(shrug_id) = question + .get("logical_key") + .and_then(Value::as_str) + .and_then(|key| shrugs.get(key)) + else { + continue; + }; + if !matches!( + question.get("status").and_then(Value::as_str), + Some("open" | "asked" | "awaiting_authority") + ) { + continue; + } + let closure_event_id = close_unknown(repo, &question, shrug_id)?; + let mut updated = question.clone(); + if let Value::Object(values) = &mut updated { + values.insert("status".to_owned(), json!("closed")); + values.insert("closure_event_id".to_owned(), json!(closure_event_id)); + } + append_company(repo, "questions.jsonl", &updated)?; + } + Ok(()) +} + fn status(question_id: &str, json: bool) -> Result<(), ContractError> { let repo = repo()?; let question = find_question(question_id)?; From d2699962ce1a54d0256c087eec603c74845d603c Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 13:22:34 -0800 Subject: [PATCH 08/23] Treat a hook prompt and its transcript copy as one message Since the UserPromptSubmit hook began queueing prompts for a detached `session observe` worker (8379a2a), a message the host later delivers in its transcript is observed twice: once under the id the hook derives from the prompt text, once under the host's own id. Each copy minted its own observation, candidates and receipts, so a Stop returned both sets and V-9 parity failed with "host Stop did not retain the observation's admission receipts". observe now looks up the session's events before it assigns ids: a record whose text the session already observed, where either side is a hook prompt id, takes the id seen first. Candidate ids are derived from the message id and admission is idempotent per candidate, so the second copy returns the first copy's receipts and the identity-keyed ledgers keep one row. The worker and an explicit observe can run at once, so the read and the ledger appends are serialized by a lock beside the Personal ledgers. Spec: spec/verification.md V-9 parity --- CHANGELOG.md | 7 +++ crates/kinbase/src/session.rs | 57 ++++++++++++++++++ crates/kinbase/tests/hook_host_protocol.rs | 70 ++++++++++++++++++++++ 3 files changed, 134 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ae9a9e..7c26f1f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,13 @@ Notable changes to Kinbase. Dates are UTC. "The governance guard blocks the edit" and "incorporate" no longer route to the Company. (#43) +### Fixed + +- A prompt the `UserPromptSubmit` hook captured and the transcript's copy of + the same message are one message: the transcript copy takes the hook's id, + so it mints no second set of candidates and receipts, and a Stop returns + each receipt once. + ## 0.1.2 - 2026-10-30 ### Fixed diff --git a/crates/kinbase/src/session.rs b/crates/kinbase/src/session.rs index da35084..fe4b98f 100644 --- a/crates/kinbase/src/session.rs +++ b/crates/kinbase/src/session.rs @@ -543,6 +543,15 @@ pub fn observe( } } } + // A hook prompt's worker and an observe of the transcript can run at + // once; each must see the other's events before it picks an id, so the + // read below and the ledger appends are serialized. + // shortcut: one lock for every session's observes, held through + // classification; stripe it by session if live-classifier workers queue. + let store = crate::store::store_root(crate::StoreKind::Personal, &repo); + crate::paths::ensure_private_dir(&store, "physical store root")?; + let observe_lock = crate::paths::lock_file(&store.join(".observe.lock"), "observe lock")?; + adopt_seen_prompt_ids(session, &mut records); let mut observations = Vec::new(); for record in &records { let event_id = record["id"].as_str().unwrap_or_default().to_owned(); @@ -777,6 +786,7 @@ pub fn observe( for candidate in &candidate_records { append_personal("candidates.jsonl", candidate)?; } + drop(observe_lock); let mut admissions = Vec::new(); let mut questions = BTreeSet::new(); @@ -821,6 +831,53 @@ pub fn observe( Ok(()) } +/// An id `queue_hook_observation` derived for a host prompt. +fn is_hook_prompt_id(id: &str) -> bool { + id.strip_prefix("prompt_") + .is_some_and(|rest| rest.len() == 24 && rest.bytes().all(|b| b.is_ascii_hexdigit())) +} + +/// A host prompt and the transcript's copy of it are one message. The hook +/// queues the prompt under an id derived from its text and the transcript +/// names it again under the host's own id; each minted its own candidates +/// and receipts, so a Stop returned both sets (V-9 parity). A record whose +/// text this session already observed, where either side is a hook prompt, +/// takes the id seen first, so its candidates and receipts are the same ones. +fn adopt_seen_prompt_ids(session: &str, records: &mut [Map]) { + let canonical = crate::json::jcs_text(&Value::String(session.to_owned())); + let Ok(session_text) = serde_json::from_str::(&canonical) else { + return; + }; + let marker = format!("\"session_id\":{canonical}"); + let seen = personal_records_tagged( + "session-events.jsonl", + "session_id", + &[session_text.as_str()], + |line| crate::store::bytes_contain(line, marker.as_bytes()), + ); + for record in records.iter_mut() { + let (Some(id), Some(text)) = ( + record.get("id").and_then(Value::as_str), + record.get("text").and_then(Value::as_str), + ) else { + continue; + }; + let digest = sha256_bytes(text.as_bytes()); + let first = seen + .iter() + .filter(|event| { + crate::json::get_str(event, "session_id") == Some(session_text.as_str()) + && crate::json::get_str(event, "text_digest") == Some(digest.as_str()) + }) + .filter_map(|event| crate::json::get_str(event, "event_id")) + .find(|seen_id| *seen_id != id && (is_hook_prompt_id(id) || is_hook_prompt_id(seen_id))) + .map(str::to_owned); + if let Some(first) = first { + record.insert("id".to_owned(), Value::String(first)); + } + } +} + /// A host session token is caller-supplied and opaque. Record it as active /// when it has not been seen before so Stop/SessionEnd can checkpoint it. /// The host a session source kind comes from. diff --git a/crates/kinbase/tests/hook_host_protocol.rs b/crates/kinbase/tests/hook_host_protocol.rs index 8db5c91..ce973f8 100644 --- a/crates/kinbase/tests/hook_host_protocol.rs +++ b/crates/kinbase/tests/hook_host_protocol.rs @@ -360,6 +360,76 @@ fn the_same_prompt_seen_again_adds_no_record() { assert_eq!(counts(), first, "{ledgers:?}"); } +#[test] +fn the_transcript_copy_of_a_hook_prompt_is_the_same_message() { + // The hook captured the prompt and the transcript then named it again + // under the host's own id: each minted its own candidates and receipts, + // so a Stop returned both sets (V-9 parity). + let temp = TempDir::new().expect("tempdir"); + let world = world(&temp); + let text = "We decided to keep the retry budget at three attempts."; + let prompt = json!({ + "session_id": "host-session-15", + "cwd": world.repo.display().to_string(), + "hook_event_name": "UserPromptSubmit", + "prompt": text + }); + assert!( + kinbase( + &world, + &["hooks", "dispatch", "claude", "UserPromptSubmit"], + &[], + prompt.to_string().as_bytes(), + ) + .status + .success() + ); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while fs::read_dir(pending_dir(&world)) + .map(|mut entries| entries.next().is_some()) + .unwrap_or(false) + { + assert!( + std::time::Instant::now() < deadline, + "the worker never finished" + ); + std::thread::sleep(std::time::Duration::from_millis(50)); + } + // One observation, and with it one set of atoms and candidates. + let observations = || { + fs::read_to_string(world.personal.join("observations.jsonl")) + .map(|text| text.lines().count()) + .unwrap_or(0) + }; + let before = observations(); + assert_eq!(before, 1, "the prompt was observed"); + let transcript = temp.path().join("transcript.jsonl"); + fs::write( + &transcript, + format!( + "{}\n", + json!({"id": "host-native-1", "role": "user", "text": text, + "observed_at": chrono::Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string(), + "source_kind": "claude_jsonl"}) + ), + ) + .expect("transcript"); + let observed = ok(&kinbase( + &world, + &[ + "session", + "observe", + "host-session-15", + "--event", + transcript.to_str().unwrap(), + "--json", + ], + &[], + b"", + )); + assert_eq!(observations(), before, "{observed}"); +} + fn pending_dir(world: &World) -> PathBuf { world.personal.join("pending-observations") } From 647dd4a8cbfaef9594fc6e00a1f8fdbea802636e Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 13:13:23 -0800 Subject: [PATCH 09/23] Admit Company candidates after the local destinations of a message test_expired_closing_deadline_emits_one_signed_orphan_abandoned found no orphan_abandoned after the closing deadline. `session observe` admitted a message's candidates in sentence order, so for "personal. company. codebase." the Company attempt failed against an unreachable endpoint while only the Personal sibling had committed. The apology went to Personal alone; the Codebase sibling committed afterwards and was owed none. Since b8273fa a repository closes only the apologies its own Codebase committed, so the deadline had nothing to abandon. Local destinations are now admitted first and Company last, so every destination committed by the time Company fails receives its apology. Spec: spec/architecture.md (a terminally divergent fan-out emits a new apology Unknown in every committed destination) --- crates/kinbase/src/session.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/kinbase/src/session.rs b/crates/kinbase/src/session.rs index fe4b98f..4bb2a82 100644 --- a/crates/kinbase/src/session.rs +++ b/crates/kinbase/src/session.rs @@ -795,7 +795,15 @@ pub fn observe( questions.insert(question); } } - for candidate in &candidate_records { + // Company goes last: an apology is owed in every destination committed + // when the Company attempt fails, and a Codebase sibling admitted after + // that failure got none, so its deadline had no orphan to abandon. + let (company, local): (Vec<&Value>, Vec<&Value>) = + candidate_records.iter().partition(|candidate| { + crate::json::get_str(candidate, "destination") + .is_some_and(|destination| destination.starts_with("company")) + }); + for candidate in local.into_iter().chain(company) { admissions.push(admit_candidate(&launcher, &repo, candidate)?); } From 72156e82187ef84f2a78134f4069f0b6da7e58dc Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 13:13:33 -0800 Subject: [PATCH 10/23] Re-read the nonce reservation under the admission lock After a fan-out was killed, test_kill_at_every_transition_then_concurrent_retry retried it with two concurrent checkpoints and found two Codebase events for one candidate. Each checkpoint read the journal outside the admission lock, found no reservation, built its own event bytes (a different asserted_at), then took the lock in turn; the second rebound the nonce to its own bytes and committed a second event. Under the lock, a reservation another process completed meanwhile now decides the bytes, so a concurrent retry commits the same content-addressed event. Spec: spec/architecture.md (a matching committed event returns its original receipt) --- crates/kinbase/src/session.rs | 42 +++++++++++++++++++++++------------ 1 file changed, 28 insertions(+), 14 deletions(-) diff --git a/crates/kinbase/src/session.rs b/crates/kinbase/src/session.rs index 4bb2a82..15f33f0 100644 --- a/crates/kinbase/src/session.rs +++ b/crates/kinbase/src/session.rs @@ -3043,20 +3043,24 @@ fn reserve_nonce( payload_digest: &str, receipt_id: &str, ) -> Result<(Vec, Value), ContractError> { - let bound = journal - .read("nonce_reservation") - .and_then(|marker| crate::json::get_str(&marker, "event_canonical").map(str::to_owned)); - let (canonical, event) = match bound { - Some(canonical) => { - let event = crate::json::parse_strict_value(canonical.as_bytes()).map_err(|error| { - ContractError::integrity( - "DIGEST_MISMATCH", - format!("journaled event bytes are not canonical: {error}"), - "Preserve the journal; the bound event bytes are never reinterpreted.", - ) - })?; - (canonical, event) - } + let bound = || -> Result, ContractError> { + let Some(canonical) = journal + .read("nonce_reservation") + .and_then(|marker| crate::json::get_str(&marker, "event_canonical").map(str::to_owned)) + else { + return Ok(None); + }; + let event = crate::json::parse_strict_value(canonical.as_bytes()).map_err(|error| { + ContractError::integrity( + "DIGEST_MISMATCH", + format!("journaled event bytes are not canonical: {error}"), + "Preserve the journal; the bound event bytes are never reinterpreted.", + ) + })?; + Ok(Some((canonical, event))) + }; + let (canonical, event) = match bound()? { + Some(bound) => bound, None => { let event = build_destination_event(Some(launcher), store, repository_uuid, record)?; (crate::json::record_text(&event)?, event) @@ -3064,6 +3068,16 @@ fn reserve_nonce( }; if !journal.is_complete("nonce_reservation") { let _generation = repository.admission_lock(repository_uuid)?; + // Two concurrent retries both found no reservation and each built + // its own bytes (a different `asserted_at`); the second used to + // rebind the nonce to them and commit a second event. Whoever + // reserved first under the lock decides the bytes. + if journal.is_complete("nonce_reservation") + && let Some(reserved) = bound()? + { + let (canonical, event) = reserved; + return Ok((canonical.into_bytes(), event)); + } journal.begin( "nonce_reservation", json!({ From 4b8556310435603b7bd80576631f520309ac160b Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 13:13:33 -0800 Subject: [PATCH 11/23] Tolerate losing the race to add the quarantine identity column Two concurrent checkpoints in test_kill_at_every_transition_then_concurrent_retry opened a store that had no quarantine identity column yet. Both saw it missing, both ran ALTER TABLE, and the second failed "duplicate column name", ending its checkpoint with RUN_INTEGRITY_FAILED. The column arrived in d7a0522 as a check-then-alter migration. A duplicate-column failure now means another process added the column first; the unique index is still created if absent. --- crates/kinbase/src/private.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/kinbase/src/private.rs b/crates/kinbase/src/private.rs index a187842..498afe1 100644 --- a/crates/kinbase/src/private.rs +++ b/crates/kinbase/src/private.rs @@ -265,10 +265,20 @@ impl PrivateStore { ) .map_err(sqlite_error("quarantine schema"))?; if !has_identity { + // Two processes opening a fresh store both see no column; the + // second ALTER then failed "duplicate column name" and ended a + // concurrent checkpoint with RUN_INTEGRITY_FAILED. Losing that + // race is success: the column exists. + match self + .connection + .execute_batch("ALTER TABLE quarantine ADD COLUMN identity TEXT;") + { + Err(error) if error.to_string().contains("duplicate column name") => {} + added => added.map_err(sqlite_error("quarantine identity"))?, + } self.connection .execute_batch( - "ALTER TABLE quarantine ADD COLUMN identity TEXT; - CREATE UNIQUE INDEX IF NOT EXISTS quarantine_identity ON quarantine(identity);", + "CREATE UNIQUE INDEX IF NOT EXISTS quarantine_identity ON quarantine(identity);", ) .map_err(sqlite_error("quarantine identity"))?; } From 5fb1142dff438b9fb39893cf049b5d668ca7992a Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 13:13:33 -0800 Subject: [PATCH 12/23] Stop asking a Company endpoint that already ran out its read budget test_partial_fanout_failure_does_not_roll_back_committed_destination timed out with empty stdout: observing the held-out corpus against a Company endpoint that accepts connections and never answers waited the 20 s read budget once per Company candidate, 44 of them, far past the 120 s the caller allows. The budget was 1.5 s when the suite last passed; af69319 raised it to 20 s so slow snapshots stop reading as outages, and that stays. A process now remembers an endpoint that let a request run out its read budget and fails later requests to it at once with COMPANY_UNREACHABLE. The attempts it skips stay pending and are retried by a later pass, as an unreachable attempt already was. Spec: spec/cli.md (COMPANY_UNREACHABLE: Company endpoint cannot answer within timeout) --- crates/kinbase/src/company/client.rs | 32 ++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/crates/kinbase/src/company/client.rs b/crates/kinbase/src/company/client.rs index d3769e5..e6d53bd 100644 --- a/crates/kinbase/src/company/client.rs +++ b/crates/kinbase/src/company/client.rs @@ -13,6 +13,11 @@ use std::time::Duration; static SEQUENCE: AtomicU64 = AtomicU64::new(0); +/// `host:port` of each Company endpoint that ran out a read budget in this +/// process. +static UNANSWERED: std::sync::OnceLock>> = + std::sync::OnceLock::new(); + /// A snapshot is a reduction over the whole Company event log, so it costs /// what the log costs: 2.5 s against one deployment's 2,720 events and rising. /// At 1,500 ms -- a bound sized for proof fixtures -- every repository in the @@ -163,9 +168,21 @@ impl Client { if self.oidc.is_some() || self.gateway_key.is_some() { headers.insert(1, ("X-Kinbase-Token".to_owned(), self.token.token.clone())); } + // An endpoint that let one request run out its read budget is not + // asked again by this process: an observation fanning out 44 Company + // candidates to a silent endpoint waited 20 s for each, 15 minutes in + // all, and every later attempt is retried by a later pass anyway. + let endpoint = format!("{}:{}", self.host, self.port); + let silent = UNANSWERED.get_or_init(Default::default); + if silent.lock().is_ok_and(|silent| silent.contains(&endpoint)) { + return Err(ContractError::unreachable( + "Company endpoint did not answer within the read budget earlier in this process; not asked again", + ) + .with_detail(json!({"timeout_observed": true, "omitted_count": 1}))); + } self.bytes_sent .set(self.bytes_sent.get() + body_bytes.len() as u64 + 256); - http::request( + let response = http::request( self.scheme, &self.host, self.port, @@ -174,7 +191,18 @@ impl Client { &headers, &body_bytes, read_timeout, - ) + ); + if let Err(error) = &response + && error + .detail + .as_ref() + .and_then(|detail| detail.get("timeout_observed")) + == Some(&Value::Bool(true)) + && let Ok(mut silent) = silent.lock() + { + silent.insert(endpoint); + } + response } pub fn get(&self, path: &str) -> Result { From 438ecc633c60f0873785296d7b40081843c38a05 Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 14:33:02 -0800 Subject: [PATCH 13/23] Address review: one read of .kin/config, generic wording, and a full changelog Read .kin/config once and match a named marker instead of a hard-coded length. Amendment 006 and release.yml no longer name the deployment, which also clears generic_by_construction's last disclosure. The changelog now lists every user-visible change in this branch, not only the hook-prompt fix. --- .github/workflows/release.yml | 2 +- CHANGELOG.md | 25 +++++++++++++++++++ crates/kinbase/src/codebase.rs | 9 +++---- spec/amendment-006-kinbase-config-filename.md | 3 ++- 4 files changed, 32 insertions(+), 7 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e085382..03a69bf 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -67,7 +67,7 @@ jobs: with: pattern: kinbase-* merge-multiple: true - # wandercom releases are immutable once published, so the assets go onto a + # Releases here are immutable once published, so the assets go onto a # draft first. A re-run after a partial publish finds the draft and finishes it. - env: GH_TOKEN: ${{ github.token }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c26f1f..a62a952 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,8 +22,33 @@ Notable changes to Kinbase. Dates are UTC. "The governance guard blocks the edit" and "incorporate" no longer route to the Company. (#43) +### Changed (from fixing acceptance failures) + +- Omitting `--as-of` on `status`, `fsck`, `explain`, `corpus rebuild` and + `recall` uses the repository's recorded proof clock again + (`as_of_source=recorded-proof-clock`), not the cached authority snapshot's + `issued_at`. `project` and SessionStart still advance to the snapshot. +- A git commit carrying an agent `Co-authored-by:` trailer is recorded as + `ai_generated` whoever its author is, so its standing stays capped; existing + repositories re-record such commits on their next ingest. Ingest output now + reports each observation's `provenance` and `standing`. +- A contested key with no answering authority opens a question, and a later + shrug on that key closes it. +- `session observe` admits a message's Personal and Codebase candidates + before its Company candidate, so a Company failure leaves an apology in every + destination that already committed. +- Once a Company endpoint has used up its read budget, the rest of that + command fails further requests to it at once with `COMPANY_UNREACHABLE`; + they stay pending and a later run retries them. + ### Fixed +- A malformed kinbase config at `.kin/config` (one naming `kinbase-repo/`) + refuses with exit 5 instead of being skipped as Kindex's file. +- GitHub exports are ordered by one clock: when any export has no date of its + own, all are ordered by file modification time. +- Two concurrent checkpoints no longer fail on adding the quarantine identity + column, and concurrent retries of one admission commit one event. - A prompt the `UserPromptSubmit` hook captured and the transcript's copy of the same message are one message: the transcript copy takes the hook's id, so it mints no second set of candidates and receipts, and a Stop returns diff --git a/crates/kinbase/src/codebase.rs b/crates/kinbase/src/codebase.rs index 769650d..a912b3d 100644 --- a/crates/kinbase/src/codebase.rs +++ b/crates/kinbase/src/codebase.rs @@ -320,12 +320,11 @@ fn config_path_for(kin: &std::path::Path) -> Option { // A `.kin/config` naming our schema is kinbase's own, so malformed bytes there // must refuse with exit 5 (spec/cli.md first-run table), not be skipped as // Kindex's; Kindex's YAML never names `kinbase-repo/`. - let legacy_names_ours = std::fs::read(&legacy) - .is_ok_and(|bytes| bytes.windows(13).any(|window| window == b"kinbase-repo/")); + const MARKER: &[u8] = b"kinbase-repo/"; + let bytes = std::fs::read(&legacy).unwrap_or_default(); + let legacy_names_ours = bytes.windows(MARKER.len()).any(|window| window == MARKER); let legacy_parses = || { - std::fs::read_to_string(&legacy) - .ok() - .is_some_and(|text| RepoConfig::parse(&text).is_ok()) + std::str::from_utf8(&bytes).is_ok_and(|text| RepoConfig::parse(text).is_ok()) }; if legacy_names_ours && (!ours.exists() || !legacy_parses()) { return Some(legacy); diff --git a/spec/amendment-006-kinbase-config-filename.md b/spec/amendment-006-kinbase-config-filename.md index 1d81087..fc3fc5b 100644 --- a/spec/amendment-006-kinbase-config-filename.md +++ b/spec/amendment-006-kinbase-config-filename.md @@ -6,7 +6,8 @@ ratify its exact digest.** ## Why The ratified artifacts name kinbase's tracked repository config `.kin/config`. -Kindex already owns that path, in YAML, and most Wander repositories carry one. +Kindex already owns that path, in YAML, and most repositories at one deployment +carry one. Kinbase read Kindex's YAML as a malformed kinbase config and refused with `DIGEST_MISMATCH`, so it could not be initialised in those repositories. Commit `e970ae5` ("Give kinbase its own config filename so it can share .kin/ with From a3cf6d99177b42c7b431c3d7b6256fc4e2b1ea47 Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 14:32:39 -0800 Subject: [PATCH 14/23] Adopt a hook prompt's id only for user messages Adoption matched on text alone, so an assistant turn that repeated a captured prompt word for word took the prompt's id; its observation and atoms then collided with the prompt's and the identity-keyed ledgers dropped the assistant turn as a duplicate. Session events now record the message role, and adoption applies only when both the record and the earlier event are user messages. An event written before the role was recorded is never adopted, which keeps the turns apart as they were before adoption existed. --- crates/kinbase/src/session.rs | 8 +++++++- crates/kinbase/tests/hook_host_protocol.rs | 17 ++++++++++++----- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/crates/kinbase/src/session.rs b/crates/kinbase/src/session.rs index 15f33f0..75b4231 100644 --- a/crates/kinbase/src/session.rs +++ b/crates/kinbase/src/session.rs @@ -597,6 +597,7 @@ pub fn observe( "event_id": event_id, "event_type": "observation", "observed_at": observed_at, + "role": record["role"], "text_digest": digest }), )); @@ -851,6 +852,9 @@ fn is_hook_prompt_id(id: &str) -> bool { /// and receipts, so a Stop returned both sets (V-9 parity). A record whose /// text this session already observed, where either side is a hook prompt, /// takes the id seen first, so its candidates and receipts are the same ones. +/// Only user messages qualify on both sides: an assistant turn that echoes a +/// prompt is a turn of its own, and adopting the prompt's id dropped it as a +/// duplicate. A seen event without a recorded role is never adopted. fn adopt_seen_prompt_ids(session: &str, records: &mut [Map]) { let canonical = crate::json::jcs_text(&Value::String(session.to_owned())); let Ok(session_text) = serde_json::from_str::(&canonical) else { @@ -864,9 +868,10 @@ fn adopt_seen_prompt_ids(session: &str, records: &mut [Map]) { |line| crate::store::bytes_contain(line, marker.as_bytes()), ); for record in records.iter_mut() { - let (Some(id), Some(text)) = ( + let (Some(id), Some(text), Some("user")) = ( record.get("id").and_then(Value::as_str), record.get("text").and_then(Value::as_str), + record.get("role").and_then(Value::as_str), ) else { continue; }; @@ -876,6 +881,7 @@ fn adopt_seen_prompt_ids(session: &str, records: &mut [Map]) { .filter(|event| { crate::json::get_str(event, "session_id") == Some(session_text.as_str()) && crate::json::get_str(event, "text_digest") == Some(digest.as_str()) + && crate::json::get_str(event, "role") == Some("user") }) .filter_map(|event| crate::json::get_str(event, "event_id")) .find(|seen_id| *seen_id != id && (is_hook_prompt_id(id) || is_hook_prompt_id(seen_id))) diff --git a/crates/kinbase/tests/hook_host_protocol.rs b/crates/kinbase/tests/hook_host_protocol.rs index ce973f8..39c6892 100644 --- a/crates/kinbase/tests/hook_host_protocol.rs +++ b/crates/kinbase/tests/hook_host_protocol.rs @@ -403,14 +403,21 @@ fn the_transcript_copy_of_a_hook_prompt_is_the_same_message() { }; let before = observations(); assert_eq!(before, 1, "the prompt was observed"); + // The transcript carries the prompt again and an assistant turn that + // echoes it word for word; the echo is a turn of its own. let transcript = temp.path().join("transcript.jsonl"); + let line = |id: &str, role: &str| { + json!({"id": id, "role": role, "text": text, + "observed_at": chrono::Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string(), + "source_kind": "claude_jsonl"}) + .to_string() + }; fs::write( &transcript, format!( - "{}\n", - json!({"id": "host-native-1", "role": "user", "text": text, - "observed_at": chrono::Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string(), - "source_kind": "claude_jsonl"}) + "{}\n{}\n", + line("host-native-1", "user"), + line("host-native-2", "assistant") ), ) .expect("transcript"); @@ -427,7 +434,7 @@ fn the_transcript_copy_of_a_hook_prompt_is_the_same_message() { &[], b"", )); - assert_eq!(observations(), before, "{observed}"); + assert_eq!(observations(), before + 1, "{observed}"); } fn pending_dir(world: &World) -> PathBuf { From 0ce1fa33b919dfdbc5c3ec99daaab8f513ecec1b Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 14:34:28 -0800 Subject: [PATCH 15/23] Attribute a commit to an agent only from its authorship metadata commit_provenance searched the subject as well as the trailers and author identity for agent markers. Once an agent marker meant `ai_generated` outright, an ordinary subject such as "Fix cursor pagination" marked an unattributed commit as agent-written, and ingest reported provenance that no metadata supports. A subject is prose, not authorship: only the `Co-authored-by` trailers and the author identity attribute a commit now, and unmarked history stays `unknown`. Spec: amendment-003-ruling-contract.md requirements 4 (provenance) and 6 (unlabelled) --- crates/kinbase/src/lifecycle.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/crates/kinbase/src/lifecycle.rs b/crates/kinbase/src/lifecycle.rs index d19b26f..675ade4 100644 --- a/crates/kinbase/src/lifecycle.rs +++ b/crates/kinbase/src/lifecycle.rs @@ -1942,12 +1942,15 @@ const BOT_MARKERS: [&str; 5] = [ /// wrote it -- most tools leave no marker at all, so any existing repository's /// history is largely unrecoverable. Claiming those commits as deliberate human /// direction would manufacture exactly the signal this field exists to protect. -fn commit_provenance(author: &str, email: &str, trailers: &str, subject: &str) -> String { +fn commit_provenance(author: &str, email: &str, trailers: &str) -> String { let identity = format!("{author} {email}").to_lowercase(); if BOT_MARKERS.iter().any(|marker| identity.contains(marker)) { return "bot".to_owned(); } - let attributed = format!("{trailers} {subject}").to_lowercase(); + // Only authorship metadata attributes a commit. A subject is prose: "Fix + // cursor pagination" names no agent, and reading it marked ordinary history + // as agent-written. + let attributed = trailers.to_lowercase(); let agent = AGENT_MARKERS .iter() .any(|marker| attributed.contains(marker) || identity.contains(marker)); @@ -2061,7 +2064,7 @@ fn scan_git_history( tree: parts[2].to_owned(), author_date: parts[3].to_owned(), subject: parts[7].to_owned(), - provenance: commit_provenance(parts[4], parts[5], parts[6], parts[7]), + provenance: commit_provenance(parts[4], parts[5], parts[6]), }); } let by_sha: BTreeMap<&str, &CommitInfo> = commits.iter().map(|c| (c.sha.as_str(), c)).collect(); @@ -4466,11 +4469,11 @@ mod tests { fn an_agent_trailer_beside_a_human_author_is_not_human_review() { let trailer = "Claude "; assert_eq!( - commit_provenance("Ada", "ada@example.invalid", trailer, "Fix"), + commit_provenance("Ada", "ada@example.invalid", trailer), "ai_generated" ); assert_eq!( - commit_provenance("Ada", "ada@example.invalid", "", "Fix"), + commit_provenance("Ada", "ada@example.invalid", ""), "unknown" ); } From dfffb18665a1818d6e9fbd69a77ce7bee231eae0 Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 14:34:28 -0800 Subject: [PATCH 16/23] Scope shrug closure, keep it from refusing projection, and ask a conflict once Review of the shrug and contested-key questions found four defects: - close_shrugged matched questions by logical key alone, so a shrug held by an evidence repository, or in another store under the same key, closed a question it does not govern. Shrugs are now taken only from this repository's own stores and match on the key and the scope of the Unknown the question asks about. - A close_shrugged error (a question whose Unknown record is missing, for one) refused every projection. It now reports a `shrug-closure-failed` diagnostic and the projection continues, as the orphan-abandonment path does for status. - close_unknown byte-sliced the closing id at 7..19, which panics on a short id or one whose range splits a character; a shrug fact id reaches it unvalidated. It slices with `str::get` and falls back to the whole id. - A conflict outside the projected decision was asked on every recording projection under the caller's decision, and the question id hashes the decision, so each distinct --decision opened another question for one conflict. Such a conflict is now asked under the decision its first question used, so it keeps one question. Blocking Unknowns still ask per decision, since the decision is what they block. Also removes find_unknown, left without callers when closure moved to the repository-explicit lookup. Spec: amendment-003-ruling-contract.md requirements 2 (unknown) and 5 (shrug) --- crates/kinbase/src/projector.rs | 45 ++++++++++++++++++----- crates/kinbase/src/questions.rs | 64 +++++++++++++++++++++++++-------- 2 files changed, 86 insertions(+), 23 deletions(-) diff --git a/crates/kinbase/src/projector.rs b/crates/kinbase/src/projector.rs index 7fa6d35..133079a 100644 --- a/crates/kinbase/src/projector.rs +++ b/crates/kinbase/src/projector.rs @@ -335,6 +335,7 @@ pub fn project_with( sources.push((evidence.clone(), crate::StoreKind::Codebase)); } let mut evidence_fact_count = 0usize; + let mut own_shrugs: BTreeMap<(String, String), String> = BTreeMap::new(); for (index, (source, store)) in sources.iter().enumerate() { let store_view = load_view(launcher, source, *store, as_of)?; conflict_event_ids.extend( @@ -346,6 +347,22 @@ pub fn project_with( ); if index >= 2 { evidence_fact_count += store_view.view.facts.len(); + } else { + // Only this repository's own stores may settle its questions: a + // shrug held by an evidence repository is that repository's ruling. + own_shrugs.extend( + store_view + .view + .facts + .iter() + .filter(|fact| fact.atom_kind == "shrug" && fact.status == "current") + .map(|fact| { + ( + (fact.logical_key.clone(), fact.scope.clone()), + fact.fact_id.clone(), + ) + }), + ); } facts.extend(store_view.view.facts); view_unknowns.extend(store_view.view.unknowns); @@ -357,14 +374,14 @@ pub fn project_with( // raised and its persisted Unknown stayed open for every later read, so the // shrug never became terminal (amendment 003, `shrug`). Closed before the // closure set is read, so this projection already honours it. - if recording == Recording::Full { - let shrugs: BTreeMap<&str, &str> = facts - .iter() - .filter(|fact| fact.atom_kind == "shrug" && fact.status == "current") - .map(|fact| (fact.logical_key.as_str(), fact.fact_id.as_str())) - .collect(); - if !shrugs.is_empty() { - crate::questions::close_shrugged(repo, &shrugs)?; + // A failed closure must not refuse the projection: the question stays + // open, which is the state it was already in, and the failure is reported. + if recording == Recording::Full && !own_shrugs.is_empty() { + if let Err(error) = crate::questions::close_shrugged(repo, &own_shrugs) { + crate::output::diagnostic( + "shrug-closure-failed", + json!({"code": error.code, "message": error.message}), + ); } } // A closure record is authoritative across stores: the original Unknown @@ -687,7 +704,17 @@ pub fn project_with( .iter() .filter(|unknown| unknown.loss_if_absent >= 7_000 || unknown.kind == "conflict") .partition(|unknown| blocks(unknown)); - for unknown in blocking.into_iter().chain(elsewhere) { + let blocking_count = blocking.len(); + for (index, unknown) in blocking.into_iter().chain(elsewhere).enumerate() { + // A conflict asked from an unrelated decision keeps the question it + // already has: the id hashes the decision, so asking under each + // caller's decision would open one question per decision. + let asked_under = if index >= blocking_count { + crate::questions::decision_asked_for(repo, &unknown.unknown_id) + } else { + None + }; + let decision = asked_under.as_deref().unwrap_or(decision); if let Some(id) = crate::questions::ensure_question(repo, unknown, decision, &evidence, &remaining)? { diff --git a/crates/kinbase/src/questions.rs b/crates/kinbase/src/questions.rs index e86d583..7bc12d9 100644 --- a/crates/kinbase/src/questions.rs +++ b/crates/kinbase/src/questions.rs @@ -85,10 +85,6 @@ fn find_question(question_id: &str) -> Result { }) } -fn find_unknown(question_id: &str) -> Result { - find_unknown_in(&repo()?, question_id) -} - fn find_unknown_in(repo: &Path, question_id: &str) -> Result { for store in [crate::StoreKind::Company, crate::StoreKind::Codebase] { if let Ok(records) = crate::store::read_records(store, repo, "unknowns.jsonl") { @@ -1094,6 +1090,16 @@ pub(crate) fn authority_fact_event( Ok(event) } +/// The short form of a closing record's id used in the closure event id: the +/// twelve characters after a seven-byte prefix (`answer_`), or the whole id +/// when that range is not on character boundaries. A shrug's fact id has no +/// such prefix, and byte slicing panicked on a short or multibyte one. +fn closure_suffix(answer_id: &str) -> &str { + answer_id + .get(7..min(19, answer_id.len())) + .unwrap_or(answer_id) +} + fn close_unknown(repo: &Path, question: &Value, answer_id: &str) -> Result { let unknown_id = question .get("unknown_id") @@ -1151,10 +1157,7 @@ fn close_unknown(repo: &Path, question: &Value, answer_id: &str) -> Result Result, + shrugs: &BTreeMap<(String, String), String>, ) -> Result<(), ContractError> { for question in latest_questions(repo).into_values() { - let Some(shrug_id) = question - .get("logical_key") - .and_then(Value::as_str) - .and_then(|key| shrugs.get(key)) - else { + let field = |name: &str| { + question + .get(name) + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned() + }; + let Some(shrug_id) = shrugs.get(&(field("logical_key"), field("unknown_scope"))) else { continue; }; if !matches!( @@ -1204,6 +1214,19 @@ pub(crate) fn close_shrugged( Ok(()) } +/// The decision an Unknown was first asked under, if any question asks about it. +pub(crate) fn decision_asked_for(repo: &Path, unknown_id: &str) -> Option { + company_records_with_repo(repo, "questions.jsonl") + .into_iter() + .find(|record| record.get("unknown_id").and_then(Value::as_str) == Some(unknown_id)) + .and_then(|record| { + record + .get("decision") + .and_then(Value::as_str) + .map(str::to_owned) + }) +} + fn status(question_id: &str, json: bool) -> Result<(), ContractError> { let repo = repo()?; let question = find_question(question_id)?; @@ -1273,3 +1296,16 @@ fn io_error(error: std::io::Error) -> ContractError { ExitCode::InternalFailure, ) } + +#[cfg(test)] +mod tests { + use super::closure_suffix; + + #[test] + fn a_short_or_multibyte_closing_id_does_not_panic() { + assert_eq!(closure_suffix("answer_0123456789abcdef"), "0123456789ab"); + assert_eq!(closure_suffix("fact_1"), "fact_1"); + // Byte 7 falls inside the first `é`. + assert_eq!(closure_suffix("fact_xéééééééé"), "fact_xéééééééé"); + } +} From ca57f7637d800b8bcb9507672e82c6e034b74dea Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 14:35:20 -0800 Subject: [PATCH 17/23] Flag a timeout only when the Company read actually timed out http::request marked timeout_observed on any error reading the status line, so a connection reset also looked like a spent read budget, and the client then skipped that endpoint for the rest of the process. Only WouldBlock (macOS) and TimedOut (Linux) now count as a timeout; any other read error is still COMPANY_UNREACHABLE and the endpoint is asked again. --- crates/kinbase/src/http.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/kinbase/src/http.rs b/crates/kinbase/src/http.rs index e3af4d6..25e4e49 100644 --- a/crates/kinbase/src/http.rs +++ b/crates/kinbase/src/http.rs @@ -620,7 +620,12 @@ pub fn request( error.kind() )) .with_detail(serde_json::json!({ - "timeout_observed": true, + // A read timeout surfaces as WouldBlock on macOS and TimedOut on + // Linux; a reset or other read error is not a spent budget. + "timeout_observed": matches!( + error.kind(), + std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut + ), "omitted_count": 1 })) })?; From 3e24c4a0a68889f098f999f453b83d5d73f92d23 Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 14:35:32 -0800 Subject: [PATCH 18/23] Admit Company candidates last in the checkpoint too The checkpoint admitted a session's candidates in candidate_id order, so a Company candidate could still be tried before its Codebase sibling. If Company then failed, the Codebase commit that followed got no apology, the same orphan gap that observe already closes by admitting Company last. The checkpoint now orders its candidates the same way, keeping candidate_id order within each group. Spec: spec/architecture.md (a terminally divergent fan-out emits a new apology Unknown in every committed destination) --- crates/kinbase/src/session.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/kinbase/src/session.rs b/crates/kinbase/src/session.rs index 75b4231..b3ddee5 100644 --- a/crates/kinbase/src/session.rs +++ b/crates/kinbase/src/session.rs @@ -2099,7 +2099,14 @@ pub fn checkpoint_internal(session: &str) -> Result<(Value, Option = candidates.values().collect(); + ordered.sort_by_key(|candidate| { + crate::json::get_str(candidate, "destination") + .is_some_and(|destination| destination.starts_with("company")) + }); + for candidate in ordered { let admitted = (|| { let digest = candidate_digest(candidate)?; let latest = latest.as_ref().map_err(Clone::clone)?; From b46d8e04a87b3785057cab8d079d0375662defec Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 14:35:32 -0800 Subject: [PATCH 19/23] Prefer any bound reservation bytes under the admission lock Under the lock, reserve_nonce re-read the journal only when the reservation was complete. A peer that began a reservation and crashed before completing it had already bound its event bytes, and this process then rebound the nonce to its own different bytes. Under the lock, any bytes already bound now win, just as they do in the read outside the lock. A completed reservation returns as before. --- crates/kinbase/src/session.rs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/crates/kinbase/src/session.rs b/crates/kinbase/src/session.rs index b3ddee5..d62b3ce 100644 --- a/crates/kinbase/src/session.rs +++ b/crates/kinbase/src/session.rs @@ -3072,7 +3072,7 @@ fn reserve_nonce( })?; Ok(Some((canonical, event))) }; - let (canonical, event) = match bound()? { + let (mut canonical, mut event) = match bound()? { Some(bound) => bound, None => { let event = build_destination_event(Some(launcher), store, repository_uuid, record)?; @@ -3083,12 +3083,13 @@ fn reserve_nonce( let _generation = repository.admission_lock(repository_uuid)?; // Two concurrent retries both found no reservation and each built // its own bytes (a different `asserted_at`); the second used to - // rebind the nonce to them and commit a second event. Whoever - // reserved first under the lock decides the bytes. - if journal.is_complete("nonce_reservation") - && let Some(reserved) = bound()? - { - let (canonical, event) = reserved; + // rebind the nonce to them and commit a second event. Bytes another + // process bound meanwhile win, whether it completed the reservation + // or crashed after beginning it. + if let Some(reserved) = bound()? { + (canonical, event) = reserved; + } + if journal.is_complete("nonce_reservation") { return Ok((canonical.into_bytes(), event)); } journal.begin( From 7a94e0dc63e4c55a995bd85755be8c8647112cbd Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 14:57:26 -0800 Subject: [PATCH 20/23] Merge the Unreleased changelog headings after rebasing onto #64 --- CHANGELOG.md | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a62a952..9038719 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,14 +4,6 @@ Notable changes to Kinbase. Dates are UTC. ## Unreleased -### Fixed - -- `hooks dispatch` no longer exits 4 (`CONFIG_INVARIANT`, "inherited - descriptor(s) outside the frozen allowlist") when the host leaks an open - descriptor into the hook. Startup attestation closes such descriptors for a - hook and names them on stderr; one under the Personal root still fails it. - Candidate spec amendment 004 records the change. - ### Changed - A statement goes to the Company only when it claims organization-wide @@ -21,9 +13,6 @@ Notable changes to Kinbase. Dates are UTC. organization word ("company policy", "the organization's roadmap"). "The governance guard blocks the edit" and "incorporate" no longer route to the Company. (#43) - -### Changed (from fixing acceptance failures) - - Omitting `--as-of` on `status`, `fsck`, `explain`, `corpus rebuild` and `recall` uses the repository's recorded proof clock again (`as_of_source=recorded-proof-clock`), not the cached authority snapshot's @@ -43,6 +32,11 @@ Notable changes to Kinbase. Dates are UTC. ### Fixed +- `hooks dispatch` no longer exits 4 (`CONFIG_INVARIANT`, "inherited + descriptor(s) outside the frozen allowlist") when the host leaks an open + descriptor into the hook. Startup attestation closes such descriptors for a + hook and names them on stderr; one under the Personal root still fails it. + Candidate spec amendment 004 records the change. - A malformed kinbase config at `.kin/config` (one naming `kinbase-repo/`) refuses with exit 5 instead of being skipped as Kindex's file. - GitHub exports are ordered by one clock: when any export has no date of its From 30c93f2d3c505444a7ac090fada654902b92c27a Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 15:05:37 -0800 Subject: [PATCH 21/23] Report a spent read budget from every phase of a Company answer Only a timeout while reading the status line set timeout_observed. When Company sent the status line and then stalled in the headers or the body, those reads used up the same read budget but reported nothing, so the client never marked the endpoint unanswered. A fan-out then waited the full budget again for every candidate. The status-line, header, fixed-body and chunked-body reads now report through one helper. As before, only WouldBlock or TimedOut counts as a timeout, so a reset in any phase still does not mark the endpoint. A unit test stalls a loopback answer after the status line, after the headers, and mid chunked body, and checks that each reports the timeout. --- crates/kinbase/src/http.rs | 114 ++++++++++++++++++++++++++++--------- 1 file changed, 88 insertions(+), 26 deletions(-) diff --git a/crates/kinbase/src/http.rs b/crates/kinbase/src/http.rs index 25e4e49..a6c7e63 100644 --- a/crates/kinbase/src/http.rs +++ b/crates/kinbase/src/http.rs @@ -615,19 +615,10 @@ pub fn request( let mut reader = BufReader::new(stream); let mut status_line = String::new(); reader.read_line(&mut status_line).map_err(|error| { - ContractError::unreachable(format!( - "Company endpoint did not answer within the read budget ({})", - error.kind() - )) - .with_detail(serde_json::json!({ - // A read timeout surfaces as WouldBlock on macOS and TimedOut on - // Linux; a reset or other read error is not a spent budget. - "timeout_observed": matches!( - error.kind(), - std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut - ), - "omitted_count": 1 - })) + read_failure( + "Company endpoint did not answer within the read budget", + error.kind(), + ) })?; if status_line.is_empty() { return Err(ContractError::unreachable( @@ -645,12 +636,9 @@ pub fn request( let mut chunked = false; loop { let mut line = String::new(); - let read = reader.read_line(&mut line).map_err(|error| { - ContractError::unreachable(format!( - "Company endpoint headers unreadable ({})", - error.kind() - )) - })?; + let read = reader + .read_line(&mut line) + .map_err(|error| read_failure("Company endpoint headers unreadable", error.kind()))?; if read == 0 || line.trim().is_empty() { break; } @@ -681,8 +669,10 @@ pub fn request( if chunked || content_length.is_none() { raw.clear(); let read = reader.by_ref().take(limit as u64 + 1).read_to_end(&mut raw); - if read.is_err() && (!chunked || raw.is_empty()) { - return Err(ContractError::unreachable("Company response truncated")); + if let Err(error) = &read + && (!chunked || raw.is_empty()) + { + return Err(read_failure("Company response truncated", error.kind())); } if raw.len() > limit { return Err(ContractError::limit( @@ -691,13 +681,15 @@ pub fn request( )); } if chunked { - raw = crate::classifier::decode_chunked(&raw) - .map_err(|_| ContractError::unreachable("Company response truncated"))?; + raw = crate::classifier::decode_chunked(&raw).map_err(|_| match &read { + Err(error) => read_failure("Company response truncated", error.kind()), + Ok(_) => ContractError::unreachable("Company response truncated"), + })?; } } else if !raw.is_empty() { - reader.read_exact(&mut raw).map_err(|error| { - ContractError::unreachable(format!("Company response truncated ({})", error.kind())) - })?; + reader + .read_exact(&mut raw) + .map_err(|error| read_failure("Company response truncated", error.kind()))?; } let body = if raw.is_empty() { Value::Null @@ -708,6 +700,76 @@ pub fn request( Ok(Response { status, body, raw }) } +/// A failed read of a Company answer. Every phase (status line, headers, +/// body) waits on the same read budget, so each says whether the budget ran +/// out: a timeout surfaces as WouldBlock on macOS and TimedOut on Linux, while +/// a reset or other read error is not a spent budget. +fn read_failure(message: &str, kind: std::io::ErrorKind) -> ContractError { + ContractError::unreachable(format!("{message} ({kind})")).with_detail(serde_json::json!({ + "timeout_observed": matches!( + kind, + std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut + ), + "omitted_count": 1 + })) +} + +#[cfg(test)] +mod read_budget_tests { + use super::*; + use std::net::TcpListener; + + /// Answer one request with `sent`, then hold the connection open, silent. + fn stalled_after(sent: &'static [u8]) -> ContractError { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); + let port = listener.local_addr().expect("address").port(); + let server = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().expect("accept"); + let mut head = [0u8; 4096]; + let _ = stream.read(&mut head); + let _ = stream.write_all(sent); + std::thread::sleep(Duration::from_millis(600)); + }); + let outcome = request( + Scheme::Http, + "127.0.0.1", + port, + "GET", + "/", + &[], + &[], + Duration::from_millis(200), + ); + let _ = server.join(); + match outcome { + Ok(response) => panic!("a stalled answer must fail, got status {}", response.status), + Err(error) => error, + } + } + + #[test] + fn a_stall_after_the_status_line_is_a_spent_read_budget() { + let sends: [&'static [u8]; 3] = [ + b"HTTP/1.1 200 OK\r\n", + b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n{}", + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n2\r\n{}\r\n", + ]; + for sent in sends { + let error = stalled_after(sent); + assert_eq!(error.code, "COMPANY_UNREACHABLE"); + assert_eq!( + error + .detail + .as_ref() + .and_then(|detail| detail.get("timeout_observed")), + Some(&serde_json::Value::Bool(true)), + "{}", + String::from_utf8_lossy(sent) + ); + } + } +} + #[cfg(test)] mod error_body_tests { use super::*; From 398a37f6af901e78d2c7073587aaf91d331fc406 Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 15:09:08 -0800 Subject: [PATCH 22/23] Skip a conflict that already has a question so the next one is asked A projection raises at most one question, and the stage visited non-blocking Unknowns in the same order every time. Once the first open conflict had a question, ensure_question returned that existing id on every later projection and the loop took its one-question break there, so a second contested key was never asked; an unrelated high-loss Unknown with a question starved conflicts behind it the same way. A non-blocking Unknown that already has a question is now skipped before the break, so each projection asks the next one not yet asked and every open conflict gets exactly one question. That skip also replaces asking under the first question's decision as the guard against one question per --decision. Blocking Unknowns are unchanged: they are asked per decision, since the decision is what they block. A unit test drives two open conflicts through two projections and checks both are asked once. Spec: amendment-003-ruling-contract.md requirement 2 (unknown) --- crates/kinbase/src/projector.rs | 87 ++++++++++++++++++++++++++++----- 1 file changed, 76 insertions(+), 11 deletions(-) diff --git a/crates/kinbase/src/projector.rs b/crates/kinbase/src/projector.rs index 133079a..5ce566c 100644 --- a/crates/kinbase/src/projector.rs +++ b/crates/kinbase/src/projector.rs @@ -52,6 +52,30 @@ const TIERS: [(&str, i64, i64); 7] = [ ("broad_search", 250, 250), ]; +/// The Unknowns a projection may raise its one question about, in order. +/// +/// Blocking Unknowns come first and keep their question per decision: the +/// decision is what they block. An Unknown that blocks nothing here is asked +/// once, ever: one that already has a question is skipped. Otherwise the +/// first such Unknown returned its existing question on every projection and +/// took the one-question break, so a second contested key was never asked; +/// and asking it under each caller's decision (the id hashes the decision) +/// opened one question per decision for a single conflict. +fn questions_to_raise<'a>( + blocking: Vec<&'a UnknownOut>, + elsewhere: Vec<&'a UnknownOut>, + already_asked: impl Fn(&str) -> bool, +) -> Vec<&'a UnknownOut> { + blocking + .into_iter() + .chain( + elsewhere + .into_iter() + .filter(|unknown| !already_asked(&unknown.unknown_id)), + ) + .collect() +} + #[derive(Debug, Clone)] pub(crate) struct UnknownOut { pub(crate) unknown_id: String, @@ -704,17 +728,10 @@ pub fn project_with( .iter() .filter(|unknown| unknown.loss_if_absent >= 7_000 || unknown.kind == "conflict") .partition(|unknown| blocks(unknown)); - let blocking_count = blocking.len(); - for (index, unknown) in blocking.into_iter().chain(elsewhere).enumerate() { - // A conflict asked from an unrelated decision keeps the question it - // already has: the id hashes the decision, so asking under each - // caller's decision would open one question per decision. - let asked_under = if index >= blocking_count { - crate::questions::decision_asked_for(repo, &unknown.unknown_id) - } else { - None - }; - let decision = asked_under.as_deref().unwrap_or(decision); + let to_ask = questions_to_raise(blocking, elsewhere, |unknown_id| { + crate::questions::decision_asked_for(repo, unknown_id).is_some() + }); + for unknown in to_ask { if let Some(id) = crate::questions::ensure_question(repo, unknown, decision, &evidence, &remaining)? { @@ -2904,6 +2921,54 @@ mod set_fold_differential_tests { } } +#[cfg(test)] +mod question_order_tests { + use super::{UnknownOut, questions_to_raise}; + use std::cell::RefCell; + use std::collections::BTreeSet; + + fn conflict(id: &str) -> UnknownOut { + UnknownOut { + unknown_id: id.to_owned(), + logical_key: id.to_owned(), + scope: String::new(), + decision_blocked: String::new(), + owner_role: String::new(), + owner_identity: String::new(), + question: String::new(), + evidence: Vec::new(), + loss_if_absent: 9_000, + status: "open".to_owned(), + kind: "conflict".to_owned(), + } + } + + #[test] + fn every_open_conflict_gets_one_question_across_projections() { + let (first, second) = (conflict("unknown_a"), conflict("unknown_b")); + let asked = RefCell::new(BTreeSet::new()); + // Each projection raises at most one question: the first it may ask. + let project = || { + let order = questions_to_raise(Vec::new(), vec![&first, &second], |id| { + asked.borrow().contains(id) + }); + if let Some(unknown) = order.first() { + asked.borrow_mut().insert(unknown.unknown_id.clone()); + } + }; + project(); + project(); + assert_eq!( + *asked.borrow(), + BTreeSet::from(["unknown_a".to_owned(), "unknown_b".to_owned()]) + ); + let remaining = questions_to_raise(Vec::new(), vec![&first, &second], |id| { + asked.borrow().contains(id) + }); + assert!(remaining.is_empty(), "a conflict was asked twice"); + } +} + #[cfg(test)] mod stem_tests { use super::stem; From 6f0e0b0d2bef7b5e667e1ee49ad55e41e33c7710 Mon Sep 17 00:00:00 2001 From: Shane Barakat Date: Mon, 16 Nov 2026 15:18:18 -0800 Subject: [PATCH 23/23] Walk past a blocker already asked under this decision When a projection had several blocking Unknowns, the first kept its existing question and took the one-question break every time, so a second blocker was never asked and could never be resolved. A blocker already asked under this decision still supplies the reported question, but the walk continues until one new question is raised. --- crates/kinbase/src/projector.rs | 10 ++++++++-- crates/kinbase/src/questions.rs | 8 ++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/kinbase/src/projector.rs b/crates/kinbase/src/projector.rs index 5ce566c..c450472 100644 --- a/crates/kinbase/src/projector.rs +++ b/crates/kinbase/src/projector.rs @@ -731,12 +731,18 @@ pub fn project_with( let to_ask = questions_to_raise(blocking, elsewhere, |unknown_id| { crate::questions::decision_asked_for(repo, unknown_id).is_some() }); + // One new question per projection. A blocker already asked under this + // decision still answers for it (its question is the one reported), but + // the walk goes on, or a second blocker behind it is never asked. for unknown in to_ask { + let asked_before = crate::questions::asked_under(repo, &unknown.unknown_id, decision); if let Some(id) = crate::questions::ensure_question(repo, unknown, decision, &evidence, &remaining)? { - raised = Some(id); - break; + raised.get_or_insert(id); + if !asked_before { + break; + } } } raised diff --git a/crates/kinbase/src/questions.rs b/crates/kinbase/src/questions.rs index 7bc12d9..4fcb296 100644 --- a/crates/kinbase/src/questions.rs +++ b/crates/kinbase/src/questions.rs @@ -1215,6 +1215,14 @@ pub(crate) fn close_shrugged( } /// The decision an Unknown was first asked under, if any question asks about it. +/// Whether `unknown_id` already has a question under exactly `decision`. +pub(crate) fn asked_under(repo: &Path, unknown_id: &str, decision: &str) -> bool { + company_records_with_repo(repo, "questions.jsonl").iter().any(|record| { + record.get("unknown_id").and_then(Value::as_str) == Some(unknown_id) + && record.get("decision").and_then(Value::as_str) == Some(decision) + }) +} + pub(crate) fn decision_asked_for(repo: &Path, unknown_id: &str) -> Option { company_records_with_repo(repo, "questions.jsonl") .into_iter()