Compare commits

...
Author SHA1 Message Date
mathiasandClaude Opus 5 3c70b6f367 fix(claudewatcher): scrub credentials embedded in URL userinfo
CI / Lint / Test / Vet (push) Successful in 33s
CI / Mirror to GitHub (push) Successful in 5s
The scrubber had a rule for `postgres://user:pass@` and none for the
general `scheme://user:secret@host` form — which is exactly what a git
credential store holds:

    https://<user>:<token>@git.d-ma.be

Verified against all 13 DefaultRules with an invented value: it matched
none of them. Not authorization-header, not bearer-token, and not
homelab-env-token, which needs a `_TOKEN=`-style prefix a bare URL does
not have. So such a turn was ingested rather than dropped, against the
stated intent in this file's own doc comment:

    Fail-closed by design: we'd rather lose signal than ingest
    credentials into a public-readable brain.

It failed closed for the shapes it named and open for this one.

How it surfaced: a test suite in mathias/infra executed a script that
configures git while inheriting the operator's real $HOME, read koala's
live ~/.git-credentials, and printed two live values. ~/.claude/projects
is this watcher's own input, so the scrubber was the last line of defence
for that mistake. A sweep of that tree found 12 occurrences of 2 distinct
credential-shaped URLs across 4 transcripts in 3 sessions — so the shape
had been passing for a while, not just that once. Both credentials are
being rotated (infra#466).

The generalisable point is not "do not read the credential file". That
mistake will recur. It is that this shape must fail closed, because the
scrubber is what decides whether such a mistake is survivable or
permanent.

Ordering: the new rule sits after postgres-uri-with-password so a DSN
still reports the more specific name, the same convention as
authorization-header before bearer-token.

Both directions are tested, because a rule that dropped every URL with a
colon would discard most of the signal this watcher exists to keep. The
{8,} floor on the secret half keeps `https://host:443/path` and
`https://user:@host` out; the `[^:\s/@]+` user half stops a host:port
pair being read as userinfo. Must-not-scrub cases include a host with a
port, a password-less DSN, a colon in a query string, and the literal
printf format string `https://oauth2:%s@%s`.

Closes #142
Refs mathias/infra#466

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-30 16:08:17 +02:00
mathiasandClaude Opus 5 b3b555fa23 chore(context): adopt canonical context-sync.sh and re-sync adapters
CI / Lint / Test / Vet (push) Successful in 1m46s
CI / Mirror to GitHub (push) Successful in 4s
infra's scripts/context-sync.sh is the estate canonical, and it moved in infra
262369b (a SIGPIPE fix on the placeholder-reporting path: `printf | grep -o |
head -1` became `head -1 < <(grep -o ...)`). Every other repo still carried the
old line, so ContextSyncScriptDrift and ContextAdapterDrift were both firing.

Also picks up the canonical AGENT.md change from local-dev a01ee80 — rule 5's
GitOps review lane and the new precedence rule — which every repo's adapters
need regenerated for regardless of the script.

Refs mathias/infra#470

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-30 10:36:40 +02:00
mathiasandClaude Opus 5 e9805c7eb6 chore(context): regenerate derived adapters from the canonical root context
CI / Lint / Test / Vet (push) Successful in 56s
CI / Mirror to GitHub (push) Successful in 5s
ContextAdapterDrift was firing for 13 repos. Picks up behaviour rule 7
("Finish what's closable"), which landed in ~/dev/.context/AGENT.md and never
reached any repo's derived files.

Where mcp.json changes, it also picks up root MCP config the repo was stale on:
brain/gitea/infra move from public hostnames to tailnet Serve URLs, and gitea's
bearer changes from GITEA_MCP_TOKEN to DMABE_GITEA_API_TOKEN — gitea-mcp
authenticates by pass-through and 401s on the former, so a harness syncing from
the old file had a dead gitea server and no signal saying so.

No literal secrets: mcp.json carries ${VAR} placeholders only.

CLAUDE.md deliberately unchanged — context-sync writes it from PROJECT.md alone,
since Claude Code walks up to ~/dev/CLAUDE.md for root context.

Refs mathias/infra ContextAdapterDrift

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-25 07:34:25 +02:00
mathias 3d5af85713 fix(frontmatter): consolidate 3 independent fence-parsers into one (#139)
CI / Lint / Test / Vet (push) Successful in 32s
CI / Mirror to GitHub (push) Successful in 4s
Co-authored-by: Mathias <mthbqv@gmail.com>
2026-09-23 13:07:32 +00:00
mathiasandClaude Sonnet 5 c6341f020a feat(server): say at startup when alerting is unconfigured (#107) (#140)
CI / Lint / Test / Vet (push) Successful in 39s
CI / Mirror to GitHub (push) Successful in 5s
feat(server): say at startup when alerting is unconfigured (#107)

WARN once at startup when BRAIN_NTFY_URL is unset, naming what will not fire (brain_edit_root governance rewrites, capture audit degradation). Rebase of PR #108 (never CI-tested) onto current main, no functional change to alertingWarnings.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Mathias <mthbqv@gmail.com>
2026-09-23 13:02:40 +00:00
mathiasandClaude Sonnet 5 e157311cd8 fix(mcp): validate the claim envelope before brain_edit writes too (#136)
CI / Lint / Test / Vet (push) Successful in 39s
CI / Mirror to GitHub (push) Successful in 4s
7 review rounds closed 8 distinct bypasses across two mechanism families: fence-detection (field-name substring, block-containment, fence-stripping, CRLF, UTF-8 BOM) and value-extraction (folded YAML block scalar hiding an invalid value). A known v1 gap remains in the block-scalar fold's handling of blank-line-interrupted continuations — documented on checkClaimEnvelope, accepted deliberately (narrow, requires an already-privileged caller deliberately constructing a specific malformed-YAML shape) rather than chased past diminishing returns. Real fix (shared, tested, encoding-normalized frontmatter parser) tracked separately as hyperguild#138.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Mathias <mthbqv@gmail.com>
2026-09-23 10:28:07 +00:00
mathias a5f502eb9c fix(api): UpdateNote reserves updated_at/supersedes/supersede_reason from the caller's fragment (#137)
CI / Mirror to GitHub (push) Successful in 3s
CI / Lint / Test / Vet (push) Successful in 39s
Closes #125. Skips updated_at/supersedes/supersede_reason in the caller fragment merge loop so they cannot be set via the fragment, only via the intended entry points.
delete_branch_after_merge=true

Co-authored-by: Mathias <mthbqv@gmail.com>
2026-09-23 08:18:30 +00:00
mathias 7ed2a7d3b4 fix(api): frontmatter parser must not misparse indented list items as keys (#135)
CI / Mirror to GitHub (push) Successful in 4s
CI / Lint / Test / Vet (push) Successful in 40s
Co-authored-by: Mathias <mthbqv@gmail.com>
2026-09-23 08:12:06 +00:00
mathiasandClaude Sonnet 5 674858fe5e fix(watcher): never walk into raw/rejected/ — brain_reject (closes #81)
CI / Lint / Test / Vet (push) Successful in 33s
CI / Mirror to GitHub (push) Successful in 4s
Adds brain_reject (RejectNote + MCP tool) and fixes the watcher to skip raw/rejected/, preventing declined notes from being silently re-ingested and republished.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Mathias <mthbqv@gmail.com>
2026-09-23 06:06:35 +00:00
mathias 9a37881441 feat(pipeline): feed the current source page into the extraction prompt (#106) (#132)
CI / Lint / Test / Vet (push) Successful in 39s
CI / Mirror to GitHub (push) Successful in 4s
Co-authored-by: Mathias <mthbqv@gmail.com>
2026-09-23 05:45:47 +00:00
mathias f324f04944 fix: hyperguild brain write requires wing/hall, not legacy type/slug (#79)
CI / Lint / Test / Vet (push) Successful in 34s
CI / Mirror to GitHub (push) Successful in 4s
Removes brain_write legacy domain/type/knowledge-path params (ADR-0012) and migrates the previously-missed cmd/hyperguild CLI caller (hyperguild brain write) from <type> <slug> to <wing> <hall> <slug>, fixing a 100%% regression the first review round caught. Adds TestWrite_CLIPayloadRoundTrips exercising the real Handler.Write over HTTP to pin the wire contract.

Closes #79.

Co-authored-by: Mathias <mthbqv@gmail.com>
2026-09-23 05:43:28 +00:00
mathiasandClaude Sonnet 5 cdafdf6e0f fix(wiki): surface merge conflicts as textual-diff warnings (closes #104)
CI / Lint / Test / Vet (push) Successful in 33s
CI / Mirror to GitHub (push) Successful in 4s
Textual-diff conflict detection only (semantic contradiction detection via brain-gardener Judge deferred, confirmed by Mathias, comment 12594). Includes canonicalBlock whitespace-run normalization fix for the disagreement comparison.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Mathias <mthbqv@gmail.com>
2026-09-23 05:22:27 +00:00
mathias b340f86a45 feat(pipeline): skip extraction when the source has not changed (#105) (#126)
CI / Lint / Test / Vet (push) Successful in 40s
CI / Mirror to GitHub (push) Successful in 4s
Co-authored-by: Mathias <mthbqv@gmail.com>
2026-09-23 05:09:30 +00:00
mathias f450a6c84f feat(pipeline): ingest revises the existing page instead of clobbering it (#103)
CI / Lint / Test / Vet (push) Successful in 32s
CI / Mirror to GitHub (push) Successful in 5s
fix(wiki): give the preamble its own field instead of overloading heading=="" (#103)

Round 3 review: verified structurally that the preamble is no longer in the sections slice or the idx map, so it cannot collide with a degenerate `## ` heading. Flip-tested by reverting to the heading=="" model and confirming TestMerge_DegenerateEmptyHeadingDoesNotCollideWithPreamble goes red. Adversarial pass (multiple degenerate headings, frontmatter-only page, unicode around the ## boundary, 3x self-merge idempotency with preamble+degenerate) all held. CI green on 09aeaa9 (run 7820).

Co-authored-by: Mathias <mthbqv@gmail.com>
2026-09-22 21:43:04 +00:00
mathias 5a5d938e8e Brain-quality sweep, batch 1: brain_edit/brain_update correctness + close-session docs (#124)
CI / Lint / Test / Vet (push) Successful in 32s
CI / Mirror to GitHub (push) Successful in 4s
Co-authored-by: Mathias <mthbqv@gmail.com>
2026-09-22 21:27:11 +00:00
mathiasandClaude Opus 5 cc86a74dc5 fix(ci): stop the tag push from re-deploying, and make the infra bump idempotent
CI / Lint / Test / Vet (push) Successful in 34s
CI / Mirror to GitHub (push) Successful in 4s
Two runs of the full build+deploy fired for every push, and the second died:

    nothing to commit, working tree clean
    ❌  Failure - Main Update infra repo

The deploy was fine both times — the second run had nothing left to do. The
cause is the pair of triggers meeting: ci.yml ran on `push` to main AND on a
`v*` tag, and cd.yml keys off "CI succeeded", so `git push origin main` followed
by `git push origin refs/tags/vX` produced two CI runs for one sha and two
deploys behind them. The tag run carries the same github.sha, so it rebuilt the
same image and then found the infra manifest already pointing at it.

Nothing consumed the tag-triggered run: there is no release workflow, and cd.yml
reads github.sha rather than the tag. Dropping `tags:` removes the duplicate
build outright.

The idempotency guard stays anyway, because a manual re-run has the same shape
and should not ring the CI-red alarm for work that is already done — infra#366
turns a red run into a tracked issue, so a false red costs a real triage.

Closes #118

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 07:09:14 +02:00
mathiasandClaude Opus 5 6e449b464c fix(taskfile): remove build targets for binaries deleted months ago, and make check build (#121)
CI / Lint / Test / Vet (push) Successful in 32s
CI / Mirror to GitHub (push) Successful in 4s
Removes supervisor:dev, supervisor:build, supervisor:test:smoke, smoke:routing and scripts/smoke-routing.sh -- all pointed at cmd/supervisor (deleted c117634, 2026-05-12) or cmd/routing (iceboxed fb59c39, 2026-07-01). Repoints `build` at hyperguild:build + ingestion:build and adds `build` to `check`, so a task target naming a deleted package fails the gate instead of staying invisible to lint/test/vet.

Refs #120. Item 2 of #120 (internal/config has no non-test callers) is deliberately NOT addressed -- #120 stays open for it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Mathias <mthbqv@gmail.com>
2026-09-16 22:36:49 +00:00
mathias 868fe28c96 fix(config): delete the model-routing chain — nothing has called it since April (#119)
CI / Lint / Test / Vet (push) Successful in 31s
CI / Mirror to GitHub (push) Successful in 4s
Closes #116.

Deletes config/models.yaml, internal/config/models.go (LoadModels, ModelFor),
its test, the ModelsFile field on Config, and SUPERVISOR_MODELS_FILE from
.env.example. Option A from the issue.

Merge-gate evidence: negative claim independently re-established (no Go, shell,
Dockerfile, k8s, CI or infra-repo caller); task check exit 0 across both
modules; CI run 7374 green on the PR head.

Co-authored-by: Mathias <mthbqv@gmail.com>
2026-09-16 22:24:47 +00:00
mathiasandClaude Opus 5 6e69698343 fix(brain): a one-word tunnel title must match the prose case-exactly
CI / Mirror to GitHub (push) Successful in 4s
CI / Lint / Test / Vet (push) Successful in 31s
AutoTunnel matched note titles case-insensitively, so a one-word title linked
every entry that happened to use that word. Measured on the live corpus: 185
entries carry an auto-written See-also link to wiki/telos/decisions/wrong.md
(title "WRONG") and 136 to .../status.md — the two most-linked nodes in the
whole graph, and both of them artifacts of the English language rather than
references. telos's projects/problems/strategies/goals/beliefs entries account
for another ~60 between them.

That pollution is not cosmetic: inbound-link count is what the duplicate
Fixer picks survivors by, what orphan detection reads, and what brain_graph
shows.

One-word titles now need the title's own casing in the prose ("WRONG", "BERT",
"NLP" — an entity name in a sentence still links). Multi-word titles keep the
case-insensitive match: "risk tier middleware" is a real mention however it is
capitalised, and a three-word collision is not an accident.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 00:08:40 +02:00
mathiasandClaude Opus 5 eb2acfeeb8 fix(brain): move the wikilink strip into WriteNote/UpdateNote
CI / Mirror to GitHub (push) Successful in 4s
CI / Lint / Test / Vet (push) Successful in 32s
The BrainStore is not the only door. POST /write — the HTTP path CLAUDE.md
hands to curl and scripts — calls api.WriteNote directly, so the strip
shipped one commit ago covered brain_write and capture while leaving the raw
door ungated. A gate one door wide is not a gate.

The BrainStore keeps its own call so it can still report Ref.Unlinked to the
MCP caller; running the strip twice is a no-op on content the primitive has
already cleaned.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-16 23:59:44 +02:00
mathiasandClaude Opus 5 6e5a9cfce3 fix(brain): unwrap wikilinks that name no entry at the write boundary
CI / Mirror to GitHub (push) Successful in 4s
CI / Lint / Test / Vet (push) Successful in 35s
Every brain write accepted [[targets]] that resolve to nothing — skill
names, repo names, agent-local memory-file slugs — and each one became a
permanent [high] broken-link finding. The brain-audit digest grew 19 -> 63
high findings between 2026-08-26 and 2026-09-16; 53 of the 63 were exactly
this, and none are fixable by brain-gardener's BrokenLinkFixer, which only
repoints edit-distance-1 renames. There is no target to repoint to.

StripUnresolvedLinks resolves each link against knowledge/ + wiki/ using
brain-gardener's own resolver semantics (bare slug or wing/hall/slug path
form, code spans excluded) and unwraps the misses to plain text, reporting
them as Ref.Unlinked / the MCP `unlinked` field.

Unwrap rather than reject: a refused write on claudewatcher's unattended
ingest path is a lost learning, and the author's words are worth keeping
even when the link is not. An empty corpus is a no-op, so a misconfigured
brainDir cannot strip every link in a note.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-16 23:53:42 +02:00
mathiasandClaude Opus 5 25b79f057e feat(claudewatcher): exclude whole project directories from ingestion
CI / Mirror to GitHub (push) Successful in 4s
CI / Lint / Test / Vet (push) Successful in 1m20s
CLAUDE_INGEST_SKIP_PROJECTS takes filepath.Match globs tested against
the project directory NAME, and a matching directory is skipped during
the directory WALK — so its files are never opened and their content
never enters the process. That is a stronger property than filtering
after reading, and the difference is observable: without SkipDir,
WalkDir lists the directory's entries, and an unreadable one aborts the
entire walk, silently stopping ingestion for every other project.

Globs rather than exact names because a project directory is derived
from the session's working directory, so a git worktree yields an
ephemeral name no exact-match list could keep up with.

An unparseable pattern refuses to run. filepath.Match returns an error
ALONGSIDE a false match, so a bad pattern checked per-file would ingest
the directory while the log complained — the failure nobody notices.
Validated once, up front, in both entry points.

This complements the client-name scrubber rather than replacing it. The
scrubber drops individual turns whose content matches a client
identity; this excludes whole workspaces whose content is confidential
in ways no pattern reliably recognises. Learnings from excluded
sessions are captured deliberately through the session-close ritual
instead.

Recorded caveat: the project directory reflects the session's working
directory, NOT the repositories it touches. A session run from ~/dev
that reads an excluded repo is not excluded by this. The scrubber
remains the control for content; this is a control for workspaces.

A mutation test earned the strongest assertion here: the original tests
could not distinguish SkipDir from filtering after the walk, because
neither opens files. The unreadable-directory test can.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-15 08:09:58 +02:00
mathias 47bbac4b9f revert(lint): back out the canonical .golangci.yml adoption — repo has a nested module
CI / Lint / Test / Vet (push) Successful in 30s
CI / Mirror to GitHub (push) Successful in 3s
Adopting it turned CI red, and my pre-push verification missed why:
`golangci-lint run ./...` does NOT traverse into nested Go modules. This repo
has two — ./go.mod and ./ingestion/go.mod. I linted the root (0 issues, which
CI reproduces exactly) and never linted ingestion/, which has 3 findings:

  ingestion/internal/audit/degrading.go:81   missing case capture.AuditCentral   (exhaustive)
  ingestion/internal/capture/entities.go:37  missing case capture.ZoneUnknown    (exhaustive)
  ingestion/internal/mcp/handlers.go:29      var int_ should be int              (revive)

Those are behavioural questions and a rename, not formatting — the same class
of finding that kept cad, dispatch, ingestion-svc, dma-cli and
email-triage-agent out of the earlier waves. Consistent with that, this repo
goes back in the queue rather than being force-fitted now.

The gofumpt formatting from the same commit is kept: it is independently
correct and already green.

Verification method corrected going forward: a repo with nested modules must
be linted per module, not once from the root.
2026-09-05 14:47:39 +02:00
mathias 8a27ead91c chore(lint): adopt the canonical .golangci.yml from infra/ci-templates
CI / Mirror to GitHub (push) Skipped
CI / Lint / Test / Vet (push) Failing after 12s
Canonical lives at infra ci-templates/golangci.yml, distributed by the
infra#309 pattern: byte-identical copies, checksum drift gate in infra. Do
not edit this file here -- edit the canonical and run `task ci:sync`.

Verified locally before pushing, not pushed-and-hoped: golangci-lint v2.11.4
against a Go 1.26.1 toolchain (matching CI) reports 0 issues here.

Also applies gofumpt, which this config enables and the golangci-lint v2
default set does not check at all. That gap is why the drift was invisible:
earlier passes ran gofmt, which is weaker. Mechanical, deterministic,
build+vet verified.
2026-09-05 14:42:59 +02:00
mathias 1a9be0cfb1 style: apply gofmt
CI / Lint / Test / Vet (push) Successful in 30s
CI / Mirror to GitHub (push) Successful in 4s
Estate-wide consolidation pass. golangci-lint v2 default set enables NO
formatter, so gofmt drift accumulated silently across the estate -- 8 repos
were carrying it, this one included. Same hole that let two files rot in
dma-cli until they were found by hand (dma-cli#12).

Mechanical and deterministic: `gofmt -w`, nothing hand-edited. Verified
before commit -- gofmt -l now reports 0, go build and go vet both pass.

Clears this repo to adopt the canonical .golangci.yml (infra
ci-templates/golangci.yml, infra#309 pattern) in a later wave.
2026-09-05 12:40:34 +02:00
mathias dc2265da0b fix(ci): skip context:sync's drift check under CI, matching dma-cli/gitea-mcp
CI / Mirror to GitHub (push) Successful in 4s
CI / Lint / Test / Vet (push) Successful in 1m22s
hyperguild's Taskfile ran context:sync unconditionally in 'check', with no
guard for the CI runner having no ancestor .context/AGENT.md. That made it
silently regenerate AGENTS.md and .context/system-prompt.txt from project
context alone (82 lines vs. the committed, correct 430) and then fail its
own drift assertion against that wrong baseline every run -- a false
positive, not real drift. Verified locally: syncing with the real root
context reproduces the committed 430-line files byte for byte; syncing
without it (as CI does) produces the shorter fallback that triggered this.

Same guard dma-cli and gitea-mcp already carry, same rationale: drift is
now caught either on a developer machine or by infra's estate-wide
context-sync-drift CronJob (ADR-0019), which does have canonical access.
2026-09-05 11:36:45 +02:00
mathias c176b71b3d fix(context): AGENTS.md/system-prompt.txt committed in 4e8bdc1 were missing root content
CI / Lint / Test / Vet (push) Failing after 2s
CI / Mirror to GitHub (push) Skipped
The previous commit's regeneration produced AGENTS.md byte-identical to
CLAUDE.md (82 lines, project-only) instead of the expected root+project
concatenation (430 lines) -- root_block() rendered empty despite the run's
own log claiming "Root context: .../AGENT.md" and "AGENTS.md (root +
project...)". Not reproduced: re-running the identical command
(ROOT_CONTEXT=.../AGENT.md bash scripts/context-sync.sh) immediately after
produces the correct 430-line output every time. Whatever caused the
original miss was transient and is not diagnosed here -- flagging rather
than asserting a cause I have not confirmed.

Caught by the estate-wide context-sync-drift gate's own verification run,
not by trusting the fix commit. Regenerated fresh and confirmed root
content is present before committing this time.
2026-09-05 08:36:03 +02:00
mathias 4e8bdc137e fix(context): sync to the estate canonical context-sync.sh (ADR-0019)
CI / Lint / Test / Vet (push) Successful in 1m5s
CI / Mirror to GitHub (push) Successful in 4s
Caught by the new estate-wide context-sync-drift gate (infra, ADR-0019).
This repo's copy had diverged from the canonical established in dma-cli/
infra -- synced to it, dead Cursor/Aider artifacts removed (2026-09-01
harness decision), Taskfile's drift assertion narrowed to match, adapters
regenerated against the current canonical AGENT.md.

Changed:
M  .context/system-prompt.txt
M  AGENTS.md
M  scripts/context-sync.sh

Refs: ADR-0019 (infra)
2026-09-05 08:30:04 +02:00
mathias 42235dcb6a fix(scan): an allowlist was hiding a real Gitea PAT on a false justification
CI / Lint / Test / Vet (push) Successful in 32s
CI / Mirror to GitHub (push) Successful in 5s
infra#344. The removed block suppressed
docs/superpowers/plans/2026-04-22-phase4-attempt-wiring.md, and its description
stated why:

    "Literal placeholder word REDACTED matched as if it were a token
     (verified 2026-08-04: extracted Secret == 'REDACTED' exactly, gitleaks'
      curl-auth-header rule matched the placeholder text itself, not a real
      credential)"

That is not what the file contained. Line 1054 carried a real 40-character hex
Gitea PAT in an `Authorization: token ...` header — not the eight-character word
REDACTED. Whether the file changed after the check or the check was wrong, the
justification has been guarding the wrong thing since.

Confirmed dead by side-effect before touching it, never by printing it: `GET
/api/v1/user` with that token returns 401. So there is nothing to rotate. It is
redacted here anyway, because a dead credential in a doc is still a working
example of how to write a live one, and git history keeps the original either
way.

Two independent failures had to line up, which is the same pair as infra#256:

1. The `paths` clause made the block far broader than its description. gitleaks
   ORs global allowlist clauses and ignores `condition = "AND"`, so the ENTIRE
   file was immune — a live token pasted into that doc tomorrow would have been
   suppressed on the strength of a note about a different value.
2. The justification was never re-checked against the file it justifies.

With the token redacted the allowlist has nothing left to do, so it is deleted
rather than narrowed. Repo scans clean, and a planted live-shaped credential in
that same file is now caught.

Refs: mathias/infra#344, mathias/infra#256, mathias/infra#317
2026-08-31 07:24:07 +02:00
mathiasandClaude Sonnet 5 05330ad54a feat(brain): add Gemini as brain_answer's third LLM tier
CI / Lint / Test / Vet (push) Successful in 36s
CI / Mirror to GitHub (push) Successful in 4s
llm.Router was primary-then-fallback (berget -> iguana ollama). Both
have failed together at least once in production (berget 5xx outage +
a cold fallback model exceeding the shared timeout budget), leaving
brain_answer/brain_classify fully down.

Router gains an optional Tertiary *Client, tried only if both Primary
and Fallback fail. Nil-safe — existing 2-tier deployments (no
BRAIN_LLM_TERTIARY_URL) behave exactly as before.

main.go wires it from BRAIN_LLM_TERTIARY_URL/MODEL + GEMINI_API_KEY,
pointed at Google's OpenAI-compatible Gemini endpoint
(generativelanguage.googleapis.com/v1beta/openai/) — llm.Client already
speaks OpenAI-shaped chat-completions, so no new client type needed.

Tests: TestRouter_FallsBackToTertiaryWhenPrimaryAndFallbackFail,
TestRouter_TertiaryNotCalledWhenFallbackSucceeds, TestRouter_AllThreeFail,
TestRouter_NilTertiary (2-tier backward-compat). Full suite green
(both modules, -race), golangci-lint clean.

Deployment env vars (infra repo, separate commit — GitOps, TBD there
too): BRAIN_LLM_TERTIARY_URL, BRAIN_LLM_TERTIARY_MODEL, GEMINI_API_KEY
secretRef.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-30 14:43:25 +02:00
mathias 692244d213 security: disposition the one historical gitleaks finding (infra#326)
CI / Lint / Test / Vet (push) Successful in 31s
CI / Mirror to GitHub (push) Successful in 3s
A Gitea PAT was pasted into a CD-watching curl command in a 2026-04-22
planning doc (c9310b10, last_eight 3105a670).

Verified dead before dispositioning it, rather than assuming: authenticating
GET /api/v1/user with that exact value returns 401. It was almost certainly
invalidated by the early-August rotation of the `mathias` PATs -- the same
rotation whose fan-out caused infra#260, where CI's stale copies kept
failing. So it was killed for unrelated reasons, by luck rather than by the
leak being noticed.

No rotation outstanding. `task security:gitleaks:history` now exits 0 here.

Used .gitleaksignore (per-finding fingerprint) rather than a path allowlist
in .gitleaks.toml: a path allowlist would also blind the working-tree scan
that gates commits. Verified both directions -- history 1 -> 0, working tree
still clean.
2026-08-29 10:04:11 +02:00
mathias d98a305985 security(hooks): add local pre-commit gitleaks scan (infra#326)
CI / Lint / Test / Vet (push) Successful in 1m33s
CI / Mirror to GitHub (push) Successful in 4s
task check -> security:gitleaks was already CI-enforced here, but that
catches a leak after the push, not before -- exactly the gap infra#39's
prevention checklist called out ("gitleaks pre-commit hook in both infra
and hyperguild"), true for infra but not this repo.

Mirrors infra's own .githooks/pre-commit, minus the YAML/image-tag
checks that are infra-manifest-specific and don't apply here.

Verified functionally, not just wired: staged a real high-entropy fake
key and confirmed `git commit` is blocked by the hook
(RuleID=generic-api-key); staged a well-known documented-example AWS
key (AKIAIOSFODNN7EXAMPLE) first and confirmed gitleaks correctly
passes it (it's not a real leak, and gitleaks' own default rules know
that) -- worth recording since a naive fixture check would have looked
like detection was broken.

Enable per clone: git config core.hooksPath .githooks
2026-08-28 23:58:05 +02:00
mathiasandClaude Opus 5 670325e519 ci(deploy): refuse to patch a manifest with an empty IMAGE_TAG (infra#311)
CI / Lint / Test / Vet (push) Successful in 39s
CI / Mirror to GitHub (push) Successful in 4s
On 2026-08-25 a deploy job ran with an empty IMAGE_TAG, wrote
`image: localhost:5000/gitea-mcp:` into the infra repo and pushed it.
That is invalid YAML, so Flux failed the ENTIRE apps Kustomization --
every app stopped reconciling for about an hour, including three
unrelated deploys queued behind it.

This job's existing check could not catch it. It greps for
`image: <repo>:${IMAGE_TAG}` after the sed, and with IMAGE_TAG empty that
pattern matches the corrupted line itself, so the verification passes
because of the bug rather than despite it.

Asserting the input up front is the fix: an empty tag now fails the job
before anything is written, let alone committed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011PL5XcG68SvQqz3vGVbWbf
2026-08-25 17:25:25 +02:00
mathias 54237af7ad feat(brain): validate the claim-property envelope on write (brain#21) (#102)
CI / Lint / Test / Vet (push) Successful in 31s
CI / Mirror to GitHub (push) Skipped
First half of brain#21: half_life (volatile|seasonal|durable), applies
(local|homelab|universal), claim_provenance (asserted|inferred).

writeHallNote already passed unknown frontmatter keys through verbatim, so
preservation was free — a test now pins it so a refactor of the merge loop
cannot silently drop the fields. What was missing is validation, and it
fails closed: a value outside the enum is rejected (a lint skips what it
cannot parse, so the note would read as classified while nothing acts on
it); an envelope field without claim_provenance is rejected (a value a
model inferred must never be indistinguishable from one a human asserted,
or a single classifier pass launders guesses into apparent judgement
across the corpus); provenance alone is rejected too.

Validation runs before MkdirAll, so a rejected write leaves nothing behind.

The field is `applies`, not `scope`: scope: has been in use since brain#5
for glossary terms (homelab-core, project:<repo>), a disjoint value space
on the same key. The shipped schema keeps the name.

Notes with none of these fields are byte-identical to before. Bulk
backfill stays out of scope.

Schema documented in brain/CLAUDE.md via brain_edit_root, which produced
the hyperguild#97 audit record for the rewrite.

Refs brain#21, brain#19 (superseded), brain#5, hyperguild#97.

Co-authored-by: Mathias <mthbqv@gmail.com>
2026-08-22 08:58:34 +00:00
mathias b6ceccca26 docs: name brain-mcp and say where its code lives (#94) (#99)
CI / Lint / Test / Vet (push) Successful in 1m43s
CI / Mirror to GitHub (push) Skipped
A forge search for "brain-mcp" returned nothing for this repo: the description
mentioned neither the brain nor brain-mcp, and the README never used the string
or the hostname. Both appeared only in the generated CLAUDE.md/AGENTS.md. Since
#91 part 2 decided the code stays in ingestion, discoverability is answered by
naming.

Adds a "Where brain-mcp lives" section: the ingress, the package, a table
mapping what-you-are-looking-for to where-it-is (including that the brain
content is a separate repo), and why it is not standalone, with a pointer to
the ADR.

Also repoints the README's three forge links from the decommissioned
gitea.d-ma.be alias to git.d-ma.be. Dated files under docs/superpowers are
left alone — they record what was true when written.

Repo description and topics were set through the forge API, and NPM's
default-site was changed from congratulations to 404 so a retired hostname
reads as absent rather than as a moved repo.

Closes #94.

Co-authored-by: Mathias <mthbqv@gmail.com>
2026-08-22 06:10:06 +00:00
mathias 36a45068ab feat(mcp): record and alert on a governance-file rewrite (#97) (#98)
CI / Lint / Test / Vet (push) Successful in 1m23s
CI / Mirror to GitHub (push) Successful in 4s
brain_edit_root was gated but unobserved: on success it emitted a slog.Warn
and nothing else. That proves a rewrite was allowed, not that one happened —
and brain-sync commits it within 15 minutes authored `brain-sync`, so git
history cannot tell a CLAUDE.md rewrite apart from routine note traffic.

A successful brain_edit_root now emits an ntfy notification and an AuditEntry
through the same sink a capture already uses. notes.Result gains
PrevContentHash so both ends of the change are identifiable.

Path and hashes only in the notification body. Reserved at Internal, not
Confidential, because Confidential makes DegradingSink refuse to record while
loki is down rather than buffer. Observation is best-effort and never fails
the call; a failure to observe logs at ERROR.

Ordinary brain_edit on knowledge//wiki/ is deliberately not audited — git
history already carries the same before/after bytes with a diff.

Closes #97.

Co-authored-by: Mathias <mthbqv@gmail.com>
2026-08-22 06:09:53 +00:00
mathias 055af368cd feat(mcp): brain_read + brain_edit, contained to the sync source (brain#4) (#96)
CI / Lint / Test / Vet (push) Successful in 29s
CI / Mirror to GitHub (push) Skipped
brain_read returns a note verbatim; brain_edit is str_replace with an
exactly-once match, operating on the tree brain-sync commits from.

An adversarial design review before implementation changed three things:

1. Governance files are not in the model-facing tool. Brain content is
   ingested from the outside world and reaches a model's context, and that
   model would hold the editor — one poisoned page could rewrite the
   CLAUDE.md a .dispatch-allow agent later loads as instructions. And
   brain-sync merges with --strategy-option=ours, so the live tree beats a
   human's corrective push on the conflicting lines. CLAUDE.md now goes
   through brain_edit_root: de-surfaced from tools/list and gated on the
   local static principal. The scopes are disjoint — the privileged door
   has the smaller reach.

2. Reads needed the same allowlist, and brain_get already lacked it: it
   returned verbatim session transcripts under archive/ by path. A test
   proved the exposure live before the fix.

3. Canonicalise before allowlisting — knowledge/../.git/hooks/post-commit
   would otherwise reach a hook that brain-sync executes in a pod holding
   the Gitea push credentials.

Plus overlapping match counting, UTF-8 validation both ways, refusal while
git is mid-operation, flock with the read inside the lock, atomic
same-dir rename, and reindex only when frontmatter is touched.

Refs brain#4.

Co-authored-by: Mathias <mthbqv@gmail.com>
2026-08-18 18:14:05 +00:00
mathias eb9e3e69a9 fix(capture): name what escalated the classification in an I1 refusal (#91 part 1) (#95)
CI / Lint / Test / Vet (push) Successful in 31s
CI / Mirror to GitHub (push) Successful in 4s
The tickets array was never broken. Every ticket in the reported batch
targeted a client repo, and the I1 gate refuses a confidential capture
through a us-nexus origin at any length — reproduced live: length 1 and
20 both fine for an internal repo, length 1 refused for a client one.

What made it look like an array bug is that the refusal named neither the
offending target nor that a policy had said no, so with 20 tickets in
flight "the array is broken" was a reasonable conclusion. The refusal now
names the targets carrying the effective classification, and tells a
caller who declared confidential themselves exactly that.

Regression tests at length 1 and 20 pin the path that was already
correct; a third pins per-item partial success.

Closes #91 part 1.

Co-authored-by: Mathias <mthbqv@gmail.com>
2026-08-18 18:13:48 +00:00
mathias b7cf0efb9d chore: opt in to headless dispatch (dispatch#3)
CI / Lint / Test / Vet (push) Successful in 29s
CI / Mirror to GitHub (push) Successful in 4s
2026-08-18 06:05:18 +00:00
mathiasandClaude Opus 5 125c99bb46 fix(text): truncate on rune boundaries, not byte offsets (#93)
CI / Mirror to GitHub (push) Successful in 4s
CI / Lint / Test / Vet (push) Successful in 31s
Four call sites did `s[:limit] + "…"`. Both halves are byte operations:
len() counts bytes and a slice cuts bytes. On Swedish text — å ä ö are
two bytes, an em dash three — the cut lands mid-character and leaves an
orphaned lead byte, producing invalid UTF-8.

It failed loudly in exactly one place: wiki/index.md is written raw to
disk, where every strict decoder then rejects the whole file. The other
three (brain_context excerpts x2, brain_query excerpts) feed MCP
responses, where encoding/json silently substitutes U+FFFD — so those had
been quietly eating the last character of truncated excerpts, with no
error anywhere and nothing to notice.

textutil.Truncate counts runes and appends the marker only when content
was actually dropped; an ellipsis on complete text is a lie about the
content. The test is a property, not an example: it walks the limit
across every offset of a multi-byte string and asserts utf8.Valid at each
one, so a future off-by-one cannot pass by picking a lucky boundary.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BeAp5LTscnz2W7Ubt4eJ6m
2026-08-18 07:13:15 +02:00
mathiasandClaude Opus 5 3e537bd582 feat(brain): surface an aging review queue in brain_context (#82)
CI / Lint / Test / Vet (push) Successful in 30s
CI / Mirror to GitHub (push) Successful in 4s
brain_pending existed the whole time four real items sat unreviewed from
2026-04-23 to 2026-07-15. The tool was never the gap — nothing ever
prompted anyone to call it. The system should be what remembers the queue
exists.

Option 2 from the issue: ride along with brain_context, which sessions
already call, so noticing an aging note costs nobody a decision to go
looking. No scheduled job, no ntfy wiring, nothing new to keep running.

Threshold-gated at 14 days, and silent below it — a notice on every
context call is one people learn to skip, which reproduces the original
failure with extra steps. It reports the whole queue once it speaks: the
threshold decides whether to talk, not what to count.

It never promotes, rejects or reorders. Age is a reason to ask a human,
not a verdict; an old note may be exactly right to promote once someone
looks. A test asserts the queue is untouched and that the payload carries
a hint rather than an action.

An unreadable raw/ dir degrades to silence — brain_context is a hot path
and must not fail because the review queue is broken.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BeAp5LTscnz2W7Ubt4eJ6m
2026-08-18 00:37:48 +02:00
mathiasandClaude Opus 5 4e6fc7aeee chore(brain): de-surface brain_index from the model-facing toolset (#78)
CI / Lint / Test / Vet (push) Successful in 29s
CI / Mirror to GitHub (push) Successful in 4s
brain_index is auto-called after every write, and its own description
said so. A verb surfaced to callers that callers should never call is
cognitive load with no decision behind it — ADR-0012 rule 4.

Removed from tools/list only. The dispatch case stays, so maintenance
can still rebuild a Map of Content by hand: de-surfacing hides the verb,
not the operation. A test pins both halves, since removing the descriptor
and removing the capability look identical from the tool list.

Nothing called it directly — grepped the skills, specs and docs.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BeAp5LTscnz2W7Ubt4eJ6m
2026-08-18 00:31:06 +02:00
mathiasandClaude Opus 5 9a232ad444 fix(ingestion): retry OIDC discovery instead of exiting on cold-boot 502 (#83)
CI / Lint / Test / Vet (push) Successful in 36s
CI / Mirror to GitHub (push) Successful in 4s
On a cluster restart this pod can beat dex to serving, gets a 502 from
ingress, and exits — after connecting postgres, backfilling 794 graph
nodes and ingesting three session batches, all of which the restart
redoes. Nothing was misconfigured; it started first.

The validator now retries with bounded exponential backoff (8 attempts,
1s doubling to 30s) and is built immediately after ctx, before the
watcher and the backfill. That second part is the other half of the
issue: a genuine config error now fails in seconds rather than after all
that work.

Bounded on purpose. Retrying forever would convert a wrong issuer URL
into a process that looks alive and never serves, which is harder to
diagnose than a crash loop.

startupretry.Do is generic and tested directly: transient-then-success,
budget exhaustion surfacing the last error via errors.Is, prompt return
on context cancellation, growing-and-capped delays, and a zero-value
policy still making one attempt rather than silently succeeding.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BeAp5LTscnz2W7Ubt4eJ6m
2026-08-18 00:21:56 +02:00
mathiasandClaude Opus 5 3da0eca9b4 fix(ingestion): decide quoting with YAML itself, not a colon heuristic (#90)
CI / Lint / Test / Vet (push) Successful in 29s
CI / Mirror to GitHub (push) Successful in 4s
`title: "Foo" — bar` opens with a quote and is not quoted; the previous
prefix check read it as already-quoted and left two notes broken. Probing
the value as the right-hand side of a mapping answers the real question —
does this load as written — and leaves anything that already parses alone,
whatever it parses into.

Repairs the last two quotable files in mathias/brain. Only wiki/index.md
remains unparseable, for an unrelated reason: a truncated UTF-8 sequence.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BeAp5LTscnz2W7Ubt4eJ6m
2026-08-18 00:10:11 +02:00
mathiasandClaude Opus 5 7d1213451c chore: re-sync context adapters
CI / Lint / Test / Vet (push) Successful in 29s
CI / Mirror to GitHub (push) Successful in 3s
Root .context/AGENT.md gained the CAD sprint patterns section; the derived
adapters had not been regenerated since. Pure `task context:sync` output.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BeAp5LTscnz2W7Ubt4eJ6m
2026-08-18 00:08:07 +02:00
mathiasandClaude Opus 5 7c9293f4ed feat(ingestion): lint and repair unparseable note frontmatter (#90)
Hand-authored and promoted notes skip pipeline.BuildPages, so nothing
quotes their scalars. A title carrying an unescaped ": " yields a block
yaml.Unmarshal rejects, and every consumer that reads frontmatter drops
the note silently — 18 files repo-wide today, up from the 8 in #90.

frontmatter.Lint reports it; frontmatter.Fix quotes only what quoting can
rescue and refuses to return a document that still fails to parse, so an
unfixable file comes back byte-identical rather than half-repaired. Scan
walks a tree and reports an unreadable file as a finding instead of
aborting, so one poisoned note cannot hide the rest.

Sequence items are deliberately left alone: "- foo: bar" is valid YAML
that silently becomes a map, which is a type corruption rather than a
parse failure, and repairing it would rewrite notes that currently load.

    task lint:frontmatter          # report
    task lint:frontmatter FIX=1    # repair in place

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BeAp5LTscnz2W7Ubt4eJ6m
2026-08-18 00:07:27 +02:00
mathiasandClaude Sonnet 5 6e0155a2ab feat(security): add gitleaks pre-commit scan, wire into task check (infra#39)
CI / Lint / Test / Vet (push) Successful in 1m41s
CI / Mirror to GitHub (push) Successful in 5s
Ported from mathias/infra's .gitleaks.toml (2026-08-04) -- same
homelab bearer/MCP-token rules, plus a BRAIN_PG_DSN pattern for the
hyperguild#20 leak class. Triaged 10 initial findings: 9 were
claudewatcher's own scrubber test fixtures (deliberately fake), 1 was
gitleaks matching the literal placeholder word "REDACTED" in a plan
doc. Both allowlisted with rationale, clean scan confirmed before
wiring into `task check`.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016FQX4RwxyxuQY4yf4XaACL
2026-08-04 08:32:42 +02:00
mathiasandClaude Sonnet 5 1cea2c9f78 feat(capture): remove summary->ai-sessions write path
CI / Lint / Test / Vet (push) Successful in 29s
CI / Mirror to GitHub (push) Successful in 4s
ai-sessions#13: capture's `summary` field wrote a frontmatter shape
(title/harness/fidelity/captured_at/repos_touched) that ai-sessions'
own extract/audit pipeline can't parse -- silently invisible to that
repo's own audit tooling, and bypassing its redaction + Stage2
completeness gates by construction. Only 5 files ever landed this way
over 3 weeks; the summary capability's whole value (speed) fights
ai-sessions' whole value (redacted, audited, complete), so kill it
rather than build a second parse branch.

capture now persists insights -> brain and action items -> Gitea
tickets only. Removes Summary/SummaryResult/SummaryWriter and all
wiring (service, REST body, MCP tool schema); close-session updated to
stop assembling a summary payload. specs/capture-*.md kept as historical
record with a superseded note -- the feature shipped and is documented,
just no longer current behaviour.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WPdSHbp9Utb2hPFm9wDG59
2026-07-27 23:17:56 +02:00
mathiasandClaude Sonnet 5 9dcd60931a chore: retrigger CI after gitea-runner RBAC fix (round 6 of the CI/CD outage chain)
CI / Lint / Test / Vet (push) Successful in 30s
CI / Mirror to GitHub (push) Has been skipped
cd.yml's build+push+ssh chain fully worked last round (infra 707a3c0
landed via CD Bot). Final gap was RBAC: kubectl (new in baked-v6) had
no ServiceAccount permissions. Fixed in infra@949b333 (dedicated SA +
scoped Role/RoleBinding for flux-system + supervisor, verified live
via kubectl auth can-i before this retrigger). No code change here.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Roq1ajWKR5f1hG5Df9wC6A
2026-07-27 22:29:57 +02:00
mathiasandClaude Sonnet 5 1fac90ed2a fix(cd): pass git.d-ma.be SSH override as -o flags, not an appended ~/.ssh/config line
CI / Lint / Test / Vet (push) Successful in 29s
CI / Mirror to GitHub (push) Successful in 4s
cd.yml's own $HOME (/data) is a PVC that persists across job runs on
this runner. The previous fix (cb9c251) appended the corrected
HostName to ~/.ssh/config, but a stale 127.0.0.1:30022 entry from an
earlier failed run was already there — ssh_config is first-match-wins,
so the stale entry silently shadowed the fix and the very next run
failed identically. Cleaned the persisted stale entry on the runner
directly; this commit removes the append entirely so the step no
longer depends on file state surviving (or not surviving) between
runs — CLI -o overrides always win. Verified end-to-end against the
real infra repo from inside the runner pod (git ls-remote, correctly
reached gitea and got a clean auth rejection, not a connection error).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Roq1ajWKR5f1hG5Df9wC6A
2026-07-27 22:16:00 +02:00
mathiasandClaude Sonnet 5 cb9c2513a4 fix(cd): use in-cluster DNS for git.d-ma.be SSH, not 127.0.0.1:30022
CI / Lint / Test / Vet (push) Successful in 28s
CI / Mirror to GitHub (push) Successful in 4s
act_runner moved from koala's bare host network into a k3s pod
(2026-07-26); loopback inside that pod's own network namespace never
reaches the host, so the git.d-ma.be SSH override (used to push the
infra repo update) failed with "Connection refused". Verified
TCP+SSH-handshake reachability to gitea-ssh-nodeport.gitea.svc.cluster.local:22
from inside the actual runner pod before committing this.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Roq1ajWKR5f1hG5Df9wC6A
2026-07-27 22:09:52 +02:00
mathiasandClaude Sonnet 5 3617a6c386 chore: retrigger CI after gitea-runner baked-v6 (ssh/skopeo/buildctl/kubectl)
CI / Lint / Test / Vet (push) Successful in 28s
CI / Mirror to GitHub (push) Successful in 4s
check job passed clean on baked-v5; mirror job then exposed missing
ssh/ssh-keyscan. Fixed in infra@707a3c0, which also preemptively adds
skopeo/buildctl/kubectl for cd.yml's deploy job. No code change here —
retriggering for the full CI->CD end-to-end proof.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Roq1ajWKR5f1hG5Df9wC6A
2026-07-27 22:03:07 +02:00
mathiasandClaude Sonnet 5 1938170131 chore: retrigger CI after gitea-runner gcc/libc6-dev fix (baked-v5)
CI / Lint / Test / Vet (push) Successful in 1m12s
CI / Mirror to GitHub (push) Failing after 1s
Runner was missing gcc/libc6-dev too (-race requires cgo). Added in
infra@0f88aea. No code change here — retriggering CI.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Roq1ajWKR5f1hG5Df9wC6A
2026-07-27 21:55:20 +02:00
mathiasandClaude Sonnet 5 b34717e6b8 chore: retrigger CI after gitea-runner image fix (infra#task-baked-v4)
CI / Lint / Test / Vet (push) Failing after 34s
CI / Mirror to GitHub (push) Has been skipped
Runner was missing task (taskfile.dev), added in infra@686c90f. No
code change here — retriggering CI to confirm the fix.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Roq1ajWKR5f1hG5Df9wC6A
2026-07-27 21:49:33 +02:00
mathiasandClaude Sonnet 5 d8d7e9a307 chore(context): re-sync derived adapters (Python fallback stack, error-handling note)
CI / Lint / Test / Vet (push) Failing after 1s
CI / Mirror to GitHub (push) Has been skipped
Canonical ~/dev/.context/AGENT.md drifted (Python fallback stack table
row, Python error-handling convention) without a hyperguild commit
re-running task context:sync since — task check's drift gate has been
failing CI on every push since the sprint-1 commits landed, blocking
CD entirely (unrelated to those commits' own content: lint/test/vet
all pass clean, including -race).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Roq1ajWKR5f1hG5Df9wC6A
2026-07-27 15:18:38 +02:00
mathiasandClaude Sonnet 5 f0055483a3 fix(watcher): never re-ingest AutoTunnel's own tunnel-candidates log (#88)
CI / Lint / Test / Vet (push) Failing after 1s
CI / Mirror to GitHub (push) Has been skipped
Root cause was neither of the two mechanisms the issue named
(CanonicalizeLinks over-canonicalizing, or a schema/prompt bias) —
CanonicalizeLinks correctly resolved [[Mission]] because
wiki/concepts/mission.md genuinely exists; the extraction prompt has
no "mission" bias either. The real bug: watcher.processDir walks
brain/raw/ and feeds every .md/.txt/.pdf file to pipeline.Run as
source material to extract, with no exclusion for
tunnel-candidates-*.md — AutoTunnel's own fuzzy-match human-review
queue (logFuzzyCandidates writes it into that same raw/ directory).
The watcher's next poll re-ingested the raw candidate log itself, and
the LLM naturally surfaced "mission" as a wikilink because the log
literally lists `(term: "mission")` entries in its content — a
generic-word title match DetectTunnels correctly flagged as fuzzy
(not auto-tunneled) but which still leaked downstream once treated as
real source material.

api.ListPending already excludes tunnel-candidates-* when listing
raw/ for promotion; processDir gets the same exclusion.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Roq1ajWKR5f1hG5Df9wC6A
2026-07-27 14:37:50 +02:00
mathiasandClaude Sonnet 5 6d014c1d0f fix(ingest): CanonicalizeLinks strips wing:/wiki/ prefix and repairs path-style links (#87)
CI / Mirror to GitHub (push) Has been skipped
CI / Lint / Test / Vet (push) Failing after 2s
plainLinkRE matches any [[...]] without a pipe, including path-prefixed
forms like [[wing:homelab/failures/foo]] or [[wiki/agentsquad/decisions/bar]]
that the LLM extraction step occasionally emits. Title-lookup against
titleToSlug always fails for these (they're paths, not titles), so they
were silently left broken.

Before falling to the unknown-wikilink warning, strip a known wing:/wiki/
root prefix and emit the clean wing/hall/slug path directly — matching
the brain-graph path-style link convention.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Roq1ajWKR5f1hG5Df9wC6A
2026-07-27 14:32:31 +02:00
mathiasandClaude Sonnet 5 1001acfb44 fix(ingest): merge existing frontmatter in writeHallNote instead of stacking (#86)
CI / Lint / Test / Vet (push) Failing after 1s
CI / Mirror to GitHub (push) Has been skipped
opts.Content can already carry its own "---\n...\n---" block (e.g. from
an upstream extraction/promotion step). writeHallNote used to prepend a
second block unconditionally, making a standard frontmatter parser blind
to everything the first block declared (title, tags, ...).

splitFrontmatter now pulls the existing block's fields out first;
wing/hall/created_at are always fresh-injected, and type/domain/
source_type prefer the note's own existing value over the opts
fallback. Remaining existing fields are carried through verbatim into
the single merged block.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Roq1ajWKR5f1hG5Df9wC6A
2026-07-26 23:45:36 +02:00
mathiasandClaude Sonnet 5 6ad275b505 fix(ingest): thread source/author/published frontmatter through extraction (#85)
CI / Lint / Test / Vet (push) Failing after 1s
CI / Mirror to GitHub (push) Has been skipped
pipeline.Run parses source/author/published from the raw content's own
frontmatter and applies them deterministically to source-type RawPages
after LLM extraction — never relies on the LLM to copy them through.
buildFrontmatter now emits all three (source pages only) when present.

Backfill of the 46 already-affected wiki/sources/*.md notes is a
separate concern per the issue, not done here.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Roq1ajWKR5f1hG5Df9wC6A
2026-07-26 23:42:33 +02:00
mathiasandClaude Sonnet 5 b600cc986c chore(module): rename module github.com/mathiasbq/supervisor -> git.d-ma.be/mathias/hyperguild (#42)
CI / Lint / Test / Vet (push) Failing after 5s
CI / Mirror to GitHub (push) Has been skipped
Aligns module path with canonical Gitea source (infra ADR-0004) and
repo name. Binary only, no downstream consumers.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Roq1ajWKR5f1hG5Df9wC6A
2026-07-26 23:37:11 +02:00
mathiasandClaude Opus 4.8 9bdab1c48c fix(ingest): parse docmark's SSE-framed response, not bare JSON
CI / Lint / Test / Vet (push) Successful in 16s
CI / Mirror to GitHub (push) Has been skipped
Found via a real live-cluster end-to-end test (POST /ingest-path with a real
.docx against the deployed ingestion + docmark): 'decode docmark response:
invalid character e looking for beginning of value'. docmark's Streamable-HTTP
transport frames every response as SSE (event: message\r\ndata: {...}\r\n\r\n,
Content-Type: text/event-stream) -- stateless_http=True removes the need for
an initialize handshake/session ID, it does NOT change the wire framing to
bare JSON. My original client + its own test mock both assumed bare JSON,
so the unit tests passed while the real call failed.

sseDataPayload() extracts the data: line before JSON-unmarshaling; falls back
to the raw body if no SSE framing is present (forward-compatible). Test mock
(docmark_test.go) now emits the SAME framing the live server actually sends,
confirmed by directly probing docmark's live response before writing the fix.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 08:53:24 +02:00
mathiasandClaude Opus 4.8 6520c2fc4b feat(ingest): route DOCX/XLSX/PPTX/images through docmark (ADR-0013)
CI / Lint / Test / Vet (push) Successful in 16s
CI / Mirror to GitHub (push) Successful in 4s
Wires the sovereign docmark MCP server (git.d-ma.be/mathias/docmark) as the
converter for formats ingestion previously couldn't handle at all -- DOCX,
XLSX, PPTX, PNG/JPG. A single self-contained tools/call POST (docmark runs
stateless_http, no session handshake needed) does the conversion.

- internal/extract/docmark.go: extractViaDocmark(path) -- reads DOCMARK_URL +
  DOCMARK_BEARER_TOKEN from env, base64-encodes the file, calls docmark's
  convert_to_markdown tool, surfaces tool/HTTP errors with context.
- internal/extract/extract.go: routes .docx/.xlsx/.pptx/.png/.jpg/.jpeg to it.
- internal/api/handler.go: isSupportedExtension() replaces the static
  supportedExtensions map -- the new extensions are gated on DOCMARK_URL being
  set, checked per-request. When DOCMARK_URL is unset (e.g. this repo's
  current deployed state), behavior is byte-for-byte unchanged from today:
  same 400/silent-skip as before. Zero risk until the env var is actually
  wired in infra.

TDD throughout: docmark.go tested via httptest mock (success, not-configured,
tool-error, HTTP-error, all 6 new extensions route correctly); handler-level
test proves the DOCMARK_URL gate (docx 400 when unset, 200 when a working
mock is configured). Full task check green (fmt/vet/govulncheck/all tests).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 08:46:03 +02:00
mathiasandClaude Opus 4.8 fcbd1072b6 fix(lint): check fmt.Fprintf errors in webhook handler (infra#190)
CI / Lint / Test / Vet (push) Successful in 16s
CI / Mirror to GitHub (push) Has been skipped
errcheck flagged two unchecked fmt.Fprintf return values in
internal/webhook/webhook.go, failing CI (run 310/311) for the whole
'trigger brain-sync on Gitea push' feature -- so no new ingestion image was
ever built, and the deployed image predates this feature entirely even
though infra's manifest (secret, RBAC, env wiring) was already live.

Both writes are best-effort informational text after WriteHeader has already
committed the status code -- a failed write here only happens on client
disconnect and nothing depends on it succeeding, so explicitly discard
(_, _ =) rather than log-and-continue noise.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 08:29:39 +02:00
mathias 3b7706b358 chore(context): re-sync derived adapters (skills-source paragraph) 2026-07-09 08:28:54 +02:00
mathias 394a227877 feat(webhook): trigger brain-sync on Gitea push instead of 15-min poll
CI / Mirror to GitHub (push) Has been skipped
CI / Lint / Test / Vet (push) Failing after 8s
Adds POST /webhooks/brain-sync: verifies Gitea's HMAC-SHA256 signature,
checks the push is to mathias/brain main, then creates a one-off Job from
the existing brain-sync CronJob's template (same script the 15-min poll
already runs, just triggered on-demand). Off by default -- opt in via
GITEA_WEBHOOK_SECRET, since it needs Job-create RBAC in the "brain"
namespace a fresh deploy won't have.

10 new tests (internal/webhook), including a fake-clientset reactor to
simulate server-side GenerateName expansion, which the plain fake tracker
doesn't do on its own.

Needs (follow-up, infra repo): RBAC granting ingestion's ServiceAccount
get on cronjobs/brain-sync + create on jobs in the brain namespace, the
GITEA_WEBHOOK_SECRET env, and the actual Gitea webhook registration.
2026-07-07 22:00:56 +02:00
mathias 0f84ab5eda fix(ingest): route raw claude-session dumps to non-indexed archive, not wiki
CI / Lint / Test / Vet (push) Successful in 11s
CI / Mirror to GitHub (push) Has been skipped
claudeSink wrote every raw transcript into brain/wiki/claude-sessions/facts/
(BM25-indexed), duplicating what ai-sessions' curated summaries already
cover and out-ranking them in search (177,818 vs 45,335 BM25 weight on the
same query, per ai-sessions#10 investigation). Raw dumps now land in
brain/archive/claude-sessions/<host>/ — kept for deep lookups, never
indexed, never deleted.

Refs: ai-sessions#10
2026-07-07 11:36:01 +02:00
mathias 5b57843346 fix(lint): revert redundant Write conversion (staticcheck S1016)
CI / Lint / Test / Vet (push) Successful in 12s
CI / Mirror to GitHub (push) Successful in 3s
writeRequest and WriteNoteOptions have matching fields again now that
both carry SourceType, so the explicit field-by-field literal added
in ee1204d is flagged as a redundant conversion. Back to the plain
type conversion. Caught by task check (golangci-lint), not run
locally before the previous push -- plain go test passed, task check
(which adds -race and golangci-lint) didn't.
2026-07-04 14:13:16 +02:00
mathias ee1204d76b fix(api): default hall=facts source_type to internal (brain-gardener#7)
CI / Lint / Test / Vet (push) Failing after 5s
CI / Mirror to GitHub (push) Has been skipped
The unsourced-check fix (source_type: internal) only covered
claudewatcher's writes. 41 residual findings on the audit's next run
were manually-authored hall=facts entries written via brain_write/
capture -- also first-party observations, just a different write path,
with no way to mark them internal short of hand-editing every entry.

writeHallNote now defaults source_type to internal whenever hall ==
"facts" and the caller didn't set it explicitly. An explicit
source_type: external (now threaded through the /write HTTP endpoint)
opts a genuinely citation-needing entry back out.
2026-07-04 14:09:20 +02:00
mathias 6d58336ce2 fix(claudewatcher): tag session-dump notes source_type: internal
CI / Lint / Test / Vet (push) Successful in 12s
CI / Mirror to GitHub (push) Successful in 3s
brain-gardener#5: the audit's unsourced check was flagging 59 raw
claudewatcher session dumps as high-severity hallucination risk,
because it can't distinguish a first-party observation (a session
transcript) from an external claim needing citation.

Adds WriteNoteOptions.SourceType, emitted as source_type: <value> in
the wing/hall frontmatter route. claudeSink (the claudewatcher sink)
now always sets source_type: internal on the notes it writes.
2026-07-04 13:53:08 +02:00
mathias 0785f14220 Merge pull request 'Consolidate to single harness: icebox cmd/routing, keep cmd/hyperguild + ingestion (#75)' (#76) from feat/consolidate-single-harness into main
CI / Lint / Test / Vet (push) Successful in 12s
CI / Mirror to GitHub (push) Successful in 4s
2026-07-01 16:27:06 +00:00
mathiasandClaude Opus 4.8 a7db0dd00d feat(mode): brain+gitea in all modes; drop iceboxed routing entry (#75)
CI / Lint / Test / Vet (pull_request) Successful in 12s
CI / Mirror to GitHub (pull_request) Has been skipped
Step 7 of the consolidation: reflect gitea-mcp as an available connection
(Gitea-as-audit-trail is an invariant going forward) and stop emitting the
now-iceboxed routing pod.

- cmd/hyperguild mode.go: every mode (cloud/client-local/sovereign) now lists
  brain + gitea; removed the client-local `routing` entry (koala:30310, the
  iceboxed pod). Tests updated to the new contract.
- .mcp.json: add gitea-mcp (git-mcp.d-ma.be, Bearer ${GITEA_MCP_TOKEN}).
- cmd/hyperguild/README: modes doc updated (brain+gitea, no routing).

Refs #75.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 13:27:31 +02:00
mathiasandClaude Opus 4.8 fb59c390e2 refactor(harness): icebox cmd/routing path — consolidate to single harness (#75)
Consolidate to the hyperguild-alone harness that ran the infra#170 loop-1
experiment (cmd/hyperguild + brain-mcp; routing/injection machinery off).
Verified cmd/hyperguild has zero transitive dep on internal/routing or
cmd/routing's packages (imports only internal/tier). Removed the routing
path, which is dormant from the live session (.mcp.json wires only brain-mcp)
and entangled with the survivorship-biased pass-rate router (infra#174).

Iceboxed (recoverable at tag icebox/cmd-routing-2026-07-01 / branch
icebox/cmd-routing, commit 00e5f62):
- cmd/routing/, internal/routing/
- internal/skills/{review,debug,retrospective,trainer,project}/
  (each imported solely by cmd/routing — verified)
- Dockerfile.routing
- cd.yml: routing image build + infra bump + Flux-wait/rollout-verify
  (ingestion build/deploy unchanged)

Kept: cmd/hyperguild, ingestion/, internal/tier (used by cmd/hyperguild +
skills/org), internal/skills/{brain,org,sessionlog} (per #75; already orphaned).

Regression: root module 21→14 pkgs (−7 = exactly the removed set, no other
breakage); ingestion 24/24 unchanged. See ICEBOX.md. Refs #75, infra#170, #174.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 13:22:26 +02:00
171 changed files with 8958 additions and 4266 deletions
+23
View File
@@ -7,6 +7,29 @@
"supervisor": { "supervisor": {
"url": "http://localhost:3200/mcp", "url": "http://localhost:3200/mcp",
"description": "Hyperguild SDO — skill workers (tdd, retrospective), brain tools (brain_query, brain_write), session logging, tier detection" "description": "Hyperguild SDO — skill workers (tdd, retrospective), brain tools (brain_query, brain_write), session logging, tier detection"
},
"brain": {
"type": "http",
"url": "https://koala.tail30472e.ts.net:8443/mcp",
"headers": {
"Authorization": "Bearer ${BRAIN_MCP_TOKEN}"
}
},
"gitea": {
"_comment": "gitea-mcp authenticates by PASS-THROUGH: the bearer is a Gitea PAT it validates against Gitea and then acts as. GITEA_MCP_TOKEN -- which this entry used until 2026-09-08 -- 401s against it, so every harness synced from this file had a dead gitea server and no signal saying so. Probed 2026-09-08: GITEA_MCP_TOKEN 401, DMABE_GITEA_API_TOKEN 200, on both the public and the Serve URL.",
"type": "http",
"url": "https://koala.tail30472e.ts.net:8446/mcp",
"headers": {
"Authorization": "Bearer ${DMABE_GITEA_API_TOKEN}"
}
},
"infra": {
"_comment": "The bearer is belt-and-braces: this endpoint answers 200 with or without it, since Serve already limits reach to the tailnet. Sending it anyway means the day the server starts enforcing is not the day every harness breaks.",
"type": "http",
"url": "https://koala.tail30472e.ts.net:8444/mcp",
"headers": {
"Authorization": "Bearer ${INFRA_MCP_TOKEN}"
}
} }
} }
} }
+162 -23
View File
@@ -53,14 +53,51 @@ These rules apply to every task across every project, regardless of harness.
logical change (one tool, one fix, one test) with passing tests. Main is always logical change (one tool, one fix, one test) with passing tests. Main is always
deployable. Never create long-lived feature branches. deployable. Never create long-lived feature branches.
**Exception — parallel agents on same repo:** If another agent is known to be **The PR trigger is RISK, not concurrency.** `risk/low` work commits straight to
actively working on the same repo simultaneously, create a short-lived branch main with CI as the gate — that is most work and is unchanged. `risk/medium` and
(`agent/<description>`), finish the task, and merge to main within the same above opens a PR, even solo, even with nobody waiting to review it. This mirrors
session. Do not leave agent branches open between sessions. the tiered merge model in `assessor-loop`
`method/transfer-to-a-regulated-organisation.md` §4.1, so the estate practises
what it sells instead of merging everything on green and claiming otherwise.
**Exception — external contributor or client four-eyes requirement:** Use **Concurrency is NOT a reason to branch.** Measured 2026-08-29 across three real
PR flow only when a human reviewer outside the project is required. Document collisions between parallel sessions: two were not branching problems at all — a
the reason in PROJECT.md. generated artifact written to the same path by both (branching turns that into a
merge conflict on a 33k-line JSON), and uncommitted work in a shared checkout
(a per-session worktree fixes it) — and the third was an ordinary non-fast-forward
push resolved by rebase in seconds. Use a worktree per session on shared repos and
timestamp generated artifacts. Do not reach for a branch.
Branch+PR flow carries documented costs on solo repos: merging auto-closes gated
issues, review comments live on a thread separate from the issue's, and a
merged-and-deleted branch cannot be amended (brain:
`gitea-pr-merge-autoclose-and-review-comment-footguns`). Those are the price of
the `risk/medium`+ lane — paid deliberately, not incurred by accident.
**Exception — external contributor or client four-eyes requirement:** Use PR flow
when a human reviewer outside the project is required. Document the reason in
PROJECT.md.
**Exception — a GitOps repo where a branch cannot be reconciled.** In a repo whose
deployment watches one branch (`mathias/infra`: Flux watches `main`), a branch is
invisible to the thing that applies it. A `risk/medium` change to `alerts.yaml` or
`litellm-config.yaml` can be linted on a branch but never *exercised* there, so a
PR would buy a review of a state that was never deployed.
There, `risk/medium`+ work stays on `main` and instead requires a **recorded
adversarial review pass before the push** — `skills:pr-gatekeeper` or equivalent,
reviewing the staged diff. **The reviewer's verdict goes in the issue, not a PR
thread.** No verdict recorded means the lane was not used, and saying "the gate was
green" is not the same claim.
Be honest about what this is: a recorded *independent* pass, not four-eyes in the
sense `assessor-loop` §4.1 means for a regulated organisation, because the reviewer
is an agent. It is more than the repo had and less than the model it mirrors; do not
describe it as the stronger property. (infra#470, decided 2026-09-29.)
This lane depends on the `risk/` label being right. A label that triggers a heavier
lane is load-bearing, not cosmetic — if work that belongs in it is unlabelled, the
lane silently does not apply.
6. **Close the loop — every substantive task ends with the same ritual.** Shipping 6. **Close the loop — every substantive task ends with the same ritual.** Shipping
the code is not the end of the task; capturing it is. Run this unprompted: the code is not the end of the task; capturing it is. Run this unprompted:
@@ -78,6 +115,63 @@ These rules apply to every task across every project, regardless of harness.
- Surface the brain entries and issue numbers in the closing summary so the - Surface the brain entries and issue numbers in the closing summary so the
trail is auditable. trail is auditable.
**Chat is not a durable store. Never rely on Mathias remembering anything.**
Every gap, caveat, risk, open question and next step must land in one of four
places before the turn ends: **the brain**, **a repo** (code, docs, ADR),
**a tracker issue**, or **a plan file**. A finding stated only in conversation is
lost the moment the session closes — and this estate has repeatedly proved that a
remembered convention is an unreliable control.
This applies hardest to what is tempting to leave as a closing remark: "worth
knowing X isn't enforced yet", "this is a convention, not a gate", "we should
revisit Y". Those are exactly the items that need a locator. If it is worth
saying in a summary, it is worth writing where it can be found again without you.
7. **Finish what's closable — only involve me for a genuine call.** If a
tracker issue, PR, or checklist item is demonstrably resolved — the fix
landed, the state changed, you verified it live — close/merge/check it off
in the same turn. Don't leave it open "for the record" or park it waiting
on me to confirm something that already happened; that's bookkeeping, not
a decision. Reserve asking me (`AskUserQuestion`, a `DECISION NEEDED`
comment, or otherwise pausing) for when it's genuinely mine to call:
irreversible or prod/host-impacting actions, a real judgment call with no
clearly-better option, ambiguous intent, or anything secret-writes/
destructive-git already gate. Before claiming something is closable,
verify it live (re-check the issue, re-run the command) rather than
trusting your own earlier summary (brain: `filed-issue-not-same-as-fixed`).
8. **Control code needs an adversary, not a checklist.** Code whose job is to
refuse, deny, gate or contain is not adequately verified by a green gate.
Rule 5 makes CI the quality gate and that holds for ordinary work — but a
passing suite only asserts what its author already thought of, and for a
control the author is precisely the person whose imagination just failed.
Measured on `dispatch#75`: five review rounds, five real escapes verified by
execution, and **CI was green on every one of them** while `git rm
././.dispatch-allow` deleted the file the control existed to protect. So
route this work through a review with authority to block, instructed to
verify by execution rather than by reading the implementation. Expect to be
blocked more than once; that is the control working, not the reviewer being
difficult. (brain: `a-green-gate-is-not-evidence-for-control-code`; the
practices live in the `pr-gatekeeper` agent.)
9. **A test's name must not claim more than its assertions prove.** Name a test
after the mechanism it observes, not the goal it serves.
`DoesNotInheritEnv` is honest; `IsContained` is a claim the test cannot
support. This is not pedantry about naming — when name and assertion
diverge, the name wins in the reader's head and the gap becomes invisible,
which is what lets the defect survive review. Found three times in one PR,
twice in tests written to fix the previous instance of it; each passed while
the thing it was named for was exploitable. If you cannot name the mechanism,
you do not yet know what the test observes.
## CAD sprint patterns
Two CAD sprint archetypes (defs: brain `wiki/homelab/decisions/continuous-agentic-development-cad-concept-2026-06-16`):
- **Inception Sprint** — birth a new repo. Oath-gated close; tag only once every clause holds. Brain: `.../inception-sprint-and-oath`.
- **Sweep Sprint** — clear an existing backlog. Parallel read-only research per issue → sequential one-issue-per-commit execution. Brain: `.../sweep-sprint-and-oath`.
Shared: decisions that are yours, not the agent's, surface as `DECISION NEEDED` (question/options/recommendation/blocks) — ask live if you're present, else comment and wait, never act past it. Live-breaking regressions get `git revert`, never forward-fixed; host-network work skips even read-only research (solo, synchronous, you present). Rule 6's closing ritual only fires once every Oath clause genuinely holds — blocked = descoped-and-tracked, never marked done.
## Default stack ## Default stack
| Layer | Default | Fallback | Last resort | | Layer | Default | Fallback | Last resort |
@@ -88,7 +182,7 @@ These rules apply to every task across every project, regardless of harness.
| Containers | Docker Compose (dev), k3s (prod) | — | — | | Containers | Docker Compose (dev), k3s (prod) | — | — |
| DB | PostgreSQL + sqlc | SQLite | — | | DB | PostgreSQL + sqlc | SQLite | — |
| Search | pgvector (vector), BM25 | Qdrant (when >1M vectors or hybrid retrieval) | — | | Search | pgvector (vector), BM25 | Qdrant (when >1M vectors or hybrid retrieval) | — |
| Logging | slog (structured) | — | — | | Logging | slog (structured) | stdlib `logging` w/ structured `extra=` (or structlog) | — |
| Testing | Table-driven, testify | — | — | | Testing | Table-driven, testify | — | — |
| Agents (Go) | google.golang.org/adk + pkg/litellm adapter | — | — | | Agents (Go) | google.golang.org/adk + pkg/litellm adapter | — | — |
@@ -97,7 +191,12 @@ Exploratory: Rust, Zig — I'll tell you when I want these.
## Code conventions ## Code conventions
- **Go style**: golines, gofumpt, golangci-lint - **Go style**: golines, gofumpt, golangci-lint
- **Errors**: `fmt.Errorf("operation: %w", err)` — never naked, never log-and-return - **Python style** (fallback language): ruff (format+lint, one tool), mypy --strict (non-negotiable,
matches Go's static typing discipline), pytest + pytest-cov (table-driven via
`@pytest.mark.parametrize`), uv (venv+deps+lock, one tool), pydantic-settings (typed env-var config
— same principle as Go's typed structs), src-layout + `pyproject.toml` only (no `setup.py`)
- **Errors**: `fmt.Errorf("operation: %w", err)` — never naked, never log-and-return.
Python: `raise X from e` (exception chaining, same principle) — never bare `except`, never silent `pass`
- **Naming**: stdlib conventions, no stuttering - **Naming**: stdlib conventions, no stuttering
- **Architecture**: prefer stdlib over frameworks, constructor injection, env-var config parsed into typed structs - **Architecture**: prefer stdlib over frameworks, constructor injection, env-var config parsed into typed structs
- **Git**: conventional commits (`feat:`, `fix:`, `chore:`), commit directly to main, - **Git**: conventional commits (`feat:`, `fix:`, `chore:`), commit directly to main,
@@ -135,10 +234,10 @@ Three machines on Tailscale:
|---------|------|-----------| |---------|------|-----------|
| koala | GPU inference, heavy compute | RTX 5070, runs k3s + llama-swap + shared postgres18/pgvector | | koala | GPU inference, heavy compute | RTX 5070, runs k3s + llama-swap + shared postgres18/pgvector |
| iguana | Services, builds | M2 Ultra Mac | | iguana | Services, builds | M2 Ultra Mac |
| flamingo | Daily driver, edge | Mac mini, ~/dev is here | | flamingo | Daily driver, edge | Apple Silicon Mac, ~/dev is here |
- **Model routing**: LiteLLM in front of llama-swap (local) + cloud APIs (when permitted) - **Model routing**: LiteLLM in front of llama-swap (local) + cloud APIs (when permitted)
- **Orchestration**: k3s cluster across all three machines - **Orchestration**: k3s on koala only — single control-plane node, no workers (verified 2026-08-30). iguana and flamingo are on the tailnet but are not cluster members
- **Networking**: Tailscale mesh - **Networking**: Tailscale mesh
## Project landscape ## Project landscape
@@ -234,10 +333,11 @@ When working on a project tagged with a client name:
## Harness-agnostic principles ## Harness-agnostic principles
This context is designed to work with any AI coding tool: Supported harnesses (2026-09-01) — Cursor and Aider were dropped; do not
- Claude Code, Cursor, Aider, Open WebUI, Charmbracelet Mods/Crush re-add adapters for them:
- Pi Coding Agent, Mistral Vibe, Antigravity - Claude Code, Antigravity, OpenCode, Mistral Vibe, Crush, Pi Coding Agent
- Any tool that accepts a system prompt or reads a markdown context file - Open WebUI, Charmbracelet Mods, or any tool that takes a system prompt string
- Any other tool that reads `AGENTS.md`, which is the de facto convention
The canonical source is always `.context/AGENT.md` (root) and `.context/PROJECT.md` (per-project). The canonical source is always `.context/AGENT.md` (root) and `.context/PROJECT.md` (per-project).
Derived files are committed (see *How context propagates* below) so a `git pull` on any host yields full agent context with no setup. Derived files are committed (see *How context propagates* below) so a `git pull` on any host yields full agent context with no setup.
@@ -249,26 +349,65 @@ Canonical sources of truth:
- Project: `<repo>/.context/PROJECT.md` (per-repo) - Project: `<repo>/.context/PROJECT.md` (per-repo)
Derived files (committed, regenerated by `task context:sync`): Derived files (committed, regenerated by `task context:sync`):
- `CLAUDE.md`, `AGENTS.md`, `.cursorrules`, `.aider.conventions.md`, - `CLAUDE.md`, `AGENTS.md`, `.context/system-prompt.txt`
`.context/system-prompt.txt`
Repos still carrying `.cursorrules`, `.aider.conventions.md` or
`.aider.conf.yml` are stale: nothing regenerates them. Delete them the next time
you touch the repo, along with their entries in that repo's `task check`
assertion.
Workflow: Workflow:
1. Edit a canonical file. Run `task context:sync`. Commit canonical and 1. Edit a canonical file. Run `task context:sync`. Commit canonical and
derived together. Push. derived together. Push.
2. On any other host, `git pull` brings both. Claude Code (tree-walking) 2. On any other host, `git pull` brings both. Which file a harness reads does
uses `CLAUDE.md`; Crush / Pi / Antigravity (cwd-only) use `AGENTS.md`; NOT split cleanly by lookup strategy, so do not reason from the strategy:
Cursor uses `.cursorrules`; Aider uses `.aider.conventions.md`. - `CLAUDE.md` — Claude Code (walks up the tree)
- `AGENTS.md` — Crush, Pi, Antigravity (cwd-only), OpenCode (project root,
global at `~/.config/opencode/AGENTS.md`), and Mistral Vibe, which **walks
up** from cwd and takes the first `AGENTS.md` it finds
(user-level `~/.vibe/AGENTS.md`)
- `.context/system-prompt.txt` — Open WebUI, Mods, raw API calls; not read by
any harness, it is for pasting
Vibe tree-walks for `AGENTS.md`, so "tree-walkers use CLAUDE.md" is false.
Each repo's `AGENTS.md` embeds the canonical and is the first one found from
inside that repo, so this works — but by construction, not by luck.
3. `task check` runs `context:sync` then asserts `git status --porcelain` 3. `task check` runs `context:sync` then asserts `git status --porcelain`
is empty over the derived files (catches both modified-tracked drift is empty over the derived files (catches both modified-tracked drift
and missing-untracked adapters). A drift fails the check with a and missing-untracked adapters). A drift fails the check with a
message telling you to stage the regenerated files. message telling you to stage the regenerated files.
Behavior rules in this file and per-project rules in `PROJECT.md` apply Behavior rules in this file and per-project rules in `PROJECT.md` apply on every
unconditionally on every host, every harness. host and every harness.
**Where a project rule contradicts a rule here, the project rule governs — and it
must state its reason.** Both halves matter: the project file wins because it knows
something this file cannot (infra's Flux constraint is real and not visible from
here), and it must say why because a bare override is indistinguishable from drift.
This replaces the previous wording, which said rules here and in `PROJECT.md` both
apply *"unconditionally"*. That was not a tiebreak but a contradiction, and it went
unnoticed until rule 5 and infra's "never create feature branches" had to be obeyed
at the same time (infra#470). A standard can hold two individually sensible clauses
that are jointly unsatisfiable, and survive for as long as everyone reads it
charitably — the same failure the Inception Sprint Oath's G6 had.
## Engineering Skills ## Engineering Skills
Shared engineering skills are available in `~/dev/.skills/`. Load at task start — not "on demand" but on schedule, before writing code. See `~/dev/.skills/SKILLS_INDEX.md` for the full list. Shared engineering skills live in the **`mathias/skills`** repo (`git.d-ma.be/mathias/skills`). Load at task start — not "on demand" but on schedule, before writing code. Browse `SKILLS_INDEX.md` for the full list.
**Claude Code** installs the repo as a plugin from the marketplace the same repo hosts. That path also carries the `secret-guard` and `pre-task-ritual` hooks and the brain/gitea/infra MCP servers, which symlinks cannot:
```
/plugin marketplace add https://git.d-ma.be/mathias/skills.git
/plugin install skills@mathias
```
Skills are **namespaced** under Claude Code: load `tdd` as `skills:tdd`. The trigger table below uses bare names — prefix them.
**Crush, Pi and OpenCode** have no plugin system and are wired by `install.sh` as one directory symlink per harness via `~/.agents/skills`. Do not clone the checkout into `~/dev`: that folder is iCloud-shared between the Macs and spans two path roots (`/Users/mathias` vs `/home/mathias` on koala), so a checkout there is a git working tree with two concurrent writers, and any absolute symlink stored in it is broken on one side by construction (skills#23). Leave `SKILLS_CHECKOUT_DIR` at its host-local default.
Check a host with `task doctor` in the skills repo; it also runs automatically at session start via the plugin.
**Skill trigger table — load before starting, not after getting stuck:** **Skill trigger table — load before starting, not after getting stuck:**
+2
View File
@@ -0,0 +1,2 @@
# Presence of this file marks this repo as opt-in for headless dispatch.
# See dispatch#3.
-1
View File
@@ -1,7 +1,6 @@
# Supervisor MCP server # Supervisor MCP server
SUPERVISOR_PORT=3200 SUPERVISOR_PORT=3200
SUPERVISOR_CONFIG_DIR=./config/supervisor SUPERVISOR_CONFIG_DIR=./config/supervisor
SUPERVISOR_MODELS_FILE=./config/models.yaml
# LiteLLM gateway (iguana) # LiteLLM gateway (iguana)
LITELLM_BASE_URL=http://iguana:4000 LITELLM_BASE_URL=http://iguana:4000
+37 -68
View File
@@ -14,7 +14,6 @@ jobs:
environment: staging environment: staging
env: env:
INGESTION_IMAGE: git.d-ma.be/mathias/ingestion INGESTION_IMAGE: git.d-ma.be/mathias/ingestion
ROUTING_IMAGE: git.d-ma.be/mathias/routing
INFRA_REPO: git@git.d-ma.be:mathias/infra.git INFRA_REPO: git@git.d-ma.be:mathias/infra.git
BUILDKIT_HOST: unix:///run/buildkit/buildkitd.sock BUILDKIT_HOST: unix:///run/buildkit/buildkitd.sock
steps: steps:
@@ -41,39 +40,37 @@ jobs:
echo "Built and pushed ${INGESTION_IMAGE}:${IMAGE_TAG}" echo "Built and pushed ${INGESTION_IMAGE}:${IMAGE_TAG}"
- name: Build and push routing image
run: |
set -e
trap 'rm -f /tmp/routing-image.tar' EXIT
IMAGE_TAG="${{ github.sha }}"
echo "Building ${ROUTING_IMAGE}:${IMAGE_TAG}"
buildctl --addr "${BUILDKIT_HOST}" build \
--frontend dockerfile.v0 \
--local context=. \
--local dockerfile=. \
--opt filename=Dockerfile.routing \
--opt build-arg:VERSION="${IMAGE_TAG}" \
--output type=oci,dest=/tmp/routing-image.tar
skopeo copy \
oci-archive:/tmp/routing-image.tar \
docker://${ROUTING_IMAGE}:${IMAGE_TAG} \
--dest-creds "${{ secrets.REGISTRY_CREDS }}"
echo "Built and pushed ${ROUTING_IMAGE}:${IMAGE_TAG}"
- name: Update infra repo - name: Update infra repo
run: | run: |
set -e set -e
trap 'rm -rf /tmp/infra-update; rm -f ~/.ssh/infra_deploy_key' EXIT trap 'rm -rf /tmp/infra-update; rm -f ~/.ssh/infra_deploy_key' EXIT
IMAGE_TAG="${{ github.sha }}" IMAGE_TAG="${{ github.sha }}"
# infra#311: github.sha is never empty in practice, but the manifest
# patch below is the same shape that took Flux down estate-wide on
# 2026-08-25 -- an empty tag yields `image: <repo>:`, which is invalid
# YAML and fails the ENTIRE Kustomization, not just this app. The
# assert costs nothing and removes the class.
[ -n "${IMAGE_TAG:-}" ] || { echo "IMAGE_TAG is empty - refusing to patch"; exit 1; }
mkdir -p ~/.ssh mkdir -p ~/.ssh
echo "${{ secrets.INFRA_DEPLOY_KEY }}" > ~/.ssh/infra_deploy_key echo "${{ secrets.INFRA_DEPLOY_KEY }}" > ~/.ssh/infra_deploy_key
chmod 600 ~/.ssh/infra_deploy_key chmod 600 ~/.ssh/infra_deploy_key
printf 'Host git.d-ma.be\n HostName 127.0.0.1\n Port 30022\n StrictHostKeyChecking no\n' >> ~/.ssh/config # In-cluster DNS to gitea's SSH NodePort service, not 127.0.0.1:30022
# (that only worked when act_runner ran on koala's bare host network;
GIT_SSH_COMMAND="ssh -i ~/.ssh/infra_deploy_key -o IdentitiesOnly=yes" \ # from inside the containerized runner's own pod netns, loopback
# never reaches the host — "Connection refused", found 2026-07-27).
#
# Pass as -o overrides on the ssh invocation itself, NOT appended to
# ~/.ssh/config: $HOME (/data) is a PVC that persists across job
# runs on this runner (same "workspace not ephemeral" class as
# brain: act-runner-host-executor-tmp-persists), so an appended
# line here would pile up duplicate `Host git.d-ma.be` blocks
# across every run — ssh_config is first-match-wins, so a stale
# entry from an earlier failed run would silently shadow this
# fix forever (exactly what happened once already: this fix's
# own first attempt got appended AFTER an already-stale entry
# and lost). CLI -o options always win regardless of file state,
# so this step is safe to re-run any number of times.
GIT_SSH_COMMAND="ssh -i ~/.ssh/infra_deploy_key -o IdentitiesOnly=yes -o HostName=gitea-ssh-nodeport.gitea.svc.cluster.local -o Port=22 -o StrictHostKeyChecking=no" \
git clone "${INFRA_REPO}" /tmp/infra-update git clone "${INFRA_REPO}" /tmp/infra-update
cd /tmp/infra-update cd /tmp/infra-update
@@ -81,18 +78,22 @@ jobs:
sed -i "s|git.d-ma.be/mathias/ingestion:.*|git.d-ma.be/mathias/ingestion:${IMAGE_TAG}|" \ sed -i "s|git.d-ma.be/mathias/ingestion:.*|git.d-ma.be/mathias/ingestion:${IMAGE_TAG}|" \
"k3s/apps/supervisor/ingestion-deployment.yaml" "k3s/apps/supervisor/ingestion-deployment.yaml"
sed -i "s|git.d-ma.be/mathias/routing:.*|git.d-ma.be/mathias/routing:${IMAGE_TAG}|" \
"k3s/apps/routing/deployment.yaml"
git config user.email "cd-bot@d-ma.be" git config user.email "cd-bot@d-ma.be"
git config user.name "CD Bot" git config user.name "CD Bot"
git add "k3s/apps/supervisor/ingestion-deployment.yaml" \ git add "k3s/apps/supervisor/ingestion-deployment.yaml"
"k3s/apps/routing/deployment.yaml" # Idempotent: `git commit` exits 1 on an empty index, so a run that
git commit -m "chore(deploy): ingestion+routing → ${IMAGE_TAG}" # finds the bump already applied failed the whole job and rang the
GIT_SSH_COMMAND="ssh -i ~/.ssh/infra_deploy_key -o IdentitiesOnly=yes" \ # CI-red alarm for a deploy that was fine (hyperguild#118). Two
git push # sources of a no-op run: a manual re-run, and the tag-push CI run
# that used to shadow the branch-push one for the same sha.
echo "Infra repo updated: ingestion+routing → ${IMAGE_TAG}" if git diff --cached --quiet; then
echo "Infra already at ${IMAGE_TAG} — nothing to commit"
else
git commit -m "chore(deploy): ingestion → ${IMAGE_TAG}"
GIT_SSH_COMMAND="ssh -i ~/.ssh/infra_deploy_key -o IdentitiesOnly=yes" \
git push
echo "Infra repo updated: ingestion → ${IMAGE_TAG}"
fi
- name: Trigger Flux reconcile (immediate) - name: Trigger Flux reconcile (immediate)
run: | run: |
@@ -132,35 +133,3 @@ jobs:
kubectl describe pods -n supervisor -l app=ingestion | tail -40 kubectl describe pods -n supervisor -l app=ingestion | tail -40
exit 1 exit 1
} }
- name: Wait for Flux to apply new routing image
run: |
EXPECTED="git.d-ma.be/mathias/routing:${{ github.sha }}"
for i in $(seq 1 60); do
CURRENT=$(kubectl get deploy routing -n routing \
-o jsonpath='{.spec.template.spec.containers[0].image}' 2>/dev/null || echo "")
if [ "$CURRENT" = "$EXPECTED" ]; then
echo "✓ Flux applied routing image after ${i}s"
break
fi
sleep 1
done
kubectl get deploy routing -n routing \
-o jsonpath='{.spec.template.spec.containers[0].image}' \
| grep -qx "$EXPECTED" \
|| { echo "✗ Flux did not apply routing image within 60s"; exit 1; }
- name: Verify routing rollout
run: |
kubectl rollout status deployment/routing \
--namespace routing \
--timeout=120s \
|| {
echo "── pod status ──"
kubectl get pods -n routing -o wide
echo "── events ──"
kubectl get events -n routing --sort-by='.lastTimestamp' | tail -20
echo "── describe ──"
kubectl describe pods -n routing -l app=routing | tail -40
exit 1
}
+6 -1
View File
@@ -2,8 +2,13 @@ name: CI
"on": "on":
push: push:
# Branch only. A `v*` tag here points at a commit main already tested, so
# the tag push re-ran the whole gate and — because cd.yml keys off "CI
# succeeded" — triggered a SECOND full image build and deploy for the same
# sha. That second deploy then died on "nothing to commit" (hyperguild#118).
# Nothing consumes a tag-triggered run: there is no release workflow, and
# cd.yml reads github.sha, not the tag.
branches: [main] branches: [main]
tags: ["v*"]
pull_request: pull_request:
branches: [main] branches: [main]
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env bash
# Pre-commit secret scan for the hyperguild repo.
#
# task check -> security:gitleaks enforces this in CI, but CI is after the
# push. This catches a staged secret before it ever leaves the machine --
# the infra#39 rotation pass found exactly this class of leak (a printed
# credential, committed, archived into git) and there was no local gate to
# have caught it. Mirrors infra's own .githooks/pre-commit (infra#326).
#
# Enable once per clone: git config core.hooksPath .githooks
# Bypass if absolutely needed: git commit --no-verify
set -euo pipefail
GITLEAKS="$(command -v gitleaks || true)"
if [[ -z "$GITLEAKS" && -x "$(go env GOPATH 2>/dev/null)/bin/gitleaks" ]]; then
GITLEAKS="$(go env GOPATH)/bin/gitleaks"
fi
if [[ -z "$GITLEAKS" ]]; then
echo "⚠ gitleaks not installed — skipping local secret scan (CI still enforces it)."
echo " Install: go install github.com/zricethezav/gitleaks/v8@latest"
exit 0
fi
echo "→ Scanning staged changes for secrets..."
if ! "$GITLEAKS" protect --staged --redact --config .gitleaks.toml >/dev/null 2>&1; then
echo " ✗ gitleaks found a secret in the staged changes."
echo " Review with: gitleaks protect --staged --redact --config .gitleaks.toml -v"
echo " If it is a false positive, allowlist it in .gitleaks.toml or add a"
echo " '# gitleaks:allow' comment. Do NOT --no-verify a real secret."
exit 1
fi
echo " ✓ no staged secrets"
+71
View File
@@ -0,0 +1,71 @@
# gitleaks config for the hyperguild repo (infra#39 — leak prevention pass,
# Phase 3 checklist item: "gitleaks pre-commit hook in infra AND hyperguild").
#
# Ported from mathias/infra's .gitleaks.toml (2026-08-04) — same homelab
# token-shape rules, minus the SOPS/searxng allowlists infra needed (this
# repo doesn't use SOPS).
title = "hyperguild gitleaks config"
[extend]
useDefault = true
# --- Homelab-specific rules -------------------------------------------------
[[rules]]
id = "homelab-static-bearer"
description = "Homelab MCP/LLM static bearer or API key assigned a long literal value"
regex = '''(?i)\b(DMABE_[A-Z0-9_]+|[A-Z0-9_]*MCP_TOKEN|ROUTING_MCP_TOKEN|INFRA_MCP_TOKEN|BRAIN_MCP_TOKEN|GITEA_MCP_TOKEN|LITELLM_MASTER_KEY|LITELLM_SALT_KEY|DMABE_LLMAPI_KEY|BRAIN_PG_DSN)\s*[:=]\s*['"]?([A-Za-z0-9/_+.\-]{16,})['"]?'''
keywords = ["dmabe_", "mcp_token", "litellm_master_key", "litellm_salt_key", "llmapi_key", "brain_pg_dsn"]
[[rules.allowlists]]
description = "Env indirection is not a literal secret"
regexes = [
'''os\.environ''',
'''valueFrom''',
'''secretKeyRef''',
'''\$\{?[A-Za-z_][A-Za-z0-9_]*\}?''',
'''REDACTED''',
'''<[A-Z_]+>''',
]
[[rules]]
id = "homelab-authorization-bearer"
description = "Hardcoded Authorization: Bearer header"
regex = '''(?i)authorization['"]?\s*[:=]\s*['"]?bearer\s+([A-Za-z0-9/_+.\-=]{16,})'''
keywords = ["authorization", "bearer"]
[[rules.allowlists]]
description = "Env indirection is not a literal secret"
regexes = [
'''\$\{?[A-Za-z_][A-Za-z0-9_]*\}?''',
'''os\.environ''',
'''REDACTED''',
'''<[A-Z_]+>''',
]
# --- Global allowlist: claudewatcher's own scrubber test fixtures ------------
# ingestion/internal/claudewatcher/{scrubber,watcher}_test.go deliberately
# contain fake secret-shaped literals to test that the scrubber detects and
# redacts them. Verified 2026-08-04: all 9 findings here are test fixtures
# (github-pat, jwt, generic-api-key, homelab-authorization-bearer rules) plus
# 1 doc finding that was gitleaks matching the literal placeholder word
# "REDACTED" in a plan doc — not a real secret in either case.
[[allowlists]]
description = "claudewatcher scrubber test fixtures — deliberately fake secrets"
paths = [
'''ingestion/internal/claudewatcher/scrubber_test\.go$''',
'''ingestion/internal/claudewatcher/watcher_test\.go$''',
]
# infra#344: the allowlist that used to sit here is gone, and so is the reason
# for it. It suppressed docs/superpowers/plans/2026-04-22-phase4-attempt-wiring.md
# on the stated grounds that "extracted Secret == 'REDACTED' exactly ... the
# placeholder text itself, not a real credential" (verified 2026-08-04). That was
# not what the file contained: line 1054 carried a real 40-char hex Gitea PAT in
# an `Authorization: token ...` header. Confirmed dead by side-effect — GET
# /api/v1/user with it returns 401 — and redacted in that file, so there is now
# nothing to allowlist.
#
# The `paths` entry also made the block far broader than its description: gitleaks
# ORs global allowlist clauses and ignores `condition = "AND"`, so the whole file
# was immune, not just lines matching /REDACTED/. A live token added to that doc
# would have been suppressed on the strength of a note about a different value.
+33
View File
@@ -0,0 +1,33 @@
# Historical gitleaks findings, dispositioned (infra#326 / infra#317).
#
# WHY THIS FILE AND NOT .gitleaks.toml:
# This is a finding in git HISTORY, surfaced by the full-history audit
# (`task security:gitleaks:history`). The working-tree scan that gates commits
# (`task security:gitleaks`, the pre-commit hook, CI) is clean. Suppressing by
# PATH in .gitleaks.toml would also blind the working-tree scan for that file
# forever; a fingerprint pins one finding in one commit, so a NEW secret in the
# same file still fires.
#
# History is not rewritten here, so the remediation for a real leak is
# ROTATION -- making the committed value worthless -- never scrubbing.
#
# Dispositioned 2026-08-29. Re-check with: task security:gitleaks:history
# --- Real credential, ALREADY DEAD -------------------------------------------
# A Gitea PAT pasted into a CD-watching command in a planning doc
# (`Authorization: token <40-hex>`, last_eight 3105a670).
#
# Verified dead 2026-08-29: authenticating against
# GET https://git.d-ma.be/api/v1/user with this exact value returns 401, so the
# committed token no longer grants anything. It was almost certainly invalidated
# by the early-August rotation of the `mathias` PATs (the same rotation whose
# fan-out caused infra#260, where CI copies of the old value kept failing).
#
# No rotation action outstanding. Kept as a fingerprint rather than removed from
# history because history cannot be rewritten here.
#
# The generalisable lesson is recorded separately: a credential printed into a
# doc/transcript is permanent, so the only remedy is rotating it -- which in
# this case had already happened for unrelated reasons, by luck rather than by
# the leak being noticed.
c9310b1079478bf4430b0a2dfb25445d7ccc9b59:docs/superpowers/plans/2026-04-22-phase4-attempt-wiring.md:curl-auth-header:1053
+7
View File
@@ -6,6 +6,13 @@
"headers": { "headers": {
"Authorization": "Bearer ${BRAIN_MCP_TOKEN}" "Authorization": "Bearer ${BRAIN_MCP_TOKEN}"
} }
},
"gitea": {
"type": "http",
"url": "https://git-mcp.d-ma.be/mcp",
"headers": {
"Authorization": "Bearer ${GITEA_MCP_TOKEN}"
}
} }
} }
} }
+162 -23
View File
@@ -48,14 +48,51 @@ These rules apply to every task across every project, regardless of harness.
logical change (one tool, one fix, one test) with passing tests. Main is always logical change (one tool, one fix, one test) with passing tests. Main is always
deployable. Never create long-lived feature branches. deployable. Never create long-lived feature branches.
**Exception — parallel agents on same repo:** If another agent is known to be **The PR trigger is RISK, not concurrency.** `risk/low` work commits straight to
actively working on the same repo simultaneously, create a short-lived branch main with CI as the gate — that is most work and is unchanged. `risk/medium` and
(`agent/<description>`), finish the task, and merge to main within the same above opens a PR, even solo, even with nobody waiting to review it. This mirrors
session. Do not leave agent branches open between sessions. the tiered merge model in `assessor-loop`
`method/transfer-to-a-regulated-organisation.md` §4.1, so the estate practises
what it sells instead of merging everything on green and claiming otherwise.
**Exception — external contributor or client four-eyes requirement:** Use **Concurrency is NOT a reason to branch.** Measured 2026-08-29 across three real
PR flow only when a human reviewer outside the project is required. Document collisions between parallel sessions: two were not branching problems at all — a
the reason in PROJECT.md. generated artifact written to the same path by both (branching turns that into a
merge conflict on a 33k-line JSON), and uncommitted work in a shared checkout
(a per-session worktree fixes it) — and the third was an ordinary non-fast-forward
push resolved by rebase in seconds. Use a worktree per session on shared repos and
timestamp generated artifacts. Do not reach for a branch.
Branch+PR flow carries documented costs on solo repos: merging auto-closes gated
issues, review comments live on a thread separate from the issue's, and a
merged-and-deleted branch cannot be amended (brain:
`gitea-pr-merge-autoclose-and-review-comment-footguns`). Those are the price of
the `risk/medium`+ lane — paid deliberately, not incurred by accident.
**Exception — external contributor or client four-eyes requirement:** Use PR flow
when a human reviewer outside the project is required. Document the reason in
PROJECT.md.
**Exception — a GitOps repo where a branch cannot be reconciled.** In a repo whose
deployment watches one branch (`mathias/infra`: Flux watches `main`), a branch is
invisible to the thing that applies it. A `risk/medium` change to `alerts.yaml` or
`litellm-config.yaml` can be linted on a branch but never *exercised* there, so a
PR would buy a review of a state that was never deployed.
There, `risk/medium`+ work stays on `main` and instead requires a **recorded
adversarial review pass before the push** — `skills:pr-gatekeeper` or equivalent,
reviewing the staged diff. **The reviewer's verdict goes in the issue, not a PR
thread.** No verdict recorded means the lane was not used, and saying "the gate was
green" is not the same claim.
Be honest about what this is: a recorded *independent* pass, not four-eyes in the
sense `assessor-loop` §4.1 means for a regulated organisation, because the reviewer
is an agent. It is more than the repo had and less than the model it mirrors; do not
describe it as the stronger property. (infra#470, decided 2026-09-29.)
This lane depends on the `risk/` label being right. A label that triggers a heavier
lane is load-bearing, not cosmetic — if work that belongs in it is unlabelled, the
lane silently does not apply.
6. **Close the loop — every substantive task ends with the same ritual.** Shipping 6. **Close the loop — every substantive task ends with the same ritual.** Shipping
the code is not the end of the task; capturing it is. Run this unprompted: the code is not the end of the task; capturing it is. Run this unprompted:
@@ -73,6 +110,63 @@ These rules apply to every task across every project, regardless of harness.
- Surface the brain entries and issue numbers in the closing summary so the - Surface the brain entries and issue numbers in the closing summary so the
trail is auditable. trail is auditable.
**Chat is not a durable store. Never rely on Mathias remembering anything.**
Every gap, caveat, risk, open question and next step must land in one of four
places before the turn ends: **the brain**, **a repo** (code, docs, ADR),
**a tracker issue**, or **a plan file**. A finding stated only in conversation is
lost the moment the session closes — and this estate has repeatedly proved that a
remembered convention is an unreliable control.
This applies hardest to what is tempting to leave as a closing remark: "worth
knowing X isn't enforced yet", "this is a convention, not a gate", "we should
revisit Y". Those are exactly the items that need a locator. If it is worth
saying in a summary, it is worth writing where it can be found again without you.
7. **Finish what's closable — only involve me for a genuine call.** If a
tracker issue, PR, or checklist item is demonstrably resolved — the fix
landed, the state changed, you verified it live — close/merge/check it off
in the same turn. Don't leave it open "for the record" or park it waiting
on me to confirm something that already happened; that's bookkeeping, not
a decision. Reserve asking me (`AskUserQuestion`, a `DECISION NEEDED`
comment, or otherwise pausing) for when it's genuinely mine to call:
irreversible or prod/host-impacting actions, a real judgment call with no
clearly-better option, ambiguous intent, or anything secret-writes/
destructive-git already gate. Before claiming something is closable,
verify it live (re-check the issue, re-run the command) rather than
trusting your own earlier summary (brain: `filed-issue-not-same-as-fixed`).
8. **Control code needs an adversary, not a checklist.** Code whose job is to
refuse, deny, gate or contain is not adequately verified by a green gate.
Rule 5 makes CI the quality gate and that holds for ordinary work — but a
passing suite only asserts what its author already thought of, and for a
control the author is precisely the person whose imagination just failed.
Measured on `dispatch#75`: five review rounds, five real escapes verified by
execution, and **CI was green on every one of them** while `git rm
././.dispatch-allow` deleted the file the control existed to protect. So
route this work through a review with authority to block, instructed to
verify by execution rather than by reading the implementation. Expect to be
blocked more than once; that is the control working, not the reviewer being
difficult. (brain: `a-green-gate-is-not-evidence-for-control-code`; the
practices live in the `pr-gatekeeper` agent.)
9. **A test's name must not claim more than its assertions prove.** Name a test
after the mechanism it observes, not the goal it serves.
`DoesNotInheritEnv` is honest; `IsContained` is a claim the test cannot
support. This is not pedantry about naming — when name and assertion
diverge, the name wins in the reader's head and the gap becomes invisible,
which is what lets the defect survive review. Found three times in one PR,
twice in tests written to fix the previous instance of it; each passed while
the thing it was named for was exploitable. If you cannot name the mechanism,
you do not yet know what the test observes.
## CAD sprint patterns
Two CAD sprint archetypes (defs: brain `wiki/homelab/decisions/continuous-agentic-development-cad-concept-2026-06-16`):
- **Inception Sprint** — birth a new repo. Oath-gated close; tag only once every clause holds. Brain: `.../inception-sprint-and-oath`.
- **Sweep Sprint** — clear an existing backlog. Parallel read-only research per issue → sequential one-issue-per-commit execution. Brain: `.../sweep-sprint-and-oath`.
Shared: decisions that are yours, not the agent's, surface as `DECISION NEEDED` (question/options/recommendation/blocks) — ask live if you're present, else comment and wait, never act past it. Live-breaking regressions get `git revert`, never forward-fixed; host-network work skips even read-only research (solo, synchronous, you present). Rule 6's closing ritual only fires once every Oath clause genuinely holds — blocked = descoped-and-tracked, never marked done.
## Default stack ## Default stack
| Layer | Default | Fallback | Last resort | | Layer | Default | Fallback | Last resort |
@@ -83,7 +177,7 @@ These rules apply to every task across every project, regardless of harness.
| Containers | Docker Compose (dev), k3s (prod) | — | — | | Containers | Docker Compose (dev), k3s (prod) | — | — |
| DB | PostgreSQL + sqlc | SQLite | — | | DB | PostgreSQL + sqlc | SQLite | — |
| Search | pgvector (vector), BM25 | Qdrant (when >1M vectors or hybrid retrieval) | — | | Search | pgvector (vector), BM25 | Qdrant (when >1M vectors or hybrid retrieval) | — |
| Logging | slog (structured) | — | — | | Logging | slog (structured) | stdlib `logging` w/ structured `extra=` (or structlog) | — |
| Testing | Table-driven, testify | — | — | | Testing | Table-driven, testify | — | — |
| Agents (Go) | google.golang.org/adk + pkg/litellm adapter | — | — | | Agents (Go) | google.golang.org/adk + pkg/litellm adapter | — | — |
@@ -92,7 +186,12 @@ Exploratory: Rust, Zig — I'll tell you when I want these.
## Code conventions ## Code conventions
- **Go style**: golines, gofumpt, golangci-lint - **Go style**: golines, gofumpt, golangci-lint
- **Errors**: `fmt.Errorf("operation: %w", err)` — never naked, never log-and-return - **Python style** (fallback language): ruff (format+lint, one tool), mypy --strict (non-negotiable,
matches Go's static typing discipline), pytest + pytest-cov (table-driven via
`@pytest.mark.parametrize`), uv (venv+deps+lock, one tool), pydantic-settings (typed env-var config
— same principle as Go's typed structs), src-layout + `pyproject.toml` only (no `setup.py`)
- **Errors**: `fmt.Errorf("operation: %w", err)` — never naked, never log-and-return.
Python: `raise X from e` (exception chaining, same principle) — never bare `except`, never silent `pass`
- **Naming**: stdlib conventions, no stuttering - **Naming**: stdlib conventions, no stuttering
- **Architecture**: prefer stdlib over frameworks, constructor injection, env-var config parsed into typed structs - **Architecture**: prefer stdlib over frameworks, constructor injection, env-var config parsed into typed structs
- **Git**: conventional commits (`feat:`, `fix:`, `chore:`), commit directly to main, - **Git**: conventional commits (`feat:`, `fix:`, `chore:`), commit directly to main,
@@ -130,10 +229,10 @@ Three machines on Tailscale:
|---------|------|-----------| |---------|------|-----------|
| koala | GPU inference, heavy compute | RTX 5070, runs k3s + llama-swap + shared postgres18/pgvector | | koala | GPU inference, heavy compute | RTX 5070, runs k3s + llama-swap + shared postgres18/pgvector |
| iguana | Services, builds | M2 Ultra Mac | | iguana | Services, builds | M2 Ultra Mac |
| flamingo | Daily driver, edge | Mac mini, ~/dev is here | | flamingo | Daily driver, edge | Apple Silicon Mac, ~/dev is here |
- **Model routing**: LiteLLM in front of llama-swap (local) + cloud APIs (when permitted) - **Model routing**: LiteLLM in front of llama-swap (local) + cloud APIs (when permitted)
- **Orchestration**: k3s cluster across all three machines - **Orchestration**: k3s on koala only — single control-plane node, no workers (verified 2026-08-30). iguana and flamingo are on the tailnet but are not cluster members
- **Networking**: Tailscale mesh - **Networking**: Tailscale mesh
## Project landscape ## Project landscape
@@ -229,10 +328,11 @@ When working on a project tagged with a client name:
## Harness-agnostic principles ## Harness-agnostic principles
This context is designed to work with any AI coding tool: Supported harnesses (2026-09-01) — Cursor and Aider were dropped; do not
- Claude Code, Cursor, Aider, Open WebUI, Charmbracelet Mods/Crush re-add adapters for them:
- Pi Coding Agent, Mistral Vibe, Antigravity - Claude Code, Antigravity, OpenCode, Mistral Vibe, Crush, Pi Coding Agent
- Any tool that accepts a system prompt or reads a markdown context file - Open WebUI, Charmbracelet Mods, or any tool that takes a system prompt string
- Any other tool that reads `AGENTS.md`, which is the de facto convention
The canonical source is always `.context/AGENT.md` (root) and `.context/PROJECT.md` (per-project). The canonical source is always `.context/AGENT.md` (root) and `.context/PROJECT.md` (per-project).
Derived files are committed (see *How context propagates* below) so a `git pull` on any host yields full agent context with no setup. Derived files are committed (see *How context propagates* below) so a `git pull` on any host yields full agent context with no setup.
@@ -244,26 +344,65 @@ Canonical sources of truth:
- Project: `<repo>/.context/PROJECT.md` (per-repo) - Project: `<repo>/.context/PROJECT.md` (per-repo)
Derived files (committed, regenerated by `task context:sync`): Derived files (committed, regenerated by `task context:sync`):
- `CLAUDE.md`, `AGENTS.md`, `.cursorrules`, `.aider.conventions.md`, - `CLAUDE.md`, `AGENTS.md`, `.context/system-prompt.txt`
`.context/system-prompt.txt`
Repos still carrying `.cursorrules`, `.aider.conventions.md` or
`.aider.conf.yml` are stale: nothing regenerates them. Delete them the next time
you touch the repo, along with their entries in that repo's `task check`
assertion.
Workflow: Workflow:
1. Edit a canonical file. Run `task context:sync`. Commit canonical and 1. Edit a canonical file. Run `task context:sync`. Commit canonical and
derived together. Push. derived together. Push.
2. On any other host, `git pull` brings both. Claude Code (tree-walking) 2. On any other host, `git pull` brings both. Which file a harness reads does
uses `CLAUDE.md`; Crush / Pi / Antigravity (cwd-only) use `AGENTS.md`; NOT split cleanly by lookup strategy, so do not reason from the strategy:
Cursor uses `.cursorrules`; Aider uses `.aider.conventions.md`. - `CLAUDE.md` — Claude Code (walks up the tree)
- `AGENTS.md` — Crush, Pi, Antigravity (cwd-only), OpenCode (project root,
global at `~/.config/opencode/AGENTS.md`), and Mistral Vibe, which **walks
up** from cwd and takes the first `AGENTS.md` it finds
(user-level `~/.vibe/AGENTS.md`)
- `.context/system-prompt.txt` — Open WebUI, Mods, raw API calls; not read by
any harness, it is for pasting
Vibe tree-walks for `AGENTS.md`, so "tree-walkers use CLAUDE.md" is false.
Each repo's `AGENTS.md` embeds the canonical and is the first one found from
inside that repo, so this works — but by construction, not by luck.
3. `task check` runs `context:sync` then asserts `git status --porcelain` 3. `task check` runs `context:sync` then asserts `git status --porcelain`
is empty over the derived files (catches both modified-tracked drift is empty over the derived files (catches both modified-tracked drift
and missing-untracked adapters). A drift fails the check with a and missing-untracked adapters). A drift fails the check with a
message telling you to stage the regenerated files. message telling you to stage the regenerated files.
Behavior rules in this file and per-project rules in `PROJECT.md` apply Behavior rules in this file and per-project rules in `PROJECT.md` apply on every
unconditionally on every host, every harness. host and every harness.
**Where a project rule contradicts a rule here, the project rule governs — and it
must state its reason.** Both halves matter: the project file wins because it knows
something this file cannot (infra's Flux constraint is real and not visible from
here), and it must say why because a bare override is indistinguishable from drift.
This replaces the previous wording, which said rules here and in `PROJECT.md` both
apply *"unconditionally"*. That was not a tiebreak but a contradiction, and it went
unnoticed until rule 5 and infra's "never create feature branches" had to be obeyed
at the same time (infra#470). A standard can hold two individually sensible clauses
that are jointly unsatisfiable, and survive for as long as everyone reads it
charitably — the same failure the Inception Sprint Oath's G6 had.
## Engineering Skills ## Engineering Skills
Shared engineering skills are available in `~/dev/.skills/`. Load at task start — not "on demand" but on schedule, before writing code. See `~/dev/.skills/SKILLS_INDEX.md` for the full list. Shared engineering skills live in the **`mathias/skills`** repo (`git.d-ma.be/mathias/skills`). Load at task start — not "on demand" but on schedule, before writing code. Browse `SKILLS_INDEX.md` for the full list.
**Claude Code** installs the repo as a plugin from the marketplace the same repo hosts. That path also carries the `secret-guard` and `pre-task-ritual` hooks and the brain/gitea/infra MCP servers, which symlinks cannot:
```
/plugin marketplace add https://git.d-ma.be/mathias/skills.git
/plugin install skills@mathias
```
Skills are **namespaced** under Claude Code: load `tdd` as `skills:tdd`. The trigger table below uses bare names — prefix them.
**Crush, Pi and OpenCode** have no plugin system and are wired by `install.sh` as one directory symlink per harness via `~/.agents/skills`. Do not clone the checkout into `~/dev`: that folder is iCloud-shared between the Macs and spans two path roots (`/Users/mathias` vs `/home/mathias` on koala), so a checkout there is a git working tree with two concurrent writers, and any absolute symlink stored in it is broken on one side by construction (skills#23). Leave `SKILLS_CHECKOUT_DIR` at its host-local default.
Check a host with `task doctor` in the skills repo; it also runs automatically at session start via the plugin.
**Skill trigger table — load before starting, not after getting stuck:** **Skill trigger table — load before starting, not after getting stuck:**
-30
View File
@@ -1,30 +0,0 @@
# syntax=docker/dockerfile:1
# ── Build stage ───────────────────────────────────────────────────────────────
FROM golang:1.26-bookworm AS builder
ARG VERSION=dev
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
go build -trimpath -ldflags="-s -w -X main.version=${VERSION}" \
-o /out/routing ./cmd/routing
# ── Runtime stage ─────────────────────────────────────────────────────────────
FROM gcr.io/distroless/base-debian12
COPY --from=builder /out/routing /usr/local/bin/routing
COPY config/ /app/config/
ENV SUPERVISOR_CONFIG_DIR=/app/config/supervisor
ENV ROUTING_PORT=3210
EXPOSE 3210
USER 65532:65532
ENTRYPOINT ["/usr/local/bin/routing"]
+49
View File
@@ -0,0 +1,49 @@
# Icebox — retired code (recoverable, not destroyed)
Per issue #75 (consolidate to a single harness), the routing-pod path was removed
from the live tree. It is **preserved and recoverable**, not deleted without trace.
## What was iceboxed (2026-07-01, issue #75)
| Path | Why |
|------|-----|
| `cmd/routing/` | The routing MCP-server binary; every skill call was wrapped through the broken pass-rate router (`wrap(skillName)`). |
| `internal/routing/` | Router / Fetcher / Policy / pass-rate. Signal is survivorship-biased and unusable as-is (infra#174). |
| `internal/skills/{review,debug,retrospective,trainer,project}/` | Skill handlers usable **only** through `cmd/routing` (verified: each imported solely by `cmd/routing`). |
| `Dockerfile.routing` | Built `cmd/routing` exclusively. |
| `.gitea/workflows/cd.yml` (routing steps only) | Removed the routing image build + infra image-bump + Flux-wait/rollout-verify for routing; **ingestion build/deploy is unchanged**. |
## Why
The live minimal harness is `cmd/hyperguild` + `brain-mcp` (+ `gitea-mcp` available) —
that is what ran the infra#170 loop-1 experiment (routing/injection machinery off) and
closed it twice. `cmd/hyperguild` has **zero** transitive dependency on `internal/routing`
or `cmd/routing`'s packages (it imports only `internal/tier`). The routing pass-rate signal
is being retired, not resurrected (fresh start, per infra#174).
## How to recover
Everything above is preserved at commit `00e5f62` under:
- **tag** `icebox/cmd-routing-2026-07-01`
- **branch** `icebox/cmd-routing`
```bash
# inspect
git checkout icebox/cmd-routing-2026-07-01
# restore specific packages onto a branch
git checkout icebox/cmd-routing-2026-07-01 -- cmd/routing internal/routing \
internal/skills/review internal/skills/debug internal/skills/retrospective \
internal/skills/trainer internal/skills/project Dockerfile.routing
```
## Deliberately NOT touched here (separate scope)
- **Live k8s routing deployment** (`infra` repo, `k3s/apps/routing/`) still runs its last
image; CD no longer rebuilds/redeploys it. Tearing down that deployment is a separate
infra-repo task.
- **`internal/skills/{brain,org,sessionlog}/`** — kept per #75; already had no importer
(orphaned before this cut), harmless, compile + test green.
- **`config/supervisor/{review,debug,retrospective,trainer-*}.md`** — routing skill prompts,
now orphaned data; left in place (not code, no build impact).
-1
View File
@@ -1,2 +1 @@
ingestion: cd ingestion && INGEST_BRAIN_DIR=../brain INGEST_PORT=3300 INGEST_WATCH_INTERVAL=30 go run ./cmd/server/ ingestion: cd ingestion && INGEST_BRAIN_DIR=../brain INGEST_PORT=3300 INGEST_WATCH_INTERVAL=30 go run ./cmd/server/
supervisor: SUPERVISOR_CONFIG_DIR=./config/supervisor SUPERVISOR_MODELS_FILE=./config/models.yaml SUPERVISOR_SESSIONS_DIR=./brain/sessions INGEST_BASE_URL=http://localhost:3300 INGEST_SVC_URL=http://localhost:3300 go run ./cmd/supervisor/
+93 -3
View File
@@ -5,6 +5,11 @@ Instead of letting Claude Code do whatever it wants, hyperguild enforces structu
workflows (TDD red/green/refactor), logs every session, and accumulates learnings workflows (TDD red/green/refactor), logs every session, and accumulates learnings
into a searchable brain. into a searchable brain.
**This repo is also where `brain-mcp` lives** — the MCP server at
`brain-mcp.d-ma.be` that `brain_query`, `brain_write`, `brain_read`, `brain_edit`
and `capture` are served from. It is not a separate deployable; see
[Where brain-mcp lives](#where-brain-mcp-lives).
## Hypothesis ## Hypothesis
> We believe routing skill tasks through local models, backed by brain context, > We believe routing skill tasks through local models, backed by brain context,
@@ -20,7 +25,7 @@ usage, the fast-model routing path should be reconsidered.
**hyperguild = Claude Code + MCP.** This is a supervisor for Claude Code sessions specifically. **hyperguild = Claude Code + MCP.** This is a supervisor for Claude Code sessions specifically.
For multi-agent orchestration (OpenCode + LiteLLM, executor/reviewer pipelines), see For multi-agent orchestration (OpenCode + LiteLLM, executor/reviewer pipelines), see
[agentsquad](http://gitea.d-ma.be/mathias/agentsquad) — a separate harness for a different [agentsquad](https://git.d-ma.be/mathias/agentsquad) — a separate harness for a different
orchestration model. Skills (mathias/skills) are shared between both. orchestration model. Skills (mathias/skills) are shared between both.
## How it works ## How it works
@@ -44,6 +49,91 @@ brain/
└── knowledge/ — legacy flat notes (migration pending: hyperguild#22) └── knowledge/ — legacy flat notes (migration pending: hyperguild#22)
``` ```
## Where brain-mcp lives
`brain-mcp` is served from **`ingestion/internal/mcp`** in this repo, at
**`brain-mcp.d-ma.be`**. It is a component *inside* the `ingestion` service, not
a standalone deployable — one pod in the `supervisor` namespace serves the MCP
endpoint, the REST API, and the claudewatcher together.
| You are looking for | It is here |
|---|---|
| The MCP tool surface (`brain_query`, `brain_write`, `brain_read`, `brain_edit`, `capture`, …) | `ingestion/internal/mcp` |
| The HTTP/REST API (`/query`, `/write`, `/ingest`) | `ingestion/internal/api` |
| Session ingestion from Claude Code transcripts | `ingestion/internal/claudewatcher` |
| The brain *content* (notes, wings, halls) | [`mathias/brain`](https://git.d-ma.be/mathias/brain) — a separate repo |
| Deployment manifests | `config/supervisor` |
### Why it is not its own repo
Asked and decided in [#91](https://git.d-ma.be/mathias/hyperguild/issues/91)
(part 2). `internal/mcp` imports 17 of ingestion's other internal packages and
has exactly one importer — it is the MCP facade over the service's own
internals, so "move it out" resolves to renaming `ingestion`, publishing 17
packages as a shared library, or maintaining a shim. The discoverability problem
that prompted the question is answered by naming it here instead.
Full reasoning, including the reversal trigger: brain
`wiki/hyperguild/decisions/brain-mcp-stays-in-ingestion-fix-discoverability-by-name`.
## Ingest revises, it does not overwrite
Re-ingesting a source **merges into the page already on disk** rather than
replacing it. Previously the write was unconditional, so a second ingest of the
same source discarded everything accumulated since — including hand-written
sections.
The merge is deliberately asymmetric in the existing page's favour:
| On the page | In the fresh extraction | Result |
|---|---|---|
| a section | the same section | **the on-disk version wins** |
| — | a new section | added |
| a bullet list (`Sources`, `Key Claims`, …) | more bullets | unioned, no duplicates |
| an append section (`Open Questions`, `Updates`, …) | more lines | only genuinely new lines appended |
| frontmatter | frontmatter | **the on-disk frontmatter wins** |
So an extraction can add to a note but never silently rewrite what a human put
there, which is what makes it safe to run on every ingest rather than behind a
review gate.
Re-ingesting unchanged content is **byte-identical** — no diff, so brain-sync
does not commit noise that hides real edits.
Two fields are **generator-owned** and do get refreshed on a revise:
`last_updated` and `source_hash`. Everything else on disk wins. The boundary is
an explicit allowlist, so a field nobody has thought about stays human-owned.
### Disagreement is reported, not resolved
When the fresh extraction produces a *different version* of a section that
already exists, the on-disk version still wins — but the run now says so:
```
wiki/sources/shape-up.md: source now disagrees on section "Summary" — on-disk version kept
```
That line lands in `log.md` with the rest of the run's warnings. Without it, "the
source is unchanged" and "the source changed its mind and we ignored it" look
identical from the outside.
This is deliberately **textual** disagreement, not semantic contradiction: cheap,
deterministic, no model on the write path. Deciding whether a disagreement is a
genuine contradiction stays with the Judge-gated `brain-enrich` pass, which is
approval-gated by design. Detection here, adjudication there.
## Re-ingesting an unchanged source is skipped
Ingest stores `source_hash` — sha256 of the ingested **body**, frontmatter
excluded — on the source page. A later ingest of the same source compares it
first and skips extraction entirely when it matches, reporting the skip rather
than doing it silently.
Body-only is deliberate: a re-crawl that stamps a new fetch date has not changed
the source, and treating that as drift would re-extract the corpus every time a
crawler ran. A missing or unreadable hash always means "extract" — a missed skip
costs one extraction, a wrong skip loses an update.
## Phase 1 tools (available now) ## Phase 1 tools (available now)
| Tool | What it does | | Tool | What it does |
@@ -58,7 +148,7 @@ brain/
| `tier` | Returns the current connectivity tier (1=cloud, 2=LAN, 3=offline) | | `tier` | Returns the current connectivity tier (1=cloud, 2=LAN, 3=offline) |
> **Note:** `tdd_red/green/refactor` and `spec` were retired in Plan 7 (2026-05-12). > **Note:** `tdd_red/green/refactor` and `spec` were retired in Plan 7 (2026-05-12).
> They are now SKILL.md files in [mathias/skills](http://gitea.d-ma.be/mathias/skills). > They are now SKILL.md files in [mathias/skills](https://git.d-ma.be/mathias/skills).
## Connect a project ## Connect a project
@@ -147,7 +237,7 @@ The routing pod selects models per skill call based on historical pass rate:
## Open issues ## Open issues
See [issues](http://gitea.d-ma.be/mathias/hyperguild/issues) — key open items: See [issues](https://git.d-ma.be/mathias/hyperguild/issues) — key open items:
- **#25** — skills platform overhaul (audit first, then lazy loading + brain feedback loop) - **#25** — skills platform overhaul (audit first, then lazy loading + brain feedback loop)
- **#24** — reduce context burn from skill listing - **#24** — reduce context burn from skill listing
+74 -36
View File
@@ -21,7 +21,7 @@ tasks:
# ── Development ──────────────────────────────────────────────────────────── # ── Development ────────────────────────────────────────────────────────────
start: start:
desc: Start ingestion + supervisor (requires goreman — go install github.com/mattn/goreman@latest) desc: Start ingestion (requires goreman — go install github.com/mattn/goreman@latest)
cmds: cmds:
- goreman start - goreman start
@@ -32,11 +32,6 @@ tasks:
- lsof -ti:3200 | xargs kill -9 2>/dev/null || true - lsof -ti:3200 | xargs kill -9 2>/dev/null || true
- echo "hyperguild stopped" - echo "hyperguild stopped"
supervisor:dev:
desc: Run supervisor MCP server (development)
cmds:
- go run ./cmd/supervisor
hyperguild:dev: hyperguild:dev:
desc: Run hyperguild CLI from source (e.g. task hyperguild:dev -- tier) desc: Run hyperguild CLI from source (e.g. task hyperguild:dev -- tier)
cmds: cmds:
@@ -67,14 +62,9 @@ tasks:
build: build:
desc: Build all binaries desc: Build all binaries
cmds: cmds:
- task: supervisor:build - task: hyperguild:build
- task: ingestion:build - task: ingestion:build
supervisor:build:
desc: Build supervisor binary
cmds:
- go build -trimpath -ldflags="-s -w -X main.version={{.VERSION}}" -o bin/supervisor ./cmd/supervisor
ingestion:build: ingestion:build:
desc: Build ingestion server binary desc: Build ingestion server binary
dir: ingestion dir: ingestion
@@ -84,29 +74,90 @@ tasks:
# ── Quality ──────────────────────────────────────────────────────────────── # ── Quality ────────────────────────────────────────────────────────────────
check: check:
desc: Run all checks (context freshness + lint + test + vet) across all modules desc: Run all checks (context freshness + lint + test + vet + build) across all modules
cmds: cmds:
- task: context:sync # Context sync is skipped under CI, matching dma-cli, gitea-mcp, and the
# rest of the estate. It is not a preference: context-sync.sh walks UP
# the tree for the canonical .context/AGENT.md, which lives in local-dev
# and does not exist on a CI runner. Without this guard, the script
# silently falls back to "project context only" and regenerates AGENTS.md
# and .context/system-prompt.txt shorter than their committed, correct
# versions -- so the drift assertion fails every CI run for a purely
# environmental reason, not real drift. Verified, not assumed: this is
# exactly what was happening here (AGENTS.md 430 lines committed vs. an
# 82-line regeneration on the runner).
#
# The cost is real and worth stating: drift is therefore only ever caught
# on a developer machine, or by infra's estate-wide context-sync-drift
# CronJob (ADR-0019), which does have canonical access and is the actual
# enforcement mechanism now.
- cmd: | - cmd: |
drift=$(git status --porcelain -- AGENTS.md CLAUDE.md .context/system-prompt.txt 2>/dev/null) if [ -n "${CI:-}" ]; then
if [ -n "$drift" ]; then echo "✓ context sync: skipped in CI (no canonical AGENT.md on the runner)"
echo "ERROR: derived adapters drifted from canonical context." >&2 else
echo "$drift" >&2 bash scripts/context-sync.sh
echo "" >&2 drift=$(git status --porcelain -- AGENTS.md CLAUDE.md .context/system-prompt.txt 2>/dev/null)
echo "Run: git add AGENTS.md CLAUDE.md .context/system-prompt.txt" >&2 if [ -n "$drift" ]; then
echo " git commit -m 'chore: re-sync context adapters'" >&2 echo "ERROR: derived adapters drifted from canonical context." >&2
exit 1 echo "$drift" >&2
echo "" >&2
echo "Run: git add AGENTS.md CLAUDE.md .context/system-prompt.txt" >&2
echo " git commit -m 'chore: re-sync context adapters'" >&2
exit 1
fi
echo "✓ context: canonical and adapters are in sync"
fi fi
echo "✓ context: canonical and adapters are in sync"
- task: lint - task: lint
- task: test - task: test
- task: vet - task: vet
# `build` is in the gate deliberately (hyperguild#120). vet and test walk
# ./... , which enumerates the packages that EXIST — so a build target
# naming a DELETED package is invisible to both. `task build` pointed at
# ./cmd/supervisor for months after that directory was removed, and CI
# stayed green the whole time because nothing in check ever built.
- task: build
- task: security:gitleaks
# ── Security ─────────────────────────────────────────────
security:gitleaks:
desc: Scan the working tree for secrets (gitleaks, fail-closed; skipped if gitleaks absent)
dir: '{{.ROOT_DIR}}'
cmds:
- |
GL="$(command -v gitleaks || true)"
[ -z "$GL" ] && [ -x "$(go env GOPATH 2>/dev/null)/bin/gitleaks" ] && GL="$(go env GOPATH)/bin/gitleaks"
if [ -z "$GL" ]; then
echo "⚠ gitleaks not installed — skipping secret scan (CI enforces it)."
echo " Install: go install github.com/zricethezav/gitleaks/v8@latest"
exit 0
fi
"$GL" detect --no-git --redact --config .gitleaks.toml --source .
security:gitleaks:history:
desc: "One-time FULL-HISTORY secret audit (infra#39 rotation pass; not a per-push gate)"
dir: '{{.ROOT_DIR}}'
cmds:
- |
GL="$(command -v gitleaks || true)"
[ -z "$GL" ] && [ -x "$(go env GOPATH 2>/dev/null)/bin/gitleaks" ] && GL="$(go env GOPATH)/bin/gitleaks"
if [ -z "$GL" ]; then
echo "gitleaks not installed: go install github.com/zricethezav/gitleaks/v8@latest" >&2
exit 2
fi
echo "Scanning FULL git history (redacted). Known historical leaks are expected"
echo "until the infra#39 rotation pass completes — triage against the rotation list."
"$GL" detect --redact --config .gitleaks.toml
lint: lint:
cmds: cmds:
- golangci-lint run ./... - golangci-lint run ./...
- cd ingestion && golangci-lint run ./... - cd ingestion && golangci-lint run ./...
lint:frontmatter:
desc: Report brain notes whose YAML frontmatter does not parse (BRAIN=path, FIX=1 repairs in place)
cmds:
- cd ingestion && go run ./cmd/frontmatterlint {{if .FIX}}-fix{{end}} {{.BRAIN | default "../../brain"}}
test: test:
cmds: cmds:
- go test -race -count=1 ./... - go test -race -count=1 ./...
@@ -118,19 +169,6 @@ tasks:
- govulncheck ./... || true - govulncheck ./... || true
- cd ingestion && go vet ./... - cd ingestion && go vet ./...
supervisor:test:smoke:
desc: Smoke test supervisor via MCP (requires start running)
cmds:
- |
curl -s -X POST http://localhost:${SUPERVISOR_PORT:-3200}/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' | jq .
smoke:routing:
desc: Boot the routing pod against live LiteLLM + brain and verify _routing logs land
cmds:
- bash scripts/smoke-routing.sh
# ── Git / Release ────────────────────────────────────────────────────────── # ── Git / Release ──────────────────────────────────────────────────────────
tag: tag:
+15 -13
View File
@@ -55,18 +55,21 @@ Flags:
- `--limit N` — max results (default 5) - `--limit N` — max results (default 5)
- `--json` — emit the raw response envelope - `--json` — emit the raw response envelope
### `hyperguild brain write <type> <slug>` ### `hyperguild brain write <wing> <hall> <slug>`
Reads markdown from stdin, writes a knowledge entry. Reads markdown from stdin, writes it to `brain/wiki/<wing>/<hall>/<slug>.md`
with `wing`/`hall`/`created_at` frontmatter injected (there is no legacy
`brain/knowledge/` fallback — ADR-0012 / #79, both wing and hall are
required).
```bash ```bash
$ cat <<EOF | hyperguild brain write knowledge example-lesson $ cat <<EOF | hyperguild brain write homelab facts example-lesson
# Example lesson # Example lesson
## Lesson ## Lesson
... ...
EOF EOF
knowledge/example-lesson.md wiki/homelab/facts/example-lesson.md
``` ```
### `hyperguild brain pass-rate <skill>` ### `hyperguild brain pass-rate <skill>`
@@ -112,16 +115,15 @@ Flags:
- `--out PATH` — output file (default `./.mcp.json`) - `--out PATH` — output file (default `./.mcp.json`)
- `--force` — overwrite an existing file - `--force` — overwrite an existing file
Modes: Modes (all list **brain + gitea** — Gitea is the audit-trail invariant of the
consolidated single harness, #75):
- **cloud** — brain MCP only. Claude Code with no routing. - **cloud** — brain + gitea MCP.
- **client-local** — brain + routing pod. The `routing` entry points at - **client-local** — brain + gitea MCP. (The former `routing` entry pointing at
`koala:30310/mcp` (the routing pod, deployed in Plan 6). The `koala:30310/mcp` was removed — the routing pod is iceboxed, #75.)
`X-Hyperguild-Mode: client-local` header is forward-compat for future - **sovereign** — brain + gitea, with a `_mode_note` explaining that this mode
modes; the pod treats absent or unknown values as `client-local`. primarily uses Crush + LiteLLM and the `.mcp.json` is a Claude Code fallback
- **sovereign** — brain only, with a `_mode_note` explaining that this for emergency offline use.
mode primarily uses Crush + LiteLLM and the `.mcp.json` is a Claude
Code fallback for emergency offline use.
## Environment ## Environment
+6 -5
View File
@@ -60,13 +60,14 @@ func runBrainWrite(ctx context.Context, args []string, stdin io.Reader, stdout,
if err := fs.Parse(args); err != nil { if err := fs.Parse(args); err != nil {
return fmt.Errorf("parse flags: %w", err) return fmt.Errorf("parse flags: %w", err)
} }
if fs.NArg() < 2 { if fs.NArg() < 3 {
return errors.New("type and slug required (e.g. brain write knowledge my-slug)") return errors.New("wing, hall and slug required (e.g. brain write homelab facts my-slug)")
} }
kind := fs.Arg(0) wing := fs.Arg(0)
slug := fs.Arg(1) hall := fs.Arg(1)
slug := fs.Arg(2)
res, err := newBrainClient().Write(ctx, kind, slug, stdin) res, err := newBrainClient().Write(ctx, wing, hall, slug, stdin)
if err != nil { if err != nil {
return err return err
} }
+5 -5
View File
@@ -101,7 +101,7 @@ func TestRunBrainWrite_Success(t *testing.T) {
var out, errBuf bytes.Buffer var out, errBuf bytes.Buffer
err := runBrain( err := runBrain(
context.Background(), context.Background(),
[]string{"write", "knowledge", "test-slug"}, []string{"write", "homelab", "facts", "test-slug"},
strings.NewReader("# Test\n\nSome body content.\n"), strings.NewReader("# Test\n\nSome body content.\n"),
&out, &errBuf, &out, &errBuf,
) )
@@ -111,9 +111,9 @@ func TestRunBrainWrite_Success(t *testing.T) {
func TestRunBrainWrite_MissingArgs(t *testing.T) { func TestRunBrainWrite_MissingArgs(t *testing.T) {
var out, errBuf bytes.Buffer var out, errBuf bytes.Buffer
err := runBrain(context.Background(), []string{"write", "knowledge"}, strings.NewReader("x"), &out, &errBuf) err := runBrain(context.Background(), []string{"write", "homelab"}, strings.NewReader("x"), &out, &errBuf)
assert.Error(t, err) assert.Error(t, err)
assert.Contains(t, err.Error(), "type and slug required") assert.Contains(t, err.Error(), "wing, hall and slug required")
} }
func TestRunBrainWrite_BackendError(t *testing.T) { func TestRunBrainWrite_BackendError(t *testing.T) {
@@ -127,7 +127,7 @@ func TestRunBrainWrite_BackendError(t *testing.T) {
var out, errBuf bytes.Buffer var out, errBuf bytes.Buffer
err := runBrain( err := runBrain(
context.Background(), context.Background(),
[]string{"write", "knowledge", "bad slug"}, []string{"write", "homelab", "facts", "bad slug"},
strings.NewReader("body"), strings.NewReader("body"),
&out, &errBuf, &out, &errBuf,
) )
@@ -150,7 +150,7 @@ func TestRunBrainWrite_EmptyStdin(t *testing.T) {
t.Setenv("BRAIN_URL", srv.URL) t.Setenv("BRAIN_URL", srv.URL)
var out, errBuf bytes.Buffer var out, errBuf bytes.Buffer
err := runBrain(context.Background(), []string{"write", "knowledge", "empty"}, strings.NewReader(""), &out, &errBuf) err := runBrain(context.Background(), []string{"write", "homelab", "facts", "empty"}, strings.NewReader(""), &out, &errBuf)
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, 0, gotLen, "empty stdin should produce empty content payload") assert.Equal(t, 0, gotLen, "empty stdin should produce empty content payload")
} }
+6 -5
View File
@@ -84,16 +84,17 @@ type WriteResult struct {
Path string `json:"path"` Path string `json:"path"`
} }
func (c *brainClient) Write(ctx context.Context, kind, slug string, content io.Reader) (*WriteResult, error) { func (c *brainClient) Write(ctx context.Context, wing, hall, filename string, content io.Reader) (*WriteResult, error) {
body, err := io.ReadAll(content) body, err := io.ReadAll(content)
if err != nil { if err != nil {
return nil, fmt.Errorf("read content: %w", err) return nil, fmt.Errorf("read content: %w", err)
} }
payload, err := json.Marshal(struct { payload, err := json.Marshal(struct {
Type string `json:"type"` Wing string `json:"wing"`
Slug string `json:"slug"` Hall string `json:"hall"`
Content string `json:"content"` Filename string `json:"filename"`
}{Type: kind, Slug: slug, Content: string(body)}) Content string `json:"content"`
}{Wing: wing, Hall: hall, Filename: filename, Content: string(body)})
if err != nil { if err != nil {
return nil, fmt.Errorf("marshal payload: %w", err) return nil, fmt.Errorf("marshal payload: %w", err)
} }
+10 -8
View File
@@ -65,23 +65,25 @@ func TestBrainClient_Write_Success(t *testing.T) {
assert.Equal(t, http.MethodPost, r.Method) assert.Equal(t, http.MethodPost, r.Method)
body, _ := io.ReadAll(r.Body) body, _ := io.ReadAll(r.Body)
var got struct { var got struct {
Type string `json:"type"` Wing string `json:"wing"`
Slug string `json:"slug"` Hall string `json:"hall"`
Content string `json:"content"` Filename string `json:"filename"`
Content string `json:"content"`
} }
require.NoError(t, json.Unmarshal(body, &got)) require.NoError(t, json.Unmarshal(body, &got))
assert.Equal(t, "knowledge", got.Type) assert.Equal(t, "homelab", got.Wing)
assert.Equal(t, "find-h", got.Slug) assert.Equal(t, "facts", got.Hall)
assert.Equal(t, "find-h", got.Filename)
assert.Equal(t, "# body\n", got.Content) assert.Equal(t, "# body\n", got.Content)
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"path":"knowledge/find-h.md"}`)) _, _ = w.Write([]byte(`{"path":"wiki/homelab/facts/find-h.md"}`))
})) }))
defer srv.Close() defer srv.Close()
c := &brainClient{baseURL: srv.URL, http: srv.Client()} c := &brainClient{baseURL: srv.URL, http: srv.Client()}
res, err := c.Write(context.Background(), "knowledge", "find-h", strings.NewReader("# body\n")) res, err := c.Write(context.Background(), "homelab", "facts", "find-h", strings.NewReader("# body\n"))
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "knowledge/find-h.md", res.Path) assert.Equal(t, "wiki/homelab/facts/find-h.md", res.Path)
} }
func TestBrainClient_PassRate_Success(t *testing.T) { func TestBrainClient_PassRate_Success(t *testing.T) {
+26 -19
View File
@@ -59,31 +59,40 @@ func runMode(ctx context.Context, args []string, _ io.Reader, stdout, stderr io.
return nil return nil
} }
// giteaMCPURL is the public Gitea MCP endpoint (OAuth via Dex/Authentik). Gitea
// is the audit-trail invariant of the consolidated single harness (#75), so every
// mode lists it as an available connection.
const giteaMCPURL = "https://git-mcp.d-ma.be/mcp"
func brainEntry(brainURL string) map[string]any {
return map[string]any{
"url": brainURL + "/mcp",
"description": "Brain MCP — knowledge query, write, ingestion, session log",
}
}
func giteaEntry() map[string]any {
return map[string]any{
"url": giteaMCPURL,
"description": "Gitea MCP — issues/PRs/repo ops (audit-trail invariant)",
}
}
func modeCloud(brainURL string) map[string]any { func modeCloud(brainURL string) map[string]any {
return map[string]any{ return map[string]any{
"mcpServers": map[string]any{ "mcpServers": map[string]any{
"brain": map[string]any{ "brain": brainEntry(brainURL),
"url": brainURL + "/mcp", "gitea": giteaEntry(),
"description": "Brain MCP — knowledge query, write, ingestion, session log",
},
}, },
} }
} }
func modeClientLocal(brainURL string) map[string]any { func modeClientLocal(brainURL string) map[string]any {
// The routing pod is iceboxed (#75); the consolidated harness is brain + gitea.
return map[string]any{ return map[string]any{
"mcpServers": map[string]any{ "mcpServers": map[string]any{
"brain": map[string]any{ "brain": brainEntry(brainURL),
"url": brainURL + "/mcp", "gitea": giteaEntry(),
"description": "Brain MCP — knowledge query, write, ingestion, session log",
},
"routing": map[string]any{
"url": "http://koala:30310/mcp",
"description": "Mode 2 routing pod — routes skill calls to LiteLLM/local",
"headers": map[string]any{
"X-Hyperguild-Mode": "client-local",
},
},
}, },
} }
} }
@@ -92,10 +101,8 @@ func modeSovereign(brainURL string) map[string]any {
return map[string]any{ return map[string]any{
"_mode_note": "Sovereign mode primarily uses Crush + LiteLLM. This .mcp.json is provided as Claude Code fallback (e.g. emergency offline editing).", "_mode_note": "Sovereign mode primarily uses Crush + LiteLLM. This .mcp.json is provided as Claude Code fallback (e.g. emergency offline editing).",
"mcpServers": map[string]any{ "mcpServers": map[string]any{
"brain": map[string]any{ "brain": brainEntry(brainURL),
"url": brainURL + "/mcp", "gitea": giteaEntry(),
"description": "Brain MCP — knowledge query, write, ingestion, session log",
},
}, },
} }
} }
+11 -17
View File
@@ -35,11 +35,13 @@ func TestRunMode_Cloud_Default(t *testing.T) {
servers, ok := got["mcpServers"].(map[string]any) servers, ok := got["mcpServers"].(map[string]any)
require.True(t, ok, "mcpServers must be a JSON object") require.True(t, ok, "mcpServers must be a JSON object")
assert.Contains(t, servers, "brain") assert.Contains(t, servers, "brain")
assert.Contains(t, servers, "gitea")
assert.NotContains(t, servers, "routing") assert.NotContains(t, servers, "routing")
assert.NotContains(t, got, "_mode_note") assert.NotContains(t, got, "_mode_note")
} }
func TestRunMode_ClientLocal_HasRoutingEntry(t *testing.T) { func TestRunMode_ClientLocal_NoRouting_HasGitea(t *testing.T) {
// #75: the routing pod is iceboxed; the consolidated harness is brain + gitea.
dir := t.TempDir() dir := t.TempDir()
outPath := filepath.Join(dir, ".mcp.json") outPath := filepath.Join(dir, ".mcp.json")
t.Setenv("BRAIN_URL", "http://koala:30330") t.Setenv("BRAIN_URL", "http://koala:30330")
@@ -51,17 +53,11 @@ func TestRunMode_ClientLocal_HasRoutingEntry(t *testing.T) {
got := readJSON(t, outPath) got := readJSON(t, outPath)
servers := got["mcpServers"].(map[string]any) servers := got["mcpServers"].(map[string]any)
require.Contains(t, servers, "brain") require.Contains(t, servers, "brain")
require.Contains(t, servers, "routing") require.Contains(t, servers, "gitea")
assert.NotContains(t, servers, "routing", "routing pod iceboxed (#75)")
routing := servers["routing"].(map[string]any)
assert.NotContains(t, routing, "_routing_pending", "placeholder should be removed once Plan 6 ships")
headers, ok := routing["headers"].(map[string]any)
require.True(t, ok, "routing entry should have headers block")
assert.Equal(t, "client-local", headers["X-Hyperguild-Mode"])
} }
func TestModeClientLocalHasRoutingHeader(t *testing.T) { func TestModeGiteaEntryPresentAndWellFormed(t *testing.T) {
tmp := t.TempDir() + "/mcp.json" tmp := t.TempDir() + "/mcp.json"
out := &bytes.Buffer{} out := &bytes.Buffer{}
stderr := &bytes.Buffer{} stderr := &bytes.Buffer{}
@@ -73,13 +69,10 @@ func TestModeClientLocalHasRoutingHeader(t *testing.T) {
require.NoError(t, json.Unmarshal(body, &doc)) require.NoError(t, json.Unmarshal(body, &doc))
servers := doc["mcpServers"].(map[string]any) servers := doc["mcpServers"].(map[string]any)
routing := servers["routing"].(map[string]any) require.NotContains(t, servers, "routing")
assert.Equal(t, "http://koala:30310/mcp", routing["url"]) gitea, ok := servers["gitea"].(map[string]any)
assert.NotContains(t, routing, "_routing_pending", "placeholder should be removed once Plan 6 ships") require.True(t, ok, "gitea entry must be present (audit-trail invariant)")
assert.Equal(t, "https://git-mcp.d-ma.be/mcp", gitea["url"])
headers, ok := routing["headers"].(map[string]any)
require.True(t, ok, "routing entry should have headers block")
assert.Equal(t, "client-local", headers["X-Hyperguild-Mode"])
} }
func TestRunMode_Sovereign_HasModeNote(t *testing.T) { func TestRunMode_Sovereign_HasModeNote(t *testing.T) {
@@ -94,6 +87,7 @@ func TestRunMode_Sovereign_HasModeNote(t *testing.T) {
assert.Contains(t, got, "_mode_note") assert.Contains(t, got, "_mode_note")
servers := got["mcpServers"].(map[string]any) servers := got["mcpServers"].(map[string]any)
assert.Contains(t, servers, "brain") assert.Contains(t, servers, "brain")
assert.Contains(t, servers, "gitea")
assert.NotContains(t, servers, "routing") assert.NotContains(t, servers, "routing")
} }
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"io" "io"
"os" "os"
"github.com/mathiasbq/supervisor/internal/tier" "git.d-ma.be/mathias/hyperguild/internal/tier"
) )
const defaultAnthropicProbe = "https://api.anthropic.com" const defaultAnthropicProbe = "https://api.anthropic.com"
-170
View File
@@ -1,170 +0,0 @@
package main
// The internal/skills/{debug,retrospective,review,trainer} packages imported
// below are also imported by cmd/supervisor. Plan 7 (supervisor retirement)
// MUST NOT delete these four packages — the routing pod is their second
// consumer. Plan 7 deletes only internal/skills/{tdd,spec,tier} (the skills
// that don't route to local), the supervisor binary, and supervisor manifests.
// See docs/superpowers/specs/2026-05-04-mode-2-routing-pod-design.md (Constraints).
import (
"context"
"log/slog"
"net/http"
"os"
"time"
"github.com/mathiasbq/supervisor/internal/auth"
"github.com/mathiasbq/supervisor/internal/config"
iexec "github.com/mathiasbq/supervisor/internal/exec"
"github.com/mathiasbq/supervisor/internal/githubclient"
"github.com/mathiasbq/supervisor/internal/mcp"
"github.com/mathiasbq/supervisor/internal/mcpclient"
"github.com/mathiasbq/supervisor/internal/registry"
"github.com/mathiasbq/supervisor/internal/routing"
"github.com/mathiasbq/supervisor/internal/skills/debug"
"github.com/mathiasbq/supervisor/internal/skills/project"
"github.com/mathiasbq/supervisor/internal/skills/retrospective"
"github.com/mathiasbq/supervisor/internal/skills/review"
"github.com/mathiasbq/supervisor/internal/skills/trainer"
)
func main() {
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
slog.SetDefault(logger)
cfg, err := config.LoadRouting()
if err != nil {
logger.Error("config load failed", "err", err)
os.Exit(1)
}
configDir := envOr("SUPERVISOR_CONFIG_DIR", "/app/config/supervisor")
mustRead := func(path string) string {
b, err := os.ReadFile(configDir + "/" + path)
if err != nil {
logger.Error("read prompt failed", "path", path, "err", err)
os.Exit(1)
}
return string(b)
}
llm := iexec.NewLiteLLM(cfg.LiteLLMBaseURL, cfg.LiteLLMAPIKey, 0)
router := &routing.Router{
Fetcher: routing.NewFetcher(cfg.BrainURL, "7d", time.Duration(cfg.PassRateTTLSeconds)*time.Second),
Logger: routing.NewLogger(cfg.BrainURL, cfg.BrainMCPToken),
Policy: routing.Policy{Floor: cfg.RouteLocalFloor, Ceil: cfg.RouteLocalCeil},
FastModel: cfg.FastModel,
ThinkingModel: cfg.ThinkingModel,
Complete: llm.Complete,
}
// Skill packages call CompleteFunc(ctx, model, system, user) — no session_id
// or project_root in the signature. Rather than modifying every skill's API
// (and inflating Plan 6's blast radius), the routing pod logs every decision
// under a fixed session_id "_routing". Operators query
// `GET /pass-rate?skill=_routing&window=...` to inspect routing health.
const routingSessionID = "_routing"
wrap := func(skillName string) routing.CompleteFunc {
return func(ctx context.Context, _, system, user string) (string, int64, error) {
// The model param is ignored: the router picks the model based on policy.
return router.Run(ctx, routing.RunInput{
Skill: skillName,
System: system,
User: user,
SessionID: routingSessionID,
ProjectRoot: "",
})
}
}
reg := registry.New()
reg.Register(review.New(review.Config{
SkillPrompt: mustRead("review.md"),
DefaultModel: cfg.FastModel,
CompleteFunc: review.CompleteFunc(wrap("review")),
}))
reg.Register(debug.New(debug.Config{
SkillPrompt: mustRead("debug.md"),
DefaultModel: cfg.FastModel,
CompleteFunc: debug.CompleteFunc(wrap("debug")),
}))
reg.Register(retrospective.New(retrospective.Config{
SkillPrompt: mustRead("retrospective.md"),
DefaultModel: cfg.FastModel,
CompleteFunc: retrospective.CompleteFunc(wrap("retrospective")),
}))
reg.Register(trainer.New(trainer.Config{
ReaderPrompt: mustRead("trainer-reader.md"),
WriterPrompt: mustRead("trainer-writer.md"),
DefaultModel: cfg.FastModel,
CompleteFunc: trainer.CompleteFunc(wrap("trainer")),
}))
if cfg.GiteaMCPURL != "" {
mcpC, err := mcpclient.New(cfg.GiteaMCPURL, cfg.GiteaMCPToken)
if err != nil {
logger.Error("mcpclient init for project_create — GITEA_MCP_URL is set but GITEA_MCP_TOKEN is empty (check routing-secrets)", "err", err)
os.Exit(1)
}
var ghClient *githubclient.Client
if cfg.GitHubPAT != "" {
ghClient = githubclient.New(cfg.GitHubPAT)
}
reg.Register(project.New(project.Config{
Client: mcpC,
GitHub: ghClient,
GiteaOwner: cfg.GiteaOwner,
GitHubOwner: cfg.GitHubOwner,
GitHubPAT: cfg.GitHubPAT,
InfraRepo: cfg.InfraRepo,
}))
logger.Info("project_create registered", "gitea_mcp_url", cfg.GiteaMCPURL,
"gitea_owner", cfg.GiteaOwner, "github_owner", cfg.GitHubOwner,
"infra_repo", cfg.InfraRepo, "github_pat_set", cfg.GitHubPAT != "")
} else {
logger.Info("project_create skipped — GITEA_MCP_URL not set")
}
var validator *auth.Validator
if dexURL := os.Getenv("DEX_ISSUER_URL"); dexURL != "" {
audience := os.Getenv("MCP_AUDIENCE")
v, err := auth.NewValidator(dexURL, audience)
if err != nil {
logger.Error("build jwt validator", "err", err)
os.Exit(1)
}
validator = v
logger.Info("jwt auth enabled", "issuer", dexURL)
}
srv := mcp.NewServer(reg, cfg.MCPAuthToken, validator)
mux := http.NewServeMux()
mux.Handle("/mcp", srv)
mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})
if dexURL := os.Getenv("DEX_ISSUER_URL"); dexURL != "" {
resourceURL := os.Getenv("MCP_RESOURCE_URL")
mux.HandleFunc("GET /.well-known/oauth-protected-resource",
auth.ProtectedResourceHandler(resourceURL, dexURL))
}
addr := ":" + cfg.Port
logger.Info("routing pod starting", "addr", addr,
"fast", cfg.FastModel, "thinking", cfg.ThinkingModel,
"floor", cfg.RouteLocalFloor, "ceil", cfg.RouteLocalCeil)
if err := http.ListenAndServe(addr, mux); err != nil { //nolint:gosec
logger.Error("server stopped", "err", err)
os.Exit(1)
}
}
func envOr(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}
-135
View File
@@ -1,135 +0,0 @@
package main_test
import (
"context"
"encoding/json"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"strconv"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestRoutingPodEndToEnd boots the binary against fake LiteLLM + brain servers,
// calls tools/list and one tools/call, and verifies the brain saw a session_log POST.
func TestRoutingPodEndToEnd(t *testing.T) {
if testing.Short() {
t.Skip("end-to-end binary boot")
}
var brainHits int
llm := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]any{
"choices": []map[string]any{{"message": map[string]any{"role": "assistant", "content": "stub"}}},
})
}))
defer llm.Close()
brain := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/pass-rate":
brainHits++
_ = json.NewEncoder(w).Encode(map[string]any{"pass_rate": 0.95})
case "/mcp":
brainHits++
_ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": 1, "result": map[string]any{}})
}
}))
defer brain.Close()
port := freePort(t)
addr := "127.0.0.1:" + port
baseURL := "http://" + addr
bin := buildRouting(t)
cmd := exec.Command(bin)
cmd.Env = []string{
"ROUTING_PORT=" + port,
"LITELLM_BASE_URL=" + llm.URL,
"LITELLM_API_KEY=stub",
"BRAIN_URL=" + brain.URL,
"SUPERVISOR_CONFIG_DIR=../../config/supervisor",
"PATH=" + os.Getenv("PATH"),
"HOME=" + os.Getenv("HOME"),
}
require.NoError(t, cmd.Start())
t.Cleanup(func() { _ = cmd.Process.Kill() })
require.NoError(t, waitForPort(t, addr, 30*time.Second))
resp := mcpCall(t, baseURL+"/mcp", `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`)
assert.Contains(t, resp, `"review"`)
assert.Contains(t, resp, `"debug"`)
assert.Contains(t, resp, `"retrospective"`)
assert.Contains(t, resp, `"trainer"`)
resp = mcpCall(t, baseURL+"/mcp", `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"review","arguments":{"project_root":"/tmp","files":["README.md"]}}}`)
_ = resp // shape varies by skill; we only need a 200
// Wait briefly for the async session_log to land.
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) && brainHits < 2 {
time.Sleep(50 * time.Millisecond)
}
assert.GreaterOrEqual(t, brainHits, 2, "expected at least one /pass-rate hit and one /mcp session_log hit")
}
func buildRouting(t *testing.T) string {
t.Helper()
bin := t.TempDir() + "/routing"
out, err := exec.Command("go", "build", "-o", bin, "github.com/mathiasbq/supervisor/cmd/routing").CombinedOutput()
require.NoError(t, err, "build failed: %s", out)
return bin
}
func waitForPort(_ *testing.T, addr string, dur time.Duration) error {
deadline := time.Now().Add(dur)
for time.Now().Before(deadline) {
c, err := http.Get("http://" + addr + "/healthz") //nolint:noctx
if err == nil {
_ = c.Body.Close()
return nil
}
conn, err := http.NewRequest(http.MethodPost, "http://"+addr+"/mcp", strings.NewReader(`{}`))
if err == nil {
r, err := http.DefaultClient.Do(conn)
if err == nil {
_ = r.Body.Close()
return nil
}
}
time.Sleep(50 * time.Millisecond)
}
return context.DeadlineExceeded
}
func mcpCall(t *testing.T, url, body string) string {
t.Helper()
r, err := http.Post(url, "application/json", strings.NewReader(body)) //nolint:noctx
require.NoError(t, err)
defer func() { _ = r.Body.Close() }()
raw, err := io.ReadAll(r.Body)
require.NoError(t, err)
return string(raw)
}
// freePort grabs an OS-assigned TCP port and releases it. There is a small
// race window before the subprocess re-binds it, but it is acceptable for
// test isolation against a hardcoded port colliding with another test or
// stray process.
func freePort(t *testing.T) string {
t.Helper()
l, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
port := l.Addr().(*net.TCPAddr).Port
require.NoError(t, l.Close())
return strconv.Itoa(port)
}
-26
View File
@@ -1,26 +0,0 @@
# Model selection — first entry per skill is used.
# Override per-call by passing model in the MCP tool args.
# Model names come from LiteLLM /v1/models (host/name format).
default_chain:
- iguana/qwen3-coder-next
skills:
tdd:
chain:
- koala/qwen3-coder-30b
review:
chain:
- iguana/devstral
debug:
chain:
- iguana/deepseek-r1-14b
spec:
chain:
- koala/phi4-14b
retrospective:
chain:
- iguana/qwen3-coder-next
trainer:
chain:
- iguana/qwen3-coder-next
@@ -1051,7 +1051,7 @@ git push
```bash ```bash
# Poll until complete (replace RUN_ID with the new run): # Poll until complete (replace RUN_ID with the new run):
curl -s "https://gitea.d-ma.be/api/v1/repos/mathias/hyperguild/actions/runs?limit=2" \ curl -s "https://gitea.d-ma.be/api/v1/repos/mathias/hyperguild/actions/runs?limit=2" \
-H "Authorization: token 736a8c36adcc6ecb41fff56e5ae4d0eb3105a670" \ -H "Authorization: token <REDACTED-dead-gitea-pat-infra#344>" \
| python3 -c "import sys,json; [print(r['id'],r['status'],r.get('conclusion','—')) for r in json.load(sys.stdin)['workflow_runs']]" | python3 -c "import sys,json; [print(r['id'],r['status'],r.get('conclusion','—')) for r in json.load(sys.stdin)['workflow_runs']]"
``` ```
@@ -16,7 +16,7 @@ Three needs converge on a single small Go binary:
- [ ] `hyperguild tier` returns the same `tier.Info` that `internal/tier.Detect` produces for the same probe URLs, in < 3 s under all three tier conditions, with both human-readable and `--json` output. - [ ] `hyperguild tier` returns the same `tier.Info` that `internal/tier.Detect` produces for the same probe URLs, in < 3 s under all three tier conditions, with both human-readable and `--json` output.
- [ ] `hyperguild brain query <topic>` returns BM25 results from the brain HTTP REST `/query` endpoint, exit 0 on success and non-zero on transport failure. - [ ] `hyperguild brain query <topic>` returns BM25 results from the brain HTTP REST `/query` endpoint, exit 0 on success and non-zero on transport failure.
- [ ] `hyperguild brain write <type> <slug>` reads markdown content from stdin, posts to `/write` with the type and slug, and creates `brain/knowledge/<slug>.md`. A round-trip (`hyperguild brain query <slug>` immediately after) finds the entry. - [ ] `hyperguild brain write <wing> <hall> <slug>` reads markdown content from stdin, posts to `/write` with wing/hall/filename, and creates `brain/wiki/<wing>/<hall>/<slug>.md`. A round-trip (`hyperguild brain query <slug>` immediately after) finds the entry. (Updated post-ADR-0012/#79: the legacy `<type> <slug>` shape and the `brain/knowledge/` fallback were removed; wing and hall are now required.)
- [ ] `hyperguild mode <cloud|client-local|sovereign>` writes a parseable JSON file at the target path with the per-mode `mcpServers` entries; `jq -e .mcpServers` succeeds on the output. - [ ] `hyperguild mode <cloud|client-local|sovereign>` writes a parseable JSON file at the target path with the per-mode `mcpServers` entries; `jq -e .mcpServers` succeeds on the output.
- [ ] All commands print usage on `--help`, exit 2 on unknown flags, exit non-zero on operational errors. - [ ] All commands print usage on `--help`, exit 2 on unknown flags, exit non-zero on operational errors.
- [ ] `task check` passes (lint + test + vet) on each task and on the merged branch. - [ ] `task check` passes (lint + test + vet) on each task and on the merged branch.
@@ -50,7 +50,7 @@ Three needs converge on a single small Go binary:
- **`brain` subcommand calls the HTTP REST API.** Two nested subcommands: - **`brain` subcommand calls the HTTP REST API.** Two nested subcommands:
- `brain query <topic>` issues `POST /query` with JSON body `{query, limit}` (default `--limit 5`), prints results in human-readable form by default and with `--json` for machine consumption. - `brain query <topic>` issues `POST /query` with JSON body `{query, limit}` (default `--limit 5`), prints results in human-readable form by default and with `--json` for machine consumption.
- `brain write <type> <slug>` reads stdin, posts `POST /write` with JSON body `{type, slug, content}`, prints the resulting path on success. - `brain write <wing> <hall> <slug>` reads stdin, posts `POST /write` with JSON body `{wing, hall, filename, content}`, prints the resulting path on success. (Updated post-ADR-0012/#79: wing and hall are required, replacing the old `<type> <slug>` shape and the `brain/knowledge/` legacy fallback.)
Rationale: HTTP REST is simpler than MCP framing for a CLI. Per CLAUDE.md, the REST endpoints are documented as the official non-MCP interface. Rationale: HTTP REST is simpler than MCP framing for a CLI. Per CLAUDE.md, the REST endpoints are documented as the official non-MCP interface.
- **`mode <name>` writes a per-mode `.mcp.json` template.** Defaults to writing `./.mcp.json` (cwd); accepts `--out <path>`. Per-mode bodies: - **`mode <name>` writes a per-mode `.mcp.json` template.** Defaults to writing `./.mcp.json` (cwd); accepts `--out <path>`. Per-mode bodies:
+1 -1
View File
@@ -1,4 +1,4 @@
module github.com/mathiasbq/supervisor module git.d-ma.be/mathias/hyperguild
go 1.26.1 go 1.26.1
+53
View File
@@ -0,0 +1,53 @@
// Command frontmatterlint reports markdown notes whose YAML frontmatter does
// not parse, and optionally repairs the ones that only need quoting.
//
// go run ./cmd/frontmatterlint ../../brain # report
// go run ./cmd/frontmatterlint -fix ../../brain # repair in place
//
// Exit codes: 0 clean (or everything repaired), 1 findings remain, 2 the scan
// itself failed.
package main
import (
"flag"
"fmt"
"os"
"github.com/mathiasbq/hyperguild/ingestion/internal/frontmatter"
)
func main() {
fix := flag.Bool("fix", false, "repair files that quoting can rescue, in place")
flag.Parse()
root := "."
if flag.NArg() > 0 {
root = flag.Arg(0)
}
findings, err := frontmatter.Scan(root, *fix)
if err != nil {
fmt.Fprintln(os.Stderr, "frontmatterlint:", err)
os.Exit(2)
}
var unresolved int
for _, f := range findings {
if f.Repaired {
fmt.Printf("repaired %s\n", f.Path)
continue
}
unresolved++
fmt.Printf("BROKEN %s: %v\n", f.Path, f.Err)
}
if unresolved > 0 {
fmt.Fprintf(os.Stderr, "\n%d file(s) with unparseable frontmatter", unresolved)
if !*fix {
fmt.Fprint(os.Stderr, " — re-run with -fix")
}
fmt.Fprintln(os.Stderr)
os.Exit(1)
}
fmt.Printf("✓ frontmatter: %d file(s) repaired, none broken\n", len(findings))
}
+177 -39
View File
@@ -32,14 +32,36 @@ import (
"github.com/mathiasbq/hyperguild/ingestion/internal/pipeline" "github.com/mathiasbq/hyperguild/ingestion/internal/pipeline"
"github.com/mathiasbq/hyperguild/ingestion/internal/reranker" "github.com/mathiasbq/hyperguild/ingestion/internal/reranker"
"github.com/mathiasbq/hyperguild/ingestion/internal/search" "github.com/mathiasbq/hyperguild/ingestion/internal/search"
"github.com/mathiasbq/hyperguild/ingestion/internal/startupretry"
"github.com/mathiasbq/hyperguild/ingestion/internal/vectorstore" "github.com/mathiasbq/hyperguild/ingestion/internal/vectorstore"
"github.com/mathiasbq/hyperguild/ingestion/internal/watcher" "github.com/mathiasbq/hyperguild/ingestion/internal/watcher"
"github.com/mathiasbq/hyperguild/ingestion/internal/webhook"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
) )
// claudeSink converts each claudewatcher.Batch into one wiki note under // kubeClient builds an in-cluster Kubernetes client (falls back to
// brain/wiki/claude-sessions/facts/. v1 emits one note per session // $KUBECONFIG for local dev/testing against a real cluster).
// keyed by host + session id; classifier-driven hall routing is a func kubeClient() (kubernetes.Interface, error) {
// follow-up (hyperguild#27 v2). if cfg, err := rest.InClusterConfig(); err == nil {
return kubernetes.NewForConfig(cfg)
}
rules := clientcmd.NewDefaultClientConfigLoadingRules()
cc := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, &clientcmd.ConfigOverrides{})
cfg, err := cc.ClientConfig()
if err != nil {
return nil, fmt.Errorf("kube config (no in-cluster, no kubeconfig): %w", err)
}
return kubernetes.NewForConfig(cfg)
}
// claudeSink converts each claudewatcher.Batch into a raw session dump
// under brain/archive/claude-sessions/<host>/. Deliberately NOT a wiki
// note (api.WriteNote / brain/wiki/) — raw full transcripts out-ranked
// curated ai-sessions summaries in BM25 (177,818 vs 45,335 on the same
// query) and duplicated content already summarized elsewhere. Kept for
// deep lookups, never indexed. See ai-sessions#10.
type claudeSink struct { type claudeSink struct {
brainDir string brainDir string
logger *slog.Logger logger *slog.Logger
@@ -67,16 +89,14 @@ func (s *claudeSink) Ingest(ctx context.Context, b claudewatcher.Batch) error {
sb.WriteString("\n\n") sb.WriteString("\n\n")
} }
slug := "session-" + b.Host + "-" + b.SessionID slug := "session-" + b.Host + "-" + b.SessionID
if _, err := api.WriteNote(s.brainDir, api.WriteNoteOptions{ dest := filepath.Join(s.brainDir, "archive", "claude-sessions", b.Host, slug+".md")
Filename: slug, if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
Wing: "claude-sessions", return fmt.Errorf("create claude-sessions archive dir: %w", err)
Hall: "facts",
Type: "source",
Domain: b.ProjectID,
Content: sb.String(),
}); err != nil {
return fmt.Errorf("write claude session note: %w", err)
} }
if err := os.WriteFile(dest, []byte(sb.String()), 0o644); err != nil {
return fmt.Errorf("write claude session archive: %w", err)
}
s.logger.Debug("claude session archived (non-indexed)", "path", dest)
return nil return nil
} }
@@ -124,6 +144,47 @@ func envInt(key string, fallback int) int {
return fallback return fallback
} }
// buildNotifier returns the ntfy notifier, or a nil interface when
// BRAIN_NTFY_URL is unset. A nil *interface* (not a typed-nil) is required so
// DegradingSink/Reconcile and the governance observer skip it cleanly.
// alertingWarnings names every alert that will not fire under the current
// configuration (#107).
//
// buildNotifier returns a nil interface when BRAIN_NTFY_URL is unset, and every
// consumer skips a nil notifier silently — right for an unconfigured homelab,
// wrong for an alert whose entire value is that someone finds out. The cost of
// the silence is that "configured and working" and "never configured" are
// byte-identical in behaviour: no error, no warning, only a message that never
// arrives, which nobody notices because nobody is waiting for an alert they
// have never seen. Two alerts were dark in production for exactly that reason
// (#100), found by firing a real event rather than by reading anything.
//
// WARN rather than fatal, deliberately. The brain sibling rule
// (`empty-credential-must-refuse-to-start-not-switch-modes`) says an empty
// credential must be a startup error, never a silent mode switch — but that is
// about a control being removed. Here observability is degraded, not a gate
// bypassed, and refusing to boot would break the unconfigured-homelab case the
// nil notifier exists to support. What the rule does demand, and what this
// provides, is that the mode switch stops being silent.
//
// Pure and env-injected so the message is testable without a running server:
// the reason this gap survived is that nothing about it was observable.
func alertingWarnings(getenv func(string) string) []string {
var out []string
if getenv("BRAIN_NTFY_URL") == "" {
out = append(out, "alerting DISABLED: BRAIN_NTFY_URL unset — "+
"brain_edit_root governance rewrites and capture audit degradation will not notify")
}
return out
}
func buildNotifier() audit.Notifier {
if n := audit.NewNtfyNotifier(os.Getenv("BRAIN_NTFY_URL"), os.Getenv("BRAIN_NTFY_TOKEN")); n != nil {
return n
}
return nil
}
// buildAuditSink selects the capture audit sink. When BRAIN_LOKI_URL is // buildAuditSink selects the capture audit sink. When BRAIN_LOKI_URL is
// set it builds the classification-aware DegradingSink (loki central + // set it builds the classification-aware DegradingSink (loki central +
// durable file buffer + optional ntfy) and starts the reconcile loop; // durable file buffer + optional ntfy) and starts the reconcile loop;
@@ -141,12 +202,7 @@ func buildAuditSink(ctx context.Context, brainDir string, logger *slog.Logger) c
logger.Error("capture audit buffer init", "err", err) logger.Error("capture audit buffer init", "err", err)
os.Exit(1) os.Exit(1)
} }
// Keep notifier as a nil interface (not a typed-nil) when unconfigured notifier := buildNotifier()
// so DegradingSink/Reconcile skip it cleanly.
var notifier audit.Notifier
if n := audit.NewNtfyNotifier(os.Getenv("BRAIN_NTFY_URL"), os.Getenv("BRAIN_NTFY_TOKEN")); n != nil {
notifier = n
}
reconcileInterval := time.Duration(envInt("BRAIN_AUDIT_RECONCILE_INTERVAL", 60)) * time.Second reconcileInterval := time.Duration(envInt("BRAIN_AUDIT_RECONCILE_INTERVAL", 60)) * time.Second
audit.StartReconcile(ctx, central, buffer, notifier, reconcileInterval) audit.StartReconcile(ctx, central, buffer, notifier, reconcileInterval)
logger.Info("capture audit: loki+buffer sink", "loki", lokiURL, "reconcile_s", int(reconcileInterval.Seconds())) logger.Info("capture audit: loki+buffer sink", "loki", lokiURL, "reconcile_s", int(reconcileInterval.Seconds()))
@@ -178,6 +234,10 @@ func systemHostname() string {
func main() { func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
for _, w := range alertingWarnings(os.Getenv) {
logger.Warn(w)
}
brainDir := envOr("INGEST_BRAIN_DIR", "../brain") brainDir := envOr("INGEST_BRAIN_DIR", "../brain")
port := envOr("INGEST_PORT", "3300") port := envOr("INGEST_PORT", "3300")
@@ -211,6 +271,11 @@ func main() {
fallbackModel := envOr("BRAIN_LLM_FALLBACK_MODEL", "gemma4:31b") fallbackModel := envOr("BRAIN_LLM_FALLBACK_MODEL", "gemma4:31b")
router.Fallback = llm.New(fallbackURL, "", fallbackModel, timeout) router.Fallback = llm.New(fallbackURL, "", fallbackModel, timeout)
} }
if tertiaryURL := os.Getenv("BRAIN_LLM_TERTIARY_URL"); tertiaryURL != "" {
tertiaryModel := envOr("BRAIN_LLM_TERTIARY_MODEL", "gemini-2.5-flash")
tertiaryKey := os.Getenv("GEMINI_API_KEY")
router.Tertiary = llm.New(tertiaryURL, tertiaryKey, tertiaryModel, timeout)
}
answerComplete = router.Complete answerComplete = router.Complete
logger.Info("brain answer LLM configured", "primary", primaryURL, "model", primaryModel) logger.Info("brain answer LLM configured", "primary", primaryURL, "model", primaryModel)
} }
@@ -295,6 +360,36 @@ func main() {
} }
ctx := context.Background() ctx := context.Background()
// Built before the watcher, the graph backfill and session ingestion, and
// retried rather than fatal (#83). Two separate reasons:
//
// - On a cold cluster boot this pod can beat dex to serving and gets a
// 502 from ingress. Nothing is misconfigured; it simply started first.
// Exiting there meant CrashLoopBackOff redoing the backfill on every
// attempt, with exponential backoff stretching the brain outage.
// - Constructing it first means a genuine config error (wrong issuer,
// bad audience) fails in seconds instead of after all that work.
//
// The budget stays bounded: retrying forever would turn a misconfiguration
// into a process that looks alive and never serves.
jwtValidator, err := startupretry.Do(ctx,
startupretry.Policy{Attempts: 8, Base: time.Second, Max: 30 * time.Second},
func(ctx context.Context) (*chassisauth.JWTValidator, error) {
v, err := chassisauth.NewJWTValidator(ctx, os.Getenv("DEX_ISSUER_URL"), os.Getenv("MCP_AUDIENCE"))
if err != nil {
logger.Warn("oidc discovery not ready, retrying", "err", err)
}
return v, err
})
if err != nil {
logger.Error("build jwt validator", "err", err)
os.Exit(1)
}
if jwtValidator != nil {
logger.Info("jwt auth enabled", "issuer", os.Getenv("DEX_ISSUER_URL"))
}
if watchInterval > 0 { if watchInterval > 0 {
watcher.Start(ctx, watcher.Config{ watcher.Start(ctx, watcher.Config{
BrainDir: brainDir, BrainDir: brainDir,
@@ -336,15 +431,39 @@ func main() {
} }
host := envOr("CLAUDE_INGEST_HOST", systemHostname()) host := envOr("CLAUDE_INGEST_HOST", systemHostname())
interval := time.Duration(envInt("CLAUDE_INGEST_INTERVAL", 60)) * time.Second interval := time.Duration(envInt("CLAUDE_INGEST_INTERVAL", 60)) * time.Second
// Project directories excluded from ingestion entirely, as globs
// against the project directory name — e.g.
// "*cobalt-dingo*,*claude-worktrees-bridge-cse*".
//
// This is a veto list, deliberately named as one. It complements the
// client-name scrubber rather than replacing it: the scrubber drops
// individual TURNS whose content matches, while this never opens a
// project's files at all. Sessions working on live company financials
// are excluded here because their content is confidential in ways no
// pattern reliably recognises, and their learnings are captured
// deliberately through the session-close ritual instead.
//
// Caveat worth knowing: a project directory is derived from the
// session's WORKING DIRECTORY, not from the repositories it touches.
// A session run from ~/dev that happens to read a skipped repo will
// NOT be excluded by this. The scrubber remains the control for
// content; this is a control for whole workspaces.
skipProjects := splitList(os.Getenv("CLAUDE_INGEST_SKIP_PROJECTS"))
if len(skipProjects) > 0 {
logger.Info("claudewatcher: projects excluded from ingestion", "patterns", skipProjects)
}
sink := &claudeSink{brainDir: brainDir, logger: logger} sink := &claudeSink{brainDir: brainDir, logger: logger}
go func() { go func() {
if err := claudewatcher.Watch(ctx, claudewatcher.Config{ if err := claudewatcher.Watch(ctx, claudewatcher.Config{
SessionsDir: claudeDir, SessionsDir: claudeDir,
Host: host, Host: host,
Interval: interval, Interval: interval,
Sink: sink, Sink: sink,
Cursors: cursorStore, Cursors: cursorStore,
Logger: logger, Logger: logger,
SkipProjects: skipProjects,
}); err != nil && err != context.Canceled { }); err != nil && err != context.Canceled {
logger.Error("claudewatcher exited", "err", err) logger.Error("claudewatcher exited", "err", err)
} }
@@ -352,6 +471,29 @@ func main() {
logger.Info("claudewatcher started", logger.Info("claudewatcher started",
"sessions_dir", claudeDir, "host", host, "interval", interval) "sessions_dir", claudeDir, "host", host, "interval", interval)
} }
// Gitea push webhook -> on-demand brain-sync Job, instead of waiting up
// to 15 minutes for the next CronJob poll. Off by default (opt in via
// GITEA_WEBHOOK_SECRET) since it needs Job-create RBAC in the "brain"
// namespace that a fresh deploy won't have granted yet.
var webhookHandler *webhook.Handler
if webhookSecret := os.Getenv("GITEA_WEBHOOK_SECRET"); webhookSecret != "" {
kc, err := kubeClient()
if err != nil {
logger.Error("brain-sync webhook: kube client", "err", err)
os.Exit(1)
}
webhookHandler = &webhook.Handler{
Secret: webhookSecret,
Clientset: kc,
Namespace: envOr("BRAIN_SYNC_NAMESPACE", "brain"),
CronJobName: envOr("BRAIN_SYNC_CRONJOB", "brain-sync"),
WatchRepo: envOr("BRAIN_SYNC_WATCH_REPO", "mathias/brain"),
Logger: logger,
}
logger.Info("brain-sync webhook enabled", "namespace", webhookHandler.Namespace, "cronjob", webhookHandler.CronJobName)
}
if vectorStore != nil { if vectorStore != nil {
embedSyncInterval := envInt("BRAIN_EMBED_SYNC_INTERVAL", 300) embedSyncInterval := envInt("BRAIN_EMBED_SYNC_INTERVAL", 300)
vectorstore.StartSync(ctx, brainDir, vectorStore, vectorstore.StartSync(ctx, brainDir, vectorStore,
@@ -373,15 +515,9 @@ func main() {
mux.HandleFunc("POST /promote", h.Promote) mux.HandleFunc("POST /promote", h.Promote)
mux.HandleFunc("POST /backfill-embeddings", h.BackfillEmbeddings) mux.HandleFunc("POST /backfill-embeddings", h.BackfillEmbeddings)
mux.HandleFunc("GET /pass-rate", h.PassRate) mux.HandleFunc("GET /pass-rate", h.PassRate)
jwtValidator, err := chassisauth.NewJWTValidator(ctx, os.Getenv("DEX_ISSUER_URL"), os.Getenv("MCP_AUDIENCE")) if webhookHandler != nil {
if err != nil { mux.Handle("POST /webhooks/brain-sync", webhookHandler)
logger.Error("build jwt validator", "err", err)
os.Exit(1)
} }
if jwtValidator != nil {
logger.Info("jwt auth enabled", "issuer", os.Getenv("DEX_ISSUER_URL"))
}
// Resource-metadata URL is only emitted on 401 when Dex OAuth is // Resource-metadata URL is only emitted on 401 when Dex OAuth is
// configured. Static-Bearer-only deployments leave this empty so // configured. Static-Bearer-only deployments leave this empty so
// clients never see an OAuth challenge. // clients never see an OAuth challenge.
@@ -412,12 +548,8 @@ func main() {
os.Exit(1) os.Exit(1)
} }
auditSink := buildAuditSink(ctx, brainDir, logger) auditSink := buildAuditSink(ctx, brainDir, logger)
// The Gitea client also satisfies SummaryWriter (#66): session
// summaries are written to mathias/ai-sessions over the same API
// token. nil only if a future tracker impl lacks file writes.
summaryWriter, _ := tracker.(capture.SummaryWriter)
captureSvc := capture.NewService( captureSvc := capture.NewService(
mcpSrv.BrainStore(), tracker, summaryWriter, classCfg, auditSink) mcpSrv.BrainStore(), tracker, classCfg, auditSink)
sovereign := splitList(os.Getenv("BRAIN_CAPTURE_SOVEREIGN_PRINCIPALS")) sovereign := splitList(os.Getenv("BRAIN_CAPTURE_SOVEREIGN_PRINCIPALS"))
resolver := capturehttp.NewOriginResolver(sovereign) resolver := capturehttp.NewOriginResolver(sovereign)
captureH := capturehttp.New(captureSvc, jwtValidator, mcpToken, "local-cli", resolver) captureH := capturehttp.New(captureSvc, jwtValidator, mcpToken, "local-cli", resolver)
@@ -427,7 +559,13 @@ func main() {
// the existing /mcp OAuth connector. mcpSrv is already wrapped above; // the existing /mcp OAuth connector. mcpSrv is already wrapped above;
// WithCapture mutates the same instance, so the tool appears live. // WithCapture mutates the same instance, so the tool appears live.
mcpSrv.WithCapture(captureSvc, jwtValidator, mcpToken, "local-cli", resolver) mcpSrv.WithCapture(captureSvc, jwtValidator, mcpToken, "local-cli", resolver)
logger.Info("capture enabled (REST + MCP tool)", "sovereign_principals", len(sovereign)) // hyperguild#97: a governance-file rewrite gets the same trail a
// capture already gets, plus an out-of-band alert. Wired here because
// brain_edit_root needs the capture plumbing anyway — that is what
// re-derives the static principal its gate checks.
mcpSrv.WithGovernanceObserver(auditSink, buildNotifier())
logger.Info("capture enabled (REST + MCP tool)", "sovereign_principals", len(sovereign),
"governance_observer", true)
} else { } else {
logger.Info("capture endpoint disabled (BRAIN_GITEA_TOKEN unset)") logger.Info("capture endpoint disabled (BRAIN_GITEA_TOKEN unset)")
} }
+78
View File
@@ -0,0 +1,78 @@
// ingestion/cmd/server/main_test.go
package main
import (
"context"
"log/slog"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/mathiasbq/hyperguild/ingestion/internal/claudewatcher"
)
func TestClaudeSink_IngestWritesToNonIndexedArchiveNotWiki(t *testing.T) {
dir := t.TempDir()
sink := &claudeSink{brainDir: dir, logger: slog.New(slog.NewTextHandler(os.Stderr, nil))}
err := sink.Ingest(context.Background(), claudewatcher.Batch{
Host: "koala",
FilePath: "/host-home-claude/projects/-home-mathias-dev/abc.jsonl",
SessionID: "abc",
ProjectID: "-home-mathias-dev",
Turns: []claudewatcher.Turn{
{Type: "assistant", Content: "did a thing"},
},
})
require.NoError(t, err)
got, err := os.ReadFile(filepath.Join(dir, "archive", "claude-sessions", "koala", "session-koala-abc.md"))
require.NoError(t, err, "raw session dump must land in the non-indexed archive")
assert.Contains(t, string(got), "did a thing")
_, err = os.Stat(filepath.Join(dir, "wiki", "claude-sessions"))
assert.True(t, os.IsNotExist(err), "raw transcripts must never land under wiki/ (ai-sessions#10 — BM25 pollution)")
}
// --- #107: an unconfigured alert must announce itself ----------------------
func TestAlertingWarnings(t *testing.T) {
tests := []struct {
name string
env map[string]string
want []string // substrings that must appear across the warnings
none bool // true = expect no warnings at all
}{
{
// The failure this exists to prevent: two alerts dark in
// production, discovered only by firing a real event and watching
// nothing arrive (#100).
name: "notifier unconfigured names what will not fire",
env: map[string]string{},
want: []string{"BRAIN_NTFY_URL", "brain_edit_root", "audit"},
},
{
name: "configured notifier is silent",
env: map[string]string{"BRAIN_NTFY_URL": "http://ntfy/brain-alerts"},
none: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := alertingWarnings(func(k string) string { return tt.env[k] })
if tt.none {
assert.Empty(t, got)
return
}
joined := strings.Join(got, " ")
for _, w := range tt.want {
assert.Contains(t, joined, w)
}
})
}
}
+44 -4
View File
@@ -2,17 +2,57 @@ module github.com/mathiasbq/hyperguild/ingestion
go 1.26.1 go 1.26.1
require github.com/stretchr/testify v1.11.1 require (
github.com/stretchr/testify v1.11.1
k8s.io/api v0.31.3
k8s.io/apimachinery v0.31.3
k8s.io/client-go v0.31.3
)
require ( require (
github.com/kr/text v0.2.0 // indirect github.com/emicklei/go-restful/v3 v3.11.0 // indirect
github.com/fxamacker/cbor/v2 v2.7.0 // indirect
github.com/go-logr/logr v1.4.2 // indirect
github.com/go-openapi/jsonpointer v0.19.6 // indirect
github.com/go-openapi/jsonreference v0.20.2 // indirect
github.com/go-openapi/swag v0.22.4 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/google/gnostic-models v0.6.8 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/google/gofuzz v1.2.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/imdario/mergo v0.3.6 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/lestrrat-go/jwx/v2 v2.1.6 // indirect github.com/lestrrat-go/jwx/v2 v2.1.6 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/rogpeppe/go-internal v1.15.0 // indirect github.com/rogpeppe/go-internal v1.15.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/x448/float16 v0.8.4 // indirect
golang.org/x/net v0.26.0 // indirect
golang.org/x/oauth2 v0.21.0 // indirect
golang.org/x/term v0.28.0 // indirect
golang.org/x/time v0.3.0 // indirect
google.golang.org/protobuf v1.34.2 // indirect
gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
k8s.io/klog/v2 v2.130.1 // indirect
k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340 // indirect
k8s.io/utils v0.0.0-20240711033017-18e509b52bc8 // indirect
sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect
sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect
sigs.k8s.io/yaml v1.4.0 // indirect
) )
require ( require (
git.d-ma.be/mathias/mcp-chassis v0.2.0 git.d-ma.be/mathias/mcp-chassis v0.2.0
github.com/davecgh/go-spew v1.1.1 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect
github.com/goccy/go-json v0.10.3 // indirect github.com/goccy/go-json v0.10.3 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect
@@ -24,7 +64,7 @@ require (
github.com/lestrrat-go/httprc v1.0.6 // indirect github.com/lestrrat-go/httprc v1.0.6 // indirect
github.com/lestrrat-go/iter v1.0.2 // indirect github.com/lestrrat-go/iter v1.0.2 // indirect
github.com/lestrrat-go/option v1.0.1 // indirect github.com/lestrrat-go/option v1.0.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/segmentio/asm v1.2.0 // indirect github.com/segmentio/asm v1.2.0 // indirect
golang.org/x/crypto v0.32.0 // indirect golang.org/x/crypto v0.32.0 // indirect
golang.org/x/sync v0.17.0 // indirect golang.org/x/sync v0.17.0 // indirect
+135 -4
View File
@@ -2,12 +2,46 @@ git.d-ma.be/mathias/mcp-chassis v0.2.0 h1:6fLmb7xqRa2nNVWsHaUbbfbArgDXJw/gDhb09c
git.d-ma.be/mathias/mcp-chassis v0.2.0/go.mod h1:Ks7EK2UnGAN0H3rJjKUxUagX8/ZBdtLrOlcUbv0RwH8= git.d-ma.be/mathias/mcp-chassis v0.2.0/go.mod h1:Ks7EK2UnGAN0H3rJjKUxUagX8/ZBdtLrOlcUbv0RwH8=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 h1:NMZiJj8QnKe1LgsbDayM4UoHwbvwDRwnI3hwNaAHRnc= github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 h1:NMZiJj8QnKe1LgsbDayM4UoHwbvwDRwnI3hwNaAHRnc=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40= github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40=
github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxERmMY4rD+g=
github.com/emicklei/go-restful/v3 v3.11.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc=
github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E=
github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ=
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-openapi/jsonpointer v0.19.6 h1:eCs3fxoIi3Wh6vtgmLTOjdhSpiqphQ+DaPn38N2ZdrE=
github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs=
github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2KvnJRumpMGbE=
github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k=
github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14=
github.com/go-openapi/swag v0.22.4 h1:QLMzNJnMGPRNDCbySlcj1x01tzU8/9LTTL9hZZZogBU=
github.com/go-openapi/swag v0.22.4/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14=
github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI=
github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8=
github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA= github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA=
github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/gnostic-models v0.6.8 h1:yo/ABAfM5IMRsS1VnXjTBvUb61tFIHozhlYvRgGre9I=
github.com/google/gnostic-models v0.6.8/go.mod h1:5n7qKqH0f5wFt+aWF8CW6pZLLNOfYuF5OpfBSENuI8U=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/pprof v0.0.0-20240525223248-4bfdf5a9a2af h1:kmjWCqn2qkEml422C2Rrd27c3VGxi6a/6HNq8QmHRKM=
github.com/google/pprof v0.0.0-20240525223248-4bfdf5a9a2af/go.mod h1:K1liHPHnj73Fdn/EKuT8nrFqBihUSKXoLYU0BuatOYo=
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/imdario/mergo v0.3.6 h1:xTNEAn+kxVO7dTZGu0CegyqKZmoWFI0rF8UxjlB2d28=
github.com/imdario/mergo v0.3.6/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
@@ -16,8 +50,17 @@ github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw=
github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/lestrrat-go/blackmagic v1.0.3 h1:94HXkVLxkZO9vJI/w2u1T0DAoprShFd13xtnSINtDWs= github.com/lestrrat-go/blackmagic v1.0.3 h1:94HXkVLxkZO9vJI/w2u1T0DAoprShFd13xtnSINtDWs=
@@ -32,30 +75,118 @@ github.com/lestrrat-go/jwx/v2 v2.1.6 h1:hxM1gfDILk/l5ylers6BX/Eq1m/pnxe9NBwW6lVf
github.com/lestrrat-go/jwx/v2 v2.1.6/go.mod h1:Y722kU5r/8mV7fYDifjug0r8FK8mZdw0K0GpJw/l8pU= github.com/lestrrat-go/jwx/v2 v2.1.6/go.mod h1:Y722kU5r/8mV7fYDifjug0r8FK8mZdw0K0GpJw/l8pU=
github.com/lestrrat-go/option v1.0.1 h1:oAzP2fvZGQKWkvHa1/SAcFolBEca1oN+mQ7eooNBEYU= github.com/lestrrat-go/option v1.0.1 h1:oAzP2fvZGQKWkvHa1/SAcFolBEca1oN+mQ7eooNBEYU=
github.com/lestrrat-go/option v1.0.1/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I= github.com/lestrrat-go/option v1.0.1/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/onsi/ginkgo/v2 v2.19.0 h1:9Cnnf7UHo57Hy3k6/m5k3dRfGTMXGvxhHFvkDTCTpvA=
github.com/onsi/ginkgo/v2 v2.19.0/go.mod h1:rlwLi9PilAFJ8jCg9UE1QP6VBpd6/xj3SRC0d6TU0To=
github.com/onsi/gomega v1.19.0 h1:4ieX6qQjPP/BfC3mpsAtIGGlxTWPeA3Inl/7DtXw1tw=
github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.15.0 h1:D0RCU5rMAp+SpgkiNdrjfJ+LX4J1M32V2NeCY7EJ6hc= github.com/rogpeppe/go-internal v1.15.0 h1:D0RCU5rMAp+SpgkiNdrjfJ+LX4J1M32V2NeCY7EJ6hc=
github.com/rogpeppe/go-internal v1.15.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs= github.com/rogpeppe/go-internal v1.15.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs=
github.com/segmentio/asm v1.2.0 h1:9BQrFxC+YOHJlTlHGkTrFWf59nbL3XnCoFLTwDCI7ys= github.com/segmentio/asm v1.2.0 h1:9BQrFxC+YOHJlTlHGkTrFWf59nbL3XnCoFLTwDCI7ys=
github.com/segmentio/asm v1.2.0/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs= github.com/segmentio/asm v1.2.0/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
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/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc= golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc=
golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc= golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
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-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.26.0 h1:soB7SVo0PWrY4vPW/+ay0jKDNScG2X9wFeYlXIvJsOQ=
golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE=
golang.org/x/oauth2 v0.21.0 h1:tsimM75w1tF/uws5rbeHzIWxEqElMehnc+iW793zsZs=
golang.org/x/oauth2 v0.21.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
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.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.28.0 h1:/Ts8HFuMR2E6IP/jlo7QVLZHggjKQbhu/7H0LJFr3Gg=
golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek=
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/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4=
golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
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-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg=
golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s=
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-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/evanphx/json-patch.v4 v4.12.0 h1:n6jtcsulIzXPJaxegRbvFNNrZDjbij7ny3gmSPG+6V4=
gopkg.in/evanphx/json-patch.v4 v4.12.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M=
gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc=
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
k8s.io/api v0.31.3 h1:umzm5o8lFbdN/hIXbrK9oRpOproJO62CV1zqxXrLgk8=
k8s.io/api v0.31.3/go.mod h1:UJrkIp9pnMOI9K2nlL6vwpxRzzEX5sWgn8kGQe92kCE=
k8s.io/apimachinery v0.31.3 h1:6l0WhcYgasZ/wk9ktLq5vLaoXJJr5ts6lkaQzgeYPq4=
k8s.io/apimachinery v0.31.3/go.mod h1:rsPdaZJfTfLsNJSQzNHQvYoTmxhoOEofxtOsF3rtsMo=
k8s.io/client-go v0.31.3 h1:CAlZuM+PH2cm+86LOBemaJI/lQ5linJ6UFxKX/SoG+4=
k8s.io/client-go v0.31.3/go.mod h1:2CgjPUTpv3fE5dNygAr2NcM8nhHzXvxB8KL5gYc3kJs=
k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk=
k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE=
k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340 h1:BZqlfIlq5YbRMFko6/PM7FjZpUb45WallggurYhKGag=
k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340/go.mod h1:yD4MZYeKMBwQKVht279WycxKyM84kkAx2DPrTXaeb98=
k8s.io/utils v0.0.0-20240711033017-18e509b52bc8 h1:pUdcCO1Lk/tbT5ztQWOBi5HBgbBP1J8+AsQnQCKsi8A=
k8s.io/utils v0.0.0-20240711033017-18e509b52bc8/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0=
sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo=
sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0=
sigs.k8s.io/structured-merge-diff/v4 v4.4.1 h1:150L+0vs/8DA78h1u02ooW1/fFq/Lwr+sGiqlzvrtq4=
sigs.k8s.io/structured-merge-diff/v4 v4.4.1/go.mod h1:N8hJocpFajUSSeSJ9bOZ77VzejKZaXsTtZo4/u7Io08=
sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E=
sigs.k8s.io/yaml v1.4.0/go.mod h1:Ejl7/uTz7PSA4eKMyQCUTnhZYNmLIl+5c2lQPGR2BPY=
+44 -12
View File
@@ -1,6 +1,12 @@
package api package api
import "strings" import (
"strings"
// Aliased: this package's own frontmatter type (below) would collide
// with the imported package's name otherwise.
sharedfm "github.com/mathiasbq/hyperguild/ingestion/internal/frontmatter"
)
// frontmatter is an ordered, line-preserving view of a note's YAML // frontmatter is an ordered, line-preserving view of a note's YAML
// frontmatter block. It deliberately avoids a full YAML round-trip: the // frontmatter block. It deliberately avoids a full YAML round-trip: the
@@ -25,21 +31,37 @@ type fmLine struct {
// frontmatter block is recognised only when the file opens with a `---` // frontmatter block is recognised only when the file opens with a `---`
// fence and a closing `---` fence follows. Otherwise the whole input is // fence and a closing `---` fence follows. Otherwise the whole input is
// the body and the returned frontmatter is empty. // the body and the returned frontmatter is empty.
//
// Fence detection itself is frontmatter.Split (hyperguild#138) — this
// package's own contribution is purely the ordered, line-preserving fmLine
// shape below, which a shared parser has no business owning since it's
// specific to how brain_update does a surgical, byte-round-trip edit.
func parseFrontmatter(src string) (frontmatter, string) { func parseFrontmatter(src string) (frontmatter, string) {
var fm frontmatter var fm frontmatter
if !strings.HasPrefix(src, "---\n") { blockBytes, restBytes, ok := sharedfm.Split([]byte(src))
if !ok {
return fm, src return fm, src
} }
rest := src[len("---\n"):] // sharedfm.Split's block/rest boundary sits one byte earlier than this
end := strings.Index(rest, "\n---\n") // package's always has: block keeps the "\n" immediately before the
if end < 0 { // closing fence, and rest keeps the "\n" immediately after it (both by
// Opening fence with no closing fence — treat as bodyless content. // design, for Fix's own reconstruction). This package's block/body
return fm, src // never included either — TrimSuffix/TrimPrefix restore that exact
} // boundary. Split guarantees ok=true only when "\n---\n" matched, so
block := rest[:end] // both trims are always exactly one byte, never ambiguous.
body := rest[end+len("\n---\n"):] block := strings.TrimSuffix(string(blockBytes), "\n")
body := strings.TrimPrefix(string(restBytes), "\n")
for _, line := range strings.Split(block, "\n") { for _, line := range strings.Split(block, "\n") {
// An indented line is a continuation (a YAML block-list item, a
// wrapped value) never a top-level key, regardless of whether it
// happens to contain a colon — " - 'Chapter 3: The Reckoning'" is
// not a key named "- 'Chapter 3" (hyperguild#128). Checked before
// Cut so a colon inside one never reaches the key/value path.
if line != "" && (line[0] == ' ' || line[0] == '\t') {
fm.lines = append(fm.lines, fmLine{raw: line})
continue
}
key, val, ok := strings.Cut(line, ":") key, val, ok := strings.Cut(line, ":")
key = strings.TrimSpace(key) key = strings.TrimSpace(key)
if !ok || key == "" || strings.HasPrefix(strings.TrimSpace(line), "#") { if !ok || key == "" || strings.HasPrefix(strings.TrimSpace(line), "#") {
@@ -83,9 +105,19 @@ func (f *frontmatter) render() string {
var b strings.Builder var b strings.Builder
b.WriteString("---\n") b.WriteString("---\n")
for _, l := range f.lines { for _, l := range f.lines {
if l.key == "" { switch {
case l.key == "":
b.WriteString(l.raw) b.WriteString(l.raw)
} else { case l.value == "":
// A key with nothing after the colon (the YAML block-list
// shape: "aliases:" followed by indented "- item" lines on
// their own raw lines) must stay bare — "key: " with a
// trailing space is a different byte sequence than the
// original, and this type's whole purpose (see the package
// doc) is a byte-preserving round-trip.
b.WriteString(l.key)
b.WriteByte(':')
default:
b.WriteString(l.key) b.WriteString(l.key)
b.WriteString(": ") b.WriteString(": ")
b.WriteString(l.value) b.WriteString(l.value)
@@ -59,3 +59,37 @@ func TestFrontmatterRenderRoundTrips(t *testing.T) {
fm, _ := parseFrontmatter(src) fm, _ := parseFrontmatter(src)
assert.Equal(t, src, fm.render()) assert.Equal(t, src, fm.render())
} }
func TestParseFrontmatterIndentedListItemWithColonIsNotMisparsedAsKey(t *testing.T) {
// hyperguild#128: an indented YAML block-list item that happens to
// contain a colon (e.g. a title with a subtitle) is a continuation
// line, never a top-level key — strings.Cut doesn't know that just
// because TrimSpace(key) happens to be non-empty. Misparsing it as a
// key/value pair and re-rendering strips its indentation, de-indenting
// it out of the list it belongs to. Same bug class already found and
// fixed in the sibling internal/wiki package's parseFrontmatterBlock
// (hyperguild#126 review round 3) — this package was the original the
// reimplementation was modeled on and had the gap too.
src := "---\naliases:\n - 'Chapter 3: The Reckoning'\ntitle: 'X'\n---\nbody\n"
fm, _ := parseFrontmatter(src)
fm.set("updated_at", "2026-09-23T00:00:00Z")
out := fm.render()
assert.Contains(t, out, " - 'Chapter 3: The Reckoning'",
"the indented list item must survive verbatim, not get re-emitted as a de-indented fake key")
assert.NotContains(t, out, "\n- 'Chapter 3",
"must not be split into a fake key/value pair at column 0 (as opposed to surviving indented, asserted above)")
}
func TestFrontmatterRenderEmptyValueKeyStaysBareNoTrailingSpace(t *testing.T) {
// Companion to the indented-list-item fix: "aliases:" (a key with
// nothing after the colon, the YAML block-list header) must round-trip
// bare, not as "aliases: " with a trailing space — a different byte
// sequence than the original, breaking this type's whole reason for
// being a line-preserving view rather than a YAML re-marshal.
// render() returns only the frontmatter block (see
// TestFrontmatterRenderRoundTrips), no trailing body.
src := "---\naliases:\n - one\n - two\n---\n"
fm, _ := parseFrontmatter(src)
assert.Equal(t, src, fm.render())
}
+158 -82
View File
@@ -12,6 +12,7 @@ import (
"time" "time"
"github.com/mathiasbq/hyperguild/ingestion/internal/brain" "github.com/mathiasbq/hyperguild/ingestion/internal/brain"
"github.com/mathiasbq/hyperguild/ingestion/internal/claim"
"github.com/mathiasbq/hyperguild/ingestion/internal/extract" "github.com/mathiasbq/hyperguild/ingestion/internal/extract"
"github.com/mathiasbq/hyperguild/ingestion/internal/pipeline" "github.com/mathiasbq/hyperguild/ingestion/internal/pipeline"
"github.com/mathiasbq/hyperguild/ingestion/internal/search" "github.com/mathiasbq/hyperguild/ingestion/internal/search"
@@ -51,12 +52,11 @@ type queryRequest struct {
} }
type writeRequest struct { type writeRequest struct {
Content string `json:"content"` Content string `json:"content"`
Filename string `json:"filename,omitempty"` Filename string `json:"filename,omitempty"`
Type string `json:"type,omitempty"` Wing string `json:"wing,omitempty"`
Domain string `json:"domain,omitempty"` Hall string `json:"hall,omitempty"`
Wing string `json:"wing,omitempty"` SourceType string `json:"source_type,omitempty"` // "external" opts a hall=facts entry out of the internal default
Hall string `json:"hall,omitempty"`
} }
type ingestRequest struct { type ingestRequest struct {
@@ -108,19 +108,16 @@ func (h *Handler) Query(w http.ResponseWriter, r *http.Request) {
// WriteNoteOptions configures how a brain note is written. // WriteNoteOptions configures how a brain note is written.
// //
// When both Wing and Hall are non-empty, the note routes into the // Wing and Hall are both required: the note routes into the structured
// structured wiki at brain/wiki/<wing>/<hall>/<slug>.md and gets // wiki at brain/wiki/<wing>/<hall>/<slug>.md and gets wing/hall/created_at
// wing/hall/created_at injected into its YAML frontmatter. // injected into its YAML frontmatter. There is no other valid destination
// // (the legacy brain/knowledge/ fallback was removed — ADR-0012 / #79).
// When either is empty, the note falls back to brain/knowledge/<filename>
// with optional type/domain frontmatter (legacy behaviour).
type WriteNoteOptions struct { type WriteNoteOptions struct {
Content string Content string
Filename string Filename string
Type string Wing string
Domain string Hall string
Wing string SourceType string // "internal" marks a first-party observation (e.g. claudewatcher) that needs no external citation
Hall string
} }
// WriteNote writes a markdown note into the brain. Returns the path // WriteNote writes a markdown note into the brain. Returns the path
@@ -129,14 +126,21 @@ func WriteNote(brainDir string, opts WriteNoteOptions) (string, error) {
if opts.Content == "" { if opts.Content == "" {
return "", fmt.Errorf("content is required") return "", fmt.Errorf("content is required")
} }
if opts.Wing == "" || opts.Hall == "" {
return "", fmt.Errorf("wing and hall are required")
}
if opts.Wing != "" && opts.Hall != "" { // In the primitive, not in a caller: POST /write reaches here directly,
return writeHallNote(brainDir, opts) // without the BrainStore, and a gate one door wide is not a gate.
// BrainStore still calls the strip itself to report Ref.Unlinked; the
// second pass is a no-op on already-clean content.
clean, _, err := brain.StripUnresolvedLinks(brainDir, opts.Content)
if err != nil {
return "", err
} }
if opts.Wing != "" || opts.Hall != "" { opts.Content = clean
return "", fmt.Errorf("wing and hall must be set together")
} return writeHallNote(brainDir, opts)
return writeLegacyNote(brainDir, opts)
} }
// writeHallNote routes a note into brain/wiki/<wing>/<hall>/ and injects // writeHallNote routes a note into brain/wiki/<wing>/<hall>/ and injects
@@ -150,77 +154,141 @@ func writeHallNote(brainDir string, opts WriteNoteOptions) (string, error) {
if err != nil { if err != nil {
return "", err return "", err
} }
existingFields, body := splitFrontmatter(opts.Content)
existingByKey := make(map[string]frontmatterField, len(existingFields))
for _, f := range existingFields {
existingByKey[f.key] = f
}
// Validate the claim-property envelope BEFORE creating the directory, so a
// rejected write leaves nothing behind — not even an empty hall dir
// (brain#21). Fail closed: a value outside the enum is worse than an absent
// one, because a lint skips what it cannot parse and the note then reads as
// classified while nothing acts on it.
if err := claim.ValidateEnvelope(scalarValues(existingFields)); err != nil {
return "", fmt.Errorf("claim envelope: %w", err)
}
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil { if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
return "", fmt.Errorf("create hall dir: %w", err) return "", fmt.Errorf("create hall dir: %w", err)
} }
emitted := make(map[string]bool, 6)
var fm strings.Builder var fm strings.Builder
fm.WriteString("---\n") fm.WriteString("---\n")
fmt.Fprintf(&fm, "wing: %s\n", brain.Sanitise(opts.Wing)) fmt.Fprintf(&fm, "wing: %s\n", brain.Sanitise(opts.Wing))
fmt.Fprintf(&fm, "hall: %s\n", opts.Hall) fmt.Fprintf(&fm, "hall: %s\n", opts.Hall)
fmt.Fprintf(&fm, "created_at: %s\n", time.Now().UTC().Format(time.RFC3339)) fmt.Fprintf(&fm, "created_at: %s\n", time.Now().UTC().Format(time.RFC3339))
if opts.Type != "" { emitted["wing"], emitted["hall"], emitted["created_at"] = true, true, true
fmt.Fprintf(&fm, "type: %s\n", opts.Type)
// writeField merges one key: opts.Content's own value (if the note already
// carries this field in its own frontmatter) always wins over the fallback,
// so promotion/extraction-step metadata survives verbatim instead of being
// shadowed by a second, stacked frontmatter block (#86).
writeField := func(key, fallback string) {
emitted[key] = true
if f, ok := existingByKey[key]; ok {
for _, line := range f.lines {
fm.WriteString(line)
fm.WriteString("\n")
}
return
}
if fallback != "" {
fmt.Fprintf(&fm, "%s: %s\n", key, fallback)
}
} }
if opts.Domain != "" { sourceType := opts.SourceType
fmt.Fprintf(&fm, "domain: %s\n", opts.Domain) if sourceType == "" && opts.Hall == "facts" {
// Most hall=facts entries are first-party (an eval/benchmark the
// writer ran itself), not external claims — default to internal and
// require an explicit source_type: external opt-out for the rare
// citation-needing entry (brain-gardener#7).
sourceType = "internal"
}
writeField("source_type", sourceType)
for _, f := range existingFields {
if emitted[f.key] {
continue
}
for _, line := range f.lines {
fm.WriteString(line)
fm.WriteString("\n")
}
} }
fm.WriteString("---\n") fm.WriteString("---\n")
if err := os.WriteFile(dest, []byte(fm.String()+opts.Content), 0o644); err != nil { if err := os.WriteFile(dest, []byte(fm.String()+body), 0o644); err != nil {
return "", fmt.Errorf("write: %w", err) return "", fmt.Errorf("write: %w", err)
} }
rel, _ := filepath.Rel(brainDir, dest) rel, _ := filepath.Rel(brainDir, dest)
return filepath.ToSlash(rel), nil return filepath.ToSlash(rel), nil
} }
// writeLegacyNote preserves the original brain/knowledge/ behaviour for // scalarValues flattens frontmatter fields to key -> scalar value for
// callers that have not adopted the wing/hall taxonomy. // validation. Multi-line values (lists, nested blocks) yield the text after
func writeLegacyNote(brainDir string, opts WriteNoteOptions) (string, error) { // the colon on the first line, which is empty for a list — correct here,
filename := opts.Filename // since every claim-property field is a scalar enum.
if filename == "" { func scalarValues(fields []frontmatterField) map[string]string {
filename = fmt.Sprintf("%s-auto.md", time.Now().UTC().Format("2006-01-02-150405")) out := make(map[string]string, len(fields))
} for _, f := range fields {
if len(f.lines) == 0 {
rawDir := filepath.Join(brainDir, "knowledge") continue
if err := os.MkdirAll(rawDir, 0o755); err != nil {
return "", fmt.Errorf("create raw dir: %w", err)
}
finalContent := opts.Content
if opts.Type != "" || opts.Domain != "" {
var fm strings.Builder
fm.WriteString("---\n")
if opts.Type != "" {
fmt.Fprintf(&fm, "type: %s\n", opts.Type)
} }
if opts.Domain != "" { _, value, found := strings.Cut(f.lines[0], ":")
fmt.Fprintf(&fm, "domain: %s\n", opts.Domain) if !found {
continue
} }
fm.WriteString("---\n") out[f.key] = strings.TrimSpace(value)
finalContent = fm.String() + opts.Content
} }
return out
if strings.ContainsAny(filename, `/\`) {
return "", fmt.Errorf("invalid filename")
}
base := filepath.Base(filename)
if base == "." || base == ".." || base == "" {
return "", fmt.Errorf("invalid filename")
}
if !strings.HasSuffix(base, ".md") {
base += ".md"
}
dest := filepath.Join(rawDir, base)
if err := os.WriteFile(dest, []byte(finalContent), 0o644); err != nil {
return "", fmt.Errorf("write: %w", err)
}
rel, _ := filepath.Rel(brainDir, dest)
return filepath.ToSlash(rel), nil
} }
// Write handles POST /write — write raw content to brain/knowledge/. // frontmatterField is one top-level YAML key from a frontmatter block,
// along with its raw line and any indented continuation lines (e.g. a
// bulleted list value spanning multiple lines).
type frontmatterField struct {
key string
lines []string
}
// splitFrontmatter splits a leading "---\n...\n---\n" YAML block out of
// content, returning its top-level fields in original order and the
// remaining body. If content has no leading frontmatter block, fields is
// nil and body is content unchanged.
func splitFrontmatter(content string) (fields []frontmatterField, body string) {
if !strings.HasPrefix(content, "---\n") {
return nil, content
}
lines := strings.Split(content, "\n")
i := 1
var cur *frontmatterField
for ; i < len(lines); i++ {
line := lines[i]
if strings.TrimSpace(line) == "---" {
i++
break
}
if line != "" && !strings.HasPrefix(line, " ") && !strings.HasPrefix(line, "\t") {
if cur != nil {
fields = append(fields, *cur)
}
key, _, _ := strings.Cut(line, ":")
cur = &frontmatterField{key: strings.TrimSpace(key), lines: []string{line}}
} else if cur != nil {
cur.lines = append(cur.lines, line)
}
}
if cur != nil {
fields = append(fields, *cur)
}
body = strings.Join(lines[i:], "\n")
return fields, body
}
// Write handles POST /write — write a note into brain/wiki/<wing>/<hall>/.
func (h *Handler) Write(w http.ResponseWriter, r *http.Request) { func (h *Handler) Write(w http.ResponseWriter, r *http.Request) {
var req writeRequest var req writeRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil { if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
@@ -233,10 +301,10 @@ func (h *Handler) Write(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, err.Error()) writeError(w, http.StatusBadRequest, err.Error())
return return
} }
if req.Wing != "" && req.Hall != "" { // WriteNote errors out above unless both are set, so this always runs —
if err := brain.BuildWingIndex(h.brainDir, req.Wing); err != nil { // no legacy fallback path left to guard against.
h.logger.Warn("auto-index failed", "wing", req.Wing, "err", err) if err := brain.BuildWingIndex(h.brainDir, req.Wing); err != nil {
} h.logger.Warn("auto-index failed", "wing", req.Wing, "err", err)
} }
writeJSON(w, map[string]string{"path": relPath}) writeJSON(w, map[string]string{"path": relPath})
} }
@@ -332,11 +400,19 @@ func (h *Handler) Ingest(w http.ResponseWriter, r *http.Request) {
writeJSON(w, ingestResponse{Pages: pages, Warnings: warnings}) writeJSON(w, ingestResponse{Pages: pages, Warnings: warnings})
} }
// supportedExtensions lists file extensions that IngestPath will process. // isSupportedExtension reports whether IngestPath will process ext.
var supportedExtensions = map[string]bool{ // .docx/.xlsx/.pptx/.png/.jpg/.jpeg require docmark (ADR-0013) and are only
".md": true, // supported when DOCMARK_URL is configured — checked per-call (not cached at
".txt": true, // package init) so it reflects the environment at request time.
".pdf": true, func isSupportedExtension(ext string) bool {
switch ext {
case ".md", ".txt", ".pdf":
return true
case ".docx", ".xlsx", ".pptx", ".png", ".jpg", ".jpeg":
return os.Getenv("DOCMARK_URL") != ""
default:
return false
}
} }
// IngestPath handles POST /ingest-path — ingest a file or directory. // IngestPath handles POST /ingest-path — ingest a file or directory.
@@ -369,7 +445,7 @@ func (h *Handler) IngestPath(w http.ResponseWriter, r *http.Request) {
return nil return nil
} }
ext := strings.ToLower(filepath.Ext(path)) ext := strings.ToLower(filepath.Ext(path))
if !supportedExtensions[ext] { if !isSupportedExtension(ext) {
return nil return nil
} }
content, readErr := extract.Text(path) content, readErr := extract.Text(path)
@@ -397,7 +473,7 @@ func (h *Handler) IngestPath(w http.ResponseWriter, r *http.Request) {
} }
} else { } else {
ext := strings.ToLower(filepath.Ext(req.Path)) ext := strings.ToLower(filepath.Ext(req.Path))
if !supportedExtensions[ext] { if !isSupportedExtension(ext) {
writeError(w, http.StatusBadRequest, fmt.Sprintf("unsupported file extension: %s", ext)) writeError(w, http.StatusBadRequest, fmt.Sprintf("unsupported file extension: %s", ext))
return return
} }
+283 -22
View File
@@ -65,11 +65,13 @@ func TestQuery_ReturnsResults(t *testing.T) {
assert.NotEmpty(t, results) assert.NotEmpty(t, results)
} }
func TestWrite_CreatesKnowledgeFile(t *testing.T) { func TestWrite_CreatesWikiFile(t *testing.T) {
dir, h := setup(t) dir, h := setup(t)
body, _ := json.Marshal(map[string]any{ body, _ := json.Marshal(map[string]any{
"content": "# Test note\n\nSome content.", "content": "# Test note\n\nSome content.",
"filename": "test-note.md", "filename": "test-note",
"wing": "homelab",
"hall": "facts",
}) })
req := httptest.NewRequest(http.MethodPost, "/write", bytes.NewReader(body)) req := httptest.NewRequest(http.MethodPost, "/write", bytes.NewReader(body))
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
@@ -81,11 +83,25 @@ func TestWrite_CreatesKnowledgeFile(t *testing.T) {
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp)) require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))
assert.NotEmpty(t, resp["path"]) assert.NotEmpty(t, resp["path"])
content, err := os.ReadFile(filepath.Join(dir, "knowledge", "test-note.md")) content, err := os.ReadFile(filepath.Join(dir, "wiki", "homelab", "facts", "test-note.md"))
require.NoError(t, err) require.NoError(t, err)
assert.Contains(t, string(content), "Some content.") assert.Contains(t, string(content), "Some content.")
} }
// TestWrite_RequiresWingAndHall is the HTTP-contract counterpart of
// TestWriteNote_RequiresWingAndHall: a caller (e.g. the MCP brain_write
// handler) that omits wing/hall gets a 400, not a silent legacy write.
func TestWrite_RequiresWingAndHall(t *testing.T) {
_, h := setup(t)
body, _ := json.Marshal(map[string]any{"content": "no destination"})
req := httptest.NewRequest(http.MethodPost, "/write", bytes.NewReader(body))
rec := httptest.NewRecorder()
h.Write(rec, req)
assert.Equal(t, http.StatusBadRequest, rec.Code)
}
func TestQuery_RequiresQuery(t *testing.T) { func TestQuery_RequiresQuery(t *testing.T) {
_, h := setup(t) _, h := setup(t)
body, _ := json.Marshal(map[string]any{"limit": 5}) body, _ := json.Marshal(map[string]any{"limit": 5})
@@ -97,13 +113,131 @@ func TestQuery_RequiresQuery(t *testing.T) {
assert.Equal(t, http.StatusBadRequest, rec.Code) assert.Equal(t, http.StatusBadRequest, rec.Code)
} }
func TestWrite_IncludesFrontmatterWhenTypeProvided(t *testing.T) { func TestWriteNote_HallRouteIncludesSourceTypeWhenSet(t *testing.T) {
dir := t.TempDir()
rel, err := api.WriteNote(dir, api.WriteNoteOptions{
Content: "# Claude session abc (koala)\n\nBody.\n",
Filename: "session-koala-abc",
Wing: "claude-sessions",
Hall: "facts",
SourceType: "internal",
})
require.NoError(t, err)
got, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(rel)))
require.NoError(t, err)
assert.Contains(t, string(got), "source_type: internal")
assert.Contains(t, string(got), "wing: claude-sessions")
}
func TestWriteNote_HallFactsDefaultsSourceTypeInternalWhenUnset(t *testing.T) {
dir := t.TempDir()
rel, err := api.WriteNote(dir, api.WriteNoteOptions{
Content: "manually captured fact.\n",
Wing: "agentsquad",
Hall: "facts",
})
require.NoError(t, err)
got, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(rel)))
require.NoError(t, err)
// Most hall=facts entries are first-party (an eval/benchmark the agent ran
// itself), not external claims — default to internal, require explicit
// opt-out for the rare case that does need a citation (brain-gardener#7).
assert.Contains(t, string(got), "source_type: internal")
}
func TestWriteNote_HallFactsPreservesExplicitExternalSourceType(t *testing.T) {
dir := t.TempDir()
rel, err := api.WriteNote(dir, api.WriteNoteOptions{
Content: "vendor pricing claim, needs a citation.\n",
Wing: "agentsquad",
Hall: "facts",
SourceType: "external",
})
require.NoError(t, err)
got, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(rel)))
require.NoError(t, err)
assert.Contains(t, string(got), "source_type: external")
}
func TestWriteNote_HallRouteOmitsSourceTypeForNonFactsHalls(t *testing.T) {
dir := t.TempDir()
rel, err := api.WriteNote(dir, api.WriteNoteOptions{
Content: "a decision record.\n",
Wing: "agentsquad",
Hall: "decisions",
})
require.NoError(t, err)
got, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(rel)))
require.NoError(t, err)
assert.NotContains(t, string(got), "source_type")
}
func TestWriteNote_HallRouteMergesExistingFrontmatterInsteadOfStacking(t *testing.T) {
dir := t.TempDir()
rel, err := api.WriteNote(dir, api.WriteNoteOptions{
Content: "---\ntitle: act_runner host-executor\ntags: [gitea-actions, act_runner]\n---\n\n# Body\n\nSome content.\n",
Filename: "act-runner-host-executor",
Wing: "homelab",
Hall: "failures",
})
require.NoError(t, err)
got, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(rel)))
require.NoError(t, err)
body := string(got)
// exactly one frontmatter block: only two "---" delimiter lines total
assert.Equal(t, 2, strings.Count(body, "---\n"), "expected a single merged frontmatter block, not stacked blocks")
assert.Contains(t, body, "wing: homelab")
assert.Contains(t, body, "hall: failures")
assert.Contains(t, body, "title: act_runner host-executor")
assert.Contains(t, body, "tags: [gitea-actions, act_runner]")
assert.Contains(t, body, "# Body")
}
// TestWriteNote_RequiresWingAndHall pins the post-legacy-removal contract
// (hyperguild#79 / ADR-0012): with the knowledge/ fallback gone, wing+hall
// is the only valid destination, so omitting either is a caller error, not
// a silent fallback.
func TestWriteNote_RequiresWingAndHall(t *testing.T) {
cases := []struct {
name string
wing string
hall string
}{
{"neither set", "", ""},
{"wing only", "homelab", ""},
{"hall only", "", "facts"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
dir := t.TempDir()
_, err := api.WriteNote(dir, api.WriteNoteOptions{
Content: "body",
Wing: tc.wing,
Hall: tc.hall,
})
require.Error(t, err)
assert.Contains(t, err.Error(), "wing and hall are required")
})
}
}
func TestWrite_GeneratesFilenameIfAbsent(t *testing.T) {
dir, h := setup(t) dir, h := setup(t)
body, _ := json.Marshal(map[string]any{ body, _ := json.Marshal(map[string]any{
"content": "Some learning.", "content": "auto name",
"filename": "typed-note.md", "wing": "homelab",
"type": "concept", "hall": "facts",
"domain": "software",
}) })
req := httptest.NewRequest(http.MethodPost, "/write", bytes.NewReader(body)) req := httptest.NewRequest(http.MethodPost, "/write", bytes.NewReader(body))
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
@@ -111,26 +245,54 @@ func TestWrite_IncludesFrontmatterWhenTypeProvided(t *testing.T) {
h.Write(rec, req) h.Write(rec, req)
assert.Equal(t, http.StatusOK, rec.Code) assert.Equal(t, http.StatusOK, rec.Code)
content, err := os.ReadFile(filepath.Join(dir, "knowledge", "typed-note.md")) entries, err := os.ReadDir(filepath.Join(dir, "wiki", "homelab", "facts"))
require.NoError(t, err) require.NoError(t, err)
assert.Contains(t, string(content), "type: concept") require.Len(t, entries, 1)
assert.Contains(t, string(content), "domain: software") assert.True(t, strings.HasSuffix(entries[0].Name(), ".md"))
assert.Contains(t, string(content), "Some learning.")
} }
func TestWrite_GeneratesFilenameIfAbsent(t *testing.T) { // TestWrite_CLIPayloadRoundTrips exercises the real Handler.Write (not a
// hand-rolled mock) over an actual HTTP round trip, POSTing the exact JSON
// envelope cmd/hyperguild's brainClient.Write sends: {wing, hall, filename,
// content}. cmd/hyperguild lives in a separate Go module from ingestion
// (no shared go.work), so a Go-level test can't import brainClient
// directly — this test instead pins the wire contract from the server
// side and proves a real `hyperguild brain write <wing> <hall> <slug>`
// invocation writes a real file with real frontmatter under wiki/<wing>/<hall>/.
// A prior version of this contract test on the client side (in
// cmd/hyperguild/http_test.go) used only an httptest.NewServer with a
// hand-rolled mock body, so it stayed green through a regression where the
// server required wing/hall but the client never sent them (hyperguild#79
// PR review).
func TestWrite_CLIPayloadRoundTrips(t *testing.T) {
dir, h := setup(t) dir, h := setup(t)
body, _ := json.Marshal(map[string]any{"content": "auto name"}) srv := httptest.NewServer(http.HandlerFunc(h.Write))
req := httptest.NewRequest(http.MethodPost, "/write", bytes.NewReader(body)) defer srv.Close()
rec := httptest.NewRecorder()
h.Write(rec, req) payload, err := json.Marshal(struct {
Wing string `json:"wing"`
Hall string `json:"hall"`
Filename string `json:"filename"`
Content string `json:"content"`
}{Wing: "homelab", Hall: "facts", Filename: "cli-roundtrip", Content: "# CLI roundtrip\n\nReal write.\n"})
require.NoError(t, err)
assert.Equal(t, http.StatusOK, rec.Code) resp, err := http.Post(srv.URL+"/write", "application/json", bytes.NewReader(payload)) //nolint:noctx
entries, _ := os.ReadDir(filepath.Join(dir, "knowledge")) require.NoError(t, err)
// +1 because setup already wrote tdd.md defer resp.Body.Close() //nolint:errcheck
assert.Len(t, entries, 2)
assert.True(t, strings.HasSuffix(entries[1].Name(), ".md")) assert.Equal(t, http.StatusOK, resp.StatusCode)
var out struct {
Path string `json:"path"`
}
require.NoError(t, json.NewDecoder(resp.Body).Decode(&out))
assert.Equal(t, "wiki/homelab/facts/cli-roundtrip.md", out.Path)
written, err := os.ReadFile(filepath.Join(dir, "wiki", "homelab", "facts", "cli-roundtrip.md"))
require.NoError(t, err)
assert.Contains(t, string(written), "wing: homelab")
assert.Contains(t, string(written), "hall: facts")
assert.Contains(t, string(written), "Real write.")
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -330,3 +492,102 @@ func TestIngestPath_Directory(t *testing.T) {
require.True(t, ok, "pages must be an array") require.True(t, ok, "pages must be an array")
assert.NotEmpty(t, pagesSlice) assert.NotEmpty(t, pagesSlice)
} }
// --- brain#21: claim-property envelope on the write path -------------------
func TestWriteNote_PreservesClaimEnvelopeVerbatim(t *testing.T) {
// writeHallNote already passes unknown keys through; this pins that
// behaviour for the envelope specifically, so a future refactor of the
// merge loop cannot silently drop it.
dir := t.TempDir()
rel, err := api.WriteNote(dir, api.WriteNoteOptions{
Content: "---\nhalf_life: durable\napplies: universal\nclaim_provenance: asserted\n---\n\nA durable claim.\n",
Wing: "homelab",
Hall: "decisions",
})
require.NoError(t, err)
got, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(rel)))
require.NoError(t, err)
assert.Contains(t, string(got), "half_life: durable")
assert.Contains(t, string(got), "applies: universal")
assert.Contains(t, string(got), "claim_provenance: asserted")
}
func TestWriteNote_RejectsInvalidClaimEnvelopeAndWritesNothing(t *testing.T) {
// Fail closed: a value outside the enum must not land. A lint skips what
// it cannot parse, so an unvalidated write produces a note that reads as
// classified while nothing acts on it.
dir := t.TempDir()
_, err := api.WriteNote(dir, api.WriteNoteOptions{
Content: "---\nhalf_life: forever\nclaim_provenance: asserted\n---\n\nBody.\n",
Filename: "bad-envelope",
Wing: "homelab",
Hall: "facts",
})
require.Error(t, err)
assert.Contains(t, err.Error(), "half_life")
_, statErr := os.Stat(filepath.Join(dir, "wiki/homelab/facts/bad-envelope.md"))
assert.True(t, os.IsNotExist(statErr), "a rejected write must leave no file behind")
}
func TestWriteNote_RejectsClaimFieldWithoutProvenance(t *testing.T) {
dir := t.TempDir()
_, err := api.WriteNote(dir, api.WriteNoteOptions{
Content: "---\napplies: homelab\n---\n\nBody.\n",
Filename: "no-provenance",
Wing: "homelab",
Hall: "facts",
})
require.Error(t, err)
assert.Contains(t, err.Error(), "claim_provenance")
_, statErr := os.Stat(filepath.Join(dir, "wiki/homelab/facts/no-provenance.md"))
assert.True(t, os.IsNotExist(statErr))
}
// The HTTP POST /write door reaches WriteNote directly, without the
// BrainStore, so the unresolved-wikilink strip has to live in the primitive
// or that door stays ungated.
func TestWriteNote_UnwrapsUnresolvedWikilinks(t *testing.T) {
dir := t.TempDir()
_, err := api.WriteNote(dir, api.WriteNoteOptions{
Content: "# Target\n\nbody\n", Filename: "target", Wing: "a", Hall: "facts",
})
require.NoError(t, err)
rel, err := api.WriteNote(dir, api.WriteNoteOptions{
Content: "See [[target]] and [[gitea-ci]].\n",
Filename: "src", Wing: "a", Hall: "facts",
})
require.NoError(t, err)
got, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(rel)))
require.NoError(t, err)
assert.Contains(t, string(got), "[[target]]")
assert.Contains(t, string(got), "and gitea-ci.")
assert.NotContains(t, string(got), "[[gitea-ci]]")
}
func TestUpdateNote_UnwrapsUnresolvedWikilinks(t *testing.T) {
dir := t.TempDir()
_, err := api.WriteNote(dir, api.WriteNoteOptions{
Content: "old\n", Filename: "n", Wing: "a", Hall: "facts",
})
require.NoError(t, err)
rel, _, _, err := api.UpdateNote(dir, api.UpdateNoteOptions{
Wing: "a", Hall: "facts", Slug: "n",
Content: "Related: [[secret-hygiene]].\n", Reason: "r",
})
require.NoError(t, err)
got, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(rel)))
require.NoError(t, err)
assert.Contains(t, string(got), "Related: secret-hygiene.")
assert.NotContains(t, string(got), "[[secret-hygiene]]")
}
@@ -0,0 +1,61 @@
// ingestion/internal/api/ingestpath_docmark_test.go
package api_test
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestIngestPath_DocxUnsupportedWhenDocmarkNotConfigured(t *testing.T) {
t.Setenv("DOCMARK_URL", "")
_, h := setup(t)
dir := t.TempDir()
f := filepath.Join(dir, "doc.docx")
require.NoError(t, os.WriteFile(f, []byte("fake docx"), 0o644))
body, _ := json.Marshal(map[string]any{"path": f, "source": "test-doc", "dry_run": true})
req := httptest.NewRequest(http.MethodPost, "/ingest-path", bytes.NewReader(body))
rec := httptest.NewRecorder()
h.IngestPath(rec, req)
assert.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
}
func TestIngestPath_DocxSupportedWhenDocmarkConfigured(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"# Converted Doc"}]}}`))
}))
defer srv.Close()
t.Setenv("DOCMARK_URL", srv.URL+"/mcp")
t.Setenv("DOCMARK_BEARER_TOKEN", "tok")
_, h := setup(t)
dir := t.TempDir()
f := filepath.Join(dir, "doc.docx")
require.NoError(t, os.WriteFile(f, []byte("fake docx"), 0o644))
body, _ := json.Marshal(map[string]any{"path": f, "source": "test-doc", "dry_run": true})
req := httptest.NewRequest(http.MethodPost, "/ingest-path", bytes.NewReader(body))
rec := httptest.NewRecorder()
h.IngestPath(rec, req)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
var resp map[string]any
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))
pages, ok := resp["pages"].([]any)
require.True(t, ok)
assert.NotEmpty(t, pages)
}
+62
View File
@@ -145,6 +145,68 @@ func PromoteNote(brainDir string, opts PromoteOptions) (string, error) {
return relSlash, nil return relSlash, nil
} }
// RejectOptions identifies a raw note to reject and why.
type RejectOptions struct {
Filename string // basename in brain/raw/
Reason string // optional
}
// RejectNote records a human decision not to promote a brain/raw/ note,
// without silently losing it: it stamps rejected_at (+ reject_reason when
// given) into frontmatter and moves the file to brain/raw/rejected/, using
// the same write-then-delete safety PromoteNote uses — the source survives
// any write failure — and the same basename-only filename validation.
//
// A rejected note never entered the wiki, so no index rebuild or
// auto-tunnel run: unlike PromoteNote, this is the end of the note's
// journey, not the start of a new one. It stays out of ListPending's view
// (raw/rejected/ is a subdirectory, and ListPending's os.ReadDir on raw/
// does not recurse), so a rejected note is never re-surfaced as pending —
// the human decision, once made, stays made, the same principle behind
// this estate's "issue status is surfaced, not auto-closed, but once a
// human decides, the decision is recorded" rule applied one level earlier.
func RejectNote(brainDir string, opts RejectOptions) (string, error) {
base := filepath.Base(opts.Filename)
if base != opts.Filename || base == "." || base == ".." || strings.ContainsAny(opts.Filename, `/\`) {
return "", fmt.Errorf("invalid filename %q", opts.Filename)
}
src := filepath.Join(brainDir, "raw", base)
raw, err := os.ReadFile(src)
if err != nil {
if os.IsNotExist(err) {
return "", fmt.Errorf("pending note %q does not exist in raw/", base)
}
return "", fmt.Errorf("read source: %w", err)
}
dest := filepath.Join(brainDir, "raw", "rejected", base)
if _, statErr := os.Stat(dest); statErr == nil {
rel, _ := filepath.Rel(brainDir, dest)
return "", fmt.Errorf("a rejected note named %s already exists", filepath.ToSlash(rel))
}
fm, body := parseFrontmatter(string(raw))
fm.set("rejected_at", time.Now().UTC().Format(time.RFC3339))
if opts.Reason != "" {
fm.set("reject_reason", opts.Reason)
}
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
return "", fmt.Errorf("create rejected dir: %w", err)
}
// Write-then-delete: the source survives any write failure.
if err := os.WriteFile(dest, []byte(fm.render()+body), 0o644); err != nil {
return "", fmt.Errorf("write rejected note: %w", err)
}
if err := os.Remove(src); err != nil {
return "", fmt.Errorf("rejected note written but source removal failed: %w", err)
}
rel, _ := filepath.Rel(brainDir, dest)
return filepath.ToSlash(rel), nil
}
// excerpt returns the first n runes of s, trimmed, single-spaced. // excerpt returns the first n runes of s, trimmed, single-spaced.
func excerpt(s string, n int) string { func excerpt(s string, n int) string {
s = strings.TrimSpace(s) s = strings.TrimSpace(s)
+82
View File
@@ -119,3 +119,85 @@ func TestPromoteRebuildsWingIndex(t *testing.T) {
require.NoError(t, err, "wing _index regenerated") require.NoError(t, err, "wing _index regenerated")
assert.Contains(t, string(idx), "x", "promoted note appears in the index") assert.Contains(t, string(idx), "x", "promoted note appears in the index")
} }
// --- RejectNote (hyperguild#81) ---------------------------------------------
func TestRejectHappyPath(t *testing.T) {
dir := t.TempDir()
writeRaw(t, dir, "2026-04-23-fed-sentiment-scrape.md",
"---\ncreated_at: 2026-04-23T13:20:07Z\n---\n# Sentiment scrape\n\nbody.\n")
rel, err := RejectNote(dir, RejectOptions{
Filename: "2026-04-23-fed-sentiment-scrape.md", Reason: "generic scrape, not homelab-relevant",
})
require.NoError(t, err)
assert.Equal(t, "raw/rejected/2026-04-23-fed-sentiment-scrape.md", rel)
// Source removed from the pending queue.
_, statErr := os.Stat(filepath.Join(dir, "raw", "2026-04-23-fed-sentiment-scrape.md"))
assert.True(t, os.IsNotExist(statErr), "source removed from raw/ after reject")
got, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(rel)))
require.NoError(t, err)
s := string(got)
assert.Contains(t, s, "created_at: 2026-04-23T13:20:07Z", "original created_at preserved")
assert.Contains(t, s, "rejected_at:")
assert.Contains(t, s, "reject_reason: generic scrape, not homelab-relevant")
assert.Contains(t, s, "# Sentiment scrape", "body preserved for later reference")
// Rejected notes never entered the wiki, and are no longer pending.
pending, err := ListPending(dir)
require.NoError(t, err)
assert.Empty(t, pending)
}
func TestRejectWithoutReason(t *testing.T) {
dir := t.TempDir()
writeRaw(t, dir, "2026-06-01-x.md", "body\n")
rel, err := RejectNote(dir, RejectOptions{Filename: "2026-06-01-x.md"})
require.NoError(t, err)
got, _ := os.ReadFile(filepath.Join(dir, filepath.FromSlash(rel)))
assert.NotContains(t, string(got), "reject_reason:", "no reason given, none stamped")
}
func TestRejectMissingSourceErrors(t *testing.T) {
_, err := RejectNote(t.TempDir(), RejectOptions{Filename: "ghost.md"})
require.Error(t, err)
}
func TestRejectRejectsTraversalFilename(t *testing.T) {
_, err := RejectNote(t.TempDir(), RejectOptions{Filename: "../escape.md"})
require.Error(t, err)
}
func TestRejectCollisionNoOverwrite(t *testing.T) {
dir := t.TempDir()
dest := filepath.Join(dir, "raw", "rejected", "x.md")
require.NoError(t, os.MkdirAll(filepath.Dir(dest), 0o755))
require.NoError(t, os.WriteFile(dest, []byte("EXISTING\n"), 0o644))
writeRaw(t, dir, "x.md", "NEW\n")
_, err := RejectNote(dir, RejectOptions{Filename: "x.md"})
require.Error(t, err, "collision must error, not overwrite")
got, _ := os.ReadFile(dest)
assert.Equal(t, "EXISTING\n", string(got), "target not overwritten")
_, statErr := os.Stat(filepath.Join(dir, "raw", "x.md"))
assert.NoError(t, statErr, "source preserved on collision (atomic: no delete without write)")
}
func TestRejectedNotesAreNotListedAsPendingAgain(t *testing.T) {
// ListPending already skips tunnel-candidates-*.md; confirm raw/rejected/
// (a subdirectory) doesn't leak into the top-level pending listing either
// — os.ReadDir on raw/ doesn't recurse, but pin it so a future change to
// ListPending can't silently start surfacing rejected notes as pending
// again.
dir := t.TempDir()
writeRaw(t, dir, "2026-06-01-x.md", "body\n")
_, err := RejectNote(dir, RejectOptions{Filename: "2026-06-01-x.md"})
require.NoError(t, err)
pending, err := ListPending(dir)
require.NoError(t, err)
assert.Empty(t, pending, "a rejected note must not still appear as pending")
}
+56 -1
View File
@@ -10,6 +10,7 @@ import (
"time" "time"
"github.com/mathiasbq/hyperguild/ingestion/internal/brain" "github.com/mathiasbq/hyperguild/ingestion/internal/brain"
"github.com/mathiasbq/hyperguild/ingestion/internal/claim"
) )
// ContentHash returns the lowercase hex sha256 of b. It is the note's // ContentHash returns the lowercase hex sha256 of b. It is the note's
@@ -64,6 +65,14 @@ func UpdateNote(brainDir string, opts UpdateNoteOptions) (relPath, contentHash,
return "", "", "", fmt.Errorf("content is required") return "", "", "", fmt.Errorf("content is required")
} }
// Same reason as WriteNote: the strip belongs in the primitive so every
// door inherits it.
clean, _, err := brain.StripUnresolvedLinks(brainDir, opts.Content)
if err != nil {
return "", "", "", err
}
opts.Content = clean
var rel string var rel string
if opts.Path != "" { if opts.Path != "" {
rel = opts.Path rel = opts.Path
@@ -90,14 +99,60 @@ func UpdateNote(brainDir string, opts UpdateNoteOptions) (relPath, contentHash,
} }
priorHash = ContentHash(prior) priorHash = ContentHash(prior)
// A caller may lead opts.Content with its own frontmatter fence to set or
// change fields on supersede (e.g. the claim envelope). Split it off
// before it reaches the body — left un-split, it would render as a
// second, inert `---`-fenced block of literal text rather than taking
// effect, and any claim-envelope fields inside it would reach disk
// unvalidated (hyperguild#111: the same rule that guards note birth in
// writeHallNote must guard a change to the same fields).
contentFM, contentBody := parseFrontmatter(opts.Content)
fm, _ := parseFrontmatter(string(prior)) fm, _ := parseFrontmatter(string(prior))
for _, l := range contentFM.lines {
// updated_at/supersedes/supersede_reason are this function's own
// output, not something a caller's fragment sets — updated_at and
// supersedes are already unconditionally re-set below regardless of
// what the loop does with them, but supersede_reason is only
// re-set when opts.Reason is non-empty, so without this skip a
// caller could set it via its own fragment and have it survive
// even when Reason is empty, bypassing the one intended entry
// point for that field (hyperguild#125, found in #111's review).
// Skipping all three here rather than relying on the unconditional
// overwrites below to save the other two keeps the invariant
// explicit at the one place it can be silently broken by a future
// reordering, not implicit in call order.
if l.key == "" || l.key == "updated_at" || l.key == "supersedes" || l.key == "supersede_reason" {
continue
}
fm.set(l.key, l.value)
}
fm.set("updated_at", time.Now().UTC().Format(time.RFC3339)) fm.set("updated_at", time.Now().UTC().Format(time.RFC3339))
fm.set("supersedes", priorHash) fm.set("supersedes", priorHash)
if opts.Reason != "" { if opts.Reason != "" {
fm.set("supersede_reason", opts.Reason) fm.set("supersede_reason", opts.Reason)
} }
out := []byte(fm.render() + opts.Content) // Validate the envelope AFTER the merge, against the full field set that
// is about to reach disk — not just the caller's fragment. Validating the
// fragment alone would miss a caller that supersedes claim_provenance to
// empty while half_life/applies survive untouched from the prior note:
// each side looks individually fine, but the merged result is an
// unprovenanced envelope, which is the exact laundering this check
// exists to catch. (Caught in review before merge, not filed after —
// worth being honest about in the history: this second pass was the
// actual fix; the first one validated the wrong document.)
envelope := make(map[string]string, len(fm.lines))
for _, l := range fm.lines {
if l.key != "" {
envelope[l.key] = l.value
}
}
if err := claim.ValidateEnvelope(envelope); err != nil {
return "", "", "", fmt.Errorf("claim envelope: %w", err)
}
out := []byte(fm.render() + contentBody)
if err := os.WriteFile(abs, out, 0o644); err != nil { if err := os.WriteFile(abs, out, 0o644); err != nil {
return "", "", "", fmt.Errorf("write: %w", err) return "", "", "", fmt.Errorf("write: %w", err)
} }
+147
View File
@@ -52,6 +52,114 @@ func TestUpdateNoteSupersedesAndStamps(t *testing.T) {
assert.Contains(t, s, "supersede_reason: facts changed") assert.Contains(t, s, "supersede_reason: facts changed")
} }
func TestUpdateNoteRejectsInvalidEnvelopeAndWritesNothing(t *testing.T) {
// hyperguild#111: WriteNote validates the claim envelope before create;
// UpdateNote didn't before supersede, so the same rule must hold on
// change as on birth, fail-closed, nothing written on rejection.
brainDir := t.TempDir()
original := "---\nwing: jepa-fx\nhall: facts\ncreated_at: 2026-01-01T00:00:00Z\n---\n# Old\n\nold body\n"
rel := seedNote(t, brainDir, "wiki/jepa-fx/facts/val-vol.md", original)
_, _, _, err := UpdateNote(brainDir, UpdateNoteOptions{
Path: rel,
Content: "---\nhalf_life: forever\n---\n# New\n\nnew body\n",
})
require.Error(t, err)
assert.Contains(t, err.Error(), "claim envelope")
got, err := os.ReadFile(filepath.Join(brainDir, filepath.FromSlash(rel)))
require.NoError(t, err)
assert.Equal(t, original, string(got), "rejected update must leave the note byte-identical")
}
func TestUpdateNoteRejectsAppliesWithoutProvenance(t *testing.T) {
brainDir := t.TempDir()
original := "---\nwing: jepa-fx\nhall: facts\n---\nold\n"
rel := seedNote(t, brainDir, "wiki/jepa-fx/facts/val-vol.md", original)
_, _, _, err := UpdateNote(brainDir, UpdateNoteOptions{
Path: rel,
Content: "---\napplies: universal\n---\nnew\n",
})
require.Error(t, err)
assert.Contains(t, err.Error(), "claim envelope")
got, err := os.ReadFile(filepath.Join(brainDir, filepath.FromSlash(rel)))
require.NoError(t, err)
assert.Equal(t, original, string(got))
}
func TestUpdateNoteAcceptsValidEnvelopeAndMergesIntoFrontmatter(t *testing.T) {
brainDir := t.TempDir()
rel := seedNote(t, brainDir, "wiki/jepa-fx/facts/val-vol.md",
"---\nwing: jepa-fx\nhall: facts\ncreated_at: 2026-01-01T00:00:00Z\n---\nold\n")
_, _, _, err := UpdateNote(brainDir, UpdateNoteOptions{
Path: rel,
Content: "---\nhalf_life: durable\napplies: universal\nclaim_provenance: asserted\n---\nnew body\n",
})
require.NoError(t, err)
got, err := os.ReadFile(filepath.Join(brainDir, filepath.FromSlash(rel)))
require.NoError(t, err)
s := string(got)
assert.Contains(t, s, "half_life: durable")
assert.Contains(t, s, "applies: universal")
assert.Contains(t, s, "claim_provenance: asserted")
assert.Contains(t, s, "wing: jepa-fx", "prior fields survive")
assert.Contains(t, s, "new body")
assert.Equal(t, 2, strings.Count(s, "---\n"),
"exactly one open+close fence pair — the caller's own fence must not leak in as a second, inert block")
}
func TestUpdateNoteRejectsClearingProvenanceWhileEnvelopeSurvives(t *testing.T) {
// Found in review, not written speculatively: validating only the
// caller's fragment (rather than the merged result) let a caller blank
// out claim_provenance alone while half_life/applies survived from the
// prior note untouched — each side looks fine on its own, the merged
// envelope on disk is the unprovenanced one the whole check exists to
// catch.
brainDir := t.TempDir()
original := "---\nwing: jepa-fx\nhall: facts\nhalf_life: durable\napplies: universal\nclaim_provenance: asserted\n---\nold\n"
rel := seedNote(t, brainDir, "wiki/jepa-fx/facts/val-vol.md", original)
_, _, _, err := UpdateNote(brainDir, UpdateNoteOptions{
Path: rel,
Content: "---\nclaim_provenance: \n---\nnew body\n",
})
require.Error(t, err)
assert.Contains(t, err.Error(), "claim envelope")
got, err := os.ReadFile(filepath.Join(brainDir, filepath.FromSlash(rel)))
require.NoError(t, err)
assert.Equal(t, original, string(got), "rejected update must leave the note byte-identical")
}
func TestUpdateNoteWithoutEnvelopeFieldsIsUnchangedFromToday(t *testing.T) {
// Regression pin: plain fence-less content (the common case) must behave
// exactly as it did before the envelope-merge fix.
brainDir := t.TempDir()
rel := seedNote(t, brainDir, "wiki/jepa-fx/facts/val-vol.md",
"---\nwing: jepa-fx\nhall: facts\ncreated_at: 2026-01-01T00:00:00Z\ncustom: keep-me\n---\n# Old\n\nold body\n")
relPath, hash, priorHash, err := UpdateNote(brainDir, UpdateNoteOptions{
Path: rel,
Content: "# New\n\nnew body\n",
Reason: "facts changed",
})
require.NoError(t, err)
assert.Equal(t, rel, relPath)
assert.NotEmpty(t, hash)
assert.NotEqual(t, hash, priorHash)
got, err := os.ReadFile(filepath.Join(brainDir, filepath.FromSlash(rel)))
require.NoError(t, err)
s := string(got)
assert.Contains(t, s, "# New")
assert.Contains(t, s, "custom: keep-me")
assert.Contains(t, s, "supersedes: "+priorHash)
}
func TestUpdateNoteResolvesByWingHallSlug(t *testing.T) { func TestUpdateNoteResolvesByWingHallSlug(t *testing.T) {
brainDir := t.TempDir() brainDir := t.TempDir()
seedNote(t, brainDir, "wiki/jepa-fx/facts/val-vol.md", seedNote(t, brainDir, "wiki/jepa-fx/facts/val-vol.md",
@@ -123,6 +231,45 @@ func TestUpdateThenReadRoundTripsHash(t *testing.T) {
assert.Equal(t, hash, readHash, "update content_hash must round-trip through ReadNote") assert.Equal(t, hash, readHash, "update content_hash must round-trip through ReadNote")
} }
func TestUpdateNoteSupersedeReasonNotSettableViaCallerFragmentWhenReasonOptionEmpty(t *testing.T) {
// hyperguild#125, found in #111's review: the merge loop applied every
// field from the caller's leading frontmatter fragment, including
// supersede_reason -- which is only re-set unconditionally when
// opts.Reason is non-empty, so a caller could set it via its own
// fragment and have it survive even with Reason left empty, bypassing
// the one intended entry point for that field.
brainDir := t.TempDir()
rel := seedNote(t, brainDir, "wiki/a/facts/n.md", "---\nwing: a\nhall: facts\n---\nold\n")
_, _, _, err := UpdateNote(brainDir, UpdateNoteOptions{
Path: rel,
Content: "---\nsupersede_reason: snuck in via the fragment\n---\nnew\n",
// Reason deliberately left empty.
})
require.NoError(t, err)
got, err := os.ReadFile(filepath.Join(brainDir, filepath.FromSlash(rel)))
require.NoError(t, err)
assert.NotContains(t, string(got), "supersede_reason",
"supersede_reason must not appear at all when opts.Reason is empty, regardless of what the fragment tried to set")
}
func TestUpdateNoteSupersedeReasonFromOptionStillWorks(t *testing.T) {
// Regression pin: the legitimate entry point (opts.Reason) must be
// completely unaffected by #125's fix.
brainDir := t.TempDir()
rel := seedNote(t, brainDir, "wiki/a/facts/n.md", "---\nwing: a\nhall: facts\n---\nold\n")
_, _, _, err := UpdateNote(brainDir, UpdateNoteOptions{
Path: rel, Content: "new\n", Reason: "facts changed",
})
require.NoError(t, err)
got, err := os.ReadFile(filepath.Join(brainDir, filepath.FromSlash(rel)))
require.NoError(t, err)
assert.Contains(t, string(got), "supersede_reason: facts changed")
}
func TestContentHashStable(t *testing.T) { func TestContentHashStable(t *testing.T) {
assert.Equal(t, ContentHash([]byte("abc")), ContentHash([]byte("abc"))) assert.Equal(t, ContentHash([]byte("abc")), ContentHash([]byte("abc")))
assert.NotEqual(t, ContentHash([]byte("abc")), ContentHash([]byte("abd"))) assert.NotEqual(t, ContentHash([]byte("abc")), ContentHash([]byte("abd")))
+2 -2
View File
@@ -28,8 +28,8 @@ type FileBuffer struct {
} }
type bufferLine struct { type bufferLine struct {
ID string `json:"id"` ID string `json:"id"`
Entry capture.AuditEntry `json:"entry"` Entry capture.AuditEntry `json:"entry"`
} }
// NewFileBuffer returns a buffer backed by path. The parent directory is // NewFileBuffer returns a buffer backed by path. The parent directory is
+4 -4
View File
@@ -46,10 +46,10 @@ func (f *fakeNotifier) Notify(_ context.Context, msg string) error {
// unwritableBuffer always reports it cannot be written (floor condition). // unwritableBuffer always reports it cannot be written (floor condition).
type unwritableBuffer struct{} type unwritableBuffer struct{}
func (unwritableBuffer) Writable() error { return errors.New("disk full") } func (unwritableBuffer) Writable() error { return errors.New("disk full") }
func (unwritableBuffer) Append(capture.AuditEntry) error { return errors.New("disk full") } func (unwritableBuffer) Append(capture.AuditEntry) error { return errors.New("disk full") }
func (unwritableBuffer) Pending() ([]audit.Buffered, error) { return nil, nil } func (unwritableBuffer) Pending() ([]audit.Buffered, error) { return nil, nil }
func (unwritableBuffer) Confirm(string) error { return nil } func (unwritableBuffer) Confirm(string) error { return nil }
func newFileBuffer(t *testing.T) *audit.FileBuffer { func newFileBuffer(t *testing.T) *audit.FileBuffer {
t.Helper() t.Helper()
+157
View File
@@ -0,0 +1,157 @@
package brain
import (
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
)
// wikilinkRE matches [[target]] and [[target|Display Text]].
var wikilinkRE = regexp.MustCompile(`\[\[([^\]|]+)(?:\|([^\]]*))?\]\]`)
// fencedCodeRE and inlineCodeRE mark the regions where a [[...]] is a
// syntax example rather than a link. Same exclusion brain-gardener's audit
// applies on the read side, so the write gate and the audit agree on what
// counts as a link at all.
var (
fencedCodeRE = regexp.MustCompile("(?s)```.*?```")
inlineCodeRE = regexp.MustCompile("`[^`\n]*`")
)
// StripUnresolvedLinks unwraps every [[wikilink]] in content whose target
// resolves to no entry under knowledge/ or wiki/, leaving the link's display
// text (or its target) as plain prose. It returns the rewritten content and
// the sorted, de-duplicated targets it unwrapped.
//
// WHY UNWRAP RATHER THAN REJECT THE WRITE
// Agents write [[...]] around anything that feels related — a skill name, a
// repo, an agent-local memory file — and none of those are brain entries.
// Every one of those becomes a permanent [high] broken-link finding that no
// deterministic Fixer can repair, because there is no target to repoint to:
// the brain-audit digest grew from 19 to 63 high findings between 2026-08-26
// and 2026-09-16, and 53 of the 63 were exactly this. Rejecting the write
// instead would push the failure onto claudewatcher's unattended ingest path,
// where a refused write is a lost learning. Unwrapping keeps the author's
// words, keeps the write, and keeps the graph honest.
//
// An empty corpus (no knowledge/ or wiki/ yet, or a misconfigured brainDir)
// returns content unchanged: nothing resolving is a bootstrap state, not
// evidence that every target was invented.
func StripUnresolvedLinks(brainDir, content string) (string, []string, error) {
index, err := entryIndex(brainDir)
if err != nil {
return "", nil, err
}
if len(index) == 0 {
return content, nil, nil
}
code := codeSpans(content)
stripped := map[string]struct{}{}
var b strings.Builder
last := 0
for _, m := range wikilinkRE.FindAllStringSubmatchIndex(content, -1) {
start, end := m[0], m[1]
if overlaps(start, end, code) {
continue
}
target := strings.TrimSpace(content[m[2]:m[3]])
if _, ok := index[linkKey(target)]; ok {
continue
}
display := target
if m[4] >= 0 {
if d := strings.TrimSpace(content[m[4]:m[5]]); d != "" {
display = d
}
}
b.WriteString(content[last:start])
b.WriteString(display)
last = end
stripped[target] = struct{}{}
}
if last == 0 {
return content, nil, nil
}
b.WriteString(content[last:])
targets := make([]string, 0, len(stripped))
for t := range stripped {
targets = append(targets, t)
}
sort.Strings(targets)
return b.String(), targets, nil
}
// linkedTrees are the two trees that hold linkable entries — the same pair
// package notes admits under ScopeNotes. Duplicated rather than imported
// because that list is unexported there and this is a read-only mirror.
var linkedTrees = []string{"knowledge", "wiki"}
// entryIndex maps every form a wikilink may name an entry by — its bare slug
// and its path form (wiki/<wing>/<hall>/<slug>.md -> wing/hall/slug) — to a
// present marker. Mirrors brain-gardener's resolver so an accepted link is
// one the audit will also resolve.
func entryIndex(brainDir string) (map[string]struct{}, error) {
index := map[string]struct{}{}
for _, dir := range linkedTrees {
root := filepath.Join(brainDir, dir)
if _, err := os.Stat(root); os.IsNotExist(err) {
continue
} else if err != nil {
return nil, fmt.Errorf("stat %s: %w", dir, err)
}
err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() || !strings.HasSuffix(path, ".md") {
return nil
}
rel, err := filepath.Rel(brainDir, path)
if err != nil {
return err
}
rel = filepath.ToSlash(rel)
index[strings.TrimSuffix(filepath.Base(rel), ".md")] = struct{}{}
index[strings.TrimPrefix(strings.TrimSuffix(rel, ".md"), "wiki/")] = struct{}{}
return nil
})
if err != nil {
return nil, fmt.Errorf("walk %s: %w", dir, err)
}
}
return index, nil
}
// linkKey normalises a link target for index lookup: an exact path form is
// tried as written, and anything else falls back to its final segment.
func linkKey(target string) string {
return strings.TrimSuffix(target, ".md")
}
// codeSpans returns the byte ranges of fenced blocks and inline code spans.
func codeSpans(content string) [][2]int {
var spans [][2]int
for _, m := range fencedCodeRE.FindAllStringIndex(content, -1) {
spans = append(spans, [2]int{m[0], m[1]})
}
for _, m := range inlineCodeRE.FindAllStringIndex(content, -1) {
spans = append(spans, [2]int{m[0], m[1]})
}
return spans
}
// overlaps reports whether [start,end) intersects any span.
func overlaps(start, end int, spans [][2]int) bool {
for _, s := range spans {
if start < s[1] && end > s[0] {
return true
}
}
return false
}
@@ -0,0 +1,93 @@
package brain_test
import (
"testing"
"github.com/mathiasbq/hyperguild/ingestion/internal/brain"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// seedCorpus writes the two entries every linkcheck case resolves against.
func seedCorpus(t *testing.T, dir string) {
t.Helper()
seedNote(t, dir, "wiki/homelab/facts/real-entry.md",
"---\nwing: homelab\nhall: facts\ntitle: 'Real entry'\n---\n\nbody.\n")
seedNote(t, dir, "knowledge/legacy-entry.md",
"---\ntitle: 'Legacy entry'\n---\n\nbody.\n")
}
func TestStripUnresolvedLinks(t *testing.T) {
tests := []struct {
name string
body string
want string
stripped []string
}{
{
name: "bare slug that resolves is kept",
body: "See [[real-entry]] for the rule.",
want: "See [[real-entry]] for the rule.",
},
{
name: "path-style target that resolves is kept",
body: "See [[homelab/facts/real-entry]].",
want: "See [[homelab/facts/real-entry]].",
},
{
name: "knowledge/ entry resolves by bare slug",
body: "See [[legacy-entry]].",
want: "See [[legacy-entry]].",
},
{
name: "unresolvable target is unwrapped to plain text",
body: "Related: [[secret-hygiene]].",
want: "Related: secret-hygiene.",
stripped: []string{"secret-hygiene"},
},
{
name: "unresolvable aliased target keeps its display text",
body: "Related: [[feedback_check_host_not_assume|check the host]].",
want: "Related: check the host.",
stripped: []string{"feedback_check_host_not_assume"},
},
{
name: "link inside a fenced code block is left alone",
body: "Syntax:\n\n```\n[[wing/hall/slug]]\n```\n",
want: "Syntax:\n\n```\n[[wing/hall/slug]]\n```\n",
},
{
name: "link inside an inline code span is left alone",
body: "Write `[[wing/hall/slug]]` to link.",
want: "Write `[[wing/hall/slug]]` to link.",
},
{
name: "every unresolvable target is reported once, sorted",
body: "[[zeta-gap]] and [[alpha-gap]] and [[zeta-gap]] again.",
want: "zeta-gap and alpha-gap and zeta-gap again.",
stripped: []string{"alpha-gap", "zeta-gap"},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
dir := t.TempDir()
seedCorpus(t, dir)
got, stripped, err := brain.StripUnresolvedLinks(dir, tc.body)
require.NoError(t, err)
assert.Equal(t, tc.want, got)
assert.Equal(t, tc.stripped, stripped)
})
}
}
func TestStripUnresolvedLinks_MissingBrainDirIsNotAGate(t *testing.T) {
// A brain dir with no knowledge//wiki/ tree yet must not turn every link
// into an unresolved one — an empty corpus is a bootstrap state, not
// evidence that the author invented the target.
got, stripped, err := brain.StripUnresolvedLinks(t.TempDir(), "See [[real-entry]].")
require.NoError(t, err)
assert.Equal(t, "See [[real-entry]].", got)
assert.Nil(t, stripped)
}
+22 -4
View File
@@ -54,11 +54,24 @@ func DetectTunnels(brainDir, content string) ([]TunnelCandidate, error) {
return nil return nil
} }
title, _ := readTitleAndCreated(path, strings.TrimSuffix(d.Name(), ".md")) title, _ := readTitleAndCreated(path, strings.TrimSuffix(d.Name(), ".md"))
needle := strings.ToLower(strings.TrimSpace(title)) title = strings.TrimSpace(title)
if needle == "" { if title == "" {
return nil return nil
} }
idx := strings.Index(lowerContent, needle)
// A one-word title has to match the prose case-exactly. Matched
// case-insensitively, it links every entry that happens to use the
// word: "WRONG" (wiki/telos/decisions/wrong.md) collected 185 inbound
// See-also links and "Status" 136, making the two most-linked nodes in
// the graph artifacts of the English language rather than references.
// Multi-word titles keep the case-insensitive match — "risk tier
// middleware" in prose is a real mention however it is capitalised,
// and a three-word collision is not an accident.
haystack, needle := lowerContent, strings.ToLower(title)
if isSingleWord(title) {
haystack, needle = content, title
}
idx := strings.Index(haystack, needle)
if idx == -1 { if idx == -1 {
return nil return nil
} }
@@ -69,7 +82,7 @@ func DetectTunnels(brainDir, content string) ([]TunnelCandidate, error) {
out = append(out, TunnelCandidate{ out = append(out, TunnelCandidate{
TargetPath: filepath.ToSlash(rel), TargetPath: filepath.ToSlash(rel),
MatchedTerm: title, MatchedTerm: title,
Exact: isWholeWord(lowerContent, idx, len(needle)), Exact: isWholeWord(haystack, idx, len(needle)),
}) })
return nil return nil
}) })
@@ -79,6 +92,11 @@ func DetectTunnels(brainDir, content string) ([]TunnelCandidate, error) {
return out, nil return out, nil
} }
// isSingleWord reports whether title is one whitespace-free token.
func isSingleWord(title string) bool {
return !strings.ContainsAny(title, " \t")
}
// isWholeWord reports whether the substring at [idx, idx+n) in s is // isWholeWord reports whether the substring at [idx, idx+n) in s is
// bounded by non-alphanumeric characters (or string edges). // bounded by non-alphanumeric characters (or string edges).
func isWholeWord(s string, idx, n int) bool { func isWholeWord(s string, idx, n int) bool {
+57 -11
View File
@@ -102,16 +102,29 @@ func TestDetectTunnels_ExactTitleMatch(t *testing.T) {
func TestDetectTunnels_FuzzyMatch(t *testing.T) { func TestDetectTunnels_FuzzyMatch(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
seedNote(t, dir, "wiki/x/facts/routing.md", seedNote(t, dir, "wiki/x/facts/routing-table.md",
"---\ntitle: Routing\n---\nbody.\n") "---\ntitle: 'Routing Table'\n---\nbody.\n")
// Substring of title appears in content, but not as a whole word. // Substring of title appears in content, but not as a whole word.
candidates, err := brain.DetectTunnels(dir, "rerouting handles failover") candidates, err := brain.DetectTunnels(dir, "the routing tables were rebuilt")
require.NoError(t, err) require.NoError(t, err)
require.Len(t, candidates, 1) require.Len(t, candidates, 1)
assert.False(t, candidates[0].Exact, "substring-only match should be fuzzy") assert.False(t, candidates[0].Exact, "substring-only match should be fuzzy")
} }
// A one-word title whose only appearance is lowercase inside another word is
// not even a candidate: it would fill the review file with English rather than
// with references.
func TestDetectTunnels_SingleWordSubstringIsNotACandidate(t *testing.T) {
dir := t.TempDir()
seedNote(t, dir, "wiki/x/facts/routing.md",
"---\ntitle: Routing\n---\nbody.\n")
candidates, err := brain.DetectTunnels(dir, "rerouting handles failover")
require.NoError(t, err)
assert.Empty(t, candidates)
}
func TestDetectTunnels_NoFrontmatterFallsBackToSlug(t *testing.T) { func TestDetectTunnels_NoFrontmatterFallsBackToSlug(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
seedNote(t, dir, "wiki/x/facts/widget-flags.md", "# widget flags\n\nbody.\n") seedNote(t, dir, "wiki/x/facts/widget-flags.md", "# widget flags\n\nbody.\n")
@@ -126,20 +139,21 @@ func TestDetectTunnels_NoFrontmatterFallsBackToSlug(t *testing.T) {
func TestAutoTunnel_FuzzyGoesToCandidatesFile(t *testing.T) { func TestAutoTunnel_FuzzyGoesToCandidatesFile(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
// Existing note in a different wing whose title is "Routing". // Existing note in a different wing whose title is "Routing Table".
seedNote(t, dir, "wiki/other/facts/routing.md", seedNote(t, dir, "wiki/other/facts/routing-table.md",
"---\nwing: other\nhall: facts\ntitle: Routing\n---\nbody.\n") "---\nwing: other\nhall: facts\ntitle: 'Routing Table'\n---\nbody.\n")
// Source note in another wing whose body mentions "rerouting" (substring match only). // Source note in another wing whose body mentions "routing tables"
// (substring match only — the title is not there as a whole word).
seedNote(t, dir, "wiki/jepa-fx/facts/new.md", seedNote(t, dir, "wiki/jepa-fx/facts/new.md",
"---\nwing: jepa-fx\nhall: facts\n---\nrerouting traffic\n") "---\nwing: jepa-fx\nhall: facts\n---\nrouting tables rebuilt\n")
require.NoError(t, brain.AutoTunnel(dir, require.NoError(t, brain.AutoTunnel(dir,
"wiki/jepa-fx/facts/new.md", "rerouting traffic")) "wiki/jepa-fx/facts/new.md", "routing tables rebuilt"))
// Source must not get auto-linked (fuzzy). // Source must not get auto-linked (fuzzy).
got, err := os.ReadFile(filepath.Join(dir, "wiki/jepa-fx/facts/new.md")) got, err := os.ReadFile(filepath.Join(dir, "wiki/jepa-fx/facts/new.md"))
require.NoError(t, err) require.NoError(t, err)
assert.NotContains(t, string(got), "[[other/facts/routing]]") assert.NotContains(t, string(got), "[[other/facts/routing-table]]")
// Candidates file must list the pair. // Candidates file must list the pair.
matches, err := filepath.Glob(filepath.Join(dir, "raw", "tunnel-candidates-*.md")) matches, err := filepath.Glob(filepath.Join(dir, "raw", "tunnel-candidates-*.md"))
@@ -148,7 +162,7 @@ func TestAutoTunnel_FuzzyGoesToCandidatesFile(t *testing.T) {
body, err := os.ReadFile(matches[0]) body, err := os.ReadFile(matches[0])
require.NoError(t, err) require.NoError(t, err)
assert.Contains(t, string(body), "wiki/jepa-fx/facts/new.md") assert.Contains(t, string(body), "wiki/jepa-fx/facts/new.md")
assert.Contains(t, string(body), "wiki/other/facts/routing.md") assert.Contains(t, string(body), "wiki/other/facts/routing-table.md")
assert.Contains(t, string(body), "Routing") assert.Contains(t, string(body), "Routing")
} }
@@ -175,3 +189,35 @@ func TestWriteTunnel_AppendsToExistingSeeAlso(t *testing.T) {
assert.Contains(t, s, "[[a/facts/old]]") assert.Contains(t, s, "[[a/facts/old]]")
assert.Contains(t, s, "[[b/facts/y]]") assert.Contains(t, s, "[[b/facts/y]]")
} }
// A one-word title matched case-insensitively links every entry that happens
// to use that word. Live cost before this rule: 185 entries auto-linked to
// wiki/telos/decisions/wrong.md (title "WRONG") and 136 to .../status.md,
// making the two most-linked nodes in the graph pure artifacts.
func TestDetectTunnels_SingleWordTitleNeedsAnExactCaseMatch(t *testing.T) {
dir := t.TempDir()
seedNote(t, dir, "wiki/telos/decisions/wrong.md",
"---\nwing: telos\nhall: decisions\ntitle: WRONG\n---\n# WRONG\n\nRetired beliefs.\n")
got, err := brain.DetectTunnels(dir, "The obvious fix was to reject the write. Wrong here.")
require.NoError(t, err)
for _, c := range got {
assert.False(t, c.Exact, "a lowercase prose word must not auto-link a one-word title: %+v", c)
}
got, err = brain.DetectTunnels(dir, "The beliefs listed under WRONG were retired.")
require.NoError(t, err)
require.Len(t, got, 1)
assert.True(t, got[0].Exact, "the title's own casing appearing in prose is a real reference")
}
func TestDetectTunnels_MultiWordTitleStaysCaseInsensitive(t *testing.T) {
dir := t.TempDir()
seedNote(t, dir, "wiki/homelab/facts/risk-tier.md",
"---\nwing: homelab\nhall: facts\ntitle: 'Risk Tier Middleware'\n---\nbody\n")
got, err := brain.DetectTunnels(dir, "We rebuilt the risk tier middleware last week.")
require.NoError(t, err)
require.Len(t, got, 1)
assert.True(t, got[0].Exact)
}
+14 -4
View File
@@ -42,11 +42,15 @@ func (s *Store) WithGraph(g graphsync.Store) *Store {
// Write creates a brain note and returns its read-after-write handle. // Write creates a brain note and returns its read-after-write handle.
func (s *Store) Write(ctx context.Context, n capture.Note) (capture.Ref, error) { func (s *Store) Write(ctx context.Context, n capture.Note) (capture.Ref, error) {
content, unlinked, err := brain.StripUnresolvedLinks(s.brainDir, n.Content)
if err != nil {
return capture.Ref{}, err
}
n.Content = content
relPath, err := api.WriteNote(s.brainDir, api.WriteNoteOptions{ relPath, err := api.WriteNote(s.brainDir, api.WriteNoteOptions{
Content: n.Content, Content: n.Content,
Filename: n.Filename, Filename: n.Filename,
Type: n.Type,
Domain: n.Domain,
Wing: n.Wing, Wing: n.Wing,
Hall: n.Hall, Hall: n.Hall,
}) })
@@ -57,13 +61,19 @@ func (s *Store) Write(ctx context.Context, n capture.Note) (capture.Ref, error)
s.indexInGraph(ctx, "brain_write", relPath) s.indexInGraph(ctx, "brain_write", relPath)
_, _, hash, _ := api.ReadNote(s.brainDir, relPath) _, _, hash, _ := api.ReadNote(s.brainDir, relPath)
return capture.Ref{ID: relPath, Path: relPath, ContentHash: hash}, nil return capture.Ref{ID: relPath, Path: relPath, ContentHash: hash, Unlinked: unlinked}, nil
} }
// Update supersedes an existing note in place. slug may be a bare slug // Update supersedes an existing note in place. slug may be a bare slug
// (resolved against n.Wing/n.Hall) or a full brain-relative path (when it // (resolved against n.Wing/n.Hall) or a full brain-relative path (when it
// contains a slash). It never creates — a missing target is an error. // contains a slash). It never creates — a missing target is an error.
func (s *Store) Update(ctx context.Context, slug string, n capture.Note) (capture.Ref, error) { func (s *Store) Update(ctx context.Context, slug string, n capture.Note) (capture.Ref, error) {
content, unlinked, err := brain.StripUnresolvedLinks(s.brainDir, n.Content)
if err != nil {
return capture.Ref{}, err
}
n.Content = content
opts := api.UpdateNoteOptions{Content: n.Content, Reason: n.Reason} opts := api.UpdateNoteOptions{Content: n.Content, Reason: n.Reason}
if strings.Contains(slug, "/") { if strings.Contains(slug, "/") {
opts.Path = slug opts.Path = slug
@@ -80,7 +90,7 @@ func (s *Store) Update(ctx context.Context, slug string, n capture.Note) (captur
} }
s.indexInGraph(ctx, "brain_update", relPath) s.indexInGraph(ctx, "brain_update", relPath)
return capture.Ref{ID: relPath, Path: relPath, ContentHash: hash, Superseded: true}, nil return capture.Ref{ID: relPath, Path: relPath, ContentHash: hash, Superseded: true, Unlinked: unlinked}, nil
} }
// Get fetches a note by id/path — the read-after-write confirmation // Get fetches a note by id/path — the read-after-write confirmation
@@ -83,3 +83,45 @@ func TestStoreGetRoundTripsHash(t *testing.T) {
assert.Equal(t, "a", note.Frontmatter["wing"]) assert.Equal(t, "a", note.Frontmatter["wing"])
assert.Contains(t, note.Body, "# Body") assert.Contains(t, note.Body, "# Body")
} }
func TestStoreWriteUnwrapsUnresolvedWikilinks(t *testing.T) {
dir := t.TempDir()
s := brainstore.New(dir)
_, err := s.Write(context.Background(), capture.Note{
Content: "# Target\n\nbody\n", Filename: "target", Wing: "a", Hall: "facts",
})
require.NoError(t, err)
ref, err := s.Write(context.Background(), capture.Note{
Content: "See [[target]] and [[secret-hygiene]].\n",
Filename: "src", Wing: "a", Hall: "facts",
})
require.NoError(t, err)
assert.Equal(t, []string{"secret-hygiene"}, ref.Unlinked)
got, err := os.ReadFile(filepath.Join(dir, "wiki/a/facts/src.md"))
require.NoError(t, err)
assert.Contains(t, string(got), "[[target]]")
assert.Contains(t, string(got), "and secret-hygiene.")
assert.NotContains(t, string(got), "[[secret-hygiene]]")
}
func TestStoreUpdateUnwrapsUnresolvedWikilinks(t *testing.T) {
dir := t.TempDir()
s := brainstore.New(dir)
_, err := s.Write(context.Background(), capture.Note{
Content: "old\n", Filename: "n", Wing: "a", Hall: "facts",
})
require.NoError(t, err)
ref, err := s.Update(context.Background(), "n", capture.Note{
Content: "Related: [[cad-babysit]].\n", Wing: "a", Hall: "facts", Reason: "r",
})
require.NoError(t, err)
assert.Equal(t, []string{"cad-babysit"}, ref.Unlinked)
got, err := os.ReadFile(filepath.Join(dir, "wiki/a/facts/n.md"))
require.NoError(t, err)
assert.Contains(t, string(got), "Related: cad-babysit.")
assert.NotContains(t, string(got), "[[cad-babysit]]")
}
+2 -18
View File
@@ -1,8 +1,7 @@
// Package capture is the Clean-Architecture use-case for the uniform // Package capture is the Clean-Architecture use-case for the uniform
// capture capability (issue #49/#51): persist a finished session's // capture capability (issue #49/#51): persist a finished session's
// valuable output — insights → brain, action items → Gitea tickets, // valuable output — insights → brain, action items → Gitea tickets —
// optional summary → ai-sessions — with one invocation, identical core // with one invocation, identical core behaviour across every harness.
// behaviour across every harness.
// //
// This package is pure orchestration. It depends only on ports // This package is pure orchestration. It depends only on ports
// (interfaces) and plain entities — no HTTP, no live Gitea, no embedding // (interfaces) and plain entities — no HTTP, no live Gitea, no embedding
@@ -83,19 +82,11 @@ type Ticket struct {
Body string Body string
} }
// Summary is an optional session summary bound for ai-sessions.
type Summary struct {
Title string
Body string
ReposTouched []string
}
// CaptureInput is the whole capture request. // CaptureInput is the whole capture request.
type CaptureInput struct { type CaptureInput struct {
Context CaptureContext Context CaptureContext
Insights []Insight Insights []Insight
Tickets []Ticket Tickets []Ticket
Summary *Summary
DryRun bool DryRun bool
} }
@@ -117,12 +108,6 @@ type TicketResult struct {
OK bool `json:"ok"` OK bool `json:"ok"`
} }
// SummaryResult is the summary outcome in the receipt.
type SummaryResult struct {
Path string `json:"path,omitempty"`
OK bool `json:"ok"`
}
// ItemError pins a failure to a specific request item for the partial // ItemError pins a failure to a specific request item for the partial
// receipt. Item is a stable locator like "insight[1]" or "ticket[0]". // receipt. Item is a stable locator like "insight[1]" or "ticket[0]".
type ItemError struct { type ItemError struct {
@@ -136,7 +121,6 @@ type ItemError struct {
type CaptureReceipt struct { type CaptureReceipt struct {
Insights []InsightResult `json:"insights"` Insights []InsightResult `json:"insights"`
Tickets []TicketResult `json:"tickets"` Tickets []TicketResult `json:"tickets"`
Summary *SummaryResult `json:"summary,omitempty"`
Errors []ItemError `json:"errors"` Errors []ItemError `json:"errors"`
EffectiveClassification string `json:"effective_classification,omitempty"` EffectiveClassification string `json:"effective_classification,omitempty"`
DryRun bool `json:"dry_run"` DryRun bool `json:"dry_run"`
+6 -10
View File
@@ -15,6 +15,10 @@ type Ref struct {
Path string Path string
ContentHash string ContentHash string
Superseded bool Superseded bool
// Unlinked names the [[wikilink]] targets the store unwrapped to plain
// text because they resolve to no entry. Reported rather than rejected:
// see brain.StripUnresolvedLinks for why the write still lands.
Unlinked []string
} }
// StoredNote is a brain note fetched by Get: the read-after-write // StoredNote is a brain note fetched by Get: the read-after-write
@@ -27,17 +31,14 @@ type StoredNote struct {
Body string Body string
} }
// Note is the brain-write payload. It carries both the wing/hall taxonomy // Note is the brain-write payload: wing+hall are the only routing fields
// and the legacy type/domain fields so a single BrainStore serves both // (the legacy type/domain params were removed — ADR-0012 / #79). Reason is
// capture insights and the existing MCP brain_write surface. Reason is
// the supersede rationale, used only by Update. // the supersede rationale, used only by Update.
type Note struct { type Note struct {
Content string Content string
Filename string Filename string
Wing string Wing string
Hall string Hall string
Type string
Domain string
Reason string Reason string
} }
@@ -69,11 +70,6 @@ type IssueTracker interface {
CommentIssue(ctx context.Context, repo string, number int, body string) (IssueRef, error) CommentIssue(ctx context.Context, repo string, number int, body string) (IssueRef, error)
} }
// SummaryWriter is the ai-sessions summary port.
type SummaryWriter interface {
WriteFile(ctx context.Context, repo, path, content string) error
}
// ClassificationPolicy derives a target's sensitivity (model C). The // ClassificationPolicy derives a target's sensitivity (model C). The
// "stricter wins" combination of declared vs derived is use-case policy // "stricter wins" combination of declared vs derived is use-case policy
// and lives in the service, so the port stays minimal. Satisfied by // and lives in the service, so the port stays minimal. Satisfied by
+49 -97
View File
@@ -2,8 +2,6 @@ package capture
import ( import (
"context" "context"
"crypto/sha256"
"encoding/hex"
"fmt" "fmt"
"strings" "strings"
"time" "time"
@@ -14,22 +12,19 @@ import (
// Service is the CaptureSession use-case. It depends only on ports. // Service is the CaptureSession use-case. It depends only on ports.
type Service struct { type Service struct {
brain BrainStore brain BrainStore
issues IssueTracker issues IssueTracker
summaries SummaryWriter policy ClassificationPolicy
policy ClassificationPolicy audit AuditSink
audit AuditSink
// now is the clock, injectable for deterministic summary paths and // now is the clock, injectable for deterministic audit timestamps in
// audit timestamps in tests. // tests.
now func() time.Time now func() time.Time
} }
// NewService constructs a Service from its ports. summaries may be nil // NewService constructs a Service from its ports.
// when no summary persistence is wired; a CaptureInput with a Summary func NewService(b BrainStore, tr IssueTracker, p ClassificationPolicy, a AuditSink) *Service {
// then fails that item rather than panicking. return &Service{brain: b, issues: tr, policy: p, audit: a, now: time.Now}
func NewService(b BrainStore, tr IssueTracker, sw SummaryWriter, p ClassificationPolicy, a AuditSink) *Service {
return &Service{brain: b, issues: tr, summaries: sw, policy: p, audit: a, now: time.Now}
} }
var validActions = map[string]bool{"create": true, "close": true, "comment": true} var validActions = map[string]bool{"create": true, "close": true, "comment": true}
@@ -88,7 +83,7 @@ func (s *Service) Capture(ctx context.Context, in CaptureInput) (CaptureReceipt,
declared, _ = classification.ParseLevel(in.Context.Classification) declared, _ = classification.ParseLevel(in.Context.Classification)
} }
effective, securityEvents := s.resolveClassification(declared, in) effective, securityEvents, escalators := s.resolveClassification(declared, in)
// Server-derived origin governs the I1 gate; a caller-asserted harness // Server-derived origin governs the I1 gate; a caller-asserted harness
// label that names a different zone is descriptive-only and logged as a // label that names a different zone is descriptive-only and logged as a
@@ -112,8 +107,8 @@ func (s *Service) Capture(ctx context.Context, in CaptureInput) (CaptureReceipt,
Items: nil, // refused before any write Items: nil, // refused before any write
SecurityEvents: append(securityEvents, "I1 refusal: confidential capture via us-nexus origin"), SecurityEvents: append(securityEvents, "I1 refusal: confidential capture via us-nexus origin"),
}, AuditCentral) }, AuditCentral)
return CaptureReceipt{}, fmt.Errorf("%w: effective classification confidential through %s origin", return CaptureReceipt{}, fmt.Errorf("%w: effective classification confidential through %s origin (%s)",
ErrSovereigntyRefused, in.Context.Origin) ErrSovereigntyRefused, in.Context.Origin, escalationReason(escalators))
} }
receipt := CaptureReceipt{ receipt := CaptureReceipt{
@@ -131,9 +126,6 @@ func (s *Service) Capture(ctx context.Context, in CaptureInput) (CaptureReceipt,
for _, tk := range in.Tickets { for _, tk := range in.Tickets {
receipt.Tickets = append(receipt.Tickets, TicketResult{Repo: tk.Repo, Action: tk.Action, Number: tk.Number, OK: true}) receipt.Tickets = append(receipt.Tickets, TicketResult{Repo: tk.Repo, Action: tk.Action, Number: tk.Number, OK: true})
} }
if in.Summary != nil {
receipt.Summary = &SummaryResult{Path: s.summaryPath(in.Context, in.Summary), OK: true}
}
return receipt, nil return receipt, nil
} }
@@ -169,16 +161,6 @@ func (s *Service) Capture(ctx context.Context, in CaptureInput) (CaptureReceipt,
landed = append(landed, fmt.Sprintf("ticket:%s#%d", tk.Repo, res.Number)) landed = append(landed, fmt.Sprintf("ticket:%s#%d", tk.Repo, res.Number))
} }
if in.Summary != nil {
res, err := s.persistSummary(ctx, in.Context, in.Summary)
receipt.Summary = &res
if err != nil {
receipt.Errors = append(receipt.Errors, ItemError{Item: "summary", Error: err.Error()})
} else {
landed = append(landed, "summary:"+res.Path)
}
}
// I5: persist the request-level audit record of exactly what landed, // I5: persist the request-level audit record of exactly what landed,
// using the outcome reserved before the writes. AuditBuffered surfaces // using the outcome reserved before the writes. AuditBuffered surfaces
// the degraded (locally-buffered) state on the receipt. // the degraded (locally-buffered) state on the receipt.
@@ -239,15 +221,28 @@ func (s *Service) validate(in CaptureInput) error {
return nil return nil
} }
// resolveClassification computes the effective level (stricter of // resolveClassification computes the effective level (stricter of declared
// declared and every target's derived level) and collects a security // and every target's derived level), collects a security event whenever the
// event whenever the caller under-declared relative to a target floor. // caller under-declared relative to a target floor, and names the targets
func (s *Service) resolveClassification(declared classification.Level, in CaptureInput) (classification.Level, []string) { // that carry the strictest level.
//
// That third return is what makes an I1 refusal actionable. A caller sending
// twenty tickets gets one refusal; without the offending target it cannot
// tell which repo tripped the gate, and infra#265 shows what happens next —
// the caller concluded the tickets ARRAY was broken, built a fallback of
// twenty individual calls, and filed a bug against the wrong thing.
func (s *Service) resolveClassification(declared classification.Level, in CaptureInput) (classification.Level, []string, []string) {
effective := declared effective := declared
var events []string var events []string
derivedFor := map[string]classification.Level{}
var order []string
consider := func(kind classification.TargetKind, name string) { consider := func(kind classification.TargetKind, name string) {
derived := s.policy.Derive(classification.Target{Kind: kind, Name: name}) derived := s.policy.Derive(classification.Target{Kind: kind, Name: name})
effective = classification.Stricter(effective, derived) effective = classification.Stricter(effective, derived)
if _, seen := derivedFor[name]; !seen {
derivedFor[name] = derived
order = append(order, name)
}
if declared < derived { if declared < derived {
events = append(events, fmt.Sprintf("classification under-declared: declared=%s target=%s(%s) derived=%s", events = append(events, fmt.Sprintf("classification under-declared: declared=%s target=%s(%s) derived=%s",
declared, name, kindString(kind), derived)) declared, name, kindString(kind), derived))
@@ -259,12 +254,28 @@ func (s *Service) resolveClassification(declared classification.Level, in Captur
for _, tk := range in.Tickets { for _, tk := range in.Tickets {
consider(classification.RepoTarget, tk.Repo) consider(classification.RepoTarget, tk.Repo)
} }
if in.Summary != nil {
for _, repo := range in.Summary.ReposTouched { // Only targets that actually reach the effective level are named: at
consider(classification.RepoTarget, repo) // twenty tickets, listing the innocent ones is noise that hides the one
// that matters.
var escalators []string
for _, name := range order {
if derivedFor[name] == effective && effective > declared {
escalators = append(escalators, name)
} }
} }
return effective, events return effective, events, escalators
}
// escalationReason renders why the effective classification landed where it
// did, for an operator reading a refusal. Naming the caller's own declaration
// matters as much as naming a target: "you asked for this" and "a repo you
// touched required it" call for different fixes.
func escalationReason(escalators []string) string {
if len(escalators) == 0 {
return "declared by the caller; no target required it"
}
return "required by: " + strings.Join(escalators, ", ")
} }
func (s *Service) persistInsight(ctx context.Context, ins Insight) (InsightResult, string, error) { func (s *Service) persistInsight(ctx context.Context, ins Insight) (InsightResult, string, error) {
@@ -309,60 +320,6 @@ func (s *Service) persistTicket(ctx context.Context, tk Ticket) (TicketResult, e
return res, nil return res, nil
} }
func (s *Service) persistSummary(ctx context.Context, c CaptureContext, sum *Summary) (SummaryResult, error) {
if s.summaries == nil {
return SummaryResult{OK: false}, fmt.Errorf("no summary writer configured")
}
path := s.summaryPath(c, sum)
content := s.renderSummary(c, sum)
repo := "ai-sessions"
if err := s.summaries.WriteFile(ctx, repo, path, content); err != nil {
return SummaryResult{Path: path, OK: false}, err
}
return SummaryResult{Path: path, OK: true}, nil
}
// summaryPath builds summaries/<harness>/<YYYY-MM>/<date>-<slug>-<ref8>.md.
// The ref8 disambiguator is derived from the session_ref (or the title
// when no ref is present) so distinct sessions never collide.
func (s *Service) summaryPath(c CaptureContext, sum *Summary) string {
t := s.now().UTC()
slug := brain.Sanitise(sum.Title)
if slug == "" {
slug = "summary"
}
seed := c.SessionRef
if seed == "" {
seed = sum.Title + sum.Body
}
sum8 := shortHash(seed)
return fmt.Sprintf("summaries/%s/%s/%s-%s-%s.md",
brain.Sanitise(c.Harness), t.Format("2006-01"), t.Format("2006-01-02"), slug, sum8)
}
// renderSummary stamps fidelity + session metadata into frontmatter so the
// richer-fidelity-supersedes-thinner collision rule has the data it needs.
func (s *Service) renderSummary(c CaptureContext, sum *Summary) string {
var b strings.Builder
b.WriteString("---\n")
fmt.Fprintf(&b, "title: %s\n", sum.Title)
fmt.Fprintf(&b, "harness: %s\n", c.Harness)
if c.SessionRef != "" {
fmt.Fprintf(&b, "session_ref: %s\n", c.SessionRef)
}
fmt.Fprintf(&b, "fidelity: %s\n", c.Fidelity)
fmt.Fprintf(&b, "captured_at: %s\n", s.now().UTC().Format(time.RFC3339))
if len(sum.ReposTouched) > 0 {
fmt.Fprintf(&b, "repos_touched: [%s]\n", strings.Join(sum.ReposTouched, ", "))
}
b.WriteString("---\n\n")
b.WriteString(sum.Body)
if !strings.HasSuffix(sum.Body, "\n") {
b.WriteByte('\n')
}
return b.String()
}
func kindString(k classification.TargetKind) string { func kindString(k classification.TargetKind) string {
if k == classification.RepoTarget { if k == classification.RepoTarget {
return "repo" return "repo"
@@ -381,8 +338,3 @@ func firstLine(s string) string {
} }
return s return s
} }
func shortHash(s string) string {
sum := sha256.Sum256([]byte(s))
return hex.EncodeToString(sum[:])[:8]
}
+122 -53
View File
@@ -3,6 +3,7 @@ package capture
import ( import (
"context" "context"
"errors" "errors"
"fmt"
"strings" "strings"
"testing" "testing"
"time" "time"
@@ -59,12 +60,18 @@ type fakeTracker struct {
closed []int closed []int
comments []int comments []int
err error err error
// failOnTitle makes CreateIssue fail for one specific title, so a
// partial-failure receipt can be exercised without failing every item.
failOnTitle string
} }
func (f *fakeTracker) CreateIssue(_ context.Context, repo, title, _ string) (IssueRef, error) { func (f *fakeTracker) CreateIssue(_ context.Context, repo, title, _ string) (IssueRef, error) {
if f.err != nil { if f.err != nil {
return IssueRef{}, f.err return IssueRef{}, f.err
} }
if f.failOnTitle != "" && title == f.failOnTitle {
return IssueRef{}, errors.New("tracker refused this one")
}
f.created = append(f.created, repo+":"+title) f.created = append(f.created, repo+":"+title)
return IssueRef{Repo: repo, Number: 100 + len(f.created), URL: "https://git/" + repo + "/issues/x"}, nil return IssueRef{Repo: repo, Number: 100 + len(f.created), URL: "https://git/" + repo + "/issues/x"}, nil
} }
@@ -85,24 +92,11 @@ func (f *fakeTracker) CommentIssue(_ context.Context, repo string, number int, _
return IssueRef{Repo: repo, Number: number}, nil return IssueRef{Repo: repo, Number: number}, nil
} }
type fakeSummary struct {
paths []string
content []string
err error
}
func (f *fakeSummary) WriteFile(_ context.Context, _, path, content string) error {
if f.err != nil {
return f.err
}
f.paths = append(f.paths, path)
f.content = append(f.content, content)
return nil
}
// fakePolicy derives from an explicit map; default Internal so tests pin // fakePolicy derives from an explicit map; default Internal so tests pin
// behaviour without depending on the real defaulting. // behaviour without depending on the real defaulting.
type fakePolicy struct{ tags map[string]classification.Level } type fakePolicy struct {
tags map[string]classification.Level
}
func (p fakePolicy) Derive(t classification.Target) classification.Level { func (p fakePolicy) Derive(t classification.Target) classification.Level {
if lvl, ok := p.tags[t.Name]; ok { if lvl, ok := p.tags[t.Name]; ok {
@@ -135,8 +129,8 @@ func (f *fakeAudit) Record(_ context.Context, e AuditEntry, _ AuditOutcome) erro
// --- helpers --- // --- helpers ---
func newSvc(b BrainStore, tr IssueTracker, sw SummaryWriter, p ClassificationPolicy, a AuditSink) *Service { func newSvc(b BrainStore, tr IssueTracker, p ClassificationPolicy, a AuditSink) *Service {
s := NewService(b, tr, sw, p, a) s := NewService(b, tr, p, a)
s.now = func() time.Time { return time.Date(2026, 6, 22, 12, 0, 0, 0, time.UTC) } s.now = func() time.Time { return time.Date(2026, 6, 22, 12, 0, 0, 0, time.UTC) }
return s return s
} }
@@ -151,7 +145,7 @@ func TestCaptureHappyPath(t *testing.T) {
b := &fakeBrain{} b := &fakeBrain{}
tr := &fakeTracker{} tr := &fakeTracker{}
au := &fakeAudit{} au := &fakeAudit{}
svc := newSvc(b, tr, nil, fakePolicy{}, au) svc := newSvc(b, tr, fakePolicy{}, au)
rec, err := svc.Capture(context.Background(), CaptureInput{ rec, err := svc.Capture(context.Background(), CaptureInput{
Context: baseCtx(), Context: baseCtx(),
@@ -180,7 +174,7 @@ func TestCaptureHappyPath(t *testing.T) {
func TestCaptureSupersedeNotDuplicate(t *testing.T) { func TestCaptureSupersedeNotDuplicate(t *testing.T) {
b := &fakeBrain{} b := &fakeBrain{}
svc := newSvc(b, &fakeTracker{}, nil, fakePolicy{}, &fakeAudit{}) svc := newSvc(b, &fakeTracker{}, fakePolicy{}, &fakeAudit{})
rec, err := svc.Capture(context.Background(), CaptureInput{ rec, err := svc.Capture(context.Background(), CaptureInput{
Context: baseCtx(), Context: baseCtx(),
@@ -197,7 +191,7 @@ func TestCaptureValidationFailClosed(t *testing.T) {
b := &fakeBrain{} b := &fakeBrain{}
tr := &fakeTracker{} tr := &fakeTracker{}
au := &fakeAudit{} au := &fakeAudit{}
svc := newSvc(b, tr, nil, fakePolicy{}, au) svc := newSvc(b, tr, fakePolicy{}, au)
_, err := svc.Capture(context.Background(), CaptureInput{ _, err := svc.Capture(context.Background(), CaptureInput{
Context: baseCtx(), Context: baseCtx(),
@@ -216,7 +210,7 @@ func TestCaptureValidationFailClosed(t *testing.T) {
} }
func TestCaptureValidationRejectsBadTicket(t *testing.T) { func TestCaptureValidationRejectsBadTicket(t *testing.T) {
svc := newSvc(&fakeBrain{}, &fakeTracker{}, nil, fakePolicy{}, &fakeAudit{}) svc := newSvc(&fakeBrain{}, &fakeTracker{}, fakePolicy{}, &fakeAudit{})
_, err := svc.Capture(context.Background(), CaptureInput{ _, err := svc.Capture(context.Background(), CaptureInput{
Context: baseCtx(), Context: baseCtx(),
Tickets: []Ticket{{Repo: "hyperguild", Action: "frobnicate"}}, // bad action Tickets: []Ticket{{Repo: "hyperguild", Action: "frobnicate"}}, // bad action
@@ -239,7 +233,7 @@ func TestCapturePartialFailureBestEffort(t *testing.T) {
}} }}
tr := &fakeTracker{} tr := &fakeTracker{}
au := &fakeAudit{} au := &fakeAudit{}
svc := newSvc(b, tr, nil, fakePolicy{}, au) svc := newSvc(b, tr, fakePolicy{}, au)
rec, err := svc.Capture(context.Background(), CaptureInput{ rec, err := svc.Capture(context.Background(), CaptureInput{
Context: baseCtx(), Context: baseCtx(),
@@ -264,7 +258,7 @@ func TestCaptureDryRunWritesNothing(t *testing.T) {
b := &fakeBrain{} b := &fakeBrain{}
tr := &fakeTracker{} tr := &fakeTracker{}
au := &fakeAudit{} au := &fakeAudit{}
svc := newSvc(b, tr, nil, fakePolicy{}, au) svc := newSvc(b, tr, fakePolicy{}, au)
rec, err := svc.Capture(context.Background(), CaptureInput{ rec, err := svc.Capture(context.Background(), CaptureInput{
Context: baseCtx(), Context: baseCtx(),
@@ -287,7 +281,7 @@ func TestCaptureStricterClassificationWins(t *testing.T) {
b := &fakeBrain{} b := &fakeBrain{}
au := &fakeAudit{} au := &fakeAudit{}
pol := fakePolicy{tags: map[string]classification.Level{"client-seb": classification.Confidential}} pol := fakePolicy{tags: map[string]classification.Level{"client-seb": classification.Confidential}}
svc := newSvc(b, &fakeTracker{}, nil, pol, au) svc := newSvc(b, &fakeTracker{}, pol, au)
ctx := baseCtx() ctx := baseCtx()
ctx.Classification = "internal" ctx.Classification = "internal"
@@ -306,7 +300,7 @@ func TestCaptureCallerRaisingSensitivityHonoured(t *testing.T) {
// Caller declares confidential; target internal → effective confidential, NOT a security event. // Caller declares confidential; target internal → effective confidential, NOT a security event.
au := &fakeAudit{} au := &fakeAudit{}
pol := fakePolicy{tags: map[string]classification.Level{"hyperguild": classification.Internal}} pol := fakePolicy{tags: map[string]classification.Level{"hyperguild": classification.Internal}}
svc := newSvc(&fakeBrain{}, &fakeTracker{}, nil, pol, au) svc := newSvc(&fakeBrain{}, &fakeTracker{}, pol, au)
ctx := baseCtx() ctx := baseCtx()
ctx.Classification = "confidential" ctx.Classification = "confidential"
@@ -319,26 +313,6 @@ func TestCaptureCallerRaisingSensitivityHonoured(t *testing.T) {
assert.Empty(t, au.entries[0].SecurityEvents, "raising sensitivity is honoured, not flagged") assert.Empty(t, au.entries[0].SecurityEvents, "raising sensitivity is honoured, not flagged")
} }
func TestCaptureSummaryPathAndFidelity(t *testing.T) {
sw := &fakeSummary{}
svc := newSvc(&fakeBrain{}, &fakeTracker{}, sw, fakePolicy{}, &fakeAudit{})
ctx := baseCtx()
ctx.Fidelity = "transcript-parse"
ctx.SessionRef = "abc123def456"
rec, err := svc.Capture(context.Background(), CaptureInput{
Context: ctx,
Summary: &Summary{Title: "Session Wrap", Body: "did stuff", ReposTouched: []string{"hyperguild"}},
})
require.NoError(t, err)
require.NotNil(t, rec.Summary)
assert.True(t, rec.Summary.OK)
require.Len(t, sw.paths, 1)
assert.True(t, strings.HasPrefix(sw.paths[0], "summaries/claude-code/2026-06/"), "path: %s", sw.paths[0])
assert.Contains(t, sw.paths[0], "session-wrap")
assert.Contains(t, sw.content[0], "fidelity: transcript-parse", "fidelity stamped in frontmatter")
}
// --- I1 sovereignty gate (#53) --- // --- I1 sovereignty gate (#53) ---
func TestCaptureRefusesConfidentialViaUSNexus(t *testing.T) { func TestCaptureRefusesConfidentialViaUSNexus(t *testing.T) {
@@ -346,7 +320,7 @@ func TestCaptureRefusesConfidentialViaUSNexus(t *testing.T) {
tr := &fakeTracker{} tr := &fakeTracker{}
au := &fakeAudit{} au := &fakeAudit{}
pol := fakePolicy{tags: map[string]classification.Level{"client-seb": classification.Confidential}} pol := fakePolicy{tags: map[string]classification.Level{"client-seb": classification.Confidential}}
svc := newSvc(b, tr, nil, pol, au) svc := newSvc(b, tr, pol, au)
ctx := baseCtx() ctx := baseCtx()
ctx.Classification = "confidential" ctx.Classification = "confidential"
@@ -368,7 +342,7 @@ func TestCaptureRefusesConfidentialViaUSNexus(t *testing.T) {
func TestCaptureAllowsConfidentialViaSovereign(t *testing.T) { func TestCaptureAllowsConfidentialViaSovereign(t *testing.T) {
b := &fakeBrain{} b := &fakeBrain{}
pol := fakePolicy{tags: map[string]classification.Level{"client-seb": classification.Confidential}} pol := fakePolicy{tags: map[string]classification.Level{"client-seb": classification.Confidential}}
svc := newSvc(b, &fakeTracker{}, nil, pol, &fakeAudit{}) svc := newSvc(b, &fakeTracker{}, pol, &fakeAudit{})
ctx := baseCtx() ctx := baseCtx()
ctx.Classification = "confidential" ctx.Classification = "confidential"
@@ -387,7 +361,7 @@ func TestCaptureAssertedLabelIgnoredAndLogged(t *testing.T) {
// us-nexus; confidential ⇒ refused, and the discrepancy is a security event. // us-nexus; confidential ⇒ refused, and the discrepancy is a security event.
au := &fakeAudit{} au := &fakeAudit{}
pol := fakePolicy{tags: map[string]classification.Level{"client-seb": classification.Confidential}} pol := fakePolicy{tags: map[string]classification.Level{"client-seb": classification.Confidential}}
svc := newSvc(&fakeBrain{}, &fakeTracker{}, nil, pol, au) svc := newSvc(&fakeBrain{}, &fakeTracker{}, pol, au)
ctx := baseCtx() ctx := baseCtx()
ctx.Harness = "sovereign-soil" // asserted ctx.Harness = "sovereign-soil" // asserted
@@ -407,7 +381,7 @@ func TestCaptureAssertedLabelIgnoredAndLogged(t *testing.T) {
func TestCaptureInternalViaUSNexusAllowed(t *testing.T) { func TestCaptureInternalViaUSNexusAllowed(t *testing.T) {
// us-nexus origin is fine for non-confidential data. // us-nexus origin is fine for non-confidential data.
b := &fakeBrain{} b := &fakeBrain{}
svc := newSvc(b, &fakeTracker{}, nil, fakePolicy{}, &fakeAudit{}) svc := newSvc(b, &fakeTracker{}, fakePolicy{}, &fakeAudit{})
ctx := baseCtx() ctx := baseCtx()
ctx.Origin = ZoneUSNexus // internal classification, so gate doesn't fire ctx.Origin = ZoneUSNexus // internal classification, so gate doesn't fire
rec, err := svc.Capture(context.Background(), CaptureInput{ rec, err := svc.Capture(context.Background(), CaptureInput{
@@ -426,7 +400,7 @@ func TestCaptureRefusesWhenAuditReserveFails(t *testing.T) {
b := &fakeBrain{} b := &fakeBrain{}
tr := &fakeTracker{} tr := &fakeTracker{}
au := &fakeAudit{reserveErr: errors.New("central sink unreachable")} au := &fakeAudit{reserveErr: errors.New("central sink unreachable")}
svc := newSvc(b, tr, nil, fakePolicy{}, au) svc := newSvc(b, tr, fakePolicy{}, au)
_, err := svc.Capture(context.Background(), CaptureInput{ _, err := svc.Capture(context.Background(), CaptureInput{
Context: baseCtx(), Context: baseCtx(),
@@ -443,7 +417,7 @@ func TestCaptureFlagsLocallyBufferedAudit(t *testing.T) {
// proceeds and the receipt flags the degraded audit state. // proceeds and the receipt flags the degraded audit state.
b := &fakeBrain{} b := &fakeBrain{}
au := &fakeAudit{reserveMode: AuditBuffered} au := &fakeAudit{reserveMode: AuditBuffered}
svc := newSvc(b, &fakeTracker{}, nil, fakePolicy{}, au) svc := newSvc(b, &fakeTracker{}, fakePolicy{}, au)
rec, err := svc.Capture(context.Background(), CaptureInput{ rec, err := svc.Capture(context.Background(), CaptureInput{
Context: baseCtx(), Context: baseCtx(),
@@ -458,7 +432,7 @@ func TestCaptureFlagsLocallyBufferedAudit(t *testing.T) {
func TestCaptureDryRunSkipsAuditGate(t *testing.T) { func TestCaptureDryRunSkipsAuditGate(t *testing.T) {
// dry_run must not even probe the audit sink (writes nothing anywhere). // dry_run must not even probe the audit sink (writes nothing anywhere).
au := &fakeAudit{reserveErr: errors.New("would refuse")} au := &fakeAudit{reserveErr: errors.New("would refuse")}
svc := newSvc(&fakeBrain{}, &fakeTracker{}, nil, fakePolicy{}, au) svc := newSvc(&fakeBrain{}, &fakeTracker{}, fakePolicy{}, au)
rec, err := svc.Capture(context.Background(), CaptureInput{ rec, err := svc.Capture(context.Background(), CaptureInput{
Context: baseCtx(), Context: baseCtx(),
@@ -469,3 +443,98 @@ func TestCaptureDryRunSkipsAuditGate(t *testing.T) {
assert.True(t, rec.DryRun) assert.True(t, rec.DryRun)
assert.Empty(t, au.entries) assert.Empty(t, au.entries)
} }
// ---- hyperguild#91 part 1 -------------------------------------------------
//
// The reported symptom was "capture with a tickets array fails" (infra#265:
// 20 tickets errored, 5 errored, caller fell back to 20 individual
// issue_create calls). The array was never the failing dimension — every
// ticket targeted a client repo, and the I1 gate refuses that through a
// us-nexus origin at ANY length. The refusal did not say which target
// escalated the classification, so it read as a malfunction.
func TestCapture_TicketsArrayWorksAtLengthOne(t *testing.T) {
b, tr, au := &fakeBrain{}, &fakeTracker{}, &fakeAudit{}
svc := newSvc(b, tr, fakePolicy{}, au)
rec, err := svc.Capture(context.Background(), CaptureInput{
Context: baseCtx(),
Tickets: []Ticket{{Repo: "hyperguild", Action: "create", Title: "one", Body: "b"}},
})
require.NoError(t, err)
require.Len(t, rec.Tickets, 1)
assert.True(t, rec.Tickets[0].OK)
assert.Len(t, tr.created, 1)
assert.Empty(t, rec.Errors)
}
func TestCapture_TicketsArrayWorksAtLengthMany(t *testing.T) {
b, tr, au := &fakeBrain{}, &fakeTracker{}, &fakeAudit{}
svc := newSvc(b, tr, fakePolicy{}, au)
in := CaptureInput{Context: baseCtx()}
for i := range 20 {
in.Tickets = append(in.Tickets, Ticket{
Repo: "hyperguild", Action: "create", Title: fmt.Sprintf("t%02d", i), Body: "b",
})
}
rec, err := svc.Capture(context.Background(), in)
require.NoError(t, err)
require.Len(t, rec.Tickets, 20, "one receipt entry per ticket")
for i, r := range rec.Tickets {
assert.True(t, r.OK, "ticket %d failed: %+v", i, rec.Errors)
}
assert.Len(t, tr.created, 20)
assert.Empty(t, rec.Errors)
}
func TestCapture_OneFailingTicketDoesNotSinkTheRest(t *testing.T) {
// infra#265 asked explicitly: "if ticket 3 of 5 fails, what happened to
// 1 and 2?" They land, and the receipt says so per item.
b, au := &fakeBrain{}, &fakeAudit{}
tr := &fakeTracker{failOnTitle: "boom"}
svc := newSvc(b, tr, fakePolicy{}, au)
rec, err := svc.Capture(context.Background(), CaptureInput{
Context: baseCtx(),
Tickets: []Ticket{
{Repo: "hyperguild", Action: "create", Title: "ok-1", Body: "b"},
{Repo: "hyperguild", Action: "create", Title: "boom", Body: "b"},
{Repo: "hyperguild", Action: "create", Title: "ok-3", Body: "b"},
},
})
require.NoError(t, err, "a per-item failure is a partial receipt, not a call error")
require.Len(t, rec.Tickets, 3)
assert.True(t, rec.Tickets[0].OK)
assert.False(t, rec.Tickets[1].OK)
assert.True(t, rec.Tickets[2].OK)
require.Len(t, rec.Errors, 1)
assert.Contains(t, rec.Errors[0].Item, "ticket[1]")
}
func TestCapture_I1RefusalNamesWhatEscalatedTheClassification(t *testing.T) {
// The actual defect behind infra#265. Without the offending target in
// the message, a caller with 20 tickets cannot tell which repo tripped
// the gate — and reasonably concludes the array itself is broken.
b, tr, au := &fakeBrain{}, &fakeTracker{}, &fakeAudit{}
pol := fakePolicy{tags: map[string]classification.Level{"trucker-ecommerce": classification.Confidential}}
svc := newSvc(b, tr, pol, au)
ctx := baseCtx()
ctx.Origin = ZoneUSNexus
_, err := svc.Capture(context.Background(), CaptureInput{
Context: ctx,
Tickets: []Ticket{
{Repo: "hyperguild", Action: "create", Title: "fine", Body: "b"},
{Repo: "trucker-ecommerce", Action: "create", Title: "client work", Body: "b"},
},
})
require.ErrorIs(t, err, ErrSovereigntyRefused)
assert.Contains(t, err.Error(), "trucker-ecommerce",
"the refusal must name the target that escalated the classification")
assert.NotContains(t, err.Error(), "hyperguild",
"only the offending target, or the message is noise at 20 tickets")
assert.Empty(t, tr.created, "refused before any write")
}
-15
View File
@@ -55,7 +55,6 @@ type request struct {
Context contextBody `json:"context"` Context contextBody `json:"context"`
Insights []insightBody `json:"insights"` Insights []insightBody `json:"insights"`
Tickets []ticketBody `json:"tickets"` Tickets []ticketBody `json:"tickets"`
Summary *summaryBody `json:"summary,omitempty"`
DryRun bool `json:"dry_run"` DryRun bool `json:"dry_run"`
} }
@@ -82,12 +81,6 @@ type ticketBody struct {
Body string `json:"body,omitempty"` Body string `json:"body,omitempty"`
} }
type summaryBody struct {
Title string `json:"title"`
Body string `json:"body"`
ReposTouched []string `json:"repos_touched,omitempty"`
}
// ServeHTTP authenticates, derives origin, runs the use-case, and maps the // ServeHTTP authenticates, derives origin, runs the use-case, and maps the
// result to an HTTP status. // result to an HTTP status.
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
@@ -183,11 +176,6 @@ func (b request) toInput() capture.CaptureInput {
Repo: t.Repo, Action: t.Action, Number: t.Number, Title: t.Title, Body: t.Body, Repo: t.Repo, Action: t.Action, Number: t.Number, Title: t.Title, Body: t.Body,
}) })
} }
if b.Summary != nil {
in.Summary = &capture.Summary{
Title: b.Summary.Title, Body: b.Summary.Body, ReposTouched: b.Summary.ReposTouched,
}
}
return in return in
} }
@@ -204,9 +192,6 @@ func statusFor(rec capture.CaptureReceipt) int {
for _, t := range rec.Tickets { for _, t := range rec.Tickets {
count(&ok, &fail, t.OK) count(&ok, &fail, t.OK)
} }
if rec.Summary != nil {
count(&ok, &fail, rec.Summary.OK)
}
switch { switch {
case fail == 0: case fail == 0:
return http.StatusOK return http.StatusOK
@@ -38,9 +38,11 @@ func (f fakeTracker) CreateIssue(context.Context, string, string, string) (captu
} }
return capture.IssueRef{Repo: "hyperguild", Number: 1, URL: "https://git/1"}, nil return capture.IssueRef{Repo: "hyperguild", Number: 1, URL: "https://git/1"}, nil
} }
func (fakeTracker) CloseIssue(context.Context, string, int, string) (capture.IssueRef, error) { func (fakeTracker) CloseIssue(context.Context, string, int, string) (capture.IssueRef, error) {
return capture.IssueRef{}, nil return capture.IssueRef{}, nil
} }
func (fakeTracker) CommentIssue(context.Context, string, int, string) (capture.IssueRef, error) { func (fakeTracker) CommentIssue(context.Context, string, int, string) (capture.IssueRef, error) {
return capture.IssueRef{}, nil return capture.IssueRef{}, nil
} }
@@ -49,7 +51,7 @@ func newHandler(t *testing.T, v capturehttp.Validator, tr capture.IssueTracker,
t.Helper() t.Helper()
cfg, err := classification.Load(t.TempDir()) cfg, err := classification.Load(t.TempDir())
require.NoError(t, err) require.NoError(t, err)
svc := capture.NewService(brainstore.New(t.TempDir()), tr, nil, cfg, audit.NewSlogSink(nil)) svc := capture.NewService(brainstore.New(t.TempDir()), tr, cfg, audit.NewSlogSink(nil))
return capturehttp.New(svc, v, staticTok, "local-cli", capturehttp.NewOriginResolver(sovereign)) return capturehttp.New(svc, v, staticTok, "local-cli", capturehttp.NewOriginResolver(sovereign))
} }
@@ -183,6 +185,7 @@ type refusingAudit struct{}
func (refusingAudit) Reserve(context.Context, classification.Level) (capture.AuditOutcome, error) { func (refusingAudit) Reserve(context.Context, classification.Level) (capture.AuditOutcome, error) {
return 0, errors.New("central audit sink unreachable") return 0, errors.New("central audit sink unreachable")
} }
func (refusingAudit) Record(context.Context, capture.AuditEntry, capture.AuditOutcome) error { func (refusingAudit) Record(context.Context, capture.AuditEntry, capture.AuditOutcome) error {
return nil return nil
} }
@@ -190,7 +193,7 @@ func (refusingAudit) Record(context.Context, capture.AuditEntry, capture.AuditOu
func TestAuditUnavailableIs503(t *testing.T) { func TestAuditUnavailableIs503(t *testing.T) {
cfg, err := classification.Load(t.TempDir()) cfg, err := classification.Load(t.TempDir())
require.NoError(t, err) require.NoError(t, err)
svc := capture.NewService(brainstore.New(t.TempDir()), fakeTracker{}, nil, cfg, refusingAudit{}) svc := capture.NewService(brainstore.New(t.TempDir()), fakeTracker{}, cfg, refusingAudit{})
h := capturehttp.New(svc, nil, staticTok, "local-cli", capturehttp.NewOriginResolver(nil)) h := capturehttp.New(svc, nil, staticTok, "local-cli", capturehttp.NewOriginResolver(nil))
rr := do(t, h, "Bearer "+staticTok, internalReq()) rr := do(t, h, "Bearer "+staticTok, internalReq())
+98
View File
@@ -0,0 +1,98 @@
// Package claim validates the claim-property frontmatter that says when and
// where a note's claim holds, and who decided that (brain#21).
//
// Two families were designed together and land separately. This is the
// applicability envelope:
//
// half_life: volatile | seasonal | durable — how fast it decays
// applies: local | homelab | universal — how widely it holds
// claim_provenance: asserted | inferred — who set the above
//
// The strength family (confidence, contested) follows once the ingest-time
// contradiction detector exists to populate it.
//
// Why the envelope is validated rather than merely accepted: a value outside
// the enum is worse than an absent one. A lint skips what it cannot parse, so
// the note reads as classified while nothing acts on it — the field becomes
// decoration that suppresses the very review it was added to trigger.
//
// Why `applies` and not `scope`: `scope:` has been in use since brain#5 for
// glossary terms (`homelab-core`, `project:<repo>`) — a disjoint value space
// on the same key. The shipped schema keeps the name; this one takes another.
package claim
import (
"fmt"
"strings"
)
// Field names, exported so writers and lints agree on the spelling.
const (
FieldHalfLife = "half_life"
FieldApplies = "applies"
FieldProvenance = "claim_provenance"
)
var (
halfLives = []string{"volatile", "seasonal", "durable"}
appliesTo = []string{"local", "homelab", "universal"}
provenances = []string{"asserted", "inferred"}
)
// ValidateEnvelope checks the envelope fields of one note's frontmatter.
//
// Absent fields are valid: the envelope is opt-in for new writes, and a
// corpus-wide backfill is deliberately out of scope (brain#21) — inferring
// 1113 notes' properties in bulk has the same failure mode as the extraction
// pass that produced 28 wrong wikilinks out of 67.
func ValidateEnvelope(fm map[string]string) error {
halfLife, hasHalfLife := present(fm, FieldHalfLife)
applies, hasApplies := present(fm, FieldApplies)
prov, hasProv := present(fm, FieldProvenance)
if hasHalfLife {
if err := oneOf(FieldHalfLife, halfLife, halfLives); err != nil {
return err
}
}
if hasApplies {
if err := oneOf(FieldApplies, applies, appliesTo); err != nil {
return err
}
}
if hasProv {
if err := oneOf(FieldProvenance, prov, provenances); err != nil {
return err
}
}
// The field and its provenance travel together or not at all. A value
// whose author is unknown cannot be trusted differently from one Mathias
// asserted, which is how an inferred guess hardens into accepted fact.
switch {
case (hasHalfLife || hasApplies) && !hasProv:
return fmt.Errorf("%s is required when %s or %s is set",
FieldProvenance, FieldHalfLife, FieldApplies)
case hasProv && !hasHalfLife && !hasApplies:
return fmt.Errorf("%s is set but neither %s nor %s is",
FieldProvenance, FieldHalfLife, FieldApplies)
}
return nil
}
// present reports a trimmed field value and whether it was set to anything
// non-empty. A key written with an empty value is treated as absent rather
// than as an error: that is a caller emitting a placeholder, not asserting.
func present(fm map[string]string, key string) (string, bool) {
v := strings.TrimSpace(fm[key])
return v, v != ""
}
func oneOf(field, value string, allowed []string) error {
for _, a := range allowed {
if a == value {
return nil
}
}
return fmt.Errorf("%s: %q is not one of %s", field, value, strings.Join(allowed, ", "))
}
+89
View File
@@ -0,0 +1,89 @@
// Package claim_test covers the claim-property envelope (brain#21).
package claim_test
import (
"testing"
"github.com/mathiasbq/hyperguild/ingestion/internal/claim"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestValidateEnvelope(t *testing.T) {
tests := []struct {
name string
fm map[string]string
wantErr string
}{
{
name: "absent is fine — the fields are opt-in on new writes",
fm: map[string]string{"wing": "homelab", "hall": "facts"},
},
{
name: "complete envelope with provenance",
fm: map[string]string{
"half_life": "durable", "applies": "universal", "claim_provenance": "asserted",
},
},
{
name: "inferred provenance is equally valid — it just must be stated",
fm: map[string]string{
"half_life": "volatile", "applies": "local", "claim_provenance": "inferred",
},
},
{
// A value nobody can act on is worse than no value: a lint
// silently skips it, so the note looks classified and isn't.
name: "unknown half_life value",
fm: map[string]string{"half_life": "forever", "claim_provenance": "asserted"},
wantErr: `half_life: "forever" is not one of volatile, seasonal, durable`,
},
{
name: "unknown applies value",
fm: map[string]string{"applies": "galaxy", "claim_provenance": "asserted"},
wantErr: `applies: "galaxy" is not one of local, homelab, universal`,
},
{
// brain#21: a value a model inferred must never be
// indistinguishable from one Mathias asserted. Writing the field
// without saying who set it is exactly that laundering.
name: "envelope field without provenance",
fm: map[string]string{"half_life": "durable"},
wantErr: "claim_provenance is required when half_life or applies is set",
},
{
name: "applies without provenance",
fm: map[string]string{"applies": "homelab"},
wantErr: "claim_provenance is required when half_life or applies is set",
},
{
name: "unknown provenance value",
fm: map[string]string{"half_life": "durable", "claim_provenance": "probably"},
wantErr: `claim_provenance: "probably" is not one of asserted, inferred`,
},
{
// Provenance alone says who set fields that aren't there.
name: "provenance without any envelope field",
fm: map[string]string{"claim_provenance": "asserted"},
wantErr: "claim_provenance is set but neither half_life nor applies is",
},
{
// The glossary wing has used scope: homelab-core since #5. The
// envelope deliberately does NOT claim that key (brain#21).
name: "glossary scope is untouched",
fm: map[string]string{"scope": "homelab-core", "term": "koala"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := claim.ValidateEnvelope(tt.fm)
if tt.wantErr == "" {
assert.NoError(t, err)
return
}
require.Error(t, err)
assert.Contains(t, err.Error(), tt.wantErr)
})
}
}
@@ -43,6 +43,26 @@ var DefaultRules = []Rule{
// JSON, so both segments begin with "eyJ". // JSON, so both segments begin with "eyJ".
{Name: "jwt", RE: regexp.MustCompile(`eyJ[A-Za-z0-9_\-]{8,}\.eyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}`)}, {Name: "jwt", RE: regexp.MustCompile(`eyJ[A-Za-z0-9_\-]{8,}\.eyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}`)},
{Name: "postgres-uri-with-password", RE: regexp.MustCompile(`postgres(?:ql)?://[^:\s/]+:[^@\s/]+@`)}, {Name: "postgres-uri-with-password", RE: regexp.MustCompile(`postgres(?:ql)?://[^:\s/]+:[^@\s/]+@`)},
// Any credential embedded in a URL's userinfo, which is what a git credential
// store holds: `https://<user>:<token>@host`. The postgres rule above is the
// same shape narrowed to one scheme, and is kept ahead of this one only so a
// DSN reports the more specific name -- same ordering convention as
// authorization-header before bearer-token.
//
// Added after this shape passed ALL rules and was therefore ingested rather
// than dropped (hyperguild#142). It reached ~/.claude/projects -- this
// watcher's own input -- because a test suite in mathias/infra executed a
// script that configures git while inheriting the operator's real $HOME, read
// koala's live credential store, and printed it. Two credentials were rotated
// (infra#466). The scrubber is the control that decides whether that class of
// mistake is survivable, and for this shape it was failing open.
//
// The {8,} floor on the secret half is what keeps `https://host:443/path` and
// `https://user:@host` out; the `[^:\s/@]+` user half stops a host:port pair
// being read as userinfo. Both directions are covered by
// TestScrub_URLUserinfoCredential, because a rule that dropped every URL with
// a colon in it would discard most of the signal this watcher exists to keep.
{Name: "url-userinfo-credential", RE: regexp.MustCompile(`[a-zA-Z][a-zA-Z0-9+.\-]*://[^:\s/@]+:[^@\s/]{8,}@`)},
{Name: "private-key", RE: regexp.MustCompile(`-----BEGIN[^-]*PRIVATE KEY-----`)}, {Name: "private-key", RE: regexp.MustCompile(`-----BEGIN[^-]*PRIVATE KEY-----`)},
{Name: "ssh-key", RE: regexp.MustCompile(`ssh-(?:rsa|ed25519|ecdsa)\s+[A-Za-z0-9+/=]{40,}`)}, {Name: "ssh-key", RE: regexp.MustCompile(`ssh-(?:rsa|ed25519|ecdsa)\s+[A-Za-z0-9+/=]{40,}`)},
{Name: "github-pat", RE: regexp.MustCompile(`\b(?:ghp|gho|ghu|ghr|gha)_[A-Za-z0-9]{30,}\b`)}, {Name: "github-pat", RE: regexp.MustCompile(`\b(?:ghp|gho|ghu|ghr|gha)_[A-Za-z0-9]{30,}\b`)},
@@ -46,6 +46,64 @@ func TestScrub_PoisonedFixtures(t *testing.T) {
} }
} }
// A credential embedded in a URL's userinfo is the shape a git credential store
// holds -- `https://<user>:<token>@host` -- and it walked past every rule until
// hyperguild#142. There was a rule for `postgres://user:pass@` and nothing for the
// general form, so `~/.git-credentials` content was ingested rather than dropped.
//
// Found the hard way: a test suite in mathias/infra executed a script that
// configures git while inheriting the operator's real $HOME, read koala's live
// credential store, and printed two live credentials into a session transcript.
// ~/.claude/projects is this watcher's own input, so the scrubber was the last
// line of defence for that mistake and it failed open. Two credentials were
// rotated (infra#466).
//
// The lesson is not "do not read the credential file" -- that mistake will recur.
// It is that this shape must fail closed, because the scrubber is what decides
// whether such a mistake is survivable.
func TestScrub_URLUserinfoCredential(t *testing.T) {
// Every secret below is INVENTED. None is or was a real credential.
mustScrub := []struct {
name string
content string
}{
{"git-credential-store-user", "https://mathias:0123456789abcdef0123456789abcdef01234567@git.d-ma.be"},
{"git-credential-store-oauth2", "https://oauth2:0123456789abcdef0123456789abcdef01234567@git.d-ma.be"},
{"in-context-payload-line", `payload line: https://mathias:0123456789abcdef0123456789abcdef01234567@git.d-ma.be`},
{"clone-url-in-argv", "git clone https://oauth2:abcdefghijklmnopqrstuvwx@git.d-ma.be/mathias/infra.git"},
{"http-not-https", "http://admin:supersecretvalue123@10.0.1.20/api"},
{"git-plus-ssh-scheme", "git+ssh://deploy:abcdefghijklmnop@example.com/repo"},
{"redis-scheme", "redis://default:abcdefghijklmnopqrst@10.0.1.20:6379/0"},
}
for _, tc := range mustScrub {
t.Run(tc.name, func(t *testing.T) {
assert.NotEmpty(t, Scrub(tc.content),
"a credential in URL userinfo must be dropped, not ingested")
})
}
// The other direction matters as much: a rule that scrubs every URL with a
// colon in it would drop most of the signal this watcher exists to keep.
mustNotScrub := []struct {
name string
content string
}{
{"host-with-port", "cloning https://git.d-ma.be:443/mathias/infra.git"},
{"postgres-no-password", "postgres://localhost:5432/brain"},
{"url-with-colon-in-query", "GET https://example.com/path?filter=a:b&x=1"},
{"plain-url", "see https://git.d-ma.be/mathias/infra/issues/466"},
{"userinfo-no-secret", "https://user:@example.com"},
{"format-string-placeholder", `printf 'https://oauth2:%s@%s\n' "$TOKEN" "$HOST"`},
{"scheme-relative-time", "duration https://example.com took 00:03:22"},
}
for _, tc := range mustNotScrub {
t.Run(tc.name, func(t *testing.T) {
assert.Empty(t, Scrub(tc.content),
"this is not a credential and must pass through")
})
}
}
func TestScrub_CleanContentPassesThrough(t *testing.T) { func TestScrub_CleanContentPassesThrough(t *testing.T) {
cases := []string{ cases := []string{
"", "",
@@ -0,0 +1,231 @@
package claudewatcher
import (
"context"
"log/slog"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// recordingHandler captures log records so a test can assert that a file was
// never even attempted — the absence of a read error is the evidence.
type recordingHandler struct {
mu sync.Mutex
records []string
}
func (h *recordingHandler) Enabled(context.Context, slog.Level) bool { return true }
func (h *recordingHandler) Handle(_ context.Context, r slog.Record) error {
h.mu.Lock()
defer h.mu.Unlock()
var sb strings.Builder
sb.WriteString(r.Message)
r.Attrs(func(a slog.Attr) bool {
sb.WriteString(" " + a.Key + "=" + a.Value.String())
return true
})
h.records = append(h.records, sb.String())
return nil
}
func (h *recordingHandler) WithAttrs([]slog.Attr) slog.Handler { return h }
func (h *recordingHandler) WithGroup(string) slog.Handler { return h }
func (h *recordingHandler) contains(substr string) bool {
h.mu.Lock()
defer h.mu.Unlock()
for _, r := range h.records {
if strings.Contains(r, substr) {
return true
}
}
return false
}
func session(t *testing.T, root, project, id string) string {
t.Helper()
dir := filepath.Join(root, project)
require.NoError(t, os.MkdirAll(dir, 0o755))
return writeSession(t, dir, id, []string{
`{"type":"user","sessionId":"` + id + `","message":"a prompt"}`,
`{"type":"assistant","sessionId":"` + id + `","message":{"content":[{"type":"text","text":"an answer"}]}}`,
})
}
// A named project is not ingested, and its neighbours still are.
func TestSkipProjects_skipsTheNamedProjectOnly(t *testing.T) {
tmp := t.TempDir()
session(t, tmp, "-home-mathias-dev-AGENTS-cobalt-dingo", "skipped")
session(t, tmp, "-home-mathias-dev", "kept")
sink := &memSink{}
require.NoError(t, TickOnce(context.Background(), Config{
SessionsDir: tmp,
Host: "koala",
Sink: sink,
SkipProjects: []string{"-home-mathias-dev-AGENTS-cobalt-dingo"},
}))
require.Len(t, sink.batches, 1)
assert.Equal(t, "kept", sink.batches[0].SessionID)
assert.Equal(t, "-home-mathias-dev", sink.batches[0].ProjectID)
}
// Globs are necessary, not a convenience. A project directory is derived from
// the session's WORKING DIRECTORY, so a git worktree produces an ephemeral
// name like "-home-mathias-dev--claude-worktrees-bridge-cse-017xoC...". An
// exact-match list could never keep up with those.
func TestSkipProjects_globMatchesEphemeralWorktreeNames(t *testing.T) {
tmp := t.TempDir()
session(t, tmp, "-home-mathias-dev--claude-worktrees-bridge-cse-017xoCEcrc35", "worktree")
session(t, tmp, "-home-mathias-dev", "kept")
sink := &memSink{}
require.NoError(t, TickOnce(context.Background(), Config{
SessionsDir: tmp,
Host: "koala",
Sink: sink,
SkipProjects: []string{"*claude-worktrees-bridge-cse*"},
}))
require.Len(t, sink.batches, 1)
assert.Equal(t, "kept", sink.batches[0].SessionID)
}
// The point of skipping at the directory walk: the file is never OPENED, so
// its content never enters this process. Proven by making it unreadable — a
// skipped file produces no read error because nothing tried to read it, while
// the same file in a non-skipped project does.
func TestSkipProjects_theFileIsNeverOpened(t *testing.T) {
tmp := t.TempDir()
path := session(t, tmp, "-home-mathias-dev-AGENTS-cobalt-dingo", "unreadable")
require.NoError(t, os.Chmod(path, 0o000))
t.Cleanup(func() { _ = os.Chmod(path, 0o644) })
rec := &recordingHandler{}
sink := &memSink{}
require.NoError(t, TickOnce(context.Background(), Config{
SessionsDir: tmp,
Host: "koala",
Sink: sink,
Logger: slog.New(rec),
SkipProjects: []string{"*cobalt-dingo*"},
}))
assert.Empty(t, sink.batches)
assert.False(t, rec.contains("file failed"),
"a skipped file must not even be attempted")
}
// The control test for the one above: without the skip, the unreadable file IS
// attempted and fails. Otherwise the assertion above could pass for the wrong
// reason.
func TestSkipProjects_withoutTheSkipTheSameFileIsAttempted(t *testing.T) {
tmp := t.TempDir()
path := session(t, tmp, "-home-mathias-dev-AGENTS-cobalt-dingo", "unreadable")
require.NoError(t, os.Chmod(path, 0o000))
t.Cleanup(func() { _ = os.Chmod(path, 0o644) })
rec := &recordingHandler{}
require.NoError(t, TickOnce(context.Background(), Config{
SessionsDir: tmp,
Host: "koala",
Sink: &memSink{},
Logger: slog.New(rec),
}))
assert.True(t, rec.contains("file failed"),
"the unreadable file must fail when not skipped — otherwise the skip test proves nothing")
}
// Patterns match the project directory NAME, not the whole path. A temp
// directory or a home directory component must not accidentally match and
// silently disable ingestion.
func TestSkipProjects_matchesTheProjectNameNotTheFullPath(t *testing.T) {
tmp := t.TempDir()
session(t, tmp, "-home-mathias-dev", "kept")
sink := &memSink{}
require.NoError(t, TickOnce(context.Background(), Config{
SessionsDir: tmp,
Host: "koala",
Sink: sink,
// tmp is somewhere under /tmp; this must not match the project name.
SkipProjects: []string{"*tmp*"},
}))
require.Len(t, sink.batches, 1, "a path component outside the project name must not match")
}
// An unparseable pattern must stop the watcher rather than be ignored. A
// silently dropped skip rule means ingesting what was meant to be excluded,
// which is the failure that cannot be noticed after the fact.
func TestSkipProjects_invalidPatternRefusesToRun(t *testing.T) {
tmp := t.TempDir()
session(t, tmp, "-home-mathias-dev", "kept")
sink := &memSink{}
err := TickOnce(context.Background(), Config{
SessionsDir: tmp,
Host: "koala",
Sink: sink,
SkipProjects: []string{"[unclosed"},
})
require.Error(t, err)
assert.Contains(t, err.Error(), "[unclosed")
assert.Empty(t, sink.batches, "nothing may be ingested while a skip rule is broken")
}
func TestSkipProjects_emptyListChangesNothing(t *testing.T) {
tmp := t.TempDir()
session(t, tmp, "-home-mathias-dev", "kept")
sink := &memSink{}
require.NoError(t, TickOnce(context.Background(), Config{
SessionsDir: tmp, Host: "koala", Sink: sink, SkipProjects: nil,
}))
require.Len(t, sink.batches, 1)
}
// The difference between SkipDir and filtering after the walk, made
// observable: an unreadable skipped directory must not disturb anything.
//
// Without SkipDir, WalkDir reads the directory's entries, gets a permission
// error, and that error aborts the ENTIRE walk — so one skipped project with
// awkward permissions would silently stop ingesting every other project.
// Returning SkipDir means its contents are never listed at all.
//
// Added after a mutation test showed the earlier assertions could not tell the
// two implementations apart.
func TestSkipProjects_anUnreadableSkippedDirDoesNotBreakTheWalk(t *testing.T) {
tmp := t.TempDir()
session(t, tmp, "-home-mathias-dev", "kept")
blocked := filepath.Join(tmp, "-home-mathias-dev-AGENTS-cobalt-dingo")
require.NoError(t, os.MkdirAll(blocked, 0o755))
_ = writeSession(t, blocked, "secret", []string{
`{"type":"user","sessionId":"secret","message":"should never be read"}`,
})
require.NoError(t, os.Chmod(blocked, 0o000))
t.Cleanup(func() { _ = os.Chmod(blocked, 0o755) })
sink := &memSink{}
require.NoError(t, TickOnce(context.Background(), Config{
SessionsDir: tmp,
Host: "koala",
Sink: sink,
SkipProjects: []string{"*cobalt-dingo*"},
}))
require.Len(t, sink.batches, 1, "an unreadable skipped directory must not abort the walk")
assert.Equal(t, "kept", sink.batches[0].SessionID)
}
+59 -2
View File
@@ -45,6 +45,25 @@ type Config struct {
Sink Sink Sink Sink
Cursors *CursorStore Cursors *CursorStore
Logger *slog.Logger Logger *slog.Logger
// SkipProjects excludes whole project directories from ingestion, as
// filepath.Match globs tested against the project directory NAME (the
// basename, e.g. "-home-mathias-dev"), not the full path.
//
// Globs rather than exact names because a project directory is derived
// from the session's working directory, so a git worktree yields an
// ephemeral name like
// "-home-mathias-dev--claude-worktrees-bridge-cse-017xoC..." that no
// exact-match list could keep up with.
//
// Matching directories are skipped during the directory WALK, so their
// files are never opened and their content never enters this process —
// which is a stronger property than filtering it out afterwards.
//
// An unparseable pattern stops the watcher. A silently dropped skip rule
// means ingesting what was meant to be excluded, and that is not
// noticeable after the fact.
SkipProjects []string
} }
// Watch runs the polling loop until ctx is cancelled. Returns ctx.Err() // Watch runs the polling loop until ctx is cancelled. Returns ctx.Err()
@@ -68,6 +87,9 @@ func Watch(ctx context.Context, cfg Config) error {
if cfg.Logger == nil { if cfg.Logger == nil {
cfg.Logger = slog.Default() cfg.Logger = slog.Default()
} }
if err := validateSkipPatterns(cfg.SkipProjects); err != nil {
return err
}
cfg.Logger.Info("claudewatcher: started", cfg.Logger.Info("claudewatcher: started",
"sessions_dir", cfg.SessionsDir, "sessions_dir", cfg.SessionsDir,
"host", cfg.Host, "host", cfg.Host,
@@ -91,7 +113,7 @@ func Watch(ctx context.Context, cfg Config) error {
// runTick is one polling pass. Exposed (lowercase) for tests via // runTick is one polling pass. Exposed (lowercase) for tests via
// TickOnce. // TickOnce.
func runTick(ctx context.Context, cfg Config) { func runTick(ctx context.Context, cfg Config) {
files, err := listSessionFiles(cfg.SessionsDir) files, err := listSessionFiles(cfg.SessionsDir, cfg.SkipProjects, cfg.Logger)
if err != nil { if err != nil {
cfg.Logger.Warn("claudewatcher: list session files", "err", err) cfg.Logger.Warn("claudewatcher: list session files", "err", err)
return return
@@ -119,17 +141,52 @@ func TickOnce(ctx context.Context, cfg Config) error {
if cfg.Logger == nil { if cfg.Logger == nil {
cfg.Logger = slog.Default() cfg.Logger = slog.Default()
} }
if err := validateSkipPatterns(cfg.SkipProjects); err != nil {
return err
}
runTick(ctx, cfg) runTick(ctx, cfg)
return nil return nil
} }
func listSessionFiles(root string) ([]string, error) { // validateSkipPatterns rejects a pattern filepath.Match cannot parse.
//
// Checked up front rather than per file: a bad pattern that only failed at
// match time would be reported once per session file per tick, and — worse —
// filepath.Match returns an error alongside a false match, so the directory
// would be ingested while the log complained.
func validateSkipPatterns(patterns []string) error {
for _, p := range patterns {
if _, err := filepath.Match(p, "probe"); err != nil {
return fmt.Errorf("invalid skip-project pattern %q: %w", p, err)
}
}
return nil
}
// skipProject reports whether a project directory name matches any pattern.
func skipProject(name string, patterns []string) bool {
for _, p := range patterns {
// The error case is already excluded by validateSkipPatterns.
if ok, _ := filepath.Match(p, name); ok {
return true
}
}
return false
}
func listSessionFiles(root string, skip []string, log *slog.Logger) ([]string, error) {
var out []string var out []string
err := filepath.WalkDir(root, func(path string, d os.DirEntry, walkErr error) error { err := filepath.WalkDir(root, func(path string, d os.DirEntry, walkErr error) error {
if walkErr != nil { if walkErr != nil {
return walkErr return walkErr
} }
if d.IsDir() { if d.IsDir() {
// SkipDir, so nothing inside is even listed. The files are never
// opened and their content never reaches this process.
if path != root && skipProject(d.Name(), skip) {
log.Info("claudewatcher: project skipped by configuration", "project", d.Name())
return filepath.SkipDir
}
return nil return nil
} }
if !strings.HasSuffix(path, ".jsonl") { if !strings.HasSuffix(path, ".jsonl") {
+148
View File
@@ -0,0 +1,148 @@
// ingestion/internal/extract/docmark.go
package extract
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
// docmarkRequest is a JSON-RPC 2.0 tools/call request for docmark's
// convert_to_markdown tool.
type docmarkRequest struct {
JSONRPC string `json:"jsonrpc"`
ID int `json:"id"`
Method string `json:"method"`
Params struct {
Name string `json:"name"`
Arguments struct {
ContentBase64 string `json:"content_base64"`
Filename string `json:"filename"`
} `json:"arguments"`
} `json:"params"`
}
type docmarkResponse struct {
Result *struct {
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"content"`
IsError bool `json:"isError"`
} `json:"result"`
Error *struct {
Message string `json:"message"`
} `json:"error"`
}
// extractViaDocmark converts path (PDF/DOCX/XLSX/PPTX/image) to Markdown by
// calling the docmark MCP server with a single self-contained tools/call
// request (docmark runs stateless_http -- no initialize handshake or session
// ID needed). DOCMARK_URL must be set (e.g.
// http://docmark.docmark.svc.cluster.local:3001/mcp); DOCMARK_BEARER_TOKEN
// is docmark's static bearer (network is docmark's primary auth boundary,
// this is defense-in-depth — ADR-0013).
func extractViaDocmark(path string) (string, error) {
url := os.Getenv("DOCMARK_URL")
if url == "" {
return "", fmt.Errorf("extractViaDocmark: DOCMARK_URL is not set")
}
raw, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("read %s: %w", path, err)
}
var reqBody docmarkRequest
reqBody.JSONRPC = "2.0"
reqBody.ID = 1
reqBody.Method = "tools/call"
reqBody.Params.Name = "convert_to_markdown"
reqBody.Params.Arguments.ContentBase64 = base64.StdEncoding.EncodeToString(raw)
reqBody.Params.Arguments.Filename = fileBase(path)
payload, err := json.Marshal(reqBody)
if err != nil {
return "", fmt.Errorf("marshal docmark request: %w", err)
}
httpReq, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(payload))
if err != nil {
return "", fmt.Errorf("build docmark request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Accept", "application/json, text/event-stream")
if tok := os.Getenv("DOCMARK_BEARER_TOKEN"); tok != "" {
httpReq.Header.Set("Authorization", "Bearer "+tok)
}
client := &http.Client{Timeout: 60 * time.Second}
resp, err := client.Do(httpReq)
if err != nil {
return "", fmt.Errorf("call docmark: %w", err)
}
defer func() { _ = resp.Body.Close() }()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("read docmark response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("docmark: HTTP %d: %s", resp.StatusCode, string(body))
}
jsonBody := body
if data := sseDataPayload(body); data != nil {
jsonBody = data
}
var out docmarkResponse
if err := json.Unmarshal(jsonBody, &out); err != nil {
return "", fmt.Errorf("decode docmark response: %w", err)
}
if out.Error != nil {
return "", fmt.Errorf("docmark: %s", out.Error.Message)
}
if out.Result == nil || len(out.Result.Content) == 0 {
return "", fmt.Errorf("docmark: empty response")
}
text := out.Result.Content[0].Text
if out.Result.IsError {
return "", fmt.Errorf("docmark: %s", text)
}
return text, nil
}
// sseDataPayload extracts the JSON payload from an SSE-framed response body
// ("event: message\r\ndata: {...}\r\n\r\n"). docmark's Streamable-HTTP
// transport frames every response this way (Content-Type: text/event-stream)
// regardless of stateless_http — that flag removes the session/initialize
// requirement, not the SSE wire framing. Returns nil if body isn't SSE-framed
// (e.g. a plain-JSON response, kept as a fallback for forward-compatibility).
func sseDataPayload(body []byte) []byte {
const prefix = "data: "
for _, line := range bytes.Split(body, []byte("\n")) {
line = bytes.TrimRight(line, "\r")
if bytes.HasPrefix(line, []byte(prefix)) {
return bytes.TrimPrefix(line, []byte(prefix))
}
}
return nil
}
// fileBase returns the final path segment (like filepath.Base, kept local to
// avoid importing path/filepath just for this one call).
func fileBase(path string) string {
for i := len(path) - 1; i >= 0; i-- {
if path[i] == '/' || path[i] == '\\' {
return path[i+1:]
}
}
return path
}
+189
View File
@@ -0,0 +1,189 @@
// ingestion/internal/extract/docmark_test.go
package extract
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// mcpToolResult mirrors the shape of docmark's JSON-RPC tools/call response.
type mcpToolResult struct {
JSONRPC string `json:"jsonrpc"`
ID int `json:"id"`
Result *struct {
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"content"`
IsError bool `json:"isError"`
} `json:"result,omitempty"`
Error *struct {
Message string `json:"message"`
} `json:"error,omitempty"`
}
// writeMCPResponse mirrors docmark's REAL response framing (empirically
// confirmed against the live server): Content-Type: text/event-stream,
// body is SSE-framed ("event: message\r\ndata: {...}\r\n\r\n"), not bare
// JSON -- inherent to MCP Streamable-HTTP, independent of stateless_http.
func writeMCPResponse(w http.ResponseWriter, body mcpToolResult) {
payload, _ := json.Marshal(body)
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("event: message\r\ndata: "))
_, _ = w.Write(payload)
_, _ = w.Write([]byte("\r\n\r\n"))
}
func TestExtractViaDocmark_Success(t *testing.T) {
var gotAuth, gotAccept string
var gotBody map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotAuth = r.Header.Get("Authorization")
gotAccept = r.Header.Get("Accept")
b, _ := io.ReadAll(r.Body)
_ = json.Unmarshal(b, &gotBody)
writeMCPResponse(w, mcpToolResult{
JSONRPC: "2.0", ID: 1,
Result: &struct {
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"content"`
IsError bool `json:"isError"`
}{
Content: []struct {
Type string `json:"type"`
Text string `json:"text"`
}{{Type: "text", Text: "# Converted\n\nhello"}},
},
})
}))
defer srv.Close()
t.Setenv("DOCMARK_URL", srv.URL+"/mcp")
t.Setenv("DOCMARK_BEARER_TOKEN", "test-token-123")
dir := t.TempDir()
path := filepath.Join(dir, "doc.docx")
require.NoError(t, os.WriteFile(path, []byte("fake docx bytes"), 0o644))
got, err := extractViaDocmark(path)
require.NoError(t, err)
assert.Equal(t, "# Converted\n\nhello", got)
assert.Equal(t, "Bearer test-token-123", gotAuth)
assert.Contains(t, gotAccept, "application/json")
params, _ := gotBody["params"].(map[string]any)
require.NotNil(t, params)
assert.Equal(t, "convert_to_markdown", params["name"])
args, _ := params["arguments"].(map[string]any)
require.NotNil(t, args)
assert.Equal(t, "doc.docx", args["filename"])
assert.NotEmpty(t, args["content_base64"])
}
func TestExtractViaDocmark_NotConfigured(t *testing.T) {
t.Setenv("DOCMARK_URL", "")
dir := t.TempDir()
path := filepath.Join(dir, "doc.docx")
require.NoError(t, os.WriteFile(path, []byte("x"), 0o644))
_, err := extractViaDocmark(path)
require.Error(t, err)
assert.Contains(t, err.Error(), "DOCMARK_URL")
}
func TestExtractViaDocmark_ToolErrorSurfacesMessage(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
writeMCPResponse(w, mcpToolResult{
JSONRPC: "2.0", ID: 1,
Result: &struct {
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"content"`
IsError bool `json:"isError"`
}{
Content: []struct {
Type string `json:"type"`
Text string `json:"text"`
}{{Type: "text", Text: "unsupported format for 'doc.docx'"}},
IsError: true,
},
})
}))
defer srv.Close()
t.Setenv("DOCMARK_URL", srv.URL+"/mcp")
t.Setenv("DOCMARK_BEARER_TOKEN", "tok")
dir := t.TempDir()
path := filepath.Join(dir, "doc.docx")
require.NoError(t, os.WriteFile(path, []byte("x"), 0o644))
_, err := extractViaDocmark(path)
require.Error(t, err)
assert.Contains(t, err.Error(), "unsupported format")
}
func TestExtractViaDocmark_HTTPErrorSurfaces(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte("unauthorized"))
}))
defer srv.Close()
t.Setenv("DOCMARK_URL", srv.URL+"/mcp")
t.Setenv("DOCMARK_BEARER_TOKEN", "wrong")
dir := t.TempDir()
path := filepath.Join(dir, "doc.docx")
require.NoError(t, os.WriteFile(path, []byte("x"), 0o644))
_, err := extractViaDocmark(path)
require.Error(t, err)
assert.Contains(t, err.Error(), "401")
}
func TestText_RoutesDocxXlsxPptxImagesToDocmark(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
writeMCPResponse(w, mcpToolResult{
JSONRPC: "2.0", ID: 1,
Result: &struct {
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"content"`
IsError bool `json:"isError"`
}{
Content: []struct {
Type string `json:"type"`
Text string `json:"text"`
}{{Type: "text", Text: "converted"}},
},
})
}))
defer srv.Close()
t.Setenv("DOCMARK_URL", srv.URL+"/mcp")
t.Setenv("DOCMARK_BEARER_TOKEN", "tok")
for _, ext := range []string{".docx", ".xlsx", ".pptx", ".png", ".jpg", ".jpeg"} {
t.Run(ext, func(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "f"+ext)
require.NoError(t, os.WriteFile(path, []byte("x"), 0o644))
got, err := Text(path)
require.NoError(t, err)
assert.Equal(t, "converted", got)
})
}
}
+5 -1
View File
@@ -8,7 +8,9 @@ import (
) )
// Text reads the file at path and returns its plain-text content. // Text reads the file at path and returns its plain-text content.
// Supported extensions: .md, .txt (passthrough), .pdf (via pdftotext). // Supported extensions: .md, .txt (passthrough), .pdf (via pdftotext),
// .docx/.xlsx/.pptx/.png/.jpg/.jpeg (via docmark, ADR-0013 -- requires
// DOCMARK_URL to be set; see docmark.go).
func Text(path string) (string, error) { func Text(path string) (string, error) {
ext := strings.ToLower(fileExt(path)) ext := strings.ToLower(fileExt(path))
switch ext { switch ext {
@@ -20,6 +22,8 @@ func Text(path string) (string, error) {
return string(b), nil return string(b), nil
case ".pdf": case ".pdf":
return extractPDF(path) return extractPDF(path)
case ".docx", ".xlsx", ".pptx", ".png", ".jpg", ".jpeg":
return extractViaDocmark(path)
default: default:
return "", fmt.Errorf("unsupported file extension: %s", ext) return "", fmt.Errorf("unsupported file extension: %s", ext)
} }
@@ -0,0 +1,167 @@
// Package frontmatter lints and repairs the YAML frontmatter block of a
// markdown note.
//
// Notes written directly — hand-authored, or promoted from brain/raw/ — do not
// pass through pipeline.BuildPages, so nothing quotes their scalars. A title
// containing an unescaped ": " then produces a block that yaml.Unmarshal
// rejects with "mapping values are not allowed here", and every consumer that
// reads frontmatter silently skips the note.
//
// Fix is deliberately conservative: it only adds quoting, never reorders or
// rewrites, and it refuses to return a document that still does not parse.
package frontmatter
import (
"bytes"
"fmt"
"regexp"
"strings"
"gopkg.in/yaml.v3"
)
const fence = "---"
// Lint reports whether doc's frontmatter block parses as YAML.
//
// A document with no frontmatter block, or with an unterminated one, is not an
// error: there is nothing claiming to be YAML.
func Lint(doc []byte) error {
b, ok := block(doc)
if !ok {
return nil
}
var v any
if err := yaml.Unmarshal(b, &v); err != nil {
return fmt.Errorf("frontmatter: %w", err)
}
return nil
}
// Fix quotes unquoted scalars whose value breaks YAML parsing and returns the
// repaired document.
//
// It returns (doc, false, nil) when the document already parses, and
// (doc, false, err) when quoting cannot rescue it — an unfixable document is
// always returned byte-identical, never half-repaired.
func Fix(doc []byte) ([]byte, bool, error) {
if err := Lint(doc); err == nil {
return doc, false, nil
}
b, ok := block(doc)
if !ok {
// Lint only fails when there is a block, so this is unreachable in
// practice; return the original rather than guess.
return doc, false, nil
}
fixed := quoteScalars(b)
if bytes.Equal(fixed, b) {
return doc, false, fmt.Errorf("frontmatter: not repairable by quoting: %w", Lint(doc))
}
var v any
if err := yaml.Unmarshal(fixed, &v); err != nil {
return doc, false, fmt.Errorf("frontmatter: quoting did not repair the block: %w", err)
}
_, rest, _ := Split(doc)
out := []byte(fence + "\n")
out = append(out, fixed...)
out = append(out, []byte(fence)...)
out = append(out, rest...)
return out, true, nil
}
// mappingLine matches "key: value" at any indentation, capturing the prefix so
// it can be re-emitted untouched.
//
// Sequence items ("- value") are deliberately not handled: "- foo: bar" is
// valid YAML, so a document containing one does not reach Fix in the first
// place. See the Lint table for why that gap is left open.
var mappingLine = regexp.MustCompile(`^(\s*[A-Za-z_][\w.-]*:[ \t]+)(\S.*)$`)
// quoteScalars single-quotes every unquoted scalar value in the block that
// contains a colon. Values that are already quoted, or that carry YAML syntax
// this package has no business rewriting, are left alone.
func quoteScalars(block []byte) []byte {
lines := strings.Split(string(block), "\n")
for i, line := range lines {
m := mappingLine.FindStringSubmatch(line)
if m == nil {
continue
}
prefix, value := m[1], m[2]
if !needsQuoting(value) {
continue
}
lines[i] = prefix + "'" + strings.ReplaceAll(value, "'", "''") + "'"
}
return []byte(strings.Join(lines, "\n"))
}
// needsQuoting reports whether a scalar value has to be quoted to load as the
// string it plainly is.
//
// The test is YAML's own parser rather than a pattern: ask whether the value
// stands alone as the right-hand side of a mapping. Heuristics get this wrong
// in both directions — `title: "Foo" — bar` opens with a quote but is not
// quoted, and a value may contain a colon inside quotes and be perfectly fine.
//
// Anything that already parses is left alone, whatever it parses into — a flow
// collection, a number, a bool. It is not broken, and quoting would change its
// type.
func needsQuoting(value string) bool {
if strings.HasPrefix(value, "|") || strings.HasPrefix(value, ">") {
return false // block scalar; its content is not parsed as YAML
}
var probe map[string]any
return yaml.Unmarshal([]byte("v: "+value+"\n"), &probe) != nil
}
// block returns the raw YAML between the opening and closing fences.
func block(doc []byte) ([]byte, bool) {
b, _, ok := Split(doc)
return b, ok
}
// Split returns doc's frontmatter block and everything from the closing
// fence onward (the closing fence itself excluded, its trailing newline
// included), or ok=false if doc has no properly-fenced frontmatter.
//
// The canonical fence detector for this codebase (hyperguild#138): three
// independent reimplementations of this same logic each grew their own gap
// through separate bug-fixing before being consolidated here —
// internal/mcp's needed a CRLF/BOM guard added after both silently defeated
// its own HasPrefix check, and internal/api's closing-fence match had no
// trailing-newline requirement, so a document ending in "\n---extra" with no
// real newline after the fence was treated as validly closed. Both classes
// are closed here, once, for every caller.
func Split(doc []byte) (block, rest []byte, ok bool) {
s := strings.TrimPrefix(string(doc), "\xef\xbb\xbf")
s = strings.ReplaceAll(s, "\r\n", "\n")
if !strings.HasPrefix(s, fence+"\n") {
return nil, nil, false
}
body := s[len(fence)+1:]
idx := strings.Index(body, "\n"+fence)
if idx < 0 {
return nil, nil, false
}
// What follows the closing fence must be either a newline (a real body
// follows) or nothing at all (the fence is the literal end of the
// document — no body, not a bypass attempt). Anything else, e.g.
// "\n---extra", is not a valid close: an earlier version of this check
// accepted it, which is exactly the looser match hyperguild#138 closes.
after := idx + 1 + len(fence)
switch {
case after == len(body):
return []byte(body[:idx+1]), nil, true
case body[after] == '\n':
return []byte(body[:idx+1]), []byte(body[after:]), true
default:
return nil, nil, false
}
}
@@ -0,0 +1,240 @@
// ingestion/internal/frontmatter/frontmatter_test.go
package frontmatter
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
)
func TestLint(t *testing.T) {
tests := []struct {
name string
doc string
wantErr bool
}{
{
name: "no frontmatter block is not an error",
doc: "# Just a heading\n\nSome body text.\n",
},
{
name: "quoted title parses",
doc: "---\ntitle: 'Headless dispatch runs: Bash is denied'\n---\n\nbody\n",
},
{
name: "plain title parses",
doc: "---\ntitle: A simple title\nwing: homelab\n---\n\nbody\n",
},
{
name: "unquoted colon in title does not parse",
doc: "---\ntitle: Headless dispatch runs: Bash is denied — use gitea MCP\nwing: homelab\n---\n\nbody\n",
wantErr: true,
},
{
// Known gap, deliberately not fixed here: this parses, but the
// item becomes map[string]any{"Headless dispatch": "denied"}
// rather than a string. It is a silent type corruption, not a
// parse failure, so repairing it would rewrite documents that
// currently load — out of scope for a lint about broken YAML.
name: "unquoted colon in a list item parses as a mapping, not an error",
doc: "---\ntitle: Fine\naliases:\n - Headless dispatch: denied\n---\n\nbody\n",
},
{
name: "unterminated frontmatter is not treated as frontmatter",
doc: "---\ntitle: no closing fence\n\nbody\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := Lint([]byte(tt.doc))
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
})
}
}
func TestFix(t *testing.T) {
tests := []struct {
name string
doc string
wantChanged bool
wantKey string
wantValue string
}{
{
name: "quotes an unquoted title containing a colon",
doc: "---\ntitle: Headless dispatch runs: Bash is denied — use gitea MCP\nwing: homelab\n---\n\nbody\n",
wantChanged: true,
wantKey: "title",
wantValue: "Headless dispatch runs: Bash is denied — use gitea MCP",
},
{
// Parses already (see the Lint table), so Fix must leave it alone
// rather than rewrite a document that loads.
name: "leaves a colon-bearing list item alone because it already parses",
doc: "---\ntitle: Fine\naliases:\n - Headless dispatch: denied\n---\n\nbody\n",
wantChanged: false,
wantKey: "title",
wantValue: "Fine",
},
{
name: "escapes an embedded single quote when quoting",
doc: "---\ntitle: Don't do this: it breaks\n---\n\nbody\n",
wantChanged: true,
wantKey: "title",
wantValue: "Don't do this: it breaks",
},
{
// The value opens with a double quote and then keeps going after
// the closing one, so YAML reads it as a quoted scalar followed by
// junk. Treating "starts with a quote" as "already quoted" leaves
// this broken forever.
name: "quotes a value that only looks quoted",
doc: "---\ntitle: \"Evaluation Driven Generation\" — a TDD-style scaffold\ntags: [a, b]\n---\n\nbody\n",
wantChanged: true,
wantKey: "title",
wantValue: "\"Evaluation Driven Generation\" — a TDD-style scaffold",
},
{
name: "leaves an already-valid document untouched",
doc: "---\ntitle: 'Already quoted: fine'\nwing: homelab\n---\n\nbody\n",
wantChanged: false,
wantKey: "title",
wantValue: "Already quoted: fine",
},
{
name: "leaves a document with no frontmatter untouched",
doc: "# Heading\n\nbody: with a colon\n",
wantChanged: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, changed, err := Fix([]byte(tt.doc))
require.NoError(t, err)
assert.Equal(t, tt.wantChanged, changed)
if !tt.wantChanged {
assert.Equal(t, tt.doc, string(got), "unchanged docs must be returned byte-identical")
}
// Whatever came back must parse — that is the whole point.
require.NoError(t, Lint(got), "Fix must not return a document that still fails to parse")
if tt.wantKey == "" {
return
}
block, ok := block(got)
require.True(t, ok)
var m map[string]any
require.NoError(t, yaml.Unmarshal(block, &m))
assert.Equal(t, tt.wantValue, m[tt.wantKey], "the value must survive quoting unchanged")
})
}
}
func TestFix_LeavesStructuredValuesStructured(t *testing.T) {
// Only the broken scalar may be touched. A flow sequence on a neighbouring
// line still has to load as a sequence afterwards, not as a string.
doc := "---\ntitle: Broken: here\ntags: [prompting, llm]\ncount: 3\n---\n\nbody\n"
got, changed, err := Fix([]byte(doc))
require.NoError(t, err)
require.True(t, changed)
b, ok := block(got)
require.True(t, ok)
var m map[string]any
require.NoError(t, yaml.Unmarshal(b, &m))
assert.Equal(t, "Broken: here", m["title"])
assert.Equal(t, []any{"prompting", "llm"}, m["tags"])
assert.Equal(t, 3, m["count"])
}
func TestFix_PreservesBodyExactly(t *testing.T) {
body := "\nThe body has: colons, 'quotes', and\n---\na horizontal rule.\n"
doc := "---\ntitle: Broken: title\n---" + body
got, changed, err := Fix([]byte(doc))
require.NoError(t, err)
require.True(t, changed)
assert.True(t, len(got) > 0)
_, rest, ok := Split([]byte(doc))
require.True(t, ok)
_, gotRest, ok := Split(got)
require.True(t, ok)
assert.Equal(t, string(rest), string(gotRest), "the body must not be touched")
}
func TestFix_RefusesToReturnAnUnparseableResult(t *testing.T) {
// A frontmatter block that quoting cannot rescue: the structure itself is
// broken, not a scalar. Fix must return the original and an error rather
// than a half-repaired document.
doc := "---\ntitle: fine\n\tbad: tab-indented mapping\n - stray list item\n---\n\nbody\n"
got, changed, err := Fix([]byte(doc))
require.Error(t, err)
assert.False(t, changed)
assert.Equal(t, doc, string(got), "an unfixable document must come back byte-identical")
}
// TestSplit_NormalizesCRLFBeforeFenceDetection is hyperguild#138: a note
// whose fence lines use CRLF ("---\r\n") failed strings.HasPrefix(doc,
// "---\n") on the precondition read in internal/mcp's independent
// reimplementation -- encoding alone, no adversarial input, silently
// defeated fence detection there before this consolidation. Split must
// never repeat that.
func TestSplit_NormalizesCRLFBeforeFenceDetection(t *testing.T) {
doc := "---\r\ntitle: 'n'\r\nhalf_life: durable\r\n---\r\n\r\nbody\r\n"
block, rest, ok := Split([]byte(doc))
require.True(t, ok)
assert.Contains(t, string(block), "half_life: durable")
assert.Contains(t, string(rest), "body")
}
// TestSplit_StripsALeadingUTF8BOM is the same mechanism one layer earlier:
// a leading BOM (Notepad's default "UTF-8" save, PowerShell's pre-v6
// Out-File/Set-Content) defeats the same HasPrefix check before CRLF
// normalization even applies.
func TestSplit_StripsALeadingUTF8BOM(t *testing.T) {
doc := "\xef\xbb\xbf---\ntitle: 'n'\n---\n\nbody\n"
block, rest, ok := Split([]byte(doc))
require.True(t, ok)
assert.Contains(t, string(block), "title: 'n'")
assert.Contains(t, string(rest), "body")
}
// TestSplit_RequiresANewlineAfterTheClosingFence closes the looser match
// internal/api's independent reimplementation carried (strings.Index(body,
// "\n"+fence) with no trailing-newline requirement): a document ending in
// "\n---extra" with no newline separating the fence from what follows it is
// not a valid closing fence and must not be treated as one.
func TestSplit_RequiresANewlineAfterTheClosingFence(t *testing.T) {
doc := "---\ntitle: 'n'\n---extra-not-a-real-close"
_, _, ok := Split([]byte(doc))
assert.False(t, ok, "a fence line not followed by a newline is not a valid closing fence")
}
// TestSplit_AcceptsAClosingFenceThatIsTheLastBytesOfTheDocument is a
// regression pin found in review of hyperguild#138: the fix for the
// "\n---extra" bypass above must not also reject the legitimate case of a
// closing fence with nothing after it at all (no trailing newline because
// there's no body, not because a bypass is being attempted) -- this
// package's own private split() accepted that shape before the
// consolidation, and cmd/frontmatterlint's Lint/Fix relied on it.
func TestSplit_AcceptsAClosingFenceThatIsTheLastBytesOfTheDocument(t *testing.T) {
doc := "---\ntitle: 'n'\n---"
block, rest, ok := Split([]byte(doc))
require.True(t, ok, "a closing fence at literal end-of-file, with nothing after it, is valid -- there is no body to require a newline before")
assert.Contains(t, string(block), "title: 'n'")
assert.Equal(t, "", string(rest))
}
+84
View File
@@ -0,0 +1,84 @@
// ingestion/internal/frontmatter/scan.go
package frontmatter
import (
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"unicode/utf8"
)
// Finding is one markdown file whose frontmatter does not parse.
type Finding struct {
Path string // relative to the scanned root
Err error // why it does not parse, or why the repair was refused
Repaired bool // true only when fix was requested and the file was rewritten
}
// Scan walks root for *.md files whose frontmatter fails to parse.
//
// With fix set, each finding that quoting can rescue is rewritten in place;
// anything quoting cannot rescue is reported and left byte-identical. A file
// that cannot be read or decoded is reported as a finding rather than aborting
// the walk — one poisoned note must not hide the other findings.
func Scan(root string, fix bool) ([]Finding, error) {
var found []Finding
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() || !strings.EqualFold(filepath.Ext(path), ".md") {
return nil
}
rel, relErr := filepath.Rel(root, path)
if relErr != nil {
rel = path
}
doc, readErr := os.ReadFile(path)
if readErr != nil {
found = append(found, Finding{Path: rel, Err: readErr})
return nil
}
if !utf8.Valid(doc) {
found = append(found, Finding{Path: rel, Err: fmt.Errorf("not valid UTF-8")})
return nil
}
if lintErr := Lint(doc); lintErr == nil {
return nil
}
if !fix {
found = append(found, Finding{Path: rel, Err: Lint(doc)})
return nil
}
repaired, changed, fixErr := Fix(doc)
if fixErr != nil || !changed {
found = append(found, Finding{Path: rel, Err: fixErr})
return nil
}
if writeErr := writeFilePreservingMode(path, repaired); writeErr != nil {
found = append(found, Finding{Path: rel, Err: writeErr})
return nil
}
found = append(found, Finding{Path: rel, Repaired: true})
return nil
})
if err != nil {
return nil, fmt.Errorf("scan %s: %w", root, err)
}
return found, nil
}
func writeFilePreservingMode(path string, content []byte) error {
mode := fs.FileMode(0o644)
if info, err := os.Stat(path); err == nil {
mode = info.Mode().Perm()
}
return os.WriteFile(path, content, mode)
}
+103
View File
@@ -0,0 +1,103 @@
// ingestion/internal/frontmatter/scan_test.go
package frontmatter
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func writeTree(t *testing.T, files map[string]string) string {
t.Helper()
root := t.TempDir()
for name, content := range files {
path := filepath.Join(root, name)
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
require.NoError(t, os.WriteFile(path, []byte(content), 0o644))
}
return root
}
const (
brokenDoc = "---\ntitle: Broken: title here\nwing: homelab\n---\n\nbody\n"
validDoc = "---\ntitle: 'Fine: quoted'\n---\n\nbody\n"
)
func TestScan_ReportsOnlyBrokenFiles(t *testing.T) {
root := writeTree(t, map[string]string{
"wiki/a/broken.md": brokenDoc,
"wiki/a/valid.md": validDoc,
"wiki/b/plain.md": "# no frontmatter\n\nbody: with colon\n",
"wiki/a/notes.txt": brokenDoc, // not markdown — must be ignored
})
found, err := Scan(root, false)
require.NoError(t, err)
require.Len(t, found, 1)
assert.Equal(t, "wiki/a/broken.md", found[0].Path)
assert.False(t, found[0].Repaired)
assert.Error(t, found[0].Err)
// Dry run must not touch the file.
got, err := os.ReadFile(filepath.Join(root, "wiki/a/broken.md"))
require.NoError(t, err)
assert.Equal(t, brokenDoc, string(got))
}
func TestScan_FixWritesRepairedFilesAndLeavesTheRestAlone(t *testing.T) {
root := writeTree(t, map[string]string{
"wiki/a/broken.md": brokenDoc,
"wiki/a/valid.md": validDoc,
})
found, err := Scan(root, true)
require.NoError(t, err)
require.Len(t, found, 1)
assert.True(t, found[0].Repaired)
assert.NoError(t, found[0].Err)
repaired, err := os.ReadFile(filepath.Join(root, "wiki/a/broken.md"))
require.NoError(t, err)
require.NoError(t, Lint(repaired), "the repaired file must parse")
assert.Contains(t, string(repaired), "title: 'Broken: title here'")
assert.Contains(t, string(repaired), "wing: homelab", "untouched keys must survive")
untouched, err := os.ReadFile(filepath.Join(root, "wiki/a/valid.md"))
require.NoError(t, err)
assert.Equal(t, validDoc, string(untouched))
// Second pass finds nothing — the repair is idempotent and complete.
again, err := Scan(root, true)
require.NoError(t, err)
assert.Empty(t, again)
}
func TestScan_ReportsUnfixableWithoutWriting(t *testing.T) {
unfixable := "---\ntitle: fine\n\tbad: tab-indented\n - stray\n---\n\nbody\n"
root := writeTree(t, map[string]string{"wiki/x.md": unfixable})
found, err := Scan(root, true)
require.NoError(t, err)
require.Len(t, found, 1)
assert.False(t, found[0].Repaired)
assert.Error(t, found[0].Err)
got, err := os.ReadFile(filepath.Join(root, "wiki/x.md"))
require.NoError(t, err)
assert.Equal(t, unfixable, string(got), "an unfixable file must be left exactly as it was")
}
func TestScan_ReportsUndecodableFilesInsteadOfFailingTheRun(t *testing.T) {
root := writeTree(t, map[string]string{"wiki/ok.md": validDoc})
require.NoError(t, os.WriteFile(filepath.Join(root, "wiki/bad-bytes.md"),
[]byte{'-', '-', '-', '\n', 0xff, 0xfe, '\n', '-', '-', '-', '\n'}, 0o644))
found, err := Scan(root, false)
require.NoError(t, err, "one unreadable file must not abort the whole scan")
require.Len(t, found, 1)
assert.Equal(t, "wiki/bad-bytes.md", found[0].Path)
}
+15 -4
View File
@@ -5,14 +5,18 @@ import (
"fmt" "fmt"
) )
// Router calls Primary first; on any error falls back to Fallback. // Router calls Primary first; on any error falls back to Fallback, then to
// Fallback may be nil, in which case primary errors are returned directly. // Tertiary. Fallback and Tertiary may each be nil — a nil tier is skipped and
// the chain returns the errors accumulated so far.
type Router struct { type Router struct {
Primary *Client Primary *Client
Fallback *Client Fallback *Client
Tertiary *Client
} }
// Complete implements pipeline.CompleteFunc, routing through Primary then Fallback. // Complete implements pipeline.CompleteFunc, routing through Primary, then
// Fallback, then Tertiary — trying each configured tier in order and
// returning the first success.
func (r *Router) Complete(ctx context.Context, system, user string) (string, error) { func (r *Router) Complete(ctx context.Context, system, user string) (string, error) {
out, err := r.Primary.Complete(ctx, system, user) out, err := r.Primary.Complete(ctx, system, user)
if err == nil { if err == nil {
@@ -22,8 +26,15 @@ func (r *Router) Complete(ctx context.Context, system, user string) (string, err
return "", fmt.Errorf("primary llm: %w", err) return "", fmt.Errorf("primary llm: %w", err)
} }
out, err2 := r.Fallback.Complete(ctx, system, user) out, err2 := r.Fallback.Complete(ctx, system, user)
if err2 != nil { if err2 == nil {
return out, nil
}
if r.Tertiary == nil {
return "", fmt.Errorf("primary llm: %w; fallback llm: %v", err, err2) return "", fmt.Errorf("primary llm: %w; fallback llm: %v", err, err2)
} }
out, err3 := r.Tertiary.Complete(ctx, system, user)
if err3 != nil {
return "", fmt.Errorf("primary llm: %w; fallback llm: %v; tertiary llm: %v", err, err2, err3)
}
return out, nil return out, nil
} }
+75
View File
@@ -69,3 +69,78 @@ func TestRouter_NilFallback(t *testing.T) {
_, err := r.Complete(context.Background(), "sys", "user") _, err := r.Complete(context.Background(), "sys", "user")
assert.Error(t, err) assert.Error(t, err)
} }
func TestRouter_FallsBackToTertiaryWhenPrimaryAndFallbackFail(t *testing.T) {
fail := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "unavailable", http.StatusServiceUnavailable)
}))
defer fail.Close()
tertiary := mockServer(t, "from-tertiary")
defer tertiary.Close()
r := &Router{
Primary: New(fail.URL, "", "m", time.Second),
Fallback: New(fail.URL, "", "m", time.Second),
Tertiary: New(tertiary.URL, "", "m", time.Second),
}
out, err := r.Complete(context.Background(), "sys", "user")
require.NoError(t, err)
assert.Equal(t, "from-tertiary", out)
}
func TestRouter_TertiaryNotCalledWhenFallbackSucceeds(t *testing.T) {
fail := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "unavailable", http.StatusServiceUnavailable)
}))
defer fail.Close()
fallback := mockServer(t, "from-fallback")
defer fallback.Close()
tertiary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Error("tertiary must not be called when fallback succeeds")
}))
defer tertiary.Close()
r := &Router{
Primary: New(fail.URL, "", "m", time.Second),
Fallback: New(fallback.URL, "", "m", time.Second),
Tertiary: New(tertiary.URL, "", "m", time.Second),
}
out, err := r.Complete(context.Background(), "sys", "user")
require.NoError(t, err)
assert.Equal(t, "from-fallback", out)
}
func TestRouter_AllThreeFail(t *testing.T) {
fail := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "err", http.StatusBadGateway)
}))
defer fail.Close()
r := &Router{
Primary: New(fail.URL, "", "m", time.Second),
Fallback: New(fail.URL, "", "m", time.Second),
Tertiary: New(fail.URL, "", "m", time.Second),
}
_, err := r.Complete(context.Background(), "sys", "user")
assert.Error(t, err)
assert.Contains(t, err.Error(), "primary llm")
assert.Contains(t, err.Error(), "fallback llm")
assert.Contains(t, err.Error(), "tertiary llm")
}
func TestRouter_NilTertiary(t *testing.T) {
// Existing 2-tier deployments (no BRAIN_LLM_TERTIARY_URL) must keep working
// exactly as before — Tertiary is opt-in, not required.
fail := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "err", http.StatusBadGateway)
}))
defer fail.Close()
r := &Router{
Primary: New(fail.URL, "", "m", time.Second),
Fallback: New(fail.URL, "", "m", time.Second),
}
_, err := r.Complete(context.Background(), "sys", "user")
assert.Error(t, err)
assert.NotContains(t, err.Error(), "tertiary")
}
+1 -1
View File
@@ -165,7 +165,7 @@ func TestBrainUpdateReembedsNewContent(t *testing.T) {
ctx := context.Background() ctx := context.Background()
callResult(t, toolCall(t, srv, "brain_write", map[string]any{ callResult(t, toolCall(t, srv, "brain_write", map[string]any{
"content": "# Note\n\nthe OLD distinctive payload\n", "content": "# Note\n\nthe OLD distinctive payload\n",
"filename": "n", "wing": "a", "hall": "facts", "filename": "n", "wing": "a", "hall": "facts",
})) }))
+66 -20
View File
@@ -14,6 +14,7 @@ import (
"github.com/mathiasbq/hyperguild/ingestion/internal/capture" "github.com/mathiasbq/hyperguild/ingestion/internal/capture"
"github.com/mathiasbq/hyperguild/ingestion/internal/extract" "github.com/mathiasbq/hyperguild/ingestion/internal/extract"
"github.com/mathiasbq/hyperguild/ingestion/internal/graphsync" "github.com/mathiasbq/hyperguild/ingestion/internal/graphsync"
"github.com/mathiasbq/hyperguild/ingestion/internal/notes"
"github.com/mathiasbq/hyperguild/ingestion/internal/pipeline" "github.com/mathiasbq/hyperguild/ingestion/internal/pipeline"
"github.com/mathiasbq/hyperguild/ingestion/internal/search" "github.com/mathiasbq/hyperguild/ingestion/internal/search"
"github.com/mathiasbq/hyperguild/ingestion/internal/session" "github.com/mathiasbq/hyperguild/ingestion/internal/session"
@@ -52,14 +53,12 @@ func (s *Server) tools() []map[string]any {
}, },
{ {
"name": "brain_write", "name": "brain_write",
"description": "Write a markdown note to the brain. With wing+hall set, routes to brain/wiki/<wing>/<hall>/ with wing/hall/created_at frontmatter; otherwise writes to brain/knowledge/ (legacy).", "description": "Write a markdown note to brain/wiki/<wing>/<hall>/ with wing/hall/created_at frontmatter. Both wing and hall are required.",
"inputSchema": schema([]string{"content"}, map[string]any{ "inputSchema": schema([]string{"content", "wing", "hall"}, map[string]any{
"content": str("markdown content"), "content": str("markdown content"),
"filename": str("optional filename or slug"), "filename": str("optional filename or slug"),
"type": str("optional frontmatter type (legacy)"), "wing": str("topic domain, e.g. jepa-fx"),
"domain": str("optional frontmatter domain (legacy)"), "hall": enum("memory type", halls...),
"wing": str("optional topic domain, e.g. jepa-fx"),
"hall": enum("optional memory type (requires wing)", halls...),
}), }),
}, },
{ {
@@ -97,6 +96,16 @@ func (s *Server) tools() []map[string]any {
"slug": str("optional target slug; defaults to filename minus date prefix"), "slug": str("optional target slug; defaults to filename minus date prefix"),
}), }),
}, },
{
"name": "brain_reject",
"description": "Reject a brain/raw/ note: stamps rejected_at (+ reject_reason if given) into frontmatter and moves it to brain/raw/rejected/ — never deleted outright, and never re-surfaced by brain_pending. The third option alongside promote/leave-pending; a human decision, never automatic. Returns {path}.",
"inputSchema": schema([]string{"filename"}, map[string]any{
"filename": str("basename in brain/raw/, e.g. 2026-04-23-fed-sentiment-scrape.md"),
"reason": str("optional; why this isn't worth promoting"),
}),
},
noteToolDescriptors()[0],
noteToolDescriptors()[1],
{ {
"name": "brain_tunnel", "name": "brain_tunnel",
"description": "Create an explicit bidirectional [[wikilink]] between two notes in different wings. Idempotent.", "description": "Create an explicit bidirectional [[wikilink]] between two notes in different wings. Idempotent.",
@@ -105,13 +114,6 @@ func (s *Server) tools() []map[string]any {
"target": str("path of target note (must be in a different wing)"), "target": str("path of target note (must be in a different wing)"),
}), }),
}, },
{
"name": "brain_index",
"description": "Regenerate _index.md (Map of Content) for one or all wings under brain/wiki/. Auto-called after brain_write with wing+hall.",
"inputSchema": schema([]string{}, map[string]any{
"wing": str("optional wing to index; if absent, rebuilds every wing"),
}),
},
{ {
"name": "brain_ingest_raw", "name": "brain_ingest_raw",
"description": "Ingest pre-structured pages into the brain wiki, bypassing the LLM extraction step.", "description": "Ingest pre-structured pages into the brain wiki, bypassing the LLM extraction step.",
@@ -231,12 +233,19 @@ func (s *Server) brainQuery(ctx context.Context, args json.RawMessage) (json.Raw
type brainWriteArgs struct { type brainWriteArgs struct {
Content string `json:"content"` Content string `json:"content"`
Filename string `json:"filename,omitempty"` Filename string `json:"filename,omitempty"`
Type string `json:"type,omitempty"`
Domain string `json:"domain,omitempty"`
Wing string `json:"wing,omitempty"` Wing string `json:"wing,omitempty"`
Hall string `json:"hall,omitempty"` Hall string `json:"hall,omitempty"`
} }
// unlinkedNote explains the `unlinked` field to the caller that caused it.
// The write landed; what is gone is the [[...]] around a target that names no
// brain entry. Said here rather than only in a doc comment because the caller
// is a model that will otherwise repeat it on the next write.
const unlinkedNote = "these [[wikilink]] targets resolve to no brain entry, " +
"so they were unwrapped to plain text. Link only entries that exist " +
"(a filename under knowledge/ or wiki/); write the target entry first if " +
"you want the link, and keep skills, repos and agent-local memory files as prose."
func (s *Server) brainWrite(ctx context.Context, args json.RawMessage) (json.RawMessage, error) { func (s *Server) brainWrite(ctx context.Context, args json.RawMessage) (json.RawMessage, error) {
var a brainWriteArgs var a brainWriteArgs
if err := json.Unmarshal(args, &a); err != nil { if err := json.Unmarshal(args, &a); err != nil {
@@ -249,15 +258,18 @@ func (s *Server) brainWrite(ctx context.Context, args json.RawMessage) (json.Raw
ref, err := s.store.Write(ctx, capture.Note{ ref, err := s.store.Write(ctx, capture.Note{
Content: a.Content, Content: a.Content,
Filename: a.Filename, Filename: a.Filename,
Type: a.Type,
Domain: a.Domain,
Wing: a.Wing, Wing: a.Wing,
Hall: a.Hall, Hall: a.Hall,
}) })
if err != nil { if err != nil {
return nil, err return nil, err
} }
return json.Marshal(map[string]string{"id": ref.ID, "path": ref.Path, "content_hash": ref.ContentHash}) out := map[string]any{"id": ref.ID, "path": ref.Path, "content_hash": ref.ContentHash}
if len(ref.Unlinked) > 0 {
out["unlinked"] = ref.Unlinked
out["unlinked_note"] = unlinkedNote
}
return json.Marshal(out)
} }
type brainUpdateArgs struct { type brainUpdateArgs struct {
@@ -301,9 +313,14 @@ func (s *Server) brainUpdate(ctx context.Context, args json.RawMessage) (json.Ra
if err != nil { if err != nil {
return nil, err return nil, err
} }
return json.Marshal(map[string]any{ out := map[string]any{
"id": ref.ID, "path": ref.Path, "content_hash": ref.ContentHash, "superseded": ref.Superseded, "id": ref.ID, "path": ref.Path, "content_hash": ref.ContentHash, "superseded": ref.Superseded,
}) }
if len(ref.Unlinked) > 0 {
out["unlinked"] = ref.Unlinked
out["unlinked_note"] = unlinkedNote
}
return json.Marshal(out)
} }
type brainGetArgs struct { type brainGetArgs struct {
@@ -327,6 +344,15 @@ func (s *Server) brainGet(ctx context.Context, args json.RawMessage) (json.RawMe
if target == "" { if target == "" {
return nil, fmt.Errorf("id or path is required") return nil, fmt.Errorf("id or path is required")
} }
// Containment: the store resolves any brain-relative path, and
// parseFrontmatter returns the WHOLE file as body when there is no
// frontmatter fence — so without this, brain_get reads verbatim session
// transcripts under archive/ and sessions/, which BM25 never indexes and
// which nobody therefore thinks of as reachable. Same allowlist as
// brain_read (brain#4).
if _, err := notes.Resolve(s.brainDir, target, notes.ScopeNotes); err != nil {
return nil, err
}
note, err := s.store.Get(ctx, target) note, err := s.store.Get(ctx, target)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -371,6 +397,26 @@ func (s *Server) brainPromote(ctx context.Context, args json.RawMessage) (json.R
return json.Marshal(map[string]string{"path": relPath}) return json.Marshal(map[string]string{"path": relPath})
} }
type brainRejectArgs struct {
Filename string `json:"filename"`
Reason string `json:"reason,omitempty"`
}
// brainReject records a decision not to promote a raw/ note (api.RejectNote:
// frontmatter-stamp + move to raw/rejected/). No graph indexing — a rejected
// note never entered the wiki, so there's nothing to index.
func (s *Server) brainReject(_ context.Context, args json.RawMessage) (json.RawMessage, error) {
var a brainRejectArgs
if err := json.Unmarshal(args, &a); err != nil {
return nil, fmt.Errorf("parse args: %w", err)
}
relPath, err := api.RejectNote(s.brainDir, api.RejectOptions{Filename: a.Filename, Reason: a.Reason})
if err != nil {
return nil, err
}
return json.Marshal(map[string]string{"path": relPath})
}
// indexInGraph is a best-effort wrapper around graphsync.IndexDoc that // indexInGraph is a best-effort wrapper around graphsync.IndexDoc that
// logs failures but never propagates them — the underlying write/ingest // logs failures but never propagates them — the underlying write/ingest
// has already succeeded and the graph is an augmentation, not a // has already succeeded and the graph is an augmentation, not a
+70 -29
View File
@@ -51,25 +51,50 @@ func TestBrainQueryReturnsResults(t *testing.T) {
assert.Contains(t, text, "tdd.md") assert.Contains(t, text, "tdd.md")
} }
func TestBrainWriteCreatesFile(t *testing.T) { // TestBrainWriteIgnoresLegacyTypeAndDomainParams pins the post-#79 contract:
// domain/type were removed from the schema and the handler's arg struct, so
// a caller that still sends them (the old MCP surface) gets a normal wing+
// hall write with no error and no effect from the stale fields — silently
// dropped by json.Unmarshal, not rejected. Only content in its OWN
// frontmatter (unrelated to these params) can set type/domain, per
// TestWriteNote_HallRouteMergesExistingFrontmatterInsteadOfStacking in the
// api package.
func TestBrainWriteIgnoresLegacyTypeAndDomainParams(t *testing.T) {
brainDir := t.TempDir() brainDir := t.TempDir()
srv := mcp.NewServer(brainDir, nil, nil, nil) srv := mcp.NewServer(brainDir, nil, nil, nil)
resp := toolCall(t, srv, "brain_write", map[string]any{ resp := toolCall(t, srv, "brain_write", map[string]any{
"content": "# Test\n\nbody", "content": "# Test\n\nbody",
"filename": "test.md", "filename": "test",
"wing": "homelab",
"hall": "facts",
"type": "note", "type": "note",
"domain": "personal", "domain": "personal",
}) })
require.Nil(t, resp["error"]) require.Nil(t, resp["error"])
got, err := os.ReadFile(filepath.Join(brainDir, "knowledge", "test.md")) got, err := os.ReadFile(filepath.Join(brainDir, "wiki", "homelab", "facts", "test.md"))
require.NoError(t, err) require.NoError(t, err)
assert.Contains(t, string(got), "type: note") assert.NotContains(t, string(got), "type: note")
assert.Contains(t, string(got), "domain: personal") assert.NotContains(t, string(got), "domain: personal")
assert.Contains(t, string(got), "# Test") assert.Contains(t, string(got), "# Test")
} }
// TestBrainWriteRequiresWingAndHall is the MCP-tool-call counterpart of
// api.TestWriteNote_RequiresWingAndHall: the legacy brain/knowledge/
// fallback is gone, so a caller omitting either param gets a tool error,
// not a silent legacy write.
func TestBrainWriteRequiresWingAndHall(t *testing.T) {
brainDir := t.TempDir()
srv := mcp.NewServer(brainDir, nil, nil, nil)
resp := toolCall(t, srv, "brain_write", map[string]any{
"content": "x",
"filename": "no-destination",
})
require.NotNil(t, resp["error"])
}
func TestBrainWriteWingHallRoutesToWiki(t *testing.T) { func TestBrainWriteWingHallRoutesToWiki(t *testing.T) {
brainDir := t.TempDir() brainDir := t.TempDir()
srv := mcp.NewServer(brainDir, nil, nil, nil) srv := mcp.NewServer(brainDir, nil, nil, nil)
@@ -208,30 +233,11 @@ func TestBrainTunnelRejectsMissing(t *testing.T) {
require.NotNil(t, resp["error"]) require.NotNil(t, resp["error"])
} }
func TestBrainWriteRejectsTraversal(t *testing.T) { // Filename traversal/sanitisation on the wiki route is covered directly
brainDir := t.TempDir() // against brain.NotePath/Sanitise in internal/brain/path_test.go
srv := mcp.NewServer(brainDir, nil, nil, nil) // (TestNotePath_SanitisesWingAndSlug, TestSanitise) — those tests exercised
// the now-deleted brain/knowledge/ legacy path's own separate filename
resp := toolCall(t, srv, "brain_write", map[string]any{ // validation, which had no equivalent once that path was removed (#79).
"content": "x",
"filename": "../escape.md",
})
require.NotNil(t, resp["error"])
}
func TestBrainWriteAcceptsDoubleDotInName(t *testing.T) {
brainDir := t.TempDir()
srv := mcp.NewServer(brainDir, nil, nil, nil)
resp := toolCall(t, srv, "brain_write", map[string]any{
"content": "x",
"filename": "notes..draft.md",
})
require.Nil(t, resp["error"])
_, err := os.Stat(filepath.Join(brainDir, "knowledge", "notes..draft.md"))
require.NoError(t, err, "filename with embedded .. should be allowed")
}
func TestBrainIngestRawDryRun(t *testing.T) { func TestBrainIngestRawDryRun(t *testing.T) {
brainDir := t.TempDir() brainDir := t.TempDir()
@@ -390,3 +396,38 @@ func TestBrainPromoteInvalidHallErrors(t *testing.T) {
_, srcErr := os.Stat(filepath.Join(raw, "x.md")) _, srcErr := os.Stat(filepath.Join(raw, "x.md"))
assert.NoError(t, srcErr, "source untouched on validation error") assert.NoError(t, srcErr, "source untouched on validation error")
} }
func TestBrainRejectMovesToRejectedSubdir(t *testing.T) {
brainDir := t.TempDir()
raw := filepath.Join(brainDir, "raw")
require.NoError(t, os.MkdirAll(raw, 0o755))
require.NoError(t, os.WriteFile(filepath.Join(raw, "2026-04-23-scrape.md"),
[]byte("---\ncreated_at: 2026-04-23T13:20:07Z\n---\n# Scrape\n\nbody\n"), 0o644))
srv := mcp.NewServer(brainDir, nil, nil, nil)
resp := toolCall(t, srv, "brain_reject", map[string]any{
"filename": "2026-04-23-scrape.md", "reason": "generic scrape, not homelab-relevant",
})
require.Nil(t, resp["error"], "got: %v", resp["error"])
text := resp["result"].(map[string]any)["content"].([]any)[0].(map[string]any)["text"].(string)
assert.Contains(t, text, "raw/rejected/2026-04-23-scrape.md")
got, err := os.ReadFile(filepath.Join(brainDir, "raw/rejected/2026-04-23-scrape.md"))
require.NoError(t, err)
assert.Contains(t, string(got), "reject_reason: generic scrape, not homelab-relevant")
_, srcErr := os.Stat(filepath.Join(raw, "2026-04-23-scrape.md"))
assert.True(t, os.IsNotExist(srcErr), "source removed from raw/")
// A rejected note must not still show up as pending.
pendingResp := toolCall(t, srv, "brain_pending", map[string]any{})
pendingText := pendingResp["result"].(map[string]any)["content"].([]any)[0].(map[string]any)["text"].(string)
assert.Contains(t, pendingText, `"pending":[]`)
}
func TestBrainRejectMissingSourceErrors(t *testing.T) {
brainDir := t.TempDir()
srv := mcp.NewServer(brainDir, nil, nil, nil)
resp := toolCall(t, srv, "brain_reject", map[string]any{"filename": "ghost.md"})
require.NotNil(t, resp["error"])
}
+76
View File
@@ -0,0 +1,76 @@
package mcp
import (
"time"
"github.com/mathiasbq/hyperguild/ingestion/internal/api"
)
// pendingNudgeThreshold is how old a raw/ note has to be before brain_context
// mentions the queue. Two weeks: long enough that a note written this sprint
// does not nag, short enough that four items cannot sit unnoticed for three
// months again (#82).
const pendingNudgeThreshold = 14 * 24 * time.Hour
// PendingNudge is the in-session reminder that the promote/reject queue has
// items waiting. It is advisory: a count, an age, and how to look.
type PendingNudge struct {
Pending int `json:"pending"` // everything in the queue
Aging int `json:"aging"` // those past the threshold
Oldest string `json:"oldest"` // filename of the oldest pending note
OldestDays int `json:"oldest_days"` // its age, in whole days
Hint string `json:"hint"`
}
// pendingNudge summarises the raw/ review queue, or returns nil when there is
// nothing worth saying.
//
// The trigger is the missing half of the queue (#82): brain_pending has always
// existed, and four real items still sat unreviewed from 2026-04-23 to
// 2026-07-15 because nothing ever prompted anyone to call it. The system
// should be what remembers the queue exists.
//
// Threshold-gated on purpose. A notice on every context call is one people
// learn to skip, which reproduces the original failure with extra steps.
//
// It never promotes, rejects, or reorders anything. Age is a reason to ask a
// human, not a verdict — an old note may be exactly right to promote once
// someone finally looks at it.
func pendingNudge(brainDir string, now time.Time, threshold time.Duration) *PendingNudge {
pending, err := api.ListPending(brainDir)
if err != nil || len(pending) == 0 {
// brain_context is a hot path; a broken queue degrades to silence
// rather than failing the call that asked for project context.
return nil
}
var aging int
var oldestName string
var oldestAge time.Duration
for _, p := range pending {
created, perr := time.Parse(time.RFC3339, p.CreatedAt)
if perr != nil {
continue // an unparseable timestamp is not evidence of age
}
age := now.Sub(created)
if age >= threshold {
aging++
}
if age > oldestAge {
oldestAge, oldestName = age, p.Filename
}
}
if aging == 0 {
return nil
}
return &PendingNudge{
Pending: len(pending),
Aging: aging,
Oldest: oldestName,
OldestDays: int(oldestAge.Hours() / 24),
Hint: "call brain_pending to review; nothing is promoted or rejected automatically",
}
}
@@ -0,0 +1,115 @@
package mcp
import (
"context"
"encoding/json"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// writePending drops a raw/ note whose created_at is age old.
func writePending(t *testing.T, brainDir, name string, age time.Duration, now time.Time) {
t.Helper()
raw := filepath.Join(brainDir, "raw")
require.NoError(t, os.MkdirAll(raw, 0o755))
body := "---\ncreated_at: " + now.Add(-age).UTC().Format(time.RFC3339) + "\n---\n\nnote body\n"
require.NoError(t, os.WriteFile(filepath.Join(raw, name), []byte(body), 0o644))
}
func TestPendingNudge_SilentWhenNothingIsPending(t *testing.T) {
// No queue, no nudge. A notice that fires every session is one people
// learn to skip, which is how the queue got ignored for three months in
// the first place (#82).
got := pendingNudge(t.TempDir(), time.Now(), 14*24*time.Hour)
assert.Nil(t, got)
}
func TestPendingNudge_SilentWhileEverythingIsBelowTheThreshold(t *testing.T) {
now := time.Now()
dir := t.TempDir()
writePending(t, dir, "fresh.md", 2*24*time.Hour, now)
got := pendingNudge(dir, now, 14*24*time.Hour)
assert.Nil(t, got, "a two-day-old note is not aging")
}
func TestPendingNudge_ReportsCountAndOldestAgeOnceSomethingAges(t *testing.T) {
now := time.Now()
dir := t.TempDir()
writePending(t, dir, "old.md", 100*24*time.Hour, now)
writePending(t, dir, "older.md", 120*24*time.Hour, now)
writePending(t, dir, "fresh.md", 1*24*time.Hour, now)
got := pendingNudge(dir, now, 14*24*time.Hour)
require.NotNil(t, got)
// All three are pending; the threshold decides whether to speak, not
// what to count. Someone opening the queue sees the whole queue.
assert.Equal(t, 3, got.Pending)
assert.Equal(t, 2, got.Aging)
assert.Equal(t, 120, got.OldestDays)
assert.Equal(t, "older.md", got.Oldest)
}
func TestPendingNudge_NeverDecidesAnything(t *testing.T) {
// Aging is a trigger to ask a human, never a verdict. The nudge must
// carry no action and must leave the queue exactly as it found it.
now := time.Now()
dir := t.TempDir()
writePending(t, dir, "ancient.md", 365*24*time.Hour, now)
before, err := os.ReadDir(filepath.Join(dir, "raw"))
require.NoError(t, err)
got := pendingNudge(dir, now, 14*24*time.Hour)
require.NotNil(t, got)
after, err := os.ReadDir(filepath.Join(dir, "raw"))
require.NoError(t, err)
assert.Len(t, after, len(before), "the nudge must not promote or reject anything")
assert.Contains(t, got.Hint, "brain_pending", "the nudge should say how to look, not act")
}
func TestPendingNudge_SurvivesAnUnreadableQueue(t *testing.T) {
// brain_context is a hot path; a broken raw/ dir must degrade to silence
// rather than failing the whole context call.
dir := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(dir, "raw"), []byte("not a directory"), 0o644))
assert.NotPanics(t, func() {
assert.Nil(t, pendingNudge(dir, time.Now(), 14*24*time.Hour))
})
}
func TestBrainContext_CarriesTheNudgeWithoutFailingWhenTheQueueIsEmpty(t *testing.T) {
// The wiring, not the summary: a nudge that never reaches a caller is the
// same as no nudge, and brain_context must still work with no queue.
dir := t.TempDir()
srv := NewServer(dir, nil, nil, nil)
raw, err := srv.brainContext(context.Background(),
json.RawMessage(`{"project_root":"/home/mathias/dev/AGENTS/hyperguild"}`))
require.NoError(t, err)
var empty map[string]any
require.NoError(t, json.Unmarshal(raw, &empty))
assert.NotContains(t, empty, "pending_review", "silence when nothing is aging")
writePending(t, dir, "ancient.md", 200*24*time.Hour, time.Now())
raw, err = srv.brainContext(context.Background(),
json.RawMessage(`{"project_root":"/home/mathias/dev/AGENTS/hyperguild"}`))
require.NoError(t, err)
var withQueue map[string]any
require.NoError(t, json.Unmarshal(raw, &withQueue))
nudge, ok := withQueue["pending_review"].(map[string]any)
require.True(t, ok, "the nudge must reach the caller: %v", withQueue)
assert.Equal(t, float64(1), nudge["aging"])
assert.Equal(t, "ancient.md", nudge["oldest"])
}
+19 -1
View File
@@ -1,9 +1,14 @@
// Package mcp implements an MCP HTTP handler for the ingestion service. // Package mcp implements an MCP HTTP handler for the ingestion service.
// Exposed tools: brain_query, brain_write, brain_update, brain_get, // Exposed tools: brain_query, brain_write, brain_update, brain_get,
// brain_pending, brain_promote, brain_index, brain_tunnel, brain_ingest, // brain_pending, brain_promote, brain_tunnel, brain_ingest,
// brain_ingest_raw, brain_answer, brain_classify, brain_graph, // brain_ingest_raw, brain_answer, brain_classify, brain_graph,
// brain_context, session_log, and capture (the #55 relay tool, registered // brain_context, session_log, and capture (the #55 relay tool, registered
// only when WithCapture is set). // only when WithCapture is set).
//
// brain_index dispatches but is deliberately absent from tools/list: it is
// auto-called after every write, so surfacing it as a caller verb is
// cognitive load with no decision behind it (ADR-0012 rule 4, #78). It stays
// callable for maintenance — de-surfacing hides the verb, not the operation.
package mcp package mcp
import ( import (
@@ -44,6 +49,8 @@ type rpcError struct {
// Server handles MCP JSON-RPC over HTTP for the ingestion service. // Server handles MCP JSON-RPC over HTTP for the ingestion service.
type Server struct { type Server struct {
brainDir string brainDir string
govAudit capture.AuditSink
govNotify govNotifier
pipeline pipeline.Config pipeline pipeline.Config
llm pipeline.CompleteFunc llm pipeline.CompleteFunc
answerLLM pipeline.CompleteFunc // nil = brain_answer and brain_classify unavailable answerLLM pipeline.CompleteFunc // nil = brain_answer and brain_classify unavailable
@@ -268,8 +275,19 @@ func (s *Server) handleCall(ctx context.Context, name string, args json.RawMessa
return s.brainPending(ctx, args) return s.brainPending(ctx, args)
case "brain_promote": case "brain_promote":
return s.brainPromote(ctx, args) return s.brainPromote(ctx, args)
case "brain_reject":
return s.brainReject(ctx, args)
case "capture": case "capture":
return s.brainCapture(ctx, args) return s.brainCapture(ctx, args)
case "brain_read":
return s.brainRead(ctx, args)
case "brain_edit":
return s.brainEdit(ctx, args)
case "brain_edit_root":
// Dispatches but is intentionally absent from tools/list — see
// tools_notes.go for why a governance-file editor must not be
// discoverable by a model.
return s.brainEditRoot(ctx, args)
case "brain_index": case "brain_index":
return s.brainIndex(ctx, args) return s.brainIndex(ctx, args)
case "brain_tunnel": case "brain_tunnel":
+36 -2
View File
@@ -58,12 +58,44 @@ func TestServerToolsList(t *testing.T) {
} }
assert.ElementsMatch(t, []string{ assert.ElementsMatch(t, []string{
"brain_query", "brain_write", "brain_update", "brain_get", "brain_query", "brain_write", "brain_update", "brain_get",
"brain_pending", "brain_promote", "brain_pending", "brain_promote", "brain_reject",
"brain_index", "brain_tunnel", "brain_read", "brain_edit",
"brain_tunnel",
"brain_ingest_raw", "brain_ingest", "brain_ingest_raw", "brain_ingest",
"brain_answer", "brain_classify", "brain_graph", "brain_context", "brain_answer", "brain_classify", "brain_graph", "brain_context",
"session_log", "session_log",
}, names) }, names)
// brain_index is auto-called after every brain_write, so surfacing it as
// a caller verb is cognitive load with no decision behind it (ADR-0012
// rule 4, #78). The capability stays reachable — see the admin test below.
assert.NotContains(t, names, "brain_index")
// brain_edit_root is de-surfaced for a sharper reason than brain_index:
// brain content is ingested from the outside world and reaches a model's
// context, so a listed governance-file editor would be a durable
// prompt-injection path — one poisoned page rewriting the CLAUDE.md a
// .dispatch-allow agent later loads as instructions.
assert.NotContains(t, names, "brain_edit_root")
}
func TestBrainIndexStaysCallableForAdminUseAfterDeSurfacing(t *testing.T) {
// De-surfacing hides the verb from the model-facing list; it must not
// remove the operation. A maintenance caller still needs to rebuild a
// Map of Content by hand.
srv := mcp.NewServer(t.TempDir(), nil, nil, nil)
req := httptest.NewRequest(http.MethodPost, "/mcp", body(t, map[string]any{
"jsonrpc": "2.0", "id": 3, "method": "tools/call",
"params": map[string]any{"name": "brain_index", "arguments": map[string]any{}},
}))
rr := httptest.NewRecorder()
srv.ServeHTTP(rr, req)
require.Equal(t, http.StatusOK, rr.Code)
var resp map[string]any
require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &resp))
assert.NotContains(t, resp, "error", "brain_index must still dispatch: %v", resp["error"])
} }
func TestServerNotificationGetsNoBody(t *testing.T) { func TestServerNotificationGetsNoBody(t *testing.T) {
@@ -102,9 +134,11 @@ type stubTracker struct{}
func (stubTracker) CreateIssue(context.Context, string, string, string) (capture.IssueRef, error) { func (stubTracker) CreateIssue(context.Context, string, string, string) (capture.IssueRef, error) {
return capture.IssueRef{}, nil return capture.IssueRef{}, nil
} }
func (stubTracker) CloseIssue(context.Context, string, int, string) (capture.IssueRef, error) { func (stubTracker) CloseIssue(context.Context, string, int, string) (capture.IssueRef, error) {
return capture.IssueRef{}, nil return capture.IssueRef{}, nil
} }
func (stubTracker) CommentIssue(context.Context, string, int, string) (capture.IssueRef, error) { func (stubTracker) CommentIssue(context.Context, string, int, string) (capture.IssueRef, error) {
return capture.IssueRef{}, nil return capture.IssueRef{}, nil
} }
+5 -9
View File
@@ -31,7 +31,7 @@ func captureToolDescriptor() map[string]any {
"type": "object", "type": "object",
"properties": map[string]any{ "properties": map[string]any{
"text": str("the insight body"), "wing": str("brain wing"), "text": str("the insight body"), "wing": str("brain wing"),
"hall": str("brain hall (facts/decisions/failures/hypotheses/sources)"), "hall": str("brain hall (facts/decisions/failures/hypotheses/sources)"),
"supersede_slug": str("optional: slug of a prior note to revise in place instead of creating"), "supersede_slug": str("optional: slug of a prior note to revise in place instead of creating"),
}, },
"required": []string{"text", "wing", "hall"}, "required": []string{"text", "wing", "hall"},
@@ -41,7 +41,7 @@ func captureToolDescriptor() map[string]any {
"properties": map[string]any{ "properties": map[string]any{
"repo": str("gitea repo (owner is always mathias)"), "action": str("create|close|comment"), "repo": str("gitea repo (owner is always mathias)"), "action": str("create|close|comment"),
"number": map[string]any{"type": "integer", "description": "issue number (close/comment)"}, "number": map[string]any{"type": "integer", "description": "issue number (close/comment)"},
"title": str("issue title (create)"), "body": str("issue/comment body"), "title": str("issue title (create)"), "body": str("issue/comment body"),
}, },
"required": []string{"repo", "action"}, "required": []string{"repo", "action"},
} }
@@ -51,24 +51,20 @@ func captureToolDescriptor() map[string]any {
"context": map[string]any{ "context": map[string]any{
"type": "object", "type": "object",
"properties": map[string]any{ "properties": map[string]any{
"harness": str("descriptive harness label (telemetry only, never a gate input)"), "harness": str("descriptive harness label (telemetry only, never a gate input)"),
"session_ref": str("optional session reference"), "fidelity": str("live-capture|transcript-parse|agent-runlog"), "session_ref": str("optional session reference"), "fidelity": str("live-capture|transcript-parse|agent-runlog"),
"actor": str("acting user/agent"), "classification": str("caller-declared sensitivity: public|internal|confidential"), "actor": str("acting user/agent"), "classification": str("caller-declared sensitivity: public|internal|confidential"),
}, },
}, },
"insights": map[string]any{"type": "array", "items": insightItem}, "insights": map[string]any{"type": "array", "items": insightItem},
"tickets": map[string]any{"type": "array", "items": ticketItem}, "tickets": map[string]any{"type": "array", "items": ticketItem},
"summary": map[string]any{"type": "object", "properties": map[string]any{ "dry_run": map[string]any{"type": "boolean", "description": "validate + return the would-be receipt, write nothing"},
"title": str("summary title"), "body": str("summary body"),
"repos_touched": map[string]any{"type": "array", "items": map[string]any{"type": "string"}},
}},
"dry_run": map[string]any{"type": "boolean", "description": "validate + return the would-be receipt, write nothing"},
}, },
} }
b, _ := json.Marshal(schema) b, _ := json.Marshal(schema)
return map[string]any{ return map[string]any{
"name": "capture", "name": "capture",
"description": "Persist a session's value uniformly: insights → brain (write or supersede), action items → Gitea tickets, optional summary → ai-sessions. The relay door for MCP-native harnesses. Origin is server-derived from your authenticated identity; confidential captures through a us-nexus surface are refused (I1). Returns a partial-aware receipt.", "description": "Persist a session's value uniformly: insights → brain (write or supersede), action items → Gitea tickets. The relay door for MCP-native harnesses. Origin is server-derived from your authenticated identity; confidential captures through a us-nexus surface are refused (I1). Returns a partial-aware receipt.",
"inputSchema": json.RawMessage(b), "inputSchema": json.RawMessage(b),
} }
} }
+3 -1
View File
@@ -28,9 +28,11 @@ type capFakeTracker struct{}
func (capFakeTracker) CreateIssue(context.Context, string, string, string) (capture.IssueRef, error) { func (capFakeTracker) CreateIssue(context.Context, string, string, string) (capture.IssueRef, error) {
return capture.IssueRef{Repo: "hyperguild", Number: 1, URL: "https://git/1"}, nil return capture.IssueRef{Repo: "hyperguild", Number: 1, URL: "https://git/1"}, nil
} }
func (capFakeTracker) CloseIssue(context.Context, string, int, string) (capture.IssueRef, error) { func (capFakeTracker) CloseIssue(context.Context, string, int, string) (capture.IssueRef, error) {
return capture.IssueRef{}, nil return capture.IssueRef{}, nil
} }
func (capFakeTracker) CommentIssue(context.Context, string, int, string) (capture.IssueRef, error) { func (capFakeTracker) CommentIssue(context.Context, string, int, string) (capture.IssueRef, error) {
return capture.IssueRef{}, nil return capture.IssueRef{}, nil
} }
@@ -49,7 +51,7 @@ func captureServer(t *testing.T, validator capturehttp.Validator, sovereign []st
brainDir := t.TempDir() brainDir := t.TempDir()
cfg, err := classification.Load(brainDir) cfg, err := classification.Load(brainDir)
require.NoError(t, err) require.NoError(t, err)
svc := capture.NewService(brainstore.New(brainDir), capFakeTracker{}, nil, cfg, audit.NewSlogSink(nil)) svc := capture.NewService(brainstore.New(brainDir), capFakeTracker{}, cfg, audit.NewSlogSink(nil))
srv := mcp.NewServer(brainDir, nil, nil, nil) srv := mcp.NewServer(brainDir, nil, nil, nil)
srv.WithCapture(svc, validator, capStaticTok, "local-cli", capturehttp.NewOriginResolver(sovereign)) srv.WithCapture(svc, validator, capStaticTok, "local-cli", capturehttp.NewOriginResolver(sovereign))
return srv, brainDir return srv, brainDir
+12 -9
View File
@@ -8,8 +8,10 @@ import (
"path/filepath" "path/filepath"
"sort" "sort"
"strings" "strings"
"time"
"github.com/mathiasbq/hyperguild/ingestion/internal/search" "github.com/mathiasbq/hyperguild/ingestion/internal/search"
"github.com/mathiasbq/hyperguild/ingestion/internal/textutil"
) )
// brainContextArgs is the input shape of brain_context. project_root is // brainContextArgs is the input shape of brain_context. project_root is
@@ -155,17 +157,21 @@ func (s *Server) brainContext(ctx context.Context, args json.RawMessage) (json.R
entries = entries[:limit] entries = entries[:limit]
} }
return json.Marshal(map[string]any{"entries": entries}) out := map[string]any{"entries": entries}
// The queue nudge rides along with a call the session already makes, so
// noticing an aging note costs nobody a decision to go looking (#82).
// Advisory only, and absent entirely when there is nothing to say.
if n := pendingNudge(s.brainDir, time.Now(), pendingNudgeThreshold); n != nil {
out["pending_review"] = n
}
return json.Marshal(out)
} }
// truncateExcerpt clamps an already-stripped excerpt to maxLen characters // truncateExcerpt clamps an already-stripped excerpt to maxLen characters
// without re-running the frontmatter parser. The ellipsis suffix matches // without re-running the frontmatter parser. The ellipsis suffix matches
// the convention used in search.excerpt. // the convention used in search.excerpt.
func truncateExcerpt(s string, maxLen int) string { func truncateExcerpt(s string, maxLen int) string {
if len(s) <= maxLen { return textutil.Truncate(s, maxLen)
return s
}
return s[:maxLen] + "…"
} }
// readExcerpt loads a doc relative to brainDir, strips its frontmatter, // readExcerpt loads a doc relative to brainDir, strips its frontmatter,
@@ -185,10 +191,7 @@ func readExcerpt(brainDir, relPath string, maxLen int) string {
if len(parts) == 3 { if len(parts) == 3 {
body = strings.TrimSpace(parts[2]) body = strings.TrimSpace(parts[2])
} }
if len(body) > maxLen { return textutil.Truncate(body, maxLen)
return body[:maxLen] + "…"
}
return body
} }
// max1 returns the maximum of n and 1, used to guard against divide-by-zero // max1 returns the maximum of n and 1, used to guard against divide-by-zero
+399
View File
@@ -0,0 +1,399 @@
package mcp
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"strings"
"time"
"github.com/mathiasbq/hyperguild/ingestion/internal/brain"
"github.com/mathiasbq/hyperguild/ingestion/internal/capture"
"github.com/mathiasbq/hyperguild/ingestion/internal/claim"
"github.com/mathiasbq/hyperguild/ingestion/internal/classification"
"github.com/mathiasbq/hyperguild/ingestion/internal/frontmatter"
"github.com/mathiasbq/hyperguild/ingestion/internal/notes"
)
// noteToolDescriptors are the model-facing halves of brain#4.
//
// brain_edit_root is deliberately absent: it dispatches but is not listed, the
// same de-surfacing ADR-0012 rule 4 applies to brain_index (#78). Hiding the
// verb matters here for a specific reason — brain content is ingested from the
// outside world and reaches a model's context, so a listed governance-file
// editor is a durable prompt-injection path: one poisoned page could rewrite
// the CLAUDE.md that a .dispatch-allow agent later obeys. A human who knows
// the tool exists can still call it; a model reading tools/list cannot
// discover it.
func noteToolDescriptors() []map[string]any {
str := func(d string) map[string]any { return map[string]any{"type": "string", "description": d} }
schema := func(required []string, props map[string]any) json.RawMessage {
b, _ := json.Marshal(map[string]any{"type": "object", "required": required, "properties": props})
return b
}
return []map[string]any{
{
"name": "brain_read",
"description": "Return a note's raw markdown verbatim — no synthesis, no excerpting. " +
"Use this to obtain the exact text before brain_edit; never build old_str from a " +
"brain_query excerpt, which is truncated and normalised and will not match.",
"inputSchema": schema([]string{"path"}, map[string]any{
"path": str("brain-relative path under knowledge/ or wiki/, e.g. wiki/homelab/facts/x.md"),
}),
},
{
"name": "brain_edit",
"description": "Replace exactly one occurrence of old_str with new_str in a note, leaving " +
"every other byte identical. Fails loudly if old_str is absent or matches more than " +
"once — extend old_str until it is unique. Does NOT stamp updated_at or supersedes " +
"(brain_update does); it is a byte-level patch, not a metadata operation.",
"inputSchema": schema([]string{"path", "old_str", "new_str"}, map[string]any{
"path": str("brain-relative path under knowledge/ or wiki/"),
"old_str": str("exact text to replace; must occur exactly once"),
"new_str": str("replacement text; empty string deletes old_str"),
}),
},
}
}
// --- hyperguild#97: governance-rewrite observability -----------------------
// govNotifier raises an out-of-band alert. Declared here rather than importing
// internal/audit so the MCP package keeps depending on capture alone.
type govNotifier interface {
Notify(ctx context.Context, msg string) error
}
// WithGovernanceObserver attaches the audit sink and notifier that observe a
// successful brain_edit_root. Both are optional; either may be nil.
func (s *Server) WithGovernanceObserver(sink capture.AuditSink, n govNotifier) {
s.govAudit, s.govNotify = sink, n
}
type brainReadArgs struct {
Path string `json:"path"`
}
func (s *Server) brainRead(_ context.Context, args json.RawMessage) (json.RawMessage, error) {
var a brainReadArgs
if err := json.Unmarshal(args, &a); err != nil {
return nil, fmt.Errorf("parse args: %w", err)
}
content, err := notes.Read(s.brainDir, a.Path)
if err != nil {
return nil, err
}
return json.Marshal(map[string]any{"path": a.Path, "content": string(content)})
}
type brainEditArgs struct {
Path string `json:"path"`
OldStr string `json:"old_str"`
NewStr string `json:"new_str"`
}
// brainEdit is the model-facing editor: notes only.
//
// Deliberately NOT audited (#97). A note edit is already fully reconstructible
// from git history, which carries the same before/after bytes plus a diff.
// Governance files get the extra trail because they change what later agents
// obey — the asymmetry is about instruction-carrying content, not about how
// hard the change is to reconstruct. Auditing every note edit would also bury
// the rare governance record under routine traffic, which is how an alert
// stops being read.
func (s *Server) brainEdit(_ context.Context, args json.RawMessage) (json.RawMessage, error) {
_, out, err := s.editWithScope(args, notes.ScopeNotes)
return out, err
}
// brainEditRoot edits a governance file (CLAUDE.md). De-surfaced AND gated on
// the authenticated principal: only the static local-CLI token may call it, so
// a claude.ai-origin session — the one that may have just read an untrusted
// page — cannot rewrite the instructions later agents load.
func (s *Server) brainEditRoot(ctx context.Context, args json.RawMessage) (json.RawMessage, error) {
info, ok := ctx.Value(principalKey).(principalInfo)
if !ok || !info.viaStatic {
return nil, fmt.Errorf("brain_edit_root requires the local static principal; " +
"a governance file is not editable from a model-facing origin")
}
res, out, err := s.editWithScope(args, notes.ScopeRoot)
if err != nil {
// A refusal is not a rewrite. Recording or alerting on one would cry
// wolf, and the gate already logs its own denials.
return out, err
}
// A durable instruction rewrite should be loud, not silent.
slog.Warn("brain_edit_root applied", "principal", info.principal, "result", string(out))
s.observeGovernanceEdit(ctx, info.principal, res)
return out, err
}
// observeGovernanceEdit records and alerts on a rewrite that already landed.
//
// Best-effort by construction: the bytes are written and brain-sync will commit
// them within the quarter hour, so failing the call here would report a
// non-rewrite to the caller while the rewrite sits on disk. A failure to
// observe is therefore logged at ERROR — the one case where the trail itself is
// what broke, and the only remaining signal.
func (s *Server) observeGovernanceEdit(ctx context.Context, principal string, res notes.Result) {
// Path and hashes only. The notification leaves the cluster for a phone
// via a third-party topic; a hash identifies the rewrite, the bytes would
// leak whatever was written into an instruction file.
msg := fmt.Sprintf("brain_edit_root applied\npath=%s\nprincipal=%s\nbefore=%s\nafter=%s",
res.Path, principal, res.PrevContentHash, res.ContentHash)
if s.govNotify != nil {
if err := s.govNotify.Notify(ctx, msg); err != nil {
slog.Error("brain_edit_root notify failed", "path", res.Path, "err", err)
}
}
if s.govAudit == nil {
return
}
// Internal, not Confidential: a governance file is not client data, and
// Confidential would make DegradingSink REFUSE to record while loki is
// down rather than buffer — losing exactly the record that matters most.
outcome, err := s.govAudit.Reserve(ctx, classification.Internal)
if err != nil {
slog.Error("brain_edit_root audit reserve failed", "path", res.Path, "err", err)
return
}
entry := capture.AuditEntry{
Timestamp: time.Now().UTC(),
Principal: principal,
Actor: "brain_edit_root",
Harness: "mcp",
EffectiveClassification: classification.Internal.String(),
Items: []string{res.Path},
SecurityEvents: []string{fmt.Sprintf(
"governance file rewritten: %s before=%s after=%s",
res.Path, res.PrevContentHash, res.ContentHash)},
}
if err := s.govAudit.Record(ctx, entry, outcome); err != nil {
slog.Error("brain_edit_root audit record failed", "path", res.Path, "err", err)
}
}
func (s *Server) editWithScope(args json.RawMessage, scope notes.Scope) (notes.Result, json.RawMessage, error) {
var a brainEditArgs
if err := json.Unmarshal(args, &a); err != nil {
return notes.Result{}, nil, fmt.Errorf("parse args: %w", err)
}
// hyperguild#123: brain_write/brain_update both validate the claim
// envelope before writing (hyperguild#111: "same rules when a note
// changes as when it's born"); brain_edit didn't — a byte-level string
// replace has no frontmatter awareness at all, so it could rewrite an
// existing half_life:/applies:/claim_provenance: line straight past the
// validator entirely. Scoped to notes only (governance files have no
// claim-envelope concept).
if scope == notes.ScopeNotes {
if verr := checkClaimEnvelope(s.brainDir, a.Path, a.OldStr, a.NewStr); verr != nil {
return notes.Result{}, nil, fmt.Errorf("claim envelope: %w", verr)
}
}
res, err := notes.Edit(s.brainDir, a.Path, a.OldStr, a.NewStr, scope)
if err != nil {
if errors.Is(err, notes.ErrDegenerate) && a.OldStr == "" {
// hyperguild#115: "old_str is empty" alone doesn't say whether the
// caller sent it empty or a hop between the caller and here lost
// it. Naming the raw argument byte count makes that distinguishable
// without a second investigation.
return notes.Result{}, nil, fmt.Errorf("%w (raw arguments were %d bytes)", err, len(args))
}
return notes.Result{}, nil, err
}
// Reindex only when the edit could have changed what the index reads.
// BuildWingIndex consumes title/created_at from the frontmatter block;
// BM25 walks the filesystem live and embeddings are mtime-driven, so an
// unconditional rebuild would buy nothing and dirty a second file —
// _index.md being precisely the class brain-sync already needs a bespoke
// conflict resolver for.
if wing := wingOf(res.Path); wing != "" && touchesFrontmatter(a.OldStr, a.NewStr) {
if ierr := brain.BuildWingIndex(s.brainDir, wing); ierr != nil {
// Best-effort, matching every other index hook here: the write
// already landed and will be committed, so failing the call would
// make the caller retry an edit whose old_str no longer exists.
res.ReindexError = ierr.Error()
}
}
out, merr := json.Marshal(res)
return res, out, merr
}
// wingOf returns the wing for a wiki path, or "" for knowledge/ and root.
func wingOf(rel string) string {
parts := strings.Split(rel, "/")
if len(parts) < 3 || parts[0] != "wiki" {
return ""
}
return parts[1]
}
// touchesFrontmatter reports whether either side of the edit mentions a field
// the wing index reads.
func touchesFrontmatter(oldStr, newStr string) bool {
for _, s := range []string{oldStr, newStr} {
if strings.Contains(s, "title:") || strings.Contains(s, "created_at:") || strings.Contains(s, "---") {
return true
}
}
return false
}
// checkClaimEnvelope previews what old_str->new_str would produce — the
// exact strings.Replace(before, oldStr, newStr, 1) formula notes.Edit
// itself uses internally — and validates the resulting frontmatter's claim
// envelope before the real edit is allowed to run. Fail-closed: an invalid
// result blocks the edit entirely, the same posture writeHallNote/UpdateNote
// already apply on create/supersede.
//
// Gated on old_str appearing within the note's frontmatter BLOCK, not on
// old_str/new_str mentioning a claim-envelope field NAME — found in review:
// a field-name-substring gate misses a value-only edit like
// "asserted"->"guessed" on a claim_provenance line, which never mentions
// the field name at all. That is exactly the shape of edit a minimal,
// natural diff produces, so a field-name gate was closing the issue in
// name only. Checking block containment instead means any edit that
// couldn't possibly touch the frontmatter (its target text only exists in
// the body) is still skipped cheaply, while nothing inside the fence can
// slip through unvalidated regardless of which token it targets.
//
// This does not replicate notes.Edit's uniqueness/CRLF/conflict-marker
// checks — if old_str is absent or ambiguous, this preview may not match
// what Edit ultimately does, but Edit independently and correctly rejects
// those cases at write time regardless of what this function decides, so
// the only thing riding on this preview's accuracy is the envelope check
// itself, not write safety.
// checkClaimEnvelope previews what old_str->new_str would produce and
// validates the resulting claim envelope before the real edit runs
// (hyperguild#123). Seven review rounds closed every plausible bypass in the
// fence-detection family (field-name substring, block-containment,
// fence-stripping, CRLF, UTF-8 BOM) and the first instance of a
// value-extraction gap (a folded YAML block scalar hiding a value behind an
// empty inline colon).
//
// Known, accepted v1 gap: frontmatterScalars's block-scalar fold is a
// best-effort approximation, not a YAML parser — a blank line interrupting a
// folded continuation, or other contrived multi-line YAML shapes not yet
// probed (block-scalar indicators `|`/`>`, inline comments on a key line,
// quoted multi-line values), can still hide an invalid value from
// ValidateEnvelope. Accepted deliberately rather than chased indefinitely:
// every bypass found so far requires the caller to already hold brain_edit
// write access and to deliberately construct a specific malformed-YAML shape
// with knowledge of this exact gap — a narrow, low-likelihood threat next to
// the diminishing returns of another incremental patch round. The real fix
// (a shared, tested, encoding-normalized frontmatter parser used by all
// three independent implementations in this codebase) is tracked separately
// as hyperguild#138, not bolted on here piece by piece.
func checkClaimEnvelope(brainDir, path, oldStr, newStr string) error {
if oldStr == "" {
// hyperguild#115: strings.Replace treats "" as matching position 0,
// which would make an empty old_str look like an edit that inserts
// text before the fence — a degenerate-input case that belongs to
// notes.Edit's own "old_str is empty" refusal, not to the envelope
// check.
return nil
}
before, err := notes.Read(brainDir, path)
if err != nil {
// Let notes.Edit itself produce the real error (missing file, etc.)
// — this function's job is the envelope, not read failures.
return nil
}
// No gate on where old_str falls relative to the frontmatter fence:
// round 2 found that requiring old_str to be fully contained in the
// extracted block was itself bypassable by an old_str disambiguated
// across the closing "---" into the body. Simpler and bypass-proof:
// always compute what the edit would produce and validate that
// resulting state's envelope. A body-only edit leaves the frontmatter
// (and thus the validation outcome) unchanged, so this is a no-op for
// the common case and fail-closed for every case that touches the
// envelope, regardless of how old_str is phrased.
_, hadFence := frontmatterBlock(string(before))
after := strings.Replace(string(before), oldStr, newStr, 1)
_, hasFence := frontmatterBlock(after)
if hadFence && !hasFence {
// Round 3: an edit that drops the closing fence degrades `after`
// to "unfenced" — frontmatterScalars then sees an empty map and
// ValidateEnvelope({}) is nil by design (absent fields are valid),
// so an invalid value would otherwise land with zero error while
// also corrupting the note's structure. A previously-fenced note
// must stay fenced, full stop.
return fmt.Errorf("edit would remove the frontmatter fence")
}
return claim.ValidateEnvelope(frontmatterScalars(after))
}
// frontmatterBlock returns the raw text between doc's opening and closing
// `---` fences, or ok=false if doc has no (properly closed) fence.
func frontmatterBlock(doc string) (block string, ok bool) {
// hyperguild#138: fence detection itself is frontmatter.Split, shared
// with internal/api and internal/frontmatter — the CRLF/BOM guards that
// used to live here (added piecemeal across rounds 4 and 5 of #123's
// review) are now the shared parser's job, so every caller inherits a
// fix instead of needing bug-for-bug parity edits.
b, _, ok := frontmatter.Split([]byte(doc))
if !ok {
return "", false
}
// Split's block keeps the "\n" immediately before the closing fence
// (by design — see its own doc comment); this function never included
// it. Split guarantees ok=true only when "\n---\n" matched, so this is
// always exactly one byte, never ambiguous.
return strings.TrimSuffix(string(b), "\n"), true
}
// frontmatterScalars extracts top-level "key: value" scalar pairs from
// doc's leading fence block, for the claim-envelope check only — not a
// general frontmatter parser. Indented lines (YAML block-list items,
// wrapped values) are skipped rather than misparsed as keys, same fix as
// hyperguild#126/#128 in the sibling packages this mirrors.
func frontmatterScalars(doc string) map[string]string {
out := map[string]string{}
block, ok := frontmatterBlock(doc)
if !ok {
return out
}
lines := strings.Split(block, "\n")
for i := 0; i < len(lines); i++ {
line := lines[i]
if line != "" && (line[0] == ' ' || line[0] == '\t') {
continue
}
key, val, ok := strings.Cut(line, ":")
if !ok {
continue
}
val = strings.TrimSpace(val)
if val == "" {
// Round 6: a colon with nothing after it is ambiguous — it can
// be a genuinely empty/omitted value, or the start of a YAML
// block scalar whose real value lives on the indented
// continuation line(s) that follow (e.g. "half_life:\n
// durable"). Treating the latter as absent let an edit smuggle
// an invalid value straight past ValidateEnvelope: the field
// read as unset while the disk actually carried a value. Fold
// the continuation in as a best-effort join so oneOf() still
// sees it. A genuinely empty value (no indented line follows)
// still folds to "", preserving present()'s existing
// placeholder-not-assertion contract.
var cont []string
for i+1 < len(lines) {
next := lines[i+1]
if next == "" || (next[0] != ' ' && next[0] != '\t') {
break
}
cont = append(cont, strings.TrimSpace(next))
i++
}
val = strings.Join(cont, " ")
}
out[strings.TrimSpace(key)] = val
}
return out
}
+557
View File
@@ -0,0 +1,557 @@
// ingestion/internal/mcp/tools_notes_test.go
package mcp_test
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/mathiasbq/hyperguild/ingestion/internal/audit"
"github.com/mathiasbq/hyperguild/ingestion/internal/brainstore"
"github.com/mathiasbq/hyperguild/ingestion/internal/capture"
"github.com/mathiasbq/hyperguild/ingestion/internal/capturehttp"
"github.com/mathiasbq/hyperguild/ingestion/internal/classification"
"github.com/mathiasbq/hyperguild/ingestion/internal/mcp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// ---- brain#4: brain_read / brain_edit through the JSON-RPC surface --------
func newBrainRepo(t *testing.T) string {
t.Helper()
dir := t.TempDir()
require.NoError(t, os.MkdirAll(filepath.Join(dir, ".git"), 0o755))
require.NoError(t, os.MkdirAll(filepath.Join(dir, "wiki/homelab/facts"), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(dir, "wiki/homelab/facts/n.md"),
[]byte("---\ntitle: 'n'\n---\n\nalpha\nbeta\n"), 0o644))
require.NoError(t, os.WriteFile(filepath.Join(dir, "CLAUDE.md"), []byte("# rules\n"), 0o644))
return dir
}
func call(t *testing.T, srv *mcp.Server, name string, args map[string]any) map[string]any {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/mcp", body(t, map[string]any{
"jsonrpc": "2.0", "id": 1, "method": "tools/call",
"params": map[string]any{"name": name, "arguments": args},
}))
rr := httptest.NewRecorder()
srv.ServeHTTP(rr, req)
var resp map[string]any
require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &resp))
return resp
}
func TestBrainReadAndEdit_RoundTripThroughJSONRPC(t *testing.T) {
// The Go functions are tested in internal/notes; this pins the transport,
// because a tool that works in-process and is unreachable over JSON-RPC
// is indistinguishable from a working one in a unit test.
dir := newBrainRepo(t)
srv := mcp.NewServer(dir, nil, nil, nil)
resp := call(t, srv, "brain_read", map[string]any{"path": "wiki/homelab/facts/n.md"})
require.NotContains(t, resp, "error", "%v", resp["error"])
resp = call(t, srv, "brain_edit", map[string]any{
"path": "wiki/homelab/facts/n.md", "old_str": "beta", "new_str": "BETA",
})
require.NotContains(t, resp, "error", "%v", resp["error"])
got, err := os.ReadFile(filepath.Join(dir, "wiki/homelab/facts/n.md"))
require.NoError(t, err)
assert.Equal(t, "---\ntitle: 'n'\n---\n\nalpha\nBETA\n", string(got),
"only the matched bytes may change")
}
func TestBrainEdit_EmptyOldStrErrorNamesRawArgumentBytes(t *testing.T) {
// hyperguild#115: a session reported "old_str is empty" with an old_str
// that, on their end, was never empty. The server-side path was
// unreachable to reproduce (verified separately: a fresh brain_edit call
// with real content round-trips cleanly), which points at something
// between a specific client and this call losing the field. The fix this
// issue actually asked for isn't a behavior change — old_str=="" must
// still refuse — it's that the refusal should say how many raw argument
// bytes it received, so "client sent empty" is distinguishable from
// "server received empty after some hop lost it" without a second
// session's worth of guessing.
dir := newBrainRepo(t)
srv := mcp.NewServer(dir, nil, nil, nil)
resp := call(t, srv, "brain_edit", map[string]any{
"path": "wiki/homelab/facts/n.md", "old_str": "", "new_str": "BETA",
})
errMsg, ok := resp["error"].(map[string]any)["message"].(string)
require.True(t, ok, "%v", resp)
assert.Contains(t, errMsg, "old_str is empty")
assert.Contains(t, errMsg, "raw arguments were", "%v", errMsg)
}
func TestBrainEdit_RejectsAnInvalidClaimEnvelopeWrittenViaStringReplace(t *testing.T) {
// hyperguild#123: brain_write/brain_update both validate the claim
// envelope (half_life/applies/claim_provenance) before writing —
// brain_edit didn't, even though it's the one live, model-facing path
// that can rewrite an existing envelope line directly via raw string
// replace, no parsing involved. "same rules when a note changes as when
// it's born" (hyperguild#111's own framing) applies here too.
dir := newBrainRepo(t)
note := filepath.Join(dir, "wiki/homelab/facts/n.md")
require.NoError(t, os.WriteFile(note,
[]byte("---\ntitle: 'n'\nhalf_life: durable\napplies: universal\nclaim_provenance: asserted\n---\n\nbody\n"), 0o644))
srv := mcp.NewServer(dir, nil, nil, nil)
resp := call(t, srv, "brain_edit", map[string]any{
"path": "wiki/homelab/facts/n.md", "old_str": "claim_provenance: asserted", "new_str": "claim_provenance: guessed",
})
require.Contains(t, resp, "error", "%v", resp)
got, err := os.ReadFile(note)
require.NoError(t, err)
assert.Contains(t, string(got), "claim_provenance: asserted", "rejected edit must leave the note byte-identical")
}
func TestBrainEdit_RejectsAValueOnlyEditThatBreaksTheEnvelope(t *testing.T) {
// Found in review: the original gate (touchesClaimEnvelope) checked
// whether old_str/new_str mention the FIELD NAME — but a minimal diff
// (the natural shape of any real edit, model-generated or human) can
// target just the VALUE token and never mention the field name at all.
// "asserted" -> "guessed" on a claim_provenance line walked straight
// past the field-name substring check and wrote an invalid enum value
// with no error — the exact bypass #123 was supposed to close, closed
// in name only.
dir := newBrainRepo(t)
note := filepath.Join(dir, "wiki/homelab/facts/n.md")
require.NoError(t, os.WriteFile(note,
[]byte("---\ntitle: 'n'\nhalf_life: durable\napplies: universal\nclaim_provenance: asserted\n---\n\nbody\n"), 0o644))
srv := mcp.NewServer(dir, nil, nil, nil)
resp := call(t, srv, "brain_edit", map[string]any{
"path": "wiki/homelab/facts/n.md", "old_str": "asserted", "new_str": "guessed",
})
require.Contains(t, resp, "error", "%v", resp)
got, err := os.ReadFile(note)
require.NoError(t, err)
assert.Contains(t, string(got), "claim_provenance: asserted", "rejected edit must leave the note byte-identical")
}
func TestBrainEdit_RejectsAnOldStrThatCrossesTheClosingFence(t *testing.T) {
// Found in round-2 review: the position-based gate required old_str to
// be fully CONTAINED in the extracted frontmatter block (which excludes
// both "---" fence lines). An old_str disambiguated by extending past
// the closing fence into the body — a natural choice, since notes.Edit
// requires old_str to be unique in the file — fails that containment
// test, so checkClaimEnvelope skips validation entirely while
// notes.Edit still applies the replace verbatim. Same invalid-enum
// outcome as the original two bypasses, reached a third way.
dir := newBrainRepo(t)
note := filepath.Join(dir, "wiki/homelab/facts/n.md")
require.NoError(t, os.WriteFile(note,
[]byte("---\ntitle: 'n'\nhalf_life: durable\napplies: universal\nclaim_provenance: asserted\n---\n\nbody\n"), 0o644))
srv := mcp.NewServer(dir, nil, nil, nil)
resp := call(t, srv, "brain_edit", map[string]any{
"path": "wiki/homelab/facts/n.md",
"old_str": "asserted\n---\n\nbody",
"new_str": "guessed\n---\n\nbody",
})
require.Contains(t, resp, "error", "%v", resp)
got, err := os.ReadFile(note)
require.NoError(t, err)
assert.Contains(t, string(got), "claim_provenance: asserted", "rejected edit must leave the note byte-identical")
}
func TestBrainEdit_RejectsAnEditThatRemovesTheClosingFence(t *testing.T) {
// Found in round-3 review: checkClaimEnvelope always validates the
// resulting frontmatter of `after` — but an edit whose new_str drops
// the closing "---" degrades `after` to "unfenced" in the same call.
// frontmatterBlock(after) then returns ok=false, frontmatterScalars
// returns an empty map, and claim.ValidateEnvelope({}) is nil by
// design (absent fields are valid) — so an invalid enum value lands on
// disk with zero error, and the note is left permanently unfenced.
// Structural fix: a note that had a valid fence before the edit must
// still have one after, or the edit is rejected outright.
dir := newBrainRepo(t)
note := filepath.Join(dir, "wiki/homelab/facts/n.md")
require.NoError(t, os.WriteFile(note,
[]byte("---\ntitle: 'n'\nhalf_life: durable\napplies: universal\nclaim_provenance: asserted\n---\n\nbody\n"), 0o644))
srv := mcp.NewServer(dir, nil, nil, nil)
resp := call(t, srv, "brain_edit", map[string]any{
"path": "wiki/homelab/facts/n.md",
"old_str": "claim_provenance: asserted\n---\n",
"new_str": "claim_provenance: not-a-real-value\n",
})
require.Contains(t, resp, "error", "%v", resp)
got, err := os.ReadFile(note)
require.NoError(t, err)
assert.Contains(t, string(got), "claim_provenance: asserted\n---\n", "rejected edit must leave the note byte-identical, fence intact")
}
func TestBrainEdit_RejectsAnInvalidEnvelopeOnACRLFFencedNote(t *testing.T) {
// Found in round-4 review: frontmatterBlock's fence detection matches
// the literal byte sequence "---\n" / "\n---\n". A note whose fence
// lines use CRLF ("---\r\n") fails strings.HasPrefix(doc, "---\n") on
// the BEFORE read, so hadFence is false — not because the fence is
// missing, but because \r sits in front of every \n. hadFence&&!hasFence
// can then never fire, frontmatterScalars falls back to an empty map,
// and claim.ValidateEnvelope({}) is nil by design. No adversarial
// old_str/new_str crafting needed: encoding alone silently disables the
// whole envelope check for this note. Zero CRLF-fenced notes exist in
// the live corpus today, but nothing in the code prevents one.
dir := newBrainRepo(t)
note := filepath.Join(dir, "wiki/homelab/facts/n.md")
require.NoError(t, os.WriteFile(note,
[]byte("---\r\ntitle: 'n'\r\nhalf_life: durable\r\napplies: universal\r\nclaim_provenance: asserted\r\n---\r\n\r\nbody\r\n"), 0o644))
srv := mcp.NewServer(dir, nil, nil, nil)
resp := call(t, srv, "brain_edit", map[string]any{
"path": "wiki/homelab/facts/n.md", "old_str": "asserted", "new_str": "guessed",
})
require.Contains(t, resp, "error", "%v", resp)
got, err := os.ReadFile(note)
require.NoError(t, err)
assert.Contains(t, string(got), "claim_provenance: asserted", "rejected edit must leave the note byte-identical")
}
func TestBrainEdit_RejectsAnInvalidEnvelopeOnABOMPrefixedNote(t *testing.T) {
// Found in round-5 review: the same "encoding property empties
// frontmatterScalars's map" mechanism as the CRLF bypass, one layer
// earlier — a leading UTF-8 BOM (EF BB BF) defeats
// strings.HasPrefix(doc, "---\n") exactly like CRLF did, before that
// prefix is even reached. Notepad's default "UTF-8" save and
// PowerShell's pre-v6 Out-File/Set-Content both emit a BOM, so this is
// a live, plausible authoring path, not an exotic one — same severity
// and same one-line cost as the CRLF fix, fixed the same way rather
// than deferred to hyperguild#138.
dir := newBrainRepo(t)
note := filepath.Join(dir, "wiki/homelab/facts/n.md")
require.NoError(t, os.WriteFile(note,
[]byte("\xef\xbb\xbf---\ntitle: 'n'\nhalf_life: durable\napplies: universal\nclaim_provenance: asserted\n---\n\nbody\n"), 0o644))
srv := mcp.NewServer(dir, nil, nil, nil)
resp := call(t, srv, "brain_edit", map[string]any{
"path": "wiki/homelab/facts/n.md", "old_str": "asserted", "new_str": "guessed",
})
require.Contains(t, resp, "error", "%v", resp)
got, err := os.ReadFile(note)
require.NoError(t, err)
assert.Contains(t, string(got), "claim_provenance: asserted", "rejected edit must leave the note byte-identical")
}
func TestBrainEdit_RejectsAFoldedScalarThatHidesAnInvalidValue(t *testing.T) {
// Found in round-6 review: a different mechanism from the encoding
// family (rounds 1-6 were all about fence detection; this is the field
// extractor). old_str="half_life: durable", new_str="half_life:\n
// garbage-value" turns the field into a YAML block-scalar shape: the
// top-level line is now "half_life:" with an empty inline value, and
// the real value lives on the indented continuation line that follows.
// frontmatterScalars's indentation guard skips that continuation line
// outright, so the field reads as present-with-empty-value —
// present()'s own contract then treats that as absent (a placeholder,
// not an assertion) — and claim.ValidateEnvelope never sees the
// invalid value at all. No encoding quirk needed: one ordinary
// brain_edit call smuggles an out-of-enum value straight past the
// check the field was supposed to be validated by.
dir := newBrainRepo(t)
note := filepath.Join(dir, "wiki/homelab/facts/n.md")
require.NoError(t, os.WriteFile(note,
[]byte("---\ntitle: 'n'\nhalf_life: durable\napplies: universal\nclaim_provenance: asserted\n---\n\nbody\n"), 0o644))
srv := mcp.NewServer(dir, nil, nil, nil)
resp := call(t, srv, "brain_edit", map[string]any{
"path": "wiki/homelab/facts/n.md",
"old_str": "half_life: durable",
"new_str": "half_life:\n garbage-value",
})
require.Contains(t, resp, "error", "%v", resp)
got, err := os.ReadFile(note)
require.NoError(t, err)
assert.Contains(t, string(got), "half_life: durable", "rejected edit must leave the note byte-identical")
}
func TestBrainEdit_AllowsAValidClaimEnvelopeEdit(t *testing.T) {
dir := newBrainRepo(t)
note := filepath.Join(dir, "wiki/homelab/facts/n.md")
require.NoError(t, os.WriteFile(note,
[]byte("---\ntitle: 'n'\nhalf_life: durable\napplies: universal\nclaim_provenance: asserted\n---\n\nbody\n"), 0o644))
srv := mcp.NewServer(dir, nil, nil, nil)
resp := call(t, srv, "brain_edit", map[string]any{
"path": "wiki/homelab/facts/n.md", "old_str": "half_life: durable", "new_str": "half_life: seasonal",
})
require.NotContains(t, resp, "error", "%v", resp)
got, err := os.ReadFile(note)
require.NoError(t, err)
assert.Contains(t, string(got), "half_life: seasonal")
}
func TestBrainEdit_UnrelatedEditsSkipTheEnvelopeCheckEntirely(t *testing.T) {
// The gate only engages when old_str/new_str actually mention an
// envelope field name — an ordinary body edit on a note that happens to
// carry a valid envelope must not pay for (or be affected by) a check
// that has nothing to do with it.
dir := newBrainRepo(t)
note := filepath.Join(dir, "wiki/homelab/facts/n.md")
require.NoError(t, os.WriteFile(note,
[]byte("---\ntitle: 'n'\nhalf_life: durable\napplies: universal\nclaim_provenance: asserted\n---\n\nold body\n"), 0o644))
srv := mcp.NewServer(dir, nil, nil, nil)
resp := call(t, srv, "brain_edit", map[string]any{
"path": "wiki/homelab/facts/n.md", "old_str": "old body", "new_str": "new body",
})
require.NotContains(t, resp, "error", "%v", resp)
got, err := os.ReadFile(note)
require.NoError(t, err)
assert.Contains(t, string(got), "new body")
}
func TestBrainEditRoot_GovernanceFilesAreNeverEnvelopeChecked(t *testing.T) {
// CLAUDE.md has no claim-envelope concept at all — the check must be
// scoped to notes (ScopeNotes), never applied on the governance path.
srv, _, _, _ := govServer(t)
resp := authCall(t, srv, "Bearer "+capStaticTok, "brain_edit_root", map[string]any{
"path": "CLAUDE.md", "old_str": "# rules", "new_str": "half_life: durable",
})
require.NotContains(t, resp, "error", "%v", resp)
}
func TestBrainEdit_RefusesGovernanceFilesFromTheModelFacingTool(t *testing.T) {
dir := newBrainRepo(t)
srv := mcp.NewServer(dir, nil, nil, nil)
resp := call(t, srv, "brain_edit", map[string]any{
"path": "CLAUDE.md", "old_str": "# rules", "new_str": "# rewritten",
})
require.Contains(t, resp, "error", "brain_edit must not reach CLAUDE.md")
got, err := os.ReadFile(filepath.Join(dir, "CLAUDE.md"))
require.NoError(t, err)
assert.Equal(t, "# rules\n", string(got))
}
func TestBrainEditRoot_RefusedWithoutTheLocalStaticPrincipal(t *testing.T) {
// No principal in context is the model-facing case (and the default in
// this test server): the privileged door must stay shut.
dir := newBrainRepo(t)
srv := mcp.NewServer(dir, nil, nil, nil)
resp := call(t, srv, "brain_edit_root", map[string]any{
"path": "CLAUDE.md", "old_str": "# rules", "new_str": "# rewritten",
})
require.Contains(t, resp, "error")
got, err := os.ReadFile(filepath.Join(dir, "CLAUDE.md"))
require.NoError(t, err)
assert.Equal(t, "# rules\n", string(got), "governance file must be untouched")
}
func TestBrainGet_CannotReachSessionTranscripts(t *testing.T) {
// Pre-existing hole, not introduced here: api.ReadNote resolves any
// brain-relative path and parseFrontmatter returns the WHOLE file as body
// when there is no frontmatter fence. archive/ holds verbatim Claude
// session transcripts (up to 500 KB) that BM25 never indexes, so they are
// invisible to search and trivially readable by path — and CLAUDE.md
// documents the layout.
dir := newBrainRepo(t)
require.NoError(t, os.MkdirAll(filepath.Join(dir, "archive/claude-sessions/koala"), 0o755))
require.NoError(t, os.WriteFile(
filepath.Join(dir, "archive/claude-sessions/koala/session-1.md"),
[]byte("verbatim transcript with tool output\n"), 0o644))
srv := mcp.NewServer(dir, nil, nil, nil)
resp := call(t, srv, "brain_get", map[string]any{"path": "archive/claude-sessions/koala/session-1.md"})
require.Contains(t, resp, "error", "brain_get must not read outside knowledge/ and wiki/")
assert.NotContains(t, string(mustJSON(t, resp)), "verbatim transcript")
}
func TestBrainGet_StillReadsNotes(t *testing.T) {
dir := newBrainRepo(t)
srv := mcp.NewServer(dir, nil, nil, nil)
resp := call(t, srv, "brain_get", map[string]any{"path": "wiki/homelab/facts/n.md"})
assert.NotContains(t, resp, "error", "%v", resp["error"])
}
func mustJSON(t *testing.T, v any) []byte {
t.Helper()
b, err := json.Marshal(v)
require.NoError(t, err)
return b
}
// ---- hyperguild#97: a governance rewrite must be observed, not just gated ----
// govSink captures audit records. Governance edits are rare, so the whole
// history is kept and asserted on rather than sampled.
type govSink struct {
entries []capture.AuditEntry
outcomes []capture.AuditOutcome
recErr error
}
func (s *govSink) Reserve(context.Context, classification.Level) (capture.AuditOutcome, error) {
return capture.AuditCentral, nil
}
func (s *govSink) Record(_ context.Context, e capture.AuditEntry, o capture.AuditOutcome) error {
s.entries = append(s.entries, e)
s.outcomes = append(s.outcomes, o)
return s.recErr
}
type govNotifier struct {
msgs []string
err error
}
func (n *govNotifier) Notify(_ context.Context, msg string) error {
n.msgs = append(n.msgs, msg)
return n.err
}
// govServer wires capture (which is what re-derives the static principal) plus
// the #97 observer, and returns the brain dir so the test can read the file.
func govServer(t *testing.T) (*mcp.Server, string, *govSink, *govNotifier) {
t.Helper()
dir := newBrainRepo(t)
cfg, err := classification.Load(dir)
require.NoError(t, err)
svc := capture.NewService(brainstore.New(dir), capFakeTracker{}, cfg, audit.NewSlogSink(nil))
srv := mcp.NewServer(dir, nil, nil, nil)
srv.WithCapture(svc, nil, capStaticTok, "local-cli", capturehttp.NewOriginResolver(nil))
sink, notifier := &govSink{}, &govNotifier{}
srv.WithGovernanceObserver(sink, notifier)
return srv, dir, sink, notifier
}
// authCall is call() with an Authorization header, so the static principal is
// present and brain_edit_root's gate opens.
func authCall(t *testing.T, srv *mcp.Server, authz, name string, args map[string]any) map[string]any {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/mcp", body(t, map[string]any{
"jsonrpc": "2.0", "id": 1, "method": "tools/call",
"params": map[string]any{"name": name, "arguments": args},
}))
if authz != "" {
req.Header.Set("Authorization", authz)
}
rr := httptest.NewRecorder()
srv.ServeHTTP(rr, req)
var resp map[string]any
require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &resp))
return resp
}
func sha256hex(s string) string {
sum := sha256.Sum256([]byte(s))
return hex.EncodeToString(sum[:])
}
func TestBrainEditRoot_RecordsAnAuditEntryNamingPrincipalPathAndBothHashes(t *testing.T) {
// The gate proves a rewrite was ALLOWED. Only a record proves one HAPPENED
// — and brain-sync will commit it within 15 minutes authored `brain-sync`,
// so git history cannot tell it apart from routine note traffic.
srv, dir, sink, _ := govServer(t)
resp := authCall(t, srv, "Bearer "+capStaticTok, "brain_edit_root", map[string]any{
"path": "CLAUDE.md", "old_str": "# rules", "new_str": "# rewritten",
})
require.NotContains(t, resp, "error", "%v", resp["error"])
require.Len(t, sink.entries, 1, "exactly one audit record per governance rewrite")
e := sink.entries[0]
assert.Equal(t, "local-cli", e.Principal)
assert.Contains(t, e.Items, "CLAUDE.md", "the record must name what was rewritten")
joined := strings.Join(e.SecurityEvents, " ")
assert.Contains(t, joined, sha256hex("# rules\n"), "before-hash must be recorded")
assert.Contains(t, joined, sha256hex("# rewritten\n"), "after-hash must be recorded")
assert.NotZero(t, e.Timestamp)
got, err := os.ReadFile(filepath.Join(dir, "CLAUDE.md"))
require.NoError(t, err)
assert.Equal(t, "# rewritten\n", string(got))
}
func TestBrainEditRoot_NotifiesWithPathAndHashesButNeverContent(t *testing.T) {
srv, _, _, notifier := govServer(t)
resp := authCall(t, srv, "Bearer "+capStaticTok, "brain_edit_root", map[string]any{
"path": "CLAUDE.md", "old_str": "# rules", "new_str": "# rewritten",
})
require.NotContains(t, resp, "error", "%v", resp["error"])
require.Len(t, notifier.msgs, 1)
msg := notifier.msgs[0]
assert.Contains(t, msg, "CLAUDE.md")
assert.Contains(t, msg, "local-cli")
assert.Contains(t, msg, sha256hex("# rules\n"))
assert.Contains(t, msg, sha256hex("# rewritten\n"))
// The notification travels to a phone through a third-party topic. A hash
// identifies a rewrite; the bytes would leak whatever was written.
assert.NotContains(t, msg, "# rewritten", "no file content in the notification body")
assert.NotContains(t, msg, "# rules")
}
func TestBrainEditRoot_RefusedProducesNoRecordNoNotificationNoWrite(t *testing.T) {
srv, dir, sink, notifier := govServer(t)
// No Authorization header → no static principal → the gate stays shut.
resp := authCall(t, srv, "", "brain_edit_root", map[string]any{
"path": "CLAUDE.md", "old_str": "# rules", "new_str": "# rewritten",
})
require.Contains(t, resp, "error")
assert.Empty(t, sink.entries, "a refusal is not a rewrite — recording one would cry wolf")
assert.Empty(t, notifier.msgs)
got, err := os.ReadFile(filepath.Join(dir, "CLAUDE.md"))
require.NoError(t, err)
assert.Equal(t, "# rules\n", string(got))
}
func TestBrainEditRoot_FailedEditProducesNoRecordNoNotification(t *testing.T) {
// Authorised but no match: the door opened and nothing went through it.
srv, _, sink, notifier := govServer(t)
resp := authCall(t, srv, "Bearer "+capStaticTok, "brain_edit_root", map[string]any{
"path": "CLAUDE.md", "old_str": "absent-from-the-file", "new_str": "x",
})
require.Contains(t, resp, "error")
assert.Empty(t, sink.entries)
assert.Empty(t, notifier.msgs)
}
func TestBrainEdit_OnOrdinaryNotesIsNotAudited(t *testing.T) {
// The decided asymmetry (#97): note edits are covered by git history, which
// carries the same before/after bytes with a diff. Governance files get the
// extra trail because they change what later agents obey, not because they
// are harder to reconstruct.
srv, _, sink, notifier := govServer(t)
resp := authCall(t, srv, "Bearer "+capStaticTok, "brain_edit", map[string]any{
"path": "wiki/homelab/facts/n.md", "old_str": "beta", "new_str": "BETA",
})
require.NotContains(t, resp, "error", "%v", resp["error"])
assert.Empty(t, sink.entries, "note edits must not fill the governance audit trail")
assert.Empty(t, notifier.msgs)
}
+282
View File
@@ -0,0 +1,282 @@
package notes
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"syscall"
"unicode/utf8"
)
// maxNoteBytes caps what Read will hand back. Generous for knowledge/ and
// wiki/ (the largest note today is far under it) and small enough that a
// pathological file cannot flood a caller's context.
const maxNoteBytes = 256 << 10
// Errors callers distinguish.
var (
ErrNoMatch = errors.New("notes: old_str not found")
ErrAmbiguous = errors.New("notes: old_str matches more than once")
ErrNotUTF8 = errors.New("notes: content is not valid UTF-8")
ErrGitBusy = errors.New("notes: a git operation is in progress")
ErrTooLarge = errors.New("notes: file exceeds the readable size limit")
ErrDegenerate = errors.New("notes: edit is degenerate")
ErrInConflict = errors.New("notes: file contains unresolved conflict markers")
)
// pathLocks serialises edits per file within this process. The flock below
// covers the cross-process case (two pods share the hostPath during a rolling
// update, and brain-fix/brain-enrich write the same tree).
var pathLocks sync.Map // string -> *sync.Mutex
// Result is what a successful edit reports.
type Result struct {
Path string `json:"path"`
// PrevContentHash is the sha256 of the file as it was before this edit.
// Paired with ContentHash it identifies a rewrite in an audit trail or an
// alert without carrying any of the bytes (hyperguild#97).
PrevContentHash string `json:"prev_content_hash"`
ContentHash string `json:"content_hash"`
BytesBefore int `json:"bytes_before"`
BytesAfter int `json:"bytes_after"`
ReindexError string `json:"reindex_error,omitempty"`
}
// Read returns a note's bytes verbatim.
//
// No frontmatter parsing, no excerpting, no normalisation: the entire purpose
// is to give a caller an exact basis for an edit. An excerpt from brain_query
// would be truncated and normalised, and every old_str built from one would
// miss.
func Read(brainDir, path string) ([]byte, error) {
t, err := Resolve(brainDir, path, ScopeNotes)
if err != nil {
return nil, err
}
return readContained(t)
}
// ReadScoped is Read for a caller already holding the privileged scope.
func ReadScoped(brainDir, path string, scope Scope) ([]byte, error) {
t, err := Resolve(brainDir, path, scope)
if err != nil {
return nil, err
}
return readContained(t)
}
func readContained(t Target) ([]byte, error) {
fi, err := os.Stat(t.Abs)
if err != nil {
return nil, fmt.Errorf("notes: stat %s: %w", t.Rel, err)
}
if fi.Size() > maxNoteBytes {
return nil, fmt.Errorf("%w: %s is %d bytes (limit %d)", ErrTooLarge, t.Rel, fi.Size(), maxNoteBytes)
}
b, err := os.ReadFile(t.Abs)
if err != nil {
return nil, fmt.Errorf("notes: read %s: %w", t.Rel, err)
}
// The MCP response marshals this into a JSON string, and encoding/json
// substitutes U+FFFD for invalid UTF-8 — silently returning different
// bytes than the file holds, which defeats "verbatim" entirely.
if !utf8.Valid(b) {
return nil, fmt.Errorf("%w: %s", ErrNotUTF8, t.Rel)
}
return b, nil
}
// Edit replaces exactly one occurrence of oldStr with newStr, in place.
//
// Fails loudly and writes nothing on: zero matches, more than one match
// (counted with overlap), degenerate arguments, invalid UTF-8, a git operation
// in flight, or unresolved conflict markers in the target.
func Edit(brainDir, path, oldStr, newStr string, scope Scope) (Result, error) {
t, err := Resolve(brainDir, path, scope)
if err != nil {
return Result{}, err
}
if oldStr == "" {
return Result{}, fmt.Errorf("%w: old_str is empty", ErrDegenerate)
}
if oldStr == newStr {
return Result{}, fmt.Errorf("%w: old_str equals new_str", ErrDegenerate)
}
if !utf8.ValidString(newStr) {
return Result{}, fmt.Errorf("%w: new_str", ErrNotUTF8)
}
// brain#2 guard: refuse to write to a tree the sync does not commit from.
if err := assertSyncSource(brainDir); err != nil {
return Result{}, err
}
if err := assertGitIdle(brainDir); err != nil {
return Result{}, err
}
mu := lockFor(t.Abs)
mu.Lock()
defer mu.Unlock()
unlock, err := flockFile(t.Abs)
if err != nil {
return Result{}, err
}
defer unlock()
// Read INSIDE the lock: the match count must be evaluated against the
// bytes we are about to overwrite, or a concurrent edit is silently lost
// while both callers are told they succeeded.
before, err := readContained(t)
if err != nil {
return Result{}, err
}
if hasConflictMarkers(before) {
return Result{}, fmt.Errorf("%w: %s", ErrInConflict, t.Rel)
}
switch n := countOverlapping(string(before), oldStr); {
case n == 0:
return Result{}, fmt.Errorf("%w in %s (0 matches)%s", ErrNoMatch, t.Rel, crlfHint(string(before), oldStr))
case n > 1:
return Result{}, fmt.Errorf("%w in %s (%d matches) — extend old_str until it is unique",
ErrAmbiguous, t.Rel, n)
}
after := strings.Replace(string(before), oldStr, newStr, 1)
if err := writeAtomic(t.Abs, []byte(after)); err != nil {
return Result{}, err
}
sum := sha256.Sum256([]byte(after))
prev := sha256.Sum256(before)
return Result{
Path: t.Rel,
PrevContentHash: hex.EncodeToString(prev[:]),
ContentHash: hex.EncodeToString(sum[:]),
BytesBefore: len(before),
BytesAfter: len(after),
}, nil
}
// countOverlapping counts occurrences allowing overlap. bytes.Count does not:
// "aa" occurs once in "aaa" by its reckoning, so a Count-based uniqueness
// check accepts an ambiguous edit as unique.
func countOverlapping(s, sub string) int {
var n, from int
for {
i := strings.Index(s[from:], sub)
if i < 0 {
return n
}
n++
from += i + 1
}
}
// crlfHint reports whether the caller's old_str would have matched if line
// endings agreed. It never normalises — that would break byte-identity — but
// an opaque "no match" is unfixable from the caller's side, and a stripped \r
// is the likeliest cause.
func crlfHint(content, oldStr string) string {
if strings.Contains(content, "\r\n") && !strings.Contains(oldStr, "\r\n") {
if strings.Contains(strings.ReplaceAll(content, "\r\n", "\n"), oldStr) {
return " — the file uses CRLF line endings and old_str does not; include the \\r"
}
}
return ""
}
func hasConflictMarkers(b []byte) bool {
s := string(b)
return strings.Contains(s, "\n<<<<<<< ") || strings.HasPrefix(s, "<<<<<<< ")
}
// assertGitIdle refuses while brain-sync (or brain-fix, or a human) has a git
// operation in flight. An edit landing between `git merge` and its abort is
// either hard-reset away or committed as a wrongly resolved conflict — and the
// caller was told it succeeded.
func assertGitIdle(brainDir string) error {
for _, marker := range []string{"MERGE_HEAD", "REBASE_HEAD", "CHERRY_PICK_HEAD", "index.lock"} {
if _, err := os.Stat(filepath.Join(brainDir, ".git", marker)); err == nil {
return fmt.Errorf("%w (.git/%s present) — retry after the sync settles", ErrGitBusy, marker)
}
}
return nil
}
func lockFor(abs string) *sync.Mutex {
v, _ := pathLocks.LoadOrStore(abs, &sync.Mutex{})
return v.(*sync.Mutex)
}
// flockFile takes an advisory lock covering other processes sharing the
// hostPath — during a RollingUpdate two ingestion pods do.
func flockFile(abs string) (func(), error) {
f, err := os.OpenFile(abs+".lock", os.O_CREATE|os.O_RDWR, 0o644)
if err != nil {
return nil, fmt.Errorf("notes: lock %s: %w", filepath.Base(abs), err)
}
if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil {
_ = f.Close()
return nil, fmt.Errorf("notes: flock %s: %w", filepath.Base(abs), err)
}
return func() {
_ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
_ = f.Close()
_ = os.Remove(abs + ".lock")
}, nil
}
// writeAtomic replaces the file via a same-directory temp + rename, then
// fsyncs the directory so the rename survives a node crash.
//
// Same directory because a rename across the hostPath boundary fails with
// EXDEV; the ".tmp" suffix because the tree's .gitignore already covers it, so
// a leaked temp is not committed by `git add -A`.
func writeAtomic(abs string, content []byte) error {
dir := filepath.Dir(abs)
tmp, err := os.CreateTemp(dir, filepath.Base(abs)+".*.tmp")
if err != nil {
return fmt.Errorf("notes: temp file: %w", err)
}
tmpName := tmp.Name()
defer func() { _ = os.Remove(tmpName) }() // no-op once renamed
if _, err := tmp.Write(content); err != nil {
_ = tmp.Close()
return fmt.Errorf("notes: write temp: %w", err)
}
if err := tmp.Sync(); err != nil {
_ = tmp.Close()
return fmt.Errorf("notes: sync temp: %w", err)
}
if err := tmp.Close(); err != nil {
return fmt.Errorf("notes: close temp: %w", err)
}
// CreateTemp makes 0600; every other writer of this tree uses 0644 and
// other uids read it.
if err := os.Chmod(tmpName, 0o644); err != nil {
return fmt.Errorf("notes: chmod temp: %w", err)
}
if err := os.Rename(tmpName, abs); err != nil {
return fmt.Errorf("notes: rename: %w", err)
}
return fsyncDir(dir)
}
func fsyncDir(dir string) error {
d, err := os.Open(dir)
if err != nil {
return fmt.Errorf("notes: open dir: %w", err)
}
defer func() { _ = d.Close() }()
if err := d.Sync(); err != nil {
return fmt.Errorf("notes: fsync dir: %w", err)
}
return nil
}
+256
View File
@@ -0,0 +1,256 @@
package notes
import (
"os"
"path/filepath"
"strings"
"sync"
"testing"
)
func seed(t *testing.T, dir, rel, content string) string {
t.Helper()
abs := filepath.Join(dir, rel)
if err := os.MkdirAll(filepath.Dir(abs), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(abs, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
return abs
}
func read(t *testing.T, abs string) string {
t.Helper()
b, err := os.ReadFile(abs)
if err != nil {
t.Fatal(err)
}
return string(b)
}
func TestRead_ReturnsVerbatimBytes(t *testing.T) {
dir := newBrain(t)
const body = "---\ntitle: 'x'\n---\n\nbody with double spaces\r\nand a CRLF line\nno trailing newline"
seed(t, dir, "knowledge/verbatim.md", body)
got, err := Read(dir, "knowledge/verbatim.md")
if err != nil {
t.Fatalf("Read: %v", err)
}
if string(got) != body {
t.Errorf("Read returned %q, want the file byte-for-byte", got)
}
}
func TestRead_RefusesNonUTF8RatherThanCorruptingIt(t *testing.T) {
// The response is marshalled into a JSON string, and encoding/json
// replaces invalid UTF-8 with U+FFFD. Returning it would mean every
// old_str the caller derives from that region can never match, and
// pasting it back would write the corruption to disk permanently.
dir := newBrain(t)
seed(t, dir, "knowledge/bad.md", "ok \xff\xfe broken\n")
if _, err := Read(dir, "knowledge/bad.md"); err == nil {
t.Fatal("Read accepted invalid UTF-8; it must refuse rather than silently substitute")
}
}
func TestEdit_ReplacesExactlyOnceAndLeavesEveryOtherByteAlone(t *testing.T) {
dir := newBrain(t)
const body = "---\ntitle: 'x'\n---\n\nalpha\nbeta\ngamma\n"
abs := seed(t, dir, "knowledge/n.md", body)
res, err := Edit(dir, "knowledge/n.md", "beta", "BETA", ScopeNotes)
if err != nil {
t.Fatalf("Edit: %v", err)
}
want := strings.Replace(body, "beta", "BETA", 1)
if got := read(t, abs); got != want {
t.Errorf("file = %q, want %q", got, want)
}
if res.ContentHash == "" {
t.Error("result should carry a content hash for read-after-write confirmation")
}
}
func TestEdit_RefusesAmbiguousAndAbsentMatchesWithoutWriting(t *testing.T) {
dir := newBrain(t)
const body = "alpha\nalpha\n"
abs := seed(t, dir, "knowledge/n.md", body)
cases := []struct{ name, old, want string }{
{"two matches", "alpha", "2"},
{"no match", "delta", "0"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
_, err := Edit(dir, "knowledge/n.md", tc.old, "x", ScopeNotes)
if err == nil {
t.Fatal("want a loud refusal")
}
if !strings.Contains(err.Error(), tc.want) {
t.Errorf("error must state the match count, got %v", err)
}
if got := read(t, abs); got != body {
t.Errorf("file changed on a refused edit: %q", got)
}
})
}
}
func TestEdit_CountsOverlappingMatches(t *testing.T) {
// bytes.Count counts NON-overlapping occurrences: "aa" in "aaa" is 1, so
// a Count-based uniqueness check calls an ambiguous edit unique.
dir := newBrain(t)
seed(t, dir, "knowledge/n.md", "aaa\n")
if _, err := Edit(dir, "knowledge/n.md", "aa", "b", ScopeNotes); err == nil {
t.Fatal("overlapping matches must be reported as ambiguous")
}
}
func TestEdit_RejectsDegenerateArguments(t *testing.T) {
dir := newBrain(t)
seed(t, dir, "knowledge/n.md", "alpha\n")
if _, err := Edit(dir, "knowledge/n.md", "", "x", ScopeNotes); err == nil {
t.Error("empty old_str must be rejected")
}
if _, err := Edit(dir, "knowledge/n.md", "alpha", "alpha", ScopeNotes); err == nil {
t.Error("a no-op edit must be rejected rather than burning a sync cycle")
}
}
func TestEdit_DeletionIsLegal(t *testing.T) {
dir := newBrain(t)
abs := seed(t, dir, "knowledge/n.md", "keep\ndrop\n")
if _, err := Edit(dir, "knowledge/n.md", "drop\n", "", ScopeNotes); err != nil {
t.Fatalf("Edit: %v", err)
}
if got := read(t, abs); got != "keep\n" {
t.Errorf("file = %q, want %q", got, "keep\n")
}
}
func TestEdit_ReportsWhenOnlyLineEndingsDiffer(t *testing.T) {
// The likeliest real failure: the caller's old_str lost its \r. Never
// normalise silently — that breaks byte-identity — but say so, because an
// opaque "no match" is unfixable from the caller's side.
dir := newBrain(t)
seed(t, dir, "knowledge/n.md", "alpha\r\nbeta\r\n")
_, err := Edit(dir, "knowledge/n.md", "alpha\nbeta", "x", ScopeNotes)
if err == nil {
t.Fatal("want a refusal")
}
if !strings.Contains(err.Error(), "line ending") {
t.Errorf("error should point at CRLF, got %v", err)
}
}
func TestEdit_RefusesWhileGitIsMidOperation(t *testing.T) {
// brain-sync runs `git merge -X ours origin/main`, and aborts on conflict
// with a hard reset. An edit landing inside that window is either erased
// or committed as a wrongly-resolved conflict, and the caller was told it
// succeeded.
dir := newBrain(t)
seed(t, dir, "knowledge/n.md", "alpha\n")
for _, marker := range []string{"MERGE_HEAD", "index.lock", "REBASE_HEAD"} {
t.Run(marker, func(t *testing.T) {
p := filepath.Join(dir, ".git", marker)
if err := os.WriteFile(p, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
defer func() { _ = os.Remove(p) }()
if _, err := Edit(dir, "knowledge/n.md", "alpha", "beta", ScopeNotes); err == nil {
t.Errorf("edit accepted while %s exists", marker)
}
})
}
}
func TestEdit_RefusesAFileHoldingConflictMarkers(t *testing.T) {
dir := newBrain(t)
seed(t, dir, "knowledge/n.md", "<<<<<<< HEAD\nours\n=======\ntheirs\n>>>>>>> origin/main\n")
if _, err := Edit(dir, "knowledge/n.md", "ours", "x", ScopeNotes); err == nil {
t.Fatal("editing one side of an unresolved conflict must be refused")
}
}
func TestEdit_ConcurrentEditsBothApply(t *testing.T) {
// Read-modify-write with no lock loses one update AND reports success for
// both. old_str uniqueness does not protect against it: uniqueness is
// evaluated against the stale read.
dir := newBrain(t)
abs := seed(t, dir, "knowledge/n.md", "alpha\nbeta\n")
var wg sync.WaitGroup
errs := make([]error, 2)
for i, pair := range [][2]string{{"alpha", "ALPHA"}, {"beta", "BETA"}} {
wg.Add(1)
go func(i int, old, new string) {
defer wg.Done()
_, errs[i] = Edit(dir, "knowledge/n.md", old, new, ScopeNotes)
}(i, pair[0], pair[1])
}
wg.Wait()
for i, err := range errs {
if err != nil {
t.Fatalf("edit %d failed: %v", i, err)
}
}
if got := read(t, abs); got != "ALPHA\nBETA\n" {
t.Errorf("file = %q, want both edits applied", got)
}
}
func TestEdit_LeavesNoTemporaryFileBehind(t *testing.T) {
dir := newBrain(t)
seed(t, dir, "knowledge/n.md", "alpha\n")
if _, err := Edit(dir, "knowledge/n.md", "alpha", "beta", ScopeNotes); err != nil {
t.Fatal(err)
}
entries, err := os.ReadDir(filepath.Join(dir, "knowledge"))
if err != nil {
t.Fatal(err)
}
for _, e := range entries {
if e.Name() != "note.md" && e.Name() != "n.md" {
t.Errorf("stray file left in the tree: %q (git add -A would commit it)", e.Name())
}
}
}
func TestEdit_PreservesReadableMode(t *testing.T) {
// Other uids write this tree (brain-fix, brain-enrich). os.CreateTemp
// yields 0600 and rename preserves it, which would break them silently.
dir := newBrain(t)
abs := seed(t, dir, "knowledge/n.md", "alpha\n")
if _, err := Edit(dir, "knowledge/n.md", "alpha", "beta", ScopeNotes); err != nil {
t.Fatal(err)
}
fi, err := os.Stat(abs)
if err != nil {
t.Fatal(err)
}
if fi.Mode().Perm() != 0o644 {
t.Errorf("mode = %v, want 0644", fi.Mode().Perm())
}
}
func TestEdit_RefusesNonUTF8Replacement(t *testing.T) {
dir := newBrain(t)
seed(t, dir, "knowledge/n.md", "alpha\n")
if _, err := Edit(dir, "knowledge/n.md", "alpha", "bad \xff", ScopeNotes); err == nil {
t.Fatal("new_str with invalid UTF-8 must be refused, not written")
}
}
+201
View File
@@ -0,0 +1,201 @@
// Package notes provides containment-checked read and surgical edit of brain
// notes on the live tree that brain-sync commits from.
//
// Everything here is defensive for one reason: brain content is ingested from
// the outside world, that content reaches a model's context via brain_query /
// brain_context, and these primitives are callable by that model. A path bug
// is therefore not a path bug — it is an outside author choosing a file.
package notes
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
)
// Scope is which part of the tree a caller is allowed to touch.
type Scope int
const (
// ScopeNotes is the model-facing scope: markdown under knowledge/ and
// wiki/ only.
ScopeNotes Scope = iota
// ScopeRoot admits the named governance files and NOTHING else. It exists so
// there is an MCP path to CLAUDE.md at all — the absence of one is what
// pushed a session to edit via the gitea REST API on 2026-06-16, which
// never reached the live tree and wedged brain-sync for hours. It is NOT
// reachable from the model-facing toolset; see tools_notes.go.
ScopeRoot
)
// rootFiles is an exact-name allowlist, deliberately not a "root *.md" glob.
//
// Two reasons. log.md is gitignored, so an edit to it applies to the live tree
// and never reaches gitea — the exact shape of brain#2, admitted by a glob. And
// a glob auto-admits whatever governance file appears next (AGENTS.md, a
// bootstrap doc) with nobody reviewing that decision.
var rootFiles = map[string]bool{"CLAUDE.md": true}
// noteDirs are the two trees that hold notes.
var noteDirs = []string{"knowledge/", "wiki/"}
// deniedPrefixes are refused in every scope, independent of the allowlist.
//
// A static backstop rather than a consequence of the allowlist being right:
// .git/hooks/post-commit is executed by brain-sync inside a pod holding the
// Gitea push credentials, and archive/ + sessions/ hold verbatim session
// transcripts that BM25 never indexes and so nobody thinks of as reachable.
var deniedPrefixes = []string{".git/", "archive/", "sessions/", "raw/", "training-data/", ".obsidian/"}
// Errors are sentinels so callers can distinguish a refusal from an I/O fault.
var (
ErrOutsideBrain = errors.New("notes: path escapes the brain dir")
ErrNotAllowed = errors.New("notes: path is not editable through this tool")
ErrNotSyncSource = errors.New("notes: brain dir is not the sync source")
)
// Target is a resolved, contained path.
type Target struct {
Rel string // brain-relative, cleaned
Abs string // absolute, symlink-checked
}
// Resolve canonicalises path, then checks it against the scope's allowlist,
// then re-checks containment after symlink evaluation.
//
// Order matters and is the point: a prefix test on the raw argument accepts
// "knowledge/../.git/hooks/post-commit", because Clean only collapses it
// afterwards.
func Resolve(brainDir, path string, scope Scope) (Target, error) {
// Note: the sync-source assertion lives on the WRITE path (Edit), not
// here. brain#2 was an edit landing where the sync could not commit it; a
// read from such a tree is merely a read.
// 1. Canonicalise. Rooting at "/" makes Clean collapse every ".." that
// would otherwise escape, and ToSlash normalises separators first.
clean := strings.TrimPrefix(filepath.Clean("/"+filepath.ToSlash(path)), "/")
if clean == "" || clean == "." {
return Target{}, fmt.Errorf("%w: empty path", ErrNotAllowed)
}
// 2. Static denials, before any allowlist reasoning.
for _, d := range deniedPrefixes {
if strings.HasPrefix(clean+"/", d) {
return Target{}, fmt.Errorf("%w: %q is not note content", ErrNotAllowed, clean)
}
}
if strings.HasPrefix(filepath.Base(clean), ".") {
return Target{}, fmt.Errorf("%w: dotfiles are not editable", ErrNotAllowed)
}
// 3. Scope allowlist.
if err := allow(clean, scope); err != nil {
return Target{}, err
}
// 4. Containment, lexically.
abs := filepath.Join(brainDir, filepath.FromSlash(clean))
if !within(brainDir, abs) {
return Target{}, fmt.Errorf("%w: %q", ErrOutsideBrain, path)
}
// 5. Containment again, after resolving symlinks. The tree is Syncthing
// managed, so a link can appear without anyone adding one on purpose;
// a symlinked note or directory would otherwise read and write outside
// the brain entirely.
if err := assertNoSymlinkEscape(brainDir, abs); err != nil {
return Target{}, err
}
return Target{Rel: clean, Abs: abs}, nil
}
// allow enforces the scope's allowlist. The two scopes are DISJOINT, not
// nested: the privileged root scope reaches governance files and nothing else,
// so the tool that carries the higher privilege carries the smaller reach.
func allow(clean string, scope Scope) error {
if scope == ScopeRoot {
if !rootFiles[clean] {
return fmt.Errorf("%w: %q is not a governance file", ErrNotAllowed, clean)
}
return nil
}
if !isNotePath(clean) {
return fmt.Errorf("%w: %q is outside knowledge/ and wiki/", ErrNotAllowed, clean)
}
return nil
}
func isNotePath(clean string) bool {
var inDir bool
for _, d := range noteDirs {
if strings.HasPrefix(clean, d) {
inDir = true
break
}
}
if !inDir || filepath.Ext(clean) != ".md" {
return false
}
// _index.md is generated per wing, and brain-sync's conflict resolver
// deliberately resolves it in origin's favour — an edit here is reverted
// by design, so accepting one would be a lie.
return filepath.Base(clean) != "_index.md"
}
func within(root, abs string) bool {
rel, err := filepath.Rel(root, abs)
if err != nil {
return false
}
return rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
}
// assertNoSymlinkEscape resolves the deepest existing ancestor of abs and
// requires it to still be inside brainDir. The file itself need not exist
// (a create is legal); its directory chain must be real and contained.
func assertNoSymlinkEscape(brainDir, abs string) error {
if fi, err := os.Lstat(abs); err == nil && fi.Mode()&os.ModeSymlink != 0 {
return fmt.Errorf("%w: %q is a symlink", ErrNotAllowed, abs)
}
realRoot, err := filepath.EvalSymlinks(brainDir)
if err != nil {
return fmt.Errorf("notes: resolve brain dir: %w", err)
}
dir := filepath.Dir(abs)
for {
resolved, err := filepath.EvalSymlinks(dir)
if err == nil {
if !within(realRoot, resolved) {
return fmt.Errorf("%w: %q resolves outside the brain dir", ErrOutsideBrain, dir)
}
return nil
}
if !os.IsNotExist(err) {
return fmt.Errorf("notes: resolve %q: %w", dir, err)
}
parent := filepath.Dir(dir)
if parent == dir {
return fmt.Errorf("%w: no existing ancestor for %q", ErrOutsideBrain, abs)
}
dir = parent
}
}
// assertSyncSource refuses a brain dir that is not a git working tree.
//
// brain#2 was an edit landing on a directory the sync does not commit from.
// That cannot be prevented by review — a wrong INGEST_BRAIN_DIR in a future
// manifest reintroduces it while every unit test still passes — so it is
// asserted at runtime, the same check brain-sync itself makes before running.
func assertSyncSource(brainDir string) error {
if fi, err := os.Stat(filepath.Join(brainDir, ".git")); err != nil || !fi.IsDir() {
return fmt.Errorf("%w: %q has no .git, so an edit there would never be committed",
ErrNotSyncSource, brainDir)
}
return nil
}
+146
View File
@@ -0,0 +1,146 @@
package notes
import (
"os"
"path/filepath"
"strings"
"testing"
)
// newBrain lays out a tree shaped like the live one: a git dir, note dirs,
// and the non-note areas that must never be reachable.
func newBrain(t *testing.T) string {
t.Helper()
dir := t.TempDir()
for _, d := range []string{
".git/hooks", "knowledge", "wiki/homelab/facts", "archive/claude-sessions/koala",
"sessions", "raw", ".obsidian",
} {
if err := os.MkdirAll(filepath.Join(dir, d), 0o755); err != nil {
t.Fatal(err)
}
}
write := func(p, s string) {
t.Helper()
if err := os.WriteFile(filepath.Join(dir, p), []byte(s), 0o644); err != nil {
t.Fatal(err)
}
}
write("CLAUDE.md", "# instructions\n")
write("log.md", "ignored scratch\n")
write("knowledge/note.md", "# note\n")
write("wiki/homelab/facts/f.md", "# fact\n")
write("wiki/homelab/_index.md", "# index\n")
write("archive/claude-sessions/koala/session-1.md", "verbatim transcript\n")
write("sessions/s.jsonl", "{}\n")
write(".git/hooks/post-commit", "#!/bin/sh\n")
return dir
}
func TestResolve_AcceptsNotePaths(t *testing.T) {
dir := newBrain(t)
for _, p := range []string{"knowledge/note.md", "wiki/homelab/facts/f.md"} {
got, err := Resolve(dir, p, ScopeNotes)
if err != nil {
t.Errorf("Resolve(%q): %v", p, err)
continue
}
if !strings.HasPrefix(got.Abs, dir) {
t.Errorf("Resolve(%q).Abs = %q, want inside %q", p, got.Abs, dir)
}
}
}
func TestResolve_RefusesEscapesAndNonNoteAreas(t *testing.T) {
dir := newBrain(t)
// Canonicalisation must happen BEFORE the allowlist check. A prefix test
// on the raw argument accepts every one of these: "knowledge/..%2f" style
// inputs collapse to .git, and .git/hooks/post-commit is executed by
// brain-sync inside a pod holding the Gitea push credentials.
refuse := []string{
"knowledge/../.git/hooks/post-commit",
"wiki/../.git/config",
"./knowledge/../.git/config",
"knowledge//../.git/config",
"../../etc/passwd",
"/etc/passwd",
".git/config",
"archive/claude-sessions/koala/session-1.md", // verbatim transcripts
"sessions/s.jsonl",
"raw/x.md",
".obsidian/workspace.json",
"log.md", // gitignored: an edit here would never sync (brain#2)
"wiki/homelab/_index.md", // generated; brain-sync resolves it in origin's favour
"knowledge/note.txt", // not markdown
"CLAUDE.md", // root file — not reachable in the notes scope
}
for _, p := range refuse {
if _, err := Resolve(dir, p, ScopeNotes); err == nil {
t.Errorf("Resolve(%q) = nil error, want refusal", p)
}
}
}
func TestResolve_RootScopeAdmitsOnlyNamedFiles(t *testing.T) {
dir := newBrain(t)
if _, err := Resolve(dir, "CLAUDE.md", ScopeRoot); err != nil {
t.Errorf("Resolve(CLAUDE.md, ScopeRoot): %v", err)
}
// log.md is the reason this is an exact-name list and not "root *.md":
// it is gitignored, so an edit would apply locally and never reach gitea.
for _, p := range []string{"log.md", "AGENTS.md", "knowledge/note.md", ".git/config"} {
if _, err := Resolve(dir, p, ScopeRoot); err == nil {
t.Errorf("Resolve(%q, ScopeRoot) = nil error, want refusal", p)
}
}
}
func TestResolve_RefusesSymlinkedTargets(t *testing.T) {
dir := newBrain(t)
outside := filepath.Join(t.TempDir(), "secret.md")
if err := os.WriteFile(outside, []byte("secret\n"), 0o644); err != nil {
t.Fatal(err)
}
// The tree is Syncthing-managed, so a symlink can appear without anyone
// adding one deliberately. Containment must survive it.
if err := os.Symlink(outside, filepath.Join(dir, "knowledge/link.md")); err != nil {
t.Skipf("symlinks unavailable: %v", err)
}
if _, err := Resolve(dir, "knowledge/link.md", ScopeNotes); err == nil {
t.Error("Resolve followed a symlink out of the brain dir")
}
if err := os.Symlink(filepath.Dir(outside), filepath.Join(dir, "wiki/escape")); err != nil {
t.Skipf("symlinks unavailable: %v", err)
}
if _, err := Resolve(dir, "wiki/escape/secret.md", ScopeNotes); err == nil {
t.Error("Resolve followed a symlinked directory out of the brain dir")
}
}
func TestResolve_RefusesWhenTheTreeIsNotTheSyncSource(t *testing.T) {
// brain#2 was "wrote to a directory the sync does not commit from". No
// code review prevents that recurring — a wrong INGEST_BRAIN_DIR in a
// future manifest reintroduces it and every unit test still passes. So
// assert the property at runtime, the way brain-sync itself does.
dir := t.TempDir()
if err := os.MkdirAll(filepath.Join(dir, "knowledge"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "knowledge/note.md"), []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
// Reads are fine anywhere; the guard belongs to writes.
if _, err := Resolve(dir, "knowledge/note.md", ScopeNotes); err != nil {
t.Fatalf("Resolve should not require .git for a read: %v", err)
}
_, err := Edit(dir, "knowledge/note.md", "x", "y", ScopeNotes)
if err == nil {
t.Fatal("Edit accepted a tree with no .git — the write would never be committed")
}
if !strings.Contains(err.Error(), "sync source") {
t.Errorf("error should name the cause, got %v", err)
}
}
+12
View File
@@ -76,6 +76,18 @@ func buildFrontmatter(rp RawPage, date string) string {
} }
fmt.Fprintf(&sb, "date_ingested: %s\n", date) fmt.Fprintf(&sb, "date_ingested: %s\n", date)
fmt.Fprintf(&sb, "last_updated: %s\n", date) fmt.Fprintf(&sb, "last_updated: %s\n", date)
if rp.SourceHash != "" {
fmt.Fprintf(&sb, "source_hash: %s\n", rp.SourceHash)
}
if rp.Source != "" {
fmt.Fprintf(&sb, "source: %s\n", yamlScalar(rp.Source))
}
if rp.Author != "" {
fmt.Fprintf(&sb, "author: %s\n", yamlScalar(rp.Author))
}
if rp.Published != "" {
fmt.Fprintf(&sb, "published: %s\n", yamlScalar(rp.Published))
}
case "concept": case "concept":
if rp.Domain != "" { if rp.Domain != "" {
fmt.Fprintf(&sb, "domain: %s\n", yamlScalar(rp.Domain)) fmt.Fprintf(&sb, "domain: %s\n", yamlScalar(rp.Domain))
+46
View File
@@ -154,6 +154,52 @@ func TestBuildPages_EntityNoSubtype(t *testing.T) {
assert.Contains(t, pages[0].Content, "title: 'Basecamp'") assert.Contains(t, pages[0].Content, "title: 'Basecamp'")
} }
func TestBuildPages_SourcePageCarriesSourceAuthorPublished(t *testing.T) {
raw := []RawPage{
{
Title: "Ornith",
Type: "source",
Subtype: "article",
Content: "## Summary\n\nAn agentic coding model.\n",
Source: "https://example.com/ornith",
Author: "Jane Doe",
Published: "2026-07-20",
},
}
pages, warnings := BuildPages(raw, "ornith", "2026-07-26")
require.Len(t, pages, 1)
assert.Empty(t, warnings)
p := pages[0]
assert.Contains(t, p.Content, "source: 'https://example.com/ornith'")
assert.Contains(t, p.Content, "author: 'Jane Doe'")
assert.Contains(t, p.Content, "published: '2026-07-20'")
}
func TestBuildPages_SourcePageOmitsSourceAuthorPublishedWhenEmpty(t *testing.T) {
raw := []RawPage{
{Title: "Shape Up", Type: "source", Subtype: "book", Content: "## Summary\n\nA book.\n"},
}
pages, _ := BuildPages(raw, "shape-up", "2026-04-23")
require.Len(t, pages, 1)
assert.NotContains(t, pages[0].Content, "source:")
assert.NotContains(t, pages[0].Content, "author:")
assert.NotContains(t, pages[0].Content, "published:")
}
func TestBuildPages_ConceptPageIgnoresSourceAuthorPublished(t *testing.T) {
// source/author/published are source-note-only metadata; a concept page
// shouldn't carry them even if somehow set on the RawPage.
raw := []RawPage{
{Title: "Betting", Type: "concept", Content: "## Definition\n\nFoo.\n", Source: "x", Author: "y", Published: "z"},
}
pages, _ := BuildPages(raw, "src", "2026-04-23")
require.Len(t, pages, 1)
assert.NotContains(t, pages[0].Content, "source:")
assert.NotContains(t, pages[0].Content, "author:")
assert.NotContains(t, pages[0].Content, "published:")
}
func TestBuildPages_EmptyTitleSkippedWithWarning(t *testing.T) { func TestBuildPages_EmptyTitleSkippedWithWarning(t *testing.T) {
raw := []RawPage{ raw := []RawPage{
{Title: "", Type: "concept", Content: "## Definition\n\nFoo.\n"}, {Title: "", Type: "concept", Content: "## Definition\n\nFoo.\n"},
+25 -5
View File
@@ -51,6 +51,21 @@ func buildTitleMap(pages []wiki.Page, inventory map[wiki.PageType][]wiki.Entry)
return m return m
} }
// pathStylePrefixes are known root prefixes the LLM extraction step
// sometimes bakes into a wikilink target instead of emitting a clean
// wing/hall/slug path (or bare title). Stripping them repairs the link
// in place — see hyperguild#87.
var pathStylePrefixes = []string{"wing:", "wiki/"}
func stripPathStylePrefix(displayName string) (string, bool) {
for _, prefix := range pathStylePrefixes {
if stripped, ok := strings.CutPrefix(displayName, prefix); ok {
return stripped, true
}
}
return displayName, false
}
func canonicalizeContent(content string, titleToSlug map[string]string) (string, []string) { func canonicalizeContent(content string, titleToSlug map[string]string) (string, []string) {
var warnings []string var warnings []string
result := plainLinkRE.ReplaceAllStringFunc(content, func(match string) string { result := plainLinkRE.ReplaceAllStringFunc(content, func(match string) string {
@@ -59,12 +74,17 @@ func canonicalizeContent(content string, titleToSlug map[string]string) (string,
return match return match
} }
displayName := sub[1] displayName := sub[1]
slug, ok := titleToSlug[strings.ToLower(displayName)]
if !ok { if slug, ok := titleToSlug[strings.ToLower(displayName)]; ok {
warnings = append(warnings, fmt.Sprintf("unknown wikilink: [[%s]]", displayName)) return "[[" + slug + "|" + displayName + "]]"
return match
} }
return "[[" + slug + "|" + displayName + "]]"
if stripped, hadPrefix := stripPathStylePrefix(displayName); hadPrefix {
return "[[" + stripped + "]]"
}
warnings = append(warnings, fmt.Sprintf("unknown wikilink: [[%s]]", displayName))
return match
}) })
return result, warnings return result, warnings
} }
+47
View File
@@ -102,6 +102,53 @@ func TestCanonicalizeLinks_CurrentBatchPagesResolved(t *testing.T) {
assert.Contains(t, got[0].Content, "[[betting|Betting]]") assert.Contains(t, got[0].Content, "[[betting|Betting]]")
} }
func TestCanonicalizeLinks_StripsWingColonPrefix(t *testing.T) {
pages := []wiki.Page{
{
Path: "wiki/homelab/failures/act-runner-host-mode-container-needs-node-and-libatomic.md",
Content: "---\ntitle: 'act_runner host-mode'\n---\n\nSee [[wing:homelab/failures/rootless-buildah-act-runner-run-containers-denied]].\n",
},
}
got, warnings := CanonicalizeLinks(pages, map[wiki.PageType][]wiki.Entry{})
require.Len(t, got, 1)
assert.Empty(t, warnings)
assert.Contains(t, got[0].Content, "[[homelab/failures/rootless-buildah-act-runner-run-containers-denied]]")
assert.NotContains(t, got[0].Content, "wing:")
}
func TestCanonicalizeLinks_StripsWikiSlashPrefix(t *testing.T) {
pages := []wiki.Page{
{
Path: "wiki/agentsquad/hypotheses/council-consolidation-standalone-deliberation-service.md",
Content: "---\ntitle: 'council consolidation'\n---\n\nSee [[wiki/agentsquad/decisions/autoresearch-council-sibling-pipe]].\n",
},
}
got, warnings := CanonicalizeLinks(pages, map[wiki.PageType][]wiki.Entry{})
require.Len(t, got, 1)
assert.Empty(t, warnings)
assert.Contains(t, got[0].Content, "[[agentsquad/decisions/autoresearch-council-sibling-pipe]]")
assert.NotContains(t, got[0].Content, "wiki/agentsquad/decisions/autoresearch-council-sibling-pipe]]\n\n") // no leftover wiki/ prefix
assert.NotContains(t, got[0].Content, "[[wiki/")
}
func TestCanonicalizeLinks_TitleLookupStillTakesPriorityOverPrefixStrip(t *testing.T) {
// A plain link that resolves via the title map must still use the
// normal slug|Display form, not fall through to prefix-strip repair.
pages := []wiki.Page{
{
Path: "wiki/sources/shape-up.md",
Content: "---\ntitle: 'Shape Up'\n---\n\nSee [[Betting]].\n",
},
}
inventory := map[wiki.PageType][]wiki.Entry{
wiki.PageTypeConcept: {{Slug: "betting", Title: "Betting"}},
}
got, warnings := CanonicalizeLinks(pages, inventory)
require.Len(t, got, 1)
assert.Empty(t, warnings)
assert.Contains(t, got[0].Content, "[[betting|Betting]]")
}
func TestCanonicalizeLinks_MultipleLinksInOnePage(t *testing.T) { func TestCanonicalizeLinks_MultipleLinksInOnePage(t *testing.T) {
pages := []wiki.Page{ pages := []wiki.Page{
{ {
+72
View File
@@ -15,6 +15,18 @@ type RawPage struct {
Subtype string `json:"subtype"` // entity: person|company|tool|model|framework|technology; source: article|pdf|book|video|note|project Subtype string `json:"subtype"` // entity: person|company|tool|model|framework|technology; source: article|pdf|book|video|note|project
Domain string `json:"domain"` Domain string `json:"domain"`
Content string `json:"content"` // Markdown body only — no frontmatter Content string `json:"content"` // Markdown body only — no frontmatter
// Source, Author, Published are deterministic passthrough from the raw
// ingested content's own frontmatter (see parseContentFrontmatter) — never
// set by the LLM. json:"-" keeps them immune to same-named keys the LLM
// might emit. Only meaningful for Type == "source".
// SourceHash is sha256 of the ingested BODY (frontmatter excluded), stamped
// so the next ingest of the same source can tell "unchanged" from "edited"
// without re-running extraction (#105).
SourceHash string `json:"-"`
Source string `json:"-"`
Author string `json:"-"`
Published string `json:"-"`
} }
// ParseRawPages parses LLM output as a JSON array of RawPage objects. // ParseRawPages parses LLM output as a JSON array of RawPage objects.
@@ -98,6 +110,66 @@ func repairJSON(s string) string {
return b.String() return b.String()
} }
// sourceMeta is source/author/published pulled from the raw ingested
// content's own frontmatter — deterministic passthrough, never LLM output.
type sourceMeta struct {
Source string
Author string
Published string
// BodyHash is sha256 of the content with any leading frontmatter removed.
// Body-only on purpose: a re-crawl that stamps a new fetch date has not
// changed the source, and treating that as drift would re-extract the
// whole corpus every time a crawler ran (#105).
BodyHash string
}
// parseContentFrontmatter extracts source/author/published from a leading
// "---\n...\n---" YAML block in raw ingested content. Only these three flat
// scalar keys are recognised; anything else in the block is ignored. Returns
// a zero-value sourceMeta if content has no frontmatter block.
func parseContentFrontmatter(content string) sourceMeta {
var meta sourceMeta
if !strings.HasPrefix(content, "---\n") && !strings.HasPrefix(content, "---\r\n") {
return meta
}
lines := strings.Split(content, "\n")
for _, line := range lines[1:] {
if strings.TrimSpace(line) == "---" {
break
}
key, val, ok := strings.Cut(line, ":")
if !ok {
continue
}
key = strings.TrimSpace(key)
val = strings.Trim(strings.TrimSpace(val), `"'`)
switch key {
case "source":
meta.Source = val
case "author":
meta.Author = val
case "published":
meta.Published = val
}
}
return meta
}
// applySourceMeta deterministically overwrites Source/Author/Published on
// every "source"-type page with meta — the LLM never controls these fields.
func applySourceMeta(pages []RawPage, meta sourceMeta) {
for i := range pages {
if pages[i].Type != "source" {
continue
}
pages[i].SourceHash = meta.BodyHash
pages[i].Source = meta.Source
pages[i].Author = meta.Author
pages[i].Published = meta.Published
}
}
func stripFences(s string) string { func stripFences(s string) string {
for _, prefix := range []string{"```json\n", "```json\r\n", "```\n", "```\r\n"} { for _, prefix := range []string{"```json\n", "```json\r\n", "```\n", "```\r\n"} {
if strings.HasPrefix(s, prefix) { if strings.HasPrefix(s, prefix) {
+120 -2
View File
@@ -3,6 +3,8 @@ package pipeline
import ( import (
"context" "context"
"crypto/sha256"
"encoding/hex"
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
@@ -26,6 +28,11 @@ type Config struct {
type Result struct { type Result struct {
Pages []string // relative paths written (or would-be written in dry-run) Pages []string // relative paths written (or would-be written in dry-run)
Warnings []string Warnings []string
// Skipped reports that the source was byte-identical to the last ingest,
// so no extraction ran and nothing was written. Reported rather than
// silent: a run that does nothing must say so, or "the pipeline is fine"
// and "the pipeline stopped working" look the same (#105, #107).
Skipped bool
} }
// Run ingests content and writes structured wiki pages to brainDir/wiki/. // Run ingests content and writes structured wiki pages to brainDir/wiki/.
@@ -43,13 +50,32 @@ func Run(ctx context.Context, cfg Config, brainDir, content, source string, dryR
sourceSlug := wiki.Slug(source) sourceSlug := wiki.Slug(source)
date := time.Now().UTC().Format("2006-01-02") date := time.Now().UTC().Format("2006-01-02")
// Drift check BEFORE any extraction: an unchanged source costs a full LLM
// pass over every chunk to produce a result that merges to nothing (#105).
// The merge is already idempotent (#103), so this is cost and signal, not
// correctness — which is why it is safe for it to be an early return.
bodyHash := hashBody(content)
if !dryRun && bodyHash != "" && bodyHash == storedSourceHash(brainDir, sourceSlug) {
return Result{Skipped: true, Warnings: []string{
fmt.Sprintf("source %q unchanged since last ingest (hash %s) — extraction skipped", source, bodyHash[:12]),
}}, nil
}
// The source's own page path is deterministic (sourceSlug, computed above)
// even before extraction runs, unlike a concept/entity page's path, which
// only exists once the model has produced a title. So page-aware
// extraction (#106) is scoped to the source page: it's the one page every
// chunk's prompt can be given in advance.
existingPage := readSourcePage(brainDir, sourceSlug)
chunks := Chunk(content, cfg.ChunkSize) chunks := Chunk(content, cfg.ChunkSize)
var allRaw []RawPage var allRaw []RawPage
var allWarnings []string var allWarnings []string
for _, chunk := range chunks { for _, chunk := range chunks {
userPrompt := BuildPrompt(schema, source, chunk, inventory) userPrompt := BuildPrompt(schema, source, chunk, inventory, existingPage)
output, err := cfg.Complete(ctx, systemPrompt, userPrompt) output, err := cfg.Complete(ctx, systemPrompt, userPrompt)
if err != nil { if err != nil {
return Result{}, fmt.Errorf("LLM call: %w", err) return Result{}, fmt.Errorf("LLM call: %w", err)
@@ -59,6 +85,10 @@ func Run(ctx context.Context, cfg Config, brainDir, content, source string, dryR
allWarnings = append(allWarnings, warnings...) allWarnings = append(allWarnings, warnings...)
} }
meta := parseContentFrontmatter(content)
meta.BodyHash = bodyHash
applySourceMeta(allRaw, meta)
return buildAndWrite(allRaw, sourceSlug, date, brainDir, source, inventory, allWarnings, dryRun) return buildAndWrite(allRaw, sourceSlug, date, brainDir, source, inventory, allWarnings, dryRun)
} }
@@ -94,7 +124,19 @@ func buildAndWrite(rawPages []RawPage, sourceSlug, date, brainDir, source string
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil { if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
return Result{}, fmt.Errorf("mkdir for %s: %w", page.Path, err) return Result{}, fmt.Errorf("mkdir for %s: %w", page.Path, err)
} }
if err := os.WriteFile(dest, []byte(page.Content), 0o644); err != nil { content, conflicts, err := reviseOrCreate(dest, page)
if err != nil {
return Result{}, err
}
for _, heading := range conflicts {
// Reported, not resolved. The on-disk version stands; whether
// the disagreement is a genuine contradiction is the
// Judge-gated enrich pass's call, not the write path's.
warnings = append(warnings, fmt.Sprintf(
"%s: source now disagrees on section %q — on-disk version kept",
page.Path, heading))
}
if err := os.WriteFile(dest, []byte(content), 0o644); err != nil {
return Result{}, fmt.Errorf("write %s: %w", page.Path, err) return Result{}, fmt.Errorf("write %s: %w", page.Path, err)
} }
} }
@@ -113,6 +155,82 @@ func buildAndWrite(rawPages []RawPage, sourceSlug, date, brainDir, source string
return Result{Pages: written, Warnings: warnings}, nil return Result{Pages: written, Warnings: warnings}, nil
} }
// hashBody returns sha256 of content with any leading frontmatter block
// removed, or "" for empty content.
//
// Body-only on purpose: a re-crawl that stamps a new fetch date has not changed
// the source, and treating that as drift would re-extract the corpus every time
// a crawler ran (#105).
func hashBody(content string) string {
body := content
if strings.HasPrefix(body, "---\n") {
if _, rest, found := strings.Cut(body[4:], "\n---"); found {
body = strings.TrimPrefix(rest, "\n")
}
}
if strings.TrimSpace(body) == "" {
return ""
}
sum := sha256.Sum256([]byte(body))
return hex.EncodeToString(sum[:])
}
// readSourcePage returns the full on-disk content of the source page at
// wiki/sources/<sourceSlug>.md, or "" when it doesn't exist yet.
func readSourcePage(brainDir, sourceSlug string) string {
raw, err := os.ReadFile(filepath.Join(brainDir, "wiki", "sources", sourceSlug+".md"))
if err != nil {
return ""
}
return string(raw)
}
// storedSourceHash reads source_hash from the source page a previous ingest
// wrote, or "" when there is no such page or no such field.
//
// Absence always means "extract". That is the fail-safe direction: a missed
// skip costs one extraction, while a wrong skip loses an update silently — and
// silence is the failure mode this repo keeps paying for.
func storedSourceHash(brainDir, sourceSlug string) string {
for _, line := range strings.Split(readSourcePage(brainDir, sourceSlug), "\n") {
if key, value, found := strings.Cut(line, ":"); found && strings.TrimSpace(key) == "source_hash" {
return strings.TrimSpace(value)
}
}
return ""
}
// reviseOrCreate returns the bytes to write for one extracted page: merged into
// whatever is already on disk, or the page as-is when the path is new.
//
// This is the compile half of compile-on-ingest. Before it, the write was an
// unconditional os.WriteFile, so re-ingesting a source replaced its page
// wholesale and discarded everything accumulated since — including human edits
// (hyperguild#43: "re-ingest overwrites wholesale").
//
// The merge is deliberately asymmetric in the existing page's favour:
// wiki.Merge keeps the on-disk frontmatter and the on-disk version of any
// section both sides carry, adds sections only the extraction produced, and
// unions bullet lists. So a freshly extracted page can add to a note but never
// silently rewrite what a human put there — which is what makes it safe to run
// this on every ingest rather than behind a review gate.
//
// Known limitation: because the on-disk frontmatter wins, `last_updated` keeps
// its first-ingest date on a revised page. Left deliberately — the alternative
// is this function editing frontmatter it does not own, and no lint reads that
// field today.
func reviseOrCreate(dest string, page wiki.Page) (string, []string, error) {
existing, err := os.ReadFile(dest)
switch {
case os.IsNotExist(err):
return page.Content, nil, nil
case err != nil:
return "", nil, fmt.Errorf("read existing %s: %w", page.Path, err)
}
merged, conflicts := wiki.MergeReport(wiki.Page{Path: page.Path, Content: string(existing)}, page)
return merged.Content, conflicts, nil
}
// mergeAll deduplicates pages by path, merging content from later occurrences. // mergeAll deduplicates pages by path, merging content from later occurrences.
func mergeAll(pages []wiki.Page) []wiki.Page { func mergeAll(pages []wiki.Page) []wiki.Page {
order := make([]string, 0, len(pages)) order := make([]string, 0, len(pages))
@@ -8,6 +8,7 @@ import (
"net/http/httptest" "net/http/httptest"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"testing" "testing"
"time" "time"
@@ -130,6 +131,40 @@ func TestRun_MergesDuplicatePaths(t *testing.T) {
assert.Contains(t, string(content), "[[Baz]]") assert.Contains(t, string(content), "[[Baz]]")
} }
func TestRun_ThreadsSourceAuthorPublishedFromContentFrontmatter(t *testing.T) {
brainDir := t.TempDir()
for _, sub := range []string{"wiki/concepts", "wiki/entities", "wiki/sources"} {
require.NoError(t, os.MkdirAll(filepath.Join(brainDir, sub), 0o755))
}
llmResponse := mustJSON([]RawPage{{
Title: "Ornith",
Type: "source",
Subtype: "article",
Content: "## Summary\n\nAn agentic coding model.\n",
}})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]any{
"choices": []map[string]any{{"message": map[string]any{"content": llmResponse}}},
})
}))
defer srv.Close()
cfg := Config{Complete: llm.New(srv.URL, "", "m", 30*time.Second).Complete}
rawContent := "---\nsource: https://example.com/ornith\nauthor: Jane Doe\npublished: 2026-07-20\n---\n\nAn agentic coding model that runs on your laptop.\n"
result, err := Run(context.Background(), cfg, brainDir, rawContent, "ornith", false)
require.NoError(t, err)
require.Len(t, result.Pages, 1)
content, err := os.ReadFile(filepath.Join(brainDir, "wiki", "sources", "ornith.md"))
require.NoError(t, err)
assert.Contains(t, string(content), "source: 'https://example.com/ornith'")
assert.Contains(t, string(content), "author: 'Jane Doe'")
assert.Contains(t, string(content), "published: '2026-07-20'")
}
func mustJSON(v any) string { func mustJSON(v any) string {
b, err := json.Marshal(v) b, err := json.Marshal(v)
if err != nil { if err != nil {
@@ -137,3 +172,254 @@ func mustJSON(v any) string {
} }
return string(b) return string(b)
} }
// --- B1: compile-on-ingest — revise the existing page, never clobber it -----
func TestRunRaw_MergesIntoAnExistingPageInsteadOfOverwritingIt(t *testing.T) {
// Before this, buildAndWrite did an unconditional os.WriteFile: re-ingesting
// a source replaced its page wholesale, discarding anything accumulated
// since — including human edits. hyperguild#43 recorded the symptom as
// "re-ingest overwrites wholesale".
dir := t.TempDir()
page := filepath.Join(dir, "wiki", "sources", "shape-up.md")
require.NoError(t, os.MkdirAll(filepath.Dir(page), 0o755))
require.NoError(t, os.WriteFile(page, []byte(`---
title: 'Shape Up'
---
## Summary
A book about shaping product work.
## My Take
Read this before the next planning cycle.
`), 0o644))
_, err := RunRaw(dir, "shape-up", []RawPage{{
Title: "Shape Up", Type: "source", Subtype: "book", Domain: "product-strategy",
Content: "## Summary\n\nA book about shaping product work.\n\n## Key Claims\n\n- Appetite beats estimation.\n",
}}, false)
require.NoError(t, err)
got, err := os.ReadFile(page)
require.NoError(t, err)
s := string(got)
assert.Contains(t, s, "## My Take", "a section the extraction never saw must survive the merge")
assert.Contains(t, s, "Read this before the next planning cycle.")
assert.Contains(t, s, "Appetite beats estimation.", "newly extracted material must still land")
}
func TestRunRaw_ReIngestingUnchangedContentIsByteIdentical(t *testing.T) {
// Compile-on-ingest runs on every ingest, so "nothing changed" must produce
// no diff at all. Otherwise every re-ingest dirties the tree, brain-sync
// commits it, and the git history fills with noise that hides real edits.
dir := t.TempDir()
raw := []RawPage{{
Title: "Shape Up", Type: "source", Subtype: "book", Domain: "product-strategy",
Content: "## Summary\n\nA book about shaping product work.\n\n## Open Questions\n\n- Does appetite scale?\n",
}}
_, err := RunRaw(dir, "shape-up", raw, false)
require.NoError(t, err)
first, err := os.ReadFile(filepath.Join(dir, "wiki", "sources", "shape-up.md"))
require.NoError(t, err)
_, err = RunRaw(dir, "shape-up", raw, false)
require.NoError(t, err)
second, err := os.ReadFile(filepath.Join(dir, "wiki", "sources", "shape-up.md"))
require.NoError(t, err)
assert.Equal(t, string(first), string(second),
"re-ingesting unchanged content must leave the page byte-identical")
}
// --- #105: source drift — an unchanged re-ingest must not re-extract --------
func TestRun_SkipsExtractionWhenTheSourceIsUnchanged(t *testing.T) {
// #103 made a re-ingest harmless (byte-identical merge). It is still not
// free: the full LLM extraction runs over every chunk to produce a result
// that merges to nothing. This is the cost half.
dir := t.TempDir()
var calls int
cfg := Config{Complete: func(_ context.Context, _, _ string) (string, error) {
calls++
return `[{"title":"Shape Up","type":"source","subtype":"book","domain":"product","content":"## Summary\n\nA book.\n"}]`, nil
}}
content := "---\nsource: https://example.com/shape-up\n---\n\nThe body of the article.\n"
first, err := Run(context.Background(), cfg, dir, content, "shape-up", false)
require.NoError(t, err)
require.Equal(t, 1, calls, "first ingest must extract")
assert.False(t, first.Skipped)
second, err := Run(context.Background(), cfg, dir, content, "shape-up", false)
require.NoError(t, err)
assert.Equal(t, 1, calls, "unchanged content must not be extracted again")
assert.True(t, second.Skipped, "the skip must be reported, not silent")
}
func TestRun_ReExtractsWhenTheSourceBodyChanged(t *testing.T) {
dir := t.TempDir()
var calls int
cfg := Config{Complete: func(_ context.Context, _, _ string) (string, error) {
calls++
return `[{"title":"Shape Up","type":"source","subtype":"book","domain":"product","content":"## Summary\n\nA book.\n"}]`, nil
}}
_, err := Run(context.Background(), cfg, dir, "---\nsource: x\n---\n\nversion one\n", "shape-up", false)
require.NoError(t, err)
_, err = Run(context.Background(), cfg, dir, "---\nsource: x\n---\n\nversion two — the source was edited\n", "shape-up", false)
require.NoError(t, err)
assert.Equal(t, 2, calls, "changed content must be re-extracted")
}
// --- #106: page-aware extraction — the model sees the page it is revising --
func TestRun_ExistingSourcePageIsIncludedInTheExtractionPrompt(t *testing.T) {
// #103 made the merge asymmetric (on-disk wins); #106 is the other half —
// the extraction itself gets to see what's already there instead of
// producing a page blind and letting the merge reconcile it afterwards.
// This only proves the existing page reaches the prompt; the byte-identical
// guarantee for an echoed-back revision is a separate test below.
dir := t.TempDir()
for _, sub := range []string{"wiki/concepts", "wiki/entities", "wiki/sources"} {
require.NoError(t, os.MkdirAll(filepath.Join(dir, sub), 0o755))
}
seeded := "---\ntitle: 'Shape Up'\n---\n\n## Summary\n\nA book about shaping product work.\n\n## Key Claims\n\n- Appetite beats estimation.\n"
page := filepath.Join(dir, "wiki", "sources", "shape-up.md")
require.NoError(t, os.WriteFile(page, []byte(seeded), 0o644))
var gotPrompt string
cfg := Config{Complete: func(_ context.Context, _, user string) (string, error) {
gotPrompt = user
return mustJSON([]RawPage{{
Title: "Shape Up", Type: "source", Subtype: "book",
Content: "## Summary\n\nA book about shaping product work.\n",
}}), nil
}}
// Deliberately does not mention "Appetite beats estimation." — that phrase
// can only reach the prompt via the existing on-disk page, not the source
// content, so its presence proves the page was threaded through.
content := "A short editorial update to the book's listing. No new claims here."
_, err := Run(context.Background(), cfg, dir, content, "shape-up", false)
require.NoError(t, err)
assert.Contains(t, gotPrompt, "Appetite beats estimation.",
"the existing page's content must be visible to the extraction prompt")
assert.Contains(t, gotPrompt, "revis", "the prompt must ask for a revision, not a fresh page")
}
func TestRun_NewSourceHasNoExistingPageInThePrompt(t *testing.T) {
// The other side of the same behavior: a source with no page on disk yet
// must not get an "existing page" section injected into its prompt at all.
dir := t.TempDir()
for _, sub := range []string{"wiki/concepts", "wiki/entities", "wiki/sources"} {
require.NoError(t, os.MkdirAll(filepath.Join(dir, sub), 0o755))
}
var gotPrompt string
cfg := Config{Complete: func(_ context.Context, _, user string) (string, error) {
gotPrompt = user
return mustJSON([]RawPage{{
Title: "New Thing", Type: "source", Subtype: "article",
Content: "## Summary\n\nBrand new.\n",
}}), nil
}}
_, err := Run(context.Background(), cfg, dir, "Brand new content.", "new-thing", false)
require.NoError(t, err)
assert.NotContains(t, gotPrompt, "Current page",
"a source with no page on disk yet must not get a revision section in its prompt")
}
func TestRun_RevisionEchoingExistingPageStaysByteIdentical(t *testing.T) {
// The issue's explicit risk: a model given the current page will sometimes
// echo it back verbatim. That must not duplicate content or otherwise
// perturb the page — the deterministic merge is still the backstop.
dir := t.TempDir()
for _, sub := range []string{"wiki/concepts", "wiki/entities", "wiki/sources"} {
require.NoError(t, os.MkdirAll(filepath.Join(dir, sub), 0o755))
}
seeded := "---\ntitle: 'Shape Up'\n---\n\n## Summary\n\nA book about shaping product work.\n\n## Key Claims\n\n- Appetite beats estimation.\n"
page := filepath.Join(dir, "wiki", "sources", "shape-up.md")
require.NoError(t, os.WriteFile(page, []byte(seeded), 0o644))
cfg := Config{Complete: func(_ context.Context, _, _ string) (string, error) {
return mustJSON([]RawPage{{
Title: "Shape Up", Type: "source", Subtype: "book",
Content: "## Summary\n\nA book about shaping product work.\n\n## Key Claims\n\n- Appetite beats estimation.\n",
}}), nil
}}
content := "A short editorial update to the book's listing. No new claims here."
result, err := Run(context.Background(), cfg, dir, content, "shape-up", false)
require.NoError(t, err)
require.False(t, result.Skipped)
got, err := os.ReadFile(page)
require.NoError(t, err)
want := "---\ntitle: 'Shape Up'\nlast_updated: " + time.Now().UTC().Format("2006-01-02") +
"\nsource_hash: " + hashBody(content) + "\n---\n\n" +
"## Summary\n\nA book about shaping product work.\n\n" +
"## Key Claims\n\n- Appetite beats estimation.\n"
assert.Equal(t, want, string(got),
"a revision pass that echoes the existing page back must not duplicate or alter its content")
}
func TestRun_FrontmatterOnlyChangeIsNotDrift(t *testing.T) {
// The hash covers the body, so re-fetching a page whose metadata moved
// (a re-crawl stamping a new date) is not treated as the source changing.
dir := t.TempDir()
var calls int
cfg := Config{Complete: func(_ context.Context, _, _ string) (string, error) {
calls++
return `[{"title":"Shape Up","type":"source","subtype":"book","domain":"product","content":"## Summary\n\nA book.\n"}]`, nil
}}
_, err := Run(context.Background(), cfg, dir, "---\nsource: x\nfetched: monday\n---\n\nsame body\n", "shape-up", false)
require.NoError(t, err)
_, err = Run(context.Background(), cfg, dir, "---\nsource: x\nfetched: tuesday\n---\n\nsame body\n", "shape-up", false)
require.NoError(t, err)
assert.Equal(t, 1, calls, "only the body counts as the source")
}
func TestRunRaw_ReportsWhenTheSourceDisagreesWithWhatIsOnDisk(t *testing.T) {
// The on-disk version still wins — that is what makes unattended ingest
// safe. But the run must say that the source now claims something else,
// or a changed source is indistinguishable from an unchanged one.
dir := t.TempDir()
page := filepath.Join(dir, "wiki", "sources", "shape-up.md")
require.NoError(t, os.MkdirAll(filepath.Dir(page), 0o755))
require.NoError(t, os.WriteFile(page, []byte(`---
title: 'Shape Up'
---
## Summary
Appetite is fixed, scope is variable.
`), 0o644))
res, err := RunRaw(dir, "shape-up", []RawPage{{
Title: "Shape Up", Type: "source", Subtype: "book", Domain: "product",
Content: "## Summary\n\nAppetite is negotiable and scope is fixed.\n",
}}, false)
require.NoError(t, err)
got, err := os.ReadFile(page)
require.NoError(t, err)
assert.Contains(t, string(got), "Appetite is fixed", "on-disk version wins")
joined := strings.Join(res.Warnings, " ")
assert.Contains(t, joined, "Summary", "the disagreeing section must be named")
assert.Contains(t, joined, "shape-up", "and the page it happened on")
}
+24 -2
View File
@@ -22,8 +22,18 @@ Each element must have exactly these fields:
Wikilinks in content: [[Display Name]] — just the display name, no slug, no pipe separator. Wikilinks in content: [[Display Name]] — just the display name, no slug, no pipe separator.
Only link to pages listed in the inventory or pages you are creating in this response.` Only link to pages listed in the inventory or pages you are creating in this response.`
// BuildPrompt constructs the user prompt for a single chunk. // BuildPrompt constructs the user prompt for a single chunk. existingPage is
func BuildPrompt(schema, source, content string, inventory map[wiki.PageType][]wiki.Entry) string { // the full current content (frontmatter + body) of the source's own wiki page
// when one already exists on disk, or "" for a source being ingested for the
// first time. When non-empty, the model is asked to revise that page rather
// than write a fresh one — see hyperguild#106. The deterministic merge in
// wiki.Merge remains the backstop regardless of what the model returns: an
// on-disk section the model doesn't touch survives untouched, and a section
// it does touch only takes effect where Merge's strategy allows the fresh
// side to change anything (bullet union, append) — never for an ordinary
// section, so the model proposing a revision is never how a page gets
// overwritten.
func BuildPrompt(schema, source, content string, inventory map[wiki.PageType][]wiki.Entry, existingPage string) string {
var sb strings.Builder var sb strings.Builder
fmt.Fprintf(&sb, "Today's date is %s.\n\n", time.Now().UTC().Format("2006-01-02")) fmt.Fprintf(&sb, "Today's date is %s.\n\n", time.Now().UTC().Format("2006-01-02"))
@@ -49,6 +59,18 @@ func BuildPrompt(schema, source, content string, inventory map[wiki.PageType][]w
sb.WriteString("\n") sb.WriteString("\n")
} }
if existingPage != "" {
sb.WriteString("## Current page for this source — revise it, don't restart\n\n")
sb.WriteString("This source has already been ingested and has the wiki page shown below.\n")
sb.WriteString("You are revising that page, not writing a fresh one:\n")
sb.WriteString(" - Add sections or claims the source below supports that this page doesn't have yet.\n")
sb.WriteString(" - Strengthen a claim where the source gives more detail, evidence, or nuance than what's already there.\n")
sb.WriteString(" - Leave unchanged whatever the source doesn't affect — reuse the existing wording verbatim rather than paraphrasing it, so an unchanged claim is recognized as unchanged.\n")
sb.WriteString(" - A merge step keeps this page's on-disk content for any section you don't return, so it's fine to omit a section you aren't revising.\n\n")
sb.WriteString(existingPage)
sb.WriteString("\n\n")
}
sb.WriteString("## Non-negotiable rules\n\n") sb.WriteString("## Non-negotiable rules\n\n")
sb.WriteString("1. Output ONLY a valid JSON array — no prose, no fences.\n") sb.WriteString("1. Output ONLY a valid JSON array — no prose, no fences.\n")
sb.WriteString("2. Fields: title, type, subtype (if applicable), domain (if applicable), content.\n") sb.WriteString("2. Fields: title, type, subtype (if applicable), domain (if applicable), content.\n")
+2 -4
View File
@@ -12,6 +12,7 @@ import (
"strings" "strings"
"github.com/mathiasbq/hyperguild/ingestion/internal/brain" "github.com/mathiasbq/hyperguild/ingestion/internal/brain"
"github.com/mathiasbq/hyperguild/ingestion/internal/textutil"
"github.com/mathiasbq/hyperguild/ingestion/internal/vectorstore" "github.com/mathiasbq/hyperguild/ingestion/internal/vectorstore"
) )
@@ -427,8 +428,5 @@ func excerpt(content string, maxLen int) string {
if len(parts) == 3 { if len(parts) == 3 {
body = strings.TrimSpace(parts[2]) body = strings.TrimSpace(parts[2])
} }
if len(body) > maxLen { return textutil.Truncate(body, maxLen)
return body[:maxLen] + "…"
}
return body
} }
+4 -4
View File
@@ -32,12 +32,12 @@ type Entry struct {
type Attempt struct { type Attempt struct {
Attempt int `json:"attempt"` Attempt int `json:"attempt"`
Model string `json:"model"` Model string `json:"model"`
Tier string `json:"tier"` // local | subagent | managed Tier string `json:"tier"` // local | subagent | managed
DurationMs int64 `json:"duration_ms"` DurationMs int64 `json:"duration_ms"`
WarmStart bool `json:"warm_start"` // model already loaded in llama-swap WarmStart bool `json:"warm_start"` // model already loaded in llama-swap
Verified bool `json:"verified"` Verified bool `json:"verified"`
Verdict string `json:"verdict,omitempty"` // accept | escalate | error Verdict string `json:"verdict,omitempty"` // accept | escalate | error
Feedback string `json:"feedback,omitempty"` // verifier feedback on escalation Feedback string `json:"feedback,omitempty"` // verifier feedback on escalation
OutputSummary string `json:"output_summary,omitempty"` OutputSummary string `json:"output_summary,omitempty"`
RunnerOutput string `json:"runner_output,omitempty"` RunnerOutput string `json:"runner_output,omitempty"`
} }
@@ -0,0 +1,75 @@
// Package startupretry retries a startup dependency that may not be serving
// yet, instead of exiting on its first failure.
//
// It exists for the cold-boot ordering race (#83): on a cluster restart the
// ingestion pod can reach OIDC discovery before dex is answering, gets a 502
// from ingress, and dies — after having already connected postgres, backfilled
// the graph and ingested session batches, all of which the restart redoes.
// Nothing is misconfigured in that scenario; the pod simply started first.
//
// The budget is bounded on purpose. Retrying forever would turn a genuine
// misconfiguration (wrong issuer URL, bad audience) into a process that looks
// healthy and never serves, which is harder to diagnose than a crash loop.
package startupretry
import (
"context"
"fmt"
"time"
)
// Policy bounds the retry: at most Attempts calls, with the delay doubling
// from Base and capped at Max.
type Policy struct {
Attempts int // total calls, including the first; < 1 means 1
Base time.Duration // delay before the second attempt
Max time.Duration // ceiling for the doubling delay
}
// Do calls fn until it succeeds, the attempt budget is spent, or ctx ends.
//
// The returned error wraps the last failure, so callers keep the diagnosis
// they would have had without the retry.
func Do[T any](ctx context.Context, p Policy, fn func(context.Context) (T, error)) (T, error) {
var zero T
attempts := p.Attempts
if attempts < 1 {
attempts = 1
}
delay := p.Base
var lastErr error
for i := range attempts {
if err := ctx.Err(); err != nil {
return zero, fmt.Errorf("startupretry: %w", err)
}
v, err := fn(ctx)
if err == nil {
return v, nil
}
lastErr = err
if i == attempts-1 {
break
}
if delay <= 0 {
delay = time.Second
}
if p.Max > 0 && delay > p.Max {
delay = p.Max
}
select {
case <-ctx.Done():
return zero, fmt.Errorf("startupretry: %w", ctx.Err())
case <-time.After(delay):
}
delay *= 2
}
return zero, fmt.Errorf("startupretry: gave up after %d attempts: %w", attempts, lastErr)
}

Some files were not shown because too many files have changed in this diff Show More