@massu/core 1.15.2 → 1.15.4

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.
@@ -1,21 +1,40 @@
1
1
  #!/usr/bin/env node
2
2
  import{createRequire as __cr}from"module";const require=__cr(import.meta.url);
3
-
4
- // src/hooks/pre-delete-check.ts
5
- import Database2 from "better-sqlite3";
6
- import { existsSync as existsSync3 } from "fs";
7
-
8
- // src/config.ts
9
- import { resolve as resolve2, dirname } from "path";
10
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
11
- import { homedir as homedir2 } from "os";
12
- import { parse as parseYaml } from "yaml";
13
- import { z } from "zod";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __esm = (fn, res, err) => function __init() {
8
+ if (err) throw err[0];
9
+ try {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ } catch (e) {
12
+ throw err = [e], e;
13
+ }
14
+ };
15
+ var __export = (target, all) => {
16
+ for (var name in all)
17
+ __defProp(target, name, { get: all[name], enumerable: true });
18
+ };
19
+ var __copyProps = (to, from, except, desc) => {
20
+ if (from && typeof from === "object" || typeof from === "function") {
21
+ for (let key of __getOwnPropNames(from))
22
+ if (!__hasOwnProp.call(to, key) && key !== except)
23
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
24
+ }
25
+ return to;
26
+ };
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
14
28
 
15
29
  // src/lib/memory-path.ts
