@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,22 +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/memory-db.ts
5
- import Database from "better-sqlite3";
6
- import { dirname as dirname2, basename } from "path";
7
- import { existsSync as existsSync3, mkdirSync as mkdirSync2 } from "fs";
8
-
9
- // src/config.ts
10
- import { resolve as resolve2, dirname } from "path";
11
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
12
- import { homedir as homedir2 } from "os";
13
- import { parse as parseYaml } from "yaml";
14
- 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);
15
28
 
16
29
  // src/lib/memory-path.ts
17
30
  function encodeMemoryDirName(projectRoot) {
18
31
  return projectRoot.replace(/\//g, "-");
19
32
  }
33
+ var init_memory_path = __esm({
34
+ "src/lib/memory-path.ts"() {
35
+ "use strict";
36
+ }
37
+ });
20
38
 
21
39
  // src/credentials.ts
22
40
  import { homedir } from "os";
@@ -29,9 +47,6 @@ import {
29
47
  rmSync,
30
48
  chmodSync
31
49
  } from "fs";
32
- var MASSU_ENV_API_KEY = "MASSU_API_KEY";
33
- var MASSU_ENV_CLOUD_ENDPOINT = "MASSU_CLOUD_ENDPOINT";
34
- var DEFAULT_CLOUD_ENDPOINT = "https://api.massu.ai/v1";
35
50
  function credentialsDir(home = homedir()) {
36
51
  return resolve(home, ".massu");
37
52
  }
@@ -79,391 +94,160 @@ function resolveEndpoint(opts = {}) {
79
94
  if (envEp.length > 0) return envEp;
80
95
  return DEFAULT_CLOUD_ENDPOINT;
81
96
  }
82
-
83
- // src/config.ts
84
- var DomainConfigSchema = z.object({
85
- name: z.string().default("Unknown"),
86
- routers: z.array(z.string()).default([]),
87
- pages: z.array(z.string()).default([]),
88
- tables: z.array(z.string()).default([]),
89
- allowedImportsFrom: z.array(z.string()).default([])
90
- });
91
- var PatternRuleConfigSchema = z.object({
92
- pattern: z.string().default("**"),
93
- rules: z.array(z.string()).default([]),
94
- language: z.string().optional()
95
- });
96
- var CostModelSchema = z.object({
97
- input_per_million: z.number(),
98
- output_per_million: z.number(),
99
- cache_read_per_million: z.number().optional(),
100
- cache_write_per_million: z.number().optional()
101
- });
102
- var AnalyticsConfigSchema = z.object({
103
- quality: z.object({
104
- weights: z.record(z.string(), z.number()).default({
105
- bug_found: -5,
106
- vr_failure: -10,
107
- incident: -20,
108
- cr_violation: -3,
109
- vr_pass: 2,
110
- clean_commit: 5,
111
- successful_verification: 3
112
- }),
113
- categories: z.array(z.string()).default(["security", "architecture", "coupling", "tests", "rule_compliance"])
114
- }).optional(),
115
- cost: z.object({
116
- models: z.record(z.string(), CostModelSchema).default({}),
117
- currency: z.string().default("USD")
118
- }).optional(),
119
- prompts: z.object({
120
- success_indicators: z.array(z.string()).default(["committed", "approved", "looks good", "perfect", "great", "thanks"]),
121
- failure_indicators: z.array(z.string()).default(["revert", "wrong", "that's not", "undo", "incorrect"]),
122
- max_turns_for_success: z.number().default(2)
123
- }).optional()
124
- }).optional();
125
- var CustomPatternSchema = z.object({
126
- pattern: z.string(),
127
- severity: z.string(),
128
- message: z.string()
129
- });
130
- var GovernanceConfigSchema = z.object({
131
- audit: z.object({
132
- formats: z.array(z.string()).default(["summary", "detailed", "soc2"]),
133
- retention_days: z.number().default(365),
134
- auto_log: z.record(z.string(), z.boolean()).default({
135
- code_changes: true,
136
- rule_enforcement: true,
137
- approvals: true,
138
- commits: true
139
- })
140
- }).optional(),
141
- validation: z.object({
142
- realtime: z.boolean().default(true),
143
- checks: z.record(z.string(), z.boolean()).default({
144
- rule_compliance: true,
145
- import_existence: true,
146
- naming_conventions: true
147
- }),
148
- custom_patterns: z.array(CustomPatternSchema).default([])
149
- }).optional(),
150
- adr: z.object({
151
- detection_phrases: z.array(z.string()).default(["chose", "decided", "switching to", "moving from", "going with"]),
152
- template: z.string().default("default"),
153
- storage: z.string().default("database"),
154
- output_dir: z.string().default("docs/adr")
155
- }).optional()
156
- }).optional();
157
- var SecurityPatternSchema = z.object({
158
- pattern: z.string(),
159
- severity: z.string(),
160
- category: z.string(),
161
- description: z.string()
162
- });
163
- var SecurityConfigSchema = z.object({
164
- patterns: z.array(SecurityPatternSchema).default([]),
165
- auto_score_on_edit: z.boolean().default(true),
166
- score_threshold_alert: z.number().default(50),
167
- severity_weights: z.record(z.string(), z.number()).optional(),
168
- restrictive_licenses: z.array(z.string()).optional(),
169
- dep_alternatives: z.record(z.string(), z.array(z.string())).optional(),
170
- dependencies: z.object({
171
- package_manager: z.string().default("npm"),
172
- blocked_packages: z.array(z.string()).default([]),
173
- preferred_packages: z.record(z.string(), z.string()).default({}),
174
- max_bundle_size_kb: z.number().default(500)
175
- }).optional()
176
- }).optional();
177
- var TeamConfigSchema = z.object({
178
- enabled: z.boolean().default(false),
179
- sync_backend: z.string().default("local"),
180
- developer_id: z.string().default("auto"),
181
- share_by_default: z.boolean().default(false),
182
- expertise_weights: z.object({
183
- session: z.number().default(20),
184
- observation: z.number().default(10)
185
- }).optional(),
186
- privacy: z.object({
187
- share_file_paths: z.boolean().default(true),
188
- share_code_snippets: z.boolean().default(false),
189
- share_observations: z.boolean().default(true)
190
- }).optional()
191
- }).optional();
192
- var RegressionConfigSchema = z.object({
193
- test_patterns: z.array(z.string()).default([
194
- "{dir}/__tests__/{name}.test.{ext}",
195
- "{dir}/{name}.spec.{ext}",
196
- "tests/{path}.test.{ext}"
197
- ]),
198
- test_runner: z.string().default("npm test"),
199
- health_thresholds: z.object({
200
- healthy: z.number().default(80),
201
- warning: z.number().default(50)
202
- }).optional()
203
- }).optional();
204
- var AutoLearningConfigSchema = z.object({
205
- enabled: z.boolean().default(true),
206
- incidentDir: z.string().default("docs/incidents"),
207
- memoryDir: z.string().default("memory"),
208
- memoryIndexFile: z.string().default("MEMORY.md"),
209
- enforcementHooksDir: z.string().default("scripts/hooks"),
210
- fixDetection: z.object({
211
- enabled: z.boolean().default(true),
212
- lookbackDays: z.number().default(7),
213
- signals: z.array(z.string()).default([
214
- "removed_broken_code",
215
- "added_error_handling",
216
- "method_name_correction",
217
- "auth_fix",
218
- "nil_handling_fix",
219
- "concurrency_fix",
220
- "async_pattern_fix",
221
- "added_missing_import"
222
- ])
223
- }).default({}),
224
- failureClassification: z.object({
225
- enabled: z.boolean().default(true),
226
- thresholds: z.object({
227
- known: z.number().default(5),
228
- similar: z.number().default(3)
229
- }).default({}),
230
- scoring: z.object({
231
- diffPatternWeight: z.number().default(3),
232
- filePatternWeight: z.number().default(2),
233
- promptKeywordWeight: z.number().default(2)
234
- }).default({})
235
- }).default({}),
236
- pipeline: z.object({
237
- requireIncidentReport: z.boolean().default(true),
238
- requirePreventionRule: z.boolean().default(true),
239
- requireEnforcement: z.boolean().default(true)
240
- }).default({}),
241
- // plan-v0.2-interactive-rule-approval P-D-008 / P-D-009: project-configured
242
- // custom destinations for the rule-candidate funnel. The classifier matches
243
- // a candidate to one of these entries when none of the framework
244
- // destinations (pattern-scanner / claude-md-cr / corrections-md) apply.
245
- customDestinations: z.array(z.object({
246
- name: z.string(),
247
- path: z.string(),
248
- triggerKeywords: z.array(z.string()).default([]),
249
- template: z.string()
250
- })).default([])
251
- }).optional();
252
- var CloudConfigSchema = z.object({
253
- enabled: z.boolean().default(false),
254
- apiKey: z.string().optional(),
255
- endpoint: z.string().optional(),
256
- sync: z.object({
257
- memory: z.boolean().default(true),
258
- analytics: z.boolean().default(true),
259
- audit: z.boolean().default(true)
260
- }).default({ memory: true, analytics: true, audit: true })
261
- }).optional();
262
- var ConventionsConfigSchema = z.object({
263
- claudeDirName: z.string().default(".claude").refine(
264
- (s) => !s.includes("..") && !s.startsWith("/"),
265
- { message: 'claudeDirName must not contain ".." or start with "/"' }
266
- ),
267
- sessionStatePath: z.string().default(".claude/session-state/CURRENT.md").refine(
268
- (s) => !s.includes("..") && !s.startsWith("/"),
269
- { message: 'sessionStatePath must not contain ".." or start with "/"' }
270
- ),
271
- sessionArchivePath: z.string().default(".claude/session-state/archive").refine(
272
- (s) => !s.includes("..") && !s.startsWith("/"),
273
- { message: 'sessionArchivePath must not contain ".." or start with "/"' }
274
- ),
275
- knowledgeCategories: z.array(z.string()).default([
276
- "patterns",
277
- "commands",
278
- "incidents",
279
- "reference",
280
- "protocols",
281
- "checklists",
282
- "playbooks",
283
- "critical",
284
- "scripts",
285
- "status",
286
- "templates",
287
- "loop-state",
288
- "session-state",
289
- "agents"
290
- ]),
291
- knowledgeSourceFiles: z.array(z.string()).default(["CLAUDE.md", "MEMORY.md", "corrections.md"]),
292
- excludePatterns: z.array(z.string()).default(["/ARCHIVE/", "/SESSION-HISTORY/"])
293
- }).optional();
294
- var PythonDomainConfigSchema = z.object({
295
- name: z.string(),
296
- packages: z.array(z.string()),
297
- 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
+ }
298
105
  });
299
- var PythonConfigSchema = z.object({
300
- root: z.string(),
301
- alembic_dir: z.string().optional(),
302
- domains: z.array(PythonDomainConfigSchema).default([]),
303
- exclude_dirs: z.array(z.string()).default(["__pycache__", ".venv", "venv", ".mypy_cache", ".pytest_cache"])
304
- }).optional();
305
- var PathsConfigSchema = z.object({
306
- source: z.string().default("src"),
307
- aliases: z.record(z.string(), z.string()).default({ "@": "src" }),
308
- monorepo_roots: z.array(z.string()).optional(),
309
- routers: z.string().optional(),
310
- routerRoot: z.string().optional(),
311
- pages: z.string().optional(),
312
- middleware: z.string().optional(),
313
- schema: z.string().optional(),
314
- components: z.string().optional(),
315
- 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
+ }
316
243
  });
