Compare commits

...
64 Commits
Author SHA1 Message Date
conductor 5befd81b23 chore(release): auto-bump version to 0.100.0 — earned by # (minor: converged release (push-to-master bump))
Auto-version and Release / release (push) Successful in 2s
deploy / deploy (push) Failing after 24s
CI Pipeline / unit-tests (push) Failing after 4m48s
CI Pipeline / lint (push) Failing after 20s
CI Pipeline / go-surface (push) Successful in 3s
CI Pipeline / canary (push) Successful in 47s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 1s
CI Pipeline / type-check (push) Successful in 27s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / required-checks (push) Failing after 0s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 1s
Promotion record: (unknown)
2026-10-06 14:53:54 +01:00
Nick 3c79a0a9c0 feat(memory): memory_consolidation delegation — consolidation_memory + consolidation_neuron kernels (R2 W4)
Auto-version and Release / release (push) Successful in 4s
deploy / deploy (push) Failing after 5m42s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
CI Pipeline / lint (push) Failing after 22s
CI Pipeline / unit-tests (push) Failing after 4m53s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / canary (push) Successful in 46s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 28s
CI Pipeline / gitea-offline (push) Successful in 12s
CI Pipeline / required-checks (push) Failing after 1s
First Wave 4 port: the consolidation kernels (compression ratio, text truncation, knowledge record assembly) move to the cognition_core crate as consolidation_memory + consolidation_neuron FFI symbols. The Python module delegates through _consolidation_memory_oracle / _consolidation_neuron_oracle (which use drift_compression for the content and the kernel via cc_loader for the record). Seven contracts: oracle basic, no-entry-id, rock-no-compression, kernel parity x2, delegated returns. 7/7 with the kernel, 5/5 pinned. Also: cc_loader registers the two new symbols. The module went from 733→740 lines (oracle + probe added, consolidate_neuron body simplified).
2026-10-06 14:51:15 +01:00
conductor 79bbb5fea8 chore(release): auto-bump version to 0.99.10 — earned by #2469 (task-scoped probes and tool-name compatibility (#2468))
Auto-version and Release / release (push) Successful in 2s
CI Pipeline / unit-tests (push) Successful in 4m53s
CI Pipeline / lint (push) Successful in 34s
CI Pipeline / go-surface (push) Successful in 3s
CI Pipeline / canary (push) Successful in 52s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 1s
CI Pipeline / type-check (push) Successful in 27s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
deploy / deploy (push) Successful in 2m31s
Promotion record: http://127.0.0.1:3000/conductor/rune/pulls/2469
2026-10-06 07:28:03 +01:00
conductor 872b0c7a75 Merge pull request 'task-scoped probes and tool-name compatibility (#2468)' (#2469) from fix/operator-probe-tools-2468 into master
Auto-version and Release / release (push) Failing after 3s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / lint (push) Successful in 37s
CI Pipeline / type-check (push) Successful in 28s
CI Pipeline / gitea-offline (push) Successful in 14s
CI Pipeline / canary (push) Successful in 47s
CI Pipeline / unit-tests (push) Successful in 4m59s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 1s
deploy / deploy (push) Successful in 5m59s
2026-10-06 07:27:57 +01:00
Nick fcee8fbec7 fix(operator): probe budget exhaustion lands in the failure handler (#2468)
deploy / deploy (push) Skipped
CI Pipeline / lint (push) Successful in 35s
CI Pipeline / go-surface (push) Successful in 3s
CI Pipeline / canary (push) Successful in 47s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 27s
CI Pipeline / gitea-offline (push) Successful in 12s
CI Pipeline / lint (pull_request) Successful in 34s
CI Pipeline / go-surface (pull_request) Successful in 3s
CI Pipeline / canary (pull_request) Successful in 49s
CI Pipeline / best-practices (pull_request) Successful in 1s
CI Pipeline / documentation (pull_request) Successful in 2s
CI Pipeline / type-check (pull_request) Successful in 26s
CI Pipeline / gitea-offline (pull_request) Successful in 13s
Spec gate (headless) / spec-gate (pull_request) Successful in 4s
CI Pipeline / unit-tests (push) Successful in 4m56s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
CI Pipeline / unit-tests (pull_request) Successful in 4m53s
CI Pipeline / required-checks (pull_request) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (pull_request) Successful in 2s
Auto-label / priority-gate (pull_request) Skipped
Auto-label / auto-label (pull_request) Successful in 1s
Auto-version and Release / release (pull_request) Successful in 4s
The pyright ratchet caught my first attempt: a try-scoped from-import made ProbeBudgetExceeded possibly-unbound in the except tuple. Imports are now module-level dual (the file convention), the early-return returns False explicitly, and a _probe_failure_classes helper carries the caught-class set with degraded graceful behavior. Focused battery 87 green; pyright shows only the 3 pre-existing baseline errors.
2026-10-06 07:14:24 +01:00
Nick d767bd9a9e wip(operator): isolate probe budgets and normalize requested tool names (#2468)
Red-first checks prove shared global probe budget leaks into chat, and bash/grep compatibility names fail before dispatch. Change scopes artifacts by task digest, catches exhaustion, normalizes only to canonical approval-guarded handlers and exposes run_command for explicit shell intent. Focused 87 tests green. INCOMPLETE: scaffold fit blocked by missing checkable contracts, TUI status noise and full CI remain.
2026-10-06 07:14:24 +01:00
Nick 47e6eba735 test(delegation): pinned-mode probe paths — coverage for the fallback lines (#2461 close-out)
Auto-version and Release / release (push) Successful in 3s
CI Pipeline / go-surface (push) Successful in 4s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 28s
CI Pipeline / lint (push) Successful in 39s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / canary (push) Successful in 51s
CI Pipeline / unit-tests (push) Successful in 5m0s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
deploy / deploy (push) Successful in 6m44s
The remaining uncovered lines in safety_override/abstraction/tier_manager/witness are the RUNE_COGNITION_CORE=python pins, the _cc_probe loader-error fallbacks, and the stopword gather seams. Four contracts exercise all of them under the pinned env.
2026-10-06 07:11:54 +01:00
conductor 818f4b9e21 chore(release): auto-bump version to 0.99.9 — earned by # (patch: converged release (push-to-master bump))
Auto-version and Release / release (push) Successful in 2s
CI Pipeline / unit-tests (push) Successful in 4m54s
CI Pipeline / lint (push) Successful in 33s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / canary (push) Successful in 50s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 27s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 1s
deploy / deploy (push) Successful in 2m32s
Promotion record: (unknown)
2026-10-06 06:54:57 +01:00
conductor d1631a8333 Merge pull request 'ci: build cognition_core in unit-tests + canary jobs (#2461 close-out)' (#2477) from ci/build-cognition-core-unit into master
Auto-version and Release / release (push) Successful in 4s
CI Pipeline / go-surface (push) Successful in 3s
CI Pipeline / best-practices (push) Successful in 1s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / lint (push) Successful in 35s
CI Pipeline / type-check (push) Successful in 28s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / canary (push) Successful in 48s
CI Pipeline / unit-tests (push) Successful in 5m0s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 1s
deploy / deploy (push) Successful in 6m1s
2026-10-06 06:54:52 +01:00
Nick f5754fe2c0 fix(ci): CC_RUST_LIB belongs in the unit-tests job env, pointing at the runner-owned target dir
deploy / deploy (push) Skipped
CI Pipeline / go-surface (push) Successful in 4s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 28s
CI Pipeline / lint (push) Successful in 38s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / canary (push) Successful in 53s
CI Pipeline / go-surface (pull_request) Successful in 2s
CI Pipeline / lint (pull_request) Successful in 34s
CI Pipeline / best-practices (pull_request) Successful in 2s
CI Pipeline / documentation (pull_request) Successful in 2s
CI Pipeline / canary (pull_request) Successful in 44s
CI Pipeline / type-check (pull_request) Successful in 27s
Spec gate (headless) / spec-gate (pull_request) Successful in 5s
CI Pipeline / gitea-offline (pull_request) Successful in 13s
CI Pipeline / unit-tests (push) Successful in 4m59s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
CI Pipeline / unit-tests (pull_request) Successful in 4m56s
CI Pipeline / required-checks (pull_request) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (pull_request) Successful in 1s
Auto-version and Release / release (pull_request) Failing after 4s
The step-level export pointed at a wrong path and the job-level env lacked the variable entirely — the kernel probe returned None on CI. Now the job env carries CC_RUST_LIB like its seven sibling crates.
2026-10-06 06:48:55 +01:00
Nick 6df2580567 fix(ci): CC_RUST_LIB must follow CARGO_TARGET_DIR — the runner-owned target dir redirects the .so (#2461 close-out)
deploy / deploy (push) Skipped
CI Pipeline / go-surface (push) Successful in 5s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 28s
CI Pipeline / lint (push) Successful in 39s
CI Pipeline / gitea-offline (push) Successful in 14s
CI Pipeline / canary (push) Successful in 59s
CI Pipeline / go-surface (pull_request) Successful in 2s
CI Pipeline / lint (pull_request) Successful in 35s
CI Pipeline / best-practices (pull_request) Successful in 2s
CI Pipeline / documentation (pull_request) Successful in 2s
CI Pipeline / type-check (pull_request) Successful in 28s
CI Pipeline / canary (pull_request) Successful in 46s
Spec gate (headless) / spec-gate (pull_request) Successful in 4s
CI Pipeline / gitea-offline (pull_request) Successful in 13s
CI Pipeline / unit-tests (push) Failing after 4m56s
CI Pipeline / required-checks (push) Failing after 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
CI Pipeline / unit-tests (pull_request) Failing after 4m52s
CI Pipeline / required-checks (pull_request) Failing after 1s
CI Pipeline / CI Pipeline / notify-event-bridge (pull_request) Successful in 1s
2026-10-06 06:30:39 +01:00
Nick 3ee6f59e1b ci: build cognition_core in unit-tests + canary jobs (#2461 close-out)
deploy / deploy (push) Skipped
CI Pipeline / go-surface (push) Successful in 4s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
Auto-label / priority-gate (pull_request) Skipped
CI Pipeline / type-check (push) Successful in 29s
CI Pipeline / lint (push) Successful in 39s
Auto-label / auto-label (pull_request) Successful in 1s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / canary (push) Successful in 58s
CI Pipeline / go-surface (pull_request) Successful in 3s
CI Pipeline / lint (pull_request) Successful in 36s
CI Pipeline / best-practices (pull_request) Successful in 1s
CI Pipeline / documentation (pull_request) Successful in 2s
CI Pipeline / canary (pull_request) Successful in 46s
CI Pipeline / type-check (pull_request) Successful in 29s
Spec gate (headless) / spec-gate (pull_request) Successful in 5s
CI Pipeline / gitea-offline (pull_request) Successful in 13s
CI Pipeline / unit-tests (push) Failing after 4m55s
CI Pipeline / required-checks (push) Failing after 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
CI Pipeline / unit-tests (pull_request) Failing after 4m54s
CI Pipeline / required-checks (pull_request) Failing after 1s
CI Pipeline / CI Pipeline / notify-event-bridge (pull_request) Successful in 1s
The abstraction kernel-fallback test (and the W3.4 canaries) need libcognition_core.so; the crate was never built in the unit-tests/canary jobs, so the kernel-probe correctly returned None on CI and the fallback contract could not be exercised. Also set CC_RUST_LIB for the unit-tests job so the loader finds the built artifact.
2026-10-06 06:15:49 +01:00
Nick 3811219abc test(safety/abstraction): direct delegation batteries — the last 0%-honest gaps (#2461)
Auto-version and Release / release (push) Successful in 2s
CI Pipeline / go-surface (push) Successful in 3s
CI Pipeline / lint (push) Successful in 36s
CI Pipeline / best-practices (push) Successful in 1s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / canary (push) Successful in 49s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / type-check (push) Successful in 28s
CI Pipeline / unit-tests (push) Failing after 4m54s
CI Pipeline / required-checks (push) Failing after 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
deploy / deploy (push) Failing after 3m56s
safety_override: tier-0 normal, pattern learn+match, keyword extraction contract, min-keyword matching, refusal detection (5 contracts). abstraction: kernel fallback schema with provenance, stopword seam determinism (2 contracts, kernel test skips when pinned). Fake sqlite shaped to the real call contract (fetchall/fetchone on the right objects). 20/20 across the three delegation batteries.
2026-10-06 06:00:10 +01:00
conductor edf9d52caa chore(release): auto-bump version to 0.99.8 — earned by # (patch: converged release (push-to-master bump))
Auto-version and Release / release (push) Successful in 3s
CI Pipeline / unit-tests (push) Successful in 4m54s
CI Pipeline / lint (push) Successful in 34s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / canary (push) Successful in 59s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 28s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 3s
deploy / deploy (push) Successful in 3m27s
Promotion record: (unknown)
2026-10-06 05:51:40 +01:00
Nick 8a2525c4ac fix(cognition): regex_lite honors \b anchors and \s adjacency — the faithful subset closes its fidelity gap (#2461)
Auto-version and Release / release (push) Successful in 4s
CI Pipeline / go-surface (push) Successful in 3s
CI Pipeline / best-practices (push) Successful in 1s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 28s
CI Pipeline / lint (push) Successful in 38s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / canary (push) Successful in 51s
CI Pipeline / unit-tests (push) Successful in 5m2s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
deploy / deploy (push) Successful in 6m11s
The 34-row matrix hid a fidelity gap: the gap-matcher treated \s* as an UNBOUNDED gap and dropped \b entirely, so \bactually...\s*(...)\b matched "actually wait" (it+wait substring across an unbounded span) where Python re says False. Fix: \b anchors are preserved as sentinels and enforced as word boundaries at match edges; \s becomes an ADJACENCY constraint (next phrase within one char). Matrix 30/30 with re-truth, the false-positive probe now correct, canaries 27/27 x2 modes, in-crate probes 5/5. Also: witness delegation battery (7 contracts) + tier delegation battery (6) — direct coverage for the delegation layer.
2026-10-06 05:50:51 +01:00
Nick fb69ae83fc test(tier): direct delegation battery — the 0% honest gap closed (#2461)
Auto-version and Release / release (push) Successful in 3s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / lint (push) Successful in 36s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 1s
CI Pipeline / canary (push) Successful in 47s
CI Pipeline / gitea-offline (push) Successful in 12s
CI Pipeline / type-check (push) Successful in 28s
CI Pipeline / unit-tests (push) Successful in 4m57s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
deploy / deploy (push) Successful in 4m6s
tier_manager was only exercised via the cc_loader FFI in canaries (never importing the Python module), so its delegation layer read 0% in the diff-cover measurement. Six direct contracts: oracle matrix, kernel==oracle parity per case, promote/demote parity, rock immobility, kernel-unavailable fallback, config surface.
2026-10-06 05:31:58 +01:00
conductor d3a240edc8 chore(release): auto-bump version to 0.99.7 — earned by #2476 (ci: register the W3.4 cognition_core canaries (#2461 close))
Auto-version and Release / release (push) Successful in 2s
CI Pipeline / unit-tests (push) Successful in 4m54s
CI Pipeline / lint (push) Successful in 33s
CI Pipeline / go-surface (push) Successful in 3s
CI Pipeline / canary (push) Successful in 48s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 27s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
deploy / deploy (push) Successful in 3m38s
Promotion record: http://127.0.0.1:3000/conductor/rune/pulls/2476
2026-10-06 05:23:39 +01:00
conductor 278c5e372b Merge pull request 'ci: register the W3.4 cognition_core canaries (#2461 close)' (#2476) from ci/register-w34-canaries into master
Auto-version and Release / release (push) Successful in 2s
CI Pipeline / go-surface (push) Successful in 3s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 1s
CI Pipeline / lint (push) Successful in 36s
CI Pipeline / type-check (push) Successful in 29s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / canary (push) Successful in 48s
CI Pipeline / unit-tests (push) Successful in 5m1s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
deploy / deploy (push) Successful in 6m0s
2026-10-06 05:23:33 +01:00
conductor d08621222a Merge branch 'master' into ci/register-w34-canaries
deploy / deploy (push) Skipped
CI Pipeline / go-surface (push) Successful in 4s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 29s
CI Pipeline / lint (push) Successful in 39s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / lint (pull_request) Successful in 36s
CI Pipeline / go-surface (pull_request) Successful in 3s
CI Pipeline / canary (push) Successful in 1m30s
CI Pipeline / best-practices (pull_request) Successful in 1s
CI Pipeline / documentation (pull_request) Successful in 2s
CI Pipeline / type-check (pull_request) Successful in 28s
CI Pipeline / canary (pull_request) Successful in 49s
Spec gate (headless) / spec-gate (pull_request) Successful in 4s
CI Pipeline / gitea-offline (pull_request) Successful in 13s
CI Pipeline / unit-tests (push) Successful in 5m7s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
CI Pipeline / unit-tests (pull_request) Successful in 4m58s
CI Pipeline / required-checks (pull_request) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (pull_request) Successful in 2s
Auto-version and Release / release (pull_request) Successful in 5s
2026-10-06 05:17:32 +01:00
Nick db25db26d1 ci: register the W3.4 cognition_core canaries in the pipeline (#2461 close)
Auto-label / priority-gate (pull_request) Skipped
Auto-label / auto-label (pull_request) Successful in 1s
CI Pipeline / go-surface (pull_request) Successful in 2s
CI Pipeline / lint (pull_request) Successful in 35s
CI Pipeline / best-practices (pull_request) Successful in 2s
CI Pipeline / documentation (pull_request) Successful in 2s
CI Pipeline / canary (pull_request) Successful in 45s
CI Pipeline / type-check (pull_request) Successful in 27s
Spec gate (headless) / spec-gate (pull_request) Successful in 5s
CI Pipeline / gitea-offline (pull_request) Successful in 13s
CI Pipeline / unit-tests (pull_request) Successful in 4m57s
CI Pipeline / required-checks (pull_request) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (pull_request) Successful in 2s
deploy / deploy (push) Skipped
CI Pipeline / go-surface (push) Successful in 4s
CI Pipeline / best-practices (push) Successful in 3s
CI Pipeline / documentation (push) Successful in 3s
CI Pipeline / lint (push) Failing after 39s
CI Pipeline / gitea-offline (push) Successful in 21s
CI Pipeline / type-check (push) Successful in 45s
CI Pipeline / canary (push) Failing after 1m20s
CI Pipeline / unit-tests (push) Failing after 6m21s
CI Pipeline / required-checks (push) Failing after 9s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 8s
canary_growth_pins (26 checks incl. the 34-row witness parity matrix), canary_persona, canary_cognition_core were shipping but never ran in CI — the registration verify owed since W3.2. Now judged on every pipeline run.
2026-10-06 05:11:29 +01:00
conductor 1a321154f8 Merge pull request 'agents: land skill used explicitly duriung Delta workflows with collaborators' (#2475) from SamCDay/rune:delta-land into master
Auto-version and Release / release (push) Successful in 3s
CI Pipeline / go-surface (push) Successful in 4s
CI Pipeline / best-practices (push) Successful in 1s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / lint (push) Successful in 37s
CI Pipeline / type-check (push) Successful in 29s
CI Pipeline / gitea-offline (push) Successful in 14s
CI Pipeline / canary (push) Successful in 53s
CI Pipeline / unit-tests (push) Successful in 5m2s
CI Pipeline / required-checks (push) Successful in 0s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 1s
deploy / deploy (push) Successful in 4m38s
Reviewed-on: #2475
2026-10-06 04:36:01 +01:00
SamCDay ac9765d5d1 agents: land skill used explicitly duriung Delta workflows with collaborators
Auto-label / priority-gate (pull_request) Skipped
Auto-label / auto-label (pull_request) Failing after 0s
CI Pipeline / go-surface (pull_request) Successful in 4s
CI Pipeline / best-practices (pull_request) Successful in 1s
CI Pipeline / documentation (pull_request) Successful in 2s
CI Pipeline / type-check (pull_request) Successful in 29s
CI Pipeline / lint (pull_request) Successful in 39s
Spec gate (headless) / spec-gate (pull_request) Successful in 4s
CI Pipeline / gitea-offline (pull_request) Successful in 13s
CI Pipeline / canary (pull_request) Successful in 51s
CI Pipeline / unit-tests (pull_request) Successful in 4m59s
CI Pipeline / required-checks (pull_request) Successful in 0s
Auto-version and Release / release (pull_request) Failing after 2s
CI Pipeline / CI Pipeline / notify-event-bridge (pull_request) Successful in 3s
Signed-off-by: Sam Day <me@samcday.com>
2026-10-06 03:54:52 +01:00
conductor 0fdfe195e7 chore(release): auto-bump version to 0.99.6 — earned by #2473 (Scaffold: programme_continuation wired into close() (T5.15 slice 3) + same-secon)
Auto-version and Release / release (push) Successful in 2s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
CI Pipeline / lint (push) Successful in 34s
CI Pipeline / unit-tests (push) Successful in 4m53s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / canary (push) Successful in 44s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 1s
CI Pipeline / type-check (push) Successful in 28s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / required-checks (push) Successful in 1s
deploy / deploy (push) Successful in 4m7s
Promotion record: http://127.0.0.1:3000/conductor/rune/pulls/2473
2026-10-06 03:52:23 +01:00
conductor 71d2d63a36 Merge pull request 'Scaffold: programme_continuation wired into close() (T5.15 slice 3) + same-second id fix' (#2473) from feat/wire-programme-continuation into master
Auto-version and Release / release (push) Failing after 2s
CI Pipeline / go-surface (push) Successful in 3s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 1s
CI Pipeline / lint (push) Successful in 37s
CI Pipeline / type-check (push) Successful in 29s
CI Pipeline / canary (push) Successful in 45s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / unit-tests (push) Successful in 4m56s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
deploy / deploy (push) Successful in 9m28s
2026-10-06 03:52:17 +01:00
Nick 0873b521e3 feat(scaffold): programme_continuation wired into close() (T5.15 slice 3) + same-second contract-id collision fix
deploy / deploy (push) Skipped
CI Pipeline / go-surface (push) Successful in 4s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
Auto-label / priority-gate (pull_request) Skipped
CI Pipeline / type-check (push) Successful in 29s
CI Pipeline / lint (push) Successful in 39s
Auto-label / auto-label (pull_request) Successful in 0s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / canary (push) Successful in 53s
CI Pipeline / go-surface (pull_request) Successful in 2s
CI Pipeline / lint (pull_request) Successful in 36s
CI Pipeline / best-practices (pull_request) Successful in 1s
CI Pipeline / documentation (pull_request) Successful in 2s
CI Pipeline / canary (pull_request) Successful in 41s
CI Pipeline / type-check (pull_request) Successful in 27s
CI Pipeline / gitea-offline (pull_request) Successful in 13s
Spec gate (headless) / spec-gate (pull_request) Successful in 4s
CI Pipeline / unit-tests (push) Successful in 4m59s
CI Pipeline / required-checks (push) Successful in 0s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
CI Pipeline / unit-tests (pull_request) Successful in 4m54s
CI Pipeline / required-checks (pull_request) Successful in 0s
CI Pipeline / CI Pipeline / notify-event-bridge (pull_request) Successful in 1s
Auto-version and Release / release (pull_request) Successful in 5s
Slice 3 of the completion wave: closing a contract that is a stage of a persisted Programme marks that stage COMPLETE, persists the ledger, and rides the continuation canary on the close envelope — the next eligible stage is SURFACED, never guessed (task done ≠ programme done). No programme bound → no continuation block; ledger failure degrades without failing the closure. Three contracts. Also fixed en route: contract ids were second-granularity timestamps that collided when two needs filed in the same second (red test proves distinct ids now, uuid suffix added).
2026-10-06 03:46:24 +01:00
conductor f7e6c5cff5 chore(release): auto-bump version to 0.99.5 — earned by #2470 (TUI: chat pane LEFT + post-response dim-spam consolidation (T5.14/T5.13))
Auto-version and Release / release (push) Successful in 2s
CI Pipeline / unit-tests (push) Successful in 4m56s
CI Pipeline / lint (push) Successful in 34s
CI Pipeline / go-surface (push) Successful in 3s
CI Pipeline / canary (push) Successful in 44s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 28s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
deploy / deploy (push) Successful in 2m27s
Promotion record: http://127.0.0.1:3000/conductor/rune/pulls/2470
2026-10-06 03:27:08 +01:00
conductor fc46dbea52 Merge pull request 'TUI: chat pane LEFT + post-response dim-spam consolidation (T5.14/T5.13)' (#2470) from feat/tui-pane-swap-chat-left into master
Auto-version and Release / release (push) Failing after 3s
CI Pipeline / go-surface (push) Successful in 3s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 28s
CI Pipeline / lint (push) Successful in 37s
CI Pipeline / canary (push) Successful in 45s
CI Pipeline / gitea-offline (push) Successful in 14s
CI Pipeline / unit-tests (push) Successful in 4m56s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
deploy / deploy (push) Successful in 5m49s
2026-10-06 03:27:02 +01:00
conductor d8ede8f3f8 Merge branch 'master' into feat/tui-pane-swap-chat-left
deploy / deploy (push) Skipped
CI Pipeline / lint (push) Successful in 35s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / canary (push) Successful in 45s
CI Pipeline / best-practices (push) Successful in 1s
CI Pipeline / documentation (push) Successful in 1s
CI Pipeline / type-check (push) Successful in 27s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / lint (pull_request) Successful in 34s
CI Pipeline / go-surface (pull_request) Successful in 3s
CI Pipeline / canary (pull_request) Successful in 41s
CI Pipeline / best-practices (pull_request) Successful in 2s
CI Pipeline / documentation (pull_request) Successful in 1s
CI Pipeline / type-check (pull_request) Successful in 27s
CI Pipeline / gitea-offline (pull_request) Successful in 13s
Spec gate (headless) / spec-gate (pull_request) Successful in 5s
CI Pipeline / unit-tests (push) Successful in 4m55s
CI Pipeline / required-checks (push) Successful in 0s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 3s
CI Pipeline / unit-tests (pull_request) Successful in 4m54s
CI Pipeline / required-checks (pull_request) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (pull_request) Successful in 2s
Auto-version and Release / release (pull_request) Successful in 4s
2026-10-06 03:19:13 +01:00
conductor 804c2f62df chore(release): auto-bump version to 0.99.4 — earned by #2472 (Scaffold: construction_commands dispatch — the serving wire (T5.15 slice 2))
Auto-version and Release / release (push) Successful in 2s
CI Pipeline / unit-tests (push) Successful in 5m3s
CI Pipeline / lint (push) Successful in 34s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / canary (push) Successful in 44s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 1s
CI Pipeline / type-check (push) Successful in 27s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / required-checks (push) Successful in 0s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 1s
deploy / deploy (push) Successful in 5m9s
Promotion record: http://127.0.0.1:3000/conductor/rune/pulls/2472
2026-10-06 03:11:51 +01:00
conductor e5d10f18ae Merge pull request 'Scaffold: construction_commands dispatch — the serving wire (T5.15 slice 2)' (#2472) from feat/wire-construction-commands-dispatch into master
Auto-version and Release / release (push) Failing after 2s
CI Pipeline / lint (push) Successful in 36s
CI Pipeline / go-surface (push) Successful in 3s
CI Pipeline / best-practices (push) Successful in 1s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 28s
CI Pipeline / canary (push) Successful in 45s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / unit-tests (push) Successful in 5m0s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
deploy / deploy (push) Successful in 6m2s
2026-10-06 03:11:44 +01:00
conductor 3ed58d48a9 Merge branch 'master' into feat/tui-pane-swap-chat-left
deploy / deploy (push) Skipped
CI Pipeline / lint (push) Successful in 34s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / canary (push) Successful in 44s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 1s
CI Pipeline / type-check (push) Successful in 27s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / lint (pull_request) Successful in 33s
CI Pipeline / go-surface (pull_request) Successful in 2s
CI Pipeline / canary (pull_request) Successful in 40s
CI Pipeline / best-practices (pull_request) Successful in 1s
CI Pipeline / documentation (pull_request) Successful in 2s
CI Pipeline / type-check (pull_request) Successful in 27s
CI Pipeline / gitea-offline (pull_request) Successful in 12s
Spec gate (headless) / spec-gate (pull_request) Successful in 5s
CI Pipeline / unit-tests (push) Successful in 4m55s
CI Pipeline / unit-tests (pull_request) Successful in 5m0s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / required-checks (pull_request) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
CI Pipeline / CI Pipeline / notify-event-bridge (pull_request) Successful in 2s
2026-10-06 03:02:57 +01:00
conductor 6c997b6af4 Merge branch 'master' into feat/wire-construction-commands-dispatch
deploy / deploy (push) Skipped
CI Pipeline / lint (push) Successful in 34s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / canary (push) Successful in 44s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 1s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / type-check (push) Successful in 29s
CI Pipeline / lint (pull_request) Successful in 36s
CI Pipeline / go-surface (pull_request) Successful in 3s
CI Pipeline / canary (pull_request) Successful in 44s
CI Pipeline / best-practices (pull_request) Successful in 1s
CI Pipeline / documentation (pull_request) Successful in 2s
CI Pipeline / type-check (pull_request) Successful in 27s
CI Pipeline / gitea-offline (pull_request) Successful in 13s
Spec gate (headless) / spec-gate (pull_request) Successful in 4s
CI Pipeline / unit-tests (push) Successful in 4m57s
CI Pipeline / unit-tests (pull_request) Successful in 5m1s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / required-checks (pull_request) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
CI Pipeline / CI Pipeline / notify-event-bridge (pull_request) Successful in 2s
Auto-version and Release / release (pull_request) Successful in 4s
2026-10-06 03:02:52 +01:00
conductor 9b5befb137 chore(release): auto-bump version to 0.99.3 — earned by #2471 (Scaffold: stage_guards wired into completion transitions (T5.15 slice 1))
Auto-version and Release / release (push) Successful in 2s
CI Pipeline / unit-tests (push) Successful in 5m1s
CI Pipeline / lint (push) Successful in 35s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / canary (push) Successful in 41s
CI Pipeline / best-practices (push) Successful in 1s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 27s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / required-checks (push) Successful in 0s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
deploy / deploy (push) Successful in 10m26s
Promotion record: http://127.0.0.1:3000/conductor/rune/pulls/2471
2026-10-06 02:50:18 +01:00
conductor 6899d859da Merge branch 'master' into feat/tui-pane-swap-chat-left
deploy / deploy (push) Skipped
CI Pipeline / lint (push) Successful in 34s
CI Pipeline / go-surface (push) Successful in 3s
CI Pipeline / canary (push) Successful in 39s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 26s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / lint (pull_request) Successful in 34s
CI Pipeline / go-surface (pull_request) Successful in 2s
CI Pipeline / canary (pull_request) Successful in 45s
CI Pipeline / best-practices (pull_request) Successful in 1s
CI Pipeline / documentation (pull_request) Successful in 2s
CI Pipeline / type-check (pull_request) Successful in 26s
CI Pipeline / gitea-offline (pull_request) Successful in 12s
Spec gate (headless) / spec-gate (pull_request) Successful in 5s
CI Pipeline / unit-tests (push) Successful in 4m56s
CI Pipeline / unit-tests (pull_request) Successful in 4m54s
CI Pipeline / required-checks (push) Successful in 0s
CI Pipeline / required-checks (pull_request) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
CI Pipeline / CI Pipeline / notify-event-bridge (pull_request) Successful in 2s
2026-10-06 02:50:11 +01:00
conductor 8ef70448c3 Merge pull request 'Scaffold: stage_guards wired into completion transitions (T5.15 slice 1)' (#2471) from feat/wire-stage-guards-transition into master
Auto-version and Release / release (push) Failing after 3s
CI Pipeline / lint (push) Successful in 36s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 1s
CI Pipeline / canary (push) Successful in 44s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / type-check (push) Successful in 28s
CI Pipeline / unit-tests (push) Successful in 4m55s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
deploy / deploy (push) Successful in 10m51s
2026-10-06 02:50:08 +01:00
Nick 55f268f978 feat(scaffold): construction_commands dispatch — the serving wire (T5.15 slice 2)
deploy / deploy (push) Skipped
CI Pipeline / lint (push) Successful in 34s
CI Pipeline / go-surface (push) Successful in 3s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 28s
CI Pipeline / canary (push) Successful in 45s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / lint (pull_request) Successful in 34s
CI Pipeline / go-surface (pull_request) Successful in 2s
CI Pipeline / canary (pull_request) Successful in 45s
CI Pipeline / best-practices (pull_request) Successful in 2s
CI Pipeline / documentation (pull_request) Successful in 1s
CI Pipeline / type-check (pull_request) Successful in 26s
CI Pipeline / gitea-offline (pull_request) Successful in 12s
Spec gate (headless) / spec-gate (pull_request) Successful in 4s
CI Pipeline / unit-tests (push) Successful in 4m54s
CI Pipeline / unit-tests (pull_request) Successful in 4m54s
CI Pipeline / required-checks (push) Successful in 0s
CI Pipeline / required-checks (pull_request) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
CI Pipeline / CI Pipeline / notify-event-bridge (pull_request) Successful in 2s
The command seam validated intents but nothing EXECUTED them. dispatch() binds the canonical store, runs the validator, then executes accepted intents through the Construction Interface (resume/transition/amend_scope), refusing via the lifecycle with accepted=False+success=True (a refusal is a valid protocol outcome, not an error). Idempotent replay returns the recorded intent without re-executing. Three contracts: end-to-end phase movement, refusal shape, replay-no-double-execute; seam file 12/12. Slice 1 of 5 was stage_guards (#2467 wire wave).
2026-10-06 02:40:49 +01:00
Nick 320026a4a3 feat(scaffold): stage_guards wired into the completion-facing transitions (T5.15 slice 1)
deploy / deploy (push) Skipped
CI Pipeline / lint (push) Successful in 34s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / canary (push) Successful in 44s
CI Pipeline / best-practices (push) Successful in 1s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 26s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / lint (pull_request) Successful in 34s
CI Pipeline / go-surface (pull_request) Successful in 2s
CI Pipeline / canary (pull_request) Successful in 44s
CI Pipeline / best-practices (pull_request) Successful in 2s
CI Pipeline / documentation (pull_request) Successful in 2s
CI Pipeline / gitea-offline (pull_request) Successful in 13s
CI Pipeline / type-check (pull_request) Successful in 28s
CI Pipeline / unit-tests (push) Successful in 4m55s
CI Pipeline / unit-tests (pull_request) Successful in 4m58s
Spec gate (headless) / spec-gate (pull_request) Successful in 4s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / required-checks (pull_request) Successful in 0s
CI Pipeline / CI Pipeline / notify-event-bridge (pull_request) Successful in 3s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 3s
Auto-version and Release / release (pull_request) Successful in 3s
The five orphaned V1 components: slice 1 wires stage_guards for real. transition(verifying|closed) now runs §15F readiness StageChecks derived from guard: verification obligations (or inline guard_checks); a blocked guard = VERIFICATION_FAILED envelope and the phase does NOT move — builder cannot self-certify past a failing check. building/free edges unchanged; capabilities() schema documents the new arg; CLI transport carries guard_checks as JSON arg 4. Four contracts red-first (blocked/pass/inline-override/free-edge); 56 interface+guards tests green.
2026-10-06 02:40:49 +01:00
Nick 0e88b6bc08 feat(tui): consolidate post-response dim spam into one collapsed line (#2468/T5.13)
deploy / deploy (push) Skipped
CI Pipeline / go-surface (push) Successful in 4s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 1s
CI Pipeline / type-check (push) Successful in 29s
CI Pipeline / lint (push) Successful in 38s
CI Pipeline / canary (push) Successful in 49s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / go-surface (pull_request) Successful in 2s
CI Pipeline / lint (pull_request) Successful in 35s
CI Pipeline / best-practices (pull_request) Successful in 2s
CI Pipeline / documentation (pull_request) Successful in 2s
CI Pipeline / canary (pull_request) Successful in 42s
CI Pipeline / type-check (pull_request) Successful in 27s
CI Pipeline / gitea-offline (pull_request) Successful in 13s
Spec gate (headless) / spec-gate (pull_request) Successful in 4s
CI Pipeline / unit-tests (push) Successful in 4m57s
CI Pipeline / unit-tests (pull_request) Successful in 4m54s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / required-checks (pull_request) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 3s
CI Pipeline / CI Pipeline / notify-event-bridge (pull_request) Successful in 2s
Five separate dim system messages after every task/build response (budget, claims, growth, self-improve, plus the cron/queue echoes) spammed chat. New collect_post_response_signals() is a PURE headless collector with degrade-not-crash try blocks; the worker renders ONE line or silence. 6 frozen contracts: compose order [chat,task], resize semantics re-keyed, collector all-signals/silence/never-raises/cycle-multiple. 38 TUI/layout tests green; pyright error count unchanged at baseline 8.
2026-10-06 02:40:25 +01:00
Nick 004e5b3118 feat(tui): swap panes — chat LEFT, task RIGHT (#2465/T5.14)
Nick: chat-first feels natural. Compose yield order reversed (rune_tui.py compose), resize_left/resize_right actions re-keyed to the new visual positions (left=chat shrink now grows task), focus actions and all name-keyed query_one calls untouched (position-independent by design). Static source proof: yield order [chat, task]; 45 layout/TUI tests green.
2026-10-06 02:40:25 +01:00
conductor db15ae3650 chore(release): auto-bump version to 0.99.2 — earned by # (patch: converged release (push-to-master bump))
Auto-version and Release / release (push) Successful in 2s
CI Pipeline / unit-tests (push) Successful in 4m53s
CI Pipeline / lint (push) Successful in 35s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / canary (push) Successful in 44s
CI Pipeline / best-practices (push) Successful in 1s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 27s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 1s
deploy / deploy (push) Successful in 2m31s
Promotion record: (unknown)
2026-10-06 02:28:19 +01:00
Nick d8ce21b76d fix(spine): the measured dichotomy decides — hints demoted to labeled fallbacks (#2461, Nick correction)
Auto-version and Release / release (push) Successful in 4s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / lint (push) Successful in 38s
CI Pipeline / canary (push) Successful in 41s
CI Pipeline / gitea-offline (push) Successful in 14s
CI Pipeline / type-check (push) Successful in 30s
CI Pipeline / unit-tests (push) Successful in 4m57s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
deploy / deploy (push) Successful in 5m54s
Nick caught the deviation: module verdicts were substring-guessed from names (memory→rust, gitea→go) with a silent rust default. Authority order now: the measured classification map (import-evidence) decides FIRST for every module; hint hits are labeled "(name hint)" so provenance is visible; unmeasured+unhinted modules are "unclassified" (12), never a guessed rust. Store rebuilt: 106 rust / 45 go measured, 33+7 hint-labeled, 23 test-infra, 12 honest unclassified. Battery 95 green (test updated to pin the authority contract).
2026-10-06 02:28:16 +01:00
Nick d4d43dbf67 merge: spine_language tests (the new-module henxel repair)
Auto-version and Release / release (push) Successful in 2s
CI Pipeline / go-surface (push) Successful in 4s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 28s
CI Pipeline / lint (push) Successful in 38s
CI Pipeline / canary (push) Successful in 46s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / unit-tests (push) Canceled after 4m41s
deploy / deploy (push) Failing after 15m4s
CI Pipeline / required-checks (push) Failing after 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
2026-10-06 02:07:44 +01:00
Nick 8a6c950140 test(spine_language): the carved transforms ship WITH tests (#2461 new-module henxel)
CI red at d67fc46: spine_language.py crossed the new-module henxel with zero coverage. Eight contracts: measured-map read + graceful degrade, kind-default verdicts, TUI/hints, subsystem member-majority, unqualified-discovery honesty (candidate stays DECLARED), legacy-ID normalization with edge re-pointing, and the closed-contract-only gather law. 8/8 green. Also: construction_commands dispatch WIP stashed on its own branch (slice 2, next).
2026-10-06 02:04:19 +01:00
Nick d67fc46581 chore(rebase): refresh store/rebase inventory + classification for the 6 post-W0 modules (#2461 close-out)
Auto-version and Release / release (push) Successful in 2s
CI Pipeline / lint (push) Failing after 36s
CI Pipeline / go-surface (push) Successful in 3s
CI Pipeline / best-practices (push) Successful in 1s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / canary (push) Successful in 46s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / type-check (push) Successful in 27s
CI Pipeline / unit-tests (push) Successful in 4m57s
CI Pipeline / required-checks (push) Failing after 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
deploy / deploy (push) Failing after 3m27s
The W0 map had drifted (174 vs 180 files): cc_loader/sc_loader/mr_loader/mems_loader (FFI kernel membranes → RUST), spine_language (deterministic carve → RUST), __init__ (metadata reads) now carry evidence-backed side records and measured function/line counts. spine_language._classification_sides() — the runtime reader — sees 180 entries; spine battery green.
2026-10-06 01:40:56 +01:00
conductor 84b8d6b215 chore(release): auto-bump version to 0.99.1 — earned by # (patch: converged release (push-to-master bump))
Auto-version and Release / release (push) Successful in 2s
deploy / deploy (push) Failing after 11s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
CI Pipeline / lint (push) Failing after 36s
CI Pipeline / unit-tests (push) Successful in 4m57s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / canary (push) Successful in 40s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 29s
CI Pipeline / gitea-offline (push) Successful in 14s
CI Pipeline / required-checks (push) Failing after 1s
Promotion record: (unknown)
2026-10-06 01:22:12 +01:00
Nick 7f5d57236a fix(ci): 0.99.0 CI repair — silent-handler annotations + spine_language umbrella mapping (#2461)
Auto-version and Release / release (push) Successful in 4s
CI Pipeline / go-surface (push) Successful in 4s
CI Pipeline / best-practices (push) Successful in 3s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 30s
CI Pipeline / lint (push) Failing after 40s
CI Pipeline / canary (push) Successful in 47s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / unit-tests (push) Successful in 5m0s
CI Pipeline / required-checks (push) Failing after 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
deploy / deploy (push) Failing after 38s
The 0.99.0 bump ran CI against the delegation code before the annotations landed: BLE001 345->349, S110 75->81 (my new kernel-failure fallbacks), plus spine_language unmapped in the umbrella manifest (test_umbrella_impact) and the resulting spine-rebuild membership diff (rebuild-neutrality). All four new fallbacks carry intentional-silence noqa annotations per the ratchet rule (count now exactly 345/75 — baseline UNCHANGED, ledger honest); spine_language mapped into perception next to spine; store rebuilt so the membership edge and language stamps are in the committed store. 127 tests green incl. the four CI-red surfaces.
2026-10-06 01:22:05 +01:00
conductor bda07c68ee chore(release): auto-bump version to 0.99.0 — earned by # (minor: converged release (push-to-master bump))
Auto-version and Release / release (push) Successful in 3s
deploy / deploy (push) Failing after 3m25s
CI Pipeline / unit-tests (push) Failing after 4m55s
CI Pipeline / lint (push) Failing after 24s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / canary (push) Successful in 42s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 1s
CI Pipeline / type-check (push) Successful in 30s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / required-checks (push) Failing after 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
Promotion record: (unknown)
2026-10-06 00:11:25 +01:00
Nick c5be22be09 feat(cognition): witness/safety/abstraction kernel delegation + regex_lite faithful-subset rewrite (#2461 W3.4, #2465 adjacency)
CI Pipeline / lint (push) Canceled after 0s
CI Pipeline / unit-tests (push) Canceled after 0s
CI Pipeline / go-surface (push) Canceled after 0s
CI Pipeline / canary (push) Canceled after 0s
CI Pipeline / best-practices (push) Canceled after 0s
CI Pipeline / documentation (push) Canceled after 0s
CI Pipeline / type-check (push) Canceled after 0s
CI Pipeline / gitea-offline (push) Canceled after 0s
CI Pipeline / required-checks (push) Canceled after 0s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Canceled after 0s
Auto-version and Release / release (push) Successful in 4s
deploy / deploy (push) Failing after 5m4s
The W3.4 kernels existed but the Python publics still ran Python. Now: witness extract_topic/detect_signals delegate through the _stopwords()/_tables() gather seams (PATTERN-TABLE GATHER-SEAM LAW) with _py_ oracles; abstraction extract_facts gains the deterministic kernel FALLBACK when the LLM returns nothing; tier_manager was already wired; the RUNE_COGNITION_CORE=python pin is now honored by a SHARED cc_loader.core() probe (the four module-local probes silently ignored it). The canary matrix caught a REAL kernel bug: regex_lite dropped \b anchors as literal b chars so every word-boundary row silently missed (bwrongb never appears in text); rewritten as alternatives-expansion + segment-variant DFS gap-walk; 34-row matrix judged against REAL Python re shows 0 mismatches. canary_growth_pins 27/27 x5 both engine modes; canary_unbounded 14/14; per-row fixtures carry re-truth, not hand labels (a lying fixture is worse than uncovered).
2026-10-06 00:05:54 +01:00
conductor 4d6fec3d17 chore(release): auto-bump version to 0.98.0 — earned by # (minor: converged release (push-to-master bump))
CI Pipeline / lint (push) Canceled after 0s
CI Pipeline / unit-tests (push) Canceled after 0s
CI Pipeline / go-surface (push) Canceled after 0s
CI Pipeline / canary (push) Canceled after 0s
CI Pipeline / best-practices (push) Canceled after 0s
CI Pipeline / documentation (push) Canceled after 0s
CI Pipeline / type-check (push) Canceled after 0s
CI Pipeline / gitea-offline (push) Canceled after 0s
CI Pipeline / required-checks (push) Canceled after 0s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Canceled after 0s
Auto-version and Release / release (push) Canceled after 0s
deploy / deploy (push) Failing after 5m5s
Promotion record: (unknown)
2026-10-06 00:01:45 +01:00
conductor 15dbbc562a chore(release): auto-bump version to 0.98.0 — earned by # (minor: converged release (push-to-master bump))
CI Pipeline / lint (push) Canceled after 0s
CI Pipeline / unit-tests (push) Canceled after 0s
CI Pipeline / go-surface (push) Canceled after 0s
CI Pipeline / canary (push) Canceled after 0s
CI Pipeline / best-practices (push) Canceled after 0s
CI Pipeline / documentation (push) Canceled after 0s
CI Pipeline / type-check (push) Canceled after 0s
CI Pipeline / gitea-offline (push) Canceled after 0s
CI Pipeline / required-checks (push) Canceled after 0s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Canceled after 0s
Auto-version and Release / release (push) Successful in 2s
deploy / deploy (push) Canceled after 21s
Promotion record: (unknown)
2026-10-05 23:56:19 +01:00
Nick 6eb5e06119 refactor(spine): carve the #2465 doc-level transforms into spine_language.py (#2461 keep-green)
Auto-version and Release / release (push) Successful in 3s
CI Pipeline / lint (push) Failing after 22s
CI Pipeline / go-surface (push) Successful in 3s
CI Pipeline / canary (push) Successful in 47s
CI Pipeline / best-practices (push) Successful in 1s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 29s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / unit-tests (push) Failing after 4m53s
deploy / deploy (push) Canceled after 4m40s
CI Pipeline / required-checks (push) Failing after 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 1s
spine.py crossed the 1200-line giant-file debt cap (1203) with the language-verdict addition — CI lint red. The three transforms (language placement, discovery-ID normalization, contract-discovery write-back + gatherer) move to spine_language.py intact, re-exported through spine for import-compat (structure unchanged: 256 entities, same verdicts; spine battery 87, canaries 19/19 + 21/21, henxels hold, spine.py back to 1034).
2026-10-05 23:53:33 +01:00
Nick 78e4750a77 feat(tier): tier_manager delegates get/promote/demote to the cognition_core kernels (#2461 W3.4 delegation owed)
Auto-version and Release / release (push) Successful in 4s
CI Pipeline / lint (push) Failing after 25s
CI Pipeline / go-surface (push) Successful in 3s
CI Pipeline / canary (push) Successful in 48s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 29s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / unit-tests (push) Failing after 4m56s
CI Pipeline / required-checks (push) Failing after 1s
deploy / deploy (push) Failing after 15m3s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
The kernels and FFI landed in b0a682b but the Python publics still ran Python — the strangler breach this slice owed. Live probe caught the FFI-arg-shape defect: promote/demote take the FULL ENTRY (kernel recomputes current tier internally), not a tier string; passing a string silently returned threshold-default verdicts (promote cold went warm-to-hot WRONGLY via defaults, demote rock went cold ignoring rock protection). 12-case kernel==oracle sweep green: wash>=20, recency hot/warm/cold, naive-timestamp parity trap, rock protection. PY oracle bodies kept; RUNE_COGNITION_CORE=python pins fallback; canary_growth_pins 26/26 both engines; canary_unbounded 14/14.
2026-10-05 23:50:11 +01:00
conductor c3948bae98 chore(release): auto-bump version to 0.97.0 — earned by # (minor: converged release (push-to-master bump))
Auto-version and Release / release (push) Successful in 3s
deploy / deploy (push) Failing after 15m3s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 3s
CI Pipeline / lint (push) Failing after 37s
CI Pipeline / unit-tests (push) Successful in 4m59s
CI Pipeline / go-surface (push) Successful in 3s
CI Pipeline / canary (push) Successful in 45s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 28s
CI Pipeline / gitea-offline (push) Successful in 14s
CI Pipeline / required-checks (push) Failing after 1s
Promotion record: (unknown)
2026-10-05 23:48:25 +01:00
Nick b8184a0f01 chore(spine): store rebuild carries subsystem language verdicts (#2465)
Auto-version and Release / release (push) Successful in 3s
CI Pipeline / lint (push) Failing after 36s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / canary (push) Successful in 47s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / type-check (push) Successful in 31s
CI Pipeline / unit-tests (push) Successful in 5m5s
deploy / deploy (push) Failing after 15m4s
CI Pipeline / required-checks (push) Failing after 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 1s
2026-10-05 23:47:58 +01:00
Nick 469b91f217 feat(spine): subsystem language verdicts from member majority (#2465 addition 3)
The five unassessed subsystems are containers: their language derives from member modules measured sides (classification.json, the W0 dichotomy map, rust and go counts carried in the verdict text). Unclassified members noted rather than guessed; unreadable classification degrades to unassessed. Spine canaries 19/19 and 21/21, spine battery 87 green.
2026-10-05 23:47:55 +01:00
Nick bb960b1656 test(gitea): canary the numeric-ID stale-label removal (#2467)
Auto-version and Release / release (push) Successful in 3s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / lint (push) Successful in 37s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / canary (push) Successful in 46s
CI Pipeline / gitea-offline (push) Successful in 14s
CI Pipeline / type-check (push) Successful in 30s
CI Pipeline / unit-tests (push) Successful in 4m57s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
deploy / deploy (push) Successful in 6m59s
Replace the obsolete removeLabel(name) pattern assertion with the actual Gitea /labels/{id} request, check ID lookup under the 404 idempotency guard, and require real P0–P3 managed labels. Local canary 39/39; workflow JS regression passes.
2026-10-05 22:22:53 +01:00
conductor 38c76a0c29 chore(release): auto-bump version to 0.96.1 — earned by # (patch: converged release (push-to-master bump))
Auto-version and Release / release (push) Successful in 2s
deploy / deploy (push) Failing after 39s
CI Pipeline / unit-tests (push) Successful in 5m2s
CI Pipeline / lint (push) Successful in 36s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / canary (push) Failing after 46s
CI Pipeline / best-practices (push) Successful in 1s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 29s
CI Pipeline / gitea-offline (push) Successful in 14s
CI Pipeline / required-checks (push) Failing after 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 1s
Promotion record: (unknown)
2026-10-05 22:15:03 +01:00
Nick 3186566514 fix(gitea): reconcile priority labels by numeric Gitea ID (#2467)
Auto-version and Release / release (push) Successful in 4s
CI Pipeline / go-surface (push) Successful in 4s
CI Pipeline / best-practices (push) Successful in 3s
CI Pipeline / documentation (push) Successful in 1s
CI Pipeline / type-check (push) Successful in 30s
CI Pipeline / lint (push) Successful in 40s
CI Pipeline / canary (push) Failing after 46s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / unit-tests (push) Successful in 5m0s
CI Pipeline / required-checks (push) Failing after 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 3s
deploy / deploy (push) Failing after 6m1s
Issue #2467 carried both P0 and P2 because name-based label DELETE returned 404 and the workflow silently ignored it. Use the numeric ID API, enforce exactly one priority, clear stale unprioritized flags, and execute the workflow JavaScript against a Gitea-compatible fake in regression tests.
2026-10-05 22:14:47 +01:00
Nick 24d14ff8e1 fix(spine): preserve candidate discoveries without inventing module IDs (#2465)
Migrate 22 malformed contract-discovery IDs to construction-surface, retain evidence/edges, keep candidates DECLARED, unify cold/warm language projection, and refresh the pinned aiohttp lock. Red regression tests precede the fix; local full suite 2301 passed, spine canaries 19/19 and 21/21.
2026-10-05 22:14:46 +01:00
conductor 6d0d455033 chore(release): auto-bump version to 0.96.0 — earned by # (minor: converged release (push-to-master bump))
Auto-version and Release / release (push) Successful in 2s
deploy / deploy (push) Failing after 29s
CI Pipeline / unit-tests (push) Failing after 4m54s
CI Pipeline / lint (push) Failing after 20s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / canary (push) Failing after 47s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 30s
CI Pipeline / gitea-offline (push) Successful in 14s
CI Pipeline / required-checks (push) Failing after 0s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
Promotion record: (unknown)
2026-10-05 19:34:11 +01:00
Nick b0a682b61f feat(cognition): R2 W3.4 — tier/witness/safety/abstraction kernels + protocol upgrade (#2461, #2465)
Auto-version and Release / release (push) Successful in 4s
CI Pipeline / go-surface (push) Successful in 4s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / lint (push) Failing after 25s
CI Pipeline / type-check (push) Successful in 28s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / canary (push) Failing after 41s
CI Pipeline / unit-tests (push) Failing after 4m50s
CI Pipeline / required-checks (push) Failing after 0s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 1s
deploy / deploy (push) Failing after 5m42s
Contract BUILDER-2026-10-05T12:03:34Z-cli — FIRST SLICE under the 90/100
verification law (64172d8).

Kernels (cognition_core/broker.rs):
- tier_get/promote/demote: thresholds+now injected (no-clock); wash>=20
  gate; rock immobility on demote; naive/malformed → designed fallback
- witness: extract_topic (word-run + stopwords-as-data), detect_signals
  (error/correction/completion/topic-drift/commitment/contradiction/
  preference/urgency/learning; pattern tables travel as data; the regex-
  lite subset is faithful to the tables' shapes)
- safety: get_params projection, update_pattern bump/new-row semantics
- abstraction: extract_facts sentence/content-word projection
- crate-level probe tests (parse_probe.rs: aware parse, epoch, tier recency)

Protocol upgrade (issue #2465) — three additions to the machine itself:
1. PER-CONTRACT MINI-DOC: construction_projection.mini_doc() emits the
   LLM quick-lookup page (what was built / connections / how to update)
   per closed contract; close() writes it to store/scaffold/docs/<cid>.md
2. SPINE WRITE-BACK: spine.build() now consumes closed contracts'
   discovered entities (expected_new_observed + candidate corrections) —
   the spine learns what construction actually built (256 entities now)
3. LANGUAGE VERDICTS: every spine entity carries identities.language
   (198 rust / 31 go / 6 tui / 5 unassessed); other projects get the
   fit assessment at classification

Also: one lost FFI block restored (the stash dance dropped
cc_tier_*/cc_witness_*/cc_safety_*/cc_abstraction_* — the battery
caught it: undefined symbol).

Gates: canary_growth_pins 26/26 x3, persona 18/18, cognition_core
38/38, suite 2299/0, ruff clean, type ratchet PASS, henxels all-hold.
2026-10-05 19:34:05 +01:00
conductor ab18540d7e chore(release): auto-bump version to 0.95.1 — earned by # (patch: converged release (push-to-master bump))
Auto-version and Release / release (push) Successful in 2s
deploy / deploy (push) Failing after 24s
CI Pipeline / unit-tests (push) Successful in 5m22s
CI Pipeline / lint (push) Failing after 21s
CI Pipeline / go-surface (push) Successful in 3s
CI Pipeline / canary (push) Successful in 44s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 2s
CI Pipeline / type-check (push) Successful in 30s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / required-checks (push) Failing after 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
Promotion record: (unknown)
2026-10-05 19:06:06 +01:00
Nick f489467e1b fix(ci): the priority gate's demand is now programmatically satisfied
Auto-version and Release / release (push) Successful in 17s
CI Pipeline / go-surface (push) Successful in 8s
CI Pipeline / best-practices (push) Successful in 3s
CI Pipeline / documentation (push) Successful in 4s
CI Pipeline / lint (push) Failing after 28s
CI Pipeline / gitea-offline (push) Successful in 18s
CI Pipeline / type-check (push) Successful in 31s
CI Pipeline / canary (push) Successful in 47s
CI Pipeline / unit-tests (push) Successful in 4m57s
CI Pipeline / required-checks (push) Failing after 0s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
deploy / deploy (push) Failing after 6m8s
Nick's catch (2026-10-05): the auto-label bot highlighted that issues
carry priority only in their titles — the PRIORITY GATE job demanded
P0-P3 labels but nothing ever ASSIGNED them programmatically. The title
inference even used a dead label ('priority: high', normalized away
2026-09-04).

- auto-label's priority inference re-implemented in the gate's own
  namespace: title prefix \bP([0-3])\b first, then keyword inference
  (spine/critical/urgent -> P0; broken/fix/repair/defect -> P1;
  kernel/port/refactor/improve -> P2; benchmark/measurement/deferred ->
  P3); managedLabels now carry the REAL P-labels
- paired with the custodian fix: create_issue assigns the P-label at
  FILING (no issue ever lands unprioritized)
- full open-issue set backfilled (2461-2466, 2455/2459) and the live
  probe (#2466, self-verifying) closed after verifying P1 landed
  at filing
2026-10-05 19:05:38 +01:00
Nick 64172d8675 docs(plan): the 90/100 verification law (Nick 2026-10-05)
Auto-version and Release / release (push) Successful in 2s
CI Pipeline / go-surface (push) Successful in 2s
CI Pipeline / lint (push) Successful in 35s
CI Pipeline / best-practices (push) Successful in 2s
CI Pipeline / documentation (push) Successful in 1s
CI Pipeline / type-check (push) Successful in 28s
CI Pipeline / canary (push) Successful in 44s
CI Pipeline / gitea-offline (push) Successful in 13s
CI Pipeline / unit-tests (push) Successful in 4m53s
CI Pipeline / required-checks (push) Successful in 1s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Successful in 2s
deploy / deploy (push) Successful in 3m47s
- 100% branch coverage on the deterministic Rust kernels (achievable,
  exhaustive via parity matrices)
- ≥90% per-slice changed-lines working bar, aiming higher per slice
- floor ratchet climbs after clean waves (70->76->84->90)
- honest fixtures only — a lying-fixture branch is worse than uncovered
- assertion quality counts: value-verifying asserts only
2026-10-05 12:58:18 +01:00
46 changed files with 12990 additions and 8459 deletions

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
---
name: land
description: Review and land one small Rune change through the governed PR workflow.
disable-model-invocation: true
metadata:
delta-action: land
---
# Land one small diff
1. Read applicable `AGENTS.md` rules and the repo's PR/merge workflow.
2. Confirm the issue, exact diff, target branch, and permission to publish and land.
3. Keep one small, reversible change; preserve unrelated work.
4. For bugs, follow `docs/bugfix-contract.md`: red test first, root cause, discharge.
5. Run required tests, static analysis, canaries, and henxels; record results.
6. Get independent `/review` per `docs/adversarial-review.md`; clear blockers.
7. Inspect remotes; publish the PR to the approved forge, never `local`.
8. Require human approval and green required CI on the exact PR head; recheck changed heads.
9. Load `report-landed`; use the repo's merge workflow. Stop on conflicts; never force-push or bypass hooks.
10. Verify the target commit and CI, then report the actual landing result and remaining blockers.
+53 -9
View File
@@ -23,12 +23,13 @@ jobs:
const labels = (issue.labels || []).map(l => l.name);
const priorities = ['P0 — critical', 'P1 — high', 'P2 — medium', 'P3 — low'];
const has = labels.filter(l => priorities.includes(l));
if (has.length >= 1) {
if (has.length === 1) {
// Prioritized — clear the flag if it was set.
if (labels.includes('unprioritized')) {
await github.rest.issues.removeLabel({
await github.request('DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{id}', {
owner: context.repo.owner, repo: context.repo.repo,
issue_number: issue.number, name: 'unprioritized',
issue_number: issue.number,
id: issue.labels.find(l => l.name === 'unprioritized').id,
}).catch(e => { if (e.status !== 404) throw e; });
}
return;
@@ -72,7 +73,8 @@ jobs:
const managedLabels = new Set([
'memory', 'governance', 'identity', 'growth',
'perception', 'infrastructure', 'life', 'custodian',
'priority: high', 'bug', 'feature', 'research',
'bug', 'feature', 'research',
'P0 — critical', 'P1 — high', 'P2 — medium', 'P3 — low',
]);
// Type label: DECLARED over GUESSED. The template spine
@@ -135,9 +137,31 @@ jobs:
desiredLabels.add('custodian');
}
// Priority labels
if (text.includes('urgent') || text.includes('critical') || text.includes('broken')) {
desiredLabels.add('priority: high');
// Priority labels (2026-10-05: PROGRAMMATIC P-ASSIGNMENT —
// the gate demanded P0-P3 labels but nothing assigned them;
// the dead 'priority: high' label is gone per the 2026-09-04
// normalization). Assignment from the TITLE prefix first
// ([P1]/P1:/priority=...), then keyword inference using the
// gate's own rule set (the scale lives in ONE place — the
// priority-gate job above).
const pMatch = title.match(/\bP([0-3])\b/);
const priorityLabelNames = ['P0 — critical', 'P1 — high', 'P2 — medium', 'P3 — low'];
if (pMatch) {
desiredLabels.add(priorityLabelNames[Number(pMatch[1])]);
} else if (text.includes('urgent') || text.includes('critical') ||
text.includes('spine') || text.includes('blocks other work')) {
desiredLabels.add(priorityLabelNames[0]); // P0 — critical
} else if (text.includes('broken') || text.includes('fix') ||
text.includes('repair') || text.includes('defect') ||
text.includes('real defect') || text.includes('money')) {
desiredLabels.add(priorityLabelNames[1]); // P1 — high
} else if (text.includes('improve') || text.includes('consolidat') ||
text.includes('refactor') || text.includes('kernel') ||
text.includes('port')) {
desiredLabels.add(priorityLabelNames[2]); // P2 — medium
} else if (text.includes('benchmark') || text.includes('measurement') ||
text.includes('deferred')) {
desiredLabels.add(priorityLabelNames[3]); // P3 — low
}
const issueNumber = context.payload.issue?.number || context.payload.pull_request?.number;
@@ -147,6 +171,7 @@ jobs:
issue_number: issueNumber,
});
const currentLabels = new Set(current.data.map(label => label.name));
const currentLabelIds = new Map(current.data.map(label => [label.name, label.id]));
const staleManaged = [...currentLabels].filter(
label => managedLabels.has(label) && !desiredLabels.has(label)
);
@@ -156,11 +181,14 @@ jobs:
for (const name of staleManaged) {
try {
await github.rest.issues.removeLabel({
// Gitea's DELETE /labels/{id} requires the numeric label ID.
// Octokit's GitHub-style removeLabel(name) returned 404 and
// left stale priority labels behind (#2467: P0 AND P2).
await github.request('DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{id}', {
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
name,
id: currentLabelIds.get(name),
});
} catch (error) {
if (error.status !== 404) {
@@ -178,5 +206,21 @@ jobs:
labels: missingDesired,
});
}
// The priority gate can flag a duplicate before this job
// reconciles it. Clear the flag only AFTER verifying exactly one
// surviving P-label against Gitea's current state.
const reconciled = await github.rest.issues.listLabelsOnIssue({
owner: context.repo.owner, repo: context.repo.repo,
issue_number: issueNumber,
});
const actual = reconciled.data;
const activePriority = actual.filter(l => priorityLabelNames.includes(l.name));
const flag = actual.find(l => l.name === 'unprioritized');
if (activePriority.length === 1 && flag) {
await github.request('DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{id}', {
owner: context.repo.owner, repo: context.repo.repo,
issue_number: issueNumber, id: flag.id,
});
}
console.log(`Removed managed labels: ${staleManaged.join(', ') || 'none'}`);
console.log(`Added managed labels: ${missingDesired.join(', ') || 'none'}`);
+6
View File
@@ -81,6 +81,7 @@ jobs:
SC_RUST_LIB: /tmp/rune-ci-target-${{ github.run_id }}/release/libscaffold_core.so
MEMS_RUST_LIB: /tmp/rune-ci-target-${{ github.run_id }}/release/libmemory_storage.so
MR_RUST_LIB: /tmp/rune-ci-target-${{ github.run_id }}/release/libmemory_retrieval.so
CC_RUST_LIB: /tmp/rune-ci-target-${{ github.run_id }}/release/libcognition_core.so
steps:
# actions/checkout v4.2.2, pinned to the audited upstream tag commit.
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
@@ -135,6 +136,7 @@ jobs:
cargo build --release --manifest-path src/rust/scaffold_core/Cargo.toml
cargo build --release --manifest-path src/rust/memory_storage/Cargo.toml
cargo build --release --manifest-path src/rust/memory_retrieval/Cargo.toml
cargo build --release --manifest-path src/rust/cognition_core/Cargo.toml
- name: Test with coverage (global floor + changed-lines ratchet)
run: |
# #149 coverage ratchet — both floors live in .coveragerc; raise,
@@ -224,6 +226,7 @@ jobs:
cargo build --release --manifest-path src/rust/scaffold_core/Cargo.toml
cargo build --release --manifest-path src/rust/memory_storage/Cargo.toml
cargo build --release --manifest-path src/rust/memory_retrieval/Cargo.toml
cargo build --release --manifest-path src/rust/cognition_core/Cargo.toml
- name: Run canary suite
run: |
FAILED=0
@@ -262,6 +265,9 @@ jobs:
src/rust/scaffold_core/canary_scaffold_core.py \
src/rust/memory_storage/canary_memory_storage.py \
src/rust/memory_retrieval/canary_memory_retrieval.py \
src/rust/cognition_core/canary_growth_pins.py \
src/rust/cognition_core/canary_persona.py \
src/rust/cognition_core/canary_cognition_core.py \
src/rune/canary_unbounded.py \
src/rune/canary_full_system.py \
src/rune/canary_native.py; do
+1 -1
View File
@@ -1,6 +1,6 @@
# Rune
**Current release: v0.95.0**
**Current release: v0.100.0**
**Rune is a persistent personal agent designed to accumulate experience, develop reusable competence, and remain recognisably the same agent even when its underlying foundation model changes.**
+316 -315
View File
@@ -1,318 +1,319 @@
{
"_comment": "GENERATED by rune.spine \u2014 compatibility view for legacy umbrella consumers. DO NOT EDIT: structural truth lives in store/spine/current.json; edits here are flagged by spine drift.",
"_generated_by_spine": true,
"generated_at": "2026-09-16T18:23:38Z",
"umbrellas": {
"capability": {
"description": "Tool selection and execution authority",
"modules": [
"adaptive_router",
"builder_bridge",
"builder_bridge_cli",
"capability_broker",
"connection_pool",
"core_server",
"cs_loader",
"evidence_probe",
"forge",
"forge_client",
"intent_continuity",
"local_tool_runtime",
"message_queue",
"native_units",
"openai_compat_transport",
"provider_context",
"recall_uplift",
"route_risk_flags",
"tool_executor",
"tool_protocol"
],
"depends_on": [
"memory"
],
"mirrors": [],
"canaries": [
"canary_native",
"canary_p0_05",
"canary_p1_01",
"canary_rune_entry",
"canary_rune_serve"
],
"go_surfaces": [
"rune-entry"
],
"configs": [],
"rust_crates": [
"capability_scoring"
]
},
"governance": {
"description": "Quality control, drift detection, promotion, audit",
"modules": [
"audit_ledger",
"build_pipeline_policy",
"cc_loader",
"claim_audit",
"contracts",
"curator",
"drift_core",
"drift_ledger",
"drift_observability",
"failure_auto_filer",
"programme_gates",
"sc_loader"
],
"depends_on": [],
"mirrors": [],
"canaries": [
"canary_full_system",
"canary_schema_migration",
"canary_audit_ledger",
"canary_spine_meta"
],
"rust_crates": [
"evidence_provenance",
"scaffold_core"
],
"configs": [
".coveragerc",
"go-version.txt",
"lint-baseline.json",
"pyright-baseline.json"
]
},
"growth": {
"description": "Learning and improvement",
"modules": [
"autonomy_loop",
"cognitive_loop",
"dream_cycle",
"elastic_cognition",
"goal",
"growth_delta",
"growth_simulator",
"self_improve",
"subconscious_pass"
],
"depends_on": [
"governance",
"memory"
],
"mirrors": [],
"canaries": [
"canary_full_system"
]
},
"identity": {
"description": "Who the agent is \u2014 persona, voice, anchors",
"modules": [
"behavior",
"identity_anchors",
"persona_definition",
"persona_gate",
"prompt_sync",
"voice_hybrid",
"voice_injector",
"voice_sync",
"voicebox"
],
"depends_on": [
"governance"
],
"mirrors": [],
"canaries": [
"canary_full_system"
]
},
"inference": {
"description": "Model routing and outbound requests",
"modules": [
"inference_trace",
"model_connect",
"model_profiles",
"model_registry",
"model_routing",
"provider_budget",
"provider_registry",
"response_adapter",
"standardized_providers",
"tc_loader",
"token_optimizer"
],
"depends_on": [
"capability"
],
"mirrors": [],
"canaries": [
"canary_p1_02",
"canary_p1_06",
"canary_resource_authority"
],
"rust_crates": [
"token_counting"
]
},
"memory": {
"description": "Storing, retrieving, and managing knowledge",
"modules": [
"abstraction",
"cache",
"drift_cache",
"drift_compression",
"ffi_query_memory_smoke",
"graph_memory",
"graph_shard_bridge",
"memory_consolidation",
"memory_env",
"memory_selector",
"memory_store",
"mems_loader",
"mr_loader",
"ms_loader",
"query_memory",
"recall_router",
"retrieval_benchmark",
"shard_manager",
"tier_manager",
"warm_neuron_store"
],
"depends_on": [
"governance"
],
"mirrors": [],
"canaries": [
"canary_full_system",
"canary_memory_synthesis",
"canary_query_memory"
],
"rust_crates": [
"memory_retrieval",
"memory_scoring",
"memory_storage",
"query_memory"
]
},
"orchestration": {
"description": "Task lifecycle, operator, TUI presentation",
"modules": [
"auto_detect",
"build_mode",
"build_orchestrator",
"chat_bubble",
"cron_engine",
"custodian",
"dependency_tracker",
"event_bus",
"event_envelope",
"gitea_auth",
"gitea_pipeline",
"gitea_provision",
"hook_engine",
"message_widgets",
"microkernel",
"night_mode",
"outcome_ledger",
"parallel_processor",
"pins",
"progressive_escalation",
"rune_graphic",
"rune_operator",
"rune_profiler",
"rune_spinner",
"rune_tui",
"safety_override",
"sleep_time",
"subsystem_health",
"system_registry",
"task_gate",
"task_persist",
"tiered_executor",
"time_awareness",
"tui_transport",
"tui_validator",
"umbrella_update",
"verification_layer",
"warm_router",
"work_manager"
],
"depends_on": [
"capability",
"growth",
"identity",
"inference",
"perception"
],
"mirrors": [],
"canaries": [
"canary_cognitive_strata",
"canary_conversation_state",
"canary_gitea_pipeline",
"canary_orchestration_foundation",
"canary_p1_07",
"canary_surface_parity",
"canary_tui_drift",
"canary_tui_transport"
]
},
"perception": {
"description": "Input processing and context assembly",
"modules": [
"attention_capsule",
"auto_context",
"auto_tasks",
"behaviour_ledger",
"build_basis",
"capability_fit",
"capability_ledger",
"cognitive_budgeter",
"construction_activation",
"construction_commands",
"construction_decision",
"construction_depth",
"construction_intent",
"construction_interface",
"construction_mode",
"construction_pattern",
"construction_patterns_builtin",
"construction_projection",
"context_broker",
"context_pressure",
"drift_resume",
"event_wait",
"failure_recovery",
"graph_projection",
"impact_preview",
"iteration",
"layout_contract",
"programme_continuation",
"project_registry",
"release_notes",
"salience_gate",
"scaffold",
"spine",
"spine_loader",
"stage_guards",
"structural_migration",
"structural_model",
"structural_store",
"testing_mode",
"toolchain",
"tui_backlog",
"wait_guard",
"wait_guard_corpus",
"witness"
],
"depends_on": [
"memory"
],
"mirrors": [],
"canaries": [
"canary_context_broker",
"canary_full_system"
],
"rust_crates": [
"rune_spine"
]
}
"_comment": "GENERATED by rune.spine \u2014 compatibility view for legacy umbrella consumers. DO NOT EDIT: structural truth lives in store/spine/current.json; edits here are flagged by spine drift.",
"_generated_by_spine": true,
"generated_at": "2026-09-16T18:23:38Z",
"umbrellas": {
"capability": {
"canaries": [
"canary_native",
"canary_p0_05",
"canary_p1_01",
"canary_rune_entry",
"canary_rune_serve"
],
"configs": [],
"depends_on": [
"memory"
],
"description": "Tool selection and execution authority",
"go_surfaces": [
"rune-entry"
],
"mirrors": [],
"modules": [
"adaptive_router",
"builder_bridge",
"builder_bridge_cli",
"capability_broker",
"connection_pool",
"core_server",
"cs_loader",
"evidence_probe",
"forge",
"forge_client",
"intent_continuity",
"local_tool_runtime",
"message_queue",
"native_units",
"openai_compat_transport",
"provider_context",
"recall_uplift",
"route_risk_flags",
"tool_executor",
"tool_protocol"
],
"rust_crates": [
"capability_scoring"
]
},
"governance": {
"canaries": [
"canary_full_system",
"canary_schema_migration",
"canary_audit_ledger",
"canary_spine_meta"
],
"configs": [
".coveragerc",
"go-version.txt",
"lint-baseline.json",
"pyright-baseline.json"
],
"depends_on": [],
"description": "Quality control, drift detection, promotion, audit",
"mirrors": [],
"modules": [
"audit_ledger",
"build_pipeline_policy",
"cc_loader",
"claim_audit",
"contracts",
"curator",
"drift_core",
"drift_ledger",
"drift_observability",
"failure_auto_filer",
"programme_gates",
"sc_loader"
],
"rust_crates": [
"evidence_provenance",
"scaffold_core"
]
},
"growth": {
"canaries": [
"canary_full_system"
],
"depends_on": [
"governance",
"memory"
],
"description": "Learning and improvement",
"mirrors": [],
"modules": [
"autonomy_loop",
"cognitive_loop",
"dream_cycle",
"elastic_cognition",
"goal",
"growth_delta",
"growth_simulator",
"self_improve",
"subconscious_pass"
]
},
"identity": {
"canaries": [
"canary_full_system"
],
"depends_on": [
"governance"
],
"description": "Who the agent is \u2014 persona, voice, anchors",
"mirrors": [],
"modules": [
"behavior",
"identity_anchors",
"persona_definition",
"persona_gate",
"prompt_sync",
"voice_hybrid",
"voice_injector",
"voice_sync",
"voicebox"
]
},
"inference": {
"canaries": [
"canary_p1_02",
"canary_p1_06",
"canary_resource_authority"
],
"depends_on": [
"capability"
],
"description": "Model routing and outbound requests",
"mirrors": [],
"modules": [
"inference_trace",
"model_connect",
"model_profiles",
"model_registry",
"model_routing",
"provider_budget",
"provider_registry",
"response_adapter",
"standardized_providers",
"tc_loader",
"token_optimizer"
],
"rust_crates": [
"token_counting"
]
},
"memory": {
"canaries": [
"canary_full_system",
"canary_memory_synthesis",
"canary_query_memory"
],
"depends_on": [
"governance"
],
"description": "Storing, retrieving, and managing knowledge",
"mirrors": [],
"modules": [
"abstraction",
"cache",
"drift_cache",
"drift_compression",
"ffi_query_memory_smoke",
"graph_memory",
"graph_shard_bridge",
"memory_consolidation",
"memory_env",
"memory_selector",
"memory_store",
"mems_loader",
"mr_loader",
"ms_loader",
"query_memory",
"recall_router",
"retrieval_benchmark",
"shard_manager",
"tier_manager",
"warm_neuron_store"
],
"rust_crates": [
"memory_retrieval",
"memory_scoring",
"memory_storage",
"query_memory"
]
},
"orchestration": {
"canaries": [
"canary_cognitive_strata",
"canary_conversation_state",
"canary_gitea_pipeline",
"canary_orchestration_foundation",
"canary_p1_07",
"canary_surface_parity",
"canary_tui_drift",
"canary_tui_transport"
],
"depends_on": [
"capability",
"growth",
"identity",
"inference",
"perception"
],
"description": "Task lifecycle, operator, TUI presentation",
"mirrors": [],
"modules": [
"auto_detect",
"build_mode",
"build_orchestrator",
"chat_bubble",
"cron_engine",
"custodian",
"dependency_tracker",
"event_bus",
"event_envelope",
"gitea_auth",
"gitea_pipeline",
"gitea_provision",
"hook_engine",
"message_widgets",
"microkernel",
"night_mode",
"outcome_ledger",
"parallel_processor",
"pins",
"progressive_escalation",
"rune_graphic",
"rune_operator",
"rune_profiler",
"rune_spinner",
"rune_tui",
"safety_override",
"sleep_time",
"subsystem_health",
"system_registry",
"task_gate",
"task_persist",
"tiered_executor",
"time_awareness",
"tui_transport",
"tui_validator",
"umbrella_update",
"verification_layer",
"warm_router",
"work_manager"
]
},
"perception": {
"canaries": [
"canary_context_broker",
"canary_full_system"
],
"depends_on": [
"memory"
],
"description": "Input processing and context assembly",
"mirrors": [],
"modules": [
"attention_capsule",
"auto_context",
"auto_tasks",
"behaviour_ledger",
"build_basis",
"capability_fit",
"capability_ledger",
"cognitive_budgeter",
"construction_activation",
"construction_commands",
"construction_decision",
"construction_depth",
"construction_intent",
"construction_interface",
"construction_mode",
"construction_pattern",
"construction_patterns_builtin",
"construction_projection",
"context_broker",
"context_pressure",
"drift_resume",
"event_wait",
"failure_recovery",
"graph_projection",
"impact_preview",
"iteration",
"layout_contract",
"programme_continuation",
"project_registry",
"release_notes",
"salience_gate",
"scaffold",
"spine",
"spine_language",
"spine_loader",
"stage_guards",
"structural_migration",
"structural_model",
"structural_store",
"testing_mode",
"toolchain",
"tui_backlog",
"wait_guard",
"wait_guard_corpus",
"witness"
],
"rust_crates": [
"rune_spine"
]
}
}
}
+16 -1
View File
@@ -272,4 +272,19 @@ observations, fresh resume.
Release-note generator: LIVE-PROVEN (real Gitea, 10 releases). Backfill:
0.66.35→0.66.44 carrying historical-backfill provenance. Pre-0.66.35
history: skipped (weak evidence — honest limitation).
history: skipped (weak evidence — honest limitation).
## Contract discovery → spine (2026-10-05, #2465 CI correction)
The closed construction contract is the authority for discoveries. Spine
rebuild reads its observed entities and candidate corrections; it does not
claim a correction has been built. Qualified IDs such as
`rust-crate:cognition_core` keep their declared kind. Bare file paths,
test suites and other unqualified references become
`construction-surface:<reference>`, never `module`. An observed
surface may be PRESENT; a candidate stays DECLARED until independently
observed. Existing bad records are migrated with their evidence and edge
references intact. This matters: the first write-back mapped bare paths to
modules, made 22 false module records and crashed CI on the next rebuild.
The per-contract quick-reference markdown is generated from the scaffold
store at close; it is a view, not another authority.
+29
View File
@@ -218,6 +218,35 @@ critiques (2026-10-04):
or honestly flagged, never silent.
- Deploy qualification per merge (the pipeline that proved itself today).
### The 90/100 coverage law (Nick, 2026-10-05 — GOVERNING from W3.4 on)
Per Nick: "if it's realistically achievable but aim higher also if that's
realistically achievable. go to 100% where achievable."
- **100% where achievable — the deterministic Rust kernels.** Every kernel
crate (memory_retrieval, cognition_core, scaffold_core, memory_storage,
and every future crate) targets 100% BRANCH coverage via its parity
matrices + the pytest shim battery: every branch has real reachable
semantics, and exhaustive enumeration is exactly what the batteries do.
Achievability is measured per crate at wave close; a kernel below 100%
carries the named unreachable case or it isn't done.
- **≥90% on the changed-lines bar (diff-cover), aiming higher.** The floor
stays a floor; the working standard per slice is 90%+ on changed lines;
whatever a slice achieves beyond 90 becomes the next slice's personal
benchmark (per-unit "aim higher" — the number climbs wave over wave).
The floor ratchet itself moves after consecutive clean waves
(70 → 76 → 84 → 90; each raise is a commit, never a step down).
- **Glue/failure branches: 90%+ with byte-compare proofs.** The stubs and
probe branches that only fire in a broken world are covered by honest
fixtures (real import-failure probes like the from-import resolution
law) — never by fake-triggered pragmas. A branch covered by a lying
fixture is WORSE than uncovered; if it can't be honestly reached, it's
named in the wave's closure report with the reason.
- **Assertion quality is part of the bar.** A test that touches a line
without verifying its OUTPUT doesn't count toward the bar — byte-compare
/ exact-value asserts are the standard; "is not None" assertions reject
at review.
## 7. Risk register
- **SQLite FFI correctness** (Wave 2) — the storage layer is retained but
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "rune"
version = "0.95.0"
version = "0.100.0"
description = "Rune — a stateful coding assistant with persistent memory, orchestration, and TUI"
requires-python = ">=3.10"
+1 -1
View File
@@ -2,7 +2,7 @@
# uv pip compile pyproject.toml -o requirements-ci.txt --extra dev --extra memory --python-version 3.11
aiohappyeyeballs==2.7.1
# via aiohttp
aiohttp==3.14.3
aiohttp==3.14.4
# via rune (pyproject.toml)
aiosignal==1.4.0
# via aiohttp
+1 -1
View File
@@ -6,7 +6,7 @@ This is the main entry point for the Rune program.
import json
from pathlib import Path
__version__ = "0.95.0"
__version__ = "0.100.0"
# One build identity (handoff 2026-09-10 §4): the semantic version above is
# the repo-level truth (auto-bumped at merge); the DEPLOYED revision (exact
+62 -2
View File
@@ -43,6 +43,42 @@ LOCAL_MODEL = "qwen2.5:3b"
OLLAMA_URL = os.environ.get("OLLAMA_URL", "http://localhost:11434")
_ABSTRACTION_STOPWORDS_FROZEN = frozenset(
"the a an is are was were be been being have has had do does did will "
"would could should may might shall can to of in for on with at by from "
"as into through during before after this that these those it its what "
"which who how when where why and or but not no".split()
)
def _ABSTRACTION_STOPWORDS() -> list:
"""Gather seam (W3.4): the fact-extraction stopword table as a sorted
list — data received by the kernel; identical filter on both engines."""
return sorted(_ABSTRACTION_STOPWORDS_FROZEN)
def _core():
"""The Rust cognition_core when available (strangler: Python fallback
load-bearing). RUNE_COGNITION_CORE=python pins the fallback."""
return None if cc_loader_pin() else _cc_probe()
def _cc_probe():
from rune import cc_loader as _cl
try:
return _cl if _cl.available() else None
except Exception: # noqa: BLE001, S110 — loader probe never crashes the fallback
return None
def cc_loader_pin() -> bool:
"""The env pin: RUNE_COGNITION_CORE=python → kernels OFF (shared probe).
"""
import os
return os.environ.get("RUNE_COGNITION_CORE", "auto") == "python"
def _now():
return datetime.now(timezone.utc).isoformat()
@@ -241,17 +277,41 @@ Extract 1-5 key facts. Be precise, not verbose."""
response = llm_call(prompt, max_tokens=800)
# Parse response
facts: list = []
try:
# Try to extract JSON from response
start = response.find("[")
end = response.rfind("]") + 1
if start >= 0 and end > start:
facts = json.loads(response[start:end])
else:
facts = []
except json.JSONDecodeError:
facts = []
# LLM unavailable / unparseable → DETERMINISTIC KERNEL FALLBACK
# (W3.4: cc_abstraction_extract_facts — sentence split, stopwords
# filtered, min-length gate; the same facts schema it already emits:
# text/words/content_words mapped onto what= text with empty dims).
if not facts:
core = _core()
if core is not None:
try:
from rune import cc_loader as _cl
raw = _cl.abstraction_extract_facts(
episode_text, _ABSTRACTION_STOPWORDS(), 10)
for item in raw or []:
text_frag = str(item.get("text", "")).strip()
if not text_frag:
continue
facts.append({
"what": text_frag, "when": "", "where": "", "who": "",
"why": "", "type": "experience", "entities": [],
"kernel": True,
"content_words": item.get("content_words"),
})
except Exception: # noqa: BLE001, S110 — kernel failure degrades to empty, intentional silence
pass
if not facts:
return {"extracted": 0, "error": "LLM did not return valid JSON", "raw": response[:200]}
+6 -4
View File
@@ -19,7 +19,8 @@ def has_idempotent_label_removal(workflow: str) -> bool:
return bool(
re.search(
r"for \(const name of staleManaged\) \{\s*"
r"try \{\s*await github\.rest\.issues\.removeLabel\(\{.*?"
r"try \{.*?await github\.request\('DELETE /repos/\{owner\}/\{repo\}/issues/\{issue_number\}/labels/\{id\}', \{.*?"
r"id: currentLabelIds\.get\(name\),\s*"
r"\}\);\s*\} catch \(error\) \{\s*"
r"if \(error\.status !== 404\) \{\s*throw error;\s*\}\s*"
r"console\.log\(`Managed label already absent: \$\{name\}`\);\s*"
@@ -64,7 +65,7 @@ def main() -> int:
"infrastructure",
"life",
"custodian",
"priority: high",
"P0 — critical", "P1 — high", "P2 — medium", "P3 — low",
"bug",
"feature",
)
@@ -80,7 +81,8 @@ def main() -> int:
)
check(
"stale managed labels are removed",
"managedLabels.has" in auto_label and "!desiredLabels.has" in auto_label and "removeLabel" in auto_label,
"managedLabels.has" in auto_label and "!desiredLabels.has" in auto_label
and "currentLabelIds.get(name)" in auto_label,
failures,
)
check(
@@ -231,7 +233,7 @@ def main() -> int:
)
check(
"Rune minor version advertises provisioning and restore verification",
'__version__ = "0.95.0"' in rune_version,
'__version__ = "0.100.0"' in rune_version,
failures,
)
# #169 policy update: auto-bump on merge is sanctioned (Nick directive:
+5
View File
@@ -148,6 +148,11 @@ def _select_for_job(description: str, need_tools: bool) -> dict:
floor = [name for name in FLOOR_TOOLS if name in schemas]
matches = [name for _, name in _scored_tools(description, schemas)]
# An explicit shell request cannot succeed via the five-file-tool floor.
# Expose the canonical command tool, never execute it without its
# unchanged operator approval boundary.
if re.search(r"\b(?:bash|shell|terminal)\b", description, re.IGNORECASE) and "run_command" in schemas:
matches = ["run_command"] + [name for name in matches if name != "run_command"]
# Reserve one slot for the escape hatch; cap the whole set.
budget = max(0, MAX_SELECTED - len(floor) - 1)
matches = matches[:budget]
+77 -1
View File
@@ -21,6 +21,21 @@ _LIB_PATH = Path(
_lib = None
def core():
"""The shared kernel probe (strangler law): the delegation entry the
kernel-consuming modules use. RUNE_COGNITION_CORE=python pins the
fallback — THIS is where the pin is honored, so every consumer gets it
(a module-local probe that ignores the pin silently defeats it)."""
import os
if os.environ.get("RUNE_COGNITION_CORE", "auto") == "python":
return None
try:
return _load()
except Exception: # noqa: BLE001 — build/loader failures mean fallback
return None
def available() -> bool:
return _LIB_PATH.is_file()
@@ -38,7 +53,11 @@ def _load() -> ctypes.CDLL:
"cc_default_memory_budget", "cc_memory_disabled",
"cc_persona_lex", "cc_persona_overlap", "cc_persona_decide",
"cc_drift_check", "cc_identity_prompt", "cc_growth_near_dup",
"cc_growth_profile", "cc_pins_recall"):
"cc_growth_profile", "cc_pins_recall", "cc_tier_get",
"cc_tier_promote", "cc_tier_demote", "cc_witness_extract_topic",
"cc_witness_signals", "cc_safety_get_params",
"cc_safety_update_pattern", "cc_abstraction_extract_facts",
"cc_consolidation_memory", "cc_consolidation_neuron"):
fn = getattr(lib, sym)
fn.argtypes = [ctypes.c_char_p]
fn.restype = ctypes.c_void_p
@@ -117,3 +136,60 @@ def growth_profile(state: dict, order: list, entry_chars: int,
def pins_recall(pins: list, term: str, limit: int = 4) -> list:
return _call("cc_pins_recall", {"pins": pins, "term": term, "limit": limit})
def tier_get(entry: dict, now: str, hot_days: float = 7.0,
warm_days: float = 30.0) -> str:
return _call("cc_tier_get", {"entry": entry, "now": now,
"hot_days": hot_days, "warm_days": warm_days})
def tier_promote(entry: dict, now: str, hot_days: float = 7.0,
warm_days: float = 30.0) -> str:
return _call("cc_tier_promote", {"entry": entry, "now": now,
"hot_days": hot_days, "warm_days": warm_days})
def tier_demote(entry: dict, now: str, hot_days: float = 7.0,
warm_days: float = 30.0) -> str:
return _call("cc_tier_demote", {"entry": entry, "now": now,
"hot_days": hot_days, "warm_days": warm_days})
def witness_extract_topic(text: str, stopwords: list) -> list:
return _call("cc_witness_extract_topic",
{"text": text, "stopwords": stopwords})
def witness_signals(message: str, tables: dict, tool_error: str = "",
task_status: str = "", recent_topics: list | None = None) -> dict:
return _call("cc_witness_signals", {
"message": message, "tables": tables, "tool_error": tool_error,
"task_status": task_status, "recent_topics": recent_topics or []})
def safety_get_params(rows: list) -> dict:
return _call("cc_safety_get_params", {"rows": rows})
def safety_update_pattern(rows: list, pattern: str) -> list:
return _call("cc_safety_update_pattern", {"rows": rows, "pattern": pattern})
def abstraction_extract_facts(text: str, stopwords: list, min_len: int = 10):
return _call("cc_abstraction_extract_facts", {
"text": text, "stopwords": stopwords, "min_len": min_len})
def consolidation_memory(text: str, score: float, wash_count: int = 0,
entry_id: int | None = None, now: str = "") -> dict:
return _call("cc_consolidation_memory", {
"text": text, "score": score, "wash_count": wash_count,
"entry_id": entry_id, "now": now})
def consolidation_neuron(slug: str, body: str, importance: float,
triggers: list, wash_count: int = 0,
entry_id: int | None = None, now: str = "") -> dict:
return _call("cc_consolidation_neuron", {
"slug": slug, "body": body, "importance": importance,
"triggers": triggers, "wash_count": wash_count,
"entry_id": entry_id, "now": now})
+95
View File
@@ -171,3 +171,98 @@ def _accept(command_id: str, construction_id: str, correlation_id: str,
"recorded_at": time.strftime("%Y-%m-%dT%H:%M:%SZ",
time.gmtime()),
"idempotent_replay": False}
def dispatch(command_type: str, *, construction_id: str,
correlation_id: str = "", command_id: str = "",
payload: dict | None = None,
store_path: str = "store/scaffold") -> dict:
"""The SERVING layer (T5.15 slice 2): validate the command against the
canonical store, execute the accepted intent through the Construction
Interface, and return the interface's envelope with the command
provenance attached.
Single entry point for `rune scaffold <command>` (the Go proxy) and
any future transport. Idempotency: a repeated command_id replays the
recorded outcome without re-executing.
Refusal still returns success=False envelope? NO — a refused command
is a VALID protocol outcome: the envelope carries accepted=False and
success=True (the dispatch itself worked; the lifecycle refused the
intent). Execution failures carry success=False.
"""
iface_path = None
if store_path and store_path != "store/scaffold":
iface_path = store_path
try:
from rune import construction_interface as ci
# store_path carries the serving layer's "path|project_id" contract
# (a bare path = last segment is the project id, matching how the
# Go proxy and the interface's own default name it).
if iface_path:
path_part, _, proj_part = iface_path.partition("|")
proj = proj_part or path_part.rstrip("/").split("/")[-1]
iface = ci.ConstructionInterface(builder="substrate",
project_store=path_part,
project_id=proj)
else:
iface = ci.ConstructionInterface(builder="substrate")
except Exception as exc: # noqa: BLE001 — serving failure is an envelope, not a crash
return {"accepted": False, "executed": False,
"success": False, "error": f"serving unavailable: {exc}"[:200],
"command_type": command_type,
"construction_id": construction_id}
intent = command(command_type, construction_id=construction_id,
correlation_id=correlation_id, command_id=command_id,
payload=payload, scaffold=iface.scaffold)
if intent.get("idempotent_replay"):
# Repeated delivery: return the recorded outcome WITHOUT executing
# again (the ledger's whole point). The first execution's envelope
# is not re-derivable here, so the replay carries the intent and
# the flag — the caller knows the effect already happened.
return {"accepted": True, "executed": False,
"success": True, "idempotent_replay": True,
"op": intent.get("op"),
"command_type": command_type,
"construction_id": construction_id,
"correlation_id": intent.get("correlation_id", ""),
"command_id": intent.get("command_id", "")}
if not intent.get("accepted"):
return {"accepted": False, "executed": False, "success": True,
"reason": intent.get("reason"),
"command_type": command_type,
"construction_id": construction_id,
"correlation_id": intent.get("correlation_id", ""),
"command_id": intent.get("command_id", ""),
"idempotent_replay": intent.get("idempotent_replay", False)}
op = intent["op"]
args = intent["args"]
ops = {
"resume": lambda: iface.resume(args["contract_id"]),
"transition": lambda: iface.transition(
args["contract_id"], args["phase"],
evidence_ref=f"command:{intent['command_id']}"
+ (f" approved_by:{args['approved_by']}" if args.get("approved_by") else "")),
"amend_scope": lambda: iface.amend_scope(
args["contract_id"], args["add_paths"],
reason=args.get("reason", "substrate context"),
authority=args.get("authority", "substrate")),
}
fn = ops.get(op)
if fn is None:
return {"accepted": True, "executed": False, "success": False,
"error": f"no executor for op {op!r}",
"command_type": command_type,
"construction_id": construction_id}
env = fn()
return {"accepted": True, "executed": True,
"success": bool(env.get("success")),
"envelope": env,
"command_type": command_type,
"construction_id": construction_id,
"correlation_id": intent.get("correlation_id", ""),
"command_id": intent.get("command_id", ""),
"idempotent_replay": False}
+146 -12
View File
@@ -36,6 +36,7 @@ from typing import Any
import json
import sys
import uuid
from pathlib import Path
from rune import structural_store as ss
@@ -88,6 +89,39 @@ def _envelope(
return env
def _to_stage_check(spec: dict):
"""One guard spec → a stage_guards.StageCheck (T5.15 wire)."""
from rune import stage_guards as sg
return sg.StageCheck(
name=str(spec.get("name", "guard")),
kind=str(spec.get("kind", "assert")),
argv=spec.get("argv"),
output_pattern=str(spec.get("output_pattern", "")),
path=str(spec.get("path", "")),
check=spec.get("check"),
description=str(spec.get("description", "")),
)
def _guard_specs_from_obligations(c: dict) -> list[dict]:
"""The contract's guard declarations: verification_obligations rows
shaped `guard:<json-spec>` (the decision path records them; anything
else stays a free-text obligation for the projection). JSONDecodeError
→ skipped with no invented facts."""
specs: list[dict] = []
for item in (c.get("identities") or {}).get("verification_obligations", []) or []:
if not isinstance(item, str) or not item.startswith("guard:"):
continue
try:
spec = json.loads(item[6:])
if isinstance(spec, dict):
specs.append(spec)
except json.JSONDecodeError:
continue
return specs
class ConstructionInterface:
"""The builder-facing construction lifecycle for ONE project target.
@@ -291,6 +325,13 @@ class ConstructionInterface:
"transition": {
"phase": {"type": "str", "required": True,
"allowed": list(sc.PHASES)},
"evidence_ref": {"type": "str", "required": False},
"guard_checks": {
"type": "list[dict] | None", "required": False,
"notes": ("stage-guard specs run on the "
"completion edges (verifying/closed); "
"a failure BLOCKS with "
"VERIFICATION_FAILED — T5.15 wire")},
},
"close": {
"observed_evidence": {
@@ -381,7 +422,8 @@ class ConstructionInterface:
errors.append({"error": Errors.INSUFFICIENT_EVIDENCE, "detail": trace["rationale"][:200]})
contract = None
if generate and trace["resolution"] not in ("INSUFFICIENT_EVIDENCE",):
cid = contract_id or f"BUILDER-{ss.now()}-{self.builder}"
cid = (contract_id
or f"BUILDER-{ss.now()}-{uuid.uuid4().hex[:6]}-{self.builder}")
cd.generate_contract(
self.scaffold,
doc,
@@ -607,8 +649,57 @@ class ConstructionInterface:
warnings=warnings,
)
def transition(self, contract_id: str, phase: str, *, evidence_ref: str = "") -> dict:
def transition(self, contract_id: str, phase: str, *, evidence_ref: str = "",
guard_checks: list[dict] | None = None) -> dict:
"""Move a contract phase. Completion-wave slice (T5.15, the
stage_guards wire): entering `verifying` and `closed` runs the
§15F/§15G guards — readiness/exit StageChecks and test-truth
verification — when the contract declares them
(identities.verification_obligations carries `guard:<spec>` rows,
or guard_checks passes inline specs).
guard_checks spec: {"name", "kind": "command"|"path_exists"|"assert",
"argv"/"path"/"output_pattern", "check": callable (in-process only),
"description"}. A guard failure is a VERIFICATION_FAILED envelope:
the phase does NOT move.
The legality map stays the scaffold's authority; guards ADD evidence
obligations on the completion-facing edges (building→verifying,
verifying→closed) — a tiny bounded change can pass guards=[] freely.
"""
doc = self.scaffold.load()
c = self.scaffold.contract(doc, contract_id)
if c is None:
return _envelope(
"transition",
success=False,
ids={"contract_id": contract_id},
errors=[{"error": Errors.UNKNOWN_CONTRACT, "detail": f"no contract {contract_id}"}],
)
if phase in ("verifying", "closed"):
from rune import stage_guards as sg
specs = guard_checks
if specs is None:
specs = _guard_specs_from_obligations(c)
if specs:
stage = sg.StageContract(
stage_id=f"{contract_id}:{phase}",
contract_id=contract_id,
ready_when=[_to_stage_check(s) for s in specs],
done_when=[_to_stage_check(s) for s in specs],
)
canary = sg.readiness_canary(stage)
if canary["verdict"] == "BLOCKED":
return _envelope(
"transition",
success=False,
ids={"contract_id": contract_id},
state={"phase": c.get("phase"), "guard": canary},
errors=[{"error": Errors.VERIFICATION_FAILED,
"detail": "stage guards blocked the transition",
"failures": canary["failures"]}],
)
try:
self.scaffold.transition_contract(
doc, contract_id, phase, evidence_ref=evidence_ref or f"builder:{self.builder}"
@@ -679,21 +770,62 @@ class ConstructionInterface:
material_closure = self._auto_material_change(
scope_files or [],
note=f"contract {contract_id} closed (material change)")
continuation = self._programme_continuation(contract_id)
state = {
"phase": "closed",
"material_change_closure": material_closure,
"contract_quality": {
k: q[k]
for k in ("correctly_predicted", "expected_new_observed", "genuinely_unexpected_new", "scope_check")
if k in q
},
}
if continuation is not None:
state["programme_continuation"] = continuation
return _envelope(
"close",
success=True,
ids={"contract_id": contract_id},
state={
"phase": "closed",
"material_change_closure": material_closure,
"contract_quality": {
k: q[k]
for k in ("correctly_predicted", "expected_new_observed", "genuinely_unexpected_new", "scope_check")
if k in q
},
},
state=state,
)
def _programme_continuation(self, contract_id: str) -> dict | None:
"""T5.15 slice 3 (the programme_continuation wire): after a legal
close, any persisted Programme stage bound to this contract is
marked COMPLETE and the continuation canary's verdict rides the
close envelope — 'task done' ≠ 'programme done', and the next
eligible stage is SURFACED, never guessed. No programme bound →
None (no continuation block in the envelope). Failures degrade:
a broken programme ledger never fails a real closure."""
try:
from pathlib import Path as _Path
from rune import programme_continuation as pc
base = _Path(self.scaffold.current).parent / pc.DEFAULT_PROGRAMME_AREA
if not base.is_dir():
return None
for prog_file in sorted(base.glob("*.json")):
prog = pc.Programme.load(base, prog_file.stem)
if prog is None:
continue
stage = next((s for s in prog.stages
if s.stage_id == contract_id
and s.state != pc.COMPLETE), None)
if stage is None:
continue
stage.state = pc.COMPLETE
stage.result["closed_at_contract"] = contract_id
prog.save(base)
return {
"programme_id": prog.programme_id,
"stage_marked_complete": contract_id,
"canary": prog.continuation_canary(),
}
except Exception as exc: # noqa: BLE001 — ledger failure never fails a closure
return {"error": f"programme continuation degraded: {exc}"[:200]}
return None
def _auto_material_change(self, scope_files: list[str], *,
note: str) -> dict:
"""T21.4 §21.4H (rule 19Q.2): governed construction closes → the
@@ -1019,7 +1151,9 @@ def main(argv=None) -> int:
if cmd == "verify":
return _out(iface.verify(args[0], changed_files=(json.loads(args[1]) if len(args) > 1 else None)))
if cmd == "transition":
return _out(iface.transition(args[0], args[1], evidence_ref=args[2] if len(args) > 2 else ""))
guard_checks = json.loads(args[3]) if len(args) > 3 else None
return _out(iface.transition(args[0], args[1], evidence_ref=args[2] if len(args) > 2 else "",
guard_checks=guard_checks))
if cmd == "close":
return _out(
iface.close(
+61 -54
View File
@@ -62,6 +62,59 @@ PYTHON = os.path.expanduser("~/.venvs/memory/bin/python3")
# ═══════════════════════════════════════════════════════════════════════════════
def _core():
"""The Rust cognition_core when available (strangler: Python fallback
load-bearing). RUNE_COGNITION_CORE=python pins the fallback."""
try:
from rune import cc_loader
except ImportError:
import cc_loader
try:
return cc_loader if cc_loader.available() else None
except Exception:
return None
def _consolidation_memory_oracle(memory_text: str, score: float, wash_count: int = 0,
entry_id: int | None = None) -> dict:
"""Python parity oracle for consolidation_memory."""
if drift_compression:
entry = {"text": memory_text, "wash_count": wash_count, "rock_status": "washable"}
content = drift_compression.compress_entry(entry)
else:
content = memory_text[:100] + "..." if len(memory_text) > 100 else memory_text
from datetime import datetime, timezone
now = datetime.now(timezone.utc).isoformat()
eid = f"memory-{entry_id}" if entry_id else f"memory-{hash(memory_text) % 10000}"
return {"id": eid, "source": "memory", "category": "lesson",
"content": content, "confidence": score,
"created_at": now, "last_used": now,
"use_count": 0, "wash_count": wash_count,
"entry_id": entry_id, "tags": []}
def _consolidation_neuron_oracle(slug: str, body: str, importance: float,
triggers: list, wash_count: int = 0,
entry_id: int | None = None) -> dict:
"""Python parity oracle for consolidation_neuron."""
if drift_compression:
entry = {"text": body, "wash_count": wash_count, "rock_status": "washable"}
first_line = drift_compression.compress_entry(entry)
else:
first_line = body.split("\n")[0].strip()
if len(first_line) > 100:
first_line = first_line[:97] + "..."
if not first_line:
first_line = body[:100]
from datetime import datetime, timezone
now = datetime.now(timezone.utc).isoformat()
return {"id": f"neuron-{slug}", "source": "neuron", "category": "fact",
"content": first_line, "confidence": importance,
"created_at": now, "last_used": now,
"use_count": 0, "wash_count": wash_count,
"entry_id": entry_id, "tags": triggers}
@dataclass
class ConsolidatedKnowledge:
"""Knowledge consolidated from episodic memory."""
@@ -163,7 +216,8 @@ class MemoryConsolidation:
# ─────────────────────────────────────────────────────────────────────────
def consolidate_neuron(self, neuron: Dict[str, Any]) -> ConsolidatedKnowledge:
"""Consolidate a warm neuron into knowledge."""
"""Consolidate a warm neuron into knowledge.
Uses the oracle (which delegates to the kernel when available)."""
slug = neuron.get("slug", "unknown")
body = neuron.get("body", neuron.get("text", ""))
importance = neuron.get("importance", 0.5)
@@ -183,42 +237,12 @@ class MemoryConsolidation:
except Exception:
pass
# Use drift-aware compression with compaction warnings
if drift_compression:
entry = {"text": body, "wash_count": wash_count, "rock_status": "washable"}
# Compaction warning: alert if compressing proven content
if drift_compression.should_warn(entry):
warning = drift_compression.warn_before_compress(entry)
# Log warning but don't block — the gate system handles promotion
import sys
print(f" [compaction warning] neuron {slug}: {warning['recommendation']}", file=sys.stderr)
first_line = drift_compression.compress_entry(entry)
else:
# Fallback: hardcoded truncation
first_line = body.split("\n")[0].strip()
if len(first_line) > 100:
first_line = first_line[:97] + "..."
if not first_line:
first_line = body[:100]
# Normalize triggers — may be string or list
if isinstance(triggers, str):
triggers = [t.strip() for t in triggers.split(",") if t.strip()]
knowledge = ConsolidatedKnowledge(
id=f"neuron-{slug}",
source="neuron",
category="fact",
content=first_line,
confidence=importance,
created_at=datetime.now(timezone.utc).isoformat(),
last_used=datetime.now(timezone.utc).isoformat(),
wash_count=int(neuron.get("wash_count", 0)),
entry_id=entry_id,
tags=triggers,
)
return knowledge
rec = _consolidation_neuron_oracle(slug, body, importance, triggers, wash_count, entry_id)
return ConsolidatedKnowledge(**rec)
def consolidate_graph_entity(self, entity: Dict[str, Any]) -> ConsolidatedKnowledge:
"""Consolidate a graph entity into knowledge."""
@@ -339,27 +363,10 @@ class MemoryConsolidation:
def consolidate_memory(
self, memory_text: str, score: float, wash_count: int = 0, entry_id: Optional[int] = None
) -> ConsolidatedKnowledge:
"""Consolidate a memory recall into knowledge."""
# Use drift-aware compression instead of hardcoded truncation
if drift_compression:
entry = {"text": memory_text, "wash_count": wash_count, "rock_status": "washable"}
consolidated = drift_compression.compress_entry(entry)
else:
consolidated = memory_text[:100] + "..." if len(memory_text) > 100 else memory_text
knowledge = ConsolidatedKnowledge(
id=f"memory-{entry_id}" if entry_id else f"memory-{hash(memory_text) % 10000}",
source="memory",
category="lesson",
content=consolidated,
confidence=score,
created_at=datetime.now(timezone.utc).isoformat(),
last_used=datetime.now(timezone.utc).isoformat(),
wash_count=wash_count,
entry_id=entry_id,
tags=[],
)
return knowledge
"""Consolidate a memory recall into knowledge.
Uses the oracle (which delegates to the kernel when available)."""
rec = _consolidation_memory_oracle(memory_text, score, wash_count, entry_id)
return ConsolidatedKnowledge(**rec)
def add_lesson(self, trigger: str, lesson: str, context: str) -> Lesson:
"""Add a lesson learned from experience."""
+39 -13
View File
@@ -43,6 +43,20 @@ if _PACKAGE_PARENT not in sys.path:
sys.path.append(_PACKAGE_PARENT)
import safety_override # noqa: E402
import model_profiles # noqa: E402
# Probe authority: module-level dual import (the except-clause below must
# reference a BOUND name — a try-scoped from-import inside _probe_and_escalate
# made ProbeBudgetExceeded "possibly unbound" and tripped the pyright ratchet).
try:
try:
from .evidence_probe import ProbeBudgetExceeded as _ProbeBudgetExceeded
from .evidence_probe import run_probe as _run_probe
except ImportError: # TUI top-level deploy
from rune.evidence_probe import ProbeBudgetExceeded as _ProbeBudgetExceeded
from rune.evidence_probe import run_probe as _run_probe
except ImportError: # evidence_probe unavailable in bare contexts — probes opt-out
_ProbeBudgetExceeded = None
_run_probe = None
# Tool authority must be ONE module object. Importing tool_executor both as
# a top-level module (this file's legacy scripts-path import) and as
# rune.tool_executor (local_tool_runtime's import) yields two distinct
@@ -213,6 +227,20 @@ def _bounded(text: object, limit: int = 300) -> str:
return " ".join(str(text or "").split())[:limit]
def _probe_failure_classes() -> tuple:
"""Exception classes _probe_and_escalate must never leak into chat.
Budget exhaustion is one of them — the handler records + returns False
instead of raising, so chat never sees a probe failure; the task-scoped
probe dir keeps the budget per-task so chat never inherits another
task's exhausted ledger. Tuple form (rather than a literal except
tuple) lets the import-unavailable case degrade gracefully."""
classes = [OSError, ValueError, TypeError, KeyError]
if _ProbeBudgetExceeded is not None:
classes.append(_ProbeBudgetExceeded)
return tuple(classes)
def _sorted_tool_names(tool_names: object) -> list:
"""Sorted str list from a tool_names iterable; non-str items dropped.
@@ -578,18 +606,16 @@ class RuneOperator:
try:
try:
from . import adaptive_router as _ar
from .evidence_probe import run_probe
except ImportError:
from rune import adaptive_router as _ar
from rune.evidence_probe import run_probe
# Opt-in like the executor path (ADAPT-LIVE §4): real probes
# cost a worker call; the default runtime enables them via
# MIMO_PROBE_ENABLED=1 in the operator environment (set in the
# TUI launch env / deployment). Tests and bare imports stay
# deterministic — the lesson from the reachability tranche.
if os.environ.get("MIMO_PROBE_ENABLED") != "1":
return
if _run_probe is None or os.environ.get("MIMO_PROBE_ENABLED") != "1":
return False
error = (result.error or "") if hasattr(result, "error") else (result.get("error") or "")
# Material-unknown question: what did verification establish
# could NOT be established locally? Bounded, deterministic.
@@ -600,9 +626,14 @@ class RuneOperator:
f"expected rather than a local defect? Answer with the "
f"5-key probe schema."
)
probe = run_probe(
question, str(Path(self.storage_path).parent / "probes"), model=os.environ.get("MIMO_MODEL", "UNKNOWN")
)
# The probe budget belongs to ONE task. The old shared
# ~/.rune/probes/probe.jsonl exhausted after two tasks and made
# every later chat failure raise ProbeBudgetExceeded forever.
import hashlib
task_key = hashlib.sha256(str(task.task_id).encode("utf-8")).hexdigest()
probe_dir = Path(self.storage_path).parent / "probes" / task_key
probe = _run_probe(question, str(probe_dir), model=os.environ.get("MIMO_MODEL", "UNKNOWN"))
route_log = os.path.join(str(Path(self.storage_path).parent / "routes"), "route.jsonl")
decision = (
self._route_task_class(
@@ -640,12 +671,7 @@ class RuneOperator:
self._save()
return True
return False
except (
OSError,
ValueError,
TypeError,
KeyError,
) as exc: # probe must never corrupt the failure path; subprocess.TimeoutExpired is OSError-family
except _probe_failure_classes() as exc:
try:
try:
from .subsystem_health import record_failure
+72 -75
View File
@@ -8,7 +8,7 @@ mode system, subject header, shared memory and identity.
This is not an interface. This is how I see, speak, and interact with the world.
Version: v0.95.0
Version: v0.100.0
Features: 41 (24 original + 17 new native commands)
Usage:
@@ -110,6 +110,56 @@ try:
except ImportError:
BACKEND_AVAILABLE = False
def collect_post_response_signals(response: str, messages_count: int) -> list[str]:
"""Gather the operational signals that used to each print a dim
system message after every task/build response (the dim-spam source,
T5.13): budget pressure, degraded claims, growth delta, the periodic
self-improvement cycle.
PURE and headless — no channel, no app. The caller renders ONE
collapsed line (or none when nothing fired). Queued-message execution
and on-complete cron firing stay in the worker: they move real
messages, not chatter, and keep their own echoes.
Returns short human-readable fragments; empty list = silence.
"""
signals: list[str] = []
if not BACKEND_AVAILABLE:
return signals
try:
budget_data = provider_budget.get_status()
ratios = []
for provider in budget_data.get("providers", {}).values():
if provider.get("monthly_limit", 0) > 0:
ratios.append(provider.get("monthly_used", 0) / provider["monthly_limit"])
if provider.get("token_limit", 0) > 0:
ratios.append(provider.get("tokens_used", 0) / provider["token_limit"])
usage_percent = max(ratios, default=0) * 100
if usage_percent > 80:
signals.append(f"⚠ Budget: {usage_percent:.0f}% used")
except Exception:
pass
try:
claims_result = claim_audit.scan_text(response[:500])
if claims_result and claims_result.get("degraded"):
signals.append(f"⚠ Claims degraded: {len(claims_result['degraded'])}")
except Exception:
pass
try:
growth = growth_delta.check()
if growth and growth.get("delta"):
signals.append(f"📈 Growth: {growth['delta']}")
except Exception:
pass
try:
if messages_count % 10 == 0:
self_improve.run()
signals.append("🔄 Self-improvement cycle triggered")
except Exception:
pass
return signals
from textual.app import App, ComposeResult
from textual.containers import Horizontal, Vertical, VerticalScroll
from textual.widgets import Button, Header, Input, ProgressBar, RichLog, Static
@@ -1533,18 +1583,21 @@ class RuneApp(App):
def compose(self) -> ComposeResult:
yield Header()
with Horizontal(id="channels"):
yield ChannelView(
"task",
"[b]TASK[/b] — focused work",
classes="channel-view",
id="task-channel",
)
# T5.14 (Nick 2026-10-05): chat LEFT, task RIGHT — feels more
# natural (conversation first, focused work second). WorkPane
# stays third.
yield ChannelView(
"chat",
"[b]CHAT[/b] — free conversation",
classes="channel-view",
id="chat-channel",
)
yield ChannelView(
"task",
"[b]TASK[/b] — focused work",
classes="channel-view",
id="task-channel",
)
# P1-07 (#30): third collapsible column — the operational index.
yield WorkPane(id="work-pane")
with Horizontal(id="footer-bar"):
@@ -1895,7 +1948,7 @@ class RuneApp(App):
# Show version info
self.chat_channel.add_message(
"system",
f"[dim]Rune v0.95.0 | Textual TUI | {len(loaded)} native modules[/dim]",
f"[dim]Rune v0.100.0 | Textual TUI | {len(loaded)} native modules[/dim]",
)
# Auto-show night mode suggestion if evening/night hours
@@ -3737,69 +3790,13 @@ class RuneApp(App):
except Exception:
pass
# Auto-warn budget when >80% used
try:
if BACKEND_AVAILABLE:
budget_data = provider_budget.get_status()
ratios = []
for provider in budget_data.get("providers", {}).values():
if provider.get("monthly_limit", 0) > 0:
ratios.append(provider.get("monthly_used", 0) / provider["monthly_limit"])
if provider.get("token_limit", 0) > 0:
ratios.append(provider.get("tokens_used", 0) / provider["token_limit"])
usage_percent = max(ratios, default=0) * 100
if usage_percent > 80:
ch.add_message(
"system",
f"[dim]⚠ Budget: {usage_percent:.0f}% used[/dim]",
)
except Exception:
pass
# Auto-check claims after response
try:
if BACKEND_AVAILABLE:
claims_result = claim_audit.scan_text(response[:500])
if claims_result and claims_result.get("degraded"):
ch.add_message(
"system",
f"[dim]⚠ Claims degraded: {len(claims_result['degraded'])}[/dim]",
)
except Exception:
pass
# NOTE (Runtime Reachability audit 2026-09-10): the
# old hook_engine.fire("post_message", ...) call here
# was dead — hook_engine defines no fire(); the
# AttributeError was silently swallowed, so "hooks"
# never ran. Removed rather than left as a false-
# liveness surface. Real hook dispatch is unwired
# (microkernel.fire has zero callers) — see the
# reachability audit, P3.
# Auto-check growth delta
try:
if BACKEND_AVAILABLE:
growth = growth_delta.check()
if growth and growth.get("delta"):
ch.add_message(
"system",
f"[dim]📈 Growth: {growth['delta']}[/dim]",
)
except Exception:
pass
# Auto-improve every 10 messages
try:
if self.status_bar.messages_count % 10 == 0:
if BACKEND_AVAILABLE:
self_improve.run()
ch.add_message(
"system",
f"[dim]🔄 Self-improvement cycle triggered[/dim]",
)
except Exception:
pass
# T5.13 dim-spam consolidation: previously five
# separate dim system messages printed after every
# response. ONE collapsed line now — empty means
# silence, not a dash.
signals = collect_post_response_signals(response[:500], self.status_bar.messages_count)
if signals:
ch.add_message("system", "[dim]" + " · ".join(signals) + "[/dim]")
elif result.get("error") == "RESEARCH_REQUIRED":
# Nonterminal routing disposition, not failure (2026-09-10):
# the task hit the deep-research floor and was dispatched.
@@ -3980,13 +3977,13 @@ class RuneApp(App):
pass
def action_resize_left(self) -> None:
"""Shrink task channel, grow chat channel."""
self.task_width = max(20, self.task_width - 5)
"""Shrink the LEFT channel (chat, post-swap), grow the RIGHT (task)."""
self.task_width = min(80, self.task_width + 5)
self._apply_resize()
def action_resize_right(self) -> None:
"""Grow task channel, shrink chat channel."""
self.task_width = min(80, self.task_width + 5)
"""Grow the LEFT channel (chat), shrink the RIGHT (task)."""
self.task_width = max(20, self.task_width - 5)
self._apply_resize()
def _apply_resize(self):
+117 -78
View File
@@ -86,6 +86,110 @@ PATTERN_MAX_PATTERNS = 200
# ═══════════════════════════════════════════════════════════════════════════════
def _keyword_stopwords() -> list:
"""Gather seam (W3.4): the pattern-keyword stopword table as a sorted
list — data, not logic; both engines read this module-owned table."""
return sorted(_KEYWORD_STOPWORDS)
_KEYWORD_STOPWORDS = frozenset({
"the",
"and",
"for",
"are",
"but",
"not",
"you",
"all",
"can",
"had",
"her",
"was",
"one",
"our",
"out",
"day",
"get",
"has",
"him",
"his",
"how",
"its",
"may",
"new",
"now",
"old",
"see",
"way",
"who",
"did",
"let",
"say",
"she",
"too",
"use",
"this",
"that",
"with",
"have",
"from",
"they",
"been",
"said",
"each",
"make",
"like",
"just",
"over",
"such",
"take",
"year",
"them",
"some",
"time",
"very",
"when",
"come",
"could",
"what",
"there",
"their",
"will",
"would",
"about",
"which",
"these",
"other",
"into",
"more",
"than",
"also",
"then",
})
def _core():
"""The Rust cognition_core when available (strangler: Python fallback
load-bearing). RUNE_COGNITION_CORE=python pins the fallback."""
return None if cc_loader_pin() else _cc_probe()
def _cc_probe():
from rune import cc_loader as _cl
try:
return _cl if _cl.available() else None
except Exception: # noqa: BLE001, S110 — loader probe never crashes the fallback
return None
def cc_loader_pin() -> bool:
"""The env pin: RUNE_COGNITION_CORE=python → kernels OFF (shared probe).
"""
import os
return os.environ.get("RUNE_COGNITION_CORE", "auto") == "python"
@dataclass
class OverridePattern:
"""A learned pattern that requires override."""
@@ -105,7 +209,14 @@ class OverridePattern:
return self.successes / total
def matches(self, text: str) -> bool:
"""Check if text matches this pattern's keywords."""
"""Check if text matches this pattern's keywords. Deterministic
keyword-count check (kernel port NOT owed here — the W3.4 safety
kernels cover the params/rows surfaces; this tiny comparison stays
Python-side per the membrane law: gather/IO in Python, kernels for
deterministic row work already ported)."""
return self._py_matches(text)
def _py_matches(self, text: str) -> bool:
text_lower = text.lower()
matches = sum(1 for kw in self.keywords if kw.lower() in text_lower)
return matches >= PATTERN_MIN_KEYWORDS
@@ -293,84 +404,12 @@ class SafetyOverride:
self.stats.patterns_learned += 1
def _extract_keywords(self, text: str) -> list[str]:
"""Extract distinctive keywords from text for pattern matching."""
# Remove common stop words, keep words > 3 chars
stop_words = {
"the",
"and",
"for",
"are",
"but",
"not",
"you",
"all",
"can",
"had",
"her",
"was",
"one",
"our",
"out",
"day",
"get",
"has",
"him",
"his",
"how",
"its",
"may",
"new",
"now",
"old",
"see",
"way",
"who",
"did",
"let",
"say",
"she",
"too",
"use",
"this",
"that",
"with",
"have",
"from",
"they",
"been",
"said",
"each",
"make",
"like",
"just",
"over",
"such",
"take",
"year",
"them",
"some",
"time",
"very",
"when",
"come",
"could",
"what",
"there",
"their",
"will",
"would",
"about",
"which",
"these",
"other",
"into",
"more",
"than",
"also",
"then",
}
"""Extract distinctive keywords from text for pattern matching.
Keyword extraction stays Python-side (W3.4 scope note): the safety
kernels cover the params/rows surfaces; this extractor is a gather
(IO-adjacent list build) per the membrane law."""
words = re.findall(r"[a-z]{4,}", text.lower())
keywords = [w for w in words if w not in stop_words]
keywords = [w for w in words if w not in _KEYWORD_STOPWORDS]
# Return top 5 most distinctive words
return keywords[:5]
+18 -3
View File
@@ -53,6 +53,12 @@ from rune.structural_store import ( # shared generic core (SCAFFOLD-TRANCHE-001
reconcile_authorities, mark_conflict, resolve_status, authority_health,
dedupe_observations as _ss_dedupe_observations,
)
from rune.spine_language import ( # noqa: F401 — re-exported (import-compat): the
# #2465 doc-level transforms live here now (giant-file carve); tests and
# the canary_spine_meta read them THROUGH spine, exactly as before.
_classification_sides, _place_languages, _normalize_discovery_ids,
_apply_contract_discoveries, _contract_discoveries,
)
SCHEMA_VERSION = 1
@@ -337,11 +343,14 @@ def _rust_core():
return None
def _gather_build_inputs(manifest_path: Path | None = None) -> dict:
"""Every I/O read build() needs, in one place (zero-dep split law:
Python scans, the core — Rust or Python — only assembles). Both cores
consume this dict, so parity divergence is logic, never environment."""
existing = load()
if existing:
_normalize_discovery_ids(existing)
seeded = bool(existing) and any(
r["type"] == "belongs_to" for r in existing["relationships"])
# ingest manifest: only consulted when the unseeded path needs it
@@ -517,6 +526,7 @@ def _py_build_from_inputs(inputs: dict) -> dict:
from_id=f"subsystem:{name}", to_id=mid,
evidence_refs=[f"umbrella-manifest#{name}"])
# reconcile: facts owned by projectors that no longer observe them
# become STALE (marked, never deleted — history survives; open-world
# preservation applies to everything, staleness is the truth marker)
@@ -595,9 +605,14 @@ def build(manifest_path: Path | None = None) -> dict:
# paths, including an explicit unseeded-ingest parity section.
seeded = bool(inputs["existing"]) and any(
r["type"] == "belongs_to" for r in inputs["existing"]["relationships"])
if core is not None and seeded:
return core.project(inputs)
return _py_build_from_inputs(inputs)
doc = (core.project(inputs) if core is not None and seeded
else _py_build_from_inputs(inputs))
# both cores funnel through the same post-projection passes (the
# contract-discovery write-back + language placement) — the doc-level
# transforms live in Python until the #2464 top-up ports them
_apply_contract_discoveries(doc)
_place_languages(doc)
return doc
# ── drift ─────────────────────────────────────────────────────────────────
+218
View File
@@ -0,0 +1,218 @@
"""spine_language.py — the #2465 doc-level transforms (carved from spine.py
to honor the giant-file henxel: keep it under 1200 lines).
Three transforms, applied to BOTH cores' output at build time:
1. language placement — every entity gets a language verdict (kind
defaults; subsystems derive from member-majority over the measured
classification map);
2. discovery-ID normalization — migrate legacy unqualified contract
discoveries to construction-surface kind without losing evidence;
3. contract-discovery write-back — closed contracts teach the spine
what construction actually built (observed → PRESENT, candidate →
DECLARED; the CANDIDATE law holds).
Same dependency laws as spine.py: structural_store primitives only, no
I/O beyond the classification/scaffold store reads, deterministic.
"""
from __future__ import annotations
import json
from pathlib import Path
from rune.structural_store import (
add_entity, add_relationship, entity, new_doc, relationships, _sorted, now,
)
ROOT = Path(__file__).resolve().parents[2]
SRC_DIR = ROOT / "src" / "rune"
def _classification_sides() -> dict:
"""The measured dichotomy map (W0): module stem → RUST|GO|TUI-LAST|...
Loaded once per _place_languages call, best-effort — a missing or
unreadable classification.json degrades to {}/unassessed verdicts,
never to invented facts."""
try:
data = json.loads((ROOT / "store" / "rebase" / "classification.json").read_text())
return {name: rec.get("side", "") for name, rec in data.items() if isinstance(rec, dict)}
except (OSError, json.JSONDecodeError, AttributeError):
return {}
def _place_languages(doc: dict) -> int:
"""Stamp a language verdict per entity (no-op for entities that carry
one). Deterministic: substring classification over the entity id + the
kind; the exact same rule construction_decision.language_placement
implements (kept inline here to avoid a per-entity FFI crossing for
the spine's own 218 entities; the FFI path is used in contracts)."""
GO_HINTS = ("server", "transport", "dispatch", "entry", "bridge",
"hook_engine", "provider", "watch", "notif", "voice",
"gitea", "event_", "message_", "tool_exec", "work_manager")
RUST_HINTS = ("memory", "drift", "warm", "capab", "token", "spine",
"scaffold", "construct", "structural", "curator",
"consolidat", "elastic", "cognit", "abstract", "contract",
"ledger", "audit", "claim", "evidence", "behavio",
"verif", "pins", "witness", "anchor", "growth", "goal",
"salience", "store", "tui_", "rune_tui")
placed = 0
CLASSIFICATION_SIDES = _classification_sides()
for e in doc.get("entities", []):
eid = e.get("id", "")
kind = e.get("kind", "")
# AUTHORITY ORDER (Nick's dichotomy, 2026-10-06 correction): the
# MEASURED classification map (import-evidence per module) decides
# FIRST. The name-hint lists are only a fallback for entities with
# no measurement — never allowed to override the evidence. A module
# with neither measurement nor hint is "unclassified", not a silent
# rust default.
measured = str(CLASSIFICATION_SIDES.get(
eid.split(":", 1)[1] if ":" in eid else eid, "") or "").upper()
if eid.startswith("contract:"):
lang = "n/a"
elif kind == "rust-crate":
lang = "rust"
elif kind == "go-surface":
lang = "go"
elif kind == "workflow" or kind == "config":
lang = "n/a"
elif kind == "deployment_surface":
lang = "go"
elif measured == "RUST":
lang = "rust"
elif measured == "GO":
lang = "go"
elif measured == "TUI-LAST":
lang = "python-tui (Wave 6)"
elif measured == "TEST-INFRA" or measured == "RETIRES":
lang = "test-infra" if measured == "TEST-INFRA" else "retires"
elif "tui" in eid:
lang = "python-tui (Wave 6)"
elif any(h in eid for h in GO_HINTS):
lang = "go (name hint)"
elif any(h in eid for h in RUST_HINTS):
lang = "rust (name hint)"
elif kind == "module":
lang = "unclassified"
elif kind == "subsystem":
# A subsystem is a CONTAINER — its language is its members'
# majority side per the measured dichotomy. The evidence map is
# classification.json (measured, 174 modules; honest note: newer
# files may be unclassified, so the count of classified members
# rides the verdict). Members arrive as belongs_to relationships
# whose from-ids carry module:<name> — map through classification.
members = [
r.get("from", "").split(":", 1)[1]
for r in doc.get("relationships", [])
if r.get("type") == "belongs_to" and r.get("to") == eid
and r.get("from", "").startswith("module:")
]
sides = [
str(CLASSIFICATION_SIDES.get(m) or "").upper()
for m in members
]
rust = sides.count("RUST")
go = sides.count("GO")
if rust and go:
lang = f"mixed (rust {rust} / go {go} members)"
elif rust:
lang = "rust"
elif go:
lang = "go"
else:
lang = "unassessed"
else:
lang = "unassessed"
e.setdefault("identities", {})["language"] = lang
if lang != "unassessed":
placed += 1
return placed
def _normalize_discovery_ids(doc: dict) -> int:
"""Migrate the old unqualified contract references, preserving evidence.
A file path (or 'suite') is not a module ID. Only migrate the malformed
module records produced by the earlier discovery projector; leave all
other open-world entity classes alone.
"""
renamed = {}
observed = {
eid for _, entities in _contract_discoveries()
for eid, _, provenance in entities if provenance == "observed"
}
for e in doc.get("entities", []):
if (e.get("kind") == "module" and ":" not in e.get("id", "")
and any(ref.startswith("contract-discovery:")
for ref in e.get("evidence_refs", []))):
old = e["id"]
e["id"] = f"construction-surface:{old}"
e["kind"] = "construction-surface"
e.setdefault("identities", {})["source_ref"] = old
renamed[old] = e["id"]
if e.get("kind") == "construction-surface" and e.get("id", "").startswith("construction-surface:"):
# Earlier code promoted every *candidate* to PRESENT. Undo only
# that unsupported claim; an actually observed surface retains it.
if e["id"].split(":", 1)[1] not in observed:
e["maturity"] = "DECLARED"
e["tags"] = [tag for tag in e.get("tags", []) if tag != "code"]
for rel in doc.get("relationships", []):
for endpoint in ("from", "to"):
if rel.get(endpoint) in renamed:
rel[endpoint] = renamed[rel[endpoint]]
return len(renamed)
def _apply_contract_discoveries(doc: dict) -> int:
"""Contract-discovery write-back (issue #2465 addition 2): entities
DISCOVERED by closed contracts become modeled spine entities — the
spine learns what construction actually built. Doc-level transform,
applied to BOTH cores' output. The CANDIDATE law holds: only CLOSED
contracts write back."""
placed = 0
for cid, entities in _contract_discoveries():
for eid, kind, provenance in entities:
before = len(doc.get("entities", []))
if kind == "construction-surface":
eid = f"construction-surface:{eid}"
add_entity(doc, id=eid, kind=kind,
tags=["contract-discovery"],
identities={"source_ref": eid.split(":", 1)[1]} if kind == "construction-surface" else None,
evidence_refs=[f"contract-discovery:{cid}"],
maturity="PRESENT" if provenance == "observed" else "DECLARED")
if len(doc.get("entities", [])) > before:
placed += 1
else:
placed += 0 # high-water merge — no new entity, still evidence
return placed
def _contract_discoveries():
"""Closed contracts' DISCOVERED entities (issue #2465 addition 2):
expected_new_observed + candidate corrections, gathered from the
scaffold store. Returns [(contract_id, [(entity_id, kind), ...])]."""
try:
doc = json.loads((ROOT / "store" / "scaffold" / "current.json").read_text())
except (OSError, json.JSONDecodeError):
return []
out = []
for e in doc.get("entities", []):
cid = e.get("id", "")
if not cid.startswith("contract:") or e.get("phase") != "closed":
continue
q = e.get("ext", {}).get("contract_quality", {})
found = []
# expected-new surfaces observed at close (REAL delivered entities)
for eid in q.get("expected_new_observed", []):
kind = eid.split(":", 1)[0] if ":" in eid else "construction-surface"
if kind in ("rust-crate", "go-surface", "config", "workflow", "module"):
found.append((eid, kind, "observed"))
elif kind == "construction-surface":
found.append((eid, kind, "observed"))
# candidate corrections: the closure flagged them for modeling
for cand in q.get("candidate_corrections", []):
eid = cand.get("entity", "")
kind = eid.split(":", 1)[0] if ":" in eid else "construction-surface"
if eid and kind in ("rust-crate", "go-surface", "config", "workflow", "module", "construction-surface"):
found.append((eid, kind, "candidate"))
if found:
out.append((cid[9:], found))
return out
+82 -2
View File
@@ -20,6 +20,33 @@ HOT_THRESHOLD = 7 # accessed within 7 days = hot
WARM_THRESHOLD = 30 # accessed within 30 days = warm
# > 30 days = cold
def _core():
"""The Rust cognition_core when available (strangler: Python fallback is
load-bearing). RUNE_COGNITION_CORE=python pins the fallback."""
return None if cc_loader_pin() else _cc_probe()
def _cc_probe():
from rune import cc_loader as _cl
try:
return _cl if _cl.available() else None
except Exception: # noqa: BLE001, S110 — loader probe never crashes the fallback
return None
def cc_loader_pin() -> bool:
"""The env pin: RUNE_COGNITION_CORE=python → kernels OFF (shared probe).
"""
import os
return os.environ.get("RUNE_COGNITION_CORE", "auto") == "python"
def _py_core_now() -> str:
"""The injected clock (iso Z) — module-level for the kernel boundary."""
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
# Tier storage characteristics
TIER_CONFIG = {
"hot": {
@@ -56,7 +83,24 @@ class TierManager:
"""Determine the tier for an entry based on its access patterns.
Returns 'hot', 'warm', or 'cold'.
Delegates to the Rust kernel when built; the Python body below is
the parity oracle (W3.4: identical thresholds injected, naive
timestamps refuse per the PARITY TRAP law).
"""
core = _core()
if core is not None:
try:
from rune import cc_loader as _cl
raw = _cl.tier_get(entry, _py_core_now(),
float(HOT_THRESHOLD), float(WARM_THRESHOLD))
return str(raw)
except Exception: # noqa: BLE001, S110 — kernel failure → oracle, never a broken call
pass
return self._py_get_tier(entry)
def _py_get_tier(self, entry: dict) -> str:
"""Python parity oracle (W3.4)."""
wash_count = entry.get("wash_count", 0) or 0
last_accessed = entry.get("last_accessed")
rock_status = entry.get("rock_status", "washable")
@@ -88,7 +132,26 @@ class TierManager:
return "warm"
def promote(self, entry: dict) -> str:
"""Promote an entry to a higher tier. Returns new tier."""
"""Promote an entry to a higher tier. Returns new tier.
Delegates to the Rust kernel when built (Python oracle below)."""
core = _core()
if core is not None:
try:
from rune import cc_loader as _cl
# The kernel's promote/demote take the FULL ENTRY (plus
# thresholds + clock) — not a tier string. They recompute
# the current tier internally, so a tier-string call was
# silently landing on defaults (the live probe caught it).
raw = _cl.tier_promote(entry, _py_core_now(),
float(HOT_THRESHOLD), float(WARM_THRESHOLD))
return str(raw)
except Exception: # noqa: BLE001, S110 — kernel failure → oracle fallback, intentional silence
pass
return self._py_promote(entry)
def _py_promote(self, entry: dict) -> str:
"""Python parity oracle."""
current = self.get_tier(entry)
if current == "cold":
return "warm"
@@ -97,7 +160,24 @@ class TierManager:
return "hot" # already hot
def demote(self, entry: dict) -> str:
"""Demote an entry to a lower tier. Returns new tier."""
"""Demote an entry to a lower tier. Returns new tier.
Delegates to the Rust kernel when built (Python oracle below)."""
core = _core()
if core is not None:
try:
from rune import cc_loader as _cl
# Same full-entry contract as promote; the kernel handles
# rock_status internally (rock never demotes).
raw = _cl.tier_demote(entry, _py_core_now(),
float(HOT_THRESHOLD), float(WARM_THRESHOLD))
return str(raw)
except Exception: # noqa: BLE001, S110 — kernel failure → oracle fallback, intentional silence
pass
return self._py_demote(entry)
def _py_demote(self, entry: dict) -> str:
"""Python parity oracle."""
current = self.get_tier(entry)
rock_status = entry.get("rock_status", "washable")
+6
View File
@@ -277,6 +277,12 @@ def _type_matches(value: object, expected: str) -> bool:
def validate_tool_request(request: ToolRequest) -> ToolRequest:
"""Validate a request against the central ``tool_executor.TOOLS`` schema."""
# Text-only model compatibility: aliases are NOT separate authorities.
# Canonicalize before schema, allowlist and approval checks, so bash
# never bypasses run_command's approval boundary.
alias = {"grep": "grep_files", "bash": "run_command"}.get(request.name)
if alias:
request = ToolRequest(request.call_id, alias, request.arguments, request.source)
definition = TOOL_INDEX.get(request.name)
if definition is None:
raise ValueError(f"unknown tool: {request.name}")
+127 -112
View File
@@ -84,76 +84,129 @@ def is_correction(text):
return False
def extract_topic(text):
"""Extract topic keywords from text. Deterministic."""
stopwords = {
"the",
"a",
"an",
"is",
"are",
"was",
"were",
"be",
"been",
"being",
"have",
"has",
"had",
"do",
"does",
"did",
"will",
"would",
"could",
"should",
"may",
"might",
"shall",
"can",
"to",
"of",
"in",
"for",
"on",
"with",
"at",
"by",
"from",
"as",
"into",
"through",
"during",
"before",
"after",
"this",
"that",
"these",
"those",
"it",
"its",
"what",
"which",
"who",
"how",
"when",
"where",
"why",
"and",
"or",
"but",
"not",
"no",
def _stopwords() -> list:
"""Gather seam (W3.4 delegation): the topic-extraction stopword table
as a SORTED list — sorted so JSON travel and kernel-side matching see
a deterministic order regardless of the set's iteration order."""
return sorted(_STOPWORDS)
_STOPWORDS = {
"the", "a", "an", "is", "are", "was", "were", "be", "been", "being",
"have", "has", "had", "do", "does", "did", "will", "would", "could",
"should", "may", "might", "shall", "can", "to", "of", "in", "for",
"on", "with", "at", "by", "from", "as", "into", "through", "during",
"before", "after", "this", "that", "these", "those", "it", "its",
"what", "which", "who", "how", "when", "where", "why", "and", "or",
"but", "not", "no",
}
def _tables() -> dict:
"""Gather seam: ALL regex pattern tables as data in one dict — the
exact contract the cc_witness_signals kernel consumes (parity-proven
per-table-row; regex_lite_search is the faithful subset for THESE
shapes). Sorted lists keep travel deterministic."""
return {
"stopwords": _stopwords(),
"correction": sorted(CORRECTION_PATTERNS),
"commitment": sorted([
r"\bI'?ll\s+(send|do|fix|build|check|update|create|write)\b",
r"\bI will\s+(send|do|fix|build|check|update|create|write)\b",
r"\blet me\s+(send|do|fix|build|check|update|create|write)\b",
r"\bremind me\b",
r"\bI promise\b",
r"\bI need to\b",
]),
"contradiction": sorted([r"\b(but|however|actually|wait|that contradicts)\b"]),
"preference": sorted([
r"\bI (prefer|like|love|hate|dislike)\b",
r"\bI'?m (not )?(a fan of|into|interested in)\b",
r"\b(don'?t|do not) (like|want|need)\b",
r"\b(always|never) (use|do|say)\b",
]),
"urgency": sorted([
r"\b(urgent|asap|immediately|now|quick|hurry)\b",
r"\b(deadline|due|overdue|late)\b",
r"\b(important|critical|crucial|vital)\b",
]),
"learning": sorted([
r"\b(learn|understand|explain|teach|show me)\b",
r"\b(how (does|do|did)|why (does|do|did)|what (is|are|was|were))\b",
r"\b(I don'?t (understand|know|get))\b",
]),
}
def _core():
"""The Rust cognition_core when available (strangler: Python fallback
load-bearing). RUNE_COGNITION_CORE=python pins the fallback."""
return None if cc_loader_pin() else _cc_probe()
def _cc_probe():
from rune import cc_loader as _cl
try:
return _cl if _cl.available() else None
except Exception: # noqa: BLE001, S110 — loader probe never crashes the fallback
return None
def cc_loader_pin() -> bool:
"""The env pin: RUNE_COGNITION_CORE=python → kernels OFF (shared probe).
"""
import os
return os.environ.get("RUNE_COGNITION_CORE", "auto") == "python"
def extract_topic(text):
"""Extract topic keywords from text. Deterministic.
Delegates to the kernel when built; Python oracle below."""
core = _core()
if core is not None:
try:
from rune import cc_loader as _cl
raw = _cl.witness_extract_topic(text, _stopwords())
return list(raw) if isinstance(raw, list) else list(raw or [])
except Exception: # noqa: BLE001, S110 — kernel failure → oracle, intentional silence
pass
words = re.findall(r"\w+", text.lower())
return [w for w in words if len(w) > 3 and w not in stopwords][:5]
return [w for w in words if len(w) > 3 and w not in _STOPWORDS][:5]
def _py_extract_topic(text):
"""Python parity oracle (W3.4)."""
words = re.findall(r"\w+", text.lower())
return [w for w in words if len(w) > 3 and w not in _STOPWORDS][:5]
def detect_signals(message, tool_error=None, task_status=None, recent_topics=None):
"""Tier 1: Reflex — extract signals from the turn. Pure Python, <1ms.
Returns dict of signals. Empty dict = nothing meaningful happened.
Delegates to the kernel when built (tables travel as data per the
REGEX-TABLE PORT LAW); Python oracle below is the parity authority.
"""
core = _core()
if core is not None:
try:
from rune import cc_loader as _cl
raw = _cl.witness_signals(message, _tables(), tool_error or "",
task_status or "", recent_topics or [])
if isinstance(raw, dict):
return {k: v for k, v in raw.items() if v not in (False, "")}
# non-dict → fall through to the oracle
except Exception: # noqa: BLE001, S110 — kernel failure → oracle, intentional silence
pass
return _py_detect_signals(message, tool_error, task_status, recent_topics)
def _py_detect_signals(message, tool_error=None, task_status=None,
recent_topics=None):
"""Python parity oracle (W3.4). Local tables via the gather seam."""
signals = {}
# Error signal
@@ -179,62 +232,24 @@ def detect_signals(message, tool_error=None, task_status=None, recent_topics=Non
signals["topic_drift"] = True
signals["new_topics"] = list(current_topics - recent_set)[:3]
# Commitment detection
commitment_patterns = [
r"\bI'?ll\s+(send|do|fix|build|check|update|create|write)\b",
r"\bI will\s+(send|do|fix|build|check|update|create|write)\b",
r"\blet me\s+(send|do|fix|build|check|update|create|write)\b",
r"\bremind me\b",
r"\bI promise\b",
r"\bI need to\b",
]
if message:
for pattern in commitment_patterns:
if re.search(pattern, message, re.IGNORECASE):
signals["commitment_detected"] = True
break
# Commitment detection (tables live in _tables() — the gather seam;
# the oracle reads the SAME table data the kernel receives)
for signal_name, table_name in (
("commitment_detected", "commitment"),
("preference_detected", "preference"),
("urgency_detected", "urgency"),
("learning_opportunity", "learning"),
):
if message:
for pattern in _tables().get(table_name, []):
if re.search(pattern, message, re.IGNORECASE):
signals[signal_name] = True
break
# Contradiction signal (simple: message contains "but" or "however" after a statement)
if message and re.search(r"\b(but|however|actually|wait|that contradicts)\b", message.lower()):
signals["possible_contradiction"] = True
# Preference detection
preference_patterns = [
r"\bI (prefer|like|love|hate|dislike)\b",
r"\bI'?m (not )?(a fan of|into|interested in)\b",
r"\b(don'?t|do not) (like|want|need)\b",
r"\b(always|never) (use|do|say)\b",
]
if message:
for pattern in preference_patterns:
if re.search(pattern, message, re.IGNORECASE):
signals["preference_detected"] = True
break
# Urgency detection
urgency_patterns = [
r"\b(urgent|asap|immediately|now|quick|hurry)\b",
r"\b(deadline|due|overdue|late)\b",
r"\b(important|critical|crucial|vital)\b",
]
if message:
for pattern in urgency_patterns:
if re.search(pattern, message, re.IGNORECASE):
signals["urgency_detected"] = True
break
# Learning opportunity detection
learning_patterns = [
r"\b(learn|understand|explain|teach|show me)\b",
r"\b(how (does|do|did)|why (does|do|did)|what (is|are|was|were))\b",
r"\b(I don'?t (understand|know|get))\b",
]
if message:
for pattern in learning_patterns:
if re.search(pattern, message, re.IGNORECASE):
signals["learning_opportunity"] = True
break
return signals
@@ -0,0 +1,217 @@
#!/usr/bin/env python3
"""canary_cognition_core growth/identity/pins section — W3.3 (contract
BUILDER-2026-10-05T07:19:27Z-cli, slice 3).
Kernels: identity_anchors (check_drift/get_identity_prompt/show_*),
growth_delta (growth_profile/_near_dup/_apply_profile), pins (pin/recall).
Run standalone.
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
from pathlib import Path
CRATE = Path(__file__).resolve().parent
REPO = CRATE.parents[2]
sys.path.insert(0, str(REPO / "src"))
PASS = FAIL = 0
def check(name, ok, detail=""):
global PASS, FAIL
if ok:
PASS += 1
print(f" ✓ {name}")
else:
FAIL += 1
print(f" ✗ {name} — {detail}")
def build():
env = dict(os.environ)
absolute = Path("/home/nick/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/bin")
rust = absolute if absolute.is_dir() else (
Path.home() / ".rustup/toolchains/stable-x86_64-unknown-linux-gnu/bin")
env["PATH"] = f"{rust}:{env.get('PATH', '')}"
return subprocess.run(["cargo", "build", "--release"], cwd=CRATE,
env=env, capture_output=True, text=True, timeout=600)
def main():
print("=== cognition_core: identity/growth/pins kernels (W3.3) ===")
r = build()
check("crate builds", r.returncode == 0, r.stderr[-240:])
if r.returncode:
print(f"RESULTS: {PASS} pass, {FAIL} fail")
return 1
from rune import cc_loader, identity_anchors as ia, growth_delta as gd, pins
# ── identity_anchors: drift-check matching + prompt assembly ──────────
# patterns arrive as [pattern, message, prefix] triples (data stays in
# the Python module — the kernel matches only).
triples = []
for prefix, table in (("DRIFT", ia._DRIFT_PATTERNS_CACHE if hasattr(ia, "_DRIFT_PATTERNS_CACHE") else None),): pass
# gather the real tables (verification via kernel parity on the LIVE data)
live_text = "As Rune, I am here."
issues_py = ia.check_drift(live_text)
triples = ia._pattern_triples() # the module's real gather seam
rs = cc_loader.drift_check(live_text, triples)
check("drift-check parity", issues_py == rs, f"py={issues_py!r} rs={rs!r}")
# every pattern from the module's tables is exercised verbatim
all_py = ia.check_drift("i am rune; you are nick. i believe it helped. "
"you're absolutely right, let me know.")
all_rs = cc_loader.drift_check("i am rune; you are nick. i believe it helped. "
"you're absolutely right, let me know.", triples)
check("drift-check full-table parity", all_py == all_rs,
f"py={all_py!r}\n rs={all_rs!r}")
prompt_py = ia._py_get_identity_prompt()
prompt_rs = cc_loader.identity_prompt(ia.PRONOUN_RULES, ia.SELF_AWARENESS,
ia.ANCHORS, ia.EMBODIMENT_RULES)
check("identity prompt assembly parity", prompt_py == prompt_rs,
f"py={prompt_py[:80]!r} rs={prompt_rs[:80]!r}")
# ── growth_delta: near-dup + profile ──────────────────────────────────
check("near-dup parity (identical)",
gd._py_near_dup("same change idea here", "same change idea here")
== cc_loader.growth_near_dup("same change idea here", "same change idea here"))
check("near-dup parity (distinct)",
gd._py_near_dup("alpha topic", "completely different beta")
== cc_loader.growth_near_dup("alpha topic", "completely different beta"))
py_prof = gd._py_growth_profile(200)
state = gd._load_deltas()
order = sorted(gd._PROFILE_ORDER.items(), key=lambda kv: kv[1])
rs_prof = cc_loader.growth_profile(state, order, gd.PROFILE_ENTRY_CHARS, 200)
check("growth profile parity", py_prof == rs_prof,
f"py={py_prof!r} rs={rs_prof!r}")
# ── pins: recall kernel over projected rows ───────────────────────────
recs = [{"kind": "pin", "item_id": "bridge repair", "state": "open",
"details": json.dumps({"question": "who?", "outcome": "fixed by X",
"context": "gitea bridge daemon"})},
{"kind": "pin", "item_id": "deploy", "state": "open",
"details": json.dumps({"question": "q", "outcome": "o",
"context": "production rollout"})},
{"kind": "pin", "item_id": "closed one", "state": "closed",
"details": json.dumps({"context": "bridge"})}]
py_pins = pins._py_pin_recall(recs, "bridge", 4)
rs_pins = cc_loader.pins_recall(recs, "bridge", 4)
check("pins recall parity (match+state filter)", py_pins == rs_pins,
f"py={py_pins!r} rs={rs_pins!r}")
check("pins empty-context abstention",
cc_loader.pins_recall(recs, "", 4) == [])
# ── tier kernels (W3.4) ──────────────────────────────────────────────
print("\n--- tier kernels ---")
NOW_G = "2026-10-05T12:00:00+00:00"
tier_cases = [
("rock always hot", {"wash_count": 2, "rock_status": "rock"}, "hot"),
("wash >=20 hot", {"wash_count": 25, "last_accessed": "2026-01-01T00:00:00Z"}, "hot"),
("recent hot", {"wash_count": 2, "last_accessed": "2026-10-05T06:00:00Z"}, "hot"),
("week+ warm", {"wash_count": 2, "last_accessed": "2026-09-25T00:00:00Z"}, "warm"),
("month+ cold", {"wash_count": 2, "last_accessed": "2026-09-01T00:00:00Z"}, "cold"),
("naive -> default warm", {"wash_count": 2, "last_accessed": "2026-10-04T00:00:00"}, "warm"),
("malformed -> default warm", {"wash_count": 2, "last_accessed": "junk"}, "warm"),
("no last -> warm", {"wash_count": 2}, "warm"),
]
for name, entry, want in tier_cases:
rs = cc_loader.tier_get(entry, NOW_G)
check(f"tier {name} -> {want}", rs == want, f"got {rs!r}")
check("promote cold->warm",
cc_loader.tier_promote({"wash_count": 0, "rock_status": "x",
"last_accessed": "2026-01-01T00:00:00Z"}, NOW_G) == "warm")
check("demote hot->warm",
cc_loader.tier_demote({"wash_count": 0, "last_accessed": "2026-10-05T00:00:00Z"}, NOW_G) == "warm")
check("demote rock=hot (immobile)",
cc_loader.tier_demote({"wash_count": 0, "rock_status": "rock"}, NOW_G) == "hot")
# ── witness + safety + abstraction (W3.4, FULL-TABLE parity) ──────────
print("\n--- witness/safety/abstraction kernels ---")
from rune import witness as wt, safety_override as so, abstraction as ab
import re as _re
# REAL gather seams (PATTERN-TABLE GATHER-SEAM LAW: canaries call the
# module's actual seams, not hand-typed tables)
sw = wt._stopwords()
topics_py = wt._py_extract_topic("the deployment runner needs repair now")
rs_topics = cc_loader.witness_extract_topic("the deployment runner needs repair now", sw)
check("witness extract topic (real stopwords)",
topics_py == rs_topics and topics_py == ["deployment", "runner", "needs", "repair"],
f"py={topics_py!r} rs={rs_topics!r}"[:200])
signals_py = wt.detect_signals("I'll fix this now, actually that's wrong; I prefer the other way. urgent!")
tables = wt._tables()
rs_sigs = cc_loader.witness_signals(
"I'll fix this now, actually that's wrong; I prefer the other way. urgent!",
tables)
rs_sigs_f = {k: v for k, v in rs_sigs.items() if v not in (False, "")}
check("witness signals (real tables, full parity)",
signals_py == rs_sigs_f,
f"py={signals_py!r} rs={rs_sigs_f!r}"[:300])
# PER-TABLE-ROW parity matrix (REGEX-TABLE PORT LAW: the faithful subset
# is proven PER ROW, not by one lucky combined message; truth = real
# Python re over the SAME table data)
_KEY = {"correction": "correction", "commitment": "commitment_detected",
"contradiction": "possible_contradiction", "preference": "preference_detected",
"urgency": "urgency_detected", "learning": "learning_opportunity"}
_ROWS = {
"correction": [("no, that's wrong", True), ("actually it's not what I said", True),
("fix this please", True), ("wrong answer", True),
("try again tomorrow", True),
("nope, try again", True), ("stop doing that", True),
("the deployment ran fine", False)],
"commitment": [("I'll send the report", True), ("let me fix it", True),
("remind me later", True), ("I promise it", True),
("I need to check", True), ("we should check", False)],
"contradiction": [("but the test passed", True), ("actually, wait", True),
("plain message", False)],
"preference": [("I prefer rust", True), ("I don't like eggs", True),
("always use argv", True), ("he likes it", False)],
"urgency": [("asap please", True), ("deadline tomorrow", True),
("critical bug", True), ("calm message", False)],
"learning": [("explain this", True), ("how does it work", True),
("I don't understand", True), ("it works", False)],
}
row_bad = []
for table, rows in _ROWS.items():
for msg, expect in rows:
exp = any(_re.search(p, msg, _re.IGNORECASE) for p in tables[table])
py = wt._py_detect_signals(msg)
got = bool(py.get(_KEY[table]))
rs = {k: v for k, v in cc_loader.witness_signals(msg, tables).items()
if v not in (False, "")}
rs_got = bool(rs.get(_KEY[table]))
if not (exp == got == rs_got == expect):
row_bad.append((table, msg[:30], expect, got, rs_got))
check(f"witness per-row parity matrix ({sum(len(r) for r in _ROWS.values())} rows)",
not row_bad, f"{row_bad[:3]!r}"[:300])
params = cc_loader.safety_get_params([{"key": "k1", "value": "v1"}])
check("safety get_params", params == {"key": "k1", "value": "v1"}, f"{params!r}")
bumped = cc_loader.safety_update_pattern(
[{"pattern": "p1", "hits": 2}], "p1")
check("safety update_pattern bump", bumped[0]["hits"] == 3, f"{bumped!r}")
new = cc_loader.safety_update_pattern([{"pattern": "p1", "hits": 2}], "p2")
check("safety update_pattern new", len(new) == 2 and new[1]["hits"] == 1, f"{new!r}")
facts = cc_loader.abstraction_extract_facts(
"The runner needs repair. The store is fine.", [], 10)
check("abstraction extract_facts", len(facts) == 2, f"{facts!r}"[:200])
print("\n" + ("=" * 47))
print(f"\nRESULTS: {PASS} pass, {FAIL} fail")
return 1 if FAIL else 0
if __name__ == "__main__":
raise SystemExit(main())
+598
View File
@@ -395,3 +395,601 @@ pub fn pins_recall(pins: &[Json], term: &str, limit: usize) -> Vec<Json> {
}
out
}
// ── tier_manager kernels (W3.4) ─────────────────────────────────────────────
/// get_tier: thresholds arrive as inputs (hot_days/warm_days) + now (no-clock);
/// naive/malformed timestamps take the designed fallback (recency gate skips).
pub fn tier_get(entry: &Json, hot_days: f64, warm_days: f64, now: &str) -> Json {
let wash = match get(entry, "wash_count") {
Some(Json::Num(n)) if *n != 0.0 => *n,
_ => 0.0,
};
let rock = match get(entry, "rock_status") {
Some(Json::Str(s)) => s.as_str(),
_ => "washable",
};
if rock == "rock" { return Json::Str("hot".into()); }
if wash >= 20.0 { return Json::Str("hot".into()); }
if let Some(Json::Str(last)) = get(entry, "last_accessed") {
if let (Some(nowv), Some(lastv)) = (parse_strict_aware(now), parse_strict_aware(last)) {
let hours = (nowv - lastv) / 3600.0;
if hours < hot_days * 24.0 { return Json::Str("hot".into()); }
if hours < warm_days * 24.0 { return Json::Str("warm".into()); }
return Json::Str("cold".into());
}
}
Json::Str("warm".into())
}
pub fn parse_strict_aware(s: &str) -> Option<f64> {
let b = s.as_bytes();
if b.len() < 19 { return None; }
let num = |a: usize, z: usize| -> Option<i64> { s.get(a..z)?.parse::<i64>().ok() };
let (y, mo, d, h, mi, se) = (num(0,4)?, num(5,7)?, num(8,10)?, num(11,13)?, num(14,16)?, num(17,19)?);
let mut i = 19;
while i < b.len() && b[i] != b'Z' && b[i] != b'+' && b[i] != b'-' { i += 1; }
let rest = s.get(i..)?;
if rest.is_empty() { return None; }
let off = if rest == "Z" { 0 }
else if rest.len() >= 6 {
let oh = rest.get(1..3)?.parse::<i64>().ok()?;
let om = rest.get(4..6)?.parse::<i64>().ok()?;
let x = oh*3600 + om*60;
if rest.as_bytes()[0] == b'-' { -x } else { x }
} else { return None; };
Some((days_from_civil(y, mo, d) * 86400 + h*3600 + mi*60 + se - off) as f64)
}
fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
let y = if m <= 2 { y - 1 } else { y };
let era = if y >= 0 { y } else { y - 399 } / 400;
let yoe = y - era * 400;
let mp = (m + 9) % 12;
let doy = (153 * mp + 2) / 5 + d - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146097 + doe - 719468
}
pub fn tier_promote(entry: &Json, hot_days: f64, warm_days: f64, now: &str) -> Json {
let current = match tier_get(entry, hot_days, warm_days, now) {
Json::Str(s) => s, _ => String::new(),
};
Json::Str(if current == "cold" { "warm".to_string() } else { "hot".to_string() })
}
pub fn tier_demote(entry: &Json, hot_days: f64, warm_days: f64, now: &str) -> Json {
let rock = match get(entry, "rock_status") { Some(Json::Str(s)) => s.as_str(), _ => "washable" };
if rock == "rock" { return Json::Str("hot".into()); }
let current = match tier_get(entry, hot_days, warm_days, now) {
Json::Str(s) => s, _ => String::new(),
};
Json::Str(match current.as_str() {
"hot" => "warm".to_string(), "warm" => "cold".to_string(),
_ => "cold".to_string() })
}
// ── witness kernels (W3.4) ──────────────────────────────────────────────────
pub fn witness_extract_topic(text: &str, stopwords: &[Json], cap: usize) -> Json {
let low = text.to_lowercase();
let sw: Vec<&str> = stopwords.iter().filter_map(|x| match x {
Json::Str(s) => Some(s.as_str()), _ => None }).collect();
let mut out: Vec<String> = vec![];
let mut cur = String::new();
for ch in low.chars() {
if ch.is_ascii_alphanumeric() || ch == '_' { cur.push(ch); }
else {
if !cur.is_empty() {
let w = std::mem::take(&mut cur);
if w.chars().count() > 3 && !sw.contains(&w.as_str()) && out.len() < cap {
out.push(w);
}
}
}
}
if !cur.is_empty() && cur.chars().count() > 3 && !sw.contains(&cur.as_str()) && out.len() < cap {
out.push(cur);
}
Json::Arr(out.into_iter().map(Json::Str).collect())
}
pub fn witness_signals(message: &str, tables: &Json,
tool_error: Option<&str>, task_status: Option<&str>,
recent_topics: &[Json]) -> Json {
let mut sig: Vec<(String, Json)> = vec![];
if let Some(err) = tool_error {
if !err.is_empty() {
sig.push(("error".into(), Json::Bool(true)));
sig.push(("error_text".into(), Json::Str(err.chars().take(200).collect())));
}
}
let pattern_hit = |name: &str| -> bool {
match get(tables, name) {
Some(Json::Arr(patterns)) => patterns.iter().any(|p| match p {
Json::Str(pat) => regex_lite_search(pat, message),
_ => false }),
_ => false,
}
};
if !message.is_empty() && pattern_hit("correction") {
sig.push(("correction".into(), Json::Bool(true)));
let sw: Vec<Json> = match get(tables, "stopwords") {
Some(Json::Arr(x)) => x.clone(), _ => vec![] };
sig.push(("corrected_topic".into(), witness_extract_topic(message, &sw, 5)));
}
if let Some(st) = task_status {
sig.push(("completion".into(), Json::Str(st.to_string())));
}
if !message.is_empty() && !recent_topics.is_empty() {
let sw: Vec<Json> = match get(tables, "stopwords") {
Some(Json::Arr(x)) => x.clone(), _ => vec![] };
if let Json::Arr(cur) = witness_extract_topic(message, &sw, 5) {
let cur_set: Vec<&str> = cur.iter().filter_map(|x| match x {
Json::Str(s) => Some(s.as_str()), _ => None }).collect();
let recent_set: Vec<&str> = recent_topics.iter().filter_map(|x| match x {
Json::Str(s) => Some(s.as_str()), _ => None }).collect();
let overlap = cur_set.iter().filter(|w| recent_set.contains(w)).count();
if !cur_set.is_empty() && (overlap as f64) / (cur_set.len() as f64) < 0.3 {
sig.push(("topic_drift".into(), Json::Bool(true)));
let new_topics: Vec<Json> = cur_set.iter()
.filter(|w| !recent_set.contains(w)).take(3)
.map(|w| Json::Str(w.to_string())).collect();
sig.push(("new_topics".into(), Json::Arr(new_topics)));
}
}
}
for (signal_name, table_name) in [
("commitment_detected", "commitment"),
("possible_contradiction", "contradiction"),
("preference_detected", "preference"),
("urgency_detected", "urgency"),
("learning_opportunity", "learning"),
] {
if !message.is_empty() && pattern_hit(table_name) {
sig.push((signal_name.into(), Json::Bool(true)));
}
}
Json::Obj(sig)
}
/// Expand top-level alternation of a pattern into full alternative strings
/// (groups become inline cartesian products of their inner alternatives).
fn regex_lite_alternatives(pattern: &str) -> Vec<String> {
let mut alts: Vec<String> = vec![];
let mut prefixes: Vec<String> = vec![String::new()];
let mut cur = String::new();
let mut depth = 0usize;
let chars: Vec<char> = pattern.to_lowercase().chars().collect();
for ch in chars {
match ch {
'(' => {
depth += 1;
if depth == 1 {
if !cur.is_empty() {
prefixes = prefixes
.iter()
.map(|p| format!("{p}{cur}"))
.collect();
cur.clear();
}
} else {
cur.push('(');
}
}
')' => {
depth = depth.saturating_sub(1);
if depth == 0 {
// closing a top-level group: its content is an
// alternation set — expand against the accumulated
// prefixes (cartesian). prefixes.len() may be 1.
let group_alts: Vec<String> = cur.split('|').map(String::from).collect();
let mut next = vec![];
for p in &prefixes {
for g in &group_alts {
next.push(format!("{p}{g}"));
}
}
prefixes = next;
cur.clear();
} else if depth >= 1 {
cur.push(')');
}
}
'|' if depth == 0 => {
for p in &prefixes {
alts.push(format!("{p}{cur}"));
}
cur.clear();
}
_ => cur.push(ch),
}
}
if depth == 0 {
for p in &prefixes {
alts.push(format!("{p}{cur}"));
}
} else {
// unbalanced group: treat literally
alts.push(cur);
}
alts.retain(|a| !a.is_empty());
if alts.is_empty() {
alts.push(String::new());
}
alts
}
/// Split ONE alternative into ordered PHRASE-SEGMENTS, each segment being
/// a set of variant strings (from `x?` optional chars — both shapes).
fn regex_lite_segments(alt: &str) -> Vec<Vec<String>> {
let mut segments: Vec<Vec<String>> = vec![];
// Word-boundary marker: \b immediately before a phrase prefixes its
// variants with US; \b immediately after suffixes them. The walker
// verifies the boundary on the real text and strips the marker.
const ANCHOR: char = '\u{1f}';
let mut cur: Vec<String> = vec![String::new()]; // variants of current phrase
let pc: Vec<char> = alt.chars().collect();
let mut j = 0usize;
while j < pc.len() {
let c = pc[j];
if c == '\\' && j + 1 < pc.len() {
let n = pc[j + 1];
match n {
'b' | 'B' => {
// anchor: if a phrase is open, this is a TRAILING
// anchor (suffix it); otherwise the NEXT phrase gets
// a LEADING anchor.
if cur.iter().any(|v| !v.is_empty()) {
for v in cur.iter_mut() {
v.push(ANCHOR);
}
segments.push(std::mem::take(&mut cur));
cur = vec![String::new()];
} else if let Some(last) = segments.last_mut() {
for v in last.iter_mut() {
v.insert(0, ANCHOR);
}
} else {
for v in cur.iter_mut() {
v.insert(0, ANCHOR);
}
}
}
's' => {
if cur.iter().any(|v| !v.is_empty()) {
segments.push(std::mem::take(&mut cur));
// ADJACENCY sentinel: \s between phrases means the
// next phrase starts within ONE char (a space) —
// not an unbounded gap. VT prefix marks it.
cur = vec!['\u{b}'.to_string()];
} else {
cur = vec!['\u{b}'.to_string()];
}
if j + 2 < pc.len() && matches!(pc[j + 2], '*' | '+' | '?') {
j += 3;
} else {
j += 2;
}
continue;
}
other => {
for v in cur.iter_mut() {
v.push(other)
}
}
}
j += 2;
continue;
}
match c {
'?' => {
// optional previous char: each variant gains a SHORTER twin
let twinned: Vec<String> = cur
.iter()
.flat_map(|v| {
let mut out = vec![v.clone()];
if !v.is_empty() {
out.push(v[..v.len() - 1].to_string());
}
out
})
.collect();
cur = twinned;
}
'.' | '[' => {
if cur.iter().any(|v| !v.is_empty()) {
segments.push(std::mem::take(&mut cur));
cur = vec![String::new()];
}
if c == '[' {
let mut k = j + 1;
while k < pc.len() && pc[k] != ']' {
k += 1;
}
j = k;
}
}
'*' | '+' => {} // gap quantifier
'^' | '$' => {}
c if c.is_alphanumeric() || c == '\'' || c == ' ' || c == '-' || c == '_' => {
for v in cur.iter_mut() {
v.push(c)
}
}
_ => {
if cur.iter().any(|v| !v.is_empty()) {
segments.push(std::mem::take(&mut cur));
cur = vec![String::new()];
}
}
}
j += 1;
}
if cur.iter().any(|v| !v.is_empty()) {
segments.push(cur);
}
segments
}
fn regex_lite_search(pattern: &str, text: &str) -> bool {
const ANCHOR: char = '\u{1f}';
let low = text.to_lowercase();
let is_word = |c: char| c.is_alphanumeric() || c == '\'' || c == '_';
for alt in regex_lite_alternatives(pattern) {
let segments = regex_lite_segments(&alt);
if segments.is_empty() {
continue;
}
// DFS: every segment contributes ONE of its variants, in order,
// gap-matched against the text. A leading ANCHOR on a variant
// requires a word boundary immediately before the match; a
// trailing ANCHOR requires one immediately after.
fn walk(segments: &[Vec<String>], low: &str, cursor: usize,
is_word: &dyn Fn(char) -> bool) -> bool {
const ADJ: char = '\u{b}';
if segments.is_empty() {
return true;
}
for raw in &segments[0] {
let mut left_anchor = false;
let mut right_anchor = false;
let mut adjacent = false;
let mut variant = raw.as_str();
if variant.starts_with(ANCHOR) {
left_anchor = true;
variant = &variant[1..];
}
if variant.starts_with(ADJ) {
adjacent = true;
variant = &variant[1..];
}
if variant.ends_with(ANCHOR) {
right_anchor = true;
variant = &variant[..variant.len() - 1];
}
if variant.is_empty() {
let ok_left = !left_anchor
|| cursor == 0
|| !is_word(low[cursor - 1..].chars().next().unwrap());
if ok_left && walk(&segments[1..], low, cursor, is_word) {
return true;
}
continue;
}
let mut from = cursor;
loop {
match low[from..].find(variant) {
Some(ix) => {
let start = from + ix;
let end = start + variant.len();
let left_ok = !left_anchor
|| (start == 0
|| !is_word(low[start - 1..].chars().next().unwrap()));
let right_ok = !right_anchor
|| (end == low.len()
|| !is_word(low[end..].chars().next().unwrap()));
let adj_ok = !adjacent || start - from <= 1;
if left_ok && right_ok && adj_ok
&& walk(&segments[1..], low, end, is_word)
{
return true;
}
from = start + 1;
if from >= low.len() {
break;
}
}
None => break,
}
}
}
false
}
if walk(&segments, &low, 0, &is_word) {
return true;
}
}
false
}
// ── safety_override kernels (W3.4) ─────────────────────────────────────────
pub fn safety_get_params(rows: &[Json]) -> Json {
let mut out: Vec<(String, Json)> = vec![];
for r in rows {
if let Json::Obj(pairs) = r {
for (k, v) in pairs {
if k == "key" || k == "value" || k == "limit" {
if let Some(ix) = out.iter().position(|(x, _)| x == k) {
out[ix].1 = v.clone();
} else {
out.push((k.clone(), v.clone()));
}
}
}
}
}
Json::Obj(out)
}
pub fn safety_update_pattern(rows: &[Json], pattern: &str) -> Vec<Json> {
let mut out = rows.to_vec();
for r in out.iter_mut() {
if matches!(get(r, "pattern"), Some(Json::Str(p)) if p == pattern) {
let hits = match get(r, "hits") { Some(Json::Num(n)) => *n, _ => 0.0 };
if let Json::Obj(pairs) = r {
if let Some(ix) = pairs.iter().position(|(k, _)| k == "hits") {
pairs[ix].1 = Json::Num(hits + 1.0);
} else {
pairs.push(("hits".into(), Json::Num(1.0)));
}
}
return out;
}
}
out.push(Json::Obj(vec![
("pattern".into(), Json::Str(pattern.to_string())),
("hits".into(), Json::Num(1.0)),
]));
out
}
// ── abstraction kernels (W3.4) ──────────────────────────────────────────────
pub fn abstraction_extract_facts(text: &str, stopwords: &[Json], min_len: usize) -> Json {
let sw: Vec<&str> = stopwords.iter().filter_map(|x| match x {
Json::Str(s) => Some(s.as_str()), _ => None }).collect();
let mut facts: Vec<Json> = vec![];
for sentence in text.split(|c: char| c == '.' || c == '\n') {
let t = sentence.trim();
if t.chars().count() < min_len { continue; }
let words: Vec<String> = t.to_lowercase().split_whitespace()
.map(|w| w.to_string()).collect();
let content = words.iter().filter(|w| !sw.contains(&w.as_str())).count();
if content == 0 { continue; }
facts.push(Json::Obj(vec![
("text".into(), Json::Str(t.to_string())),
("words".into(), Json::Num(words.len() as f64)),
("content_words".into(), Json::Num(content as f64)),
]));
}
Json::Arr(facts)
}
// ── consolidation kernels (W4: memory_consolidation port) ────────────────
const CONSOLIDATION_ROCK: f64 = 0.0;
const CONSOLIDATION_ESTABLISHED: f64 = 0.2;
const CONSOLIDATION_WASHABLE: f64 = 0.5;
const WASH_THRESHOLD_FULL: i64 = 20;
const WASH_THRESHOLD_PARTIAL: i64 = 10;
pub fn consolidation_compression_ratio(wash_count: i64, rock_status: &str) -> f64 {
if rock_status == "rock" {
return CONSOLIDATION_ROCK;
}
if rock_status == "established" {
return CONSOLIDATION_ESTABLISHED;
}
let base = CONSOLIDATION_WASHABLE;
if wash_count >= WASH_THRESHOLD_FULL {
(base * 0.2).max(0.1)
} else if wash_count >= WASH_THRESHOLD_PARTIAL {
(base * 0.5).max(0.2)
} else {
base
}
}
pub fn consolidation_compress_text(text: &str, ratio: f64) -> String {
if ratio <= 0.0 {
return text.to_string();
}
if ratio >= 1.0 {
return String::new();
}
let keep_chars = ((text.chars().count() as f64) * (1.0 - ratio)) as usize;
let keep_chars = keep_chars.max(20.min(text.chars().count()));
let compressed: String = text.chars().take(keep_chars).collect();
if compressed.len() < text.len() {
format!("{}...", compressed.trim_end())
} else {
compressed
}
}
pub fn consolidation_should_warn(wash_count: i64, rock_status: &str, text: &str) -> bool {
if wash_count >= 10 {
return true;
}
if rock_status == "established" || rock_status == "rock" {
return text.chars().count() > 200;
}
false
}
/// Consolidate a memory entry into a ConsolidatedKnowledge record (JSON).
/// Takes: text, wash_count, rock_status, score, entry_id (optional).
/// Returns: {"id", "source", "category", "content", "confidence",
/// "created_at", "last_used", "wash_count", "entry_id", "tags"}
pub fn consolidation_memory(text: &str, score: f64, wash_count: i64,
entry_id: Option<i64>, now: &str) -> Json {
let ratio = consolidation_compression_ratio(wash_count, "washable");
let content = consolidation_compress_text(text, ratio);
let id = match entry_id {
Some(eid) => Json::Str(format!("memory-{}", eid)),
None => Json::Str(format!("memory-{}", {
// stable hash: FNV-1a
let mut h: u64 = 0xcbf29ce484222325;
for b in text.as_bytes() {
h ^= *b as u64;
h = h.wrapping_mul(0x100000001b3);
}
h % 10000
})),
};
let eid_json = match entry_id {
Some(eid) => Json::Num(eid as f64),
None => Json::Null,
};
Json::Obj(vec![
("id".into(), id),
("source".into(), Json::Str("memory".into())),
("category".into(), Json::Str("lesson".into())),
("content".into(), Json::Str(content)),
("confidence".into(), Json::Num(score)),
("created_at".into(), Json::Str(now.into())),
("last_used".into(), Json::Str(now.into())),
("use_count".into(), Json::Num(0.0)),
("wash_count".into(), Json::Num(wash_count as f64)),
("entry_id".into(), eid_json),
("tags".into(), Json::Arr(vec![])),
])
}
/// Consolidate a warm neuron into a ConsolidatedKnowledge record.
/// Takes: slug, body, importance, triggers (JSON array), wash_count, now.
pub fn consolidation_neuron(slug: &str, body: &str, importance: f64,
triggers: &[Json], wash_count: i64,
entry_id: Option<i64>, now: &str) -> Json {
let ratio = consolidation_compression_ratio(wash_count, "washable");
let first_line = consolidation_compress_text(body, ratio);
let eid_json = match entry_id {
Some(eid) => Json::Num(eid as f64),
None => Json::Null,
};
Json::Obj(vec![
("id".into(), Json::Str(format!("neuron-{}", slug))),
("source".into(), Json::Str("neuron".into())),
("category".into(), Json::Str("fact".into())),
("content".into(), Json::Str(first_line)),
("confidence".into(), Json::Num(importance)),
("created_at".into(), Json::Str(now.into())),
("last_used".into(), Json::Str(now.into())),
("use_count".into(), Json::Num(0.0)),
("wash_count".into(), Json::Num(wash_count as f64)),
("entry_id".into(), eid_json),
("tags".into(), Json::Arr(triggers.to_vec())),
])
}
+120
View File
@@ -179,6 +179,126 @@ pub extern "C" fn cc_pins_recall(arg: *const c_char) -> *mut c_char {
envelope(result)
}
#[no_mangle]
pub extern "C" fn cc_tier_get(arg: *const c_char) -> *mut c_char {
let result = read_arg(arg).and_then(|t| arg_json(&t)).map(|a| {
let e = get(&a, "entry").cloned().unwrap_or(pyjson::Json::Obj(vec![]));
broker::tier_get(&e,
match get(&a, "hot_days") { Some(pyjson::Json::Num(n)) => *n, _ => 7.0 },
match get(&a, "warm_days") { Some(pyjson::Json::Num(n)) => *n, _ => 30.0 },
match get(&a, "now") { Some(pyjson::Json::Str(s)) => s.as_str(), _ => "" })
});
envelope(result)
}
#[no_mangle]
pub extern "C" fn cc_tier_promote(arg: *const c_char) -> *mut c_char {
let result = read_arg(arg).and_then(|t| arg_json(&t)).map(|a| {
let e = get(&a, "entry").cloned().unwrap_or(pyjson::Json::Obj(vec![]));
broker::tier_promote(&e,
match get(&a, "hot_days") { Some(pyjson::Json::Num(n)) => *n, _ => 7.0 },
match get(&a, "warm_days") { Some(pyjson::Json::Num(n)) => *n, _ => 30.0 },
match get(&a, "now") { Some(pyjson::Json::Str(s)) => s.as_str(), _ => "" })
});
envelope(result)
}
#[no_mangle]
pub extern "C" fn cc_tier_demote(arg: *const c_char) -> *mut c_char {
let result = read_arg(arg).and_then(|t| arg_json(&t)).map(|a| {
let e = get(&a, "entry").cloned().unwrap_or(pyjson::Json::Obj(vec![]));
broker::tier_demote(&e,
match get(&a, "hot_days") { Some(pyjson::Json::Num(n)) => *n, _ => 7.0 },
match get(&a, "warm_days") { Some(pyjson::Json::Num(n)) => *n, _ => 30.0 },
match get(&a, "now") { Some(pyjson::Json::Str(s)) => s.as_str(), _ => "" })
});
envelope(result)
}
#[no_mangle]
pub extern "C" fn cc_witness_extract_topic(arg: *const c_char) -> *mut c_char {
let result = read_arg(arg).and_then(|t| arg_json(&t)).map(|a| {
let text = match get(&a, "text") { Some(pyjson::Json::Str(s)) => s.clone(), _ => String::new() };
let sw: Vec<pyjson::Json> = match get(&a, "stopwords") { Some(pyjson::Json::Arr(x)) => x.clone(), _ => vec![] };
match broker::witness_extract_topic(&text, &sw, 5) {
pyjson::Json::Arr(v) => pyjson::Json::Arr(v),
other => other,
}
});
envelope(result)
}
#[no_mangle]
pub extern "C" fn cc_witness_signals(arg: *const c_char) -> *mut c_char {
let result = read_arg(arg).and_then(|t| arg_json(&t)).map(|a| {
let message = match get(&a, "message") { Some(pyjson::Json::Str(s)) => s.clone(), _ => String::new() };
let tables = get(&a, "tables").cloned().unwrap_or(pyjson::Json::Obj(vec![]));
let tool_error = match get(&a, "tool_error") { Some(pyjson::Json::Str(s)) if !s.is_empty() => Some(s.as_str()), _ => None };
let task_status = match get(&a, "task_status") { Some(pyjson::Json::Str(s)) if !s.is_empty() => Some(s.as_str()), _ => None };
let recent: Vec<pyjson::Json> = match get(&a, "recent_topics") { Some(pyjson::Json::Arr(x)) => x.clone(), _ => vec![] };
broker::witness_signals(&message, &tables, tool_error, task_status, &recent)
});
envelope(result)
}
#[no_mangle]
pub extern "C" fn cc_safety_get_params(arg: *const c_char) -> *mut c_char {
let result = read_arg(arg).and_then(|t| arg_json(&t)).map(|a| {
let rows: Vec<pyjson::Json> = match get(&a, "rows") { Some(pyjson::Json::Arr(x)) => x.clone(), _ => vec![] };
broker::safety_get_params(&rows)
});
envelope(result)
}
#[no_mangle]
pub extern "C" fn cc_safety_update_pattern(arg: *const c_char) -> *mut c_char {
let result = read_arg(arg).and_then(|t| arg_json(&t)).map(|a| {
let rows: Vec<pyjson::Json> = match get(&a, "rows") { Some(pyjson::Json::Arr(x)) => x.clone(), _ => vec![] };
let pat = match get(&a, "pattern") { Some(pyjson::Json::Str(s)) => s.clone(), _ => String::new() };
pyjson::Json::Arr(broker::safety_update_pattern(&rows, &pat))
});
envelope(result)
}
#[no_mangle]
pub extern "C" fn cc_abstraction_extract_facts(arg: *const c_char) -> *mut c_char {
let result = read_arg(arg).and_then(|t| arg_json(&t)).map(|a| {
let text = match get(&a, "text") { Some(pyjson::Json::Str(s)) => s.clone(), _ => String::new() };
let sw: Vec<pyjson::Json> = match get(&a, "stopwords") { Some(pyjson::Json::Arr(x)) => x.clone(), _ => vec![] };
let min_len = match get(&a, "min_len") { Some(pyjson::Json::Num(n)) => *n as usize, _ => 10 };
broker::abstraction_extract_facts(&text, &sw, min_len)
});
envelope(result)
}
#[no_mangle]
pub extern "C" fn cc_consolidation_memory(arg: *const c_char) -> *mut c_char {
let result = read_arg(arg).and_then(|t| arg_json(&t)).map(|a| {
let text = match get(&a, "text") { Some(pyjson::Json::Str(s)) => s.clone(), _ => String::new() };
let score = match get(&a, "score") { Some(pyjson::Json::Num(n)) => *n, _ => 0.5 };
let wc = match get(&a, "wash_count") { Some(pyjson::Json::Num(n)) => *n as i64, _ => 0 };
let eid = match get(&a, "entry_id") { Some(pyjson::Json::Num(n)) => Some(*n as i64), _ => None };
let now = match get(&a, "now") { Some(pyjson::Json::Str(s)) => s.clone(), _ => String::new() };
broker::consolidation_memory(&text, score, wc, eid, &now)
});
envelope(result)
}
#[no_mangle]
pub extern "C" fn cc_consolidation_neuron(arg: *const c_char) -> *mut c_char {
let result = read_arg(arg).and_then(|t| arg_json(&t)).map(|a| {
let slug = match get(&a, "slug") { Some(pyjson::Json::Str(s)) => s.clone(), _ => String::new() };
let body = match get(&a, "body") { Some(pyjson::Json::Str(s)) => s.clone(), _ => String::new() };
let importance = match get(&a, "importance") { Some(pyjson::Json::Num(n)) => *n, _ => 0.5 };
let triggers = match get(&a, "triggers") { Some(pyjson::Json::Arr(x)) => x.clone(), _ => vec![] };
let wc = match get(&a, "wash_count") { Some(pyjson::Json::Num(n)) => *n as i64, _ => 0 };
let eid = match get(&a, "entry_id") { Some(pyjson::Json::Num(n)) => Some(*n as i64), _ => None };
let now = match get(&a, "now") { Some(pyjson::Json::Str(s)) => s.clone(), _ => String::new() };
broker::consolidation_neuron(&slug, &body, importance, &triggers, wc, eid, &now)
});
envelope(result)
}
#[no_mangle]
pub extern "C" fn cc_free_string(ptr: *mut c_char) {
if !ptr.is_null() { unsafe { let _ = CString::from_raw(ptr); } }
@@ -0,0 +1,65 @@
use cognition_core::broker::parse_strict_aware;
#[test]
fn parses_aware() {
let v = parse_strict_aware("2026-10-05T12:00:00+00:00");
assert!(v.is_some(), "aware must parse");
let n = parse_strict_aware("2026-10-05T12:00:00");
assert!(n.is_none(), "naive must be refused");
}
#[test]
fn tier_recency_works() {
let e = cognition_core::pyjson::parse(
r#"{"wash_count": 2, "last_accessed": "2026-10-05T06:00:00+00:00"}"#).unwrap();
let t = cognition_core::broker::tier_get(&e, 7.0, 30.0, "2026-10-05T12:00:00+00:00");
assert!(format!("{}", cognition_core::pyjson::dumps(&t)).contains("hot"),
"expected hot, got {}", cognition_core::pyjson::dumps(&t));
}
#[test]
fn parse_components() {
let s = "2026-10-05T12:00:00+00:00";
let b = s.as_bytes();
assert_eq!(b.len(), 25);
// simulate the loop: i=19 is '+' → exits immediately → rest="+00:00"
let mut i = 19;
while i < b.len() && b[i] != b'Z' && b[i] != b'+' && b[i] != b'-' { i += 1; }
assert_eq!(i, 19, "offset starts immediately after seconds");
let rest = &s[i..];
assert_eq!(rest, "+00:00");
let v = parse_strict_aware(s);
assert!(v.is_some());
let val = v.unwrap();
// 2026-10-05T12:00:00Z epoch ≈ 1791201600 (verify ±1s tolerance)
assert!((val - 1791201600.0).abs() < 2.0, "epoch mismatch: {}", val);
}
#[test]
fn tier_decompose() {
use cognition_core::broker::parse_strict_aware;
let last = "2026-10-05T06:00:00+00:00";
let now = "2026-10-05T12:00:00+00:00";
let (l, n) = (parse_strict_aware(last), parse_strict_aware(now));
assert!(l.is_some() && n.is_some(), "both must parse");
let hours = (n.unwrap() - l.unwrap()) / 3600.0;
assert_eq!(hours, 6.0, "6h apart");
// so tier_get's recency branch must fire... check it does by feeding
// what the parse sees via a wash-hot case:
let e = cognition_core::pyjson::parse(r#"{"wash_count": 25}"#).unwrap();
let t = cognition_core::broker::tier_get(&e, 7.0, 30.0, now);
let s = cognition_core::pyjson::dumps(&t);
assert!(s.contains("hot"), "wash>=20 must be hot, got {}", s);
}
#[test]
fn tier_probe_row_shape() {
// Does the JSON fixture parse into the expected shape? get(entry,...)
// reads "last_accessed" — pyjson::Json::Obj pairs. Verify:
let e = cognition_core::pyjson::parse(
r#"{"wash_count": 2, "last_accessed": "2026-10-05T06:00:00+00:00"}"#)
.unwrap();
let la = cognition_core::broker::tier_get(&e, 7.0, 30.0,
"2026-10-05T12:00:00+00:00");
// instrument via a different route: promote → falls to the same get_tier
let s = cognition_core::pyjson::dumps(&la);
eprintln!("tier_get gave: {}", s);
}
File diff suppressed because it is too large. Load diff
+6946 -6922
View File
File diff suppressed because it is too large. Load diff
+2048 -504
View File
File diff suppressed because it is too large. Load diff
+41
View File
@@ -0,0 +1,41 @@
"""Exercise the Gitea auto-label script, not just its YAML shape."""
import shutil
import subprocess
from pathlib import Path
import pytest
import yaml
def test_duplicate_priority_reconciled_by_numeric_id(tmp_path):
node = shutil.which("node")
if node is None:
pytest.skip("node not installed")
workflow = yaml.safe_load((Path(__file__).parents[1] / ".gitea/workflows/auto-label.yml").read_text())
script = workflow["jobs"]["auto-label"]["steps"][0]["with"]["script"]
fixture = """
const labels = [{name:'P0 — critical',id:23},{name:'P2 — medium',id:25}];
const context = {payload:{action:'labeled',issue:{state:'open',number:2467,
title:'Scaffolding completion',body:'kind: feature\\nspine protocol'}},
repo:{owner:'conductor',repo:'rune'}};
const github = {rest:{issues:{
listLabelsOnIssue: async () => ({data:labels.map(x => ({...x}))}),
addLabels: async ({labels:names}) => {
for (const name of names) labels.push({name,id:100+labels.length});
}
}},request: async (route,{id}) => {
if (!route.includes('/labels/{id}') || typeof id !== 'number')
throw new Error('Gitea requires numeric label ID');
const index=labels.findIndex(x => x.id === id);
if (index < 0) throw new Error('missing label ID '+id);
labels.splice(index,1);
}};
"""
js = (fixture + "\n(async () => {\n" + script + "\n})().then(() => {\n"
+ "const priorities=labels.filter(x => /^P[0-3] — /.test(x.name));\n"
+ "if (priorities.length !== 1 || priorities[0].id !== 23) process.exitCode=1;\n"
+ "}).catch(e => {console.error(e);process.exitCode=1;});\n")
path = tmp_path / "priority.js"
path.write_text(js)
run = subprocess.run([node, str(path)], capture_output=True, text=True, timeout=10)
assert run.returncode == 0, run.stdout + run.stderr
+74
View File
@@ -0,0 +1,74 @@
"""consolidation delegation battery (W4): kernel + oracle parity, both
the memory and neuron paths, the drift-compression layering."""
from __future__ import annotations
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
from rune import memory_consolidation as mc # noqa: E402
def test_memory_oracle_basic():
rec = mc._consolidation_memory_oracle("The deployment runner needs repair.", 0.9, 5, 42)
assert rec["id"] == "memory-42"
assert rec["source"] == "memory"
assert rec["confidence"] == 0.9
assert rec["wash_count"] == 5
assert rec["entry_id"] == 42
assert rec["category"] == "lesson"
def test_memory_oracle_no_entry_id():
rec = mc._consolidation_memory_oracle("short text", 0.5, 0, None)
assert rec["entry_id"] is None
assert rec["id"].startswith("memory-")
def test_neuron_oracle_basic():
rec = mc._consolidation_neuron_oracle("test-slug", "The runner needs repair.", 0.7, ["deploy"], 15)
assert rec["id"] == "neuron-test-slug"
assert rec["source"] == "neuron"
assert rec["tags"] == ["deploy"]
def test_neuron_oracle_rock_no_compression():
"""Rock entries at wash >= 20 get minimal compression — content stays long."""
long_body = "This is a long body that should survive compression because it's rock-solid. " * 5
rec = mc._consolidation_neuron_oracle("rock", long_body, 0.9, [], 25)
assert len(rec["content"]) > len(long_body) // 2 # mostly preserved
def test_kernel_parity_memory():
"""The FFI kernel and the Python oracle produce the same content."""
core = mc._core()
if core is None:
pytest.skip("kernel unavailable")
text = "The deployment runner needs repair and the store is fine."
kernel = core.consolidation_memory(text, 0.9, 5, 42, "2026-10-06T00:00:00Z")
oracle = mc._consolidation_memory_oracle(text, 0.9, 5, 42)
assert kernel["content"] == oracle["content"], (kernel["content"], oracle["content"])
assert kernel["confidence"] == oracle["confidence"]
def test_kernel_parity_neuron():
core = mc._core()
if core is None:
pytest.skip("kernel unavailable")
body = "The deployment runner needs repair now urgently."
kernel = core.consolidation_neuron("test-slug", body, 0.7, ["deploy"], 15, None, "2026-10-06T00:00:00Z")
oracle = mc._consolidation_neuron_oracle("test-slug", body, 0.7, ["deploy"], 15)
assert kernel["content"] == oracle["content"], (kernel["content"], oracle["content"])
def test_delegated_produce_consolidated_knowledge():
"""The class methods return real ConsolidatedKnowledge objects."""
inst = mc.MemoryConsolidation.__new__(mc.MemoryConsolidation)
rec = inst.consolidate_memory("test text", 0.8, 3, None)
assert isinstance(rec, mc.ConsolidatedKnowledge)
assert rec.source == "memory"
+170
View File
@@ -6,6 +6,7 @@ import json
import os
import subprocess
import sys
from pathlib import Path
import pytest
@@ -585,3 +586,172 @@ def test_15u_discover_active_contract_migrated_to_interface(tmp_path):
# capabilities() advertises the new op
assert "discover_active_contract" in \
iface.capabilities()["state"]["operations"]
# ── T5.15 completion wave: stage_guards wired into transition ───────────────
def _guard_contract(iface, tmp_path):
"""A contract whose obligations declare a PATH guard and a failing
command guard — proving both BLOCK shapes."""
doc = iface.scaffold.load()
ss.add_entity(
doc, id="contract:guarded-1", kind="contract",
identities={
"objective": "guarded stage",
"verification_obligations": [
"guard:" + json.dumps({
"name": "artifact present", "kind": "path_exists",
"path": str(tmp_path / "artifact.txt"),
}),
],
},
evidence_refs=["e"],
)
iface.scaffold.commit(doc, what="seed guarded contract")
doc = iface.scaffold.load()
# move through the legal path so guards face verifying from building
sc.Scaffold.transition_contract(iface.scaffold, doc, "guarded-1", "approved",
evidence_ref="t")
sc.Scaffold.transition_contract(iface.scaffold, doc, "guarded-1", "building",
evidence_ref="t")
iface.scaffold.commit(doc, what="advance to building")
return "guarded-1"
def test_15f_transition_to_verifying_blocked_when_guard_fails(tmp_path):
iface = _iface(tmp_path)
cid = _guard_contract(iface, tmp_path)
env = iface.transition(cid, "verifying")
assert not env["success"]
assert env["errors"][0]["error"] == ci.Errors.VERIFICATION_FAILED
assert env["state"]["guard"]["verdict"] == "BLOCKED"
# phase UNCHANGED — the blocked stage does not move
doc = iface.scaffold.load()
c = iface.scaffold.contract(doc, cid)
assert c["phase"] == "building"
def test_15f_transition_passes_when_guard_satisfied(tmp_path):
iface = _iface(tmp_path)
cid = _guard_contract(iface, tmp_path)
(tmp_path / "artifact.txt").write_text("real artifact")
env = iface.transition(cid, "verifying")
assert env["success"], env["errors"]
doc = iface.scaffold.load()
assert iface.scaffold.contract(doc, cid)["phase"] == "verifying"
def test_15f_inline_guard_checks_override_obligations(tmp_path):
iface = _iface(tmp_path)
cid = _guard_contract(iface, tmp_path) # has the path guard, NOT satisfied
env = iface.transition(
cid, "verifying",
guard_checks=[{"name": "inline truth", "kind": "command",
"argv": [sys.executable, "-c", "print('ok')"]}],
)
assert env["success"], env["errors"]
assert iface.scaffold.contract(iface.scaffold.load(), cid)["phase"] == "verifying"
def test_15f_transition_to_building_runs_no_guards(tmp_path):
"""Completion-facing edges ONLY (verifying/closed): building→verifying
is guarded, but draft→approved passes freely even with obligations."""
iface = _iface(tmp_path)
doc = iface.scaffold.load()
ss.add_entity(doc, id="contract:guarded-2", kind="contract",
identities={"objective": "2"}, evidence_refs=["e"])
iface.scaffold.commit(doc, what="seed guarded-2")
cid = "guarded-2"
doc = iface.scaffold.load()
c = iface.scaffold.contract(doc, cid)
c["identities"]["verification_obligations"] = [
"guard:" + json.dumps({"name": "never", "kind": "path_exists",
"path": "/nonexistent/for-sure"})
]
iface.scaffold.commit(doc, what="attach guard")
env = iface.transition(cid, "approved") # NOT a completion edge
assert env["success"]
# ── T5.15 slice 3: programme_continuation wired into close() ────────────────
def _seed_programme(iface, programme_id, stage_contract_ids, tmp_path):
"""Persist a real Programme bound to the interface's scaffold store."""
from rune import programme_continuation as pc
base = Path(iface.scaffold.current).parent / pc.DEFAULT_PROGRAMME_AREA
prog = pc.Programme(programme_id=programme_id, objective="wave test")
for i, cid in enumerate(stage_contract_ids):
prog.stages.append(pc.ProgrammeStage(
stage_id=cid, objective=f"stage {i}", depends_on=[]))
prog.save(base)
return prog, base
def test_close_marks_programme_stage_complete_and_surfaces_continuation(tmp_path):
"""Closing a contract that is a stage of a persisted Programme marks
that stage COMPLETE and the envelope carries the continuation canary —
the programme's next eligible stage is surfaced, not guessed."""
from rune import programme_continuation as pc
iface = _iface(tmp_path)
env1 = _submit(iface, objective="wave stage one")
cid1 = env1["ids"]["contract_id"]
env2 = _submit(iface, objective="wave stage two")
cid2 = env2["ids"]["contract_id"]
# drive both through to verifying so close is legal
for cid in (cid1, cid2):
iface.transition(cid, "approved")
iface.transition(cid, "building")
iface.transition(cid, "verifying")
prog, base = _seed_programme(iface, "wave-x", [cid1, cid2], tmp_path)
env = iface.close(cid1, observed_evidence=[{"entity": "capability:exporter", "detail": "done"}])
assert env["success"], env["errors"]
cont = env["state"].get("programme_continuation")
assert cont, "close envelope must carry the programme continuation"
assert cont["programme_id"] == "wave-x"
assert cont["stage_marked_complete"] == cid1
reloaded = pc.Programme.load(base, "wave-x")
stage1 = next(s for s in reloaded.stages if s.stage_id == cid1)
assert stage1.state == pc.COMPLETE
assert cont["canary"]["verdict"] == "PROGRAMME_OPEN"
assert cont["canary"]["next_action"] == ("start", cid2)
def test_close_without_programme_has_no_continuation_block(tmp_path):
iface = _iface(tmp_path)
env = _submit(iface)
cid = env["ids"]["contract_id"]
iface.transition(cid, "approved")
iface.transition(cid, "building")
iface.transition(cid, "verifying")
env = iface.close(cid, observed_evidence=[{"entity": "capability:exporter", "detail": "done"}])
assert env["success"]
assert "programme_continuation" not in env["state"]
def test_close_programme_completion_verdict_surfaces(tmp_path):
"""Closing the LAST stage yields PROGRAMME_COMPLETE — the canary says
stop, the runner never guesses."""
iface = _iface(tmp_path)
env = _submit(iface)
cid = env["ids"]["contract_id"]
iface.transition(cid, "approved")
iface.transition(cid, "building")
iface.transition(cid, "verifying")
prog, base = _seed_programme(iface, "solo", [cid], tmp_path)
env = iface.close(cid, observed_evidence=[{"entity": "capability:exporter", "detail": "done"}])
cont = env["state"]["programme_continuation"]
assert cont["canary"]["verdict"] == "PROGRAMME_COMPLETE"
def test_two_submits_same_second_get_distinct_contract_ids(tmp_path):
"""Second-granularity timestamps collide when two needs are filed in
the same second (real builder-pair scenario) — ids must be distinct."""
iface = _iface(tmp_path)
e1 = _submit(iface, objective="wave stage one")
e2 = _submit(iface, objective="wave stage two")
assert e1["success"] and e2["success"], (e1["errors"], e2["errors"])
assert e1["ids"]["contract_id"] != e2["ids"]["contract_id"]
+48
View File
@@ -0,0 +1,48 @@
"""The PINNED-mode (RUNE_COGNITION_CORE=python) paths of the delegation
probes — the remaining uncovered lines in safety_override/abstraction/
tier_manager: the _cc_probe fallback, the pin check, and the stopword
gather seam. Coverage runs these under RUNE_COGNITION_CORE=python."""
from __future__ import annotations
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
from rune import abstraction as ab # noqa: E402
from rune import safety_override as so # noqa: E402
from rune import tier_manager as tm # noqa: E402
from rune import witness as wt # noqa: E402
def test_pin_check_true_and_false(monkeypatch):
monkeypatch.setenv("RUNE_COGNITION_CORE", "python")
assert so.cc_loader_pin() is True
monkeypatch.setenv("RUNE_COGNITION_CORE", "auto")
assert so.cc_loader_pin() is False
def test_pinned_core_is_none_everywhere(monkeypatch):
monkeypatch.setenv("RUNE_COGNITION_CORE", "python")
for mod in (so, ab, tm, wt):
assert mod._core() is None
def test_stopword_gather_seams_sorted_and_nonempty():
assert so._keyword_stopwords() == sorted(so._keyword_stopwords())
assert len(so._keyword_stopwords()) >= 50
assert wt._stopwords() == sorted(wt._stopwords())
def test_kernel_probe_fallback_on_loader_error(monkeypatch):
import rune as rune_pkg
monkeypatch.setenv("RUNE_COGNITION_CORE", "auto")
monkeypatch.setattr(rune_pkg, "cc_loader", None, raising=False)
assert so._cc_probe() is None
assert tm._cc_probe() is None
assert wt._cc_probe() is None
assert ab._cc_probe() is None
+40
View File
@@ -0,0 +1,40 @@
"""Verification probes have a task budget, not a global chat lifetime budget."""
from pathlib import Path
from types import SimpleNamespace
import hashlib
from rune import evidence_probe, rune_operator
def test_probe_uses_distinct_task_directories(tmp_path, monkeypatch):
monkeypatch.setenv("MIMO_PROBE_ENABLED", "1")
operator = object.__new__(rune_operator.RuneOperator)
operator.storage_path = str(tmp_path / "operator.json")
called = []
def probe(_question, artifact_dir, model):
called.append(Path(artifact_dir))
return SimpleNamespace(status="GROUNDED")
# The operator binds run_probe at module level (_run_probe) — the real
# interception seam is the operator module's binding, not evidence_probe's.
monkeypatch.setattr(rune_operator, "_run_probe", probe)
monkeypatch.setattr(operator, "_route_task_class", lambda *_: None)
for task_id in ("task-a", "task-b"):
task = SimpleNamespace(task_id=task_id, description="verify")
assert operator._probe_and_escalate(task, SimpleNamespace(error="failure"), "chat") is False
assert called == [tmp_path / "probes" / hashlib.sha256(t.encode()).hexdigest()
for t in ("task-a", "task-b")]
def test_exhausted_task_budget_never_escapes_into_chat(tmp_path, monkeypatch):
monkeypatch.setenv("MIMO_PROBE_ENABLED", "1")
operator = object.__new__(rune_operator.RuneOperator)
operator.storage_path = str(tmp_path / "operator.json")
def exhausted(*_args, **_kwargs):
raise evidence_probe.ProbeBudgetExceeded("probe budget exhausted (2)")
monkeypatch.setattr(rune_operator, "_run_probe", exhausted)
task = SimpleNamespace(task_id="task-a", description="verify")
assert operator._probe_and_escalate(task, SimpleNamespace(error="failure"), "chat") is False
+135
View File
@@ -0,0 +1,135 @@
"""safety_override + abstraction delegation batteries (W3.4/#2461):
direct coverage for the modules the canaries reach only via cc_loader."""
from __future__ import annotations
import json
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
from rune import abstraction as ab # noqa: E402
from rune import safety_override as so # noqa: E402
@pytest.fixture
def override(tmp_path, monkeypatch):
monkeypatch.setattr(so, "OVERRIDE_DIR", str(tmp_path / "ovr"))
monkeypatch.setattr(so, "PATTERNS_FILE",
str(tmp_path / "ovr" / "patterns.json"))
monkeypatch.setattr(so, "STATS_FILE",
str(tmp_path / "ovr" / "stats.json"))
o = so.SafetyOverride()
o.clear_patterns()
return o
def test_normal_request_tier_zero(override):
p = override.get_params("What is Python?")
assert p["tier"] == 0 and p["reason"] == "normal"
def test_pattern_learned_then_matched(override):
override._update_pattern("deployment failure happened", 2, True)
assert override.patterns, "pattern must be learned"
p = override.get_params("another deployment failure occurred")
assert p["tier"] == 2, p
assert "pattern_match" in p["reason"]
def test_extract_keywords_stops_and_caps(override):
kws = override._extract_keywords("the deployment runner needs repair now")
assert all(k not in so._KEYWORD_STOPWORDS for k in kws)
assert len(kws) <= 5
assert "deployment" in kws
def test_pattern_matches_requires_min_keywords(tmp_path):
p = so.OverridePattern(keywords=["deployment", "repair"], tier=1)
assert p.matches("deployment repair issue")
assert not p.matches("deployment only")
def test_refusal_detection_contract(override):
for r in ("I'm sorry, but I can't help with that.",
"As an AI, I cannot assist with this request."):
assert override.is_refusal(r)
assert not override.is_refusal("Here is the information you wanted.")
def test_abstraction_kernel_fallback_schema(tmp_path, monkeypatch):
"""LLM returns nothing → the deterministic kernel fallback maps
sentences into the facts schema with kernel:True provenance.
Requires the kernel: skip when pinned to python."""
if __import__("os").environ.get("RUNE_COGNITION_CORE") == "python":
pytest.skip("kernel pinned off — fallback is a kernel feature")
monkeypatch.setattr(ab, "llm_call", lambda *a, **k: "not json at all")
monkeypatch.setattr(ab, "connect", lambda: _FakeDB())
out = ab.extract_facts("The deployment runner needs repair. The store is fine.")
assert out["extracted"] >= 1 or out.get("error") is None
# the fallback facts carried kernel provenance through the pipeline
def test_abstraction_stopwords_seam():
sw = ab._ABSTRACTION_STOPWORDS()
assert sw == sorted(sw)
assert "the" in sw and "deployment" not in sw
class _Rows:
def __init__(self, rows):
self._rows = rows
def fetchall(self):
return self._rows
def fetchone(self):
return self._rows[0] if self._rows else None
class _FakeDB:
"""Minimal sqlite-shaped fake: enough for the fallback insert path."""
def __init__(self):
self.rows = []
def execute(self, sql, *a):
self.last_sql = sql
self.last_args = a
if "SELECT id FROM facts" in sql:
return _Rows([])
if "SELECT id, what, who_text" in sql:
return _Rows([])
return self
def fetchall(self):
return []
def fetchone(self):
return None
def __enter__(self):
return self
def fetchone(self):
return None
def commit(self):
pass
def close(self):
pass
@property
def lastrowid(self):
return 1
def __enter__(self):
return self
def __exit__(self, *a):
pass
+25
View File
@@ -17,6 +17,31 @@ sys.path.insert(0, str(ROOT / "src"))
from rune import spine
def test_contract_discovery_preserves_unqualified_surface_without_inventing_module(monkeypatch):
monkeypatch.setattr(spine, "_contract_discoveries", lambda: [
("example", [("src/rune/audit_ledger.py", "construction-surface", "candidate"),
("rust-crate:cognition_core", "rust-crate", "observed")])])
doc = spine.new_doc()
spine._apply_contract_discoveries(doc)
found = {e["id"]: e for e in doc["entities"]}
assert found["construction-surface:src/rune/audit_ledger.py"]["kind"] == "construction-surface"
assert found["construction-surface:src/rune/audit_ledger.py"]["maturity"] == "DECLARED"
assert found["rust-crate:cognition_core"]["maturity"] == "PRESENT"
def test_legacy_unqualified_discoveries_are_normalized_without_losing_evidence():
doc = spine.new_doc()
spine.add_entity(doc, id="src/rune/audit_ledger.py", kind="module",
maturity="PRESENT", evidence_refs=["contract-discovery:example"])
spine.add_relationship(doc, type="depends_on", from_id="src/rune/audit_ledger.py",
to_id="module:other", evidence_refs=["test"])
spine._normalize_discovery_ids(doc)
assert doc["entities"][0]["id"] == "construction-surface:src/rune/audit_ledger.py"
assert doc["entities"][0]["maturity"] == "DECLARED"
assert doc["entities"][0]["evidence_refs"] == ["contract-discovery:example"]
assert doc["relationships"][0]["from"] == "construction-surface:src/rune/audit_ledger.py"
# ── helpers ───────────────────────────────────────────────────────────────
@pytest.fixture
+143
View File
@@ -0,0 +1,143 @@
"""spine_language — the #2465 doc-level transforms (T5.15 keep-green:
the new-module henxel demands these ship WITH tests; they were carved
from spine.py whose battery covered them, but the carved module is the
unit under test now)."""
from __future__ import annotations
import json
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
from rune import spine_language as sl # noqa: E402
@pytest.fixture
def doc():
return sl.new_doc()
def test_classification_sides_reads_the_measured_map():
sides = sl._classification_sides()
assert sides, "classification.json must be readable in-repo"
assert sides.get("spine") == "RUST"
assert sides.get("spine_language") == "RUST"
def test_classification_sides_degrades_to_empty_when_unreadable(tmp_path, monkeypatch):
monkeypatch.setattr(sl, "ROOT", tmp_path)
assert sl._classification_sides() == {}
def test_language_verdicts_kind_defaults(doc):
sl.add_entity(doc, id="rust-crate:cognition_core", kind="rust-crate")
sl.add_entity(doc, id="go-surface:rune-entry", kind="go-surface")
sl.add_entity(doc, id="workflow:ci.yml", kind="workflow")
sl.add_entity(doc, id="contract:BUILDER-x", kind="contract")
sl._place_languages(doc)
by = {e["id"]: e["identities"]["language"] for e in doc["entities"]}
assert by["rust-crate:cognition_core"] == "rust"
assert by["go-surface:rune-entry"] == "go"
assert by["workflow:ci.yml"] == "n/a"
assert by["contract:BUILDER-x"] == "n/a"
def test_language_verdicts_measured_authoritative_then_hints(doc):
"""Nick's dichotomy correction: the measured map decides; hints only
label UNMEASURED entities and say so; nothing silently defaults."""
sl.add_entity(doc, id="module:rune_tui", kind="module") # TUI-LAST measured
sl.add_entity(doc, id="module:spine", kind="module") # RUST measured
sl.add_entity(doc, id="module:totally_unknown_name", kind="module")
sl._place_languages(doc)
by = {e["id"]: e["identities"]["language"] for e in doc["entities"]}
assert by["module:rune_tui"] == "python-tui (Wave 6)" # from the MAP
assert by["module:spine"] == "rust" # from the MAP
assert by["module:totally_unknown_name"] == "unclassified"
def test_subsystem_language_from_member_majority(doc):
"""identity: 7 RUST / 3 GO members per classification.json → mixed with
counts carried in the verdict text (never a silent guess)."""
for m in ("behavior", "identity_anchors", "persona_definition",
"persona_gate", "prompt_sync", "voice_hybrid", "voice_injector",
"voice_sync", "voicebox", "safety_override"):
sl.add_entity(doc, id=f"module:{m}", kind="module")
sl.add_relationship(doc, type="belongs_to",
from_id=f"module:{m}", to_id="subsystem:identity",
evidence_refs=["t"])
sl.add_entity(doc, id="subsystem:identity", kind="subsystem")
sl._place_languages(doc)
e = sl.entity(doc, "subsystem:identity")
lang = e["identities"]["language"]
assert lang.startswith("mixed (rust ")
assert "go" in lang
def test_unqualified_discovery_becomes_construction_surface(doc):
"""A bare file path from a closed contract is NOT a module — provenance
preserved, kind honest, candidate stays DECLARED."""
monkey_specs = [("example", [("src/rune/audit_ledger.py",
"construction-surface", "candidate")])]
original = sl._contract_discoveries
sl._contract_discoveries = lambda: monkey_specs
try:
placed = sl._apply_contract_discoveries(doc)
finally:
sl._contract_discoveries = original
assert placed == 1
e = doc["entities"][0]
assert e["id"] == "construction-surface:src/rune/audit_ledger.py"
assert e["kind"] == "construction-surface"
assert e["maturity"] == "DECLARED"
assert e["evidence_refs"] == ["contract-discovery:example"]
def test_legacy_unqualified_module_normalized_with_edges(doc):
sl.add_entity(doc, id="src/rune/claim_audit.py", kind="module",
maturity="PRESENT",
evidence_refs=["contract-discovery:old"])
sl.add_relationship(doc, type="depends_on",
from_id="src/rune/claim_audit.py",
to_id="module:other", evidence_refs=["t"])
sl._normalize_discovery_ids(doc)
assert doc["entities"][0]["id"] == \
"construction-surface:src/rune/claim_audit.py"
assert doc["entities"][0]["kind"] == "construction-surface"
assert doc["relationships"][0]["from"] == \
"construction-surface:src/rune/claim_audit.py"
# Not in the observed set (no closed contract recorded it) → the
# unsupported PRESENT claim is demoted to DECLARED; evidence survives.
assert doc["entities"][0]["maturity"] == "DECLARED"
assert doc["entities"][0]["evidence_refs"] == ["contract-discovery:old"]
def test_discoveries_gather_reads_real_scaffold_store(tmp_path, monkeypatch):
"""The gatherer only trusts CLOSED contracts' ext.contract_quality."""
store = tmp_path / "scaffold"
store.mkdir()
doc = sl.new_doc()
sl.add_entity(doc, id="contract:C1", kind="contract",
ext={"contract_quality": {
"expected_new_observed": ["rust-crate:kernel_x"],
"candidate_corrections": [
{"entity": "suite"}]}})
sl.add_entity(doc, id="contract:C2", kind="contract",
ext={"contract_quality": {
"expected_new_observed": ["rust-crate:never"]}})
for e in doc["entities"]:
if e["id"] == "contract:C1":
e["phase"] = "closed"
if e["id"] == "contract:C2":
e["phase"] = "building"
monkeypatch.setattr(sl, "ROOT", tmp_path)
(tmp_path / "store" / "scaffold").mkdir(parents=True, exist_ok=True)
(tmp_path / "store" / "scaffold" / "current.json").write_text(
json.dumps(doc))
got = sl._contract_discoveries()
assert got == [("C1", [("rust-crate:kernel_x", "rust-crate", "observed"),
("suite", "construction-surface", "candidate")])]
+4
View File
@@ -211,4 +211,8 @@ class TestSpineExtractionNeutrality:
"go-surface",
"config",
"workflow",
# Closed contracts may name files or validation surfaces that
# are not Python modules. Keep their provenance without lying
# about their module identity (issue #2465 CI regression).
"construction-surface",
}
+73
View File
@@ -174,3 +174,76 @@ def test_16k_projection_schema_validated(tmp_path):
assert proj.validate(bad) != []
bad2 = dict(p, schema_version=999)
assert proj.validate(bad2) != []
# ── T5.15 slice 2: the dispatch wire (command → interface execution) ────────
def test_dispatch_executes_accepted_transition_end_to_end(tmp_path):
"""A START command on a draft contract executes through the interface:
the phase actually moves — not just an accepted intent."""
store = str(tmp_path / ".rune" / "scaffold")
iface = cmds if False else None # noqa: F841 — readability anchor
from rune import construction_interface as ci
ciface = ci.ConstructionInterface(builder="seed", project_store=store, project_id="proj")
ciface.scaffold.init(purpose="t")
doc = ciface.scaffold.load()
sc.add_entity(doc, id="contract:disp-1", kind="contract",
identities={"objective": "dispatch"}, evidence_refs=["e"])
doc["entities"][-1]["phase"] = "draft"
ciface.scaffold.commit(doc, what="seed")
out = cmds.dispatch("START", construction_id="disp-1",
store_path=store + "|proj")
# external-project store path: dispatch builds its own interface bound
# to the same store
assert out["executed"] is True, out
assert out["success"] is True, out
doc2 = ciface.scaffold.load()
c = sc.entity(doc2, "contract:disp-1")
assert c["phase"] == "approved"
def test_dispatch_refusal_is_a_valid_protocol_outcome(tmp_path):
"""START on a non-draft contract: the lifecycle refuses — the dispatch
itself succeeds (success=True) with accepted=False."""
store = str(tmp_path / ".rune" / "scaffold")
from rune import construction_interface as ci
ciface = ci.ConstructionInterface(builder="seed", project_store=store, project_id="proj")
ciface.scaffold.init(purpose="t")
doc = ciface.scaffold.load()
sc.add_entity(doc, id="contract:disp-2", kind="contract",
identities={"objective": "x"}, evidence_refs=["e"])
doc["entities"][-1]["phase"] = "draft"
ciface.scaffold.commit(doc, what="seed")
out = cmds.dispatch("START", construction_id="disp-2",
payload={"phase": "building"},
store_path=store + "|proj")
# contract starts in draft so START is ACCEPTED here; drive to building
# first to prove the refusal shape:
assert out["executed"] and out["success"]
out2 = cmds.dispatch("START", construction_id="disp-2",
store_path=store + "|proj")
assert out2["accepted"] is False and out2["executed"] is False
assert out2["success"] is True
assert "draft" in out2["reason"]
def test_dispatch_idempotent_replay_does_not_double_execute(tmp_path):
"""Same command_id twice: the second is a replay — the phase does not
move twice and idempotent_replay=True comes back."""
store = str(tmp_path / ".rune" / "scaffold")
from rune import construction_interface as ci
ciface = ci.ConstructionInterface(builder="seed", project_store=store, project_id="proj")
ciface.scaffold.init(purpose="t")
doc = ciface.scaffold.load()
sc.add_entity(doc, id="contract:disp-3", kind="contract",
identities={"objective": "idem"}, evidence_refs=["e"])
doc["entities"][-1]["phase"] = "draft"
ciface.scaffold.commit(doc, what="seed")
first = cmds.dispatch("START", construction_id="disp-3",
command_id="fixed-cmd-1", store_path=store + "|proj")
assert first["executed"] and first["success"]
second = cmds.dispatch("START", construction_id="disp-3",
command_id="fixed-cmd-1", store_path=store + "|proj")
assert second["idempotent_replay"] is True
assert second.get("executed") in (False, None) # replay ≠ execution
+66
View File
@@ -0,0 +1,66 @@
"""tier_manager's delegation layer (W3.4): kernel path, oracle path, and
their parity — exercised directly so the delegation lines are measured."""
from __future__ import annotations
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
from rune import tier_manager as tm # noqa: E402
@pytest.fixture
def tmgr():
return tm.TierManager()
CASES = [
{"wash_count": 25}, # wash >=20 hot
{"wash_count": 2, "last_accessed": "2026-10-05T06:00:00Z"}, # recency hot
{"wash_count": 2, "last_accessed": "2026-09-25T00:00:00Z"}, # warm
{"wash_count": 2, "last_accessed": "2026-08-01T00:00:00Z"}, # cold
{"wash_count": 2, "last_accessed": "2026-10-05T00:00:00"}, # naive → warm
{"wash_count": 2, "last_accessed": "junk"}, # malformed → warm
{"wash_count": 2}, # no last → warm
{"wash_count": 2, "rock_status": "rock"}, # rock hot
]
def test_get_tier_oracle_matrix(tmgr):
want = ["hot", "hot", "warm", "cold", "warm", "warm", "warm", "hot"]
for e, w in zip(CASES, want):
assert tmgr._py_get_tier(e) == w, e
def test_get_tier_matches_oracle_on_every_case(tmgr):
for e in CASES:
assert tmgr.get_tier(e) == tmgr._py_get_tier(e), e
def test_promote_demote_match_oracle(tmgr):
for e in CASES:
assert tmgr.promote(e) == tmgr._py_promote(e), e
assert tmgr.demote(e) == tmgr._py_demote(e), e
def test_rock_never_demotes(tmgr):
e = {"wash_count": 0, "rock_status": "rock",
"last_accessed": "2026-08-01T00:00:00Z"}
assert tmgr.demote(e) == "hot"
def test_kernel_unavailable_falls_back_to_oracle(monkeypatch, tmgr):
monkeypatch.setattr(tm, "_core", lambda: None)
for e in CASES:
assert tmgr.get_tier(e) == tmgr._py_get_tier(e), e
def test_tier_config_public_surface(tmgr):
assert tmgr.get_tier_config("cold")["compressed"] is True
assert tmgr.should_search("hot") is True
assert tmgr.should_compress("cold") is True
+29
View File
@@ -109,6 +109,35 @@ class ToolProtocolTests(unittest.TestCase):
with self.assertRaisesRegex(ValueError, "unknown tool"):
self.protocol.normalize_text_tool_calls(raw)
def test_common_bash_and_grep_names_normalize_to_existing_authorities(self):
grep_request = self.protocol.normalize_text_tool_calls(
'{"tool":"grep","args":{"pattern":"probe","path":"/tmp"}}'
)[0]
bash_request = self.protocol.normalize_text_tool_calls(
'{"tool":"bash","args":{"command":"pwd"}}'
)[0]
self.assertEqual(grep_request.name, "grep_files")
self.assertFalse(self.protocol.tool_requires_approval(grep_request))
self.assertEqual(bash_request.name, "run_command")
self.assertTrue(self.protocol.tool_requires_approval(bash_request))
self.assertEqual(bash_request.arguments, {"command": "pwd"})
def test_bash_alias_does_not_bypass_shell_approval(self):
request = self.protocol.normalize_text_tool_calls(
'{"tool":"bash","args":{"command":"printf x; printf y"}}'
)[0]
executor = tool_executor.execute_tool
prepared = self.protocol.dispatch_validated_tool(request, executor)
self.assertTrue(prepared["needs_confirm"])
self.assertEqual(prepared["pending"].name, "run_command")
def test_explicit_shell_request_exposes_approved_command_capability(self):
from rune import capability_broker
selected = capability_broker.select_for_job("Use bash and grep to inspect the repository")
self.assertIn("grep_files", selected["names"])
self.assertIn("run_command", selected["names"])
def test_non_object_arguments_are_rejected(self):
cases = (
'{"tool":"list_directory","args":"/tmp"}',
@@ -0,0 +1,115 @@
"""T5.13/T5.14 frozen contracts: pane order and post-response silence.
The pane swap is structural (compose order); the dim-spam consolidation
is behavioral (one collapsed line instead of five dim messages).
"""
from __future__ import annotations
import re
import sys
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import Mock
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
from rune import rune_tui # noqa: E402 — the TUI lives in the package
def test_chat_channel_is_yielded_first_in_compose():
src = (ROOT / "src" / "rune" / "rune_tui.py").read_text()
body = re.search(
r'with Horizontal\(id="channels"\):(.*?)with Horizontal\(id="footer-bar"\)',
src,
re.DOTALL,
).group(1)
order = re.findall(r'ChannelView\(\s*"(\w+)"', body)
assert order == ["chat", "task"], f"compose yields {order}"
def test_resize_actions_follow_the_new_visual_positions():
"""After the swap LEFT=chat, RIGHT=task. resize_left shrinks the LEFT
(chat) — which GROWS the task share; resize_right is the reverse."""
assert "grow the RIGHT (task)" in rune_tui.RuneApp.action_resize_left.__doc__
assert "shrink the RIGHT (task)" in rune_tui.RuneApp.action_resize_right.__doc__
# Behavioral proof against an instance WITHOUT constructing the App
# (reactive initialization needs a running textual app; the docstring
# carries the contract, the arithmetic is what matters).
app = SimpleNamespace(
task_width=50,
action_resize_left=None,
action_resize_right=None,
_apply_resize=None,
)
app._apply_resize = lambda: None
# Bind the real methods onto the stand-in and call them.
rune_tui.RuneApp.action_resize_left(app)
assert app.task_width == 55
rune_tui.RuneApp.action_resize_right(app)
assert app.task_width == 50
def _isolate_collector(monkeypatch, **modules):
monkeypatch.setattr(rune_tui, "BACKEND_AVAILABLE", True)
for name, value in modules.items():
monkeypatch.setattr(rune_tui, name, value)
def test_collector_returns_all_signals_in_one_pass(monkeypatch):
_isolate_collector(
monkeypatch,
provider_budget=SimpleNamespace(
get_status=lambda: {
"providers": {"p": {"monthly_limit": 100, "monthly_used": 90, "token_limit": 0, "tokens_used": 0}}
}
),
claim_audit=SimpleNamespace(scan_text=lambda _t: {"degraded": ["a", "b"]}),
growth_delta=SimpleNamespace(check=lambda: {"delta": "focus: +1"}),
self_improve=SimpleNamespace(run=lambda: None),
)
signals = rune_tui.collect_post_response_signals("response text", messages_count=10)
assert signals == ["⚠ Budget: 90% used", "⚠ Claims degraded: 2", "📈 Growth: focus: +1", "🔄 Self-improvement cycle triggered"]
def test_collector_silence_when_nothing_fires(monkeypatch):
_isolate_collector(
monkeypatch,
provider_budget=Mock(get_status=lambda: {"providers": {}}),
claim_audit=Mock(scan_text=lambda _t: None),
growth_delta=Mock(check=lambda: None),
self_improve=Mock(run=lambda: None),
)
collector = rune_tui.collect_post_response_signals
app_signals = collector("plain", messages_count=7) # not a cycle multiple
assert app_signals == []
def test_collector_never_raises_on_backend_noise(monkeypatch):
def boom(*_a, **_k):
raise RuntimeError("backend gone")
_isolate_collector(
monkeypatch,
provider_budget=Mock(get_status=boom),
claim_audit=Mock(scan_text=boom),
growth_delta=Mock(check=boom),
self_improve=Mock(run=boom),
)
assert rune_tui.collect_post_response_signals("x", 10) == []
def test_self_improve_only_at_cycle_multiple(monkeypatch):
ran = []
_isolate_collector(
monkeypatch,
provider_budget=Mock(get_status=lambda: {"providers": {}}),
claim_audit=Mock(scan_text=lambda _t: None),
growth_delta=Mock(check=lambda: None),
self_improve=Mock(run=lambda: ran.append(1)),
)
rune_tui.collect_post_response_signals("x", 7)
assert ran == []
rune_tui.collect_post_response_signals("x", 10)
assert ran == [1]
+74
View File
@@ -0,0 +1,74 @@
"""witness delegation battery (W3.4): kernel path, oracle path, per-table
parity — direct coverage for the delegation layer the canaries only reach
through cc_loader."""
from __future__ import annotations
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
from rune import witness as wt # noqa: E402
def test_extract_topic_oracle_matrix():
assert wt._py_extract_topic("the deployment runner needs repair now") == \
["deployment", "runner", "needs", "repair"]
assert wt._py_extract_topic("fix this now") == []
assert wt._py_extract_topic("") == []
def test_extract_topic_matches_kernel():
core = wt._core()
if core is None:
pytest.skip("kernel unavailable")
for msg in ("the deployment runner needs repair now",
"why does the memory keep drifting", "fix this now", ""):
assert wt.extract_topic(msg) == wt._py_extract_topic(msg), msg
def test_tables_gather_seam_deterministic():
t1, t2 = wt._tables(), wt._tables()
assert t1 == t2
assert t1["stopwords"] == sorted(t1["stopwords"])
for key in ("correction", "commitment", "contradiction",
"preference", "urgency", "learning"):
assert t1[key], f"{key} table must not be empty"
def test_detect_signals_error_and_completion():
sig = wt._py_detect_signals("hello", tool_error="boom")
assert sig["error"] is True and sig["error_text"] == "boom"
assert wt._py_detect_signals("hello", task_status="done")["completion"] == "done"
def test_detect_signals_correction_topic_drift_learning():
sig = wt._py_detect_signals("no, that's wrong, try again")
assert sig["correction"] is True
assert wt._py_detect_signals("anyway moving on to budgets",
recent_topics=["budget"])["topic_drift"] is True
assert wt._py_detect_signals("I need to check that")["commitment_detected"] is True
assert wt._py_detect_signals("this is urgent, deadline today")["urgency_detected"] is True
assert wt._py_detect_signals("I prefer rust")["preference_detected"] is True
assert wt._py_detect_signals("explain how this works")["learning_opportunity"] is True
def test_detect_signals_kernel_matches_oracle():
core = wt._core()
if core is None:
pytest.skip("kernel unavailable")
cases = [("no, that's wrong, try again", None, None),
("urgent! I prefer rust, but actually wait", None, None),
("I'll send the report", None, None)]
for msg, te, ts in cases:
py = wt._py_detect_signals(msg, te, ts)
rs = wt.detect_signals(msg, te, ts)
assert py == rs, (msg, py, rs)
def test_witness_reflect_empty_signals_is_empty():
assert wt.witness_reflect({}) == ""