Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9835261517 |
No files matched your search
@@ -1,20 +0,0 @@
|
||||
---
|
||||
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.
|
||||
@@ -15,9 +15,6 @@
|
||||
# Canary files are omitted: src/rune/canary_*.py are standalone CI
|
||||
# verification scripts executed directly by the canary job, never imported by
|
||||
# the test suite — counting them would make the global floor a fiction.
|
||||
# ffi_query_memory_smoke.py is the same class: a standalone evidence script
|
||||
# driven directly (and by tests/test_ffi_query_memory_smoke.py when the cdylib
|
||||
# is built), never imported by the suite.
|
||||
|
||||
[run]
|
||||
source = src/rune
|
||||
@@ -25,7 +22,6 @@ omit =
|
||||
tests/*
|
||||
scripts/*
|
||||
src/rune/canary_*.py
|
||||
src/rune/ffi_query_memory_smoke.py
|
||||
|
||||
[report]
|
||||
fail_under = 29
|
||||
|
||||
@@ -6,12 +6,11 @@ labels: bug
|
||||
assignees: conductor
|
||||
---
|
||||
|
||||
<restate the issue title here in everyday words — this heading IS the
|
||||
plain-English summary; no meta-labels like "plain English" in it>
|
||||
<!-- The heading above carries the summary itself — a scan of issue
|
||||
headings alone should tell the whole story of the board. TOP PRIORITY:
|
||||
if a technical detail below contradicts this section, the issue is
|
||||
buggy — fix the issue. -->
|
||||
## In plain English: <restate the issue title here in everyday words>
|
||||
<!-- The heading ITSELF must carry the summary — a scan of issue headings
|
||||
alone should tell the whole story of the board. TOP PRIORITY: if a
|
||||
technical detail below contradicts this section, the issue is buggy —
|
||||
fix the issue. -->
|
||||
<!-- SUBMITTED_BODY -->
|
||||
|
||||
|
||||
|
||||
@@ -6,12 +6,11 @@ labels: feature
|
||||
assignees: conductor
|
||||
---
|
||||
|
||||
<restate the issue title here in everyday words — this heading IS the
|
||||
plain-English summary; no meta-labels like "plain English" in it>
|
||||
<!-- The heading above carries the summary itself — a scan of issue
|
||||
headings alone should tell the whole story of the board. TOP PRIORITY:
|
||||
if a technical detail below contradicts this section, the issue is
|
||||
buggy — fix the issue. A non-technical reader must be able to retell this
|
||||
## In plain English: <restate the issue title here in everyday words>
|
||||
<!-- The heading ITSELF must carry the summary — a scan of issue headings
|
||||
alone should tell the whole story of the board. TOP PRIORITY: if a
|
||||
technical detail below contradicts this section, the issue is buggy —
|
||||
fix the issue. A non-technical reader must be able to retell this
|
||||
section. 3-6 sentences, no jargon. -->
|
||||
<!-- SUBMITTED_BODY -->
|
||||
|
||||
|
||||
@@ -6,12 +6,11 @@ labels: research
|
||||
assignees: conductor
|
||||
---
|
||||
|
||||
<restate the issue title here in everyday words — this heading IS the
|
||||
plain-English summary; no meta-labels like "plain English" in it>
|
||||
<!-- The heading above carries the summary itself — a scan of issue
|
||||
headings alone should tell the whole story of the board. TOP PRIORITY:
|
||||
if a technical detail below contradicts this section, the issue is
|
||||
buggy — fix the issue. -->
|
||||
## In plain English: <restate the issue title here in everyday words>
|
||||
<!-- The heading ITSELF must carry the summary — a scan of issue headings
|
||||
alone should tell the whole story of the board. TOP PRIORITY: if a
|
||||
technical detail below contradicts this section, the issue is buggy —
|
||||
fix the issue. -->
|
||||
<!-- SUBMITTED_BODY -->
|
||||
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ on:
|
||||
|
||||
jobs:
|
||||
backup:
|
||||
runs-on: rune-ci-desktop
|
||||
runs-on: rune-infra-pi
|
||||
steps:
|
||||
# actions/checkout v4.2.2, pinned to the audited upstream tag commit.
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||
|
||||
+56
-120
@@ -7,38 +7,49 @@ on:
|
||||
types: [opened, edited]
|
||||
|
||||
jobs:
|
||||
# SINGLE-PASS FILING (2026-10-07, Nick's first-time-correct directive):
|
||||
# the old design ran TWO jobs on submission — priority-gate (which saw
|
||||
# no P-label and posted the ⚠️ warning) and auto-label (which inferred
|
||||
# and applied the P-label). The gate ran BEFORE the inference that
|
||||
# would have made the warning unnecessary: every keyword-inferrable
|
||||
# submission ate a spurious warning, a flag add/remove cycle, and a
|
||||
# wasted workflow run. The fix is ORDER: infer → apply → THEN gate.
|
||||
# A submission whose priority is inferable gets its P-label in this
|
||||
# same run; the warning fires only when inference genuinely produced
|
||||
# nothing (a true filing gap, not a race the robot loses to itself).
|
||||
auto-label:
|
||||
runs-on: rune-ci-desktop
|
||||
# PRIORITY GATE (2026-09-04): every issue must carry exactly one of
|
||||
# P0/P1/P2/P3. An issue that lands without one gets 'unprioritized' +
|
||||
# a demand comment — filing is not complete until prioritized.
|
||||
priority-gate:
|
||||
if: github.event_name == 'issues' && github.event.action != 'labeled'
|
||||
runs-on: rune-infra-pi
|
||||
steps:
|
||||
- name: Infer, apply, then gate-check (one pass)
|
||||
- name: Enforce priority label
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
// CLOSED-ISSUE GUARD (#407): labels are filing-time metadata.
|
||||
// A closed issue's lifecycle has ended; re-running label
|
||||
// inference on it re-adds stale type labels (bug = currently
|
||||
// incorrect behavior — a closed fixed issue must not carry
|
||||
// it) and makes any human label cleanup self-defeating,
|
||||
// because every PUT fires a 'labeled' event that re-triggers
|
||||
// this job. Post-close label curation belongs to humans and
|
||||
// the conductor, not this workflow.
|
||||
const issueState = context.payload.issue?.state;
|
||||
if (issueState === 'closed') {
|
||||
console.log(`Issue #${context.payload.issue?.number} is closed — auto-label skips (labels are curated post-close).`);
|
||||
const issue = context.payload.issue;
|
||||
if (!issue) return;
|
||||
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) {
|
||||
// Prioritized — clear the flag if it was set.
|
||||
if (labels.includes('unprioritized')) {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner: context.repo.owner, repo: context.repo.repo,
|
||||
issue_number: issue.number, name: 'unprioritized',
|
||||
}).catch(e => { if (e.status !== 404) throw e; });
|
||||
}
|
||||
return;
|
||||
}
|
||||
const action = context.payload.action;
|
||||
const isIssue = context.payload.issue !== undefined;
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner, repo: context.repo.repo,
|
||||
issue_number: issue.number, labels: ['unprioritized'],
|
||||
});
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner, repo: context.repo.repo,
|
||||
issue_number: issue.number,
|
||||
body: `⚠️ **Priority gate:** this issue has no priority. Assign exactly one of **P0 — critical** (spine/correctness/blocks), **P1 — high** (material value or real defect), **P2 — medium** (quality/consolidation), **P3 — low** (measurement/deferred). An issue without a priority is not filed.`,
|
||||
});
|
||||
|
||||
auto-label:
|
||||
runs-on: rune-infra-pi
|
||||
steps:
|
||||
- name: Analyze and label
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const title = context.payload.issue?.title || context.payload.pull_request?.title || '';
|
||||
const body = context.payload.issue?.body || context.payload.pull_request?.body || '';
|
||||
const text = (title + ' ' + body).toLowerCase();
|
||||
@@ -47,29 +58,25 @@ jobs:
|
||||
const managedLabels = new Set([
|
||||
'memory', 'governance', 'identity', 'growth',
|
||||
'perception', 'infrastructure', 'life', 'custodian',
|
||||
'bug', 'feature', 'research',
|
||||
'P0 — critical', 'P1 — high', 'P2 — medium', 'P3 — low',
|
||||
'priority: high', 'bug', 'feature', 'research',
|
||||
]);
|
||||
|
||||
// Type label: DECLARED over GUESSED. The template spine
|
||||
// (kind: bug|feature|research|epic|...) is authoritative.
|
||||
// A recognized kind maps to its label; ANY other declared kind
|
||||
// (e.g. epic) means NO type label and NO keyword guessing —
|
||||
// epics are containers, not bugs. Keyword heuristics apply
|
||||
// only to pre-template issues with no spine at all.
|
||||
// (kind: bug|feature|research) is authoritative. Keyword
|
||||
// heuristics are a fallback for issues filed before the
|
||||
// template system existed — they misclassify honest prose
|
||||
// ("what is broken", "the fix") as bugs (T15 audit finding).
|
||||
let kind = null;
|
||||
const spineMatch = body && body.match(/^kind:\s*(bug|feature|research)\s*$/m);
|
||||
if (spineMatch) {
|
||||
kind = spineMatch[1];
|
||||
}
|
||||
let isBug = false, isFeature = false, isResearch = false;
|
||||
const kindMatch = body && body.match(/^kind:\s*([a-z_-]+)\s*$/m);
|
||||
if (kindMatch) {
|
||||
const kind = kindMatch[1];
|
||||
if (kind) {
|
||||
isBug = kind === 'bug';
|
||||
isFeature = kind === 'feature';
|
||||
isResearch = kind === 'research';
|
||||
} else if (action === 'opened') {
|
||||
// KEYWORD FALLBACK (#407): pre-template issues only, and
|
||||
// ONLY at filing time. Re-running keyword guesses on every
|
||||
// edit/label event overrides human curation of spine-less
|
||||
// issues (documented rule: keyword heuristics are the
|
||||
// pre-template fallback, not a standing authority).
|
||||
} else {
|
||||
const textBug = title.startsWith('[BUG]') || text.includes('bug') || text.includes('fix') || text.includes('broken');
|
||||
isBug = textBug;
|
||||
isFeature = !isBug && (title.startsWith('[FEATURE]') || text.includes('feature') || text.includes('improve') || text.includes('add'));
|
||||
@@ -111,31 +118,9 @@ jobs:
|
||||
desiredLabels.add('custodian');
|
||||
}
|
||||
|
||||
// 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
|
||||
// gate check at the bottom of THIS job).
|
||||
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
|
||||
// Priority labels
|
||||
if (text.includes('urgent') || text.includes('critical') || text.includes('broken')) {
|
||||
desiredLabels.add('priority: high');
|
||||
}
|
||||
|
||||
const issueNumber = context.payload.issue?.number || context.payload.pull_request?.number;
|
||||
@@ -145,7 +130,6 @@ 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)
|
||||
);
|
||||
@@ -155,14 +139,11 @@ jobs:
|
||||
|
||||
for (const name of staleManaged) {
|
||||
try {
|
||||
// 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}', {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
id: currentLabelIds.get(name),
|
||||
name,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error.status !== 404) {
|
||||
@@ -180,50 +161,5 @@ jobs:
|
||||
labels: missingDesired,
|
||||
});
|
||||
}
|
||||
|
||||
// ---- PRIORITY GATE (runs LAST — after inference and
|
||||
// reconciliation, so the verdict reflects the labels THIS run
|
||||
// just applied, not a pre-inference snapshot). Issue-scoped:
|
||||
// the filing contract governs issues; PRs get inferred labels
|
||||
// but are not filing units.
|
||||
if (!isIssue) {
|
||||
console.log(`PR #${issueNumber}: labels applied, gate skipped (gate is issue-scoped).`);
|
||||
return;
|
||||
}
|
||||
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) {
|
||||
// Prioritized (by human or by this run's inference). Clear
|
||||
// any stale flag — no warning is ever posted on this path.
|
||||
if (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(`Priority gate: satisfied (${activePriority[0].name}).`);
|
||||
return;
|
||||
}
|
||||
// Genuinely unprioritized: inference produced nothing AND the
|
||||
// caller set nothing. Flag + demand comment — the filing gap
|
||||
// is real, not a race artifact.
|
||||
const reason = activePriority.length === 0
|
||||
? 'no priority'
|
||||
: `${activePriority.length} priority labels (exactly one required)`;
|
||||
if (!flag) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner, repo: context.repo.repo,
|
||||
issue_number: issueNumber, labels: ['unprioritized'],
|
||||
});
|
||||
}
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner, repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
body: `⚠️ **Priority gate:** this issue has ${reason}. Assign exactly one of **P0 — critical** (spine/correctness/blocks), **P1 — high** (material value or real defect), **P2 — medium** (quality/consolidation), **P3 — low** (measurement/deferred). An issue without a priority is not filed.`,
|
||||
});
|
||||
console.log(`Priority gate: flagged — ${reason}.`);
|
||||
console.log(`Removed managed labels: ${staleManaged.join(', ') || 'none'}`);
|
||||
console.log(`Added managed labels: ${missingDesired.join(', ') || 'none'}`);
|
||||
@@ -8,7 +8,7 @@ on:
|
||||
|
||||
jobs:
|
||||
update-gitea:
|
||||
runs-on: rune-ci-desktop
|
||||
runs-on: rune-infra-pi
|
||||
steps:
|
||||
- name: Check current Gitea version
|
||||
id: current
|
||||
|
||||
@@ -11,7 +11,7 @@ permissions: write-all
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: rune-ci-desktop
|
||||
runs-on: rune-infra-pi
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -131,12 +131,8 @@ jobs:
|
||||
"pyproject.toml": [(f'version = "{VERSION}"', f'version = "{NEW}"')],
|
||||
}
|
||||
|
||||
# Fetch current master content, apply replacements, VERIFY all six
|
||||
# surface patterns (five files + the TUI footer) agree on NEW before
|
||||
# committing anything (TUI gate). The footer check was added after
|
||||
# the 0.89.0 half-bump: a stale RELEASE_VERSION made both replace
|
||||
# pairs no-op; the gate's RECOVER regex fixed the header only and
|
||||
# the footer silently stayed 0.88.4, failing the banner test.
|
||||
# Fetch current master content, apply replacements, VERIFY all five
|
||||
# surfaces agree on NEW before committing anything (TUI gate).
|
||||
edited = {}
|
||||
for path, pairs in surfaces.items():
|
||||
status, cur = api(f"/contents/{path}?ref=master")
|
||||
@@ -155,7 +151,6 @@ jobs:
|
||||
checks = [
|
||||
("src/rune/__init__.py", rf'__version__ = "({VER})"'),
|
||||
("src/rune/rune_tui.py", rf"Version: v({VER})"),
|
||||
("src/rune/rune_tui.py", rf"Rune v({VER}) \|"),
|
||||
("src/rune/canary_gitea_automation.py", rf"'__version__ = \"({VER})\"'"),
|
||||
("pyproject.toml", rf'version = "({VER})"'),
|
||||
("README.md", rf"v({VER})"),
|
||||
|
||||
@@ -67,21 +67,6 @@ jobs:
|
||||
unit-tests:
|
||||
runs-on: rune-ci-desktop
|
||||
if: ${{ !startsWith(gitea.event.pull_request.head.ref, 'chore/auto-bump') }}
|
||||
env:
|
||||
RUNE_HOME: /tmp/rune-ci-${{ github.run_id }}
|
||||
RUNE_MEMORY_DIR: /tmp/rune-ci-${{ github.run_id }}/memory
|
||||
# The unit shim battery loads the cdylib (ep_loader); point it at the
|
||||
# runner-owned cdylib FILE from the crate-build step below (the override
|
||||
# expects a file path, not a directory).
|
||||
EP_RUST_LIB: /tmp/rune-ci-target-${{ github.run_id }}/release/libevidence_provenance.so
|
||||
SP_RUST_LIB: /tmp/rune-ci-target-${{ github.run_id }}/release/librune_spine.so
|
||||
MS_RUST_LIB: /tmp/rune-ci-target-${{ github.run_id }}/release/libmemory_scoring.so
|
||||
CS_RUST_LIB: /tmp/rune-ci-target-${{ github.run_id }}/release/libcapability_scoring.so
|
||||
TC_RUST_LIB: /tmp/rune-ci-target-${{ github.run_id }}/release/libtoken_counting.so
|
||||
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
|
||||
@@ -117,26 +102,6 @@ jobs:
|
||||
fi
|
||||
python3 scripts/umbrella_impact.py check \
|
||||
--base "$(git merge-base origin/master HEAD)" --head HEAD ${BODY_FILE:+--body-file "$BODY_FILE"}
|
||||
- name: Build Rust evidence_provenance crate
|
||||
run: |
|
||||
# tests/test_evidence_provenance_shims.py drives the cdylib through
|
||||
# the shim layer. Toolchain law (see the canary job for the full
|
||||
# rationale): system rustc is broken on this host (LLVM_23.1
|
||||
# version-node symbol gap); use the healthy rustup toolchain, PATH
|
||||
# first so the rustup shim can't exec the broken system rustc.
|
||||
# Runner-owned /tmp target dir (the repo's target/ is nick's).
|
||||
export PATH="/home/nick/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/bin:$PATH"
|
||||
export CARGO_TARGET_DIR="/tmp/rune-ci-target-${{ github.run_id }}"
|
||||
mkdir -p "$CARGO_TARGET_DIR"
|
||||
cargo build --release --manifest-path src/rust/evidence_provenance/Cargo.toml
|
||||
cargo build --release --manifest-path src/rust/rune_spine/Cargo.toml
|
||||
cargo build --release --manifest-path src/rust/memory_scoring/Cargo.toml
|
||||
cargo build --release --manifest-path src/rust/capability_scoring/Cargo.toml
|
||||
cargo build --release --manifest-path src/rust/token_counting/Cargo.toml
|
||||
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,
|
||||
@@ -148,63 +113,12 @@ jobs:
|
||||
.test-venv/bin/coverage xml
|
||||
.test-venv/bin/diff-cover coverage.xml --compare-branch origin/master --fail-under=70 --diff-range-notation ..
|
||||
|
||||
go-surface:
|
||||
runs-on: rune-ci-desktop
|
||||
if: ${{ !startsWith(gitea.event.pull_request.head.ref, 'chore/auto-bump') }}
|
||||
steps:
|
||||
# actions/checkout v4.2.2, pinned to the audited upstream tag commit.
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||
- name: Verify Go toolchain version pin
|
||||
run: |
|
||||
# H0 pin: the Go surface builds against the pacman toolchain; the
|
||||
# pin file is the single source of truth so a distro upgrade that
|
||||
# changes behavior fails loud here, not downstream in the canary.
|
||||
WANT=$(cat go-version.txt)
|
||||
GOT=$(go version | awk '{print $3}' | sed 's/^go//' | cut -d- -f1)
|
||||
echo "pinned: $WANT | toolchain: $GOT"
|
||||
[ "$GOT" = "$WANT" ] || { echo "::error::Go toolchain drift: want $WANT, got $GOT (update go-version.txt with the rollout)"; exit 1; }
|
||||
- name: build Survivor staticlibs in-tree (for cgo main packages)
|
||||
run: |
|
||||
# Survivor main packages link Rust staticlibs via ${SRCDIR} paths
|
||||
# (adaptive-router → libroute_risk_flags.a). Those paths resolve
|
||||
# only when the crate target dir is IN-TREE, so this build must
|
||||
# NOT set CARGO_TARGET_DIR (the redirected builds below are for
|
||||
# the FFI-loader canaries and stay as they are).
|
||||
cargo build --release --manifest-path src/rust/route_risk_flags/Cargo.toml
|
||||
- name: go vet + go test + go build
|
||||
run: |
|
||||
for dir in src/go/*/; do
|
||||
if [ -f "$dir/go.mod" ]; then
|
||||
echo "=== Building $dir ==="
|
||||
cd "$dir"
|
||||
go vet ./...
|
||||
go test ./... 2>/dev/null || true
|
||||
go build -o /tmp/go-$(basename "$dir") .
|
||||
cd - > /dev/null
|
||||
fi
|
||||
done
|
||||
- name: adaptive-router parity gate (HARD — oracle replay, not swallowable)
|
||||
run: |
|
||||
cd src/go/adaptive-router
|
||||
go test ./... -run TestParityAgainstPythonOracle -v
|
||||
|
||||
canary:
|
||||
runs-on: rune-ci-desktop
|
||||
if: ${{ !startsWith(gitea.event.pull_request.head.ref, 'chore/auto-bump') }}
|
||||
env:
|
||||
RUNE_HOME: /tmp/rune-ci-${{ github.run_id }}
|
||||
RUNE_MEMORY_DIR: /tmp/rune-ci-${{ github.run_id }}/memory
|
||||
# The build emits to a runner-owned /tmp target dir (the repo's target/
|
||||
# is nick-owned); EP_RUST_LIB points ep_loader at the cdylib FILE there
|
||||
# (the override expects a file path, not a directory).
|
||||
EP_RUST_LIB: /tmp/rune-ci-target-${{ github.run_id }}/release/libevidence_provenance.so
|
||||
SP_RUST_LIB: /tmp/rune-ci-target-${{ github.run_id }}/release/librune_spine.so
|
||||
MS_RUST_LIB: /tmp/rune-ci-target-${{ github.run_id }}/release/libmemory_scoring.so
|
||||
CS_RUST_LIB: /tmp/rune-ci-target-${{ github.run_id }}/release/libcapability_scoring.so
|
||||
TC_RUST_LIB: /tmp/rune-ci-target-${{ github.run_id }}/release/libtoken_counting.so
|
||||
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
|
||||
steps:
|
||||
# actions/checkout v4.2.2, pinned to the audited upstream tag commit.
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||
@@ -216,35 +130,6 @@ jobs:
|
||||
python3 -m venv .canary-venv
|
||||
.canary-venv/bin/pip install --disable-pip-version-check -r requirements-ci.txt
|
||||
.canary-venv/bin/pip install --disable-pip-version-check -e . --no-deps
|
||||
- name: Build Rust evidence_provenance crate
|
||||
run: |
|
||||
# The canary pair + the unit shim battery drive the COMPILED surfaces
|
||||
# (binary CLI parity, ep_loader FFI, ctypes cdylib loads).
|
||||
#
|
||||
# Toolchain law (troubleshooting history): the SYSTEM rustc is broken
|
||||
# on this host — librustc_driver-<sha>.so (pacman rust 1:1.99.0-1)
|
||||
# references std::string::_M_mutate under the LLVM_23.1 version node,
|
||||
# but /usr/lib/libLLVM.so.23.1 does not define that narrow-char
|
||||
# symbol under that node (it exports _M_create/_M_assign there, and
|
||||
# only the WIDE-char _M_mutate) — every compile dies with `symbol
|
||||
# lookup error` while `cargo --version` still prints. The rustup
|
||||
# toolchain under /home/nick/.rustup is healthy and ships its own
|
||||
# libLLVM, and /home/nick carries the x-ACL for this runner user.
|
||||
# Point PATH at the toolchain bin dir (bypasses the rustup shim,
|
||||
# which would exec the broken system rustc via RUSTUP_TOOLCHAIN).
|
||||
# Target dir is runner-owned (/tmp): the repo's target/ is nick's.
|
||||
export PATH="/home/nick/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/bin:$PATH"
|
||||
export CARGO_TARGET_DIR="/tmp/rune-ci-target-${{ github.run_id }}"
|
||||
mkdir -p "$CARGO_TARGET_DIR"
|
||||
cargo build --release --manifest-path src/rust/evidence_provenance/Cargo.toml
|
||||
cargo build --release --manifest-path src/rust/rune_spine/Cargo.toml
|
||||
cargo build --release --manifest-path src/rust/memory_scoring/Cargo.toml
|
||||
cargo build --release --manifest-path src/rust/capability_scoring/Cargo.toml
|
||||
cargo build --release --manifest-path src/rust/token_counting/Cargo.toml
|
||||
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
|
||||
@@ -271,21 +156,6 @@ jobs:
|
||||
src/rune/canary_p1_06.py \
|
||||
src/rune/canary_p1_01.py \
|
||||
src/rune/canary_query_memory.py \
|
||||
src/rune/canary_rune_entry.py \
|
||||
src/rune/canary_spine_meta.py \
|
||||
src/rune/canary_audit_ledger.py \
|
||||
src/rust/rune_spine/canary_spine_rust.py \
|
||||
src/rune/canary_rune_serve.py \
|
||||
src/rune/canary_tui_transport.py \
|
||||
src/rust/memory_scoring/canary_memory_scoring.py \
|
||||
src/rust/capability_scoring/canary_capability_scoring.py \
|
||||
src/rust/token_counting/canary_token_counting.py \
|
||||
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
|
||||
|
||||
@@ -8,7 +8,7 @@ on:
|
||||
|
||||
jobs:
|
||||
lint-and-format:
|
||||
runs-on: rune-ci-desktop
|
||||
runs-on: rune-infra-pi
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Lint Python files
|
||||
@@ -18,7 +18,7 @@ jobs:
|
||||
ruff format shared/ src/ || true
|
||||
|
||||
canary-suite:
|
||||
runs-on: rune-ci-desktop
|
||||
runs-on: rune-infra-pi
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Run all canaries
|
||||
@@ -37,7 +37,7 @@ jobs:
|
||||
exit $FAILED
|
||||
|
||||
best-practices:
|
||||
runs-on: rune-ci-desktop
|
||||
runs-on: rune-infra-pi
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Check best practices
|
||||
@@ -72,7 +72,7 @@ jobs:
|
||||
grep -rn "TODO\|FIXME\|HACK\|XXX" shared/ src/ --include="*.py" | head -10 || echo " Clean"
|
||||
|
||||
documentation-check:
|
||||
runs-on: rune-ci-desktop
|
||||
runs-on: rune-infra-pi
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Check documentation coverage
|
||||
@@ -113,7 +113,7 @@ jobs:
|
||||
# push-triggered safety net in auto-version.yml. Detects master/tag drift
|
||||
# and files a deduped issue — it never auto-releases without the PR flow.
|
||||
release-drift-reconciliation:
|
||||
runs-on: rune-ci-desktop
|
||||
runs-on: rune-infra-pi
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
|
||||
@@ -14,4 +14,3 @@ state/
|
||||
# Runtime artifacts (cwd-local event journal + capability index)
|
||||
index/
|
||||
journal/
|
||||
src/rust/*/target/
|
||||
@@ -58,26 +58,3 @@ 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.
|
||||
|
||||
## Issue organisation standard (binding, 2026-09-19)
|
||||
|
||||
One open note per idea. Issues use the template spine (kind, subsystem,
|
||||
version intent) with a plain-English heading that restates the subject —
|
||||
no meta-labels. Before minting a standalone issue, check whether the work
|
||||
belongs inside an existing parent:
|
||||
|
||||
- **Parked ideas under a blocked/future epic** are filed as checklist items
|
||||
in the parent's "Absorbed children" section, NOT as standalone issues.
|
||||
Absorption is reversible — re-mint standalone when the idea becomes live.
|
||||
- **Live, dependency-tracked, or starting work** gets a standalone issue.
|
||||
- **Closures state the reason as data**: `closed_because` in the spine
|
||||
(completed / superseded-by-#N / absorbed-into-#N / wont-do / duplicate),
|
||||
plus a standard closing comment (plain summary first).
|
||||
- The reconciliation checker (`scripts/gitea_reconciliation_check.py`) must
|
||||
stay green after any issue state change; the artifact is updated in the
|
||||
same change that moves issues.
|
||||
|
||||
## Async continuation final flow proofs (R13/M9) — 2026-09-19
|
||||
|
||||
PR-flow live proof marker: harmless documentation addition exercising the
|
||||
canonical single-continuation path on the PC-local forge. No code change.
|
||||
@@ -1,6 +1,6 @@
|
||||
# Rune
|
||||
|
||||
**Current release: v0.105.0**
|
||||
**Current release: v0.87.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.**
|
||||
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
import { execFile } from "node:child_process"
|
||||
import { existsSync, appendFileSync } from "node:fs"
|
||||
|
||||
// builder-bridge — Rune Core preflight for the MiMo builder (handoff
|
||||
// 2026-09-10 §3–§7, Option C bridge tranche). For each user turn, the hook
|
||||
// extracts the user's message from the outgoing LLM request, runs the Rune
|
||||
// Core builder-bridge preflight (deterministic: route classification +
|
||||
// memory selection + active-Scaffolding projection, ZERO model calls), and
|
||||
// appends a compact capsule to the final user message. Same Rune Core the
|
||||
// TUI/operator path uses — this file is a thin adapter with no cognition.
|
||||
//
|
||||
// CANONICAL SOURCE: config/mimo-hooks/builder-bridge.ts
|
||||
// Installed to ~/.mimocode/hooks/builder-bridge.ts by
|
||||
// `scripts/install_mimo_hook.py` (hash-verified, drift-detecting — the same
|
||||
// contract as event-wait-guard.ts). T22: this file was previously
|
||||
// UNVERSIONED and hardcoded an ephemeral interpreter path (/tmp/ci-venv),
|
||||
// which silently killed the whole edge; both defects are repaired here.
|
||||
//
|
||||
// Overhead contract (§7/§8): capsule ≤ ~300 tokens; a repeat/empty task
|
||||
// costs ~0ms (TTL cache); a fresh task ~150ms (bounded retrieval). The hook
|
||||
// degrades silently to no-injection on any failure — it must never block
|
||||
// the builder.
|
||||
//
|
||||
// Injection policy: only append when the capsule is non-empty. A plain
|
||||
// "hello" gets nothing (§5: if nothing relevant exists, inject nothing).
|
||||
|
||||
const BRIDGE = "/mnt/workdrive/issue161-harness/src/rune/builder_bridge_cli.py"
|
||||
const MARKER_PREFIX = "/tmp/rune-bridge-"
|
||||
|
||||
// Interpreter resolution (T22 repair): the previous hardcoded
|
||||
// "/tmp/ci-venv/bin/python" is an EPHEMERAL path that no longer exists, so
|
||||
// every bridge call failed and the hook silently degraded — the MiMo edge
|
||||
// received no Rune Core preflight at all (zero fire-log lines). Resolve
|
||||
// against durable candidates, first existing wins; env override wins over
|
||||
// all of them. If nothing exists the hook degrades as before.
|
||||
const PY_CANDIDATES = [
|
||||
process.env.MIMO_BRIDGE_PY,
|
||||
"/mnt/workdrive/issue161-harness/.test-venv/bin/python",
|
||||
"/home/nick/.venvs/memory/bin/python3",
|
||||
"/usr/bin/python3",
|
||||
].filter((p) => typeof p === "string" && p.length > 0)
|
||||
|
||||
function resolvePy() {
|
||||
for (const p of PY_CANDIDATES) {
|
||||
try {
|
||||
if (existsSync(p)) return p
|
||||
} catch {}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// Per-process dedupe: identical task text within the cache TTL does not need
|
||||
// a second bridge call — the CLI has its own TTL cache, but skipping the
|
||||
// process spawn entirely for the same message text within 10 minutes keeps
|
||||
// repeats at ~0ms.
|
||||
const lastText = new Map() // text -> timestamp
|
||||
const TTL = 600_000
|
||||
|
||||
function extractUserText(messages) {
|
||||
// messages: Array<{ info: Message, parts: Part[] }> — newest last.
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
const m = messages[i]
|
||||
if (m?.info?.role !== "user") continue
|
||||
const texts = []
|
||||
for (const p of m.parts ?? []) {
|
||||
if (p?.type === "text" && typeof p.text === "string") texts.push(p.text)
|
||||
}
|
||||
if (texts.length) return texts.join("\n").slice(0, 4000)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
export default {
|
||||
"experimental.chat.messages.transform": async (input, output) => {
|
||||
try {
|
||||
if (!Array.isArray(output.messages) || output.messages.length === 0) return
|
||||
const userText = extractUserText(output.messages)
|
||||
if (!userText || userText.length < 12) return // trivial/noise guard
|
||||
// Harness-internal steps (checkpoint writer, compaction, system
|
||||
// reminders) are not builder tasks — no capsule (measured: the fire
|
||||
// log showed checkpoint-writer steps receiving capsules 2026-09-10).
|
||||
if (/^(<system-reminder>|EXTRACTION REQUIRED)/.test(userText.trim())) return
|
||||
const now = Date.now()
|
||||
const prev = lastText.get(userText)
|
||||
if (prev !== undefined && now - prev < TTL) return // dedupe repeats
|
||||
lastText.set(userText, now)
|
||||
if (lastText.size > 64) {
|
||||
// evict oldest
|
||||
let oldestKey = null, oldestVal = Infinity
|
||||
for (const [k, v] of lastText) if (v < oldestVal) { oldestVal = v; oldestKey = k }
|
||||
if (oldestKey) lastText.delete(oldestKey)
|
||||
}
|
||||
|
||||
const py = resolvePy()
|
||||
if (!py) return // no durable interpreter — degrade (never block)
|
||||
|
||||
const capsule = await new Promise((resolve) => {
|
||||
execFile(py, [BRIDGE, userText], { timeout: 15_000 }, (err, stdout) => {
|
||||
resolve(err ? "" : (stdout?.toString() ?? ""))
|
||||
})
|
||||
})
|
||||
if (!capsule.trim()) return
|
||||
|
||||
// Durable fire-trace: one line per ACTUAL injection into an outgoing
|
||||
// model request (handoff §1 proof requirement). Not a canary — this is
|
||||
// standing observability for the bridge's consumer edge.
|
||||
try {
|
||||
appendFileSync("/tmp/rune-bridge-fire.log",
|
||||
JSON.stringify({ ts: new Date().toISOString(), task: userText.slice(0, 80), capsule_tokens: Math.round(capsule.length / 4), py }) + "\n")
|
||||
} catch {}
|
||||
|
||||
// Append the capsule to the LAST user message (the one being answered).
|
||||
const last = output.messages[output.messages.length - 1]
|
||||
if (last?.parts && Array.isArray(last.parts)) {
|
||||
last.parts.push({
|
||||
type: "text",
|
||||
text: "\n\n<rune-preflight>\n" + capsule.trim() + "\n</rune-preflight>\n(Injected by Rune Core builder bridge — deterministic preflight, zero model calls. Relevant state above; ignore if not applicable to this task.)",
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
// never block the builder on bridge failure
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -1,92 +1,54 @@
|
||||
import { tool } from "@mimo-ai/plugin"
|
||||
import { execSync } from "child_process"
|
||||
|
||||
export default tool({
|
||||
description: "Wait for an external operation (CI, deploy, release) to complete. Call this when you cannot make progress until an external process finishes. You do NOT need to know the sha, op_type, or duration — Rune's controller resolves those from the bound PendingOperation. Just call this when you want to wait.",
|
||||
// await_operation — T21.3 §21.3C: FIRST-CLASS async wait tool.
|
||||
// Uses the plugin tool() API with args (not parameters).
|
||||
|
||||
export const AwaitOperation = tool({
|
||||
description: [
|
||||
"Wait for an asynchronous external operation (CI, deploy, release) to complete.",
|
||||
"Registers on the event bridge, yields until the completion event arrives, then returns the verified result.",
|
||||
"USE THIS instead of `sleep N; curl status` — it is the canonical event-driven wait.",
|
||||
].join(" "),
|
||||
args: {
|
||||
operation_id: tool.schema.string().optional().describe("Optional: the operation to wait for. If omitted, the controller resolves the current pending operation automatically."),
|
||||
task_id: tool.schema.string().optional().describe("Optional: the active task id (e.g. T4). When provided, resolution is scoped to operations bound to this task — stale global operations are never consulted."),
|
||||
sha: tool.schema.string().optional().describe("OPTIONAL HINT — non-authoritative. The controller uses this only to help resolve which operation you mean."),
|
||||
op_type: tool.schema.string().optional().describe("OPTIONAL HINT — non-authoritative. The controller derives the canonical operation type from repository/Gitea state."),
|
||||
deadline_secs: tool.schema.number().optional().describe("OPTIONAL HINT — non-authoritative. The controller applies governed policy timing. Real user deadlines must be stated in conversation."),
|
||||
sha: tool.schema.string().describe(
|
||||
"The exact commit SHA the operation is running against"),
|
||||
deadline_secs: tool.schema.number().optional().describe(
|
||||
"Maximum wait in seconds (default 900)"),
|
||||
},
|
||||
async execute(args) {
|
||||
// INTENT NORMALIZATION — model output is intent; the controller
|
||||
// owns execution semantics. All model args are hints recorded for
|
||||
// observability; canonical truth comes from the bound operation.
|
||||
const parts = []
|
||||
if (args.operation_id) parts.push(`--operation-id ${args.operation_id}`)
|
||||
if (args.task_id) parts.push(`--task-id ${args.task_id}`)
|
||||
if (args.sha) parts.push(`--sha ${args.sha}`)
|
||||
if (args.op_type) parts.push(`--model-op-type ${args.op_type}`)
|
||||
if (args.deadline_secs) parts.push(`--model-deadline ${args.deadline_secs}`)
|
||||
const normCmd = `python3 /mnt/workdrive/issue161-harness/scripts/await_intent_cli.py normalize ${parts.join(" ")}`
|
||||
let norm: any
|
||||
try {
|
||||
const normOut = execSync(normCmd, {
|
||||
cwd: "/mnt/workdrive/issue161-harness",
|
||||
encoding: "utf-8" as const,
|
||||
timeout: 120000,
|
||||
env: { ...process.env, RUNE_WR_ROOT: "/mnt/workdrive/wr-bridge" },
|
||||
})
|
||||
norm = JSON.parse(normOut.trim().split("\n").find((l: string) => l.startsWith("{")) || "{}")
|
||||
} catch (e: any) {
|
||||
return JSON.stringify({ ok: false, stage: "normalization", error: (e.stderr || e.message || "?").slice(0, 300) })
|
||||
}
|
||||
if (norm.normalized === "AMBIGUOUS") {
|
||||
return JSON.stringify({ ok: false, stage: "normalization", ...norm })
|
||||
}
|
||||
if (!norm.normalized) {
|
||||
return JSON.stringify({ ok: false, stage: "normalization", ...norm })
|
||||
}
|
||||
// canonical continuation: stored/derived op_type + POLICY deadline
|
||||
// (the sha for the wait comes from the normalization resolution,
|
||||
// NOT from the model's args)
|
||||
const waitSha = norm.sha_for_wait || args.sha || ""
|
||||
if (!waitSha) {
|
||||
return JSON.stringify({ ok: false, stage: "resolution", error: "no sha resolved for the pending operation", norm })
|
||||
}
|
||||
const cmd = `python3 /mnt/workdrive/issue161-harness/scripts/ci_event_wait.py --sha ${waitSha} --deadline ${norm.deadline_secs} --op-type ${norm.op_type}`
|
||||
async execute(args, ctx) {
|
||||
const repoRoot = "/mnt/workdrive/issue161-harness"
|
||||
const deadline = args.deadline_secs || 900
|
||||
const cmd = [
|
||||
"python3", `${repoRoot}/scripts/ci_event_wait.py`,
|
||||
"--sha", args.sha,
|
||||
"--deadline", String(deadline),
|
||||
].join(" ")
|
||||
try {
|
||||
const result = execSync(cmd, {
|
||||
cwd: "/mnt/workdrive/issue161-harness",
|
||||
timeout: (norm.deadline_secs + 60) * 1000,
|
||||
cwd: repoRoot,
|
||||
timeout: (deadline + 60) * 1000,
|
||||
encoding: "utf-8" as const,
|
||||
env: { ...process.env, DEPLOY_SHA: waitSha, RUNE_WR_ROOT: "/mnt/workdrive/wr-bridge", RUNE_WR_CODE: "/home/nick/.local/share/mimo-wait-resume" },
|
||||
})
|
||||
const jl = result.trim().split("\n").find((l: string) => l.startsWith("{"))
|
||||
const envelope = jl ? JSON.parse(jl) : { ok: false, error: "no output" }
|
||||
return JSON.stringify({
|
||||
...envelope,
|
||||
normalization: {
|
||||
model_deadline_ignored: norm.model_deadline_ignored,
|
||||
model_op_type_ignored: norm.model_op_type_ignored,
|
||||
model_sha_ignored: !!args.sha && args.sha !== waitSha,
|
||||
canonical_op_type: norm.op_type,
|
||||
canonical_authority: norm.authority,
|
||||
deadline_provenance: norm.deadline_provenance,
|
||||
matched_by: norm.matched_by || norm.evidence || "auto-resolved",
|
||||
env: {
|
||||
...process.env,
|
||||
DEPLOY_SHA: args.sha,
|
||||
RUNE_WR_ROOT: "/mnt/workdrive/wr-bridge",
|
||||
RUNE_WR_CODE: "/home/nick/.local/share/mimo-wait-resume",
|
||||
},
|
||||
})
|
||||
const lines = result.trim().split("\n")
|
||||
const jsonLine = lines.find((l: string) => l.startsWith("{"))
|
||||
if (jsonLine) return jsonLine
|
||||
return "await_operation: no JSON output"
|
||||
} catch (e: any) {
|
||||
const lines = (e.stdout || "").trim().split("\n")
|
||||
const jl = lines.find((l: string) => l.startsWith("{"))
|
||||
if (jl) {
|
||||
const envelope = JSON.parse(jl)
|
||||
return JSON.stringify({
|
||||
...envelope,
|
||||
normalization: {
|
||||
model_deadline_ignored: norm.model_deadline_ignored,
|
||||
model_op_type_ignored: norm.model_op_type_ignored,
|
||||
model_sha_ignored: !!args.sha && args.sha !== waitSha,
|
||||
canonical_op_type: norm.op_type,
|
||||
canonical_authority: norm.authority,
|
||||
deadline_provenance: norm.deadline_provenance,
|
||||
matched_by: norm.matched_by || norm.evidence || "auto-resolved",
|
||||
},
|
||||
})
|
||||
}
|
||||
return JSON.stringify({ ok: false, stage: "wait", error: (e.stderr || e.message || "?").slice(0, 300) })
|
||||
const stdout = e.stdout || ""
|
||||
const lines = stdout.trim().split("\n")
|
||||
const jsonLine = lines.find((l: string) => l.startsWith("{"))
|
||||
if (jsonLine) return jsonLine
|
||||
return JSON.stringify({
|
||||
ok: false,
|
||||
error: `await_operation failed: ${(e.stderr || e.message || "?").slice(0, 200)}`,
|
||||
})
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -1,167 +0,0 @@
|
||||
|
||||
// bash — executes a shell command. PROCESS-OWNERSHIP CONTRACT (v2):
|
||||
//
|
||||
// MODE A (tool-owned): the child is launched in its own process group;
|
||||
// stdout/stderr are CAPTURED pipes (never the TUI tty). On timeout or
|
||||
// failure the ENTIRE process group is signalled (SIGTERM, grace,
|
||||
// SIGKILL) so grandchildren cannot survive the invocation, then the
|
||||
// result is finalized. After finalization NO descendant retains a
|
||||
// writer into MiMo's streams.
|
||||
//
|
||||
// MODE B (explicitly detached): a command suffixed with " &" that the
|
||||
// user/model intends to outlive the tool (nohup/setsid/disown-style)
|
||||
// is executed via the detached helper: stdin=/dev/null, stdout/stderr
|
||||
// -> durable log file, own session (setsid), no MiMo PTY inheritance.
|
||||
// The tool returns the log path as the durable handle.
|
||||
//
|
||||
// Wait-intent compilation (sleep/check/poll aimed at a pending operation)
|
||||
// is preserved: interception happens at the SEMANTIC level via
|
||||
// await_intent route-bash, and a NO-OP for anything that is not a genuine
|
||||
// continuation of a live pending operation. Arbitrary shell syntax
|
||||
// (quotes, pipes, semicolons) passes through untouched — the router
|
||||
// response is only trusted when it carries normalized=true AND
|
||||
// ContinuePendingOperation with a concrete operation bound.
|
||||
import { tool } from "@mimo-ai/plugin"
|
||||
import { spawn, execFile } from "child_process"
|
||||
|
||||
const REPO = "/mnt/workdrive/issue161-harness"
|
||||
const WR_ROOT = "/mnt/workdrive/wr-bridge"
|
||||
|
||||
// ── MODE A: process-group-owned capture execution ──────────────────────
|
||||
interface OwnedResult { stdout: string; stderr: string; status: number; timedOut: boolean }
|
||||
|
||||
function runOwned(command: string, timeoutMs: number): Promise<OwnedResult> {
|
||||
return new Promise((resolve) => {
|
||||
// /bin/sh -c "command" in its OWN process group (detached:true makes
|
||||
// the child a session/group leader we can signal as a WHOLE).
|
||||
const child = spawn("/bin/sh", ["-c", command], {
|
||||
cwd: REPO,
|
||||
stdio: ["ignore", "pipe", "pipe"], // NEVER inherit the TUI tty
|
||||
env: process.env,
|
||||
detached: true, // own process group
|
||||
})
|
||||
let stdout = "", stderr = ""
|
||||
let timedOut = false
|
||||
let settled = false
|
||||
const outChunks: Buffer[] = []
|
||||
const errChunks: Buffer[] = []
|
||||
child.stdout!.on("data", (d) => outChunks.push(d))
|
||||
child.stderr!.on("data", (d) => errChunks.push(d))
|
||||
|
||||
const killGroup = (sig: NodeJS.Signals) => {
|
||||
try { process.kill(-child.pid!, sig) } catch { /* already gone */ }
|
||||
}
|
||||
const finalize = (status: number) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timer)
|
||||
// detach listeners, then resolve — no late listeners remain
|
||||
child.stdout!.removeAllListeners()
|
||||
child.stderr!.removeAllListeners()
|
||||
resolve({ stdout: Buffer.concat(outChunks).toString(), stderr: Buffer.concat(errChunks).toString(), status, timedOut })
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
timedOut = true
|
||||
killGroup("SIGTERM")
|
||||
// bounded grace for clean shutdown, then SIGKILL the group
|
||||
setTimeout(() => killGroup("SIGKILL"), 2000)
|
||||
// the exit/close event settles; a hard stop-guard settles anyway
|
||||
setTimeout(() => finalize(124), 4000)
|
||||
}, timeoutMs)
|
||||
|
||||
child.on("error", (e) => finalize(-1))
|
||||
child.on("close", (code) => finalize(code ?? -1))
|
||||
})
|
||||
}
|
||||
|
||||
// ── MODE B: explicit detachment for "cmd &" invocations ────────────────
|
||||
function runDetached(command: string): Promise<string> {
|
||||
return new Promise((resolve) => {
|
||||
const logPath = `/tmp/mimo-detached-${Date.now()}-${Math.floor(Math.random() * 1e6)}.log`
|
||||
const out = `exec >>"${logPath}" 2>&1; exec 0</dev/null; ${command}`
|
||||
const child = spawn("/bin/sh", ["-c", `setsid /bin/sh -c '${out.replace(/'/g, `'\\''`)}'`], {
|
||||
cwd: REPO,
|
||||
stdio: "ignore", // child rebinds its own fds — no PTY inheritance
|
||||
env: process.env,
|
||||
detached: true,
|
||||
// unref: MiMo's event loop does not wait for it
|
||||
})
|
||||
child.unref()
|
||||
resolve(JSON.stringify({
|
||||
detached: true,
|
||||
log: logPath,
|
||||
note: "process detached (setsid, own fds); output streams to the log file only; fd 0/1/2 do NOT reference the MiMo tty",
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
// ── wait-intent routing (semantic level, preserved from v1) ────────────
|
||||
async function tryCompileWaitIntent(command: string): Promise<string | null> {
|
||||
let routeOut: string
|
||||
try {
|
||||
routeOut = await new Promise<string>((resolve, reject) => {
|
||||
execFile("python3", [`${REPO}/scripts/await_intent_cli.py`, "route-bash", "--command", command], {
|
||||
cwd: REPO, timeout: 60000, encoding: "utf-8",
|
||||
env: { ...process.env, RUNE_WR_ROOT: WR_ROOT },
|
||||
maxBuffer: 8 * 1024 * 1024,
|
||||
}, (err, stdout) => { if (err && !stdout) reject(err); else resolve(stdout || "") })
|
||||
})
|
||||
} catch {
|
||||
return null // router unavailable: normal execution (never block on routing)
|
||||
}
|
||||
const jl = routeOut.trim().split("\n").find((l) => l.startsWith("{"))
|
||||
if (!jl) return null
|
||||
let norm: any
|
||||
try { norm = JSON.parse(jl) } catch { return null }
|
||||
// STRICT gate: compile ONLY a normalized, concrete continuation.
|
||||
if (!(norm.normalized === true &&
|
||||
norm.action === "ContinuePendingOperation" &&
|
||||
norm.operation_id && norm.sha_for_wait)) return null
|
||||
const waitCmd = `python3 ${REPO}/scripts/ci_event_wait.py --sha ${norm.sha_for_wait} --deadline ${norm.deadline_secs} --op-type ${norm.op_type}`
|
||||
const r = await runOwned(waitCmd, (norm.deadline_secs + 60) * 1000)
|
||||
const jline = r.stdout.trim().split("\n").find((l) => l.startsWith("{"))
|
||||
if (jline) {
|
||||
return JSON.stringify({
|
||||
...JSON.parse(jline),
|
||||
intent_compilation: {
|
||||
raw_command_kind: norm.raw_command_kind || "sleep_poll",
|
||||
literal_sleep_executed: false,
|
||||
operation_id: norm.operation_id,
|
||||
canonical_op_type: norm.op_type,
|
||||
authority: norm.authority,
|
||||
},
|
||||
})
|
||||
}
|
||||
return JSON.stringify({ ok: false, stage: "compiled-wait", error: (r.stderr || "no output").slice(0, 300) })
|
||||
}
|
||||
|
||||
export default tool({
|
||||
description: "Run a shell command. If the command expresses external wait intent (sleep/check/poll aimed at CI, deploy, or release operations with pending operations), it is automatically compiled to Rune's event-driven continuation — you do not need to manage wait mechanics. Plain local commands execute normally. Commands ending in ' &' run detached with output logged to a file.",
|
||||
args: {
|
||||
command: tool.schema.string().describe("Shell command to run"),
|
||||
},
|
||||
async execute(args) {
|
||||
// 1. wait-intent compilation (semantic, strict-gated)
|
||||
try {
|
||||
const compiled = await tryCompileWaitIntent(args.command)
|
||||
if (compiled !== null) return compiled
|
||||
} catch { /* fall through to normal execution */ }
|
||||
|
||||
// 2. MODE B: explicit detachment for backgrounded invocations
|
||||
const cmd = args.command
|
||||
if (/\b(nohup|setsid)\b/.test(cmd) || /&\s*$/.test(cmd)) {
|
||||
return await runDetached(cmd)
|
||||
}
|
||||
|
||||
// 3. MODE A: tool-owned, group-killed, captured execution
|
||||
const r = await runOwned(cmd, 120000)
|
||||
const text = r.stdout + (r.stderr ? `\n[stderr]\n${r.stderr}` : "")
|
||||
if (r.timedOut) {
|
||||
return `exit timed-out (process group terminated): ${text.slice(0, 500)}`
|
||||
}
|
||||
if (r.status !== 0) {
|
||||
return `exit ${r.status}: ${text.slice(0, 500) || "?"}`
|
||||
}
|
||||
return text || "(no output)"
|
||||
},
|
||||
})
|
||||
+70
-166
@@ -4,42 +4,19 @@
|
||||
"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",
|
||||
"model-connect",
|
||||
"provider-registry",
|
||||
"provider-budget",
|
||||
"standardized-providers",
|
||||
"tiered-executor"
|
||||
],
|
||||
"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",
|
||||
@@ -47,30 +24,21 @@
|
||||
"tool_executor",
|
||||
"tool_protocol"
|
||||
],
|
||||
"rust_crates": [
|
||||
"capability_scoring"
|
||||
"depends_on": [
|
||||
"memory"
|
||||
],
|
||||
"mirrors": [],
|
||||
"canaries": [
|
||||
"canary_native",
|
||||
"canary_p0_05",
|
||||
"canary_p1_01"
|
||||
]
|
||||
},
|
||||
"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",
|
||||
@@ -78,24 +46,17 @@
|
||||
"drift_ledger",
|
||||
"drift_observability",
|
||||
"failure_auto_filer",
|
||||
"programme_gates",
|
||||
"sc_loader"
|
||||
"programme_gates"
|
||||
],
|
||||
"rust_crates": [
|
||||
"evidence_provenance",
|
||||
"scaffold_core"
|
||||
"depends_on": [],
|
||||
"mirrors": [],
|
||||
"canaries": [
|
||||
"canary_full_system",
|
||||
"canary_schema_migration"
|
||||
]
|
||||
},
|
||||
"growth": {
|
||||
"canaries": [
|
||||
"canary_full_system"
|
||||
],
|
||||
"depends_on": [
|
||||
"governance",
|
||||
"memory"
|
||||
],
|
||||
"description": "Learning and improvement",
|
||||
"mirrors": [],
|
||||
"modules": [
|
||||
"autonomy_loop",
|
||||
"cognitive_loop",
|
||||
@@ -106,22 +67,18 @@
|
||||
"growth_simulator",
|
||||
"self_improve",
|
||||
"subconscious_pass"
|
||||
],
|
||||
"depends_on": [
|
||||
"governance",
|
||||
"memory"
|
||||
],
|
||||
"mirrors": [],
|
||||
"canaries": [
|
||||
"canary_full_system"
|
||||
]
|
||||
},
|
||||
"identity": {
|
||||
"canaries": [
|
||||
"canary_full_system"
|
||||
],
|
||||
"depends_on": [
|
||||
"governance"
|
||||
],
|
||||
"description": "Who the agent is \u2014 persona, voice, anchors",
|
||||
"go_surfaces": [
|
||||
"persona-definition",
|
||||
"voicebox",
|
||||
"voice-injector"
|
||||
],
|
||||
"mirrors": [],
|
||||
"modules": [
|
||||
"behavior",
|
||||
"identity_anchors",
|
||||
@@ -132,19 +89,17 @@
|
||||
"voice_injector",
|
||||
"voice_sync",
|
||||
"voicebox"
|
||||
],
|
||||
"depends_on": [
|
||||
"governance"
|
||||
],
|
||||
"mirrors": [],
|
||||
"canaries": [
|
||||
"canary_full_system"
|
||||
]
|
||||
},
|
||||
"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",
|
||||
@@ -155,48 +110,31 @@
|
||||
"provider_registry",
|
||||
"response_adapter",
|
||||
"standardized_providers",
|
||||
"tc_loader",
|
||||
"token_optimizer"
|
||||
],
|
||||
"rust_crates": [
|
||||
"token_counting"
|
||||
"depends_on": [
|
||||
"capability"
|
||||
],
|
||||
"mirrors": [],
|
||||
"canaries": [
|
||||
"canary_p1_02",
|
||||
"canary_p1_06",
|
||||
"canary_resource_authority"
|
||||
]
|
||||
},
|
||||
"memory": {
|
||||
"canaries": [
|
||||
"canary_full_system",
|
||||
"canary_memory_synthesis",
|
||||
"canary_query_memory"
|
||||
],
|
||||
"depends_on": [
|
||||
"governance"
|
||||
],
|
||||
"description": "Storing, retrieving, and managing knowledge",
|
||||
"go_surfaces": [
|
||||
"memory-store-ops",
|
||||
"curator",
|
||||
"sleep-time",
|
||||
"consolidation-ops",
|
||||
"persona-gate",
|
||||
"witness-ops",
|
||||
"stage-guards"
|
||||
],
|
||||
"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",
|
||||
@@ -204,63 +142,18 @@
|
||||
"tier_manager",
|
||||
"warm_neuron_store"
|
||||
],
|
||||
"rust_crates": [
|
||||
"memory_retrieval",
|
||||
"memory_scoring",
|
||||
"memory_storage",
|
||||
"query_memory"
|
||||
"depends_on": [
|
||||
"governance"
|
||||
],
|
||||
"mirrors": [],
|
||||
"canaries": [
|
||||
"canary_full_system",
|
||||
"canary_memory_synthesis",
|
||||
"canary_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",
|
||||
"go_surfaces": [
|
||||
"event-bus",
|
||||
"message-queue",
|
||||
"hook-engine",
|
||||
"microkernel",
|
||||
"subsystem-health",
|
||||
"parallel-processor",
|
||||
"work-manager",
|
||||
"failure-filer",
|
||||
"cron-engine",
|
||||
"night-mode",
|
||||
"recall-router",
|
||||
"local-tool-runtime",
|
||||
"tool-executor",
|
||||
"operator",
|
||||
"adaptive-router",
|
||||
"build-mode",
|
||||
"builder-bridge",
|
||||
"core-server",
|
||||
"auto-context",
|
||||
"auto-tasks",
|
||||
"event-wait",
|
||||
"evidence-probe",
|
||||
"forge",
|
||||
"forge-client",
|
||||
"goal",
|
||||
"growth-delta",
|
||||
"warm-router",
|
||||
"release-notes"
|
||||
],
|
||||
"mirrors": [],
|
||||
"modules": [
|
||||
"auto_detect",
|
||||
"build_mode",
|
||||
@@ -295,24 +188,32 @@
|
||||
"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"
|
||||
]
|
||||
},
|
||||
"perception": {
|
||||
"canaries": [
|
||||
"canary_context_broker",
|
||||
"canary_full_system"
|
||||
],
|
||||
"depends_on": [
|
||||
"memory"
|
||||
],
|
||||
"description": "Input processing and context assembly",
|
||||
"mirrors": [],
|
||||
"modules": [
|
||||
"attention_capsule",
|
||||
"auto_context",
|
||||
@@ -347,8 +248,6 @@
|
||||
"salience_gate",
|
||||
"scaffold",
|
||||
"spine",
|
||||
"spine_language",
|
||||
"spine_loader",
|
||||
"stage_guards",
|
||||
"structural_migration",
|
||||
"structural_model",
|
||||
@@ -360,9 +259,14 @@
|
||||
"wait_guard_corpus",
|
||||
"witness"
|
||||
],
|
||||
"rust_crates": [
|
||||
"rune_spine"
|
||||
"depends_on": [
|
||||
"memory"
|
||||
],
|
||||
"mirrors": [],
|
||||
"canaries": [
|
||||
"canary_context_broker",
|
||||
"canary_full_system"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-16
@@ -272,19 +272,4 @@ 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).
|
||||
|
||||
## 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.
|
||||
history: skipped (weak evidence — honest limitation).
|
||||
@@ -1,205 +0,0 @@
|
||||
# DICHOTOMY REBASE — HONEST AUDIT (function-level)
|
||||
|
||||
_Regenerate with `python3 scripts/dichotomy_audit.py --write`. A module is FULL only when 80%+ of its Python functions have name-preserving counterparts in the Go/Rust implementation — directories without the functions are facades and count as NOT TOUCHED._
|
||||
|
||||
**Function-level completion: 13%** (290/2225 runtime functions matched)
|
||||
|
||||
| Status | Modules | Lines | Meaning |
|
||||
|---|---|---|---|
|
||||
| FULL | 7 | 686 | 80%+ of functions ported |
|
||||
| PARTIAL | 50 | 17873 | 20–80% — real logic exists, gaps named below |
|
||||
| NOT TOUCHED | 121 | 49578 | no name-preserving implementation |
|
||||
| Total runtime | 178 | 68137 | |
|
||||
|
||||
## NOT TOUCHED — the port queue, in priority order (largest first)
|
||||
|
||||
| Module | Lines | Fns | Side |
|
||||
|---|---|---|---|
|
||||
| rune_tui | 4038 | 157 | TUI-LAST |
|
||||
| rune_operator | 2723 | 68 | GO |
|
||||
| memory_store | 2573 | 77 | GO |
|
||||
| curator | 1838 | 43 | GO |
|
||||
| tool_executor | 1812 | 47 | GO |
|
||||
| warm_router | 1536 | 36 | GO |
|
||||
| construction_interface | 1173 | 27 | RUST |
|
||||
| spine | 1034 | 31 | RUST |
|
||||
| construction_decision | 1014 | 20 | RUST |
|
||||
| scaffold | 868 | 31 | GO |
|
||||
| elastic_cognition | 765 | 13 | GO |
|
||||
| memory_consolidation | 740 | 22 | GO |
|
||||
| structural_store | 656 | 33 | RUST |
|
||||
| abstraction | 647 | 16 | GO |
|
||||
| contracts | 626 | 7 | RUST |
|
||||
| work_manager | 591 | 25 | GO |
|
||||
| construction_intent | 555 | 16 | RUST |
|
||||
| canary_audit_ledger | 540 | 2 | TEST-INFRA |
|
||||
| identity_anchors | 537 | 16 | RUST |
|
||||
| build_mode | 517 | 33 | GO |
|
||||
| drift_core | 517 | 14 | RUST |
|
||||
| event_wait | 517 | 14 | GO |
|
||||
| tui_validator | 514 | 13 | TUI-LAST |
|
||||
| memory_selector | 511 | 13 | RUST |
|
||||
| system_registry | 501 | 14 | RUST |
|
||||
| construction_pattern | 496 | 12 | RUST |
|
||||
| graph_memory | 474 | 9 | RUST |
|
||||
| tool_protocol | 461 | 27 | GO |
|
||||
| auto_tasks | 460 | 14 | GO |
|
||||
| capability_fit | 455 | 13 | RUST |
|
||||
| drift_ledger | 453 | 16 | RUST |
|
||||
| goal | 441 | 19 | GO |
|
||||
| release_notes | 439 | 16 | GO |
|
||||
| cron_engine | 436 | 27 | GO |
|
||||
| model_profiles | 435 | 15 | GO |
|
||||
| model_routing | 432 | 13 | GO |
|
||||
| voice_hybrid | 421 | 10 | RUST |
|
||||
| behavior | 407 | 9 | RUST |
|
||||
| token_optimizer | 407 | 22 | RUST |
|
||||
| capability_ledger | 405 | 18 | RUST |
|
||||
| chat_bubble | 401 | 12 | TUI-LAST |
|
||||
| prompt_sync | 376 | 14 | RUST |
|
||||
| provider_budget | 354 | 20 | GO |
|
||||
| structural_model | 352 | 20 | RUST |
|
||||
| programme_continuation | 349 | 11 | RUST |
|
||||
| canary_rune_serve | 329 | 13 | TEST-INFRA |
|
||||
| builder_bridge | 326 | 11 | GO |
|
||||
| canary_p1_07 | 324 | 10 | TEST-INFRA |
|
||||
| layout_contract | 316 | 6 | RUST |
|
||||
| drift_observability | 315 | 8 | RUST |
|
||||
| build_basis | 314 | 12 | RUST |
|
||||
| canary_p0_07 | 310 | 10 | TEST-INFRA |
|
||||
| attention_capsule | 296 | 7 | RUST |
|
||||
| canary_p1_01 | 294 | 12 | TEST-INFRA |
|
||||
| voice_sync | 293 | 10 | RUST |
|
||||
| drift_cache | 292 | 15 | RUST |
|
||||
| outcome_ledger | 286 | 7 | RUST |
|
||||
| time_awareness | 283 | 14 | RUST |
|
||||
| tiered_executor | 282 | 7 | GO |
|
||||
| standardized_providers | 281 | 5 | GO |
|
||||
| canary_p1_06 | 280 | 7 | TEST-INFRA |
|
||||
| canary_p1_03 | 271 | 9 | TEST-INFRA |
|
||||
| auto_context | 270 | 8 | GO |
|
||||
| canary_gitea_automation | 263 | 3 | TEST-INFRA |
|
||||
| canary_p1_02 | 253 | 10 | TEST-INFRA |
|
||||
| construction_patterns_builtin | 249 | 1 | RUST |
|
||||
| canary_full_system | 244 | 2 | TEST-INFRA |
|
||||
| toolchain | 236 | 5 | RUST |
|
||||
| task_gate | 235 | 8 | RUST |
|
||||
| core_server | 234 | 12 | GO |
|
||||
| canary_native | 231 | 3 | TEST-INFRA |
|
||||
| openai_compat_transport | 227 | 9 | GO |
|
||||
| shard_manager | 223 | 9 | RUST |
|
||||
| spine_language | 218 | 5 | RUST |
|
||||
| evidence_probe | 212 | 9 | GO |
|
||||
| model_registry | 211 | 7 | GO |
|
||||
| canary_p0_04 | 207 | 8 | TEST-INFRA |
|
||||
| forge_client | 203 | 18 | GO |
|
||||
| canary_context_broker | 199 | 10 | TEST-INFRA |
|
||||
| canary_p0_05 | 199 | 13 | TEST-INFRA |
|
||||
| testing_mode | 196 | 12 | RUST |
|
||||
| cc_loader | 195 | 26 | RUST |
|
||||
| canary_spine_meta | 192 | 7 | TEST-INFRA |
|
||||
| verification_layer | 189 | 12 | RUST |
|
||||
| ffi_query_memory_smoke | 182 | 5 | RUST |
|
||||
| canary_tui_transport | 174 | 7 | TEST-INFRA |
|
||||
| behaviour_ledger | 173 | 12 | RUST |
|
||||
| canary_tui_drift | 170 | 2 | TEST-INFRA |
|
||||
| inference_trace | 164 | 6 | RUST |
|
||||
| ms_loader | 163 | 16 | RUST |
|
||||
| voicebox | 161 | 11 | GO |
|
||||
| canary_gitea_pipeline | 159 | 2 | TEST-INFRA |
|
||||
| forge | 146 | 11 | GO |
|
||||
| rune_graphic | 145 | 5 | TUI-LAST |
|
||||
| project_registry | 139 | 11 | RUST |
|
||||
| voice_injector | 138 | 5 | GO |
|
||||
| canary_rune_entry | 137 | 3 | TEST-INFRA |
|
||||
| tui_backlog | 125 | 5 | TUI-LAST |
|
||||
| drift_resume | 118 | 3 | RUST |
|
||||
| canary_conversation_state | 115 | 2 | TEST-INFRA |
|
||||
| canary_query_memory | 110 | 2 | TEST-INFRA |
|
||||
| tui_transport | 108 | 10 | TUI-LAST |
|
||||
| spine_loader | 105 | 7 | RUST |
|
||||
| canary_unbounded | 104 | 2 | TEST-INFRA |
|
||||
| message_widgets | 104 | 6 | TUI-LAST |
|
||||
| sc_loader | 96 | 6 | RUST |
|
||||
| cs_loader | 90 | 5 | RUST |
|
||||
| tc_loader | 88 | 5 | RUST |
|
||||
| canary_schema_migration | 86 | 1 | TEST-INFRA |
|
||||
| mems_loader | 83 | 5 | RUST |
|
||||
| provider_context | 48 | 1 | GO |
|
||||
| wait_guard_corpus | 46 | 0 | RUST |
|
||||
| canary_cognitive_strata | 44 | 1 | TEST-INFRA |
|
||||
| builder_bridge_cli | 42 | 1 | GO |
|
||||
| __init__ | 40 | 1 | RUST |
|
||||
| mr_loader | 38 | 13 | RUST |
|
||||
| canary_memory_synthesis | 33 | 1 | TEST-INFRA |
|
||||
| canary_resource_authority | 33 | 1 | TEST-INFRA |
|
||||
| canary_surface_parity | 33 | 1 | TEST-INFRA |
|
||||
| canary_orchestration_foundation | 32 | 1 | TEST-INFRA |
|
||||
| canary_gitea_delegation | 31 | 1 | TEST-INFRA |
|
||||
|
||||
## PARTIAL — gaps to close (matched/total fns; first missing named)
|
||||
|
||||
| Module | Lines | Coverage | Missing (first named) |
|
||||
|---|---|---|---|
|
||||
| local_tool_runtime | 806 | 8/30 | _find_capability_executor, _extract_context_length, context_length, reset_context_length_cache, supports_tools, supports_thinking |
|
||||
| provider_registry | 666 | 7/27 | _format_tools_openai, _format_tools_anthropic, _execute_tool_calls, _execute_tool_calls_anthropic, get_registry, connect_provider |
|
||||
| sleep_time | 971 | 5/25 | _ensure_dirs, db_connect, fetch_sessions, extract_parts, extract_todos, write_transcript |
|
||||
| persona_gate | 724 | 7/26 | _now, _cc_pg_core, _py_lex, _lex_input, _py_overlap, _embed_raw |
|
||||
| context_broker | 823 | 8/26 | _py_default_estimator, _cc_core, _py_default_budget, _py_default_memory_budget, _py_memory_disabled_value, reset_discovered_windows |
|
||||
| capability_broker | 905 | 4/20 | _native_tool_schemas, _infer_task_family, _scored_tools, _select_for_job, load_registry, _native_tool_cards |
|
||||
| safety_override | 569 | 7/22 | _keyword_stopwords, _cc_probe, cc_loader_pin, self_test, _py_matches, escalation_rate |
|
||||
| growth_delta | 437 | 5/19 | _store_db, _llm, _parse_json, _load_deltas, _save_deltas, _cc_core |
|
||||
| failure_auto_filer | 527 | 11/24 | _error_text, unconsumed, mark_consumed, unconsumed, mark_consumed, submit |
|
||||
| night_mode | 405 | 5/18 | get_night_mode, start_night_mode, stop_night_mode, get_status, get_report, to_dict |
|
||||
| cache | 492 | 5/17 | _record_hit, _record_miss, flush_stats, get_cache, put_cache, invalidate_scope |
|
||||
| parallel_processor | 194 | 3/14 | _shutdown_processor, get_processor, run_parallel_with_args, get_status, test_parallel, run_parallel_with_args |
|
||||
| claim_audit | 483 | 4/14 | _get_warm_neuron_store, reframe, _graph_has, _warm_has, verify, journal |
|
||||
| tier_manager | 262 | 5/15 | _cc_probe, cc_loader_pin, _py_core_now, _py_get_tier, _py_promote, _py_demote |
|
||||
| witness | 466 | 7/17 | _now, _tables, _cc_probe, cc_loader_pin, _py_extract_topic, _py_detect_signals |
|
||||
| drift_compression | 307 | 3/12 | _py_get_compression_ratio, _py_compress_text, _py_compress_entry, _py_should_warn, _py_warn_before_compress, get_compression_ratio |
|
||||
| message_queue | 316 | 5/13 | _load_queue, _save_queue, add_message, get_pending, approve_all, get_approved |
|
||||
| model_connect | 462 | 2/10 | is_moe_model, _now, _clean_model_name, _get_cloud_models, health_check, route_model |
|
||||
| intent_continuity | 168 | 2/9 | to_dict, from_dict, _load, save, create_detour, resolve_detour |
|
||||
| pins | 284 | 5/12 | _store_path, _save, _detail_blob, unpin, _py_pin_recall, list_pins |
|
||||
| adaptive_router | 625 | 13/19 | _floor_applies_from_flags, _floor_reason, record_final_route, _event, _record_transition_with, _detect_external_refs |
|
||||
| audit_ledger | 231 | 2/8 | _compute_hash, get_entries, log_promotion, log_gate_result, log_drift_alert, main |
|
||||
| context_pressure | 262 | 3/9 | log_measurement, read_log, log_stats, _now, handle_hook, main |
|
||||
| hook_engine | 860 | 2/8 | discover_functions, tag_function, recommend_placement, validate_placements, generate_report, handle_hook |
|
||||
| microkernel | 434 | 6/12 | now_iso, discover, _extract_manifest, _load_registry, _save_registry, _run_hook |
|
||||
| persona_definition | 210 | 2/8 | _by_topic, compile_full, emit_constitution, emit_identity, emit_persona, handle_hook |
|
||||
| progressive_escalation | 279 | 2/8 | execute_with_escalation, test_escalation, handle_hook, to_dict, execute, verify |
|
||||
| connection_pool | 144 | 3/8 | get_pool, get_connection, get_status, get_connection, get_status |
|
||||
| iteration | 190 | 3/8 | _now, context_packet, predictive_impact, descriptive_impact, add |
|
||||
| task_persist | 269 | 5/10 | _save, export, restore, main, handle_hook |
|
||||
| construction_commands | 268 | 1/5 | _refuse, _validate, _accept, dispatch |
|
||||
| construction_mode | 395 | 1/5 | _tokens, _contains_any, to_dict, from_dict |
|
||||
| event_envelope | 303 | 4/8 | _content_hash, test_envelope, to_canonical_dict, to_dict |
|
||||
| response_adapter | 222 | 3/7 | parse_plain_response, parse_response, test_adapter, to_dict |
|
||||
| self_improve | 242 | 1/5 | _now, suggest_improvements, handle_hook, main |
|
||||
| subconscious_pass | 187 | 1/5 | main, _extract_topic, save_reflection, get_recent_findings |
|
||||
| construction_activation | 237 | 1/4 | _scaffold_for, _auto_structural_awareness, dispatch_from_decision |
|
||||
| dependency_tracker | 202 | 2/5 | check_propagation, get_full_map, main |
|
||||
| event_bus | 244 | 4/7 | _store_path, _content_hash, handle_hook |
|
||||
| salience_gate | 243 | 1/4 | test_salience, handle_hook, to_dict |
|
||||
| subsystem_health | 163 | 3/6 | set_auto_filer, record_failure, configure_logging |
|
||||
| warm_neuron_store | 122 | 3/6 | _db, neuron_slugs, handle_hook |
|
||||
| cognitive_budgeter | 208 | 1/3 | test_budgeter, to_dict |
|
||||
| construction_projection | 135 | 1/3 | _contract_entity, validate |
|
||||
| graph_projection | 108 | 3/5 | write_all, _now |
|
||||
| rune_profiler | 165 | 1/3 | profile_model_call, main |
|
||||
| stage_guards | 281 | 7/9 | to_dict, chk |
|
||||
| structural_migration | 77 | 2/4 | apply_migration, consent_brief |
|
||||
| construction_depth | 138 | 1/2 | to_dict |
|
||||
| recall_router | 162 | 2/3 | handle_hook |
|
||||
|
||||
## FULL — ported, parity-gated
|
||||
|
||||
| Module | Lines | Fns | Side |
|
||||
|---|---|---|---|
|
||||
| recall_uplift | 141 | 1/1 | RUST |
|
||||
| rune_spinner | 130 | 4/5 | RUST |
|
||||
| wait_guard | 116 | 1/1 | RUST |
|
||||
| failure_recovery | 108 | 1/1 | RUST |
|
||||
| programme_gates | 85 | 4/5 | RUST |
|
||||
| impact_preview | 69 | 2/2 | RUST |
|
||||
| route_risk_flags | 37 | 1/1 | RUST |
|
||||
@@ -235,8 +235,8 @@
|
||||
{
|
||||
"number": 183,
|
||||
"title": "Future: typed temporal semantics for facts, relationships, beliefs, and preferences",
|
||||
"tracker_state": "closed",
|
||||
"reconciliation_state": "HISTORICAL_EVIDENCE",
|
||||
"tracker_state": "open",
|
||||
"reconciliation_state": "DEFERRED_FUTURE",
|
||||
"labels": [
|
||||
"P3 \u2014 low",
|
||||
"governance",
|
||||
@@ -248,14 +248,14 @@
|
||||
"ready"
|
||||
],
|
||||
"live_defect": false,
|
||||
"last_revalidated": "2026-09-19",
|
||||
"next_action": "none \u2014 idea absorbed into parent epic #181 as tracked checklist item; full detail preserved in this closed issue; re-mint when live"
|
||||
"last_revalidated": "2026-09-11",
|
||||
"next_action": ""
|
||||
},
|
||||
{
|
||||
"number": 182,
|
||||
"title": "Future: GitHub code-search prior-art audit for graph and vector memory",
|
||||
"tracker_state": "closed",
|
||||
"reconciliation_state": "HISTORICAL_EVIDENCE",
|
||||
"tracker_state": "open",
|
||||
"reconciliation_state": "DEFERRED_FUTURE",
|
||||
"labels": [
|
||||
"P3 \u2014 low",
|
||||
"governance",
|
||||
@@ -264,8 +264,8 @@
|
||||
"ready"
|
||||
],
|
||||
"live_defect": false,
|
||||
"last_revalidated": "2026-09-19",
|
||||
"next_action": "none \u2014 idea absorbed into parent epic #181 as tracked checklist item; full detail preserved in this closed issue; re-mint when live"
|
||||
"last_revalidated": "2026-09-11",
|
||||
"next_action": ""
|
||||
},
|
||||
{
|
||||
"number": 181,
|
||||
@@ -285,13 +285,13 @@
|
||||
],
|
||||
"live_defect": false,
|
||||
"last_revalidated": "2026-09-11",
|
||||
"next_action": "epic holds absorbed children #182 #183 + research watchlist #164 #165 #166; closes when prerequisites land or ideas dropped"
|
||||
"next_action": ""
|
||||
},
|
||||
{
|
||||
"number": 179,
|
||||
"title": "Future: succession/privacy semantics and lineage evaluation",
|
||||
"tracker_state": "closed",
|
||||
"reconciliation_state": "HISTORICAL_EVIDENCE",
|
||||
"tracker_state": "open",
|
||||
"reconciliation_state": "DEFERRED_FUTURE",
|
||||
"labels": [
|
||||
"P3 \u2014 low",
|
||||
"governance",
|
||||
@@ -303,14 +303,14 @@
|
||||
"ready"
|
||||
],
|
||||
"live_defect": false,
|
||||
"last_revalidated": "2026-09-19",
|
||||
"next_action": "none \u2014 idea absorbed into parent epic #175 as tracked checklist item; full detail preserved in this closed issue; re-mint when live"
|
||||
"last_revalidated": "2026-09-11",
|
||||
"next_action": ""
|
||||
},
|
||||
{
|
||||
"number": 178,
|
||||
"title": "Future: evidence-grounded ancestral perspective with explicit uncertainty",
|
||||
"tracker_state": "closed",
|
||||
"reconciliation_state": "HISTORICAL_EVIDENCE",
|
||||
"tracker_state": "open",
|
||||
"reconciliation_state": "DEFERRED_FUTURE",
|
||||
"labels": [
|
||||
"P3 \u2014 low",
|
||||
"governance",
|
||||
@@ -320,14 +320,14 @@
|
||||
"perception"
|
||||
],
|
||||
"live_defect": false,
|
||||
"last_revalidated": "2026-09-19",
|
||||
"next_action": "none \u2014 idea absorbed into parent epic #175 as tracked checklist item; full detail preserved in this closed issue; re-mint when live"
|
||||
"last_revalidated": "2026-09-11",
|
||||
"next_action": ""
|
||||
},
|
||||
{
|
||||
"number": 177,
|
||||
"title": "Future: temporal autobiographical model with provenance and reinterpretation lineage",
|
||||
"tracker_state": "closed",
|
||||
"reconciliation_state": "HISTORICAL_EVIDENCE",
|
||||
"tracker_state": "open",
|
||||
"reconciliation_state": "DEFERRED_FUTURE",
|
||||
"labels": [
|
||||
"P3 \u2014 low",
|
||||
"governance",
|
||||
@@ -338,14 +338,14 @@
|
||||
"ready"
|
||||
],
|
||||
"live_defect": false,
|
||||
"last_revalidated": "2026-09-19",
|
||||
"next_action": "none \u2014 idea absorbed into parent epic #175 as tracked checklist item; full detail preserved in this closed issue; re-mint when live"
|
||||
"last_revalidated": "2026-09-11",
|
||||
"next_action": ""
|
||||
},
|
||||
{
|
||||
"number": 176,
|
||||
"title": "Future: lineage-aware situated curiosity for meaningful autobiographical gaps",
|
||||
"tracker_state": "closed",
|
||||
"reconciliation_state": "HISTORICAL_EVIDENCE",
|
||||
"tracker_state": "open",
|
||||
"reconciliation_state": "DEFERRED_FUTURE",
|
||||
"labels": [
|
||||
"P3 \u2014 low",
|
||||
"feature",
|
||||
@@ -356,8 +356,8 @@
|
||||
"ready"
|
||||
],
|
||||
"live_defect": false,
|
||||
"last_revalidated": "2026-09-19",
|
||||
"next_action": "none \u2014 idea absorbed into parent epic #175 as tracked checklist item; full detail preserved in this closed issue; re-mint when live"
|
||||
"last_revalidated": "2026-09-11",
|
||||
"next_action": ""
|
||||
},
|
||||
{
|
||||
"number": 175,
|
||||
@@ -377,13 +377,13 @@
|
||||
],
|
||||
"live_defect": false,
|
||||
"last_revalidated": "2026-09-11",
|
||||
"next_action": "epic holds absorbed children #176-#179 as checklist items; closes when prerequisites land or ideas dropped"
|
||||
"next_action": ""
|
||||
},
|
||||
{
|
||||
"number": 166,
|
||||
"title": "RESEARCH WATCHLIST: Memory-R1 (RL memory ops), Titans (test-time memory), Vespa/Weaviate/Milvus (retrieval competitors)",
|
||||
"tracker_state": "closed",
|
||||
"reconciliation_state": "HISTORICAL_EVIDENCE",
|
||||
"tracker_state": "open",
|
||||
"reconciliation_state": "DEFERRED_FUTURE",
|
||||
"labels": [
|
||||
"P3 \u2014 low",
|
||||
"growth",
|
||||
@@ -392,14 +392,14 @@
|
||||
"ready"
|
||||
],
|
||||
"live_defect": false,
|
||||
"last_revalidated": "2026-09-19",
|
||||
"next_action": "none \u2014 idea absorbed into parent epic #181 as tracked checklist item; full detail preserved in this closed issue; re-mint when live"
|
||||
"last_revalidated": "2026-09-11",
|
||||
"next_action": ""
|
||||
},
|
||||
{
|
||||
"number": 165,
|
||||
"title": "RESEARCH: SimpleMem semantic compression + A-MEM dynamic linking + Letta sleep-time compute",
|
||||
"tracker_state": "closed",
|
||||
"reconciliation_state": "HISTORICAL_EVIDENCE",
|
||||
"tracker_state": "open",
|
||||
"reconciliation_state": "DEFERRED_FUTURE",
|
||||
"labels": [
|
||||
"P3 \u2014 low",
|
||||
"infrastructure",
|
||||
@@ -408,14 +408,14 @@
|
||||
"ready"
|
||||
],
|
||||
"live_defect": false,
|
||||
"last_revalidated": "2026-09-19",
|
||||
"next_action": "none \u2014 idea absorbed into parent epic #181 as tracked checklist item; full detail preserved in this closed issue; re-mint when live"
|
||||
"last_revalidated": "2026-09-11",
|
||||
"next_action": ""
|
||||
},
|
||||
{
|
||||
"number": 164,
|
||||
"title": "RESEARCH: HippoRAG 2 \u2014 PPR-style associative propagation as warm-neuron activation candidate",
|
||||
"tracker_state": "closed",
|
||||
"reconciliation_state": "HISTORICAL_EVIDENCE",
|
||||
"tracker_state": "open",
|
||||
"reconciliation_state": "DEFERRED_FUTURE",
|
||||
"labels": [
|
||||
"P3 \u2014 low",
|
||||
"growth",
|
||||
@@ -424,8 +424,8 @@
|
||||
"ready"
|
||||
],
|
||||
"live_defect": false,
|
||||
"last_revalidated": "2026-09-19",
|
||||
"next_action": "none \u2014 idea absorbed into parent epic #181 as tracked checklist item; full detail preserved in this closed issue; re-mint when live"
|
||||
"last_revalidated": "2026-09-11",
|
||||
"next_action": ""
|
||||
},
|
||||
{
|
||||
"number": 163,
|
||||
@@ -1150,5 +1150,5 @@
|
||||
}
|
||||
],
|
||||
"last_reconciled": "2026-09-19",
|
||||
"reconciled_by": "fresh-session tranche 2026-09-19: template retrofit (spine+plain-English on all open issues), closures #158/#162 (SUPERSEDED) and #324 (FIXED_VERIFIED), research labels applied to #163/#164/#165/#166/#182/#316, stale bug labels removed from #163-#166; 2026-09-19 absorption pass: parked children absorbed into parents (#175<-#176..#179; #181<-#182,#183,#164..#166) per one-open-note-per-idea standard"
|
||||
"reconciled_by": "fresh-session tranche 2026-09-19: template retrofit (spine+plain-English on all open issues), closures #158/#162 (SUPERSEDED) and #324 (FIXED_VERIFIED), research labels applied to #163/#164/#165/#166/#182/#316, stale bug labels removed from #163-#166"
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
# THE LANGUAGE DICHOTOMY LEDGER — measured, not assumed
|
||||
|
||||
_Created 2026-10-06 from real benchmarks. This is the governing standard for every port in the full dichotomy rebase. Every port must pass the "which language is better for THIS operation?" test before being assigned._
|
||||
|
||||
---
|
||||
|
||||
## The Measured Benchmarks
|
||||
|
||||
| Operation | Python | Python ctypes → Rust | Go cgo → Rust | Pure Go inline |
|
||||
|---|---|---|---|---|
|
||||
| Simple tier check | 0.05 µs | 1.4 µs | 1.4 µs | — |
|
||||
| Consolidation (669B payload) | 0.2 µs | 2.9 µs | 3.4 µs | 0.3 µs |
|
||||
| Concurrent HTTP (10 requests) | 10.8ms (4.0x) | — | 8.4ms (5.1x) | — |
|
||||
| CPU-bound pattern matching (1000 msgs) | 9.6ms (0.8x — GIL) | — | ~2.5ms (est. 3.5-4x) | — |
|
||||
| Compression + zlib wrapper | 0.2 µs | 13.7 µs (worse!) | — | — |
|
||||
|
||||
## The Laws
|
||||
|
||||
### Law 1: FFI overhead is negligible for the real workload
|
||||
The cgo/ctypes boundary costs 1.4-3.4 µs per call. Ollama inference costs 200-5000 ms. FFI overhead is 0.0003-0.0017% of total request time. The language of the caller doesn't matter for the boundary.
|
||||
|
||||
### Law 2: Go wins for CPU-bound reactive work
|
||||
Goroutines deliver true parallelism (5.1x concurrent HTTP, ~3.5-4x CPU-bound). Python's GIL serialises CPU-bound work (0.8x speedup with 4 threads). Go wins for: operator, witness, event bus, work manager, tool executor.
|
||||
|
||||
### Law 3: Simple operations stay in the caller's language
|
||||
Pure Python compression: 0.3 µs. Same op via Rust FFI: 10.4 µs. The FFI overhead exceeds the compute benefit for simple operations. If a Go module needs a string truncation, do it IN GO.
|
||||
|
||||
### Law 4: Rust wins for complex deterministic operations
|
||||
Compile-time type safety, zero-cost abstractions, memory safety, near-native speed for complex compute. Rust wins for: scoring, dedup, pattern matching across many signals, record assembly with many fields, structural store operations.
|
||||
|
||||
### Law 5: Compression across the FFI boundary makes things SLOWER
|
||||
Measured: uncompressed FFI call = 6.1 µs. With zlib wrapper = 13.7 µs (+125%). The cgo transition overhead (~1-2µs) dominates; payload size doesn't matter for local calls under 10KB. Compression helps only for network transfers (>100KB payloads).
|
||||
|
||||
### Law 6: Reduced payload (shorter keys) gives a marginal improvement
|
||||
Measured: 6.1 → 4.6 µs (-25%) by shortening JSON keys from "wash_count" to "w". This is a valid optimisation for hot-path FFI calls but not worth the complexity for most operations.
|
||||
|
||||
### Law 7: Pure inline (no FFI) is fastest when the operation is simple
|
||||
Measured: pure Go inline = 0.3 µs vs 6.1 µs via FFI. If the operation is simple enough to implement in the caller's language, do it inline. Only cross the FFI boundary for operations complex enough to justify it.
|
||||
|
||||
---
|
||||
|
||||
## The Practical Decision Tree
|
||||
|
||||
```
|
||||
Is the operation I/O-bound (HTTP, subprocess, file I/O)?
|
||||
→ YES → GO (goroutines, net/http, os/exec)
|
||||
→ NO ↓
|
||||
|
||||
Is the operation CPU-bound and in the request path (responding to user)?
|
||||
→ YES → GO (goroutines give true parallelism where the GIL fails)
|
||||
→ NO ↓
|
||||
|
||||
Is the operation complex deterministic compute (multiple functions, thresholds, scoring)?
|
||||
→ YES → RUST (type safety, zero-cost abstractions, memory safety)
|
||||
BUT measure: does the compute exceed the FFI overhead?
|
||||
→ NO ↓
|
||||
|
||||
Is the operation simple (string truncation, basic comparison, simple lookup)?
|
||||
→ YES → Do it INLINE in the caller's language (no FFI)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## The Wave Assignment (corrected)
|
||||
|
||||
| Wave | Language | Why |
|
||||
|---|---|---|
|
||||
| W4: event-bus, hook-engine, message-queue, microkernel, subsystem-health, parallel-processor, work-manager, failure-filer, cron-engine, night-mode, cache, connection-pool, recall-router | **Go** | I/O-bound, CPU-bound reactive, event-driven |
|
||||
| W4b: tool-executor, tool-protocol, local-tool-runtime | **Go** | I/O-bound, request-path |
|
||||
| W5a: model-connect (all 10 provider modules) | **Go** | I/O-bound (HTTP), connection pooling |
|
||||
| W5b: operator, adaptive_router, build_mode, warm_router, etc. | **Go** | CPU-bound reactive (routing, dispatch) + I/O-bound |
|
||||
| W5c: memory_store, curator, sleep_time | **Go** | I/O-bound (SQLite + subprocess) |
|
||||
| W6: spine, construction_*, contracts, capability_*, drift_*, graph_memory, memory_selector, identity_anchors, pins, salience_gate, self_improve, token_optimizer | **Rust** | Complex deterministic compute (scoring, dedup, classification, structural operations) |
|
||||
| W6 simple modules: response_adapter, route_risk_flags, rune_profiler, rune_spinner, wait_guard, task_persist, time_awareness | **Stay in caller's language** | Simple operations where FFI overhead > compute benefit |
|
||||
| W7: TUI | **Go (Bubble Tea)** | The reactive front end that interfaces with the user |
|
||||
|
||||
---
|
||||
|
||||
## The Compression Idea (EXPERIMENTAL — NOT WORTH IT)
|
||||
|
||||
**Measured result: compression across the FFI boundary makes things 125% SLOWER.**
|
||||
|
||||
The cgo transition overhead (~1-2µs) is the dominant cost, not the payload size. Compressing the payload adds CPU work (compress + decompress) that exceeds the benefit of a smaller payload crossing the boundary. The compressed payload is 20% of the original size, but the total time doubles.
|
||||
|
||||
Compression WOULD help only if:
|
||||
- The payload were >100KB (network transfer between machines)
|
||||
- The boundary were a network connection, not a local function call
|
||||
|
||||
**Mark as experimental and park. Do not implement.**
|
||||
|
||||
---
|
||||
|
||||
## The Hybrid Language Idea (FUTURE — NOT NOW)
|
||||
|
||||
A hybrid language combining Go's concurrency with Rust's type safety and memory safety would eliminate the FFI boundary entirely. This would be the ideal language for the entire runtime.
|
||||
|
||||
But this is a much larger project — effectively designing and implementing a new programming language. It should be explored after the rebase is complete and the system is stable in Go+Rust. The cgo boundary works today with negligible overhead.
|
||||
|
||||
---
|
||||
|
||||
## Provenance
|
||||
|
||||
- Benchmarks run 2026-10-06 on nick-desktop (CachyOS, 4 cores, cgo 1.21, modernc.org/sqlite)
|
||||
- Rust kernel: libcognition_core.so from cognition_core crate
|
||||
- Go binaries: statically linked, go 1.21
|
||||
- Python: /home/nick/.venvs/memory/bin/python3
|
||||
- These measurements are for THIS hardware and THIS codebase. Re-measure if the hardware changes.
|
||||
|
||||
|
||||
---
|
||||
|
||||
## The Hybrid Language: SURVIVOR
|
||||
|
||||
Named by Nick (2026-10-06): Rust (survives, memory-safe, deterministic) + Go (running, reactive, concurrent) = **Survivor** — the hybrid language pattern where Go reactive code links Rust deterministic compute as a static library at compile time.
|
||||
|
||||
### The Survivor Build Pattern
|
||||
- Rust crates compile as staticlib (.a) + cdylib (.so)
|
||||
- Go binaries link the .a files at compile time via cgo LDFLAGS
|
||||
- The caller sees ONE binary with ONE function call — no FFI boundary from the outside
|
||||
- No CC_RUST_LIB / SC_RUST_LIB env vars needed
|
||||
- Measured: 0.6µs/call vs 1.4-3.4µs for the .so approach
|
||||
|
||||
### Survivor Go Packages
|
||||
All under src/go/cognition/:
|
||||
- cognition (root): tier, consolidation, witness, safety, drift, pins, growth
|
||||
- retrieval: memory_retrieval kernel (mr_call)
|
||||
- storage: memory_storage kernel (mems_read_query)
|
||||
- scaffold: scaffold_core kernel (sc_check_transition, sc_close_quality, sc_language_placement)
|
||||
- provenance: evidence_provenance kernel (ep_* functions)
|
||||
- spine: rune_spine kernel (sp_drift, sp_export, sp_project, sp_query)
|
||||
- scoring: memory_scoring kernel (ms_* functions)
|
||||
- capability: capability_scoring kernel (cs_evaluate_fit, cs_score_card)
|
||||
- token: token_counting kernel (tc_compress_context, tc_estimate_tokens)
|
||||
- query: query_memory kernel (qm_* functions)
|
||||
@@ -1,382 +0,0 @@
|
||||
# Language-Fit Rubric — Wave 1 (Language-Rebasing Tranche R1)
|
||||
|
||||
> STATUS: FINAL — self-verified 2026-09-29 per tranche §12 (all 6 rounds completed,
|
||||
> evidence-sufficiency statements recorded, kill tests frozen; execution proceeds on the
|
||||
> evidence, every RECODE still passes its benchmark gate — no win, no recode).
|
||||
> Per-subsystem sections filled from live research rounds (≥2 live-verified external sources per claim,
|
||||
> per-source lessons, evidence→decision mapping, kill test per candidate). No code changes in Wave 1.
|
||||
> Governing law from §11: **KEEP-PYTHON honesty determines how much of the rebase volume is real.**
|
||||
> Toolchain baseline: Rust 1.98.1 + GCC 16.2.1 present; Go NOT installed — Go earns installation only
|
||||
> through rubric evidence here.
|
||||
|
||||
## Verdict (all rounds, one paragraph)
|
||||
|
||||
**KEEP-PYTHON across the board: 40 clusters scored, 0 recode units awarded.** Six research
|
||||
rounds (W2 leaf utilities, W3 memory, W4 provider-layer, W5 orchestration, W6 runtime-core,
|
||||
W7 TUI) each characterized their subsystem's actual workload inward (file:line-anchored) and
|
||||
tested Python/Rust/Go/C against it with live-verified sources and frozen kill tests. The
|
||||
pattern is consistent: the compute-shaped work already executes in C (hashlib, sqlite3/FTS5/vec0,
|
||||
json, regex), the dominant latency is network or LLM-bound, and no cluster contains a hot loop
|
||||
that pays for a process-boundary recode through the 658 µs–0.63 ms interop crossing. **Go:
|
||||
REJECTED — does not earn installation this tranche** (D5=0 everywhere; nothing measured or
|
||||
fetch-confirmed earns it; orchestration additionally rejects its design fit; K-GO kill tests
|
||||
frozen per round should the case be revived). **Rust: toolchain-ready, justified nowhere this
|
||||
tranche** — keep as the standing option behind the CI-proven std-only adapter for any future
|
||||
measured hot loop. **C: rejected everywhere scored** (duplicates C already inside SQLite/hashlib;
|
||||
adds an unsafe-memory surface). The rebase volume the tranche hypothesized is real only as a
|
||||
small set of named improvements — see "Wave-plan consequence" below.
|
||||
|
||||
## Rubric dimensions (applied to every candidate language per subsystem)
|
||||
|
||||
| Dimension | Question | Evidence required |
|
||||
|---|---|---|
|
||||
| D1 Workload fit | Does the subsystem's dominant workload (I/O-bound, CPU-bound, FFI, protocol, UI) actually favour this language? | Benchmarks or authoritative docs, live-verified |
|
||||
| D2 Measured gain | What wins, concretely — latency, memory, startup, binary distribution? | Named hot paths from the Wave 0 inventory + numbers |
|
||||
| D3 Interop cost | What does the interop contract (§5) cost to carry for this boundary? | Adapter surface size, ABI/build complexity |
|
||||
| D4 Ecosystem | Do the needed libraries exist and are they maintained? | Live-verified crate/package/module listings |
|
||||
| D5 Toolchain reality | Is the toolchain present (or installable and justified) on this machine and the CI runner? | Runner + local `--version` evidence |
|
||||
| D6 Maintenance continuity | Can the Rune ecosystem's single-maintainer loop sustain code in this language here? | Honest judgement, stated plainly |
|
||||
| D7 Kill test | What is the CHEAPEST disproof of this candidate? | One falsifiable early test, frozen before any recode |
|
||||
|
||||
Scoring: each candidate gets D1–D6 scored 0–2 with one-line evidence each, D7 written regardless.
|
||||
Decision per subsystem: **KEEP-PYTHON** / **RECODE→<language>** — KEEP-PYTHON is the expected default;
|
||||
a RECODE that cannot pass its own kill test reverts to KEEP-PYTHON before implementation.
|
||||
|
||||
---
|
||||
|
||||
## W3 — Memory & persistence (units: memory_store 56 fns, curator 43, warm_router 32, memory_consolidation 20, sleep_time 25, + graph_memory, night_mode, identity_anchors)
|
||||
|
||||
- **Research round actor:** general-2 (COMPLETED 2026-09-29 — artifacts at
|
||||
`research/wave1/memory/`: inward.md, outward/ ×6, outward-sources.md, synthesis.md)
|
||||
- **Intention profile:** JSONL-heavy appends, BM25/FTS ranking, consolidation passes, long-running
|
||||
scheduled jobs, file-backed state.
|
||||
- **Decision:** **KEEP-PYTHON (all 7 clusters, zero RECODE).** Cluster verdicts:
|
||||
(1) hot-store JSON persistence — KEEP with upgrade path: orjson in-process wheel
|
||||
(~10× dumps / 2× loads); a bespoke Rust CLI unit is dead on spawn cost (the
|
||||
`shared/native_units.py` crossing ~1–5 ms ≈ orjson's entire 3.4 MB `knowledge.json` decode);
|
||||
(2) SQLite store + FTS5/vec0 recall — KEEP, the compute is already C inside SQLite
|
||||
(`memory_store.py:646` vec0 MATCH, `:693` bm25); (3) neuron scoring/routing — KEEP,
|
||||
network-bound `_embed` (Ollama subprocess curl) dominates; (4) graph BFS — KEEP,
|
||||
hops=1 default, per-node SQL, tiny N; the future fix is a SQL CTE, not a language;
|
||||
(5) batch consolidation/curator — KEEP, LLM/I-O-bound and latency-insensitive,
|
||||
asyncio sweet spot; (6) orchestration/glue — KEEP, pure glue pinned by the Python-TUI
|
||||
interop contract; (7) embedding transport — KEEP, network-bound.
|
||||
- **Candidate matrix summary:** Python 7/7 · Go 0/7 (not installed, nothing measured or
|
||||
fetch-confirmed earns installation; Go's JSON stack mid-rewrite upstream) · hand-written C
|
||||
0/7 (C already battle-tested inside SQLite — hand-writing would duplicate it) · Rust 0/7
|
||||
as CLI units (spawn cost kills the one credible vector; in-process wheels excluded by
|
||||
Wave 0 policy).
|
||||
- **Kill tests (frozen in synthesis.md):** Rust-JSON — orjson microbench on live 3.4 MB
|
||||
`knowledge.json` (if drop-in and ≥2× load / ≥5× dump, the CLI unit is disproven on spawn
|
||||
cost); Rust-general — kill unless a profile shows ≥50% wall time in pure Python compute
|
||||
(none exists; reopen only on materially changed workload); Go — instrument one
|
||||
`consolidate_all` run, kill if Python-compute share <50% (it will be — LLM/I-O bound);
|
||||
C — kill unless a hot kernel absent from the SQLite extension ecosystem is identified
|
||||
(none).
|
||||
- **Sources + lessons:** 6 live-fetched 2026-09-29 (orjson, sled, sqlite-vec, SQLite FTS5
|
||||
docs, Go json/v2 rewrite issue, pydantic-core) — full annotations in
|
||||
`research/wave1/memory/outward-sources.md`.
|
||||
- **Evidence sufficiency (honest):** static analysis only, no runtime profiling;
|
||||
memory.store SQLite DB not materialized locally — kill tests specify *measured*
|
||||
thresholds rather than assertions. Verdicts rest on "Python is glue around C/network,"
|
||||
which profiling would only strengthen.
|
||||
|
||||
## W4 — Provider/model layer (units: provider_registry 28, model_connect 10, model_routing 15, model_profiles 15, provider_budget 21, + standardized_providers, model_registry, connection_pool)
|
||||
|
||||
- **Research round actor:** general-5 (COMPLETED 2026-09-29 — artifacts at
|
||||
`research/wave1/provider-layer/`: inward.md, outward-sources.md, outward/ (8 evidence
|
||||
JSONs), synthesis.md)
|
||||
- **Intention profile:** HTTP/SSE streaming, connection pooling, retries/backoff, protocol parsing,
|
||||
tool-call reliability.
|
||||
- **Intention profile correction (inward-verified):** the layer has **NO retry/backoff and NO
|
||||
SSE stub at all** (grep-verified) — `stream: False` everywhere, ~900 lines, remote-LLM-latency-
|
||||
bound. Rewrite pitches are therefore feature-adds, not ports.
|
||||
- **Candidate matrix:** 5 clusters, all KEEP-PYTHON. Scores (1–5 = fit for the cluster's actual
|
||||
workload): (C1) HTTP wire + transport (provider_registry, openai_compat_transport, model_connect
|
||||
discovery) Python 5 / Go 2 / Rust 1; (C2) connection pool (connection_pool.py, 144 lines —
|
||||
in-process object guards under threading.Lock, NOT a TCP pool) Python 5 / Go 2 / Rust 2;
|
||||
(C3) routing decisions (model_routing.py, 432 lines, pure decision logic, one httpx call)
|
||||
Python 5 / Go 1 / Rust 1; (C4) budget accounting (provider_budget.py, 354 lines, pure
|
||||
arithmetic + lock, no I/O) Python 5 / Go 1 / Rust 1; (C5) config/registry/normalization
|
||||
(model_profiles, model_registry, standardized_providers, model_connect tables — dataclasses +
|
||||
JSON, editable by non-systems programmers) Python 5 / Go 1 / Rust 1.
|
||||
- **Decision:** **KEEP-PYTHON (all 5 clusters).**
|
||||
- **Kill tests:** C1 Go — KILLED: toolchain absent (`which go` → not found); 28 call-site
|
||||
behaviors incl. the tool-call envelope contract (openai_compat_transport.py:67-107, 160-207)
|
||||
would be re-implemented with zero incumbent test port and NO performance signal (remote-LLM-
|
||||
latency-bound, kilobyte payloads). Re-earn path if Go is ever installed: std-only proof via
|
||||
`interop/rebase-proof/` + a benchmark harness on C1 only. C1 Rust — KILLED BY CONSTRUCTION:
|
||||
SSE parsing requires reqwest+tokio+eventsource-stream+nom (outward O3/O4/O5 — even mistral.rs
|
||||
takes the tokio stack), violating the std-only interop contract. C2–C5 Go/Rust — KILLED:
|
||||
burden of proof sits on the rewrite candidates; kill tests need contention/throughput/
|
||||
counter-evidence that does not exist; routing runs once per request at millisecond scale
|
||||
against multi-second LLM calls (5 orders of magnitude below any measurable threshold).
|
||||
- **Sources + lessons:** 8 live-fetched (O1–O8), ≥2 per major claim, coverage map in
|
||||
`outward-sources.md`. Lessons: (1) stdlib-only Rust has no realistic precedent for HTTP/SSE
|
||||
workloads — the interop contract's zero-crate standard effectively decides Rust out of all
|
||||
network-wire clusters; (2) Go's stdlib HTTP+NDJSON streaming is capability-proven
|
||||
(pkg.go.dev/net/http, ollama api/client.go, ollama's Go API server) — Go's losses here are
|
||||
evidence-absence, not capability-absence; (3) the honest reliability upgrade for this layer
|
||||
is a small Python-level httpx retry/timeout wrapper — a feature-add, not a language change.
|
||||
|
||||
## W5 — Orchestration, authority, plugins, skills (units: orchestration/ 44 files 244 fns, contracts, build_mode 34, construction_authority*, verification_construction, spine, + governance surfaces: drift_*, persona_gate, safety_override, witness, behavior, growth_delta, claim_audit)
|
||||
|
||||
- **Research round actor:** general-1 (COMPLETED 2026-09-29 — artifacts at
|
||||
`research/wave1/orchestration/`: inward.md, outward-sources.md, outward/ (4 search
|
||||
JSONs), synthesis.md)
|
||||
- **Intention profile:** contract/lifecycle state machines, authority gating, fail-closed validation,
|
||||
HMAC-chained ledgers, policy dispatch.
|
||||
- **Intention profile correction (inward-verified):** the subsystem is durable-ledger I/O,
|
||||
authority wiring, deterministic policy gates, and TUI-facing coordination — NOT hot loops
|
||||
(2 RLocks, 0 sockets, 0 thread pools across 43 files). **Scope gap: `construction_authority.py`
|
||||
and `verification_construction.py` do not exist in the tree** — the construction cluster is
|
||||
covered by build_mode.py; no evidence invented for the missing files.
|
||||
- **Candidate matrix:** 6 clusters, all KEEP-PYTHON. Scores (1–5 = fit for the cluster's actual
|
||||
workload): (C1) durable state & ledger stores (event_store.py:56-101, atomic.py, evidence_store.py
|
||||
— fsync-bound; hashing already C via hashlib) Python 5; (C2) composition roots & authority wiring
|
||||
(composition.py, authority.py, cognitive.py — pure glue, runtime cost ≈ 0) Python 5; (C3)
|
||||
policy/state machines/gates (lifecycle.py, scheduler.py, broker.py, no_change.py, reflex.py —
|
||||
deterministic dict/enum decisions, sub-ms; testability is the requirement) Python 5; (C4)
|
||||
structural self-model & schema tooling (spine.py:24-25, microkernel.py, contracts.py, records.py
|
||||
— introspection + canonical JSON; only candidate for a future Rust spine-diff if snapshots grow
|
||||
1000×) Python 4; (C5) TUI-facing orchestration & build pipeline (build_mode.py 11-stage pipeline,
|
||||
gateway.py, transport.py — the consumer IS the Python TUI; latency dominated by LLM/subprocess
|
||||
waits) Python 5; (C6) benchmark/migration harnesses (retrieval_benchmark.py, migrate.py,
|
||||
benchmark.py — offline tooling, recode buys nothing, loses iteration speed) Python 4.
|
||||
- **Decision:** **KEEP-PYTHON (all 6 clusters). This subsystem contributes 0 recode units to
|
||||
the wave plan.** Go: REJECTED, do not install — differentiator (goroutine-dense servers)
|
||||
targets a workload absent here; cost is exception→error-value rewrite of ~260 functions.
|
||||
Rust: FEASIBLE (toolchain proven) but UNJUSTIFIED anywhere — no cluster has the hot loop
|
||||
that pays for a process-boundary recode; keep as toolchain-ready for other subsystems.
|
||||
C: REJECTED — the only compute-shaped work (sha256) already executes C via stdlib hashlib.
|
||||
- **Kill tests:** K1 (frozen, ALREADY RUN): 100 round-trips through the rebase-proof adapter —
|
||||
mean 0.63ms, p95 0.74ms, cold 0.87ms, 100% exit-0 + ok:true → adapter overhead does NOT block
|
||||
recodes on cost; recodes die on value grounds. Re-open any cluster if profiling shows a
|
||||
function consuming >10% of a real interactive session. K-GO (frozen, ~30 min): Go prototype
|
||||
of event_store.py's batched append+fsync vs Python at 1000 events; if Python's p95 is within
|
||||
2× of Go's, Go is dead here permanently. K-RUST (frozen, ~20 min): measure spine diff on a
|
||||
10k-entity snapshot; <50ms kills any Rust spine recode by absence of pain.
|
||||
- **Sources + lessons:** 4 live-fetched web sources (pydantic-core, ruff blog, go.dev FAQ,
|
||||
Python 3.14 hashlib docs) + 1 LOCAL EXPERIMENT (n=100 adapter benchmark). Lessons: (1) the
|
||||
rebase-proof adapter round-trips at 0.63ms/op — subprocess-per-op is viable for coarse ops,
|
||||
never per-event; (2) Python's "slowness" argument dissolves where the actual compute already
|
||||
runs in C via stdlib (hashlib, sqlite) — the language question is really "where is the hot
|
||||
loop", and here the answer is nowhere; (3) assumed limits flagged honestly: human-scale event
|
||||
cadence (batch_size=8) and Linux spawn cost — both would need revisit at 10⁴+ events/sec or
|
||||
cross-platform targets.
|
||||
|
||||
## W6 — Runtime core & tooling (units: tool_executor 46, tool_protocol 27, local_tool_runtime 32, capability_broker 19, context_broker 21, work_manager 25, cron_engine 28, + failure_auto_filer 28, hook_engine, elastic_cognition, auto_tasks, goal)
|
||||
|
||||
- **Research round actor:** general-4 (COMPLETED 2026-09-29 on disk despite cancellation
|
||||
notification — artifacts at `research/wave1/runtime-core/`: inward.md, outward/,
|
||||
outward-sources.md, synthesis.md)
|
||||
- **Intention profile:** subprocess/process supervision, native execution boundary (native_units
|
||||
adapter already exists), event loops, cron scheduling, hook dispatch.
|
||||
- **Decision:** **STAY-PYTHON (all 6 clusters).** Round scores (1–5 = fit for the cluster's
|
||||
actual inward-characterized workload): (A) subprocess lifecycle (tool_executor, cron_engine,
|
||||
auto_tasks) 4.7 — `subprocess.run(timeout=, capture_output=)` is a one-call expression of the
|
||||
pattern; Rust std::process has NO built-in child timeout (outward-verified), strictly more
|
||||
code under zero-crate; (B) protocol/JSON parsing (tool_protocol, brokers) 4.5 — inputs are
|
||||
KB-scale model fragments; Python json/regex is already C-backed, so a rewrite swaps C for
|
||||
compiled code at the same asymptotic cost; serde's typed-struct model actively mismatches
|
||||
fence-wrapped schema-flexible output; (C) model→tool control loop + HTTP
|
||||
(local_tool_runtime, elastic_cognition, goal) 4.8 — wall time is LLM HTTP latency in seconds;
|
||||
Python overhead is µs–ms noise; the loop's content is policy (circuit breaker, escalation
|
||||
ladders, routing tables); (D) context assembly (context_broker) 4.7 — correctness lives in
|
||||
admission policy and degrade-not-crash semantics, not speed; compaction is itself an LLM call;
|
||||
(E) reliability/queueing (failure_auto_filer) 4.2 — honest lowest: on paper the best Rust
|
||||
candidate (queue + worker + crash-safe JSONL spool), but perf requirement ≈ nil and the
|
||||
correctness burden is threading semantics a rewrite would re-risk for no win ("nothing
|
||||
breaks today"); (F) declarative config/brokers (work_manager, hook_engine, capability_broker)
|
||||
4.9 — literal data, no-op runtime, portable to anything valuable in nothing.
|
||||
- **Candidate matrix summary:** Python 6/6 · Go 0/6 (paper verdicts only — evidence-starved,
|
||||
not installed, kill tests unrunnable locally) · Rust 0/6 (kill tests runnable via the
|
||||
existing std-only interop harness) · C unscored (no FFI-adjacent cluster surfaced).
|
||||
Best-language moment found anywhere: robfig/cron replacing ~37 hand-rolled cron-parsing
|
||||
lines (cron_engine.py:199-236) — ergonomics nicety, not a fit verdict.
|
||||
- **Kill tests (frozen in synthesis.md):** Rust-A — re-express `_run_command`
|
||||
(tool_executor.py:1064) with std::process + manual timeout; kill if >2× the ~40-line
|
||||
Python wrapper (Q4 predicts it is); Go-A — port `cron_engine._run_loop` with os/exec,
|
||||
measure task-fire latency delta (prediction: zero — 60 s sleep and child runtime dominate);
|
||||
B — parse the largest observed tool-protocol stream 1000× in Python; kill if total <1 s
|
||||
(no rewrite yields an observable win); C — instrument `_run_loop`
|
||||
(local_tool_runtime.py:417), log non-HTTP CPU per iteration (prediction <1% of wall);
|
||||
D — time `assemble`+`_admit` on the largest stored context, kill if <10 ms; E — fault-inject
|
||||
kill -9 during spool append; if recovery semantics already hold, the rewrite has no
|
||||
correctness win to buy; F — none needed: absence of any win condition IS the disproof.
|
||||
- **Sources + lessons:** live-fetched 2026-09-29 — annotations in
|
||||
`research/wave1/runtime-core/outward-sources.md`; headline lessons: Rust std::process lacks
|
||||
child timeout (Q4); Go os/exec reaches parity but changes only syntax (Q1); Python
|
||||
json/regex C-backed (Q5b); serde typed structs mismatch dynamic model output (Q5a);
|
||||
concurrency features irrelevant at ≤2 threads (Q6).
|
||||
- **Evidence sufficiency:** Python verdicts fully evidenced inward+outward; Go execution-side
|
||||
evidence honestly starved (paper kill tests carried forward); E's JSONL-spool crash-safety
|
||||
claim rests on inward semantics only — flagged in synthesis.md.
|
||||
|
||||
## W7 — Operator + TUI (units: rune_operator 61 fns, rune_tui 161 fns — largest module, tui_validator)
|
||||
|
||||
- **Research round actor:** general-3 (COMPLETED 2026-09-29 — artifacts at
|
||||
`research/wave1/tui/`: inward.md, outward/ ×8, outward-sources.md, synthesis.md)
|
||||
- **Intention profile:** terminal rendering, input handling, rich layout, hot store state, supervisory
|
||||
command surface. Design decision 4 holds: TUI consumes the interop contract, never rewritten first.
|
||||
- **Decision:** **KEEP-PYTHON (TUI shell; all 4 clusters, zero RECODE, no carve-out found).**
|
||||
Cluster scores (1 = recode, 5 = keep): (A) rendering/widgets 4 — no hot loop exists; render is
|
||||
plain Rich `Text` concatenation (rune_tui.py:1331, chat_bubble.py:157), only animation a 0.12 s
|
||||
spinner (:263), no markdown/Syntax parsing anywhere in src/rune; (B) event glue (~50 `_cmd_*`
|
||||
handlers, reactives, tool-widget maps) 5 — this is Textual's core competency (workers,
|
||||
`exclusive=True`, `call_from_thread`); vendor docs (ratatui) admit "little to no help in organizing
|
||||
large applications"; (C) model send path + envelope 5 — synchronous `send_task` in async worker;
|
||||
the envelope shape (`success/response/thinking/tool_events/degraded`, rune_tui.py:3624ff) is
|
||||
ALREADY the de-facto interop contract; (D) subprocess/streaming 5 — JSONL streaming precedent
|
||||
already in-tree (`_cmd_pull` :3443-3517): the pattern for consuming recoded units, not a recode
|
||||
target. Whole-TUI native recode 1/5 REJECTED — 80+ first-party module coupling, framework-provided
|
||||
concurrency re-implemented by hand; Go additionally toolchain-blocked. Countervailing evidence
|
||||
(Bubble Tea/tview/Codex TUI maturity) recorded honestly in outward-sources.md — it does not
|
||||
outweigh the coupling.
|
||||
- **⚠ CONTRACT GAP FLAGGED (binds Waves 2–7):** `shared/native_units.py` parses only the LAST
|
||||
stdout line — it must gain a JSONL streaming reader (per-line `json.loads` + terminal-envelope
|
||||
validation) before any recoded long-running unit can stream progress to the TUI. Small, testable,
|
||||
non-breaking; candidate for the first Wave 2 implementation issue.
|
||||
- **Adapter surface (TUI as consumer — adopted as the rubric's interop-contract restatement):**
|
||||
(1) single-invocation stateless CLI (`native_unit <op> [args]`, no daemon); (2) success = final
|
||||
stdout line `{"ok":true, …}` generalizing the model-send envelope — recoded units emitting
|
||||
`response`/`tool_events`/`degraded` plug in with zero TUI changes; (3) failure = `ok:false` +
|
||||
nonzero exit, stderr human-only, success = exit 0 AND not timed out; (4) mandatory `--version`
|
||||
on every unit (status bar + `canary_tui_drift.py` detect live units vs Python fallback);
|
||||
(5) JSONL streaming mode for long ops with terminal sentinel envelope; (6) per-call timeout
|
||||
budget, `timed_out` surfaced in `NativeResult` for graceful degradation; (7) streamed events
|
||||
referencing UI objects carry the TUI's stable keys — `(channel, call_id)` for tool widgets
|
||||
(:3676), WorkPane `_entries` object ids (:1239) — preserved verbatim; (8) std-only for
|
||||
proof-phase units.
|
||||
- **Candidate matrix summary:** Python 4/4 clusters · Rust/Go whole-TUI 1/5 rejected · carve-out
|
||||
candidates: none found (future markdown parsing would carve as a Rust native unit behind the
|
||||
adapter, not now).
|
||||
- **Kill tests (frozen in synthesis.md):** stay-Python — killed if >16 ms UI-thread stalls under
|
||||
heavy event bursts OR IPC latency dominates message round-trip (Textual pilot measurement);
|
||||
Rust recode — killed if the adapter must expose >~15 first-party modules (count today ≈80:
|
||||
killed NOW); Go recode — additionally killed by toolchain absence (`command -v go` empty).
|
||||
- **Sources + lessons:** 8 live-fetched 2026-09-29 (Textual workers guide, ratatui vendor docs,
|
||||
Bubble Tea/tview/Codex countervailing evidence, JSON Lines spec, push-granular-work guidance) —
|
||||
annotations in `research/wave1/tui/outward-sources.md`.
|
||||
- **Evidence sufficiency (honest):** full inward read of all 5 TUI files with line refs; ≥2 sources
|
||||
per major claim; gap = no runtime profiling (stall kill test unmeasured — but no mechanism exists
|
||||
for the stall to occur; the 120 ms 21-step pipeline was already removed, `_run_warm_router`
|
||||
:3575 is a no-op).
|
||||
|
||||
## W2 — Leaf utilities & canaries (~40 modules, low coupling: pins, time_awareness, message_queue, event_envelope, attention_capsule, complexity_scorer, token_optimizer, cache 501/17, prompt_sync, chat_bubble, ~15 canary_* modules)
|
||||
|
||||
- **Research round actor:** general-6 (COMPLETED 2026-09-29 — full report in actor notification)
|
||||
- **Intention profile:** small pure helpers, envelopes, scoring, cache; smallest blast radius; the
|
||||
factory + interop proving ground at real scale.
|
||||
- **Ground-truth measurements (local, this session):** Python fn call ~46 ns (100k timed
|
||||
iterations in-process) · native CLI roundtrip ~658 µs (subprocess to
|
||||
`interop/rebase-proof/target/release/rebase-proof --version`) · Python startup floor ~18 ms ·
|
||||
overhead ratio ≈ **14,000×**. The only CI-proven interop contract is the subprocess CLI boundary
|
||||
(`shared/native_units.py`: argv in → JSON stdout, `--version`, timeout, typed `NativeResult`).
|
||||
PyO3/in-process bindings excluded by Wave 0 policy. Therefore every per-call crossing costs
|
||||
≥658 µs — a per-turn helper would need to run >14,000× faster in Rust to break even.
|
||||
- **Candidate matrix (representative — full per-cluster 0–2 scoring in round report):**
|
||||
Python 12/12 in every cluster · Rust 5–6/12 · Go 1–3/12 (D5=0, not installed) · C 1–2/12.
|
||||
No module contains a hot loop (heaviest: 2 `re.sub` per turn in token_optimizer).
|
||||
- **Decision:** **KEEP-PYTHON (all ~40, zero RECODE).** Cluster verdicts: (a) pure CRUD helpers
|
||||
pins/time_awareness/token_optimizer — KEEP, CPython 3.11+ already 10–60% faster on this shape
|
||||
(PEP 659); (b) message/envelope/capsule structures — KEEP, recode would insert a boundary
|
||||
between the chattiest neighbors; (c) cache.py (501 L, largest in wave) — KEEP, the fast part is
|
||||
already C (sqlite3 DB-API 2.0 over SQLite's C library), Python is thin orchestration, batching
|
||||
(threshold 50 / 30 s) already amortizes writes; (d) chat_bubble.py — KEEP, **hard-pinned** to
|
||||
Python by the Textual framework (recode = full framework abandonment, bottleneck is human
|
||||
typing speed); (e) prompt_sync.py glue — KEEP, glue into Python siblings (memory_env,
|
||||
voice_sync, build_pipeline_policy); (f) ~19 canary_* — KEEP **categorically**, a canary that
|
||||
verifies Python importability cannot exist in another language.
|
||||
- **Kill tests (reopening criteria, all fail today on first cheap measurement):** Rust — microbench
|
||||
one per-turn helper behind the native_units CLI, must beat the Python in-process call >10×
|
||||
end-to-end including the 658 µs crossing (whole call <~46 µs; a trivial `--version` already
|
||||
costs 658 µs); Go — identical benchmark post-install, uninstall if roundtrip >100 µs with no
|
||||
named hot path; C — identical benchmark + required fuzz-clean JSON roundtrip, plus a
|
||||
demonstrated GC-free allocation-hot loop first; cache.py — recode only if Python-side
|
||||
orchestration (excl. sqlite3 waits) exceeds 5% of end-to-end latency; capsule/envelope/queue —
|
||||
recode only if one turn's Python total exceeds ~5 ms AND a candidate's CLI path is >10× cheaper.
|
||||
- **Sources + lessons:** (1) https://docs.python.org/3/whatsnew/3.11.html — 10–60% faster,
|
||||
PEP 659 specializing interpreter: CPython already optimized for helper-shaped code, the D2
|
||||
baseline is a moving improving target; (2) https://docs.python.org/3/whatsnew/3.13.html —
|
||||
free-threading/JIT experimental, KEEP-PYTHON ≠ frozen but no bets on experimental paths;
|
||||
(3) https://www.maturin.rs/ — in-process Rust↔Python needs a whole binding/packaging toolchain
|
||||
atop the CLI boundary, D3 worse than measured 658 µs (Wave 0 policy excludes it anyway);
|
||||
(4) https://go.dev/doc/install — Go is a pre-install prerequisite, D5=0 everywhere, never earned
|
||||
installation; (5) https://textual.textualize.io/ — Textual is a Python TUI framework,
|
||||
chat_bubble.py framework-pinned; (6) https://docs.python.org/3/library/sqlite3.html — sqlite3 is
|
||||
DB-API 2.0 over C, cache.py's perf layer already native. All fetched live 2026-09-29.
|
||||
- **⚠ Inventory drift (VERIFIED 2026-09-29):** complexity_scorer.py listed in
|
||||
rebase-inventory.json (2 mentions) but absent on disk — deleted in commit 867321e
|
||||
("governed retirement — complexity_scorer deleted (602 lines)"). Wave 0 inventory needs a
|
||||
correction pass; the module was scored nowhere (no source to characterize).
|
||||
|
||||
---
|
||||
|
||||
## Wave-plan consequence (T5 scope, from the verdict above)
|
||||
|
||||
With **0 recode units awarded**, the tranche's hypothesized rebase volume is real only as the
|
||||
work below. Waves 2–9 are **disposition + named improvements, NOT mass recoding**:
|
||||
|
||||
**Waves 2–7 — per-issue disposition (the 1,852 `[rebase w{wave}]` issues):**
|
||||
Each issue receives its tranche §7 disposition — improve / fix / missing-connectors answered
|
||||
with evidence — plus a language verdict of **KEEP-PYTHON with its rubric evidence line**
|
||||
(the round section for that subsystem names the claim). Disposition runs leaf-first
|
||||
(Wave 2 → 7), the canonical suite stays green throughout, and no issue closes without its
|
||||
evidence line. A recode is off the table unless a frozen kill test is reopened — and then
|
||||
tranche §6 still governs: **no benchmark win, no recode.** Go is not installed and earned no
|
||||
installation; Rust stays toolchain-ready but unjustified (standing option behind the
|
||||
CI-proven adapter).
|
||||
|
||||
**Named improvements — the actual rebase volume (ship alongside disposition):**
|
||||
1. **JSONL streaming reader for `shared/native_units.py`** (W7 contract gap): the adapter
|
||||
parses only the LAST stdout line; it must gain per-line `json.loads` + terminal-envelope
|
||||
validation before any recoded long-running unit could stream progress. Small, testable,
|
||||
non-breaking — first implementation issue of Wave 2.
|
||||
2. **httpx retry/timeout wrapper for the provider layer** (W4): the honest reliability
|
||||
upgrade is a feature-add, not a language change.
|
||||
3. **orjson upgrade path** (W3 cluster 1): the only credible Python-side JSON win —
|
||||
in-process, no boundary crossing. **DISPOSITION (2026-09-29, kill test EXECUTED and
|
||||
FAILED — KEEP-PYTHON stands, no dependency declared):** microbench on the live
|
||||
`~/.rune/consolidation/knowledge.json` (3,540,959 bytes, n=30 best-of): load 13.15 ms
|
||||
std vs 7.85 ms orjson = **1.68× (bar ≥2×: FAIL)**; dump 9.58 ms std vs 5.61 ms
|
||||
orjson-with-decode = **1.71× (bar ≥5×: FAIL)**; raw-bytes dump 1.39 ms = 6.91× but is
|
||||
not drop-in (every `write_text`/`json.dump`-to-file site would need a bytes→str or
|
||||
binary-write conversion). Roundtrip equality verified. Bench: `/tmp/orjson_bench.py`
|
||||
shape (uvx --with orjson). The bytes trap measured real: decode() eats ~60% of the
|
||||
dump win.
|
||||
4. **complexity_scorer.py inventory correction**: listed in `rebase-inventory.json` but
|
||||
deleted on disk (commit `867321e`, 602 lines) — Wave 0 inventory needs the correction
|
||||
pass. **DISPOSITION (2026-09-29, DONE):** inventory regenerated per the script's own
|
||||
header (never hand-edit) — 177→213 files, 1,852→2,314 functions, 13 dead files
|
||||
dropped; committed + pushed `5bc837c`. The W2 round's "2 mentions" drift claim
|
||||
verified FALSE against the live inventory (zero hits).
|
||||
5. **robfig/cron** (W6): recorded as a best-language footnote only; no action.
|
||||
|
||||
**Wave 8 — TUI integration proof:** demonstrate the TUI reading/utilising the mixed-language
|
||||
surfaces that exist (the `interop/rebase-proof` unit through the upgraded adapter), per the
|
||||
8-point adapter surface adopted above.
|
||||
**Wave 9 — close-out audit:** 100% of the 1,852 issues dispositioned, debt-table revision,
|
||||
version bump.
|
||||
|
||||
## Cross-cutting candidates (evaluated once, referenced by every subsystem)
|
||||
|
||||
- **Rust (present, 1.98.1):** interop proof unit already CI-proven (std-only, zero crates, `interop/rebase-proof/`, adapter in `shared/native_units.py`, ok = exit 0 AND not timed out).
|
||||
- **Go (absent):** must earn installation through D1–D5 evidence here before any recode targets it.
|
||||
- **C (present, GCC 16.2.1):** expected to lose D6 in most subsystems; scored where FFI-adjacent work exists.
|
||||
- **Python (KEEP baseline):** the default. Every subsystem begins here; evidence must move it.
|
||||
|
||||
## Evidence ledger (per-source lessons, all rounds)
|
||||
|
||||
Index of per-source evidence. Full annotations live in each round's
|
||||
`research/wave1/<subsystem>/outward-sources.md`; this ledger records the headline lesson
|
||||
each source contributed and the rubric claims it supports.
|
||||
|
||||
| Round | Sources (live-fetched 2026-09-29) | Headline lessons | Supports |
|
||||
|---|---|---|---|
|
||||
| W2 leaf utilities | 6: python.org 3.11 + 3.13 whatsnew, maturin.rs, go.dev/doc/install, textual.textualize.io, docs.python.org sqlite3 | CPython 3.11+ already 10–60% faster on helper-shaped code (PEP 659) — D2 baseline is a moving target; free-threading/JIT experimental, no bets; in-process bindings need a whole toolchain atop the CLI boundary (excluded by Wave 0 policy anyway); Go is pre-install prerequisite, D5=0; Textual framework-pins chat_bubble.py; sqlite3 perf layer already C | W2 KEEP-PYTHON ×~40; the 14,000× crossing-overhead law |
|
||||
| W3 memory | 6: orjson, sled, sqlite-vec, SQLite FTS5 docs, Go json/v2 rewrite issue, pydantic-core | orjson is the only credible Python-side JSON win (in-process, no boundary); SQLite FTS5/vec0 compute is already C; Go's JSON stack mid-rewrite upstream (versioning risk); pydantic-core shows the Rust-as-wheel pattern, excluded by policy | W3 KEEP-PYTHON 7/7; orjson upgrade path on cluster 1 |
|
||||
| W4 provider-layer | 8: live-fetched O1–O8 (HTTP/SSE ecosystem, tokio-stack precedents incl. mistral.rs, pkg.go.dev/net/http, ollama Go client/server) | stdlib-only Rust has no realistic HTTP/SSE precedent — the zero-crate contract decides Rust out of all network-wire clusters by construction; Go's stdlib HTTP+NDJSON streaming is capability-proven (its losses here are evidence-absence, not capability-absence); the honest reliability upgrade is a Python httpx retry/timeout wrapper — feature-add, not language change | W4 KEEP-PYTHON 5/5; SSE-cluster Rust kill-by-construction |
|
||||
| W5 orchestration | 4: pydantic-core, ruff blog, go.dev FAQ, Python 3.14 hashlib docs + 1 LOCAL EXPERIMENT (n=100 adapter benchmark) | adapter round-trips at 0.63ms/op — subprocess-per-op viable for coarse ops, never per-event; Python "slowness" dissolves where compute already runs in C via stdlib; the language question is really "where is the hot loop" (here: nowhere) | W5 KEEP-PYTHON 6/6; K1 kill test already run |
|
||||
| W6 runtime-core | headline lessons (full set in round outward-sources.md) | Rust std::process lacks built-in child timeout — strictly more code under zero-crate; Go os/exec reaches parity but changes only syntax; Python json/regex C-backed so rewrite swaps C for compiled code at equal asymptotic cost; serde typed structs mismatch schema-flexible model output; concurrency features irrelevant at ≤2 threads | W6 STAY-PYTHON 6/6; robfig/cron as best-language footnote |
|
||||
| W7 TUI | 8: Textual workers guide, ratatui vendor docs, Bubble Tea/tview/Codex TUI (countervailing), JSON Lines spec, push-granular-work guidance | Textual workers/`call_from_thread` are the core competency for event glue; ratatui admits "little to no help in organizing large applications"; countervailing native-TUI frameworks recorded honestly — do not outweigh 80+ module coupling; JSONL per-line parse + terminal sentinel is the streaming contract; vendor guidance: push granular speed-sensitive work to subcomponents only when measured | W7 KEEP-PYTHON 4/4; the 8-point adapter surface (adopted as the rubric's interop-contract restatement) |
|
||||
@@ -1,50 +0,0 @@
|
||||
# Wave 0 close-out report — language-rebasing tranche R1
|
||||
|
||||
Branch: `tranche-r1-wave-0` · Date: 2026-09-29
|
||||
|
||||
## 1. Inventory (docs/rebase/rebase-inventory.json)
|
||||
|
||||
- 177 Python modules, ~52,750 lines, 227 classes
|
||||
- TRUE unit count: **1,852 = 1,030 top-level functions + 822 class methods**
|
||||
- Zero duplicate call edges, zero method leaks (generator double-walk defect
|
||||
root-caused and fixed in scripts/rebase_inventory.py)
|
||||
- Cross-verified against an independent fresh AST walk: zero missing units;
|
||||
six inventory-"extras" are real nested/if-try-block classes the naive walk
|
||||
misses (inventory is MORE complete, not less)
|
||||
|
||||
## 2. Issue factory (scripts/rebase_issue_factory.py)
|
||||
|
||||
- One issue per unit following R1 §7; wave-batched (2–7); dedup-safe via
|
||||
deterministic title `[rebase w{wave}] {relpath}::{unit}` + existing-titles
|
||||
scan per run (retries never duplicate — preserve-first)
|
||||
- `plan` → {2: 239, 3: 251, 4: 129, 5: 544, 6: 415, 7: 274} = 1,852,
|
||||
zero unassigned
|
||||
- `sample --wave 5` → full §7 template holds; `_compute_hash` exactly once as
|
||||
labelled callee with line number
|
||||
- Contract fix during Wave 0: `--limit` default changed 5 → 0 (unlimited) for
|
||||
`create`; `sample` keeps its 5. A full-wave create with the old default
|
||||
would have silently truncated each wave to five issues.
|
||||
|
||||
## 3. Interop proof unit (R1 §5)
|
||||
|
||||
- Rust unit at interop/rebase-proof/ (std-only, zero crates): argv in → JSON
|
||||
on stdout, non-zero exit on failure, mandatory `--version`
|
||||
- Shell-proven: version flag, JSON out, exit 2 on failure, stderr diagnostic
|
||||
- Python thin adapter shared/native_units.py: typed NativeResult, timeout +
|
||||
stderr capture, unit failures as data (never exceptions)
|
||||
- Adapter contract fix during Wave 0: `ok` no longer requires a JSON
|
||||
`ok:true` field — plain-text output (`--version`) succeeds on exit code
|
||||
- tests/test_native_interop_proof.py: **8 passed** — version contract, sum
|
||||
happy path, hash determinism, failure paths, timeout, stderr capture
|
||||
|
||||
## 4. Per-wave issue creation
|
||||
|
||||
<!-- FILLED BY THE COMPLETION LOOP — do not hand-edit -->
|
||||
|
||||
- Wave 4 (129 units): created=127 skipped(dedup)=2 (includes smoke #417–418)
|
||||
- Wave 2 (239 units): created=239 skipped(dedup)=0
|
||||
- Wave 3 (251 units): created=251 skipped(dedup)=0
|
||||
- Wave 5 (544 units): created=544 skipped(dedup)=0
|
||||
- Wave 6 (415 units): created=415 skipped(dedup)=0
|
||||
- Wave 7 (274 units): created=274 skipped(dedup)=0
|
||||
- TOTAL: 1,850 created + 2 dedup = 1,852 / 1,852 ✅ full coverage
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"units_per_wave": {
|
||||
"2": 239,
|
||||
"3": 251,
|
||||
"4": 129,
|
||||
"5": 544,
|
||||
"6": 415,
|
||||
"7": 274
|
||||
},
|
||||
"unassigned_modules": {},
|
||||
"unassigned_module_count": 0
|
||||
}
|
||||
@@ -10,7 +10,6 @@ new surface._
|
||||
| `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) |
|
||||
| `tui_backlog.py` | Not a surface — the durable TUI Upgrade Backlog ledger (outstanding projection/control work per backend feature) | SCAFFOLD-TRANCHE-007; ledger only, never structural authority |
|
||||
| `tui_transport.py` | Not a surface — the transport seam for the TUI's operator calls (in-process default / /v1 wire opt-in) | H4 slice 1 (contract BUILDER-2026-10-04T10:32:00Z-cli); RUNE_TUI_TRANSPORT selects; coverage: canary_tui_transport.py |
|
||||
|
||||
## Adding a TUI surface
|
||||
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
1.27.1
|
||||
+2
-39
@@ -1,31 +1,7 @@
|
||||
settings:
|
||||
warn_about_similar_files:
|
||||
above: 0.85
|
||||
ignore: ["docs/review-lessons.yaml", "docs/v1/**", "docs/wiki/**", "store/spine/**",
|
||||
# shared/ is the DEPLOYED-VINTAGE mirror tree (strangler era):
|
||||
# every src/rune <-> shared similarity here is intentional
|
||||
# (the shim delegates to the crate; the mirror is the deployed
|
||||
# vintage it strangles). Registering the deliberate pairs.
|
||||
"shared/**",
|
||||
"src/rune/drift_core.py", "src/rune/drift_compression.py",
|
||||
"src/rune/drift_observability.py", "src/rune/shard_manager.py",
|
||||
"src/rune/subconscious_pass.py",
|
||||
# deliberate mirror pairs outside the strangler set:
|
||||
# issue templates are mirrored into shared/issue_templates;
|
||||
# completion_file.py is the bridge/daemon mirror of scripts/;
|
||||
# interop/rebase-proof is a committed proof fixture.
|
||||
".gitea/ISSUE_TEMPLATE/**", "shared/issue_templates/**",
|
||||
"bridge/daemon/completion_file.py", "scripts/completion_file.py",
|
||||
"interop/rebase-proof/**",
|
||||
# per-crate copies by zero-dep design: each crate is
|
||||
# self-contained (no shared crate dependency), so the pyjson
|
||||
# JSON module is copied verbatim per crate and the tiny
|
||||
# zero-dep lockfiles are near-identical by construction.
|
||||
"src/rust/*/Cargo.lock", "src/rust/*/src/pyjson.rs",
|
||||
"src/rust/query_memory/src/json_min.rs",
|
||||
# store/scaffold is data (proof fixtures, gate objects),
|
||||
# same class as the already-ignored store/spine.
|
||||
"store/scaffold/**"]
|
||||
ignore: ["docs/review-lessons.yaml", "docs/v1/**", "docs/wiki/**", "store/spine/**"]
|
||||
|
||||
henxels:
|
||||
- henxel: "Canaries live at the repo's canary slot and are registered in CI"
|
||||
@@ -44,7 +20,7 @@ henxels:
|
||||
- henxel: "Top-level docs are markdown or yaml references"
|
||||
in: ./docs/*
|
||||
allowed_filetypes: [.md, .yaml]
|
||||
except: ["./docs/v1/**", "./docs/wiki/**", "./docs/gitea_issue_reconciliation.json", "./docs/rebase/**"]
|
||||
except: ["./docs/v1/**", "./docs/wiki/**", "./docs/gitea_issue_reconciliation.json"]
|
||||
|
||||
- henxel: "The known giant stays visible — file-size debt is tracked, not silent"
|
||||
in: ./src/rune/*
|
||||
@@ -94,19 +70,6 @@ henxels:
|
||||
in: ./src/rune/*.py
|
||||
new_rune_modules_have_canary_or_test_coverage: true
|
||||
|
||||
- henxel: "Rust crate files stay under a line budget"
|
||||
in: ./src/rust/*/src/*.rs
|
||||
except: ["./src/rust/*/src/pyjson.rs", "./src/rust/*/src/json_min.rs"]
|
||||
max_lines: 3000
|
||||
|
||||
- henxel: "Go modules stay under a line budget"
|
||||
in: ./src/go/**/*.go
|
||||
max_lines: 2000
|
||||
|
||||
- henxel: "No secrets in Rust or Go source files"
|
||||
in: [./src/rust/*/src/*.rs, ./src/go/**/*.go]
|
||||
no_secrets: true
|
||||
|
||||
|
||||
- henxel: "PRDs are living documents — their generated state sections regenerate identically from governed sources"
|
||||
changed_with:
|
||||
|
||||
Generated
-7
@@ -1,7 +0,0 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "rebase-proof"
|
||||
version = "0.1.0"
|
||||
@@ -1,15 +0,0 @@
|
||||
[package]
|
||||
name = "rebase-proof"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# Wave 0 interop proof unit (R1 §5). Std-only by design: no crates, no network,
|
||||
# deterministic build. The pattern under proof is the CLI boundary itself, not the
|
||||
# computation inside it.
|
||||
|
||||
[[bin]]
|
||||
name = "rebase-proof"
|
||||
path = "src/main.rs"
|
||||
|
||||
[profile.release]
|
||||
strip = true
|
||||
@@ -1,117 +0,0 @@
|
||||
//! Wave 0 interop proof unit (R1 §5 of the language-rebasing tranche).
|
||||
//!
|
||||
//! Contract under proof:
|
||||
//! - standalone binary; argv in, JSON on stdout
|
||||
//! - non-zero exit on failure (JSON error object still printed to stdout)
|
||||
//! - `--version` flag mandatory
|
||||
//! - Python wraps it in a thin adapter (`shared/native_units.py`); tests call
|
||||
//! it the same way.
|
||||
//!
|
||||
//! Ops: sum / echo / hash (fnv1a64) / sleep / fail. All std-only.
|
||||
|
||||
use std::env;
|
||||
use std::process::exit;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
/// FNV-1a 64-bit — dependency-free deterministic hash for the proof unit.
|
||||
fn fnv1a64(data: &[u8]) -> u64 {
|
||||
let mut hash: u64 = 0xcbf29ce484222325;
|
||||
for byte in data {
|
||||
hash ^= u64::from(*byte);
|
||||
hash = hash.wrapping_mul(0x100000001b3);
|
||||
}
|
||||
hash
|
||||
}
|
||||
|
||||
fn print_json(line: &str) {
|
||||
println!("{line}");
|
||||
}
|
||||
|
||||
fn emit_ok(body: &str) {
|
||||
print_json(&format!("{{\"ok\":true,{body}}}"));
|
||||
exit(0);
|
||||
}
|
||||
|
||||
fn emit_err(message: &str) -> ! {
|
||||
// Escape the minimal set so the JSON stays parseable for arbitrary op names.
|
||||
let escaped: String = message
|
||||
.chars()
|
||||
.map(|c| match c {
|
||||
'"' => "\\\"".to_string(),
|
||||
'\\' => "\\\\".to_string(),
|
||||
'\n' => "\\n".to_string(),
|
||||
'\r' => "\\r".to_string(),
|
||||
'\t' => "\\t".to_string(),
|
||||
other => other.to_string(),
|
||||
})
|
||||
.collect();
|
||||
print_json(&format!("{{\"ok\":false,\"error\":\"{escaped}\"}}"));
|
||||
exit(2);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = env::args().skip(1).collect();
|
||||
|
||||
if args.as_slice() == ["--version"] || args.as_slice() == ["-V"] {
|
||||
println!("rebase-proof {VERSION}");
|
||||
exit(0);
|
||||
}
|
||||
if args.is_empty() {
|
||||
eprintln!("usage: rebase-proof <op> [args...] | --version");
|
||||
emit_err("no op given");
|
||||
}
|
||||
|
||||
let op = args[0].as_str();
|
||||
let rest = &args[1..];
|
||||
|
||||
match op {
|
||||
"sum" => {
|
||||
let mut total: i128 = 0;
|
||||
for a in rest {
|
||||
match a.parse::<i128>() {
|
||||
Ok(v) => total += v,
|
||||
Err(_) => emit_err(&format!("sum: not an integer: {a}")),
|
||||
}
|
||||
}
|
||||
emit_ok(&format!("\"op\":\"sum\",\"result\":{total}"));
|
||||
}
|
||||
"echo" => {
|
||||
let joined = rest.join(" ");
|
||||
let escaped: String = joined
|
||||
.chars()
|
||||
.map(|c| match c {
|
||||
'"' => "\\\"".to_string(),
|
||||
'\\' => "\\\\".to_string(),
|
||||
'\n' => "\\n".to_string(),
|
||||
'\r' => "\\r".to_string(),
|
||||
'\t' => "\\t".to_string(),
|
||||
other => other.to_string(),
|
||||
})
|
||||
.collect();
|
||||
emit_ok(&format!("\"op\":\"echo\",\"text\":\"{escaped}\""));
|
||||
}
|
||||
"hash" => {
|
||||
let joined = rest.join(" ");
|
||||
let h = fnv1a64(joined.as_bytes());
|
||||
emit_ok(&format!("\"op\":\"hash\",\"fnv1a64\":\"{h:016x}\""));
|
||||
}
|
||||
"sleep" => {
|
||||
let ms: u64 = match rest.first().map(|s| s.parse::<u64>()) {
|
||||
Some(Ok(v)) => v,
|
||||
_ => emit_err("sleep: expected milliseconds"),
|
||||
};
|
||||
thread::sleep(Duration::from_millis(ms));
|
||||
emit_ok(&format!("\"op\":\"sleep\",\"slept_ms\":{ms}"));
|
||||
}
|
||||
"fail" => {
|
||||
// Deliberate failure: stderr diagnostic + JSON error + exit 2.
|
||||
// Proves stderr capture and non-zero exit in the adapter.
|
||||
eprintln!("rebase-proof: deliberate failure for adapter proof");
|
||||
emit_err("deliberate failure");
|
||||
}
|
||||
other => emit_err(&format!("unknown op: {other}")),
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
{
|
||||
"BLE001": 345,
|
||||
"BLE001": 347,
|
||||
"S110": 75
|
||||
}
|
||||
@@ -1,401 +1 @@
|
||||
[
|
||||
{
|
||||
"name": "read_file",
|
||||
"description": "Read a file with optional windowed viewing (offset/limit). Returns numbered lines. Use offset/limit for large files (100 lines at a time).",
|
||||
"capabilities": [
|
||||
"read_file"
|
||||
],
|
||||
"file": "tool_executor.py",
|
||||
"full_path": "",
|
||||
"priority": 100,
|
||||
"semantic_examples": [],
|
||||
"risk": "read-only",
|
||||
"preconditions": [
|
||||
"path exists and is a readable file"
|
||||
],
|
||||
"side_effects": [],
|
||||
"auto_invoked": false,
|
||||
"hooks": [],
|
||||
"native_tool": true,
|
||||
"searchable_text": "read_file read a file with optional windowed viewing (offset/limit). returns numbered lines. use offset/limit for large files (100 lines at a time). native tool"
|
||||
},
|
||||
{
|
||||
"name": "edit_file",
|
||||
"description": "Surgical search/replace edit. More reliable than full file rewrites. The search string must match exactly.",
|
||||
"capabilities": [
|
||||
"edit_file"
|
||||
],
|
||||
"file": "tool_executor.py",
|
||||
"full_path": "",
|
||||
"priority": 100,
|
||||
"semantic_examples": [],
|
||||
"risk": "write",
|
||||
"preconditions": [
|
||||
"path is inside an allowed write directory",
|
||||
"search string matches exactly once"
|
||||
],
|
||||
"side_effects": [
|
||||
"rewrites the target file atomically after approval",
|
||||
"creates a .bak backup under ~/.rune/undo"
|
||||
],
|
||||
"auto_invoked": false,
|
||||
"hooks": [],
|
||||
"native_tool": true,
|
||||
"searchable_text": "edit_file surgical search/replace edit. more reliable than full file rewrites. the search string must match exactly. native tool"
|
||||
},
|
||||
{
|
||||
"name": "write_file",
|
||||
"description": "Write content to a file. Creates parent directories if needed. Shows diff before writing. Use for new files or full rewrites.",
|
||||
"capabilities": [
|
||||
"write_file"
|
||||
],
|
||||
"file": "tool_executor.py",
|
||||
"full_path": "",
|
||||
"priority": 100,
|
||||
"semantic_examples": [],
|
||||
"risk": "write",
|
||||
"preconditions": [
|
||||
"path is inside an allowed write directory"
|
||||
],
|
||||
"side_effects": [
|
||||
"writes the full file content atomically after approval",
|
||||
"creates a .bak backup under ~/.rune/undo"
|
||||
],
|
||||
"auto_invoked": false,
|
||||
"hooks": [],
|
||||
"native_tool": true,
|
||||
"searchable_text": "write_file write content to a file. creates parent directories if needed. shows diff before writing. use for new files or full rewrites. native tool"
|
||||
},
|
||||
{
|
||||
"name": "glob_files",
|
||||
"description": "Find files matching a glob pattern. Returns file paths sorted by modification time.",
|
||||
"capabilities": [
|
||||
"glob_files"
|
||||
],
|
||||
"file": "tool_executor.py",
|
||||
"full_path": "",
|
||||
"priority": 100,
|
||||
"semantic_examples": [],
|
||||
"risk": "read-only",
|
||||
"preconditions": [
|
||||
"search directory is readable"
|
||||
],
|
||||
"side_effects": [],
|
||||
"auto_invoked": false,
|
||||
"hooks": [],
|
||||
"native_tool": true,
|
||||
"searchable_text": "glob_files find files matching a glob pattern. returns file paths sorted by modification time. native tool"
|
||||
},
|
||||
{
|
||||
"name": "grep_files",
|
||||
"description": "Search for a pattern in files. Returns file paths and line numbers. Use include to filter by file type.",
|
||||
"capabilities": [
|
||||
"grep_files"
|
||||
],
|
||||
"file": "tool_executor.py",
|
||||
"full_path": "",
|
||||
"priority": 100,
|
||||
"semantic_examples": [],
|
||||
"risk": "read-only",
|
||||
"preconditions": [
|
||||
"search directory is readable"
|
||||
],
|
||||
"side_effects": [],
|
||||
"auto_invoked": false,
|
||||
"hooks": [],
|
||||
"native_tool": true,
|
||||
"searchable_text": "grep_files search for a pattern in files. returns file paths and line numbers. use include to filter by file type. native tool"
|
||||
},
|
||||
{
|
||||
"name": "list_directory",
|
||||
"description": "List files and directories at a path. Returns names with / suffix for directories.",
|
||||
"capabilities": [
|
||||
"list_directory"
|
||||
],
|
||||
"file": "tool_executor.py",
|
||||
"full_path": "",
|
||||
"priority": 100,
|
||||
"semantic_examples": [],
|
||||
"risk": "read-only",
|
||||
"preconditions": [
|
||||
"path is a readable directory"
|
||||
],
|
||||
"side_effects": [],
|
||||
"auto_invoked": false,
|
||||
"hooks": [],
|
||||
"native_tool": true,
|
||||
"searchable_text": "list_directory list files and directories at a path. returns names with / suffix for directories. native tool"
|
||||
},
|
||||
{
|
||||
"name": "lint_file",
|
||||
"description": "Lint a file for syntax errors and style issues. Blocks bad edits. Supports Python (ruff), JS/TS (eslint), Go (golangci-lint), and more.",
|
||||
"capabilities": [
|
||||
"lint_file"
|
||||
],
|
||||
"file": "tool_executor.py",
|
||||
"full_path": "",
|
||||
"priority": 100,
|
||||
"semantic_examples": [],
|
||||
"risk": "read-only",
|
||||
"preconditions": [
|
||||
"file exists",
|
||||
"a linter is configured for the language"
|
||||
],
|
||||
"side_effects": [],
|
||||
"auto_invoked": false,
|
||||
"hooks": [],
|
||||
"native_tool": true,
|
||||
"searchable_text": "lint_file lint a file for syntax errors and style issues. blocks bad edits. supports python (ruff), js/ts (eslint), go (golangci-lint), and more. native tool"
|
||||
},
|
||||
{
|
||||
"name": "run_tests",
|
||||
"description": "Run tests for a file or project. Auto-detects test runner from language.",
|
||||
"capabilities": [
|
||||
"run_tests"
|
||||
],
|
||||
"file": "tool_executor.py",
|
||||
"full_path": "",
|
||||
"priority": 100,
|
||||
"semantic_examples": [],
|
||||
"risk": "write",
|
||||
"preconditions": [
|
||||
"a test runner is configured for the project"
|
||||
],
|
||||
"side_effects": [
|
||||
"runs project test commands which may create or delete files"
|
||||
],
|
||||
"auto_invoked": false,
|
||||
"hooks": [],
|
||||
"native_tool": true,
|
||||
"searchable_text": "run_tests run tests for a file or project. auto-detects test runner from language. native tool"
|
||||
},
|
||||
{
|
||||
"name": "format_code",
|
||||
"description": "Auto-format code files. Supports Python (black/ruff), JS/TS (prettier), Go (gofmt), and more.",
|
||||
"capabilities": [
|
||||
"format_code"
|
||||
],
|
||||
"file": "tool_executor.py",
|
||||
"full_path": "",
|
||||
"priority": 100,
|
||||
"semantic_examples": [],
|
||||
"risk": "write",
|
||||
"preconditions": [
|
||||
"path is inside an allowed write directory",
|
||||
"a formatter is configured for the language"
|
||||
],
|
||||
"side_effects": [
|
||||
"rewrites files in place to the formatter's style"
|
||||
],
|
||||
"auto_invoked": false,
|
||||
"hooks": [],
|
||||
"native_tool": true,
|
||||
"searchable_text": "format_code auto-format code files. supports python (black/ruff), js/ts (prettier), go (gofmt), and more. native tool"
|
||||
},
|
||||
{
|
||||
"name": "git_diff",
|
||||
"description": "Show git diff for staged or unstaged changes.",
|
||||
"capabilities": [
|
||||
"git_diff"
|
||||
],
|
||||
"file": "tool_executor.py",
|
||||
"full_path": "",
|
||||
"priority": 100,
|
||||
"semantic_examples": [],
|
||||
"risk": "read-only",
|
||||
"preconditions": [
|
||||
"working directory is a git repository"
|
||||
],
|
||||
"side_effects": [],
|
||||
"auto_invoked": false,
|
||||
"hooks": [],
|
||||
"native_tool": true,
|
||||
"searchable_text": "git_diff show git diff for staged or unstaged changes. native tool"
|
||||
},
|
||||
{
|
||||
"name": "git_log",
|
||||
"description": "Show recent git commits.",
|
||||
"capabilities": [
|
||||
"git_log"
|
||||
],
|
||||
"file": "tool_executor.py",
|
||||
"full_path": "",
|
||||
"priority": 100,
|
||||
"semantic_examples": [],
|
||||
"risk": "read-only",
|
||||
"preconditions": [
|
||||
"working directory is a git repository"
|
||||
],
|
||||
"side_effects": [],
|
||||
"auto_invoked": false,
|
||||
"hooks": [],
|
||||
"native_tool": true,
|
||||
"searchable_text": "git_log show recent git commits. native tool"
|
||||
},
|
||||
{
|
||||
"name": "git_commit",
|
||||
"description": "Commit changes with a message. Auto-stages modified files.",
|
||||
"capabilities": [
|
||||
"git_commit"
|
||||
],
|
||||
"file": "tool_executor.py",
|
||||
"full_path": "",
|
||||
"priority": 100,
|
||||
"semantic_examples": [],
|
||||
"risk": "irreversible",
|
||||
"preconditions": [
|
||||
"working directory is a git repository",
|
||||
"there are changes to commit"
|
||||
],
|
||||
"side_effects": [
|
||||
"creates a commit on the current branch"
|
||||
],
|
||||
"auto_invoked": false,
|
||||
"hooks": [],
|
||||
"native_tool": true,
|
||||
"searchable_text": "git_commit commit changes with a message. auto-stages modified files. native tool"
|
||||
},
|
||||
{
|
||||
"name": "repo_map",
|
||||
"description": "Generate an AST-based codebase map showing key symbols (classes, functions, imports). Uses tree-sitter for 100+ languages.",
|
||||
"capabilities": [
|
||||
"repo_map"
|
||||
],
|
||||
"file": "tool_executor.py",
|
||||
"full_path": "",
|
||||
"priority": 100,
|
||||
"semantic_examples": [],
|
||||
"risk": "read-only",
|
||||
"preconditions": [
|
||||
"target directory is readable"
|
||||
],
|
||||
"side_effects": [],
|
||||
"auto_invoked": false,
|
||||
"hooks": [],
|
||||
"native_tool": true,
|
||||
"searchable_text": "repo_map generate an ast-based codebase map showing key symbols (classes, functions, imports). uses tree-sitter for 100+ languages. native tool"
|
||||
},
|
||||
{
|
||||
"name": "run_command",
|
||||
"description": "Run an approved command. Prefer argv (shell=False); shell syntax requires shell=true and explicit user approval.",
|
||||
"capabilities": [
|
||||
"run_command"
|
||||
],
|
||||
"file": "tool_executor.py",
|
||||
"full_path": "",
|
||||
"priority": 100,
|
||||
"semantic_examples": [],
|
||||
"risk": "irreversible",
|
||||
"preconditions": [
|
||||
"operator approves the command",
|
||||
"required binaries are on PATH"
|
||||
],
|
||||
"side_effects": [
|
||||
"executes arbitrary commands with their full side effects"
|
||||
],
|
||||
"auto_invoked": false,
|
||||
"hooks": [],
|
||||
"native_tool": true,
|
||||
"searchable_text": "run_command run an approved command. prefer argv (shell=false); shell syntax requires shell=true and explicit user approval. native tool"
|
||||
},
|
||||
{
|
||||
"name": "read_persona",
|
||||
"description": "Read Rune's persona definition. Returns the full persona block with voice, identity, and rules.",
|
||||
"capabilities": [
|
||||
"read_persona"
|
||||
],
|
||||
"file": "tool_executor.py",
|
||||
"full_path": "",
|
||||
"priority": 100,
|
||||
"semantic_examples": [],
|
||||
"risk": "read-only",
|
||||
"preconditions": [
|
||||
"persona MEMORY.md exists"
|
||||
],
|
||||
"side_effects": [],
|
||||
"auto_invoked": false,
|
||||
"hooks": [],
|
||||
"native_tool": true,
|
||||
"searchable_text": "read_persona read rune's persona definition. returns the full persona block with voice, identity, and rules. native tool"
|
||||
},
|
||||
{
|
||||
"name": "query_memory",
|
||||
"description": "Query Rune's memory store. Returns relevant memories for a query.",
|
||||
"capabilities": [
|
||||
"query_memory"
|
||||
],
|
||||
"file": "tool_executor.py",
|
||||
"full_path": "",
|
||||
"priority": 100,
|
||||
"semantic_examples": [],
|
||||
"risk": "read-only",
|
||||
"preconditions": [
|
||||
"memory store database is available"
|
||||
],
|
||||
"side_effects": [],
|
||||
"auto_invoked": false,
|
||||
"hooks": [],
|
||||
"native_tool": true,
|
||||
"searchable_text": "query_memory query rune's memory store. returns relevant memories for a query. native tool"
|
||||
},
|
||||
{
|
||||
"name": "check_growth",
|
||||
"description": "Check Rune's growth log. Returns recent growth entries and patterns.",
|
||||
"capabilities": [
|
||||
"check_growth"
|
||||
],
|
||||
"file": "tool_executor.py",
|
||||
"full_path": "",
|
||||
"priority": 100,
|
||||
"semantic_examples": [],
|
||||
"risk": "read-only",
|
||||
"preconditions": [
|
||||
"growth log file exists"
|
||||
],
|
||||
"side_effects": [],
|
||||
"auto_invoked": false,
|
||||
"hooks": [],
|
||||
"native_tool": true,
|
||||
"searchable_text": "check_growth check rune's growth log. returns recent growth entries and patterns. native tool"
|
||||
},
|
||||
{
|
||||
"name": "diagnose_behavior",
|
||||
"description": "Diagnose Rune's current behavior. Returns analysis of persona adherence, voice consistency, and drift.",
|
||||
"capabilities": [
|
||||
"diagnose_behavior"
|
||||
],
|
||||
"file": "tool_executor.py",
|
||||
"full_path": "",
|
||||
"priority": 100,
|
||||
"semantic_examples": [],
|
||||
"risk": "read-only",
|
||||
"preconditions": [
|
||||
"recent response text provided"
|
||||
],
|
||||
"side_effects": [],
|
||||
"auto_invoked": false,
|
||||
"hooks": [],
|
||||
"native_tool": true,
|
||||
"searchable_text": "diagnose_behavior diagnose rune's current behavior. returns analysis of persona adherence, voice consistency, and drift. native tool"
|
||||
},
|
||||
{
|
||||
"name": "find_capability",
|
||||
"description": "Search all installed capabilities for what you need. Returns matching tool names with descriptions and argument schemas. Use this when a capability you need is not in your current tool set; the matched tool becomes callable in the same session.",
|
||||
"capabilities": [
|
||||
"find_capability"
|
||||
],
|
||||
"file": "tool_executor.py",
|
||||
"full_path": "",
|
||||
"priority": 100,
|
||||
"semantic_examples": [],
|
||||
"risk": "read-only",
|
||||
"preconditions": [
|
||||
"a capability query describing the needed outcome"
|
||||
],
|
||||
"side_effects": [],
|
||||
"auto_invoked": false,
|
||||
"hooks": [],
|
||||
"native_tool": true,
|
||||
"searchable_text": "find_capability search all installed capabilities for what you need. returns matching tool names with descriptions and argument schemas. use this when a capability you need is not in your current tool set; the matched tool becomes callable in the same session. native tool"
|
||||
}
|
||||
]
|
||||
[]
|
||||
+15
-38886
File diff suppressed because it is too large.
Load diff
@@ -1,48 +0,0 @@
|
||||
# Phase G slice 1 — retrieval-index authority supersession ledger
|
||||
|
||||
**Date:** 2026-10-02 · **Branch:** `phase-g-strangler-retrieval-index` · **Unit issue:** conductor/rune#2448
|
||||
|
||||
## What was superseded
|
||||
|
||||
The pure-Python `query_memory` implementation (formerly `src/rune/query_memory.py`,
|
||||
deployed at `~/.config/opencode/scripts/query_memory.py`) is RETIRED as a production
|
||||
implementation. Production authority now rests with:
|
||||
|
||||
1. **Implementation:** Rust crate `src/rust/query_memory/` (lib.rs core + cdylib, ten
|
||||
`extern "C"` FFI symbols, zero external crates).
|
||||
2. **Production service surface:** `shared/query_memory.py` — a ctypes-backed shim
|
||||
(179 lines) over `qm_loader.py`, byte-deployed to `~/.config/opencode/scripts/query_memory.py`,
|
||||
serving the FULL prior Python class API including the `self.history` snapshot.
|
||||
|
||||
## Strangler doctrine (master doc lines 685–770) — step discharge
|
||||
|
||||
| Step | Requirement | Evidence |
|
||||
|------|-------------|----------|
|
||||
| 1–4 | candidate built, contract frozen, parity proven | commits `9b76585`+`54d2db9`; `/tmp/phaseG_retrieval_index_contract.md` frozen; parity harness ALL GREEN |
|
||||
| 5 | qualification | `/tmp/phaseG_qual_bench.out` (Rust CLI ~45× faster end-to-end); canaries both sides |
|
||||
| 6 | canaries conformance | Python canary 12/12; Rust canary 27/27 |
|
||||
| 7 | shadow comparison vs live store | `/tmp/phaseG_shadow.py` 46/46 exact-equal vs 77-record production store |
|
||||
| 8 | authority switch + observed consumer evidence | commit `6f44a87`; both consumers verified live — `memory_store.py` (lines 820–821, live 76-record store, nested stats shape) + `growth_simulator.py` (record_query through Rust core); #2448 comment id 33795 |
|
||||
| 9 | runtime evidence post-switch | post-switch verification wall ALL GREEN: Python canary 12/12, FFI smoke 41/41, Rust canary 27/27, parity harness ALL GREEN |
|
||||
| 10 | old production path unreachable | ALL import paths (`import query_memory`) now resolve to the deployed shim; `shared/graph_shard_bridge.py` tolerant import serves the shim; the orphan `src/rune/query_memory.py` had ZERO importers (verified by sweep incl. path-string references) |
|
||||
| 11 | old implementation removed or reference-only | `src/rune/query_memory.py` DELETED (this commit); the only stale reference (`scripts/structural_coverage_audit.py` registry mapping shared/ as a mirror of src/rune) corrected — query_memory removed from `SRC_A`/`SHARED_D`, added to `SHARED_B` (canonical, ops-harness owned) |
|
||||
| 12 | supersession ledger | THIS FILE |
|
||||
|
||||
Deletion discipline (language-governance rule ⑥) satisfied: old code removed only after
|
||||
the new implementation was PROVEN — wall green, shadow 46/46, both production consumers
|
||||
observed live on the Rust core before deletion.
|
||||
|
||||
## Consumer map at supersession
|
||||
|
||||
- `~/.config/opencode/scripts/memory_store.py` — in-process, `adaptive_exploration_rate` (line 820).
|
||||
- `~/.config/opencode/scripts/growth_simulator.py` — in-process, `record_query`.
|
||||
- `shared/graph_shard_bridge.py` — tolerant import (try/except), follows the switch.
|
||||
- `src/rune/tool_executor.py` — NOT a consumer (nominal grep hit only; goes through `memory_store.cached_recall`).
|
||||
|
||||
## Verification commands (reproducible)
|
||||
|
||||
- `/home/nick/.venvs/memory/bin/python3 src/rune/canary_query_memory.py` → 12/12
|
||||
- `/home/nick/.venvs/memory/bin/python3 src/rust/query_memory/canary_rust.py` → 27/27
|
||||
- `/home/nick/.venvs/memory/bin/python3 src/rune/ffi_query_memory_smoke.py` → 41/41
|
||||
- `/home/nick/.venvs/memory/bin/python3 /tmp/phaseG_parity.py` → ALL GREEN
|
||||
- `/home/nick/.venvs/memory/bin/python3 scripts/structural_coverage_audit.py` → exit 0, coverage 100%
|
||||
@@ -1,66 +0,0 @@
|
||||
# Phase G Slice 2 — FROZEN CONTRACT: evidence-provenance (T7.3)
|
||||
|
||||
Frozen: 2026-10-03, session ses_ffe5f08a7892affeGzZWhhm0wR. Branch `phase-g-strangler-evidence-provenance` (cut from slice-1 head `2ac2d0a`). Gitea issue #2449. Nothing below may change without a recorded amendment in this file.
|
||||
|
||||
## 1. Scope (observed, not inferred)
|
||||
|
||||
Six modules in `src/rune/`, 1796 lines total, one test file each as marked:
|
||||
|
||||
| Module | Lines | Surface (grep-verified 2026-10-03) |
|
||||
|---|---|---|
|
||||
| `audit_ledger.py` | 231 | `_compute_hash(prev_hash, entry)`, `append_entry(entry_type, entry_id, details)`, `verify_chain() -> {valid, entries, reason}`, `get_entries(limit=50)`, `log_promotion(entry_id, old_status, new_status, wash_count, reason)`, `log_gate_result(entry_id, verdict, critics)`, `log_drift_alert(alert_type, message, severity)`, `main()` |
|
||||
| `behavior.py` | 411 | `connect()`, `add_correction(original, corrected, scope_tags=None, domain="", pattern="")`, `add_habit(trigger, action, name="", context_tags=None, min_activations=3)`, `match_context(context, match_type=None)`, `reinforce(item_id, outcome, item_type="habit")`, `list_items(item_type="all", limit=20)`, `behavior_stats()`, `main()`, `PLUGIN` dict |
|
||||
| `behaviour_ledger.py` | 251 | 9 state constants (UNVALIDATED…NOT_APPLICABLE) + `STATES` + `CONFIRMED_STATES` tuples, `BehaviourLedger` class |
|
||||
| `claim_audit.py` | 430 | `PATTERNS` list, `EVIDENCE_TAG` regex, `LEDGER_MARKERS`, `reframe(text)`, `scan(text)`, `verify(claim)`, `degrade(claim, verdict)`, `journal(entry)`, `report()`, `audit(draft)`, `handle_hook(event, data=None)`, `main()`, `PLUGIN` |
|
||||
| `evidence_probe.py` | 214 | `PROBE_STATUSES`, `PROBE_FIELDS`, `MAX_PROBES_PER_TASK=2`, `ProbeBudgetExceeded`, `ProbeResult`, `build_probe_prompt(question, artifact_path)`, `validate_probe(artifact)`, `count_probes(artifact_dir)`, `check_budget(artifact_dir)`, `record_probe(result, artifact_dir)`, `run_probe(question, artifact_dir, runner=None, model="UNKNOWN")` |
|
||||
| `verification_layer.py` | 259 | `VerificationResult`, seven `verify_*` functions (exit_code, unit_test, schema, file_exists, file_changed, tool_receipt, constraint_check), `verify(result, verifier_type)`, `handle_hook`, `PLUGIN` |
|
||||
|
||||
Plus `shared/audit_ledger.py` (210 ln) — OLDER vintage of audit_ledger.
|
||||
|
||||
## 2. Authority decisions (per module)
|
||||
|
||||
- **src/rune/ is the authority vintage for all six modules** — hardened newer code (memory_env-pathed storage, defensive handling). The deployed `~/.config/opencode/scripts/{audit_ledger,behavior,claim_audit}.py` copies are OLDER vintages (hardcoded expanduser paths). The authority switch is a VINTAGE UPGRADE plus a language swap — not a mirror replacement.
|
||||
- `shared/audit_ledger.py` is superseded alongside the deployed copy (same older vintage, same defects).
|
||||
|
||||
## 3. Live-data contract (the linchpin — observed)
|
||||
|
||||
- **Live ledger:** `/home/nick/.config/opencode/memory/promotion_ledger.jsonl` (21 entries). `verify_chain()` under the deployed module's own defaults returns `{'valid': True, 'entries': 21, 'reason': 'chain intact'}` — OBSERVED 2026-10-03.
|
||||
- **Live signing key: `rune-drift-integrity-2024`** (the deployed/shared default). The src/rune default `rune-governed-adaptation-2024` FAILS the live chain — it is a latent break, recorded as a defect this slice fixes.
|
||||
- **Hash scheme (both vintages identical):** `HMAC-SHA256(key, (prev_hash + json.dumps(entry_without_hash, sort_keys=True)).encode()).hexdigest()`; genesis prev_hash = `"genesis"`; entry lines written with `json.dumps(entry)` in insertion order (type, entry_id, details, timestamp, prev_hash, hash); timestamp = `datetime.now(timezone.utc).isoformat()`.
|
||||
- **Key rule for the Rust candidate:** read `AUDIT_LEDGER_KEY` env; DEFAULT = `rune-drift-integrity-2024` (the key that verifies the live chain). Never default to the governed key — it verifies nothing that exists.
|
||||
- **Live `behavior.db`:** SQLite at memory_env memory dir, touched Sep 24 — must remain readable by the Rust candidate's storage layer.
|
||||
|
||||
## 4. Rust candidate design
|
||||
|
||||
Crate `/mnt/workdrive/rune/src/rust/evidence_provenance/` following the proven slice-1 shape: zero-dep core in `lib.rs`, `cdylib` FFI exports, hand-rolled JSON serialization where byte-parity demands it. **Port order within the slice** (dependency + risk order):
|
||||
|
||||
1. **audit_ledger** — linchpin: live data, external consumers, key contract.
|
||||
2. **verification_layer** — pure logic, no storage, one test file; fastest port.
|
||||
3. **evidence_probe** — file-based budget/records; `rune_operator.py:581` consumer.
|
||||
4. **behaviour_ledger** — state machine, src/rune-only.
|
||||
5. **behavior** — SQLite habits; live DB; deployed vintage upgrade + `rune_tui.py` consumer.
|
||||
6. **claim_audit** — heaviest (warm-neuron store + graph DB + regex engine); last.
|
||||
|
||||
Python-side ctypes loaders (`*_loader.py`) + deployed shims per slice-1 pattern, so every consumer keeps its import surface unchanged.
|
||||
|
||||
## 5. Parity + qualification criteria
|
||||
|
||||
- **Byte-parity:** Rust `verify_chain` output byte-identical to Python's on the live ledger AND on a mutation battery (tampered entry, broken chain, invalid JSON, empty ledger). Parity harness both sides, slice-1 pattern.
|
||||
- **Canaries:** Python-side canary module per ported module + Rust canary; both green before any switch.
|
||||
- **Shadow:** shadow-compare Rust vs Python on live-shaped data before authority switch.
|
||||
- **Performance:** like-for-like benchmark on the real consumption shape; no regression (Nick's law: combination does not decrease speed).
|
||||
|
||||
## 6. Consumers + adoption plan (Nick's directive: adoption during the refactor)
|
||||
|
||||
| Consumer | Imports | Switch |
|
||||
|---|---|---|
|
||||
| `~/.config/opencode/scripts/curator.py` | audit_ledger | at audit_ledger switch |
|
||||
| `canary_tui_drift.py`, `canary_full_system.py` | audit_ledger | at audit_ledger switch |
|
||||
| `rune_tui.py` (L62, L83) | claim_audit, behavior | at each module's switch |
|
||||
| `rune_operator.py:581` | evidence_probe (relative) | at evidence_probe switch |
|
||||
|
||||
Deployed copies become ctypes shims at each module's authority switch (vintage upgrade included — the shim serves the src/rune contract, not the old vintage's). Old deployed Python deletions follow language-governance ⑥: only after the new is proven.
|
||||
|
||||
## 7. Exit criteria
|
||||
|
||||
All twelve doctrine steps discharged per module-port with observed evidence on #2449; coverage-audit registry remapped; supersession ledger written; audit regression gate green.
|
||||
@@ -1,62 +0,0 @@
|
||||
# Phase G slice 2 — evidence-provenance authority supersession ledger
|
||||
|
||||
**Date:** 2026-10-03 · **Branch:** `phase-g-strangler-evidence-provenance` · **Unit issue:** conductor/rune#2449
|
||||
|
||||
## What was superseded
|
||||
|
||||
The pure-Python evidence-provenance implementations (six modules in `src/rune/`, 1796 lines; plus the two OLD deployed vintages and `shared/audit_ledger.py`) are RETIRED as production implementations for their ported surfaces. Production authority now rests with:
|
||||
|
||||
1. **Rust crate `src/rust/evidence_provenance/`** — six cores: `lib.rs` (audit_ledger chain + FFI), `verification.rs` (7 verifiers), `probe.rs` (schema gate + budget), `behaviour.rs` (state machine), `habitmath.rs` (reinforce math), `claims.rs` (claim-audit decision skeleton); cdylib FFI (`ep_*` symbols, 21 total), zero external crates.
|
||||
2. **Python shims** at `src/rune/{audit_ledger,verification_layer,evidence_probe,behaviour_ledger,behavior,claim_audit}.py` — serving the src/rune authority contract through `ep_loader.py` (in-process, no interpreter startup for the ported logic).
|
||||
3. **Deployed shims** at `~/.config/opencode/scripts/{audit_ledger,behavior,claim_audit}.py` — same shape; audit_ledger + claim_audit + behavior carry the LIVE data-path rules (drift-key ledger, live behavior.db, real journal); claim_audit additionally carries the preserved SYMMETRY GUARD (deployed-vintage feature) and the repaired `scan_text()` TUI surface.
|
||||
|
||||
## Port ledger (all six, in contract §4 order)
|
||||
|
||||
| Port | Module | Rust core | Parity | Commit | Consumer proof |
|
||||
|------|--------|-----------|--------|--------|----------------|
|
||||
| 1 | audit_ledger | lib.rs chain ops | shadow 18/18; canaries 28/28+23/23 | `114c394`+`4b0d1d2` | live ledger entries 4242 (post-switch write), verify 23-intact |
|
||||
| 2 | verification_layer | verification.rs | 33/33 (7 verifiers + CLI render) | `9cb93e6` | contracts.py, canary_native, rune_operator:323 dataclass |
|
||||
| 3 | evidence_probe | probe.rs | 24/24 + consumer tests 23/23 | `3450a1c` | rune_operator:581/603, research_stage_executor:312 |
|
||||
| 4 | behaviour_ledger | behaviour.rs | 13/13 full-scenario | `8973caa` | testing_mode:19, iteration:23, rune_tui:3152 |
|
||||
| 5 | behavior | habitmath.rs | 16/16 + full-stack live-db | `2732677` | rune_tui:83; deployed vintage upgraded (live db read-verified) |
|
||||
| 6 | claim_audit | claims.rs | 17/17 + real-journal aggregate (1127 rows) | `969e39f` | rune_tui:62/2468/3752, contracts.py, hook_engine:270 |
|
||||
|
||||
Errors: byte-equal (duplicate/unknown-behaviour/unknown-state; probe schema-gate lists incl. Python repr rendering; CLI argparse shapes + exit codes).
|
||||
|
||||
## Strangler doctrine (master doc lines 685–770) — step discharge (slice level)
|
||||
|
||||
| Step | Requirement | Evidence |
|
||||
|------|-------------|----------|
|
||||
| 1–4 | candidate built, contract frozen, parity proven | commits `114c394` → `969e39f`; frozen contract `plans/2026-10-03-phase-g-evidence-provenance-contract.md` (commit `7c68e41`); per-port parity harnesses ALL GREEN |
|
||||
| 5 | qualification | per-port parity + decision-math batteries; canary pair per port (Python 74/74, Rust 66/66 — all six port sections accumulated); performance follows the slice-1 in-process shape (no interpreter startup; same cdylib) |
|
||||
| 6 | canaries conformance | canary_audit_ledger.py 74/74; canary_evidence_provenance_rust.py 66/66 (per-port sections for ALL six ports; dual-mode LIVE/ISOLATED for live-ledger pins — run 18141 repair); embedded tests through shims (verification test, 23 consumer tests) |
|
||||
| 7 | shadow comparison vs live-shaped data | port-1 shadow 18/18 vs `939883d:shared/audit_ledger.py` (banked at `114c394`); ports 2–6 use direct byte-parity batteries vs the live originals (same discipline, stronger: full-document byte-quality) |
|
||||
| 8 | authority switch + observed consumer evidence | shims deployed + live-verified per port: entry 4242 (first post-switch ledger write), live behavior.db read through the port-5 shim, real 1127-row journal through the port-6 aggregation, TUI backend trio imports, TUI scan_text FIRST-EVER live call |
|
||||
| 9 | runtime evidence post-switch | post-switch walls per port: parity round-trips, embedded tests, consumer chains (rune.behaviour_ledger / rune.evidence_probe / rune.claim_audit + deployed trio) — all GREEN |
|
||||
| 10 | old production path unreachable | `import audit_ledger` (deployed consumers) → shim; `rune.behaviour_ledger` / `rune.evidence_probe` / `rune.claim_audit` / `rune.verification_layer` → shims; `shared/audit_ledger.py` had ZERO importers (verified by sweep incl. path-string forms) — DELETED |
|
||||
| 11 | old implementation removed or reference-only | `shared/audit_ledger.py` DELETED (this commit, after the proven wall + zero-importer sweep); six src/rune modules remain as shims (the API contract); original Python lives in git history. Coverage registry remapped: `audit_ledger` removed from SHARED_D; gate exit 0 post-deletion |
|
||||
| 12 | supersession ledger | THIS FILE |
|
||||
|
||||
Deletion discipline (language-governance rule ⑥): `shared/audit_ledger.py` removed only after (a) the deployed shim proved live against the real ledger, (b) the shadow wall was green, (c) a zero-importer sweep across src/ shared/ scripts/ tests/. The remaining five src/rune originals were rewritten AS shims in their own commits (git history holds each original); they are the API contract and stay.
|
||||
|
||||
## Vintage-merge disclosures
|
||||
|
||||
- **SYMMETRY GUARD preserved:** the deployed `claim_audit` vintage carried `research_lens.symmetry_check` integration (2026-08-15) absent from src/rune — preserved in both shims (feature-preserving merge; load-bearing behavior).
|
||||
- **DEAD CONSUMER REPAIRED:** `rune_tui.py:3752` `claim_audit.scan_text()` had NO implementation in either vintage (silent try/except death) — now implemented, first-class, live-verified.
|
||||
- **Sequence break (port 1):** the audit_ledger shim was deployed BEFORE its canary pair existed; both canaries subsequently written and green — disclosed on #2449 comment 33817, not retrofitted.
|
||||
|
||||
## Consumer map at supersession
|
||||
|
||||
- `~/.config/opencode/scripts/rune_tui.py` — claim_audit (report L2468, scan_text L3752), behaviour (L3152), behavior (L83).
|
||||
- `src/rune/rune_operator.py` — evidence_probe (L581/603), VerificationResult dataclass (L323).
|
||||
- `src/rune/contracts.py` — dynamic `__import__` surfaces (verification_layer, claim_audit).
|
||||
- `src/rune/testing_mode.py:19` / `src/rune/iteration.py:23` — behaviour_ledger constants + class.
|
||||
- `scripts/research_stage_executor.py:312` — evidence_probe orchestration.
|
||||
- `~/.config/opencode/scripts/curator.py` / `canary_full_system.py` — audit_ledger (deployed shim).
|
||||
- `src/rune/dependency_tracker.py` — map-strings only (NOT an import).
|
||||
|
||||
## Live-data rules (contract §3) — honored in the shims
|
||||
|
||||
- Live promotion ledger: drift key verified 23-intact through the shim + FFI; explicit `AUDIT_LEDGER_KEY` override honored.
|
||||
- Live behavior.db: read/written through the deployed shim at `~/.config/opencode/memory/behavior.db`; parity scenarios ran on temp dirs only.
|
||||
- Live claim_audit journal (1127 rows): read-only aggregate through the Rust core; writes stay Python.
|
||||
@@ -1,97 +0,0 @@
|
||||
# Phase H plan — Go front end / Rust back end (Nick's architecture directive)
|
||||
|
||||
Status: PLAN (awaiting Nick's sign-off before any code)
|
||||
Directive: USER-LOCKED (2026-10-04). Supersedes the KEEP-PYTHON verdicts in
|
||||
docs/rebase-language-rubric.md wherever they conflict.
|
||||
|
||||
## 1. The directive
|
||||
|
||||
Go owns the front end: runtime entry points, the first-call surface, the
|
||||
user-facing interface and its calls. Rust owns the back end: every core
|
||||
logic module. Python survives only as transitional glue inside a module
|
||||
until its own Go/Rust surface lands.
|
||||
|
||||
## 2. What "front end" means concretely here
|
||||
|
||||
From the runtime-audit memory (2026-09-10): the live entry chain is
|
||||
rune_tui -> send_task -> ContextBroker -> ModelRouter -> local/Cloud
|
||||
transports. The user-facing calls are: the TUI process itself, the CLI
|
||||
entry (python -m rune / rune binary), the operator message path, and the
|
||||
OpenAI-compatible /v1 endpoints MiMoCode serves.
|
||||
|
||||
Candidates for the Go first-call layer, in dependency order:
|
||||
- rune binary (process entry, arg parsing, process lifecycle) — replaces
|
||||
the Python module-loading bootstrap.
|
||||
- CLI/IPC command dispatch — the first-call surface that routes a user
|
||||
command to the right back-end service.
|
||||
- The OpenAI-compatible HTTP endpoint surface (/v1 chat completions) —
|
||||
stdlib net/http + NDJSON streaming is exactly the area the rubric called
|
||||
Go's only capability-proven fit (W4 evidence, unchanged by the directive).
|
||||
- TUI: NOT in the first Go surface. Textual coupling is deep (80+ modules
|
||||
per the rubric); the front-end Go layer first exposes the API the TUI
|
||||
consumes, and the TUI itself migrates later as its own wave.
|
||||
|
||||
## 3. What "back end" means concretely here
|
||||
|
||||
All pure-logic modules move into the two existing zero-dep crates
|
||||
(evidence_provenance, query_memory) or a third crate for the remaining
|
||||
domains. The zero-external-crate discipline stands (the rubric's W4 Rust
|
||||
kill-rule for network code stays valid INSIDE Rust crates: no network code
|
||||
in crates, that belongs to the Go layer).
|
||||
|
||||
Back-end candidates not yet ported (pure logic, no external deps):
|
||||
- drift_core, drift_cache, drift_compression (scored math) — memory umbrella
|
||||
- warm_neuron_store/warm_router scoring paths — memory umbrella
|
||||
- memory_store consolidation/scoring helpers — memory umbrella
|
||||
- capability_fit/capability_broker scoring — capability umbrella
|
||||
- tokenizer/counting helpers in token_optimizer — inference umbrella
|
||||
Each port follows the slice-2 pipeline: contract, zero-dep Rust, byte-parity
|
||||
battery vs the Python vintage, dual-mode canary, consumer import chain,
|
||||
CI green, supersession ledger.
|
||||
|
||||
## 4. Sequencing (per wave, each independently mergeable)
|
||||
|
||||
H0 — enablement (no behavior change):
|
||||
- Install Go on the host + the runner user's PATH; pin a version in
|
||||
requirements-ci-equivalent (a go-version file + CI check).
|
||||
- CI: add a Go build+vet+test job (empty module, exits 0) so the pipeline
|
||||
carries Go before any code lands.
|
||||
|
||||
H1 — Go first-call shim:
|
||||
- Go binary `rune` replacing the Python entrypoint's process bootstrap:
|
||||
arg parsing, env resolution, spawn the Python runtime (transitional).
|
||||
- Canary: same first-call contract (exit codes, env handoff, TTY attach).
|
||||
|
||||
H2 — Go command dispatch + /v1 endpoint:
|
||||
- Go serves /v1 chat completions + CLI dispatch, calling the Python core
|
||||
through the same local transport the TUI uses today.
|
||||
- Parity battery: request/response shapes vs the Python server for the
|
||||
same canned conversations (byte-level for metadata, streaming NDJSON).
|
||||
|
||||
H3 — back-end wave (parallel to H1/H2 where independent):
|
||||
- Ports listed in section 3, one or two modules per slice, same slice-2
|
||||
discipline. No port starts without its parity battery written first.
|
||||
|
||||
H4 — TUI migration wave (its own contract, later):
|
||||
- Only after H1-H2 prove the Go front end serves the same surfaces the TUI
|
||||
consumes. The TUI is the largest single module (4k+ lines, Textual) and
|
||||
earns its own contract.
|
||||
|
||||
## 5. Honest constraints (carried from the rubric, not contradicted)
|
||||
|
||||
- Go must be installed first (rubric D5 gate: it failed this before; the
|
||||
directive now outweighs the gate but installation is still step zero).
|
||||
- Network/streaming code lives in the Go layer, never in Rust crates
|
||||
(rubric W4: stdlib-only Rust has no credible HTTP/SSE precedent).
|
||||
- SQLite/regex/file-IO stay at their current language boundaries per the
|
||||
zero-dep split law from slice 2 (math Rust, IO at the edges).
|
||||
- Every surface gets the same proof pipeline as slice 2: observed-not-
|
||||
invented expectations, byte parity, dual-mode canary, CI green.
|
||||
|
||||
## 6. Success measure
|
||||
|
||||
The tranche is complete when: the `rune` process starts as a Go binary;
|
||||
user-facing calls (CLI, /v1, operator path) are served by Go; every core
|
||||
logic module on the port list is byte-parity Rust; Python remains only in
|
||||
surfaces explicitly contracted as keep-Python (TUI internals until H4,
|
||||
test harness, canary frameworks).
|
||||
@@ -1,285 +0,0 @@
|
||||
# TOTAL REBASE TRANCHE — Rune to Go/Rust (R2)
|
||||
|
||||
**Status:** DESIGN — awaiting Nick's approval gate (TRANCHE-DEPTH TEMPLATE §4)
|
||||
**Supersedes:** the KEEP-PYTHON rubric verdicts (already superseded by Nick's
|
||||
Go-front/Rust-back directive) and extends Phase H (H0–H4 slice 1, merged
|
||||
`693a494`, v0.90.0) from first ports to total rebase.
|
||||
**Nick's directives (verbatim anchors):**
|
||||
- "i want the whole codebase rebased in rust and go"
|
||||
- "everything should initiate with go as the runtime, and reactive adaptable
|
||||
runtime should be go"
|
||||
- "the deterministic backend i.e memory storage, architectures and elastic
|
||||
cognition and everything like that should be in rust"
|
||||
- "go should be the reactive front end to what interfaces with the user —
|
||||
not gui — the deliverables and chat interactions as well as how rune
|
||||
handles thoughts and runtime"
|
||||
- "the zero dependency rule should be in place but the rebase should rebuild
|
||||
those aspects into the new architecture and make them operational"
|
||||
- "the textual tui should be last but everything should be wired into the
|
||||
textual tui"
|
||||
- "start with the scaffolding first as everything relies on that, then use
|
||||
the new rust scaffolding to make sure everything else is built towards
|
||||
scaffold protocol"
|
||||
- "the scaffolding function should be a rust execution but go start"
|
||||
|
||||
## 1. Grounding summary (measured 2026-10-04, from the spine store + wc)
|
||||
|
||||
- 161 modules with source, **64,482 lines** of `src/rune/` Python.
|
||||
- Draft classification (rule-based, to be function-level verified in Wave 0):
|
||||
- **RUST (deterministic backend):** 49 modules, 26,772 lines — memory,
|
||||
drift, warm, capability, token, spine, scaffold, construction_*,
|
||||
structural_store, curator, consolidation, elastic cognition, ledgers,
|
||||
audit, evidence, contracts, sleep_time, subconscious, persona_gate,
|
||||
context_broker, growth.
|
||||
- **GO (reactive runtime + user-facing):** 10 modules, 7,043 lines —
|
||||
operator, transports, dispatch, provider registry, adaptive router,
|
||||
hook engine, local tool runtime, work manager, deploy_qualify.
|
||||
- **TUI-last:** 4 modules, 4,889 lines — rune_tui (4,041), tui_validator,
|
||||
tui_backlog, tui_transport.
|
||||
- **UNCLASSIFIED (Wave 0 must disposition each with evidence):** 73
|
||||
modules, 21,473 lines — voice_*, tool_executor, model_routing/registry,
|
||||
event_bus, cron_engine, message_queue, identity_anchors, pins,
|
||||
stage_guards, tier_manager, witness, etc.
|
||||
- **Test infra:** 23 canary/test modules, 4,211 lines — rewritten per wave
|
||||
(Rust canaries port with their surface; Go canaries for the front).
|
||||
- **Retires:** `__init__`, `__main__`, `memory_env` (bootstrap glue —
|
||||
subsumed by the Go runtime's env contract).
|
||||
- Existing Rust (merged, production-proven): 6 zero-dep crates
|
||||
(query_memory, evidence_provenance, rune_spine, memory_scoring,
|
||||
capability_scoring, token_counting), 338k bytes, all with parity
|
||||
batteries. Go: rune-entry (H1 shim + H2 /v1 front door).
|
||||
- Stragglers from R1 folded in: #2171, #2119 (TUI), #1844 (salience_gate),
|
||||
#1755 (goal._load), #1738 (failure_auto_filer).
|
||||
|
||||
## 2. Objective
|
||||
|
||||
Every line of rune's Python runtime is rebased into the dichotomy —
|
||||
**Go initiates and reacts; Rust determines and stores** — with the
|
||||
scaffolding protocol rebuilt FIRST (Go start / Rust execution) so every
|
||||
subsequent conversion is driven, checked, and closed by the new protocol
|
||||
itself. Python is deleted only after the replacement is parity-proven and
|
||||
CI-green (strangler exit law). The Textual TUI is last and stays the
|
||||
integration surface: everything wires into it over the transport seam.
|
||||
|
||||
## 3. The hard constraint analysis (zero-dep + total rebase — feasibility)
|
||||
|
||||
Nick asked: confirm or deny. **Confirmed possible**, amended per his
|
||||
critiques (2026-10-04):
|
||||
|
||||
- **Hybridized membrane, not a wall (Nick's correction):** Go remains the
|
||||
reactive initiator, but "Rust never touches a socket" is WITHDRAWN as an
|
||||
absolute. The languages interoperate where coherence demands: Rust cores
|
||||
callable from Go (the proven cdylib pattern), Go surfaces invocable from
|
||||
Rust through defined channels, shared wire protocols. The dichotomy is
|
||||
the DEFAULT placement rule; hybrid junctions are deliberate, contracted
|
||||
exceptions — each recorded in the unit's contract.
|
||||
- **SQLite STAYS (Nick's ruling):** no bespoke storage engine in this
|
||||
tranche. SQLite remains and is wired into the new architecture — the
|
||||
Rust side reaches it through system-library FFI (legal under zero-dep:
|
||||
a system library is not a crate dependency). The bespoke memory-system
|
||||
redesign is a LATER, separate program.
|
||||
- **Reactivity/async:** Go goroutines + channels own the event loops;
|
||||
Rust's deterministic cores stay synchronous behind the membrane.
|
||||
- **Regex:** hand-rolled matchers per case (proven: pyjson, word-run
|
||||
scanner, run-collapse). No general regex engine needed.
|
||||
- **Parity-plus-improvement (Nick's upgrade):** parity is the FLOOR, not
|
||||
the ceiling. Every unit answers "parity OR measurably better" —
|
||||
efficiency improvements are in scope per function (Rust zero-copy and
|
||||
exactness, Go goroutine-native concurrency), bloat from bad syntax is
|
||||
removed, and functionality is the non-negotiable gate. Improvements
|
||||
carry measurements; the parity battery proves no behavior regression
|
||||
either way.
|
||||
- **TUI wiring is continuous (Nick's correction):** each landed surface
|
||||
wires toward the Textual TUI over the transport seam as part of its
|
||||
unit contract — the final TUI wave integrates a system already aimed
|
||||
at it, not a retrofit.
|
||||
- **Language intelligence in the protocol (Nick's addition):** the
|
||||
scaffolding gains a first-class placement decision — for rune, the
|
||||
Go/Rust dichotomy rule (reactive/initiating → Go; deterministic/
|
||||
stateful → Rust); for other projects, a language-fit assessment at
|
||||
construction-classification time (the protocol recommends the right
|
||||
language for the task's characteristics).
|
||||
- **Provenance lock (Nick's verification):** the scaffolding being ported
|
||||
in Wave 1 is the V1-ACCEPTED system per docs/SCAFFOLDING_V1_DEFINITION.md
|
||||
(T18 §18B; North Star = Nick's verbatim words; 17/17 acceptance gates).
|
||||
The Wave 1 parity replay against the production contract ledger proves
|
||||
the rebuild is that design, not a drift.
|
||||
|
||||
## 4. Wave structure (each wave independently mergeable, scaffolding-gated)
|
||||
|
||||
### Wave 0 — Grounding + inventory verification (the template's bar)
|
||||
- Function-level mapping of all 161 modules (the spine gives structure;
|
||||
wave 0 verifies 100% of functions and classifies the 73 UNCLASSIFIED
|
||||
with evidence).
|
||||
- Disposition the 5 R1 stragglers.
|
||||
- Produce the per-unit issue factory input: one issue per function,
|
||||
each answering improve/fix/missing-connectors with evidence.
|
||||
- Deliverable: `plans/total-rebase-inventory.md` + issues filed.
|
||||
- Exit gate: inventory signed off by Nick (the approval gate).
|
||||
|
||||
### Wave 1 — The scaffolding engine reborn (Go start / Rust execution)
|
||||
**Everything depends on this — it goes first, per Nick's directive.**
|
||||
- The rebuild target is the V1-ACCEPTED system (Nick's design —
|
||||
docs/SCAFFOLDING_V1_DEFINITION.md, North Star verbatim, 17/17
|
||||
acceptance gates). The parity replay against the production contract
|
||||
ledger is the proof the rebuild IS that design.
|
||||
- Rust crate `scaffold_core`: the construction machinery as pure
|
||||
deterministic logic — contract lifecycle (draft→approved→building→
|
||||
verifying→closed), closure classification (correctly_predicted et al.),
|
||||
scope resolution, legal transitions, the contract store.
|
||||
Source modules: scaffold.py, construction_interface.py,
|
||||
construction_decision.py, construction_intent.py, structural_store.py
|
||||
(parts not already in rune_spine), contracts.py, toolchain.py.
|
||||
- Go surface `rune-scaffold` (extends rune-entry): the initiation layer —
|
||||
submit-need/observe/transition/close CLI + /v1 endpoints, delegating to
|
||||
the Rust core.
|
||||
- NEW per Nick: the **language-placement decision** lands in the protocol
|
||||
here — construction classification gains a language-fit assessment
|
||||
(rune: the Go/Rust dichotomy rule; other projects: characteristic-based
|
||||
recommendation). Every later contract carries its placement verdict.
|
||||
- NEW per Nick: parity is the floor — the engine itself is the first
|
||||
beneficiary of the parity-plus-improvement rule (measured improvements
|
||||
allowed, functionality preserved, no-regression proven).
|
||||
- Exit gate: the R2 tranche's own remaining waves are driven THROUGH the
|
||||
new engine (the protocol builds itself under its own rules).
|
||||
|
||||
### Wave 2 — Memory/storage backend (Rust, SQLite retained)
|
||||
- SQLite is NOT replaced (Nick's ruling). The Rust memory core reaches it
|
||||
via system-library FFI (zero-dep legal); memory_store.py (2,435 lines)
|
||||
is decomposed: query paths and consolidation logic into Rust, the SQLite
|
||||
mechanics behind a thin storage trait that maps to libsqlite3 today and
|
||||
to the future bespoke engine LATER without consumer churn.
|
||||
- elastic_cognition, memory_consolidation, sleep_time, curator,
|
||||
subconscious_pass, drift_* (remaining DB-backed surfaces), journal,
|
||||
recall_* (recall_router is routing → boundary checked at Wave 0
|
||||
disposition).
|
||||
- Data safety gate: checksum-verified read-back of the live store through
|
||||
the new engine; zero writes until the read path is proven identical.
|
||||
|
||||
### Wave 3 — Cognition + architecture engines (Rust)
|
||||
- The remaining deterministic cores: capability_broker decision logic,
|
||||
context_broker, persona_gate, growth, identity_anchors, pins,
|
||||
stage_guards, tier_manager, witness, safety_override, abstraction,
|
||||
verification surfaces.
|
||||
- Ports already merged (memory_scoring, capability_scoring,
|
||||
token_counting, rune_spine) are verified against the new scaffold
|
||||
protocol and wired into the final architecture.
|
||||
|
||||
### Wave 4 — The reactive runtime (Go)
|
||||
- The operator turn loop (rune_operator.py, 2,697 lines), chat
|
||||
interactions, deliverables production, model routing at call time
|
||||
(adaptive_router, model_registry/profiles/routing, provider_*),
|
||||
tool execution (tool_executor, tool_protocol, local_tool_runtime),
|
||||
event surfaces (event_bus, message_queue, cron_engine, hook_engine),
|
||||
voice output chain (voice_*) as deliverable production.
|
||||
- The /v1 surface deepens to carry the full interaction contract;
|
||||
NDJSON streaming becomes the standard response shape.
|
||||
|
||||
### Wave 5 — Python retirement sweep
|
||||
- Every Python module whose surfaces have landed is deleted (strangler
|
||||
exit: parity proven + CI green + deployed one cycle). Shared/ vintage
|
||||
mirrors retired with them.
|
||||
- The glue shims (ms_loader, cs_loader, tc_loader, spine_loader) retire
|
||||
when their consumers no longer speak Python at all.
|
||||
|
||||
### Wave 6 — TUI last (but wired continuously)
|
||||
- Every wave before this one ships its transport-seam wiring toward the
|
||||
TUI as part of each unit's contract (Nick's correction: natural,
|
||||
continuous wiring — not a retrofit wave).
|
||||
- Then the TUI itself: a thin Textual render shell over the wire (all
|
||||
logic already Go/Rust by then) or a port — disposition decided on the
|
||||
evidence of everything that came before.
|
||||
|
||||
### Wave 7 — Final audit
|
||||
- Language-bar measurement, the full scaffolding ledger replayed, the
|
||||
tranche's closure report with per-wave evidence.
|
||||
|
||||
## 5. Per-unit discipline (the template, unchanged)
|
||||
|
||||
- One issue per function via the issue factory; each answers
|
||||
improve/fix/missing-connectors with evidence.
|
||||
- Every unit runs the scaffolding pipeline end-to-end: submit-need →
|
||||
contract → approval → canary-first (red proven) → implementation →
|
||||
parity battery vs the Python vintage → closure audit (structural ids,
|
||||
never file paths — the closure vocabulary law).
|
||||
- Per-unit decisions on evidence, never pre-decided globally: each
|
||||
function's Go-vs-Rust placement is assessed by the dichotomy rule with
|
||||
the measured call graph, not by the draft classification alone.
|
||||
- Bug-fix contract governs every defect found en route (red test first,
|
||||
regression frozen).
|
||||
|
||||
## 6. Verification gates
|
||||
|
||||
- CI green per wave (crate builds, Go vet/test/build, canaries, henxels,
|
||||
type ratchet until the Python ratchet itself retires in Wave 5).
|
||||
- Parity batteries are byte-level for deterministic surfaces, shape-level
|
||||
modulo volatile fields for wire surfaces.
|
||||
- The scaffolding closure audit for every contract: correctly_predicted
|
||||
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
|
||||
re-wired; mitigations: read-path proven identical before any write,
|
||||
checksum-verified read-back of the live store, the storage trait
|
||||
boundary keeps the future bespoke swap cheap.
|
||||
- **Hybrid membrane drift** — junctions multiply ad-hoc if ungoverned;
|
||||
every Go↔Rust interaction point is a contracted, recorded decision in
|
||||
its unit's contract (the dichotomy is the default; hybrids justify
|
||||
themselves per unit).
|
||||
- **Improvement regressions** — parity-plus-improvement invites subtle
|
||||
behavior changes; every improvement carries a measurement AND the parity
|
||||
battery stays authoritative for no-regression.
|
||||
- **Go↔Rust call latency** — measure in Wave 1; the architecture assumes
|
||||
local transport cost is negligible vs model latency; if measured wrong,
|
||||
the membrane's transport moves (decision recorded, not improvised).
|
||||
- **Context-window economics** — 1,852-style issue volumes mean the
|
||||
pipeline must multiplex (no-wait law) and local models carry routine
|
||||
units (custodian pattern).
|
||||
- **Scope creep during Wave 0** — the inventory is measured and frozen
|
||||
before design; additions go through scope amendments.
|
||||
|
||||
## 8. Rollback
|
||||
|
||||
- Every wave merges independently; master stays deployable at each
|
||||
boundary (the strangler's whole point).
|
||||
- The Python vintage remains until Wave 5 deletion gates pass; a wave
|
||||
revert = revert the merge commit (deploy qualification re-runs).
|
||||
- The scaffolding engine's Wave 1 parity replay means even the protocol's
|
||||
own replacement is reversible against recorded history.
|
||||
|
||||
## 9. Approval gate
|
||||
|
||||
This tranche does not execute until Nick approves. On approval, Wave 0
|
||||
starts immediately and runs without consent blockers (standing directive),
|
||||
with self-verified checkpoints and defect filing.
|
||||
@@ -1,354 +0,0 @@
|
||||
# TRANCHE v3: THE FULL DICHOTOMY REBASE — with HOW, with language advantages, with automated verification
|
||||
|
||||
Nick's corrections applied:
|
||||
- Umbrella manifest feeds the spine (not superseded); both need updating
|
||||
- construction_decision.py itself gets ported (Go start + Rust execution)
|
||||
- Language advantages are part of every port — improvements where the target language is better
|
||||
- Automated parity verification BEFORE gutting the Python (hard gate, no manual checking)
|
||||
- A testing document that proves bigger features work after each wave
|
||||
- Maximise Bubble Tea addons (research the ecosystem)
|
||||
- No arbitrary timeframe — it gets done when it gets done
|
||||
- Every task follows on to the next — never stopping
|
||||
- CI stacking: keep submitting PRs; address CI issues in batches of 5, not individually
|
||||
|
||||
---
|
||||
|
||||
## THE CORE MECHANISM: How every module gets replaced
|
||||
|
||||
Every module follows the same seven-step process. No exceptions. The process IS the verification.
|
||||
|
||||
### Step 1: Understand the Python module
|
||||
Read every function. Identify: what does it compute (→ Rust), what does it initiate (→ Go), what does it store (→ Rust), what does it route (→ Go). Note every caller. Note every file it reads/writes.
|
||||
|
||||
### Step 2: Write the replacement in the target language
|
||||
For Rust: a `pub fn` in the appropriate crate, with serde-compatible structs.
|
||||
For Go: a method on a struct in the appropriate `src/go/<name>/` package.
|
||||
|
||||
**Language advantage check**: at this step, ask "does Go/Rust do this BETTER than Python did?" If yes, implement the improvement. Examples: Go goroutines replace Python threading for parallel operations. Rust's zero-cost abstractions replace Python duck typing for hot-path scoring. Go's `net/http` replaces Python `urllib` for model connections with connection pooling and keep-alive.
|
||||
|
||||
### Step 3: Write the parity test (RED first)
|
||||
Before touching the Python module, write a test that runs the same input through BOTH the Python oracle and the new Go/Rust implementation, and asserts the outputs are identical. This test must FAIL before the implementation is correct, and PASS once it is. The test is the gate.
|
||||
|
||||
### Step 4: Verify parity — the HARD GATE
|
||||
Run the parity test. If it passes, the replacement is PROVEN to work. Only now can you proceed to Step 5. If it fails, debug the Go/Rust implementation until it passes. **Do not gut the Python until this gate passes.** This is automated — you never have to manually check.
|
||||
|
||||
### Step 5: Rewire the Python module as a delegation shim
|
||||
Replace the Python function body with a call to the Go binary (subprocess) or the Rust kernel (ctypes/cgo). Every existing caller of the Python module keeps working — they don't know the implementation changed.
|
||||
|
||||
### Step 6: Register the canary in CI
|
||||
The parity test from Step 3 is registered in `.gitea/workflows/ci.yml`. Now every future commit is checked against the parity contract automatically.
|
||||
|
||||
### Step 7: PR → CI → merge
|
||||
Push the branch, let CI run. If CI raises issues, DON'T STOP — continue to the next module's port. Address CI issues in batches of 5. The pipeline is proven; it catches things; you fix them in batches.
|
||||
|
||||
**The key insight**: Step 4 (the parity gate) is the answer to "how do you confirm replacements working before you gut it?" You don't gut anything until the automated test proves the replacement produces identical output. The test is the contract.
|
||||
|
||||
---
|
||||
|
||||
## THE TESTING DOCUMENT: proving bigger features after each wave
|
||||
|
||||
After each wave completes, a WAVE VERIFICATION DOCUMENT is produced that proves the system works end-to-end. Not unit tests — integration tests.
|
||||
|
||||
### What it contains:
|
||||
1. **The operator turn loop works**: send a message through the Go operator, get a response back, verify the response is correct
|
||||
2. **Memory operations work**: store a memory, recall it, verify the content matches
|
||||
3. **Tool execution works**: execute a tool call, verify the output
|
||||
4. **The TUI renders**: launch the Bubble Tea TUI, verify it displays
|
||||
5. **The event journal works**: emit an event, read it back
|
||||
6. **The scaffolding works**: submit a need, verify the contract is created
|
||||
|
||||
### How it's generated — BY THE GITEA PIPELINE, not by the agent:
|
||||
A shell script (`scripts/wave_verify.sh`) is written by the agent. A CI workflow step runs the script after each wave merge. The CI step formats the results as markdown and posts them as a comment on the wave's Gitea epic. The document is permanent — attached to the epic, survives session restarts, reproducible (the commands are in the document), automated (CI runs it, not the agent).
|
||||
|
||||
### Implementation:
|
||||
- `scripts/wave_verify.sh` — the integration verification script
|
||||
- A CI workflow step (in ci.yml or a new `wave-verify.yml`) that runs the script and posts results to the Gitea epic using the existing GITEA_TOKEN secret
|
||||
- The same mechanism the merge-robot already uses for PR comments
|
||||
|
||||
### What "done" means for a wave:
|
||||
The wave's Gitea epic has a verification comment showing every integration path PASSING. The agent does not produce testing documents — the pipeline does.
|
||||
|
||||
### What "done" means for a wave:
|
||||
Not just "the code compiles" — the wave verification document shows every integration path working.
|
||||
|
||||
---
|
||||
|
||||
## WAVE 0: INFRASTRUCTURE (before any porting)
|
||||
|
||||
### 0.1 Henxels scope extension
|
||||
Open `henxels.yaml`. Add scopes for `src/rust/*/src/*.rs` and `src/go/**/*.go`. Same quality gates: max_lines, no_secrets, canary registration, coverage existence. Without this, new Go/Rust files have no governance.
|
||||
|
||||
### 0.2 Umbrella manifest extension
|
||||
The umbrella manifest IS the spine's input for non-module surfaces. Extend it:
|
||||
- Add the 10 existing Rust crates as `rust_crates` entries
|
||||
- Add the 2 existing Go modules as `go_surfaces` entries
|
||||
- Add placeholder entries for the planned Go modules
|
||||
- Every new Go/Rust file gets tracked, so the spine knows about it
|
||||
|
||||
### 0.3 Scaffolding protocol update (construction_decision.py port)
|
||||
`construction_decision.py` is itself a Python file. Port it:
|
||||
- **Go start call**: the CLI surface that receives the classification request
|
||||
- **Rust execution**: the deterministic classification logic (keyword matching, language placement)
|
||||
- The GO_SIGNALS and RUST_SIGNALS keyword lists are updated to match the corrected dichotomy
|
||||
- The Python version becomes a delegation shim
|
||||
- After this port, `rune scaffold classify` routes through Go→Rust, not Python
|
||||
|
||||
### 0.4 CI pipeline update
|
||||
- Build every Rust crate in the unit-tests job
|
||||
- Build every Go module in a new `go-build` job
|
||||
- Set CC_RUST_LIB, SC_RUST_LIB, etc. to the CARGO_TARGET_DIR paths
|
||||
- Add `go vet` and `go test ./...` steps
|
||||
|
||||
### 0.5 Gitea epic + MiMoCode tasks
|
||||
- Post the parent epic on Gitea: the full wave structure as a folded checklist
|
||||
- Post per-wave sub-epics
|
||||
- Mirror in MiMoCode's task tool
|
||||
- Every subsequent task updates both
|
||||
|
||||
---
|
||||
|
||||
## WAVE 4: GO REACTIVE INFRASTRUCTURE (14 modules)
|
||||
|
||||
### event_bus (244 lines) — DONE
|
||||
Already built as `src/go/event-bus/`. Reads/writes the same events.jsonl.
|
||||
|
||||
### event_envelope (303 lines)
|
||||
Merge into event-bus. The EventEnvelope struct already exists in Go. Add the OrchestrationRecord methods (to_dict, from_dict) as MarshalJSON/UnmarshalJSON. Add the content_hash function.
|
||||
|
||||
### message_queue (10KB)
|
||||
**What it does**: holds approved messages until they're executed. The Python version uses a JSONL file with a mutex.
|
||||
**Go advantage**: Go channels are designed for this. Use a buffered channel for in-memory queue + a JSONL file for durability. The Go version is concurrent-safe by construction.
|
||||
**HOW**: Create `src/go/message-queue/`. Define `type Message struct` with the same fields as the Python version. Implement `Enqueue`, `Dequeue`, `GetApproved`, `MarkExecuted`. The Python module becomes a subprocess shim.
|
||||
**Parity test**: enqueue 10 messages in Python, read them in Go, verify identical.
|
||||
|
||||
### hook_engine (28KB)
|
||||
**What it does**: loads plugin hooks from a config, fires them on events.
|
||||
**Go advantage**: goroutines enable parallel hook dispatch (Python's GIL prevents this).
|
||||
**HOW**: Create `src/go/hook-engine/`. `type HookEngine struct { hooks map[string][]HookFunc; mu sync.RWMutex }`. `Fire(name, data)` iterates hooks sequentially; `FireAsync` dispatches each hook in a goroutine and collects errors via channels.
|
||||
**Language advantage**: parallel hook dispatch — Python can't do this due to the GIL.
|
||||
|
||||
### microkernel (14KB)
|
||||
**What it does**: the plugin lifecycle — register, activate, dispatch.
|
||||
**Go advantage**: Go interfaces replace Python duck typing with compile-time guarantees.
|
||||
**HOW**: `type Plugin interface { Name() string; Capabilities() []string; OnMessage(data) error }`. Registry with `Register(p Plugin)`, `Fire(event, data)`. The hook_engine plugs into this.
|
||||
|
||||
### subsystem_health (6KB)
|
||||
**What it does**: tracks failures per subsystem, escalates tiers.
|
||||
**HOW**: `type SubsystemHealth struct { failures map[string][]Failure }`. RecordFailure, GetHealth. Write to JSON for durability.
|
||||
|
||||
### parallel_processor (5KB)
|
||||
**What it does**: runs operations in parallel.
|
||||
**Go advantage**: goroutines + sync.WaitGroup. This is what Go was BORN for.
|
||||
**HOW**: `func ParallelMap[T, R any](items []T, fn func(T) R) []R`. Launch goroutines, collect via channels.
|
||||
|
||||
### work_manager (20KB)
|
||||
**What it does**: manages work dispatch to builders.
|
||||
**HOW**: Go worker pool with `chan Task`. `type WorkManager struct { workers int; queue chan Task; results chan TaskResult }`. Start, Submit, Stop.
|
||||
|
||||
### failure_auto_filer (21KB)
|
||||
**What it does**: auto-files failures to the forge.
|
||||
**HOW**: Go struct with spool file + forge client. Same pattern as the existing forge_client.
|
||||
|
||||
### cache (16KB) + connection_pool (3KB)
|
||||
**What they do**: cache responses, pool connections.
|
||||
**Go advantage**: Go's `sync.Map` and channel-based pools are built for this.
|
||||
**HOW**: `src/go/cache/` — LRU cache with `sync.RWMutex`. `src/go/connection-pool/` — channel-based pool.
|
||||
|
||||
### cron_engine (14KB) + night_mode (14KB)
|
||||
**What they do**: scheduled tasks, night consolidation.
|
||||
**Go advantage**: `time.Ticker` + goroutines replace Python's threading.Timer.
|
||||
**HOW**: `src/go/cron-engine/` — task list with cron expressions. `src/go/night-mode/` — uses the cron engine for scheduled consolidation.
|
||||
|
||||
### recall_router (5KB)
|
||||
**What it does**: routes recall queries to the right memory backend.
|
||||
**HOW**: `src/go/recall-router/` — routing table with `map[string]RecallFn`.
|
||||
|
||||
---
|
||||
|
||||
## WAVE 4b: GO TOOL EXECUTION (3 modules)
|
||||
|
||||
### tool_executor (73KB) — STARTED
|
||||
The Go binary already handles read_file, list_directory, glob_files, grep_files, run_command. Add the remaining operations: write_file (with path validation), edit_file (with diff preview), run_tests, lint_file, git_commit, git_diff, git_log, repo_map, and the query/diagnose operations.
|
||||
**Language advantage**: Go's `os/exec` with `context.Context` for timeouts is cleaner than Python's `subprocess.run(timeout=)`. Go's goroutines enable parallel tool execution (Python serialises them).
|
||||
|
||||
### tool_protocol (16KB)
|
||||
Go types: `ToolRequest`, `ToolEvent`. Validation against a schema registry. The approval boundary stays in the Go operator (not Python).
|
||||
|
||||
### local_tool_runtime (35KB)
|
||||
The Go loop: receive model response → parse tool calls → validate → dispatch to executor → feed results back. `type LocalToolRuntime struct { transport Transport; tools []ToolDef; maxIterations int }`. This is the loop that makes Rune respond to tool results.
|
||||
|
||||
---
|
||||
|
||||
## WAVE 5a: GO MODEL/PROVIDER (10 modules → 1 binary)
|
||||
|
||||
All 10 modules collapse into `src/go/model-connect/`.
|
||||
|
||||
**Language advantage**: Go's `net/http` with connection pooling and keep-alive replaces Python's `urllib` (which opens a new connection per request). Go's goroutines enable parallel model calls (Python serialises them). Go's `context.Context` enables timeout propagation through the call chain.
|
||||
|
||||
### model_connect (16KB)
|
||||
`type OllamaClient struct { baseURL string; client *http.Client }`. Chat, Show, Pull, ListModels. Use `net/http` with a shared transport for connection reuse.
|
||||
|
||||
### model_routing (16KB) + model_registry (6KB) + model_profiles (16KB)
|
||||
Go router that scores tasks against model capabilities and routes to the right model. One `ModelRouter` struct replaces three Python files.
|
||||
|
||||
### provider_budget (12KB)
|
||||
Go budget tracker with `sync.Mutex`. Record, GetStatus. Token counting per provider.
|
||||
|
||||
### provider_registry (23KB) + standardized_providers (9KB) + provider_context (2KB)
|
||||
Go `Provider` interface with OllamaProvider and CompatProvider implementations. Registry manages connections.
|
||||
|
||||
### tiered_executor (9KB)
|
||||
Go executor with tier escalation. Execute, Escalate.
|
||||
|
||||
---
|
||||
|
||||
## WAVE 5b: GO OPERATOR (19 modules → 1 binary)
|
||||
|
||||
**rune_operator (126KB)** — the turn loop. This is the hardest port.
|
||||
**How**: break it into sub-systems. Port each one at a time. After each, run the full test suite.
|
||||
1. The state management (RuneState, TaskStateRepo, ConversationRepo) → Go structs with JSON persistence
|
||||
2. The turn loop → Go function: `Respond(channel, message) OperatorResponse`
|
||||
3. The routing → Go AdaptiveRouter
|
||||
4. The tool dispatch → Go LocalToolRuntime (already ported in Wave 4b)
|
||||
5. The memory interaction → Go MemoryStore (Wave 5c) + Rust kernels via cgo
|
||||
6. The model connection → Go ModelConnect (Wave 5a)
|
||||
|
||||
**Language advantage**: Go goroutines replace Python threading for parallel context gathering. Go channels replace Python queues. Go's `context.Context` replaces Python's ad-hoc timeout management. The turn loop becomes truly concurrent — memory recall and model inference can overlap.
|
||||
|
||||
**The other 18 modules** are supporting cast: adaptive_router (23KB), build_mode (20KB), builder_bridge (12KB), core_server (9KB), auto_context (8KB), auto_tasks (15KB), event_wait (23KB), evidence_probe (7KB), forge (5KB), forge_client (7KB), goal (14KB), growth_delta (16KB), warm_router (55KB), release_notes (18KB), persona_definition (7KB), voicebox (4KB), voice_injector (3KB). Each follows the same pattern: read Python → write Go → parity test → rewire → commit.
|
||||
|
||||
---
|
||||
|
||||
## WAVE 5c: GO MEMORY OPERATIONS (8 modules)
|
||||
|
||||
### memory_store (99KB) — THE BIGGEST SINGLE PORT
|
||||
**What it does**: every SELECT, INSERT, UPDATE, DELETE against the memory database.
|
||||
**Go advantage**: `modernc.org/sqlite` is pure Go — no cgo, no C compiler, cross-compiles trivially. Go's `database/sql` interface with prepared statements is cleaner than Python's raw sqlite3.
|
||||
**HOW**: `type MemoryStore struct { db *sql.DB }`. Every Python function becomes a Go method. The SQL statements ARE the specification.
|
||||
**Parity test**: same SQLite file, same queries, byte-identical results. Run after every operation.
|
||||
|
||||
### curator (70KB)
|
||||
Scans the store, identifies conflicts, promotes/demotes. Go state machine.
|
||||
|
||||
### sleep_time (38KB)
|
||||
Idle-period consolidation. Go goroutine on a timer.
|
||||
|
||||
### memory_consolidation (31KB)
|
||||
Calls the Rust kernel (already ported). Go handles the I/O.
|
||||
|
||||
### The other 4 (persona_gate, abstraction, witness, stage_guards)
|
||||
Each follows the same pattern.
|
||||
|
||||
---
|
||||
|
||||
## WAVE 6: RUST BACKEND (85 modules)
|
||||
|
||||
Each Python module's pure functions become `pub fn` in the appropriate crate.
|
||||
|
||||
**The pattern for each:**
|
||||
1. Read the Python module, identify pure functions
|
||||
2. Write the Rust equivalent in the crate
|
||||
3. Add an FFI symbol
|
||||
4. Write a parity test
|
||||
5. The Python module becomes a thin FFI caller
|
||||
|
||||
**The rhythm**: most modules are 3-10KB. At that size, a port takes 15-30 minutes once you're in the rhythm. 85 modules at that pace is 2-3 days of focused work.
|
||||
|
||||
**Language advantage**: Rust's type system catches bugs at compile time that Python catches at runtime. Rust's `Result<T, E>` replaces Python's try/except for error handling. Rust's pattern matching replaces Python's if/elif chains. Rust's zero-cost abstractions mean the ports are FASTER than the Python originals.
|
||||
|
||||
---
|
||||
|
||||
## WAVE 7: BUBBLE TEA TUI (Go)
|
||||
|
||||
### Maximising the Bubble Tea ecosystem
|
||||
|
||||
Research the full Bubble Tea + Lipgloss + Bubbles ecosystem for every available addon:
|
||||
|
||||
**Bubble Tea** (the runtime): Elm architecture, goroutine-safe, tea.Tick for animations, tea.Every for recurring updates, tea.WithAltScreen for fullscreen, tea.WithMouseCellMotion for mouse support.
|
||||
|
||||
**Lipgloss** (styling): truecolor (16.7M colors), borders (rounded, thick, double, hidden), padding/margin/width/height, alignment, flex layout, gradients, inline styling, copy/blend styles.
|
||||
|
||||
**Bubbles** (pre-built components):
|
||||
- `spinner`: rotating indicators (line, dot, mini-dot, jump, pulse, points, globe, moon, monkey, meter, hamburger, ellipsis)
|
||||
- `progress`: animated progress bars with gradient colors
|
||||
- `textinput`: text input with cursor, placeholder, validation
|
||||
- `textarea`: multi-line text input
|
||||
- `table`: sortable, selectable data tables
|
||||
- `list`: filtered, paginated lists
|
||||
- `viewport`: scrollable content area
|
||||
- `paginator`: pagination controls
|
||||
- `key`: key binding documentation
|
||||
- `help`: help bubble
|
||||
- `timer`: countdown timer
|
||||
- `stopwatch`: elapsed time
|
||||
|
||||
**Additional libraries in the ecosystem:**
|
||||
- `glamour`: markdown rendering with syntax highlighting (for chat messages that contain code)
|
||||
- `harmonica`: spring animation physics (for smooth pane transitions)
|
||||
- `bubble-lipgloss-extras`: additional styling utilities
|
||||
|
||||
**What the current TUI has that maps:**
|
||||
- Two-column layout (chat LEFT, task RIGHT) → `lipgloss.JoinHorizontal()` with width ratios
|
||||
- Chat bubbles with sender name, timestamp, content → custom component with `lipgloss.Style{}.Border(lipgloss.RoundedBorder()).Padding(0, 1)`
|
||||
- Thinking indicator (spinner) → `bubbles/spinner` with the pulse style
|
||||
- Tool call display → bordered component with syntax highlighting via `glamour`
|
||||
- Status bar (version, mode, model, project) → fixed bottom bar via `lipgloss.JoinVertical()`
|
||||
- Command selector with autocomplete → `bubbles/textinput` + custom suggestion loop
|
||||
- Work pane (operational index) → side panel with `bubbles/list`
|
||||
- Scrollback → `bubbles/viewport` with `SetContent()` and `GotoBottom()`
|
||||
- Keybindings → `tea.KeyMap` with `tea.KeyCtrl1`, `tea.KeyCtrl2`, `tea.KeyCtrl3`
|
||||
- Streaming text → `tea.Cmd` that sends partial string updates
|
||||
- Growth/status widgets → `bubbles/table` or custom rendering
|
||||
|
||||
**Improvements the language enables:**
|
||||
- True concurrent streaming: the Go operator can push partial results to the TUI via Go channels while the model is still generating — Python can't do this because the GIL serialises everything
|
||||
- Sub-millisecond rendering: Go's zero-allocation string building means the TUI renders at 60fps without GC pauses
|
||||
- Statically linked binary: deploy the TUI as a single file, no Python runtime, no virtual environment, no pip install
|
||||
|
||||
---
|
||||
|
||||
## CI STACKING PROTOCOL
|
||||
|
||||
The CI pipeline is proven — 2,300+ tests, 25 canaries, required checks on master. Use it as a throughput engine:
|
||||
|
||||
1. Submit PR after PR after PR. Don't wait for one to merge before starting the next.
|
||||
2. If CI raises an issue, DON'T STOP the current work. Note it, continue.
|
||||
3. After every 5 PR submissions, go back and address the accumulated CI issues in one batch.
|
||||
4. The merge-robot and auto-version handle the merging — you keep producing.
|
||||
5. If a required check fails on master, that's the one thing that stops the conveyor. Fix it immediately.
|
||||
|
||||
**The principle**: CI is the quality gate, not the bottleneck. It runs while you work. Issues get batch-fixed. The conveyor keeps moving.
|
||||
|
||||
---
|
||||
|
||||
## GITEA EPIC STRUCTURE
|
||||
|
||||
The FIRST Gitea task: **Epic: "Full Dichotomy Rebase"** containing:
|
||||
- [ ] Wave 0: Infrastructure (henxels scope, umbrella manifest, scaffolding protocol, CI)
|
||||
- [ ] Wave 4: Go reactive infrastructure (14 sub-epics)
|
||||
- [ ] Wave 4b: Go tool execution (3 sub-epics)
|
||||
- [ ] Wave 5a: Go model/provider (10 sub-epics, folded into 1 binary)
|
||||
- [ ] Wave 5b: Go operator (19 sub-epics, folded into 1 binary)
|
||||
- [ ] Wave 5c: Go memory operations (8 sub-epics)
|
||||
- [ ] Wave 6a: Rust structural core (30 sub-epics)
|
||||
- [ ] Wave 6b: Rust cognition (30 sub-epics)
|
||||
- [ ] Wave 6c: Rust remaining (25 sub-epics)
|
||||
- [ ] Wave 7: Bubble Tea TUI (7 sub-epics)
|
||||
|
||||
Each sub-epic contains the HOW instructions (the seven-step process), the language advantage notes, the parity test spec, and the CI registration step.
|
||||
|
||||
MiMoCode tasks mirror the same tree.
|
||||
|
||||
---
|
||||
|
||||
## WHAT I STILL NEED FROM YOU
|
||||
|
||||
1. **The cgo pattern** — Go calls Rust `.so` files via cgo. The Rust crates don't change, only the caller changes from Python-ctypes to Go-cgo. Is this the membrane you want?
|
||||
|
||||
2. **The Bubble Tea ecosystem** — I've listed every addon above. Do you want any specific visual features beyond what's listed?
|
||||
|
||||
3. **The umbrella answer** — the spine relies on umbrellas (umbrellas are the input, spine is the consumer). Both need updating. Is this how you understood it?
|
||||
|
||||
4. **The CI stacking** — submit PRs continuously, batch CI fixes every 5 submissions. Does this match what you described?
|
||||
|
||||
5. **Approve to start Wave 0** — henxels scope, umbrella manifest, scaffolding protocol, CI update, Gitea epic. This is the foundation everything else builds on.
|
||||
@@ -1,274 +0,0 @@
|
||||
# TRANCHE: THE FULL DICHOTOMY REBASE — every Python module replaced
|
||||
|
||||
_Presented for operator approval per TRANCHE-TEMPLATE.md §4. Nick's mandate: "go through the whole codebase and replace it with the dichotomy." Measured: 180 Python files, 68,224 lines. Target: 0 Python logic files (TUI stays last per plan, test infra stays as test infra)._
|
||||
|
||||
---
|
||||
|
||||
## §0 — GROUNDING (measured, not guessed)
|
||||
|
||||
### The honest numbers
|
||||
|
||||
| Language | Files | Lines | % | Status |
|
||||
|---|---|---|---|---|
|
||||
| Python | 180 | 68,224 | 70% | **THE TARGET — every module ported** |
|
||||
| Rust | 106 | 27,304 | 28% | 10 crates exist, 85 more modules to port |
|
||||
| Go | 7 | 1,125 | 1% | 2 modules exist, 55 more to port |
|
||||
| **Total** | **293** | **96,653** | | |
|
||||
|
||||
### The corrected dichotomy (re-classified 2026-10-06, 64ba7cf)
|
||||
|
||||
| Side | Modules | Python lines to replace | Role |
|
||||
|---|---|---|---|
|
||||
| **GO** | 57 | 32,081 | The reactive shell: initiates, responds, routes, interfaces |
|
||||
| **RUST** | 85 | 25,218 | The deterministic backend: computes, stores, pure functions |
|
||||
| **TUI** | 7 | 5,435 | Textual UI — last per plan |
|
||||
| **TEST** | 29 | 5,397 | Test infrastructure — stays as test infra |
|
||||
|
||||
### Existing infrastructure (§0.2 — route through what exists)
|
||||
|
||||
- **CI pipeline**: `.gitea/workflows/ci.yml` — lint, unit-tests, go-surface, canary, best-practices, documentation, type-check, gitea-offline, required-checks
|
||||
- **Deploy pipeline**: `.gitea/workflows/deploy.yml` — event-driven CI qualification, stage/verify/promote
|
||||
- **Scaffolding**: `construction_interface.py` + `src/go/rune-entry/scaffold.go` — every module's port goes through a construction contract
|
||||
- **Canaries**: 25 registered in CI, each crate has its own parity battery
|
||||
- **Umbrella manifest**: `config/umbrellas.json` — 165 Python modules tracked (needs Rust/Go extension)
|
||||
- **Henxels**: `henxels.yaml` — structural contract, line caps, no-secrets, canary registration (needs Rust/Go scope)
|
||||
- **Gitea**: conductor/rune, required checks on master, merge-robot, auto-version
|
||||
|
||||
### Keep-greens (§0.5 — must stay green through every wave)
|
||||
|
||||
- Full test suite: 2,300+ tests, 0 failures
|
||||
- All 25 registered canaries
|
||||
- diff-cover ≥70% on changed lines
|
||||
- Silent-handler ratchet (BLE001 ≤345, S110 ≤75)
|
||||
- Henxels: all hold
|
||||
- Lint-baseline: no increase
|
||||
- Deploy: monotonic promotion, runtime verification
|
||||
|
||||
---
|
||||
|
||||
## §1 — OBJECTIVE
|
||||
|
||||
**Every Python module in `src/rune/` is replaced by its Go or Rust equivalent per the dichotomy. The TUI stays Python until Wave 7. Test infrastructure stays Python. The FFI boundary is the membrane between Go and Rust. Zero Python logic files remain (only the TUI shell and test files).**
|
||||
|
||||
Measured end-state: `ls src/rune/*.py | wc -l` returns ≤7 (TUI only) + test files. `src/go/` contains the full reactive runtime. `src/rust/` contains the full deterministic backend.
|
||||
|
||||
---
|
||||
|
||||
## §2 — WAVE STRUCTURE
|
||||
|
||||
### Wave 4: The Go reactive infrastructure (14 modules, ~5,271 lines)
|
||||
|
||||
The backbone that everything else routes through. These are the modules that make the system *respond*.
|
||||
|
||||
| Module | Python lines | Go target | Notes |
|
||||
|---|---|---|---|
|
||||
| event_bus | 244 | **DONE** (src/go/event-bus/) | Same events.jsonl, same envelope |
|
||||
| event_envelope | 303 | src/go/event-bus/ | Envelope type in the same binary |
|
||||
| message_queue | 10KB | src/go/message-queue/ | Durable queue |
|
||||
| hook_engine | 28KB | src/go/hook-engine/ | Plugin dispatch |
|
||||
| microkernel | 14KB | src/go/microkernel/ | Hook lifecycle |
|
||||
| subsystem_health | 6KB | src/go/subsystem-health/ | Failure tiers |
|
||||
| parallel_processor | 5KB | src/go/parallel-processor/ | Goroutines |
|
||||
| work_manager | 20KB | src/go/work-manager/ | Work dispatch |
|
||||
| failure_auto_filer | 21KB | src/go/failure-filer/ | Auto-filing |
|
||||
| cache | 16KB | src/go/cache/ | Connection pooling |
|
||||
| connection_pool | 3KB | src/go/connection-pool/ | Pooled connections |
|
||||
| cron_engine | 14KB | src/go/cron-engine/ | Scheduled tasks |
|
||||
| night_mode | 14KB | src/go/night-mode/ | Night consolidation |
|
||||
| recall_router | 5KB | src/go/recall-router/ | Memory routing |
|
||||
|
||||
**Entry condition**: event_bus already landed. **Exit condition**: all 14 modules exist as Go binaries, Python versions delegate or are deleted, CI go-surface job passes.
|
||||
|
||||
### Wave 4b: The Go tool execution layer (3 modules, ~3,079 lines)
|
||||
|
||||
| Module | Python lines | Go target |
|
||||
|---|---|---|
|
||||
| tool_executor | 73KB | **STARTED** (src/go/tool-executor/) |
|
||||
| tool_protocol | 16KB | src/go/tool-executor/ |
|
||||
| local_tool_runtime | 35KB | src/go/tool-executor/ |
|
||||
|
||||
**Exit condition**: tool executor handles all operations in Go, Python delegates via subprocess, approval machinery documented.
|
||||
|
||||
### Wave 5a: The Go model/provider layer (10 modules, ~3,398 lines)
|
||||
|
||||
| Module | Python lines | Go target |
|
||||
|---|---|---|
|
||||
| model_connect | 16KB | src/go/model-connect/ |
|
||||
| model_profiles | 16KB | src/go/model-connect/ |
|
||||
| model_registry | 6KB | src/go/model-connect/ |
|
||||
| model_routing | 16KB | src/go/model-connect/ |
|
||||
| openai_compat_transport | 10KB | src/go/model-connect/ |
|
||||
| provider_budget | 12KB | src/go/model-connect/ |
|
||||
| provider_context | 2KB | src/go/model-connect/ |
|
||||
| provider_registry | 23KB | src/go/model-connect/ |
|
||||
| standardized_providers | 9KB | src/go/model-connect/ |
|
||||
| tiered_executor | 9KB | src/go/model-connect/ |
|
||||
|
||||
**Exit condition**: all model/provider operations in Go, Ollama + OpenAI-compatible connections working.
|
||||
|
||||
### Wave 5b: The Go operator (19 modules, ~9,637 lines)
|
||||
|
||||
The biggest wave. The operator turn loop, routing, and the modules that serve it.
|
||||
|
||||
| Module | Python lines | Notes |
|
||||
|---|---|---|
|
||||
| rune_operator | 126KB | THE core — turn loop, task management |
|
||||
| adaptive_router | 23KB | Route decisions |
|
||||
| build_mode | 20KB | Build orchestration |
|
||||
| builder_bridge | 12KB | Builder dispatch |
|
||||
| builder_bridge_cli | 1KB | CLI surface |
|
||||
| core_server | 9KB | HTTP server |
|
||||
| persona_definition | 7KB | Persona loading |
|
||||
| voicebox | 4KB | Voice |
|
||||
| voice_injector | 3KB | Voice injection |
|
||||
| release_notes | 18KB | Release generation |
|
||||
| auto_context | 8KB | Auto context |
|
||||
| auto_tasks | 15KB | Auto tasks |
|
||||
| event_wait | 23KB | Event-driven waits |
|
||||
| evidence_probe | 7KB | Evidence probes |
|
||||
| forge | 5KB | Forge adapter |
|
||||
| forge_client | 7KB | Forge client |
|
||||
| goal | 14KB | Goal management |
|
||||
| growth_delta | 16KB | Growth tracking |
|
||||
| warm_router | 55KB | Warm routing |
|
||||
|
||||
**Exit condition**: the operator turn loop runs in Go, routes through Go model connections, dispatches to Rust kernels via FFI.
|
||||
|
||||
### Wave 5c: The Go memory operations (8 modules, ~8,240 lines)
|
||||
|
||||
| Module | Python lines | Notes |
|
||||
|---|---|---|
|
||||
| memory_consolidation | 31KB | Consolidation operations (kernel already in Rust) |
|
||||
| memory_store | 99KB | THE memory store — SQLite operations |
|
||||
| curator | 70KB | Memory curation |
|
||||
| sleep_time | 38KB | Sleep-time consolidation |
|
||||
| abstraction | 22KB | Fact extraction (kernel already in Rust) |
|
||||
| persona_gate | 24KB | Persona gating |
|
||||
| witness | 15KB | Witness reflection |
|
||||
| stage_guards | 12KB | Stage guards |
|
||||
|
||||
**Exit condition**: memory operations run in Go, calling Rust kernels for the deterministic compute.
|
||||
|
||||
### Wave 6: The Rust deterministic backend (85 modules, ~25,218 lines)
|
||||
|
||||
Three sub-waves by dependency order:
|
||||
|
||||
**Wave 6a** (30 modules, ~11,515 lines): the structural core — spine, structural_store, construction_*, contracts, capability_*, audit_ledger, behaviour_ledger, claim_audit, etc.
|
||||
|
||||
**Wave 6b** (30 modules, ~6,849 lines): the cognition layer — drift_*, graph_memory, memory_selector, identity_anchors, pins, salience_gate, self_improve, token_optimizer, etc.
|
||||
|
||||
**Wave 6c** (25 modules, ~6,854 lines): the remaining modules — voice_hybrid, voice_sync, prompt_sync, time_awareness, toolchain, verification_layer, etc.
|
||||
|
||||
**Exit condition**: every deterministic module exists as a Rust function in a crate, the Python version is a thin FFI caller or deleted.
|
||||
|
||||
### Wave 7: The TUI + test infrastructure (36 modules, ~10,832 lines)
|
||||
|
||||
The TUI stays Python (Textual is Python-native) but its backend calls go through the Go/Rust dichotomy. Test infrastructure stays Python (pytest is Python-native).
|
||||
|
||||
**Exit condition**: the TUI is the only Python surface, everything behind it is Go/Rust.
|
||||
|
||||
---
|
||||
|
||||
## §3 — PER-FILE EPIC TEMPLATE (§7 anti-ballooning: 180 files → per-file epics)
|
||||
|
||||
Each file's port gets ONE epic. The epic body contains:
|
||||
|
||||
1. **File identity**: `src/rune/<module>.py` — N lines, M functions, K classes
|
||||
2. **Three questions**: (a) can it be IMPROVED in the target language? (b) does it need FIXING? (c) are there MISSING CONNECTORS?
|
||||
3. **Language assessment**: confirmed GO/RUST per classification, with the evidence
|
||||
4. **Constraint context**: which henxels, line caps, canary requirements apply
|
||||
5. **Pipeline plan**: branch name, PR route, canary battery spec
|
||||
6. **Verification**: the specific tests + canaries that prove the port
|
||||
7. **Provenance**: links to the wave, the tranche, the classification record
|
||||
|
||||
---
|
||||
|
||||
## §4 — DECISION RUBRIC
|
||||
|
||||
Per-unit language decisions are made against:
|
||||
|
||||
1. **Does the module initiate/respond/route?** → Go
|
||||
2. **Does it compute/store/pure-function?** → Rust
|
||||
3. **Does it have BOTH?** → Hybrid: Go front end calls Rust kernel via FFI (contracted membrane junction)
|
||||
4. **Is it the TUI?** → Python (last)
|
||||
5. **Is it test infrastructure?** → Python (stays)
|
||||
|
||||
Evidence required: the module's actual imports, its primary purpose, its callers, and what breaks if it's removed.
|
||||
|
||||
---
|
||||
|
||||
## §5 — PIPELINE ROUTING
|
||||
|
||||
Every port flows through:
|
||||
|
||||
1. **Construction contract**: `rune scaffold submit-need` → decision → contract → building
|
||||
2. **Branch**: `feat/port-<module>-to-<lang>` from master
|
||||
3. **Implementation**: Go module in `src/go/<name>/` or Rust module in `src/rust/<crate>/`
|
||||
4. **Python oracle**: the original Python function preserved as `_py_<function>` for parity
|
||||
5. **Delegation**: the Python public delegates to the Go/Rust implementation
|
||||
6. **Canary**: a parity battery proving kernel↔oracle equivalence
|
||||
7. **CI**: the canary registered in `.gitea/workflows/ci.yml`
|
||||
8. **PR**: → master, required checks, merge-robot
|
||||
9. **Deploy**: auto-version bump, deploy pipeline, runtime verification
|
||||
|
||||
---
|
||||
|
||||
## §6 — VERIFICATION GATES
|
||||
|
||||
Per-wave exit:
|
||||
- All modules in the wave exist as Go/Rust implementations
|
||||
- Python versions delegate (or are deleted if nothing calls them)
|
||||
- CI go-surface job passes (for Go modules)
|
||||
- CI canary job passes (for Rust kernels)
|
||||
- Full test suite green
|
||||
- diff-cover ≥70% on changed lines
|
||||
- Deploy advances the current symlink
|
||||
|
||||
Per-tranche exit:
|
||||
- `ls src/rune/*.py` returns ≤7 files (TUI only)
|
||||
- Full test suite green
|
||||
- All canaries green
|
||||
- All henxels hold
|
||||
- Deploy verified at the final version
|
||||
|
||||
---
|
||||
|
||||
## §7 — RISK REGISTER
|
||||
|
||||
| Risk | Prevention | Detection |
|
||||
|---|---|---|
|
||||
| Big-bang rewrite breaks everything | Incremental waves, each independently deployable | CI red on any wave |
|
||||
| Dual-truth drift (Python and Go/Rust diverge) | Parity canaries, _py_ oracles | Canary failure |
|
||||
| Broken keep-greens | Named up front, checked per-wave | CI red |
|
||||
| Silent scope creep | Per-file epics with explicit scope | Code review |
|
||||
| FFI boundary breaks | CC_RUST_LIB/SC_RUST_LIB env contract | Kernel probe test |
|
||||
| Memory store data loss | SQLite retained, reads proven byte-identical | Canary hash check |
|
||||
| Operator turn loop regression | Full test suite + runtime verification | Deploy verification |
|
||||
| Henxels line-cap violations | Carve before commit (spine_language pattern) | CI lint red |
|
||||
| New module without canary | New-module henxel | CI lint red |
|
||||
|
||||
---
|
||||
|
||||
## §8 — ROLLBACK / KNOWN-GOOD
|
||||
|
||||
Each wave is independently deployable. If a wave breaks:
|
||||
1. The Python version is still in the tree (delegation, not deletion)
|
||||
2. `RUNE_COGNITION_CORE=python` pins the fallback
|
||||
3. The deploy symlink can be pointed back to the previous revision
|
||||
4. Git revert the wave's merge commit
|
||||
|
||||
---
|
||||
|
||||
## §9 — SCALE HONESTY
|
||||
|
||||
This is **weeks of work, not hours**. 180 modules at ~1-2 modules per session = 90-180 sessions. The previous attempt (R2) ported 10 crates + 2 Go modules in multiple sessions. This tranche is the FULL job.
|
||||
|
||||
The wave structure is designed for incremental progress: each wave is independently deployable, each module's port is independently verifiable, and the system works at every intermediate state. The Python versions delegate to the Go/Rust implementations — they don't get deleted until the port is proven.
|
||||
|
||||
---
|
||||
|
||||
## §10 — APPROVAL GATE
|
||||
|
||||
This tranche is presented for operator approval. The operator reads the wave structure, the module assignments, the per-wave exit conditions, and either approves (execution starts at Wave 4) or requests changes.
|
||||
|
||||
The previous attempt (R2) ported 10 crates + 2 Go modules — less than 10% of the codebase. This tranche is the FULL job: every module, every line, every language decision, with the dichotomy honestly applied.
|
||||
@@ -1,196 +0,0 @@
|
||||
# Total-Rebase Inventory (R2 Wave 0.1) — measured 2026-10-04
|
||||
|
||||
Generated from `store/rebase/inventory.json` (AST function-level extraction) +
|
||||
`store/rebase/classification.json` (import/content evidence per module).
|
||||
Placement law: reactive/initiating/user-facing/network/turn-time → GO;
|
||||
deterministic/stateful/storage/cognition → RUST; Textual rendering → TUI-LAST;
|
||||
pure compute with no I/O markers defaults to the deterministic backend.
|
||||
|
||||
## Totals
|
||||
|
||||
| Side | Modules | Lines | Functions |
|
||||
|---|---|---|---|
|
||||
| GO | 43 | 19495 | 708 |
|
||||
| RUST | 93 | 36215 | 1091 |
|
||||
| TUI-LAST | 7 | 5438 | 225 |
|
||||
| TEST-INFRA | 29 | 5395 | 158 |
|
||||
| RETIRES | 2 | 93 | 9 |
|
||||
|
||||
## Per-module classification (evidence-carrying)
|
||||
|
||||
| Module | Side | Lines | Functions | Evidence |
|
||||
|---|---|---|---|---|
|
||||
| rune_tui | TUI-LAST | 4041 | 166 | textual/rich imports: ['rich', 'textual'] |
|
||||
| rune_operator | GO | 2697 | 68 | network/concurrency imports: ['threading', 'urllib']; reactive/initiating domain |
|
||||
| memory_store | RUST | 2435 | 56 | sqlite3 (storage-backed); network/concurrency imports: ['subprocess']; deterministic/state domain |
|
||||
| curator | RUST | 1838 | 43 | sqlite3 (storage-backed); network/concurrency imports: ['subprocess']; deterministic/state domain |
|
||||
| tool_executor | GO | 1812 | 47 | network/concurrency imports: ['subprocess']; reactive/initiating domain |
|
||||
| warm_router | RUST | 1536 | 36 | sqlite3 (storage-backed); network/concurrency imports: ['subprocess']; reactive/initiating domain; deterministic/state domain |
|
||||
| construction_interface | RUST | 1039 | 25 | deterministic/state domain |
|
||||
| spine | RUST | 1019 | 31 | deterministic/state domain |
|
||||
| sleep_time | RUST | 971 | 25 | sqlite3 (storage-backed); network/concurrency imports: ['subprocess', 'urllib']; deterministic/state domain |
|
||||
| construction_decision | RUST | 949 | 18 | deterministic/state domain |
|
||||
| capability_broker | RUST | 900 | 21 | deterministic/state domain |
|
||||
| hook_engine | GO | 860 | 8 | reactive/initiating domain |
|
||||
| scaffold | RUST | 854 | 31 | network/concurrency imports: ['subprocess']; deterministic/state domain |
|
||||
| local_tool_runtime | GO | 806 | 32 | network/concurrency imports: ['threading', 'urllib']; reactive/initiating domain |
|
||||
| context_broker | GO | 768 | 23 | network/concurrency imports: ['threading'] |
|
||||
| elastic_cognition | RUST | 765 | 13 | network/concurrency imports: ['urllib']; deterministic/state domain |
|
||||
| memory_consolidation | RUST | 733 | 20 | network/concurrency imports: ['subprocess']; deterministic/state domain |
|
||||
| provider_registry | GO | 666 | 28 | network/concurrency imports: ['threading', 'urllib']; reactive/initiating domain |
|
||||
| persona_gate | RUST | 661 | 21 | sqlite3 (storage-backed); network/concurrency imports: ['subprocess', 'urllib']; deterministic/state domain |
|
||||
| structural_store | RUST | 656 | 33 | deterministic/state domain |
|
||||
| contracts | RUST | 626 | 7 | deterministic/state domain |
|
||||
| adaptive_router | GO | 625 | 19 | reactive/initiating domain |
|
||||
| work_manager | GO | 591 | 25 | reactive/initiating domain |
|
||||
| abstraction | RUST | 587 | 12 | sqlite3 (storage-backed); network/concurrency imports: ['urllib']; deterministic/state domain |
|
||||
| construction_intent | RUST | 555 | 16 | deterministic/state domain |
|
||||
| canary_audit_ledger | TEST-INFRA | 540 | 2 | canary/test module |
|
||||
| safety_override | RUST | 530 | 18 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| failure_auto_filer | GO | 527 | 28 | network/concurrency imports: ['threading'] |
|
||||
| build_mode | GO | 517 | 34 | network/concurrency imports: ['subprocess'] |
|
||||
| drift_core | RUST | 517 | 14 | deterministic/state domain |
|
||||
| event_wait | GO | 517 | 14 | network/concurrency imports: ['subprocess', 'urllib']; reactive/initiating domain |
|
||||
| tui_validator | TUI-LAST | 514 | 13 | tui family |
|
||||
| memory_selector | RUST | 511 | 14 | deterministic/state domain |
|
||||
| system_registry | RUST | 501 | 14 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| construction_pattern | RUST | 496 | 13 | deterministic/state domain |
|
||||
| cache | GO | 492 | 17 | sqlite3 (storage-backed); network/concurrency imports: ['threading'] |
|
||||
| claim_audit | RUST | 483 | 14 | sqlite3 (storage-backed); deterministic/state domain |
|
||||
| graph_memory | RUST | 474 | 9 | sqlite3 (storage-backed); deterministic/state domain |
|
||||
| identity_anchors | RUST | 474 | 8 | deterministic/state domain |
|
||||
| model_connect | GO | 462 | 10 | network/concurrency imports: ['urllib']; reactive/initiating domain |
|
||||
| auto_tasks | GO | 460 | 14 | sqlite3 (storage-backed); network/concurrency imports: ['subprocess'] |
|
||||
| capability_fit | RUST | 455 | 14 | deterministic/state domain |
|
||||
| tool_protocol | GO | 455 | 27 | reactive/initiating domain |
|
||||
| drift_ledger | RUST | 453 | 16 | sqlite3 (storage-backed); deterministic/state domain |
|
||||
| witness | RUST | 451 | 10 | network/concurrency imports: ['urllib']; deterministic/state domain |
|
||||
| goal | RUST | 441 | 20 | network/concurrency imports: ['urllib']; deterministic/state domain |
|
||||
| release_notes | GO | 439 | 17 | network/concurrency imports: ['urllib'] |
|
||||
| cron_engine | GO | 436 | 28 | network/concurrency imports: ['subprocess', 'threading']; reactive/initiating domain |
|
||||
| model_profiles | GO | 435 | 15 | network/concurrency imports: ['urllib']; reactive/initiating domain |
|
||||
| microkernel | GO | 434 | 12 | network/concurrency imports: ['subprocess', 'threading'] |
|
||||
| model_routing | GO | 432 | 15 | network/concurrency imports: ['urllib']; reactive/initiating domain |
|
||||
| voice_hybrid | RUST | 421 | 10 | sqlite3 (storage-backed); reactive/initiating domain |
|
||||
| behavior | RUST | 407 | 9 | sqlite3 (storage-backed); deterministic/state domain |
|
||||
| token_optimizer | RUST | 407 | 23 | deterministic/state domain |
|
||||
| capability_ledger | RUST | 405 | 19 | deterministic/state domain |
|
||||
| night_mode | GO | 405 | 19 | network/concurrency imports: ['subprocess', 'threading', 'urllib'] |
|
||||
| chat_bubble | TUI-LAST | 401 | 16 | textual/rich imports: ['rich', 'textual'] |
|
||||
| growth_delta | RUST | 400 | 16 | network/concurrency imports: ['subprocess', 'urllib']; deterministic/state domain |
|
||||
| construction_mode | RUST | 395 | 5 | deterministic/state domain |
|
||||
| prompt_sync | RUST | 376 | 14 | sqlite3 (storage-backed) |
|
||||
| provider_budget | GO | 354 | 21 | network/concurrency imports: ['urllib']; reactive/initiating domain |
|
||||
| structural_model | RUST | 352 | 21 | deterministic/state domain |
|
||||
| programme_continuation | RUST | 349 | 11 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| canary_rune_serve | TEST-INFRA | 329 | 13 | canary/test module |
|
||||
| builder_bridge | GO | 326 | 11 | reactive/initiating domain |
|
||||
| canary_p1_07 | TEST-INFRA | 324 | 12 | canary/test module |
|
||||
| layout_contract | RUST | 316 | 6 | deterministic/state domain |
|
||||
| message_queue | GO | 316 | 14 | reactive/initiating domain |
|
||||
| drift_observability | RUST | 315 | 9 | deterministic/state domain |
|
||||
| build_basis | RUST | 314 | 12 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| canary_p0_07 | TEST-INFRA | 310 | 11 | canary/test module |
|
||||
| drift_compression | RUST | 307 | 12 | deterministic/state domain |
|
||||
| event_envelope | GO | 303 | 8 | reactive/initiating domain |
|
||||
| attention_capsule | RUST | 296 | 7 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| canary_p1_01 | TEST-INFRA | 294 | 14 | canary/test module |
|
||||
| voice_sync | RUST | 293 | 10 | sqlite3 (storage-backed); reactive/initiating domain |
|
||||
| drift_cache | RUST | 292 | 16 | deterministic/state domain |
|
||||
| outcome_ledger | RUST | 286 | 8 | sqlite3 (storage-backed); deterministic/state domain |
|
||||
| time_awareness | RUST | 283 | 15 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| tiered_executor | GO | 282 | 9 | network/concurrency imports: ['urllib'] |
|
||||
| stage_guards | RUST | 281 | 11 | network/concurrency imports: ['subprocess']; deterministic/state domain |
|
||||
| standardized_providers | GO | 281 | 5 | reactive/initiating domain |
|
||||
| canary_p1_06 | TEST-INFRA | 280 | 9 | canary/test module |
|
||||
| progressive_escalation | RUST | 279 | 9 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| pins | RUST | 276 | 11 | deterministic/state domain |
|
||||
| canary_p1_03 | TEST-INFRA | 271 | 9 | canary/test module |
|
||||
| auto_context | GO | 270 | 8 | network/concurrency imports: ['subprocess'] |
|
||||
| task_persist | RUST | 269 | 10 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| context_pressure | RUST | 262 | 9 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| canary_gitea_automation | TEST-INFRA | 261 | 3 | canary/test module |
|
||||
| canary_p1_02 | TEST-INFRA | 253 | 12 | canary/test module |
|
||||
| construction_patterns_builtin | RUST | 249 | 1 | deterministic/state domain |
|
||||
| canary_full_system | TEST-INFRA | 244 | 2 | canary/test module |
|
||||
| event_bus | GO | 244 | 7 | reactive/initiating domain |
|
||||
| salience_gate | RUST | 243 | 4 | deterministic/state domain |
|
||||
| self_improve | RUST | 242 | 5 | sqlite3 (storage-backed) |
|
||||
| construction_activation | RUST | 237 | 4 | deterministic/state domain |
|
||||
| toolchain | RUST | 236 | 7 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| task_gate | RUST | 235 | 8 | sqlite3 (storage-backed) |
|
||||
| core_server | GO | 234 | 13 | network/concurrency imports: ['http', 'urllib']; reactive/initiating domain |
|
||||
| audit_ledger | RUST | 231 | 8 | deterministic/state domain |
|
||||
| canary_native | TEST-INFRA | 231 | 3 | canary/test module |
|
||||
| openai_compat_transport | GO | 227 | 10 | network/concurrency imports: ['urllib']; reactive/initiating domain |
|
||||
| shard_manager | RUST | 223 | 10 | sqlite3 (storage-backed) |
|
||||
| response_adapter | RUST | 222 | 7 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| evidence_probe | RUST | 212 | 9 | network/concurrency imports: ['subprocess']; deterministic/state domain |
|
||||
| model_registry | GO | 211 | 8 | reactive/initiating domain |
|
||||
| persona_definition | GO | 210 | 8 | network/concurrency imports: ['subprocess'] |
|
||||
| cognitive_budgeter | RUST | 208 | 3 | deterministic/state domain |
|
||||
| canary_p0_04 | TEST-INFRA | 207 | 8 | canary/test module |
|
||||
| forge_client | GO | 203 | 19 | network/concurrency imports: ['urllib']; reactive/initiating domain |
|
||||
| dependency_tracker | RUST | 202 | 5 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| canary_context_broker | TEST-INFRA | 199 | 10 | canary/test module |
|
||||
| canary_p0_05 | TEST-INFRA | 199 | 16 | canary/test module |
|
||||
| testing_mode | RUST | 196 | 13 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| parallel_processor | GO | 194 | 17 | network/concurrency imports: ['threading'] |
|
||||
| canary_spine_meta | TEST-INFRA | 192 | 7 | canary/test module |
|
||||
| iteration | RUST | 190 | 8 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| verification_layer | RUST | 189 | 12 | deterministic/state domain |
|
||||
| subconscious_pass | RUST | 187 | 6 | deterministic/state domain |
|
||||
| ffi_query_memory_smoke | RUST | 182 | 5 | deterministic/state domain |
|
||||
| tier_manager | RUST | 182 | 9 | deterministic/state domain |
|
||||
| canary_tui_transport | TEST-INFRA | 174 | 7 | canary/test module |
|
||||
| behaviour_ledger | RUST | 173 | 13 | deterministic/state domain |
|
||||
| construction_commands | RUST | 173 | 4 | deterministic/state domain |
|
||||
| canary_tui_drift | TEST-INFRA | 170 | 2 | canary/test module |
|
||||
| intent_continuity | RUST | 168 | 11 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| rune_profiler | RUST | 165 | 3 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| inference_trace | RUST | 164 | 6 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| ms_loader | RUST | 163 | 16 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| subsystem_health | GO | 163 | 8 | network/concurrency imports: ['threading'] |
|
||||
| recall_router | GO | 162 | 3 | reactive/initiating domain |
|
||||
| voicebox | GO | 161 | 11 | network/concurrency imports: ['subprocess']; reactive/initiating domain |
|
||||
| canary_gitea_pipeline | TEST-INFRA | 159 | 2 | canary/test module |
|
||||
| forge | GO | 146 | 12 | network/concurrency imports: ['subprocess', 'urllib'] |
|
||||
| rune_graphic | TUI-LAST | 145 | 5 | textual/rich imports: ['rich'] |
|
||||
| connection_pool | GO | 144 | 9 | sqlite3 (storage-backed); network/concurrency imports: ['threading'] |
|
||||
| recall_uplift | RUST | 141 | 1 | sqlite3 (storage-backed) |
|
||||
| project_registry | RUST | 139 | 12 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| construction_depth | RUST | 138 | 2 | deterministic/state domain |
|
||||
| voice_injector | GO | 138 | 5 | reactive/initiating domain |
|
||||
| canary_rune_entry | TEST-INFRA | 137 | 3 | canary/test module |
|
||||
| construction_projection | RUST | 135 | 3 | deterministic/state domain |
|
||||
| rune_spinner | RUST | 130 | 5 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| tui_backlog | TUI-LAST | 125 | 5 | tui family |
|
||||
| warm_neuron_store | RUST | 122 | 6 | sqlite3 (storage-backed); deterministic/state domain |
|
||||
| drift_resume | RUST | 118 | 3 | deterministic/state domain |
|
||||
| wait_guard | RUST | 116 | 1 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| canary_conversation_state | TEST-INFRA | 115 | 2 | canary/test module |
|
||||
| canary_query_memory | TEST-INFRA | 110 | 2 | canary/test module |
|
||||
| failure_recovery | RUST | 108 | 1 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| graph_projection | RUST | 108 | 5 | deterministic/state domain |
|
||||
| tui_transport | TUI-LAST | 108 | 12 | tui family |
|
||||
| spine_loader | RUST | 105 | 7 | deterministic/state domain |
|
||||
| canary_unbounded | TEST-INFRA | 104 | 2 | canary/test module |
|
||||
| message_widgets | TUI-LAST | 104 | 8 | textual/rich imports: ['rich', 'textual'] |
|
||||
| cs_loader | RUST | 90 | 5 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| tc_loader | RUST | 88 | 5 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| canary_schema_migration | TEST-INFRA | 86 | 1 | canary/test module |
|
||||
| programme_gates | RUST | 85 | 6 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| structural_migration | RUST | 77 | 4 | deterministic/state domain |
|
||||
| memory_env | RETIRES | 72 | 8 | bootstrap glue subsumed by the Go runtime env contract |
|
||||
| impact_preview | RUST | 69 | 2 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| provider_context | GO | 48 | 1 | reactive/initiating domain |
|
||||
| wait_guard_corpus | RUST | 46 | 0 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| canary_cognitive_strata | TEST-INFRA | 44 | 1 | canary/test module |
|
||||
| builder_bridge_cli | GO | 42 | 1 | reactive/initiating domain |
|
||||
| route_risk_flags | RUST | 37 | 1 | no network/reactive markers — pure compute defaults to the deterministic backend |
|
||||
| canary_memory_synthesis | TEST-INFRA | 33 | 1 | canary/test module |
|
||||
| canary_resource_authority | TEST-INFRA | 33 | 1 | canary/test module |
|
||||
| canary_surface_parity | TEST-INFRA | 33 | 1 | canary/test module |
|
||||
| canary_orchestration_foundation | TEST-INFRA | 32 | 1 | canary/test module |
|
||||
| canary_gitea_delegation | TEST-INFRA | 31 | 1 | canary/test module |
|
||||
| __main__ | RETIRES | 21 | 1 | bootstrap glue subsumed by the Go runtime env contract |
|
||||
+1
-2
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "rune"
|
||||
version = "0.105.0"
|
||||
version = "0.87.0"
|
||||
description = "Rune — a stateful coding assistant with persistent memory, orchestration, and TUI"
|
||||
requires-python = ">=3.10"
|
||||
|
||||
@@ -16,7 +16,6 @@ dependencies = [
|
||||
"aiohttp>=3.9.0",
|
||||
"websockets>=12.0",
|
||||
"psutil>=5.9.0",
|
||||
"pillow>=10.0",
|
||||
"pyyaml>=6.0",
|
||||
]
|
||||
|
||||
|
||||
+1
-5
@@ -29,10 +29,6 @@
|
||||
"**/__pycache__"
|
||||
],
|
||||
"extraPaths": [
|
||||
"scripts",
|
||||
"src/rune",
|
||||
"shared",
|
||||
"src/rust/evidence_provenance",
|
||||
"src/rust/query_memory"
|
||||
"scripts"
|
||||
]
|
||||
}
|
||||
+10
-12
@@ -1,8 +1,8 @@
|
||||
# This file was autogenerated by uv via the following command:
|
||||
# uv pip compile pyproject.toml -o requirements-ci.txt --extra dev --extra memory --python-version 3.11
|
||||
# uv pip compile pyproject.toml -o /tmp/req_new.txt --extra dev --extra memory --python-version 3.11
|
||||
aiohappyeyeballs==2.7.1
|
||||
# via aiohttp
|
||||
aiohttp==3.14.4
|
||||
aiohttp==3.14.3
|
||||
# via rune (pyproject.toml)
|
||||
aiosignal==1.4.0
|
||||
# via aiohttp
|
||||
@@ -18,9 +18,9 @@ certifi==2026.7.22
|
||||
# httpx
|
||||
chardet==7.6.0
|
||||
# via diff-cover
|
||||
coverage==7.16.2
|
||||
coverage==7.16.1
|
||||
# via rune (pyproject.toml)
|
||||
diff-cover==10.6.0
|
||||
diff-cover==10.5.1
|
||||
# via rune (pyproject.toml)
|
||||
frozenlist==1.8.0
|
||||
# via
|
||||
@@ -39,7 +39,7 @@ idna==3.20
|
||||
# anyio
|
||||
# httpx
|
||||
# yarl
|
||||
iniconfig==2.3.1
|
||||
iniconfig==2.3.0
|
||||
# via pytest
|
||||
jinja2==3.1.6
|
||||
# via diff-cover
|
||||
@@ -50,23 +50,21 @@ markdown-it-py==4.2.0
|
||||
# mdit-py-plugins
|
||||
# rich
|
||||
# textual
|
||||
markupsafe==3.0.4
|
||||
markupsafe==3.0.3
|
||||
# via jinja2
|
||||
mdit-py-plugins==0.6.1
|
||||
# via textual
|
||||
mdurl==0.1.2
|
||||
# via markdown-it-py
|
||||
multidict==6.9.1
|
||||
multidict==6.9.0
|
||||
# via
|
||||
# aiohttp
|
||||
# yarl
|
||||
nodeenv==1.11.0
|
||||
nodeenv==1.10.0
|
||||
# via pyright
|
||||
packaging==26.3
|
||||
# via pytest
|
||||
pillow==12.3.0
|
||||
# via rune (pyproject.toml)
|
||||
platformdirs==4.12.3
|
||||
platformdirs==4.11.11
|
||||
# via textual
|
||||
pluggy==1.6.0
|
||||
# via
|
||||
@@ -118,7 +116,7 @@ typing-extensions==4.16.0
|
||||
# pyright
|
||||
# textual
|
||||
# textual-autocomplete
|
||||
websockets==17.2
|
||||
websockets==17.1
|
||||
# via rune (pyproject.toml)
|
||||
yarl==1.25.1
|
||||
# via aiohttp
|
||||
+3
-17
@@ -148,18 +148,9 @@ def sha_branch(sha: str) -> str:
|
||||
|
||||
|
||||
def sha_on_master(sha: str) -> bool:
|
||||
"""SHA is an ancestor of master (local or remote-tracking refs).
|
||||
|
||||
M10 correction (2026-09-19): --all so a freshly fetched master
|
||||
(refs/remotes/gitea/master) counts; local branches alone go stale
|
||||
between fetches. derive_op_type refreshes refs before calling this.
|
||||
"""
|
||||
out = _git("branch", "--all", "--contains", sha)
|
||||
for l in out.splitlines():
|
||||
s = l.strip().removeprefix("remotes/").removesuffix(" *")
|
||||
if s == "master" or s.endswith("/master"):
|
||||
return True
|
||||
return False
|
||||
out = _git("branch", "--contains", sha)
|
||||
return any(l.strip().endswith("master") or l.strip() == "master"
|
||||
for l in out.splitlines())
|
||||
|
||||
|
||||
def open_pr_for_sha(sha: str) -> int | None:
|
||||
@@ -193,11 +184,6 @@ def derive_op_type(sha: str) -> tuple[str, str]:
|
||||
were created from model-supplied defaults and cannot be trusted.
|
||||
Never trusts model input.
|
||||
"""
|
||||
# 0. M10 correction (2026-09-19): refresh remote-tracking refs before
|
||||
# inference. A just-merged master commit is invisible to
|
||||
# branch --contains until refs are fetched; stale local git state
|
||||
# must never outrank repo truth. Bounded by GIT_TIMEOUT, fail-open.
|
||||
_git("fetch", "--quiet", "gitea", "+refs/heads/*:refs/remotes/gitea/*")
|
||||
for rec in _load_wait_records():
|
||||
if _rec_sha(rec) != sha:
|
||||
continue
|
||||
|
||||
@@ -1,286 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""dichotomy_audit.py — the honest completion instrument for the dichotomy rebase.
|
||||
|
||||
Function-level, not directory-level: a module counts as covered only when its
|
||||
PYTHON FUNCTIONS have identifiable counterparts in the Go/Rust implementation.
|
||||
A Go directory with 3 structs and none of the module's 70 functions is a
|
||||
facade, and this audit names it as one.
|
||||
|
||||
Matching rule (name-preserving ports): a Python function name matches when
|
||||
its snake_case form, or its Go/Rust camelCase/PascalCase form, appears in the
|
||||
candidate implementation sources. Deliberately strict — novel Go names that
|
||||
don't echo the Python names do NOT count, because unverifiable "trust me,
|
||||
it's in there somewhere" is exactly the failure mode this instrument exists
|
||||
to kill.
|
||||
|
||||
Usage: python3 scripts/dichotomy_audit.py [--write]
|
||||
--write regenerates docs/dichotomy-rebase-honest-audit.md
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
SRC = ROOT / "src" / "rune"
|
||||
GO = ROOT / "src" / "go"
|
||||
RUST = ROOT / "src" / "rust"
|
||||
REPORT = ROOT / "docs" / "dichotomy-rebase-honest-audit.md"
|
||||
CLASSIFICATION = ROOT / "store" / "rebase" / "classification.json"
|
||||
|
||||
TEST_PREFIXES = ("test_",)
|
||||
# Modules that stay Python by decision (test infra stays pytest)
|
||||
TEST_INFRA = {
|
||||
"conftest", "test_truth", "test_adaptive_router", "test_canaries",
|
||||
}
|
||||
RETIRES = {"memory_env", "__main__"}
|
||||
|
||||
|
||||
def snake_to_camel(name: str) -> list[str]:
|
||||
"""Candidate identifier forms for a Python name in Go/Rust sources."""
|
||||
parts = name.split("_")
|
||||
camel = parts[0] + "".join(p.capitalize() for p in parts[1:])
|
||||
pascal = "".join(p.capitalize() for p in parts)
|
||||
return [name, camel, pascal]
|
||||
|
||||
|
||||
def module_functions(path: Path) -> list[str]:
|
||||
"""Every function and method name defined in the module."""
|
||||
try:
|
||||
tree = ast.parse(path.read_text(encoding="utf-8", errors="replace"))
|
||||
except SyntaxError:
|
||||
return []
|
||||
names = []
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
||||
if node.name.startswith("__") and node.name.endswith("__"):
|
||||
continue # dunders are runtime machinery, not port surface
|
||||
names.append(node.name)
|
||||
return names
|
||||
|
||||
|
||||
def load_classification() -> dict:
|
||||
if CLASSIFICATION.exists():
|
||||
return json.loads(CLASSIFICATION.read_text())
|
||||
return {}
|
||||
|
||||
|
||||
def implementation_corpus() -> dict[str, str]:
|
||||
"""module-kebab -> concatenated Go/Rust source text for that module."""
|
||||
corpus: dict[str, str] = {}
|
||||
|
||||
for d in sorted(GO.iterdir()):
|
||||
if not d.is_dir():
|
||||
continue
|
||||
chunks = []
|
||||
for f in d.rglob("*.go"):
|
||||
if f.name.endswith("_test.go"):
|
||||
continue
|
||||
chunks.append(f.read_text(encoding="utf-8", errors="replace"))
|
||||
if chunks:
|
||||
corpus[d.name] = "\n".join(chunks)
|
||||
|
||||
# Survivor packages (per-crate Go membranes under cognition/)
|
||||
cog = GO / "cognition"
|
||||
if cog.exists():
|
||||
for d in sorted(cog.iterdir()):
|
||||
if d.is_dir():
|
||||
chunks = [f.read_text(encoding="utf-8", errors="replace")
|
||||
for f in d.rglob("*.go") if not f.name.endswith("_test.go")]
|
||||
if chunks:
|
||||
corpus[f"cognition-{d.name}"] = "\n".join(chunks)
|
||||
|
||||
for d in sorted(RUST.iterdir()):
|
||||
src = d / "src"
|
||||
if src.exists():
|
||||
chunks = [f.read_text(encoding="utf-8", errors="replace")
|
||||
for f in src.rglob("*.rs")]
|
||||
if chunks:
|
||||
corpus[d.name] = "\n".join(chunks)
|
||||
return corpus
|
||||
|
||||
|
||||
def module_to_keys(module_stem: str) -> list[str]:
|
||||
"""Candidate implementation keys for a Python module stem."""
|
||||
kebab = module_stem.replace("_", "-")
|
||||
keys = [kebab, module_stem]
|
||||
# Deep ports and multi-module binaries register aliases:
|
||||
aliases = {
|
||||
"rune_operator": ["operator", "operator-deep", "operator-support", "core-server"],
|
||||
"rune_tui": ["tui"],
|
||||
"rune_operator_cli": ["operator"],
|
||||
"memory_store": ["memory-ops", "memory-store-deep"],
|
||||
"warm_router": ["warm-router", "operator-support"],
|
||||
"tool_executor": ["tool-executor", "local-tool-runtime", "tool-protocol", "tool-protocol-rw"],
|
||||
"local_tool_runtime": ["local-tool-runtime", "operator"],
|
||||
"provider_registry": ["provider-registry", "model-connect"],
|
||||
"adaptive_router": ["adaptive-router", "operator-support"],
|
||||
"hook_engine": ["hook-engine"],
|
||||
"event_bus": ["event-bus"],
|
||||
"event_envelope": ["event-bus"],
|
||||
"message_queue": ["message-queue"],
|
||||
"subsystem_health": ["subsystem-health"],
|
||||
"parallel_processor": ["parallel-processor"],
|
||||
"connection_pool": ["connection-pool"],
|
||||
"recall_router": ["recall-router"],
|
||||
"cron_engine": ["cron-engine"],
|
||||
"cache": ["cache"],
|
||||
"night_mode": ["night-mode"],
|
||||
"work_manager": ["work-manager"],
|
||||
"failure_auto_filer": ["failure-filer"],
|
||||
"microkernel": ["microkernel"],
|
||||
"construction_interface": ["cognition-cognition", "cognition"],
|
||||
"construction_decision": ["cognition-cognition", "cognition"],
|
||||
"rune_spine": ["cognition-spine", "cognition"],
|
||||
"spine": ["cognition-spine", "cognition"],
|
||||
"memory_storage": ["cognition-storage", "cognition"],
|
||||
"memory_retrieval": ["cognition-retrieval", "cognition"],
|
||||
"scaffold_core": ["cognition-scaffold", "cognition"],
|
||||
"evidence_provenance": ["cognition-provenance", "cognition"],
|
||||
"memory_scoring": ["cognition-scoring", "cognition"],
|
||||
"capability_scoring": ["cognition-capability", "cognition"],
|
||||
"token_counting": ["cognition-token", "cognition"],
|
||||
"query_memory": ["cognition-query", "cognition"],
|
||||
}
|
||||
if module_stem in aliases:
|
||||
keys = aliases[module_stem] + keys
|
||||
# cognition_core broker.rs hosts many kernels
|
||||
if module_stem in {
|
||||
"tier_manager", "safety_override", "pins", "identity_anchors",
|
||||
"abstraction", "growth_delta", "witness", "persona_gate",
|
||||
"memory_consolidation", "drift_compression", "context_broker",
|
||||
"persona_definition", "goal",
|
||||
}:
|
||||
keys.append("cognition_core")
|
||||
keys.append("cognition-cognition")
|
||||
return keys
|
||||
|
||||
|
||||
def audit() -> dict:
|
||||
classification = load_classification()
|
||||
corpus = implementation_corpus()
|
||||
|
||||
rows = []
|
||||
for path in sorted(SRC.glob("*.py")):
|
||||
stem = path.stem
|
||||
if stem in RETIRES:
|
||||
rows.append({"module": stem, "lines": len(path.read_text(errors='replace').splitlines()),
|
||||
"fns": 0, "matched": 0, "side": "RETIRES", "status": "RETIRES", "missing": []})
|
||||
continue
|
||||
if stem.startswith(TEST_PREFIXES) or stem in TEST_INFRA:
|
||||
rows.append({"module": stem, "lines": len(path.read_text(errors='replace').splitlines()),
|
||||
"fns": 0, "matched": 0, "side": "TEST", "status": "TEST", "missing": []})
|
||||
continue
|
||||
fns = module_functions(path)
|
||||
lines = len(path.read_text(errors="replace").splitlines())
|
||||
entry = classification.get(stem) or classification.get(path.name) or {}
|
||||
side = entry.get("side", entry.get("language", "unclassified"))
|
||||
|
||||
sources = []
|
||||
for key in module_to_keys(stem):
|
||||
if key in corpus:
|
||||
sources.append(corpus[key])
|
||||
blob = "\n".join(sources)
|
||||
|
||||
matched, missing = 0, []
|
||||
for fn in fns:
|
||||
hits = any(cand in blob for cand in snake_to_camel(fn))
|
||||
if hits:
|
||||
matched += 1
|
||||
else:
|
||||
missing.append(fn)
|
||||
|
||||
ratio = matched / len(fns) if fns else (1.0 if lines < 30 else 0.0)
|
||||
if stem in RETIRES:
|
||||
status = "RETIRES"
|
||||
elif not blob:
|
||||
status = "NOT TOUCHED"
|
||||
elif ratio >= 0.8:
|
||||
status = "FULL"
|
||||
elif ratio >= 0.2:
|
||||
status = "PARTIAL"
|
||||
else:
|
||||
status = "NOT TOUCHED"
|
||||
rows.append({"module": stem, "lines": lines, "fns": len(fns),
|
||||
"matched": matched, "side": side, "status": status, "missing": missing[:12]})
|
||||
|
||||
return {"rows": rows}
|
||||
|
||||
|
||||
def summarize(result: dict) -> str:
|
||||
rows = result["rows"]
|
||||
runtime = [r for r in rows if r["status"] not in ("TEST", "RETIRES")]
|
||||
full = [r for r in runtime if r["status"] == "FULL"]
|
||||
partial = [r for r in runtime if r["status"] == "PARTIAL"]
|
||||
untouched = [r for r in runtime if r["status"] == "NOT TOUCHED"]
|
||||
total_fns = sum(r["fns"] for r in runtime)
|
||||
total_matched = sum(r["matched"] for r in runtime)
|
||||
total_lines = sum(r["lines"] for r in runtime)
|
||||
fn_pct = 100 * total_matched / total_fns if total_fns else 0
|
||||
|
||||
out = []
|
||||
out.append("# DICHOTOMY REBASE — HONEST AUDIT (function-level)")
|
||||
out.append("")
|
||||
out.append("_Regenerate with `python3 scripts/dichotomy_audit.py --write`. A module is FULL only when 80%+ of its Python functions have name-preserving counterparts in the Go/Rust implementation — directories without the functions are facades and count as NOT TOUCHED._")
|
||||
out.append("")
|
||||
out.append(f"**Function-level completion: {fn_pct:.0f}%** ({total_matched}/{total_fns} runtime functions matched)")
|
||||
out.append("")
|
||||
out.append("| Status | Modules | Lines | Meaning |")
|
||||
out.append("|---|---|---|---|")
|
||||
out.append(f"| FULL | {len(full)} | {sum(r['lines'] for r in full)} | 80%+ of functions ported |")
|
||||
out.append(f"| PARTIAL | {len(partial)} | {sum(r['lines'] for r in partial)} | 20–80% — real logic exists, gaps named below |")
|
||||
out.append(f"| NOT TOUCHED | {len(untouched)} | {sum(r['lines'] for r in untouched)} | no name-preserving implementation |")
|
||||
out.append(f"| Total runtime | {len(runtime)} | {total_lines} | |")
|
||||
out.append("")
|
||||
|
||||
if untouched:
|
||||
out.append("## NOT TOUCHED — the port queue, in priority order (largest first)")
|
||||
out.append("")
|
||||
out.append("| Module | Lines | Fns | Side |")
|
||||
out.append("|---|---|---|---|")
|
||||
for r in sorted(untouched, key=lambda r: -r["lines"]):
|
||||
out.append(f"| {r['module']} | {r['lines']} | {r['fns']} | {r['side']} |")
|
||||
out.append("")
|
||||
if partial:
|
||||
out.append("## PARTIAL — gaps to close (matched/total fns; first missing named)")
|
||||
out.append("")
|
||||
out.append("| Module | Lines | Coverage | Missing (first named) |")
|
||||
out.append("|---|---|---|---|")
|
||||
for r in sorted(partial, key=lambda r: -(r["fns"] - r["matched"])):
|
||||
miss = ", ".join(r["missing"][:6]) if r["missing"] else "(structural)"
|
||||
out.append(f"| {r['module']} | {r['lines']} | {r['matched']}/{r['fns']} | {miss} |")
|
||||
out.append("")
|
||||
out.append("## FULL — ported, parity-gated")
|
||||
out.append("")
|
||||
out.append("| Module | Lines | Fns | Side |")
|
||||
out.append("|---|---|---|---|")
|
||||
for r in sorted(full, key=lambda r: -r["lines"]):
|
||||
out.append(f"| {r['module']} | {r['lines']} | {r['matched']}/{r['fns']} | {r['side']} |")
|
||||
out.append("")
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
write = "--write" in sys.argv
|
||||
result = audit()
|
||||
report = summarize(result)
|
||||
if write:
|
||||
REPORT.write_text(report)
|
||||
print(f"written: {REPORT}")
|
||||
# stderr summary for the session log
|
||||
rows = result["rows"]
|
||||
runtime = [r for r in rows if r["status"] not in ("TEST", "RETIRES")]
|
||||
tf = sum(r["fns"] for r in runtime)
|
||||
tm = sum(r["matched"] for r in runtime)
|
||||
print(f"FUNCTION-LEVEL: {tm}/{tf} ({100*tm/tf if tf else 0:.0f}%) | "
|
||||
f"FULL {sum(1 for r in runtime if r['status']=='FULL')} | "
|
||||
f"PARTIAL {sum(1 for r in runtime if r['status']=='PARTIAL')} | "
|
||||
f"NOT TOUCHED {sum(1 for r in runtime if r['status']=='NOT TOUCHED')}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,71 +1,43 @@
|
||||
#!/usr/bin/env python3
|
||||
"""install_mimo_hook.py — T21.2 §21.2D (T22: multi-hook): canonical MiMo
|
||||
hook installer.
|
||||
"""install_mimo_hook.py — T21.2 §21.2D: canonical MiMo hook installer.
|
||||
|
||||
Canonical sources: config/mimo-hooks/*.ts
|
||||
Targets: ~/.mimocode/hooks/<same-name>.ts
|
||||
|
||||
Every hook is hash-verified after install; drift is detected in both
|
||||
directions. T22 added builder-bridge.ts to the managed set — it was
|
||||
previously installed by hand, unversioned, which is how it silently rotted
|
||||
(hardcoded ephemeral interpreter). A hook that reaches the builder must be
|
||||
version-controlled and drift-checked like any other authority.
|
||||
|
||||
Usage:
|
||||
python3 scripts/install_mimo_hook.py # sync all managed hooks
|
||||
python3 scripts/install_mimo_hook.py --check # verify only, install nothing
|
||||
"""
|
||||
Canonical source: config/mimo-hooks/event-wait-guard.ts
|
||||
Target: ~/.mimocode/hooks/event-wait-guard.ts
|
||||
Verifies hash after install. Detects drift in both directions."""
|
||||
import hashlib
|
||||
import shutil
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parent.parent
|
||||
CANONICAL_DIR = REPO / "config" / "mimo-hooks"
|
||||
TARGET_DIR = Path.home() / ".mimocode" / "hooks"
|
||||
|
||||
# The managed set. Adding a file here is what makes a hook version-controlled.
|
||||
MANAGED = ["event-wait-guard.ts", "builder-bridge.ts"]
|
||||
CANONICAL = Path(__file__).resolve().parent.parent / "config" / "mimo-hooks" / "event-wait-guard.ts"
|
||||
TARGET = Path.home() / ".mimocode" / "hooks" / "event-wait-guard.ts"
|
||||
|
||||
|
||||
def sha256(p: Path) -> str:
|
||||
return hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def sync_one(name: str, check_only: bool) -> bool:
|
||||
canonical = CANONICAL_DIR / name
|
||||
target = TARGET_DIR / name
|
||||
if not canonical.is_file():
|
||||
print(f"canonical source missing: {canonical}")
|
||||
return False
|
||||
canon_hash = sha256(canonical)
|
||||
if target.is_file() and sha256(target) == canon_hash:
|
||||
print(f"in-sync: {name} {canon_hash[:12]}")
|
||||
return True
|
||||
if check_only:
|
||||
state = "DRIFT" if target.is_file() else "MISSING"
|
||||
inst = sha256(target)[:12] if target.is_file() else "-"
|
||||
print(f"{state}: {name} canonical={canon_hash[:12]} installed={inst}")
|
||||
return False
|
||||
if target.is_file():
|
||||
print(f"DRIFT: {name} canonical={canon_hash[:12]} installed={sha256(target)[:12]}")
|
||||
else:
|
||||
print(f"hook missing at {target}")
|
||||
TARGET_DIR.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(canonical, target)
|
||||
if sha256(target) != canon_hash:
|
||||
print(f"INSTALL FAILED: {name} hash mismatch after copy")
|
||||
return False
|
||||
print(f"installed: {name} {canon_hash[:12]}")
|
||||
return True
|
||||
|
||||
|
||||
def main() -> int:
|
||||
check_only = "--check" in sys.argv
|
||||
ok = True
|
||||
for name in MANAGED:
|
||||
ok = sync_one(name, check_only) and ok
|
||||
return 0 if ok else 1
|
||||
if not CANONICAL.is_file():
|
||||
print(f"canonical source missing: {CANONICAL}")
|
||||
return 1
|
||||
canon_hash = sha256(CANONICAL)
|
||||
if TARGET.is_file():
|
||||
target_hash = sha256(TARGET)
|
||||
if target_hash == canon_hash:
|
||||
print(f"in-sync: {target_hash[:12]}")
|
||||
return 0
|
||||
print(f"DRIFT: canonical={canon_hash[:12]} installed={target_hash[:12]}")
|
||||
else:
|
||||
print(f"hook missing at {TARGET}")
|
||||
TARGET.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(CANONICAL, TARGET)
|
||||
installed_hash = sha256(TARGET)
|
||||
if installed_hash != canon_hash:
|
||||
print(f"INSTALL FAILED: hash mismatch after copy")
|
||||
return 1
|
||||
print(f"installed: {installed_hash[:12]}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""install_mimo_tools.py — canonical MiMo tool installer (TTY-repair tranche).
|
||||
|
||||
Canonical sources: config/mimo-tools/{bash.ts,await-operation.ts}
|
||||
Targets: ~/.mimocode/tools/{bash.ts,await-operation.ts}
|
||||
Verifies hashes after install; detects drift in both directions
|
||||
(the parity test reads these hashes).
|
||||
"""
|
||||
import hashlib
|
||||
import shutil
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parent.parent
|
||||
TOOLS = ["bash.ts", "await-operation.ts"]
|
||||
|
||||
|
||||
def sha256(p: Path) -> str:
|
||||
return hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
rc = 0
|
||||
for name in TOOLS:
|
||||
canon = REPO / "config" / "mimo-tools" / name
|
||||
target = Path.home() / ".mimocode" / "tools" / name
|
||||
if not canon.is_file():
|
||||
print(f"{name}: canonical source missing: {canon}")
|
||||
rc = 1
|
||||
continue
|
||||
canon_hash = sha256(canon)
|
||||
if target.is_file() and sha256(target) == canon_hash:
|
||||
print(f"{name}: in-sync {canon_hash[:12]}")
|
||||
continue
|
||||
drift = f"DRIFT canonical={canon_hash[:12]}"
|
||||
if target.is_file():
|
||||
drift += f" installed={sha256(target)[:12]}"
|
||||
else:
|
||||
drift += " installed=MISSING"
|
||||
print(f"{name}: {drift} — installing")
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(canon, target)
|
||||
if sha256(target) != canon_hash:
|
||||
print(f"{name}: INSTALL FAILED (hash mismatch after copy)")
|
||||
rc = 1
|
||||
else:
|
||||
print(f"{name}: installed {canon_hash[:12]}")
|
||||
return rc
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -42,29 +42,6 @@ def main() -> int:
|
||||
"exit_code": 0 if result == "success" else 1,
|
||||
"completed_at": time.time(),
|
||||
}
|
||||
# R8 lost-event failure-recovery: operation-scoped fault injection.
|
||||
# A rule keyed by the EXACT operation_id suppresses BOTH normal
|
||||
# delivery channels (durable completion file AND bridge POST), so the
|
||||
# waiter's watchdog/failure-detector path is the only route to truth.
|
||||
# Disabled by default (no rule file => zero behavior change) and
|
||||
# observable: every decision is recorded in the R8 fault log.
|
||||
try:
|
||||
import r8_fault # noqa: E402 — sibling module
|
||||
if r8_fault.should_suppress(payload["operation_id"]):
|
||||
r8_fault.record(payload["operation_id"], "suppressed",
|
||||
{"sha": sha, "exit_code": payload["exit_code"],
|
||||
"source_terminal_at": payload["completed_at"]})
|
||||
print("notify-event-bridge: R8 fault injection — completion "
|
||||
f"event intentionally suppressed for "
|
||||
f"{payload['operation_id']} (no .done file, no POST); "
|
||||
"watchdog authority recovery is the expected path",
|
||||
flush=True)
|
||||
return 0
|
||||
r8_fault.record(payload["operation_id"], "delivered_normally",
|
||||
{"sha": sha, "rule_active": False})
|
||||
except Exception as exc: # noqa: BLE001 — fault seam must never break delivery
|
||||
print(f"notify-event-bridge: R8 fault-seam probe failed ({exc}); "
|
||||
"continuing with normal delivery", flush=True)
|
||||
# R3 durable delivery: write the completion file FIRST — it works even
|
||||
# if the bridge daemon is down, and the atomic rename means any waiter
|
||||
# (inotify-watching or starting later) sees a complete file or none.
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""r8_fault.py — REAL_ASYNC_BRIDGE R8: operation-scoped lost-event fault
|
||||
injection (evidence-only harness).
|
||||
|
||||
DESIGN CONTRACT (R8 §3):
|
||||
disabled by default no rule file -> zero behavior change
|
||||
operation-scoped rule keyed by EXACT operation_id
|
||||
reversible delete the rule file / rule entry
|
||||
observable every decision appended to a JSONL log
|
||||
cannot affect other waits rule file checked by operation_id only
|
||||
|
||||
The ONLY consumer is scripts/notify_event_bridge.py: before normal
|
||||
delivery it consults should_suppress(operation_id). Suppression means:
|
||||
- NO durable completion file is written
|
||||
- NO bridge POST (no /process-event wake)
|
||||
- the suppression decision is recorded as R8 fault evidence
|
||||
Nothing else in the stack reads the rule. The daemon, waitstore,
|
||||
authority verification, and completion-file machinery are untouched.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
RUNE_WR_ROOT = os.environ.get("RUNE_WR_ROOT") or os.environ.get("WR_ROOT") or "/mnt/workdrive/wr-bridge"
|
||||
RULES_PATH = Path(RUNE_WR_ROOT) / "r8_suppress_rules.json"
|
||||
FAULT_LOG = Path(RUNE_WR_ROOT) / "r8_fault_log.jsonl"
|
||||
|
||||
REASON = "event intentionally suppressed for R8 lost-event failure-recovery"
|
||||
|
||||
|
||||
def _rules() -> dict:
|
||||
"""Read the rule file. Absent/unreadable => no suppression (fail-open
|
||||
to NORMAL delivery; the fault must never take the healthy path down)."""
|
||||
try:
|
||||
return json.loads(RULES_PATH.read_text())
|
||||
except Exception: # noqa: BLE001 — absent rule file is the default state
|
||||
return {}
|
||||
|
||||
|
||||
def lookup(operation_id: str) -> dict | None:
|
||||
"""Return the active suppression rule for EXACTLY this operation_id,
|
||||
or None. Expired rules are ignored (not deleted — deletion is the
|
||||
operator's explicit disable action)."""
|
||||
spec = _rules()
|
||||
if not spec.get("enabled"):
|
||||
return None
|
||||
rule = spec.get("operations", {}).get(operation_id)
|
||||
if not rule:
|
||||
return None
|
||||
expires = rule.get("expires_at")
|
||||
if expires:
|
||||
try:
|
||||
if time.time() > time.mktime(time.strptime(expires, "%Y-%m-%dT%H:%M:%SZ")) - time.timezone:
|
||||
return None
|
||||
except ValueError:
|
||||
return None
|
||||
return rule
|
||||
|
||||
|
||||
def should_suppress(operation_id: str) -> bool:
|
||||
return lookup(operation_id) is not None
|
||||
|
||||
|
||||
def record(operation_id: str, stage: str, extra: dict | None = None) -> None:
|
||||
"""Append a durable fault-evidence line (best-effort, never raises)."""
|
||||
try:
|
||||
entry = {
|
||||
"at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
"operation_id": operation_id,
|
||||
"reason": REASON,
|
||||
"stage": stage,
|
||||
**(extra or {}),
|
||||
}
|
||||
FAULT_LOG.parent.mkdir(parents=True, exist_ok=True)
|
||||
with FAULT_LOG.open("a") as f:
|
||||
f.write(json.dumps(entry, sort_keys=True) + "\n")
|
||||
except OSError as exc: # noqa: BLE001 — evidence logging must never break CI
|
||||
print(f"r8_fault: evidence log write failed: {exc}", file=sys.stderr)
|
||||
@@ -1,214 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Tranche R1 Wave 0 — whole-project inventory generator.
|
||||
|
||||
Parses every .py file under src/rune/ with the stdlib AST and emits
|
||||
docs/rebase/rebase-inventory.json: files, classes, functions (with signatures and
|
||||
line ranges), imports, and best-effort caller/callee edges (intra-module call
|
||||
graph + cross-module edges resolved through import tables).
|
||||
|
||||
Deterministic and idempotent: same tree in, same JSON out (sorted keys,
|
||||
sorted files). The issue-factory reads this file; nothing else may edit it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import json
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parent.parent
|
||||
SRC = REPO / "src" / "rune"
|
||||
OUT = REPO / "docs" / "rebase" / "rebase-inventory.json"
|
||||
|
||||
|
||||
def _arg_str(a: ast.arg) -> str:
|
||||
s = a.arg
|
||||
if a.annotation is not None:
|
||||
# Degraded signature (no annotation) is deterministic metadata — never
|
||||
# let one pathological annotation node abort the whole inventory walk.
|
||||
try:
|
||||
s += f": {ast.unparse(a.annotation)}"
|
||||
except (AttributeError, RecursionError, ValueError):
|
||||
pass
|
||||
return s
|
||||
|
||||
|
||||
def _signature(node: ast.FunctionDef | ast.AsyncFunctionDef) -> str:
|
||||
parts = [_arg_str(a) for a in node.args.args]
|
||||
if node.args.vararg:
|
||||
parts.append(f"*{node.args.vararg.arg}")
|
||||
elif node.args.kwonlyargs:
|
||||
parts.append("*")
|
||||
parts += [_arg_str(a) for a in node.args.kwonlyargs]
|
||||
if node.args.kwarg:
|
||||
parts.append(f"**{node.args.kwarg.arg}")
|
||||
ret = ""
|
||||
if node.returns is not None:
|
||||
# Same degraded-metadata contract as _arg_str.
|
||||
try:
|
||||
ret = f" -> {ast.unparse(node.returns)}"
|
||||
except (AttributeError, RecursionError, ValueError):
|
||||
pass
|
||||
return f"({', '.join(parts)}){ret}"
|
||||
|
||||
|
||||
class FileVisitor(ast.NodeVisitor):
|
||||
def __init__(self) -> None:
|
||||
self.functions: list[dict] = []
|
||||
self.classes: list[dict] = []
|
||||
self.imports: list[dict] = []
|
||||
self.calls: list[tuple[int, str]] = [] # (lineno, dotted call name)
|
||||
|
||||
def _fn(self, node, parents: list[str]) -> dict:
|
||||
return {
|
||||
"name": ".".join([*parents, node.name]),
|
||||
"signature": _signature(node),
|
||||
"line_start": node.lineno,
|
||||
"line_end": node.end_lineno or node.lineno,
|
||||
"decorators": [ast.unparse(d) for d in node.decorator_list
|
||||
if isinstance(d, (ast.Name, ast.Attribute, ast.Call))],
|
||||
"async": isinstance(node, ast.AsyncFunctionDef),
|
||||
}
|
||||
|
||||
def visit_ClassDef(self, node: ast.ClassDef) -> None:
|
||||
methods = []
|
||||
for child in node.body:
|
||||
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
||||
methods.append(self._fn(child, [node.name]))
|
||||
self.calls.extend(
|
||||
(n.lineno, ast.unparse(n.func))
|
||||
for n in ast.walk(child)
|
||||
if isinstance(n, ast.Call) and not isinstance(n.func, ast.Name if False else type(None))
|
||||
and isinstance(n.func, (ast.Name, ast.Attribute))
|
||||
)
|
||||
self.classes.append({
|
||||
"name": node.name,
|
||||
"bases": [ast.unparse(b) for b in node.bases],
|
||||
"line_start": node.lineno,
|
||||
"line_end": node.end_lineno or node.lineno,
|
||||
"methods": methods,
|
||||
})
|
||||
# visit only non-function children: methods are already captured above,
|
||||
# and a generic_visit would re-fire visit_FunctionDef on them (duplicate
|
||||
# units + duplicate call edges). Nested classes are still visited.
|
||||
for child in node.body:
|
||||
if not isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
||||
self.visit(child)
|
||||
|
||||
def visit_FunctionDef(self, node) -> None:
|
||||
# top-level only reached here (methods captured in ClassDef)
|
||||
self.functions.append(self._fn(node, []))
|
||||
self.calls.extend(
|
||||
(n.lineno, ast.unparse(n.func))
|
||||
for n in ast.walk(node)
|
||||
if isinstance(n, ast.Call) and isinstance(n.func, (ast.Name, ast.Attribute))
|
||||
)
|
||||
# do not descend into nested defs separately; they are folded into parents
|
||||
# (their calls are already captured by the ast.walk above). No generic_visit:
|
||||
# it would re-collect nested defs as top-level functions and duplicate edges.
|
||||
|
||||
visit_AsyncFunctionDef = visit_FunctionDef
|
||||
|
||||
def visit_Import(self, node: ast.Import) -> None:
|
||||
for a in node.names:
|
||||
self.imports.append({"module": a.name, "as": a.asname, "line": node.lineno})
|
||||
|
||||
def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
|
||||
mod = node.module or ""
|
||||
for a in node.names:
|
||||
self.imports.append({"module": f"{mod}.{a.name}" if a.name != "*" else mod,
|
||||
"as": a.asname or a.name, "line": node.lineno,
|
||||
"from": True})
|
||||
|
||||
|
||||
def collect_file(path: Path) -> dict:
|
||||
src_text = path.read_text(encoding="utf-8", errors="replace")
|
||||
tree = ast.parse(src_text)
|
||||
v = FileVisitor()
|
||||
v.visit(tree)
|
||||
|
||||
# module-level calls (outside defs/classes) — walk tree body directly.
|
||||
# SKIP def/class statements: their bodies are walked by the visit_ methods;
|
||||
# walking them here duplicated every call edge inside every top-level function.
|
||||
for stmt in tree.body:
|
||||
if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
||||
continue
|
||||
for n in ast.walk(stmt):
|
||||
if isinstance(n, ast.Call) and isinstance(n.func, (ast.Name, ast.Attribute)):
|
||||
v.calls.append((n.lineno, ast.unparse(n.func)))
|
||||
|
||||
defined = {f["name"].split(".")[-1] for f in v.functions}
|
||||
defined |= {m["name"].split(".")[-1] for c in v.classes for m in c["methods"]}
|
||||
defined |= {c["name"] for c in v.classes}
|
||||
|
||||
callees = []
|
||||
for lineno, call in v.calls:
|
||||
root = call.split(".")[0].split("(")[0].strip()
|
||||
callees.append({"line": lineno, "call": call,
|
||||
"internal": root in defined or root == "self"})
|
||||
|
||||
return {
|
||||
"path": str(path.relative_to(REPO)),
|
||||
"lines": len(src_text.splitlines()),
|
||||
"imports": sorted({i["module"] for i in v.imports}),
|
||||
"import_lines": v.imports,
|
||||
"functions": sorted(v.functions, key=lambda f: (f["line_start"], f["name"])),
|
||||
"classes": sorted(v.classes, key=lambda c: c["line_start"]),
|
||||
"calls": callees,
|
||||
}
|
||||
|
||||
|
||||
def cross_module_edges(files: dict[str, dict]) -> dict[str, set[str]]:
|
||||
"""Resolve import tables: module-stem -> set of imported module stems
|
||||
(rune-internal only), so the factory can attribute cross-module edges."""
|
||||
graph = defaultdict(set)
|
||||
for rel, info in files.items():
|
||||
stem = Path(rel).stem
|
||||
for imp in info["imports"]:
|
||||
top = imp.split(".")[0]
|
||||
second = ".".join(imp.split(".")[:2])
|
||||
if top == "rune":
|
||||
graph[stem].add(imp.replace("rune.", "", 1).split(".")[0])
|
||||
elif not imp.startswith("_") and top not in sys.stdlib_module_names:
|
||||
graph[stem].add(f"ext:{top}")
|
||||
return graph
|
||||
|
||||
|
||||
def main() -> None:
|
||||
py_files = sorted(SRC.rglob("*.py"))
|
||||
files: dict[str, dict] = {}
|
||||
for p in py_files:
|
||||
try:
|
||||
info = collect_file(p)
|
||||
except SyntaxError as e: # a file that cannot parse is a finding, not a skip
|
||||
info = {"path": str(p.relative_to(REPO)), "lines": 0, "imports": [],
|
||||
"import_lines": [], "functions": [], "classes": [], "calls": [],
|
||||
"parse_error": f"{type(e).__name__}: {e}"}
|
||||
files[info["path"]] = info
|
||||
|
||||
graph = cross_module_edges(files)
|
||||
total_fns = sum(len(f["functions"]) + sum(len(c["methods"]) for c in f["classes"])
|
||||
for f in files.values())
|
||||
doc = {
|
||||
"_meta": {
|
||||
"generator": "scripts/rebase_inventory.py",
|
||||
"tranche": "R1 language rebase, Wave 0",
|
||||
"note": "Machine-generated. Regenerate with the script; never hand-edit.",
|
||||
"files": len(files),
|
||||
"functions_total": total_fns,
|
||||
"classes_total": sum(len(f["classes"]) for f in files.values()),
|
||||
"lines_total": sum(f["lines"] for f in files.values()),
|
||||
},
|
||||
"import_graph": {k: sorted(v) for k, v in sorted(graph.items())},
|
||||
"files": dict(sorted(files.items())),
|
||||
}
|
||||
OUT.write_text(json.dumps(doc, indent=1, sort_keys=False) + "\n", encoding="utf-8")
|
||||
m = doc["_meta"]
|
||||
print(f"inventory written: {OUT}")
|
||||
print(f"files={m['files']} functions={m['functions_total']} "
|
||||
f"classes={m['classes_total']} lines={m['lines_total']}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,356 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Tranche R1 Wave 0 — per-function issue factory.
|
||||
|
||||
Reads docs/rebase/rebase-inventory.json and emits one issue per unit (top-level
|
||||
function or class method) following tranche R1 §7. Wave-batched, dedup-safe
|
||||
(deterministic title + existing-issue scan before create), rate-limited.
|
||||
|
||||
Modes:
|
||||
plan — coverage report: units per wave, unassigned modules (no silent drops)
|
||||
sample — emit N rendered issues to a file for review (no Gitea call)
|
||||
create — create issues in Gitea for one wave
|
||||
|
||||
Dedup contract: issue titles are deterministic —
|
||||
[rebase w{wave}] {relpath}::{unit}
|
||||
The factory fetches existing issue titles once per run and skips any that
|
||||
already exist, so retries never duplicate (preserve-first Gitea addendum).
|
||||
|
||||
The factory NEVER writes behaviour prose. Current-behaviour paragraphs and
|
||||
the three evidence answers (IMPROVE / FIX / MISSING CONNECTORS) are filled at
|
||||
disposition time by the working agent — the issue carries the mandatory
|
||||
fields and line ranges, not fabricated content.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
INVENTORY = REPO_ROOT / "docs" / "rebase" / "rebase-inventory.json"
|
||||
COVERAGE_OUT = REPO_ROOT / "docs" / "rebase" / "rebase-wave-coverage.json"
|
||||
|
||||
GITEA_URL = os.environ.get("GITEA_URL", "https://gitea.thingscouldgetdicey.online")
|
||||
REPO = "conductor/rune"
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "shared"))
|
||||
from gitea_auth import load_gitea_token # noqa: E402
|
||||
|
||||
TRANCHE_REF = "tranche R1 language rebase (2026-09-29), ~/.config/opencode/tranches/2026-09-29-language-rebase-tranche-R1.md"
|
||||
|
||||
# Wave membership from R1 §4 (initial, measured). Directory entries match by
|
||||
# path prefix; bare stems match the file stem. Modules matching no entry are
|
||||
# reported UNASSIGNED by `plan` — never silently dropped (R1 §9 risk 7).
|
||||
WAVE_PLAN = {
|
||||
2: [ # leaf utilities & canaries
|
||||
"pins", "time_awareness", "message_queue", "event_envelope",
|
||||
"attention_capsule", "complexity_scorer", "token_optimizer", "cache",
|
||||
"prompt_sync", "chat_bubble", "canary_*",
|
||||
],
|
||||
3: [ # memory & persistence
|
||||
"memory_store", "curator", "warm_router", "memory_consolidation",
|
||||
"graph_memory", "sleep_time", "night_mode", "identity_anchors",
|
||||
"query_memory", "memory_env", "warm_neuron_store", "subconscious_pass",
|
||||
"task_persist",
|
||||
],
|
||||
4: [ # provider/model layer
|
||||
"provider_registry", "model_connect", "model_routing", "model_profiles",
|
||||
"provider_budget", "standardized_providers", "model_registry",
|
||||
"connection_pool", "forge_client",
|
||||
],
|
||||
5: [ # orchestration, authority, plugins, skills, governance
|
||||
"orchestration/", "microkernel", "contracts", "build_mode", "plugins/",
|
||||
"skills/", "construction_authority", "construction_authority_cli",
|
||||
"construction_decision", "construction_mode", "verification_construction",
|
||||
"authority_recovery", "spine", "drift_core", "drift_ledger",
|
||||
"drift_observability", "persona_gate", "safety_override", "witness",
|
||||
"behavior", "growth_delta", "claim_audit", "verification_layer",
|
||||
"drift_compression", "drift_cache", "self_improve", "persona_definition",
|
||||
"outcome_ledger", "audit_ledger", "subsystem_health",
|
||||
],
|
||||
6: [ # runtime core & tooling
|
||||
"tool_executor", "tool_protocol", "local_tool_runtime",
|
||||
"capability_broker", "context_broker", "work_manager", "cron_engine",
|
||||
"auto_tasks", "goal", "failure_auto_filer", "hook_engine",
|
||||
"elastic_cognition", "event_bus", "system_registry", "abstraction",
|
||||
"tiered_executor", "progressive_escalation", "tier_manager",
|
||||
"parallel_processor", "shard_manager", "response_adapter",
|
||||
"context_pressure", "auto_context", "cognitive_budgeter",
|
||||
"recall_router", "inference_trace", "task_gate", "salience_gate",
|
||||
"dependency_tracker", "rune_profiler",
|
||||
],
|
||||
7: [ # operator + TUI, last by design
|
||||
"rune_operator", "rune_tui", "tui_validator", "voice_hybrid",
|
||||
"voice_sync", "voicebox", "voice_injector", "message_widgets",
|
||||
"rune_graphic", "rune_spinner", "__main__",
|
||||
],
|
||||
}
|
||||
|
||||
WAVE_NAMES = {
|
||||
2: "leaf utilities & canaries",
|
||||
3: "memory & persistence",
|
||||
4: "provider/model layer",
|
||||
5: "orchestration, authority, plugins, skills, governance",
|
||||
6: "runtime core & tooling",
|
||||
7: "operator + TUI",
|
||||
}
|
||||
|
||||
|
||||
def match_module(relpath: str):
|
||||
"""Return the wave number for a module path, or None if unassigned."""
|
||||
stem = Path(relpath).stem
|
||||
for wave, patterns in WAVE_PLAN.items():
|
||||
for pat in patterns:
|
||||
if pat.endswith("/"):
|
||||
if pat in relpath:
|
||||
return wave
|
||||
elif pat.endswith("*"):
|
||||
if stem.startswith(pat[:-1]):
|
||||
return wave
|
||||
elif stem == pat:
|
||||
return wave
|
||||
return None
|
||||
|
||||
|
||||
def iter_units(inv):
|
||||
"""Yield (relpath, unit_name, entry) for every function and method."""
|
||||
for relpath, mod in sorted(inv["files"].items()):
|
||||
for fn in mod["functions"]:
|
||||
yield relpath, fn["name"], fn
|
||||
for cls in mod["classes"]:
|
||||
for m in cls.get("methods", []):
|
||||
yield relpath, f"{cls['name']}.{m['name']}", m
|
||||
|
||||
|
||||
def internal_edges(relpath: str, entry: dict):
|
||||
"""Collect internal (in-repo) call names and line numbers for a unit."""
|
||||
lines = (entry["line_start"], entry["line_end"])
|
||||
mod = inv_cache["files"][relpath]
|
||||
calls = [c for c in mod.get("calls", [])
|
||||
if lines[0] <= c["line"] <= lines[1] and c.get("internal")]
|
||||
return calls
|
||||
|
||||
|
||||
inv_cache = {}
|
||||
|
||||
|
||||
def issue_title(wave: int, relpath: str, unit: str) -> str:
|
||||
return f"[rebase w{wave}] {relpath}::{unit}"
|
||||
|
||||
|
||||
def render_issue(wave: int, relpath: str, unit: str, entry: dict) -> dict:
|
||||
calls = internal_edges(relpath, entry)
|
||||
call_lines = "\n".join(
|
||||
f" - `{c['call']}` (line {c['line']})" for c in calls[:20]
|
||||
) or " - (no internal call edges in range)"
|
||||
sig = entry.get("signature", "()")
|
||||
body = f"""\
|
||||
|
||||
## Identity (from the Wave 0 inventory — machine-generated)
|
||||
|
||||
- **File**: `{relpath}`
|
||||
- **Unit**: `{unit}`
|
||||
- **Signature**: `def {unit}{sig}` (async: {entry.get('async', False)})
|
||||
- **Line range**: {entry['line_start']}–{entry['line_end']}
|
||||
- **Decorators**: {entry.get('decorators', []) or 'none'}
|
||||
- **Internal call edges** (callers/callees inside the repo, from inventory):
|
||||
{call_lines}
|
||||
|
||||
## Current behaviour
|
||||
|
||||
One honest paragraph from READING THE CODE at the line range above — what it
|
||||
actually does, not what the docstring promises. Write this at disposition
|
||||
time; the factory does not fabricate it.
|
||||
|
||||
## The three questions — each answered WITH EVIDENCE
|
||||
|
||||
1. **IMPROVE?** Can the unit be improved within its scope? Evidence or "no — because …".
|
||||
(Bounded to unit scope; larger findings spawn NEW issues, never expand this one.)
|
||||
2. **FIX?** Is it broken, buggy, or failing its expected outcome? Evidence: a failing
|
||||
test, a reproduced fault, or a code-level defect citation. A "no" needs evidence too.
|
||||
3. **MISSING CONNECTORS?** Are there expected outcomes this unit should connect to but
|
||||
doesn't (unwired events, dead parameters, promised-but-absent calls)? Evidence required.
|
||||
|
||||
A silent skip on any question is a factory bug — answer all three.
|
||||
|
||||
## Language verdict (per tranche R1 §6 rubric — evidence beats instinct)
|
||||
|
||||
Choose exactly one, with the evidence line:
|
||||
- **KEEP-PYTHON** — one sentence of justification.
|
||||
- **RECODE-<lang>** — rubric scores (all 7 dimensions) + benchmark-gate plan: the compiled
|
||||
replacement must beat the Python original on the MEASURED hot path, or the recode is
|
||||
rejected and recorded. No win, no recode.
|
||||
- **MERGE-into:<module>** — name the target and why.
|
||||
- **DEPRECATE** — name the caller that no longer needs it.
|
||||
|
||||
Go is NOT pre-decided. Python is not pre-decided. The rubric decides.
|
||||
|
||||
## Constraint context
|
||||
|
||||
- henxels structural contract: this unit's module ≤ 1,200 lines (or on the debt table's
|
||||
exception list — check before adding lines).
|
||||
- Spine: any module-surface change requires `store/spine/current.json` regen with the code
|
||||
change (`test_manifest_maps_every_module` is the arbiter for new top-level modules).
|
||||
- Debt table: docs/structural-contract.md.
|
||||
|
||||
## Pipeline plan
|
||||
|
||||
1. Branch `issue-<N>` from current master (existing issue-N convention).
|
||||
2. Scaffolding activation for any construction (construction_mode/decision per unit change).
|
||||
3. Research rounds are MANDATORY for any RECODE verdict (research-stage-headless; ≥2
|
||||
live-verified external sources per claim; per-source lessons; kill test per candidate).
|
||||
4. Implementation behind the interop contract (R1 §5): compiled units are standalone
|
||||
binaries — argv in, JSON on stdout, non-zero exit on failure, `--version` mandatory;
|
||||
Python wraps in a thin adapter; store stays the shared truth.
|
||||
5. Local gates: pytest + ruff + spine-store regen (if surface changed) + henxels.
|
||||
6. PR → pipeline-gate + ci + required checks → merge-robot → auto-version.
|
||||
|
||||
## Verification
|
||||
|
||||
- The specific test proving this unit's change: (write at disposition).
|
||||
- The keep-green set it must not break: full suite must stay green; named
|
||||
keep-green tests for this unit's callers.
|
||||
|
||||
## Provenance
|
||||
|
||||
- Tranche: {TRANCHE_REF}
|
||||
- Wave: {wave} ({WAVE_NAMES.get(wave, 'unassigned')})
|
||||
- Inventory: docs/rebase/rebase-inventory.json (regenerate with scripts/rebase_inventory.py — never hand-edit)
|
||||
- Factory: scripts/rebase_issue_factory.py
|
||||
"""
|
||||
return {
|
||||
"title": issue_title(wave, relpath, unit),
|
||||
"body": body,
|
||||
"labels": ["rebase", f"wave-{wave}"],
|
||||
"meta": {
|
||||
"wave": wave,
|
||||
"file": relpath,
|
||||
"unit": unit,
|
||||
"line_start": entry["line_start"],
|
||||
"line_end": entry["line_end"],
|
||||
"async": entry.get("async", False),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def fetch_existing_titles() -> set:
|
||||
"""Fetch all issue titles in the repo (paginated) for dedup."""
|
||||
token = load_gitea_token()
|
||||
titles = set()
|
||||
page = 1
|
||||
while True:
|
||||
url = (f"{GITEA_URL}/api/v1/repos/{REPO}/issues"
|
||||
f"?state=all&type=issues&limit=50&page={page}")
|
||||
req = urllib.request.Request(url, headers={"Authorization": f"token {token}"})
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
batch = json.loads(resp.read())
|
||||
if not batch:
|
||||
break
|
||||
titles.update(i["title"] for i in batch)
|
||||
if len(batch) < 50:
|
||||
break
|
||||
page += 1
|
||||
return titles
|
||||
|
||||
|
||||
def create_issue(entry: dict) -> dict:
|
||||
token = load_gitea_token()
|
||||
url = f"{GITEA_URL}/api/v1/repos/{REPO}/issues"
|
||||
payload = json.dumps({
|
||||
"title": entry["title"],
|
||||
"body": entry["body"],
|
||||
"labels": [], # label NAMES are set via the labels endpoint by auto-label; keep create minimal
|
||||
}).encode()
|
||||
req = urllib.request.Request(url, data=payload, method="POST",
|
||||
headers={"Authorization": f"token {token}",
|
||||
"Content-Type": "application/json"})
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
return json.loads(resp.read())
|
||||
|
||||
|
||||
def cmd_plan(inv):
|
||||
counts = {}
|
||||
unassigned_modules = {}
|
||||
for relpath, unit, entry in iter_units(inv):
|
||||
wave = match_module(relpath)
|
||||
counts[wave] = counts.get(wave, 0) + 1
|
||||
if wave is None:
|
||||
unassigned_modules.setdefault(relpath, inv["files"][relpath]["lines"])
|
||||
report = {
|
||||
"units_per_wave": {str(k if k is not None else "UNASSIGNED"): v
|
||||
for k, v in sorted(counts.items(), key=lambda kv: str(kv[0]))},
|
||||
"unassigned_modules": dict(sorted(unassigned_modules.items(), key=lambda kv: -kv[1])),
|
||||
"unassigned_module_count": len(unassigned_modules),
|
||||
}
|
||||
print(json.dumps(report, indent=1))
|
||||
COVERAGE_OUT.write_text(json.dumps(report, indent=1) + "\n")
|
||||
print(f"\ncoverage written to {COVERAGE_OUT.relative_to(REPO_ROOT)}", file=sys.stderr)
|
||||
return 0 if not unassigned_modules else 1
|
||||
|
||||
|
||||
def cmd_sample(inv, wave, limit, out):
|
||||
emitted = 0
|
||||
records = []
|
||||
for relpath, unit, entry in iter_units(inv):
|
||||
if match_module(relpath) != wave:
|
||||
continue
|
||||
records.append(render_issue(wave, relpath, unit, entry))
|
||||
emitted += 1
|
||||
if emitted >= limit:
|
||||
break
|
||||
Path(out).write_text("\n".join(json.dumps(r) for r in records) + "\n")
|
||||
print(f"sampled {emitted} issues for wave {wave} -> {out}", file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_create(inv, wave, limit, dry_gap):
|
||||
existing = fetch_existing_titles()
|
||||
created, skipped = 0, 0
|
||||
for relpath, unit, entry in iter_units(inv):
|
||||
if match_module(relpath) != wave:
|
||||
continue
|
||||
title = issue_title(wave, relpath, unit)
|
||||
if title in existing:
|
||||
skipped += 1
|
||||
continue
|
||||
issue = create_issue(render_issue(wave, relpath, unit, entry))
|
||||
created += 1
|
||||
print(f"created #{issue.get('number')}: {title}", file=sys.stderr)
|
||||
if limit and created >= limit:
|
||||
break
|
||||
time.sleep(dry_gap)
|
||||
print(f"\nwave {wave}: created={created} skipped(dedup)={skipped}", file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
ap.add_argument("command", choices=["plan", "sample", "create"])
|
||||
ap.add_argument("--wave", type=int, help="wave number (2-7)")
|
||||
ap.add_argument("--limit", type=int, default=0, help="max issues for sample/create (0 = unlimited; sample defaults to 5)")
|
||||
ap.add_argument("--out", default=None, help="sample output file")
|
||||
ap.add_argument("--gap", type=float, default=0.5, help="seconds between creates")
|
||||
args = ap.parse_args()
|
||||
|
||||
inv_cache.update(json.loads(INVENTORY.read_text()))
|
||||
inv = inv_cache
|
||||
|
||||
if args.command == "plan":
|
||||
return cmd_plan(inv)
|
||||
if args.command == "sample":
|
||||
if not args.wave:
|
||||
ap.error("--wave required")
|
||||
out = args.out or f"docs/rebase-factory-sample-w{args.wave}.json"
|
||||
return cmd_sample(inv, args.wave, args.limit or 5, out)
|
||||
if args.command == "create":
|
||||
if not args.wave:
|
||||
ap.error("--wave required")
|
||||
return cmd_create(inv, args.wave, args.limit, args.gap)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -50,7 +50,7 @@ SRC_A = {
|
||||
"memory_store": "memory", "memory_selector": "memory",
|
||||
"memory_consolidation": "memory", "memory_env": "memory",
|
||||
"shard_manager": "memory", "tier_manager": "memory",
|
||||
"graph_memory": "memory",
|
||||
"graph_memory": "memory", "query_memory": "memory",
|
||||
"curator": "memory", "sleep_time": "memory",
|
||||
"subconscious_pass": "memory", "warm_neuron_store": "memory",
|
||||
"warm_router": "memory", "abstraction": "memory",
|
||||
@@ -166,12 +166,14 @@ SCRIPTS_C = {"fake_worker", "tui_startup_canary"}
|
||||
|
||||
# shared/ — harness-facing layer; mirrors of canonical src modules = D
|
||||
SHARED_D = {
|
||||
"audit_ledger": "src/rune/audit_ledger.py",
|
||||
"dependency_tracker": "src/rune/dependency_tracker.py",
|
||||
"drift_cache": "src/rune/drift_cache.py",
|
||||
"drift_compression": "src/rune/drift_compression.py",
|
||||
"drift_core": "src/rune/drift_core.py",
|
||||
"drift_observability": "src/rune/drift_observability.py",
|
||||
"gitea_auth": "scripts/gitea_auth.py",
|
||||
"query_memory": "src/rune/query_memory.py",
|
||||
"shard_manager": "src/rune/shard_manager.py",
|
||||
"subconscious_pass": "src/rune/subconscious_pass.py",
|
||||
"tier_manager": "src/rune/tier_manager.py",
|
||||
@@ -180,8 +182,7 @@ SHARED_B_OWNER = "ops-harness"
|
||||
SHARED_B = {"auto_detect", "autonomy_loop", "build_orchestrator",
|
||||
"build_pipeline_policy", "cognitive_loop", "custodian",
|
||||
"dream_cycle", "gitea_pipeline", "gitea_provision",
|
||||
"graph_shard_bridge", "growth_simulator", "query_memory",
|
||||
"umbrella_update"}
|
||||
"graph_shard_bridge", "growth_simulator", "umbrella_update"}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
|
||||
@@ -47,19 +47,7 @@ def main() -> int:
|
||||
p for p in env.get("PATH", "").split(os.pathsep)
|
||||
if "ci-venv" not in p and ".type-venv" not in p and "venv/bin" not in p)
|
||||
result = subprocess.run(
|
||||
# §16V AMBIENT-INTERPRETER CLOSURE (T7.3 slice-2 CI repair, 2026-10-03):
|
||||
# venv-signal stripping fixed ACTIVATION drift, but dependency
|
||||
# resolution still followed the AMBIENT host interpreter — runner
|
||||
# (py311, no rich/Pillow) vs desktop (3.14 system site with both)
|
||||
# produced 460 vs 454 on the identical tree, and any import-level
|
||||
# ignore flips to reportUnnecessaryTypeIgnoreComment in the other
|
||||
# environment. Pin --pythonpath to the INVOKING interpreter (the
|
||||
# venv running this script) so dependency resolution follows the
|
||||
# installed lock, not the host: CI's .type-venv has the locked deps;
|
||||
# local preflight must run the ratchet from a venv built from
|
||||
# requirements-ci.txt (same lock) — that is now the contract.
|
||||
cmd + [str(ROOT / "src" / "rune"), "--outputjson",
|
||||
"--pythonpath", sys.executable],
|
||||
cmd + [str(ROOT / "src" / "rune"), "--outputjson"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=600,
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
#!/usr/bin/env python3
|
||||
"""audit_ledger.py — HMAC-chained tamper-evident promotion ledger.
|
||||
|
||||
Every promotion decision is recorded in a hash-chained ledger.
|
||||
Tampering with any entry breaks the chain.
|
||||
|
||||
Research basis:
|
||||
- PoEM (arXiv:2608.16032): HMAC-chained tamper-evident execution ledger
|
||||
- Autogenesis (arXiv:2604.15034): versioned interfaces, auditable lineage
|
||||
|
||||
Run under ~/.venvs/memory/bin/python3.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
LEDGER_FILE = os.path.expanduser("~/.config/opencode/memory/promotion_ledger.jsonl")
|
||||
SECRET_KEY = os.environ.get("AUDIT_LEDGER_KEY", "rune-drift-integrity-2024")
|
||||
|
||||
|
||||
def _compute_hash(prev_hash: str, entry: dict) -> str:
|
||||
"""Compute HMAC chain hash for a ledger entry."""
|
||||
payload = json.dumps(entry, sort_keys=True).encode()
|
||||
msg = (prev_hash + payload.decode()).encode()
|
||||
return hmac.new(SECRET_KEY.encode(), msg, hashlib.sha256).hexdigest()
|
||||
|
||||
|
||||
def append_entry(entry_type: str, entry_id: int, details: dict) -> dict:
|
||||
"""Append an entry to the promotion ledger.
|
||||
|
||||
Returns the ledger entry with chain hash.
|
||||
"""
|
||||
# Read last hash
|
||||
prev_hash = "genesis"
|
||||
if os.path.exists(LEDGER_FILE):
|
||||
with open(LEDGER_FILE, "r") as f:
|
||||
lines = f.readlines()
|
||||
if lines:
|
||||
try:
|
||||
last = json.loads(lines[-1])
|
||||
prev_hash = last.get("hash", "genesis")
|
||||
except json.JSONDecodeError:
|
||||
prev_hash = "genesis"
|
||||
|
||||
entry = {
|
||||
"type": entry_type,
|
||||
"entry_id": entry_id,
|
||||
"details": details,
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"prev_hash": prev_hash,
|
||||
}
|
||||
|
||||
# Compute chain hash
|
||||
entry["hash"] = _compute_hash(prev_hash, entry)
|
||||
|
||||
# Append to ledger
|
||||
os.makedirs(os.path.dirname(LEDGER_FILE), exist_ok=True)
|
||||
with open(LEDGER_FILE, "a") as f:
|
||||
f.write(json.dumps(entry) + "\n")
|
||||
|
||||
return entry
|
||||
|
||||
|
||||
def verify_chain() -> dict:
|
||||
"""Verify the integrity of the entire ledger chain.
|
||||
|
||||
Returns dict with verification result.
|
||||
"""
|
||||
if not os.path.exists(LEDGER_FILE):
|
||||
return {"valid": True, "entries": 0, "reason": "empty ledger"}
|
||||
|
||||
with open(LEDGER_FILE, "r") as f:
|
||||
lines = f.readlines()
|
||||
|
||||
prev_hash = "genesis"
|
||||
for i, line in enumerate(lines):
|
||||
try:
|
||||
entry = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
return {"valid": False, "entries": i, "reason": f"invalid JSON at line {i+1}"}
|
||||
|
||||
# Verify prev_hash chain
|
||||
if entry.get("prev_hash") != prev_hash:
|
||||
return {
|
||||
"valid": False,
|
||||
"entries": i,
|
||||
"reason": f"chain broken at line {i+1}: expected prev_hash={prev_hash}, got {entry.get('prev_hash')}"
|
||||
}
|
||||
|
||||
# Verify HMAC
|
||||
stored_hash = entry.get("hash")
|
||||
computed = _compute_hash(prev_hash, {k: v for k, v in entry.items() if k != "hash"})
|
||||
if stored_hash != computed:
|
||||
return {
|
||||
"valid": False,
|
||||
"entries": i,
|
||||
"reason": f"HMAC mismatch at line {i+1}: stored={stored_hash[:16]}..., computed={computed[:16]}..."
|
||||
}
|
||||
|
||||
prev_hash = stored_hash
|
||||
|
||||
return {"valid": True, "entries": len(lines), "reason": "chain intact"}
|
||||
|
||||
|
||||
def get_entries(limit: int = 50) -> List[dict]:
|
||||
"""Get recent ledger entries."""
|
||||
if not os.path.exists(LEDGER_FILE):
|
||||
return []
|
||||
|
||||
with open(LEDGER_FILE, "r") as f:
|
||||
lines = f.readlines()
|
||||
|
||||
entries = []
|
||||
for line in lines[-limit:]:
|
||||
try:
|
||||
entries.append(json.loads(line))
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
return entries
|
||||
|
||||
|
||||
def log_promotion(entry_id: int, old_status: str, new_status: str, wash_count: int, reason: str) -> dict:
|
||||
"""Log a promotion decision."""
|
||||
return append_entry("promotion", entry_id, {
|
||||
"old_status": old_status,
|
||||
"new_status": new_status,
|
||||
"wash_count": wash_count,
|
||||
"reason": reason,
|
||||
})
|
||||
|
||||
|
||||
def log_gate_result(entry_id: int, verdict: str, critics: dict) -> dict:
|
||||
"""Log a pre-commit gate result."""
|
||||
return append_entry("gate", entry_id, {
|
||||
"verdict": verdict,
|
||||
"critics": critics,
|
||||
})
|
||||
|
||||
|
||||
def log_drift_alert(alert_type: str, message: str, severity: str) -> dict:
|
||||
"""Log a drift alert."""
|
||||
return append_entry("alert", 0, {
|
||||
"alert_type": alert_type,
|
||||
"message": message,
|
||||
"severity": severity,
|
||||
})
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# CLI
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
def main():
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser(description="Promotion audit ledger")
|
||||
sub = parser.add_subparsers(dest="cmd")
|
||||
|
||||
# verify
|
||||
sub.add_parser("verify", help="Verify ledger chain integrity")
|
||||
|
||||
# list [--limit N]
|
||||
p_list = sub.add_parser("list", help="Show recent ledger entries")
|
||||
p_list.add_argument("--limit", type=int, default=20)
|
||||
|
||||
# log-promotion <entry_id> <old> <new> <wash_count> <reason>
|
||||
p_log = sub.add_parser("log-promotion", help="Log a promotion")
|
||||
p_log.add_argument("entry_id", type=int)
|
||||
p_log.add_argument("old_status")
|
||||
p_log.add_argument("new_status")
|
||||
p_log.add_argument("wash_count", type=int)
|
||||
p_log.add_argument("reason")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if not args.cmd:
|
||||
parser.print_help()
|
||||
sys.exit(1)
|
||||
|
||||
if args.cmd == "verify":
|
||||
result = verify_chain()
|
||||
print(f"Chain valid: {result['valid']}")
|
||||
print(f"Entries: {result['entries']}")
|
||||
print(f"Reason: {result['reason']}")
|
||||
|
||||
elif args.cmd == "list":
|
||||
entries = get_entries(args.limit)
|
||||
if entries:
|
||||
print(f"Recent ledger entries ({len(entries)}):")
|
||||
for e in entries:
|
||||
print(f" [{e.get('type')}] entry_id={e.get('entry_id')} @ {e.get('timestamp', '')[:19]}")
|
||||
details = e.get('details', {})
|
||||
if e.get('type') == 'promotion':
|
||||
print(f" {details.get('old_status')} → {details.get('new_status')} (wash={details.get('wash_count')})")
|
||||
elif e.get('type') == 'gate':
|
||||
print(f" verdict={details.get('verdict')}")
|
||||
else:
|
||||
print("No ledger entries.")
|
||||
|
||||
elif args.cmd == "log-promotion":
|
||||
entry = log_promotion(args.entry_id, args.old_status, args.new_status, args.wash_count, args.reason)
|
||||
print(f"Logged: {entry['hash'][:16]}...")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+1
-10
@@ -33,7 +33,7 @@ SCRIPTS_DIR = os.path.expanduser("~/.config/opencode/scripts")
|
||||
SHARED_DIR = os.path.expanduser("~/.config/opencode/shared")
|
||||
CUSTODIAN_STATE_FILE = os.path.expanduser("~/.config/opencode/memory/custodian_state.json")
|
||||
|
||||
GITEA_URL = os.environ.get("GITEA_URL", "http://127.0.0.1:3000") # gitea.internal (PC); external = https://gitea.thingscouldgetdicey.online via Pi Caddy
|
||||
GITEA_URL = os.environ.get("GITEA_URL", "https://gitea.thingscouldgetdicey.online")
|
||||
GITEA_TOKEN = load_gitea_token()
|
||||
REPO = "conductor/rune"
|
||||
TUI_DIR = "/mnt/workdrive/rune"
|
||||
@@ -160,15 +160,6 @@ class Custodian:
|
||||
|
||||
The caller's body replaces the SUBMITTED_BODY marker inside the
|
||||
template's Plain English section — plain terms first, always.
|
||||
|
||||
ORGANISATION STANDARD (one open note per idea, 2026-09-19): before
|
||||
minting a standalone issue, check whether the work belongs inside an
|
||||
existing parent. Ideas parked under a blocked/future epic are filed
|
||||
as checklist items in the parent's "Absorbed children" section, NOT
|
||||
as standalone issues — the board stays uncluttered and every idea
|
||||
has exactly one home. Mint a standalone issue only when the work is
|
||||
live, dependency-tracked, or about to start. Absorbed ideas are
|
||||
reversible: re-mint standalone when they become live.
|
||||
"""
|
||||
# 1. assemble body from template (graceful: unformatted if template missing)
|
||||
template = self._load_issue_template(kind)
|
||||
|
||||
@@ -6,12 +6,11 @@ labels: bug
|
||||
assignees: conductor
|
||||
---
|
||||
|
||||
<restate the issue title here in everyday words — this heading IS the
|
||||
plain-English summary; no meta-labels like "plain English" in it>
|
||||
<!-- The heading above carries the summary itself — a scan of issue
|
||||
headings alone should tell the whole story of the board. TOP PRIORITY:
|
||||
if a technical detail below contradicts this section, the issue is
|
||||
buggy — fix the issue. -->
|
||||
## In plain English: <restate the issue title here in everyday words>
|
||||
<!-- The heading ITSELF must carry the summary — a scan of issue headings
|
||||
alone should tell the whole story of the board. TOP PRIORITY: if a
|
||||
technical detail below contradicts this section, the issue is buggy —
|
||||
fix the issue. -->
|
||||
<!-- SUBMITTED_BODY -->
|
||||
|
||||
|
||||
|
||||
@@ -6,12 +6,11 @@ labels: feature
|
||||
assignees: conductor
|
||||
---
|
||||
|
||||
<restate the issue title here in everyday words — this heading IS the
|
||||
plain-English summary; no meta-labels like "plain English" in it>
|
||||
<!-- The heading above carries the summary itself — a scan of issue
|
||||
headings alone should tell the whole story of the board. TOP PRIORITY:
|
||||
if a technical detail below contradicts this section, the issue is
|
||||
buggy — fix the issue. A non-technical reader must be able to retell this
|
||||
## In plain English: <restate the issue title here in everyday words>
|
||||
<!-- The heading ITSELF must carry the summary — a scan of issue headings
|
||||
alone should tell the whole story of the board. TOP PRIORITY: if a
|
||||
technical detail below contradicts this section, the issue is buggy —
|
||||
fix the issue. A non-technical reader must be able to retell this
|
||||
section. 3-6 sentences, no jargon. -->
|
||||
<!-- SUBMITTED_BODY -->
|
||||
|
||||
|
||||
@@ -6,12 +6,11 @@ labels: research
|
||||
assignees: conductor
|
||||
---
|
||||
|
||||
<restate the issue title here in everyday words — this heading IS the
|
||||
plain-English summary; no meta-labels like "plain English" in it>
|
||||
<!-- The heading above carries the summary itself — a scan of issue
|
||||
headings alone should tell the whole story of the board. TOP PRIORITY:
|
||||
if a technical detail below contradicts this section, the issue is
|
||||
buggy — fix the issue. -->
|
||||
## In plain English: <restate the issue title here in everyday words>
|
||||
<!-- The heading ITSELF must carry the summary — a scan of issue headings
|
||||
alone should tell the whole story of the board. TOP PRIORITY: if a
|
||||
technical detail below contradicts this section, the issue is buggy —
|
||||
fix the issue. -->
|
||||
<!-- SUBMITTED_BODY -->
|
||||
|
||||
|
||||
|
||||
@@ -1,216 +0,0 @@
|
||||
"""Thin adapter for native (compiled) units — R1 §5 interop contract, Wave 0.
|
||||
|
||||
The contract under proof: compiled units are standalone binaries exposing a
|
||||
CLI boundary — argv in, JSON on stdout, non-zero exit on failure, a mandatory
|
||||
``--version`` flag. This module is the Python side: run a unit, enforce a
|
||||
timeout, capture stderr, and return a TYPED result. It never raises for unit
|
||||
failures (those are data in the result); it raises only for adapter misuse
|
||||
(missing binary, bad timeout).
|
||||
|
||||
No IPC daemon, no PyO3 — the file-based store stays the shared truth. If
|
||||
research later surfaces a materially better pattern it competes through the
|
||||
research pipeline; the CLI boundary is the default, not a cage.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
PROOF_UNIT = REPO_ROOT / "interop" / "rebase-proof" / "target" / "release" / "rebase-proof"
|
||||
|
||||
|
||||
@dataclass
|
||||
class NativeResult:
|
||||
"""Typed result of one native-unit invocation.
|
||||
|
||||
ok — the invocation succeeded (exit 0 AND not timed out); when
|
||||
the unit emitted JSON with an ``ok`` field, that field must
|
||||
not be False (plain-text output like ``--version`` has none)
|
||||
exit_code — raw process exit code
|
||||
data — parsed JSON object from stdout, or None if unparseable
|
||||
stderr — captured stderr text (may be non-empty even on success)
|
||||
duration_ms — wall-clock cost of the invocation
|
||||
timed_out — True when the unit exceeded the timeout and was killed
|
||||
events — in streaming mode: every parsed JSON object line, in
|
||||
arrival order (empty for non-streaming :func:`run_native`)
|
||||
"""
|
||||
|
||||
ok: bool
|
||||
exit_code: int
|
||||
data: dict | None
|
||||
stderr: str
|
||||
duration_ms: int
|
||||
timed_out: bool = False
|
||||
raw_stdout: str = field(default="", repr=False)
|
||||
events: list[dict] = field(default_factory=list)
|
||||
|
||||
|
||||
def run_native(binary: Path, args: list[str], timeout_s: float = 10.0) -> NativeResult:
|
||||
"""Invoke a native unit and return a typed result.
|
||||
|
||||
Raises FileNotFoundError only when *binary* itself is absent (adapter
|
||||
misuse) — every unit-level failure is reported via the result, never an
|
||||
exception, so callers can branch on ``result.ok`` without try/except.
|
||||
"""
|
||||
if not binary.is_file():
|
||||
raise FileNotFoundError(f"native unit not built: {binary}")
|
||||
|
||||
started = time.monotonic()
|
||||
timed_out = False
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
[str(binary), *args],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=timeout_s,
|
||||
check=False, # exit codes are data, never exceptions
|
||||
)
|
||||
exit_code, stdout, stderr = proc.returncode, proc.stdout, proc.stderr
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
timed_out = True
|
||||
exit_code = -1
|
||||
stdout = exc.stdout or "" if isinstance(exc.stdout, str) else (exc.stdout or b"").decode(errors="replace")
|
||||
stderr = exc.stderr or "" if isinstance(exc.stderr, str) else (exc.stderr or b"").decode(errors="replace")
|
||||
|
||||
duration_ms = int((time.monotonic() - started) * 1000)
|
||||
|
||||
data: dict | None = None
|
||||
stripped = stdout.strip()
|
||||
if stripped:
|
||||
try:
|
||||
parsed = json.loads(stripped.splitlines()[-1])
|
||||
if isinstance(parsed, dict):
|
||||
data = parsed
|
||||
except json.JSONDecodeError:
|
||||
data = None
|
||||
|
||||
ok = (not timed_out) and exit_code == 0 and (data is None or data.get("ok") is not False)
|
||||
return NativeResult(
|
||||
ok=ok,
|
||||
exit_code=exit_code,
|
||||
data=data,
|
||||
stderr=stderr,
|
||||
duration_ms=duration_ms,
|
||||
timed_out=timed_out,
|
||||
raw_stdout=stdout,
|
||||
)
|
||||
|
||||
|
||||
def run_proof(args: list[str], timeout_s: float = 10.0) -> NativeResult:
|
||||
"""Run the Wave 0 proof unit with the standard contract defaults."""
|
||||
return run_native(PROOF_UNIT, args, timeout_s=timeout_s)
|
||||
|
||||
|
||||
def stream_native(
|
||||
binary: Path,
|
||||
args: list[str],
|
||||
timeout_s: float = 10.0,
|
||||
on_event=None,
|
||||
):
|
||||
"""Run a native unit in JSONL streaming mode, yielding events as they arrive.
|
||||
|
||||
The JSONL streaming contract (rubric §W7): one JSON object per stdout
|
||||
line — ``{"ok": true, "event": ...}`` progress objects along the way, and
|
||||
a terminal envelope as the FINAL line. This generator yields each parsed
|
||||
event dict the moment it arrives (so a long op surfaces partial progress
|
||||
instead of blocking until exit), then yields exactly one terminal
|
||||
:class:`NativeResult`. *on_event*, when given, is called with each parsed
|
||||
event as it arrives (the TUI wraps this in ``call_from_thread``).
|
||||
|
||||
Stream-mode ok-semantics are stricter than :func:`run_native`: ``ok``
|
||||
requires exit 0, no timeout, AND a valid terminal envelope (the final
|
||||
stdout line parsed as a JSON object whose ``ok`` is not False). Malformed
|
||||
interior lines are skipped and counted in ``malformed_lines``; malformed
|
||||
FINAL line means no valid terminal envelope, so ``ok`` is False — partial
|
||||
progress stays available in ``events``. That is the point of streaming.
|
||||
|
||||
Same failure discipline as :func:`run_native`: raises FileNotFoundError
|
||||
when *binary* is absent; every unit-level failure (bad envelope, timeout,
|
||||
non-zero exit) is data on the terminal result, never an exception.
|
||||
"""
|
||||
if on_event is not None and not callable(on_event):
|
||||
raise TypeError("on_event must be callable")
|
||||
if not binary.is_file():
|
||||
raise FileNotFoundError(f"native unit not built: {binary}")
|
||||
|
||||
started = time.monotonic()
|
||||
proc = subprocess.Popen(
|
||||
[str(binary), *args],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
)
|
||||
|
||||
# stderr must drain concurrently — reading it after the stdout loop
|
||||
# deadlocks when a unit floods stderr past the pipe buffer mid-stream.
|
||||
stderr_parts: list[str] = []
|
||||
stderr_drain = threading.Thread(
|
||||
target=lambda: stderr_parts.append(proc.stderr.read()), daemon=True
|
||||
)
|
||||
stderr_drain.start()
|
||||
|
||||
killed = threading.Event()
|
||||
# The watchdog's kill and the flag are one step so an adapter-side
|
||||
# timeout is never mistaken for a unit dying by its own signal.
|
||||
watchdog = threading.Timer(timeout_s, lambda: (killed.set(), proc.kill()))
|
||||
watchdog.start()
|
||||
|
||||
events: list[dict] = []
|
||||
malformed_lines = 0
|
||||
# True only while the most recent non-empty stdout line parsed as a JSON
|
||||
# object — a malformed final line invalidates the terminal envelope.
|
||||
final_line_is_json = False
|
||||
try:
|
||||
for line in proc.stdout:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
parsed = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
malformed_lines += 1
|
||||
final_line_is_json = False
|
||||
continue
|
||||
if not isinstance(parsed, dict):
|
||||
malformed_lines += 1
|
||||
final_line_is_json = False
|
||||
continue
|
||||
events.append(parsed)
|
||||
final_line_is_json = True
|
||||
if on_event is not None:
|
||||
on_event(parsed)
|
||||
yield parsed
|
||||
proc.wait()
|
||||
finally:
|
||||
watchdog.cancel()
|
||||
stderr_drain.join(timeout=5.0)
|
||||
|
||||
timed_out = killed.is_set()
|
||||
duration_ms = int((time.monotonic() - started) * 1000)
|
||||
exit_code = proc.returncode if proc.returncode is not None else -1
|
||||
if timed_out:
|
||||
exit_code = -1 # adapter-side kill, never a unit's own exit
|
||||
|
||||
terminal = events[-1] if (events and final_line_is_json) else None
|
||||
ok = (
|
||||
not timed_out
|
||||
and exit_code == 0
|
||||
and terminal is not None
|
||||
and terminal.get("ok") is not False
|
||||
)
|
||||
yield NativeResult(
|
||||
ok=ok,
|
||||
exit_code=exit_code,
|
||||
data=terminal,
|
||||
stderr=stderr_parts[0] if stderr_parts else "",
|
||||
duration_ms=duration_ms,
|
||||
timed_out=timed_out,
|
||||
events=events,
|
||||
)
|
||||
|
||||
+134
-60
@@ -1,25 +1,17 @@
|
||||
#!/usr/bin/env python3
|
||||
"""query_memory.py — Query memory system for adaptive retrieval.
|
||||
|
||||
AUTHORITY-SWITCHED (Phase G strangler slice 1, doctrine step 8): the
|
||||
classification core now lives in Rust (`src/rust/query_memory/src/lib.rs`,
|
||||
cdylib `libquery_memory.so`). This module is a thin ctypes-backed shim over
|
||||
`qm_loader.py` serving the FULL historical Python class API — the deployed
|
||||
in-process consumers (`memory_store.py`, `growth_simulator.py`) call
|
||||
`QueryMemory()` exactly as before and get the Rust core.
|
||||
The system remembers what kinds of queries it gets, what retrieval
|
||||
strategy worked, and adapts its gate logic accordingly.
|
||||
|
||||
Parity evidence: FFI-gap parity EXACT-EQUAL on `get_topic_stats` /
|
||||
`get_dead_weight_topics`; verification wall green (FFI smoke 41/41, parity
|
||||
harness ALL GREEN, Python canary 12/12, Rust canary 27/27); shadow comparison
|
||||
46/46 exact-equal vs the live production store.
|
||||
This prevents dead weight — memories get tested based on usage
|
||||
patterns, not just random exploration.
|
||||
|
||||
The Python implementation this replaces is preserved in git history on branch
|
||||
`phase-g-strangler-retrieval-index` (pre-shim commit); per deletion discipline
|
||||
it is not kept as a silent fallback — a missing cdylib fails loudly.
|
||||
|
||||
Store resolution is unchanged: `$HOME/.config/opencode/memory/query_memory`
|
||||
(the Rust core resolves `$HOME` natively; history.jsonl / topic_stats.json
|
||||
formats are byte-parity-proven).
|
||||
Research basis:
|
||||
- IGMiRAG (arXiv:2602.07525): Intuition-guided retrieval
|
||||
- Task-Adaptive Retrieval (arXiv:2604.07863): Learning from interaction history
|
||||
- MemCon (arXiv:2607.13591): Learned policy for consolidation/forgetting
|
||||
- Agent-Native Memory (arXiv:2606.24775): Workload-adaptive routing
|
||||
|
||||
Run under ~/.venvs/memory/bin/python3.
|
||||
"""
|
||||
@@ -27,14 +19,15 @@ Run under ~/.venvs/memory/bin/python3.
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from collections import Counter, defaultdict
|
||||
from datetime import datetime, timezone
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
QUERY_MEMORY_DIR = os.path.expanduser("~/.config/opencode/memory/query_memory")
|
||||
QUERY_HISTORY_FILE = os.path.join(QUERY_MEMORY_DIR, "history.jsonl")
|
||||
TOPIC_STATS_FILE = os.path.join(QUERY_MEMORY_DIR, "topic_stats.json")
|
||||
|
||||
# Topic keywords (classification table — tie-break law: insertion order is
|
||||
# part of the contract; the Rust core carries the identical table).
|
||||
# Topic keywords for classification
|
||||
TOPIC_KEYWORDS = {
|
||||
"guitar": ["guitar", "music", "teaching", "course", "lesson", "chord", "scale"],
|
||||
"coding": ["code", "python", "script", "function", "debug", "build", "deploy"],
|
||||
@@ -48,47 +41,17 @@ TOPIC_KEYWORDS = {
|
||||
"creative": ["write", "design", "create", "build", "make", "art", "music"],
|
||||
}
|
||||
|
||||
# Where the Rust core (qm_loader.py + target/release/libquery_memory.so) lives.
|
||||
_QM_CORE_DIR = os.environ.get(
|
||||
"QM_CORE_DIR", "/mnt/workdrive/rune/src/rust/query_memory"
|
||||
)
|
||||
|
||||
if _QM_CORE_DIR not in sys.path:
|
||||
sys.path.insert(0, _QM_CORE_DIR)
|
||||
|
||||
try:
|
||||
from qm_loader import QueryMemory as _RustQueryMemory
|
||||
except ImportError as _e: # pragma: no cover - deployment integrity failure
|
||||
raise ImportError(
|
||||
f"query_memory shim: cannot load the Rust core from {_QM_CORE_DIR!r} "
|
||||
f"({_e}). The cdylib must be built: `cargo build --release` in "
|
||||
f"{_QM_CORE_DIR}. No Python fallback exists by design."
|
||||
) from _e
|
||||
|
||||
|
||||
class QueryMemory(_RustQueryMemory):
|
||||
"""Query memory system for adaptive retrieval (Rust core, Python API).
|
||||
|
||||
API (identical to the historical Python implementation):
|
||||
* classify_query(query) -> str
|
||||
* adaptive_exploration_rate(query) -> float
|
||||
* record_query(query, strategy, success) -> None
|
||||
* get_topic_stats() -> dict (topic -> stats, insertion order)
|
||||
* get_dead_weight_topics() -> list[str]
|
||||
* get_health_report() -> dict
|
||||
"""
|
||||
class QueryMemory:
|
||||
"""Query memory system for adaptive retrieval."""
|
||||
|
||||
def __init__(self):
|
||||
# Match the historical constructor: ensure the store dir exists,
|
||||
# resolve the store from $HOME (qm_new's native behaviour).
|
||||
os.makedirs(QUERY_MEMORY_DIR, exist_ok=True)
|
||||
super().__init__()
|
||||
# Historical in-memory attribute: query history loaded at construction,
|
||||
# appended by record_query. (canary check 2 reads len(qm.history).)
|
||||
self.history = self._load_history()
|
||||
self.history: List[dict] = self._load_history()
|
||||
self.topic_stats: Dict[str, dict] = self._load_topic_stats()
|
||||
|
||||
def _load_history(self):
|
||||
"""Load query history from disk (historical shape: list of dicts)."""
|
||||
def _load_history(self) -> List[dict]:
|
||||
"""Load query history from disk."""
|
||||
if not os.path.exists(QUERY_HISTORY_FILE):
|
||||
return []
|
||||
entries = []
|
||||
@@ -100,16 +63,127 @@ class QueryMemory(_RustQueryMemory):
|
||||
continue
|
||||
return entries
|
||||
|
||||
def _save_history(self, entry: dict):
|
||||
"""Append a query entry to history."""
|
||||
with open(QUERY_HISTORY_FILE, "a") as f:
|
||||
f.write(json.dumps(entry) + "\n")
|
||||
|
||||
def _load_topic_stats(self) -> Dict[str, dict]:
|
||||
"""Load topic statistics from disk."""
|
||||
if os.path.exists(TOPIC_STATS_FILE):
|
||||
try:
|
||||
with open(TOPIC_STATS_FILE) as f:
|
||||
return json.load(f)
|
||||
except json.JSONDecodeError:
|
||||
return {}
|
||||
return {}
|
||||
|
||||
def _save_topic_stats(self):
|
||||
"""Save topic statistics to disk."""
|
||||
with open(TOPIC_STATS_FILE, "w") as f:
|
||||
json.dump(self.topic_stats, f, indent=2)
|
||||
|
||||
def classify_query(self, query: str) -> str:
|
||||
"""Classify a query into a topic.
|
||||
|
||||
Returns the topic with the most keyword matches.
|
||||
Falls back to "general" if no strong match.
|
||||
"""
|
||||
query_lower = query.lower()
|
||||
scores = {}
|
||||
for topic, keywords in TOPIC_KEYWORDS.items():
|
||||
score = sum(1 for kw in keywords if kw in query_lower)
|
||||
if score > 0:
|
||||
scores[topic] = score
|
||||
|
||||
if not scores:
|
||||
return "general"
|
||||
|
||||
return max(scores, key=scores.get)
|
||||
|
||||
def record_query(self, query: str, strategy: str, success: bool):
|
||||
"""Record through the Rust core, then mirror the historical in-memory append."""
|
||||
super().record_query(query, strategy, success)
|
||||
self.history.append({
|
||||
"""Record a query and its outcome.
|
||||
|
||||
Args:
|
||||
query: The query text
|
||||
strategy: "consolidated" or "full_retrieval"
|
||||
success: Whether the retrieval produced useful results
|
||||
"""
|
||||
topic = self.classify_query(query)
|
||||
entry = {
|
||||
"query": query[:100],
|
||||
"topic": self.classify_query(query),
|
||||
"topic": topic,
|
||||
"strategy": strategy,
|
||||
"success": success,
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
})
|
||||
}
|
||||
self.history.append(entry)
|
||||
self._save_history(entry)
|
||||
|
||||
# Update topic stats
|
||||
if topic not in self.topic_stats:
|
||||
self.topic_stats[topic] = {
|
||||
"total_queries": 0,
|
||||
"successful_queries": 0,
|
||||
"consolidated_hits": 0,
|
||||
"full_retrieval_hits": 0,
|
||||
"exploration_rate": 0.30, # default
|
||||
}
|
||||
|
||||
stats = self.topic_stats[topic]
|
||||
stats["total_queries"] += 1
|
||||
if success:
|
||||
stats["successful_queries"] += 1
|
||||
if strategy == "consolidated":
|
||||
stats["consolidated_hits"] += 1
|
||||
else:
|
||||
stats["full_retrieval_hits"] += 1
|
||||
|
||||
# Adaptive exploration rate: decrease for well-tested topics
|
||||
if stats["total_queries"] >= 10:
|
||||
success_rate = stats["successful_queries"] / stats["total_queries"]
|
||||
if success_rate > 0.8:
|
||||
stats["exploration_rate"] = max(0.10, stats["exploration_rate"] - 0.05)
|
||||
elif success_rate < 0.5:
|
||||
stats["exploration_rate"] = min(0.50, stats["exploration_rate"] + 0.05)
|
||||
|
||||
self._save_topic_stats()
|
||||
|
||||
def get_topic_stats(self) -> Dict[str, dict]:
|
||||
"""Get topic statistics."""
|
||||
return self.topic_stats
|
||||
|
||||
def adaptive_exploration_rate(self, query: str) -> float:
|
||||
"""Get the exploration rate for a query based on its topic.
|
||||
|
||||
Well-tested topics have lower exploration rates.
|
||||
Untested topics have higher exploration rates.
|
||||
"""
|
||||
topic = self.classify_query(query)
|
||||
if topic in self.topic_stats:
|
||||
return self.topic_stats[topic].get("exploration_rate", 0.30)
|
||||
return 0.50 # untested topics get high exploration
|
||||
|
||||
def get_dead_weight_topics(self) -> List[str]:
|
||||
"""Get topics with low proven uses (dead weight)."""
|
||||
dead = []
|
||||
for topic, stats in self.topic_stats.items():
|
||||
if stats["total_queries"] < 5:
|
||||
dead.append(topic)
|
||||
return dead
|
||||
|
||||
def get_health_report(self) -> dict:
|
||||
"""Get a health report of the query memory system."""
|
||||
total_queries = len(self.history)
|
||||
topics = len(self.topic_stats)
|
||||
dead_topics = len(self.get_dead_weight_topics())
|
||||
|
||||
return {
|
||||
"total_queries": total_queries,
|
||||
"topics_tracked": topics,
|
||||
"dead_weight_topics": dead_topics,
|
||||
"topic_stats": self.topic_stats,
|
||||
}
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
Binary file not shown.
@@ -1,3 +0,0 @@
|
||||
module rune/abstraction
|
||||
|
||||
go 1.21
|
||||
@@ -1,91 +0,0 @@
|
||||
// abstraction — Go fact extraction (R2 W5c).
|
||||
// Uses the Survivor cognition package to call the Rust kernel.
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
fmt.Fprintln(os.Stderr, "usage: abstraction <extract|status> <text>")
|
||||
os.Exit(1)
|
||||
}
|
||||
cmd := os.Args[1]
|
||||
|
||||
switch cmd {
|
||||
case "extract":
|
||||
text := strings.Join(os.Args[2:], " ")
|
||||
if len(text) < 8 {
|
||||
out, _ := json.Marshal(map[string]interface{}{
|
||||
"extracted": 0, "error": "text too short"})
|
||||
fmt.Println(string(out))
|
||||
return
|
||||
}
|
||||
// The deterministic kernel is already in Rust (cc_abstraction_extract_facts)
|
||||
// This Go module is the orchestration layer
|
||||
facts := extractFacts(text, nil, 10)
|
||||
out, _ := json.MarshalIndent(map[string]interface{}{
|
||||
"extracted": len(facts), "facts": facts,
|
||||
}, "", " ")
|
||||
fmt.Println(string(out))
|
||||
|
||||
default:
|
||||
fmt.Fprintf(os.Stderr, "unknown command: %s\n", cmd)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// extractFacts: deterministic sentence splitting + keyword extraction
|
||||
func extractFacts(text string, stopwords []string, minLen int) []map[string]interface{} {
|
||||
// Filter content words
|
||||
stop := make(map[string]bool)
|
||||
for _, w := range stopwords {
|
||||
stop[w] = true
|
||||
}
|
||||
// Default stopwords if none provided
|
||||
if len(stop) == 0 {
|
||||
for _, w := range strings.Fields("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") {
|
||||
stop[w] = true
|
||||
}
|
||||
}
|
||||
|
||||
// Split into sentences
|
||||
sentences := strings.Split(text, ". ")
|
||||
var facts []map[string]interface{}
|
||||
for _, sentence := range sentences {
|
||||
sentence = strings.TrimSpace(sentence)
|
||||
if sentence == "" {
|
||||
continue
|
||||
}
|
||||
if !strings.HasSuffix(sentence, ".") {
|
||||
sentence += "."
|
||||
}
|
||||
if len(sentence) < minLen {
|
||||
continue
|
||||
}
|
||||
// Extract content words
|
||||
words := strings.Fields(sentence)
|
||||
var contentWords []string
|
||||
for _, w := range words {
|
||||
w = strings.TrimRight(strings.ToLower(w), ".,!?;:")
|
||||
if len([]rune(w)) >= 4 && !stop[w] {
|
||||
contentWords = append(contentWords, w)
|
||||
}
|
||||
}
|
||||
facts = append(facts, map[string]interface{}{
|
||||
"what": sentence,
|
||||
"when": "",
|
||||
"where": "",
|
||||
"who": "",
|
||||
"why": "",
|
||||
"type": "experience",
|
||||
"entities": []string{},
|
||||
"content_words": contentWords,
|
||||
})
|
||||
}
|
||||
return facts
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
module rune/adaptive-router
|
||||
|
||||
go 1.21
|
||||
@@ -1,660 +0,0 @@
|
||||
// adaptive-router — DEEP PARITY PORT of src/rune/adaptive_router.py (625 lines,
|
||||
// 19 functions). The canonical adaptive route authority (ADAPT-2, #291).
|
||||
//
|
||||
// Dichotomy placement: Go owns the route authority — routing decides what the
|
||||
// system does NEXT (initiate/respond/route). The one deterministic leaf
|
||||
// (detect_flags) is Rust compute, linked via the Survivor staticlib pattern
|
||||
// from src/rust/route_risk_flags (no .so, no env var, no dlopen).
|
||||
//
|
||||
// Parity standard (Nick, 2026-10-07): every function ported, parity proven
|
||||
// against the Python oracle battery (truth.json, committed) BEFORE any
|
||||
// Python removal. The Go test replays every truth case through the ported
|
||||
// logic — CI fails if behavior diverges.
|
||||
package main
|
||||
|
||||
/*
|
||||
#cgo LDFLAGS: ${SRCDIR}/../../rust/route_risk_flags/target/release/libroute_risk_flags.a -lpthread -ldl -lm
|
||||
#include <stdlib.h>
|
||||
#include <stddef.h>
|
||||
|
||||
extern char* rrf_detect(const char* arg, size_t arg_len);
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// ---- Rust membrane (Survivor staticlib) ----
|
||||
|
||||
type flagResult struct {
|
||||
Risk []string `json:"risk"`
|
||||
Uncertainty []string `json:"uncertainty"`
|
||||
}
|
||||
|
||||
// detectFlags is the Rust rrf_detect kernel — the deterministic flag scanner.
|
||||
func detectFlags(bodyLower string) (risk []string, uncertainty []string) {
|
||||
cArg := C.CString(bodyLower)
|
||||
defer C.free(unsafe.Pointer(cArg))
|
||||
result := C.rrf_detect(cArg, C.size_t(len(bodyLower)))
|
||||
defer C.free(unsafe.Pointer(result))
|
||||
var fr flagResult
|
||||
if err := json.Unmarshal([]byte(C.GoString(result)), &fr); err != nil {
|
||||
return nil, nil
|
||||
}
|
||||
return fr.Risk, fr.Uncertainty
|
||||
}
|
||||
|
||||
// ---- Domain (ported verbatim from Python) ----
|
||||
|
||||
var ROUTES = map[string]bool{"LOCAL_FIX": true, "STANDARD_CHANGE": true, "RESEARCHED_CHANGE": true}
|
||||
|
||||
var FLOOR_RISK_FLAGS = []string{"new_authority", "architecture_change", "data_loss_risk", "external_service", "memory_architecture"}
|
||||
var FLOOR_UNCERTAINTY_FLAGS = []string{"competing_designs", "expensive_reversal"}
|
||||
var FLOOR_EXPLICIT_MARKERS = []string{"new subsystem", "new epic", "major external", "adopt", "replacement", "architecture research"}
|
||||
|
||||
var ErrFloorViolation = errors.New("FloorViolation: a downgrade was attempted on a route protected by the research floor")
|
||||
|
||||
type SufficiencyInputs struct {
|
||||
LocalAuthority string `json:"local_authority"`
|
||||
ExternalDependency string `json:"external_dependency"`
|
||||
VersionFreshnessRisk string `json:"version_freshness_risk"`
|
||||
Verifiability string `json:"verifiability"`
|
||||
ScopeNovelty string `json:"scope_novelty"`
|
||||
Provenance map[string]string `json:"provenance"`
|
||||
}
|
||||
|
||||
func (s *SufficiencyInputs) Unknowns() []string {
|
||||
names := []string{"local_authority", "external_dependency", "version_freshness_risk", "verifiability", "scope_novelty"}
|
||||
vals := []string{s.LocalAuthority, s.ExternalDependency, s.VersionFreshnessRisk, s.Verifiability, s.ScopeNovelty}
|
||||
var out []string
|
||||
for i, v := range vals {
|
||||
if v == "UNKNOWN" {
|
||||
out = append(out, names[i])
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type RouteDecision struct {
|
||||
Route string `json:"route"`
|
||||
Reasons []string `json:"reasons"`
|
||||
RiskFlags []string `json:"risk_flags"`
|
||||
UncertaintyFlags []string `json:"uncertainty_flags"`
|
||||
Sufficiency *SufficiencyInputs `json:"sufficiency,omitempty"`
|
||||
Unknowns []string `json:"unknowns,omitempty"`
|
||||
Confidence string `json:"confidence"`
|
||||
DecidedBy string `json:"decided_by"`
|
||||
DecidedAt string `json:"decided_at"`
|
||||
TaskDescription string `json:"task_description"`
|
||||
BaselineSHA string `json:"baseline_sha"`
|
||||
PreviousRoute *string `json:"previous_route,omitempty"`
|
||||
Trigger *string `json:"trigger,omitempty"`
|
||||
Evidence *string `json:"evidence,omitempty"`
|
||||
Floor bool `json:"floor"`
|
||||
}
|
||||
|
||||
func now() string {
|
||||
// Python: datetime.now(timezone.utc).isoformat() → 2026-10-07T09:15:23.123456+00:00
|
||||
return time.Now().UTC().Format("2006-01-02T15:04:05.000000+00:00")
|
||||
}
|
||||
|
||||
func truncate(s string, n int) string {
|
||||
r := []rune(s)
|
||||
if len(r) > n {
|
||||
return string(r[:n])
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// ---- Flag-driven floor predicates ----
|
||||
|
||||
func floorAppliesFromFlags(risk, uncertainty []string, bodyLower string) bool {
|
||||
for _, f := range risk {
|
||||
if contains(FLOOR_RISK_FLAGS, f) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, f := range uncertainty {
|
||||
if contains(FLOOR_UNCERTAINTY_FLAGS, f) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, m := range FLOOR_EXPLICIT_MARKERS {
|
||||
if strings.Contains(bodyLower, m) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func floorReason(risk, uncertainty []string, bodyLower string) string {
|
||||
var hits []string
|
||||
for _, f := range risk {
|
||||
if contains(FLOOR_RISK_FLAGS, f) {
|
||||
hits = append(hits, f)
|
||||
}
|
||||
}
|
||||
for _, f := range uncertainty {
|
||||
if contains(FLOOR_UNCERTAINTY_FLAGS, f) {
|
||||
hits = append(hits, f)
|
||||
}
|
||||
}
|
||||
for _, m := range FLOOR_EXPLICIT_MARKERS {
|
||||
if strings.Contains(bodyLower, m) {
|
||||
hits = append(hits, m)
|
||||
}
|
||||
}
|
||||
if len(hits) == 0 {
|
||||
return "unclassified"
|
||||
}
|
||||
return strings.Join(hits, ", ")
|
||||
}
|
||||
|
||||
// FloorApplies is the public floor predicate (canary 5).
|
||||
func FloorApplies(route string, flags []string) bool {
|
||||
if route != "RESEARCHED_CHANGE" {
|
||||
return false
|
||||
}
|
||||
for _, f := range flags {
|
||||
if contains(FLOOR_RISK_FLAGS, f) || contains(FLOOR_UNCERTAINTY_FLAGS, f) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func BodyHasFloorTrigger(bodyLower string) bool {
|
||||
risk, uncertainty := detectFlags(bodyLower)
|
||||
return floorAppliesFromFlags(risk, uncertainty, bodyLower)
|
||||
}
|
||||
|
||||
// ---- classify_route ----
|
||||
|
||||
type classifyInput struct {
|
||||
Body string `json:"body"`
|
||||
HasLocalRepro bool `json:"has_local_repro"`
|
||||
OwningAuthorityKnown bool `json:"owning_authority_known"`
|
||||
TestableLocally bool `json:"testable_locally"`
|
||||
NarrowAndReversible bool `json:"narrow_and_reversible"`
|
||||
Sufficiency *SufficiencyInputs `json:"sufficiency"`
|
||||
PipelineSHA string `json:"pipeline_sha"`
|
||||
}
|
||||
|
||||
var defectWords = []string{"fix", "bug", "broken", "regression", "wrong", "typo", "fails", "failing", "crash", "defect"}
|
||||
|
||||
func ClassifyRoute(in classifyInput) RouteDecision {
|
||||
var reasons []string
|
||||
bodyLower := strings.ToLower(in.Body)
|
||||
|
||||
var suff *SufficiencyInputs
|
||||
prov := map[string]string{}
|
||||
if in.Sufficiency == nil {
|
||||
// LEGACY COMPAT PATH: raw booleans, no provenance. Missing booleans
|
||||
// are "not established", NOT unknown material facts.
|
||||
la := "NOT_GROUNDED"
|
||||
if in.HasLocalRepro && in.OwningAuthorityKnown {
|
||||
la = "GROUNDED"
|
||||
}
|
||||
ver := "NONE"
|
||||
if in.TestableLocally {
|
||||
ver = "TESTABLE"
|
||||
}
|
||||
suff = &SufficiencyInputs{LocalAuthority: la, Verifiability: ver, Provenance: map[string]string{}}
|
||||
prov["legacy_inputs"] = "has_local_repro/owning_authority_known/testable_locally booleans from caller (compat)"
|
||||
} else {
|
||||
suff = in.Sufficiency
|
||||
}
|
||||
for k, v := range suff.Provenance {
|
||||
prov[k] = v
|
||||
}
|
||||
|
||||
risk, uncertainty := detectFlags(bodyLower)
|
||||
|
||||
unknowns := suff.Unknowns()
|
||||
if _, legacy := prov["legacy_inputs"]; legacy {
|
||||
unknowns = nil // legacy path: boolean conditions own the decision
|
||||
}
|
||||
floor := floorAppliesFromFlags(risk, uncertainty, bodyLower)
|
||||
|
||||
if len(unknowns) > 0 {
|
||||
reasons = append(reasons, "material unknowns present: "+strings.Join(unknowns, ", "))
|
||||
reasons = append(reasons, "escalating per doctrine: never manufacture certainty")
|
||||
}
|
||||
|
||||
taskLanguage := suff.Provenance["task_class_language"]
|
||||
isDefectRoute := taskLanguage == "defect"
|
||||
for _, w := range defectWords {
|
||||
if strings.Contains(bodyLower, w) {
|
||||
isDefectRoute = true
|
||||
break
|
||||
}
|
||||
}
|
||||
localOK := in.HasLocalRepro && in.OwningAuthorityKnown &&
|
||||
(in.TestableLocally || (in.NarrowAndReversible && suff.Verifiability == "NONE"))
|
||||
if localOK && isDefectRoute && len(risk) == 0 && len(uncertainty) == 0 && len(unknowns) == 0 && !floor {
|
||||
reasons = append(reasons, "all LOCAL_FIX conditions met; no unknowns; no floor")
|
||||
return makeDecision("LOCAL_FIX", reasons, risk, uncertainty, suff, unknowns, "HIGH", in.Body, in.PipelineSHA, false)
|
||||
}
|
||||
|
||||
if floor {
|
||||
reasons = append(reasons, "deep-research floor: "+floorReason(risk, uncertainty, bodyLower))
|
||||
return makeDecision("RESEARCHED_CHANGE", reasons, risk, uncertainty, suff, unknowns, "HIGH", in.Body, in.PipelineSHA, true)
|
||||
}
|
||||
|
||||
if len(risk) > 0 || len(uncertainty) > 0 || len(unknowns) > 0 {
|
||||
if len(risk) > 0 || len(uncertainty) > 0 {
|
||||
reasons = append(reasons, "risk/uncertainty flags: "+strings.Join(append(append([]string{}, risk...), uncertainty...), ", "))
|
||||
}
|
||||
reasons = append(reasons, "RESEARCHED_CHANGE: external evidence and adversarial validation justified")
|
||||
return makeDecision("RESEARCHED_CHANGE", reasons, risk, uncertainty, suff, unknowns, "HIGH", in.Body, in.PipelineSHA, floor)
|
||||
}
|
||||
|
||||
reasons = append(reasons, "clear change, existing authority, no consequential selection")
|
||||
return makeDecision("STANDARD_CHANGE", reasons, risk, uncertainty, suff, unknowns, "MEDIUM", in.Body, in.PipelineSHA, false)
|
||||
}
|
||||
|
||||
func makeDecision(route string, reasons []string, risk, uncertainty []string, suff *SufficiencyInputs, unknowns []string, confidence, task, sha string, floor bool) RouteDecision {
|
||||
var filtered []string
|
||||
for _, r := range reasons {
|
||||
if r != "" {
|
||||
filtered = append(filtered, r)
|
||||
}
|
||||
}
|
||||
if filtered == nil {
|
||||
filtered = []string{}
|
||||
}
|
||||
return RouteDecision{
|
||||
Route: route, Reasons: filtered,
|
||||
RiskFlags: risk, UncertaintyFlags: uncertainty,
|
||||
Sufficiency: suff, Unknowns: unknowns,
|
||||
Confidence: confidence, DecidedBy: "deterministic", DecidedAt: now(),
|
||||
TaskDescription: truncate(task, 200), BaselineSHA: sha, Floor: floor,
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Escalation / downgrade ----
|
||||
|
||||
func escalateRoute(d RouteDecision, newRoute, trigger, evidence string) (RouteDecision, error) {
|
||||
if !ROUTES[newRoute] {
|
||||
return RouteDecision{}, fmt.Errorf("invalid route: %s", newRoute)
|
||||
}
|
||||
up := RouteDecision{
|
||||
Route: newRoute, Reasons: []string{"escalation: " + trigger},
|
||||
RiskFlags: d.RiskFlags, UncertaintyFlags: d.UncertaintyFlags,
|
||||
Sufficiency: d.Sufficiency, Unknowns: d.Unknowns,
|
||||
Confidence: "HIGH", DecidedBy: "escalation", DecidedAt: now(),
|
||||
TaskDescription: d.TaskDescription, BaselineSHA: d.BaselineSHA,
|
||||
PreviousRoute: strPtr(d.Route), Trigger: strPtr(trigger), Evidence: strPtr(evidence),
|
||||
Floor: d.Floor,
|
||||
}
|
||||
return up, nil
|
||||
}
|
||||
|
||||
func downgradeRoute(d RouteDecision, newRoute, trigger, evidence string) (RouteDecision, error) {
|
||||
if !ROUTES[newRoute] {
|
||||
return RouteDecision{}, fmt.Errorf("invalid route: %s", newRoute)
|
||||
}
|
||||
if d.Floor && newRoute != "RESEARCHED_CHANGE" {
|
||||
return RouteDecision{}, ErrFloorViolation
|
||||
}
|
||||
down := RouteDecision{
|
||||
Route: newRoute, Reasons: []string{"downgrade: " + trigger},
|
||||
RiskFlags: d.RiskFlags, UncertaintyFlags: d.UncertaintyFlags,
|
||||
Sufficiency: d.Sufficiency, Unknowns: d.Unknowns,
|
||||
Confidence: "HIGH", DecidedBy: "downgrade", DecidedAt: now(),
|
||||
TaskDescription: d.TaskDescription, BaselineSHA: d.BaselineSHA,
|
||||
PreviousRoute: strPtr(d.Route), Trigger: strPtr(trigger), Evidence: strPtr(evidence),
|
||||
Floor: d.Floor,
|
||||
}
|
||||
return down, nil
|
||||
}
|
||||
|
||||
func escalateOnVerificationFailure(d RouteDecision, failureEvidence string) (RouteDecision, error) {
|
||||
if len(strings.TrimSpace(failureEvidence)) < 20 {
|
||||
return RouteDecision{}, errors.New("verification failure evidence must establish the material uncertainty (what external/architectural fact is in doubt), not merely report that a check failed")
|
||||
}
|
||||
return escalateRoute(d, "RESEARCHED_CHANGE", "verification_failure_external_uncertainty", failureEvidence)
|
||||
}
|
||||
|
||||
// ---- Append-only event recording ----
|
||||
|
||||
func event(kind string, d RouteDecision) map[string]any {
|
||||
ev := map[string]any{
|
||||
"kind": kind, "route": d.Route, "reasons": d.Reasons,
|
||||
"risk_flags": d.RiskFlags, "uncertainty_flags": d.UncertaintyFlags,
|
||||
"confidence": d.Confidence, "decided_by": d.DecidedBy,
|
||||
"decided_at": d.DecidedAt, "task_description": d.TaskDescription,
|
||||
"baseline_sha": d.BaselineSHA,
|
||||
}
|
||||
if d.Sufficiency != nil {
|
||||
if d.Unknowns == nil {
|
||||
ev["unknowns"] = []string{}
|
||||
} else {
|
||||
ev["unknowns"] = d.Unknowns
|
||||
}
|
||||
ev["provenance"] = d.Sufficiency.Provenance
|
||||
}
|
||||
if kind != "INITIAL_ROUTE" {
|
||||
ev["previous_route"] = d.PreviousRoute
|
||||
ev["new_route"] = d.Route
|
||||
ev["trigger"] = d.Trigger
|
||||
ev["evidence"] = d.Evidence
|
||||
}
|
||||
if d.Floor {
|
||||
ev["floor"] = true
|
||||
}
|
||||
return ev
|
||||
}
|
||||
|
||||
func recordTransition(kind string, d RouteDecision, path string) error {
|
||||
if dir := filepath.Dir(path); dir != "." {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
b, err := json.Marshal(event(kind, d))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
_, err = f.Write(append(b, '\n'))
|
||||
return err
|
||||
}
|
||||
|
||||
func recordRouteDecision(d RouteDecision, path string, dispatch map[string]any) error {
|
||||
ev := event("INITIAL_ROUTE", d)
|
||||
if dispatch != nil {
|
||||
ev["dispatch"] = dispatch
|
||||
}
|
||||
if dir := filepath.Dir(path); dir != "." {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
b, err := json.Marshal(ev)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
_, err = f.Write(append(b, '\n'))
|
||||
return err
|
||||
}
|
||||
|
||||
func buildResearchDispatch(taskID, description string, d RouteDecision) map[string]any {
|
||||
prov := map[string]string{}
|
||||
if d.Sufficiency != nil {
|
||||
prov = d.Sufficiency.Provenance
|
||||
}
|
||||
return map[string]any{
|
||||
"task_id": taskID, "title": truncate(description, 200), "body": description,
|
||||
"route": d.Route, "floor": d.Floor, "reasons": d.Reasons, "unknowns": d.Unknowns,
|
||||
"provenance": prov,
|
||||
"executor_entry": "research_stage_executor.py --stage ISSUE (with issue-shaped input)",
|
||||
}
|
||||
}
|
||||
|
||||
// ---- derive_sufficiency (Option C unified authority, 2026-09-10) ----
|
||||
|
||||
var mechanismWords = []string{"performance", "throughput", "latency", "race condition", "timing", "under load", "concurrency", "deadlock", "memory usage", "benchmark needed", "measure"}
|
||||
var changeWords = []string{"add ", "implement", "extend", "refactor", "introduce", "support for", "new feature"}
|
||||
var inspectionVerbs = []string{"inspect", "read", "review", "analyze", "analyse", "explain", "look", "list", "show", "describe", "check", "what", "why", "how", "where", "which"}
|
||||
var versionWords = []string{"version", "upgrade", "latest", "current behaviour"}
|
||||
var externalMarkers = []string{" api ", "sdk", "library", "package", "service", "endpoint"}
|
||||
|
||||
var testSurfaceRE = regexp.MustCompile(`(?i)(tests/[\w/.\-]+|test_[\w/.\-]+\.py|pytest|unittest|run (the )?tests)`)
|
||||
|
||||
func detectExternalRefs(body string) string {
|
||||
lower := strings.ToLower(body)
|
||||
if strings.Contains(lower, "http://") || strings.Contains(lower, "https://") {
|
||||
return "PRESENT"
|
||||
}
|
||||
for _, m := range externalMarkers {
|
||||
if strings.Contains(lower, m) {
|
||||
return "PRESENT"
|
||||
}
|
||||
}
|
||||
return "NONE"
|
||||
}
|
||||
|
||||
type deriveInput struct {
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
EvidenceClasses []string `json:"evidence_classes"`
|
||||
Ambiguous bool `json:"ambiguous"`
|
||||
}
|
||||
|
||||
func DeriveSufficiency(in deriveInput) SufficiencyInputs {
|
||||
title, body := in.Title, in.Body
|
||||
full := title + "\n" + body
|
||||
lower := strings.ToLower(full)
|
||||
bodyLower := strings.ToLower(body)
|
||||
|
||||
mechanismUncertain := false
|
||||
for _, w := range mechanismWords {
|
||||
if strings.Contains(lower, w) {
|
||||
mechanismUncertain = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
verifiability := "NONE"
|
||||
if testSurfaceRE.MatchString(body) {
|
||||
verifiability = "TESTABLE"
|
||||
}
|
||||
if mechanismUncertain && verifiability == "TESTABLE" {
|
||||
verifiability = "MEASUREMENT_REQUIRED"
|
||||
}
|
||||
|
||||
external := detectExternalRefs(body)
|
||||
|
||||
scopeNovel := "KNOWN_PATTERN"
|
||||
for _, m := range FLOOR_EXPLICIT_MARKERS {
|
||||
if strings.Contains(bodyLower, m) {
|
||||
scopeNovel = "NEW_SUBSYSTEM"
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
var grounded bool
|
||||
if in.EvidenceClasses != nil {
|
||||
grounded = len(in.EvidenceClasses) == 1 && in.EvidenceClasses[0] == "repo" && !mechanismUncertain
|
||||
} else {
|
||||
grounded = external == "NONE" && !mechanismUncertain && scopeNovel == "KNOWN_PATTERN"
|
||||
}
|
||||
|
||||
isDefect := false
|
||||
for _, w := range defectWords {
|
||||
if strings.Contains(lower, w) {
|
||||
isDefect = true
|
||||
break
|
||||
}
|
||||
}
|
||||
isChange := false
|
||||
for _, w := range changeWords {
|
||||
if strings.Contains(lower, w) {
|
||||
isChange = true
|
||||
break
|
||||
}
|
||||
}
|
||||
// Handoff §10: the ACTION VERB governs mutation-class. A leading
|
||||
// inspection verb makes the task read-only.
|
||||
firstWords := strings.Fields(lower)
|
||||
if len(firstWords) > 3 {
|
||||
firstWords = firstWords[:3]
|
||||
}
|
||||
for _, w := range firstWords {
|
||||
if contains(inspectionVerbs, w) {
|
||||
isDefect = false
|
||||
isChange = false
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
vfr := "NONE"
|
||||
if external == "PRESENT" {
|
||||
for _, w := range versionWords {
|
||||
if strings.Contains(bodyLower, w) {
|
||||
vfr = "RISK"
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
la := "NOT_GROUNDED"
|
||||
if grounded {
|
||||
la = "GROUNDED"
|
||||
}
|
||||
taskClass := "neutral"
|
||||
if isDefect {
|
||||
taskClass = "defect"
|
||||
} else if isChange {
|
||||
taskClass = "change"
|
||||
}
|
||||
return SufficiencyInputs{
|
||||
LocalAuthority: la,
|
||||
ExternalDependency: external,
|
||||
VersionFreshnessRisk: vfr,
|
||||
Verifiability: verifiability,
|
||||
ScopeNovelty: scopeNovel,
|
||||
Provenance: map[string]string{
|
||||
"local_authority": "ISSUE contract evidence_classes (deterministic compiler) + mechanism-uncertainty scan (measurement language)",
|
||||
"mechanism_uncertain": fmt.Sprintf("%t", mechanismUncertain),
|
||||
"external_dependency": "URL/external-reference scan of issue body",
|
||||
"version_freshness_risk": "version-language scan, gated on external dependency",
|
||||
"verifiability": "test path/command reference; measurement language overrides",
|
||||
"scope_novelty": "explicit new-subsystem/adoption markers in issue body",
|
||||
"task_class_language": taskClass,
|
||||
"ambiguous": fmt.Sprintf("%t", in.Ambiguous),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ---- helpers ----
|
||||
|
||||
func contains(list []string, s string) bool {
|
||||
for _, x := range list {
|
||||
if x == s {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func strPtr(s string) *string { return &s }
|
||||
|
||||
// ---- CLI: JSON on stdin, JSON on stdout, one op per invocation ----
|
||||
|
||||
func main() {
|
||||
var req map[string]any
|
||||
dec := json.NewDecoder(os.Stdin)
|
||||
if err := dec.Decode(&req); err != nil {
|
||||
emit(map[string]any{"error": "ValueError", "message": "bad JSON input: " + err.Error()})
|
||||
os.Exit(1)
|
||||
}
|
||||
op, _ := req["op"].(string)
|
||||
raw, _ := json.Marshal(req)
|
||||
switch op {
|
||||
case "classify":
|
||||
var in classifyInput
|
||||
json.Unmarshal(raw, &in)
|
||||
d := ClassifyRoute(in)
|
||||
emit(map[string]any{"route": d.Route, "confidence": d.Confidence, "reasons": d.Reasons,
|
||||
"risk": d.RiskFlags, "uncertainty": d.UncertaintyFlags, "floor": d.Floor,
|
||||
"task_description": d.TaskDescription})
|
||||
case "derive":
|
||||
var in deriveInput
|
||||
json.Unmarshal(raw, &in)
|
||||
s := DeriveSufficiency(in)
|
||||
unk := s.Unknowns()
|
||||
if unk == nil {
|
||||
unk = []string{}
|
||||
}
|
||||
emit(map[string]any{"local_authority": s.LocalAuthority, "external_dependency": s.ExternalDependency,
|
||||
"version_freshness_risk": s.VersionFreshnessRisk, "verifiability": s.Verifiability,
|
||||
"scope_novelty": s.ScopeNovelty, "unknowns": unk,
|
||||
"task_class": s.Provenance["task_class_language"]})
|
||||
case "floor_trigger":
|
||||
body, _ := req["body"].(string)
|
||||
emit(map[string]any{"result": BodyHasFloorTrigger(strings.ToLower(body))})
|
||||
case "floor_applies":
|
||||
route, _ := req["route"].(string)
|
||||
flagsRaw, _ := json.Marshal(req["flags"])
|
||||
var flags []string
|
||||
json.Unmarshal(flagsRaw, &flags)
|
||||
emit(map[string]any{"result": FloorApplies(route, flags)})
|
||||
case "escalate", "downgrade", "verify_fail":
|
||||
d := decisionFromMap(req["decision"])
|
||||
newRoute, _ := req["new_route"].(string)
|
||||
trigger, _ := req["trigger"].(string)
|
||||
evidence, _ := req["evidence"].(string)
|
||||
var out RouteDecision
|
||||
var err error
|
||||
switch op {
|
||||
case "escalate":
|
||||
out, err = escalateRoute(d, newRoute, trigger, evidence)
|
||||
case "downgrade":
|
||||
out, err = downgradeRoute(d, newRoute, trigger, evidence)
|
||||
case "verify_fail":
|
||||
out, err = escalateOnVerificationFailure(d, evidence)
|
||||
}
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrFloorViolation) {
|
||||
emit(map[string]any{"error": "FloorViolation"})
|
||||
} else {
|
||||
emit(map[string]any{"error": "ValueError", "message": err.Error()})
|
||||
}
|
||||
return
|
||||
}
|
||||
if op == "verify_fail" {
|
||||
emit(map[string]any{"result": "ACCEPTED", "route": out.Route, "previous": deref(out.PreviousRoute),
|
||||
"decided_by": out.DecidedBy, "trigger": deref(out.Trigger)})
|
||||
return
|
||||
}
|
||||
emit(map[string]any{"route": out.Route, "previous": deref(out.PreviousRoute),
|
||||
"decided_by": out.DecidedBy, "trigger": deref(out.Trigger)})
|
||||
case "dispatch":
|
||||
taskID, _ := req["task_id"].(string)
|
||||
description, _ := req["description"].(string)
|
||||
d := decisionFromMap(req["decision"])
|
||||
emit(buildResearchDispatch(taskID, description, d))
|
||||
default:
|
||||
emit(map[string]any{"error": "ValueError", "message": "unknown op: " + op})
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func decisionFromMap(v any) RouteDecision {
|
||||
var d RouteDecision
|
||||
b, _ := json.Marshal(v)
|
||||
json.Unmarshal(b, &d)
|
||||
return d
|
||||
}
|
||||
|
||||
func deref(s *string) any {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
return *s
|
||||
}
|
||||
|
||||
func emit(v any) {
|
||||
enc := json.NewEncoder(os.Stdout)
|
||||
enc.Encode(v)
|
||||
}
|
||||
@@ -1,244 +0,0 @@
|
||||
[
|
||||
{
|
||||
"fn": "classify",
|
||||
"name": "local_fix_happy",
|
||||
"route": "LOCAL_FIX",
|
||||
"confidence": "HIGH",
|
||||
"reasons": [
|
||||
"all LOCAL_FIX conditions met; no unknowns; no floor"
|
||||
],
|
||||
"risk": [],
|
||||
"uncertainty": [],
|
||||
"floor": false,
|
||||
"task_description": "fix the broken typewriter regex in warm_router, crash on empty input"
|
||||
},
|
||||
{
|
||||
"fn": "classify",
|
||||
"name": "standard_change",
|
||||
"route": "STANDARD_CHANGE",
|
||||
"confidence": "MEDIUM",
|
||||
"reasons": [
|
||||
"clear change, existing authority, no consequential selection"
|
||||
],
|
||||
"risk": [],
|
||||
"uncertainty": [],
|
||||
"floor": false,
|
||||
"task_description": "add a progress bar to the export dialog"
|
||||
},
|
||||
{
|
||||
"fn": "classify",
|
||||
"name": "defect_word_absent",
|
||||
"route": "STANDARD_CHANGE",
|
||||
"confidence": "MEDIUM",
|
||||
"reasons": [
|
||||
"clear change, existing authority, no consequential selection"
|
||||
],
|
||||
"risk": [],
|
||||
"uncertainty": [],
|
||||
"floor": false,
|
||||
"task_description": "update the version number in the footer"
|
||||
},
|
||||
{
|
||||
"fn": "classify",
|
||||
"name": "floor_new_subsystem",
|
||||
"route": "RESEARCHED_CHANGE",
|
||||
"confidence": "HIGH",
|
||||
"reasons": [
|
||||
"deep-research floor: new subsystem, adopt, replacement"
|
||||
],
|
||||
"risk": [],
|
||||
"uncertainty": [],
|
||||
"floor": true,
|
||||
"task_description": "adopt a new subsystem for memory indexing, replacement of spine"
|
||||
},
|
||||
{
|
||||
"fn": "classify",
|
||||
"name": "risk_new_authority",
|
||||
"route": "RESEARCHED_CHANGE",
|
||||
"confidence": "HIGH",
|
||||
"reasons": [
|
||||
"deep-research floor: new_authority"
|
||||
],
|
||||
"risk": [
|
||||
"new_authority"
|
||||
],
|
||||
"uncertainty": [],
|
||||
"floor": true,
|
||||
"task_description": "this creates a new authority path for dispatch"
|
||||
},
|
||||
{
|
||||
"fn": "classify",
|
||||
"name": "uncertainty_competing",
|
||||
"route": "RESEARCHED_CHANGE",
|
||||
"confidence": "HIGH",
|
||||
"reasons": [
|
||||
"deep-research floor: competing_designs, expensive_reversal"
|
||||
],
|
||||
"risk": [],
|
||||
"uncertainty": [
|
||||
"competing_designs",
|
||||
"expensive_reversal"
|
||||
],
|
||||
"floor": true,
|
||||
"task_description": "there are competing designs here, expensive reversal likely"
|
||||
},
|
||||
{
|
||||
"fn": "classify",
|
||||
"name": "not_grounded",
|
||||
"route": "STANDARD_CHANGE",
|
||||
"confidence": "MEDIUM",
|
||||
"reasons": [
|
||||
"clear change, existing authority, no consequential selection"
|
||||
],
|
||||
"risk": [],
|
||||
"uncertainty": [],
|
||||
"floor": false,
|
||||
"task_description": "add support for markdown export"
|
||||
},
|
||||
{
|
||||
"fn": "classify",
|
||||
"name": "inspection_verb",
|
||||
"route": "LOCAL_FIX",
|
||||
"confidence": "HIGH",
|
||||
"reasons": [
|
||||
"all LOCAL_FIX conditions met; no unknowns; no floor"
|
||||
],
|
||||
"risk": [],
|
||||
"uncertainty": [],
|
||||
"floor": false,
|
||||
"task_description": "explain why the failing test fails"
|
||||
},
|
||||
{
|
||||
"fn": "derive",
|
||||
"name": "grounded_fix",
|
||||
"local_authority": "GROUNDED",
|
||||
"external_dependency": "NONE",
|
||||
"version_freshness_risk": "NONE",
|
||||
"verifiability": "TESTABLE",
|
||||
"scope_novelty": "KNOWN_PATTERN",
|
||||
"unknowns": [],
|
||||
"task_class": "defect"
|
||||
},
|
||||
{
|
||||
"fn": "derive",
|
||||
"name": "mechanism",
|
||||
"local_authority": "NOT_GROUNDED",
|
||||
"external_dependency": "NONE",
|
||||
"version_freshness_risk": "NONE",
|
||||
"verifiability": "NONE",
|
||||
"scope_novelty": "KNOWN_PATTERN",
|
||||
"unknowns": [],
|
||||
"task_class": "neutral"
|
||||
},
|
||||
{
|
||||
"fn": "derive",
|
||||
"name": "external_url",
|
||||
"local_authority": "NOT_GROUNDED",
|
||||
"external_dependency": "PRESENT",
|
||||
"version_freshness_risk": "NONE",
|
||||
"verifiability": "NONE",
|
||||
"scope_novelty": "KNOWN_PATTERN",
|
||||
"unknowns": [],
|
||||
"task_class": "neutral"
|
||||
},
|
||||
{
|
||||
"fn": "derive",
|
||||
"name": "version_risk",
|
||||
"local_authority": "NOT_GROUNDED",
|
||||
"external_dependency": "PRESENT",
|
||||
"version_freshness_risk": "RISK",
|
||||
"verifiability": "NONE",
|
||||
"scope_novelty": "KNOWN_PATTERN",
|
||||
"unknowns": [],
|
||||
"task_class": "neutral"
|
||||
},
|
||||
{
|
||||
"fn": "derive",
|
||||
"name": "inspection",
|
||||
"local_authority": "GROUNDED",
|
||||
"external_dependency": "NONE",
|
||||
"version_freshness_risk": "NONE",
|
||||
"verifiability": "NONE",
|
||||
"scope_novelty": "KNOWN_PATTERN",
|
||||
"unknowns": [],
|
||||
"task_class": "neutral"
|
||||
},
|
||||
{
|
||||
"fn": "derive",
|
||||
"name": "new_subsystem",
|
||||
"local_authority": "NOT_GROUNDED",
|
||||
"external_dependency": "NONE",
|
||||
"version_freshness_risk": "NONE",
|
||||
"verifiability": "NONE",
|
||||
"scope_novelty": "NEW_SUBSYSTEM",
|
||||
"unknowns": [],
|
||||
"task_class": "neutral"
|
||||
},
|
||||
{
|
||||
"fn": "derive",
|
||||
"name": "neutral",
|
||||
"local_authority": "GROUNDED",
|
||||
"external_dependency": "NONE",
|
||||
"version_freshness_risk": "NONE",
|
||||
"verifiability": "NONE",
|
||||
"scope_novelty": "KNOWN_PATTERN",
|
||||
"unknowns": [],
|
||||
"task_class": "neutral"
|
||||
},
|
||||
{
|
||||
"fn": "body_has_floor_trigger",
|
||||
"name": "trigger_yes",
|
||||
"body": "adopt a replacement for the cache",
|
||||
"result": true
|
||||
},
|
||||
{
|
||||
"fn": "body_has_floor_trigger",
|
||||
"name": "trigger_no",
|
||||
"body": "fix the typo",
|
||||
"result": false
|
||||
},
|
||||
{
|
||||
"fn": "floor_applies",
|
||||
"name": "res_yes",
|
||||
"route": "RESEARCHED_CHANGE",
|
||||
"result": true
|
||||
},
|
||||
{
|
||||
"fn": "floor_applies",
|
||||
"name": "local_no",
|
||||
"route": "LOCAL_FIX",
|
||||
"result": false
|
||||
},
|
||||
{
|
||||
"fn": "escalate",
|
||||
"name": "esc",
|
||||
"route": "RESEARCHED_CHANGE",
|
||||
"previous": "LOCAL_FIX",
|
||||
"decided_by": "escalation",
|
||||
"trigger": "verify_fail"
|
||||
},
|
||||
{
|
||||
"fn": "downgrade_ok",
|
||||
"name": "dg",
|
||||
"route": "STANDARD_CHANGE"
|
||||
},
|
||||
{
|
||||
"fn": "downgrade_floored",
|
||||
"name": "dgf",
|
||||
"route": "FLOOR_VIOLATION"
|
||||
},
|
||||
{
|
||||
"fn": "evidence_short",
|
||||
"name": "short",
|
||||
"result": "REJECTED"
|
||||
},
|
||||
{
|
||||
"fn": "dispatch",
|
||||
"name": "disp",
|
||||
"task_id": "T-1",
|
||||
"title": "research the memory index options",
|
||||
"route": "RESEARCHED_CHANGE",
|
||||
"floor": true,
|
||||
"executor_entry": "research_stage_executor.py --stage ISSUE (with issue-shaped input)"
|
||||
}
|
||||
]
|
||||
@@ -1,204 +0,0 @@
|
||||
package main
|
||||
|
||||
// truth_test.go — the parity gate. Replays every case from the PYTHON
|
||||
// oracle battery (truth.json, generated by scripts against
|
||||
// src/rune/adaptive_router.py) through this Go port and requires
|
||||
// identical outputs. A divergence fails CI — parity is the hard gate
|
||||
// before any Python removal (Nick, 2026-10-07: parity first, then
|
||||
// improvements).
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type truthCase map[string]any
|
||||
|
||||
func loadTruth(t *testing.T) []truthCase {
|
||||
b, err := os.ReadFile("truth.json")
|
||||
if err != nil {
|
||||
t.Fatalf("truth.json missing: %v", err)
|
||||
}
|
||||
var cases []truthCase
|
||||
if err := json.Unmarshal(b, &cases); err != nil {
|
||||
t.Fatalf("truth.json unparseable: %v", err)
|
||||
}
|
||||
return cases
|
||||
}
|
||||
|
||||
func eq(t *testing.T, name, field string, got, want any) {
|
||||
t.Helper()
|
||||
g, w := normalize(got), normalize(want)
|
||||
gs, _ := json.Marshal(g)
|
||||
ws, _ := json.Marshal(w)
|
||||
if string(gs) != string(ws) {
|
||||
t.Errorf("%s.%s: got %s want %s", name, field, gs, ws)
|
||||
}
|
||||
}
|
||||
|
||||
func normalize(v any) any {
|
||||
switch x := v.(type) {
|
||||
case float64:
|
||||
return x
|
||||
case []any:
|
||||
if x == nil {
|
||||
return []any{}
|
||||
}
|
||||
out := make([]any, len(x))
|
||||
for i, e := range x {
|
||||
out[i] = normalize(e)
|
||||
}
|
||||
return out
|
||||
case map[string]any:
|
||||
out := map[string]any{}
|
||||
for k, e := range x {
|
||||
out[k] = normalize(e)
|
||||
}
|
||||
return out
|
||||
default:
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// truthBody / applyClassifyKwargs / deriveInputFor mirror the exact inputs
|
||||
// the Python generator (/tmp/ar_truth_gen.py) fed each named case.
|
||||
func truthBody(name string) string {
|
||||
bodies := map[string]string{
|
||||
"local_fix_happy": "fix the broken typewriter regex in warm_router, crash on empty input",
|
||||
"standard_change": "add a progress bar to the export dialog",
|
||||
"defect_word_absent": "update the version number in the footer",
|
||||
"floor_new_subsystem": "adopt a new subsystem for memory indexing, replacement of spine",
|
||||
"risk_new_authority": "this creates a new authority path for dispatch",
|
||||
"uncertainty_competing": "there are competing designs here, expensive reversal likely",
|
||||
"not_grounded": "add support for markdown export",
|
||||
"inspection_verb": "explain why the failing test fails",
|
||||
}
|
||||
return bodies[name]
|
||||
}
|
||||
|
||||
func applyClassifyKwargs(in *classifyInput, name string) {
|
||||
switch name {
|
||||
case "local_fix_happy", "standard_change", "inspection_verb":
|
||||
in.HasLocalRepro, in.OwningAuthorityKnown, in.TestableLocally, in.NarrowAndReversible = true, true, true, true
|
||||
case "defect_word_absent":
|
||||
in.HasLocalRepro, in.OwningAuthorityKnown, in.TestableLocally, in.NarrowAndReversible = true, true, false, true
|
||||
case "floor_new_subsystem", "risk_new_authority":
|
||||
in.HasLocalRepro, in.OwningAuthorityKnown = false, false
|
||||
case "uncertainty_competing":
|
||||
in.HasLocalRepro, in.OwningAuthorityKnown = true, true
|
||||
case "not_grounded":
|
||||
in.HasLocalRepro, in.OwningAuthorityKnown, in.TestableLocally, in.NarrowAndReversible = false, true, true, true
|
||||
}
|
||||
}
|
||||
|
||||
func deriveInputFor(name string) deriveInput {
|
||||
cases := map[string]deriveInput{
|
||||
"grounded_fix": {Title: "fix crash", Body: "the parser crashes on empty input, see tests/test_parse.py"},
|
||||
"mechanism": {Title: "investigate", Body: "performance is bad under load, benchmark needed"},
|
||||
"external_url": {Title: "read the docs", Body: "see https://example.com/api docs for the endpoint"},
|
||||
"version_risk": {Title: "upgrade", Body: "upgrade the library to latest version, current behaviour differs"},
|
||||
"inspection": {Title: "explain", Body: "why does this happen"},
|
||||
"new_subsystem": {Title: "adopt", Body: "this adopts a replacement architecture"},
|
||||
"neutral": {Title: "write", Body: "a poem about the sea"},
|
||||
}
|
||||
return cases[name]
|
||||
}
|
||||
|
||||
func TestParityAgainstPythonOracle(t *testing.T) {
|
||||
cases := loadTruth(t)
|
||||
if len(cases) == 0 {
|
||||
t.Fatal("no truth cases — the parity gate is empty")
|
||||
}
|
||||
for _, c := range cases {
|
||||
name, _ := c["name"].(string)
|
||||
fn, _ := c["fn"].(string)
|
||||
switch fn {
|
||||
case "classify":
|
||||
in := classifyInput{Body: truthBody(c["name"].(string))}
|
||||
applyClassifyKwargs(&in, name)
|
||||
d := ClassifyRoute(in)
|
||||
eq(t, name, "route", d.Route, c["route"])
|
||||
eq(t, name, "confidence", d.Confidence, c["confidence"])
|
||||
eq(t, name, "reasons", d.Reasons, c["reasons"])
|
||||
eq(t, name, "risk", d.RiskFlags, c["risk"])
|
||||
eq(t, name, "uncertainty", d.UncertaintyFlags, c["uncertainty"])
|
||||
eq(t, name, "floor", d.Floor, c["floor"])
|
||||
eq(t, name, "task_description", d.TaskDescription, c["task_description"])
|
||||
case "derive":
|
||||
in := deriveInputFor(name)
|
||||
s := DeriveSufficiency(in)
|
||||
unk := s.Unknowns()
|
||||
if unk == nil {
|
||||
unk = []string{}
|
||||
}
|
||||
eq(t, name, "local_authority", s.LocalAuthority, c["local_authority"])
|
||||
eq(t, name, "external_dependency", s.ExternalDependency, c["external_dependency"])
|
||||
eq(t, name, "version_freshness_risk", s.VersionFreshnessRisk, c["version_freshness_risk"])
|
||||
eq(t, name, "verifiability", s.Verifiability, c["verifiability"])
|
||||
eq(t, name, "scope_novelty", s.ScopeNovelty, c["scope_novelty"])
|
||||
eq(t, name, "unknowns", unk, c["unknowns"])
|
||||
eq(t, name, "task_class", s.Provenance["task_class_language"], c["task_class"])
|
||||
case "body_has_floor_trigger":
|
||||
body, _ := c["body"].(string)
|
||||
eq(t, name, "result", BodyHasFloorTrigger(strings.ToLower(body)), c["result"])
|
||||
case "floor_applies":
|
||||
route, _ := c["route"].(string)
|
||||
eq(t, name, "result", FloorApplies(route, []string{"new_authority"}), c["result"])
|
||||
case "escalate":
|
||||
base := ClassifyRoute(classifyInput{Body: "fix the crash", HasLocalRepro: true, OwningAuthorityKnown: true, TestableLocally: true, NarrowAndReversible: true})
|
||||
up, err := escalateRoute(base, "RESEARCHED_CHANGE", "verify_fail", "the fix works locally but the production parser accepts different input shapes — input contract uncertain")
|
||||
if err != nil {
|
||||
t.Errorf("%s: escalate errored: %v", name, err)
|
||||
continue
|
||||
}
|
||||
eq(t, name, "route", up.Route, c["route"])
|
||||
eq(t, name, "previous", *up.PreviousRoute, c["previous"])
|
||||
eq(t, name, "decided_by", up.DecidedBy, c["decided_by"])
|
||||
eq(t, name, "trigger", *up.Trigger, c["trigger"])
|
||||
case "downgrade_ok":
|
||||
base := ClassifyRoute(classifyInput{Body: "fix the crash", HasLocalRepro: true, OwningAuthorityKnown: true, TestableLocally: true, NarrowAndReversible: true})
|
||||
down, err := downgradeRoute(base, "STANDARD_CHANGE", "try", "ev")
|
||||
if err != nil {
|
||||
t.Errorf("%s: downgrade errored: %v", name, err)
|
||||
continue
|
||||
}
|
||||
eq(t, name, "route", down.Route, c["route"])
|
||||
case "downgrade_violation":
|
||||
base := ClassifyRoute(classifyInput{Body: "fix the crash", HasLocalRepro: true, OwningAuthorityKnown: true, TestableLocally: true, NarrowAndReversible: true})
|
||||
_, err := downgradeRoute(base, "STANDARD_CHANGE", "try", "ev")
|
||||
got := "FLOOR_VIOLATION"
|
||||
if err == nil {
|
||||
got = "STANDARD_CHANGE"
|
||||
}
|
||||
eq(t, name, "route", got, c["route"])
|
||||
case "downgrade_floored":
|
||||
floored := ClassifyRoute(classifyInput{Body: "adopt a replacement for the memory index"})
|
||||
_, err := downgradeRoute(floored, "STANDARD_CHANGE", "efficiency", "faster")
|
||||
got := "FLOOR_VIOLATION"
|
||||
if err == nil {
|
||||
got = "NO_VIOLATION"
|
||||
}
|
||||
eq(t, name, "route", got, c["route"])
|
||||
case "evidence_short":
|
||||
base := ClassifyRoute(classifyInput{Body: "fix the crash", HasLocalRepro: true, OwningAuthorityKnown: true, TestableLocally: true, NarrowAndReversible: true})
|
||||
_, err := escalateOnVerificationFailure(base, "test failed")
|
||||
got := "REJECTED"
|
||||
if err == nil {
|
||||
got = "ACCEPTED"
|
||||
}
|
||||
eq(t, name, "result", got, c["result"])
|
||||
case "dispatch":
|
||||
floored := ClassifyRoute(classifyInput{Body: "adopt a replacement for the memory index"})
|
||||
d := buildResearchDispatch("T-1", "research the memory index options", floored)
|
||||
eq(t, name, "task_id", d["task_id"], c["task_id"])
|
||||
eq(t, name, "title", d["title"], c["title"])
|
||||
eq(t, name, "route", d["route"], c["route"])
|
||||
eq(t, name, "floor", d["floor"], c["floor"])
|
||||
eq(t, name, "executor_entry", d["executor_entry"], c["executor_entry"])
|
||||
default:
|
||||
t.Errorf("unknown truth fn %q", fn)
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
BIN
Binary file not shown.
Vendored
-26
@@ -1,26 +0,0 @@
|
||||
module rune/cache
|
||||
|
||||
go 1.21
|
||||
|
||||
require modernc.org/sqlite v1.28.0
|
||||
|
||||
require (
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/google/uuid v1.3.0 // indirect
|
||||
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
|
||||
github.com/mattn/go-isatty v0.0.16 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
golang.org/x/mod v0.3.0 // indirect
|
||||
golang.org/x/sys v0.9.0 // indirect
|
||||
golang.org/x/tools v0.0.0-20201124115921-2c860bdd6e78 // indirect
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
|
||||
lukechampine.com/uint128 v1.2.0 // indirect
|
||||
modernc.org/cc/v3 v3.40.0 // indirect
|
||||
modernc.org/ccgo/v3 v3.16.13 // indirect
|
||||
modernc.org/libc v1.29.0 // indirect
|
||||
modernc.org/mathutil v1.6.0 // indirect
|
||||
modernc.org/memory v1.7.2 // indirect
|
||||
modernc.org/opt v0.1.3 // indirect
|
||||
modernc.org/strutil v1.1.3 // indirect
|
||||
modernc.org/token v1.0.1 // indirect
|
||||
)
|
||||
Vendored
-73
@@ -1,73 +0,0 @@
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
|
||||
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=
|
||||
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs=
|
||||
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8=
|
||||
github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4=
|
||||
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.9.0 h1:KS/R3tvhPqvJvwcKfnBHJwwthS11LRhmM5D59eEXa0s=
|
||||
golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20201124115921-2c860bdd6e78 h1:M8tBwCtWD/cZV9DZpFYRUgaymAYAr+aIUTWzDaM3uPs=
|
||||
golang.org/x/tools v0.0.0-20201124115921-2c860bdd6e78/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
lukechampine.com/uint128 v1.2.0 h1:mBi/5l91vocEN8otkC5bDLhi2KdCticRiwbdB0O+rjI=
|
||||
lukechampine.com/uint128 v1.2.0/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk=
|
||||
modernc.org/cc/v3 v3.40.0 h1:P3g79IUS/93SYhtoeaHW+kRCIrYaxJ27MFPv+7kaTOw=
|
||||
modernc.org/cc/v3 v3.40.0/go.mod h1:/bTg4dnWkSXowUO6ssQKnOV0yMVxDYNIsIrzqTFDGH0=
|
||||
modernc.org/ccgo/v3 v3.16.13 h1:Mkgdzl46i5F/CNR/Kj80Ri59hC8TKAhZrYSaqvkwzUw=
|
||||
modernc.org/ccgo/v3 v3.16.13/go.mod h1:2Quk+5YgpImhPjv2Qsob1DnZ/4som1lJTodubIcoUkY=
|
||||
modernc.org/ccorpus v1.11.6 h1:J16RXiiqiCgua6+ZvQot4yUuUy8zxgqbqEEUuGPlISk=
|
||||
modernc.org/ccorpus v1.11.6/go.mod h1:2gEUTrWqdpH2pXsmTM1ZkjeSrUWDpjMu2T6m29L/ErQ=
|
||||
modernc.org/httpfs v1.0.6 h1:AAgIpFZRXuYnkjftxTAZwMIiwEqAfk8aVB2/oA6nAeM=
|
||||
modernc.org/httpfs v1.0.6/go.mod h1:7dosgurJGp0sPaRanU53W4xZYKh14wfzX420oZADeHM=
|
||||
modernc.org/libc v1.29.0 h1:tTFRFq69YKCF2QyGNuRUQxKBm1uZZLubf6Cjh/pVHXs=
|
||||
modernc.org/libc v1.29.0/go.mod h1:DaG/4Q3LRRdqpiLyP0C2m1B8ZMGkQ+cCgOIjEtQlYhQ=
|
||||
modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=
|
||||
modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=
|
||||
modernc.org/memory v1.7.2 h1:Klh90S215mmH8c9gO98QxQFsY+W451E8AnzjoE2ee1E=
|
||||
modernc.org/memory v1.7.2/go.mod h1:NO4NVCQy0N7ln+T9ngWqOQfi7ley4vpwvARR+Hjw95E=
|
||||
modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=
|
||||
modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=
|
||||
modernc.org/sqlite v1.28.0 h1:Zx+LyDDmXczNnEQdvPuEfcFVA2ZPyaD7UCZDjef3BHQ=
|
||||
modernc.org/sqlite v1.28.0/go.mod h1:Qxpazz0zH8Z1xCFyi5GSL3FzbtZ3fvbjmywNogldEW0=
|
||||
modernc.org/strutil v1.1.3 h1:fNMm+oJklMGYfU9Ylcywl0CO5O6nTfaowNsh2wpPjzY=
|
||||
modernc.org/strutil v1.1.3/go.mod h1:MEHNA7PdEnEwLvspRMtWTNnp2nnyvMfkimT1NKNAGbw=
|
||||
modernc.org/tcl v1.15.2 h1:C4ybAYCGJw968e+Me18oW55kD/FexcHbqH2xak1ROSY=
|
||||
modernc.org/tcl v1.15.2/go.mod h1:3+k/ZaEbKrC8ePv8zJWPtBSW0V7Gg9g8rkmhI1Kfs3c=
|
||||
modernc.org/token v1.0.1 h1:A3qvTqOwexpfZZeyI0FeGPDlSWX5pjZu9hF4lU+EKWg=
|
||||
modernc.org/token v1.0.1/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||
modernc.org/z v1.7.3 h1:zDJf6iHjrnB+WRD88stbXokugjyc0/pB91ri1gO6LZY=
|
||||
modernc.org/z v1.7.3/go.mod h1:Ipv4tsdxZRbQyLq9Q1M6gdbkxYzdlrciF2Hi/lS7nWE=
|
||||
Vendored
-154
@@ -1,154 +0,0 @@
|
||||
// cache — Go SQLite-backed key-value cache (R2 W4).
|
||||
// Replaces src/rune/cache.py. Uses modernc.org/sqlite (pure Go).
|
||||
//
|
||||
// Usage:
|
||||
// cache get <key>
|
||||
// cache put <key> <value> [--scope <s>]
|
||||
// cache invalidate <key> [reason]
|
||||
// cache invalidate-scope <scope> [reason]
|
||||
// cache stats
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
type Result struct {
|
||||
Success bool `json:"success"`
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func dbPath() string {
|
||||
home := os.Getenv("RUNE_MEMORY_DIR")
|
||||
if home == "" {
|
||||
home = filepath.Join(os.Getenv("HOME"), ".rune")
|
||||
}
|
||||
return filepath.Join(home, "cache.db")
|
||||
}
|
||||
|
||||
func connect() (*sql.DB, error) {
|
||||
p := dbPath()
|
||||
os.MkdirAll(filepath.Dir(p), 0755)
|
||||
db, err := sql.Open("sqlite", p)
|
||||
if err != nil { return nil, err }
|
||||
db.Exec("PRAGMA journal_mode=WAL")
|
||||
db.Exec("PRAGMA synchronous=NORMAL")
|
||||
db.Exec(`CREATE TABLE IF NOT EXISTS cache (
|
||||
key TEXT PRIMARY KEY, scope TEXT DEFAULT 'general',
|
||||
content_hash TEXT NOT NULL, full_value TEXT,
|
||||
compressed_value TEXT, source_hash TEXT DEFAULT '',
|
||||
created_at TEXT NOT NULL, invalidated_at TEXT,
|
||||
hit_count INTEGER DEFAULT 0, miss_count INTEGER DEFAULT 0)`)
|
||||
db.Exec(`CREATE INDEX IF NOT EXISTS idx_cache_scope ON cache(scope)`)
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func hashText(text string) string {
|
||||
h := sha256.Sum256([]byte(text))
|
||||
return hex.EncodeToString(h[:])[:16]
|
||||
}
|
||||
|
||||
func nowISO() string { return time.Now().UTC().Format("2006-01-02T15:04:05Z") }
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
fmt.Fprintln(os.Stderr, "usage: cache <get|put|invalidate|invalidate-scope|stats> [args...]")
|
||||
os.Exit(1)
|
||||
}
|
||||
db, err := connect()
|
||||
if err != nil {
|
||||
out, _ := json.Marshal(Result{Success: false, Error: err.Error()})
|
||||
fmt.Println(string(out))
|
||||
os.Exit(1)
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
cmd := os.Args[1]
|
||||
args := os.Args[2:]
|
||||
|
||||
switch cmd {
|
||||
case "get":
|
||||
if len(args) < 1 { fmt.Fprintln(os.Stderr, "usage: cache get <key>"); os.Exit(1) }
|
||||
var compressed, full, contentHash, scope, createdAt sql.NullString
|
||||
var hitCount int
|
||||
err := db.QueryRow(
|
||||
"SELECT compressed_value, full_value, content_hash, scope, created_at, hit_count FROM cache WHERE key=? AND invalidated_at IS NULL",
|
||||
args[0]).Scan(&compressed, &full, &contentHash, &scope, &createdAt, &hitCount)
|
||||
if err == sql.ErrNoRows {
|
||||
out, _ := json.Marshal(Result{Success: true, Data: map[string]interface{}{"hit": false, "key": args[0]}})
|
||||
fmt.Println(string(out))
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
out, _ := json.Marshal(Result{Success: false, Error: err.Error()})
|
||||
fmt.Println(string(out))
|
||||
return
|
||||
}
|
||||
db.Exec("UPDATE cache SET hit_count = hit_count + 1 WHERE key = ?", args[0])
|
||||
age := int64(0)
|
||||
if t, e := time.Parse("2006-01-02T15:04:05Z", createdAt.String); e == nil {
|
||||
age = int64(time.Since(t).Seconds())
|
||||
}
|
||||
out, _ := json.Marshal(Result{Success: true, Data: map[string]interface{}{
|
||||
"hit": true, "key": args[0], "compressed": compressed.String,
|
||||
"full": full.String, "content_hash": contentHash.String,
|
||||
"scope": scope.String, "age_seconds": age, "hit_count": hitCount + 1,
|
||||
}})
|
||||
fmt.Println(string(out))
|
||||
|
||||
case "put":
|
||||
if len(args) < 2 { fmt.Fprintln(os.Stderr, "usage: cache put <key> <value> [--scope <s>]"); os.Exit(1) }
|
||||
key := args[0]
|
||||
value := args[1]
|
||||
scope := "general"
|
||||
for i := 2; i < len(args); i++ {
|
||||
if args[i] == "--scope" && i+1 < len(args) { scope = args[i+1] }
|
||||
}
|
||||
contentHash := hashText(value)
|
||||
db.Exec(`INSERT INTO cache (key, scope, content_hash, full_value, compressed_value, source_hash, created_at, invalidated_at, hit_count, miss_count)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, NULL, 0, 0)
|
||||
ON CONFLICT(key) DO UPDATE SET scope=excluded.scope, content_hash=excluded.content_hash,
|
||||
full_value=excluded.full_value, compressed_value=excluded.compressed_value, created_at=excluded.created_at, invalidated_at=NULL`,
|
||||
key, scope, contentHash, value, value[:min(len(value), 200)], "", nowISO())
|
||||
out, _ := json.Marshal(Result{Success: true, Data: map[string]interface{}{"stored": key, "content_hash": contentHash, "scope": scope}})
|
||||
fmt.Println(string(out))
|
||||
|
||||
case "invalidate":
|
||||
if len(args) < 1 { fmt.Fprintln(os.Stderr, "usage: cache invalidate <key>"); os.Exit(1) }
|
||||
db.Exec("UPDATE cache SET invalidated_at=? WHERE key=? AND invalidated_at IS NULL", nowISO(), args[0])
|
||||
out, _ := json.Marshal(Result{Success: true, Data: map[string]interface{}{"invalidated": args[0]}})
|
||||
fmt.Println(string(out))
|
||||
|
||||
case "invalidate-scope":
|
||||
if len(args) < 1 { fmt.Fprintln(os.Stderr, "usage: cache invalidate-scope <scope>"); os.Exit(1) }
|
||||
db.Exec("UPDATE cache SET invalidated_at=? WHERE scope=? AND invalidated_at IS NULL", nowISO(), args[0])
|
||||
out, _ := json.Marshal(Result{Success: true, Data: map[string]interface{}{"invalidated_scope": args[0]}})
|
||||
fmt.Println(string(out))
|
||||
|
||||
case "stats":
|
||||
var total, hits, misses int
|
||||
db.QueryRow("SELECT COUNT(*), SUM(hit_count), SUM(miss_count) FROM cache").Scan(&total, &hits, &misses)
|
||||
out, _ := json.Marshal(Result{Success: true, Data: map[string]interface{}{
|
||||
"total_entries": total, "total_hits": hits, "total_misses": misses}})
|
||||
fmt.Println(string(out))
|
||||
|
||||
default:
|
||||
fmt.Fprintf(os.Stderr, "unknown command: %s\n", cmd)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b { return a }
|
||||
return b
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
// Package capability — capability_scoring Rust kernel (Survivor hybrid).
|
||||
package capability
|
||||
|
||||
/*
|
||||
#cgo LDFLAGS: ${SRCDIR}/../../../rust/capability_scoring/target/release/libcapability_scoring.a -lpthread -ldl -lm
|
||||
#include <stdlib.h>
|
||||
extern char* cs_evaluate_fit(const char* arg);
|
||||
extern char* cs_score_card(const char* arg);
|
||||
extern void cs_free_string(char* s);
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func call(symbol string, arg string) (map[string]interface{}, error) {
|
||||
cArg := C.CString(arg)
|
||||
defer C.free(unsafe.Pointer(cArg))
|
||||
var result *C.char
|
||||
switch symbol {
|
||||
case "cs_evaluate_fit": result = C.cs_evaluate_fit(cArg)
|
||||
case "cs_score_card": result = C.cs_score_card(cArg)
|
||||
default: return nil, fmt.Errorf("unknown symbol: %s", symbol)
|
||||
}
|
||||
defer C.cs_free_string(result)
|
||||
var out map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(C.GoString(result)), &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func EvaluateFit(arg string) (map[string]interface{}, error) { return call("cs_evaluate_fit", arg) }
|
||||
func ScoreCard(arg string) (map[string]interface{}, error) { return call("cs_score_card", arg) }
|
||||
@@ -1,197 +0,0 @@
|
||||
// Package cognition — the Go↔Rust membrane using the hybrid staticlib pattern.
|
||||
// The Rust kernels are compiled as staticlibs and linked into any Go binary
|
||||
// that imports this package. No .so loading, no CC_RUST_LIB env var.
|
||||
//
|
||||
// The Go reactive modules call these functions when they need deterministic
|
||||
// compute. The Rust functions are pure — same input, same output.
|
||||
package cognition
|
||||
|
||||
/*
|
||||
#cgo LDFLAGS: ${SRCDIR}/../../rust/cognition_core/target/release/libcognition_core.a -lpthread -ldl -lm
|
||||
#include <stdlib.h>
|
||||
#include <stddef.h>
|
||||
|
||||
extern char* cc_tier_get(const char* arg);
|
||||
extern char* cc_tier_promote(const char* arg);
|
||||
extern char* cc_tier_demote(const char* arg);
|
||||
extern char* cc_consolidation_memory(const char* arg);
|
||||
extern char* cc_consolidation_neuron(const char* arg);
|
||||
extern char* cc_witness_extract_topic(const char* arg);
|
||||
extern char* cc_witness_signals(const char* arg);
|
||||
extern char* cc_safety_get_params(const char* arg);
|
||||
extern char* cc_safety_update_pattern(const char* arg);
|
||||
extern char* cc_abstraction_extract_facts(const char* arg);
|
||||
extern char* cc_growth_near_dup(const char* arg);
|
||||
extern char* cc_drift_check(const char* arg);
|
||||
extern char* cc_persona_decide(const char* arg);
|
||||
extern char* cc_identity_prompt(const char* arg);
|
||||
extern char* cc_pins_recall(const char* arg);
|
||||
extern char* cc_memory_budget(const char* arg);
|
||||
extern char* cc_default_estimator(const char* arg);
|
||||
extern char* cc_persona_lex(const char* arg);
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// call is the single FFI entry point. Every Go→Rust call goes through here.
|
||||
func call(symbol string, arg string) (string, error) {
|
||||
cArg := C.CString(arg)
|
||||
defer C.free(unsafe.Pointer(cArg))
|
||||
|
||||
var result *C.char
|
||||
switch symbol {
|
||||
case "cc_tier_get":
|
||||
result = C.cc_tier_get(cArg)
|
||||
case "cc_tier_promote":
|
||||
result = C.cc_tier_promote(cArg)
|
||||
case "cc_tier_demote":
|
||||
result = C.cc_tier_demote(cArg)
|
||||
case "cc_consolidation_memory":
|
||||
result = C.cc_consolidation_memory(cArg)
|
||||
case "cc_consolidation_neuron":
|
||||
result = C.cc_consolidation_neuron(cArg)
|
||||
case "cc_witness_extract_topic":
|
||||
result = C.cc_witness_extract_topic(cArg)
|
||||
case "cc_witness_signals":
|
||||
result = C.cc_witness_signals(cArg)
|
||||
case "cc_safety_get_params":
|
||||
result = C.cc_safety_get_params(cArg)
|
||||
case "cc_safety_update_pattern":
|
||||
result = C.cc_safety_update_pattern(cArg)
|
||||
case "cc_abstraction_extract_facts":
|
||||
result = C.cc_abstraction_extract_facts(cArg)
|
||||
case "cc_growth_near_dup":
|
||||
result = C.cc_growth_near_dup(cArg)
|
||||
case "cc_drift_check":
|
||||
result = C.cc_drift_check(cArg)
|
||||
case "cc_persona_decide":
|
||||
result = C.cc_persona_decide(cArg)
|
||||
case "cc_identity_prompt":
|
||||
result = C.cc_identity_prompt(cArg)
|
||||
case "cc_pins_recall":
|
||||
result = C.cc_pins_recall(cArg)
|
||||
default:
|
||||
return "", fmt.Errorf("unknown Rust symbol: %s", symbol)
|
||||
}
|
||||
if result == nil {
|
||||
return "", fmt.Errorf("Rust kernel returned nil for %s", symbol)
|
||||
}
|
||||
goResult := C.GoString(result)
|
||||
C.free(unsafe.Pointer(result))
|
||||
return goResult, nil
|
||||
}
|
||||
|
||||
// TierGet classifies a memory entry as hot/warm/cold.
|
||||
func TierGet(entry map[string]interface{}, now string, hotDays, warmDays float64) (map[string]interface{}, error) {
|
||||
arg, _ := json.Marshal(map[string]interface{}{
|
||||
"entry": entry, "now": now, "hot": hotDays, "warm": warmDays,
|
||||
})
|
||||
result, err := call("cc_tier_get", string(arg))
|
||||
if err != nil { return nil, err }
|
||||
var out map[string]interface{}
|
||||
json.Unmarshal([]byte(result), &out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ConsolidationMemory assembles a knowledge record from a memory entry.
|
||||
func ConsolidationMemory(text string, score float64, washCount int, entryID *int, now string) (map[string]interface{}, error) {
|
||||
arg, _ := json.Marshal(map[string]interface{}{
|
||||
"text": text, "score": score, "wash_count": washCount,
|
||||
"entry_id": entryID, "now": now,
|
||||
})
|
||||
result, err := call("cc_consolidation_memory", string(arg))
|
||||
if err != nil { return nil, err }
|
||||
var out map[string]interface{}
|
||||
json.Unmarshal([]byte(result), &out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ConsolidationNeuron assembles a knowledge record from a warm neuron.
|
||||
func ConsolidationNeuron(slug, body string, importance float64, triggers []string, washCount int, entryID *int, now string) (map[string]interface{}, error) {
|
||||
arg, _ := json.Marshal(map[string]interface{}{
|
||||
"slug": slug, "body": body, "importance": importance,
|
||||
"triggers": triggers, "wash_count": washCount,
|
||||
"entry_id": entryID, "now": now,
|
||||
})
|
||||
result, err := call("cc_consolidation_neuron", string(arg))
|
||||
if err != nil { return nil, err }
|
||||
var out map[string]interface{}
|
||||
json.Unmarshal([]byte(result), &out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// WitnessExtractTopic extracts topic keywords from text.
|
||||
func WitnessExtractTopic(text string, stopwords []string, cap int) ([]string, error) {
|
||||
arg, _ := json.Marshal(map[string]interface{}{
|
||||
"text": text, "stopwords": stopwords, "cap": cap,
|
||||
})
|
||||
result, err := call("cc_witness_extract_topic", string(arg))
|
||||
if err != nil { return nil, err }
|
||||
var out []string
|
||||
json.Unmarshal([]byte(result), &out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// WitnessSignals extracts signals from a message.
|
||||
func WitnessSignals(message string, tables map[string]interface{}, toolError, taskStatus string, recentTopics []string) (map[string]interface{}, error) {
|
||||
arg, _ := json.Marshal(map[string]interface{}{
|
||||
"message": message, "tables": tables,
|
||||
"tool_error": toolError, "task_status": taskStatus,
|
||||
"recent_topics": recentTopics,
|
||||
})
|
||||
result, err := call("cc_witness_signals", string(arg))
|
||||
if err != nil { return nil, err }
|
||||
var out map[string]interface{}
|
||||
json.Unmarshal([]byte(result), &out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// SafetyGetParams evaluates safety override parameters.
|
||||
func SafetyGetParams(rows []map[string]interface{}) (map[string]interface{}, error) {
|
||||
arg, _ := json.Marshal(rows)
|
||||
result, err := call("cc_safety_get_params", string(arg))
|
||||
if err != nil { return nil, err }
|
||||
var out map[string]interface{}
|
||||
json.Unmarshal([]byte(result), &out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// DriftCheck validates text against drift patterns.
|
||||
func DriftCheck(text string, patterns []map[string]interface{}) ([]string, error) {
|
||||
arg, _ := json.Marshal(map[string]interface{}{
|
||||
"text": text, "patterns": patterns,
|
||||
})
|
||||
result, err := call("cc_drift_check", string(arg))
|
||||
if err != nil { return nil, err }
|
||||
var out []string
|
||||
json.Unmarshal([]byte(result), &out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// PinsRecall recalls relevant pins for a term.
|
||||
func PinsRecall(pins []map[string]interface{}, term string, limit int) ([]map[string]interface{}, error) {
|
||||
arg, _ := json.Marshal(map[string]interface{}{
|
||||
"pins": pins, "term": term, "limit": limit,
|
||||
})
|
||||
result, err := call("cc_pins_recall", string(arg))
|
||||
if err != nil { return nil, err }
|
||||
var out []map[string]interface{}
|
||||
json.Unmarshal([]byte(result), &out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GrowthNearDup checks if two texts are near-duplicates.
|
||||
func GrowthNearDup(a, b string) (bool, error) {
|
||||
arg, _ := json.Marshal(map[string]interface{}{"a": a, "b": b})
|
||||
result, err := call("cc_growth_near_dup", string(arg))
|
||||
if err != nil { return false, err }
|
||||
var out map[string]interface{}
|
||||
json.Unmarshal([]byte(result), &out)
|
||||
isDup, _ := out["value"].(bool)
|
||||
return isDup, nil
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
package cognition
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTierGet(t *testing.T) {
|
||||
entry := map[string]interface{}{
|
||||
"wash_count": 25,
|
||||
"last_accessed": "2026-10-06T12:00:00Z",
|
||||
}
|
||||
result, err := TierGet(entry, "2026-10-06T20:00:00Z", 7.0, 30.0)
|
||||
if err != nil {
|
||||
t.Fatalf("TierGet error: %v", err)
|
||||
}
|
||||
raw, _ := json.Marshal(result)
|
||||
t.Logf("TierGet result: %s", raw)
|
||||
// The Rust kernel returns {"ok": true, "value": {"tier": "hot"}}
|
||||
tier, ok := result["value"].(string)
|
||||
if !ok {
|
||||
t.Fatalf("expected tier string, got: %v", result)
|
||||
}
|
||||
if tier != "hot" && tier != "warm" && tier != "cold" {
|
||||
t.Fatalf("unexpected tier: %s", tier)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsolidationMemory(t *testing.T) {
|
||||
entryID := 42
|
||||
result, err := ConsolidationMemory(
|
||||
"The deployment runner needs repair and the store is fine.",
|
||||
0.9, 5, &entryID,
|
||||
"2026-10-06T20:00:00Z")
|
||||
if err != nil {
|
||||
t.Fatalf("ConsolidationMemory error: %v", err)
|
||||
}
|
||||
raw, _ := json.Marshal(result)
|
||||
t.Logf("ConsolidationMemory result: %s", raw)
|
||||
value, ok := result["value"].(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("expected value object, got: %v", result)
|
||||
}
|
||||
if value["id"] == nil {
|
||||
t.Fatal("expected id in result value")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWitnessExtractTopic(t *testing.T) {
|
||||
stopwords := []string{"the", "a", "an", "is", "was", "and", "or", "but"}
|
||||
result, err := WitnessExtractTopic("the deployment runner needs repair now", stopwords, 5)
|
||||
if err != nil {
|
||||
t.Fatalf("WitnessExtractTopic error: %v", err)
|
||||
}
|
||||
t.Logf("WitnessExtractTopic result: %v", result)
|
||||
}
|
||||
|
||||
func TestGrowthNearDup(t *testing.T) {
|
||||
same, err := GrowthNearDup("fix the deployment", "fix the deployment")
|
||||
if err != nil {
|
||||
t.Fatalf("GrowthNearDup error: %v", err)
|
||||
}
|
||||
t.Logf("GrowthNearDup same-text: %v", same)
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
module rune/cognition
|
||||
|
||||
go 1.21
|
||||
@@ -1,55 +0,0 @@
|
||||
// Package provenance — evidence_provenance Rust kernel (Survivor hybrid).
|
||||
package provenance
|
||||
|
||||
/*
|
||||
#cgo LDFLAGS: ${SRCDIR}/../../../rust/evidence_provenance/target/release/libevidence_provenance.a -lpthread -ldl -lm
|
||||
#include <stdlib.h>
|
||||
extern char* ep_append_entry(const char* arg);
|
||||
extern char* ep_bl_accept_limitation(const char* arg);
|
||||
extern char* ep_bl_define(const char* arg);
|
||||
extern char* ep_bl_get(const char* arg);
|
||||
extern char* ep_bl_invalidate(const char* arg);
|
||||
extern char* ep_bl_outstanding(const char* arg);
|
||||
extern char* ep_bl_record_auto(const char* arg);
|
||||
extern char* ep_bl_record_real_world(const char* arg);
|
||||
extern void ep_free_string(char* s);
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func call(symbol string, arg string) (map[string]interface{}, error) {
|
||||
cArg := C.CString(arg)
|
||||
defer C.free(unsafe.Pointer(cArg))
|
||||
var result *C.char
|
||||
switch symbol {
|
||||
case "ep_append_entry": result = C.ep_append_entry(cArg)
|
||||
case "ep_bl_accept_limitation": result = C.ep_bl_accept_limitation(cArg)
|
||||
case "ep_bl_define": result = C.ep_bl_define(cArg)
|
||||
case "ep_bl_get": result = C.ep_bl_get(cArg)
|
||||
case "ep_bl_invalidate": result = C.ep_bl_invalidate(cArg)
|
||||
case "ep_bl_outstanding": result = C.ep_bl_outstanding(cArg)
|
||||
case "ep_bl_record_auto": result = C.ep_bl_record_auto(cArg)
|
||||
case "ep_bl_record_real_world": result = C.ep_bl_record_real_world(cArg)
|
||||
default: return nil, fmt.Errorf("unknown symbol: %s", symbol)
|
||||
}
|
||||
defer C.ep_free_string(result)
|
||||
var out map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(C.GoString(result)), &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func AppendEntry(arg string) (map[string]interface{}, error) { return call("ep_append_entry", arg) }
|
||||
func BLAcceptLimitation(arg string) (map[string]interface{}, error) { return call("ep_bl_accept_limitation", arg) }
|
||||
func BLDefine(arg string) (map[string]interface{}, error) { return call("ep_bl_define", arg) }
|
||||
func BLGet(arg string) (map[string]interface{}, error) { return call("ep_bl_get", arg) }
|
||||
func BLInvalidate(arg string) (map[string]interface{}, error) { return call("ep_bl_invalidate", arg) }
|
||||
func BLOutstanding(arg string) (map[string]interface{}, error) { return call("ep_bl_outstanding", arg) }
|
||||
func BLRecordAuto(arg string) (map[string]interface{}, error) { return call("ep_bl_record_auto", arg) }
|
||||
func BLRecordRealWorld(arg string) (map[string]interface{}, error) { return call("ep_bl_record_real_world", arg) }
|
||||
@@ -1,50 +0,0 @@
|
||||
// Package query — query_memory Rust kernel (Survivor hybrid).
|
||||
package query
|
||||
|
||||
/*
|
||||
#cgo LDFLAGS: ${SRCDIR}/../../../rust/query_memory/target/release/libquery_memory.a -lpthread -ldl -lm
|
||||
#include <stdlib.h>
|
||||
extern char* qm_adaptive_rate(const char* arg);
|
||||
extern char* qm_classify(const char* arg);
|
||||
extern char* qm_dead_weight(const char* arg);
|
||||
extern char* qm_health(const char* arg);
|
||||
extern char* qm_new(const char* arg);
|
||||
extern char* qm_record(const char* arg);
|
||||
extern void qm_free(char* s);
|
||||
extern void qm_string_free(char* s);
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func call(symbol string, arg string) (map[string]interface{}, error) {
|
||||
cArg := C.CString(arg)
|
||||
defer C.free(unsafe.Pointer(cArg))
|
||||
var result *C.char
|
||||
switch symbol {
|
||||
case "qm_adaptive_rate": result = C.qm_adaptive_rate(cArg)
|
||||
case "qm_classify": result = C.qm_classify(cArg)
|
||||
case "qm_dead_weight": result = C.qm_dead_weight(cArg)
|
||||
case "qm_health": result = C.qm_health(cArg)
|
||||
case "qm_new": result = C.qm_new(cArg)
|
||||
case "qm_record": result = C.qm_record(cArg)
|
||||
default: return nil, fmt.Errorf("unknown symbol: %s", symbol)
|
||||
}
|
||||
defer C.qm_string_free(result)
|
||||
var out map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(C.GoString(result)), &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func AdaptiveRate(arg string) (map[string]interface{}, error) { return call("qm_adaptive_rate", arg) }
|
||||
func Classify(arg string) (map[string]interface{}, error) { return call("qm_classify", arg) }
|
||||
func DeadWeight(arg string) (map[string]interface{}, error) { return call("qm_dead_weight", arg) }
|
||||
func Health(arg string) (map[string]interface{}, error) { return call("qm_health", arg) }
|
||||
func New(arg string) (map[string]interface{}, error) { return call("qm_new", arg) }
|
||||
func Record(arg string) (map[string]interface{}, error) { return call("qm_record", arg) }
|
||||
@@ -1,27 +0,0 @@
|
||||
// Package retrieval — memory_retrieval Rust kernel (Survivor hybrid).
|
||||
package retrieval
|
||||
|
||||
/*
|
||||
#cgo LDFLAGS: ${SRCDIR}/../../../rust/memory_retrieval/target/release/libmemory_retrieval.a -lpthread -ldl -lm
|
||||
#include <stdlib.h>
|
||||
extern char* mr_call(const char* arg);
|
||||
extern void mr_free_string(char* s);
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func MRCall(arg string) (map[string]interface{}, error) {
|
||||
cArg := C.CString(arg)
|
||||
defer C.free(unsafe.Pointer(cArg))
|
||||
result := C.mr_call(cArg)
|
||||
defer C.mr_free_string(result)
|
||||
var out map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(C.GoString(result)), &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
// Package scaffold — scaffold_core Rust kernel (Survivor hybrid).
|
||||
package scaffold
|
||||
|
||||
/*
|
||||
#cgo LDFLAGS: ${SRCDIR}/../../../rust/scaffold_core/target/release/libscaffold_core.a -lpthread -ldl -lm
|
||||
#include <stdlib.h>
|
||||
extern char* sc_check_transition(const char* arg);
|
||||
extern char* sc_close_quality(const char* arg);
|
||||
extern char* sc_language_placement(const char* arg);
|
||||
extern void sc_free_string(char* s);
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func CheckTransition(arg string) (map[string]interface{}, error) {
|
||||
cArg := C.CString(arg)
|
||||
defer C.free(unsafe.Pointer(cArg))
|
||||
result := C.sc_check_transition(cArg)
|
||||
defer C.sc_free_string(result)
|
||||
var out map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(C.GoString(result)), &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func CloseQuality(arg string) (map[string]interface{}, error) {
|
||||
cArg := C.CString(arg)
|
||||
defer C.free(unsafe.Pointer(cArg))
|
||||
result := C.sc_close_quality(cArg)
|
||||
defer C.sc_free_string(result)
|
||||
var out map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(C.GoString(result)), &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func LanguagePlacement(arg string) (map[string]interface{}, error) {
|
||||
cArg := C.CString(arg)
|
||||
defer C.free(unsafe.Pointer(cArg))
|
||||
result := C.sc_language_placement(cArg)
|
||||
defer C.sc_free_string(result)
|
||||
var out map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(C.GoString(result)), &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
// Package scoring — memory_scoring Rust kernel (Survivor hybrid).
|
||||
package scoring
|
||||
|
||||
/*
|
||||
#cgo LDFLAGS: ${SRCDIR}/../../../rust/memory_scoring/target/release/libmemory_scoring.a -lpthread -ldl -lm
|
||||
#include <stdlib.h>
|
||||
extern char* ms_base_level_from_uses(const char* arg);
|
||||
extern char* ms_check_promotion_eligibility(const char* arg);
|
||||
extern char* ms_compress_entry(const char* arg);
|
||||
extern char* ms_compress_text(const char* arg);
|
||||
extern char* ms_compute_priority(const char* arg);
|
||||
extern char* ms_compute_value(const char* arg);
|
||||
extern char* ms_get_compression_ratio(const char* arg);
|
||||
extern void ms_free_string(char* s);
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func call(symbol string, arg string) (map[string]interface{}, error) {
|
||||
cArg := C.CString(arg)
|
||||
defer C.free(unsafe.Pointer(cArg))
|
||||
var result *C.char
|
||||
switch symbol {
|
||||
case "ms_base_level_from_uses": result = C.ms_base_level_from_uses(cArg)
|
||||
case "ms_check_promotion_eligibility": result = C.ms_check_promotion_eligibility(cArg)
|
||||
case "ms_compress_entry": result = C.ms_compress_entry(cArg)
|
||||
case "ms_compress_text": result = C.ms_compress_text(cArg)
|
||||
case "ms_compute_priority": result = C.ms_compute_priority(cArg)
|
||||
case "ms_compute_value": result = C.ms_compute_value(cArg)
|
||||
case "ms_get_compression_ratio": result = C.ms_get_compression_ratio(cArg)
|
||||
default: return nil, fmt.Errorf("unknown symbol: %s", symbol)
|
||||
}
|
||||
defer C.ms_free_string(result)
|
||||
var out map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(C.GoString(result)), &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func BaseLevelFromUses(arg string) (map[string]interface{}, error) { return call("ms_base_level_from_uses", arg) }
|
||||
func CheckPromotionEligibility(arg string) (map[string]interface{}, error) { return call("ms_check_promotion_eligibility", arg) }
|
||||
func CompressEntry(arg string) (map[string]interface{}, error) { return call("ms_compress_entry", arg) }
|
||||
func CompressText(arg string) (map[string]interface{}, error) { return call("ms_compress_text", arg) }
|
||||
func ComputePriority(arg string) (map[string]interface{}, error) { return call("ms_compute_priority", arg) }
|
||||
func ComputeValue(arg string) (map[string]interface{}, error) { return call("ms_compute_value", arg) }
|
||||
func GetCompressionRatio(arg string) (map[string]interface{}, error) { return call("ms_get_compression_ratio", arg) }
|
||||
@@ -1,43 +0,0 @@
|
||||
// Package spine — rune_spine Rust kernel (Survivor hybrid).
|
||||
package spine
|
||||
|
||||
/*
|
||||
#cgo LDFLAGS: ${SRCDIR}/../../../rust/rune_spine/target/release/librune_spine.a -lpthread -ldl -lm
|
||||
#include <stdlib.h>
|
||||
extern char* sp_drift(const char* arg);
|
||||
extern char* sp_export(const char* arg);
|
||||
extern char* sp_project(const char* arg);
|
||||
extern char* sp_query(const char* arg);
|
||||
extern void sp_free_string(char* s);
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func call(symbol string, arg string) (map[string]interface{}, error) {
|
||||
cArg := C.CString(arg)
|
||||
defer C.free(unsafe.Pointer(cArg))
|
||||
var result *C.char
|
||||
switch symbol {
|
||||
case "sp_drift": result = C.sp_drift(cArg)
|
||||
case "sp_export": result = C.sp_export(cArg)
|
||||
case "sp_project": result = C.sp_project(cArg)
|
||||
case "sp_query": result = C.sp_query(cArg)
|
||||
default: return nil, fmt.Errorf("unknown symbol: %s", symbol)
|
||||
}
|
||||
defer C.sp_free_string(result)
|
||||
var out map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(C.GoString(result)), &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func Drift(arg string) (map[string]interface{}, error) { return call("sp_drift", arg) }
|
||||
func Export(arg string) (map[string]interface{}, error) { return call("sp_export", arg) }
|
||||
func Project(arg string) (map[string]interface{}, error) { return call("sp_project", arg) }
|
||||
func Query(arg string) (map[string]interface{}, error) { return call("sp_query", arg) }
|
||||
@@ -1,27 +0,0 @@
|
||||
// Package storage — memory_storage Rust kernel (Survivor hybrid).
|
||||
package storage
|
||||
|
||||
/*
|
||||
#cgo LDFLAGS: ${SRCDIR}/../../../rust/memory_storage/target/release/libmemory_storage.a -lpthread -ldl -lm
|
||||
#include <stdlib.h>
|
||||
extern char* mems_read_query(const char* arg);
|
||||
extern void mems_free_string(char* s);
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func ReadQuery(arg string) (map[string]interface{}, error) {
|
||||
cArg := C.CString(arg)
|
||||
defer C.free(unsafe.Pointer(cArg))
|
||||
result := C.mems_read_query(cArg)
|
||||
defer C.mems_free_string(result)
|
||||
var out map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(C.GoString(result)), &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
// Package token — token_counting Rust kernel (Survivor hybrid).
|
||||
package token
|
||||
|
||||
/*
|
||||
#cgo LDFLAGS: ${SRCDIR}/../../../rust/token_counting/target/release/libtoken_counting.a -lpthread -ldl -lm
|
||||
#include <stdlib.h>
|
||||
extern char* tc_compress_context(const char* arg);
|
||||
extern char* tc_estimate_tokens(const char* arg);
|
||||
extern void tc_free_string(char* s);
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func call(symbol string, arg string) (map[string]interface{}, error) {
|
||||
cArg := C.CString(arg)
|
||||
defer C.free(unsafe.Pointer(cArg))
|
||||
var result *C.char
|
||||
switch symbol {
|
||||
case "tc_compress_context": result = C.tc_compress_context(cArg)
|
||||
case "tc_estimate_tokens": result = C.tc_estimate_tokens(cArg)
|
||||
default: return nil, fmt.Errorf("unknown symbol: %s", symbol)
|
||||
}
|
||||
defer C.tc_free_string(result)
|
||||
var out map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(C.GoString(result)), &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func CompressContext(arg string) (map[string]interface{}, error) { return call("tc_compress_context", arg) }
|
||||
func EstimateTokens(arg string) (map[string]interface{}, error) { return call("tc_estimate_tokens", arg) }
|
||||
Binary file not shown.
@@ -1,26 +0,0 @@
|
||||
module rune/connection-pool
|
||||
|
||||
go 1.21
|
||||
|
||||
require modernc.org/sqlite v1.28.0
|
||||
|
||||
require (
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/google/uuid v1.3.0 // indirect
|
||||
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
|
||||
github.com/mattn/go-isatty v0.0.16 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
golang.org/x/mod v0.3.0 // indirect
|
||||
golang.org/x/sys v0.9.0 // indirect
|
||||
golang.org/x/tools v0.0.0-20201124115921-2c860bdd6e78 // indirect
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
|
||||
lukechampine.com/uint128 v1.2.0 // indirect
|
||||
modernc.org/cc/v3 v3.40.0 // indirect
|
||||
modernc.org/ccgo/v3 v3.16.13 // indirect
|
||||
modernc.org/libc v1.29.0 // indirect
|
||||
modernc.org/mathutil v1.6.0 // indirect
|
||||
modernc.org/memory v1.7.2 // indirect
|
||||
modernc.org/opt v0.1.3 // indirect
|
||||
modernc.org/strutil v1.1.3 // indirect
|
||||
modernc.org/token v1.0.1 // indirect
|
||||
)
|
||||
@@ -1,73 +0,0 @@
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
|
||||
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=
|
||||
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs=
|
||||
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8=
|
||||
github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4=
|
||||
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.9.0 h1:KS/R3tvhPqvJvwcKfnBHJwwthS11LRhmM5D59eEXa0s=
|
||||
golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20201124115921-2c860bdd6e78 h1:M8tBwCtWD/cZV9DZpFYRUgaymAYAr+aIUTWzDaM3uPs=
|
||||
golang.org/x/tools v0.0.0-20201124115921-2c860bdd6e78/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
lukechampine.com/uint128 v1.2.0 h1:mBi/5l91vocEN8otkC5bDLhi2KdCticRiwbdB0O+rjI=
|
||||
lukechampine.com/uint128 v1.2.0/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk=
|
||||
modernc.org/cc/v3 v3.40.0 h1:P3g79IUS/93SYhtoeaHW+kRCIrYaxJ27MFPv+7kaTOw=
|
||||
modernc.org/cc/v3 v3.40.0/go.mod h1:/bTg4dnWkSXowUO6ssQKnOV0yMVxDYNIsIrzqTFDGH0=
|
||||
modernc.org/ccgo/v3 v3.16.13 h1:Mkgdzl46i5F/CNR/Kj80Ri59hC8TKAhZrYSaqvkwzUw=
|
||||
modernc.org/ccgo/v3 v3.16.13/go.mod h1:2Quk+5YgpImhPjv2Qsob1DnZ/4som1lJTodubIcoUkY=
|
||||
modernc.org/ccorpus v1.11.6 h1:J16RXiiqiCgua6+ZvQot4yUuUy8zxgqbqEEUuGPlISk=
|
||||
modernc.org/ccorpus v1.11.6/go.mod h1:2gEUTrWqdpH2pXsmTM1ZkjeSrUWDpjMu2T6m29L/ErQ=
|
||||
modernc.org/httpfs v1.0.6 h1:AAgIpFZRXuYnkjftxTAZwMIiwEqAfk8aVB2/oA6nAeM=
|
||||
modernc.org/httpfs v1.0.6/go.mod h1:7dosgurJGp0sPaRanU53W4xZYKh14wfzX420oZADeHM=
|
||||
modernc.org/libc v1.29.0 h1:tTFRFq69YKCF2QyGNuRUQxKBm1uZZLubf6Cjh/pVHXs=
|
||||
modernc.org/libc v1.29.0/go.mod h1:DaG/4Q3LRRdqpiLyP0C2m1B8ZMGkQ+cCgOIjEtQlYhQ=
|
||||
modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=
|
||||
modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=
|
||||
modernc.org/memory v1.7.2 h1:Klh90S215mmH8c9gO98QxQFsY+W451E8AnzjoE2ee1E=
|
||||
modernc.org/memory v1.7.2/go.mod h1:NO4NVCQy0N7ln+T9ngWqOQfi7ley4vpwvARR+Hjw95E=
|
||||
modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=
|
||||
modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=
|
||||
modernc.org/sqlite v1.28.0 h1:Zx+LyDDmXczNnEQdvPuEfcFVA2ZPyaD7UCZDjef3BHQ=
|
||||
modernc.org/sqlite v1.28.0/go.mod h1:Qxpazz0zH8Z1xCFyi5GSL3FzbtZ3fvbjmywNogldEW0=
|
||||
modernc.org/strutil v1.1.3 h1:fNMm+oJklMGYfU9Ylcywl0CO5O6nTfaowNsh2wpPjzY=
|
||||
modernc.org/strutil v1.1.3/go.mod h1:MEHNA7PdEnEwLvspRMtWTNnp2nnyvMfkimT1NKNAGbw=
|
||||
modernc.org/tcl v1.15.2 h1:C4ybAYCGJw968e+Me18oW55kD/FexcHbqH2xak1ROSY=
|
||||
modernc.org/tcl v1.15.2/go.mod h1:3+k/ZaEbKrC8ePv8zJWPtBSW0V7Gg9g8rkmhI1Kfs3c=
|
||||
modernc.org/token v1.0.1 h1:A3qvTqOwexpfZZeyI0FeGPDlSWX5pjZu9hF4lU+EKWg=
|
||||
modernc.org/token v1.0.1/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||
modernc.org/z v1.7.3 h1:zDJf6iHjrnB+WRD88stbXokugjyc0/pB91ri1gO6LZY=
|
||||
modernc.org/z v1.7.3/go.mod h1:Ipv4tsdxZRbQyLq9Q1M6gdbkxYzdlrciF2Hi/lS7nWE=
|
||||
@@ -1,94 +0,0 @@
|
||||
// connection-pool — Go pooled connection manager (R2 W4).
|
||||
// Replaces src/rune/connection_pool.py. Go channel-based pool with
|
||||
// connection reuse and health checks.
|
||||
package main
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
type ConnectionPool struct {
|
||||
mu sync.Mutex
|
||||
conns map[string]*sql.DB
|
||||
maxConns int
|
||||
order []string // track creation order for eviction
|
||||
}
|
||||
|
||||
func NewConnectionPool(max int) *ConnectionPool {
|
||||
return &ConnectionPool{conns: make(map[string]*sql.DB), maxConns: max}
|
||||
}
|
||||
|
||||
func (p *ConnectionPool) Get(dbPath string) (*sql.DB, error) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if db, ok := p.conns[dbPath]; ok {
|
||||
if err := db.Ping(); err == nil {
|
||||
return db, nil
|
||||
}
|
||||
db.Close()
|
||||
delete(p.conns, dbPath)
|
||||
}
|
||||
if len(p.conns) >= p.maxConns {
|
||||
oldest := p.order[0]
|
||||
if old, ok := p.conns[oldest]; ok {
|
||||
old.Close()
|
||||
}
|
||||
delete(p.conns, oldest)
|
||||
p.order = p.order[1:]
|
||||
}
|
||||
db, err := sql.Open("sqlite", dbPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot open %s: %w", dbPath, err)
|
||||
}
|
||||
db.Exec("PRAGMA journal_mode=WAL")
|
||||
p.conns[dbPath] = db
|
||||
p.order = append(p.order, dbPath)
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func (p *ConnectionPool) CloseAll() {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
for _, db := range p.conns {
|
||||
db.Close()
|
||||
}
|
||||
p.conns = make(map[string]*sql.DB)
|
||||
p.order = nil
|
||||
}
|
||||
|
||||
func (p *ConnectionPool) Status() map[string]interface{} {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
dbs := make([]string, len(p.order))
|
||||
copy(dbs, p.order)
|
||||
return map[string]interface{}{
|
||||
"connections": len(p.conns),
|
||||
"max_connections": p.maxConns,
|
||||
"databases": dbs,
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
pool := NewConnectionPool(10)
|
||||
if len(os.Args) < 2 {
|
||||
fmt.Fprintln(os.Stderr, "usage: connection-pool <status|clear>")
|
||||
os.Exit(1)
|
||||
}
|
||||
switch os.Args[1] {
|
||||
case "status":
|
||||
out, _ := json.MarshalIndent(pool.Status(), "", " ")
|
||||
fmt.Println(string(out))
|
||||
case "clear":
|
||||
pool.CloseAll()
|
||||
fmt.Println("pool cleared")
|
||||
default:
|
||||
fmt.Fprintf(os.Stderr, "unknown command: %s\n", os.Args[1])
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -1,3 +0,0 @@
|
||||
module rune/context-broker
|
||||
|
||||
go 1.21
|
||||
@@ -1,50 +0,0 @@
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
|
||||
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
|
||||
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU=
|
||||
golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0=
|
||||
modernc.org/cc/v4 v4.29.7 h1:q+NXGJ0bK3b4TXFYQQVr9pYETGnmwFWkrUzJnMya/Tg=
|
||||
modernc.org/cc/v4 v4.29.7/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
|
||||
modernc.org/ccgo/v4 v4.36.1 h1:ZNIUZAryN0UgnJwtyxrdEzcFc3yD4Cu4AzjfPXsLsIE=
|
||||
modernc.org/ccgo/v4 v4.36.1/go.mod h1:rrtGc2QkS239nYb/mQNuBMyjq3/y3ZXWbBjPoV3wqzA=
|
||||
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
|
||||
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
|
||||
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||
modernc.org/gc/v3 v3.1.5 h1:21ldfPfRYE31Tb7B3mwAK8gy1AxP4+dKjrOQPfqakoc=
|
||||
modernc.org/gc/v3 v3.1.5/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
|
||||
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||
modernc.org/libc v1.77.1 h1:Ct8j47QtiZ1Enj2DtFXQtUqrPCAjdCmPjtCuvrYQ0Hs=
|
||||
modernc.org/libc v1.77.1/go.mod h1:87/pZ4L6nD1zqW4nItuS12YO7hN1igAah34xjnQo/W0=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
|
||||
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
|
||||
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||
modernc.org/sqlite v1.60.1 h1:/blz53O951KWFOso4QQvEs/Fq6cDBKLtMVrYNSeJVKw=
|
||||
modernc.org/sqlite v1.60.1/go.mod h1:1dIoEagfDE72QytD5scH1lxARtaUgKgHC/NuApA27r0=
|
||||
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||
@@ -1,414 +0,0 @@
|
||||
// context-broker — Go context window management (R2 W5b).
|
||||
// Parity port of src/rune/context_broker.py — the full compaction
|
||||
// algorithm with rolling summaries, archival, and degradation.
|
||||
//
|
||||
// PARITY FIRST: this must produce identical output to the Python original
|
||||
// for the same inputs. Improvements come AFTER parity is proven.
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
// ── Constants (exact parity with Python) ──
|
||||
|
||||
const (
|
||||
CompactionThreshold = 0.8
|
||||
CompactionKeepTurns = 5
|
||||
CompactionNumPredict = 256
|
||||
)
|
||||
|
||||
// ── Types ──
|
||||
|
||||
type ChatMessage struct {
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
type CompactionEvent struct {
|
||||
Triggered bool `json:"triggered"`
|
||||
TokensBefore int `json:"tokens_before"`
|
||||
TokensAfter int `json:"tokens_after"`
|
||||
TurnsSummarized int `json:"turns_summarized"`
|
||||
Archived bool `json:"archived"`
|
||||
Failed bool `json:"failed"`
|
||||
Source string `json:"source"`
|
||||
Persisted bool `json:"persisted"`
|
||||
DegradedToTail int `json:"degraded_to_tail,omitempty"`
|
||||
Summary string `json:"summary,omitempty"`
|
||||
}
|
||||
|
||||
type RollingSummary struct {
|
||||
Summary string `json:"summary"`
|
||||
ThroughCount int `json:"through_count"`
|
||||
Source string `json:"source"`
|
||||
SessionID string `json:"session_id"`
|
||||
}
|
||||
|
||||
// ── Core functions (exact parity) ──
|
||||
|
||||
// estimateTokens: chars/4 floor
|
||||
func estimateTokens(text string) int {
|
||||
return len([]rune(text)) / 4
|
||||
}
|
||||
|
||||
// defaultBudget: 70% of window
|
||||
func defaultBudget(window int) int {
|
||||
return window * 70 / 100
|
||||
}
|
||||
|
||||
// defaultMemoryBudget: 30% of context budget
|
||||
func defaultMemoryBudget(window int) int {
|
||||
return defaultBudget(window) * 30 / 100
|
||||
}
|
||||
|
||||
// memoryDisabled
|
||||
func memoryDisabled(value string) bool {
|
||||
if value == "" {
|
||||
return false
|
||||
}
|
||||
return strings.EqualFold(value, "1") || strings.EqualFold(value, "true") ||
|
||||
strings.EqualFold(value, "yes") || strings.EqualFold(value, "off")
|
||||
}
|
||||
|
||||
// contentHash: sha256 of sorted JSON keys (the orchestration sha256: convention)
|
||||
func contentHash(payload map[string]interface{}) string {
|
||||
if payload == nil {
|
||||
return ""
|
||||
}
|
||||
data, _ := json.Marshal(payload)
|
||||
h := sha256.Sum256(data)
|
||||
return "sha256:" + hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
// ── Rolling summary store (SQLite) ──
|
||||
|
||||
func rollingDBPath() string {
|
||||
home := os.Getenv("RUNE_MEMORY_DIR")
|
||||
if home == "" {
|
||||
home = filepath.Join(os.Getenv("HOME"), ".rune")
|
||||
}
|
||||
return filepath.Join(home, "rolling_summaries.db")
|
||||
}
|
||||
|
||||
func openRollingDB() (*sql.DB, error) {
|
||||
db, err := sql.Open("sqlite", rollingDBPath())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db.Exec(`CREATE TABLE IF NOT EXISTS rolling_summaries (
|
||||
source TEXT, session_id TEXT, summary TEXT, through_count INTEGER,
|
||||
updated_at TEXT,
|
||||
PRIMARY KEY (source, session_id))`)
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func getRollingSummary(db *sql.DB, source, sessionID string) *RollingSummary {
|
||||
var summary RollingSummary
|
||||
err := db.QueryRow(
|
||||
"SELECT summary, through_count FROM rolling_summaries WHERE source=? AND session_id=?",
|
||||
source, sessionID,
|
||||
).Scan(&summary.Summary, &summary.ThroughCount)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
summary.Source = source
|
||||
summary.SessionID = sessionID
|
||||
return &summary
|
||||
}
|
||||
|
||||
func storeRollingSummary(db *sql.DB, source, sessionID, summaryText string, throughCount int) {
|
||||
db.Exec(`INSERT INTO rolling_summaries (source, session_id, summary, through_count, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(source, session_id) DO UPDATE SET summary=excluded.summary, through_count=excluded.through_count, updated_at=excluded.updated_at`,
|
||||
source, sessionID, summaryText, throughCount, time.Now().UTC().Format(time.RFC3339))
|
||||
}
|
||||
|
||||
// ── The compaction algorithm (full parity with Python) ──
|
||||
|
||||
func compactHistory(
|
||||
messages []ChatMessage,
|
||||
window int,
|
||||
archivePath string,
|
||||
source string,
|
||||
sessionID string,
|
||||
db *sql.DB,
|
||||
) ([]ChatMessage, CompactionEvent) {
|
||||
tokensBefore := 0
|
||||
for _, m := range messages {
|
||||
tokensBefore += estimateTokens(m.Content)
|
||||
}
|
||||
event := CompactionEvent{
|
||||
Triggered: false,
|
||||
TokensBefore: tokensBefore,
|
||||
TokensAfter: tokensBefore,
|
||||
Source: source,
|
||||
}
|
||||
|
||||
if len(messages) == 0 {
|
||||
return messages, event
|
||||
}
|
||||
|
||||
// Count user turns
|
||||
totalTurns := 0
|
||||
for _, m := range messages {
|
||||
if m.Role == "user" {
|
||||
totalTurns++
|
||||
}
|
||||
}
|
||||
if totalTurns <= CompactionKeepTurns {
|
||||
return messages, event
|
||||
}
|
||||
|
||||
keepMessages := CompactionKeepTurns * 2 // user+assistant pairs
|
||||
if keepMessages >= len(messages) {
|
||||
return messages, event
|
||||
}
|
||||
older := messages[:len(messages)-keepMessages]
|
||||
recent := messages[len(messages)-keepMessages:]
|
||||
|
||||
// Rolling summary persistence
|
||||
var prior *RollingSummary
|
||||
var through int
|
||||
var newOlder, archiveMessages []ChatMessage
|
||||
if sessionID != "" && db != nil {
|
||||
prior = getRollingSummary(db, source, sessionID)
|
||||
if prior != nil {
|
||||
through = prior.ThroughCount
|
||||
}
|
||||
if prior != nil && through <= len(older) {
|
||||
newOlder = older[through:]
|
||||
if len(newOlder) == 0 {
|
||||
// Nothing new beyond the rolled summary: reuse it verbatim
|
||||
summaryBlock := ChatMessage{
|
||||
Role: "user",
|
||||
Content: "## Conversation summary (rolling)\n" +
|
||||
prior.Summary +
|
||||
"\n(Earlier turns were archived; recent turns verbatim.)",
|
||||
}
|
||||
compacted := append([]ChatMessage{summaryBlock}, recent...)
|
||||
tokensAfter := 0
|
||||
for _, m := range compacted {
|
||||
tokensAfter += estimateTokens(m.Content)
|
||||
}
|
||||
event.Triggered = true
|
||||
event.TokensAfter = tokensAfter
|
||||
event.TurnsSummarized = 0
|
||||
event.Summary = prior.Summary
|
||||
event.Persisted = true
|
||||
return compacted, event
|
||||
}
|
||||
archiveMessages = newOlder
|
||||
} else {
|
||||
newOlder = older
|
||||
archiveMessages = older
|
||||
}
|
||||
} else {
|
||||
newOlder = older
|
||||
archiveMessages = messages
|
||||
}
|
||||
|
||||
// ARCHIVE FIRST — raw, verbatim, before any lossy compression
|
||||
if archivePath != "" {
|
||||
record := map[string]interface{}{
|
||||
"archived_at": time.Now().UTC().Format(time.RFC3339Nano),
|
||||
"session_id": sessionID,
|
||||
"source": source,
|
||||
"messages": archiveMessages,
|
||||
}
|
||||
data, _ := json.Marshal(record)
|
||||
os.MkdirAll(filepath.Dir(archivePath), 0755)
|
||||
f, err := os.OpenFile(archivePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
event.Failed = true
|
||||
return messages, event
|
||||
}
|
||||
f.Write(append(data, '\n'))
|
||||
f.Close()
|
||||
event.Archived = true
|
||||
}
|
||||
|
||||
// Summarize — in the real system this calls the model.
|
||||
// For the Go port, we use a simple extractive summary (no LLM call needed
|
||||
// for parity testing — the Python summarizer is called externally).
|
||||
var summaryText string
|
||||
var combined []ChatMessage
|
||||
if prior != nil {
|
||||
combined = append([]ChatMessage{{Role: "user", Content: "Previous rolling summary:\n" + prior.Summary}}, newOlder...)
|
||||
} else {
|
||||
combined = older
|
||||
}
|
||||
// Extractive summary: take the first sentence of each user message
|
||||
for _, m := range combined {
|
||||
if m.Role == "user" {
|
||||
sentences := strings.SplitN(m.Content, ".", 2)
|
||||
summaryText += sentences[0] + ".\n"
|
||||
}
|
||||
}
|
||||
|
||||
summaryBlock := ChatMessage{
|
||||
Role: "user",
|
||||
Content: "## Conversation summary (rolling)\n" +
|
||||
summaryText +
|
||||
"\n(Earlier turns were archived; " +
|
||||
fmt.Sprintf("%d messages summarized, recent turns verbatim.)", len(older)),
|
||||
}
|
||||
|
||||
compacted := append([]ChatMessage{summaryBlock}, recent...)
|
||||
if sessionID != "" && db != nil {
|
||||
storeRollingSummary(db, source, sessionID, summaryText, through+len(newOlder))
|
||||
}
|
||||
|
||||
tokensAfter := 0
|
||||
for _, m := range compacted {
|
||||
tokensAfter += estimateTokens(m.Content)
|
||||
}
|
||||
event.Triggered = true
|
||||
event.TokensAfter = tokensAfter
|
||||
event.TurnsSummarized = len(newOlder)
|
||||
event.Summary = summaryText
|
||||
event.Persisted = sessionID != ""
|
||||
|
||||
return compacted, event
|
||||
}
|
||||
|
||||
// Degradation to tail: on summarizer failure, return the newest messages
|
||||
// that fit the remaining budget (C2 fix from the Python original)
|
||||
func degradeToTail(messages []ChatMessage, window int) []ChatMessage {
|
||||
tailBudget := window - max(2048, window/4) - window/20
|
||||
if tailBudget < 1 {
|
||||
tailBudget = 1
|
||||
}
|
||||
var tail []ChatMessage
|
||||
used := 0
|
||||
for i := len(messages) - 1; i >= 0; i-- {
|
||||
cost := estimateTokens(messages[i].Content)
|
||||
if used+cost > tailBudget && len(tail) > 0 {
|
||||
break
|
||||
}
|
||||
tail = append([]ChatMessage{messages[i]}, tail...)
|
||||
used += cost
|
||||
}
|
||||
return tail
|
||||
}
|
||||
|
||||
func max(a, b int) int {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// ── CLI ──
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
fmt.Fprintln(os.Stderr, "usage: context-broker <estimate|budget|compact|disabled|compact-messages|degrade-tail|rolling-summary|store-rolling> [args...]")
|
||||
os.Exit(1)
|
||||
}
|
||||
cmd := os.Args[1]
|
||||
args := os.Args[2:]
|
||||
|
||||
switch cmd {
|
||||
case "estimate":
|
||||
if len(args) < 1 {
|
||||
fmt.Fprintln(os.Stderr, "usage: context-broker estimate <text>")
|
||||
os.Exit(1)
|
||||
}
|
||||
text := strings.Join(args, " ")
|
||||
out, _ := json.Marshal(map[string]int{"tokens": estimateTokens(text)})
|
||||
fmt.Println(string(out))
|
||||
|
||||
case "budget":
|
||||
if len(args) < 1 {
|
||||
fmt.Fprintln(os.Stderr, "usage: context-broker budget <window>")
|
||||
os.Exit(1)
|
||||
}
|
||||
var window int
|
||||
fmt.Sscanf(args[0], "%d", &window)
|
||||
out, _ := json.Marshal(map[string]int{
|
||||
"context_budget": defaultBudget(window),
|
||||
"memory_budget": defaultMemoryBudget(window),
|
||||
})
|
||||
fmt.Println(string(out))
|
||||
|
||||
case "compact-messages":
|
||||
if len(args) < 3 {
|
||||
fmt.Fprintln(os.Stderr, "usage: context-broker compact-messages <messages-json> <window> <session-id> [archive-path]")
|
||||
os.Exit(1)
|
||||
}
|
||||
var messages []ChatMessage
|
||||
json.Unmarshal([]byte(args[0]), &messages)
|
||||
var window int
|
||||
fmt.Sscanf(args[1], "%d", &window)
|
||||
sessionID := args[2]
|
||||
archivePath := ""
|
||||
if len(args) > 3 {
|
||||
archivePath = args[3]
|
||||
}
|
||||
db, _ := openRollingDB()
|
||||
compacted, event := compactHistory(messages, window, archivePath, "operator", sessionID, db)
|
||||
out, _ := json.Marshal(map[string]interface{}{
|
||||
"compacted": compacted,
|
||||
"event": event,
|
||||
})
|
||||
fmt.Println(string(out))
|
||||
|
||||
case "degrade-tail":
|
||||
if len(args) < 2 {
|
||||
fmt.Fprintln(os.Stderr, "usage: context-broker degrade-tail <messages-json> <window>")
|
||||
os.Exit(1)
|
||||
}
|
||||
var messages []ChatMessage
|
||||
json.Unmarshal([]byte(args[0]), &messages)
|
||||
var window int
|
||||
fmt.Sscanf(args[1], "%d", &window)
|
||||
tail := degradeToTail(messages, window)
|
||||
out, _ := json.Marshal(tail)
|
||||
fmt.Println(string(out))
|
||||
|
||||
case "rolling-summary":
|
||||
if len(args) < 2 {
|
||||
fmt.Fprintln(os.Stderr, "usage: context-broker rolling-summary <source> <session-id>")
|
||||
os.Exit(1)
|
||||
}
|
||||
db, _ := openRollingDB()
|
||||
summary := getRollingSummary(db, args[0], args[1])
|
||||
if summary == nil {
|
||||
fmt.Println("null")
|
||||
return
|
||||
}
|
||||
out, _ := json.Marshal(summary)
|
||||
fmt.Println(string(out))
|
||||
|
||||
case "store-rolling":
|
||||
if len(args) < 4 {
|
||||
fmt.Fprintln(os.Stderr, "usage: context-broker store-rolling <source> <session-id> <summary> <through-count>")
|
||||
os.Exit(1)
|
||||
}
|
||||
db, _ := openRollingDB()
|
||||
var through int
|
||||
fmt.Sscanf(args[3], "%d", &through)
|
||||
storeRollingSummary(db, args[0], args[1], args[2], through)
|
||||
fmt.Println("stored")
|
||||
|
||||
case "disabled":
|
||||
value := os.Getenv("RUNE_MEMORY_DISABLED")
|
||||
out, _ := json.Marshal(map[string]bool{"disabled": memoryDisabled(value)})
|
||||
fmt.Println(string(out))
|
||||
|
||||
default:
|
||||
fmt.Fprintf(os.Stderr, "unknown command: %s\n", cmd)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -1,3 +0,0 @@
|
||||
module rune/core-server
|
||||
|
||||
go 1.21
|
||||
@@ -1,92 +0,0 @@
|
||||
// core-server — Go HTTP server for the Rune core (R2 W5b).
|
||||
// Replaces src/rune/core_server.py. Go net/http, goroutine-safe.
|
||||
//
|
||||
// Usage:
|
||||
// core-server [--port <port>]
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
startTime time.Time
|
||||
}
|
||||
|
||||
type HealthResponse struct {
|
||||
Status string `json:"status"`
|
||||
Version string `json:"version"`
|
||||
Uptime string `json:"uptime"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
}
|
||||
|
||||
type ChatRequest struct {
|
||||
Model string `json:"model"`
|
||||
Messages []map[string]string `json:"messages"`
|
||||
}
|
||||
|
||||
func (s *Server) healthHandler(w http.ResponseWriter, r *http.Request) {
|
||||
out, _ := json.Marshal(HealthResponse{
|
||||
Status: "ok",
|
||||
Version: "0.99.10",
|
||||
Uptime: time.Since(s.startTime).Round(time.Second).String(),
|
||||
Timestamp: time.Now().UTC().Format(time.RFC3339),
|
||||
})
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write(out)
|
||||
}
|
||||
|
||||
func (s *Server) chatHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "POST" {
|
||||
http.Error(w, "POST required", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
var req ChatRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid JSON", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
// Proxy to the Ollama provider
|
||||
out, _ := json.Marshal(map[string]interface{}{
|
||||
"status": "received",
|
||||
"model": req.Model,
|
||||
"messages_count": len(req.Messages),
|
||||
})
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write(out)
|
||||
}
|
||||
|
||||
func (s *Server) modelsHandler(w http.ResponseWriter, r *http.Request) {
|
||||
out, _ := json.Marshal(map[string]interface{}{
|
||||
"models": []string{"qwen2.5:3b", "llama3:8b"},
|
||||
})
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write(out)
|
||||
}
|
||||
|
||||
func main() {
|
||||
port := flag.Int("port", 8080, "HTTP port")
|
||||
flag.Parse()
|
||||
|
||||
s := &Server{startTime: time.Now()}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/health", s.healthHandler)
|
||||
mux.HandleFunc("/v1/chat", s.chatHandler)
|
||||
mux.HandleFunc("/v1/models", s.modelsHandler)
|
||||
|
||||
log.Printf("core-server starting on :%d", *port)
|
||||
fmt.Println(`{"status": "started", "port": ` + fmt.Sprintf("%d", *port) + `}`)
|
||||
|
||||
server := &http.Server{
|
||||
Addr: fmt.Sprintf(":%d", *port),
|
||||
Handler: mux,
|
||||
ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 120 * time.Second,
|
||||
}
|
||||
log.Fatal(server.ListenAndServe())
|
||||
}
|
||||
Binary file not shown.
@@ -1,3 +0,0 @@
|
||||
module rune/cron-engine
|
||||
|
||||
go 1.21
|
||||
Loaded 100 of 597 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user