317
- var LanguageFrameworkEntrySchema = z.object({
318
- framework: z.string().optional(),
319
- test_framework: z.string().optional(),
320
- test: z.string().optional(),
321
- runtime: z.string().optional(),
322
- orm: z.string().optional(),
323
- router: z.string().optional(),
324
- ui: z.string().optional()
325
- }).passthrough();
326
- var FrameworkConfigSchema = z.object({
327
- type: z.string().default("typescript"),
328
- primary: z.string().optional(),
329
- router: z.string().default("none"),
330
- orm: z.string().default("none"),
331
- ui: z.string().default("none"),
332
- languages: z.record(z.string(), LanguageFrameworkEntrySchema).optional()
333
- }).passthrough();
334
- var DetectedConfigSchema = z.object({}).passthrough().optional();
335
- var VerificationEntrySchema = z.object({
336
- type: z.string().optional(),
337
- test: z.string().optional(),
338
- syntax: z.string().optional(),
339
- lint: z.string().optional(),
340
- build: z.string().optional()
341
- }).passthrough();
342
- var VerificationConfigSchema = z.record(z.string(), VerificationEntrySchema).optional();
343
- var CanonicalPathsSchema = z.record(z.string(), z.string()).optional();
344
- var VerificationTypesSchema = z.record(z.string(), z.string()).optional();
345
- var DetectionRuleEntrySchema = z.object({
346
- signals: z.array(z.string()).default([]),
347
- priority: z.number().optional()
348
- }).passthrough();
349
- var DetectionConfigSchema = z.object({
350
- rules: z.record(
351
- z.string(),
352
- // language
353
- z.record(z.string(), DetectionRuleEntrySchema)
354
- // framework -> rule entry
355
- ).optional(),
356
- signal_weights: z.record(z.string(), z.number()).optional(),
357
- disable_builtin: z.boolean().optional()
358
- }).passthrough().optional();
359
- var WatchConfigSchema = z.object({
360
- debounce_ms: z.number().int().positive().default(3e3),
361
- storm_threshold: z.number().int().positive().default(50),
362
- deep_storm_threshold: z.number().int().positive().default(500),
363
- hard_timeout_ms: z.number().int().positive().default(3e5),
364
- scope: z.enum(["paths", "full"]).default("paths"),
365
- // Plan 3a hotfix 2026-05-02: refuse to start if the watch surface
366
- // exceeds this many files. Prevents the misconfig pattern where
367
- // `paths.source_dirs` includes `.` or otherwise expands to a 60K+
368
- // file tree, producing 30-100% steady CPU. Override via
369
- // `paths_full_root_opt_in: true` for users on small repos who genuinely
370
- // need root-level watching.
371
- max_watched_files: z.number().int().positive().default(1e4),
372
- paths_full_root_opt_in: z.boolean().default(false)
373
- }).passthrough().optional();
374
- var AdapterLocalPathSchema = z.string().refine((s) => !/^([A-Za-z]:[\\/]|[\\/])/.test(s), {
375
- message: "absolute paths are rejected; adapters.local entries must be relative to the massu.config.yaml directory"
376
- }).refine((s) => !s.split(/[\\/]/).includes(".."), {
377
- message: "parent-directory traversal (`..`) is rejected; adapters.local entries must stay inside the project tree"
378
- }).transform((s) => s.split(/[\\/]/).filter((part) => part !== "" && part !== ".").join("/"));
379
- var AdaptersConfigSchema = z.object({
380
- enabled: z.boolean().default(false),
381
- local: z.array(AdapterLocalPathSchema).default([])
382
- }).passthrough().optional();
383
- var TelemetryConfigSchema = z.object({
384
- adapters: z.boolean().default(false)
385
- }).passthrough().optional();
386
- var LSPConfigSchema = z.object({
387
- enabled: z.boolean().default(false),
388
- servers: z.array(z.object({
389
- language: z.string(),
390
- command: z.string(),
391
- // F-014 (closed 2026-05-06): explicit opt-in to spawn SUID/SGID
392
- // binaries. Default false — argv[0] with the SUID bit is rejected
393
- // unless this is true. Decision is auditable in the YAML.
394
- allow_setuid: z.boolean().default(false),
395
- // F-015 (closed 2026-05-06): per-server RSS budget (MB). Watchdog
396
- // SIGKILLs the server after sustained breach. Default 1024 MB.
397
- // Set to 0 to disable the watchdog for this server.
398
- max_rss_mb: z.number().int().nonnegative().default(1024)
399
- })).default([]),
400
- autoDetect: z.object({
401
- viaPortScan: z.boolean().default(false)
402
- }).optional()
403
- }).passthrough();
404
- var RawConfigSchema = z.object({
405
- schema_version: z.union([z.literal(1), z.literal(2)]).default(1),
406
- project: z.object({
407
- name: z.string().default("my-project"),
408
- root: z.string().default("auto")
409
- }).default({ name: "my-project", root: "auto" }),
410
- framework: FrameworkConfigSchema.default({
411
- type: "typescript",
412
- router: "none",
413
- orm: "none",
414
- ui: "none"
415
- }),
416
- paths: PathsConfigSchema.default({ source: "src", aliases: { "@": "src" } }),
417
- toolPrefix: z.string().default("massu"),
418
- dbAccessPattern: z.string().optional(),
419
- knownMismatches: z.record(z.string(), z.record(z.string(), z.string())).optional(),
420
- accessScopes: z.array(z.string()).optional(),
421
- domains: z.array(DomainConfigSchema).default([]),
422
- rules: z.array(PatternRuleConfigSchema).default([]),
423
- // P-M-036 (plan-stage-d-medium-sweep): customer-authored CR-style
424
- // governance rules. DISTINCT from `rules:` above (path-scoped lint hints
425
- // used by pattern-scanner). At config-refresh time these entries are
426
- // loaded into the `knowledge_rules` SQLite table with
427
- // `source = 'customer-config'` so `massu_knowledge_rule` and the
428
- // governance docs surface customer-defined rules alongside framework CRs.
429
- governance_rules: z.array(
430
- z.object({
431
- id: z.string().min(1, "governance_rules[].id is required"),
432
- title: z.string().min(1, "governance_rules[].title is required"),
433
- description: z.string().min(1, "governance_rules[].description is required"),
434
- vr_type: z.string().default("VR-CUSTOM"),
435
- reference_path: z.string().optional(),
436
- severity: z.enum(["critical", "high", "medium", "low", "info"]).default("medium")
437
- }).passthrough()
438
- ).default([]),
439
- analytics: AnalyticsConfigSchema,
440
- governance: GovernanceConfigSchema,
441
- security: SecurityConfigSchema,
442
- team: TeamConfigSchema,
443
- regression: RegressionConfigSchema,
444
- cloud: CloudConfigSchema,
445
- conventions: ConventionsConfigSchema,
446
- autoLearning: AutoLearningConfigSchema,
447
- python: PythonConfigSchema,
448
- // P2-004 / P2-005 / P2-006 / P2-008: v2 extensions (all optional)
449
- verification: VerificationConfigSchema,
450
- canonical_paths: CanonicalPathsSchema,
451
- verification_types: VerificationTypesSchema,
452
- detection: DetectionConfigSchema,
453
- // Plan #2: detector-owned per-language conventions (free-form passthrough)
454
- detected: DetectedConfigSchema,
455
- // Plan 3a: file-watcher daemon tunables
456
- watch: WatchConfigSchema,
457
- // Plan 3c: third-party adapter registry kill-switch + signing override + local-path opt-in.
458
- adapters: AdaptersConfigSchema,
459
- // Plan 3c: anonymous adapter-discovery telemetry opt-in (default off).
460
- telemetry: TelemetryConfigSchema,
461
- // Plan 3b Phase 4: optional LSP enrichment of AST adapter results.
462
- lsp: LSPConfigSchema.optional()
463
- }).passthrough();
464
- var _config = null;
465
- var _resolvedApiKeySource = "none";
466
- 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";
467
251
  function findProjectRoot() {
468
252
  const cwd = process.cwd();
469
253
  let dir = cwd;
@@ -563,6 +347,7 @@ Hint: run \`massu config refresh\` to regenerate a valid config or fix the liste
563
347
  team: parsed.team,
564
348
  regression: parsed.regression,
565
349
  cloud: parsed.cloud,
350
+ memory: parsed.memory,
566
351
  conventions: parsed.conventions,
567
352
  autoLearning: parsed.autoLearning,
568
353
  python: parsed.python,
@@ -627,20 +412,1246 @@ function getResolvedPaths() {
627
412
  settingsLocalPath: resolve2(root, claudeDirName, "settings.local.json")
628
413
  };
629
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/hooks/lib/hook-failure-signal.ts
954
+ import { appendFileSync, mkdirSync as mkdirSync3, existsSync as existsSync4 } from "fs";
955
+ import { join as join2, dirname as dirname3 } from "path";
956
+ function resolveFailureLogPath() {
957
+ const explicit = process.env.MASSU_HOOK_FAILURE_LOG;
958
+ if (explicit) return explicit;
959
+ let dir = process.cwd();
960
+ for (let i = 0; i < 12; i++) {
961
+ if (existsSync4(join2(dir, ".massu")) || existsSync4(join2(dir, "massu.config.yaml"))) {
962
+ return join2(dir, ".massu", "hook-failures.jsonl");
963
+ }
964
+ const parent = dirname3(dir);
965
+ if (parent === dir) break;
966
+ dir = parent;
967
+ }
968
+ return join2(process.cwd(), ".massu", "hook-failures.jsonl");
969
+ }
970
+ function recordHookFailure(hook, error, context) {
971
+ const record = {
972
+ hook,
973
+ error: error instanceof Error ? error.message : String(error),
974
+ stack: error instanceof Error ? error.stack?.split("\n").slice(0, 6).join("\n") : void 0,
975
+ context,
976
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
977
+ };
978
+ let wroteSomething = false;
979
+ try {
980
+ const path = resolveFailureLogPath();
981
+ mkdirSync3(dirname3(path), { recursive: true });
982
+ appendFileSync(path, JSON.stringify(record) + "\n", "utf-8");
983
+ wroteSomething = true;
984
+ } catch {
985
+ }
986
+ try {
987
+ process.stderr.write(
988
+ `[massu] HOOK FAILURE in ${hook}: ${record.error}
989
+ [massu] This is a bug in Massu, not in your code. See .massu/hook-failures.jsonl
990
+ `
991
+ );
992
+ wroteSomething = true;
993
+ } catch {
994
+ }
995
+ try {
996
+ recordHookHealthRow(record);
997
+ } catch {
998
+ }
999
+ return wroteSomething;
1000
+ }
1001
+ function recordHookHealthRow(record) {
1002
+ const { getMemoryDb: getMemoryDb2 } = (init_memory_db(), __toCommonJS(memory_db_exports));
1003
+ const db = getMemoryDb2();
1004
+ try {
1005
+ db.prepare(
1006
+ `INSERT INTO hook_health (hook, error, context_json, occurred_at)
1007
+ VALUES (?, ?, ?, ?)`
1008
+ ).run(
1009
+ record.hook,
1010
+ record.error,
1011
+ record.context ? JSON.stringify(record.context) : null,
1012
+ record.timestamp
1013
+ );
1014
+ } finally {
1015
+ db.close();
1016
+ }
1017
+ }
1018
+ var init_hook_failure_signal = __esm({
1019
+ "src/hooks/lib/hook-failure-signal.ts"() {
1020
+ "use strict";
1021
+ }
1022
+ });
1023
+
1024
+ // src/memory-embedder-tokenizer.ts
1025
+ import { readFileSync as readFileSync3 } from "fs";
1026
+ function loadVocab(vocabPath) {
1027
+ const lines = readFileSync3(vocabPath, "utf-8").split("\n");
1028
+ const vocab = /* @__PURE__ */ new Map();
1029
+ for (let i = 0; i < lines.length; i++) {
1030
+ const tok = lines[i].replace(/\r$/, "");
1031
+ if (tok.length === 0 && i === lines.length - 1) continue;
1032
+ vocab.set(tok, i);
1033
+ }
1034
+ return vocab;
1035
+ }
1036
+ function isWhitespace(ch) {
1037
+ if (ch === " " || ch === " " || ch === "\n" || ch === "\r") return true;
1038
+ const cp = ch.codePointAt(0);
1039
+ return cp === 160 || cp >= 8192 && cp <= 8202 || cp === 8232 || cp === 8233 || cp === 8239 || cp === 8287 || cp === 12288 || cp === 65279;
1040
+ }
1041
+ function isControl(ch) {
1042
+ if (ch === " " || ch === "\n" || ch === "\r") return false;
1043
+ const cp = ch.codePointAt(0);
1044
+ return cp <= 31 || cp >= 127 && cp <= 159;
1045
+ }
1046
+ function isPunctuation(ch) {
1047
+ const cp = ch.codePointAt(0);
1048
+ if (cp >= 33 && cp <= 47 || cp >= 58 && cp <= 64 || cp >= 91 && cp <= 96 || cp >= 123 && cp <= 126)
1049
+ return true;
1050
+ return /\p{P}|\p{S}/u.test(ch);
1051
+ }
1052
+ function isCJK(cp) {
1053
+ return cp >= 19968 && cp <= 40959 || cp >= 13312 && cp <= 19903 || cp >= 131072 && cp <= 173791 || cp >= 173824 && cp <= 177983 || cp >= 177984 && cp <= 178207 || cp >= 178208 && cp <= 183983 || cp >= 63744 && cp <= 64255 || cp >= 194560 && cp <= 195103;
1054
+ }
1055
+ function stripAccents(text) {
1056
+ return text.normalize("NFD").replace(/\p{Mn}/gu, "");
1057
+ }
1058
+ function basicTokenize(text) {
1059
+ let cleaned = "";
1060
+ for (const ch of text) {
1061
+ const cp = ch.codePointAt(0);
1062
+ if (cp === 0 || cp === 65533 || isControl(ch)) continue;
1063
+ if (isWhitespace(ch)) {
1064
+ cleaned += " ";
1065
+ continue;
1066
+ }
1067
+ if (isCJK(cp)) {
1068
+ cleaned += " " + ch + " ";
1069
+ continue;
1070
+ }
1071
+ cleaned += ch;
1072
+ }
1073
+ const rawTokens = cleaned.split(/\s+/).filter(Boolean);
1074
+ const out = [];
1075
+ for (let tok of rawTokens) {
1076
+ tok = stripAccents(tok.toLowerCase());
1077
+ let cur = "";
1078
+ for (const ch of tok) {
1079
+ if (isPunctuation(ch)) {
1080
+ if (cur) {
1081
+ out.push(cur);
1082
+ cur = "";
1083
+ }
1084
+ out.push(ch);
1085
+ } else {
1086
+ cur += ch;
1087
+ }
1088
+ }
1089
+ if (cur) out.push(cur);
1090
+ }
1091
+ return out;
1092
+ }
1093
+ function wordpieceTokenize(token, vocab, maxChars = 100) {
1094
+ if (token.length > maxChars) return [UNK];
1095
+ const chars = Array.from(token);
1096
+ const subTokens = [];
1097
+ let start = 0;
1098
+ let bad = false;
1099
+ while (start < chars.length) {
1100
+ let end = chars.length;
1101
+ let curSub = null;
1102
+ while (start < end) {
1103
+ let substr = chars.slice(start, end).join("");
1104
+ if (start > 0) substr = "##" + substr;
1105
+ if (vocab.has(substr)) {
1106
+ curSub = substr;
1107
+ break;
1108
+ }
1109
+ end -= 1;
1110
+ }
1111
+ if (curSub === null) {
1112
+ bad = true;
1113
+ break;
1114
+ }
1115
+ subTokens.push(curSub);
1116
+ start = end;
1117
+ }
1118
+ return bad ? [UNK] : subTokens;
1119
+ }
1120
+ function encode(text, vocab, opts = {}) {
1121
+ const maxLen = opts.maxLen ?? 256;
1122
+ const basic = basicTokenize(text);
1123
+ const wpTokens = [];
1124
+ for (const t of basic) {
1125
+ for (const sub of wordpieceTokenize(t, vocab)) wpTokens.push(sub);
1126
+ }
1127
+ const truncated = wpTokens.slice(0, maxLen - 2);
1128
+ const tokens = [CLS, ...truncated, SEP];
1129
+ const unkId = vocab.get(UNK) ?? 100;
1130
+ const input_ids = tokens.map((t) => vocab.get(t) ?? unkId);
1131
+ const attention_mask = tokens.map(() => 1);
1132
+ const token_type_ids = tokens.map(() => 0);
1133
+ return { tokens, input_ids, attention_mask, token_type_ids };
1134
+ }
1135
+ var UNK, CLS, SEP;
1136
+ var init_memory_embedder_tokenizer = __esm({
1137
+ "src/memory-embedder-tokenizer.ts"() {
1138
+ "use strict";
1139
+ UNK = "[UNK]";
1140
+ CLS = "[CLS]";
1141
+ SEP = "[SEP]";
1142
+ }
1143
+ });
1144
+
1145
+ // src/memory-embedder.ts
1146
+ import { fileURLToPath } from "url";
1147
+ import { dirname as dirname4, join as join3 } from "path";
1148
+ import { existsSync as existsSync5 } from "fs";
1149
+ import { createRequire } from "module";
1150
+ function getActiveEmbedModel() {
1151
+ return _activeModel;
1152
+ }
1153
+ function loadEmbedSettings() {
1154
+ try {
1155
+ const r = getConfig().memory?.recall;
1156
+ return {
1157
+ enabled: r?.embedEnabled ?? true,
1158
+ endpoint: r?.embedEndpoint,
1159
+ model: r?.embedModel
1160
+ };
1161
+ } catch {
1162
+ return { enabled: true };
1163
+ }
1164
+ }
1165
+ function embeddingsDisabled() {
1166
+ return process.env.MASSU_DISABLE_EMBEDDINGS === "1";
1167
+ }
1168
+ function resolveModelDir() {
1169
+ try {
1170
+ let dir = dirname4(fileURLToPath(import.meta.url));
1171
+ let root = null;
1172
+ for (let i = 0; i < 8; i++) {
1173
+ if (existsSync5(join3(dir, "package.json"))) {
1174
+ root = dir;
1175
+ break;
1176
+ }
1177
+ const parent = dirname4(dir);
1178
+ if (parent === dir) break;
1179
+ dir = parent;
1180
+ }
1181
+ if (!root) return null;
1182
+ for (const rel of ["dist/embedder", "assets/embedder"]) {
1183
+ const candidate = join3(root, rel);
1184
+ if (existsSync5(join3(candidate, "model_quantized.onnx"))) return candidate;
1185
+ }
1186
+ return null;
1187
+ } catch {
1188
+ return null;
1189
+ }
1190
+ }
1191
+ function resolveWasmDir() {
1192
+ try {
1193
+ const req = createRequire(import.meta.url);
1194
+ const main2 = req.resolve(ORT_PKG);
1195
+ return dirname4(main2);
1196
+ } catch {
1197
+ return null;
1198
+ }
1199
+ }
1200
+ async function getSession() {
1201
+ if (_sessionPromise) return _sessionPromise;
1202
+ _sessionPromise = (async () => {
1203
+ try {
1204
+ const modelDir = resolveModelDir();
1205
+ const wasmDir = resolveWasmDir();
1206
+ if (!modelDir || !wasmDir) return null;
1207
+ const ort = await import(
1208
+ /* @vite-ignore */
1209
+ ORT_PKG
1210
+ );
1211
+ ort.env.wasm.numThreads = 1;
1212
+ ort.env.wasm.proxy = false;
1213
+ ort.env.wasm.wasmPaths = wasmDir.endsWith("/") ? wasmDir : wasmDir + "/";
1214
+ _ortTensor = ort.Tensor;
1215
+ const modelPath = join3(modelDir, "model_quantized.onnx");
1216
+ const vocabPath = join3(modelDir, "vocab.txt");
1217
+ _vocab = loadVocab(vocabPath);
1218
+ const session = await ort.InferenceSession.create(modelPath, {
1219
+ executionProviders: ["wasm"],
1220
+ graphOptimizationLevel: "all"
1221
+ });
1222
+ return session;
1223
+ } catch {
1224
+ return null;
1225
+ }
1226
+ })();
1227
+ return _sessionPromise;
1228
+ }
1229
+ function meanPool(hidden, mask, seqLen, hiddenSize) {
1230
+ const out = new Float32Array(hiddenSize);
1231
+ let maskSum = 0;
1232
+ for (let t = 0; t < seqLen; t++) {
1233
+ const m = mask[t];
1234
+ if (m === 0) continue;
1235
+ maskSum += m;
1236
+ const base = t * hiddenSize;
1237
+ for (let h = 0; h < hiddenSize; h++) out[h] += hidden[base + h] * m;
1238
+ }
1239
+ const denom = Math.max(maskSum, 1e-9);
1240
+ for (let h = 0; h < hiddenSize; h++) out[h] /= denom;
1241
+ return out;
1242
+ }
1243
+ function chunkForEmbedding(text) {
1244
+ const t = text.trim();
1245
+ if (!t) return [];
1246
+ if (t.length <= CHUNK_TARGET_CHARS) return [t];
1247
+ const chunks = [];
1248
+ let start = 0;
1249
+ while (start < t.length && chunks.length < MAX_CHUNKS_PER_RECORD) {
1250
+ let end = Math.min(start + CHUNK_TARGET_CHARS, t.length);
1251
+ if (end < t.length) {
1252
+ const floor = start + Math.floor(CHUNK_TARGET_CHARS / 2);
1253
+ const slice = t.slice(start, end);
1254
+ const para = slice.lastIndexOf("\n\n");
1255
+ const sent = Math.max(slice.lastIndexOf(". "), slice.lastIndexOf(".\n"));
1256
+ const space = slice.lastIndexOf(" ");
1257
+ for (const rel of [para, sent, space]) {
1258
+ const abs = start + rel;
1259
+ if (rel > 0 && abs > floor) {
1260
+ end = abs + 1;
1261
+ break;
1262
+ }
1263
+ }
1264
+ }
1265
+ const chunk = t.slice(start, end).trim();
1266
+ if (chunk) chunks.push(chunk);
1267
+ if (end >= t.length) break;
1268
+ start = Math.max(end - CHUNK_OVERLAP_CHARS, start + 1);
1269
+ }
1270
+ return chunks;
1271
+ }
1272
+ async function embedTier1(text) {
1273
+ try {
1274
+ const session = await getSession();
1275
+ if (!session || !_vocab || !_ortTensor) return null;
1276
+ const { input_ids, attention_mask, token_type_ids } = encode(text, _vocab);
1277
+ const seqLen = input_ids.length;
1278
+ const ids = BigInt64Array.from(input_ids.map((x) => BigInt(x)));
1279
+ const mask = BigInt64Array.from(attention_mask.map((x) => BigInt(x)));
1280
+ const types = BigInt64Array.from(token_type_ids.map((x) => BigInt(x)));
1281
+ const dims = [1, seqLen];
1282
+ const Tensor = _ortTensor;
1283
+ const feeds = {
1284
+ input_ids: new Tensor("int64", ids, dims),
1285
+ attention_mask: new Tensor("int64", mask, dims)
1286
+ };
1287
+ if (session.inputNames.includes("token_type_ids")) {
1288
+ feeds.token_type_ids = new Tensor("int64", types, dims);
1289
+ }
1290
+ const results = await session.run(feeds);
1291
+ const outName = session.outputNames.find((n) => results[n].dims.length === 3) ?? session.outputNames[0];
1292
+ const outTensor = results[outName];
1293
+ const hiddenSize = outTensor.dims[2];
1294
+ const pooled = meanPool(outTensor.data, attention_mask, seqLen, hiddenSize);
1295
+ const vec = l2normalize(pooled);
1296
+ if (vec.length !== EMBED_DIM) return null;
1297
+ _activeModel = { modelId: EMBED_MODEL_ID, dim: EMBED_DIM };
1298
+ return vec;
1299
+ } catch {
1300
+ return null;
1301
+ }
1302
+ }
1303
+ async function embedTier0(text, settings) {
1304
+ const endpoint = settings.endpoint;
1305
+ if (!endpoint) return null;
1306
+ const requestModel = settings.model || EMBED_MODEL_ID;
1307
+ const base = endpoint.replace(/\/+$/, "");
1308
+ const url = `${base}/v1/embeddings`;
1309
+ const controller = new AbortController();
1310
+ const timer = setTimeout(() => controller.abort(), TIER0_TIMEOUT_MS);
1311
+ try {
1312
+ const res = await fetch(url, {
1313
+ method: "POST",
1314
+ headers: { "content-type": "application/json" },
1315
+ body: JSON.stringify({ model: requestModel, input: text }),
1316
+ signal: controller.signal
1317
+ });
1318
+ if (!res.ok) return null;
1319
+ const body = await res.json();
1320
+ const raw = body?.data?.[0]?.embedding;
1321
+ if (!Array.isArray(raw) || raw.length === 0) return null;
1322
+ const vec = l2normalize(Float32Array.from(raw));
1323
+ _activeModel = { modelId: requestModel, dim: vec.length };
1324
+ return vec;
1325
+ } catch {
1326
+ return null;
1327
+ } finally {
1328
+ clearTimeout(timer);
1329
+ }
1330
+ }
1331
+ async function embedBatch(texts) {
1332
+ if (!texts || texts.length === 0) return [];
1333
+ if (embeddingsDisabled()) return texts.map(() => null);
1334
+ const settings = loadEmbedSettings();
1335
+ if (!settings.enabled) return texts.map(() => null);
1336
+ const results = [];
1337
+ for (const t of texts) {
1338
+ if (!t || !t.trim()) {
1339
+ results.push(null);
1340
+ continue;
1341
+ }
1342
+ try {
1343
+ let vec = null;
1344
+ if (settings.endpoint) {
1345
+ vec = await embedTier0(t, settings);
1346
+ }
1347
+ if (!vec) vec = await embedTier1(t);
1348
+ results.push(vec);
1349
+ } catch {
1350
+ results.push(null);
1351
+ }
1352
+ }
1353
+ return results;
1354
+ }
1355
+ var EMBED_MODEL_ID, EMBED_DIM, ORT_PKG, _activeModel, _sessionPromise, _vocab, _ortTensor, CHUNK_TARGET_CHARS, CHUNK_OVERLAP_CHARS, MAX_CHUNKS_PER_RECORD, TIER0_TIMEOUT_MS;
1356
+ var init_memory_embedder = __esm({
1357
+ "src/memory-embedder.ts"() {
1358
+ "use strict";
1359
+ init_memory_vector();
1360
+ init_memory_embedder_tokenizer();
1361
+ init_config();
1362
+ EMBED_MODEL_ID = "all-MiniLM-L6-v2";
1363
+ EMBED_DIM = 384;
1364
+ ORT_PKG = "onnxruntime-web";
1365
+ _activeModel = null;
1366
+ _sessionPromise = null;
1367
+ _vocab = null;
1368
+ _ortTensor = null;
1369
+ CHUNK_TARGET_CHARS = 900;
1370
+ CHUNK_OVERLAP_CHARS = 120;
1371
+ MAX_CHUNKS_PER_RECORD = 24;
1372
+ TIER0_TIMEOUT_MS = 2e3;
1373
+ }
1374
+ });
1375
+
1376
+ // src/memory-embed-sweep.ts
1377
+ function readCursor(db, metaTable, key) {
1378
+ if (!KNOWN_META_TABLES.has(metaTable)) return 0;
1379
+ try {
1380
+ const row = db.prepare(`SELECT value FROM ${metaTable} WHERE key = ?`).get(key);
1381
+ const n = row ? Number(row.value) : 0;
1382
+ return Number.isFinite(n) && n >= 0 ? n : 0;
1383
+ } catch {
1384
+ return 0;
1385
+ }
1386
+ }
1387
+ function writeCursor(db, metaTable, key, value) {
1388
+ if (!KNOWN_META_TABLES.has(metaTable)) return;
1389
+ try {
1390
+ db.prepare(`INSERT OR REPLACE INTO ${metaTable} (key, value) VALUES (?, ?)`).run(
1391
+ key,
1392
+ String(value)
1393
+ );
1394
+ } catch {
1395
+ }
1396
+ }
1397
+ async function runEmbedSweep(db, cfg, opts = {}) {
1398
+ const batchSize = Math.max(1, opts.batchSize ?? 16);
1399
+ const limit = opts.limit ?? Infinity;
1400
+ const budgetMs = opts.budgetMs;
1401
+ const start = Date.now();
1402
+ const cursorKey = `embed_sweep_cursor_${cfg.sourceLabel}`;
1403
+ let embedded = 0;
1404
+ let scanned = 0;
1405
+ let active = getActiveEmbedModel();
1406
+ let cursor = readCursor(db, cfg.metaTable, cursorKey);
1407
+ try {
1408
+ while (true) {
1409
+ if (embedded >= limit) break;
1410
+ if (budgetMs !== void 0 && Date.now() - start >= budgetMs) break;
1411
+ const remaining = limit === Infinity ? batchSize : Math.min(batchSize, limit - embedded);
1412
+ const rows = cfg.selectMissing(db, cursor, active, Math.max(1, remaining));
1413
+ if (rows.length === 0) {
1414
+ writeCursor(db, cfg.metaTable, cursorKey, 0);
1415
+ break;
1416
+ }
1417
+ const units = [];
1418
+ for (const r of rows) {
1419
+ if (cfg.chunked) {
1420
+ const parts = chunkForEmbedding(r.text);
1421
+ if (parts.length === 0) continue;
1422
+ parts.forEach((text, chunkIx) => units.push({ id: r.id, chunkIx, text }));
1423
+ } else {
1424
+ units.push({ id: r.id, chunkIx: 0, text: r.text });
1425
+ }
1426
+ }
1427
+ const vecs = await embedBatch(units.map((u) => u.text));
1428
+ if (!active) active = getActiveEmbedModel();
1429
+ if (!active) {
1430
+ break;
1431
+ }
1432
+ const tx = db.transaction(() => {
1433
+ const del = cfg.chunked ? db.prepare(
1434
+ `DELETE FROM ${cfg.embeddingTable}
1435
+ WHERE ${cfg.idCol} = ? AND model_id = ? AND dim = ?`
1436
+ ) : null;
1437
+ const stmt = cfg.chunked ? db.prepare(
1438
+ `INSERT OR REPLACE INTO ${cfg.embeddingTable}
1439
+ (${cfg.idCol}, chunk_ix, model_id, dim, vec, created_at)
1440
+ VALUES (?, ?, ?, ?, ?, datetime('now'))`
1441
+ ) : db.prepare(
1442
+ `INSERT OR REPLACE INTO ${cfg.embeddingTable}
1443
+ (${cfg.idCol}, model_id, dim, vec, created_at)
1444
+ VALUES (?, ?, ?, ?, datetime('now'))`
1445
+ );
1446
+ const cleared = /* @__PURE__ */ new Set();
1447
+ const embeddedIds = /* @__PURE__ */ new Set();
1448
+ for (let i = 0; i < units.length; i++) {
1449
+ const v = vecs[i];
1450
+ if (!v) continue;
1451
+ const u = units[i];
1452
+ if (del && !cleared.has(u.id)) {
1453
+ del.run(u.id, active.modelId, active.dim);
1454
+ cleared.add(u.id);
1455
+ }
1456
+ if (cfg.chunked) {
1457
+ stmt.run(u.id, u.chunkIx, active.modelId, active.dim, float32ToBlob(v));
1458
+ } else {
1459
+ stmt.run(u.id, active.modelId, active.dim, float32ToBlob(v));
1460
+ }
1461
+ embeddedIds.add(u.id);
1462
+ }
1463
+ embedded += embeddedIds.size;
1464
+ });
1465
+ tx();
1466
+ scanned += rows.length;
1467
+ cursor = rows[rows.length - 1].id;
1468
+ writeCursor(db, cfg.metaTable, cursorKey, cursor);
1469
+ }
1470
+ } catch {
1471
+ }
1472
+ return { embedded, scanned };
1473
+ }
1474
+ var KNOWN_META_TABLES;
1475
+ var init_memory_embed_sweep = __esm({
1476
+ "src/memory-embed-sweep.ts"() {
1477
+ "use strict";
1478
+ init_memory_embedder();
1479
+ init_memory_vector();
1480
+ KNOWN_META_TABLES = /* @__PURE__ */ new Set(["memory_meta", "knowledge_meta"]);
1481
+ }
1482
+ });
630
1483
 
631
1484
  // src/memory-db.ts
1485
+ var memory_db_exports = {};
1486
+ __export(memory_db_exports, {
1487
+ CONSOLIDATION_LESSON_EVIDENCE: () => CONSOLIDATION_LESSON_EVIDENCE,
1488
+ MEMORY_FILE_TITLE_LIKE: () => MEMORY_FILE_TITLE_LIKE,
1489
+ MEMORY_FILE_TITLE_PREFIX: () => MEMORY_FILE_TITLE_PREFIX,
1490
+ MEMORY_SCHEMA_VERSION: () => MEMORY_SCHEMA_VERSION,
1491
+ TOOL_COST_EVENTS_RETENTION_DAYS: () => TOOL_COST_EVENTS_RETENTION_DAYS,
1492
+ USAGE_COUNTER_ARMED_KEY: () => USAGE_COUNTER_ARMED_KEY,
1493
+ addConversationTurn: () => addConversationTurn,
1494
+ addFailureClass: () => addFailureClass,
1495
+ addObservation: () => addObservation,
1496
+ addSummary: () => addSummary,
1497
+ addToolCallDetail: () => addToolCallDetail,
1498
+ addUserPrompt: () => addUserPrompt,
1499
+ appendIncidentToFailureClass: () => appendIncidentToFailureClass,
1500
+ armUsageCounter: () => armUsageCounter,
1501
+ assignImportance: () => assignImportance,
1502
+ autoDetectTaskId: () => autoDetectTaskId,
1503
+ createSession: () => createSession,
1504
+ deduplicateFailedAttempt: () => deduplicateFailedAttempt,
1505
+ dequeuePendingSync: () => dequeuePendingSync,
1506
+ drainRulePromotionEvents: () => drainRulePromotionEvents,
1507
+ drainTeamPromotions: () => drainTeamPromotions,
1508
+ drainTeamRevocations: () => drainTeamRevocations,
1509
+ embedMissingObservations: () => embedMissingObservations,
1510
+ endSession: () => endSession,
1511
+ enqueueRulePromotionEvent: () => enqueueRulePromotionEvent,
1512
+ enqueueSyncPayload: () => enqueueSyncPayload,
1513
+ enqueueTeamPromotion: () => enqueueTeamPromotion,
1514
+ enqueueTeamRevocation: () => enqueueTeamRevocation,
1515
+ expireOldLowValueObservations: () => expireOldLowValueObservations,
1516
+ getConversationTurns: () => getConversationTurns,
1517
+ getCrossTaskProgress: () => getCrossTaskProgress,
1518
+ getDecisionsAbout: () => getDecisionsAbout,
1519
+ getFailedAttempts: () => getFailedAttempts,
1520
+ getFailureClasses: () => getFailureClasses,
1521
+ getLastProcessedLine: () => getLastProcessedLine,
1522
+ getMemoryDb: () => getMemoryDb,
1523
+ getMemoryMeta: () => getMemoryMeta,
1524
+ getObservabilityDbSize: () => getObservabilityDbSize,
1525
+ getRecentObservations: () => getRecentObservations,
1526
+ getRecurrenceCountForPromptHash: () => getRecurrenceCountForPromptHash,
1527
+ getSessionStats: () => getSessionStats,
1528
+ getSessionSummaries: () => getSessionSummaries,
1529
+ getSessionTimeline: () => getSessionTimeline,
1530
+ getSessionsByTask: () => getSessionsByTask,
1531
+ getToolPatterns: () => getToolPatterns,
1532
+ incrementRetryCount: () => incrementRetryCount,
1533
+ initMemorySchema: () => initMemorySchema,
1534
+ linkSessionToTask: () => linkSessionToTask,
1535
+ markRecordSuperseded: () => markRecordSuperseded,
1536
+ memoryTableHasTemporal: () => memoryTableHasTemporal,
1537
+ migrateAuditLogCheckExtension: () => migrateAuditLogCheckExtension,
1538
+ migrateMemoryFilesFor4B: () => migrateMemoryFilesFor4B,
1539
+ migrateObservationEmbeddingChunks: () => migrateObservationEmbeddingChunks,
1540
+ pruneOldConversationTurns: () => pruneOldConversationTurns,
1541
+ pruneOldObservations: () => pruneOldObservations,
1542
+ pruneToolCostEvents: () => pruneToolCostEvents,
1543
+ recordRecallHits: () => recordRecallHits,
1544
+ recordTelemetry: () => recordTelemetry,
1545
+ removePendingSync: () => removePendingSync,
1546
+ sanitizeFts5Query: () => sanitizeFts5Query,
1547
+ sanitizeFts5QueryOr: () => sanitizeFts5QueryOr,
1548
+ scoreFailureClasses: () => scoreFailureClasses,
1549
+ searchConversationTurns: () => searchConversationTurns,
1550
+ searchObservations: () => searchObservations,
1551
+ setLastProcessedLine: () => setLastProcessedLine,
1552
+ setMemoryMeta: () => setMemoryMeta,
1553
+ upsertObservationEmbedding: () => upsertObservationEmbedding,
1554
+ usageWarmupElapsed: () => usageWarmupElapsed
1555
+ });
1556
+ import Database2 from "better-sqlite3";
1557
+ import { dirname as dirname5, basename as basename2 } from "path";
1558
+ import { existsSync as existsSync6, mkdirSync as mkdirSync4 } from "fs";
1559
+ function sanitizeFts5Query(raw) {
1560
+ const trimmed = raw.trim();
1561
+ if (!trimmed) return '""';
1562
+ const tokens = trimmed.replace(/"/g, "").split(/\s+/).filter(Boolean);
1563
+ return tokens.map((t) => `"${t}"`).join(" ");
1564
+ }
1565
+ function sanitizeFts5QueryOr(raw) {
1566
+ const trimmed = raw.trim();
1567
+ if (!trimmed) return '""';
1568
+ const tokens = trimmed.replace(/"/g, "").split(/\s+/).filter((t) => t.replace(/[^a-zA-Z0-9]/g, "").length >= 3);
1569
+ if (tokens.length === 0) return '""';
1570
+ return tokens.map((t) => `"${t}"`).join(" OR ");
1571
+ }
632
1572
  function getMemoryDb() {
633
1573
  const dbPath = getResolvedPaths().memoryDbPath;
634
- const dir = dirname2(dbPath);
635
- if (!existsSync3(dir)) {
636
- mkdirSync2(dir, { recursive: true });
1574
+ const dir = dirname5(dbPath);
1575
+ if (!existsSync6(dir)) {
1576
+ mkdirSync4(dir, { recursive: true });
637
1577
  }
638
- const db = new Database(dbPath);
1578
+ const preExisting = existsSync6(dbPath);
1579
+ const db = new Database2(dbPath);
639
1580
  db.pragma("journal_mode = WAL");
640
1581
  db.pragma("foreign_keys = ON");
1582
+ const onDisk = db.pragma("user_version", { simple: true });
1583
+ if (preExisting && onDisk !== MEMORY_SCHEMA_VERSION) {
1584
+ backupBeforeSchemaChange(
1585
+ getProjectRoot(),
1586
+ dbPath,
1587
+ (err) => recordHookFailure("memory-db:pre-ddl-backup", err, { dbPath, onDisk })
1588
+ );
1589
+ }
641
1590
  initMemorySchema(db);
1591
+ if (onDisk !== MEMORY_SCHEMA_VERSION) {
1592
+ db.pragma(`user_version = ${MEMORY_SCHEMA_VERSION}`);
1593
+ }
642
1594
  return db;
643
1595
  }
1596
+ function pruneToolCostEvents(db) {
1597
+ const result = db.prepare(
1598
+ `DELETE FROM tool_cost_events WHERE created_at < datetime('now', '-' || ? || ' days')`
1599
+ ).run(TOOL_COST_EVENTS_RETENTION_DAYS);
1600
+ return result.changes;
1601
+ }
1602
+ function migrateObservationEmbeddingChunks(db) {
1603
+ const cols = db.pragma("table_info(observation_embeddings)");
1604
+ if (cols.length === 0) return;
1605
+ if (cols.some((c) => c.name === "chunk_ix")) return;
1606
+ db.pragma("foreign_keys = OFF");
1607
+ try {
1608
+ db.exec("BEGIN TRANSACTION");
1609
+ db.exec(`
1610
+ CREATE TABLE observation_embeddings_new (
1611
+ observation_id INTEGER NOT NULL REFERENCES observations(id) ON DELETE CASCADE,
1612
+ chunk_ix INTEGER NOT NULL DEFAULT 0,
1613
+ model_id TEXT NOT NULL,
1614
+ dim INTEGER NOT NULL,
1615
+ vec BLOB NOT NULL,
1616
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
1617
+ PRIMARY KEY (observation_id, model_id, dim, chunk_ix)
1618
+ );
1619
+ INSERT INTO observation_embeddings_new
1620
+ (observation_id, chunk_ix, model_id, dim, vec, created_at)
1621
+ SELECT observation_id, 0, model_id, dim, vec, created_at FROM observation_embeddings;
1622
+ DROP TABLE observation_embeddings;
1623
+ ALTER TABLE observation_embeddings_new RENAME TO observation_embeddings;
1624
+ CREATE INDEX IF NOT EXISTS idx_obs_emb_model ON observation_embeddings(model_id);
1625
+ `);
1626
+ db.exec("COMMIT");
1627
+ } catch (err) {
1628
+ db.exec("ROLLBACK");
1629
+ throw err;
1630
+ } finally {
1631
+ db.pragma("foreign_keys = ON");
1632
+ }
1633
+ }
1634
+ function migrateMemoryFilesFor4B(db) {
1635
+ const ADDITIONS = [
1636
+ // The renderer's authorship credential (OD-1). NULL on every pre-existing row,
1637
+ // which is the safe direction: no MAC ⇒ unverifiable ⇒ the file is HUMAN.
1638
+ { table: "memory_files", name: "massu_render_mac", decl: "TEXT" },
1639
+ // F-15 stickiness: once a file is human, only `massu memory adopt` reverses it.
1640
+ { table: "memory_files", name: "adopted_human_at_epoch", decl: "INTEGER" },
1641
+ // OD-2: a CACHE of `.massu-tombstones.jsonl`. The ledger is the source of truth.
1642
+ { table: "memory_files", name: "tombstoned_at_epoch", decl: "INTEGER" },
1643
+ { table: "memory_files", name: "origin", decl: "TEXT NOT NULL DEFAULT 'local'" },
1644
+ { table: "memory_files", name: "render_suppressed", decl: "INTEGER NOT NULL DEFAULT 0" },
1645
+ // N-03 — the SOURCE row. This is the one F-08 actually requires.
1646
+ { table: "observations", name: "origin", decl: "TEXT NOT NULL DEFAULT 'local'" }
1647
+ ];
1648
+ for (const add of ADDITIONS) {
1649
+ const cols = db.prepare(`PRAGMA table_info(${add.table})`).all();
1650
+ if (cols.length === 0) continue;
1651
+ if (cols.some((c) => c.name === add.name)) continue;
1652
+ db.exec(`ALTER TABLE ${add.table} ADD COLUMN ${add.name} ${add.decl}`);
1653
+ }
1654
+ }
644
1655
  function migrateAuditLogCheckExtension(db) {
645
1656
  const row = db.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name='audit_log'").get();
646
1657
  if (!row) return;
@@ -653,7 +1664,17 @@ function migrateAuditLogCheckExtension(db) {
653
1664
  "compaction",
654
1665
  "rule_candidate_emitted",
655
1666
  "rule_promoted",
656
- "rule_dismissed"
1667
+ "rule_dismissed",
1668
+ // A-19/N-02 — without these the memory-file events throw a CHECK violation.
1669
+ // In the ingest path the throw is swallowed by a bare catch, so observability
1670
+ // silently produces NOTHING; in the renderer's transaction it ROLLS BACK a
1671
+ // legitimate render. This migration is what lets an EXISTING db accept them.
1672
+ "memory_file_ingested",
1673
+ "memory_file_expired",
1674
+ "memory_file_adopted_human",
1675
+ "memory_file_rendered",
1676
+ "memory_file_render_refused",
1677
+ "memory_file_tombstoned"
657
1678
  ];
658
1679
  const checkClauseMatch = row.sql.match(/event_type\s+TEXT\s+NOT\s+NULL\s+CHECK\s*\(\s*event_type\s+IN\s*\(([\s\S]*?)\)\s*\)/i);
659
1680
  if (checkClauseMatch) {
@@ -670,7 +1691,9 @@ function migrateAuditLogCheckExtension(db) {
670
1691
  timestamp TEXT DEFAULT (datetime('now')),
671
1692
  event_type TEXT NOT NULL CHECK(event_type IN (
672
1693
  'code_change', 'rule_enforced', 'approval', 'review', 'commit', 'compaction',
673
- 'rule_candidate_emitted', 'rule_promoted', 'rule_dismissed'
1694
+ 'rule_candidate_emitted', 'rule_promoted', 'rule_dismissed',
1695
+ 'memory_file_ingested', 'memory_file_expired', 'memory_file_adopted_human',
1696
+ 'memory_file_rendered', 'memory_file_render_refused', 'memory_file_tombstoned'
674
1697
  )),
675
1698
  actor TEXT NOT NULL DEFAULT 'ai' CHECK(actor IN ('ai', 'human', 'hook', 'agent')),
676
1699
  model_id TEXT,
@@ -742,6 +1765,11 @@ function initMemorySchema(db) {
742
1765
  importance INTEGER NOT NULL DEFAULT 3 CHECK(importance BETWEEN 1 AND 5),
743
1766
  recurrence_count INTEGER NOT NULL DEFAULT 1,
744
1767
  original_tokens INTEGER DEFAULT 0,
1768
+ -- B-10/F-08/N-03: the SOURCE-row provenance flag. The renderer refuses any
1769
+ -- row whose origin is not 'local' BEFORE it computes a path, mints a
1770
+ -- credential, or takes a snapshot. A Slice-5 synced memory arrives here with
1771
+ -- origin='team' and must never reach disk without CR-55's gates.
1772
+ origin TEXT NOT NULL DEFAULT 'local',
745
1773
  created_at TEXT NOT NULL,
746
1774
  created_at_epoch INTEGER NOT NULL,
747
1775
  FOREIGN KEY(session_id) REFERENCES sessions(session_id) ON DELETE CASCADE
@@ -840,6 +1868,27 @@ function initMemorySchema(db) {
840
1868
  value TEXT NOT NULL
841
1869
  );
842
1870
  `);