16
30
  function encodeMemoryDirName(projectRoot) {
17
31
  return projectRoot.replace(/\//g, "-");
18
32
  }
33
+ var init_memory_path = __esm({
34
+ "src/lib/memory-path.ts"() {
35
+ "use strict";
36
+ }
37
+ });
19
38
 
20
39
  // src/credentials.ts
21
40
  import { homedir } from "os";
@@ -28,9 +47,6 @@ import {
28
47
  rmSync,
29
48
  chmodSync
30
49
  } from "fs";
31
- var MASSU_ENV_API_KEY = "MASSU_API_KEY";
32
- var MASSU_ENV_CLOUD_ENDPOINT = "MASSU_CLOUD_ENDPOINT";
33
- var DEFAULT_CLOUD_ENDPOINT = "https://api.massu.ai/v1";
34
50
  function credentialsDir(home = homedir()) {
35
51
  return resolve(home, ".massu");
36
52
  }
@@ -78,391 +94,160 @@ function resolveEndpoint(opts = {}) {
78
94
  if (envEp.length > 0) return envEp;
79
95
  return DEFAULT_CLOUD_ENDPOINT;
80
96
  }
81
-
82
- // src/config.ts
83
- var DomainConfigSchema = z.object({
84
- name: z.string().default("Unknown"),
85
- routers: z.array(z.string()).default([]),
86
- pages: z.array(z.string()).default([]),
87
- tables: z.array(z.string()).default([]),
88
- allowedImportsFrom: z.array(z.string()).default([])
89
- });
90
- var PatternRuleConfigSchema = z.object({
91
- pattern: z.string().default("**"),
92
- rules: z.array(z.string()).default([]),
93
- language: z.string().optional()
94
- });
95
- var CostModelSchema = z.object({
96
- input_per_million: z.number(),
97
- output_per_million: z.number(),
98
- cache_read_per_million: z.number().optional(),
99
- cache_write_per_million: z.number().optional()
100
- });
101
- var AnalyticsConfigSchema = z.object({
102
- quality: z.object({
103
- weights: z.record(z.string(), z.number()).default({
104
- bug_found: -5,
105
- vr_failure: -10,
106
- incident: -20,
107
- cr_violation: -3,
108
- vr_pass: 2,
109
- clean_commit: 5,
110
- successful_verification: 3
111
- }),
112
- categories: z.array(z.string()).default(["security", "architecture", "coupling", "tests", "rule_compliance"])
113
- }).optional(),
114
- cost: z.object({
115
- models: z.record(z.string(), CostModelSchema).default({}),
116
- currency: z.string().default("USD")
117
- }).optional(),
118
- prompts: z.object({
119
- success_indicators: z.array(z.string()).default(["committed", "approved", "looks good", "perfect", "great", "thanks"]),
120
- failure_indicators: z.array(z.string()).default(["revert", "wrong", "that's not", "undo", "incorrect"]),
121
- max_turns_for_success: z.number().default(2)
122
- }).optional()
123
- }).optional();
124
- var CustomPatternSchema = z.object({
125
- pattern: z.string(),
126
- severity: z.string(),
127
- message: z.string()
128
- });
129
- var GovernanceConfigSchema = z.object({
130
- audit: z.object({
131
- formats: z.array(z.string()).default(["summary", "detailed", "soc2"]),
132
- retention_days: z.number().default(365),
133
- auto_log: z.record(z.string(), z.boolean()).default({
134
- code_changes: true,
135
- rule_enforcement: true,
136
- approvals: true,
137
- commits: true
138
- })
139
- }).optional(),
140
- validation: z.object({
141
- realtime: z.boolean().default(true),
142
- checks: z.record(z.string(), z.boolean()).default({
143
- rule_compliance: true,
144
- import_existence: true,
145
- naming_conventions: true
146
- }),
147
- custom_patterns: z.array(CustomPatternSchema).default([])
148
- }).optional(),
149
- adr: z.object({
150
- detection_phrases: z.array(z.string()).default(["chose", "decided", "switching to", "moving from", "going with"]),
151
- template: z.string().default("default"),
152
- storage: z.string().default("database"),
153
- output_dir: z.string().default("docs/adr")
154
- }).optional()
155
- }).optional();
156
- var SecurityPatternSchema = z.object({
157
- pattern: z.string(),
158
- severity: z.string(),
159
- category: z.string(),
160
- description: z.string()
161
- });
162
- var SecurityConfigSchema = z.object({
163
- patterns: z.array(SecurityPatternSchema).default([]),
164
- auto_score_on_edit: z.boolean().default(true),
165
- score_threshold_alert: z.number().default(50),
166
- severity_weights: z.record(z.string(), z.number()).optional(),
167
- restrictive_licenses: z.array(z.string()).optional(),
168
- dep_alternatives: z.record(z.string(), z.array(z.string())).optional(),
169
- dependencies: z.object({
170
- package_manager: z.string().default("npm"),
171
- blocked_packages: z.array(z.string()).default([]),
172
- preferred_packages: z.record(z.string(), z.string()).default({}),
173
- max_bundle_size_kb: z.number().default(500)
174
- }).optional()
175
- }).optional();
176
- var TeamConfigSchema = z.object({
177
- enabled: z.boolean().default(false),
178
- sync_backend: z.string().default("local"),
179
- developer_id: z.string().default("auto"),
180
- share_by_default: z.boolean().default(false),
181
- expertise_weights: z.object({
182
- session: z.number().default(20),
183
- observation: z.number().default(10)
184
- }).optional(),
185
- privacy: z.object({
186
- share_file_paths: z.boolean().default(true),
187
- share_code_snippets: z.boolean().default(false),
188
- share_observations: z.boolean().default(true)
189
- }).optional()
190
- }).optional();
191
- var RegressionConfigSchema = z.object({
192
- test_patterns: z.array(z.string()).default([
193
- "{dir}/__tests__/{name}.test.{ext}",
194
- "{dir}/{name}.spec.{ext}",
195
- "tests/{path}.test.{ext}"
196
- ]),
197
- test_runner: z.string().default("npm test"),
198
- health_thresholds: z.object({
199
- healthy: z.number().default(80),
200
- warning: z.number().default(50)
201
- }).optional()
202
- }).optional();
203
- var AutoLearningConfigSchema = z.object({
204
- enabled: z.boolean().default(true),
205
- incidentDir: z.string().default("docs/incidents"),
206
- memoryDir: z.string().default("memory"),
207
- memoryIndexFile: z.string().default("MEMORY.md"),
208
- enforcementHooksDir: z.string().default("scripts/hooks"),
209
- fixDetection: z.object({
210
- enabled: z.boolean().default(true),
211
- lookbackDays: z.number().default(7),
212
- signals: z.array(z.string()).default([
213
- "removed_broken_code",
214
- "added_error_handling",
215
- "method_name_correction",
216
- "auth_fix",
217
- "nil_handling_fix",
218
- "concurrency_fix",
219
- "async_pattern_fix",
220
- "added_missing_import"
221
- ])
222
- }).default({}),
223
- failureClassification: z.object({
224
- enabled: z.boolean().default(true),
225
- thresholds: z.object({
226
- known: z.number().default(5),
227
- similar: z.number().default(3)
228
- }).default({}),
229
- scoring: z.object({
230
- diffPatternWeight: z.number().default(3),
231
- filePatternWeight: z.number().default(2),
232
- promptKeywordWeight: z.number().default(2)
233
- }).default({})
234
- }).default({}),
235
- pipeline: z.object({
236
- requireIncidentReport: z.boolean().default(true),
237
- requirePreventionRule: z.boolean().default(true),
238
- requireEnforcement: z.boolean().default(true)
239
- }).default({}),
240
- // plan-v0.2-interactive-rule-approval P-D-008 / P-D-009: project-configured
241
- // custom destinations for the rule-candidate funnel. The classifier matches
242
- // a candidate to one of these entries when none of the framework
243
- // destinations (pattern-scanner / claude-md-cr / corrections-md) apply.
244
- customDestinations: z.array(z.object({
245
- name: z.string(),
246
- path: z.string(),
247
- triggerKeywords: z.array(z.string()).default([]),
248
- template: z.string()
249
- })).default([])
250
- }).optional();
251
- var CloudConfigSchema = z.object({
252
- enabled: z.boolean().default(false),
253
- apiKey: z.string().optional(),
254
- endpoint: z.string().optional(),
255
- sync: z.object({
256
- memory: z.boolean().default(true),
257
- analytics: z.boolean().default(true),
258
- audit: z.boolean().default(true)
259
- }).default({ memory: true, analytics: true, audit: true })
260
- }).optional();
261
- var ConventionsConfigSchema = z.object({
262
- claudeDirName: z.string().default(".claude").refine(
263
- (s) => !s.includes("..") && !s.startsWith("/"),
264
- { message: 'claudeDirName must not contain ".." or start with "/"' }
265
- ),
266
- sessionStatePath: z.string().default(".claude/session-state/CURRENT.md").refine(
267
- (s) => !s.includes("..") && !s.startsWith("/"),
268
- { message: 'sessionStatePath must not contain ".." or start with "/"' }
269
- ),
270
- sessionArchivePath: z.string().default(".claude/session-state/archive").refine(
271
- (s) => !s.includes("..") && !s.startsWith("/"),
272
- { message: 'sessionArchivePath must not contain ".." or start with "/"' }
273
- ),
274
- knowledgeCategories: z.array(z.string()).default([
275
- "patterns",
276
- "commands",
277
- "incidents",
278
- "reference",
279
- "protocols",
280
- "checklists",
281
- "playbooks",
282
- "critical",
283
- "scripts",
284
- "status",
285
- "templates",
286
- "loop-state",
287
- "session-state",
288
- "agents"
289
- ]),
290
- knowledgeSourceFiles: z.array(z.string()).default(["CLAUDE.md", "MEMORY.md", "corrections.md"]),
291
- excludePatterns: z.array(z.string()).default(["/ARCHIVE/", "/SESSION-HISTORY/"])
292
- }).optional();
293
- var PythonDomainConfigSchema = z.object({
294
- name: z.string(),
295
- packages: z.array(z.string()),
296
- allowed_imports_from: z.array(z.string()).default([])
97
+ var MASSU_ENV_API_KEY, MASSU_ENV_CLOUD_ENDPOINT, DEFAULT_CLOUD_ENDPOINT;
98
+ var init_credentials = __esm({
99
+ "src/credentials.ts"() {
100
+ "use strict";
101
+ MASSU_ENV_API_KEY = "MASSU_API_KEY";
102
+ MASSU_ENV_CLOUD_ENDPOINT = "MASSU_CLOUD_ENDPOINT";
103
+ DEFAULT_CLOUD_ENDPOINT = "https://api.massu.ai/v1";
104
+ }
297
105
  });
298
- var PythonConfigSchema = z.object({
299
- root: z.string(),
300
- alembic_dir: z.string().optional(),
301
- domains: z.array(PythonDomainConfigSchema).default([]),
302
- exclude_dirs: z.array(z.string()).default(["__pycache__", ".venv", "venv", ".mypy_cache", ".pytest_cache"])
303
- }).optional();
304
- var PathsConfigSchema = z.object({
305
- source: z.string().default("src"),
306
- aliases: z.record(z.string(), z.string()).default({ "@": "src" }),
307
- monorepo_roots: z.array(z.string()).optional(),
308
- routers: z.string().optional(),
309
- routerRoot: z.string().optional(),
310
- pages: z.string().optional(),
311
- middleware: z.string().optional(),
312
- schema: z.string().optional(),
313
- components: z.string().optional(),
314
- hooks: z.string().optional()
106
+
107
+ // src/config-memory-schema.ts
108
+ import { z } from "zod";
109
+ var MemoryConfigSchema;
110
+ var init_config_memory_schema = __esm({
111
+ "src/config-memory-schema.ts"() {
112
+ "use strict";
113
+ MemoryConfigSchema = z.object({
114
+ recall: z.object({
115
+ enabled: z.boolean().default(true),
116
+ maxTokens: z.number().int().positive().default(1200),
117
+ sources: z.array(
118
+ z.enum([
119
+ "observation",
120
+ "architecture_decision",
121
+ "knowledge_chunk",
122
+ "failure_class"
123
+ ])
124
+ ).default(["observation", "architecture_decision", "knowledge_chunk", "failure_class"]),
125
+ timeoutMs: z.number().int().positive().default(8e3),
126
+ limit: z.number().int().positive().default(8),
127
+ minScore: z.number().min(0).default(0),
128
+ // --- Semantic embedder (plan-living-memory-slice-2a-embedder, P3-001) ---
129
+ // embedEnabled: Tier-1 bundled WASM embedder on by default; false forces
130
+ // Tier-2 (FTS keyword-only) recall.
131
+ // embedEndpoint: optional Tier-0 OpenAI-compatible /v1/embeddings provider
132
+ // (Ollama, LM Studio, vLLM, or any hosted API). When set, embedding egresses ONLY to this
133
+ // operator-chosen endpoint; unset means zero egress (bundled model).
134
+ // embedModel: optional Tier-0 model name sent to that endpoint.
135
+ embedEnabled: z.boolean().default(true),
136
+ embedEndpoint: z.string().url().refine((s) => /^https?:\/\//i.test(s), {
137
+ message: "memory.recall.embedEndpoint must be an http(s) URL"
138
+ }).optional(),
139
+ embedModel: z.string().min(1).optional()
140
+ }).default({}),
141
+ // --- Contradiction / supersede gate (plan-living-memory-slice-2-temporal-model, P5-001) ---
142
+ // When a new high-value memory (decision/correction) is written, find
143
+ // semantically-related existing records and, if the new one contradicts an
144
+ // old one, supersede-don't-delete the old row. Fully fail-open + gated to a
145
+ // small set of high-value types so the hot capture path is untouched.
146
+ contradiction: z.object({
147
+ // Master switch. false → every write is a plain insert (prior behavior).
148
+ enabled: z.boolean().default(true),
149
+ // Optional Tier-0 external judge (OpenAI-compatible). null/unset → local
150
+ // heuristic only, ZERO egress. When set, candidate + related records egress
151
+ // ONLY to this operator-chosen endpoint; any error falls back to heuristic.
152
+ judgeEndpoint: z.string().url().refine((s) => /^https?:\/\//i.test(s), {
153
+ message: "memory.contradiction.judgeEndpoint must be an http(s) URL"
154
+ }).optional(),
155
+ // Cosine similarity above which a correction-flavored new record is treated
156
+ // as superseding a related existing record. Calibrated to all-MiniLM-L6-v2
157
+ // (same-topic contradictions ≈0.65–0.86; related-but-complementary ≈0.47).
158
+ similarityThreshold: z.number().min(0).max(1).default(0.6),
159
+ // Cosine similarity above which a new record is a near-duplicate (NOOP).
160
+ dedupThreshold: z.number().min(0).max(1).default(0.93),
161
+ // Observation types the gate runs for. High-volume 'file_change' is
162
+ // deliberately excluded so the hot path never triggers a hybridSearch.
163
+ gatedTypes: z.array(z.string()).default(["decision", "cr_violation", "failed_attempt"]),
164
+ // When true, superseded rows may still surface in recall with a
165
+ // "(superseded on <date> by #<id>)" annotation instead of being excluded.
166
+ annotateSuperseded: z.boolean().default(false),
167
+ // Time budget (ms) for the contradiction check; exceeded → fail-open (ADD).
168
+ budgetMs: z.number().int().positive().default(800)
169
+ }).default({}),
170
+ // --- Background consolidation, the "sleep-time" pass
171
+ // (plan-living-memory-slice-3-consolidation) ---
172
+ // Keeps memory sharp over years: dedupes, distills dying sessions into
173
+ // durable lessons, spots corrections you keep repeating, reweights by what
174
+ // actually gets used, and retires dead weight by EXPIRING it (never deleting).
175
+ //
176
+ // Runs with ZERO LLM and ZERO network by default — every stage is arithmetic
177
+ // plus the embedding model Massu already bundles. `llmEndpoint` is OPTIONAL
178
+ // and upgrades the prose of session summaries ONLY.
179
+ consolidation: z.object({
180
+ enabled: z.boolean().default(true),
181
+ // Bounded sweep at session end — the automatic path (no scheduler needed).
182
+ sessionSweepEnabled: z.boolean().default(true),
183
+ // OPTIONAL local/remote OpenAI-compatible chat endpoint. UNSET = zero egress.
184
+ // When set, session text egresses ONLY to this endpoint you chose.
185
+ // NOTE: the API key is NEVER configured here — it is read exclusively from
186
+ // the MASSU_MEMORY_LLM_API_KEY env var, so a key can never be committed.
187
+ llmEndpoint: z.string().url().refine((s) => /^https?:\/\//i.test(s), {
188
+ message: "memory.consolidation.llmEndpoint must be an http(s) URL"
189
+ }).optional(),
190
+ // Model NAME/ALIAS sent to llmEndpoint (e.g. "llama3.1:8b").
191
+ llmModel: z.string().optional(),
192
+ // Distill a session once its newest turn is older than this. Must stay
193
+ // INSIDE the 7-day conversation_turns prune window or the raw material is
194
+ // destroyed before it is ever summarized.
195
+ summarizeAfterDays: z.number().int().positive().default(5),
196
+ // Age past which an unprotected, never-retrieved, low-importance row may expire.
197
+ retentionDays: z.number().int().positive().default(90),
198
+ importanceFloor: z.number().int().min(1).max(5).default(2),
199
+ // Types that may NEVER expire, however old.
200
+ protectedTypes: z.array(z.string()).default(["decision", "cr_violation", "incident_near_miss"]),
201
+ // Days the retrieval counter must observe usage BEFORE any expiry is armed.
202
+ // The cold-start guard: on a fresh counter nothing has "ever been
203
+ // retrieved", so without this the first pass would gut the store.
204
+ usageWarmupDays: z.number().int().nonnegative().default(30),
205
+ // Per-pass decay on the windowed hit count, so usefulness must be sustained.
206
+ usageDecay: z.number().min(0).max(1).default(0.9),
207
+ // A record is reweighted at most once per this many days (idempotency).
208
+ reweightIntervalDays: z.number().int().positive().default(1),
209
+ // Recurrences (across >= 2 sessions) before a rule candidate is proposed.
210
+ promoteMinOccurrences: z.number().int().positive().default(3),
211
+ budgetMs: z.number().int().positive().default(3e3),
212
+ // Surface optional upgrades (e.g. "a local model was detected") in chat.
213
+ suggestUpgrades: z.boolean().default(true),
214
+ suggestIntervalDays: z.number().int().positive().default(30)
215
+ }).default({}),
216
+ // A-20 (Slice 4) — memory FILES: the mirror, and the one switch that decides whether
217
+ // Massu may ever WRITE into the user's memory directory.
218
+ //
219
+ // ⛔ `renderEnabled` DEFAULTS TO FALSE. 4B is the first capability in Massu's history
220
+ // that writes files into the place the user keeps their own hand-written prose. A new
221
+ // write capability that arrives switched-on in an `npm update` is a capability nobody
222
+ // consented to. The path is: the advisor OFFERS it in chat -> the user runs
223
+ // `massu memory render --dry-run` and sees exactly what WOULD be written -> the user
224
+ // turns it on. Three deliberate steps, none implicit. A drift-guard pins this default.
225
+ files: z.object({
226
+ // The lossless file<->store mirror (ingest side). Read-only; it writes nothing.
227
+ enabled: z.boolean().default(true),
228
+ // The ONLY flag here that grants a WRITE. Never auto-enable.
229
+ renderEnabled: z.boolean().default(false),
230
+ // Anti-spam: files Massu may render in ONE session.
231
+ renderMaxFilesPerSession: z.number().int().min(0).default(3),
232
+ // Only memories at/above this importance are worth a durable file.
233
+ renderMinImportance: z.number().int().min(1).max(5).default(4),
234
+ // The clearly-labelled MEMORY.md section Massu's pointers live under.
235
+ indexSection: z.string().default("Learned by Massu"),
236
+ // Hard bound on the managed MEMORY.md region. MEMORY.md is auto-loaded into EVERY
237
+ // turn of EVERY session, so an unbounded index is a permanent context tax — and the
238
+ // per-session cap bounds only the RATE, never the total.
239
+ indexMaxLines: z.number().int().min(1).default(50)
240
+ }).default({})
241
+ }).optional();
242
+ }
315
243
  });
316
- var LanguageFrameworkEntrySchema = z.object({
317
- framework: z.string().optional(),
318
- test_framework: z.string().optional(),
319
- test: z.string().optional(),
320
- runtime: z.string().optional(),
321
- orm: z.string().optional(),
322
- router: z.string().optional(),
323
- ui: z.string().optional()
324
- }).passthrough();
325
- var FrameworkConfigSchema = z.object({
326
- type: z.string().default("typescript"),
327
- primary: z.string().optional(),
328
- router: z.string().default("none"),
329
- orm: z.string().default("none"),
330
- ui: z.string().default("none"),
331
- languages: z.record(z.string(), LanguageFrameworkEntrySchema).optional()
332
- }).passthrough();
333
- var DetectedConfigSchema = z.object({}).passthrough().optional();
334
- var VerificationEntrySchema = z.object({
335
- type: z.string().optional(),
336
- test: z.string().optional(),
337
- syntax: z.string().optional(),
338
- lint: z.string().optional(),
339
- build: z.string().optional()
340
- }).passthrough();
341
- var VerificationConfigSchema = z.record(z.string(), VerificationEntrySchema).optional();
342
- var CanonicalPathsSchema = z.record(z.string(), z.string()).optional();
343
- var VerificationTypesSchema = z.record(z.string(), z.string()).optional();
344
- var DetectionRuleEntrySchema = z.object({
345
- signals: z.array(z.string()).default([]),
346
- priority: z.number().optional()
347
- }).passthrough();
348
- var DetectionConfigSchema = z.object({
349
- rules: z.record(
350
- z.string(),
351
- // language
352
- z.record(z.string(), DetectionRuleEntrySchema)
353
- // framework -> rule entry
354
- ).optional(),
355
- signal_weights: z.record(z.string(), z.number()).optional(),
356
- disable_builtin: z.boolean().optional()
357
- }).passthrough().optional();
358
- var WatchConfigSchema = z.object({
359
- debounce_ms: z.number().int().positive().default(3e3),
360
- storm_threshold: z.number().int().positive().default(50),
361
- deep_storm_threshold: z.number().int().positive().default(500),
362
- hard_timeout_ms: z.number().int().positive().default(3e5),
363
- scope: z.enum(["paths", "full"]).default("paths"),
364
- // Plan 3a hotfix 2026-05-02: refuse to start if the watch surface
365
- // exceeds this many files. Prevents the misconfig pattern where
366
- // `paths.source_dirs` includes `.` or otherwise expands to a 60K+
367
- // file tree, producing 30-100% steady CPU. Override via
368
- // `paths_full_root_opt_in: true` for users on small repos who genuinely
369
- // need root-level watching.
370
- max_watched_files: z.number().int().positive().default(1e4),
371
- paths_full_root_opt_in: z.boolean().default(false)
372
- }).passthrough().optional();
373
- var AdapterLocalPathSchema = z.string().refine((s) => !/^([A-Za-z]:[\\/]|[\\/])/.test(s), {
374
- message: "absolute paths are rejected; adapters.local entries must be relative to the massu.config.yaml directory"
375
- }).refine((s) => !s.split(/[\\/]/).includes(".."), {
376
- message: "parent-directory traversal (`..`) is rejected; adapters.local entries must stay inside the project tree"
377
- }).transform((s) => s.split(/[\\/]/).filter((part) => part !== "" && part !== ".").join("/"));
378
- var AdaptersConfigSchema = z.object({
379
- enabled: z.boolean().default(false),
380
- local: z.array(AdapterLocalPathSchema).default([])
381
- }).passthrough().optional();
382
- var TelemetryConfigSchema = z.object({
383
- adapters: z.boolean().default(false)
384
- }).passthrough().optional();
385
- var LSPConfigSchema = z.object({
386
- enabled: z.boolean().default(false),
387
- servers: z.array(z.object({
388
- language: z.string(),
389
- command: z.string(),
390
- // F-014 (closed 2026-05-06): explicit opt-in to spawn SUID/SGID
391
- // binaries. Default false — argv[0] with the SUID bit is rejected
392
- // unless this is true. Decision is auditable in the YAML.
393
- allow_setuid: z.boolean().default(false),
394
- // F-015 (closed 2026-05-06): per-server RSS budget (MB). Watchdog
395
- // SIGKILLs the server after sustained breach. Default 1024 MB.
396
- // Set to 0 to disable the watchdog for this server.
397
- max_rss_mb: z.number().int().nonnegative().default(1024)
398
- })).default([]),
399
- autoDetect: z.object({
400
- viaPortScan: z.boolean().default(false)
401
- }).optional()
402
- }).passthrough();
403
- var RawConfigSchema = z.object({
404
- schema_version: z.union([z.literal(1), z.literal(2)]).default(1),
405
- project: z.object({
406
- name: z.string().default("my-project"),
407
- root: z.string().default("auto")
408
- }).default({ name: "my-project", root: "auto" }),
409
- framework: FrameworkConfigSchema.default({
410
- type: "typescript",
411
- router: "none",
412
- orm: "none",
413
- ui: "none"
414
- }),
415
- paths: PathsConfigSchema.default({ source: "src", aliases: { "@": "src" } }),
416
- toolPrefix: z.string().default("massu"),
417
- dbAccessPattern: z.string().optional(),
418
- knownMismatches: z.record(z.string(), z.record(z.string(), z.string())).optional(),
419
- accessScopes: z.array(z.string()).optional(),
420
- domains: z.array(DomainConfigSchema).default([]),
421
- rules: z.array(PatternRuleConfigSchema).default([]),
422
- // P-M-036 (plan-stage-d-medium-sweep): customer-authored CR-style
423
- // governance rules. DISTINCT from `rules:` above (path-scoped lint hints
424
- // used by pattern-scanner). At config-refresh time these entries are
425
- // loaded into the `knowledge_rules` SQLite table with
426
- // `source = 'customer-config'` so `massu_knowledge_rule` and the
427
- // governance docs surface customer-defined rules alongside framework CRs.
428
- governance_rules: z.array(
429
- z.object({
430
- id: z.string().min(1, "governance_rules[].id is required"),
431
- title: z.string().min(1, "governance_rules[].title is required"),
432
- description: z.string().min(1, "governance_rules[].description is required"),
433
- vr_type: z.string().default("VR-CUSTOM"),
434
- reference_path: z.string().optional(),
435
- severity: z.enum(["critical", "high", "medium", "low", "info"]).default("medium")
436
- }).passthrough()
437
- ).default([]),
438
- analytics: AnalyticsConfigSchema,
439
- governance: GovernanceConfigSchema,
440
- security: SecurityConfigSchema,
441
- team: TeamConfigSchema,
442
- regression: RegressionConfigSchema,
443
- cloud: CloudConfigSchema,
444
- conventions: ConventionsConfigSchema,
445
- autoLearning: AutoLearningConfigSchema,
446
- python: PythonConfigSchema,
447
- // P2-004 / P2-005 / P2-006 / P2-008: v2 extensions (all optional)
448
- verification: VerificationConfigSchema,
449
- canonical_paths: CanonicalPathsSchema,
450
- verification_types: VerificationTypesSchema,
451
- detection: DetectionConfigSchema,
452
- // Plan #2: detector-owned per-language conventions (free-form passthrough)
453
- detected: DetectedConfigSchema,
454
- // Plan 3a: file-watcher daemon tunables
455
- watch: WatchConfigSchema,
456
- // Plan 3c: third-party adapter registry kill-switch + signing override + local-path opt-in.
457
- adapters: AdaptersConfigSchema,
458
- // Plan 3c: anonymous adapter-discovery telemetry opt-in (default off).
459
- telemetry: TelemetryConfigSchema,
460
- // Plan 3b Phase 4: optional LSP enrichment of AST adapter results.
461
- lsp: LSPConfigSchema.optional()
462
- }).passthrough();
463
- var _config = null;
464
- var _resolvedApiKeySource = "none";
465
- var _projectRoot = null;
244
+
245
+ // src/config.ts
246
+ import { resolve as resolve2, dirname } from "path";
247
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
248
+ import { homedir as homedir2 } from "os";
249
+ import { parse as parseYaml } from "yaml";
250
+ import { z as z2 } from "zod";
466
251
  function findProjectRoot() {
467
252
  const cwd = process.cwd();
468
253
  let dir = cwd;
@@ -562,6 +347,7 @@ Hint: run \`massu config refresh\` to regenerate a valid config or fix the liste
562
347
  team: parsed.team,
563
348
  regression: parsed.regression,
564
349
  cloud: parsed.cloud,
350
+ memory: parsed.memory,
565
351
  conventions: parsed.conventions,
566
352
  autoLearning: parsed.autoLearning,
567
353
  python: parsed.python,
@@ -626,11 +412,2917 @@ function getResolvedPaths() {
626
412
  settingsLocalPath: resolve2(root, claudeDirName, "settings.local.json")
627
413
  };
628
414
  }
415
+ var DomainConfigSchema, PatternRuleConfigSchema, CostModelSchema, AnalyticsConfigSchema, CustomPatternSchema, GovernanceConfigSchema, SecurityPatternSchema, SecurityConfigSchema, TeamConfigSchema, RegressionConfigSchema, AutoLearningConfigSchema, CloudConfigSchema, ConventionsConfigSchema, PythonDomainConfigSchema, PythonConfigSchema, PathsConfigSchema, LanguageFrameworkEntrySchema, FrameworkConfigSchema, DetectedConfigSchema, VerificationEntrySchema, VerificationConfigSchema, CanonicalPathsSchema, VerificationTypesSchema, DetectionRuleEntrySchema, DetectionConfigSchema, WatchConfigSchema, AdapterLocalPathSchema, AdaptersConfigSchema, TelemetryConfigSchema, LSPConfigSchema, RawConfigSchema, _config, _resolvedApiKeySource, _projectRoot;
416
+ var init_config = __esm({
417
+ "src/config.ts"() {
418
+ "use strict";
419
+ init_memory_path();
420
+ init_credentials();
421
+ init_config_memory_schema();
422
+ DomainConfigSchema = z2.object({
423
+ name: z2.string().default("Unknown"),
424
+ routers: z2.array(z2.string()).default([]),
425
+ pages: z2.array(z2.string()).default([]),
426
+ tables: z2.array(z2.string()).default([]),
427
+ allowedImportsFrom: z2.array(z2.string()).default([])
428
+ });
429
+ PatternRuleConfigSchema = z2.object({
430
+ pattern: z2.string().default("**"),
431
+ rules: z2.array(z2.string()).default([]),
432
+ language: z2.string().optional()
433
+ });
434
+ CostModelSchema = z2.object({
435
+ input_per_million: z2.number(),
436
+ output_per_million: z2.number(),
437
+ cache_read_per_million: z2.number().optional(),
438
+ cache_write_per_million: z2.number().optional()
439
+ });
440
+ AnalyticsConfigSchema = z2.object({
441
+ quality: z2.object({
442
+ weights: z2.record(z2.string(), z2.number()).default({
443
+ bug_found: -5,
444
+ vr_failure: -10,
445
+ incident: -20,
446
+ cr_violation: -3,
447
+ vr_pass: 2,
448
+ clean_commit: 5,
449
+ successful_verification: 3
450
+ }),
451
+ categories: z2.array(z2.string()).default(["security", "architecture", "coupling", "tests", "rule_compliance"])
452
+ }).optional(),
453
+ cost: z2.object({
454
+ models: z2.record(z2.string(), CostModelSchema).default({}),
455
+ currency: z2.string().default("USD")
456
+ }).optional(),
457
+ prompts: z2.object({
458
+ success_indicators: z2.array(z2.string()).default(["committed", "approved", "looks good", "perfect", "great", "thanks"]),
459
+ failure_indicators: z2.array(z2.string()).default(["revert", "wrong", "that's not", "undo", "incorrect"]),
460
+ max_turns_for_success: z2.number().default(2)
461
+ }).optional()
462
+ }).optional();
463
+ CustomPatternSchema = z2.object({
464
+ pattern: z2.string(),
465
+ severity: z2.string(),
466
+ message: z2.string()
467
+ });
468
+ GovernanceConfigSchema = z2.object({
469
+ audit: z2.object({
470
+ formats: z2.array(z2.string()).default(["summary", "detailed", "soc2"]),
471
+ retention_days: z2.number().default(365),
472
+ auto_log: z2.record(z2.string(), z2.boolean()).default({
473
+ code_changes: true,
474
+ rule_enforcement: true,
475
+ approvals: true,
476
+ commits: true
477
+ })
478
+ }).optional(),
479
+ validation: z2.object({
480
+ realtime: z2.boolean().default(true),
481
+ checks: z2.record(z2.string(), z2.boolean()).default({
482
+ rule_compliance: true,
483
+ import_existence: true,
484
+ naming_conventions: true
485
+ }),
486
+ custom_patterns: z2.array(CustomPatternSchema).default([])
487
+ }).optional(),
488
+ adr: z2.object({
489
+ detection_phrases: z2.array(z2.string()).default(["chose", "decided", "switching to", "moving from", "going with"]),
490
+ template: z2.string().default("default"),
491
+ storage: z2.string().default("database"),
492
+ output_dir: z2.string().default("docs/adr")
493
+ }).optional()
494
+ }).optional();
495
+ SecurityPatternSchema = z2.object({
496
+ pattern: z2.string(),
497
+ severity: z2.string(),
498
+ category: z2.string(),
499
+ description: z2.string()
500
+ });
501
+ SecurityConfigSchema = z2.object({
502
+ patterns: z2.array(SecurityPatternSchema).default([]),
503
+ auto_score_on_edit: z2.boolean().default(true),
504
+ score_threshold_alert: z2.number().default(50),
505
+ severity_weights: z2.record(z2.string(), z2.number()).optional(),
506
+ restrictive_licenses: z2.array(z2.string()).optional(),
507
+ dep_alternatives: z2.record(z2.string(), z2.array(z2.string())).optional(),
508
+ dependencies: z2.object({
509
+ package_manager: z2.string().default("npm"),
510
+ blocked_packages: z2.array(z2.string()).default([]),
511
+ preferred_packages: z2.record(z2.string(), z2.string()).default({}),
512
+ max_bundle_size_kb: z2.number().default(500)
513
+ }).optional()
514
+ }).optional();
515
+ TeamConfigSchema = z2.object({
516
+ enabled: z2.boolean().default(false),
517
+ sync_backend: z2.string().default("local"),
518
+ developer_id: z2.string().default("auto"),
519
+ share_by_default: z2.boolean().default(false),
520
+ expertise_weights: z2.object({
521
+ session: z2.number().default(20),
522
+ observation: z2.number().default(10)
523
+ }).optional(),
524
+ privacy: z2.object({
525
+ share_file_paths: z2.boolean().default(true),
526
+ share_code_snippets: z2.boolean().default(false),
527
+ share_observations: z2.boolean().default(true)
528
+ }).optional()
529
+ }).optional();
530
+ RegressionConfigSchema = z2.object({
531
+ test_patterns: z2.array(z2.string()).default([
532
+ "{dir}/__tests__/{name}.test.{ext}",
533
+ "{dir}/{name}.spec.{ext}",
534
+ "tests/{path}.test.{ext}"
535
+ ]),
536
+ test_runner: z2.string().default("npm test"),
537
+ health_thresholds: z2.object({
538
+ healthy: z2.number().default(80),
539
+ warning: z2.number().default(50)
540
+ }).optional()
541
+ }).optional();
542
+ AutoLearningConfigSchema = z2.object({
543
+ enabled: z2.boolean().default(true),
544
+ incidentDir: z2.string().default("docs/incidents"),
545
+ memoryDir: z2.string().default("memory"),
546
+ memoryIndexFile: z2.string().default("MEMORY.md"),
547
+ enforcementHooksDir: z2.string().default("scripts/hooks"),
548
+ fixDetection: z2.object({
549
+ enabled: z2.boolean().default(true),
550
+ lookbackDays: z2.number().default(7),
551
+ signals: z2.array(z2.string()).default([
552
+ "removed_broken_code",
553
+ "added_error_handling",
554
+ "method_name_correction",
555
+ "auth_fix",
556
+ "nil_handling_fix",
557
+ "concurrency_fix",
558
+ "async_pattern_fix",
559
+ "added_missing_import"
560
+ ])
561
+ }).default({}),
562
+ failureClassification: z2.object({
563
+ enabled: z2.boolean().default(true),
564
+ thresholds: z2.object({
565
+ known: z2.number().default(5),
566
+ similar: z2.number().default(3)
567
+ }).default({}),
568
+ scoring: z2.object({
569
+ diffPatternWeight: z2.number().default(3),
570
+ filePatternWeight: z2.number().default(2),
571
+ promptKeywordWeight: z2.number().default(2)
572
+ }).default({})
573
+ }).default({}),
574
+ pipeline: z2.object({
575
+ requireIncidentReport: z2.boolean().default(true),
576
+ requirePreventionRule: z2.boolean().default(true),
577
+ requireEnforcement: z2.boolean().default(true)
578
+ }).default({}),
579
+ // plan-v0.2-interactive-rule-approval P-D-008 / P-D-009: project-configured
580
+ // custom destinations for the rule-candidate funnel. The classifier matches
581
+ // a candidate to one of these entries when none of the framework
582
+ // destinations (pattern-scanner / claude-md-cr / corrections-md) apply.
583
+ customDestinations: z2.array(z2.object({
584
+ name: z2.string(),
585
+ path: z2.string(),
586
+ triggerKeywords: z2.array(z2.string()).default([]),
587
+ template: z2.string()
588
+ })).default([])
589
+ }).optional();
590
+ CloudConfigSchema = z2.object({
591
+ enabled: z2.boolean().default(false),
592
+ apiKey: z2.string().optional(),
593
+ endpoint: z2.string().optional(),
594
+ sync: z2.object({
595
+ memory: z2.boolean().default(true),
596
+ analytics: z2.boolean().default(true),
597
+ audit: z2.boolean().default(true)
598
+ }).default({ memory: true, analytics: true, audit: true })
599
+ }).optional();
600
+ ConventionsConfigSchema = z2.object({
601
+ claudeDirName: z2.string().default(".claude").refine(
602
+ (s) => !s.includes("..") && !s.startsWith("/"),
603
+ { message: 'claudeDirName must not contain ".." or start with "/"' }
604
+ ),
605
+ sessionStatePath: z2.string().default(".claude/session-state/CURRENT.md").refine(
606
+ (s) => !s.includes("..") && !s.startsWith("/"),
607
+ { message: 'sessionStatePath must not contain ".." or start with "/"' }
608
+ ),
609
+ sessionArchivePath: z2.string().default(".claude/session-state/archive").refine(
610
+ (s) => !s.includes("..") && !s.startsWith("/"),
611
+ { message: 'sessionArchivePath must not contain ".." or start with "/"' }
612
+ ),
613
+ knowledgeCategories: z2.array(z2.string()).default([
614
+ "patterns",
615
+ "commands",
616
+ "incidents",
617
+ "reference",
618
+ "protocols",
619
+ "checklists",
620
+ "playbooks",
621
+ "critical",
622
+ "scripts",
623
+ "status",
624
+ "templates",
625
+ "loop-state",
626
+ "session-state",
627
+ "agents"
628
+ ]),
629
+ knowledgeSourceFiles: z2.array(z2.string()).default(["CLAUDE.md", "MEMORY.md", "corrections.md"]),
630
+ excludePatterns: z2.array(z2.string()).default(["/ARCHIVE/", "/SESSION-HISTORY/"])
631
+ }).optional();
632
+ PythonDomainConfigSchema = z2.object({
633
+ name: z2.string(),
634
+ packages: z2.array(z2.string()),
635
+ allowed_imports_from: z2.array(z2.string()).default([])
636
+ });
637
+ PythonConfigSchema = z2.object({
638
+ root: z2.string(),
639
+ alembic_dir: z2.string().optional(),
640
+ domains: z2.array(PythonDomainConfigSchema).default([]),
641
+ exclude_dirs: z2.array(z2.string()).default(["__pycache__", ".venv", "venv", ".mypy_cache", ".pytest_cache"])
642
+ }).optional();
643
+ PathsConfigSchema = z2.object({
644
+ source: z2.string().default("src"),
645
+ aliases: z2.record(z2.string(), z2.string()).default({ "@": "src" }),
646
+ monorepo_roots: z2.array(z2.string()).optional(),
647
+ routers: z2.string().optional(),
648
+ routerRoot: z2.string().optional(),
649
+ pages: z2.string().optional(),
650
+ middleware: z2.string().optional(),
651
+ schema: z2.string().optional(),
652
+ components: z2.string().optional(),
653
+ hooks: z2.string().optional()
654
+ });
655
+ LanguageFrameworkEntrySchema = z2.object({
656
+ framework: z2.string().optional(),
657
+ test_framework: z2.string().optional(),
658
+ test: z2.string().optional(),
659
+ runtime: z2.string().optional(),
660
+ orm: z2.string().optional(),
661
+ router: z2.string().optional(),
662
+ ui: z2.string().optional()
663
+ }).passthrough();
664
+ FrameworkConfigSchema = z2.object({
665
+ type: z2.string().default("typescript"),
666
+ primary: z2.string().optional(),
667
+ router: z2.string().default("none"),
668
+ orm: z2.string().default("none"),
669
+ ui: z2.string().default("none"),
670
+ languages: z2.record(z2.string(), LanguageFrameworkEntrySchema).optional()
671
+ }).passthrough();
672
+ DetectedConfigSchema = z2.object({}).passthrough().optional();
673
+ VerificationEntrySchema = z2.object({
674
+ type: z2.string().optional(),
675
+ test: z2.string().optional(),
676
+ syntax: z2.string().optional(),
677
+ lint: z2.string().optional(),
678
+ build: z2.string().optional()
679
+ }).passthrough();
680
+ VerificationConfigSchema = z2.record(z2.string(), VerificationEntrySchema).optional();
681
+ CanonicalPathsSchema = z2.record(z2.string(), z2.string()).optional();
682
+ VerificationTypesSchema = z2.record(z2.string(), z2.string()).optional();
683
+ DetectionRuleEntrySchema = z2.object({
684
+ signals: z2.array(z2.string()).default([]),
685
+ priority: z2.number().optional()
686
+ }).passthrough();
687
+ DetectionConfigSchema = z2.object({
688
+ rules: z2.record(
689
+ z2.string(),
690
+ // language
691
+ z2.record(z2.string(), DetectionRuleEntrySchema)
692
+ // framework -> rule entry
693
+ ).optional(),
694
+ signal_weights: z2.record(z2.string(), z2.number()).optional(),
695
+ disable_builtin: z2.boolean().optional()
696
+ }).passthrough().optional();
697
+ WatchConfigSchema = z2.object({
698
+ debounce_ms: z2.number().int().positive().default(3e3),
699
+ storm_threshold: z2.number().int().positive().default(50),
700
+ deep_storm_threshold: z2.number().int().positive().default(500),
701
+ hard_timeout_ms: z2.number().int().positive().default(3e5),
702
+ scope: z2.enum(["paths", "full"]).default("paths"),
703
+ // Plan 3a hotfix 2026-05-02: refuse to start if the watch surface
704
+ // exceeds this many files. Prevents the misconfig pattern where
705
+ // `paths.source_dirs` includes `.` or otherwise expands to a 60K+
706
+ // file tree, producing 30-100% steady CPU. Override via
707
+ // `paths_full_root_opt_in: true` for users on small repos who genuinely
708
+ // need root-level watching.
709
+ max_watched_files: z2.number().int().positive().default(1e4),
710
+ paths_full_root_opt_in: z2.boolean().default(false)
711
+ }).passthrough().optional();
712
+ AdapterLocalPathSchema = z2.string().refine((s) => !/^([A-Za-z]:[\\/]|[\\/])/.test(s), {
713
+ message: "absolute paths are rejected; adapters.local entries must be relative to the massu.config.yaml directory"
714
+ }).refine((s) => !s.split(/[\\/]/).includes(".."), {
715
+ message: "parent-directory traversal (`..`) is rejected; adapters.local entries must stay inside the project tree"
716
+ }).transform((s) => s.split(/[\\/]/).filter((part) => part !== "" && part !== ".").join("/"));
717
+ AdaptersConfigSchema = z2.object({
718
+ enabled: z2.boolean().default(false),
719
+ local: z2.array(AdapterLocalPathSchema).default([])
720
+ }).passthrough().optional();
721
+ TelemetryConfigSchema = z2.object({
722
+ adapters: z2.boolean().default(false)
723
+ }).passthrough().optional();
724
+ LSPConfigSchema = z2.object({
725
+ enabled: z2.boolean().default(false),
726
+ servers: z2.array(z2.object({
727
+ language: z2.string(),
728
+ command: z2.string(),
729
+ // F-014 (closed 2026-05-06): explicit opt-in to spawn SUID/SGID
730
+ // binaries. Default false — argv[0] with the SUID bit is rejected
731
+ // unless this is true. Decision is auditable in the YAML.
732
+ allow_setuid: z2.boolean().default(false),
733
+ // F-015 (closed 2026-05-06): per-server RSS budget (MB). Watchdog
734
+ // SIGKILLs the server after sustained breach. Default 1024 MB.
735
+ // Set to 0 to disable the watchdog for this server.
736
+ max_rss_mb: z2.number().int().nonnegative().default(1024)
737
+ })).default([]),
738
+ autoDetect: z2.object({
739
+ viaPortScan: z2.boolean().default(false)
740
+ }).optional()
741
+ }).passthrough();
742
+ RawConfigSchema = z2.object({
743
+ schema_version: z2.union([z2.literal(1), z2.literal(2)]).default(1),
744
+ project: z2.object({
745
+ name: z2.string().default("my-project"),
746
+ root: z2.string().default("auto")
747
+ }).default({ name: "my-project", root: "auto" }),
748
+ framework: FrameworkConfigSchema.default({
749
+ type: "typescript",
750
+ router: "none",
751
+ orm: "none",
752
+ ui: "none"
753
+ }),
754
+ paths: PathsConfigSchema.default({ source: "src", aliases: { "@": "src" } }),
755
+ toolPrefix: z2.string().default("massu"),
756
+ dbAccessPattern: z2.string().optional(),
757
+ knownMismatches: z2.record(z2.string(), z2.record(z2.string(), z2.string())).optional(),
758
+ accessScopes: z2.array(z2.string()).optional(),
759
+ domains: z2.array(DomainConfigSchema).default([]),
760
+ rules: z2.array(PatternRuleConfigSchema).default([]),
761
+ // P-M-036 (plan-stage-d-medium-sweep): customer-authored CR-style
762
+ // governance rules. DISTINCT from `rules:` above (path-scoped lint hints
763
+ // used by pattern-scanner). At config-refresh time these entries are
764
+ // loaded into the `knowledge_rules` SQLite table with
765
+ // `source = 'customer-config'` so `massu_knowledge_rule` and the
766
+ // governance docs surface customer-defined rules alongside framework CRs.
767
+ governance_rules: z2.array(
768
+ z2.object({
769
+ id: z2.string().min(1, "governance_rules[].id is required"),
770
+ title: z2.string().min(1, "governance_rules[].title is required"),
771
+ description: z2.string().min(1, "governance_rules[].description is required"),
772
+ vr_type: z2.string().default("VR-CUSTOM"),
773
+ reference_path: z2.string().optional(),
774
+ severity: z2.enum(["critical", "high", "medium", "low", "info"]).default("medium")
775
+ }).passthrough()
776
+ ).default([]),
777
+ analytics: AnalyticsConfigSchema,
778
+ governance: GovernanceConfigSchema,
779
+ security: SecurityConfigSchema,
780
+ team: TeamConfigSchema,
781
+ regression: RegressionConfigSchema,
782
+ cloud: CloudConfigSchema,
783
+ // plan-living-memory-slice-1 P6-002: automatic-recall tunables.
784
+ memory: MemoryConfigSchema,
785
+ conventions: ConventionsConfigSchema,
786
+ autoLearning: AutoLearningConfigSchema,
787
+ python: PythonConfigSchema,
788
+ // P2-004 / P2-005 / P2-006 / P2-008: v2 extensions (all optional)
789
+ verification: VerificationConfigSchema,
790
+ canonical_paths: CanonicalPathsSchema,
791
+ verification_types: VerificationTypesSchema,
792
+ detection: DetectionConfigSchema,
793
+ // Plan #2: detector-owned per-language conventions (free-form passthrough)
794
+ detected: DetectedConfigSchema,
795
+ // Plan 3a: file-watcher daemon tunables
796
+ watch: WatchConfigSchema,
797
+ // Plan 3c: third-party adapter registry kill-switch + signing override + local-path opt-in.
798
+ adapters: AdaptersConfigSchema,
799
+ // Plan 3c: anonymous adapter-discovery telemetry opt-in (default off).
800
+ telemetry: TelemetryConfigSchema,
801
+ // Plan 3b Phase 4: optional LSP enrichment of AST adapter results.
802
+ lsp: LSPConfigSchema.optional()
803
+ }).passthrough();
804
+ _config = null;
805
+ _resolvedApiKeySource = "none";
806
+ _projectRoot = null;
807
+ }
808
+ });
809
+
810
+ // src/memory-vector.ts
811
+ function float32ToBlob(vec) {
812
+ return Buffer.from(new Uint8Array(vec.buffer, vec.byteOffset, vec.byteLength));
813
+ }
814
+ function l2normalize(vec) {
815
+ let sumSq = 0;
816
+ for (let i = 0; i < vec.length; i++) sumSq += vec[i] * vec[i];
817
+ const norm = Math.sqrt(sumSq);
818
+ if (norm === 0 || !Number.isFinite(norm)) return vec;
819
+ const out = new Float32Array(vec.length);
820
+ for (let i = 0; i < vec.length; i++) out[i] = vec[i] / norm;
821
+ return out;
822
+ }
823
+ var init_memory_vector = __esm({
824
+ "src/memory-vector.ts"() {
825
+ "use strict";
826
+ }
827
+ });
629
828
 
630
- // src/memory-db.ts
829
+ // src/db-backup.ts
631
830
  import Database from "better-sqlite3";
831
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readdirSync, statSync, unlinkSync, copyFileSync, rmSync as rmSync2 } from "fs";
832
+ import { resolve as resolve3, join, basename, dirname as dirname2 } from "path";
833
+ import { homedir as homedir3 } from "os";
834
+ function dbBackupsRoot(home = homedir3()) {
835
+ return resolve3(home, ".massu", "db-backups");
836
+ }
837
+ function projectBackupDir(projectRoot, home = homedir3()) {
838
+ const slug = basename(projectRoot).replace(/[^A-Za-z0-9._-]/g, "_") || "project";
839
+ return join(dbBackupsRoot(home), slug);
840
+ }
841
+ function backupStamp(nowMs) {
842
+ return new Date(nowMs).toISOString().replace(/[:.]/g, "-");
843
+ }
844
+ function listDbBackups(projectRoot, home = homedir3()) {
845
+ const dir = projectBackupDir(projectRoot, home);
846
+ if (!existsSync3(dir)) return [];
847
+ const out = [];
848
+ for (const f of readdirSync(dir)) {
849
+ if (!f.endsWith(".db")) continue;
850
+ const p = join(dir, f);
851
+ const st = statSync(p);
852
+ const db = f.replace(/-\d{4}-\d{2}-\d{2}T.*$/, "");
853
+ out.push({ db, path: p, bytes: st.size, mtimeMs: st.mtimeMs });
854
+ }
855
+ return out.sort((a, b) => b.mtimeMs - a.mtimeMs);
856
+ }
857
+ function hasFreshDbBackup(projectRoot, dbPath, nowMs = Date.now(), home = homedir3()) {
858
+ const name = basename(dbPath, ".db");
859
+ const backups = listDbBackups(projectRoot, home).filter((b) => b.db === name);
860
+ if (backups.length === 0) return false;
861
+ const newest = backups[0];
862
+ if (nowMs - newest.mtimeMs > FRESH_WINDOW_MS) return false;
863
+ if (existsSync3(dbPath) && statSync(dbPath).mtimeMs > newest.mtimeMs) return false;
864
+ return true;
865
+ }
866
+ function integrityOk(dbPath) {
867
+ let db = null;
868
+ try {
869
+ db = new Database(dbPath, { readonly: true });
870
+ const rows = db.pragma("integrity_check");
871
+ return rows.length === 1 && rows[0].integrity_check === "ok";
872
+ } catch {
873
+ return false;
874
+ } finally {
875
+ try {
876
+ db?.close();
877
+ } catch {
878
+ }
879
+ }
880
+ }
881
+ function backupDb(projectRoot, dbPath, nowMs = Date.now(), home = homedir3()) {
882
+ if (!existsSync3(dbPath)) {
883
+ throw new DbBackupError(`cannot back up a database that does not exist: ${dbPath}`);
884
+ }
885
+ const dir = projectBackupDir(projectRoot, home);
886
+ mkdirSync2(dir, { recursive: true });
887
+ const name = basename(dbPath, ".db");
888
+ const dest = join(dir, `${name}-${backupStamp(nowMs)}.db`);
889
+ let src = null;
890
+ try {
891
+ src = new Database(dbPath, { readonly: true });
892
+ src.exec(`VACUUM INTO '${dest.replace(/'/g, "''")}'`);
893
+ } catch (err) {
894
+ throw new DbBackupError(
895
+ `VACUUM INTO failed for ${dbPath}: ${err instanceof Error ? err.message : String(err)}`
896
+ );
897
+ } finally {
898
+ try {
899
+ src?.close();
900
+ } catch {
901
+ }
902
+ }
903
+ if (!integrityOk(dest)) {
904
+ try {
905
+ unlinkSync(dest);
906
+ } catch {
907
+ }
908
+ throw new DbBackupError(
909
+ `the backup of ${dbPath} FAILED its own integrity check and was deleted. A corrupt backup is worse than none \u2014 you only discover it when you need it.`
910
+ );
911
+ }
912
+ pruneDbBackups(projectRoot, name, DEFAULT_RETENTION, home);
913
+ const st = statSync(dest);
914
+ return { db: name, path: dest, bytes: st.size, mtimeMs: st.mtimeMs };
915
+ }
916
+ function pruneDbBackups(projectRoot, dbName, keep = DEFAULT_RETENTION, home = homedir3()) {
917
+ const mine = listDbBackups(projectRoot, home).filter((b) => b.db === dbName);
918
+ let removed = 0;
919
+ for (const old of mine.slice(keep)) {
920
+ try {
921
+ unlinkSync(old.path);
922
+ removed++;
923
+ } catch {
924
+ }
925
+ }
926
+ return removed;
927
+ }
928
+ function backupBeforeSchemaChange(projectRoot, dbPath, onError, nowMs = Date.now(), home = homedir3()) {
929
+ try {
930
+ if (!existsSync3(dbPath)) return null;
931
+ if (hasFreshDbBackup(projectRoot, dbPath, nowMs, home)) return null;
932
+ return backupDb(projectRoot, dbPath, nowMs, home);
933
+ } catch (err) {
934
+ onError(err);
935
+ return null;
936
+ }
937
+ }
938
+ var DEFAULT_RETENTION, FRESH_WINDOW_MS, DbBackupError;
939
+ var init_db_backup = __esm({
940
+ "src/db-backup.ts"() {
941
+ "use strict";
942
+ DEFAULT_RETENTION = 5;
943
+ FRESH_WINDOW_MS = 24 * 60 * 60 * 1e3;
944
+ DbBackupError = class extends Error {
945
+ constructor(message) {
946
+ super(message);
947
+ this.name = "DbBackupError";
948
+ }
949
+ };
950
+ }
951
+ });
952
+
953
+ // src/hooks/lib/hook-failure-signal.ts
954
+ import { appendFileSync, mkdirSync as mkdirSync3, existsSync as existsSync4 } from "fs";
955
+ import { join as join2, dirname as dirname3 } from "path";
956
+ function resolveFailureLogPath() {
957
+ const explicit = process.env.MASSU_HOOK_FAILURE_LOG;
958
+ if (explicit) return explicit;
959
+ let dir = process.cwd();
960
+ for (let i = 0; i < 12; i++) {
961
+ if (existsSync4(join2(dir, ".massu")) || existsSync4(join2(dir, "massu.config.yaml"))) {
962
+ return join2(dir, ".massu", "hook-failures.jsonl");
963
+ }
964
+ const parent = dirname3(dir);
965
+ if (parent === dir) break;
966
+ dir = parent;
967
+ }
968
+ return join2(process.cwd(), ".massu", "hook-failures.jsonl");
969
+ }
970
+ function recordHookFailure(hook, error, context) {
971
+ const record = {
972
+ hook,
973
+ error: error instanceof Error ? error.message : String(error),
974
+ stack: error instanceof Error ? error.stack?.split("\n").slice(0, 6).join("\n") : void 0,
975
+ context,
976
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
977
+ };
978
+ let wroteSomething = false;
979
+ try {
980
+ const path = resolveFailureLogPath();
981
+ mkdirSync3(dirname3(path), { recursive: true });
982
+ appendFileSync(path, JSON.stringify(record) + "\n", "utf-8");
983
+ wroteSomething = true;
984
+ } catch {
985
+ }
986
+ try {
987
+ process.stderr.write(
988
+ `[massu] HOOK FAILURE in ${hook}: ${record.error}
989
+ [massu] This is a bug in Massu, not in your code. See .massu/hook-failures.jsonl
990
+ `
991
+ );
992
+ wroteSomething = true;
993
+ } catch {
994
+ }
995
+ try {
996
+ recordHookHealthRow(record);
997
+ } catch {
998
+ }
999
+ return wroteSomething;
1000
+ }
1001
+ function recordHookHealthRow(record) {
1002
+ const { getMemoryDb: getMemoryDb2 } = (init_memory_db(), __toCommonJS(memory_db_exports));
1003
+ const db = getMemoryDb2();
1004
+ try {
1005
+ db.prepare(
1006
+ `INSERT INTO hook_health (hook, error, context_json, occurred_at)
1007
+ VALUES (?, ?, ?, ?)`
1008
+ ).run(
1009
+ record.hook,
1010
+ record.error,
1011
+ record.context ? JSON.stringify(record.context) : null,
1012
+ record.timestamp
1013
+ );
1014
+ } finally {
1015
+ db.close();
1016
+ }
1017
+ }
1018
+ var init_hook_failure_signal = __esm({
1019
+ "src/hooks/lib/hook-failure-signal.ts"() {
1020
+ "use strict";
1021
+ }
1022
+ });
1023
+
1024
+ // src/memory-embedder-tokenizer.ts
1025
+ import { readFileSync as readFileSync3 } from "fs";
1026
+ function loadVocab(vocabPath) {
1027
+ const lines = readFileSync3(vocabPath, "utf-8").split("\n");
1028
+ const vocab = /* @__PURE__ */ new Map();
1029
+ for (let i = 0; i < lines.length; i++) {
1030
+ const tok = lines[i].replace(/\r$/, "");
1031
+ if (tok.length === 0 && i === lines.length - 1) continue;
1032
+ vocab.set(tok, i);
1033
+ }
1034
+ return vocab;
1035
+ }
1036
+ function isWhitespace(ch) {
1037
+ if (ch === " " || ch === " " || ch === "\n" || ch === "\r") return true;
1038
+ const cp = ch.codePointAt(0);
1039
+ return cp === 160 || cp >= 8192 && cp <= 8202 || cp === 8232 || cp === 8233 || cp === 8239 || cp === 8287 || cp === 12288 || cp === 65279;
1040
+ }
1041
+ function isControl(ch) {
1042
+ if (ch === " " || ch === "\n" || ch === "\r") return false;
1043
+ const cp = ch.codePointAt(0);
1044
+ return cp <= 31 || cp >= 127 && cp <= 159;
1045
+ }
1046
+ function isPunctuation(ch) {
1047
+ const cp = ch.codePointAt(0);
1048
+ if (cp >= 33 && cp <= 47 || cp >= 58 && cp <= 64 || cp >= 91 && cp <= 96 || cp >= 123 && cp <= 126)
1049
+ return true;
1050
+ return /\p{P}|\p{S}/u.test(ch);
1051
+ }
1052
+ function isCJK(cp) {
1053
+ return cp >= 19968 && cp <= 40959 || cp >= 13312 && cp <= 19903 || cp >= 131072 && cp <= 173791 || cp >= 173824 && cp <= 177983 || cp >= 177984 && cp <= 178207 || cp >= 178208 && cp <= 183983 || cp >= 63744 && cp <= 64255 || cp >= 194560 && cp <= 195103;
1054
+ }
1055
+ function stripAccents(text) {
1056
+ return text.normalize("NFD").replace(/\p{Mn}/gu, "");
1057
+ }
1058
+ function basicTokenize(text) {
1059
+ let cleaned = "";
1060
+ for (const ch of text) {
1061
+ const cp = ch.codePointAt(0);
1062
+ if (cp === 0 || cp === 65533 || isControl(ch)) continue;
1063
+ if (isWhitespace(ch)) {
1064
+ cleaned += " ";
1065
+ continue;
1066
+ }
1067
+ if (isCJK(cp)) {
1068
+ cleaned += " " + ch + " ";
1069
+ continue;
1070
+ }
1071
+ cleaned += ch;
1072
+ }
1073
+ const rawTokens = cleaned.split(/\s+/).filter(Boolean);
1074
+ const out = [];
1075
+ for (let tok of rawTokens) {
1076
+ tok = stripAccents(tok.toLowerCase());
1077
+ let cur = "";
1078
+ for (const ch of tok) {
1079
+ if (isPunctuation(ch)) {
1080
+ if (cur) {
1081
+ out.push(cur);
1082
+ cur = "";
1083
+ }
1084
+ out.push(ch);
1085
+ } else {
1086
+ cur += ch;
1087
+ }
1088
+ }
1089
+ if (cur) out.push(cur);
1090
+ }
1091
+ return out;
1092
+ }
1093
+ function wordpieceTokenize(token, vocab, maxChars = 100) {
1094
+ if (token.length > maxChars) return [UNK];
1095
+ const chars = Array.from(token);
1096
+ const subTokens = [];
1097
+ let start = 0;
1098
+ let bad = false;
1099
+ while (start < chars.length) {
1100
+ let end = chars.length;
1101
+ let curSub = null;
1102
+ while (start < end) {
1103
+ let substr = chars.slice(start, end).join("");
1104
+ if (start > 0) substr = "##" + substr;
1105
+ if (vocab.has(substr)) {
1106
+ curSub = substr;
1107
+ break;
1108
+ }
1109
+ end -= 1;
1110
+ }
1111
+ if (curSub === null) {
1112
+ bad = true;
1113
+ break;
1114
+ }
1115
+ subTokens.push(curSub);
1116
+ start = end;
1117
+ }
1118
+ return bad ? [UNK] : subTokens;
1119
+ }
1120
+ function encode(text, vocab, opts = {}) {
1121
+ const maxLen = opts.maxLen ?? 256;
1122
+ const basic = basicTokenize(text);
1123
+ const wpTokens = [];
1124
+ for (const t2 of basic) {
1125
+ for (const sub of wordpieceTokenize(t2, vocab)) wpTokens.push(sub);
1126
+ }
1127
+ const truncated = wpTokens.slice(0, maxLen - 2);
1128
+ const tokens = [CLS, ...truncated, SEP];
1129
+ const unkId = vocab.get(UNK) ?? 100;
1130
+ const input_ids = tokens.map((t2) => vocab.get(t2) ?? unkId);
1131
+ const attention_mask = tokens.map(() => 1);
1132
+ const token_type_ids = tokens.map(() => 0);
1133
+ return { tokens, input_ids, attention_mask, token_type_ids };
1134
+ }
1135
+ var UNK, CLS, SEP;
1136
+ var init_memory_embedder_tokenizer = __esm({
1137
+ "src/memory-embedder-tokenizer.ts"() {
1138
+ "use strict";
1139
+ UNK = "[UNK]";
1140
+ CLS = "[CLS]";
1141
+ SEP = "[SEP]";
1142
+ }
1143
+ });
1144
+
1145
+ // src/memory-embedder.ts
1146
+ import { fileURLToPath } from "url";
1147
+ import { dirname as dirname4, join as join3 } from "path";
1148
+ import { existsSync as existsSync5 } from "fs";
1149
+ import { createRequire } from "module";
1150
+ function getActiveEmbedModel() {
1151
+ return _activeModel;
1152
+ }
1153
+ function loadEmbedSettings() {
1154
+ try {
1155
+ const r = getConfig().memory?.recall;
1156
+ return {
1157
+ enabled: r?.embedEnabled ?? true,
1158
+ endpoint: r?.embedEndpoint,
1159
+ model: r?.embedModel
1160
+ };
1161
+ } catch {
1162
+ return { enabled: true };
1163
+ }
1164
+ }
1165
+ function embeddingsDisabled() {
1166
+ return process.env.MASSU_DISABLE_EMBEDDINGS === "1";
1167
+ }
1168
+ function resolveModelDir() {
1169
+ try {
1170
+ let dir = dirname4(fileURLToPath(import.meta.url));
1171
+ let root = null;
1172
+ for (let i = 0; i < 8; i++) {
1173
+ if (existsSync5(join3(dir, "package.json"))) {
1174
+ root = dir;
1175
+ break;
1176
+ }
1177
+ const parent = dirname4(dir);
1178
+ if (parent === dir) break;
1179
+ dir = parent;
1180
+ }
1181
+ if (!root) return null;
1182
+ for (const rel of ["dist/embedder", "assets/embedder"]) {
1183
+ const candidate = join3(root, rel);
1184
+ if (existsSync5(join3(candidate, "model_quantized.onnx"))) return candidate;
1185
+ }
1186
+ return null;
1187
+ } catch {
1188
+ return null;
1189
+ }
1190
+ }
1191
+ function resolveWasmDir() {
1192
+ try {
1193
+ const req = createRequire(import.meta.url);
1194
+ const main2 = req.resolve(ORT_PKG);
1195
+ return dirname4(main2);
1196
+ } catch {
1197
+ return null;
1198
+ }
1199
+ }
1200
+ async function getSession() {
1201
+ if (_sessionPromise) return _sessionPromise;
1202
+ _sessionPromise = (async () => {
1203
+ try {
1204
+ const modelDir = resolveModelDir();
1205
+ const wasmDir = resolveWasmDir();
1206
+ if (!modelDir || !wasmDir) return null;
1207
+ const ort = await import(
1208
+ /* @vite-ignore */
1209
+ ORT_PKG
1210
+ );
1211
+ ort.env.wasm.numThreads = 1;
1212
+ ort.env.wasm.proxy = false;
1213
+ ort.env.wasm.wasmPaths = wasmDir.endsWith("/") ? wasmDir : wasmDir + "/";
1214
+ _ortTensor = ort.Tensor;
1215
+ const modelPath = join3(modelDir, "model_quantized.onnx");
1216
+ const vocabPath = join3(modelDir, "vocab.txt");
1217
+ _vocab = loadVocab(vocabPath);
1218
+ const session = await ort.InferenceSession.create(modelPath, {
1219
+ executionProviders: ["wasm"],
1220
+ graphOptimizationLevel: "all"
1221
+ });
1222
+ return session;
1223
+ } catch {
1224
+ return null;
1225
+ }
1226
+ })();
1227
+ return _sessionPromise;
1228
+ }
1229
+ function meanPool(hidden, mask, seqLen, hiddenSize) {
1230
+ const out = new Float32Array(hiddenSize);
1231
+ let maskSum = 0;
1232
+ for (let t2 = 0; t2 < seqLen; t2++) {
1233
+ const m = mask[t2];
1234
+ if (m === 0) continue;
1235
+ maskSum += m;
1236
+ const base = t2 * hiddenSize;
1237
+ for (let h = 0; h < hiddenSize; h++) out[h] += hidden[base + h] * m;
1238
+ }
1239
+ const denom = Math.max(maskSum, 1e-9);
1240
+ for (let h = 0; h < hiddenSize; h++) out[h] /= denom;
1241
+ return out;
1242
+ }
1243
+ function chunkForEmbedding(text) {
1244
+ const t2 = text.trim();
1245
+ if (!t2) return [];
1246
+ if (t2.length <= CHUNK_TARGET_CHARS) return [t2];
1247
+ const chunks = [];
1248
+ let start = 0;
1249
+ while (start < t2.length && chunks.length < MAX_CHUNKS_PER_RECORD) {
1250
+ let end = Math.min(start + CHUNK_TARGET_CHARS, t2.length);
1251
+ if (end < t2.length) {
1252
+ const floor = start + Math.floor(CHUNK_TARGET_CHARS / 2);
1253
+ const slice = t2.slice(start, end);
1254
+ const para = slice.lastIndexOf("\n\n");
1255
+ const sent = Math.max(slice.lastIndexOf(". "), slice.lastIndexOf(".\n"));
1256
+ const space = slice.lastIndexOf(" ");
1257
+ for (const rel of [para, sent, space]) {
1258
+ const abs = start + rel;
1259
+ if (rel > 0 && abs > floor) {
1260
+ end = abs + 1;
1261
+ break;
1262
+ }
1263
+ }
1264
+ }
1265
+ const chunk = t2.slice(start, end).trim();
1266
+ if (chunk) chunks.push(chunk);
1267
+ if (end >= t2.length) break;
1268
+ start = Math.max(end - CHUNK_OVERLAP_CHARS, start + 1);
1269
+ }
1270
+ return chunks;
1271
+ }
1272
+ async function embedTier1(text) {
1273
+ try {
1274
+ const session = await getSession();
1275
+ if (!session || !_vocab || !_ortTensor) return null;
1276
+ const { input_ids, attention_mask, token_type_ids } = encode(text, _vocab);
1277
+ const seqLen = input_ids.length;
1278
+ const ids = BigInt64Array.from(input_ids.map((x) => BigInt(x)));
1279
+ const mask = BigInt64Array.from(attention_mask.map((x) => BigInt(x)));
1280
+ const types = BigInt64Array.from(token_type_ids.map((x) => BigInt(x)));
1281
+ const dims = [1, seqLen];
1282
+ const Tensor = _ortTensor;
1283
+ const feeds = {
1284
+ input_ids: new Tensor("int64", ids, dims),
1285
+ attention_mask: new Tensor("int64", mask, dims)
1286
+ };
1287
+ if (session.inputNames.includes("token_type_ids")) {
1288
+ feeds.token_type_ids = new Tensor("int64", types, dims);
1289
+ }
1290
+ const results = await session.run(feeds);
1291
+ const outName = session.outputNames.find((n) => results[n].dims.length === 3) ?? session.outputNames[0];
1292
+ const outTensor = results[outName];
1293
+ const hiddenSize = outTensor.dims[2];
1294
+ const pooled = meanPool(outTensor.data, attention_mask, seqLen, hiddenSize);
1295
+ const vec = l2normalize(pooled);
1296
+ if (vec.length !== EMBED_DIM) return null;
1297
+ _activeModel = { modelId: EMBED_MODEL_ID, dim: EMBED_DIM };
1298
+ return vec;
1299
+ } catch {
1300
+ return null;
1301
+ }
1302
+ }
1303
+ async function embedTier0(text, settings) {
1304
+ const endpoint = settings.endpoint;
1305
+ if (!endpoint) return null;
1306
+ const requestModel = settings.model || EMBED_MODEL_ID;
1307
+ const base = endpoint.replace(/\/+$/, "");
1308
+ const url = `${base}/v1/embeddings`;
1309
+ const controller = new AbortController();
1310
+ const timer = setTimeout(() => controller.abort(), TIER0_TIMEOUT_MS);
1311
+ try {
1312
+ const res = await fetch(url, {
1313
+ method: "POST",
1314
+ headers: { "content-type": "application/json" },
1315
+ body: JSON.stringify({ model: requestModel, input: text }),
1316
+ signal: controller.signal
1317
+ });
1318
+ if (!res.ok) return null;
1319
+ const body = await res.json();
1320
+ const raw = body?.data?.[0]?.embedding;
1321
+ if (!Array.isArray(raw) || raw.length === 0) return null;
1322
+ const vec = l2normalize(Float32Array.from(raw));
1323
+ _activeModel = { modelId: requestModel, dim: vec.length };
1324
+ return vec;
1325
+ } catch {
1326
+ return null;
1327
+ } finally {
1328
+ clearTimeout(timer);
1329
+ }
1330
+ }
1331
+ async function embedBatch(texts) {
1332
+ if (!texts || texts.length === 0) return [];
1333
+ if (embeddingsDisabled()) return texts.map(() => null);
1334
+ const settings = loadEmbedSettings();
1335
+ if (!settings.enabled) return texts.map(() => null);
1336
+ const results = [];
1337
+ for (const t2 of texts) {
1338
+ if (!t2 || !t2.trim()) {
1339
+ results.push(null);
1340
+ continue;
1341
+ }
1342
+ try {
1343
+ let vec = null;
1344
+ if (settings.endpoint) {
1345
+ vec = await embedTier0(t2, settings);
1346
+ }
1347
+ if (!vec) vec = await embedTier1(t2);
1348
+ results.push(vec);
1349
+ } catch {
1350
+ results.push(null);
1351
+ }
1352
+ }
1353
+ return results;
1354
+ }
1355
+ var EMBED_MODEL_ID, EMBED_DIM, ORT_PKG, _activeModel, _sessionPromise, _vocab, _ortTensor, CHUNK_TARGET_CHARS, CHUNK_OVERLAP_CHARS, MAX_CHUNKS_PER_RECORD, TIER0_TIMEOUT_MS;
1356
+ var init_memory_embedder = __esm({
1357
+ "src/memory-embedder.ts"() {
1358
+ "use strict";
1359
+ init_memory_vector();
1360
+ init_memory_embedder_tokenizer();
1361
+ init_config();
1362
+ EMBED_MODEL_ID = "all-MiniLM-L6-v2";
1363
+ EMBED_DIM = 384;
1364
+ ORT_PKG = "onnxruntime-web";
1365
+ _activeModel = null;
1366
+ _sessionPromise = null;
1367
+ _vocab = null;
1368
+ _ortTensor = null;
1369
+ CHUNK_TARGET_CHARS = 900;
1370
+ CHUNK_OVERLAP_CHARS = 120;
1371
+ MAX_CHUNKS_PER_RECORD = 24;
1372
+ TIER0_TIMEOUT_MS = 2e3;
1373
+ }
1374
+ });
1375
+
1376
+ // src/memory-embed-sweep.ts
1377
+ function readCursor(db, metaTable, key) {
1378
+ if (!KNOWN_META_TABLES.has(metaTable)) return 0;
1379
+ try {
1380
+ const row = db.prepare(`SELECT value FROM ${metaTable} WHERE key = ?`).get(key);
1381
+ const n = row ? Number(row.value) : 0;
1382
+ return Number.isFinite(n) && n >= 0 ? n : 0;
1383
+ } catch {
1384
+ return 0;
1385
+ }
1386
+ }
1387
+ function writeCursor(db, metaTable, key, value) {
1388
+ if (!KNOWN_META_TABLES.has(metaTable)) return;
1389
+ try {
1390
+ db.prepare(`INSERT OR REPLACE INTO ${metaTable} (key, value) VALUES (?, ?)`).run(
1391
+ key,
1392
+ String(value)
1393
+ );
1394
+ } catch {
1395
+ }
1396
+ }
1397
+ async function runEmbedSweep(db, cfg, opts = {}) {
1398
+ const batchSize = Math.max(1, opts.batchSize ?? 16);
1399
+ const limit = opts.limit ?? Infinity;
1400
+ const budgetMs = opts.budgetMs;
1401
+ const start = Date.now();
1402
+ const cursorKey = `embed_sweep_cursor_${cfg.sourceLabel}`;
1403
+ let embedded = 0;
1404
+ let scanned = 0;
1405
+ let active = getActiveEmbedModel();
1406
+ let cursor = readCursor(db, cfg.metaTable, cursorKey);
1407
+ try {
1408
+ while (true) {
1409
+ if (embedded >= limit) break;
1410
+ if (budgetMs !== void 0 && Date.now() - start >= budgetMs) break;
1411
+ const remaining = limit === Infinity ? batchSize : Math.min(batchSize, limit - embedded);
1412
+ const rows = cfg.selectMissing(db, cursor, active, Math.max(1, remaining));
1413
+ if (rows.length === 0) {
1414
+ writeCursor(db, cfg.metaTable, cursorKey, 0);
1415
+ break;
1416
+ }
1417
+ const units = [];
1418
+ for (const r of rows) {
1419
+ if (cfg.chunked) {
1420
+ const parts = chunkForEmbedding(r.text);
1421
+ if (parts.length === 0) continue;
1422
+ parts.forEach((text, chunkIx) => units.push({ id: r.id, chunkIx, text }));
1423
+ } else {
1424
+ units.push({ id: r.id, chunkIx: 0, text: r.text });
1425
+ }
1426
+ }
1427
+ const vecs = await embedBatch(units.map((u) => u.text));
1428
+ if (!active) active = getActiveEmbedModel();
1429
+ if (!active) {
1430
+ break;
1431
+ }
1432
+ const tx = db.transaction(() => {
1433
+ const del = cfg.chunked ? db.prepare(
1434
+ `DELETE FROM ${cfg.embeddingTable}
1435
+ WHERE ${cfg.idCol} = ? AND model_id = ? AND dim = ?`
1436
+ ) : null;
1437
+ const stmt = cfg.chunked ? db.prepare(
1438
+ `INSERT OR REPLACE INTO ${cfg.embeddingTable}
1439
+ (${cfg.idCol}, chunk_ix, model_id, dim, vec, created_at)
1440
+ VALUES (?, ?, ?, ?, ?, datetime('now'))`
1441
+ ) : db.prepare(
1442
+ `INSERT OR REPLACE INTO ${cfg.embeddingTable}
1443
+ (${cfg.idCol}, model_id, dim, vec, created_at)
1444
+ VALUES (?, ?, ?, ?, datetime('now'))`
1445
+ );
1446
+ const cleared = /* @__PURE__ */ new Set();
1447
+ const embeddedIds = /* @__PURE__ */ new Set();
1448
+ for (let i = 0; i < units.length; i++) {
1449
+ const v = vecs[i];
1450
+ if (!v) continue;
1451
+ const u = units[i];
1452
+ if (del && !cleared.has(u.id)) {
1453
+ del.run(u.id, active.modelId, active.dim);
1454
+ cleared.add(u.id);
1455
+ }
1456
+ if (cfg.chunked) {
1457
+ stmt.run(u.id, u.chunkIx, active.modelId, active.dim, float32ToBlob(v));
1458
+ } else {
1459
+ stmt.run(u.id, active.modelId, active.dim, float32ToBlob(v));
1460
+ }
1461
+ embeddedIds.add(u.id);
1462
+ }
1463
+ embedded += embeddedIds.size;
1464
+ });
1465
+ tx();
1466
+ scanned += rows.length;
1467
+ cursor = rows[rows.length - 1].id;
1468
+ writeCursor(db, cfg.metaTable, cursorKey, cursor);
1469
+ }
1470
+ } catch {
1471
+ }
1472
+ return { embedded, scanned };
1473
+ }
1474
+ var KNOWN_META_TABLES;
1475
+ var init_memory_embed_sweep = __esm({
1476
+ "src/memory-embed-sweep.ts"() {
1477
+ "use strict";
1478
+ init_memory_embedder();
1479
+ init_memory_vector();
1480
+ KNOWN_META_TABLES = /* @__PURE__ */ new Set(["memory_meta", "knowledge_meta"]);
1481
+ }
1482
+ });
1483
+
1484
+ // src/memory-db.ts
1485
+ var memory_db_exports = {};
1486
+ __export(memory_db_exports, {
1487
+ CONSOLIDATION_LESSON_EVIDENCE: () => CONSOLIDATION_LESSON_EVIDENCE,
1488
+ MEMORY_FILE_TITLE_LIKE: () => MEMORY_FILE_TITLE_LIKE,
1489
+ MEMORY_FILE_TITLE_PREFIX: () => MEMORY_FILE_TITLE_PREFIX,
1490
+ MEMORY_SCHEMA_VERSION: () => MEMORY_SCHEMA_VERSION,
1491
+ TOOL_COST_EVENTS_RETENTION_DAYS: () => TOOL_COST_EVENTS_RETENTION_DAYS,
1492
+ USAGE_COUNTER_ARMED_KEY: () => USAGE_COUNTER_ARMED_KEY,
1493
+ addConversationTurn: () => addConversationTurn,
1494
+ addFailureClass: () => addFailureClass,
1495
+ addObservation: () => addObservation,
1496
+ addSummary: () => addSummary,
1497
+ addToolCallDetail: () => addToolCallDetail,
1498
+ addUserPrompt: () => addUserPrompt,
1499
+ appendIncidentToFailureClass: () => appendIncidentToFailureClass,
1500
+ armUsageCounter: () => armUsageCounter,
1501
+ assignImportance: () => assignImportance,
1502
+ autoDetectTaskId: () => autoDetectTaskId,
1503
+ createSession: () => createSession,
1504
+ deduplicateFailedAttempt: () => deduplicateFailedAttempt,
1505
+ dequeuePendingSync: () => dequeuePendingSync,
1506
+ drainRulePromotionEvents: () => drainRulePromotionEvents,
1507
+ drainTeamPromotions: () => drainTeamPromotions,
1508
+ drainTeamRevocations: () => drainTeamRevocations,
1509
+ embedMissingObservations: () => embedMissingObservations,
1510
+ endSession: () => endSession,
1511
+ enqueueRulePromotionEvent: () => enqueueRulePromotionEvent,
1512
+ enqueueSyncPayload: () => enqueueSyncPayload,
1513
+ enqueueTeamPromotion: () => enqueueTeamPromotion,
1514
+ enqueueTeamRevocation: () => enqueueTeamRevocation,
1515
+ expireOldLowValueObservations: () => expireOldLowValueObservations,
1516
+ getConversationTurns: () => getConversationTurns,
1517
+ getCrossTaskProgress: () => getCrossTaskProgress,
1518
+ getDecisionsAbout: () => getDecisionsAbout,
1519
+ getFailedAttempts: () => getFailedAttempts,
1520
+ getFailureClasses: () => getFailureClasses,
1521
+ getLastProcessedLine: () => getLastProcessedLine,
1522
+ getMemoryDb: () => getMemoryDb,
1523
+ getMemoryMeta: () => getMemoryMeta,
1524
+ getObservabilityDbSize: () => getObservabilityDbSize,
1525
+ getRecentObservations: () => getRecentObservations,
1526
+ getRecurrenceCountForPromptHash: () => getRecurrenceCountForPromptHash,
1527
+ getSessionStats: () => getSessionStats,
1528
+ getSessionSummaries: () => getSessionSummaries,
1529
+ getSessionTimeline: () => getSessionTimeline,
1530
+ getSessionsByTask: () => getSessionsByTask,
1531
+ getToolPatterns: () => getToolPatterns,
1532
+ incrementRetryCount: () => incrementRetryCount,
1533
+ initMemorySchema: () => initMemorySchema,
1534
+ linkSessionToTask: () => linkSessionToTask,
1535
+ markRecordSuperseded: () => markRecordSuperseded,
1536
+ memoryTableHasTemporal: () => memoryTableHasTemporal,
1537
+ migrateAuditLogCheckExtension: () => migrateAuditLogCheckExtension,
1538
+ migrateMemoryFilesFor4B: () => migrateMemoryFilesFor4B,
1539
+ migrateObservationEmbeddingChunks: () => migrateObservationEmbeddingChunks,
1540
+ pruneOldConversationTurns: () => pruneOldConversationTurns,
1541
+ pruneOldObservations: () => pruneOldObservations,
1542
+ pruneToolCostEvents: () => pruneToolCostEvents,
1543
+ recordRecallHits: () => recordRecallHits,
1544
+ recordTelemetry: () => recordTelemetry,
1545
+ removePendingSync: () => removePendingSync,
1546
+ sanitizeFts5Query: () => sanitizeFts5Query,
1547
+ sanitizeFts5QueryOr: () => sanitizeFts5QueryOr,
1548
+ scoreFailureClasses: () => scoreFailureClasses,
1549
+ searchConversationTurns: () => searchConversationTurns,
1550
+ searchObservations: () => searchObservations,
1551
+ setLastProcessedLine: () => setLastProcessedLine,
1552
+ setMemoryMeta: () => setMemoryMeta,
1553
+ upsertObservationEmbedding: () => upsertObservationEmbedding,
1554
+ usageWarmupElapsed: () => usageWarmupElapsed
1555
+ });
1556
+ import Database2 from "better-sqlite3";
1557
+ import { dirname as dirname5, basename as basename2 } from "path";
1558
+ import { existsSync as existsSync6, mkdirSync as mkdirSync4 } from "fs";
1559
+ function sanitizeFts5Query(raw) {
1560
+ const trimmed = raw.trim();
1561
+ if (!trimmed) return '""';
1562
+ const tokens = trimmed.replace(/"/g, "").split(/\s+/).filter(Boolean);
1563
+ return tokens.map((t2) => `"${t2}"`).join(" ");
1564
+ }
1565
+ function sanitizeFts5QueryOr(raw) {
1566
+ const trimmed = raw.trim();
1567
+ if (!trimmed) return '""';
1568
+ const tokens = trimmed.replace(/"/g, "").split(/\s+/).filter((t2) => t2.replace(/[^a-zA-Z0-9]/g, "").length >= 3);
1569
+ if (tokens.length === 0) return '""';
1570
+ return tokens.map((t2) => `"${t2}"`).join(" OR ");
1571
+ }
1572
+ function getMemoryDb() {
1573
+ const dbPath = getResolvedPaths().memoryDbPath;
1574
+ const dir = dirname5(dbPath);
1575
+ if (!existsSync6(dir)) {
1576
+ mkdirSync4(dir, { recursive: true });
1577
+ }
1578
+ const preExisting = existsSync6(dbPath);
1579
+ const db = new Database2(dbPath);
1580
+ db.pragma("journal_mode = WAL");
1581
+ db.pragma("foreign_keys = ON");
1582
+ const onDisk = db.pragma("user_version", { simple: true });
1583
+ if (preExisting && onDisk !== MEMORY_SCHEMA_VERSION) {
1584
+ backupBeforeSchemaChange(
1585
+ getProjectRoot(),
1586
+ dbPath,
1587
+ (err) => recordHookFailure("memory-db:pre-ddl-backup", err, { dbPath, onDisk })
1588
+ );
1589
+ }
1590
+ initMemorySchema(db);
1591
+ if (onDisk !== MEMORY_SCHEMA_VERSION) {
1592
+ db.pragma(`user_version = ${MEMORY_SCHEMA_VERSION}`);
1593
+ }
1594
+ return db;
1595
+ }
1596
+ function pruneToolCostEvents(db) {
1597
+ const result = db.prepare(
1598
+ `DELETE FROM tool_cost_events WHERE created_at < datetime('now', '-' || ? || ' days')`
1599
+ ).run(TOOL_COST_EVENTS_RETENTION_DAYS);
1600
+ return result.changes;
1601
+ }
1602
+ function migrateObservationEmbeddingChunks(db) {
1603
+ const cols = db.pragma("table_info(observation_embeddings)");
1604
+ if (cols.length === 0) return;
1605
+ if (cols.some((c) => c.name === "chunk_ix")) return;
1606
+ db.pragma("foreign_keys = OFF");
1607
+ try {
1608
+ db.exec("BEGIN TRANSACTION");
1609
+ db.exec(`
1610
+ CREATE TABLE observation_embeddings_new (
1611
+ observation_id INTEGER NOT NULL REFERENCES observations(id) ON DELETE CASCADE,
1612
+ chunk_ix INTEGER NOT NULL DEFAULT 0,
1613
+ model_id TEXT NOT NULL,
1614
+ dim INTEGER NOT NULL,
1615
+ vec BLOB NOT NULL,
1616
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
1617
+ PRIMARY KEY (observation_id, model_id, dim, chunk_ix)
1618
+ );
1619
+ INSERT INTO observation_embeddings_new
1620
+ (observation_id, chunk_ix, model_id, dim, vec, created_at)
1621
+ SELECT observation_id, 0, model_id, dim, vec, created_at FROM observation_embeddings;
1622
+ DROP TABLE observation_embeddings;
1623
+ ALTER TABLE observation_embeddings_new RENAME TO observation_embeddings;
1624
+ CREATE INDEX IF NOT EXISTS idx_obs_emb_model ON observation_embeddings(model_id);
1625
+ `);
1626
+ db.exec("COMMIT");
1627
+ } catch (err) {
1628
+ db.exec("ROLLBACK");
1629
+ throw err;
1630
+ } finally {
1631
+ db.pragma("foreign_keys = ON");
1632
+ }
1633
+ }
1634
+ function migrateMemoryFilesFor4B(db) {
1635
+ const ADDITIONS = [
1636
+ // The renderer's authorship credential (OD-1). NULL on every pre-existing row,
1637
+ // which is the safe direction: no MAC ⇒ unverifiable ⇒ the file is HUMAN.
1638
+ { table: "memory_files", name: "massu_render_mac", decl: "TEXT" },
1639
+ // F-15 stickiness: once a file is human, only `massu memory adopt` reverses it.
1640
+ { table: "memory_files", name: "adopted_human_at_epoch", decl: "INTEGER" },
1641
+ // OD-2: a CACHE of `.massu-tombstones.jsonl`. The ledger is the source of truth.
1642
+ { table: "memory_files", name: "tombstoned_at_epoch", decl: "INTEGER" },
1643
+ { table: "memory_files", name: "origin", decl: "TEXT NOT NULL DEFAULT 'local'" },
1644
+ { table: "memory_files", name: "render_suppressed", decl: "INTEGER NOT NULL DEFAULT 0" },
1645
+ // N-03 — the SOURCE row. This is the one F-08 actually requires.
1646
+ { table: "observations", name: "origin", decl: "TEXT NOT NULL DEFAULT 'local'" }
1647
+ ];
1648
+ for (const add of ADDITIONS) {
1649
+ const cols = db.prepare(`PRAGMA table_info(${add.table})`).all();
1650
+ if (cols.length === 0) continue;
1651
+ if (cols.some((c) => c.name === add.name)) continue;
1652
+ db.exec(`ALTER TABLE ${add.table} ADD COLUMN ${add.name} ${add.decl}`);
1653
+ }
1654
+ }
1655
+ function migrateAuditLogCheckExtension(db) {
1656
+ const row = db.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name='audit_log'").get();
1657
+ if (!row) return;
1658
+ const expected = [
1659
+ "code_change",
1660
+ "rule_enforced",
1661
+ "approval",
1662
+ "review",
1663
+ "commit",
1664
+ "compaction",
1665
+ "rule_candidate_emitted",
1666
+ "rule_promoted",
1667
+ "rule_dismissed",
1668
+ // A-19/N-02 — without these the memory-file events throw a CHECK violation.
1669
+ // In the ingest path the throw is swallowed by a bare catch, so observability
1670
+ // silently produces NOTHING; in the renderer's transaction it ROLLS BACK a
1671
+ // legitimate render. This migration is what lets an EXISTING db accept them.
1672
+ "memory_file_ingested",
1673
+ "memory_file_expired",
1674
+ "memory_file_adopted_human",
1675
+ "memory_file_rendered",
1676
+ "memory_file_render_refused",
1677
+ "memory_file_tombstoned"
1678
+ ];
1679
+ const checkClauseMatch = row.sql.match(/event_type\s+TEXT\s+NOT\s+NULL\s+CHECK\s*\(\s*event_type\s+IN\s*\(([\s\S]*?)\)\s*\)/i);
1680
+ if (checkClauseMatch) {
1681
+ const values = (checkClauseMatch[1].match(/'([^']+)'/g) ?? []).map((s) => s.slice(1, -1));
1682
+ if (expected.every((v) => values.includes(v))) return;
1683
+ }
1684
+ db.pragma("foreign_keys = OFF");
1685
+ try {
1686
+ db.exec("BEGIN TRANSACTION");
1687
+ db.exec(`
1688
+ CREATE TABLE audit_log_new (
1689
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1690
+ session_id TEXT NOT NULL,
1691
+ timestamp TEXT DEFAULT (datetime('now')),
1692
+ event_type TEXT NOT NULL CHECK(event_type IN (
1693
+ 'code_change', 'rule_enforced', 'approval', 'review', 'commit', 'compaction',
1694
+ 'rule_candidate_emitted', 'rule_promoted', 'rule_dismissed',
1695
+ 'memory_file_ingested', 'memory_file_expired', 'memory_file_adopted_human',
1696
+ 'memory_file_rendered', 'memory_file_render_refused', 'memory_file_tombstoned'
1697
+ )),
1698
+ actor TEXT NOT NULL DEFAULT 'ai' CHECK(actor IN ('ai', 'human', 'hook', 'agent')),
1699
+ model_id TEXT,
1700
+ file_path TEXT,
1701
+ change_type TEXT CHECK(change_type IN ('create', 'edit', 'delete')),
1702
+ rules_in_effect TEXT,
1703
+ approval_status TEXT CHECK(approval_status IN ('auto_approved', 'human_approved', 'pending', 'denied')),
1704
+ evidence TEXT,
1705
+ metadata TEXT,
1706
+ FOREIGN KEY (session_id) REFERENCES sessions(session_id) ON DELETE CASCADE
1707
+ );
1708
+ INSERT INTO audit_log_new SELECT * FROM audit_log;
1709
+ DROP TABLE audit_log;
1710
+ ALTER TABLE audit_log_new RENAME TO audit_log;
1711
+ CREATE INDEX IF NOT EXISTS idx_al_session ON audit_log(session_id);
1712
+ CREATE INDEX IF NOT EXISTS idx_al_file ON audit_log(file_path);
1713
+ CREATE INDEX IF NOT EXISTS idx_al_event ON audit_log(event_type);
1714
+ CREATE INDEX IF NOT EXISTS idx_al_timestamp ON audit_log(timestamp DESC);
1715
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_audit_rule_promoted
1716
+ ON audit_log (event_type, json_extract(metadata, '$.prompt_hash'))
1717
+ WHERE event_type = 'rule_promoted';
1718
+ `);
1719
+ db.exec("COMMIT");
1720
+ } catch (err) {
1721
+ db.exec("ROLLBACK");
1722
+ throw err;
1723
+ } finally {
1724
+ db.pragma("foreign_keys = ON");
1725
+ }
1726
+ }
1727
+ function initMemorySchema(db) {
1728
+ db.exec(`
1729
+ -- Sessions table (linked to Claude Code session IDs)
1730
+ CREATE TABLE IF NOT EXISTS sessions (
1731
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1732
+ session_id TEXT UNIQUE NOT NULL,
1733
+ project TEXT NOT NULL DEFAULT 'my-project',
1734
+ git_branch TEXT,
1735
+ started_at TEXT NOT NULL,
1736
+ started_at_epoch INTEGER NOT NULL,
1737
+ ended_at TEXT,
1738
+ ended_at_epoch INTEGER,
1739
+ status TEXT CHECK(status IN ('active', 'completed', 'abandoned')) NOT NULL DEFAULT 'active',
1740
+ plan_file TEXT,
1741
+ plan_phase TEXT,
1742
+ task_id TEXT
1743
+ );
1744
+
1745
+ CREATE INDEX IF NOT EXISTS idx_sessions_session_id ON sessions(session_id);
1746
+ CREATE INDEX IF NOT EXISTS idx_sessions_started ON sessions(started_at_epoch DESC);
1747
+ CREATE INDEX IF NOT EXISTS idx_sessions_task_id ON sessions(task_id);
1748
+
1749
+ -- Observations table (structured knowledge from tool usage)
1750
+ CREATE TABLE IF NOT EXISTS observations (
1751
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1752
+ session_id TEXT NOT NULL,
1753
+ type TEXT NOT NULL CHECK(type IN (
1754
+ 'decision', 'bugfix', 'feature', 'refactor', 'discovery',
1755
+ 'cr_violation', 'vr_check', 'pattern_compliance', 'failed_attempt',
1756
+ 'file_change', 'incident_near_miss'
1757
+ )),
1758
+ title TEXT NOT NULL,
1759
+ detail TEXT,
1760
+ files_involved TEXT DEFAULT '[]',
1761
+ plan_item TEXT,
1762
+ cr_rule TEXT,
1763
+ vr_type TEXT,
1764
+ evidence TEXT,
1765
+ importance INTEGER NOT NULL DEFAULT 3 CHECK(importance BETWEEN 1 AND 5),
1766
+ recurrence_count INTEGER NOT NULL DEFAULT 1,
1767
+ original_tokens INTEGER DEFAULT 0,
1768
+ -- B-10/F-08/N-03: the SOURCE-row provenance flag. The renderer refuses any
1769
+ -- row whose origin is not 'local' BEFORE it computes a path, mints a
1770
+ -- credential, or takes a snapshot. A Slice-5 synced memory arrives here with
1771
+ -- origin='team' and must never reach disk without CR-55's gates.
1772
+ origin TEXT NOT NULL DEFAULT 'local',
1773
+ created_at TEXT NOT NULL,
1774
+ created_at_epoch INTEGER NOT NULL,
1775
+ FOREIGN KEY(session_id) REFERENCES sessions(session_id) ON DELETE CASCADE
1776
+ );
1777
+
1778
+ CREATE INDEX IF NOT EXISTS idx_observations_session ON observations(session_id);
1779
+ CREATE INDEX IF NOT EXISTS idx_observations_type ON observations(type);
1780
+ CREATE INDEX IF NOT EXISTS idx_observations_created ON observations(created_at_epoch DESC);
1781
+ CREATE INDEX IF NOT EXISTS idx_observations_plan_item ON observations(plan_item);
1782
+ CREATE INDEX IF NOT EXISTS idx_observations_cr_rule ON observations(cr_rule);
1783
+ CREATE INDEX IF NOT EXISTS idx_observations_importance ON observations(importance DESC);
1784
+ `);
1785
+ try {
1786
+ db.exec(`
1787
+ CREATE VIRTUAL TABLE IF NOT EXISTS observations_fts USING fts5(
1788
+ title, detail, evidence,
1789
+ content='observations',
1790
+ content_rowid='id'
1791
+ );
1792
+ `);
1793
+ } catch (_e) {
1794
+ }
1795
+ db.exec(`
1796
+ CREATE TRIGGER IF NOT EXISTS observations_ai AFTER INSERT ON observations BEGIN
1797
+ INSERT INTO observations_fts(rowid, title, detail, evidence)
1798
+ VALUES (new.id, new.title, new.detail, new.evidence);
1799
+ END;
1800
+
1801
+ CREATE TRIGGER IF NOT EXISTS observations_ad AFTER DELETE ON observations BEGIN
1802
+ INSERT INTO observations_fts(observations_fts, rowid, title, detail, evidence)
1803
+ VALUES ('delete', old.id, old.title, old.detail, old.evidence);
1804
+ END;
1805
+
1806
+ CREATE TRIGGER IF NOT EXISTS observations_au AFTER UPDATE ON observations BEGIN
1807
+ INSERT INTO observations_fts(observations_fts, rowid, title, detail, evidence)
1808
+ VALUES ('delete', old.id, old.title, old.detail, old.evidence);
1809
+ INSERT INTO observations_fts(rowid, title, detail, evidence)
1810
+ VALUES (new.id, new.title, new.detail, new.evidence);
1811
+ END;
1812
+ `);
1813
+ db.exec(`
1814
+ CREATE TABLE IF NOT EXISTS session_summaries (
1815
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1816
+ session_id TEXT NOT NULL,
1817
+ request TEXT,
1818
+ investigated TEXT,
1819
+ decisions TEXT,
1820
+ completed TEXT,
1821
+ failed_attempts TEXT,
1822
+ next_steps TEXT,
1823
+ files_created TEXT DEFAULT '[]',
1824
+ files_modified TEXT DEFAULT '[]',
1825
+ verification_results TEXT DEFAULT '{}',
1826
+ plan_progress TEXT DEFAULT '{}',
1827
+ created_at TEXT NOT NULL,
1828
+ created_at_epoch INTEGER NOT NULL,
1829
+ FOREIGN KEY(session_id) REFERENCES sessions(session_id) ON DELETE CASCADE
1830
+ );
1831
+
1832
+ CREATE INDEX IF NOT EXISTS idx_summaries_session ON session_summaries(session_id);
1833
+ `);
1834
+ db.exec(`
1835
+ CREATE TABLE IF NOT EXISTS user_prompts (
1836
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1837
+ session_id TEXT NOT NULL,
1838
+ prompt_text TEXT NOT NULL,
1839
+ prompt_number INTEGER NOT NULL DEFAULT 1,
1840
+ created_at TEXT NOT NULL,
1841
+ created_at_epoch INTEGER NOT NULL,
1842
+ FOREIGN KEY(session_id) REFERENCES sessions(session_id) ON DELETE CASCADE
1843
+ );
1844
+ `);
1845
+ try {
1846
+ db.exec(`
1847
+ CREATE VIRTUAL TABLE IF NOT EXISTS user_prompts_fts USING fts5(
1848
+ prompt_text,
1849
+ content='user_prompts',
1850
+ content_rowid='id'
1851
+ );
1852
+ `);
1853
+ } catch (_e) {
1854
+ }
1855
+ db.exec(`
1856
+ CREATE TRIGGER IF NOT EXISTS prompts_ai AFTER INSERT ON user_prompts BEGIN
1857
+ INSERT INTO user_prompts_fts(rowid, prompt_text) VALUES (new.id, new.prompt_text);
1858
+ END;
1859
+
1860
+ CREATE TRIGGER IF NOT EXISTS prompts_ad AFTER DELETE ON user_prompts BEGIN
1861
+ INSERT INTO user_prompts_fts(user_prompts_fts, rowid, prompt_text)
1862
+ VALUES ('delete', old.id, old.prompt_text);
1863
+ END;
1864
+ `);
1865
+ db.exec(`
1866
+ CREATE TABLE IF NOT EXISTS memory_meta (
1867
+ key TEXT PRIMARY KEY,
1868
+ value TEXT NOT NULL
1869
+ );
1870
+ `);
1871
+ db.exec(`
1872
+ CREATE TABLE IF NOT EXISTS memory_usage (
1873
+ source TEXT NOT NULL,
1874
+ record_id INTEGER NOT NULL,
1875
+ hit_count INTEGER NOT NULL DEFAULT 0,
1876
+ hits_windowed REAL NOT NULL DEFAULT 0,
1877
+ last_hit_epoch INTEGER,
1878
+ last_reweight_epoch INTEGER,
1879
+ PRIMARY KEY (source, record_id)
1880
+ );
1881
+
1882
+ CREATE TABLE IF NOT EXISTS memory_usage_sessions (
1883
+ source TEXT NOT NULL,
1884
+ record_id INTEGER NOT NULL,
1885
+ session_id TEXT NOT NULL,
1886
+ PRIMARY KEY (source, record_id, session_id)
1887
+ );
1888
+
1889
+ CREATE INDEX IF NOT EXISTS idx_memory_usage_hits
1890
+ ON memory_usage(source, hits_windowed DESC);
1891
+ `);
1892
+ db.exec(`
1893
+ CREATE TABLE IF NOT EXISTS conversation_turns (
1894
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1895
+ session_id TEXT NOT NULL,
1896
+ turn_number INTEGER NOT NULL,
1897
+ user_prompt TEXT NOT NULL,
1898
+ assistant_response TEXT,
1899
+ tool_calls_json TEXT,
1900
+ tool_call_count INTEGER DEFAULT 0,
1901
+ model_used TEXT,
1902
+ duration_ms INTEGER,
1903
+ prompt_tokens INTEGER,
1904
+ response_tokens INTEGER,
1905
+ created_at TEXT DEFAULT (datetime('now')),
1906
+ created_at_epoch INTEGER DEFAULT (unixepoch()),
1907
+ FOREIGN KEY (session_id) REFERENCES sessions(session_id) ON DELETE CASCADE
1908
+ );
1909
+
1910
+ CREATE INDEX IF NOT EXISTS idx_ct_session ON conversation_turns(session_id);
1911
+ CREATE INDEX IF NOT EXISTS idx_ct_created ON conversation_turns(created_at DESC);
1912
+ CREATE INDEX IF NOT EXISTS idx_ct_turn ON conversation_turns(session_id, turn_number);
1913
+ `);
1914
+ db.exec(`
1915
+ CREATE TABLE IF NOT EXISTS tool_call_details (
1916
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1917
+ session_id TEXT NOT NULL,
1918
+ turn_number INTEGER NOT NULL,
1919
+ tool_name TEXT NOT NULL,
1920
+ tool_input_summary TEXT,
1921
+ tool_input_size INTEGER,
1922
+ tool_output_size INTEGER,
1923
+ tool_success INTEGER DEFAULT 1,
1924
+ duration_ms INTEGER,
1925
+ files_involved TEXT,
1926
+ created_at TEXT DEFAULT (datetime('now')),
1927
+ created_at_epoch INTEGER DEFAULT (unixepoch()),
1928
+ FOREIGN KEY (session_id) REFERENCES sessions(session_id) ON DELETE CASCADE
1929
+ );
1930
+
1931
+ CREATE INDEX IF NOT EXISTS idx_tcd_session ON tool_call_details(session_id);
1932
+ CREATE INDEX IF NOT EXISTS idx_tcd_tool ON tool_call_details(tool_name);
1933
+ CREATE INDEX IF NOT EXISTS idx_tcd_created ON tool_call_details(created_at DESC);
1934
+ `);
1935
+ try {
1936
+ db.exec(`
1937
+ CREATE VIRTUAL TABLE IF NOT EXISTS conversation_turns_fts USING fts5(
1938
+ user_prompt,
1939
+ assistant_response,
1940
+ content=conversation_turns,
1941
+ content_rowid=id
1942
+ );
1943
+ `);
1944
+ } catch (_e) {
1945
+ }
1946
+ db.exec(`
1947
+ CREATE TRIGGER IF NOT EXISTS ct_fts_insert AFTER INSERT ON conversation_turns BEGIN
1948
+ INSERT INTO conversation_turns_fts(rowid, user_prompt, assistant_response)
1949
+ VALUES (new.id, new.user_prompt, new.assistant_response);
1950
+ END;
1951
+
1952
+ CREATE TRIGGER IF NOT EXISTS ct_fts_delete AFTER DELETE ON conversation_turns BEGIN
1953
+ INSERT INTO conversation_turns_fts(conversation_turns_fts, rowid, user_prompt, assistant_response)
1954
+ VALUES ('delete', old.id, old.user_prompt, old.assistant_response);
1955
+ END;
1956
+
1957
+ CREATE TRIGGER IF NOT EXISTS ct_fts_update AFTER UPDATE ON conversation_turns BEGIN
1958
+ INSERT INTO conversation_turns_fts(conversation_turns_fts, rowid, user_prompt, assistant_response)
1959
+ VALUES ('delete', old.id, old.user_prompt, old.assistant_response);
1960
+ INSERT INTO conversation_turns_fts(rowid, user_prompt, assistant_response)
1961
+ VALUES (new.id, new.user_prompt, new.assistant_response);
1962
+ END;
1963
+ `);
1964
+ db.exec(`
1965
+ CREATE TABLE IF NOT EXISTS session_quality_scores (
1966
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1967
+ session_id TEXT NOT NULL UNIQUE,
1968
+ project TEXT NOT NULL DEFAULT 'my-project',
1969
+ score INTEGER NOT NULL DEFAULT 100,
1970
+ security_score INTEGER NOT NULL DEFAULT 100,
1971
+ architecture_score INTEGER NOT NULL DEFAULT 100,
1972
+ coupling_score INTEGER NOT NULL DEFAULT 100,
1973
+ test_score INTEGER NOT NULL DEFAULT 100,
1974
+ rule_compliance_score INTEGER NOT NULL DEFAULT 100,
1975
+ observations_total INTEGER NOT NULL DEFAULT 0,
1976
+ bugs_found INTEGER NOT NULL DEFAULT 0,
1977
+ bugs_fixed INTEGER NOT NULL DEFAULT 0,
1978
+ vr_checks_passed INTEGER NOT NULL DEFAULT 0,
1979
+ vr_checks_failed INTEGER NOT NULL DEFAULT 0,
1980
+ incidents_triggered INTEGER NOT NULL DEFAULT 0,
1981
+ created_at TEXT DEFAULT (datetime('now')),
1982
+ FOREIGN KEY (session_id) REFERENCES sessions(session_id) ON DELETE CASCADE
1983
+ );
1984
+ CREATE INDEX IF NOT EXISTS idx_sqs_session ON session_quality_scores(session_id);
1985
+ CREATE INDEX IF NOT EXISTS idx_sqs_project ON session_quality_scores(project);
1986
+ `);
1987
+ db.exec(`
1988
+ CREATE TABLE IF NOT EXISTS session_costs (
1989
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1990
+ session_id TEXT NOT NULL UNIQUE,
1991
+ project TEXT NOT NULL DEFAULT 'my-project',
1992
+ input_tokens INTEGER NOT NULL DEFAULT 0,
1993
+ output_tokens INTEGER NOT NULL DEFAULT 0,
1994
+ cache_read_tokens INTEGER NOT NULL DEFAULT 0,
1995
+ cache_write_tokens INTEGER NOT NULL DEFAULT 0,
1996
+ total_tokens INTEGER NOT NULL DEFAULT 0,
1997
+ estimated_cost_usd REAL NOT NULL DEFAULT 0.0,
1998
+ model TEXT,
1999
+ duration_minutes REAL NOT NULL DEFAULT 0.0,
2000
+ tool_calls INTEGER NOT NULL DEFAULT 0,
2001
+ created_at TEXT DEFAULT (datetime('now')),
2002
+ FOREIGN KEY (session_id) REFERENCES sessions(session_id) ON DELETE CASCADE
2003
+ );
2004
+ CREATE INDEX IF NOT EXISTS idx_sc_session ON session_costs(session_id);
2005
+ `);
2006
+ db.exec(`
2007
+ CREATE TABLE IF NOT EXISTS feature_costs (
2008
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2009
+ feature_key TEXT NOT NULL,
2010
+ session_id TEXT NOT NULL,
2011
+ tokens_used INTEGER NOT NULL DEFAULT 0,
2012
+ estimated_cost_usd REAL NOT NULL DEFAULT 0.0,
2013
+ commit_hash TEXT,
2014
+ created_at TEXT DEFAULT (datetime('now')),
2015
+ FOREIGN KEY (session_id) REFERENCES sessions(session_id) ON DELETE CASCADE
2016
+ );
2017
+ CREATE INDEX IF NOT EXISTS idx_fc_feature ON feature_costs(feature_key);
2018
+ CREATE INDEX IF NOT EXISTS idx_fc_session ON feature_costs(session_id);
2019
+ `);
2020
+ db.exec(`
2021
+ CREATE TABLE IF NOT EXISTS prompt_outcomes (
2022
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2023
+ session_id TEXT NOT NULL,
2024
+ prompt_hash TEXT NOT NULL,
2025
+ prompt_text TEXT NOT NULL,
2026
+ prompt_category TEXT NOT NULL DEFAULT 'feature',
2027
+ word_count INTEGER NOT NULL DEFAULT 0,
2028
+ outcome TEXT NOT NULL DEFAULT 'success' CHECK(outcome IN ('success', 'partial', 'failure', 'abandoned')),
2029
+ corrections_needed INTEGER NOT NULL DEFAULT 0,
2030
+ follow_up_prompts INTEGER NOT NULL DEFAULT 0,
2031
+ created_at TEXT DEFAULT (datetime('now')),
2032
+ FOREIGN KEY (session_id) REFERENCES sessions(session_id) ON DELETE CASCADE
2033
+ );
2034
+ CREATE INDEX IF NOT EXISTS idx_po_session ON prompt_outcomes(session_id);
2035
+ CREATE INDEX IF NOT EXISTS idx_po_category ON prompt_outcomes(prompt_category);
2036
+ `);
2037
+ db.exec(`
2038
+ CREATE TABLE IF NOT EXISTS audit_log (
2039
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2040
+ session_id TEXT NOT NULL,
2041
+ timestamp TEXT DEFAULT (datetime('now')),
2042
+ event_type TEXT NOT NULL CHECK(event_type IN (
2043
+ 'code_change', 'rule_enforced', 'approval', 'review', 'commit', 'compaction',
2044
+ 'rule_candidate_emitted', 'rule_promoted', 'rule_dismissed',
2045
+ 'memory_file_ingested', 'memory_file_expired', 'memory_file_adopted_human',
2046
+ 'memory_file_rendered', 'memory_file_render_refused', 'memory_file_tombstoned'
2047
+ )),
2048
+ actor TEXT NOT NULL DEFAULT 'ai' CHECK(actor IN ('ai', 'human', 'hook', 'agent')),
2049
+ model_id TEXT,
2050
+ file_path TEXT,
2051
+ change_type TEXT CHECK(change_type IN ('create', 'edit', 'delete')),
2052
+ rules_in_effect TEXT,
2053
+ approval_status TEXT CHECK(approval_status IN ('auto_approved', 'human_approved', 'pending', 'denied')),
2054
+ evidence TEXT,
2055
+ metadata TEXT,
2056
+ FOREIGN KEY (session_id) REFERENCES sessions(session_id) ON DELETE CASCADE
2057
+ );
2058
+ CREATE INDEX IF NOT EXISTS idx_al_session ON audit_log(session_id);
2059
+ CREATE INDEX IF NOT EXISTS idx_al_file ON audit_log(file_path);
2060
+ CREATE INDEX IF NOT EXISTS idx_al_event ON audit_log(event_type);
2061
+ CREATE INDEX IF NOT EXISTS idx_al_timestamp ON audit_log(timestamp DESC);
2062
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_audit_rule_promoted
2063
+ ON audit_log (event_type, json_extract(metadata, '$.prompt_hash'))
2064
+ WHERE event_type = 'rule_promoted';
2065
+ `);
2066
+ db.exec(`
2067
+ CREATE TABLE IF NOT EXISTS hook_health (
2068
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2069
+ hook TEXT NOT NULL,
2070
+ error TEXT NOT NULL,
2071
+ context_json TEXT,
2072
+ occurred_at TEXT NOT NULL DEFAULT (datetime('now'))
2073
+ );
2074
+ CREATE INDEX IF NOT EXISTS idx_hook_health_hook ON hook_health(hook);
2075
+ CREATE INDEX IF NOT EXISTS idx_hook_health_time ON hook_health(occurred_at DESC);
2076
+ `);
2077
+ db.exec(`
2078
+ CREATE TABLE IF NOT EXISTS prompt_outcomes_signal_blacklist (
2079
+ signal TEXT PRIMARY KEY,
2080
+ dismissal_count INTEGER NOT NULL DEFAULT 0,
2081
+ first_dismissed_at TEXT DEFAULT (datetime('now')),
2082
+ last_dismissed_at TEXT DEFAULT (datetime('now'))
2083
+ );
2084
+ CREATE INDEX IF NOT EXISTS idx_psb_count
2085
+ ON prompt_outcomes_signal_blacklist(dismissal_count DESC);
2086
+ `);
2087
+ migrateAuditLogCheckExtension(db);
2088
+ db.exec(`
2089
+ CREATE TABLE IF NOT EXISTS memory_files (
2090
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2091
+ rel_path TEXT NOT NULL UNIQUE COLLATE NOCASE,
2092
+ name TEXT,
2093
+ raw TEXT NOT NULL,
2094
+ frontmatter_json TEXT,
2095
+ body TEXT NOT NULL,
2096
+ content_hash TEXT NOT NULL,
2097
+ ingest_schema_version INTEGER NOT NULL DEFAULT 1,
2098
+ massu_authored INTEGER NOT NULL DEFAULT 0,
2099
+ massu_render_mac TEXT,
2100
+ adopted_human_at_epoch INTEGER,
2101
+ tombstoned_at_epoch INTEGER,
2102
+ origin TEXT NOT NULL DEFAULT 'local',
2103
+ render_suppressed INTEGER NOT NULL DEFAULT 0,
2104
+ observation_id INTEGER,
2105
+ synced_at_epoch INTEGER,
2106
+ expired_at_epoch INTEGER
2107
+ );
2108
+ CREATE INDEX IF NOT EXISTS idx_mf_hash ON memory_files(content_hash);
2109
+ CREATE INDEX IF NOT EXISTS idx_mf_expired ON memory_files(expired_at_epoch);
2110
+ CREATE INDEX IF NOT EXISTS idx_mf_obs ON memory_files(observation_id);
2111
+ `);
2112
+ db.exec(`
2113
+ CREATE TABLE IF NOT EXISTS validation_results (
2114
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2115
+ session_id TEXT NOT NULL,
2116
+ file_path TEXT NOT NULL,
2117
+ validation_type TEXT NOT NULL,
2118
+ passed INTEGER NOT NULL DEFAULT 1,
2119
+ details TEXT,
2120
+ rules_violated TEXT,
2121
+ created_at TEXT DEFAULT (datetime('now')),
2122
+ FOREIGN KEY (session_id) REFERENCES sessions(session_id) ON DELETE CASCADE
2123
+ );
2124
+ CREATE INDEX IF NOT EXISTS idx_vr_session ON validation_results(session_id);
2125
+ CREATE INDEX IF NOT EXISTS idx_vr_file ON validation_results(file_path);
2126
+ `);
2127
+ db.exec(`
2128
+ CREATE TABLE IF NOT EXISTS architecture_decisions (
2129
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2130
+ session_id TEXT NOT NULL,
2131
+ title TEXT NOT NULL,
2132
+ context TEXT,
2133
+ decision TEXT NOT NULL,
2134
+ status TEXT NOT NULL DEFAULT 'accepted' CHECK(status IN ('accepted', 'superseded', 'deprecated')),
2135
+ alternatives TEXT,
2136
+ consequences TEXT,
2137
+ affected_files TEXT,
2138
+ commit_hash TEXT,
2139
+ created_at TEXT DEFAULT (datetime('now')),
2140
+ FOREIGN KEY (session_id) REFERENCES sessions(session_id) ON DELETE CASCADE
2141
+ );
2142
+ CREATE INDEX IF NOT EXISTS idx_ad_session ON architecture_decisions(session_id);
2143
+ CREATE INDEX IF NOT EXISTS idx_ad_status ON architecture_decisions(status);
2144
+ `);
2145
+ db.exec(`
2146
+ CREATE TABLE IF NOT EXISTS security_scores (
2147
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2148
+ session_id TEXT NOT NULL,
2149
+ file_path TEXT NOT NULL,
2150
+ risk_score INTEGER NOT NULL DEFAULT 0,
2151
+ findings TEXT,
2152
+ created_at TEXT DEFAULT (datetime('now')),
2153
+ FOREIGN KEY (session_id) REFERENCES sessions(session_id) ON DELETE CASCADE
2154
+ );
2155
+ CREATE INDEX IF NOT EXISTS idx_ss_session ON security_scores(session_id);
2156
+ CREATE INDEX IF NOT EXISTS idx_ss_file ON security_scores(file_path);
2157
+ `);
2158
+ db.exec(`
2159
+ CREATE TABLE IF NOT EXISTS dependency_assessments (
2160
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2161
+ package_name TEXT NOT NULL,
2162
+ version TEXT,
2163
+ risk_score INTEGER NOT NULL DEFAULT 0,
2164
+ vulnerabilities INTEGER NOT NULL DEFAULT 0,
2165
+ last_publish_days INTEGER,
2166
+ weekly_downloads INTEGER,
2167
+ license TEXT,
2168
+ bundle_size_kb INTEGER,
2169
+ previous_removals INTEGER NOT NULL DEFAULT 0,
2170
+ assessed_at TEXT DEFAULT (datetime('now'))
2171
+ );
2172
+ CREATE INDEX IF NOT EXISTS idx_da_package ON dependency_assessments(package_name);
2173
+ `);
2174
+ db.exec(`
2175
+ CREATE TABLE IF NOT EXISTS developer_expertise (
2176
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2177
+ developer_id TEXT NOT NULL,
2178
+ module TEXT NOT NULL,
2179
+ session_count INTEGER NOT NULL DEFAULT 0,
2180
+ observation_count INTEGER NOT NULL DEFAULT 0,
2181
+ expertise_score INTEGER NOT NULL DEFAULT 0,
2182
+ last_active TEXT DEFAULT (datetime('now')),
2183
+ UNIQUE(developer_id, module)
2184
+ );
2185
+ CREATE INDEX IF NOT EXISTS idx_de_developer ON developer_expertise(developer_id);
2186
+ CREATE INDEX IF NOT EXISTS idx_de_module ON developer_expertise(module);
2187
+ `);
2188
+ db.exec(`
2189
+ CREATE TABLE IF NOT EXISTS shared_observations (
2190
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2191
+ original_id INTEGER,
2192
+ developer_id TEXT NOT NULL,
2193
+ project TEXT NOT NULL,
2194
+ observation_type TEXT NOT NULL,
2195
+ summary TEXT NOT NULL,
2196
+ file_path TEXT,
2197
+ module TEXT,
2198
+ severity INTEGER NOT NULL DEFAULT 3,
2199
+ is_shared INTEGER NOT NULL DEFAULT 0,
2200
+ shared_at TEXT,
2201
+ created_at TEXT DEFAULT (datetime('now'))
2202
+ );
2203
+ CREATE INDEX IF NOT EXISTS idx_so_developer ON shared_observations(developer_id);
2204
+ CREATE INDEX IF NOT EXISTS idx_so_file ON shared_observations(file_path);
2205
+ CREATE INDEX IF NOT EXISTS idx_so_module ON shared_observations(module);
2206
+ `);
2207
+ db.exec(`
2208
+ CREATE TABLE IF NOT EXISTS team_promotion_outbound (
2209
+ prompt_hash TEXT PRIMARY KEY,
2210
+ destination TEXT NOT NULL,
2211
+ draft_text TEXT NOT NULL,
2212
+ score REAL,
2213
+ signals_json TEXT NOT NULL DEFAULT '[]',
2214
+ content_hash TEXT NOT NULL,
2215
+ -- PA3-004 (Phase 3 Stream A): hardened-destination publish carries the
2216
+ -- publisher's review attestation so the server CHECK (hardened rows need a
2217
+ -- review_attestation) is satisfiable. hardened=0 for the Phase-2 rows.
2218
+ hardened INTEGER NOT NULL DEFAULT 0,
2219
+ review_attestation_json TEXT,
2220
+ created_at TEXT DEFAULT (datetime('now'))
2221
+ );
2222
+ CREATE TABLE IF NOT EXISTS team_revocation_outbound (
2223
+ prompt_hash TEXT PRIMARY KEY,
2224
+ created_at TEXT DEFAULT (datetime('now'))
2225
+ );
2226
+ `);
2227
+ db.exec(`
2228
+ CREATE TABLE IF NOT EXISTS rule_promotion_events_outbound (
2229
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2230
+ prompt_hash TEXT NOT NULL,
2231
+ event_type TEXT NOT NULL,
2232
+ metadata_json TEXT NOT NULL DEFAULT '{}',
2233
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
2234
+ );
2235
+ CREATE INDEX IF NOT EXISTS idx_rpe_outbound_created ON rule_promotion_events_outbound(created_at);
2236
+ `);
2237
+ db.exec(`
2238
+ CREATE TABLE IF NOT EXISTS analytics_events (
2239
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2240
+ event_type TEXT NOT NULL,
2241
+ event_data TEXT NOT NULL DEFAULT '{}',
2242
+ created_at TEXT DEFAULT (datetime('now'))
2243
+ );
2244
+ CREATE INDEX IF NOT EXISTS idx_analytics_events_type ON analytics_events(event_type);
2245
+ `);
2246
+ db.exec(`
2247
+ CREATE TABLE IF NOT EXISTS knowledge_conflicts (
2248
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2249
+ file_path TEXT NOT NULL,
2250
+ developer_a TEXT NOT NULL,
2251
+ developer_b TEXT NOT NULL,
2252
+ conflict_type TEXT NOT NULL DEFAULT 'concurrent_edit',
2253
+ resolved INTEGER NOT NULL DEFAULT 0,
2254
+ detected_at TEXT DEFAULT (datetime('now'))
2255
+ );
2256
+ CREATE INDEX IF NOT EXISTS idx_kc_file ON knowledge_conflicts(file_path);
2257
+ `);
2258
+ db.exec(`
2259
+ CREATE TABLE IF NOT EXISTS feature_health (
2260
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2261
+ feature_key TEXT NOT NULL UNIQUE,
2262
+ health_score INTEGER NOT NULL DEFAULT 100,
2263
+ tests_passing INTEGER NOT NULL DEFAULT 0,
2264
+ tests_failing INTEGER NOT NULL DEFAULT 0,
2265
+ test_coverage_pct REAL,
2266
+ modifications_since_test INTEGER NOT NULL DEFAULT 0,
2267
+ last_modified TEXT,
2268
+ last_tested TEXT,
2269
+ created_at TEXT DEFAULT (datetime('now'))
2270
+ );
2271
+ CREATE INDEX IF NOT EXISTS idx_fh_feature ON feature_health(feature_key);
2272
+ CREATE INDEX IF NOT EXISTS idx_fh_health ON feature_health(health_score);
2273
+ `);
2274
+ db.exec(`
2275
+ CREATE TABLE IF NOT EXISTS tool_cost_events (
2276
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2277
+ session_id TEXT NOT NULL,
2278
+ tool_name TEXT NOT NULL,
2279
+ estimated_input_tokens INTEGER DEFAULT 0,
2280
+ estimated_output_tokens INTEGER DEFAULT 0,
2281
+ model TEXT DEFAULT '',
2282
+ created_at TEXT DEFAULT (datetime('now'))
2283
+ );
2284
+ CREATE INDEX IF NOT EXISTS idx_tce_session ON tool_cost_events(session_id);
2285
+ CREATE INDEX IF NOT EXISTS idx_tce_tool ON tool_cost_events(tool_name);
2286
+ CREATE INDEX IF NOT EXISTS idx_tce_created ON tool_cost_events(created_at DESC);
2287
+ `);
2288
+ db.exec(`
2289
+ CREATE TABLE IF NOT EXISTS quality_events (
2290
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2291
+ session_id TEXT NOT NULL,
2292
+ event_type TEXT NOT NULL,
2293
+ tool_name TEXT NOT NULL,
2294
+ details TEXT DEFAULT '',
2295
+ created_at TEXT DEFAULT (datetime('now'))
2296
+ );
2297
+ CREATE INDEX IF NOT EXISTS idx_qe_session ON quality_events(session_id);
2298
+ CREATE INDEX IF NOT EXISTS idx_qe_event_type ON quality_events(event_type);
2299
+ CREATE INDEX IF NOT EXISTS idx_qe_created ON quality_events(created_at DESC);
2300
+ `);
2301
+ db.exec(`
2302
+ CREATE TABLE IF NOT EXISTS pending_sync (
2303
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2304
+ payload TEXT NOT NULL,
2305
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
2306
+ retry_count INTEGER NOT NULL DEFAULT 0,
2307
+ last_error TEXT
2308
+ );
2309
+ CREATE INDEX IF NOT EXISTS idx_pending_sync_created ON pending_sync(created_at ASC);
2310
+ `);
2311
+ db.exec(`
2312
+ CREATE TABLE IF NOT EXISTS license_cache (
2313
+ api_key_hash TEXT PRIMARY KEY,
2314
+ tier TEXT NOT NULL,
2315
+ valid_until TEXT NOT NULL,
2316
+ last_validated TEXT NOT NULL,
2317
+ features TEXT DEFAULT '[]'
2318
+ );
2319
+ `);
2320
+ const licenseCacheCols = db.prepare(`PRAGMA table_info(license_cache)`).all();
2321
+ if (!licenseCacheCols.some((c) => c.name === "signed_payload_json")) {
2322
+ db.exec(
2323
+ `ALTER TABLE license_cache ADD COLUMN signed_payload_json TEXT NOT NULL DEFAULT ''`
2324
+ );
2325
+ }
2326
+ const outboundCols = db.prepare(`PRAGMA table_info(team_promotion_outbound)`).all();
2327
+ if (!outboundCols.some((c) => c.name === "hardened")) {
2328
+ db.exec(`ALTER TABLE team_promotion_outbound ADD COLUMN hardened INTEGER NOT NULL DEFAULT 0`);
2329
+ }
2330
+ if (!outboundCols.some((c) => c.name === "review_attestation_json")) {
2331
+ db.exec(`ALTER TABLE team_promotion_outbound ADD COLUMN review_attestation_json TEXT`);
2332
+ }
2333
+ const sessionCols = db.prepare(`PRAGMA table_info(sessions)`).all();
2334
+ if (!sessionCols.some((c) => c.name === "consolidated_at")) {
2335
+ db.exec(`ALTER TABLE sessions ADD COLUMN consolidated_at TEXT`);
2336
+ }
2337
+ if (!sessionCols.some((c) => c.name === "consolidated_at_epoch")) {
2338
+ db.exec(`ALTER TABLE sessions ADD COLUMN consolidated_at_epoch INTEGER`);
2339
+ }
2340
+ if (!sessionCols.some((c) => c.name === "consolidated_status")) {
2341
+ db.exec(`ALTER TABLE sessions ADD COLUMN consolidated_status TEXT`);
2342
+ }
2343
+ const BITEMPORAL_COLUMNS = [
2344
+ { name: "valid_from", type: "TEXT" },
2345
+ { name: "valid_to", type: "TEXT" },
2346
+ { name: "ingested_at", type: "TEXT" },
2347
+ { name: "expired_at", type: "TEXT" },
2348
+ { name: "valid_from_epoch", type: "INTEGER" },
2349
+ { name: "valid_to_epoch", type: "INTEGER" },
2350
+ { name: "ingested_at_epoch", type: "INTEGER" },
2351
+ { name: "expired_at_epoch", type: "INTEGER" },
2352
+ { name: "superseded_by", type: "INTEGER" }
2353
+ ];
2354
+ for (const table of ["observations", "architecture_decisions"]) {
2355
+ const cols = db.prepare(`PRAGMA table_info(${table})`).all();
2356
+ for (const col of BITEMPORAL_COLUMNS) {
2357
+ if (!cols.some((c) => c.name === col.name)) {
2358
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${col.name} ${col.type}`);
2359
+ }
2360
+ }
2361
+ }
2362
+ db.exec(`
2363
+ UPDATE observations
2364
+ SET valid_from = created_at,
2365
+ ingested_at = created_at,
2366
+ valid_from_epoch = created_at_epoch,
2367
+ ingested_at_epoch = created_at_epoch
2368
+ WHERE valid_from_epoch IS NULL;
2369
+ `);
2370
+ db.exec(`
2371
+ UPDATE architecture_decisions
2372
+ SET valid_from = created_at,
2373
+ ingested_at = created_at,
2374
+ valid_from_epoch = CAST(strftime('%s', created_at) AS INTEGER),
2375
+ ingested_at_epoch = CAST(strftime('%s', created_at) AS INTEGER)
2376
+ WHERE valid_from_epoch IS NULL AND created_at IS NOT NULL;
2377
+ `);
2378
+ db.exec(`
2379
+ CREATE INDEX IF NOT EXISTS idx_observations_expired ON observations(expired_at_epoch);
2380
+ CREATE INDEX IF NOT EXISTS idx_ad_expired ON architecture_decisions(expired_at_epoch);
2381
+ `);
2382
+ db.exec(`
2383
+ CREATE TABLE IF NOT EXISTS failure_classes (
2384
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2385
+ name TEXT NOT NULL UNIQUE,
2386
+ description TEXT NOT NULL,
2387
+ diff_patterns TEXT NOT NULL DEFAULT '[]',
2388
+ file_patterns TEXT NOT NULL DEFAULT '[]',
2389
+ prompt_keywords TEXT NOT NULL DEFAULT '[]',
2390
+ incidents TEXT NOT NULL DEFAULT '[]',
2391
+ rules TEXT NOT NULL DEFAULT '[]',
2392
+ scanner_checks TEXT NOT NULL DEFAULT '[]',
2393
+ known_message TEXT NOT NULL DEFAULT '',
2394
+ needs_review INTEGER NOT NULL DEFAULT 0,
2395
+ created_at TEXT DEFAULT (datetime('now')),
2396
+ updated_at TEXT DEFAULT (datetime('now'))
2397
+ );
2398
+ CREATE INDEX IF NOT EXISTS idx_fc_name ON failure_classes(name);
2399
+ CREATE INDEX IF NOT EXISTS idx_fc_needs_review ON failure_classes(needs_review);
2400
+ `);
2401
+ db.exec(`
2402
+ CREATE TABLE IF NOT EXISTS observation_embeddings (
2403
+ observation_id INTEGER NOT NULL REFERENCES observations(id) ON DELETE CASCADE,
2404
+ chunk_ix INTEGER NOT NULL DEFAULT 0,
2405
+ model_id TEXT NOT NULL,
2406
+ dim INTEGER NOT NULL,
2407
+ vec BLOB NOT NULL,
2408
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
2409
+ PRIMARY KEY (observation_id, model_id, dim, chunk_ix)
2410
+ );
2411
+ CREATE INDEX IF NOT EXISTS idx_obs_emb_model ON observation_embeddings(model_id);
2412
+ `);
2413
+ migrateObservationEmbeddingChunks(db);
2414
+ migrateMemoryFilesFor4B(db);
2415
+ }
2416
+ function enqueueSyncPayload(db, payload) {
2417
+ db.prepare("INSERT INTO pending_sync (payload) VALUES (?)").run(payload);
2418
+ }
2419
+ function getMemoryMeta(db, key) {
2420
+ const row = db.prepare("SELECT value FROM memory_meta WHERE key = ?").get(key);
2421
+ return row ? row.value : null;
2422
+ }
2423
+ function setMemoryMeta(db, key, value) {
2424
+ db.prepare("INSERT OR REPLACE INTO memory_meta (key, value) VALUES (?, ?)").run(key, value);
2425
+ }
2426
+ function upsertObservationEmbedding(db, observationId, vec, modelId, dim) {
2427
+ db.prepare(
2428
+ `INSERT OR REPLACE INTO observation_embeddings (observation_id, model_id, dim, vec, created_at)
2429
+ VALUES (?, ?, ?, ?, datetime('now'))`
2430
+ ).run(observationId, modelId, dim, float32ToBlob(vec));
2431
+ }
2432
+ function observationEmbedText(title, detail) {
2433
+ const t2 = (title ?? "").trim();
2434
+ const d = (detail ?? "").trim();
2435
+ return d ? `${t2}. ${d}` : t2;
2436
+ }
2437
+ async function embedMissingObservations(db, opts = {}) {
2438
+ return runEmbedSweep(
2439
+ db,
2440
+ {
2441
+ embeddingTable: "observation_embeddings",
2442
+ idCol: "observation_id",
2443
+ metaTable: "memory_meta",
2444
+ sourceLabel: "observation",
2445
+ // A-04: memory bodies are now stored WHOLE (up to ~14K chars). One vector per
2446
+ // memory would cover only its first ~1,000 chars.
2447
+ chunked: true,
2448
+ selectMissing: (d, cursor, model, batchSize) => {
2449
+ const rows = model ? d.prepare(
2450
+ `SELECT o.id AS id, o.title AS title, o.detail AS detail
2451
+ FROM observations o
2452
+ WHERE o.id > ?
2453
+ AND NOT EXISTS (
2454
+ SELECT 1 FROM observation_embeddings e
2455
+ WHERE e.observation_id = o.id AND e.model_id = ? AND e.dim = ?
2456
+ )
2457
+ ORDER BY o.id LIMIT ?`
2458
+ ).all(cursor, model.modelId, model.dim, batchSize) : d.prepare(
2459
+ `SELECT o.id AS id, o.title AS title, o.detail AS detail
2460
+ FROM observations o
2461
+ WHERE o.id > ?
2462
+ AND NOT EXISTS (
2463
+ SELECT 1 FROM observation_embeddings e WHERE e.observation_id = o.id
2464
+ )
2465
+ ORDER BY o.id LIMIT ?`
2466
+ ).all(cursor, batchSize);
2467
+ return rows.map((r) => ({ id: r.id, text: observationEmbedText(r.title, r.detail) }));
2468
+ }
2469
+ },
2470
+ opts
2471
+ );
2472
+ }
2473
+ function enqueueTeamPromotion(db, promo) {
2474
+ db.prepare(`
2475
+ INSERT OR REPLACE INTO team_promotion_outbound
2476
+ (prompt_hash, destination, draft_text, score, signals_json, content_hash, hardened, review_attestation_json, created_at)
2477
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
2478
+ `).run(
2479
+ promo.prompt_hash,
2480
+ promo.destination,
2481
+ promo.draft_text.slice(0, MAX_DRAFT_TEXT_LEN),
2482
+ promo.score ?? null,
2483
+ JSON.stringify(promo.signals ?? []),
2484
+ promo.content_hash,
2485
+ promo.hardened ? 1 : 0,
2486
+ promo.review_attestation !== void 0 ? JSON.stringify(promo.review_attestation) : null
2487
+ );
2488
+ }
2489
+ function drainTeamPromotions(db) {
2490
+ const rows = db.prepare(`
2491
+ SELECT prompt_hash, destination, draft_text, score, signals_json, content_hash, hardened, review_attestation_json
2492
+ FROM team_promotion_outbound ORDER BY created_at ASC LIMIT 1000
2493
+ `).all();
2494
+ if (rows.length === 0) return [];
2495
+ db.prepare("DELETE FROM team_promotion_outbound").run();
2496
+ return rows.map((r) => ({
2497
+ prompt_hash: r.prompt_hash,
2498
+ destination: r.destination,
2499
+ draft_text: r.draft_text,
2500
+ score: r.score ?? void 0,
2501
+ signals: safeJsonArray(r.signals_json),
2502
+ content_hash: r.content_hash,
2503
+ hardened: r.hardened === 1,
2504
+ review_attestation: r.review_attestation_json ? safeJsonParse(r.review_attestation_json) : void 0
2505
+ }));
2506
+ }
2507
+ function enqueueTeamRevocation(db, promptHash) {
2508
+ db.prepare(`
2509
+ INSERT OR REPLACE INTO team_revocation_outbound (prompt_hash, created_at)
2510
+ VALUES (?, datetime('now'))
2511
+ `).run(promptHash);
2512
+ }
2513
+ function drainTeamRevocations(db) {
2514
+ const rows = db.prepare(
2515
+ `SELECT prompt_hash FROM team_revocation_outbound ORDER BY created_at ASC LIMIT 1000`
2516
+ ).all();
2517
+ if (rows.length === 0) return [];
2518
+ db.prepare("DELETE FROM team_revocation_outbound").run();
2519
+ return rows.map((r) => r.prompt_hash);
2520
+ }
2521
+ function getRecurrenceCountForPromptHash(db, promptHash) {
2522
+ try {
2523
+ const row = db.prepare(`
2524
+ SELECT json_extract(metadata, '$.recurrence_count') AS rc
2525
+ FROM audit_log
2526
+ WHERE event_type = 'rule_promoted'
2527
+ AND json_extract(metadata, '$.prompt_hash') = ?
2528
+ LIMIT 1
2529
+ `).get(promptHash);
2530
+ if (!row || row.rc === null || row.rc === void 0) return null;
2531
+ return Number(row.rc);
2532
+ } catch {
2533
+ return null;
2534
+ }
2535
+ }
2536
+ function enqueueRulePromotionEvent(db, ev) {
2537
+ try {
2538
+ db.prepare(`
2539
+ INSERT INTO rule_promotion_events_outbound
2540
+ (prompt_hash, event_type, metadata_json, created_at)
2541
+ VALUES (?, ?, ?, ?)
2542
+ `).run(
2543
+ ev.prompt_hash,
2544
+ ev.event_type,
2545
+ JSON.stringify(ev.metadata ?? {}),
2546
+ ev.created_at
2547
+ );
2548
+ db.prepare(`
2549
+ DELETE FROM rule_promotion_events_outbound
2550
+ WHERE id NOT IN (
2551
+ SELECT id FROM rule_promotion_events_outbound ORDER BY id DESC LIMIT ?
2552
+ )
2553
+ `).run(FUNNEL_EVENT_OUTBOX_CAP);
2554
+ } catch {
2555
+ }
2556
+ }
2557
+ function drainRulePromotionEvents(db) {
2558
+ const rows = db.prepare(`
2559
+ SELECT id, prompt_hash, event_type, metadata_json, created_at
2560
+ FROM rule_promotion_events_outbound ORDER BY id ASC LIMIT ?
2561
+ `).all(FUNNEL_EVENT_DRAIN_LIMIT);
2562
+ if (rows.length === 0) return [];
2563
+ const maxId = rows[rows.length - 1].id;
2564
+ db.prepare("DELETE FROM rule_promotion_events_outbound WHERE id <= ?").run(maxId);
2565
+ return rows.map((r) => ({
2566
+ prompt_hash: r.prompt_hash,
2567
+ event_type: r.event_type,
2568
+ created_at: r.created_at,
2569
+ metadata: safeJsonParse(r.metadata_json) ?? {}
2570
+ }));
2571
+ }
2572
+ function recordTelemetry(db, eventType, data) {
2573
+ try {
2574
+ db.prepare(`
2575
+ INSERT INTO analytics_events (event_type, event_data, created_at)
2576
+ VALUES (?, ?, datetime('now'))
2577
+ `).run(eventType, JSON.stringify(data));
2578
+ } catch {
2579
+ }
2580
+ }
2581
+ function safeJsonArray(json) {
2582
+ try {
2583
+ const v = JSON.parse(json);
2584
+ return Array.isArray(v) ? v : [];
2585
+ } catch {
2586
+ return [];
2587
+ }
2588
+ }
2589
+ function safeJsonParse(json) {
2590
+ try {
2591
+ return JSON.parse(json);
2592
+ } catch {
2593
+ return void 0;
2594
+ }
2595
+ }
2596
+ function dequeuePendingSync(db, limit = 10) {
2597
+ const stale = db.prepare(
2598
+ "SELECT id, retry_count, last_error FROM pending_sync WHERE retry_count >= 10 LIMIT 10000"
2599
+ ).all();
2600
+ if (stale.length > 0) {
2601
+ const ids = stale.map((s) => s.id);
2602
+ db.prepare(`DELETE FROM pending_sync WHERE id IN (${ids.map(() => "?").join(",")})`).run(...ids);
2603
+ const lastErrors = [...new Set(stale.map((s) => s.last_error).filter(Boolean))];
2604
+ process.stderr.write(
2605
+ `[massu] WARNING: ${stale.length} cloud-sync queue item(s) discarded after 10+ retries. Likely cause: invalid API key or unreachable endpoint. Recent errors: ${lastErrors.slice(0, 3).join("; ") || "(none recorded)"}
2606
+ `
2607
+ );
2608
+ try {
2609
+ db.prepare(`
2610
+ INSERT INTO analytics_events (event_type, event_data, created_at)
2611
+ VALUES (?, ?, datetime('now'))
2612
+ `).run(
2613
+ "cloud_sync_giveup",
2614
+ JSON.stringify({
2615
+ discarded_count: stale.length,
2616
+ recent_errors: lastErrors.slice(0, 3)
2617
+ })
2618
+ );
2619
+ } catch {
2620
+ }
2621
+ }
2622
+ return db.prepare(
2623
+ "SELECT id, payload, retry_count FROM pending_sync ORDER BY created_at ASC LIMIT ?"
2624
+ ).all(limit);
2625
+ }
2626
+ function removePendingSync(db, id) {
2627
+ db.prepare("DELETE FROM pending_sync WHERE id = ?").run(id);
2628
+ }
2629
+ function incrementRetryCount(db, id, error) {
2630
+ db.prepare(
2631
+ "UPDATE pending_sync SET retry_count = retry_count + 1, last_error = ? WHERE id = ?"
2632
+ ).run(error, id);
2633
+ }
2634
+ function assignImportance(type, vrResult) {
2635
+ switch (type) {
2636
+ case "decision":
2637
+ case "failed_attempt":
2638
+ return 5;
2639
+ case "cr_violation":
2640
+ case "incident_near_miss":
2641
+ return 4;
2642
+ case "vr_check":
2643
+ return vrResult === "PASS" ? 2 : 4;
2644
+ case "pattern_compliance":
2645
+ return vrResult === "PASS" ? 2 : 4;
2646
+ case "feature":
2647
+ case "bugfix":
2648
+ return 3;
2649
+ case "refactor":
2650
+ return 2;
2651
+ case "file_change":
2652
+ case "discovery":
2653
+ return 1;
2654
+ default:
2655
+ return 3;
2656
+ }
2657
+ }
2658
+ function autoDetectTaskId(planFile) {
2659
+ if (!planFile) return null;
2660
+ const base = basename2(planFile);
2661
+ return base.replace(/\.md$/, "");
2662
+ }
2663
+ function createSession(db, sessionId, opts) {
2664
+ const now = /* @__PURE__ */ new Date();
2665
+ const taskId = autoDetectTaskId(opts?.planFile);
2666
+ db.prepare(`
2667
+ INSERT OR IGNORE INTO sessions (session_id, git_branch, plan_file, task_id, started_at, started_at_epoch)
2668
+ VALUES (?, ?, ?, ?, ?, ?)
2669
+ `).run(sessionId, opts?.branch ?? null, opts?.planFile ?? null, taskId, now.toISOString(), Math.floor(now.getTime() / 1e3));
2670
+ }
2671
+ function endSession(db, sessionId, status = "completed") {
2672
+ const now = /* @__PURE__ */ new Date();
2673
+ db.prepare(`
2674
+ UPDATE sessions SET status = ?, ended_at = ?, ended_at_epoch = ? WHERE session_id = ?
2675
+ `).run(status, now.toISOString(), Math.floor(now.getTime() / 1e3), sessionId);
2676
+ }
2677
+ function memoryTableHasTemporal(db, table) {
2678
+ let perDb = _temporalColCache.get(db);
2679
+ if (!perDb) {
2680
+ perDb = /* @__PURE__ */ new Map();
2681
+ _temporalColCache.set(db, perDb);
2682
+ }
2683
+ let has = perDb.get(table);
2684
+ if (has === void 0) {
2685
+ try {
2686
+ const cols = db.prepare(`PRAGMA table_info(${table})`).all();
2687
+ has = cols.some((c) => c.name === "valid_from_epoch");
2688
+ } catch {
2689
+ has = false;
2690
+ }
2691
+ perDb.set(table, has);
2692
+ }
2693
+ return has;
2694
+ }
2695
+ function addObservation(db, sessionId, type, title, detail, opts) {
2696
+ const now = /* @__PURE__ */ new Date();
2697
+ const importance = opts?.importance ?? assignImportance(type, opts?.evidence?.includes("PASS") ? "PASS" : void 0);
2698
+ const iso = now.toISOString();
2699
+ const epochSec = Math.floor(now.getTime() / 1e3);
2700
+ let result;
2701
+ if (memoryTableHasTemporal(db, "observations")) {
2702
+ result = db.prepare(`
2703
+ INSERT INTO observations (session_id, type, title, detail, files_involved, plan_item, cr_rule, vr_type, evidence, importance, original_tokens, created_at, created_at_epoch, valid_from, ingested_at, valid_from_epoch, ingested_at_epoch)
2704
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2705
+ `).run(
2706
+ sessionId,
2707
+ type,
2708
+ title,
2709
+ detail,
2710
+ JSON.stringify(opts?.filesInvolved ?? []),
2711
+ opts?.planItem ?? null,
2712
+ opts?.crRule ?? null,
2713
+ opts?.vrType ?? null,
2714
+ opts?.evidence ?? null,
2715
+ importance,
2716
+ opts?.originalTokens ?? 0,
2717
+ iso,
2718
+ epochSec,
2719
+ iso,
2720
+ iso,
2721
+ epochSec,
2722
+ epochSec
2723
+ );
2724
+ } else {
2725
+ result = db.prepare(`
2726
+ INSERT INTO observations (session_id, type, title, detail, files_involved, plan_item, cr_rule, vr_type, evidence, importance, original_tokens, created_at, created_at_epoch)
2727
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2728
+ `).run(
2729
+ sessionId,
2730
+ type,
2731
+ title,
2732
+ detail,
2733
+ JSON.stringify(opts?.filesInvolved ?? []),
2734
+ opts?.planItem ?? null,
2735
+ opts?.crRule ?? null,
2736
+ opts?.vrType ?? null,
2737
+ opts?.evidence ?? null,
2738
+ importance,
2739
+ opts?.originalTokens ?? 0,
2740
+ iso,
2741
+ epochSec
2742
+ );
2743
+ }
2744
+ return Number(result.lastInsertRowid);
2745
+ }
2746
+ function markRecordSuperseded(db, table, recordId, successorId, nowEpochSec = Math.floor(Date.now() / 1e3)) {
2747
+ const iso = new Date(nowEpochSec * 1e3).toISOString();
2748
+ const statusClause = table === "architecture_decisions" ? `, status = 'superseded'` : "";
2749
+ const res = db.prepare(
2750
+ `UPDATE ${table}
2751
+ SET valid_to = ?, expired_at = ?, valid_to_epoch = ?, expired_at_epoch = ?, superseded_by = ?${statusClause}
2752
+ WHERE id = ? AND expired_at IS NULL AND id != ?`
2753
+ ).run(iso, iso, nowEpochSec, nowEpochSec, successorId, recordId, successorId);
2754
+ return res.changes > 0;
2755
+ }
2756
+ function addSummary(db, sessionId, summary) {
2757
+ const now = /* @__PURE__ */ new Date();
2758
+ db.prepare(`
2759
+ INSERT INTO session_summaries (session_id, request, investigated, decisions, completed, failed_attempts, next_steps, files_created, files_modified, verification_results, plan_progress, created_at, created_at_epoch)
2760
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2761
+ `).run(
2762
+ sessionId,
2763
+ summary.request ?? null,
2764
+ summary.investigated ?? null,
2765
+ summary.decisions ?? null,
2766
+ summary.completed ?? null,
2767
+ summary.failedAttempts ?? null,
2768
+ summary.nextSteps ?? null,
2769
+ JSON.stringify(summary.filesCreated ?? []),
2770
+ JSON.stringify(summary.filesModified ?? []),
2771
+ JSON.stringify(summary.verificationResults ?? {}),
2772
+ JSON.stringify(summary.planProgress ?? {}),
2773
+ now.toISOString(),
2774
+ Math.floor(now.getTime() / 1e3)
2775
+ );
2776
+ }
2777
+ function addUserPrompt(db, sessionId, text, promptNumber) {
2778
+ const now = /* @__PURE__ */ new Date();
2779
+ db.prepare(`
2780
+ INSERT INTO user_prompts (session_id, prompt_text, prompt_number, created_at, created_at_epoch)
2781
+ VALUES (?, ?, ?, ?, ?)
2782
+ `).run(sessionId, text, promptNumber, now.toISOString(), Math.floor(now.getTime() / 1e3));
2783
+ }
2784
+ function searchObservations(db, query, opts) {
2785
+ const limit = opts?.limit ?? 20;
2786
+ let sql = `
2787
+ SELECT o.id, o.type, o.title, o.created_at, o.session_id, o.importance,
2788
+ rank
2789
+ FROM observations_fts
2790
+ JOIN observations o ON observations_fts.rowid = o.id
2791
+ WHERE observations_fts MATCH ?
2792
+ `;
2793
+ const params = [sanitizeFts5Query(query)];
2794
+ if (opts?.type) {
2795
+ sql += " AND o.type = ?";
2796
+ params.push(opts.type);
2797
+ }
2798
+ if (opts?.crRule) {
2799
+ sql += " AND o.cr_rule = ?";
2800
+ params.push(opts.crRule);
2801
+ }
2802
+ if (opts?.dateFrom) {
2803
+ sql += " AND o.created_at >= ?";
2804
+ params.push(opts.dateFrom);
2805
+ }
2806
+ sql += " ORDER BY rank LIMIT ?";
2807
+ params.push(limit);
2808
+ return db.prepare(sql).all(...params);
2809
+ }
2810
+ function getRecentObservations(db, limit = 20, sessionId) {
2811
+ if (sessionId) {
2812
+ return db.prepare(`
2813
+ SELECT id, type, title, detail, importance, created_at, session_id
2814
+ FROM observations WHERE session_id = ?
2815
+ ORDER BY created_at_epoch DESC LIMIT ?
2816
+ `).all(sessionId, limit);
2817
+ }
2818
+ return db.prepare(`
2819
+ SELECT id, type, title, detail, importance, created_at, session_id
2820
+ FROM observations
2821
+ ORDER BY created_at_epoch DESC LIMIT ?
2822
+ `).all(limit);
2823
+ }
2824
+ function getSessionSummaries(db, limit = 10) {
2825
+ return db.prepare(`
2826
+ SELECT session_id, request, completed, failed_attempts, plan_progress, created_at
2827
+ FROM session_summaries
2828
+ ORDER BY created_at_epoch DESC LIMIT ?
2829
+ `).all(limit);
2830
+ }
2831
+ function getSessionTimeline(db, sessionId) {
2832
+ const session = db.prepare("SELECT * FROM sessions WHERE session_id = ?").get(sessionId);
2833
+ const observations = db.prepare("SELECT * FROM observations WHERE session_id = ? ORDER BY created_at_epoch ASC").all(sessionId);
2834
+ const summary = db.prepare("SELECT * FROM session_summaries WHERE session_id = ? ORDER BY created_at_epoch DESC LIMIT 1").get(sessionId);
2835
+ const prompts = db.prepare("SELECT * FROM user_prompts WHERE session_id = ? ORDER BY prompt_number ASC").all(sessionId);
2836
+ return {
2837
+ session: session ?? null,
2838
+ observations,
2839
+ summary: summary ?? null,
2840
+ prompts
2841
+ };
2842
+ }
2843
+ function getFailedAttempts(db, query, limit = 20) {
2844
+ if (query) {
2845
+ return db.prepare(`
2846
+ SELECT o.id, o.title, o.detail, o.session_id, o.recurrence_count, o.created_at
2847
+ FROM observations_fts
2848
+ JOIN observations o ON observations_fts.rowid = o.id
2849
+ WHERE observations_fts MATCH ? AND o.type = 'failed_attempt'
2850
+ ORDER BY o.recurrence_count DESC, rank LIMIT ?
2851
+ `).all(sanitizeFts5Query(query), limit);
2852
+ }
2853
+ return db.prepare(`
2854
+ SELECT id, title, detail, session_id, recurrence_count, created_at
2855
+ FROM observations WHERE type = 'failed_attempt'
2856
+ ORDER BY recurrence_count DESC, created_at_epoch DESC LIMIT ?
2857
+ `).all(limit);
2858
+ }
2859
+ function getDecisionsAbout(db, query, limit = 20) {
2860
+ return db.prepare(`
2861
+ SELECT o.id, o.title, o.detail, o.session_id, o.created_at
2862
+ FROM observations_fts
2863
+ JOIN observations o ON observations_fts.rowid = o.id
2864
+ WHERE observations_fts MATCH ? AND o.type = 'decision'
2865
+ ORDER BY rank LIMIT ?
2866
+ `).all(sanitizeFts5Query(query), limit);
2867
+ }
2868
+ function armUsageCounter(db, nowEpochSec) {
2869
+ const existing = getMemoryMeta(db, USAGE_COUNTER_ARMED_KEY);
2870
+ if (existing) {
2871
+ const n = Number(existing);
2872
+ if (Number.isFinite(n) && n > 0) return n;
2873
+ }
2874
+ const now = nowEpochSec ?? Math.floor(Date.now() / 1e3);
2875
+ setMemoryMeta(db, USAGE_COUNTER_ARMED_KEY, String(now));
2876
+ return now;
2877
+ }
2878
+ function usageWarmupElapsed(db, warmupDays, nowEpochSec) {
2879
+ const armed = getMemoryMeta(db, USAGE_COUNTER_ARMED_KEY);
2880
+ if (!armed) return false;
2881
+ const armedEpoch = Number(armed);
2882
+ if (!Number.isFinite(armedEpoch) || armedEpoch <= 0) return false;
2883
+ const now = nowEpochSec ?? Math.floor(Date.now() / 1e3);
2884
+ return now - armedEpoch >= warmupDays * 86400;
2885
+ }
2886
+ function expireOldLowValueObservations(db, opts) {
2887
+ const now = opts.nowEpochSec ?? Math.floor(Date.now() / 1e3);
2888
+ if (!usageWarmupElapsed(db, opts.usageWarmupDays, now)) return 0;
2889
+ const cutoffEpoch = now - opts.retentionDays * 86400;
2890
+ const typePlaceholders = opts.protectedTypes.length ? opts.protectedTypes.map(() => "?").join(",") : "''";
2891
+ const iso = new Date(now * 1e3).toISOString();
2892
+ const result = db.prepare(
2893
+ `UPDATE observations
2894
+ SET expired_at = ?,
2895
+ expired_at_epoch = ?,
2896
+ valid_to = ?,
2897
+ valid_to_epoch = ?
2898
+ WHERE expired_at IS NULL
2899
+ AND created_at_epoch < ?
2900
+ AND importance <= ?
2901
+ AND type NOT IN (${typePlaceholders})
2902
+ AND COALESCE(evidence, '') != ?
2903
+ -- A file-backed row mirrors a file the human still keeps on disk.
2904
+ -- Value-decay may never retire it; only the file's removal can.
2905
+ AND title NOT LIKE ?
2906
+ AND NOT EXISTS (
2907
+ SELECT 1 FROM memory_usage u
2908
+ WHERE u.source = 'observation'
2909
+ AND u.record_id = observations.id
2910
+ AND u.hit_count > 0
2911
+ )
2912
+ AND NOT EXISTS (
2913
+ -- The grace period: a row demoted within the last cadence
2914
+ -- window is NOT yet expirable, so being pushed to the floor can
2915
+ -- never be immediately fatal.
2916
+ SELECT 1 FROM memory_usage u
2917
+ WHERE u.source = 'observation'
2918
+ AND u.record_id = observations.id
2919
+ AND u.last_reweight_epoch IS NOT NULL
2920
+ AND u.last_reweight_epoch > ?
2921
+ )`
2922
+ ).run(
2923
+ iso,
2924
+ now,
2925
+ iso,
2926
+ now,
2927
+ cutoffEpoch,
2928
+ opts.importanceFloor,
2929
+ ...opts.protectedTypes,
2930
+ CONSOLIDATION_LESSON_EVIDENCE,
2931
+ MEMORY_FILE_TITLE_LIKE,
2932
+ now - (opts.reweightIntervalDays ?? 1) * 86400
2933
+ );
2934
+ return result.changes;
2935
+ }
2936
+ function pruneOldObservations(db, opts) {
2937
+ return expireOldLowValueObservations(db, opts);
2938
+ }
2939
+ function recordRecallHits(db, sessionId, hits, nowEpochSec) {
2940
+ if (!hits.length) return 0;
2941
+ const now = nowEpochSec ?? Math.floor(Date.now() / 1e3);
2942
+ let recorded = 0;
2943
+ const claim = db.prepare(
2944
+ `INSERT OR IGNORE INTO memory_usage_sessions (source, record_id, session_id)
2945
+ VALUES (?, ?, ?)`
2946
+ );
2947
+ const bump = db.prepare(
2948
+ `INSERT INTO memory_usage (source, record_id, hit_count, hits_windowed, last_hit_epoch)
2949
+ VALUES (?, ?, 1, 1, ?)
2950
+ ON CONFLICT(source, record_id) DO UPDATE SET
2951
+ hit_count = hit_count + 1,
2952
+ hits_windowed = hits_windowed + 1,
2953
+ last_hit_epoch = excluded.last_hit_epoch`
2954
+ );
2955
+ const tx = db.transaction(() => {
2956
+ for (const h of hits) {
2957
+ if (claim.run(h.source, h.id, sessionId).changes === 0) continue;
2958
+ bump.run(h.source, h.id, now);
2959
+ recorded++;
2960
+ }
2961
+ });
2962
+ tx();
2963
+ return recorded;
2964
+ }
2965
+ function deduplicateFailedAttempt(db, sessionId, title, detail, opts) {
2966
+ const existing = db.prepare(`
2967
+ SELECT id, recurrence_count FROM observations
2968
+ WHERE type = 'failed_attempt' AND title = ?
2969
+ ORDER BY created_at_epoch DESC LIMIT 1
2970
+ `).get(title);
2971
+ if (existing) {
2972
+ db.prepare("UPDATE observations SET recurrence_count = recurrence_count + 1, detail = COALESCE(?, detail) WHERE id = ?").run(detail, existing.id);
2973
+ return existing.id;
2974
+ }
2975
+ return addObservation(db, sessionId, "failed_attempt", title, detail, {
2976
+ ...opts,
2977
+ importance: 5
2978
+ });
2979
+ }
2980
+ function getSessionsByTask(db, taskId) {
2981
+ return db.prepare(`
2982
+ SELECT session_id, status, started_at, ended_at, plan_phase
2983
+ FROM sessions WHERE task_id = ?
2984
+ ORDER BY started_at_epoch DESC
2985
+ LIMIT 10000
2986
+ `).all(taskId);
2987
+ }
2988
+ function getCrossTaskProgress(db, taskId) {
2989
+ const sessions = db.prepare(`
2990
+ SELECT session_id FROM sessions WHERE task_id = ? LIMIT 10000
2991
+ `).all(taskId);
2992
+ const merged = {};
2993
+ for (const session of sessions) {
2994
+ const summaries = db.prepare(`
2995
+ SELECT plan_progress FROM session_summaries WHERE session_id = ? LIMIT 10000
2996
+ `).all(session.session_id);
2997
+ for (const summary of summaries) {
2998
+ try {
2999
+ const progress = JSON.parse(summary.plan_progress);
3000
+ for (const [key, value] of Object.entries(progress)) {
3001
+ if (!merged[key] || value === "complete" || value === "in_progress" && merged[key] === "pending") {
3002
+ merged[key] = value;
3003
+ }
3004
+ }
3005
+ } catch (_e) {
3006
+ }
3007
+ }
3008
+ }
3009
+ return merged;
3010
+ }
3011
+ function linkSessionToTask(db, sessionId, taskId) {
3012
+ db.prepare("UPDATE sessions SET task_id = ? WHERE session_id = ?").run(taskId, sessionId);
3013
+ }
3014
+ function addConversationTurn(db, sessionId, turnNumber, userPrompt, assistantResponse, toolCallsJson, toolCallCount, promptTokens, responseTokens) {
3015
+ const result = db.prepare(`
3016
+ INSERT INTO conversation_turns (session_id, turn_number, user_prompt, assistant_response, tool_calls_json, tool_call_count, prompt_tokens, response_tokens)
3017
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
3018
+ `).run(
3019
+ sessionId,
3020
+ turnNumber,
3021
+ userPrompt,
3022
+ assistantResponse ? assistantResponse.slice(0, 1e4) : null,
3023
+ toolCallsJson,
3024
+ toolCallCount,
3025
+ promptTokens,
3026
+ responseTokens
3027
+ );
3028
+ return Number(result.lastInsertRowid);
3029
+ }
3030
+ function addToolCallDetail(db, sessionId, turnNumber, toolName, inputSummary, inputSize, outputSize, success, filesInvolved) {
3031
+ db.prepare(`
3032
+ INSERT INTO tool_call_details (session_id, turn_number, tool_name, tool_input_summary, tool_input_size, tool_output_size, tool_success, files_involved)
3033
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
3034
+ `).run(
3035
+ sessionId,
3036
+ turnNumber,
3037
+ toolName,
3038
+ inputSummary ? inputSummary.slice(0, 500) : null,
3039
+ inputSize,
3040
+ outputSize,
3041
+ success ? 1 : 0,
3042
+ filesInvolved ? JSON.stringify(filesInvolved) : null
3043
+ );
3044
+ }
3045
+ function getLastProcessedLine(db, sessionId) {
3046
+ const row = db.prepare("SELECT value FROM memory_meta WHERE key = ?").get(`last_processed_line:${sessionId}`);
3047
+ return row ? parseInt(row.value, 10) : 0;
3048
+ }
3049
+ function setLastProcessedLine(db, sessionId, lineNumber) {
3050
+ db.prepare("INSERT OR REPLACE INTO memory_meta (key, value) VALUES (?, ?)").run(`last_processed_line:${sessionId}`, String(lineNumber));
3051
+ }
3052
+ function pruneOldConversationTurns(db, retentionDays = 90) {
3053
+ const cutoffEpoch = Math.floor(Date.now() / 1e3) - retentionDays * 86400;
3054
+ const turnsResult = db.prepare("DELETE FROM conversation_turns WHERE created_at_epoch < ?").run(cutoffEpoch);
3055
+ const detailsResult = db.prepare("DELETE FROM tool_call_details WHERE created_at_epoch < ?").run(cutoffEpoch);
3056
+ return { turnsDeleted: turnsResult.changes, detailsDeleted: detailsResult.changes };
3057
+ }
3058
+ function getConversationTurns(db, sessionId, opts) {
3059
+ let sql = "SELECT id, turn_number, user_prompt, assistant_response, tool_calls_json, tool_call_count, prompt_tokens, response_tokens, created_at FROM conversation_turns WHERE session_id = ?";
3060
+ const params = [sessionId];
3061
+ if (opts?.turnFrom !== void 0) {
3062
+ sql += " AND turn_number >= ?";
3063
+ params.push(opts.turnFrom);
3064
+ }
3065
+ if (opts?.turnTo !== void 0) {
3066
+ sql += " AND turn_number <= ?";
3067
+ params.push(opts.turnTo);
3068
+ }
3069
+ sql += " ORDER BY turn_number ASC";
3070
+ return db.prepare(sql).all(...params);
3071
+ }
3072
+ function searchConversationTurns(db, query, opts) {
3073
+ const limit = opts?.limit ?? 20;
3074
+ let sql = `
3075
+ SELECT ct.id, ct.session_id, ct.turn_number, ct.user_prompt, ct.tool_call_count, ct.response_tokens, ct.created_at, rank
3076
+ FROM conversation_turns_fts
3077
+ JOIN conversation_turns ct ON conversation_turns_fts.rowid = ct.id
3078
+ WHERE conversation_turns_fts MATCH ?
3079
+ `;
3080
+ const params = [sanitizeFts5Query(query)];
3081
+ if (opts?.sessionId) {
3082
+ sql += " AND ct.session_id = ?";
3083
+ params.push(opts.sessionId);
3084
+ }
3085
+ if (opts?.dateFrom) {
3086
+ sql += " AND ct.created_at >= ?";
3087
+ params.push(opts.dateFrom);
3088
+ }
3089
+ if (opts?.dateTo) {
3090
+ sql += " AND ct.created_at <= ?";
3091
+ params.push(opts.dateTo);
3092
+ }
3093
+ if (opts?.minToolCalls !== void 0) {
3094
+ sql += " AND ct.tool_call_count >= ?";
3095
+ params.push(opts.minToolCalls);
3096
+ }
3097
+ sql += " ORDER BY rank LIMIT ?";
3098
+ params.push(limit);
3099
+ return db.prepare(sql).all(...params);
3100
+ }
3101
+ function getToolPatterns(db, opts) {
3102
+ const groupBy = opts?.groupBy ?? "tool";
3103
+ const params = [];
3104
+ let whereClause = "";
3105
+ const conditions = [];
3106
+ if (opts?.sessionId) {
3107
+ conditions.push("session_id = ?");
3108
+ params.push(opts.sessionId);
3109
+ }
3110
+ if (opts?.toolName) {
3111
+ conditions.push("tool_name = ?");
3112
+ params.push(opts.toolName);
3113
+ }
3114
+ if (opts?.dateFrom) {
3115
+ conditions.push("created_at >= ?");
3116
+ params.push(opts.dateFrom);
3117
+ }
3118
+ if (conditions.length > 0) {
3119
+ whereClause = "WHERE " + conditions.join(" AND ");
3120
+ }
3121
+ let sql;
3122
+ switch (groupBy) {
3123
+ case "session":
3124
+ sql = `SELECT session_id, COUNT(*) as call_count, COUNT(DISTINCT tool_name) as unique_tools,
3125
+ SUM(CASE WHEN tool_success = 1 THEN 1 ELSE 0 END) as successes,
3126
+ SUM(CASE WHEN tool_success = 0 THEN 1 ELSE 0 END) as failures,
3127
+ AVG(tool_output_size) as avg_output_size
3128
+ FROM tool_call_details ${whereClause}
3129
+ GROUP BY session_id ORDER BY call_count DESC`;
3130
+ break;
3131
+ case "day":
3132
+ sql = `SELECT date(created_at) as day, COUNT(*) as call_count, COUNT(DISTINCT tool_name) as unique_tools,
3133
+ SUM(CASE WHEN tool_success = 1 THEN 1 ELSE 0 END) as successes
3134
+ FROM tool_call_details ${whereClause}
3135
+ GROUP BY date(created_at) ORDER BY day DESC`;
3136
+ break;
3137
+ default:
3138
+ sql = `SELECT tool_name, COUNT(*) as call_count,
3139
+ SUM(CASE WHEN tool_success = 1 THEN 1 ELSE 0 END) as successes,
3140
+ SUM(CASE WHEN tool_success = 0 THEN 1 ELSE 0 END) as failures,
3141
+ AVG(tool_output_size) as avg_output_size,
3142
+ AVG(tool_input_size) as avg_input_size
3143
+ FROM tool_call_details ${whereClause}
3144
+ GROUP BY tool_name ORDER BY call_count DESC`;
3145
+ break;
3146
+ }
3147
+ return db.prepare(sql).all(...params);
3148
+ }
3149
+ function getSessionStats(db, opts) {
3150
+ if (opts?.sessionId) {
3151
+ const turns = db.prepare("SELECT COUNT(*) as turn_count, SUM(tool_call_count) as total_tool_calls, SUM(prompt_tokens) as total_prompt_tokens, SUM(response_tokens) as total_response_tokens FROM conversation_turns WHERE session_id = ?").get(opts.sessionId);
3152
+ const toolBreakdown = db.prepare("SELECT tool_name, COUNT(*) as count FROM tool_call_details WHERE session_id = ? GROUP BY tool_name ORDER BY count DESC").all(opts.sessionId);
3153
+ const session = db.prepare("SELECT * FROM sessions WHERE session_id = ?").get(opts.sessionId);
3154
+ return [{
3155
+ session_id: opts.sessionId,
3156
+ status: session?.status ?? "unknown",
3157
+ started_at: session?.started_at ?? null,
3158
+ ended_at: session?.ended_at ?? null,
3159
+ ...turns,
3160
+ tool_breakdown: toolBreakdown
3161
+ }];
3162
+ }
3163
+ const limit = opts?.limit ?? 10;
3164
+ return db.prepare(`
3165
+ SELECT s.session_id, s.status, s.started_at, s.ended_at,
3166
+ COUNT(ct.id) as turn_count,
3167
+ COALESCE(SUM(ct.tool_call_count), 0) as total_tool_calls,
3168
+ COALESCE(SUM(ct.prompt_tokens), 0) as total_prompt_tokens,
3169
+ COALESCE(SUM(ct.response_tokens), 0) as total_response_tokens
3170
+ FROM sessions s
3171
+ LEFT JOIN conversation_turns ct ON s.session_id = ct.session_id
3172
+ GROUP BY s.session_id
3173
+ ORDER BY s.started_at_epoch DESC
3174
+ LIMIT ?
3175
+ `).all(limit);
3176
+ }
3177
+ function getObservabilityDbSize(db) {
3178
+ const turnsCount = db.prepare("SELECT COUNT(*) as c FROM conversation_turns").get().c;
3179
+ const detailsCount = db.prepare("SELECT COUNT(*) as c FROM tool_call_details").get().c;
3180
+ const obsCount = db.prepare("SELECT COUNT(*) as c FROM observations").get().c;
3181
+ const pageCount = db.pragma("page_count")[0]?.page_count ?? 0;
3182
+ const pageSize = db.pragma("page_size")[0]?.page_size ?? 4096;
3183
+ return {
3184
+ conversation_turns_count: turnsCount,
3185
+ tool_call_details_count: detailsCount,
3186
+ observations_count: obsCount,
3187
+ db_page_count: pageCount,
3188
+ db_page_size: pageSize,
3189
+ estimated_size_mb: Math.round(pageCount * pageSize / (1024 * 1024) * 100) / 100
3190
+ };
3191
+ }
3192
+ function addFailureClass(db, opts) {
3193
+ const result = db.prepare(`
3194
+ INSERT OR IGNORE INTO failure_classes (name, description, diff_patterns, file_patterns, prompt_keywords, incidents, rules, scanner_checks, known_message, needs_review)
3195
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
3196
+ `).run(
3197
+ opts.name,
3198
+ opts.description,
3199
+ JSON.stringify(opts.diffPatterns ?? []),
3200
+ JSON.stringify(opts.filePatterns ?? []),
3201
+ JSON.stringify(opts.promptKeywords ?? []),
3202
+ JSON.stringify(opts.incidents ?? []),
3203
+ JSON.stringify(opts.rules ?? []),
3204
+ JSON.stringify(opts.scannerChecks ?? []),
3205
+ opts.knownMessage ?? "",
3206
+ opts.needsReview ? 1 : 0
3207
+ );
3208
+ return Number(result.lastInsertRowid);
3209
+ }
3210
+ function getFailureClasses(db) {
3211
+ const rows = db.prepare("SELECT * FROM failure_classes ORDER BY name LIMIT 10000").all();
3212
+ return rows.map((row) => ({
3213
+ id: row.id,
3214
+ name: row.name,
3215
+ description: row.description,
3216
+ diff_patterns: JSON.parse(row.diff_patterns || "[]"),
3217
+ file_patterns: JSON.parse(row.file_patterns || "[]"),
3218
+ prompt_keywords: JSON.parse(row.prompt_keywords || "[]"),
3219
+ incidents: JSON.parse(row.incidents || "[]"),
3220
+ rules: JSON.parse(row.rules || "[]"),
3221
+ scanner_checks: JSON.parse(row.scanner_checks || "[]"),
3222
+ known_message: row.known_message,
3223
+ needs_review: !!row.needs_review
3224
+ }));
3225
+ }
3226
+ function appendIncidentToFailureClass(db, className, incidentId) {
3227
+ const row = db.prepare("SELECT incidents FROM failure_classes WHERE name = ?").get(className);
3228
+ if (!row) return;
3229
+ const incidents = JSON.parse(row.incidents || "[]");
3230
+ if (!incidents.includes(incidentId)) {
3231
+ incidents.push(incidentId);
3232
+ db.prepare("UPDATE failure_classes SET incidents = ?, updated_at = datetime('now') WHERE name = ?").run(JSON.stringify(incidents), className);
3233
+ }
3234
+ }
3235
+ function scoreFailureClasses(db, matchText, filePath, promptContext, weights) {
3236
+ const classes = getFailureClasses(db);
3237
+ if (classes.length === 0) return null;
3238
+ const diffWeight = weights?.diffPatternWeight ?? 3;
3239
+ const fileWeight = weights?.filePatternWeight ?? 2;
3240
+ const promptWeight = weights?.promptKeywordWeight ?? 2;
3241
+ let bestMatch = null;
3242
+ for (const fc of classes) {
3243
+ let score = 0;
3244
+ for (const pattern of fc.diff_patterns) {
3245
+ if (!pattern) continue;
3246
+ try {
3247
+ if (new RegExp(pattern, "i").test(matchText)) {
3248
+ score += diffWeight;
3249
+ }
3250
+ } catch {
3251
+ if (matchText.toLowerCase().includes(pattern.toLowerCase())) {
3252
+ score += diffWeight;
3253
+ }
3254
+ }
3255
+ }
3256
+ for (const pattern of fc.file_patterns) {
3257
+ if (!pattern) continue;
3258
+ try {
3259
+ if (new RegExp(pattern).test(filePath)) {
3260
+ score += fileWeight;
3261
+ }
3262
+ } catch {
3263
+ if (filePath.includes(pattern)) {
3264
+ score += fileWeight;
3265
+ }
3266
+ }
3267
+ }
3268
+ if (promptContext) {
3269
+ for (const keyword of fc.prompt_keywords) {
3270
+ if (!keyword) continue;
3271
+ try {
3272
+ if (new RegExp(keyword, "i").test(promptContext)) {
3273
+ score += promptWeight;
3274
+ }
3275
+ } catch {
3276
+ if (promptContext.toLowerCase().includes(keyword.toLowerCase())) {
3277
+ score += promptWeight;
3278
+ }
3279
+ }
3280
+ }
3281
+ }
3282
+ if (!bestMatch || score > bestMatch.score) {
3283
+ bestMatch = {
3284
+ name: fc.name,
3285
+ score,
3286
+ incidentCount: fc.incidents.length,
3287
+ rules: fc.rules,
3288
+ knownMessage: fc.known_message
3289
+ };
3290
+ }
3291
+ }
3292
+ return bestMatch;
3293
+ }
3294
+ var MEMORY_SCHEMA_VERSION, TOOL_COST_EVENTS_RETENTION_DAYS, MAX_DRAFT_TEXT_LEN, FUNNEL_EVENT_DRAIN_LIMIT, FUNNEL_EVENT_OUTBOX_CAP, _temporalColCache, CONSOLIDATION_LESSON_EVIDENCE, MEMORY_FILE_TITLE_PREFIX, MEMORY_FILE_TITLE_LIKE, USAGE_COUNTER_ARMED_KEY;
3295
+ var init_memory_db = __esm({
3296
+ "src/memory-db.ts"() {
3297
+ "use strict";
3298
+ init_config();
3299
+ init_memory_vector();
3300
+ init_db_backup();
3301
+ init_hook_failure_signal();
3302
+ init_memory_embed_sweep();
3303
+ MEMORY_SCHEMA_VERSION = 1;
3304
+ TOOL_COST_EVENTS_RETENTION_DAYS = 90;
3305
+ MAX_DRAFT_TEXT_LEN = 16384;
3306
+ FUNNEL_EVENT_DRAIN_LIMIT = 5e3;
3307
+ FUNNEL_EVENT_OUTBOX_CAP = 2e4;
3308
+ _temporalColCache = /* @__PURE__ */ new WeakMap();
3309
+ CONSOLIDATION_LESSON_EVIDENCE = "consolidation:session-summary";
3310
+ MEMORY_FILE_TITLE_PREFIX = "[memory-file] ";
3311
+ MEMORY_FILE_TITLE_LIKE = `${MEMORY_FILE_TITLE_PREFIX}%`;
3312
+ USAGE_COUNTER_ARMED_KEY = "usage_counter_armed_epoch";
3313
+ }
3314
+ });
3315
+
3316
+ // src/hooks/pre-delete-check.ts
3317
+ import Database3 from "better-sqlite3";
3318
+ import { existsSync as existsSync7 } from "fs";
3319
+
3320
+ // src/sentinel-db.ts
3321
+ init_config();
3322
+ init_memory_db();
632
3323
 
633
3324
  // src/lib/sql-table-names.ts
3325
+ init_config();
634
3326
  function t(suffix) {
635
3327
  return `${getConfig().toolPrefix}_${suffix}`;
636
3328
  }
@@ -717,12 +3409,16 @@ function getFeatureImpact(db, filePaths) {
717
3409
  };
718
3410
  }
719
3411
 
3412
+ // src/hooks/pre-delete-check.ts
3413
+ init_config();
3414
+
720
3415
  // src/hooks/lib/write-hook-message.ts
721
3416
  function writeHookMessage(message) {
722
3417
  process.stdout.write(JSON.stringify({ message }) + "\n");
723
3418
  }
724
3419
 
725
3420
  // src/hooks/pre-delete-check.ts
3421
+ init_hook_failure_signal();
726
3422
  var PROJECT_ROOT2 = getProjectRoot();
727
3423
  var KNOWLEDGE_PROTECTED_FILES = [
728
3424
  "knowledge-db.ts",
@@ -731,9 +3427,9 @@ var KNOWLEDGE_PROTECTED_FILES = [
731
3427
  ];
732
3428
  function getDataDb() {
733
3429
  const dbPath = getResolvedPaths().dataDbPath;
734
- if (!existsSync3(dbPath)) return null;
3430
+ if (!existsSync7(dbPath)) return null;
735
3431
  try {
736
- const db = new Database2(dbPath, { readonly: true });
3432
+ const db = new Database3(dbPath, { readonly: true });
737
3433
  db.pragma("journal_mode = WAL");
738
3434
  return db;
739
3435
  } catch {
@@ -757,9 +3453,9 @@ function checkKnowledgeFileProtection(input) {
757
3453
  }
758
3454
  }
759
3455
  for (const f of candidateFiles) {
760
- const basename = f.split("/").pop() ?? f;
761
- if (KNOWLEDGE_PROTECTED_FILES.includes(basename)) {
762
- return `KNOWLEDGE SYSTEM PROTECTION: "${basename}" is a core knowledge system file. Deleting it will break knowledge indexing and memory retrieval. Create a replacement before removing.`;
3456
+ const basename3 = f.split("/").pop() ?? f;
3457
+ if (KNOWLEDGE_PROTECTED_FILES.includes(basename3)) {
3458
+ return `KNOWLEDGE SYSTEM PROTECTION: "${basename3}" is a core knowledge system file. Deleting it will break knowledge indexing and memory retrieval. Create a replacement before removing.`;
763
3459
  }
764
3460
  }
765
3461
  return null;
@@ -867,19 +3563,22 @@ async function main() {
867
3563
  const hookInput = JSON.parse(input);
868
3564
  const messages = runPreDeleteChecks(hookInput);
869
3565
  for (const msg of messages) writeHookMessage(msg);
870
- } catch {
3566
+ } catch (err) {
3567
+ recordHookFailure("pre-delete-check", err);
3568
+ process.stderr.write("MASSU SECURITY GATE \u2014 BLOCKED (gate could not evaluate this call)\n");
3569
+ process.exit(2);
871
3570
  }
872
3571
  process.exit(0);
873
3572
  }
874
3573
  function readStdin() {
875
- return new Promise((resolve3) => {
3574
+ return new Promise((resolve5) => {
876
3575
  let data = "";
877
3576
  process.stdin.setEncoding("utf-8");
878
3577
  process.stdin.on("data", (chunk) => {
879
3578
  data += chunk;
880
3579
  });
881
- process.stdin.on("end", () => resolve3(data));
882
- setTimeout(() => resolve3(data), 400);
3580
+ process.stdin.on("end", () => resolve5(data));
3581
+ setTimeout(() => resolve5(data), 400);
883
3582
  });
884
3583
  }
885
3584
  if (process.argv[1]?.endsWith("pre-delete-check.js") || process.argv[1]?.endsWith("pre-delete-check")) {