create-claude-cabinet 0.45.0 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/README.md +6 -10
  2. package/lib/cli.js +374 -91
  3. package/lib/copy.js +108 -6
  4. package/lib/db-setup.js +122 -17
  5. package/lib/engagement-server-setup.js +34 -9
  6. package/lib/metadata.js +51 -2
  7. package/lib/migrate-from-omega.js +13 -1
  8. package/lib/mux-setup.js +33 -9
  9. package/lib/settings-merge.js +52 -10
  10. package/lib/watchtower-setup.js +230 -0
  11. package/package.json +5 -1
  12. package/templates/cabinet/_cabinet-member-template.md +8 -3
  13. package/templates/cabinet/advisories-state-schema.md +34 -7
  14. package/templates/cabinet/checklist-stats-schema.md +15 -1
  15. package/templates/cabinet/composition-patterns.md +4 -3
  16. package/templates/cabinet/memory-lifecycle-contract.md +135 -0
  17. package/templates/cabinet/pib-db-access.md +13 -0
  18. package/templates/cabinet/skill-output-conventions.md +35 -1
  19. package/templates/cabinet/watchtower-contracts.md +503 -1
  20. package/templates/cabinet/worktree-invocation-contract.md +87 -0
  21. package/templates/engagement/OVERVIEW.md +12 -0
  22. package/templates/engagement/__tests__/engagement.test.mjs +177 -2
  23. package/templates/engagement/__tests__/invoice-doc.test.mjs +195 -0
  24. package/templates/engagement/engagement-preview.mjs +100 -0
  25. package/templates/engagement/engagement-schema.md +240 -0
  26. package/templates/engagement/engagement.mjs +391 -11
  27. package/templates/engagement/pib-db-patches/pib-db-lib.mjs +10 -1
  28. package/templates/engagement/pib-db-patches/pib-db-mcp-server.mjs +5 -44
  29. package/templates/engagement/pib-db-patches/pib-db.mjs +5 -2
  30. package/templates/hooks/action-completion-gate.sh +9 -3
  31. package/templates/hooks/memory-index-guard.sh +17 -11
  32. package/templates/hooks/watchtower-session-start.sh +24 -2
  33. package/templates/mcp/pib-db.json +1 -4
  34. package/templates/mux/__tests__/mux-fail-loud.fixture.sh +44 -0
  35. package/templates/mux/__tests__/station-liveness.fixture.sh +234 -0
  36. package/templates/mux/__tests__/station-liveness.test.mjs +47 -0
  37. package/templates/mux/bin/mux +289 -56
  38. package/templates/mux/config/help.txt +1 -0
  39. package/templates/rules/acknowledge-when-corrected.md +33 -0
  40. package/templates/rules/maintainability.md +11 -0
  41. package/templates/rules/memory-capture.md +26 -4
  42. package/templates/rules/plan-before-bulk-or-irreversible-actions.md +48 -0
  43. package/templates/rules/verify-before-asserting.md +79 -0
  44. package/templates/scripts/__tests__/advisor-pass.test.mjs +238 -0
  45. package/templates/scripts/__tests__/advisories.test.mjs +262 -0
  46. package/templates/scripts/__tests__/ahead-check-origin.test.mjs +355 -0
  47. package/templates/scripts/__tests__/batch-disposition.test.mjs +235 -0
  48. package/templates/scripts/__tests__/claude-churn-authored.test.mjs +90 -0
  49. package/templates/scripts/__tests__/cross-ring-reader.test.mjs +505 -0
  50. package/templates/scripts/__tests__/dx-captures-briefing.test.mjs +169 -0
  51. package/templates/scripts/__tests__/feedback-outbox-flush.test.mjs +232 -0
  52. package/templates/scripts/__tests__/hook-runner.test.mjs +247 -0
  53. package/templates/scripts/__tests__/narrative-corpus.test.mjs +247 -0
  54. package/templates/scripts/__tests__/phase-shim.test.mjs +112 -0
  55. package/templates/scripts/__tests__/qa-handoff-gate.test.mjs +68 -0
  56. package/templates/scripts/__tests__/qa-handoff-merge-state.test.mjs +162 -0
  57. package/templates/scripts/__tests__/resolve-cli.test.mjs +314 -0
  58. package/templates/scripts/__tests__/ring-state-ownership.test.mjs +228 -3
  59. package/templates/scripts/__tests__/ring1-content-detector.test.mjs +168 -0
  60. package/templates/scripts/__tests__/ring1-flagged-actions.test.mjs +135 -0
  61. package/templates/scripts/__tests__/ring1-script-drift.test.mjs +126 -0
  62. package/templates/scripts/__tests__/ring2-queue-reader.test.mjs +80 -0
  63. package/templates/scripts/__tests__/ring2-recall-canary.test.mjs +150 -0
  64. package/templates/scripts/__tests__/ring2-roster-review.test.mjs +311 -0
  65. package/templates/scripts/__tests__/ring2-thread-context.test.mjs +189 -0
  66. package/templates/scripts/__tests__/ring3-chunk-merge.test.mjs +122 -0
  67. package/templates/scripts/__tests__/ring3-close-lenses.test.mjs +359 -0
  68. package/templates/scripts/__tests__/ring3-dedup.test.mjs +467 -0
  69. package/templates/scripts/__tests__/ring3-memory-titles.test.mjs +187 -0
  70. package/templates/scripts/__tests__/ring3-novelty-rescue.test.mjs +148 -0
  71. package/templates/scripts/__tests__/ring3-recent-slice.test.mjs +101 -0
  72. package/templates/scripts/__tests__/ring4-reconcile.test.mjs +393 -0
  73. package/templates/scripts/__tests__/routine-dispatch.test.mjs +312 -0
  74. package/templates/scripts/__tests__/shared-thread-reader.test.mjs +187 -0
  75. package/templates/scripts/__tests__/suppression-ledger.test.mjs +148 -0
  76. package/templates/scripts/__tests__/verify-backfill.test.mjs +103 -0
  77. package/templates/scripts/__tests__/verify-coverage.test.mjs +80 -0
  78. package/templates/scripts/__tests__/watchtower-snapshot.test.mjs +261 -0
  79. package/templates/scripts/__tests__/watchtower-sync.test.mjs +311 -0
  80. package/templates/scripts/load-triage-history.js +5 -2
  81. package/templates/scripts/pib-db-mcp-server.mjs +5 -44
  82. package/templates/scripts/pib-db-path.mjs +61 -0
  83. package/templates/scripts/pib-db.mjs +5 -2
  84. package/templates/scripts/validate-memory.mjs +214 -16
  85. package/templates/scripts/watchtower-advisories.mjs +309 -0
  86. package/templates/scripts/watchtower-build-context.mjs +301 -18
  87. package/templates/scripts/watchtower-cross-ring-reader.mjs +700 -0
  88. package/templates/scripts/watchtower-hook-runner.mjs +422 -0
  89. package/templates/scripts/watchtower-lib.mjs +447 -2
  90. package/templates/scripts/watchtower-narrative-corpus.mjs +385 -0
  91. package/templates/scripts/watchtower-phase-shim.mjs +171 -0
  92. package/templates/scripts/watchtower-queue.mjs +484 -1
  93. package/templates/scripts/watchtower-ring1.mjs +533 -53
  94. package/templates/scripts/watchtower-ring2.mjs +787 -48
  95. package/templates/scripts/watchtower-ring3-close.mjs +1357 -99
  96. package/templates/scripts/watchtower-ring4-runner.sh +85 -0
  97. package/templates/scripts/watchtower-ring4.mjs +753 -0
  98. package/templates/scripts/watchtower-routines.mjs +358 -0
  99. package/templates/scripts/watchtower-snapshot.mjs +452 -0
  100. package/templates/scripts/watchtower-status.sh +1 -1
  101. package/templates/scripts/watchtower-sync.mjs +393 -0
  102. package/templates/skills/audit/SKILL.md +5 -1
  103. package/templates/skills/briefing/SKILL.md +584 -236
  104. package/templates/skills/cabinet-anthropic-insider/SKILL.md +14 -6
  105. package/templates/skills/cabinet-historian/SKILL.md +14 -11
  106. package/templates/skills/cabinet-process-therapist/SKILL.md +28 -0
  107. package/templates/skills/cabinet-security/SKILL.md +11 -0
  108. package/templates/skills/cabinet-system-advocate/SKILL.md +22 -21
  109. package/templates/skills/cabinet-user-advocate/SKILL.md +13 -7
  110. package/templates/skills/catch-up/SKILL.md +113 -0
  111. package/templates/skills/cc-publish/SKILL.md +148 -25
  112. package/templates/skills/cc-remember/SKILL.md +45 -0
  113. package/templates/skills/close/SKILL.md +107 -0
  114. package/templates/skills/collab-client/SKILL.md +22 -5
  115. package/templates/skills/collab-consultant/SKILL.md +110 -2
  116. package/templates/skills/debrief/SKILL.md +148 -16
  117. package/templates/skills/debrief-classic/SKILL.md +696 -0
  118. package/templates/skills/debrief-classic/calibration.md +44 -0
  119. package/templates/skills/debrief-classic/phases/audit-pattern-capture.md +78 -0
  120. package/templates/skills/debrief-classic/phases/auto-maintenance.md +48 -0
  121. package/templates/skills/debrief-classic/phases/checklist-feedback.md +123 -0
  122. package/templates/skills/debrief-classic/phases/close-work.md +163 -0
  123. package/templates/skills/debrief-classic/phases/health-checks.md +54 -0
  124. package/templates/skills/debrief-classic/phases/inventory.md +40 -0
  125. package/templates/skills/debrief-classic/phases/loose-ends.md +52 -0
  126. package/templates/skills/debrief-classic/phases/methodology-capture.md +223 -0
  127. package/templates/skills/debrief-classic/phases/qa-handoff-sweep.md +78 -0
  128. package/templates/skills/debrief-classic/phases/record-lessons.md +177 -0
  129. package/templates/skills/debrief-classic/phases/report.md +59 -0
  130. package/templates/skills/debrief-classic/phases/update-state.md +48 -0
  131. package/templates/skills/debrief-classic/phases/upstream-feedback.md +185 -0
  132. package/templates/skills/debrief-classic/phases/verify-coverage.md +101 -0
  133. package/templates/skills/execute/SKILL.md +77 -6
  134. package/templates/skills/execute/phases/commit-and-deploy.md +8 -0
  135. package/templates/skills/execute-group/SKILL.md +23 -26
  136. package/templates/skills/generate-plan-groups/SKILL.md +20 -0
  137. package/templates/skills/inbox/SKILL.md +124 -7
  138. package/templates/skills/memory/SKILL.md +22 -6
  139. package/templates/skills/orient/SKILL.md +140 -52
  140. package/templates/skills/orient-classic/SKILL.md +770 -0
  141. package/templates/skills/orient-classic/phases/auto-maintenance.md +52 -0
  142. package/templates/skills/orient-classic/phases/briefing.md +53 -0
  143. package/templates/skills/orient-classic/phases/cabinet.md +46 -0
  144. package/templates/skills/orient-classic/phases/checklist-status.md +54 -0
  145. package/templates/skills/orient-classic/phases/context.md +88 -0
  146. package/templates/skills/orient-classic/phases/data-sync.md +35 -0
  147. package/templates/skills/orient-classic/phases/deferred-check.md +55 -0
  148. package/templates/skills/orient-classic/phases/dx-captures.md +53 -0
  149. package/templates/skills/orient-classic/phases/health-checks.md +50 -0
  150. package/templates/skills/orient-classic/phases/verify-backfill.md +109 -0
  151. package/templates/skills/orient-classic/phases/work-scan.md +69 -0
  152. package/templates/skills/plan/SKILL.md +8 -0
  153. package/templates/skills/qa-drain/SKILL.md +157 -0
  154. package/templates/skills/qa-handoff/SKILL.md +287 -46
  155. package/templates/skills/session-handoff/SKILL.md +175 -6
  156. package/templates/skills/setup-accounts/SKILL.md +38 -16
  157. package/templates/skills/threads/SKILL.md +4 -0
  158. package/templates/skills/triage-audit/SKILL.md +6 -0
  159. package/templates/skills/validate/phases/validators.md +41 -0
  160. package/templates/skills/watchtower/SKILL.md +199 -2
  161. package/templates/verify-runtime/CONVENTIONS.md +9 -0
  162. package/templates/verify-runtime/README.md +37 -0
  163. package/templates/watchtower/config.json.template +10 -2
  164. package/templates/watchtower/queue/items/item.json.schema +1 -1
  165. package/templates/workflows/execute-group-complete.js +10 -1
package/lib/copy.js CHANGED
@@ -50,17 +50,71 @@ function recordSkip(manifest, key, { identical = false, incomingHash = null } =
50
50
  }
51
51
  }
52
52
 
53
+ /**
54
+ * Files shipped as STARTER content but owned by the project the moment they
55
+ * land. The installer seeds them if absent, NEVER overwrites them, and NEVER
56
+ * records them in the manifest. Manifest presence means "CC-owned", which has
57
+ * two consequences a project-owned file must avoid: cc-upstream-guard blocks
58
+ * edits to it, and a `--yes` reinstall silently overwrites it. The recordSkip
59
+ * "identical → keep tracked" rule is content-based and so still recorded an
60
+ * UNEDITED seed in the manifest — which false-blocked the very first edit (a
61
+ * project-owned file is unedited exactly until someone edits it). These files
62
+ * are project-owned by DECLARATION, not by content divergence.
63
+ *
64
+ * Keyed by basename: there is one such seed today and the src→dest relPath
65
+ * mapping varies by call site, so a basename match is the robust check.
66
+ * `directives-project.yaml`'s own header says it is "NOT overwritten by the
67
+ * installer ... extend upstream members with project-specific mandates" —
68
+ * recording it as CC-owned false-blocked the exact edits it exists to receive
69
+ * (field incident 2026-06-17, act:2001bf54).
70
+ */
71
+ const PROJECT_OWNED_SEED_BASENAMES = new Set(['directives-project.yaml']);
72
+ function isProjectOwnedSeed(relPath) {
73
+ return PROJECT_OWNED_SEED_BASENAMES.has(path.basename(relPath));
74
+ }
75
+
76
+ /**
77
+ * The canonical FREEZE rule for an EXISTING file in a frozen module that
78
+ * differs from the incoming template (act:c1013967). Shared by both copy
79
+ * paths — copy.js's directory walk and cli.js's single-file branch — so the
80
+ * "third ownership state" is defined in exactly one place (the recordSkip
81
+ * precedent).
82
+ *
83
+ * Freeze is "CC-owned but temporarily pinned": the file is NOT overwritten,
84
+ * and — crucially — only a file that is ALREADY CC-owned (present in the prior
85
+ * manifest) is RETAINED in the new manifest, at its ON-DISK hash. Two reasons
86
+ * the on-disk hash is the only correct choice:
87
+ * - It keeps the file PRESENT in the manifest, so the upstream-cleanup loop
88
+ * never lists it for deletion (a frozen file dropped from allManifest would
89
+ * be deleted — the exact opposite of freeze).
90
+ * - On-disk == recorded keeps the value-comparison consumers green:
91
+ * cc-drift-check sees no drift, reset.js classifies it unmodified.
92
+ *
93
+ * A frozen-module file that differs but is NOT already CC-owned is
94
+ * project-owned (project-created or a kept/edited file deliberately omitted
95
+ * from the manifest). Freeze adds nothing for it — it's already never
96
+ * overwritten — so it must FALL THROUGH to the normal skip-and-omit path.
97
+ * RETAINING it would adopt a project-owned file into the manifest and clobber
98
+ * it on the unfreeze reinstall (violates the recordSkip invariant above).
99
+ *
100
+ * @returns {{manifestHash: string}} retain at on-disk hash (CC-owned)
101
+ * | {{omit: true}} fall through to skip-and-omit (project-owned)
102
+ */
103
+ function freezeRetain({ existing, isCcOwned }) {
104
+ return isCcOwned ? { manifestHash: hashContent(existing) } : { omit: true };
105
+ }
106
+
53
107
  /**
54
108
  * Recursively copy files from src to dest, surfacing conflicts.
55
109
  * Returns { copied: string[], skipped: string[], overwritten: string[] }
56
110
  */
