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 5ae9a9e..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,6 +13,40 @@ 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) +- 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 + +- `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 + 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 + each receipt once. ## 0.1.2 - 2026-10-30 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 { diff --git a/crates/kinbase/src/codebase.rs b/crates/kinbase/src/codebase.rs index c70ba2d..a912b3d 100644 --- a/crates/kinbase/src/codebase.rs +++ b/crates/kinbase/src/codebase.rs @@ -316,18 +316,20 @@ 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) - .ok() - .is_some_and(|text| RepoConfig::parse(&text).is_ok()) - { + // 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/`. + 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::str::from_utf8(&bytes).is_ok_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 { 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 { 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/http.rs b/crates/kinbase/src/http.rs index e3af4d6..a6c7e63 100644 --- a/crates/kinbase/src/http.rs +++ b/crates/kinbase/src/http.rs @@ -615,14 +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!({ - "timeout_observed": true, - "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( @@ -640,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; } @@ -676,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( @@ -686,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 @@ -703,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::*; 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 c4c9465..675ade4 100644 --- a/crates/kinbase/src/lifecycle.rs +++ b/crates/kinbase/src/lifecycle.rs @@ -1942,26 +1942,23 @@ 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)); - 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 @@ -2067,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(); @@ -2297,6 +2294,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); @@ -2332,7 +2335,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 +2368,17 @@ fn scan_github_export(source: &Path, repo: &Repository) -> Result = BTreeMap::new(); let mut newest_ids: BTreeSet = BTreeSet::new(); @@ -2513,12 +2521,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 // -------------------------------------------------------------------------- @@ -4463,6 +4465,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), + "ai_generated" + ); + assert_eq!( + commit_provenance("Ada", "ada@example.invalid", ""), + "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() } 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"))?; } diff --git a/crates/kinbase/src/projector.rs b/crates/kinbase/src/projector.rs index 6133b11..c450472 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, @@ -335,6 +359,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,12 +371,43 @@ 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); 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. + // 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 // remains in append-only history, but no later projection may treat it as // still blocking after the signed answer. @@ -616,7 +672,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 @@ -664,12 +728,21 @@ 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 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 @@ -689,7 +762,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, @@ -2853,6 +2927,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; diff --git a/crates/kinbase/src/questions.rs b/crates/kinbase/src/questions.rs index b799a5b..4fcb296 100644 --- a/crates/kinbase/src/questions.rs +++ b/crates/kinbase/src/questions.rs @@ -85,10 +85,9 @@ fn find_question(question_id: &str) -> Result { }) } -fn find_unknown(question_id: &str) -> Result { - let repo = repo()?; +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() @@ -1091,12 +1090,22 @@ 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") .and_then(Value::as_str) .unwrap_or_default(); - let prior = find_unknown(unknown_id)?; + let prior = find_unknown_in(repo, unknown_id)?; let field = |key: &str, fallback: &str| { prior .get(key) @@ -1148,10 +1157,7 @@ fn close_unknown(repo: &Path, question: &Value, answer_id: &str) -> Result Result, +) -> Result<(), ContractError> { + for question in latest_questions(repo).into_values() { + 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!( + 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(()) +} + +/// 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() + .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)?; @@ -1238,3 +1304,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éééééééé"); + } +} diff --git a/crates/kinbase/src/session.rs b/crates/kinbase/src/session.rs index da35084..d62b3ce 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(); @@ -588,6 +597,7 @@ pub fn observe( "event_id": event_id, "event_type": "observation", "observed_at": observed_at, + "role": record["role"], "text_digest": digest }), )); @@ -777,6 +787,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(); @@ -785,7 +796,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)?); } @@ -821,6 +840,58 @@ 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. +/// 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 { + 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), 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; + }; + 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()) + && 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))) + .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. @@ -2028,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)?; @@ -2978,20 +3056,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 (mut canonical, mut event) = match bound()? { + Some(bound) => bound, None => { let event = build_destination_event(Some(launcher), store, repository_uuid, record)?; (crate::json::record_text(&event)?, event) @@ -2999,6 +3081,17 @@ 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. 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( "nonce_reservation", json!({ diff --git a/crates/kinbase/tests/hook_host_protocol.rs b/crates/kinbase/tests/hook_host_protocol.rs index 8db5c91..39c6892 100644 --- a/crates/kinbase/tests/hook_host_protocol.rs +++ b/crates/kinbase/tests/hook_host_protocol.rs @@ -360,6 +360,83 @@ 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"); + // 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{}\n", + line("host-native-1", "user"), + line("host-native-2", "assistant") + ), + ) + .expect("transcript"); + let observed = ok(&kinbase( + &world, + &[ + "session", + "observe", + "host-session-15", + "--event", + transcript.to_str().unwrap(), + "--json", + ], + &[], + b"", + )); + assert_eq!(observations(), before + 1, "{observed}"); +} + fn pending_dir(world: &World) -> PathBuf { world.personal.join("pending-observations") } 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/amendment-006-kinbase-config-filename.md b/spec/amendment-006-kinbase-config-filename.md new file mode 100644 index 0000000..fc3fc5b --- /dev/null +++ b/spec/amendment-006-kinbase-config-filename.md @@ -0,0 +1,59 @@ +# 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 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 +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. 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