Skip to content

refactor(src): restructure the flat src/ tree into domain folders (#168) - #248

Merged
abogartz merged 5 commits into
mainfrom
refactor/domain-structure
Nov 1, 2026
Merged

abogartz merged 5 commits into
mainfrom
refactor/domain-structure

Conversation

@abogartz

@abogartz abogartz commented Nov 1, 2026

Copy link
Copy Markdown
Owner

Stacked on #247 (tools split) — same direction, one level up: the whole tree, not just tools/. Behavior-preserving by construction: declaration bodies moved verbatim; unit 842 pass / 0 fail and e2e 30/30 identically on the restructured tree, tsc clean, biome exit 0.

Layout

src/
  index.ts      entry: composition, hooks, capture scheduling, status plumbing
  core/         types, state, runtime, time, tokenize, lru, config/{paths,budgets}, logfmt/{format,read,publish}, cmp-ts
  store/        model/{memory,visibility,predicates}, files/{load,append,supersede,target,prune,deletions,snapshots},
                lock, undo, quarantine/{quarantine,release}, tombstones/{tombstone,rejection},
                containment, blocklist, prune, sanitize, secrets
  gate/         gate.ts (runWriteGate verbatim; #220 decomposition follows), resolver.ts
  identity/     host-events.ts (was host.ts), repokey.ts
  inject/       format, digest, budget, version, anchor, pull, epochs (was injection-epochs.ts), attribution
  recall/       score, relevant, shared-terms
  hits/ledger.ts   evidence/record.ts   consolidate/{propose,render}
  capture/      prompt, transcript, candidates, lag, triggers
  portable/     export, import, decay
  init/         detect, run, format   command/ensure.ts   status/{payload,write,format,metrics,report}
  tools/        #247 + schema.ts   viewer/ (unchanged)   tui/panel.tsx

Rules encoded (for reconcile tooling)

  1. Domain = folder; no file-name domain prefixes anywhere in src/.
  2. File = one concept, named for its primary export (store/undo.ts exports restoreSnapshot/listSnapshots — undo is the concept).
  3. No grab-bags: memory.ts (851 lines) → model + files; inject.ts → inject + recall; status.ts → status/; portable.ts → portable/; config.ts → core/config + core/time; logfmt.ts → core/logfmt/*.
  4. Cross-module imports are explicit file paths; no barrels, so the tsc graph is the dependency surface.
  5. Entry src/index.ts and package export ./tui are the only published paths that matter; ./tui now maps to src/tui/panel.tsx.

The one non-mechanical line

src/command/ensure.ts: template lookup ../command → ../../command — src/command/ (the folder) shadowed the packaged template dir when the file moved in. Exactly the collision class folders prevent; its e2e/unit coverage caught it.

Tripwires updated to the new geometry (intent kept, sharper)

  • negative-eval appendMemory allowlist names store/files/append.ts + gate/gate.ts; comment prose no longer counts as a call site.
  • governed-path tripwire: per-module runWriteGate assertions follow the move (init/run.ts); portable/capture by-proxy checks are folder-wide.
  • e2e/coverage.test.ts parses tool/hook registrations from the whole src/ tree recursively.
  • harness TUI compile targets tui/panel.tsx; package.json exports updated.

Reconcile note: 185 files, +4102/−3748 — GitHub renders moved files with rename detection; review the 10 new-module dirs by folder, not flat. While this is open, PRs touching src/ should rebase onto it rather than the reverse.

@WhollyMindless WhollyMindless left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review: CHANGES_REQUESTED — restore the mutation tooling before merge

Reviewed 359439c against stacked base e85a589 (#247), independently on Windows / Bun 1.4.4. The source reorganization looks sound in the checks below, but one developer-facing regression needs to travel with the move.

R1 — P2: mutation catalog still targets the deleted flat modules

scripts/test-sweep.ts retains paths such as src/lock.ts (line 100), src/logfmt.ts (125), src/memory.ts (163), src/undo.ts (254), and src/inject.ts (357), plus gates/repokey/portable and the calibration plant.

Reproduction: bun scripts/test-sweep.ts --validate.

  • Base e85a589: all 45 patterns validate.
  • Head 359439c: exit 1; 41 patterns fail with file-missing errors, including the self-test plant.

This prevents the sweep/calibration from running against the refactored tree even though ordinary CI is green. Please move each catalog target to its actual destination, re-anchor any fragments split across files without changing the intended invariant, and verify --validate plus calibration on the final tree. This belongs with the refactor; it is separate from the three permission-related pattern edits in #244.

Verified / limits

  • Normalized AST comparison across src/: 609 existing top-level declarations match their counterparts after the move. The only changed existing declaration is PKG_COMMANDS, with the extra parent traversal required by src/command/ensure.ts. This checks declaration preservation, not a proof that module bindings/evaluation order are equivalent.
  • Inspected relocated imports, template lookup, viewer asset path, package ./tui export, and loose tui.ts re-export. Packed-host load/TUI compilation and real-host scenarios pass locally.
  • Windows gate: typecheck/lint pass; unit 843 pass / 11 skip / 0 fail; E2E 29 pass / 1 fail. The sole E2E failure is the already-reported inherited CRLF @covers parser issue in #247, also reproduced on its base. It is not a new #248 runtime failure. Hosted checks are green at this head.
  • No full mutation sweep was possible while validation is broken. No production source changes pushed during review.

Non-blocking cleanup

The new .github/workflows/windows-debug.yml is labeled temporary in the commit. Prefer dropping it before merge. If it is intended to remain, please clarify the intentional Bun 1.3.5 pin versus the project's 1.4.4 gate and align its mutable action tags/checkout credential handling with the existing CI policy (#237/#246). This is a new workflow, not part of the mechanical source move.

Coordination with #244

We will keep the owner-only permissions fix separate, as requested. Its integration needs core/config/paths.ts, core/logfmt/publish.ts, store/lock.ts, store/files/snapshots.ts, portable/export.ts, and both status/payload.ts and status/write.ts, plus relocated test/helper imports. A plain conflict resolution is insufficient: some automatic merges preserve stale relative imports. No need to fold that behavior change into this refactor.

@abogartz

abogartz commented Nov 1, 2026

Copy link
Copy Markdown
Owner Author

Windows CI triage: runner flake, not the restructure

The first test-windows run (attempt 1) failed with 7 test failures + 4 Unhandled error between tests in concurrency.test.ts / lifecycle-evidence.test.ts. Rerunning the same SHA (gh run rerun) is green — all four jobs pass: https://github.com/abogartz/opencode-self-improvement/actions/runs/41342522085

Why it is not this diff:

  • The racing/supersede write path (appendLog / writeAtomic / handoverRename) is byte-identical to main (verified by diffing the split modules against main:src/logfmt.ts).
  • Timing, not logic: supersede racing > no row is lost took 5555 ms on the failed run vs 550 ms on the green run — the Windows worker ran ~10x slow, Bun's default hook timeouts fired, and the remaining tests in that worker failed instantly as the afterEach cleanup raced the wedged tasks (that is the ENOENT/ENOTDIR evidence-append noise; the same fail-soft lines appear in green runs too, logged (ignored)).
  • No module-state duplication introduced: all same-named top-level declarations (IS_WINDOWS, SESSION_CAP, …) already existed twice on main.

Fits the known timing-sensitivity family in #245 (parallel Windows workers vs 5s default hook budgets). The one test that was already hardened for this ("a concurrent reader…", 30s override) still tripped only because Bun applies the default 5s to beforeEach/afterEach hooks — tracked in #245 as the hook-timeout hardening follow-up rather than widening this refactor's diff.

@abogartz abogartz left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Thanks — R1 was real and is fixed; the non-blocking item was already dropped.

R1 — sweep catalog re-anchored in 6bc6b8f (now the tip). Every mutant keeps its exact find/replace region; only file: moved to the module that now owns the anchored declaration. Beyond the one-to-one moves, the placements that follow a declaration rather than a filename:

  • supersede-rmw-nolock → store/files/snapshots.ts (its anchor is stampRow, which lives there and is still what markSuperseded calls at supersede.ts:109);
  • snapshot-overwrite → store/files/snapshots.ts (claimSnapshot);
  • the calibration plant → core/logfmt/format.ts (quote());
  • read-path guards (blocklist-poison-filter-off, malformed-ts-guard-and, row-ts-any) → store/files/load.ts; visibility pair → store/model/visibility.ts; inject-one-token-shared → recall/score.ts; inject-frontier-uncapped → inject/digest.ts.

Verified on the final tree: bun scripts/test-sweep.ts --validate — all 45 patterns (incl. plant) apply to exactly one site; --selftest — plant killed deterministically (killed (1/1, 71.8s)). Full merge gate green on push.

windows-debug.yml — dropped in 6e2584a before this reply; the temporary Bun 1.3.5 pin and mutable tags left with it. Head now has no workflow changes at all.

CRLF @covers parser — your diagnosis is exactly right, with the underlying mechanism worth recording: . never matches \r and $ without /m requires end-of-string, so /@covers\s+(.+)$/ cannot match a CRLF line at all. Fixed directly on #247 (52df854) with source.split(/\r?\n/), proven red→green by converting the e2e tree to CRLF and back; #248 rebased onto it and keeps the fix in its rewritten scanner.

Rebase onto the new #247 head was clean; both heads re-ran the full gate (tsc/biome/unit 842/e2e 30).

@WhollyMindless WhollyMindless left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Round 2: APPROVED at 6bc6b8f — supersedes my changes requested

Thanks for the detailed reply. Independently rechecked on Windows / Bun 1.4.4:

  • --validate: all 45 mutation patterns, including the plant, apply to exactly one site.
  • Catalog AST comparison against the previously reviewed tree confirms that only file targets changed; find/replace expressions and scoring logic are preserved.
  • --selftest: clean baseline 843 pass / 0 fail / 11 skip (72.2s); calibration plant killed 1/1 (98.0s), exit 0. This was the calibration run, not a full mutation sweep.
  • bun test ./e2e/coverage.test.ts: 4 pass / 0 fail in the Windows CRLF checkout. The inherited parser problem is fixed.
  • Temporary debug workflow removed. No production src/ delta since my prior review; all four hosted checks are green at this head.

R1 and the cleanup notes are closed. #244 remains a separate behavior change to adapt to the final layout after the refactor settles.

Performance follow-up: I also ran six alternating full Windows unit-suite trials on the pre-refactor 054815a and the exact CI SHA ef6a397 (three each, Bun 1.4.4, four workers). Suite times were 24.09–25.67s and the cited race test 487–548ms, so I could not reproduce the 10x spike locally. All three refactor runs passed; one base run had three short-timeout failures, distinct from the hosted hook-timeout cascade. The hosted logs do confirm 5555.85ms vs 529.06ms for the race test, but the rerun changed runner image from 20261021.278.1 to 20261030.294.1. That is an environmental confound, not proof of its cause. #245 remains the appropriate follow-up for hook budgets/cleanup under load; these local results cannot rule out a load-dependent regression.

Every module now lives in a folder named for its domain, and files are named
for the concept they own instead of carrying domain prefixes. The split is
mechanical: declaration bodies moved verbatim, and the full unit (842) and
e2e (30) suites pass identically on the restructured tree.

Layout:
- core/  shared kernel: types, state, runtime, time, tokenize, lru, config/, logfmt/
- store/ the durable store: model/, files/ (load, append, supersede, target,
  prune, deletions, snapshots), lock, undo, quarantine/, tombstones/,
  containment, blocklist, sanitize, secrets
- gate/  the write gate (gate.ts) and the live-call resolver
- identity/ host event adaptation and repo identity
- inject/ rendering, digest, budget, version, anchor, pull, epochs, attribution
- recall/ scoring, relevance, shared terms
- capture/ prompt, transcript, candidates, lag, triggers
- portable/ export, import, decay
- evidence/, hits/, consolidate/, init/, command/, status/, tools/, viewer/, tui/

Mechanical rules: memory.ts, inject.ts, status.ts, capture.ts, portable.ts,
init.ts, consolidate.ts, logfmt.ts, config.ts and tombstones.ts were split
into concept files; the remaining cohesive modules moved whole. Schema moved
to tools/schema.ts, the TUI panel to tui/panel.tsx (package export ./tui
updated), and the recall scorer to tools/recall.ts earlier on.

Not behavior-preserving only in one spot: src/command/ensure.ts resolves the
packaged command templates one level deeper (src/command/ vs src/), so the
template path gained a '..' segment — the same collision the restructure is
meant to surface.

Tripwires and gates moved with the code: negative-eval's appendMemory
allowlist names the new files and skips comment prose; e2e coverage parses
registrations from the whole src/ tree; the harness TUI path follows
tui/panel.tsx.
The mega restructure moved every file the mutation catalog names; each
find/replace region is unchanged and now points at the module that owns
the anchored declaration (stampRow -> store/files/snapshots.ts, quote()
-> core/logfmt/format.ts, the append choke point -> store/files/append.ts,
and so on). --validate confirms all 45 patterns apply to exactly one site.
@abogartz
abogartz force-pushed the refactor/domain-structure branch from 6bc6b8f to 9e736da Compare November 1, 2026 20:39
@abogartz
abogartz changed the base branch from refactor/tool-registry to main November 1, 2026 22:02
@abogartz
abogartz merged commit 88c3c6c into main Nov 1, 2026
4 checks passed
@abogartz-opencode-self-improvement

Copy link
Copy Markdown

🎉 This PR is included in version 0.15.5 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants