Skip to content

feat(distill): unattended weekly /dewey-distill with rolling per-theme review PRs - #211

Merged
jflowers merged 22 commits into
unbound-force:mainfrom
jflowers:018-weekly-distill-automation
Nov 16, 2026
Merged

jflowers merged 22 commits into
unbound-force:mainfrom
jflowers:018-weekly-distill-automation

Conversation

@jflowers

Copy link
Copy Markdown
Contributor

Summary

Unattended weekly /dewey-distill automation for Dewey (issue #193, epic #153 Phase 5), delivered as 44 changed files (+12,130/−16) across 9 phases and 48 tasks.

  • US1 — Weekly trigger: opt-in weekly GitHub workflow (dewey-distill.yml.example scaffolded by dewey init as copy-not-install, gh-hud dispatches /dewey-distill-auto via autonomy agent). Single deduplicated dewey-distill-labeled issue — no assignee (GITHUB_TOKEN cannot resolve @me), second weekly run posts a re-trigger comment instead of opening a duplicate.
  • US2 — Deterministic scope: git-only scope via git ls-tree — learning identities minus every cited sources identity, plus distill-policy.yaml exclusions and optional backlog_from bound. Filesystem fallback for non-git vaults. Zero interactive questions; question tool never called.
  • US3 — Theme grouping: supersession-aware grouping — embeddings with tag fallback, deterministic tie-breakers, per-decision provenance and confidence. Explicit supersedes links preserved in theme metadata.
  • US4 — Rolling per-theme PRs: dewey-distill/<theme> branches at tier: draft labeled human-gate. Review-queue bodies per article (what changed, newly cited learning identities, applied supersessions, lint drift per feat: lint anchor_drift / anchor_missing — detect staleness from code drift, not age #147). Rebase preserves human commits, force-with-lease pushes, needs-human-resolution on conflicts. Closed theme PRs are not reopened — fresh PR created.
  • US5 — Least-privilege distiller: distiller agent narrowed via global opencode-supervisor command: dewey-distill-auto profile (feat: task-scoped guard profiles (command/agent) and guard lock jflowers/opencode-supervisor#51) — question denied, tier: validated writes rejected server-side by GuardDistillTier, all git/gh mutations confined server-side inside rolling_pr.
  • US6 — Human-only promotion: merged, code-owner-approved PR is the vouch, verified through feat: git is the source of record for page trust tiers #203 gitref blob-equality seam (gitref.NewPageBlobResolver → vault.DeriveEffectiveTier); learnings stay draft. Workspace-layout .uf/dewey/compiled/ trust display is known limitation tracked in feat: extend #203 git-derived trust tiers to the .uf/dewey/ workspace layout (compiled/ and knowledge/) #210.

Closes #193

How to Test

Enable weekly distill:

  1. Scaffold and copy the template:
    dewey init   # scaffolds inert .github/workflows/dewey-distill.yml.example, never overwriting
    cp .github/workflows/dewey-distill.yml.example .github/workflows/dewey-distill.yml
    gh label create dewey-distill --color 0E8A16 --description "Unattended weekly distill" 2>/dev/null || true
    gh label create human-gate --color D93F0B --description "Requires code-owner review" 2>/dev/null || true
  2. Prerequisites (per chore: require code-owner review for compiled knowledge pages #194): CODEOWNERS owns .uf/dewey/compiled/**, ruleset 26764121 requires code-owner approval.
  3. Supervisor prerequisite (hard, per feat: task-scoped guard profiles (command/agent) and guard lock jflowers/opencode-supervisor#51): until shipped, unattended runs exit as recorded no-ops with no_op_reason: supervisor command profile unavailable and a notice comment — nothing lost.
  4. Optional policy .uf/dewey/distill-policy.yaml:
    exclude_tags: ["scratch-*"]
    exclude_stores: ["team-knowledge-draft"]
  5. Manual trigger: gh workflow run dewey-distill.yml or push dispatch comment.

Verify:

How to Demo

  1. Show scaffolded template: workflow_templates.go embedded map → .github/workflows/dewey-distill.yml.example and .uf/dewey/distill-policy.yaml.example via dewey init.
  2. Trigger weekly workflow in fixture repo twice — demonstrate dedup (single open issue + re-trigger comment) and gh-hud dispatch of /dewey-distill-auto.
  3. Run scope: go test -run TestScope -count=1 -race ./... and show 10→8 filtering.
  4. Show grouping provenance logs and a sample rolling PR body: per-article diff, newly cited ids, supersessions, lint drift.
  5. Re-run weekly with additional learnings — show same dewey-distill/governance PR updated (human commit preserved, body reflects new total), no duplicate PR.
  6. Show needs-human-resolution label on rebase conflict and CODEOWNERS/code-owner gate blocking bot-only approvals.

Trivial demo alternative for this PR itself: enable the workflow file, run manual dispatch, inspect dewey-distill/* branches.

Key Files Changed

44 files changed, 12130 insertions(+), 16 deletions(-) — 22 commits ahead of upstream/main.

Area Key Files
Workflow template .github/workflows/dewey-distill.yml.example, workflow_templates.go, workflow_template_test.go
Agents & commands .opencode/agents/distiller.md, .opencode/commands/dewey-distill-auto.md, agents.go, slash_commands.go
Core distill tools/scope.go + tools/scope_test.go (deterministic git scope), tools/group.go + tools/group_test.go (theme grouping), tools/rolling_pr.go + tools/rolling_pr_test.go (rolling PRs), tools/distill_tools.go, tools/distill_guard.go
Security/gates gate.go + gate_test.go (dewey gate auto-answer distiller-aware, schema fix), server.go
Spec & docs specs/018-weekly-distill-automation/{spec,plan,tasks,research,data-model,quickstart,contracts/*} , README.md, AGENTS.md, .uf/dewey/distill-policy.yaml.example
Tests & perf tools/distill_e2e_test.go, tools/distill_edge_cases_test.go, tools/distill_perf_test.go, tools/distill_tools_test.go
Small fixes tools/compile.go, tools/promote.go, cli.go, cli_test.go, server_test.go
Full diff stat (top)
 tools/rolling_pr.go                            | 1857 ++++++++++++++++++++
 tools/rolling_pr_test.go                       | 1854 +++++++++++++++++++
 tools/scope.go                                 |  936 ++++++++++
 tools/scope_test.go                            |  904 ++++++++++
 tools/group.go                                 |  789 +++++++++
 tools/group_test.go                            |  479 +++++
 workflow_template_test.go                      |  333 ++++
 tools/distill_tools_test.go                    |  416 +++++
 tools/distill_tools.go                         |  374 ++++
 tools/distill_e2e_test.go                      |  372 ++++
 tools/distill_perf_test.go                     |  350 ++++
 gate.go                                        |  280 +++
 gate_test.go                                   |  237 +++
 slash_commands.go                              |  160 ++
 agents.go                                      |  118 ++
 workflow_templates.go                          |  108 ++
 specs/018-weekly-distill-automation/spec.md    |  227 +++
 specs/018-weekly-distill-automation/tasks.md   |  236 +++
 ... (44 files total)

Known Issues

Review council: APPROVE WITH ADVISORIES — 6/6 reviewers succeeded, 5 advisories (2 MEDIUM, 3 LOW), 0 blocking findings. Spec review: APPROVE WITH ADVISORIES (4 iterations). Code review: APPROVE WITH ADVISORIES (1 iteration). All CI checks green at 72a362a — go build/vet exit 0, go test -race -count=1 2079 PASS / 0 FAIL / 1 SKIP (env-only TestEnsureOllama_StartSuccess), coverage 84.8%, gaze crap 48/48, gaze GazeCRAPload 41/45, golangci-lint clean of 018-authored findings (7 pre-existing staticcheck at eb4720c).

Non-blocking advisories carried forward:

  • MEDIUM tools/rolling_pr.go:700 — restore closure discards both checkout errors (_, _ = env.runGit(...)). If restore fails (untracked collision, index.lock, detached HEAD), working tree left on distill branch with no log/warning. Fix: surface error in tool result/log.
  • MEDIUM gate.go:1137 — recordSupervisorNoOp serializes schema: 0 while all other producers write 1 (distillRunRecordSchema). Unshipped gate is the only current producer, so audit history is version-split. Fix: export schema constant or constructor.
  • LOW tools/rolling_pr.go:1257 — remoteBranchSHA conflates branch-absent with remote-unreachable (ls-remote non-zero → ("", nil)). Diagnosability only — fail-safe lease direction is correct. Fix: return distinct error for unreachable.
  • LOW tools/scope.go:870 (+ tools/group.go:710) — per-object git cat-file blob / git show spawns N+M subprocesses; could collapse to git cat-file --batch. Sub-second at current sizes; hardening note.
  • LOW .opencode/commands/dewey-distill-auto.md:141 — docs describe prs_touched:[{branch,pr_number,state,...}] but DistillRunRecord.PRsTouched is []string of branch names. Prose/implementation drift from earlier draft. Fix: reconcile command text.

Known limitation tracked separately: workspace-layout .uf/dewey/compiled/ trust-tier display — #210 (spec US6).


This PR was generated by /uf.finale (AI-assisted).

…Rs (unbound-force#193)

Spec for 018-weekly-distill-automation covering weekly scheduled trigger,
deterministic scope, assignment/supersession grouping, rolling per-theme
PRs, distiller allowlist via global config, and human vouch via merge.
Part of epic unbound-force#153 phase 5, depends on unbound-force#203/unbound-force#204.
Ship .github/workflows/dewey-distill.yml.example per
specs/018-weekly-distill-automation FR-001/FR-022 and
contracts/workflow-template.md: weekly schedule (Mon 09:00 UTC,
editable) plus workflow_dispatch, contents:read/issues:write/
pull-requests:write permissions, and the distill-trigger dedup job
—an open dewey-distill issue gets a re-trigger comment carrying the
dewey-distill-trigger marker, otherwise a new issue is created,
labeled and assigned per the contract. A concurrency group
serializes racing triggers so the at-most-one-open-issue invariant
(FR-003) holds, and the header documents the gh-hud dispatch
contract plus adoption prerequisites (labels, CODEOWNERS/ruleset
26764121, optional distill policy). The .example suffix keeps the
template inert until copied into place — opt-in adoption, never
auto-installed.

Task T001 of 018-weekly-distill-automation.
…ll automation

Apply 21 findings (6 HIGH + 15 LOW/MEDIUM) from iteration 1:
- spec.md: harden supervisor-prerequisite to fail-closed (no tightest-achievable fallback, unattended mode disabled until jflowers/opencode-supervisor#51 ships, records no-op artifact + notice)
- contracts/scope.md: bound distill-policy.yaml (16 KiB, depth 3, 100 entries), deny overly-broad ["*"], define durable no-op artifact path and provenance persistence
- contracts/rolling-pr.md: define branch sanitization charset/length/collision (FR-011), sanitization gate for critical/high findings, human-commit preservation guard (FR-015), concurrency CAS via force-with-lease
- contracts/distiller-allowlist.md: enumerate execution surface (filesystem/git/GitHub/MCP registration), deny push --force and non-distill writes, clarify global-only widening remains fail-closed

Fulfills manual-apply directive from iteration 1 human decisions (all APPLY).

Co-Authored-By: internal-model
… (T002-T005)

Phase 1 of 018-weekly-distill-automation (unbound-force#193):

- .opencode/agents/distiller.md: unattended distill agent with narrowed
  tool allowlist (deny question, deny tier:validated; allow read/lint/
  compile/curate/verify_candidates/store_compiled/supersede_learning +
  scope/group_learners/rolling_pr), mirrored byte-identically in the
  agents.go scaffold map (quotes instead of backticks per raw-string
  literal constraint)
- .opencode/commands/dewey-distill-auto.md: unattended entry point
  (scope -> group -> rolling PR pipeline, no HUMAN_GATE questions)
- .uf/dewey/distill-policy.yaml.example: optional exclusion policy
  example with defaults and bounds
- cli.go: dewey init documents the opt-in workflow-template copy path
  (no auto-install per composability, FR-001/FR-022)
- specs/018-weekly-distill-automation/checklists/automation-safety.md:
  reviewer-owned automation-safety checklist from /speckit.checklist
…(T006-T010)

Phase 2 of 018-weekly-distill-automation (unbound-force#193):

- tools/scope.go: data model (ScopeSet, DistillPolicy, Theme,
  AssignmentDecision, SupersessionLink, RollingPR, ReviewQueueArticle),
  policy loader with warn-and-skip bounds (16 KiB, depth 3, 100 entries,
  200 chars, overly-broad denial), identity tag extraction, and the two
  enumeration legs per research D-002 — git batch ls-tree through the
  gitref Runner seam plus blob reads, and the filesystem fallback for
  non-git vaults (degraded provenance, no panic)
- tools/rolling_pr.go: theme branch sanitizer per contracts/rolling-pr.md
  (lowercase, [a-z0-9] charset, dash collapse, 50-char base + 8-hex
  sha256(theme) suffix, untagged fallback, lexicographic -2/-3 collision
  suffixing, 80-char branch bound, traversal rejection)
- tools/distill_guard.go: GuardDistillTier enforces FR-012/FR-017 —
  distiller-reachable write paths reject tier:validated server-side with
  logging; store layer deliberately left unguarded (GTS-FR-005: trust
  derivation writes validated into the pages cache)
- tools/compile.go: store_compiled asserts its tier through the guard
  hook; tools/promote.go documents the human-only validated-write boundary
- tests: policy bounds and malformed-entry handling, tag-glob semantics,
  git/FS enumeration with scripted Runner, sanitizer contract examples,
  guard rejection, store_compiled draft frontmatter pin
…015)

Phase 3 of 018-weekly-distill-automation (unbound-force#193), user story 1:

- T011: dedup job steps already shipped with the template; now locked in
  by the structure test asserting the exact contract commands
- T012/T013: README gains a Weekly Unattended Distill section (Enable
  copy command, label creation, CODEOWNERS + ruleset 26764121
  prerequisites per unbound-force#194, gh-hud dispatch contract table, policy
  opt-in); AGENTS.md gains the matching Key Patterns bullet
- T014: workflow_template_test.go executes the template's own trigger
  script against a fake gh across a 4-week simulated schedule with
  overlapping triggers — the fake refuses issue create while a labeled
  issue is open, so any dedup-invariant violation (SC-002/FR-003) fails
  the run; week 2 asserts the re-trigger comment instead of a duplicate
- T015: TestInitCmd_DoesNotInstallDistillWorkflow verifies init never
  auto-installs the workflow (FR-001 opt-in copy) and logs the cp hint
  when the example ships in the vault
…-T021)

Phase 4 of 018-weekly-distill-automation (unbound-force#193), user story 2:

- ComputeScope (FR-005): learnings at the resolved default-branch ref via
  one batch ls-tree, cited set from compiled blobs read at their ls-tree
  shas, policy tag exclusions, git:<ref>:<sha> provenance; never
  interactive (FR-006) — ambiguity degrades to warn-and-skip
- Filesystem fallback (edge case non-git vault): FS scan unioned with the
  SQLite learning/ seam (StoreLearningPageNames over ListDraftCandidatePages,
  nil-safe), provenance filesystem:degraded, no panic; a nonexistent vault
  dir errors rather than masquerading as empty scope
- Durable run record (FR-021): DistillRunRecord written append-only to
  .uf/dewey/distill-runs/<YYYYMMDD-HHMMSS>.json with same-second collision
  suffixes; RecordNoOpDistillRun refuses non-empty scopes fail-closed
- Question denial tests (FR-006/SC-003): distiller agent frontmatter
  carries question: deny in tracked and embedded copies; the unattended
  command carries no HUMAN_GATE markers while interactive /dewey-distill
  keeps both
- Fixture tests per contracts/scope.md: real-git ten-learnings fixture
  (2 cited -> 8 in scope, SC-001 exact equality, FR-005 determinism),
  scratch-* policy exclusion, over-broad [*] never starves, empty scope
  no-op signal, non-git degraded fallback with store union, adapter
  coverage including the closed-store error path
- cli.go: agent scaffolding iterates deweyAgentDefinitions in sorted name
  order — map iteration randomized which agent a write failure names,
  flaking TestInitCmd_CuratorAgentWriteFailureFailsInit since distiller.md
  joined the map
… (T036-T039)

Phase 7 / US5: the unattended pipeline's three server-side stages
(scope, group_learners, rolling_pr) registered as MCP tools
(tools/distill_tools.go) so the distiller agent drives the pipeline
entirely through the guarded server surface; new
dewey gate distill-unattended startup gate (gate.go) enforces the
FR-016 global-only widening rule — only the global
opencode-supervisor command: dewey-distill-auto profile may widen,
repo-local .opencode/supervisor.yaml is never read, refusal is
fail-closed until jflowers/opencode-supervisor#51 ships and records
the FR-021 no-op artifact; distiller frontmatter gains the
distill-unattended bash allow and both gate copies (tracked file +
agents.go mirror) stay byte-identical, guarded by shape and parity
tests in cli_test.go; interactive /dewey-distill verified unchanged
(T038). Handler-level tests cover the MCP surface including the
no-op artifact recording; CRAPload 48/48, GazeCRAPload 41/45.
…r human decision

unbound-force#203's shipped trust derivation covers vault-root compiled/ and knowledge/
page families only; distill articles live at .uf/dewey/compiled/<theme>.md
(workspace layout), where the merge-vouch is recorded in git (the merged,
code-owner-approved PR on the article path) but not yet surfaced by dewey
status/doctor pending unbound-force#210.

Amend spec.md US6 (known-limitation paragraph, Independent Test, AS1,
assumption on unbound-force#203), SC-007, tasks.md Phase 8 goal/Independent Test/T040/
T042, and quickstart.md Verify to document the limitation honestly and to
verify the derivation mechanism directly via vault.DeriveEffectiveTier with
a workspace pathspec (tools/curate.go IndexKnowledgeStore precedent) rather
than asserting the doctor display. Do not move distill articles to
vault-root compiled/; do not reimplement unbound-force#203's derivation.
Sync plan.md Observable Quality row, fix spec header/research unbound-force#210
reference, remove pull-requests:write over-grant and @me assignee,
deliver workflow template via dewey init embed byte-identical to
example, add --backlog-from/--dry-run preview and rolling-pr clean-tree
preconditions, clarify distiller allowlist ref-restriction contract,
and correct amendment seam wording.
Removes "assigned to maintainer" from US1 narrative, AS1, FR-004
example and Phase 3 Goal/T012 to align with FR-002/FR-022
authoritative contract (GITHUB_TOKEN cannot resolve @me; gh-hud
dispatch keys off label). Aligns T008 branch sanitization with
contracts/rolling-pr.md (80-char limit, collapse/hash spec).

Co-Authored-By: internal-model
Co-Authored-By: internal-model

T040 documents no-reimplementation of unbound-force#203 DeriveEffectiveTier + TierBlobResolver.
Workspace-layout limitation now explicit: merge-vouch recorded in git
but displayed as draft until dewey#210.
…(T041)

Validate the US6 acceptance scenario where a reviewer posts tier:
validated via suggestion/review comment and gh-hud's feedback task
applies it as a frontmatter edit on the PR branch (unrelated comments
produce no file change). Next weekly run preserves the validated claim
via FR-015 regeneration guard and flags needs-human-resolution while
still writing only draft.

Co-Authored-By: internal-model
All five CI-exact commands from .github/workflows/ci.yml exit 0 on
018-weekly-distill-automation: go mod download, go build -v ./...,
go vet ./..., go test -race -v -count=1 -coverprofile=coverage.out
./..., gaze crap --max-crapload=48 --max-gaze-crapload=45.

2945 pass / 0 fail / 1 skip (pre-existing ollama-not-in-PATH guard).
Coverage 84.8%. CRAPload 48 (at ratchet boundary), GazeCRAPload 41.
No code changes required; review-council APPROVE happens at the
parent's Step 6 code-review dispatch.
Zero-waste / Neighborhood Rule audit for the 018 change:

- Remove the orphaned duplicate TierValidated constant; GuardDistillTier
  now compares against the canonical unexported tierValidated from
  promote_file.go.
- Give ValidateThemeBranch a production consumer: ManageRollingPRs now
  validates every AssignThemeBranches output via the extracted
  validateAssignedBranches helper (testable-core seam), failing closed
  on a sanitizer regression before any branch reaches a git refspec or
  a dry-run preview reports it. Dedicated tests pin both directions:
  sanitizer output must pass, poisoned assignments must fail closed.
- gofmt comment alignment in distill_e2e_test.go.

Audit verdicts: template copy-not-install PASS (init scaffolds only the
.example, never an active workflow); zero-waste PASS (go mod tidy no
diff, all 018-added exported symbols have live consumers or spec'd
seams); Neighborhood Rule PASS (fork point 5c830ce had 40 server.go
registrations = 37 inherited default-config tools + 3 mode-conditional;
HEAD has 56 = pure additions, zero deletions/renames/registration
edits; the 3 added tools are scope, group_learners, rolling_pr).

CI parity re-run green: build/vet exit 0, 2947 pass + 1 environmental
skip / 0 fail, coverage maintained, CRAPload 48/48, GazeCRAPload 41/45.
golangci-lint errcheck flagged the two deferred os.Remove(bodyPath)
calls in createPR and editPRBody at the Phase 9 checkpoint. Follow the
codebase's established best-effort cleanup pattern (_ = os.Remove,
tools/promote_file.go, tools/compile.go) adapted for defer: a failed
removal of the gh body temp file must not mask the function's real
result.

The seven remaining staticcheck findings are blame-verified pre-existing
(unbound-force#146-era tools/learning.go and tools/learning_test.go lines, untouched
artifacts/ files) and stay out of this change's scope.
@jflowers
jflowers enabled auto-merge (rebase) November 16, 2026 00:49

@uf-divisor uf-divisor left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Council Review — APPROVE WITH ADVISORIES

Verdict: APPROVE WITH ADVISORIES — 10 findings (4 MEDIUM, 6 LOW), none CRITICAL or HIGH. Six reviewers dispatched (adversary, architect, curator, guard, sre, testing); all six completed, four returned APPROVE and two APPROVE WITH ADVISORIES.

What this PR does

Implements specs/018-weekly-distill-automation (closes #193): an opt-in weekly GitHub Actions trigger that dispatches /dewey-distill-auto, a deterministic git-only scope, supersession-aware theme grouping, rolling per-theme dewey-distill/<theme> PRs with human-gate labels, a least-privilege distiller agent, and human-only promotion through the #203 gitref blob-equality vouch. 44 files, +12,130/−16.

Verification

  • CI: build-and-test PASS, MegaLinter PASS at 72a362a.
  • Pre-flight (ci-aware): every detected local tool is covered by a passing CI check; no local execution required. Verdict PASS.
  • Acceptance criteria: all five criteria from #193 are addressed — unattended-mode guard tests (question denied, validated writes rejected server-side), scope fixtures matching hand counts, the no-op second run, single-PR-per-theme updates, and the four-week dedup simulation.

Findings

Ten findings; nine are posted as inline comments. One has no diff anchor and is recorded here:

  • [MEDIUM] Documentation — CHANGELOG.md has no entry for this change (divisor-guard). The PR adds user-facing behavior — three new MCP tools (scope, group_learners, rolling_pr), the distiller agent, the weekly workflow template, and the distill-unattended gate — and updates README.md/AGENTS.md (52→55 tools), but CHANGELOG.md carries no entry referencing Spec: specs/018-weekly-distill-automation/spec.md. Review Checklist 6 requires a CHANGELOG entry for CLI/MCP/workflow changes.

The inline advisories cluster in three areas: concurrency (the distill handler is not wired to the shared pipeline index mutex that indexing/compile/curate receive), efficiency (the grouping/rolling path is N+1 over embedding round-trips and git cat-file subprocesses, and the pinned perf tests exercise the nil-embedder degraded path rather than the production one), and operational hygiene (the distill-runs/ artifact directory has no tracked/ignored policy; runGit discards stderr; the deferred restore discards its errors with an unbounded context; the workflow-example scaffold is check-then-write). None block merge; all are worth a follow-up.

This review was generated by /uf.review-pr (AI-assisted).

Comment thread server.go
// store backs the scope's SQLite learning union (nil degrades
// to the filesystem leg); the vault path anchors git, files,
// and artifacts.
distill := tools.NewDistill(cfg.store, cfg.embedder, cfg.vaultPath)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MEDIUM] Concurrency: the distill handler takes over the vault working tree without the shared pipeline index mutex. (divisor-sre)

rolling_pr performs the most invasive vault operations of any tool — per-theme git checkout -B, article writes, rebase, force-with-lease push — yet the handler is constructed here without the mutex that indexing, compile, and curate all share (tools.NewDistill(cfg.store, cfg.embedder, cfg.vaultPath) takes no mutex parameter). Background curation's indexMu.TryLock() on its 10-minute interval and any index/reindex MCP call can therefore run while the tree is checked out on a dewey-distill/<theme> branch:

  • curation writes markdown into .uf/dewey/knowledge/<store>/ and indexing walks the tree mid-checkout, so machine-generated files land on a theme branch and are left behind when the next anchor SHA is checked out;
  • a later checkout -B can fail with "untracked working tree files would be overwritten", aborting the run mid-pipeline while the deferred restore swallows its own error;
  • two distill runs (scheduled plus manual re-trigger, or a gh-hud redispatch) race on the same checkout — --force-with-lease protects the remote ref only, not the local tree.

Wiring the Distill handler into the same pipeline mutex its siblings receive closes the gap.

Comment thread tools/group.go
"degraded mode: exact tag match", "degraded mode: new theme for tag "+tag)
}

compVec, vecOk := componentCentroid(ctx, opts.Embedder, comp, input.Texts)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MEDIUM] Efficiency: the production grouping path is N+1 over embedding round-trips and git subprocesses. (divisor-sre)

With an embedder configured (the serve default), GroupLearners calls componentCentroid → EmbedBatch once per supersession component — and nearly every component is a singleton, so that is one sequential round-trip per learning (~500 steady state, ~1,729 on a backlog run), plus one Embed per article in embedGroupArticles. Separately, CollectGroupInput reads each learning/article body with its own git cat-file blob subprocess, and the rolling_pr handler re-runs CollectGroupInput over the same identity set right after group_learners did — roughly 2×1,729 git processes on a backlog run.

plan.md pins grouping at "O(n*m) with embeddings, <5s for 500/week, <30s for 1,729 backlog", but both pinned tests pass GroupOptions{Embedder: nil} — the tag-centroid degraded path — and build the input outside the timed window, so neither the embedding traffic nor the per-blob reads are exercised by the goal they claim to validate. At 15–40 ms per embedding round-trip the steady-state goal is plausibly exceeded on a real provider. Batching the embedding calls and blob reads (or git cat-file --batch) and timing the production path would align the tests with the pinned goals.

Comment thread tools/rolling_pr.go
// distillRunsDir is the vault-relative directory holding one JSON run
// artifact per distill run — the audit surface that exists even when no
// PR does.
const distillRunsDir = ".uf/dewey/distill-runs"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MEDIUM] Operational artifacts: .uf/dewey/distill-runs/ has no repository policy. (divisor-sre)

The new durable directory declared here is absent from .gitignore (which lists .uf/dewey/graph.db, cache/, *.lock, dewey.log), is not swept by dewey artifacts plan|sync (learnings/compiled/knowledge only), and uf_finale_stage stages everything except .uf/dewey/learnings/ — so run artifacts (one per real run plus one per refused dewey gate distill-unattended) will be staged into the next feature PR. The spec declares the directory append-only audit history whose records must not be pruned, while the clean-tree precondition tolerates untracked files, so nothing ever blocks: the outcome is silent repo churn with no owner. Deciding tracked-vs-ignored and encoding it (gitignore entry plus an artifacts-plan sweep, or a tracked-home convention) resolves the ambiguity.

Comment thread server.go
verify := tools.NewVerify(cfg.store, cfg.vaultPath)
toolCount += registerVerifyTools(srv, verify)

// Distill automation tools (018-weekly-distill-automation,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[LOW] Documentation: tool count is inconsistent between docs and code. (divisor-guard)

README.md and AGENTS.md report 55 tools across 17 categories (52→55 after this PR), while server.go's registration accounting reaches 54. The health-tool counting difference is not explained anywhere, leaving docs and code out of sync. Aligning the count — or documenting why the health tool is excluded — keeps the manifest claims verifiable.


- If open PR exists via `gh pr list --label dewey-distill --state open` → `git fetch origin/<branch>`, rebase preserving human commits (fixup! or non-distiller author), compare working-tree vs `origin/<branch>` last-committed content; if human edited file also regenerated refuse overwrite, label `needs-human-resolution`, list files in body, skip that file; else regenerate draft articles + hygiene, `gh pr edit` body, `git push --force-with-lease`.
- Else → create branch, write draft articles (`tier: draft` + `validity`/`superseded_by` hygiene), `gh pr create --label human-gate --body ReviewQueue`.
- Conflicts on rebase → leave markers, label `needs-human-resolution`, body lists files.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[LOW] Documentation: conflict recovery describes markers the implementation never leaves. (divisor-sre)

Conflict recovery is documented three times as leaving conflict markers on the PR — spec.md Edge Cases ("the run creates a conflict marker commit and labels the PR needs-human-resolution"), contracts/rolling-pr.md, and this line — but updateThemePR runs git rebase --abort on conflict, pushes nothing, and only labels needs-human-resolution. An operator following the docs will look for markers that do not exist and may assume the branch was left mid-rebase. Updating the three docs to the abort-and-label behavior keeps the recovery runbook accurate.

Comment thread README.md

When `dewey serve` starts, the MCP server is ready within 1 second. Vault indexing runs in the background — tools serve from the persistent store (previous session's data) while indexing completes. The `health` tool reports indexing status.

## Weekly Unattended Distill

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[LOW] Documentation: the required website sync issue is missing. (divisor-guard)

Weekly unattended distill is user-facing — a new command, workflow template, three MCP tools, and a gate — and AGENTS.md's Website Documentation Sync section requires a GitHub issue in unbound-force/website documenting the affected docs pages before merge. The PR references no such issue. Filing it (e.g. docs: sync dewey weekly-distill documentation with the docs label) keeps the public documentation in step with this change.

Comment thread tools/rolling_pr.go

// runGit runs one git command, translating a non-zero exit into an error
// carrying stderr.
func (e *gitEnv) runGit(ctx context.Context, args ...string) (string, error) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[LOW] Observability: runGit discards stderr. (divisor-sre)

runGit reports distill rolling pr: git <args> exited <code> and drops stderr, while the push path (pushError) already includes trimmed stderr. A scheduled failure at 09:00 Monday leaves only the command name — e.g. git checkout -B dewey-distill/auth <sha> exited 1 — with no cause (dirty index, lock contention, bad ref), and diagnosing it requires reproducing the run by hand. Carrying trimmed stderr into the error text, as the push helper already does, gives scheduled failures a cause.

Comment thread tools/rolling_pr.go
env.baseBranch = strings.TrimSpace(origRef)
restore := func() {
if env.baseBranch == "" || env.baseBranch == "HEAD" {
_, _ = env.runGit(context.Background(), "checkout", env.baseSHA)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[LOW] Recovery: the deferred restore discards its errors and has no timeout. (divisor-sre)

The deferred restore performs _, _ = env.runGit(context.Background(), "checkout", env.baseSHA) (line 702) and the same for env.baseBranch (line 705) — both errors discarded, both on an unbounded context.Background(). If files left by the run body block the checkout, or git blocks on a stale index.lock, the run returns with the vault still on dewey-distill/<theme> and no signal that the restore failed; the next run then refuses with "vault has uncommitted tracked changes", which is safe but misleading. Logging the restore failure (and bounding its context) makes a partial-state exit distinguishable from a clean one. This matches the advisory carried in the PR description.

Comment thread cli.go
Comment on lines +519 to +529
if fileExists(examplePath) {
continue // Preserve user customization.
}
if err := os.MkdirAll(filepath.Dir(examplePath), 0o755); err != nil {
logger.Warn("failed to create workflows directory for template", "path", filepath.Dir(examplePath), "err", err)
continue
}
if err := os.WriteFile(examplePath, []byte(deweyWorkflowTemplates[name]), 0o644); err != nil {
logger.Warn("failed to scaffold workflow template", "path", examplePath, "err", err)
continue
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[LOW] File handling: the workflow-example scaffold is check-then-write (TOCTOU). (divisor-sre)

The scaffold does if fileExists(examplePath) { skip } followed by os.WriteFile — and os.WriteFile truncates, so a file appearing between the check and the write is overwritten, contradicting the never-overwrite contract asserted by FR-001/SC-008 and the comment above ("an existing file is never overwritten"). The agent-file scaffold in the same function (line 451) already uses the exclusive-create form. Mirroring it closes the window:

Suggested change
if fileExists(examplePath) {
continue // Preserve user customization.
}
if err := os.MkdirAll(filepath.Dir(examplePath), 0o755); err != nil {
logger.Warn("failed to create workflows directory for template", "path", filepath.Dir(examplePath), "err", err)
continue
}
if err := os.WriteFile(examplePath, []byte(deweyWorkflowTemplates[name]), 0o644); err != nil {
logger.Warn("failed to scaffold workflow template", "path", examplePath, "err", err)
continue
}
if err := os.MkdirAll(filepath.Dir(examplePath), 0o755); err != nil {
logger.Warn("failed to create workflows directory for template", "path", filepath.Dir(examplePath), "err", err)
continue
}
f, err := os.OpenFile(examplePath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
if err != nil {
if os.IsExist(err) {
continue // Preserve user customization.
}
logger.Warn("failed to scaffold workflow template", "path", examplePath, "err", err)
continue
}
if _, werr := f.Write([]byte(deweyWorkflowTemplates[name])); werr != nil {
logger.Warn("failed to scaffold workflow template", "path", examplePath, "err", werr)
}
if err := f.Close(); err != nil {
logger.Warn("failed to close scaffolded workflow template", "path", examplePath, "err", err)
}

@jflowers
jflowers merged commit a2a2753 into unbound-force:main Nov 16, 2026
2 checks passed
@jflowers
jflowers deleted the 018-weekly-distill-automation branch November 16, 2026 02:25
jflowers added a commit to jflowers/gh-hud that referenced this pull request Nov 17, 2026
A by_label rule could never fire from the dashboard. Searched issues
carried no labels (only the one-item lookup asked for them), so neither
a by_label command nor the human-gate label matched them. And gh-hud only
searched issues assigned to you or mentioning you, while the dewey-distill
workflow (unbound-force/dewey#211) opens its issue as GITHUB_TOKEN, which
can't assign you.

The issue fields now include labels, and the dashboard searches your orgs
for open issues carrying each by_label label, one search per label. With
no orgs there is no such search, so a stranger's repo can't label an
issue into your agents.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: unattended weekly /dewey-distill with rolling per-theme review PRs

2 participants