57
- async function copyTemplates(src, dest, { dryRun = false, skipConflicts = false, skipPhases = false, projectRoot = null, existingManifest = {}, instructionPhases = new Set() } = {}) {
58
- const results = { copied: [], skipped: [], overwritten: [], manifest: {} };
59
- await walkAndCopy(src, dest, src, results, dryRun, skipConflicts, skipPhases, projectRoot, existingManifest, instructionPhases);
111
+ async function copyTemplates(src, dest, { dryRun = false, skipConflicts = false, skipPhases = false, projectRoot = null, existingManifest = {}, instructionPhases = new Set(), frozen = false } = {}) {
112
+ const results = { copied: [], skipped: [], overwritten: [], manifest: {}, frozen: [] };
113
+ await walkAndCopy(src, dest, src, results, dryRun, skipConflicts, skipPhases, projectRoot, existingManifest, instructionPhases, frozen);
60
114
  return results;
61
115
  }
62
116
 
63
- async function walkAndCopy(srcRoot, destRoot, currentSrc, results, dryRun, skipConflicts, skipPhases, projectRoot, existingManifest, instructionPhases) {
117
+ async function walkAndCopy(srcRoot, destRoot, currentSrc, results, dryRun, skipConflicts, skipPhases, projectRoot, existingManifest, instructionPhases, frozen) {
64
118
  const entries = fs.readdirSync(currentSrc, { withFileTypes: true });
65
119
 
66
120
  for (const entry of entries) {
@@ -80,11 +134,32 @@ async function walkAndCopy(srcRoot, destRoot, currentSrc, results, dryRun, skipC
80
134
  if (!dryRun && !fs.existsSync(destPath)) {
81
135
  fs.mkdirSync(destPath, { recursive: true });
82
136
  }
83
- await walkAndCopy(srcRoot, destRoot, srcPath, results, dryRun, skipConflicts, skipPhases, projectRoot, existingManifest, instructionPhases);
137
+ await walkAndCopy(srcRoot, destRoot, srcPath, results, dryRun, skipConflicts, skipPhases, projectRoot, existingManifest, instructionPhases, frozen);
84
138
  } else {
85
139
  const incoming = fs.readFileSync(srcPath, 'utf8');
86
140
  const incomingHash = hashContent(incoming);
87
141
 
142
+ // Project-owned seed (act:2001bf54): seed if absent, never overwrite,
143
+ // and ALWAYS omit from the manifest — recording it would let
144
+ // cc-upstream-guard block edits and a --yes reinstall clobber the
145
+ // consumer's content. Runs before any existsSync branch so neither the
146
+ // byte-identical path (which would re-record an unedited seed) nor the
147
+ // manifest-driven overwrite path can reach it.
148
+ if (isProjectOwnedSeed(relPath)) {
149
+ if (!fs.existsSync(destPath)) {
150
+ if (!dryRun) {
151
+ const dir = path.dirname(destPath);
152
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
153
+ fs.copyFileSync(srcPath, destPath);
154
+ }
155
+ results.copied.push(relPath);
156
+ } else {
157
+ results.skipped.push(relPath);
158
+ }
159
+ recordSkip(results.manifest, relPath); // omit — project-owned by declaration
160
+ continue;
161
+ }
162
+
88
163
  if (fs.existsSync(destPath)) {
89
164
  const existing = fs.readFileSync(destPath, 'utf8');
90
165
 
@@ -112,6 +187,24 @@ async function walkAndCopy(srcRoot, destRoot, currentSrc, results, dryRun, skipC
112
187
  continue;
113
188
  }
114
189
 
190
+ // Frozen module (act:c1013967): the file differs and is past the
191
+ // identical + seed + customized-phase guards, so it is a CC-managed
192
+ // file that WOULD be overwritten. Hold it instead. Only a file already
193
+ // CC-owned (in the prior manifest) is retained at its on-disk hash; a
194
+ // project-owned file falls through to the normal skip-and-omit path.
195
+ if (frozen) {
196
+ const manifestKey = projectRoot ? path.relative(projectRoot, destPath) : relPath;
197
+ const decision = freezeRetain({ existing, isCcOwned: Boolean(existingManifest[manifestKey]) });
198
+ if (decision.manifestHash) {
199
+ results.skipped.push(relPath);
200
+ results.frozen.push(relPath);
201
+ results.manifest[relPath] = decision.manifestHash;
202
+ console.log(` ❄ Frozen (held): ${displayPath}`);
203
+ continue;
204
+ }
205
+ // decision.omit → project-owned; fall through.
206
+ }
207
+
115
208
  if (skipConflicts) {
116
209
  // Check if file is upstream-managed (in the old manifest).
117
210
  // If so, overwrite — it can't be customized (hook enforces this).
@@ -177,6 +270,15 @@ async function walkAndCopy(srcRoot, destRoot, currentSrc, results, dryRun, skipC
177
270
  recordSkip(results.manifest, relPath);
178
271
  }
179
272
  } else {
273
+ // New file in a frozen module: hold it back so the on-disk module
274
+ // stays internally consistent at its pinned version. Report only — no
275
+ // manifest entry (there's no on-disk content to hash; a phantom entry
276
+ // would break cc-drift-check/cleanup). On unfreeze this branch creates it.
277
+ if (frozen) {
278
+ results.frozen.push(relPath);
279
+ console.log(` ❄ Frozen (held new): ${displayPath}`);
280
+ continue;
281
+ }
180
282
  if (!dryRun) {
181
283
  const dir = path.dirname(destPath);
182
284
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
@@ -215,4 +317,4 @@ function showDiff(existing, incoming, relPath) {
215
317
  console.log('');
216
318
  }
217
319
 
218
- module.exports = { copyTemplates, recordSkip };
320
+ module.exports = { copyTemplates, recordSkip, isProjectOwnedSeed, freezeRetain };
package/lib/db-setup.js CHANGED
@@ -1,46 +1,151 @@
1
1
  const { execSync } = require('child_process');
2
2
  const fs = require('fs');
3
3
  const path = require('path');
4
+ const metadata = require('./metadata');
5
+
6
+ // Substrings that identify a better-sqlite3 native-module ABI mismatch —
7
+ // the compiled .node binary was built under a different Node than the one
8
+ // running `pib-db.mjs init`. Node surfaces this as an ERR_DLOPEN_FAILED
9
+ // with a NODE_MODULE_VERSION line; field reports during consumer walks
10
+ // also showed the shorter "native module version mismatch" phrasing.
11
+ const ABI_MISMATCH_SIGNATURES = [
12
+ 'NODE_MODULE_VERSION',
13
+ 'different Node.js version',
14
+ 'was compiled against',
15
+ 'native module version mismatch',
16
+ 'ERR_DLOPEN_FAILED',
17
+ ];
18
+
19
+ function isAbiMismatch(text) {
20
+ const s = String(text || '');
21
+ return ABI_MISMATCH_SIGNATURES.some((sig) => s.includes(sig));
22
+ }
23
+
24
+ // Read the bundled pib-db schema version from the (already-copied)
25
+ // pib-db-lib.mjs as TEXT — never by importing it, so learning the version
26
+ // does not itself load better-sqlite3. Returns a number, or null when the
27
+ // file is missing or the constant can't be parsed.
28
+ function readBundledSchemaVersion(scriptsDir) {
29
+ try {
30
+ const src = fs.readFileSync(path.join(scriptsDir, 'pib-db-lib.mjs'), 'utf8');
31
+ const m = src.match(/SCHEMA_VERSION\s*=\s*(\d+)/);
32
+ return m ? Number(m[1]) : null;
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+
38
+ // Lazy-init gate: a reinstall whose recorded schema version already matches
39
+ // the bundled one (and whose pib.db exists) needs no migration, so the init
40
+ // step can be skipped entirely — and a skipped init never loads the
41
+ // (possibly stale) native module. Conservative by construction: any
42
+ // missing/unequal input returns false, so we only skip when certain there
43
+ // is nothing to migrate.
44
+ function shouldSkipInit({ dbExists, recordedVersion, bundledVersion }) {
45
+ return Boolean(
46
+ dbExists &&
47
+ bundledVersion != null &&
48
+ recordedVersion != null &&
49
+ recordedVersion === bundledVersion
50
+ );
51
+ }
4
52
 
5
53
  /**
6
54
  * Set up the PIB database in the target project.
7
- * - Copies pib-db.mjs and schema to scripts/
55
+ * - Copies are already in place (scripts/ copied by the main install loop)
8
56
  * - Runs npm init if no package.json
9
- * - Installs better-sqlite3
10
- * - Runs pib-db init
57
+ * - Installs better-sqlite3 if absent
58
+ * - Initializes/migrates the database, UNLESS the schema is already current
59
+ * (lazy-init), and self-heals an ABI-mismatched native binary.
60
+ *
61
+ * Returns { results: string[], schemaVersion: number|null }. schemaVersion
62
+ * is the applied (or confirmed-current) schema version when init succeeded
63
+ * or was correctly skipped, and null when init could not complete (ABI
64
+ * mismatch with no working rebuild) — so the caller never records a false
65
+ * "schema current" claim in .ccrc.json.
66
+ *
67
+ * `opts.exec` and `opts.log` are injectable for testing; they default to
68
+ * execSync and console.log.
11
69
  */
12
- function setupDb(projectDir) {
70
+ function setupDb(projectDir, opts = {}) {
71
+ const exec = opts.exec || ((cmd, o) => execSync(cmd, o));
72
+ const log = opts.log || console.log;
13
73
  const scriptsDir = path.join(projectDir, 'scripts');
14
74
  const results = [];
15
75
 
16
76
  // Check if package.json exists; if not, init
17
77
  const pkgPath = path.join(projectDir, 'package.json');
18
78
  if (!fs.existsSync(pkgPath)) {
19
- console.log(' Initializing package.json...');
20
- execSync('npm init -y', { cwd: projectDir, stdio: 'pipe' });
79
+ log(' Initializing package.json...');
80
+ exec('npm init -y', { cwd: projectDir, stdio: 'pipe' });
21
81
  results.push('Created package.json');
22
82
  }
23
83
 
24
84
  // pib-db.mjs uses ESM imports — .mjs extension lets Node treat it as ESM
25
85
  // regardless of the project's package.json type field
86
+ const dbScript = path.join(scriptsDir, 'pib-db.mjs');
87
+ const dbPath = path.join(projectDir, 'pib.db');
88
+ const bundledVersion = readBundledSchemaVersion(scriptsDir);
89
+
90
+ // Lazy-init: skip when the schema is already current. This is the common
91
+ // reinstall case; skipping means a no-migration release never loads
92
+ // better-sqlite3, so a stale native binary can't wall the install with an
93
+ // ABI-mismatch error it never needed to risk.
94
+ const existingMeta = metadata.read(projectDir) || {};
95
+ if (
96
+ shouldSkipInit({
97
+ dbExists: fs.existsSync(dbPath),
98
+ recordedVersion: existingMeta.dbSchemaVersion,
99
+ bundledVersion,
100
+ })
101
+ ) {
102
+ results.push(`Database schema already current (v${bundledVersion}) — skipped init`);
103
+ return { results, schemaVersion: bundledVersion };
104
+ }
26
105
 
27
- // Install better-sqlite3 if not already installed
106
+ // Install better-sqlite3 if not already installed. A pre-existing but
107
+ // stale binary is left for the rebuild path below to heal — a plain
108
+ // reinstall wouldn't change an already-satisfied semver.
28
109
  const nodeModules = path.join(projectDir, 'node_modules', 'better-sqlite3');
29
110
  if (!fs.existsSync(nodeModules)) {
30
- console.log(' Installing better-sqlite3...');
31
- execSync('npm install better-sqlite3', { cwd: projectDir, stdio: 'pipe' });
111
+ log(' Installing better-sqlite3...');
112
+ exec('npm install better-sqlite3', { cwd: projectDir, stdio: 'pipe' });
32
113
  results.push('Installed better-sqlite3');
33
114
  }
34
115
 
35
- // Initialize the database
36
- const dbScript = path.join(scriptsDir, 'pib-db.mjs');
37
- if (fs.existsSync(dbScript)) {
38
- console.log(' Initializing database...');
39
- execSync(`node ${dbScript} init`, { cwd: projectDir, stdio: 'pipe' });
40
- results.push('Initialized pib.db');
116
+ if (!fs.existsSync(dbScript)) {
117
+ return { results, schemaVersion: null };
41
118
  }
42
119
 
43
- return results;
120
+ log(' Initializing database...');
121
+ try {
122
+ exec(`node ${dbScript} init`, { cwd: projectDir, stdio: 'pipe' });
123
+ results.push('Initialized pib.db');
124
+ return { results, schemaVersion: bundledVersion };
125
+ } catch (err) {
126
+ const detail = `${String(err.stderr || '')}\n${String(err.message || '')}`;
127
+ // Non-ABI failures keep their old handling — propagate to the caller's
128
+ // existing "Database setup failed" catch.
129
+ if (!isAbiMismatch(detail)) throw err;
130
+
131
+ // ABI mismatch: rebuild the native binary once and retry. If that
132
+ // works, the install self-heals. If it doesn't, fall back to a single
133
+ // actionable line — never a stack trace, never a silent skip.
134
+ log(' better-sqlite3 built for a different Node — rebuilding once and retrying...');
135
+ try {
136
+ exec('npm rebuild better-sqlite3', { cwd: projectDir, stdio: 'pipe' });
137
+ exec(`node ${dbScript} init`, { cwd: projectDir, stdio: 'pipe' });
138
+ results.push('Rebuilt better-sqlite3 (ABI mismatch) and initialized pib.db');
139
+ return { results, schemaVersion: bundledVersion };
140
+ } catch {
141
+ results.push(
142
+ 'DB step skipped: better-sqlite3 was built for a different Node. Run ' +
143
+ '`npm rebuild better-sqlite3` then `node scripts/pib-db.mjs init` in ' +
144
+ 'this project — your existing pib.db is untouched.'
145
+ );
146
+ return { results, schemaVersion: null };
147
+ }
148
+ }
44
149
  }
45
150
 
46
- module.exports = { setupDb };
151
+ module.exports = { setupDb, isAbiMismatch, readBundledSchemaVersion, shouldSkipInit };
@@ -9,7 +9,10 @@
9
9
  *
10
10
  * Version semantics:
11
11
  * - First install: copy all managed files, create data dir, write .cc-version
12
- * - Same version: skip with log
12
+ * - Same version: fall through to the SHA256 manifest hash-compare and
13
+ * copy only files whose hashes differ (dogfood-from-source changes
14
+ * templates without a version bump — equal-version must still
15
+ * propagate; the manifest check makes this cheap and idempotent)
13
16
  * - Newer CC version: upgrade managed files, preserve data dir
14
17
  * - Older CC version than installed: skip (don't downgrade)
15
18
  */
@@ -23,6 +26,7 @@ const CC_HOME = path.join(os.homedir(), '.claude-cabinet');
23
26
  const GLOBAL_MANIFEST_PATH = path.join(CC_HOME, 'global-manifest.json');
24
27
  const INSTALL_DIR = path.join(CC_HOME, 'engagement-server');
25
28
  const VERSION_FILE = path.join(INSTALL_DIR, '.cc-version');
29
+ const TEMPLATE_DIR = path.resolve(__dirname, '..', 'templates', 'engagement-server');
26
30
 
27
31
  const MANAGED_FILES = [
28
32
  'server.mjs',
@@ -99,7 +103,7 @@ function setupEngagementServer(opts = {}) {
99
103
  const results = [];
100
104
 
101
105
  const ccVersion = require('../package.json').version;
102
- const templateDir = path.resolve(__dirname, '..', 'templates', 'engagement-server');
106
+ const templateDir = TEMPLATE_DIR;
103
107
 
104
108
  if (!fs.existsSync(templateDir)) {
105
109
  throw new Error(`engagement-server-setup: ${templateDir} not found.`);
@@ -109,15 +113,19 @@ function setupEngagementServer(opts = {}) {
109
113
 
110
114
  if (installedVersion) {
111
115
  const cmp = compareVersions(ccVersion, installedVersion);
112
- if (cmp === 0) {
113
- results.push(`engagement-server ${installedVersion} already installed — skipping`);
114
- return { results, status: 'skipped' };
115
- }
116
116
  if (cmp < 0) {
117
117
  results.push(`engagement-server ${installedVersion} is newer than CC ${ccVersion} — skipping (won't downgrade)`);
118
118
  return { results, status: 'skipped' };
119
119
  }
120
- results.push(`Upgrading engagement-server from ${installedVersion} to ${ccVersion}`);
120
+ // Equal version (cmp === 0): do NOT early-return. Fall through to the
121
+ // SHA256 manifest hash-compare below — it copies only changed files,
122
+ // so a dogfood-from-source template edit propagates even without a
123
+ // package.json version bump. The hash-compare makes this idempotent.
124
+ if (cmp === 0) {
125
+ results.push(`engagement-server ${installedVersion} already installed — checking for changed files`);
126
+ } else {
127
+ results.push(`Upgrading engagement-server from ${installedVersion} to ${ccVersion}`);
128
+ }
121
129
  } else {
122
130
  results.push(`Installing engagement-server ${ccVersion}`);
123
131
  }
@@ -187,7 +195,24 @@ function setupEngagementServer(opts = {}) {
187
195
  results.push(` Re-deploy: cd ${INSTALL_DIR} && railway up --detach`);
188
196
  }
189
197
 
190
- return { results, status: installedVersion ? 'upgraded' : 'installed' };
198
+ let status;
199
+ if (!installedVersion) {
200
+ status = 'installed';
201
+ } else if (copiedCount > 0) {
202
+ status = 'upgraded';
203
+ } else {
204
+ // Equal-or-newer version, manifest already current — nothing to do.
205
+ status = 'unchanged';
206
+ }
207
+ return { results, status };
191
208
  }
192
209
 
193
- module.exports = { setupEngagementServer };
210
+ // MANAGED_FILES, INSTALL_DIR, and TEMPLATE_DIR are exported for the
211
+ // version-gate test so it can seed a faithful, complete global manifest
212
+ // (single source of truth — the test never re-derives the file list).
213
+ module.exports = {
214
+ setupEngagementServer,
215
+ MANAGED_FILES,
216
+ INSTALL_DIR,
217
+ TEMPLATE_DIR,
218
+ };
package/lib/metadata.js CHANGED
@@ -44,7 +44,7 @@ function merge(projectDir, partial) {
44
44
  return data;
45
45
  }
46
46
 
47
- function create(projectDir, { modules, skipped, version, manifest = {} }) {
47
+ function create(projectDir, { modules, skipped, version, manifest = {}, dbSchemaVersion } = {}) {
48
48
  // Read existing first so unknown top-level keys (e.g.
49
49
  // `migrated_from_omega` set by --migrate-memory) survive the
50
50
  // install/upgrade rewrite. Only the install-specific fields below
@@ -60,6 +60,13 @@ function create(projectDir, { modules, skipped, version, manifest = {} }) {
60
60
  manifest,
61
61
  };
62
62
 
63
+ // Record the applied pib-db schema version when this install confirmed
64
+ // one (init ran or was skipped as already-current). When it didn't
65
+ // (--no-db, dry-run, or an unhealed ABI mismatch), `dbSchemaVersion` is
66
+ // undefined and any prior value rides through via `...existing` — we
67
+ // never claim "schema current" off the back of a skipped/failed init.
68
+ if (dbSchemaVersion != null) data.dbSchemaVersion = dbSchemaVersion;
69
+
63
70
  for (const mod of modules) {
64
71
  data.modules[mod] = true;
65
72
  }
@@ -71,4 +78,46 @@ function create(projectDir, { modules, skipped, version, manifest = {} }) {
71
78
  return data;
72
79
  }
73
80
 
74
- module.exports = { read, write, merge, create, metadataPath, METADATA_FILE };
81
+ /**
82
+ * Read the project's frozen-module list from `.ccrc.json`. Returns a
83
+ * normalized, deduped `string[]` of module keys the operator has pinned
84
+ * (the temporary, manifest-RETAINING third ownership state — act:c1013967).
85
+ *
86
+ * Defensive by construction: a non-array `frozenModules` (shape drift) reads
87
+ * as "nothing frozen" rather than throwing, and a genuinely-absent `.ccrc.json`
88
+ * returns `[]`. It deliberately does NOT swallow a JSON parse error — `read()`
89
+ * throws on a malformed `.ccrc.json`, which HALTS the reinstall. That fail-
90
+ * closed behavior is the point: when the freeze state can't be read, the
91
+ * installer must stop, never proceed as if nothing were frozen (which would
92
+ * silently rewrite the very files a freeze exists to protect).
93
+ */
94
+ function readFrozenModules(projectDir) {
95
+ const m = read(projectDir);
96
+ const raw = m && m.frozenModules;
97
+ if (!Array.isArray(raw)) return [];
98
+ return [...new Set(raw.filter((x) => typeof x === 'string'))];
99
+ }
100
+
101
+ /**
102
+ * Persist the frozen-module list, shallow-merged into `.ccrc.json` so every
103
+ * other field (manifest, modules, dbSchemaVersion, …) rides through. Input is
104
+ * normalized to a deduped string[]. Returns the written array.
105
+ */
106
+ function setFrozenModules(projectDir, mods) {
107
+ const normalized = Array.isArray(mods)
108
+ ? [...new Set(mods.filter((x) => typeof x === 'string'))]
109
+ : [];
110
+ merge(projectDir, { frozenModules: normalized });
111
+ return normalized;
112
+ }
113
+
114
+ module.exports = {
115
+ read,
116
+ write,
117
+ merge,
118
+ create,
119
+ metadataPath,
120
+ METADATA_FILE,
121
+ readFrozenModules,
122
+ setFrozenModules,
123
+ };
@@ -82,6 +82,13 @@ function stripUserPrefix(raw, homeDir) {
82
82
  const segs = tail.split('/');
83
83
  return segs.slice(1).join('/');
84
84
  }
85
+ // Omega project keys are historical strings recorded on whatever machine
86
+ // wrote them — a DB carried from a Mac to a Linux box (or exercised on a
87
+ // Linux CI runner) still holds /Users/<name>/... paths that the current
88
+ // machine's home root won't match. Recognize the conventional home roots
89
+ // structurally so cross-machine migrations classify instead of crashing.
90
+ const foreignHome = raw.match(/^\/(?:Users|home)\/[^/]+\/(.+)$/);
91
+ if (foreignHome) return foreignHome[1];
85
92
  return raw;
86
93
  }
87
94
 
@@ -100,7 +107,12 @@ function canonicalizeProjectKey(raw, ctx = {}) {
100
107
  const slugPath = stripUserPrefix(work, ctx.homeDir);
101
108
  const topSlug = slugPath.split('/')[0];
102
109
 
103
- return { canonical: topSlug || null, kind: 'project' };
110
+ // kind 'project' with a null canonical is an incoherent contract — the
111
+ // bucketing consumer would key a cross-project map on null and crash on
112
+ // slug derivation. An unclassifiable key is unscoped, not a null project.
113
+ if (!topSlug) return { canonical: null, kind: 'unscoped' };
114
+
115
+ return { canonical: topSlug, kind: 'project' };
104
116
  }
105
117
 
106
118
  function resolveCurrentProject(cwd, homeDir) {
package/lib/mux-setup.js CHANGED
@@ -8,7 +8,10 @@
8
8
  *
9
9
  * Version semantics:
10
10
  * - First install: copy all managed files, write .cc-version
11
- * - Same version: skip with log
11
+ * - Same version: fall through to the SHA256 manifest hash-compare and
12
+ * copy only files whose hashes differ (dogfood-from-source changes
13
+ * templates without a version bump — equal-version must still
14
+ * propagate; the manifest check makes this cheap and idempotent)
12
15
  * - Newer CC version: upgrade managed files, preserve data dirs
13
16
  * - Older CC version than installed: skip (don't downgrade)
14
17
  */
@@ -21,6 +24,7 @@ const crypto = require('crypto');
21
24
  const CC_HOME = path.join(os.homedir(), '.claude-cabinet');
22
25
  const GLOBAL_MANIFEST_PATH = path.join(CC_HOME, 'global-manifest.json');
23
26
  const MUX_VERSION_FILE = path.join(os.homedir(), '.config', 'mux', '.cc-version');
27
+ const TEMPLATE_DIR = path.resolve(__dirname, '..', 'templates', 'mux');
24
28
 
25
29
  const MANAGED_FILES = [
26
30
  { src: 'bin/mux', dest: path.join(os.homedir(), '.local', 'bin', 'mux'), mode: 0o755 },
@@ -122,7 +126,7 @@ function setupMux(opts = {}) {
122
126
  const results = [];
123
127
 
124
128
  const ccVersion = require('../package.json').version;
125
- const templateDir = path.resolve(__dirname, '..', 'templates', 'mux');
129
+ const templateDir = TEMPLATE_DIR;
126
130
 
127
131
  if (!fs.existsSync(templateDir)) {
128
132
  throw new Error(`mux-setup: ${templateDir} not found.`);
@@ -132,15 +136,19 @@ function setupMux(opts = {}) {
132
136
 
133
137
  if (installedVersion) {
134
138
  const cmp = compareVersions(ccVersion, installedVersion);
135
- if (cmp === 0) {
136
- results.push(`mux ${installedVersion} already installed — skipping`);
137
- return { results, status: 'skipped' };
138
- }
139
139
  if (cmp < 0) {
140
140
  results.push(`mux ${installedVersion} is newer than CC ${ccVersion} — skipping (won't downgrade)`);
141
141
  return { results, status: 'skipped' };
142
142
  }
143
- results.push(`Upgrading mux from ${installedVersion} to ${ccVersion}`);
143
+ // Equal version (cmp === 0): do NOT early-return. Fall through to the
144
+ // SHA256 manifest hash-compare below — it copies only changed files,
145
+ // so a dogfood-from-source template edit propagates even without a
146
+ // package.json version bump. The hash-compare makes this idempotent.
147
+ if (cmp === 0) {
148
+ results.push(`mux ${installedVersion} already installed — checking for changed files`);
149
+ } else {
150
+ results.push(`Upgrading mux from ${installedVersion} to ${ccVersion}`);
151
+ }
144
152
  } else {
145
153
  results.push(`Installing mux ${ccVersion}`);
146
154
  }
@@ -200,7 +208,16 @@ function setupMux(opts = {}) {
200
208
  setupDarwinIntegration({ dryRun, results });
201
209
  }
202
210
 
203
- return { results, status: installedVersion ? 'upgraded' : 'installed' };
211
+ let status;
212
+ if (!installedVersion) {
213
+ status = 'installed';
214
+ } else if (copiedCount > 0) {
215
+ status = 'upgraded';
216
+ } else {
217
+ // Equal-or-newer version, manifest already current — nothing to do.
218
+ status = 'unchanged';
219
+ }
220
+ return { results, status };
204
221
  }
205
222
 
206
223
  /**
@@ -308,4 +325,11 @@ function setupDarwinIntegration({ dryRun, results }) {
308
325
  }
309
326
  }
310
327
 
311
- module.exports = { setupMux };
328
+ // MANAGED_FILES and TEMPLATE_DIR are exported for the version-gate test so it
329
+ // can seed a faithful, complete global manifest (single source of truth — the
330
+ // test never re-derives the file list).
331
+ module.exports = {
332
+ setupMux,
333
+ MANAGED_FILES,
334
+ TEMPLATE_DIR,
335
+ };