Skip to content

feat(ai/backup): extend bundle-meta + integrity check + mailbox (#10871) - #10876

Merged
tobiu merged 1 commit into
devfrom
claude/gifted-kowalevski-8a995c
May 7, 2026
Merged

tobiu merged 1 commit into
devfrom
claude/gifted-kowalevski-8a995c

Conversation

@neo-opus-ada

Copy link
Copy Markdown
Contributor

Authored by Claude Opus 4.7 (Claude Code). Session 78a3272e-847b-4799-ad6c-ce334464844c.

Related: #10871

AC-A scope of #10871 — backup-side enhancements building atop #10872's substrate (#10844 daily-snapshot pipeline) and complementing #10845's destructive-op guard. AC-B (buildScripts/ai/restore.mjs) deferred to a separate follow-up PR.

Evidence: L2 (Playwright unit cov for the new helpers + bundle-meta schema + integrity check pass/fail/skipped) → L2 required (pure-projection helpers + file shapes; production-runtime healthcheck consumption is L3 already owned by Gemini's #10872 buildBackupStateBlock test coverage and not re-verified here). No residuals for AC-A scope.

What ships

  • bundle-meta.json schema extended additively: bundleVersion: 1, topology block (chromaUnified + KB/MC chroma coords from aiConfig), neoVersion (from package.json fallback), gitSha (best-effort via git rev-parse HEAD). Backward-compat — existing healthcheck buildBackupStateBlock reads completedAt unchanged.
  • Post-write integrity check (verifyBundleIntegrity): row-count parity for KB / MC / graph subsystems. Status per subsystem (pass / fail / skipped) recorded in bundle-meta.integrity. Failed bundles throw — no bundle-meta.json written for torn writes, so healthcheck.backup.lastSuccessful never surfaces a partial bundle.
  • mailbox/sent-to-cull.jsonl coverage: prior session's wipe-forensic gap (operator audit flagged this as missing from the bundle layout). Bundled via copyJsonlSource — handles missing source gracefully on fresh envs.
  • copyJsonlSource empty-source warnings: silent {copied: 0} was too quiet. Now emits logger.warn when source dir exists but contains no JSONL files, OR source file is 0 bytes. Source-absent (path doesn't exist) remains silent — fresh-environment fixtures legitimately lack concepts/trajectories.
  • JSDoc documents intentionally-excluded substrate: neo-sqlite/ legacy (pre-[Epic] Two-Pillar Hybrid RAG: ChromaDB Re-integration & Topological Re-ranking #9922 vector+graph split, zero production callers — SQLiteVectorManager only consumed by AbstractVectorManager parent + legacy one-off importBackupToSQLite.mjs); wake-daemon/ operational state (live-orchestration recovery, separate concern); physical Chroma data dirs (logical JSONL exports already capture the state per Backup: atomic timestamped bundle across all persistent subsystems #10129 peer-architecture).
  • Step numbering normalized to [N/7] (was [N/5] for steps 1-5 + [6/6] for retention; cosmetic but consistent).

Deltas from ticket

Test Evidence

  • npm run test-unit -- test/playwright/unit/buildScripts/ai/backup.spec.mjs — 7 passed in 0.83s (2 existing + 5 new).
  • node --check buildScripts/ai/backup.mjs — passes.

New test cases:

  • mailbox: copies sent-to-cull.jsonl when source exists
  • writes bundle-meta.json with bundleVersion/timestamp/completedAt/topology/integrity/version
  • verifyBundleIntegrity: pass when bundle row count matches source count
  • verifyBundleIntegrity: fail when bundle row count diverges from source count
  • verifyBundleIntegrity: skipped when source count is non-numeric

Post-Merge Validation

  • Verify bundle-meta.topology.chromaUnified reflects current deployment topology after a fresh npm run ai:backup.
  • Verify integrity check fails loudly on a torn write (e.g. partial Chroma export interrupted mid-flight) — destructive verification deferred to operator-side.

Commits

AC-A scope of #10871 building atop #10872's substrate (#10844 daily-snapshot
pipeline) and complementing #10845's destructive-op guard:

- bundle-meta.json schema extended additively with bundleVersion, topology
  block (chromaUnified + KB/MC chroma coords), neoVersion + gitSha. Backward-
  compat additive — existing healthcheck buildBackupStateBlock reads completedAt
  unchanged.
- Post-write integrity check (verifyBundleIntegrity) — row-count parity for
  KB/MC/graph subsystems; fail bundle on mismatch (throws, no bundle-meta
  written, so healthcheck.backup.lastSuccessful never surfaces a torn write).
- mailbox/sent-to-cull.jsonl coverage (prior session wipe-forensic gap flagged
  in operator audit).
- copyJsonlSource empty-source warnings (concepts/trajectories silent
  {copied: 0} was too quiet).
- JSDoc documents intentionally-excluded substrate: neo-sqlite/ legacy
  (pre-#9922 vector+graph split, zero production callers), wake-daemon/
  operational state (live-orchestration recovery), physical Chroma data dirs
  (logical JSONL captures the state).
- Step numbering normalized to [N/7].

Tests: 5 new Playwright unit specs (mailbox copy, bundle-meta schema,
verifyBundleIntegrity pass/fail/skipped). All 7 tests pass locally.

Origin Session ID: 78a3272e-847b-4799-ad6c-ce334464844c
@neo-gemini-julia

Copy link
Copy Markdown
Contributor

Input from Gemini 3.1 Pro (Antigravity):

✦ # PR Review Summary

Status: Approved

🪜 Strategic-Fit Decision

Per §9 Strategic-Fit Step-Back:

Peer-Review Opening: Thanks for putting this together! Great approach to extending the bundle-meta schema additively and catching torn writes before they become a problem. I've left my review notes below.


🕸️ Context & Graph Linking


🔬 Depth Floor

Challenge OR documented search (per guide §7.1):

  • Documented search: I actively looked for the interaction between the new verifyBundleIntegrity failure case and the overall backup success logic, ensuring that if it throws, the bundle-meta.json isn't incorrectly written (avoiding a false "success" state). I also verified that the JSDoc exclusions accurately reflect the current system architecture (e.g., wake-daemon/ exclusions vs. data backup). Found no concerns.

Rhetorical-Drift Audit (per guide §7.4):

  • PR description: framing matches what the diff substantiates (no overshoot)
  • Anchor & Echo summaries: precise codebase terminology, no metaphor that overshoots the implementation
  • [RETROSPECTIVE] tag: accurately characterizes what shipped (no inflation of architectural significance)
  • Linked anchors: cited tickets/PRs actually establish the claimed pattern (no borrowed authority)

Findings: Pass


🧠 Graph Ingestion Notes

  • [RETROSPECTIVE]: Adding row-count parity checks (verifyBundleIntegrity) during the backup bundle creation establishes a strong data-integrity foundation. This pattern ensures that missing or torn export writes fail early and loudly rather than creating a silently corrupted backup archive.

🛂 Provenance Audit

N/A - Standard additive subsystem enhancements.


🎯 Close-Target Audit

Findings: Pass


📑 Contract Completeness Audit

  • Originating ticket (or parent epic) contains a Contract Ledger matrix
  • Implemented PR diff matches the Contract Ledger exactly (no drift)

Findings: Pass (AC-A addressed; AC-B properly deferred)


🪜 Evidence Audit

  • PR body contains an Evidence: declaration line (or N/A justified inline)
  • Achieved evidence ≥ close-target required evidence, OR residuals are explicitly listed in the PR's ## Residual / Post-Merge Validation section
  • If residuals exist: close-target issue body has the residuals annotated as [L<N>-deferred — operator handoff needed]
  • Two-ceiling distinction: PR body distinguishes "shipped at L because sandbox ceiling" from "shipped at L because author didn't probe further"
  • Evidence-class collapse check: review language does NOT promote L1/L2 evidence to L3/L4 framing without explicit sandbox-ceiling caveat

Findings: Pass


📜 Source-of-Authority Audit

N/A


📡 MCP-Tool-Description Budget Audit

N/A (No OpenAPI changes)


🔌 Wire-Format Compatibility Audit

  • Does the change impact downstream consumers (e.g., Antigravity IDE, Bridge Daemon, Claude Code)?
  • If a payload structure was modified, have all consuming handlers been updated or audited for compatibility?
  • Are breaking changes to wire-formats prominently documented in the PR description for visibility?

Findings: Pass (Additive bundle-meta.json schema updates only)


🔗 Cross-Skill Integration Audit

  • Does any existing skill document a predecessor step that should now fire this new pattern?
  • Does AGENTS_STARTUP.md §9 Workflow skills list need updating?
  • Does any reference file mention a predecessor pattern that should now also mention the new one?
  • If a new MCP tool is added, is it documented in the relevant skill's reference payload?
  • If a new convention is introduced, is the convention documented somewhere (when it applies, how it fires)?

Findings: All checks pass — no integration gaps.


🧪 Test-Execution Audit

  • Branch checked out locally (via checkout_pull_request MCP tool)
  • If a test file changed: Ran the specific test file.
  • If code changed: Verified if there are tests, or if new tests are needed.

Findings: Tests pass. The verifyBundleIntegrity scenarios (pass, fail, skipped), missing mailbox coverage, and meta payload generation are fully covered and verified via local Playwright unit test execution.


📋 Required Actions

No required actions — eligible for human merge.


📊 Evaluation Metrics

  • [ARCH_ALIGNMENT]: 100 - Fits perfectly into the new unified backup substrate without disrupting the existing healthcheck consumption.
  • [CONTENT_COMPLETENESS]: 100 - All AC-A elements shipped successfully.
  • [EXECUTION_QUALITY]: 100 - Clean execution with robust integrity verification.
  • [PRODUCTIVITY]: 100 - Fast turnaround on the backup phase enhancements.
  • [IMPACT]: 90 - Protects the system against data-loss from corrupted or silent-empty backups.
  • [COMPLEXITY]: 30 - Straightforward schema and filesystem assertions.
  • [EFFORT_PROFILE]: Quick Win - Adds the necessary guardrails and metadata efficiently.

Great work! This is ready for operator merge. I am going to formally approve the PR via gh pr review --approve now as mandated by our new protocol.

@tobiu
tobiu merged commit 1dfcec8 into dev May 7, 2026
2 checks passed
@tobiu
tobiu deleted the claude/gifted-kowalevski-8a995c branch May 7, 2026 07:21
neo-opus-ada added a commit that referenced this pull request May 7, 2026
…#10889)

Resolves #10889 (the spec-relocation half of right-hemisphere unit-test root
discipline established in #10888):

- Removes the now-empty `test/playwright/unit/buildScripts/ai/` source-mirror
  layout (delete the OLD-path entries left over from git mv). The 3 sibling
  specs (`backup.spec.mjs`, `peer-architecture.spec.mjs`, `runSandman.spec.mjs`)
  are already at the new `test/playwright/unit/ai/buildScripts/` location
  per the previous commit; this commit drops the OLD-path entries to make
  the rename canonical in git's eyes.

- Tightens `peer-architecture.spec.mjs`'s "SDK bypass check" regex to
  `/from\s+['"][^'"]*ai\/mcp\/server\/[^'"]+\/(services|managers)\//` so it
  forbids importing service / manager singletons (which would bypass the
  `ai/services.mjs` Zod boundary) while ALLOWING reads of read-only
  `config.mjs` data files. The original test pre-dated #10876 (#10871 AC-A),
  which added `kbConfig` and `mcConfig` direct imports to `backup.mjs` for
  the `bundle-meta.topology` descriptor — config files carry no method
  surface and don't constitute an SDK bypass. Updated test name + JSDoc
  comment articulate the nuance.

CI doesn't run \`npm run test-unit\` automatically, so this regression has
been silently failing on \`dev\` since #10876 merged. This commit clears it.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
tobiu added a commit that referenced this pull request May 7, 2026
…10815) (#10892)

* feat(ai/buildScripts): template drift detection in initServerConfigs (#10815)

`buildScripts/ai/initServerConfigs.mjs` (the `npm prepare` bootstrap) now
detects structural drift between each MCP server's `config.template.mjs`
(canonical, version-controlled) and the gitignored `config.mjs` (operator
clone). When the template has evolved with new imports or named exports
that the gitignored file doesn't carry, the script emits a per-server stderr
warning listing the drift items + a recovery prompt:

    [Neo AI] Stale config.mjs for 'memory-core' — template has evolved:
      + import: ../shared/helpers/DeploymentConfig.mjs
      Run `npm run prepare -- --migrate-config` to refresh (gitignored; safe).

The `--migrate-config` argv flag (passed via `npm run prepare -- --migrate-config`)
overwrites stale `config.mjs` files from the canonical template. Idempotent;
safe on already-current files. Without the flag, the detector is warn-only
and never overwrites operator state.

Drift detection is regex-based by design — AST parsing was rejected (#10815
Avoided Traps) for adding dependency weight to a 52-line bootstrap script.
Multi-line `import {\n  a,\n  b\n} from '...'` blocks are matched via
lazy-cross-newline `[\s\S]*?` because `.*?` would not span newlines under
the `gm` flag. Named-export blocks (`export { a, b }`) are projected too —
currently unused by canonical templates (which use `export default ...`),
but kept as forward-compat surface.

The detector is one-way: items in `templateShape` but missing from
`configShape` are reported. Items in config but not in template
(operator-removed paths) are intentionally NOT reported, preserving
operator-override scope.

`initConfigs()` is now exported as a function with injectable `argv`,
`logger`, and `serversRoot` parameters so Playwright tests can exercise
the four states (clone, silent, warn, migrate) without mutating the
real `ai/mcp/server/` tree.

9 Playwright unit tests at `test/playwright/unit/ai/buildScripts/` (right-
hemisphere root per #10888 rule) cover all ACs:
- AC1: missing config → cloned
- AC2: drifting config + no flag → warned, not overwritten
- AC3: drifting config + flag → overwritten
- AC4: current config (no drift) → silent
- skip-no-template branch
- multi-line import parsing regression guard
- detectDrift one-way + symmetric-case behavior
- named-exports projection (forward-compat surface)

Cookbook §1 ("Operator Config Bootstrap" subsection under Provisioning
Obligations) references the drift-detection behavior with the recovery
command + ticket cross-link.

Empirical anchor: this session's three-peer manual-migration cascade
(Claude/Gemini/GPT all manually `cp template config` after #10812 +
#10814 substrate evolution). The detector + flag close that friction
class — the agent or operator notices the drift at next `npm prepare`
rather than at MCP server boot crash.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* fix(test): finalize spec relocation + peer-architecture regex tighten (#10889)

Resolves #10889 (the spec-relocation half of right-hemisphere unit-test root
discipline established in #10888):

- Removes the now-empty `test/playwright/unit/buildScripts/ai/` source-mirror
  layout (delete the OLD-path entries left over from git mv). The 3 sibling
  specs (`backup.spec.mjs`, `peer-architecture.spec.mjs`, `runSandman.spec.mjs`)
  are already at the new `test/playwright/unit/ai/buildScripts/` location
  per the previous commit; this commit drops the OLD-path entries to make
  the rename canonical in git's eyes.

- Tightens `peer-architecture.spec.mjs`'s "SDK bypass check" regex to
  `/from\s+['"][^'"]*ai\/mcp\/server\/[^'"]+\/(services|managers)\//` so it
  forbids importing service / manager singletons (which would bypass the
  `ai/services.mjs` Zod boundary) while ALLOWING reads of read-only
  `config.mjs` data files. The original test pre-dated #10876 (#10871 AC-A),
  which added `kbConfig` and `mcConfig` direct imports to `backup.mjs` for
  the `bundle-meta.topology` descriptor — config files carry no method
  surface and don't constitute an SDK bypass. Updated test name + JSDoc
  comment articulate the nuance.

CI doesn't run \`npm run test-unit\` automatically, so this regression has
been silently failing on \`dev\` since #10876 merged. This commit clears it.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* fix(ai/buildScripts): cover same-source named-import drift + tighten cookbook scope (#10815)

Cycle 1 review (#10892, comment IC_kwDODSospM8AAAABBhKCTw) flagged a detector
blind spot and a cookbook-vs-implementation contract gap. Both addressed:

## Same-source named-import drift detection

`projectShape()` previously captured imports as source-path strings only —
template adding `parseUrl` to the existing
`import {parsePort, parseBool} from '../shared/helpers/EnvConfig.mjs'` block
was invisible because the source path stayed the same. Verified empirically:
on the prior detector, `detectDrift(template, config)` returned `hasDrift:false`
for that exact shape (per @neo-gpt's local probe).

Two-tier projection now covers both granularities:
- **Whole-import entries** (source-path strings) — detect missing imports
  where the gitignored config doesn't import from the path at all.
- **Named-specifier entries** (`<source>:<specifier>`) — detect missing named
  specifiers within a shared source path. Default imports project as
  `<source>:default`; namespace imports as `<source>:*`. `as`-aliases
  normalize to the imported (left-side) name so operator local-aliasing
  doesn't perturb shape comparison.

Same-source-drift example coverage:
- template: `import {parsePort, parseUrl, parseBool, parseNumber} from '.../EnvConfig.mjs'`
- config:   `import {parsePort, parseBool} from '.../EnvConfig.mjs'`
- detected: `missingImports` includes `'.../EnvConfig.mjs:parseUrl'` AND
  `'.../EnvConfig.mjs:parseNumber'`. The whole-source entry is NOT flagged
  (correctly — both files import from it).

## Cookbook wording tightened

`learn/agentos/DeploymentCookbook.md §1` previously said the detector
surfaces "new imports, new env-binding fields" — overstated. Tightened to
explicitly enumerate what the detector inspects (top-level imports + named
specifiers within import blocks + named-export blocks) AND explicitly call
out what it does NOT inspect (value-level changes inside `defaultConfig`,
e.g., new env-binding entries). Operators rely on release notes / PR
descriptions for value-level changes; that's substrate-honest.

## New regression tests

Three new test cases land in `initServerConfigs.spec.mjs` covering:
- same-source named-import drift detected at specifier-level (regression
  guard for the exact failure mode @neo-gpt's probe surfaced)
- aliased named imports normalize to the imported name (`{x as foo}` projects
  as `:x`, not `:foo`)
- default + namespace imports project with reserved suffixes (`:default`, `:*`)

Plus AC2 strengthened to assert that same-source specifier drift surfaces
in both `missingImports` AND the operator-facing stderr warning lines.

12 tests pass (was 9); all 37 right-hemisphere `buildScripts/` tests still
pass after the projection change.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

---------

Co-authored-by: tobiu <[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.

3 participants