1871
+ db.exec(`
1872
+ CREATE TABLE IF NOT EXISTS memory_usage (
1873
+ source TEXT NOT NULL,
1874
+ record_id INTEGER NOT NULL,
1875
+ hit_count INTEGER NOT NULL DEFAULT 0,
1876
+ hits_windowed REAL NOT NULL DEFAULT 0,
1877
+ last_hit_epoch INTEGER,
1878
+ last_reweight_epoch INTEGER,
1879
+ PRIMARY KEY (source, record_id)
1880
+ );
1881
+
1882
+ CREATE TABLE IF NOT EXISTS memory_usage_sessions (
1883
+ source TEXT NOT NULL,
1884
+ record_id INTEGER NOT NULL,
1885
+ session_id TEXT NOT NULL,
1886
+ PRIMARY KEY (source, record_id, session_id)
1887
+ );
1888
+
1889
+ CREATE INDEX IF NOT EXISTS idx_memory_usage_hits
1890
+ ON memory_usage(source, hits_windowed DESC);
1891
+ `);
843
1892
  db.exec(`
844
1893
  CREATE TABLE IF NOT EXISTS conversation_turns (
845
1894
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -992,7 +2041,9 @@ function initMemorySchema(db) {
992
2041
  timestamp TEXT DEFAULT (datetime('now')),
993
2042
  event_type TEXT NOT NULL CHECK(event_type IN (
994
2043
  'code_change', 'rule_enforced', 'approval', 'review', 'commit', 'compaction',
995
- 'rule_candidate_emitted', 'rule_promoted', 'rule_dismissed'
2044
+ 'rule_candidate_emitted', 'rule_promoted', 'rule_dismissed',
2045
+ 'memory_file_ingested', 'memory_file_expired', 'memory_file_adopted_human',
2046
+ 'memory_file_rendered', 'memory_file_render_refused', 'memory_file_tombstoned'
996
2047
  )),
997
2048
  actor TEXT NOT NULL DEFAULT 'ai' CHECK(actor IN ('ai', 'human', 'hook', 'agent')),
998
2049
  model_id TEXT,
@@ -1012,6 +2063,17 @@ function initMemorySchema(db) {
1012
2063
  ON audit_log (event_type, json_extract(metadata, '$.prompt_hash'))
1013
2064
  WHERE event_type = 'rule_promoted';
1014
2065
  `);
