Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
65b76afb8c | ||
|
|
ff49fba738 | ||
|
|
62abca0538 | ||
|
|
de8c7a6e47 | ||
|
|
7402a68095 | ||
|
|
dac9bec488 | ||
|
|
a9fe30bb7c | ||
|
|
a78588048b | ||
|
|
2975d7651d | ||
|
|
9df9181767 | ||
|
|
9ce673f632 | ||
|
|
fd8bd001cb |
No files matched your search
@@ -0,0 +1,34 @@
|
||||
name: Merge robot
|
||||
|
||||
# Deterministic merge-on-green for this repo's PRs. No LLM, no polling by the
|
||||
# agent: the forge event model does the watching, this job does the one action.
|
||||
# Runs hourly + on CI completion events so green PRs merge without any agent
|
||||
# turn being spent on "check CI, merge, clean up".
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '23 * * * *'
|
||||
workflow_dispatch: {}
|
||||
workflow_run:
|
||||
workflows: ["CI Pipeline", "Auto-version and Release"]
|
||||
types: [completed]
|
||||
|
||||
permissions:
|
||||
pull_requests: write
|
||||
issues: write
|
||||
contents: read
|
||||
|
||||
env:
|
||||
OWNER: conductor
|
||||
REPO: rune
|
||||
|
||||
jobs:
|
||||
merge-green:
|
||||
runs-on: rune-ci-desktop
|
||||
steps:
|
||||
- name: Merge PRs whose protected checks are green (fail-loud)
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
SERVER: ${{ gitea.server_url }}
|
||||
run: |
|
||||
python3 scripts/merge_robot.py "$GITEA_TOKEN" "$SERVER/api/v1/repos/conductor/rune"
|
||||
@@ -17,6 +17,12 @@ Only use `git commit --no-verify` in a genuine emergency: it bypasses the hooks
|
||||
- Plans are markdown, one per build (in ./plans)
|
||||
- Top-level docs are markdown or yaml references (in ./docs/*)
|
||||
- The known giant stays visible — file-size debt is tracked, not silent (in ./src/rune/*)
|
||||
- The bug-fix discharge contract is a governed doc — it exists, is markdown, and changes are deliberate (in ./docs/bugfix-contract.md)
|
||||
- The discharge checker ships with the repo — red-first enforcement is structural (in ./scripts)
|
||||
- Discharge checker and its CI wiring change together
|
||||
- Every workflow is registered in the pipeline registry — new pipeline machinery ships with documentation (in ./.gitea/workflows/*.yml)
|
||||
- Every TUI surface is registered — no silent UI growth (in ./src/rune/*tui*.py)
|
||||
- New rune modules ship with tests or a canary — no ungoverned code surfaces (in ./src/rune/*.py)
|
||||
|
||||
### Behaviours
|
||||
|
||||
@@ -33,3 +39,12 @@ Need a check that genuinely doesn't exist? `henxels create-new-statement <name>`
|
||||
other repos, not tied to this one — contribute it upstream with `henxels contribute`.
|
||||
We're in the agentic era: send a ready-to-merge PR instead of opening an issue.
|
||||
<!-- henxels:end -->
|
||||
|
||||
## Bug fixes (binding)
|
||||
|
||||
Every bug found — by gates, CI, canaries, production, or humans — is fixed per
|
||||
`docs/bugfix-contract.md`: red test FIRST (reproduces the cause), root-cause
|
||||
fix, full pipeline re-entry (suite + ratchet + ruff + canaries + henxels;
|
||||
gates for anything beyond a mechanical minor), regression tests frozen forever,
|
||||
discharge recorded finding → test → commit. Symptom patches are rejected at
|
||||
review. To escape: edit `henxels.yaml` or this file — visibly.
|
||||
@@ -0,0 +1,86 @@
|
||||
# Bug-fix contract
|
||||
|
||||
_Binding on every agent, session, and pipeline stage in this repository. The
|
||||
henxel mirror of this contract lives in `henxels.yaml` ("bugs discharged
|
||||
red-first"); the enforcement hooks live in `scripts/check_discharge_contract.py`
|
||||
and `.gitea/workflows/pipeline-gate.yml`. Escapes from this contract are made
|
||||
by editing those files — visibly — never by silent deviation._
|
||||
|
||||
## The contract
|
||||
|
||||
When a **bug is found** — by a gate, a reviewer, CI, a canary, production, or a
|
||||
human — the fix MUST follow this cycle before it may merge:
|
||||
|
||||
1. **Red first.** A failing test that reproduces the bug is written BEFORE the
|
||||
fix. The test must fail for the *bug's cause*, not for an unrelated reason.
|
||||
A fix without a red test is a symptom patch and is rejected at review.
|
||||
2. **Root cause, not symptom.** The fix addresses the cause. If the reporter's
|
||||
diagnosis is wrong, the discharge says so and names the real cause.
|
||||
3. **Full pipeline re-entry.** The fix is treated as a NEW SUBMISSION: full
|
||||
suite, pyright ratchet (not increased), ruff, canaries, henxels, and the
|
||||
spec + quality gates for anything beyond a mechanical minor. No
|
||||
"hotfix-skips-gates" path exists.
|
||||
4. **The regression test is permanent.** Tests written for a discharged bug are
|
||||
frozen — they may be refactored, never weakened or deleted. The suite can
|
||||
only grow in assertion strength over time.
|
||||
5. **Recorded.** The fix's PR (or plan tail) maps every finding → the red test
|
||||
→ the commit. A discharge record with holes bounces at review.
|
||||
|
||||
## Scope and proportionality
|
||||
|
||||
- **Gate findings (spec/quality):** every BLOCKER/MAJOR gets the full cycle;
|
||||
MINORs get at minimum a red test OR an explicit reviewer-approved waiver
|
||||
recorded in the plan tail.
|
||||
- **Production failures:** the fix follows this contract AND, where the failing
|
||||
payload is preservable, #157's fixture pipeline (real failure → sanitised
|
||||
fixture → permanent regression test).
|
||||
- **CI/workflow bugs:** the red test is the workflow-contract assertion
|
||||
(parsed-YAML step/step-logic assertions, as in `test_workflow_script_contract.py`)
|
||||
— workflows are code; their bugs get tests too.
|
||||
- **Trivial/no-test-class bugs** (typos in comments, log strings): documented
|
||||
exemption list in this file. PR-only changes to those strings skip the red test.
|
||||
|
||||
## Why (the failure class this kills)
|
||||
|
||||
LLM-authored changes share wrong assumptions between implementation, tests, and
|
||||
docs. A symptom patch shares the reporter's wrong assumption with the fix. The
|
||||
red-first test is the cheapest known breaker of both: it forces the fixer to
|
||||
state the bug's cause in executable form before claiming to have removed it.
|
||||
|
||||
## Enforcement
|
||||
|
||||
- `scripts/check_discharge_contract.py`: verifies a PR that touches files named
|
||||
in a `Discharge:` trailer block carries at least one test-hunk per finding
|
||||
id (structural check — PR description convention: `Discharge: <id> -> <test file>`).
|
||||
- Gate reviewers are instructed (dispatch templates, issue #151) to reject
|
||||
symptom patches: "what test failed red for this bug?" is a mandatory
|
||||
reviewer question for every fix PR.
|
||||
- `henxels.yaml` carries the tracked one-line mirror so the contract is part
|
||||
of the repo's auditable contract surface.
|
||||
|
||||
## Binding refinements (pipeline doctrine, 2026-09-07)
|
||||
|
||||
6. **Soak-before-close for intermittent defects.** A flaky, timing, or
|
||||
event-delivery bug cannot be proven fixed by one green run. The fix merges
|
||||
through the normal pipeline, but the issue CLOSES only on soak evidence: a
|
||||
stated criterion (e.g. "N consecutive green runs" or "48h without
|
||||
recurrence") plus the observations meeting it. The closing comment carries
|
||||
the soak record. Merge ≠ closure for this class.
|
||||
7. **Escape accountability.** When a bug reaches production (escaped every
|
||||
gate), the discharge must answer: _which gate should have caught this, and
|
||||
why didn't it?_ The answer becomes a gate improvement — a new contract
|
||||
assertion, a checker rule, or a documented gate limit. Gate hardening is a
|
||||
first-class output of bug fixing, not an afterthought.
|
||||
8. **Fresh-context root-cause verification.** The red test proves the fixer
|
||||
understood _a_ cause. For BLOCKER/MAJOR fixes, a fresh-context reviewer
|
||||
additionally asks: does this test fail on the pre-fix code _for the right
|
||||
reason_? (Same doctrine as the black-box test author: the person who wrote
|
||||
the fix does not certify its diagnosis.)
|
||||
9. **Déjà-vu detection.** Before writing the red test, search the suite and
|
||||
closed issues for the same failure class. A second occurrence of a class
|
||||
means the first fix treated a symptom — the discharge must then cover the
|
||||
class, not the instance.
|
||||
10. **Fixture promotion.** When the red test needs a complex payload, it goes
|
||||
through #157's sanitised-fixture pipeline (real failure → secrets stripped
|
||||
→ `tests/fixtures/production/`) instead of a hand-crafted approximation.
|
||||
Real failures are the best regression tests.
|
||||
@@ -0,0 +1,35 @@
|
||||
# Module coverage debt ledger
|
||||
|
||||
_Tracked, not silent — the repo's doctrine for known debt (same pattern as the
|
||||
file-size giants in `henxels.yaml`). The `new_rune_modules_have_canary_or_test_coverage`
|
||||
henxel fails any `src/rune/*.py` module with no test reference and no canary._
|
||||
|
||||
**Rule: this list only shrinks.** Every PR that adds a test or canary for a
|
||||
module removes it here. New modules can never be added — they ship governed.
|
||||
When the list is empty, this file records the fact and the henxel needs no
|
||||
escape.
|
||||
|
||||
## Mechanism
|
||||
|
||||
The henxel reads this file: a module listed under `## Debt` is *tracked debt*
|
||||
(warning-level in the ledger, visible here) instead of a contract failure. The
|
||||
distinction matters — nothing below is approved as "fine", it is *known, owned,
|
||||
and scheduled for elimination* via the P2 consolidation tranche (#125, #41).
|
||||
|
||||
## Debt (58 modules as of 2026-09-07, baseline master 2975d76)
|
||||
|
||||
abstraction, audit_ledger, claim_audit, cognitive_budgeter, complexity_scorer,
|
||||
connection_pool, context_pressure, cron_engine, curator, dependency_tracker,
|
||||
drift_cache, drift_compression, drift_core, drift_observability,
|
||||
elastic_cognition, goal, graph_memory, growth_delta, hook_engine,
|
||||
identity_anchors, memory_consolidation, memory_env, message_queue, model_connect,
|
||||
model_registry, night_mode, outcome_ledger, parallel_processor, persona_definition,
|
||||
persona_gate, progressive_escalation, provider_budget, provider_registry,
|
||||
query_memory, recall_router, response_adapter, rune_graphic, rune_profiler,
|
||||
rune_spinner, salience_gate, self_improve, shard_manager, standardized_providers,
|
||||
subconscious_pass, system_registry, task_gate, task_persist, tiered_executor,
|
||||
tier_manager, time_awareness, token_optimizer, tui_validator, verification_layer,
|
||||
voicebox, voice_hybrid, voice_injector, voice_sync, warm_neuron_store, work_manager
|
||||
|
||||
_Henxel escape: add the module name to this list only when the PR that touches
|
||||
the module cannot also carry its first test — and say why in the PR body._
|
||||
@@ -0,0 +1,25 @@
|
||||
# Pipeline registry
|
||||
|
||||
_Every workflow in `.gitea/workflows/` is registered here — trigger, purpose,
|
||||
failure mode. Governed by the `workflows_are_governed` henxel: a new workflow
|
||||
that isn't registered fails the contract. Add the registry entry IN THE SAME
|
||||
PR as the new workflow._
|
||||
|
||||
| Workflow | Trigger | Purpose | Failure mode |
|
||||
|---|---|---|---|
|
||||
| `ci.yml` | PR + push to master | lint, unit tests, canaries, best-practices, documentation, type-check (ratchet), gitea-offline, required-checks aggregation | Required checks fail → protected merge blocked |
|
||||
| `pipeline-gate.yml` | issue events, comment created, schedule (hourly), workflow_run | gate (deps/research-pending), teach (next-issue), research-clear (evidence floor: citations, live-fetched sources, trail, synthesis qualification), incomplete-catcher (draft PRs for abandoned work) | Rejection comments name gaps; labels stay |
|
||||
| `auto-version.yml` | pull_request:closed + push to master | semver from PR title (authoritative) / push-triggered convergence safety net (scripts/version_convergence.py) → bump PR → release | Safety net reconciles slipped events; drift flagged by maintenance |
|
||||
| `maintenance.yml` | schedule | drift reconciliation (release version vs tags), housekeeping | Files advisory "release drift" issue, deduped |
|
||||
| `merge-robot.yml` | schedule (hourly) + CI completion | merge-on-green: PRs with success status + mergeable merge via API | 405 (protection/stale) logged and skipped — **known silent-failure defect under discharge (bug-fix contract)** |
|
||||
| `auto-label.yml` | issue events | priority gate, label transitions | Gate comments on unlabelled issues |
|
||||
| `auto-backup.yml` | schedule | repo backup | Journal alert on failure |
|
||||
| `auto-update-gitea.yml` | schedule | Gitea self-update | Binary-only rollback risk (T1.1 audit finding) |
|
||||
|
||||
## Adding a workflow
|
||||
|
||||
1. Create `.gitea/workflows/<name>.yml`.
|
||||
2. Add a row here (trigger / purpose / failure mode) in the same PR.
|
||||
3. If the workflow has a canary-relevant side effect, register the canary in
|
||||
`ci.yml` (the `ci_runs_all_canaries` henxel enforces it).
|
||||
4. Verify: `python3 -c "import yaml; yaml.safe_load(open('.gitea/workflows/<name>.yml'))"`.
|
||||
@@ -0,0 +1,20 @@
|
||||
# TUI registry
|
||||
|
||||
_Every TUI surface in `src/rune/` is registered here — what it renders, who
|
||||
owns it. Governed by the `tui_panels_are_governed` henxel: a new TUI surface
|
||||
that isn't registered fails the contract. Add the entry IN THE SAME PR as the
|
||||
new surface._
|
||||
|
||||
| Surface | Renders | Notes |
|
||||
|---|---|---|
|
||||
| `rune_tui.py` | The main Textual application — chat pane, work pane, status bar (version label + refresh), footer, dialogs | The known giant (file-size debt tracked in henxels); composition root for all UI |
|
||||
| `tui_validator.py` | Import-allowlist validation for TUI code | Drift defect tracked in #139 (allowlist vs `__future__`/relative imports) |
|
||||
|
||||
## Adding a TUI surface
|
||||
|
||||
1. Create the module under `src/rune/`.
|
||||
2. Add a row here (renders / notes) in the same PR.
|
||||
3. Ship a test or canary (the `new_rune_modules_have_canary_or_test_coverage`
|
||||
henxel enforces coverage).
|
||||
4. Decomposition of `rune_tui.py` along the authority map is tracked in #125 —
|
||||
new panels should target the decomposed structure, not grow the giant.
|
||||
@@ -0,0 +1,84 @@
|
||||
# Umbrella system → henxels contracts + retroactive governance — design for confirmation
|
||||
|
||||
## Part 1: Retroactive application (ready to execute now)
|
||||
|
||||
The survey found six ungoverned surfaces. Proposed henxels rules, in the tool's
|
||||
real schema, each following an existing pattern:
|
||||
|
||||
| Surface | Finding | Proposed henxel (keyed, real schema) |
|
||||
|---|---|---|
|
||||
| `shared/*.py` (24 files) | ~100% near-duplicates of `src/rune/` modules (the mtime-copy sync is the cause) | `changed_with`: when `shared/*.py` changes, `src/rune/` mirror must change too — **or better (Part 2) the dupes die** |
|
||||
| `research/**` (63 files, 16 dirs) | No index; unlinked pages | `referenced_in: docs/research-index.md` + `links_resolve` — orphan research is tracked |
|
||||
| `memory/` (runtime state tracked in git!) | `journal/events.jsonl` + runtime JSON in the repo — runtime data in version control | `forbidden_files: [./memory/journal/events.jsonl, ./memory/index/*.json]` after a one-time extraction (runtime state belongs to the deployed agent, not the codebase) |
|
||||
| `backups/*.bak` (3 files) | Build backups committed | `forbidden_files: [./backups/**]` (git history IS the backup) |
|
||||
| `specs/`, `reports/` | Type-ungoverned | `allowed_filetypes: [.md]` (matches the plans rule) |
|
||||
| `survey/` (7 files) | Ungoverned | fold into research indexing or `allowed_filetypes: [.md, .yaml]` |
|
||||
|
||||
All are mechanical; the `memory/` extraction is the only one touching runtime —
|
||||
I'd do it in the same PR with the agent's own journal-preservation discipline
|
||||
(backup branch first).
|
||||
|
||||
## Part 2: Umbrella system → contracts (needs your confirmation on shape)
|
||||
|
||||
### What the umbrella system is (verified)
|
||||
|
||||
`shared/umbrella_update.py`: a hand-maintained manifest (`UMBRELLAS` dict) of six
|
||||
functional umbrellas — **memory, governance, identity, growth, perception,
|
||||
infrastructure** — each listing shared/scripts/canaries components plus a
|
||||
`depends_on` DAG (memory→governance→identity; growth→memory+governance). Purpose:
|
||||
say "update memory" and the system knows the affected files, runs the umbrella's
|
||||
canaries, syncs shared→deploy targets by mtime, and commits.
|
||||
|
||||
### What's wrong (verified defects)
|
||||
|
||||
1. **Manifest drift**: `memory_selector.py` and every post-manifest module is in
|
||||
NO umbrella; it references canaries (`canary_unbounded.py`,
|
||||
`canary_drift_wiring.py`) that don't exist in the repo.
|
||||
2. **Two-sources-of-truth by design**: `sync_shared_to_scripts()` mtime-copies
|
||||
`shared/` → `~/.config/opencode/scripts/` + the old TUI dir. This is why
|
||||
henxels flags ~100% duplicates. The repo and the harness both "own" copies.
|
||||
3. **Hardcoded harness paths** (`~/.config/opencode/...`) — not repo-portable,
|
||||
dead on the runner.
|
||||
|
||||
### Proposed design: three contracts, one removal
|
||||
|
||||
**Contract A — `umbrella_manifest_is_complete`** (new custom statement):
|
||||
every `src/rune/*.py` and `shared/*.py` module must appear in the umbrella
|
||||
manifest (or the coverage-debt ledger). New modules force an umbrella decision —
|
||||
the manifest can never silently drift again. This is the umbrella's real
|
||||
invariant: *the system knows what needs updating* — enforced.
|
||||
|
||||
**Contract B — `umbrella_canaries_exist`** (new custom statement): every canary
|
||||
referenced by the manifest must exist in `src/rune/` and be CI-registered
|
||||
(composes with the existing `ci_runs_all_canaries`). Kills defect 1's phantom
|
||||
references.
|
||||
|
||||
**Contract C — `umbrella_dag_acyclic_and_declared`** (new custom statement):
|
||||
parse `UMBRELLAS`, verify `depends_on` is a DAG (no cycles), every dependency
|
||||
target exists. Cheap, structural, protects the reflex's core logic.
|
||||
|
||||
**The removal (your call):** the mtime-copy sync. Two honest options:
|
||||
|
||||
- **Option 1 (recommended): repo-as-source-of-truth.** The repo's `src/rune/` +
|
||||
`shared/` become the ONLY governed copies. The deployed harness gets its
|
||||
scripts from the pinned checkout (the update flow already force-checks-out
|
||||
gitea/master). `sync_shared_to_scripts()` is retired; the
|
||||
near-duplicate `shared/` files either become true imports of `src/rune` or
|
||||
move to the harness (outside the repo). Contract A then governs ONE tree.
|
||||
Cost: the harness-side scripts dir stops being independently editable —
|
||||
which is the point.
|
||||
- **Option 2: keep dual-location, gate the sync.** Keep the copies but add a
|
||||
`must_be_in_sync`-style contract: shared/ and its mirrors must be
|
||||
content-identical at commit time (henxels `changed_with` + a checksum
|
||||
statement). Cost: permanent duplication machinery; drift only detectable,
|
||||
never prevented.
|
||||
|
||||
### Sequencing
|
||||
|
||||
1. Retroactive henxels (Part 1) — one PR, mechanical.
|
||||
2. Contracts A+B+C + the manifest modernized in-repo (move `UMBRELLAS` to
|
||||
`config/umbrellas.json`, sourced by the script) — second PR.
|
||||
3. Option 1's sync retirement — its own PR, after you confirm.
|
||||
|
||||
**Confirm**: Option 1 or 2 for the sync? And does the `memory/` runtime-state
|
||||
extraction have your blessing (it touches the live journal)?
|
||||
@@ -32,3 +32,28 @@ henxels:
|
||||
- ./src/rune/tool_executor.py
|
||||
- ./src/rune/warm_router.py
|
||||
max_lines: 1200
|
||||
|
||||
- henxel: "The bug-fix discharge contract is a governed doc — it exists, is markdown, and changes are deliberate"
|
||||
in: ./docs/bugfix-contract.md
|
||||
allowed_filetypes: [.md]
|
||||
|
||||
- henxel: "The discharge checker ships with the repo — red-first enforcement is structural"
|
||||
in: ./scripts
|
||||
required_files: [check_discharge_contract.py]
|
||||
|
||||
- henxel: "Discharge checker and its CI wiring change together"
|
||||
changed_with:
|
||||
when: ./scripts/check_discharge_contract.py
|
||||
expect: ./.gitea/workflows/pipeline-gate.yml
|
||||
|
||||
- henxel: "Every workflow is registered in the pipeline registry — new pipeline machinery ships with documentation"
|
||||
in: ./.gitea/workflows/*.yml
|
||||
workflows_are_governed: true
|
||||
|
||||
- henxel: "Every TUI surface is registered — no silent UI growth"
|
||||
in: ./src/rune/*tui*.py
|
||||
tui_panels_are_governed: true
|
||||
|
||||
- henxel: "New rune modules ship with tests or a canary — no ungoverned code surfaces"
|
||||
in: ./src/rune/*.py
|
||||
new_rune_modules_have_canary_or_test_coverage: true
|
||||
@@ -15,3 +15,87 @@ def ci_runs_all_canaries(param, file, root):
|
||||
if Path(file).name in ci.read_text():
|
||||
return None
|
||||
return f"{file} is missing from .gitea/workflows/ci.yml — register it in the canary job's for-loop list"
|
||||
|
||||
|
||||
# --- Pipeline-expansion contracts (issue #204 doctrine): when a new process,
|
||||
# feature, workflow, or backend surface is added, a governing contract must
|
||||
# exist for it. These statements make "ungoverned surface" a check failure.
|
||||
|
||||
@statement(
|
||||
"workflows_are_governed",
|
||||
help="every .gitea/workflows/*.yml is referenced by docs/pipeline-registry.md — new pipeline machinery ships with documentation",
|
||||
)
|
||||
def workflows_are_governed(param, file, root):
|
||||
if not file.startswith(".gitea/workflows/") or not file.endswith(".yml"):
|
||||
return None
|
||||
registry = root / "docs" / "pipeline-registry.md"
|
||||
if not registry.exists():
|
||||
return f"docs/pipeline-registry.md is missing — create it and register {file} (every workflow documents trigger/purpose/owner)"
|
||||
if Path(file).name not in registry.read_text():
|
||||
return f"{file} is not registered in docs/pipeline-registry.md — new pipeline processes ship with a registry entry (trigger, purpose, failure mode)"
|
||||
return None
|
||||
|
||||
|
||||
@statement(
|
||||
"tui_panels_are_governed",
|
||||
help="new TUI surfaces (src/rune/*tui*.py panels/widgets) are referenced in docs/tui-registry.md — no silent UI growth",
|
||||
)
|
||||
def tui_panels_are_governed(param, file, root):
|
||||
if Path(file).stem.startswith("canary_"):
|
||||
return None
|
||||
if "tui" not in Path(file).name.lower():
|
||||
return None
|
||||
registry = root / "docs" / "tui-registry.md"
|
||||
if not registry.exists():
|
||||
return f"docs/tui-registry.md is missing — create it and register {file} (every TUI surface documents what it renders and who owns it)"
|
||||
if Path(file).name in registry.read_text():
|
||||
return None
|
||||
# registry exists but this file is new/unregistered — check for a known-exempt core list
|
||||
core = {"rune_tui.py"}
|
||||
if Path(file).name in core:
|
||||
return None
|
||||
return f"{Path(file).name} is not registered in docs/tui-registry.md — new TUI surfaces ship with a registry entry"
|
||||
|
||||
|
||||
def _tests_corpus(root) -> str:
|
||||
tests_dir = root / "tests"
|
||||
if not tests_dir.exists():
|
||||
return ""
|
||||
parts = []
|
||||
for tf in sorted(tests_dir.glob("test_*.py")):
|
||||
try:
|
||||
parts.append(tf.read_text(errors="replace"))
|
||||
except OSError:
|
||||
continue
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
@statement(
|
||||
"new_rune_modules_have_canary_or_test_coverage",
|
||||
help="every src/rune/*.py module is referenced by at least one test file or has a canary — no ungoverned code surfaces",
|
||||
)
|
||||
def new_rune_modules_have_canary_or_test_coverage(param, file, root):
|
||||
if not file.startswith("src/rune/") or not file.endswith(".py"):
|
||||
return None
|
||||
name = Path(file).stem
|
||||
if name.startswith(("canary_", "test_", "__")):
|
||||
return None
|
||||
tests_dir = root / "tests"
|
||||
if (tests_dir / f"test_{name}.py").exists():
|
||||
return None
|
||||
canary = root / "src" / "rune" / f"canary_{name}.py"
|
||||
if canary.exists():
|
||||
return None
|
||||
corpus = _tests_corpus(root)
|
||||
if name in corpus:
|
||||
return None
|
||||
debt = root / "docs" / "module-coverage-debt.md"
|
||||
if debt.exists():
|
||||
debt_text = debt.read_text(errors="replace")
|
||||
if name in debt_text:
|
||||
return None # tracked debt — visible in docs/module-coverage-debt.md (list only shrinks)
|
||||
return (
|
||||
f"{name} is referenced by no test file and has no canary — new modules ship with coverage "
|
||||
f"(a test importing/exercising it, or a canary) per docs/bugfix-contract.md; "
|
||||
f"legacy debt goes in docs/module-coverage-debt.md (tracked, not silent)"
|
||||
)
|
||||
Executable
+81
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Enforce the bug-fix discharge contract (docs/bugfix-contract.md) (#147).
|
||||
|
||||
A PR that claims discharges must carry, for every `Discharge:` finding line in
|
||||
its body, at least one ADDED test hunk in the named test file. Structural check:
|
||||
the pipeline cannot read intent, but it can verify the shape of the claim.
|
||||
|
||||
Convention (PR body):
|
||||
Discharge: F1 -> tests/test_foo.py
|
||||
Discharge: F2 -> tests/test_bar.py::test_case
|
||||
|
||||
Exit 0 when no Discharge lines exist (not a fix PR) or every line is satisfied.
|
||||
Exit 1 with the unsatisfied finding ids otherwise. Silent fixes (fix commits
|
||||
with no discharge claim AND no test hunks) are a reviewer question, not a
|
||||
script verdict — see the contract's "Why".
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
DISCHARGE_RE = re.compile(r"^\s*Discharge:\s*(?P<id>\S+)\s*->\s*(?P<file>\S+)", re.MULTILINE)
|
||||
TEST_PATH_RE = re.compile(r"(tests|src/rune)/.*?test.*\.py$")
|
||||
|
||||
|
||||
def added_test_hunks(diff: str, test_file: str) -> bool:
|
||||
"""True if the diff adds lines inside the named test file."""
|
||||
current_file: str | None = None
|
||||
for line in diff.splitlines():
|
||||
if line.startswith("+++ b/"):
|
||||
current_file = line[6:].strip()
|
||||
elif line.startswith("+") and not line.startswith("+++"):
|
||||
if current_file and (current_file == test_file or current_file.endswith("/" + test_file)):
|
||||
if TEST_PATH_RE.search(current_file):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def main() -> int:
|
||||
pr_body_path = os.environ.get("PR_BODY_FILE")
|
||||
if not pr_body_path or not os.path.exists(pr_body_path):
|
||||
print("check_discharge_contract: no PR body provided — nothing to check (exit 0)")
|
||||
return 0
|
||||
body = open(pr_body_path, encoding="utf-8").read()
|
||||
claims = DISCHARGE_RE.findall(body)
|
||||
if not claims:
|
||||
print("check_discharge_contract: no Discharge claims in PR body (exit 0)")
|
||||
return 0
|
||||
|
||||
base = os.environ.get("PR_BASE_SHA")
|
||||
head = os.environ.get("PR_HEAD_SHA") or "HEAD"
|
||||
if not base:
|
||||
print("check_discharge_contract: PR_BASE_SHA missing — cannot diff (exit 1)")
|
||||
return 1
|
||||
diff = subprocess.run(
|
||||
["git", "diff", base, head, "--", "tests/", "src/rune/"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
).stdout
|
||||
|
||||
unsatisfied = []
|
||||
for fid, test_file in claims:
|
||||
if not added_test_hunks(diff, test_file):
|
||||
unsatisfied.append(f"{fid} -> {test_file}")
|
||||
|
||||
if unsatisfied:
|
||||
print("check_discharge_contract: DISCHARGE CLAIMS WITHOUT RED TESTS (contract docs/bugfix-contract.md):")
|
||||
for u in unsatisfied:
|
||||
print(f" - {u}")
|
||||
print("Every finding needs a failing test hunk in the named file BEFORE the fix. See docs/bugfix-contract.md.")
|
||||
return 1
|
||||
print(f"check_discharge_contract: {len(claims)} discharge claim(s) verified against added test hunks")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,122 @@
|
||||
#!/usr/bin/env python3
|
||||
"""merge_robot.py — deterministic merge-on-green for this repo (#203).
|
||||
|
||||
Extracted from the inline workflow script so its logic is TESTABLE
|
||||
(bug-fix contract, docs/bugfix-contract.md: the silent no-op defect).
|
||||
|
||||
Behavior:
|
||||
- GET /user first: verify the token's identity and log it. Scoped-token
|
||||
failures are diagnosable from the job log instead of mysterious.
|
||||
- Scan open PRs; for each: combined status must be success AND mergeable.
|
||||
- Merge refusals (403/405/anything non-(200,405-already-merged)) FAIL THE JOB
|
||||
with the full error body — never print-and-continue. A robot that cannot
|
||||
merge must be visibly broken, not silently idle.
|
||||
- 405 with "behind the base branch" is retried once after a self-update of
|
||||
the head (informational), then fails loudly if still refused.
|
||||
- Every scanned PR produces a decision line: merged / skipped(reason).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from typing import Any
|
||||
|
||||
|
||||
class MergeRefused(Exception):
|
||||
"""A merge the robot expected to perform was refused by the forge."""
|
||||
|
||||
|
||||
def _api(
|
||||
base: str, token: str, path: str, method: str = "GET", data: Any = None, ok: tuple = (200,)
|
||||
) -> tuple[int, Any]:
|
||||
req = urllib.request.Request(
|
||||
base + path,
|
||||
data=json.dumps(data).encode() if data is not None else None,
|
||||
headers={"Authorization": "token " + token, "Content-Type": "application/json"},
|
||||
method=method,
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as r:
|
||||
body = r.read()
|
||||
status = r.status
|
||||
except urllib.error.HTTPError as e:
|
||||
status = e.code
|
||||
body = e.read()
|
||||
except urllib.error.URLError as e:
|
||||
raise MergeRefused(f"forge unreachable at {path}: {e.reason}") from e
|
||||
parsed: Any = json.loads(body) if body else {}
|
||||
if method == "GET" and status not in ok:
|
||||
raise MergeRefused(f"GET {path} -> {status}: {str(parsed)[:300]}")
|
||||
return status, parsed
|
||||
|
||||
|
||||
def verify_identity(base: str, token: str) -> str:
|
||||
status, user = _api(base, token, "/user")
|
||||
login = user.get("login", "?")
|
||||
print(f"merge-robot: authenticated as {login} (status {status})")
|
||||
return login
|
||||
|
||||
|
||||
def scan(base: str, token: str) -> list[dict]:
|
||||
status, prs = _api(base, token, "/pulls?state=open&limit=50")
|
||||
print(f"merge-robot: {len(prs)} open PR(s)")
|
||||
return prs
|
||||
|
||||
|
||||
def decide(base: str, token: str, pr: dict) -> str:
|
||||
"""Return a decision line for one PR; raises MergeRefused on unexpected refusals."""
|
||||
n = pr["number"]
|
||||
sha = pr["head"]["sha"]
|
||||
status, cs = _api(base, token, f"/commits/{sha}/status")
|
||||
state = cs.get("state")
|
||||
if state != "success":
|
||||
return f"#{n}: skipped (status={state})"
|
||||
status, detail = _api(base, token, f"/pulls/{n}")
|
||||
if not detail.get("mergeable", False):
|
||||
return f"#{n}: skipped (not mergeable)"
|
||||
mstatus, mresp = _api(base, token, f"/pulls/{n}/merge", "POST", {"Do": "merge"})
|
||||
if mstatus == 200:
|
||||
return f"#{n}: MERGED"
|
||||
if mstatus == 405:
|
||||
msg = str(mresp.get("message", ""))
|
||||
if "behind" in msg.lower():
|
||||
return f"#{n}: skipped (head behind base — needs branch update): {msg}"
|
||||
raise MergeRefused(f"#{n} merge refused 405: {msg}")
|
||||
if mstatus == 403:
|
||||
raise MergeRefused(f"#{n} merge FORBIDDEN 403 — token lacks pull-request write scope: {str(mresp)[:300]}")
|
||||
raise MergeRefused(f"#{n} merge failed {mstatus}: {str(mresp)[:300]}")
|
||||
|
||||
|
||||
def main_with(argv: list[str]) -> int:
|
||||
token = argv[1] if len(argv) > 1 else ""
|
||||
base = argv[2] if len(argv) > 2 else ""
|
||||
if not token or not base:
|
||||
print("usage: merge_robot.py <token> <api-base>")
|
||||
return 2
|
||||
try:
|
||||
verify_identity(base, token)
|
||||
prs = scan(base, token)
|
||||
merged = 0
|
||||
for pr in prs:
|
||||
line = decide(base, token, pr)
|
||||
print("merge-robot:", line)
|
||||
if "MERGED" in line:
|
||||
merged += 1
|
||||
time.sleep(1)
|
||||
print(f"merge-robot: done — {merged} merged of {len(prs)} scanned")
|
||||
return 0
|
||||
except MergeRefused as exc:
|
||||
print(f"merge-robot: FAILING JOB — {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
def main() -> int:
|
||||
return main_with(sys.argv)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+23
-8
@@ -25,6 +25,7 @@ Usage:
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sqlite3
|
||||
@@ -48,6 +49,8 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from grading import affirm_rule, grade_fact, tier_of
|
||||
import memory_env
|
||||
|
||||
logger = logging.getLogger("curator")
|
||||
|
||||
BLOCKS_DIR = os.path.join(memory_env.memory_dir(), "blocks")
|
||||
JOURNAL_DIR = os.path.join(memory_env.memory_dir(), "journal")
|
||||
INDEX_FILE = os.path.join(memory_env.memory_dir(), "index", "blocks_meta.json")
|
||||
@@ -83,6 +86,7 @@ def _aaak(text, topic=""):
|
||||
import aaak
|
||||
return aaak.compress(text, topic=topic, source_file="curator")
|
||||
except Exception:
|
||||
logger.debug("_aaak failed", exc_info=True)
|
||||
return ""
|
||||
|
||||
|
||||
@@ -117,6 +121,7 @@ def le_promote_eligible(proposal, existing, strength, min_strength=3,
|
||||
corpus_texts=corpus_texts)
|
||||
except Exception:
|
||||
# Fallback: old behaviour (strength-only) if the lexicon module is gone.
|
||||
logger.debug("le_promote_eligible failed", exc_info=True)
|
||||
return {"eligible": strength >= adjusted_min,
|
||||
"reason": f"lexicon module unavailable — strength gate only (adjusted_min={adjusted_min}, wash_count={wash_count})"}
|
||||
|
||||
@@ -131,6 +136,7 @@ def _block_values(label):
|
||||
db.close()
|
||||
return [r[0] for r in rows]
|
||||
except Exception:
|
||||
logger.debug("_block_values failed", exc_info=True)
|
||||
return []
|
||||
|
||||
|
||||
@@ -145,6 +151,7 @@ def _store_corpus(limit=200):
|
||||
db.close()
|
||||
return [r[0] for r in rows]
|
||||
except Exception:
|
||||
logger.debug("_store_corpus failed", exc_info=True)
|
||||
return []
|
||||
|
||||
|
||||
@@ -169,6 +176,7 @@ def _contradicts_identity(fact):
|
||||
"AND status='active'").fetchall()
|
||||
db.close()
|
||||
except Exception:
|
||||
logger.debug("_contradicts_identity failed", exc_info=True)
|
||||
return False
|
||||
values = [r[0] for r in rows]
|
||||
if not values:
|
||||
@@ -176,6 +184,7 @@ def _contradicts_identity(fact):
|
||||
try:
|
||||
return le.coherence(fact, values) == "conflict"
|
||||
except Exception:
|
||||
logger.debug("_contradicts_identity failed", exc_info=True)
|
||||
return False
|
||||
|
||||
|
||||
@@ -217,6 +226,7 @@ def store_has(text, topic=None):
|
||||
db.close()
|
||||
return n > 0
|
||||
except Exception:
|
||||
logger.debug("store_has failed", exc_info=True)
|
||||
return False
|
||||
|
||||
|
||||
@@ -236,7 +246,7 @@ def read_block(label):
|
||||
db.close()
|
||||
body = "\n".join(f"- {r[0]}" for r in rows)
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("read_block failed", exc_info=True)
|
||||
return fm, body
|
||||
|
||||
|
||||
@@ -276,11 +286,11 @@ def write_block(label, fm, body):
|
||||
import memory_store as ms
|
||||
ms._auto_associate(db, eid, text, topic=label, source="curator")
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("write_block failed", exc_info=True)
|
||||
db.commit()
|
||||
db.close()
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("write_block failed", exc_info=True)
|
||||
return block_path(label)
|
||||
|
||||
|
||||
@@ -424,7 +434,7 @@ def _embed(texts):
|
||||
if v:
|
||||
cache[t] = v
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("_embed failed", exc_info=True)
|
||||
finally:
|
||||
try:
|
||||
os.unlink(path)
|
||||
@@ -566,7 +576,7 @@ def promote_candidates(evidence_items, idx, journal_lines):
|
||||
try:
|
||||
audit_ledger.log_promotion(0, "candidate", "promoted", entry["count"], f"candidate seen {entry['count']} times")
|
||||
except Exception:
|
||||
pass # Audit logging is non-critical
|
||||
logger.debug("promote_candidates failed", exc_info=True) # Audit logging is non-critical
|
||||
|
||||
# Remove the promoted candidate so it isn't applied repeatedly.
|
||||
del cands[ck]
|
||||
@@ -675,6 +685,7 @@ def _grounded_in_sessions(fact, threshold, window_days):
|
||||
return True
|
||||
return False
|
||||
except Exception:
|
||||
logger.debug("_grounded_in_sessions failed", exc_info=True)
|
||||
return False
|
||||
|
||||
|
||||
@@ -691,11 +702,13 @@ def _grounded_in_corpus(fact):
|
||||
hits = ms.chunk_recall(db, fact[:120], budget=3, min_sim=0.78)
|
||||
cache[fact] = bool(hits)
|
||||
except Exception:
|
||||
logger.debug("_grounded_in_corpus failed", exc_info=True)
|
||||
cache[fact] = False
|
||||
finally:
|
||||
db.close()
|
||||
return cache[fact]
|
||||
except Exception:
|
||||
logger.debug("_grounded_in_corpus failed", exc_info=True)
|
||||
return False
|
||||
|
||||
|
||||
@@ -1103,7 +1116,7 @@ def apply_op(op, idx, journal_lines):
|
||||
op.get("source", "curator"),
|
||||
int(op.get("strength", 3) or 3))
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("apply_op failed", exc_info=True)
|
||||
return True
|
||||
elif op["op"] == "UPDATE":
|
||||
# Only safe when the evidence explicitly names the exact old entry.
|
||||
@@ -1371,6 +1384,7 @@ def graph_write(fact, evidence="", source="curator", strength=3):
|
||||
capture_output=True, text=True, timeout=15)
|
||||
return '"added": True' in (r.stdout or "")
|
||||
except Exception:
|
||||
logger.debug("graph_write failed", exc_info=True)
|
||||
return False
|
||||
|
||||
|
||||
@@ -1453,6 +1467,7 @@ def run_plan(evidence_items, apply=False):
|
||||
"drift-ledger.py check --strict` to audit")
|
||||
return journal_lines, ops
|
||||
except Exception as e:
|
||||
logger.debug("run_plan failed", exc_info=True)
|
||||
print(f" (drift check unavailable: {e})")
|
||||
for op in ops:
|
||||
if apply:
|
||||
@@ -1481,7 +1496,7 @@ def run_plan(evidence_items, apply=False):
|
||||
_dl2.DB = STORE_DB
|
||||
_dl2.snapshot()
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("run_plan failed", exc_info=True)
|
||||
return journal_lines, ops
|
||||
|
||||
|
||||
@@ -1532,7 +1547,7 @@ def main():
|
||||
})
|
||||
db.close()
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("main failed", exc_info=True)
|
||||
|
||||
if not evidence_items:
|
||||
print("No evidence provided and no recent entries found.", file=sys.stderr)
|
||||
|
||||
+37
-17
@@ -29,6 +29,7 @@ Run under ~/.venvs/memory/bin/python3 (has sqlite-vec).
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sqlite3
|
||||
import subprocess
|
||||
@@ -40,6 +41,8 @@ if _SD not in sys.path:
|
||||
sys.path.insert(0, _SD)
|
||||
import memory_env
|
||||
|
||||
logger = logging.getLogger("memory_store")
|
||||
|
||||
MEM_DIR = memory_env.memory_dir()
|
||||
STORE_DIR = os.path.join(MEM_DIR, "store")
|
||||
DB_PATH = os.environ.get("MEMORY_STORE_DB", memory_env.store_db())
|
||||
@@ -302,7 +305,7 @@ def _embed(texts):
|
||||
if v:
|
||||
cache[t] = v[:EMBED_DIM]
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("_embed failed", exc_info=True)
|
||||
finally:
|
||||
try:
|
||||
os.unlink(path)
|
||||
@@ -348,6 +351,7 @@ def _aaak_summary(text, topic="", source=""):
|
||||
import aaak
|
||||
return aaak.compress(text, topic=topic, source_file=source)
|
||||
except Exception:
|
||||
logger.debug("_aaak_summary failed", exc_info=True)
|
||||
return ""
|
||||
|
||||
|
||||
@@ -375,6 +379,7 @@ def _auto_associate(db, eid, text, topic="", source=""):
|
||||
(eid,)).fetchall()
|
||||
except Exception:
|
||||
# Fallback: if vec0 query fails, skip associations
|
||||
logger.debug("_auto_associate failed", exc_info=True)
|
||||
return
|
||||
|
||||
total = max(db.execute("SELECT COUNT(*) FROM entries "
|
||||
@@ -403,7 +408,7 @@ def _auto_associate(db, eid, text, topic="", source=""):
|
||||
boost = 0.35 + 0.1 * min(n_distinct, 4)
|
||||
associate(db, eid, other_id, boost=boost)
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("_auto_associate failed", exc_info=True)
|
||||
|
||||
|
||||
def _df_word(db, word):
|
||||
@@ -412,6 +417,7 @@ def _df_word(db, word):
|
||||
"SELECT COUNT(*) AS n FROM entries WHERE status='active' "
|
||||
"AND text LIKE ?", (f"%{word}%",)).fetchone()["n"]
|
||||
except Exception:
|
||||
logger.debug("_df_word failed", exc_info=True)
|
||||
return 0
|
||||
|
||||
|
||||
@@ -426,7 +432,7 @@ def _run_lexicon_reconcile():
|
||||
"--fix"],
|
||||
capture_output=True, text=True, timeout=600)
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("_run_lexicon_reconcile failed", exc_info=True)
|
||||
|
||||
|
||||
def add_entry(db, text, importance=0.5, topic="", entities=None,
|
||||
@@ -502,7 +508,7 @@ def recall(db, query, budget=RECALL_BUDGET, min_score=RECALL_MIN_SCORE):
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
pass # Cache miss on parse, fall through to full retrieval
|
||||
except (ImportError, Exception):
|
||||
pass # Cache unavailable, proceed without it
|
||||
logger.debug("recall failed", exc_info=True) # Cache unavailable, proceed without it
|
||||
|
||||
# --- Query expansion (research uplift #1). -----------------------------
|
||||
_orig_query = query
|
||||
@@ -515,6 +521,7 @@ def recall(db, query, budget=RECALL_BUDGET, min_score=RECALL_MIN_SCORE):
|
||||
# so we don't blunt the vector signal with synonyms.
|
||||
query = _orig_query
|
||||
except Exception:
|
||||
logger.debug("recall failed", exc_info=True)
|
||||
_extra = []
|
||||
# ------------------------------------------------------------------------
|
||||
qvec = _embed([f"search_query: {query}"]).get(f"search_query: {query}")
|
||||
@@ -548,6 +555,7 @@ def recall(db, query, budget=RECALL_BUDGET, min_score=RECALL_MIN_SCORE):
|
||||
"SELECT COUNT(*) AS n FROM entries WHERE status='active' "
|
||||
"AND text LIKE ?", (f"%{word}%",)).fetchone()["n"]
|
||||
except Exception:
|
||||
logger.debug("recall failed", exc_info=True)
|
||||
return 0
|
||||
dense = []
|
||||
for r in rows:
|
||||
@@ -598,7 +606,7 @@ def recall(db, query, budget=RECALL_BUDGET, min_score=RECALL_MIN_SCORE):
|
||||
for _row in _r:
|
||||
_expanded_hits.add(_row["rowid"])
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("recall failed", exc_info=True)
|
||||
if _expanded_hits:
|
||||
_ids = list(_expanded_hits)[:RECALL_BUDGET * 2]
|
||||
_ph = ",".join("?" * len(_ids))
|
||||
@@ -607,7 +615,7 @@ def recall(db, query, budget=RECALL_BUDGET, min_score=RECALL_MIN_SCORE):
|
||||
f"WHERE rowid IN ({_ph})", _ids).fetchall()
|
||||
bm25 = [(r["rowid"], float(r["score"])) for r in _rows]
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("recall failed", exc_info=True)
|
||||
# (3) Fusion. With BOTH rankers: RRF (Cormack et al. 2009). With ONLY
|
||||
# lexical (embeddings absent): RRF degenerates to a rank transform that
|
||||
# destroys the score signal needed for thresholding (Bruch et al.,
|
||||
@@ -667,7 +675,7 @@ def recall(db, query, budget=RECALL_BUDGET, min_score=RECALL_MIN_SCORE):
|
||||
if days >= 0:
|
||||
recency = RECENCY_HALF_LIFE / (RECENCY_HALF_LIFE + days)
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("recall failed", exc_info=True)
|
||||
# In lexical-only mode `base` is a raw BM25 score (negative).
|
||||
# Normalize it to a positive relevance for the metadata, keeping
|
||||
# the ranking identical. In hybrid mode `base` is an RRF rank.
|
||||
@@ -811,6 +819,7 @@ def gate_consolidated(db, query: str) -> dict:
|
||||
mc = memory_consolidation.MemoryConsolidation()
|
||||
consolidated = mc.format_knowledge_for_prompt(query)
|
||||
except Exception:
|
||||
logger.debug("gate_consolidated failed", exc_info=True)
|
||||
return {"use_consolidated": False, "reason": "consolidation unavailable", "consolidated": ""}
|
||||
|
||||
# Decision factors
|
||||
@@ -825,6 +834,7 @@ def gate_consolidated(db, query: str) -> dict:
|
||||
qm = query_memory.QueryMemory()
|
||||
exploration_rate = qm.adaptive_exploration_rate(query)
|
||||
except Exception:
|
||||
logger.debug("gate_consolidated failed", exc_info=True)
|
||||
exploration_rate = 0.30 # fallback to static rate
|
||||
|
||||
explore = random.random() < exploration_rate
|
||||
@@ -1010,7 +1020,7 @@ def tier_demotion_sweep(db) -> dict:
|
||||
elif current_tier == "warm" and new_tier == "cold":
|
||||
demoted["warm_to_cold"] += 1
|
||||
except Exception:
|
||||
pass # tier column may not exist yet
|
||||
logger.debug("tier_demotion_sweep failed", exc_info=True) # tier column may not exist yet
|
||||
|
||||
db.commit()
|
||||
return demoted
|
||||
@@ -1037,7 +1047,7 @@ def cached_recall(db, query, budget=RECALL_BUDGET, min_score=RECALL_MIN_SCORE):
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
pass
|
||||
except (ImportError, Exception):
|
||||
pass
|
||||
logger.debug("cached_recall failed", exc_info=True)
|
||||
|
||||
# Cache miss — shard routing: route query to correct shard
|
||||
try:
|
||||
@@ -1048,6 +1058,7 @@ def cached_recall(db, query, budget=RECALL_BUDGET, min_score=RECALL_MIN_SCORE):
|
||||
# Use shard for recall if available, fall back to main db
|
||||
recall_db = shard_db if shard_db else db
|
||||
except Exception:
|
||||
logger.debug("cached_recall failed", exc_info=True)
|
||||
recall_db = db
|
||||
|
||||
# Gate logic: consolidated vs full retrieval
|
||||
@@ -1070,7 +1081,7 @@ def cached_recall(db, query, budget=RECALL_BUDGET, min_score=RECALL_MIN_SCORE):
|
||||
_cache.put_cache(_cache_key, json.dumps(result, ensure_ascii=False),
|
||||
scope="retrieval")
|
||||
except (ImportError, Exception):
|
||||
pass
|
||||
logger.debug("cached_recall failed", exc_info=True)
|
||||
|
||||
return result
|
||||
|
||||
@@ -1090,6 +1101,7 @@ def _position_aware(top):
|
||||
reverse=True)
|
||||
return [s_sorted[0]] + s_sorted[2:] + [s_sorted[1]]
|
||||
except Exception:
|
||||
logger.debug("_position_aware failed", exc_info=True)
|
||||
return top
|
||||
|
||||
|
||||
@@ -1170,7 +1182,7 @@ def _fts_delete(db, eid):
|
||||
db.execute("INSERT INTO entries_fts(entries_fts, rowid, text) "
|
||||
"VALUES('delete', ?, ?)", (eid, old["text"]))
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("_fts_delete failed", exc_info=True)
|
||||
|
||||
|
||||
def delete_entry(db, eid):
|
||||
@@ -1218,7 +1230,7 @@ def reindex_entries(db, dry_run=False):
|
||||
"LEFT JOIN entries e ON e.id = v.rowid WHERE e.id IS NULL"
|
||||
).fetchone()["c"]
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("reindex_entries failed", exc_info=True)
|
||||
try:
|
||||
fts_dangling = db.execute(
|
||||
"SELECT COUNT(*) AS c FROM entries_fts f "
|
||||
@@ -1227,7 +1239,7 @@ def reindex_entries(db, dry_run=False):
|
||||
fts_total = db.execute(
|
||||
"SELECT COUNT(*) AS c FROM entries_fts").fetchone()["c"]
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("reindex_entries failed", exc_info=True)
|
||||
if dry_run:
|
||||
return {"indexed": indexed, "total": total, "missing": missing,
|
||||
"dangling": dangling, "fts_dangling": fts_dangling,
|
||||
@@ -1241,7 +1253,7 @@ def reindex_entries(db, dry_run=False):
|
||||
try:
|
||||
db.execute("DELETE FROM entries_fts")
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("reindex_entries failed", exc_info=True)
|
||||
# Contentless FTS5 cannot use DELETE FROM (raises OperationalError).
|
||||
# The clean reset is DROP + recreate, which also clears dangling rows
|
||||
# that a DELETE can never touch.
|
||||
@@ -1251,7 +1263,7 @@ def reindex_entries(db, dry_run=False):
|
||||
"CREATE VIRTUAL TABLE entries_fts USING fts5("
|
||||
"text, content='', tokenize='porter unicode61')")
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("reindex_entries failed", exc_info=True)
|
||||
rows = db.execute(
|
||||
"SELECT id, text FROM entries WHERE status='active'").fetchall()
|
||||
vec_missing = 0
|
||||
@@ -1265,6 +1277,7 @@ def reindex_entries(db, dry_run=False):
|
||||
"INSERT INTO entries_vec (rowid, embedding) VALUES (?,?)",
|
||||
(r["id"], json.dumps(vec)))
|
||||
except Exception:
|
||||
logger.debug("reindex_entries failed", exc_info=True)
|
||||
vec_missing += 1
|
||||
else:
|
||||
vec_missing += 1
|
||||
@@ -1273,6 +1286,7 @@ def reindex_entries(db, dry_run=False):
|
||||
"INSERT INTO entries_fts (rowid, text) VALUES (?,?)",
|
||||
(r["id"], text))
|
||||
except Exception:
|
||||
logger.debug("reindex_entries failed", exc_info=True)
|
||||
fts_missing += 1
|
||||
db.commit()
|
||||
return {"indexed": len(rows), "total": total, "missing": missing,
|
||||
@@ -1418,7 +1432,7 @@ def chunk_recall(db, query, budget=6, wing=None, min_sim=0.0, doc=None):
|
||||
(_fts_query(query), budget * 3)).fetchall()
|
||||
bm25 = [(r["rowid"], 0.5) for r in rows]
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("chunk_recall failed", exc_info=True)
|
||||
ranks = {}
|
||||
for lst in [dense, bm25]:
|
||||
for pos, (eid, _s) in enumerate(lst):
|
||||
@@ -1478,6 +1492,7 @@ def _extract_epub(path):
|
||||
id_map = dict(_re.findall(r'id="([^"]+)"\s+href="([^"]+)"', opf_text))
|
||||
manifest_order = [id_map[i] for i in spine_ids if i in id_map]
|
||||
except Exception:
|
||||
logger.debug("_extract_epub failed", exc_info=True)
|
||||
manifest_order = []
|
||||
if not manifest_order:
|
||||
manifest_order = [n for n in z.namelist()
|
||||
@@ -1513,6 +1528,7 @@ def _extract_epub(path):
|
||||
continue
|
||||
return "\n\n".join(parts)
|
||||
except Exception:
|
||||
logger.debug("_extract_epub failed", exc_info=True)
|
||||
r = subprocess.run(["ebook2text", path], capture_output=True,
|
||||
text=True, timeout=60)
|
||||
return r.stdout
|
||||
@@ -1541,6 +1557,7 @@ def mine_file(db, path, wing="", room="", chunk_size=1500):
|
||||
text = "\n\n".join(p["text"] for p in pages if p.get("text"))
|
||||
except Exception:
|
||||
# fallback: legacy extractor if the upgraded one is unavailable
|
||||
logger.debug("mine_file failed", exc_info=True)
|
||||
r = subprocess.run(["pdftotext", "-layout", path, "-"],
|
||||
capture_output=True, text=True, timeout=60)
|
||||
text = r.stdout
|
||||
@@ -1559,6 +1576,7 @@ def mine_file(db, path, wing="", room="", chunk_size=1500):
|
||||
else:
|
||||
return 0, f"unsupported ext {ext}"
|
||||
except Exception as e:
|
||||
logger.debug("mine_file failed", exc_info=True)
|
||||
return 0, str(e)
|
||||
if not text or not text.strip():
|
||||
return 0, "empty after parse"
|
||||
@@ -1974,6 +1992,7 @@ def main():
|
||||
row = db.execute("SELECT value FROM meta WHERE key='lexicon_version'").fetchone()
|
||||
cur_ver = int(row["value"]) if row else 0
|
||||
except Exception:
|
||||
logger.debug("main failed", exc_info=True)
|
||||
cur_ver = 0
|
||||
if cur_ver < LEXICON_VERSION:
|
||||
_run_lexicon_reconcile()
|
||||
@@ -2010,6 +2029,7 @@ def main():
|
||||
"reason": res.get("receipt", {}).get("reason", "")}))
|
||||
ok = True
|
||||
except Exception as e:
|
||||
logger.debug("main failed", exc_info=True)
|
||||
print(json.dumps({"added": False, "error": str(e)[:120]}))
|
||||
ok = False
|
||||
if ok and args.version:
|
||||
@@ -2021,7 +2041,7 @@ def main():
|
||||
_vm = _u.module_from_spec(_sp); _sp.loader.exec_module(_vm)
|
||||
_vm.snapshot(reason="memory-write", summary=text[:80])
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("main failed", exc_info=True)
|
||||
sys.exit(0 if ok else 1)
|
||||
if args.cmd == "recall":
|
||||
q = " ".join(args.arg)
|
||||
|
||||
@@ -23,6 +23,7 @@ import copy
|
||||
import difflib
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import shlex
|
||||
import sys
|
||||
@@ -33,6 +34,8 @@ from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
logger = logging.getLogger("tool_executor")
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# CONFIGURATION
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
@@ -518,6 +521,7 @@ def _backup_file(path: Path) -> Optional[str]:
|
||||
shutil.copy2(str(path), backup_path)
|
||||
return backup_path
|
||||
except Exception:
|
||||
logger.debug("_backup_file failed", exc_info=True)
|
||||
return None
|
||||
|
||||
|
||||
@@ -543,6 +547,7 @@ def undo_last():
|
||||
return original, f"Restored {original}"
|
||||
return None, "Could not determine original path"
|
||||
except Exception as e:
|
||||
logger.debug("undo_last failed", exc_info=True)
|
||||
return None, f"Undo failed: {e}"
|
||||
|
||||
|
||||
@@ -568,6 +573,7 @@ def generate_diff(path: Path, new_content: str) -> str:
|
||||
)
|
||||
return "".join(diff)
|
||||
except Exception as e:
|
||||
logger.debug("generate_diff failed", exc_info=True)
|
||||
return f"[diff error: {e}]"
|
||||
|
||||
|
||||
@@ -626,6 +632,7 @@ def _execute_tool_now(tool_name: str, args: dict) -> dict:
|
||||
else:
|
||||
return {"success": False, "error": f"Unknown tool: {tool_name}"}
|
||||
except Exception as e:
|
||||
logger.debug("_execute_tool_now failed", exc_info=True)
|
||||
return {"success": False, "error": f"{type(e).__name__}: {e}"}
|
||||
|
||||
|
||||
@@ -860,6 +867,7 @@ def _read_file(args: dict) -> dict:
|
||||
|
||||
return {"success": True, "result": result}
|
||||
except Exception as e:
|
||||
logger.debug("_read_file failed", exc_info=True)
|
||||
return {"success": False, "error": f"Read failed: {e}"}
|
||||
|
||||
|
||||
@@ -912,6 +920,7 @@ def _apply_content(path: str, content: str) -> dict:
|
||||
os.replace(tmp, str(resolved))
|
||||
return {"success": True, "result": f"Wrote {len(content)} chars to {resolved.name}"}
|
||||
except Exception as e:
|
||||
logger.debug("_apply_content failed", exc_info=True)
|
||||
return {"success": False, "error": f"Write failed: {e}"}
|
||||
|
||||
|
||||
@@ -938,6 +947,7 @@ def _list_directory(args: dict) -> dict:
|
||||
entries.append(f"{prefix}{item.name}{'/' if item.is_dir() else ''}")
|
||||
return {"success": True, "result": "\n".join(entries) if entries else "(empty)"}
|
||||
except Exception as e:
|
||||
logger.debug("_list_directory failed", exc_info=True)
|
||||
return {"success": False, "error": f"List failed: {e}"}
|
||||
|
||||
|
||||
@@ -972,9 +982,11 @@ def _search_files(args: dict) -> dict:
|
||||
"result": "\n".join(matches) + "\n[truncated — 50 matches]",
|
||||
}
|
||||
except Exception:
|
||||
logger.debug("_search_files failed", exc_info=True)
|
||||
continue
|
||||
return {"success": True, "result": "\n".join(matches) if matches else "(no matches)"}
|
||||
except Exception as e:
|
||||
logger.debug("_search_files failed", exc_info=True)
|
||||
return {"success": False, "error": f"Search failed: {e}"}
|
||||
|
||||
|
||||
@@ -1020,6 +1032,7 @@ def _run_command(args: dict) -> dict:
|
||||
except subprocess.TimeoutExpired:
|
||||
return {"success": False, "error": "Command timed out (30s)"}
|
||||
except Exception as e:
|
||||
logger.debug("_run_command failed", exc_info=True)
|
||||
return {"success": False, "error": f"Command failed: {e}"}
|
||||
|
||||
|
||||
@@ -1071,6 +1084,7 @@ def _edit_file(args: dict) -> dict:
|
||||
"content": new_content,
|
||||
}
|
||||
except Exception as e:
|
||||
logger.debug("_edit_file failed", exc_info=True)
|
||||
return {"success": False, "error": f"Edit failed: {e}"}
|
||||
|
||||
|
||||
@@ -1105,6 +1119,7 @@ def _glob_files(args: dict) -> dict:
|
||||
|
||||
return {"success": True, "result": "\n".join(formatted) if formatted else "(no matches)"}
|
||||
except Exception as e:
|
||||
logger.debug("_glob_files failed", exc_info=True)
|
||||
return {"success": False, "error": f"Glob failed: {e}"}
|
||||
|
||||
|
||||
@@ -1145,6 +1160,7 @@ def _grep_files(args: dict) -> dict:
|
||||
except subprocess.TimeoutExpired:
|
||||
return {"success": False, "error": "Search timed out"}
|
||||
except Exception as e:
|
||||
logger.debug("_grep_files failed", exc_info=True)
|
||||
return {"success": False, "error": f"Grep failed: {e}"}
|
||||
|
||||
|
||||
@@ -1246,6 +1262,7 @@ def _lint_file(args: dict) -> dict:
|
||||
else:
|
||||
return {"success": False, "error": result.stdout or result.stderr}
|
||||
except Exception as e:
|
||||
logger.debug("_lint_file failed", exc_info=True)
|
||||
return {"success": False, "error": f"Lint failed: {e}"}
|
||||
|
||||
|
||||
@@ -1286,6 +1303,7 @@ def _run_tests(args: dict) -> dict:
|
||||
except subprocess.TimeoutExpired:
|
||||
return {"success": False, "error": "Tests timed out (120s)"}
|
||||
except Exception as e:
|
||||
logger.debug("_run_tests failed", exc_info=True)
|
||||
return {"success": False, "error": f"Test failed: {e}"}
|
||||
|
||||
|
||||
@@ -1315,6 +1333,7 @@ def _format_code(args: dict) -> dict:
|
||||
else:
|
||||
return {"success": False, "error": result.stdout or result.stderr}
|
||||
except Exception as e:
|
||||
logger.debug("_format_code failed", exc_info=True)
|
||||
return {"success": False, "error": f"Format failed: {e}"}
|
||||
|
||||
|
||||
@@ -1340,6 +1359,7 @@ def _git_diff(args: dict) -> dict:
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
|
||||
return {"success": True, "result": result.stdout or "(no changes)"}
|
||||
except Exception as e:
|
||||
logger.debug("_git_diff failed", exc_info=True)
|
||||
return {"success": False, "error": f"Git diff failed: {e}"}
|
||||
|
||||
|
||||
@@ -1358,6 +1378,7 @@ def _git_log(args: dict) -> dict:
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
|
||||
return {"success": True, "result": result.stdout or "(no commits)"}
|
||||
except Exception as e:
|
||||
logger.debug("_git_log failed", exc_info=True)
|
||||
return {"success": False, "error": f"Git log failed: {e}"}
|
||||
|
||||
|
||||
@@ -1387,6 +1408,7 @@ def _git_commit(args: dict) -> dict:
|
||||
else:
|
||||
return {"success": False, "error": result.stderr or "Commit failed"}
|
||||
except Exception as e:
|
||||
logger.debug("_git_commit failed", exc_info=True)
|
||||
return {"success": False, "error": f"Git commit failed: {e}"}
|
||||
|
||||
|
||||
@@ -1420,6 +1442,7 @@ def _repo_map(args: dict) -> dict:
|
||||
# Fallback: simple function/class extraction via grep
|
||||
return _repo_map_fallback(resolved)
|
||||
except Exception:
|
||||
logger.debug("_repo_map failed", exc_info=True)
|
||||
return _repo_map_fallback(resolved)
|
||||
|
||||
|
||||
@@ -1446,6 +1469,7 @@ def _repo_map_fallback(path: Path) -> dict:
|
||||
results.append(f"## {lang}")
|
||||
results.extend(lines)
|
||||
except Exception:
|
||||
logger.debug("_repo_map_fallback failed", exc_info=True)
|
||||
continue
|
||||
|
||||
return {"success": True, "result": "\n".join(results) if results else "(no symbols found)"}
|
||||
@@ -1475,6 +1499,7 @@ def _read_persona(args: dict) -> dict:
|
||||
persona = content[persona_start:persona_end] if persona_end != -1 else content[persona_start:]
|
||||
return {"success": True, "result": persona[:5000]}
|
||||
except Exception as e:
|
||||
logger.debug("_read_persona failed", exc_info=True)
|
||||
return {"success": False, "error": f"Failed to read persona: {e}"}
|
||||
|
||||
|
||||
@@ -1507,6 +1532,7 @@ def _query_memory(args: dict) -> dict:
|
||||
finally:
|
||||
db.close()
|
||||
except Exception as e:
|
||||
logger.debug("_query_memory failed", exc_info=True)
|
||||
return {"success": False, "error": f"Memory query failed: {e}"}
|
||||
|
||||
|
||||
@@ -1534,6 +1560,7 @@ def _check_growth(args: dict) -> dict:
|
||||
else:
|
||||
return {"success": True, "result": "(no growth entries)"}
|
||||
except Exception as e:
|
||||
logger.debug("_check_growth failed", exc_info=True)
|
||||
return {"success": False, "error": f"Growth check failed: {e}"}
|
||||
|
||||
|
||||
@@ -1587,6 +1614,7 @@ def _diagnose_behavior(args: dict) -> dict:
|
||||
|
||||
return {"success": True, "result": json.dumps(diagnosis, indent=2)}
|
||||
except Exception as e:
|
||||
logger.debug("_diagnose_behavior failed", exc_info=True)
|
||||
return {"success": False, "error": f"Diagnosis failed: {e}"}
|
||||
|
||||
|
||||
@@ -1617,6 +1645,7 @@ def _find_capability(args: dict) -> dict:
|
||||
import capability_broker as broker
|
||||
matches = broker.find_capability(query)
|
||||
except Exception as exc:
|
||||
logger.debug("_find_capability failed", exc_info=True)
|
||||
return {"success": False, "error": f"find_capability failed: {exc}"}
|
||||
|
||||
if not matches:
|
||||
|
||||
+27
-16
@@ -28,6 +28,7 @@ Usage:
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
@@ -37,6 +38,8 @@ _SD = os.path.dirname(os.path.abspath(__file__))
|
||||
if _SD not in sys.path: sys.path.insert(0, _SD)
|
||||
import memory_env
|
||||
|
||||
logger = logging.getLogger("warm_router")
|
||||
|
||||
MEM_DIR = memory_env.memory_dir()
|
||||
STATE = os.path.join(MEM_DIR, "index", "warm_state.json")
|
||||
STORE_DB = memory_env.store_db()
|
||||
@@ -112,7 +115,7 @@ def record_outcome(session_id, outcome="helpful"):
|
||||
finally:
|
||||
db.close()
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("record_outcome failed", exc_info=True)
|
||||
|
||||
|
||||
def record_neuron_fire(entry_id, score=0.0, session_id="", outcome="unknown"):
|
||||
@@ -130,7 +133,7 @@ def record_neuron_fire(entry_id, score=0.0, session_id="", outcome="unknown"):
|
||||
finally:
|
||||
db.close()
|
||||
except Exception:
|
||||
pass # Non-critical — don't break firing
|
||||
logger.debug("record_neuron_fire failed", exc_info=True) # Non-critical — don't break firing
|
||||
|
||||
|
||||
def base_level_activation(entry_id, db=None):
|
||||
@@ -176,13 +179,14 @@ def base_level_activation(entry_id, db=None):
|
||||
return max(-2.0, min(b_i, 2.0))
|
||||
|
||||
except Exception:
|
||||
logger.debug("base_level_activation failed", exc_info=True)
|
||||
return -2.0 # Graceful fallback
|
||||
finally:
|
||||
if _own_db and db is not None:
|
||||
try:
|
||||
db.close()
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("base_level_activation failed", exc_info=True)
|
||||
|
||||
|
||||
def _db():
|
||||
@@ -196,6 +200,7 @@ def _aaak(text):
|
||||
import aaak
|
||||
return aaak.compress(text, topic="warm")
|
||||
except Exception:
|
||||
logger.debug("_aaak failed", exc_info=True)
|
||||
return ""
|
||||
|
||||
|
||||
@@ -224,7 +229,7 @@ def list_neurons():
|
||||
).fetchall()
|
||||
finally:
|
||||
db.close()
|
||||
except Exception as exc: # P0-06: observable degrade (T1)
|
||||
except Exception as exc: # noqa: BLE001 — degrade recorded via subsystem_health (P0-06)
|
||||
from rune.subsystem_health import record_failure
|
||||
|
||||
record_failure("warm_router", exc, tier=1, context="list_neurons")
|
||||
@@ -304,11 +309,11 @@ def write_neuron(slug, triggers, body, importance=0.5):
|
||||
source="warm_router")
|
||||
finally:
|
||||
dbw.close()
|
||||
except Exception as exc: # P0-06: observable degrade (T1)
|
||||
except Exception as exc: # noqa: BLE001 — degrade recorded via subsystem_health (P0-06)
|
||||
from rune.subsystem_health import record_failure
|
||||
|
||||
record_failure("warm_router", exc, tier=1, context="auto-associate")
|
||||
except Exception as exc: # P0-06: observable degrade (T1)
|
||||
except Exception as exc: # noqa: BLE001 — degrade recorded via subsystem_health (P0-06)
|
||||
from rune.subsystem_health import record_failure
|
||||
|
||||
record_failure("warm_router", exc, tier=1, context="write_neuron")
|
||||
@@ -357,7 +362,7 @@ def score_neuron(neuron, low_text, session_context=None, query_vec=None):
|
||||
if na and nb:
|
||||
semantic_score = dot / (na * nb)
|
||||
except Exception:
|
||||
pass # Semantic scoring is optional — keyword fallback works
|
||||
logger.debug("score_neuron failed", exc_info=True) # Semantic scoring is optional — keyword fallback works
|
||||
|
||||
# Signal 3: Context match (if session context provided)
|
||||
context_score = 0.0
|
||||
@@ -420,7 +425,7 @@ def score_neuron(neuron, low_text, session_context=None, query_vec=None):
|
||||
score += cache_boost
|
||||
cache.access(entry_id)
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("score_neuron failed", exc_info=True)
|
||||
|
||||
# Signal 7: Body-knowledge relevance (Souveraine enhancement)
|
||||
body_knowledge = neuron.get("body_knowledge", "")
|
||||
@@ -492,13 +497,14 @@ def route(text, max_tokens=DEFAULT_MAX_TOKENS, max_blocks=None,
|
||||
if primed:
|
||||
session_context = " ".join(primed.keys())
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("route failed", exc_info=True)
|
||||
|
||||
# Pre-compute query embedding once (audit fix: was N HTTP calls)
|
||||
try:
|
||||
import memory_store as _ms
|
||||
_query_vec = _ms._embed([low]).get(low)
|
||||
except Exception:
|
||||
logger.debug("route failed", exc_info=True)
|
||||
_query_vec = None
|
||||
|
||||
scored = [(score_neuron(n, low, session_context=session_context,
|
||||
@@ -567,7 +573,7 @@ def route(text, max_tokens=DEFAULT_MAX_TOKENS, max_blocks=None,
|
||||
"via_association": True})
|
||||
used_tokens += a["tokens"]
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("route failed", exc_info=True)
|
||||
# Record what fired this turn for the next turn's priming.
|
||||
if session_id and fired:
|
||||
try:
|
||||
@@ -577,7 +583,7 @@ def route(text, max_tokens=DEFAULT_MAX_TOKENS, max_blocks=None,
|
||||
[f["slug"] for f in fired],
|
||||
_max_score)
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("route failed", exc_info=True)
|
||||
# Write accumulated state once (audit fix: was N+1 file writes)
|
||||
save_state(_route_state)
|
||||
return fired, len(neurons), [{"slug": n["slug"], "score": round(s, 2)}
|
||||
@@ -653,7 +659,7 @@ def route_proactive(session_id="", active_tasks=None, recent_errors=None):
|
||||
if commitments:
|
||||
queries.append("commitment reminder promise")
|
||||
except (ImportError, Exception):
|
||||
pass
|
||||
logger.debug("route_proactive failed", exc_info=True)
|
||||
|
||||
if not queries:
|
||||
return [], 0, []
|
||||
@@ -710,7 +716,7 @@ def _associated_neuron_bodies(fired, budget_tokens):
|
||||
finally:
|
||||
db.close()
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("_associated_neuron_bodies failed", exc_info=True)
|
||||
return out
|
||||
|
||||
|
||||
@@ -728,6 +734,7 @@ def graph_context(term, hops=1, limit=4):
|
||||
capture_output=True, text=True, timeout=10)
|
||||
data = json.loads(r.stdout)
|
||||
except Exception:
|
||||
logger.debug("graph_context failed", exc_info=True)
|
||||
return ""
|
||||
# AUDIT FIX 2026-08-16: graph_memory.query returns a LIST of facts ([] for
|
||||
# an unknown entity), not a dict — the old `data.get("facts")` crashed with
|
||||
@@ -805,7 +812,7 @@ def _prime_neurons(session_id, slugs, score):
|
||||
if (now - last).total_seconds() > 86400:
|
||||
stale.append(s)
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("_prime_neurons failed", exc_info=True)
|
||||
for s in stale:
|
||||
del st["sessions"][s]
|
||||
if len(st["sessions"]) > 40:
|
||||
@@ -866,6 +873,7 @@ def _primed_associations(session_id, limit=4):
|
||||
finally:
|
||||
db.close()
|
||||
except Exception:
|
||||
logger.debug("_primed_associations failed", exc_info=True)
|
||||
return []
|
||||
|
||||
|
||||
@@ -875,7 +883,7 @@ def load_state():
|
||||
with open(STATE) as _fh:
|
||||
return json.load(_fh)
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("load_state failed", exc_info=True)
|
||||
return {"neurons": {}, "divides": []}
|
||||
|
||||
|
||||
@@ -949,12 +957,13 @@ def promote_active(dry_run=False):
|
||||
(slug, ", ".join(trigs), r["id"]))
|
||||
promoted += 1
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("promote_active failed", exc_info=True)
|
||||
db.commit()
|
||||
return promoted
|
||||
finally:
|
||||
db.close()
|
||||
except Exception:
|
||||
logger.debug("promote_active failed", exc_info=True)
|
||||
return 0
|
||||
|
||||
|
||||
@@ -1078,6 +1087,7 @@ def always_digest(max_tokens=ALWAYS_DIGEST_TOKENS):
|
||||
finally:
|
||||
db.close()
|
||||
except Exception:
|
||||
logger.debug("always_digest failed", exc_info=True)
|
||||
return []
|
||||
out = []
|
||||
used = 0
|
||||
@@ -1163,6 +1173,7 @@ def handle_hook(event, data=None):
|
||||
"fired_slugs": [f.get("slug", "") for f in fired[:5]],
|
||||
}
|
||||
except Exception as e:
|
||||
logger.debug("handle_hook failed", exc_info=True)
|
||||
return {"status": "error", "event": event, "error": str(e)[:120]}
|
||||
return {"status": "ok", "event": event, "handler": "warm_router"}
|
||||
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
"""Unit tests for scripts/merge_robot.py — the fail-loud merge-on-green logic.
|
||||
|
||||
Bug-fix contract red-first: the original inline robot swallowed merge refusals
|
||||
(print-and-continue, exit 0) — the silent no-op defect. These tests freeze the
|
||||
fail-loud behavior: refusals fail the job, identity is verified first, every
|
||||
scan produces a decision line.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
SPEC = importlib.util.spec_from_file_location("merge_robot", ROOT / "scripts" / "merge_robot.py")
|
||||
mr = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(mr)
|
||||
|
||||
|
||||
class FakeForge:
|
||||
"""Simulates the SERVER contract (not the client's logic — no circularity)."""
|
||||
|
||||
def __init__(self, prs, statuses, merge_results):
|
||||
self.prs = prs
|
||||
self.statuses = statuses # sha -> state
|
||||
self.merge_results = merge_results # pr_number -> (status, body)
|
||||
self.mergeable: dict[int, bool] = {} # pr_number -> server-reported mergeable
|
||||
self.calls: list[tuple[str, str]] = []
|
||||
|
||||
def get(self, path):
|
||||
self.calls.append(("GET", path))
|
||||
if path == "/user":
|
||||
return 200, {"login": "gitea-actions-robot"}
|
||||
if path.startswith("/pulls?state=open"):
|
||||
return 200, self.prs
|
||||
if path.startswith("/commits/"):
|
||||
sha = path.split("/")[2]
|
||||
return 200, {"state": self.statuses.get(sha, "pending")}
|
||||
if path.startswith("/pulls/") and not path.endswith("/merge"):
|
||||
n = int(path.split("/")[2])
|
||||
for pr in self.prs:
|
||||
if pr["number"] == n:
|
||||
# server truth: GET /pulls/{n} includes mergeable (default True)
|
||||
return 200, {**pr, "mergeable": self.mergeable.get(n, True)}
|
||||
return 404, {}
|
||||
raise AssertionError(f"unexpected GET {path}")
|
||||
|
||||
def post(self, path, data):
|
||||
self.calls.append(("POST", path))
|
||||
if path.endswith("/merge"):
|
||||
n = int(path.split("/")[2])
|
||||
return self.merge_results.get(n, (200, {}))
|
||||
raise AssertionError(f"unexpected POST {path}")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def forge(monkeypatch):
|
||||
f = FakeForge([], {}, {})
|
||||
|
||||
def fake_api(base, token, path, method="GET", data=None, ok=(200,)):
|
||||
f.calls.append((method, path))
|
||||
if method == "GET":
|
||||
status, body = f.get(path)
|
||||
else:
|
||||
status, body = f.post(path, data)
|
||||
return status, body
|
||||
|
||||
monkeypatch.setattr(mr, "_api", fake_api)
|
||||
return f
|
||||
|
||||
|
||||
def _pr(n, sha, state="success", mergeable=True):
|
||||
return {"number": n, "head": {"sha": sha}}, {sha: state}, mergeable
|
||||
|
||||
|
||||
def test_identity_verified_before_any_merge(forge, capsys):
|
||||
forge.prs = [{"number": 1, "head": {"sha": "a"}}]
|
||||
forge.statuses = {"a": "pending"}
|
||||
mr.main_with(["merge_robot.py", "tok", "http://x/api/v1/repos/o/r"])
|
||||
assert ("GET", "/user") == forge.calls[0], "identity check must be the first call"
|
||||
|
||||
|
||||
def test_merge_refusal_403_fails_job(forge, capsys):
|
||||
forge.prs = [{"number": 7, "head": {"sha": "s7"}}]
|
||||
forge.statuses = {"s7": "success"}
|
||||
forge.merge_results = {7: (403, {"message": "token does not have required scope"})}
|
||||
with pytest.raises(mr.MergeRefused, match="403"):
|
||||
mr.decide("base", "tok", forge.prs[0])
|
||||
|
||||
|
||||
def test_merge_refusal_405_unexpected_fails_job(forge):
|
||||
forge.prs = [{"number": 8, "head": {"sha": "s8"}}]
|
||||
forge.statuses = {"s8": "success"}
|
||||
forge.merge_results = {8: (405, {"message": "protected branch rejects"})}
|
||||
with pytest.raises(mr.MergeRefused, match="405"):
|
||||
mr.decide("base", "tok", forge.prs[0])
|
||||
|
||||
|
||||
def test_merge_success_returns_merged(forge):
|
||||
forge.prs = [{"number": 9, "head": {"sha": "s9"}}]
|
||||
forge.statuses = {"s9": "success"}
|
||||
forge.merge_results = {9: (200, {})}
|
||||
assert "MERGED" in mr.decide("base", "tok", forge.prs[0])
|
||||
|
||||
|
||||
def test_pending_pr_skipped_not_merged(forge):
|
||||
forge.prs = [{"number": 10, "head": {"sha": "s10"}}]
|
||||
forge.statuses = {"s10": "pending"}
|
||||
assert "skipped" in mr.decide("base", "tok", forge.prs[0])
|
||||
assert not any(m == "POST" for m, _ in forge.calls), "must not attempt merge on pending"
|
||||
|
||||
|
||||
def test_conflict_pr_skipped(forge):
|
||||
forge.prs = [{"number": 11, "head": {"sha": "s11"}}]
|
||||
forge.statuses = {"s11": "success"}
|
||||
forge.mergeable = {11: False} # server reports conflict
|
||||
assert "skipped" in mr.decide("base", "tok", forge.prs[0])
|
||||
assert not any(m == "POST" for m, _ in forge.calls)
|
||||
|
||||
|
||||
def test_behind_base_405_is_skip_not_crash(forge):
|
||||
"""405 'behind the base branch' = needs branch update, not a robot failure."""
|
||||
forge.prs = [{"number": 12, "head": {"sha": "s12"}}]
|
||||
forge.statuses = {"s12": "success"}
|
||||
forge.merge_results = {12: (405, {"message": "The head branch is behind the base branch"})}
|
||||
assert "skipped" in mr.decide("base", "tok", forge.prs[0])
|
||||
|
||||
|
||||
def test_main_exits_1_on_refusal(forge, monkeypatch):
|
||||
forge.prs = [{"number": 13, "head": {"sha": "s13"}}]
|
||||
forge.statuses = {"s13": "success"}
|
||||
forge.merge_results = {13: (403, {"message": "no scope"})}
|
||||
|
||||
def fake_scan(base, token):
|
||||
return forge.prs
|
||||
|
||||
monkeypatch.setattr(mr, "scan", fake_scan)
|
||||
rc = mr.main_with(["merge_robot.py", "tok", "base"])
|
||||
assert rc == 1, "refusal must fail the job (exit 1) — the silent no-op defect"
|
||||
|
||||
|
||||
def test_main_exits_0_all_merged(forge, monkeypatch):
|
||||
forge.prs = [{"number": 14, "head": {"sha": "s14"}}]
|
||||
forge.statuses = {"s14": "success"}
|
||||
forge.merge_results = {14: (200, {})}
|
||||
|
||||
def fake_scan(base, token):
|
||||
return forge.prs
|
||||
|
||||
monkeypatch.setattr(mr, "scan", fake_scan)
|
||||
assert mr.main_with(["merge_robot.py", "tok", "base"]) == 0
|
||||
Reference in new issue
Block a user