@massu/core 1.15.3 → 1.15.5

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