2066
+ db.exec(`
2067
+ CREATE TABLE IF NOT EXISTS hook_health (
2068
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2069
+ hook TEXT NOT NULL,
2070
+ error TEXT NOT NULL,
2071
+ context_json TEXT,
2072
+ occurred_at TEXT NOT NULL DEFAULT (datetime('now'))
2073
+ );
2074
+ CREATE INDEX IF NOT EXISTS idx_hook_health_hook ON hook_health(hook);
2075
+ CREATE INDEX IF NOT EXISTS idx_hook_health_time ON hook_health(occurred_at DESC);
2076
+ `);
1015
2077
  db.exec(`
1016
2078
  CREATE TABLE IF NOT EXISTS prompt_outcomes_signal_blacklist (
1017
2079
  signal TEXT PRIMARY KEY,
@@ -1023,6 +2085,30 @@ function initMemorySchema(db) {
1023
2085
  ON prompt_outcomes_signal_blacklist(dismissal_count DESC);
1024
2086
  `);
1025
2087
  migrateAuditLogCheckExtension(db);
2088
+ db.exec(`
2089
+ CREATE TABLE IF NOT EXISTS memory_files (
2090
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2091
+ rel_path TEXT NOT NULL UNIQUE COLLATE NOCASE,
2092
+ name TEXT,
2093
+ raw TEXT NOT NULL,
2094
+ frontmatter_json TEXT,
2095
+ body TEXT NOT NULL,
2096
+ content_hash TEXT NOT NULL,
2097
+ ingest_schema_version INTEGER NOT NULL DEFAULT 1,
2098
+ massu_authored INTEGER NOT NULL DEFAULT 0,
2099
+ massu_render_mac TEXT,
2100
+ adopted_human_at_epoch INTEGER,
2101
+ tombstoned_at_epoch INTEGER,
2102
+ origin TEXT NOT NULL DEFAULT 'local',
2103
+ render_suppressed INTEGER NOT NULL DEFAULT 0,
2104
+ observation_id INTEGER,
2105
+ synced_at_epoch INTEGER,
2106
+ expired_at_epoch INTEGER
2107
+ );
2108
+ CREATE INDEX IF NOT EXISTS idx_mf_hash ON memory_files(content_hash);
2109
+ CREATE INDEX IF NOT EXISTS idx_mf_expired ON memory_files(expired_at_epoch);
2110
+ CREATE INDEX IF NOT EXISTS idx_mf_obs ON memory_files(observation_id);
2111
+ `);
1026
2112
  db.exec(`
1027
2113
  CREATE TABLE IF NOT EXISTS validation_results (
1028
2114
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -1244,6 +2330,55 @@ function initMemorySchema(db) {
1244
2330
  if (!outboundCols.some((c) => c.name === "review_attestation_json")) {
1245
2331
  db.exec(`ALTER TABLE team_promotion_outbound ADD COLUMN review_attestation_json TEXT`);
1246
2332
  }
2333
+ const sessionCols = db.prepare(`PRAGMA table_info(sessions)`).all();
2334
+ if (!sessionCols.some((c) => c.name === "consolidated_at")) {
2335
+ db.exec(`ALTER TABLE sessions ADD COLUMN consolidated_at TEXT`);
2336
+ }
2337
+ if (!sessionCols.some((c) => c.name === "consolidated_at_epoch")) {
2338
+ db.exec(`ALTER TABLE sessions ADD COLUMN consolidated_at_epoch INTEGER`);
2339
+ }
2340
+ if (!sessionCols.some((c) => c.name === "consolidated_status")) {
2341
+ db.exec(`ALTER TABLE sessions ADD COLUMN consolidated_status TEXT`);
2342
+ }
2343
+ const BITEMPORAL_COLUMNS = [
2344
+ { name: "valid_from", type: "TEXT" },
2345
+ { name: "valid_to", type: "TEXT" },
2346
+ { name: "ingested_at", type: "TEXT" },
2347
+ { name: "expired_at", type: "TEXT" },
2348
+ { name: "valid_from_epoch", type: "INTEGER" },
2349
+ { name: "valid_to_epoch", type: "INTEGER" },
2350
+ { name: "ingested_at_epoch", type: "INTEGER" },
2351
+ { name: "expired_at_epoch", type: "INTEGER" },
2352
+ { name: "superseded_by", type: "INTEGER" }
2353
+ ];
2354
+ for (const table of ["observations", "architecture_decisions"]) {
2355
+ const cols = db.prepare(`PRAGMA table_info(${table})`).all();
2356
+ for (const col of BITEMPORAL_COLUMNS) {
2357
+ if (!cols.some((c) => c.name === col.name)) {
2358
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${col.name} ${col.type}`);
2359
+ }
2360
+ }
2361
+ }
2362
+ db.exec(`
2363
+ UPDATE observations
2364
+ SET valid_from = created_at,
2365
+ ingested_at = created_at,
2366
+ valid_from_epoch = created_at_epoch,
2367
+ ingested_at_epoch = created_at_epoch
2368
+ WHERE valid_from_epoch IS NULL;
2369
+ `);
2370
+ db.exec(`
2371
+ UPDATE architecture_decisions
2372
+ SET valid_from = created_at,
2373
+ ingested_at = created_at,
2374
+ valid_from_epoch = CAST(strftime('%s', created_at) AS INTEGER),
2375
+ ingested_at_epoch = CAST(strftime('%s', created_at) AS INTEGER)
2376
+ WHERE valid_from_epoch IS NULL AND created_at IS NOT NULL;
2377
+ `);
2378
+ db.exec(`
2379
+ CREATE INDEX IF NOT EXISTS idx_observations_expired ON observations(expired_at_epoch);
2380
+ CREATE INDEX IF NOT EXISTS idx_ad_expired ON architecture_decisions(expired_at_epoch);
2381
+ `);
1247
2382
  db.exec(`
1248
2383
  CREATE TABLE IF NOT EXISTS failure_classes (
1249
2384
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -1263,9 +2398,1021 @@ function initMemorySchema(db) {
1263
2398
  CREATE INDEX IF NOT EXISTS idx_fc_name ON failure_classes(name);
1264
2399
  CREATE INDEX IF NOT EXISTS idx_fc_needs_review ON failure_classes(needs_review);
1265
2400
  `);
2401
+ db.exec(`
2402
+ CREATE TABLE IF NOT EXISTS observation_embeddings (
2403
+ observation_id INTEGER NOT NULL REFERENCES observations(id) ON DELETE CASCADE,
2404
+ chunk_ix INTEGER NOT NULL DEFAULT 0,
2405
+ model_id TEXT NOT NULL,
2406
+ dim INTEGER NOT NULL,
2407
+ vec BLOB NOT NULL,
2408
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
2409
+ PRIMARY KEY (observation_id, model_id, dim, chunk_ix)
2410
+ );
2411
+ CREATE INDEX IF NOT EXISTS idx_obs_emb_model ON observation_embeddings(model_id);
2412
+ `);
2413
+ migrateObservationEmbeddingChunks(db);
2414
+ migrateMemoryFilesFor4B(db);
2415
+ }
2416
+ function enqueueSyncPayload(db, payload) {
2417
+ db.prepare("INSERT INTO pending_sync (payload) VALUES (?)").run(payload);
2418
+ }
2419
+ function getMemoryMeta(db, key) {
2420
+ const row = db.prepare("SELECT value FROM memory_meta WHERE key = ?").get(key);
2421
+ return row ? row.value : null;
2422
+ }
2423
+ function setMemoryMeta(db, key, value) {
2424
+ db.prepare("INSERT OR REPLACE INTO memory_meta (key, value) VALUES (?, ?)").run(key, value);
2425
+ }
2426
+ function upsertObservationEmbedding(db, observationId, vec, modelId, dim) {
2427
+ db.prepare(
2428
+ `INSERT OR REPLACE INTO observation_embeddings (observation_id, model_id, dim, vec, created_at)
2429
+ VALUES (?, ?, ?, ?, datetime('now'))`
2430
+ ).run(observationId, modelId, dim, float32ToBlob(vec));
2431
+ }
2432
+ function observationEmbedText(title, detail) {
2433
+ const t = (title ?? "").trim();
2434
+ const d = (detail ?? "").trim();
2435
+ return d ? `${t}. ${d}` : t;
2436
+ }
2437
+ async function embedMissingObservations(db, opts = {}) {
2438
+ return runEmbedSweep(
2439
+ db,
2440
+ {
2441
+ embeddingTable: "observation_embeddings",
2442
+ idCol: "observation_id",
2443
+ metaTable: "memory_meta",
2444
+ sourceLabel: "observation",
2445
+ // A-04: memory bodies are now stored WHOLE (up to ~14K chars). One vector per
2446
+ // memory would cover only its first ~1,000 chars.
2447
+ chunked: true,
2448
+ selectMissing: (d, cursor, model, batchSize) => {
2449
+ const rows = model ? d.prepare(
2450
+ `SELECT o.id AS id, o.title AS title, o.detail AS detail
2451
+ FROM observations o
2452
+ WHERE o.id > ?
2453
+ AND NOT EXISTS (
2454
+ SELECT 1 FROM observation_embeddings e
2455
+ WHERE e.observation_id = o.id AND e.model_id = ? AND e.dim = ?
2456
+ )
2457
+ ORDER BY o.id LIMIT ?`
2458
+ ).all(cursor, model.modelId, model.dim, batchSize) : d.prepare(
2459
+ `SELECT o.id AS id, o.title AS title, o.detail AS detail
2460
+ FROM observations o
2461
+ WHERE o.id > ?
2462
+ AND NOT EXISTS (
2463
+ SELECT 1 FROM observation_embeddings e WHERE e.observation_id = o.id
2464
+ )
2465
+ ORDER BY o.id LIMIT ?`
2466
+ ).all(cursor, batchSize);
2467
+ return rows.map((r) => ({ id: r.id, text: observationEmbedText(r.title, r.detail) }));
2468
+ }
2469
+ },
2470
+ opts
2471
+ );
2472
+ }
2473
+ function enqueueTeamPromotion(db, promo) {
2474
+ db.prepare(`
2475
+ INSERT OR REPLACE INTO team_promotion_outbound
2476
+ (prompt_hash, destination, draft_text, score, signals_json, content_hash, hardened, review_attestation_json, created_at)
2477
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
2478
+ `).run(
2479
+ promo.prompt_hash,
2480
+ promo.destination,
2481
+ promo.draft_text.slice(0, MAX_DRAFT_TEXT_LEN),
2482
+ promo.score ?? null,
2483
+ JSON.stringify(promo.signals ?? []),
2484
+ promo.content_hash,
2485
+ promo.hardened ? 1 : 0,
2486
+ promo.review_attestation !== void 0 ? JSON.stringify(promo.review_attestation) : null
2487
+ );
2488
+ }
2489
+ function drainTeamPromotions(db) {
2490
+ const rows = db.prepare(`
2491
+ SELECT prompt_hash, destination, draft_text, score, signals_json, content_hash, hardened, review_attestation_json
2492
+ FROM team_promotion_outbound ORDER BY created_at ASC LIMIT 1000
2493
+ `).all();
2494
+ if (rows.length === 0) return [];
2495
+ db.prepare("DELETE FROM team_promotion_outbound").run();
2496
+ return rows.map((r) => ({
2497
+ prompt_hash: r.prompt_hash,
2498
+ destination: r.destination,
2499
+ draft_text: r.draft_text,
2500
+ score: r.score ?? void 0,
2501
+ signals: safeJsonArray(r.signals_json),
2502
+ content_hash: r.content_hash,
2503
+ hardened: r.hardened === 1,
2504
+ review_attestation: r.review_attestation_json ? safeJsonParse(r.review_attestation_json) : void 0
2505
+ }));
2506
+ }
2507
+ function enqueueTeamRevocation(db, promptHash) {
2508
+ db.prepare(`
2509
+ INSERT OR REPLACE INTO team_revocation_outbound (prompt_hash, created_at)
2510
+ VALUES (?, datetime('now'))
2511
+ `).run(promptHash);
2512
+ }
2513
+ function drainTeamRevocations(db) {
2514
+ const rows = db.prepare(
2515
+ `SELECT prompt_hash FROM team_revocation_outbound ORDER BY created_at ASC LIMIT 1000`
2516
+ ).all();
2517
+ if (rows.length === 0) return [];
2518
+ db.prepare("DELETE FROM team_revocation_outbound").run();
2519
+ return rows.map((r) => r.prompt_hash);
2520
+ }
2521
+ function getRecurrenceCountForPromptHash(db, promptHash) {
2522
+ try {
2523
+ const row = db.prepare(`
2524
+ SELECT json_extract(metadata, '$.recurrence_count') AS rc
2525
+ FROM audit_log
2526
+ WHERE event_type = 'rule_promoted'
2527
+ AND json_extract(metadata, '$.prompt_hash') = ?
2528
+ LIMIT 1
2529
+ `).get(promptHash);
2530
+ if (!row || row.rc === null || row.rc === void 0) return null;
2531
+ return Number(row.rc);
2532
+ } catch {
2533
+ return null;
2534
+ }
2535
+ }
2536
+ function enqueueRulePromotionEvent(db, ev) {
2537
+ try {
2538
+ db.prepare(`
2539
+ INSERT INTO rule_promotion_events_outbound
2540
+ (prompt_hash, event_type, metadata_json, created_at)
2541
+ VALUES (?, ?, ?, ?)
2542
+ `).run(
2543
+ ev.prompt_hash,
2544
+ ev.event_type,
2545
+ JSON.stringify(ev.metadata ?? {}),
2546
+ ev.created_at
2547
+ );
2548
+ db.prepare(`
2549
+ DELETE FROM rule_promotion_events_outbound
2550
+ WHERE id NOT IN (
2551
+ SELECT id FROM rule_promotion_events_outbound ORDER BY id DESC LIMIT ?
2552
+ )
2553
+ `).run(FUNNEL_EVENT_OUTBOX_CAP);
2554
+ } catch {
2555
+ }
2556
+ }
2557
+ function drainRulePromotionEvents(db) {
2558
+ const rows = db.prepare(`
2559
+ SELECT id, prompt_hash, event_type, metadata_json, created_at
2560
+ FROM rule_promotion_events_outbound ORDER BY id ASC LIMIT ?
2561
+ `).all(FUNNEL_EVENT_DRAIN_LIMIT);
2562
+ if (rows.length === 0) return [];
2563
+ const maxId = rows[rows.length - 1].id;
2564
+ db.prepare("DELETE FROM rule_promotion_events_outbound WHERE id <= ?").run(maxId);
2565
+ return rows.map((r) => ({
2566
+ prompt_hash: r.prompt_hash,
2567
+ event_type: r.event_type,
2568
+ created_at: r.created_at,
2569
+ metadata: safeJsonParse(r.metadata_json) ?? {}
2570
+ }));
2571
+ }
2572
+ function recordTelemetry(db, eventType, data) {
2573
+ try {
2574
+ db.prepare(`
2575
+ INSERT INTO analytics_events (event_type, event_data, created_at)
2576
+ VALUES (?, ?, datetime('now'))
2577
+ `).run(eventType, JSON.stringify(data));
2578
+ } catch {
2579
+ }
2580
+ }
2581
+ function safeJsonArray(json) {
2582
+ try {
2583
+ const v = JSON.parse(json);
2584
+ return Array.isArray(v) ? v : [];
2585
+ } catch {
2586
+ return [];
2587
+ }
2588
+ }
2589
+ function safeJsonParse(json) {
2590
+ try {
2591
+ return JSON.parse(json);
2592
+ } catch {
2593
+ return void 0;
2594
+ }
2595
+ }
2596
+ function dequeuePendingSync(db, limit = 10) {
2597
+ const stale = db.prepare(
2598
+ "SELECT id, retry_count, last_error FROM pending_sync WHERE retry_count >= 10 LIMIT 10000"
2599
+ ).all();
2600
+ if (stale.length > 0) {
2601
+ const ids = stale.map((s) => s.id);
2602
+ db.prepare(`DELETE FROM pending_sync WHERE id IN (${ids.map(() => "?").join(",")})`).run(...ids);
2603
+ const lastErrors = [...new Set(stale.map((s) => s.last_error).filter(Boolean))];
2604
+ process.stderr.write(
2605
+ `[massu] WARNING: ${stale.length} cloud-sync queue item(s) discarded after 10+ retries. Likely cause: invalid API key or unreachable endpoint. Recent errors: ${lastErrors.slice(0, 3).join("; ") || "(none recorded)"}
2606
+ `
2607
+ );
2608
+ try {
2609
+ db.prepare(`
2610
+ INSERT INTO analytics_events (event_type, event_data, created_at)
2611
+ VALUES (?, ?, datetime('now'))
2612
+ `).run(
2613
+ "cloud_sync_giveup",
2614
+ JSON.stringify({
2615
+ discarded_count: stale.length,
2616
+ recent_errors: lastErrors.slice(0, 3)
2617
+ })
2618
+ );
2619
+ } catch {
2620
+ }
2621
+ }
2622
+ return db.prepare(
2623
+ "SELECT id, payload, retry_count FROM pending_sync ORDER BY created_at ASC LIMIT ?"
2624
+ ).all(limit);
2625
+ }
2626
+ function removePendingSync(db, id) {
2627
+ db.prepare("DELETE FROM pending_sync WHERE id = ?").run(id);
2628
+ }
2629
+ function incrementRetryCount(db, id, error) {
2630
+ db.prepare(
2631
+ "UPDATE pending_sync SET retry_count = retry_count + 1, last_error = ? WHERE id = ?"
2632
+ ).run(error, id);
2633
+ }
2634
+ function assignImportance(type, vrResult) {
2635
+ switch (type) {
2636
+ case "decision":
2637
+ case "failed_attempt":
2638
+ return 5;
2639
+ case "cr_violation":
2640
+ case "incident_near_miss":
2641
+ return 4;
2642
+ case "vr_check":
2643
+ return vrResult === "PASS" ? 2 : 4;
2644
+ case "pattern_compliance":
2645
+ return vrResult === "PASS" ? 2 : 4;
2646
+ case "feature":
2647
+ case "bugfix":
2648
+ return 3;
2649
+ case "refactor":
2650
+ return 2;
2651
+ case "file_change":
2652
+ case "discovery":
2653
+ return 1;
2654
+ default:
2655
+ return 3;
2656
+ }
2657
+ }
2658
+ function autoDetectTaskId(planFile) {
2659
+ if (!planFile) return null;
2660
+ const base = basename2(planFile);
2661
+ return base.replace(/\.md$/, "");
2662
+ }
2663
+ function createSession(db, sessionId, opts) {
2664
+ const now = /* @__PURE__ */ new Date();
2665
+ const taskId = autoDetectTaskId(opts?.planFile);
2666
+ db.prepare(`
2667
+ INSERT OR IGNORE INTO sessions (session_id, git_branch, plan_file, task_id, started_at, started_at_epoch)
2668
+ VALUES (?, ?, ?, ?, ?, ?)
2669
+ `).run(sessionId, opts?.branch ?? null, opts?.planFile ?? null, taskId, now.toISOString(), Math.floor(now.getTime() / 1e3));
2670
+ }
2671
+ function endSession(db, sessionId, status = "completed") {
2672
+ const now = /* @__PURE__ */ new Date();
2673
+ db.prepare(`
2674
+ UPDATE sessions SET status = ?, ended_at = ?, ended_at_epoch = ? WHERE session_id = ?
2675
+ `).run(status, now.toISOString(), Math.floor(now.getTime() / 1e3), sessionId);
2676
+ }
2677
+ function memoryTableHasTemporal(db, table) {
2678
+ let perDb = _temporalColCache.get(db);
2679
+ if (!perDb) {
2680
+ perDb = /* @__PURE__ */ new Map();
2681
+ _temporalColCache.set(db, perDb);
2682
+ }
2683
+ let has = perDb.get(table);
2684
+ if (has === void 0) {
2685
+ try {
2686
+ const cols = db.prepare(`PRAGMA table_info(${table})`).all();
2687
+ has = cols.some((c) => c.name === "valid_from_epoch");
2688
+ } catch {
2689
+ has = false;
2690
+ }
2691
+ perDb.set(table, has);
2692
+ }
2693
+ return has;
2694
+ }
2695
+ function addObservation(db, sessionId, type, title, detail, opts) {
2696
+ const now = /* @__PURE__ */ new Date();
2697
+ const importance = opts?.importance ?? assignImportance(type, opts?.evidence?.includes("PASS") ? "PASS" : void 0);
2698
+ const iso = now.toISOString();
2699
+ const epochSec = Math.floor(now.getTime() / 1e3);
2700
+ let result;
2701
+ if (memoryTableHasTemporal(db, "observations")) {
2702
+ result = db.prepare(`
2703
+ INSERT INTO observations (session_id, type, title, detail, files_involved, plan_item, cr_rule, vr_type, evidence, importance, original_tokens, created_at, created_at_epoch, valid_from, ingested_at, valid_from_epoch, ingested_at_epoch)
2704
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2705
+ `).run(
2706
+ sessionId,
2707
+ type,
2708
+ title,
2709
+ detail,
2710
+ JSON.stringify(opts?.filesInvolved ?? []),
2711
+ opts?.planItem ?? null,
2712
+ opts?.crRule ?? null,
2713
+ opts?.vrType ?? null,
2714
+ opts?.evidence ?? null,
2715
+ importance,
2716
+ opts?.originalTokens ?? 0,
2717
+ iso,
2718
+ epochSec,
2719
+ iso,
2720
+ iso,
2721
+ epochSec,
2722
+ epochSec
2723
+ );
2724
+ } else {
2725
+ result = db.prepare(`
2726
+ INSERT INTO observations (session_id, type, title, detail, files_involved, plan_item, cr_rule, vr_type, evidence, importance, original_tokens, created_at, created_at_epoch)
2727
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2728
+ `).run(
2729
+ sessionId,
2730
+ type,
2731
+ title,
2732
+ detail,
2733
+ JSON.stringify(opts?.filesInvolved ?? []),
2734
+ opts?.planItem ?? null,
2735
+ opts?.crRule ?? null,
2736
+ opts?.vrType ?? null,
2737
+ opts?.evidence ?? null,
2738
+ importance,
2739
+ opts?.originalTokens ?? 0,
2740
+ iso,
2741
+ epochSec
2742
+ );
2743
+ }
2744
+ return Number(result.lastInsertRowid);
2745
+ }
2746
+ function markRecordSuperseded(db, table, recordId, successorId, nowEpochSec = Math.floor(Date.now() / 1e3)) {
2747
+ const iso = new Date(nowEpochSec * 1e3).toISOString();
2748
+ const statusClause = table === "architecture_decisions" ? `, status = 'superseded'` : "";
2749
+ const res = db.prepare(
2750
+ `UPDATE ${table}
2751
+ SET valid_to = ?, expired_at = ?, valid_to_epoch = ?, expired_at_epoch = ?, superseded_by = ?${statusClause}
2752
+ WHERE id = ? AND expired_at IS NULL AND id != ?`
2753
+ ).run(iso, iso, nowEpochSec, nowEpochSec, successorId, recordId, successorId);
2754
+ return res.changes > 0;
2755
+ }
2756
+ function addSummary(db, sessionId, summary) {
2757
+ const now = /* @__PURE__ */ new Date();
2758
+ db.prepare(`
2759
+ INSERT INTO session_summaries (session_id, request, investigated, decisions, completed, failed_attempts, next_steps, files_created, files_modified, verification_results, plan_progress, created_at, created_at_epoch)
2760
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2761
+ `).run(
2762
+ sessionId,
2763
+ summary.request ?? null,
2764
+ summary.investigated ?? null,
2765
+ summary.decisions ?? null,
2766
+ summary.completed ?? null,
2767
+ summary.failedAttempts ?? null,
2768
+ summary.nextSteps ?? null,
2769
+ JSON.stringify(summary.filesCreated ?? []),
2770
+ JSON.stringify(summary.filesModified ?? []),
2771
+ JSON.stringify(summary.verificationResults ?? {}),
2772
+ JSON.stringify(summary.planProgress ?? {}),
2773
+ now.toISOString(),
2774
+ Math.floor(now.getTime() / 1e3)
2775
+ );
2776
+ }
2777
+ function addUserPrompt(db, sessionId, text, promptNumber) {
2778
+ const now = /* @__PURE__ */ new Date();
2779
+ db.prepare(`
2780
+ INSERT INTO user_prompts (session_id, prompt_text, prompt_number, created_at, created_at_epoch)
2781
+ VALUES (?, ?, ?, ?, ?)
2782
+ `).run(sessionId, text, promptNumber, now.toISOString(), Math.floor(now.getTime() / 1e3));
2783
+ }
2784
+ function searchObservations(db, query, opts) {
2785
+ const limit = opts?.limit ?? 20;
2786
+ let sql = `
2787
+ SELECT o.id, o.type, o.title, o.created_at, o.session_id, o.importance,
2788
+ rank
2789
+ FROM observations_fts
2790
+ JOIN observations o ON observations_fts.rowid = o.id
2791
+ WHERE observations_fts MATCH ?
2792
+ `;
2793
+ const params = [sanitizeFts5Query(query)];
2794
+ if (opts?.type) {
2795
+ sql += " AND o.type = ?";
2796
+ params.push(opts.type);
2797
+ }
2798
+ if (opts?.crRule) {
2799
+ sql += " AND o.cr_rule = ?";
2800
+ params.push(opts.crRule);
2801
+ }
2802
+ if (opts?.dateFrom) {
2803
+ sql += " AND o.created_at >= ?";
2804
+ params.push(opts.dateFrom);
2805
+ }
2806
+ sql += " ORDER BY rank LIMIT ?";
2807
+ params.push(limit);
2808
+ return db.prepare(sql).all(...params);
2809
+ }
2810
+ function getRecentObservations(db, limit = 20, sessionId) {
2811
+ if (sessionId) {
2812
+ return db.prepare(`
2813
+ SELECT id, type, title, detail, importance, created_at, session_id
2814
+ FROM observations WHERE session_id = ?
2815
+ ORDER BY created_at_epoch DESC LIMIT ?
2816
+ `).all(sessionId, limit);
2817
+ }
2818
+ return db.prepare(`
2819
+ SELECT id, type, title, detail, importance, created_at, session_id
2820
+ FROM observations
2821
+ ORDER BY created_at_epoch DESC LIMIT ?
2822
+ `).all(limit);
2823
+ }
2824
+ function getSessionSummaries(db, limit = 10) {
2825
+ return db.prepare(`
2826
+ SELECT session_id, request, completed, failed_attempts, plan_progress, created_at
2827
+ FROM session_summaries
2828
+ ORDER BY created_at_epoch DESC LIMIT ?
2829
+ `).all(limit);
2830
+ }
2831
+ function getSessionTimeline(db, sessionId) {
2832
+ const session = db.prepare("SELECT * FROM sessions WHERE session_id = ?").get(sessionId);
2833
+ const observations = db.prepare("SELECT * FROM observations WHERE session_id = ? ORDER BY created_at_epoch ASC").all(sessionId);
2834
+ const summary = db.prepare("SELECT * FROM session_summaries WHERE session_id = ? ORDER BY created_at_epoch DESC LIMIT 1").get(sessionId);
2835
+ const prompts = db.prepare("SELECT * FROM user_prompts WHERE session_id = ? ORDER BY prompt_number ASC").all(sessionId);
2836
+ return {
2837
+ session: session ?? null,
2838
+ observations,
2839
+ summary: summary ?? null,
2840
+ prompts
2841
+ };
2842
+ }
2843
+ function getFailedAttempts(db, query, limit = 20) {
2844
+ if (query) {
2845
+ return db.prepare(`
2846
+ SELECT o.id, o.title, o.detail, o.session_id, o.recurrence_count, o.created_at
2847
+ FROM observations_fts
2848
+ JOIN observations o ON observations_fts.rowid = o.id
2849
+ WHERE observations_fts MATCH ? AND o.type = 'failed_attempt'
2850
+ ORDER BY o.recurrence_count DESC, rank LIMIT ?
2851
+ `).all(sanitizeFts5Query(query), limit);
2852
+ }
2853
+ return db.prepare(`
2854
+ SELECT id, title, detail, session_id, recurrence_count, created_at
2855
+ FROM observations WHERE type = 'failed_attempt'
2856
+ ORDER BY recurrence_count DESC, created_at_epoch DESC LIMIT ?
2857
+ `).all(limit);
2858
+ }
2859
+ function getDecisionsAbout(db, query, limit = 20) {
2860
+ return db.prepare(`
2861
+ SELECT o.id, o.title, o.detail, o.session_id, o.created_at
2862
+ FROM observations_fts
2863
+ JOIN observations o ON observations_fts.rowid = o.id
2864
+ WHERE observations_fts MATCH ? AND o.type = 'decision'
2865
+ ORDER BY rank LIMIT ?
2866
+ `).all(sanitizeFts5Query(query), limit);
2867
+ }
2868
+ function armUsageCounter(db, nowEpochSec) {
2869
+ const existing = getMemoryMeta(db, USAGE_COUNTER_ARMED_KEY);
2870
+ if (existing) {
2871
+ const n = Number(existing);
2872
+ if (Number.isFinite(n) && n > 0) return n;
2873
+ }
2874
+ const now = nowEpochSec ?? Math.floor(Date.now() / 1e3);
2875
+ setMemoryMeta(db, USAGE_COUNTER_ARMED_KEY, String(now));
2876
+ return now;
2877
+ }
2878
+ function usageWarmupElapsed(db, warmupDays, nowEpochSec) {
2879
+ const armed = getMemoryMeta(db, USAGE_COUNTER_ARMED_KEY);
2880
+ if (!armed) return false;
2881
+ const armedEpoch = Number(armed);
2882
+ if (!Number.isFinite(armedEpoch) || armedEpoch <= 0) return false;
2883
+ const now = nowEpochSec ?? Math.floor(Date.now() / 1e3);
2884
+ return now - armedEpoch >= warmupDays * 86400;
2885
+ }
2886
+ function expireOldLowValueObservations(db, opts) {
2887
+ const now = opts.nowEpochSec ?? Math.floor(Date.now() / 1e3);
2888
+ if (!usageWarmupElapsed(db, opts.usageWarmupDays, now)) return 0;
2889
+ const cutoffEpoch = now - opts.retentionDays * 86400;
2890
+ const typePlaceholders = opts.protectedTypes.length ? opts.protectedTypes.map(() => "?").join(",") : "''";
2891
+ const iso = new Date(now * 1e3).toISOString();
2892
+ const result = db.prepare(
2893
+ `UPDATE observations
2894
+ SET expired_at = ?,
2895
+ expired_at_epoch = ?,
2896
+ valid_to = ?,
2897
+ valid_to_epoch = ?
2898
+ WHERE expired_at IS NULL
2899
+ AND created_at_epoch < ?
2900
+ AND importance <= ?
2901
+ AND type NOT IN (${typePlaceholders})
2902
+ AND COALESCE(evidence, '') != ?
2903
+ -- A file-backed row mirrors a file the human still keeps on disk.
2904
+ -- Value-decay may never retire it; only the file's removal can.
2905
+ AND title NOT LIKE ?
2906
+ AND NOT EXISTS (
2907
+ SELECT 1 FROM memory_usage u
2908
+ WHERE u.source = 'observation'
2909
+ AND u.record_id = observations.id
2910
+ AND u.hit_count > 0
2911
+ )
2912
+ AND NOT EXISTS (
2913
+ -- The grace period: a row demoted within the last cadence
2914
+ -- window is NOT yet expirable, so being pushed to the floor can
2915
+ -- never be immediately fatal.
2916
+ SELECT 1 FROM memory_usage u
2917
+ WHERE u.source = 'observation'
2918
+ AND u.record_id = observations.id
2919
+ AND u.last_reweight_epoch IS NOT NULL
2920
+ AND u.last_reweight_epoch > ?
2921
+ )`
2922
+ ).run(
2923
+ iso,
2924
+ now,
2925
+ iso,
2926
+ now,
2927
+ cutoffEpoch,
2928
+ opts.importanceFloor,
2929
+ ...opts.protectedTypes,
2930
+ CONSOLIDATION_LESSON_EVIDENCE,
2931
+ MEMORY_FILE_TITLE_LIKE,
2932
+ now - (opts.reweightIntervalDays ?? 1) * 86400
2933
+ );
2934
+ return result.changes;
2935
+ }
2936
+ function pruneOldObservations(db, opts) {
2937
+ return expireOldLowValueObservations(db, opts);
2938
+ }
2939
+ function recordRecallHits(db, sessionId, hits, nowEpochSec) {
2940
+ if (!hits.length) return 0;
2941
+ const now = nowEpochSec ?? Math.floor(Date.now() / 1e3);
2942
+ let recorded = 0;
2943
+ const claim = db.prepare(
2944
+ `INSERT OR IGNORE INTO memory_usage_sessions (source, record_id, session_id)
2945
+ VALUES (?, ?, ?)`
2946
+ );
2947
+ const bump = db.prepare(
2948
+ `INSERT INTO memory_usage (source, record_id, hit_count, hits_windowed, last_hit_epoch)
2949
+ VALUES (?, ?, 1, 1, ?)
2950
+ ON CONFLICT(source, record_id) DO UPDATE SET
2951
+ hit_count = hit_count + 1,
2952
+ hits_windowed = hits_windowed + 1,
2953
+ last_hit_epoch = excluded.last_hit_epoch`
2954
+ );
2955
+ const tx = db.transaction(() => {
2956
+ for (const h of hits) {
2957
+ if (claim.run(h.source, h.id, sessionId).changes === 0) continue;
2958
+ bump.run(h.source, h.id, now);
2959
+ recorded++;
2960
+ }
2961
+ });
2962
+ tx();
2963
+ return recorded;
2964
+ }
2965
+ function deduplicateFailedAttempt(db, sessionId, title, detail, opts) {
2966
+ const existing = db.prepare(`
2967
+ SELECT id, recurrence_count FROM observations
2968
+ WHERE type = 'failed_attempt' AND title = ?
2969
+ ORDER BY created_at_epoch DESC LIMIT 1
2970
+ `).get(title);
2971
+ if (existing) {
2972
+ db.prepare("UPDATE observations SET recurrence_count = recurrence_count + 1, detail = COALESCE(?, detail) WHERE id = ?").run(detail, existing.id);
2973
+ return existing.id;
2974
+ }
2975
+ return addObservation(db, sessionId, "failed_attempt", title, detail, {
2976
+ ...opts,
2977
+ importance: 5
2978
+ });
2979
+ }
2980
+ function getSessionsByTask(db, taskId) {
2981
+ return db.prepare(`
2982
+ SELECT session_id, status, started_at, ended_at, plan_phase
2983
+ FROM sessions WHERE task_id = ?
2984
+ ORDER BY started_at_epoch DESC
2985
+ LIMIT 10000
2986
+ `).all(taskId);
2987
+ }
2988
+ function getCrossTaskProgress(db, taskId) {
2989
+ const sessions = db.prepare(`
2990
+ SELECT session_id FROM sessions WHERE task_id = ? LIMIT 10000
2991
+ `).all(taskId);
2992
+ const merged = {};
2993
+ for (const session of sessions) {
2994
+ const summaries = db.prepare(`
2995
+ SELECT plan_progress FROM session_summaries WHERE session_id = ? LIMIT 10000
2996
+ `).all(session.session_id);
2997
+ for (const summary of summaries) {
2998
+ try {
2999
+ const progress = JSON.parse(summary.plan_progress);
3000
+ for (const [key, value] of Object.entries(progress)) {
3001
+ if (!merged[key] || value === "complete" || value === "in_progress" && merged[key] === "pending") {
3002
+ merged[key] = value;
3003
+ }
3004
+ }
3005
+ } catch (_e) {
3006
+ }
3007
+ }
3008
+ }
3009
+ return merged;
3010
+ }
3011
+ function linkSessionToTask(db, sessionId, taskId) {
3012
+ db.prepare("UPDATE sessions SET task_id = ? WHERE session_id = ?").run(taskId, sessionId);
3013
+ }
3014
+ function addConversationTurn(db, sessionId, turnNumber, userPrompt, assistantResponse, toolCallsJson, toolCallCount, promptTokens, responseTokens) {
3015
+ const result = db.prepare(`
3016
+ INSERT INTO conversation_turns (session_id, turn_number, user_prompt, assistant_response, tool_calls_json, tool_call_count, prompt_tokens, response_tokens)
3017
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
3018
+ `).run(
3019
+ sessionId,
3020
+ turnNumber,
3021
+ userPrompt,
3022
+ assistantResponse ? assistantResponse.slice(0, 1e4) : null,
3023
+ toolCallsJson,
3024
+ toolCallCount,
3025
+ promptTokens,
3026
+ responseTokens
3027
+ );
3028
+ return Number(result.lastInsertRowid);
3029
+ }
3030
+ function addToolCallDetail(db, sessionId, turnNumber, toolName, inputSummary, inputSize, outputSize, success, filesInvolved) {
3031
+ db.prepare(`
3032
+ INSERT INTO tool_call_details (session_id, turn_number, tool_name, tool_input_summary, tool_input_size, tool_output_size, tool_success, files_involved)
3033
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
3034
+ `).run(
3035
+ sessionId,
3036
+ turnNumber,
3037
+ toolName,
3038
+ inputSummary ? inputSummary.slice(0, 500) : null,
3039
+ inputSize,
3040
+ outputSize,
3041
+ success ? 1 : 0,
3042
+ filesInvolved ? JSON.stringify(filesInvolved) : null
3043
+ );
3044
+ }
3045
+ function getLastProcessedLine(db, sessionId) {
3046
+ const row = db.prepare("SELECT value FROM memory_meta WHERE key = ?").get(`last_processed_line:${sessionId}`);
3047
+ return row ? parseInt(row.value, 10) : 0;
3048
+ }
3049
+ function setLastProcessedLine(db, sessionId, lineNumber) {
3050
+ db.prepare("INSERT OR REPLACE INTO memory_meta (key, value) VALUES (?, ?)").run(`last_processed_line:${sessionId}`, String(lineNumber));
3051
+ }
3052
+ function pruneOldConversationTurns(db, retentionDays = 90) {
3053
+ const cutoffEpoch = Math.floor(Date.now() / 1e3) - retentionDays * 86400;
3054
+ const turnsResult = db.prepare("DELETE FROM conversation_turns WHERE created_at_epoch < ?").run(cutoffEpoch);
3055
+ const detailsResult = db.prepare("DELETE FROM tool_call_details WHERE created_at_epoch < ?").run(cutoffEpoch);
3056
+ return { turnsDeleted: turnsResult.changes, detailsDeleted: detailsResult.changes };
3057
+ }
3058
+ function getConversationTurns(db, sessionId, opts) {
3059
+ let sql = "SELECT id, turn_number, user_prompt, assistant_response, tool_calls_json, tool_call_count, prompt_tokens, response_tokens, created_at FROM conversation_turns WHERE session_id = ?";
3060
+ const params = [sessionId];
3061
+ if (opts?.turnFrom !== void 0) {
3062
+ sql += " AND turn_number >= ?";
3063
+ params.push(opts.turnFrom);
3064
+ }
3065
+ if (opts?.turnTo !== void 0) {
3066
+ sql += " AND turn_number <= ?";
3067
+ params.push(opts.turnTo);
3068
+ }
3069
+ sql += " ORDER BY turn_number ASC";
3070
+ return db.prepare(sql).all(...params);
3071
+ }
3072
+ function searchConversationTurns(db, query, opts) {
3073
+ const limit = opts?.limit ?? 20;
3074
+ let sql = `
3075
+ SELECT ct.id, ct.session_id, ct.turn_number, ct.user_prompt, ct.tool_call_count, ct.response_tokens, ct.created_at, rank
3076
+ FROM conversation_turns_fts
3077
+ JOIN conversation_turns ct ON conversation_turns_fts.rowid = ct.id
3078
+ WHERE conversation_turns_fts MATCH ?
3079
+ `;
3080
+ const params = [sanitizeFts5Query(query)];
3081
+ if (opts?.sessionId) {
3082
+ sql += " AND ct.session_id = ?";
3083
+ params.push(opts.sessionId);
3084
+ }
3085
+ if (opts?.dateFrom) {
3086
+ sql += " AND ct.created_at >= ?";
3087
+ params.push(opts.dateFrom);
3088
+ }
3089
+ if (opts?.dateTo) {
3090
+ sql += " AND ct.created_at <= ?";
3091
+ params.push(opts.dateTo);
3092
+ }
3093
+ if (opts?.minToolCalls !== void 0) {
3094
+ sql += " AND ct.tool_call_count >= ?";
3095
+ params.push(opts.minToolCalls);
3096
+ }
3097
+ sql += " ORDER BY rank LIMIT ?";
3098
+ params.push(limit);
3099
+ return db.prepare(sql).all(...params);
3100
+ }
3101
+ function getToolPatterns(db, opts) {
3102
+ const groupBy = opts?.groupBy ?? "tool";
3103
+ const params = [];
3104
+ let whereClause = "";
3105
+ const conditions = [];
3106
+ if (opts?.sessionId) {
3107
+ conditions.push("session_id = ?");
3108
+ params.push(opts.sessionId);
3109
+ }
3110
+ if (opts?.toolName) {
3111
+ conditions.push("tool_name = ?");
3112
+ params.push(opts.toolName);
3113
+ }
3114
+ if (opts?.dateFrom) {
3115
+ conditions.push("created_at >= ?");
3116
+ params.push(opts.dateFrom);
3117
+ }
3118
+ if (conditions.length > 0) {
3119
+ whereClause = "WHERE " + conditions.join(" AND ");
3120
+ }
3121
+ let sql;
3122
+ switch (groupBy) {
3123
+ case "session":
3124
+ sql = `SELECT session_id, COUNT(*) as call_count, COUNT(DISTINCT tool_name) as unique_tools,
3125
+ SUM(CASE WHEN tool_success = 1 THEN 1 ELSE 0 END) as successes,
3126
+ SUM(CASE WHEN tool_success = 0 THEN 1 ELSE 0 END) as failures,
3127
+ AVG(tool_output_size) as avg_output_size
3128
+ FROM tool_call_details ${whereClause}
3129
+ GROUP BY session_id ORDER BY call_count DESC`;
3130
+ break;
3131
+ case "day":
3132
+ sql = `SELECT date(created_at) as day, COUNT(*) as call_count, COUNT(DISTINCT tool_name) as unique_tools,
3133
+ SUM(CASE WHEN tool_success = 1 THEN 1 ELSE 0 END) as successes
3134
+ FROM tool_call_details ${whereClause}
3135
+ GROUP BY date(created_at) ORDER BY day DESC`;
3136
+ break;
3137
+ default:
3138
+ sql = `SELECT tool_name, COUNT(*) as call_count,
3139
+ SUM(CASE WHEN tool_success = 1 THEN 1 ELSE 0 END) as successes,
3140
+ SUM(CASE WHEN tool_success = 0 THEN 1 ELSE 0 END) as failures,
3141
+ AVG(tool_output_size) as avg_output_size,
3142
+ AVG(tool_input_size) as avg_input_size
3143
+ FROM tool_call_details ${whereClause}
3144
+ GROUP BY tool_name ORDER BY call_count DESC`;
3145
+ break;
3146
+ }
3147
+ return db.prepare(sql).all(...params);
3148
+ }
3149
+ function getSessionStats(db, opts) {
3150
+ if (opts?.sessionId) {
3151
+ const turns = db.prepare("SELECT COUNT(*) as turn_count, SUM(tool_call_count) as total_tool_calls, SUM(prompt_tokens) as total_prompt_tokens, SUM(response_tokens) as total_response_tokens FROM conversation_turns WHERE session_id = ?").get(opts.sessionId);
3152
+ const toolBreakdown = db.prepare("SELECT tool_name, COUNT(*) as count FROM tool_call_details WHERE session_id = ? GROUP BY tool_name ORDER BY count DESC").all(opts.sessionId);
3153
+ const session = db.prepare("SELECT * FROM sessions WHERE session_id = ?").get(opts.sessionId);
3154
+ return [{
3155
+ session_id: opts.sessionId,
3156
+ status: session?.status ?? "unknown",
3157
+ started_at: session?.started_at ?? null,
3158
+ ended_at: session?.ended_at ?? null,
3159
+ ...turns,
3160
+ tool_breakdown: toolBreakdown
3161
+ }];
3162
+ }
3163
+ const limit = opts?.limit ?? 10;
3164
+ return db.prepare(`
3165
+ SELECT s.session_id, s.status, s.started_at, s.ended_at,
3166
+ COUNT(ct.id) as turn_count,
3167
+ COALESCE(SUM(ct.tool_call_count), 0) as total_tool_calls,
3168
+ COALESCE(SUM(ct.prompt_tokens), 0) as total_prompt_tokens,
3169
+ COALESCE(SUM(ct.response_tokens), 0) as total_response_tokens
3170
+ FROM sessions s
3171
+ LEFT JOIN conversation_turns ct ON s.session_id = ct.session_id
3172
+ GROUP BY s.session_id
3173
+ ORDER BY s.started_at_epoch DESC
3174
+ LIMIT ?
3175
+ `).all(limit);
3176
+ }
3177
+ function getObservabilityDbSize(db) {
3178
+ const turnsCount = db.prepare("SELECT COUNT(*) as c FROM conversation_turns").get().c;
3179
+ const detailsCount = db.prepare("SELECT COUNT(*) as c FROM tool_call_details").get().c;
3180
+ const obsCount = db.prepare("SELECT COUNT(*) as c FROM observations").get().c;
3181
+ const pageCount = db.pragma("page_count")[0]?.page_count ?? 0;
3182
+ const pageSize = db.pragma("page_size")[0]?.page_size ?? 4096;
3183
+ return {
3184
+ conversation_turns_count: turnsCount,
3185
+ tool_call_details_count: detailsCount,
3186
+ observations_count: obsCount,
3187
+ db_page_count: pageCount,
3188
+ db_page_size: pageSize,
3189
+ estimated_size_mb: Math.round(pageCount * pageSize / (1024 * 1024) * 100) / 100
3190
+ };
3191
+ }
3192
+ function addFailureClass(db, opts) {
3193
+ const result = db.prepare(`
3194
+ INSERT OR IGNORE INTO failure_classes (name, description, diff_patterns, file_patterns, prompt_keywords, incidents, rules, scanner_checks, known_message, needs_review)
3195
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
3196
+ `).run(
3197
+ opts.name,
3198
+ opts.description,
3199
+ JSON.stringify(opts.diffPatterns ?? []),
3200
+ JSON.stringify(opts.filePatterns ?? []),
3201
+ JSON.stringify(opts.promptKeywords ?? []),
3202
+ JSON.stringify(opts.incidents ?? []),
3203
+ JSON.stringify(opts.rules ?? []),
3204
+ JSON.stringify(opts.scannerChecks ?? []),
3205
+ opts.knownMessage ?? "",
3206
+ opts.needsReview ? 1 : 0
3207
+ );
3208
+ return Number(result.lastInsertRowid);
3209
+ }
3210
+ function getFailureClasses(db) {
3211
+ const rows = db.prepare("SELECT * FROM failure_classes ORDER BY name LIMIT 10000").all();
3212
+ return rows.map((row) => ({
3213
+ id: row.id,
3214
+ name: row.name,
3215
+ description: row.description,
3216
+ diff_patterns: JSON.parse(row.diff_patterns || "[]"),
3217
+ file_patterns: JSON.parse(row.file_patterns || "[]"),
3218
+ prompt_keywords: JSON.parse(row.prompt_keywords || "[]"),
3219
+ incidents: JSON.parse(row.incidents || "[]"),
3220
+ rules: JSON.parse(row.rules || "[]"),
3221
+ scanner_checks: JSON.parse(row.scanner_checks || "[]"),
3222
+ known_message: row.known_message,
3223
+ needs_review: !!row.needs_review
3224
+ }));
3225
+ }
3226
+ function appendIncidentToFailureClass(db, className, incidentId) {
3227
+ const row = db.prepare("SELECT incidents FROM failure_classes WHERE name = ?").get(className);
3228
+ if (!row) return;
3229
+ const incidents = JSON.parse(row.incidents || "[]");
3230
+ if (!incidents.includes(incidentId)) {
3231
+ incidents.push(incidentId);
3232
+ db.prepare("UPDATE failure_classes SET incidents = ?, updated_at = datetime('now') WHERE name = ?").run(JSON.stringify(incidents), className);
3233
+ }
1266
3234
  }
3235
+ function scoreFailureClasses(db, matchText, filePath, promptContext, weights) {
3236
+ const classes = getFailureClasses(db);
3237
+ if (classes.length === 0) return null;
3238
+ const diffWeight = weights?.diffPatternWeight ?? 3;
3239
+ const fileWeight = weights?.filePatternWeight ?? 2;
3240
+ const promptWeight = weights?.promptKeywordWeight ?? 2;
3241
+ let bestMatch = null;
3242
+ for (const fc of classes) {
3243
+ let score = 0;
3244
+ for (const pattern of fc.diff_patterns) {
3245
+ if (!pattern) continue;
3246
+ try {
3247
+ if (new RegExp(pattern, "i").test(matchText)) {
3248
+ score += diffWeight;
3249
+ }
3250
+ } catch {
3251
+ if (matchText.toLowerCase().includes(pattern.toLowerCase())) {
3252
+ score += diffWeight;
3253
+ }
3254
+ }
3255
+ }
3256
+ for (const pattern of fc.file_patterns) {
3257
+ if (!pattern) continue;
3258
+ try {
3259
+ if (new RegExp(pattern).test(filePath)) {
3260
+ score += fileWeight;
3261
+ }
3262
+ } catch {
3263
+ if (filePath.includes(pattern)) {
3264
+ score += fileWeight;
3265
+ }
3266
+ }
3267
+ }
3268
+ if (promptContext) {
3269
+ for (const keyword of fc.prompt_keywords) {
3270
+ if (!keyword) continue;
3271
+ try {
3272
+ if (new RegExp(keyword, "i").test(promptContext)) {
3273
+ score += promptWeight;
3274
+ }
3275
+ } catch {
3276
+ if (promptContext.toLowerCase().includes(keyword.toLowerCase())) {
3277
+ score += promptWeight;
3278
+ }
3279
+ }
3280
+ }
3281
+ }
3282
+ if (!bestMatch || score > bestMatch.score) {
3283
+ bestMatch = {
3284
+ name: fc.name,
3285
+ score,
3286
+ incidentCount: fc.incidents.length,
3287
+ rules: fc.rules,
3288
+ knownMessage: fc.known_message
3289
+ };
3290
+ }
3291
+ }
3292
+ return bestMatch;
3293
+ }
3294
+ var MEMORY_SCHEMA_VERSION, TOOL_COST_EVENTS_RETENTION_DAYS, MAX_DRAFT_TEXT_LEN, FUNNEL_EVENT_DRAIN_LIMIT, FUNNEL_EVENT_OUTBOX_CAP, _temporalColCache, CONSOLIDATION_LESSON_EVIDENCE, MEMORY_FILE_TITLE_PREFIX, MEMORY_FILE_TITLE_LIKE, USAGE_COUNTER_ARMED_KEY;
3295
+ var init_memory_db = __esm({
3296
+ "src/memory-db.ts"() {
3297
+ "use strict";
3298
+ init_config();
3299
+ init_memory_vector();
3300
+ init_db_backup();
3301
+ init_hook_failure_signal();
3302
+ init_memory_embed_sweep();
3303
+ MEMORY_SCHEMA_VERSION = 1;
3304
+ TOOL_COST_EVENTS_RETENTION_DAYS = 90;
3305
+ MAX_DRAFT_TEXT_LEN = 16384;
3306
+ FUNNEL_EVENT_DRAIN_LIMIT = 5e3;
3307
+ FUNNEL_EVENT_OUTBOX_CAP = 2e4;
3308
+ _temporalColCache = /* @__PURE__ */ new WeakMap();
3309
+ CONSOLIDATION_LESSON_EVIDENCE = "consolidation:session-summary";
3310
+ MEMORY_FILE_TITLE_PREFIX = "[memory-file] ";
3311
+ MEMORY_FILE_TITLE_LIKE = `${MEMORY_FILE_TITLE_PREFIX}%`;
3312
+ USAGE_COUNTER_ARMED_KEY = "usage_counter_armed_epoch";
3313
+ }
3314
+ });
1267
3315
 
1268
3316
  // src/hooks/quality-event.ts
3317
+ init_memory_db();
3318
+
3319
+ // src/hooks/lib/tool-response.ts
3320
+ function asString(v) {
3321
+ return typeof v === "string" ? v : "";
3322
+ }
3323
+ function fromContentBlocks(arr) {
3324
+ const parts = [];
3325
+ for (const block of arr) {
3326
+ if (typeof block === "string") {
3327
+ parts.push(block);
3328
+ } else if (block && typeof block === "object") {
3329
+ const t = asString(block.text);
3330
+ if (t) parts.push(t);
3331
+ }
3332
+ }
3333
+ return parts.length > 0 ? parts.join("\n") : null;
3334
+ }
3335
+ function textFromObject(o) {
3336
+ if ("stdout" in o || "stderr" in o) {
3337
+ const out = asString(o.stdout);
3338
+ const err = asString(o.stderr);
3339
+ return err ? out ? `${out}
3340
+ ${err}` : err : out;
3341
+ }
3342
+ const file = o.file;
3343
+ if (file && typeof file === "object") {
3344
+ const c = asString(file.content);
3345
+ if (c) return c;
3346
+ }
3347
+ const content = o.content;
3348
+ if (typeof content === "string" && content) return content;
3349
+ if (Array.isArray(content)) {
3350
+ const blocks = fromContentBlocks(content);
3351
+ if (blocks) return blocks;
3352
+ }
3353
+ if ("structuredPatch" in o || "oldString" in o || "newString" in o) {
3354
+ const path = asString(o.filePath);
3355
+ const newStr = asString(o.newString);
3356
+ return [path, newStr].filter(Boolean).join("\n");
3357
+ }
3358
+ for (const k of ["text", "message", "output", "result", "stdout"]) {
3359
+ const v = asString(o[k]);
3360
+ if (v) return v;
3361
+ }
3362
+ try {
3363
+ return JSON.stringify(o);
3364
+ } catch {
3365
+ return "";
3366
+ }
3367
+ }
3368
+ function detectError(raw, text) {
3369
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {
3370
+ const o = raw;
3371
+ if (o.is_error === true || o.isError === true) return true;
3372
+ if (o.interrupted === true) return true;
3373
+ }
3374
+ return /^Error: (Exit code \d+|.*failed)/i.test(text.trimStart());
3375
+ }
3376
+ function normalizeToolResponse(raw) {
3377
+ if (raw === null || raw === void 0 || raw === "") {
3378
+ return { text: "", isError: false, shape: "empty" };
3379
+ }
3380
+ let text;
3381
+ let shape;
3382
+ if (typeof raw === "string") {
3383
+ text = raw;
3384
+ shape = "string";
3385
+ } else if (Array.isArray(raw)) {
3386
+ shape = "array";
3387
+ const blocks = fromContentBlocks(raw);
3388
+ if (blocks !== null) {
3389
+ text = blocks;
3390
+ } else {
3391
+ try {
3392
+ text = JSON.stringify(raw);
3393
+ } catch {
3394
+ text = "";
3395
+ }
3396
+ }
3397
+ } else if (typeof raw === "object") {
3398
+ shape = "object";
3399
+ try {
3400
+ text = textFromObject(raw);
3401
+ } catch {
3402
+ text = "";
3403
+ }
3404
+ } else {
3405
+ shape = "string";
3406
+ text = String(raw);
3407
+ }
3408
+ return { text, isError: detectError(raw, text), shape };
3409
+ }
3410
+ function toolResponseText(raw) {
3411
+ return normalizeToolResponse(raw).text;
3412
+ }
3413
+
3414
+ // src/hooks/quality-event.ts
3415
+ init_hook_failure_signal();
1269
3416
  var TEST_FAILURE_PATTERNS = [
1270
3417
  /\bFAIL\b/,
1271
3418
  /✗/,
@@ -1321,7 +3468,7 @@ async function main() {
1321
3468
  const input = await readStdin();
1322
3469
  const hookInput = JSON.parse(input);
1323
3470
  const { session_id, tool_name, tool_response } = hookInput;
1324
- const signals = detectQualitySignals(tool_response);
3471
+ const signals = detectQualitySignals(toolResponseText(tool_response));
1325
3472
  if (signals.length === 0) {
1326
3473
  process.exit(0);
1327
3474
  return;
@@ -1338,19 +3485,20 @@ async function main() {
1338
3485
  } finally {
1339
3486
  db.close();
1340
3487
  }
1341
- } catch (_e) {
3488
+ } catch (err) {
3489
+ recordHookFailure("quality-event", err);
1342
3490
  }
1343
3491
  process.exit(0);
1344
3492
  }
1345
3493
  function readStdin() {
1346
- return new Promise((resolve4) => {
3494
+ return new Promise((resolve5) => {
1347
3495
  let data = "";
1348
3496
  process.stdin.setEncoding("utf-8");
1349
3497
  process.stdin.on("data", (chunk) => {
1350
3498
  data += chunk;
1351
3499
  });
1352
- process.stdin.on("end", () => resolve4(data));
1353
- setTimeout(() => resolve4(data), 3e3);
3500
+ process.stdin.on("end", () => resolve5(data));
3501
+ setTimeout(() => resolve5(data), 3e3);
1354
3502
  });
1355
3503
  }
1356
3504
  main();