Skip to content

feat(store): add the local template package store - #248

Merged
Antruly merged 2 commits into
mainfrom
feat/236-template-store-p2
Oct 18, 2026
Merged

Antruly merged 2 commits into
mainfrom
feat/236-template-store-p2

Conversation

@Antruly

@Antruly Antruly commented Oct 18, 2026 •

Copy link
Copy Markdown
Owner

Summary

Part of #236. P1 (the uvp.template/1 schema and validator) landed in #244/#245; this is P2, the local store.

It adds src/application/TemplateStore.ts:

  • Root: UVP_TEMPLATE_HOME, else ~/.uvp/templates.
  • Read: a package directory is read into the observations the domain validator asks for (recursive files/, per-file SHA-256, symlink/binary observations, per-file and total limits); the validator remains the owner of the format.
  • Import: strict validation, copy to .tmp, re-validate the copy, stage the store metadata, then rename the tree into place and publish the metadata; a lock file serializes mutations. If publication fails after the rename, the new tree is removed (fresh import) or the previous tree is restored from .trash (replace), so a failed import leaves no package and a failed replace loses no version.
  • Replace: id@version is immutable; an existing pair is refused unless replace is explicit. A replace moves the old tree to .trash before the new rename and rolls back on failure; a failed trash cleanup is returned as retained.
  • List/get: readable packages plus a corrupt[] list with the reader's problems; get re-verifies file bytes against the manifest.
  • Remove: removes one version or a whole id through quarantine, reporting a retained trash directory if cleanup fails.
  • Q6: a package whose only problems are license/provenance is admitted only with allowUnverified, marked unverified: true in store metadata and never presented as verified. The source manifest is stored as authored; the relaxed validation uses a patched copy only to check the rest. The shared registry ([Feature] Remote template registry client: search, sync, download, cache, provenance #239) does not use this path.
  • Q9: versions are immutable; replace is explicit; no implicit overwrite.

No tool contract, CLI/MCP surface, search, export, scan, registry, or network call is added; those are P3/P4/P5. Generated workspaces and uvp.json are untouched.

Contract and boundary impact

  • Earliest changed layer: application workflow (local template store), using the domain validator.
  • Tool contracts: none in this PR.
  • Effects: the code reads and writes the local store. No network, process spawn, or credential.
  • Generated code/configuration: none.

Evidence and regression coverage

  • Tests added: src/application/TemplateStore.test.ts — 16 cases covering root resolution, import/list/get, duplicate/replace, byte tampering, unverified admission, non-licence problems under allow_unverified, missing README/LICENSE, unexpected top-level files, symlinks (skipped on Windows with the host reason), lock contention, corrupt entries, removal, and the two post-rename metadata failures (fresh import and replace).
  • Commands and results at 7b062a3:
npm run typecheck                                              exit 0
npm run test:local -- src/application/TemplateStore.test.ts    16 passed
npm run test:local                                             exit 0 (55 test files / 12 projects; 1250 passed, 3 Windows-only skips, named)
npm run verify:test-discovery                                  80 files, services=18
node scripts/lint.mjs                                          exit 0 (two warnings in TemplateStore.ts: pre-existing unused `FileWalk` interface; file over the 500-line limit)
npx oxfmt --check                                              2 files formatted
  • Remaining proof gaps:
    • zip import/export, search, the secret/PII scan, and the tool contracts are not in this PR (P3/P4/P5).
    • Reads are not locked: a read racing a replace can report not_found for one call; that is deliberate and reported, not retried into a stale answer.
    • The full npm run check:pr was not run locally; CI runs it for this PR. The commands above are what ran here; no claim is made about lanes they do not cover.
    • The two post-rename failure tests force the metadata rename to fail by placing a directory at the metadata destination; they exercise the rollback, not a disk-full or permission failure at every point in the sequence.

Review follow-up

The blocking finding in the review at 9672605 — a failed metadata write after the tree rename left a package behind, and an unverified package then failed its own get — is fixed at 7b062a3. Metadata is staged before any tree move, so an unwritable metadata directory fails with the store untouched; if the final publication fails, the fresh tree is removed or the replaced tree is restored, and a failed restoration is named. Both paths have a regression test.

Author readiness

Human owner: @Antruly

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

Draft. The following are left for the owner and review; none is asserted here.

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover the changed observable behaviour and its meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI or MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

Add P2 of #236: resolve UVP_TEMPLATE_HOME/~/.uvp/templates, read a package directory into the observations the domain validator asks for, import atomically through .tmp with a lock, list/get with corruption reporting, replace an id@version only with an explicit flag, remove through quarantine, and admit an unverified package only when allow_unverified is set (Q6). The id@version pair is immutable (Q9).

No tool contract, search, export, or network call is introduced.

Refs #236.

Assisted-by: Claude Code (direction-lead)
@Antruly Antruly added the ai-assisted Substantial agent involvement, as CONTRIBUTING requires it be disclosed label Oct 18, 2026
@Antruly

Antruly commented Oct 18, 2026

Copy link
Copy Markdown
Owner Author

Review — feat(store): add the local template package store

Reviewed at head 9672605 against base 23485a2 (the merge of #247). One blocking finding, then non-blocking notes. The design is sound: read the directory into the observations the domain validator asks for, let the validator own the format, stage and re-validate, and serialize mutations. What I found is a hole in the stated atomicity, not in the reading or validation.

Blocking — a failed import can leave a package, contradicting the module's own contract

importTemplatePackage renames the staged tree into place and then writes the store metadata (TemplateStore.ts:615-647). If writeStoreMetadata fails, the import throws io_error but the tree stays. The module header says "A failed import leaves no package" (line 50) and the PR body repeats it; #236's acceptance criterion is "store atomicity".

I reproduced it: an unverified package, .meta present but not writable (chmod 0o500), importTemplatePackage({allowUnverified:true}) →

import error code: io_error
package left behind: true
get code: invalid_package

The package is installed but unreadable: get reads no metadata, so it re-validates strictly and refuses the very package the import was told to admit. A retry with the same options then returns template_exists (without replace). For a verified package the tree stays readable, but the caller is still told the import failed while the package exists — the retry conversation is the same.

Suggested directions (either closes it): write the metadata into a temporary name inside .meta/<id>/ before the tree rename and rename it into place last, rolling the tree rename back if that final step fails; or treat a metadata-write failure like a failed tree rename — move the target back to staging/trash so the "no package" invariant holds. Whichever way, the failure path deserves a test; none of the 14 cases exercises a failure after the rename.

What I verified independently

  • Validation is the domain validator's, not a second interpretation. The store builds observations (recursive files/, SHA-256, symlink/binary flags) and hands them in; strict and relaxed (allowUnverified) go through the same validateTemplatePackage.
  • Path safety. id is the schema's lowercase slug and version a parsed SemVer, so path.join(root, id, version) cannot traverse; assertIdentifier also refuses ./../separators for lookups.
  • Package shape. files/ must be a real directory; top-level entries are whitelisted; symlinks, FIFOs and unknown entries are refused; README is required; LICENSE is required for a strict package; previews must be the manifest's.
  • Unverified handling (Q6). Only license*/provenance* problems are admitted; the authored template.json is what lands on disk; the relaxation uses a patched in-memory copy; licence and provenance are omitted from the returned metadata.
  • Failure paths that are covered pass as claimed: duplicate without replace → template_exists; byte tampering → invalid_package and a corrupt[] entry; a held lock → store_locked; corrupt entry listing; remove then not_found.
  • Gates at this head. Focused suite 14 passed, tsc --noEmit clean, oxfmt --check clean on both files, verify:test-discovery 80 files, knip clean. CI: all applicable checks pass.

Non-blocking (my judgement)

  1. A file is read whole before its size is checked. walkFiles does readFile and only then compares byteLength with maxFileBytes (line 311-319), and the manifest is readFiled with no bound at all. A source directory with a multi-gigabyte file OOMs the process instead of being refused — stat first (or hash the stream) would make the limit actually bound memory. This matters more once P3/P5 make the source something other than a hand-made local directory.
  2. digest in the store metadata is written and never read. readStoreMetadata returns it, but get/list use only unverified and re-derive the digest from the manifest. Either verify it on read (it would detect a metadata/tree disagreement) or drop the field.
  3. The staged copy's id/version are not checked against the path they are written to. id/version are taken from the first validation of the source; the staged re-validation can return a different manifest, and the tree is then stored (and reported by toStored) under the first pair. A source being rewritten mid-import can produce a directory whose manifest names another id@version. Comparing staged.manifest.id/version with id/version would close it.
  4. The stale-lock path has the classic ABA race. Two waiters that both see a >10-minute-old lock can both unlink it; the second unlink can delete the lock the first waiter just created, and the unconditional unlink in finally then deletes whatever lock is there. Low probability on a local store, but the comment says "the first process wins", which is only true without the stale branch.
  5. A failed rollback of a replace is not reported. If rename(trash, target) fails after rename(staging, target) failed, the old tree remains in .trash and the caller gets an io_error with no path to it; retained is only set for cleanup failures.
  6. Two new lint warnings in the new file. npm run lint exits 0 but reports FileWalk declared and never used (TemplateStore.ts:281) and the file at 653 lines against the 500 limit. The PR's "existing warnings only" is not accurate for this file; the unused interface is dead code.
  7. Coverage of the failure paths the header promises is thin. retained, the replace rollback, and a post-rename failure (the blocking finding) have no test; the 14 cases cover the happy paths and the reader's refusals well.
  8. Unverified admission does not require a LICENSE file at all. A package with no license/provenance and no LICENSE is admitted with allowUnverified (readTopLevel requires README only; the LICENSE check is inside the strict branch). That may be the intent of "unverified", but [Feature] Standard template package format and a local template store with AI-facing CRUD/search #236's layout lists LICENSE as part of a package — worth confirming the boundary is deliberate.

I have not marked this ready or approved; the blocking finding above needs a change first. I'll re-review if the head moves.

The import renamed the staged tree into place and only then wrote the
store metadata. If that write failed, the caller was told the import
failed while the package stayed in the store; for an unverified package
the next get re-validated strictly and refused the package the import had
just admitted.

Stage the metadata before moving any tree so an unwritable metadata
directory fails while the store is untouched, and publish it after the
rename. If publication still fails, remove the new tree (fresh import) or
restore the previous tree from trash (replace); a failed restoration is
named rather than reported as a clean failure. Two tests pin both paths.

Refs #236, #248.

Assisted-by: Claude Code (direction-lead)
@Antruly

Antruly commented Oct 18, 2026

Copy link
Copy Markdown
Owner Author

Re-review — the blocking finding is fixed

Reviewed the fix commit 7b062a3 (fix(store): roll back a package when metadata cannot be published) against my review of 9672605 above. No blocking finding remains.

The approach is the one that closes the hole rather than hiding it: metadata is staged into .meta/<id>/.<uuid>.json before any tree move, published by a single rename after the tree is in place, and a failed publish now has a real rollback — the new tree is dropped (new version) or the old tree is restored from .trash (replace). The invariant the module header promises is now the invariant the code enforces.

I reproduced the original failure and two adjacent ones independently (throwaway probe, deleted afterwards; git status clean):

Scenario Result at 7b062a3
Original repro: .meta present but not writable (chmod 0o500), unverified import io_error; get → not_found; no files under the store at all
New version, metadata target blocked by a directory io_error; get → not_found; list → [], corrupt: []; only the caller's own blocker remains
Replace, metadata target blocked by a directory io_error; get returns the old bytes and the old digest; no stray metadata temp

The two new tests (leaves no package when metadata cannot be published..., restores the previous package when a replace cannot publish metadata) exercise exactly those paths and fail on the old code. Focused suite 16 passed, tsc, oxfmt, lint and verify:test-discovery clean; CI at this head: every applicable job passes (the two skipped jobs are the libuvcpp/MSVC lanes selected off for this change).

Non-blocking, from the first review (unchanged)

The eight notes recorded above still stand as recorded; the fix does not touch them. The ones that matter most for later slices are still the unbounded whole-file read in walkFiles and the stale-lock ABA path — neither is made worse here.

Two small observations on the new code (my judgement, non-blocking)

  1. A failed metadata stage can leave an empty .meta/<id>/ directory. stageStoreMetadata creates the directory before writing the temporary; if the write fails, the temporary is removed and the directory stays. It is invisible to list and to get, so it is harmless debris, not a package.
  2. There is one doubly-failed path left. If the metadata commit fails, rename(target, staging) also fails, and the fallback rm(target) also fails, then the target still holds the new tree while rename(trash, target) cannot restore the old one; the error names the trash path. That needs two unrelated filesystem failures in a row, and the message is accurate about where the old package is, so I would not hold this PR for it — but it is the one route by which the "no package without metadata" invariant could still be bent.
  3. Stray .uuid.json metadata temporaries are not swept after a crash between stage and publish — same debris class as .tmp/.trash, and worth a sweep when the store gets one.

I am marking this ready and approving it for the owner under today's standing authorization.

@Antruly
Antruly marked this pull request as ready for review October 18, 2026 11:56
@Antruly

Antruly commented Oct 18, 2026

Copy link
Copy Markdown
Owner Author

Owner approval. Approved at 7b062a35738fe712a080680c4224efa2687aa981.

Reviewed in this comment after the fix commit. No blocking findings: metadata is staged before any tree move, published by one rename after the tree is in place, and a failed publish now rolls back — new version removed, or the previous tree restored from .trash. I reproduced the original failure and two adjacent ones independently and the store is left with no package in every case; the previous version's bytes survive a failed replace. Focused suite 16 passed, tsc --noEmit, oxfmt --check, lint and verify:test-discovery clean. All applicable checks pass, and readiness is declared (Owned by @Antruly; author readiness declared.).

The non-blocking notes from the first review stand as recorded and do not hold this change. #249 and #250 are stacked on this branch and will need retargeting to main after this merge.

Merging as a merge commit at the exact reviewed head.

Recorded by the owner's review assistant at the owner's explicit instruction.

@Antruly
Antruly merged commit b5abe0b into main Oct 18, 2026
21 of 22 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ai-assisted Substantial agent involvement, as CONTRIBUTING requires it be disclosed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant