featlock 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs ADDED
@@ -0,0 +1,2787 @@
1
+ // @bun
2
+ // src/cli.ts
3
+ import fs8 from "fs";
4
+ import path10 from "path";
5
+
6
+ // packages/core/src/db/registry.ts
7
+ import { Database as Database2 } from "bun:sqlite";
8
+ import { execFileSync } from "child_process";
9
+ import fs from "fs";
10
+ import path from "path";
11
+
12
+ // packages/core/src/db/query.ts
13
+ function tokenize(text) {
14
+ return text.toLowerCase().replace(/[^a-z0-9]+/g, " ").split(" ").filter((tok) => tok.length >= 3);
15
+ }
16
+ function countRegistry(snapshot) {
17
+ return {
18
+ features: snapshot.features.length,
19
+ tests: snapshot.tests.length,
20
+ invariants: snapshot.invariants.length,
21
+ auditEntries: snapshot.auditLog.length
22
+ };
23
+ }
24
+ function queryRegistryFeatures(snapshot, term) {
25
+ const tokens = tokenize(term);
26
+ if (tokens.length === 0)
27
+ return [...snapshot.features];
28
+ return snapshot.features.filter((f) => {
29
+ const hay = `${f.id} ${f.area} ${f.name} ${f.summary} ${f.acceptanceCriteria}`.toLowerCase();
30
+ return tokens.every((tok) => hay.includes(tok));
31
+ });
32
+ }
33
+ function findDuplicateFeatures(snapshot, description) {
34
+ const queryTokens = new Set(tokenize(description));
35
+ if (queryTokens.size === 0)
36
+ return [];
37
+ const results = [];
38
+ for (const f of snapshot.features) {
39
+ if (f.status === "removed")
40
+ continue;
41
+ const featTokens = new Set(tokenize(`${f.id} ${f.area} ${f.name} ${f.summary}`));
42
+ const matched = [];
43
+ for (const tok of queryTokens) {
44
+ if (featTokens.has(tok))
45
+ matched.push(tok);
46
+ }
47
+ const denom = Math.min(queryTokens.size, Math.max(1, featTokens.size));
48
+ const score = Number((matched.length / denom).toFixed(3));
49
+ if (matched.length >= 2 || score >= 0.4) {
50
+ results.push({ featureId: f.id, name: f.name, score, matchedTokens: matched });
51
+ }
52
+ }
53
+ return results.toSorted((a, b) => {
54
+ const diff = b.score - a.score;
55
+ return diff !== 0 ? diff : a.featureId.localeCompare(b.featureId);
56
+ });
57
+ }
58
+
59
+ // packages/core/src/db/schema.ts
60
+ import { Database } from "bun:sqlite";
61
+ var REGISTRY_SQL_REL = "features/registry.sql";
62
+ var REGISTRY_DB_REL = ".featlock/registry.sqlite";
63
+ var SCHEMA_SQL = `
64
+ CREATE TABLE IF NOT EXISTS features (
65
+ id TEXT PRIMARY KEY,
66
+ area TEXT NOT NULL,
67
+ name TEXT NOT NULL,
68
+ summary TEXT NOT NULL,
69
+ acceptance_criteria TEXT NOT NULL,
70
+ status TEXT NOT NULL DEFAULT 'active' CHECK(status IN ('active','deprecated','removed')),
71
+ source TEXT NOT NULL DEFAULT 'manual',
72
+ adr_ref TEXT,
73
+ removal_reason TEXT
74
+ );
75
+
76
+ CREATE TABLE IF NOT EXISTS feature_tests (
77
+ feature_id TEXT NOT NULL REFERENCES features(id),
78
+ test_path TEXT NOT NULL,
79
+ test_pattern TEXT NOT NULL,
80
+ rung TEXT NOT NULL DEFAULT 'R2',
81
+ PRIMARY KEY (feature_id, test_path, test_pattern)
82
+ );
83
+
84
+ CREATE TABLE IF NOT EXISTS invariants (
85
+ id TEXT PRIMARY KEY,
86
+ feature_id TEXT NOT NULL REFERENCES features(id),
87
+ kind TEXT NOT NULL,
88
+ statement TEXT NOT NULL,
89
+ file TEXT NOT NULL,
90
+ line INTEGER NOT NULL,
91
+ confidence REAL NOT NULL DEFAULT 1.0,
92
+ source TEXT NOT NULL,
93
+ guard_ref TEXT,
94
+ guard_anchor TEXT,
95
+ root_test_path TEXT,
96
+ status TEXT NOT NULL DEFAULT 'active' CHECK(status IN ('active','deprecated','removed'))
97
+ );
98
+
99
+ CREATE TABLE IF NOT EXISTS feature_audit_log (
100
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
101
+ feature_id TEXT NOT NULL,
102
+ action TEXT NOT NULL CHECK(action IN ('added','improved','invariant_added','deprecated','removed')),
103
+ actor TEXT NOT NULL,
104
+ summary TEXT NOT NULL,
105
+ commit_sha TEXT
106
+ );
107
+
108
+ CREATE TRIGGER IF NOT EXISTS guard_prevent_feature_delete
109
+ BEFORE DELETE ON features
110
+ WHEN OLD.status = 'active'
111
+ BEGIN
112
+ SELECT RAISE(ABORT, 'FEATLOCK_TRIGGER_BLOCK: Cannot DELETE active feature directly; mark status=removed with adr_ref and removal_reason.');
113
+ END;
114
+
115
+ CREATE TRIGGER IF NOT EXISTS guard_prevent_feature_test_delete
116
+ BEFORE DELETE ON feature_tests
117
+ WHEN EXISTS (SELECT 1 FROM features WHERE id = OLD.feature_id AND status = 'active')
118
+ BEGIN
119
+ SELECT RAISE(ABORT, 'FEATLOCK_TRIGGER_BLOCK: Cannot unlink test from an active feature without replacing coverage.');
120
+ END;
121
+
122
+ CREATE TRIGGER IF NOT EXISTS guard_prevent_invariant_delete
123
+ BEFORE DELETE ON invariants
124
+ WHEN OLD.status = 'active'
125
+ BEGIN
126
+ SELECT RAISE(ABORT, 'FEATLOCK_TRIGGER_BLOCK: Cannot DELETE active invariant directly; mark status=removed with explicit ADR justification.');
127
+ END;
128
+ `.trim();
129
+ function sqlQuote(value) {
130
+ if (value === undefined || value === null)
131
+ return "NULL";
132
+ return `'${value.replaceAll("'", "''")}'`;
133
+ }
134
+ function serializeRegistrySql(snapshot) {
135
+ if (!snapshot)
136
+ throw new Error("RegistrySnapshot is required.");
137
+ const lines = [SCHEMA_SQL, ""];
138
+ const sortedFeatures = snapshot.features.toSorted((a, b) => a.id.localeCompare(b.id));
139
+ for (const f of sortedFeatures) {
140
+ lines.push(`INSERT OR REPLACE INTO features (id, area, name, summary, acceptance_criteria, status, source, adr_ref, removal_reason) VALUES (${sqlQuote(f.id)}, ${sqlQuote(f.area)}, ${sqlQuote(f.name)}, ${sqlQuote(f.summary)}, ${sqlQuote(f.acceptanceCriteria)}, ${sqlQuote(f.status)}, ${sqlQuote(f.source)}, ${sqlQuote(f.adrRef)}, ${sqlQuote(f.removalReason)});`);
141
+ }
142
+ const sortedTests = snapshot.tests.toSorted((a, b) => `${a.featureId}:${a.testPath}:${a.testPattern}`.localeCompare(`${b.featureId}:${b.testPath}:${b.testPattern}`));
143
+ for (const t of sortedTests) {
144
+ lines.push(`INSERT OR REPLACE INTO feature_tests (feature_id, test_path, test_pattern, rung) VALUES (${sqlQuote(t.featureId)}, ${sqlQuote(t.testPath)}, ${sqlQuote(t.testPattern)}, ${sqlQuote(t.rung)});`);
145
+ }
146
+ const sortedInvariants = snapshot.invariants.toSorted((a, b) => a.id.localeCompare(b.id));
147
+ for (const inv of sortedInvariants) {
148
+ lines.push(`INSERT OR REPLACE INTO invariants (id, feature_id, kind, statement, file, line, confidence, source, guard_ref, guard_anchor, root_test_path, status) VALUES (${sqlQuote(inv.id)}, ${sqlQuote(inv.featureId)}, ${sqlQuote(inv.kind)}, ${sqlQuote(inv.statement)}, ${sqlQuote(inv.file)}, ${Math.max(1, Math.floor(inv.line))}, ${Number(inv.confidence.toFixed(3))}, ${sqlQuote(inv.source)}, ${sqlQuote(inv.guardRef)}, ${sqlQuote(inv.guardAnchor)}, ${sqlQuote(inv.rootTestPath)}, ${sqlQuote(inv.status)});`);
149
+ }
150
+ for (const log of snapshot.auditLog) {
151
+ lines.push(`INSERT INTO feature_audit_log (feature_id, action, actor, summary, commit_sha) VALUES (${sqlQuote(log.featureId)}, ${sqlQuote(log.action)}, ${sqlQuote(log.actor)}, ${sqlQuote(log.summary)}, ${sqlQuote(log.commitSha)});`);
152
+ }
153
+ return `${lines.join(`
154
+ `)}
155
+ `;
156
+ }
157
+ function ensureInvariantColumns(db) {
158
+ const cols = new Set(db.query("PRAGMA table_info(invariants)").all().map((c) => c.name));
159
+ if (!cols.has("guard_anchor"))
160
+ db.exec("ALTER TABLE invariants ADD COLUMN guard_anchor TEXT;");
161
+ if (!cols.has("root_test_path"))
162
+ db.exec("ALTER TABLE invariants ADD COLUMN root_test_path TEXT;");
163
+ }
164
+ function readSnapshotFromDb(db) {
165
+ if (!db)
166
+ throw new Error("SQLite Database instance is required.");
167
+ ensureInvariantColumns(db);
168
+ const fRows = db.query("SELECT id, area, name, summary, acceptance_criteria, status, source, adr_ref, removal_reason FROM features ORDER BY id").all();
169
+ const tRows = db.query("SELECT feature_id, test_path, test_pattern, rung FROM feature_tests ORDER BY feature_id, test_path, test_pattern").all();
170
+ const iRows = db.query("SELECT id, feature_id, kind, statement, file, line, confidence, source, guard_ref, guard_anchor, root_test_path, status FROM invariants ORDER BY id").all();
171
+ const aRows = db.query("SELECT feature_id, action, actor, summary, commit_sha FROM feature_audit_log ORDER BY seq").all();
172
+ return {
173
+ features: fRows.map((r) => ({
174
+ id: String(r.id ?? ""),
175
+ area: String(r.area ?? ""),
176
+ name: String(r.name ?? ""),
177
+ summary: String(r.summary ?? ""),
178
+ acceptanceCriteria: String(r.acceptance_criteria ?? ""),
179
+ status: r.status === "deprecated" || r.status === "removed" ? r.status : "active",
180
+ source: String(r.source ?? "manual"),
181
+ adrRef: typeof r.adr_ref === "string" ? r.adr_ref : undefined,
182
+ removalReason: typeof r.removal_reason === "string" ? r.removal_reason : undefined
183
+ })),
184
+ tests: tRows.map((r) => ({
185
+ featureId: String(r.feature_id ?? ""),
186
+ testPath: String(r.test_path ?? ""),
187
+ testPattern: String(r.test_pattern ?? ""),
188
+ rung: String(r.rung ?? "R2")
189
+ })),
190
+ invariants: iRows.map((r) => ({
191
+ id: String(r.id ?? ""),
192
+ featureId: String(r.feature_id ?? ""),
193
+ kind: String(r.kind ?? ""),
194
+ statement: String(r.statement ?? ""),
195
+ file: String(r.file ?? ""),
196
+ line: Number(r.line ?? 1),
197
+ confidence: Number(r.confidence ?? 1),
198
+ source: String(r.source ?? "ast"),
199
+ guardRef: typeof r.guard_ref === "string" ? r.guard_ref : undefined,
200
+ guardAnchor: typeof r.guard_anchor === "string" ? r.guard_anchor : undefined,
201
+ rootTestPath: typeof r.root_test_path === "string" ? r.root_test_path : undefined,
202
+ status: r.status === "deprecated" || r.status === "removed" ? r.status : "active"
203
+ })),
204
+ auditLog: aRows.map((r) => ({
205
+ featureId: String(r.feature_id ?? ""),
206
+ action: r.action === "improved" || r.action === "invariant_added" || r.action === "deprecated" || r.action === "removed" ? r.action : "added",
207
+ actor: String(r.actor ?? "agent"),
208
+ summary: String(r.summary ?? ""),
209
+ commitSha: typeof r.commit_sha === "string" ? r.commit_sha : undefined
210
+ }))
211
+ };
212
+ }
213
+ function loadSnapshotFromSql(sqlText) {
214
+ const db = new Database(":memory:");
215
+ try {
216
+ db.exec(SCHEMA_SQL);
217
+ if (sqlText.trim().length > 0)
218
+ db.exec(sqlText);
219
+ return readSnapshotFromDb(db);
220
+ } finally {
221
+ db.close();
222
+ }
223
+ }
224
+
225
+ // packages/core/src/db/registry.ts
226
+ function materializeRegistryDb(repoRoot) {
227
+ if (!repoRoot)
228
+ throw new Error("repoRoot is required to materialize registry database.");
229
+ const sqlPath = path.join(repoRoot, REGISTRY_SQL_REL);
230
+ const dbPath = path.join(repoRoot, REGISTRY_DB_REL);
231
+ fs.mkdirSync(path.dirname(dbPath), { recursive: true });
232
+ if (fs.existsSync(dbPath))
233
+ fs.rmSync(dbPath, { force: true });
234
+ const db = new Database2(dbPath);
235
+ try {
236
+ db.exec(SCHEMA_SQL);
237
+ if (fs.existsSync(sqlPath)) {
238
+ const sqlText = fs.readFileSync(sqlPath, "utf8");
239
+ if (sqlText.trim().length > 0)
240
+ db.exec(sqlText);
241
+ }
242
+ const snapshot = readSnapshotFromDb(db);
243
+ return { sqlPath, dbPath, snapshot, counts: countRegistry(snapshot) };
244
+ } finally {
245
+ db.close();
246
+ }
247
+ }
248
+ function writeRegistrySql(repoRoot, snapshot) {
249
+ if (!repoRoot)
250
+ throw new Error("repoRoot is required to write registry SQL.");
251
+ const sqlPath = path.join(repoRoot, REGISTRY_SQL_REL);
252
+ fs.mkdirSync(path.dirname(sqlPath), { recursive: true });
253
+ fs.writeFileSync(sqlPath, serializeRegistrySql(snapshot), "utf8");
254
+ return sqlPath;
255
+ }
256
+ function readRepoRegistry(repoRoot) {
257
+ const sqlPath = path.join(repoRoot, REGISTRY_SQL_REL);
258
+ if (!fs.existsSync(sqlPath)) {
259
+ return { features: [], tests: [], invariants: [], auditLog: [] };
260
+ }
261
+ return loadSnapshotFromSql(fs.readFileSync(sqlPath, "utf8"));
262
+ }
263
+ function readHeadRegistry(repoRoot) {
264
+ try {
265
+ const out = execFileSync("git", ["-C", repoRoot, "show", `HEAD:${REGISTRY_SQL_REL}`], {
266
+ encoding: "utf8",
267
+ stdio: ["ignore", "pipe", "ignore"]
268
+ });
269
+ return loadSnapshotFromSql(out);
270
+ } catch {
271
+ return null;
272
+ }
273
+ }
274
+ function recordNewFeature(input) {
275
+ if (!input.feature.id)
276
+ throw new Error("Feature id is required.");
277
+ const current = readRepoRegistry(input.repoRoot);
278
+ const next = {
279
+ features: [...current.features.filter((f) => f.id !== input.feature.id), input.feature],
280
+ tests: [...current.tests, ...input.tests],
281
+ invariants: [...current.invariants, ...input.invariants ?? []],
282
+ auditLog: [
283
+ ...current.auditLog,
284
+ { featureId: input.feature.id, action: "added", actor: input.actor ?? "agent", summary: input.feature.summary }
285
+ ]
286
+ };
287
+ writeRegistrySql(input.repoRoot, next);
288
+ materializeRegistryDb(input.repoRoot);
289
+ return next;
290
+ }
291
+ function recordFeatureImprovement(input) {
292
+ const current = readRepoRegistry(input.repoRoot);
293
+ const target = current.features.find((f) => f.id === input.featureId);
294
+ if (!target) {
295
+ throw new Error(`Feature '${input.featureId}' does not exist in ${REGISTRY_SQL_REL}. Use record-new instead.`);
296
+ }
297
+ const updated = { ...target, summary: `${target.summary} | ${input.summary}` };
298
+ const next = {
299
+ features: current.features.map((f) => f.id === input.featureId ? updated : f),
300
+ tests: [...current.tests, ...input.extraTests ?? []],
301
+ invariants: [...current.invariants, ...input.extraInvariants ?? []],
302
+ auditLog: [
303
+ ...current.auditLog,
304
+ { featureId: input.featureId, action: "improved", actor: input.actor ?? "agent", summary: input.summary }
305
+ ]
306
+ };
307
+ writeRegistrySql(input.repoRoot, next);
308
+ materializeRegistryDb(input.repoRoot);
309
+ return next;
310
+ }
311
+ var Registry = {
312
+ sqlRel: REGISTRY_SQL_REL,
313
+ dbRel: REGISTRY_DB_REL,
314
+ serializeSql: serializeRegistrySql,
315
+ loadFromSql: loadSnapshotFromSql,
316
+ readFromDb: readSnapshotFromDb,
317
+ materializeDb: materializeRegistryDb,
318
+ writeSql: writeRegistrySql,
319
+ readRepo: readRepoRegistry,
320
+ readHead: readHeadRegistry,
321
+ count: countRegistry,
322
+ queryFeatures: queryRegistryFeatures,
323
+ findDuplicates: findDuplicateFeatures,
324
+ recordNew: recordNewFeature,
325
+ recordImprovement: recordFeatureImprovement
326
+ };
327
+ // packages/core/src/discover.ts
328
+ import { execFileSync as execFileSync2 } from "child_process";
329
+ import fs2 from "fs";
330
+ import path2 from "path";
331
+ var SKIP_DIRS = new Set([
332
+ ".git",
333
+ "node_modules",
334
+ "dist",
335
+ "out",
336
+ ".featlock",
337
+ ".next",
338
+ ".turbo",
339
+ "coverage",
340
+ "target",
341
+ "__pycache__",
342
+ ".venv",
343
+ "vendor",
344
+ "bin",
345
+ "obj"
346
+ ]);
347
+ var SOURCE_EXTS = new Set([".ts", ".tsx", ".mts", ".js", ".mjs", ".py", ".rs", ".cs", ".go", ".sql"]);
348
+ var NON_LIVE_TEST_RE = /(?:^|\/)(?:examples|fixtures|templates|caught|testdata|snapshots)\//i;
349
+ function isTestPath(rel) {
350
+ if (NON_LIVE_TEST_RE.test(rel))
351
+ return false;
352
+ return /(?:^|\/)(?:tests?|__tests__|spec|caddytest|testmocks)\//i.test(rel) || /\.(?:test|spec)\.[cm]?[jt]sx?$/i.test(rel) || /(?:^|\/)test_[^/]+\.py$/i.test(rel) || /_test\.(?:py|rs|go)$/i.test(rel) || /Tests?\.cs$/i.test(rel);
353
+ }
354
+ function discoverRepo(repoDir) {
355
+ const repoRoot = path2.resolve(repoDir);
356
+ if (!fs2.existsSync(repoRoot)) {
357
+ throw new Error(`Repository directory does not exist: ${repoRoot}`);
358
+ }
359
+ const allRelPaths = [];
360
+ const files = [];
361
+ const textCache = new Map;
362
+ const stack = [repoRoot];
363
+ while (stack.length > 0) {
364
+ const current = stack.pop();
365
+ if (!current)
366
+ continue;
367
+ for (const entry of fs2.readdirSync(current, { withFileTypes: true })) {
368
+ if (SKIP_DIRS.has(entry.name))
369
+ continue;
370
+ const abs = path2.join(current, entry.name);
371
+ if (entry.isDirectory()) {
372
+ stack.push(abs);
373
+ } else if (entry.isFile()) {
374
+ const rel = path2.relative(repoRoot, abs).split(path2.sep).join("/");
375
+ allRelPaths.push(rel);
376
+ const ext = path2.extname(entry.name).toLowerCase();
377
+ if (!SOURCE_EXTS.has(ext))
378
+ continue;
379
+ const stat = fs2.statSync(abs);
380
+ if (stat.size > 512000)
381
+ continue;
382
+ const content = fs2.readFileSync(abs, "utf8");
383
+ textCache.set(rel, content);
384
+ files.push({
385
+ rel,
386
+ abs,
387
+ ext,
388
+ isTest: isTestPath(rel),
389
+ content,
390
+ lines: content.length === 0 ? 0 : content.split(`
391
+ `).length
392
+ });
393
+ }
394
+ }
395
+ }
396
+ allRelPaths.sort();
397
+ files.sort((a, b) => a.rel.localeCompare(b.rel));
398
+ const readText = (relPath) => {
399
+ const hit = textCache.get(relPath) ?? undefined;
400
+ if (textCache.has(relPath))
401
+ return hit ?? null;
402
+ const abs = path2.join(repoRoot, relPath);
403
+ if (!fs2.existsSync(abs) || !fs2.statSync(abs).isFile()) {
404
+ textCache.set(relPath, null);
405
+ return null;
406
+ }
407
+ const content = fs2.readFileSync(abs, "utf8");
408
+ textCache.set(relPath, content);
409
+ return content;
410
+ };
411
+ return { repoRoot, files, allRelPaths, readText };
412
+ }
413
+ function listStagedFiles(repoRoot) {
414
+ try {
415
+ const out = execFileSync2("git", ["-C", repoRoot, "diff", "--cached", "--name-only"], {
416
+ encoding: "utf8",
417
+ stdio: ["ignore", "pipe", "ignore"]
418
+ });
419
+ return out.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
420
+ } catch {
421
+ return [];
422
+ }
423
+ }
424
+ // packages/core/src/plugin/host.ts
425
+ import fs7 from "fs";
426
+ import path9 from "path";
427
+ import { pathToFileURL } from "url";
428
+
429
+ // packages/plugin/src/index.ts
430
+ function definePlugin(def) {
431
+ if (!def.id || def.id.trim().length === 0) {
432
+ throw new Error("Plugin id must be a non-empty string.");
433
+ }
434
+ return {
435
+ _tag: "FeatlockPlugin",
436
+ id: def.id.trim(),
437
+ guarded: def.guarded === true,
438
+ setup: def.setup
439
+ };
440
+ }
441
+ function isFeatlockPlugin(value) {
442
+ if (typeof value !== "object" || value === null)
443
+ return false;
444
+ const rec = value;
445
+ return typeof rec.id === "string" && rec.id.length > 0 && typeof rec.setup === "function";
446
+ }
447
+ var Plugin = {
448
+ define: definePlugin
449
+ };
450
+
451
+ // packages/core/src/state.ts
452
+ var activeGroup;
453
+ var activeBatch;
454
+ function withGroup(report, fn) {
455
+ const prev = activeGroup;
456
+ const grp = { failed: false, registrations: new Set, report };
457
+ activeGroup = grp;
458
+ try {
459
+ return { group: grp, result: fn() };
460
+ } finally {
461
+ activeGroup = prev;
462
+ }
463
+ }
464
+ async function withGroupAsync(report, fn) {
465
+ const prev = activeGroup;
466
+ const grp = { failed: false, registrations: new Set, report };
467
+ activeGroup = grp;
468
+ try {
469
+ const result = await fn();
470
+ return { group: grp, result };
471
+ } finally {
472
+ activeGroup = prev;
473
+ }
474
+ }
475
+ function detachGroup(grp, failure) {
476
+ if (grp.failed)
477
+ return;
478
+ grp.failed = true;
479
+ const toNotify = new Set;
480
+ for (const reg of grp.registrations) {
481
+ reg.remove();
482
+ toNotify.add(reg.notify);
483
+ }
484
+ grp.registrations.clear();
485
+ grp.report(failure);
486
+ for (const notify of toNotify)
487
+ notify();
488
+ }
489
+ function batch(fn) {
490
+ if (activeBatch?.active)
491
+ return fn();
492
+ const prev = activeBatch;
493
+ const current = { active: true, pending: new Set };
494
+ activeBatch = current;
495
+ try {
496
+ const out = fn();
497
+ current.active = false;
498
+ for (const notify of current.pending)
499
+ notify();
500
+ return out;
501
+ } finally {
502
+ current.active = false;
503
+ activeBatch = prev;
504
+ }
505
+ }
506
+ function createState(options) {
507
+ if (!options)
508
+ throw new Error("StateOptions are required.");
509
+ let cached = options.initial();
510
+ let dirty = false;
511
+ let rev = 0;
512
+ const transforms = new Set;
513
+ const invalidate = () => {
514
+ dirty = true;
515
+ rev += 1;
516
+ };
517
+ const get = () => {
518
+ if (!dirty)
519
+ return cached;
520
+ for (let attempt = 0;attempt < 32; attempt += 1) {
521
+ const startRev = rev;
522
+ const next = options.initial();
523
+ const editor = options.editor(next);
524
+ for (const entry of Array.from(transforms)) {
525
+ try {
526
+ entry.run(editor);
527
+ } catch (cause) {
528
+ if (!entry.group)
529
+ throw cause;
530
+ detachGroup(entry.group, { state: options.name ?? "anonymous", cause });
531
+ }
532
+ if (rev !== startRev)
533
+ break;
534
+ }
535
+ if (rev !== startRev)
536
+ continue;
537
+ cached = next;
538
+ dirty = false;
539
+ return cached;
540
+ }
541
+ dirty = false;
542
+ return cached;
543
+ };
544
+ const notifyNow = () => {
545
+ const value = get();
546
+ if (options.notify)
547
+ options.notify(value);
548
+ };
549
+ const markChanged = () => {
550
+ invalidate();
551
+ if (activeBatch?.active) {
552
+ activeBatch.pending.add(notifyNow);
553
+ return;
554
+ }
555
+ notifyNow();
556
+ };
557
+ const transform = (cb) => {
558
+ const grp = activeGroup;
559
+ if (grp?.failed)
560
+ return { dispose: () => {
561
+ return;
562
+ } };
563
+ const entry = { run: cb, group: grp };
564
+ transforms.add(entry);
565
+ const remove = () => {
566
+ if (transforms.delete(entry))
567
+ invalidate();
568
+ };
569
+ const grouped = { remove, notify: notifyNow };
570
+ if (grp)
571
+ grp.registrations.add(grouped);
572
+ markChanged();
573
+ return {
574
+ dispose: () => {
575
+ if (grp)
576
+ grp.registrations.delete(grouped);
577
+ if (transforms.delete(entry))
578
+ markChanged();
579
+ }
580
+ };
581
+ };
582
+ return { get, transform, reload: markChanged, invalidate, revision: () => rev };
583
+ }
584
+ function createKeyedDomainState(name) {
585
+ return createState({
586
+ name,
587
+ initial: () => [],
588
+ editor: (draft) => ({
589
+ list: () => [...draft],
590
+ get: (id) => draft.find((item) => item.id === id),
591
+ add: (item) => {
592
+ const idx = draft.findIndex((existing) => existing.id === item.id);
593
+ if (idx >= 0)
594
+ draft[idx] = item;
595
+ else
596
+ draft.push(item);
597
+ },
598
+ update: (id, fn) => {
599
+ const target = draft.find((item) => item.id === id);
600
+ if (target)
601
+ fn(target);
602
+ },
603
+ remove: (id) => {
604
+ const idx = draft.findIndex((item) => item.id === id);
605
+ if (idx >= 0)
606
+ draft.splice(idx, 1);
607
+ }
608
+ })
609
+ });
610
+ }
611
+ var State = {
612
+ create: createState,
613
+ createKeyedDomain: createKeyedDomainState,
614
+ batch,
615
+ group: withGroup,
616
+ groupAsync: withGroupAsync,
617
+ detachGroup
618
+ };
619
+
620
+ // packages/plugins/anti-deletion-guard/src/index.ts
621
+ import fs3 from "fs";
622
+ import path3 from "path";
623
+ var SKIPPED_TEST_RE = /^\s*(?:test|it|describe)\.(?:skip|todo)\s*\(/m;
624
+ function normalizeWhitespace(raw) {
625
+ return raw.replace(/\s+/g, " ").trim();
626
+ }
627
+ function checkActiveFeatureCoverage(ctx) {
628
+ if (!ctx.repoRoot)
629
+ throw new Error("CheckContext.repoRoot is required.");
630
+ const violations = [];
631
+ const activeFeatures = ctx.registry.features.filter((f) => f.status === "active");
632
+ for (const feat of activeFeatures) {
633
+ const linked = ctx.registry.tests.filter((t) => t.featureId === feat.id);
634
+ if (linked.length === 0) {
635
+ violations.push({
636
+ id: `FLK:no-test:${feat.id}`,
637
+ rule: "active-feature-requires-test",
638
+ severity: "error",
639
+ featureId: feat.id,
640
+ file: "features/registry.sql",
641
+ message: `Active feature '${feat.id}' (${feat.name}) has zero linked tests in feature_tests.`,
642
+ fix: `Link at least one real test file to '${feat.id}' via 'featlock record-improvement'.`
643
+ });
644
+ continue;
645
+ }
646
+ for (const link of linked) {
647
+ const abs = path3.join(ctx.repoRoot, link.testPath);
648
+ if (!fs3.existsSync(abs)) {
649
+ violations.push({
650
+ id: `FLK:missing-test:${feat.id}:${link.testPath}`,
651
+ rule: "linked-test-must-exist",
652
+ severity: "error",
653
+ featureId: feat.id,
654
+ file: link.testPath,
655
+ message: `Feature '${feat.id}' references missing test file '${link.testPath}'.`,
656
+ fix: `Restore '${link.testPath}' or update feature_tests with a live replacement test.`
657
+ });
658
+ continue;
659
+ }
660
+ const content = fs3.readFileSync(abs, "utf8");
661
+ if (SKIPPED_TEST_RE.test(content)) {
662
+ violations.push({
663
+ id: `FLK:skipped-test:${feat.id}:${link.testPath}`,
664
+ rule: "linked-test-not-skipped",
665
+ severity: "warn",
666
+ featureId: feat.id,
667
+ file: link.testPath,
668
+ message: `Linked test file '${link.testPath}' for feature '${feat.id}' contains skipped/todo tests.`,
669
+ fix: "Remove .skip / .todo so feature coverage executes on every run."
670
+ });
671
+ }
672
+ }
673
+ }
674
+ return violations;
675
+ }
676
+ function checkInvariantLiveness(ctx) {
677
+ if (!ctx.repoRoot)
678
+ throw new Error("CheckContext.repoRoot is required.");
679
+ const violations = [];
680
+ const fileNormCache = new Map;
681
+ const readNormalized = (rel) => {
682
+ const cached = fileNormCache.get(rel);
683
+ if (cached !== undefined)
684
+ return cached;
685
+ const abs = path3.join(ctx.repoRoot, rel);
686
+ if (!fs3.existsSync(abs))
687
+ return null;
688
+ const norm = normalizeWhitespace(fs3.readFileSync(abs, "utf8"));
689
+ fileNormCache.set(rel, norm);
690
+ return norm;
691
+ };
692
+ for (const inv of ctx.registry.invariants) {
693
+ if (inv.status !== "active")
694
+ continue;
695
+ const normContent = readNormalized(inv.file);
696
+ if (normContent === null) {
697
+ violations.push({
698
+ id: `FLK:orphan-invariant:${inv.id}`,
699
+ rule: "invariant-target-must-exist",
700
+ severity: "error",
701
+ featureId: inv.featureId,
702
+ file: inv.file,
703
+ message: `Active invariant '${inv.id}' points to missing file '${inv.file}'.`,
704
+ fix: "Restore the guarded file or migrate the invariant to its new home with an audit entry."
705
+ });
706
+ continue;
707
+ }
708
+ if (inv.guardAnchor && !ctx.allowRemoval) {
709
+ const normAnchor = normalizeWhitespace(inv.guardAnchor);
710
+ if (normAnchor.length > 0 && !normContent.includes(normAnchor)) {
711
+ const rootHint = inv.rootTestPath ? ` (root test: ${inv.rootTestPath})` : "";
712
+ violations.push({
713
+ id: `FLK:dropped-guard:${inv.id}`,
714
+ rule: "invariant-guard-dropped-in-code",
715
+ severity: "error",
716
+ featureId: inv.featureId,
717
+ file: inv.file,
718
+ message: `BLOCKED: Active invariant '${inv.id}' guard disappeared from '${inv.file}'${rootHint}: expected '${normAnchor}'.`,
719
+ fix: `Restore the guard in '${inv.file}'${inv.rootTestPath ? ` and verify '${inv.rootTestPath}'` : ""}, or formally retire the invariant with an ADR + ALLOW_FEATURE_REMOVAL=1.`
720
+ });
721
+ }
722
+ }
723
+ if (inv.rootTestPath && !fs3.existsSync(path3.join(ctx.repoRoot, inv.rootTestPath))) {
724
+ violations.push({
725
+ id: `FLK:missing-root-test:${inv.id}`,
726
+ rule: "invariant-root-test-missing",
727
+ severity: "error",
728
+ featureId: inv.featureId,
729
+ file: inv.rootTestPath,
730
+ message: `Active invariant '${inv.id}' root test '${inv.rootTestPath}' is missing.`,
731
+ fix: `Restore '${inv.rootTestPath}' or re-bind the invariant to a live root test.`
732
+ });
733
+ }
734
+ }
735
+ return violations;
736
+ }
737
+ function checkGitAntiDeletion(ctx) {
738
+ if (!ctx.previousRegistry)
739
+ return [];
740
+ const violations = [];
741
+ const currentById = new Map(ctx.registry.features.map((f) => [f.id, f]));
742
+ const currentInvById = new Map(ctx.registry.invariants.map((i) => [i.id, i]));
743
+ for (const prev of ctx.previousRegistry.features) {
744
+ if (prev.status !== "active")
745
+ continue;
746
+ const cur = currentById.get(prev.id);
747
+ if (!cur) {
748
+ violations.push({
749
+ id: `FLK:feature-deleted:${prev.id}`,
750
+ rule: "no-silent-feature-deletion",
751
+ severity: "error",
752
+ featureId: prev.id,
753
+ file: "features/registry.sql",
754
+ message: `BLOCKED: Active feature '${prev.id}' (${prev.name}) was deleted from features/registry.sql.`,
755
+ fix: "Keep the feature active, or mark status='removed' with an explicit adr_ref + removal_reason AND ALLOW_FEATURE_REMOVAL=1."
756
+ });
757
+ } else if (cur.status === "removed") {
758
+ const hasAdr = Boolean(cur.adrRef && cur.adrRef.trim().length > 0 && cur.removalReason && cur.removalReason.trim().length > 0);
759
+ if (!ctx.allowRemoval || !hasAdr) {
760
+ violations.push({
761
+ id: `FLK:unapproved-removal:${prev.id}`,
762
+ rule: "feature-removal-requires-adr",
763
+ severity: "error",
764
+ featureId: prev.id,
765
+ file: "features/registry.sql",
766
+ message: `BLOCKED: Feature '${prev.id}' transitioned to 'removed' without adr_ref, removal_reason, and ALLOW_FEATURE_REMOVAL=1.`,
767
+ fix: "Confirm intentional feature removal with the user, document adr_ref + removal_reason, and rerun with ALLOW_FEATURE_REMOVAL=1."
768
+ });
769
+ } else {
770
+ violations.push({
771
+ id: `FLK:loud-removal-warning:${prev.id}`,
772
+ rule: "loud-feature-removal-warning",
773
+ severity: "warn",
774
+ featureId: prev.id,
775
+ file: "features/registry.sql",
776
+ message: `LOUD WARNING: Feature '${prev.id}' (${prev.name}) is being REMOVED under ADR '${cur.adrRef}' (${cur.removalReason}).`,
777
+ fix: "Double-check with the human owner before merging intentional feature removal."
778
+ });
779
+ }
780
+ }
781
+ }
782
+ for (const prevInv of ctx.previousRegistry.invariants) {
783
+ if (prevInv.status !== "active")
784
+ continue;
785
+ const curInv = currentInvById.get(prevInv.id);
786
+ if (!curInv || curInv.status === "removed" && !ctx.allowRemoval) {
787
+ violations.push({
788
+ id: `FLK:invariant-deleted:${prevInv.id}`,
789
+ rule: "no-silent-invariant-deletion",
790
+ severity: "error",
791
+ featureId: prevInv.featureId,
792
+ file: "features/registry.sql",
793
+ message: `BLOCKED: Active invariant '${prevInv.id}' (${prevInv.statement}) was deleted or disabled without ALLOW_FEATURE_REMOVAL=1.`,
794
+ fix: "Restore the invariant or explicitly approve its deprecation with an ADR."
795
+ });
796
+ }
797
+ }
798
+ return violations;
799
+ }
800
+ function checkVanishedFeatures(ctx) {
801
+ if (ctx.allowRemoval || ctx.registry.features.length === 0)
802
+ return [];
803
+ const liveFeatureIds = new Set(ctx.liveExtraction.features.map((f) => f.id));
804
+ if (liveFeatureIds.size === 0)
805
+ return [];
806
+ const violations = [];
807
+ for (const feat of ctx.registry.features) {
808
+ if (feat.status !== "active" || feat.source !== "ast")
809
+ continue;
810
+ if (liveFeatureIds.has(feat.id))
811
+ continue;
812
+ violations.push({
813
+ id: `FLK:feature-vanished:${feat.id}`,
814
+ rule: "feature-removed-from-code",
815
+ severity: "error",
816
+ featureId: feat.id,
817
+ file: "features/registry.sql",
818
+ message: `BLOCKED: Active extracted feature '${feat.id}' (${feat.name}) vanished from the codebase without ADR retirement.`,
819
+ fix: `Restore the '${feat.area}' source files or formally retire '${feat.id}' with adr_ref + removal_reason and ALLOW_FEATURE_REMOVAL=1.`
820
+ });
821
+ }
822
+ return violations;
823
+ }
824
+ function checkLiveExtractionDrift(ctx) {
825
+ if (ctx.registry.features.length === 0)
826
+ return [];
827
+ const violations = [];
828
+ const severity = ctx.strictDrift ? "error" : "warn";
829
+ const regFeatureIds = new Set(ctx.registry.features.map((f) => f.id));
830
+ const regInvIds = new Set(ctx.registry.invariants.map((i) => i.id));
831
+ const regAnchors = new Set(ctx.registry.invariants.filter((i) => i.guardAnchor).map((i) => `${i.file}|${normalizeWhitespace(i.guardAnchor ?? "")}`));
832
+ for (const liveFeat of ctx.liveExtraction.features) {
833
+ if (regFeatureIds.has(liveFeat.id))
834
+ continue;
835
+ violations.push({
836
+ id: `FLK:new-feature:${liveFeat.id}`,
837
+ rule: "unrecorded-new-feature",
838
+ severity,
839
+ featureId: liveFeat.id,
840
+ file: "features/registry.sql",
841
+ message: `Unrecorded new feature '${liveFeat.id}' (${liveFeat.name}) detected in codebase.`,
842
+ fix: `Run 'featlock extract --write' or 'featlock record-new --id ${liveFeat.id}' to lock this feature into features/registry.sql.`
843
+ });
844
+ }
845
+ const regTestKeys = new Set(ctx.registry.tests.map((t) => `${t.featureId}|${t.testPath}`));
846
+ for (const liveTest of ctx.liveExtraction.tests) {
847
+ if (!regFeatureIds.has(liveTest.featureId))
848
+ continue;
849
+ if (regTestKeys.has(`${liveTest.featureId}|${liveTest.testPath}`))
850
+ continue;
851
+ violations.push({
852
+ id: `FLK:new-test:${liveTest.featureId}:${liveTest.testPath}`,
853
+ rule: "unrecorded-new-feature-test",
854
+ severity,
855
+ featureId: liveTest.featureId,
856
+ file: liveTest.testPath,
857
+ message: `Unrecorded new capability test '${liveTest.testPath}' linked to '${liveTest.featureId}'.`,
858
+ fix: `Run 'featlock extract --write' or 'featlock record-improvement --id ${liveTest.featureId} --test ${liveTest.testPath}' to save it.`
859
+ });
860
+ }
861
+ for (const liveInv of ctx.liveExtraction.invariants) {
862
+ if (liveInv.source !== "ast" || !liveInv.guardAnchor)
863
+ continue;
864
+ const anchorKey = `${liveInv.file}|${normalizeWhitespace(liveInv.guardAnchor)}`;
865
+ if (regInvIds.has(liveInv.id) || regAnchors.has(anchorKey))
866
+ continue;
867
+ const rootHint = liveInv.rootTestPath ? ` (root test: ${liveInv.rootTestPath})` : "";
868
+ violations.push({
869
+ id: `FLK:new-invariant:${liveInv.id}`,
870
+ rule: "unrecorded-new-invariant",
871
+ severity,
872
+ featureId: liveInv.featureId,
873
+ file: liveInv.file,
874
+ message: `Unrecorded new invariant '${liveInv.id}' in '${liveInv.file}:${liveInv.line}'${rootHint}: ${liveInv.statement}`,
875
+ fix: "Run 'featlock extract --write' or 'featlock record-improvement' to save this invariant in features/registry.sql."
876
+ });
877
+ }
878
+ return violations;
879
+ }
880
+ function checkStagedDiffRecorded(ctx) {
881
+ if (ctx.stagedFiles.length === 0)
882
+ return [];
883
+ const touchesCodeOrTests = ctx.stagedFiles.some((f) => /\.(?:ts|tsx|js|mjs|py|rs|cs|go)$/.test(f));
884
+ const touchesRegistry = ctx.stagedFiles.includes("features/registry.sql");
885
+ if (!touchesCodeOrTests || touchesRegistry)
886
+ return [];
887
+ return [
888
+ {
889
+ id: "FLK:staged-unrecorded",
890
+ rule: "staged-changes-record-feature",
891
+ severity: "warn",
892
+ file: "features/registry.sql",
893
+ message: "Staged code/test changes have no matching new feature or 'improved' audit entry in features/registry.sql.",
894
+ fix: "Run 'featlock record-new' or 'featlock record-improvement' before committing."
895
+ }
896
+ ];
897
+ }
898
+ var src_default = Plugin.define({
899
+ id: "featlock.guard.anti-deletion",
900
+ guarded: true,
901
+ async setup(ctx) {
902
+ await ctx.guard.transform((ed) => {
903
+ ed.add({
904
+ id: "featlock.guard.anti-deletion.core",
905
+ guarded: true,
906
+ evaluate: (checkCtx) => [
907
+ ...checkActiveFeatureCoverage(checkCtx),
908
+ ...checkInvariantLiveness(checkCtx),
909
+ ...checkGitAntiDeletion(checkCtx),
910
+ ...checkVanishedFeatures(checkCtx),
911
+ ...checkLiveExtractionDrift(checkCtx),
912
+ ...checkStagedDiffRecorded(checkCtx)
913
+ ]
914
+ });
915
+ });
916
+ }
917
+ });
918
+
919
+ // packages/plugins/ast-scanner/src/index.ts
920
+ import path5 from "path";
921
+
922
+ // packages/plugins/ast-scanner/src/polyglot.ts
923
+ import { parseSync } from "oxc-parser";
924
+
925
+ // packages/plugins/ast-scanner/src/lexical.ts
926
+ var PY_EXT = ".py";
927
+ var SINGLE_QUOTE_STRING_EXTS = new Set([".ts", ".tsx", ".mts", ".js", ".mjs", ".py"]);
928
+ var BACKTICK_EXTS = new Set([".ts", ".tsx", ".mts", ".js", ".mjs", ".go"]);
929
+ function pushSpaces(out, ch) {
930
+ out.push(ch === `
931
+ ` ? `
932
+ ` : " ");
933
+ }
934
+ function consumeQuoted(src, start, quote, out) {
935
+ out.push(quote);
936
+ let i = start + 1;
937
+ while (i < src.length) {
938
+ const ch = src[i] ?? "";
939
+ if (ch === "\\" && i + 1 < src.length) {
940
+ pushSpaces(out, ch);
941
+ pushSpaces(out, src[i + 1] ?? "");
942
+ i += 2;
943
+ continue;
944
+ }
945
+ if (ch === quote) {
946
+ out.push(quote);
947
+ return i + 1;
948
+ }
949
+ if (ch === `
950
+ ` && quote !== "`") {
951
+ out.push(`
952
+ `);
953
+ return i + 1;
954
+ }
955
+ pushSpaces(out, ch);
956
+ i += 1;
957
+ }
958
+ return i;
959
+ }
960
+ function consumeTripleQuote(src, start, quote, out) {
961
+ out.push(quote, quote, quote);
962
+ let i = start + 3;
963
+ while (i < src.length) {
964
+ if (src.startsWith(quote.repeat(3), i)) {
965
+ out.push(quote, quote, quote);
966
+ return i + 3;
967
+ }
968
+ const ch = src[i] ?? "";
969
+ if (ch === "\\" && i + 1 < src.length) {
970
+ pushSpaces(out, ch);
971
+ pushSpaces(out, src[i + 1] ?? "");
972
+ i += 2;
973
+ continue;
974
+ }
975
+ pushSpaces(out, ch);
976
+ i += 1;
977
+ }
978
+ return i;
979
+ }
980
+ function maskPython(src) {
981
+ const out = [];
982
+ let i = 0;
983
+ while (i < src.length) {
984
+ const ch = src[i] ?? "";
985
+ if (ch === "#") {
986
+ while (i < src.length && src[i] !== `
987
+ `) {
988
+ out.push(" ");
989
+ i += 1;
990
+ }
991
+ continue;
992
+ }
993
+ if ((ch === '"' || ch === "'") && src.startsWith(ch.repeat(3), i)) {
994
+ i = consumeTripleQuote(src, i, ch, out);
995
+ continue;
996
+ }
997
+ if (ch === '"' || ch === "'") {
998
+ i = consumeQuoted(src, i, ch, out);
999
+ continue;
1000
+ }
1001
+ out.push(ch);
1002
+ i += 1;
1003
+ }
1004
+ return out.join("");
1005
+ }
1006
+ function maskCLike(src, ext) {
1007
+ if (!ext)
1008
+ throw new Error("File extension is required for lexical masking.");
1009
+ const out = [];
1010
+ const allowSingle = SINGLE_QUOTE_STRING_EXTS.has(ext);
1011
+ const allowBacktick = BACKTICK_EXTS.has(ext);
1012
+ let i = 0;
1013
+ while (i < src.length) {
1014
+ const ch = src[i] ?? "";
1015
+ const next = src[i + 1] ?? "";
1016
+ if (ch === "/" && next === "/") {
1017
+ while (i < src.length && src[i] !== `
1018
+ `) {
1019
+ out.push(" ");
1020
+ i += 1;
1021
+ }
1022
+ continue;
1023
+ }
1024
+ if (ch === "/" && next === "*") {
1025
+ out.push(" ", " ");
1026
+ i += 2;
1027
+ while (i < src.length && !(src[i] === "*" && src[i + 1] === "/")) {
1028
+ pushSpaces(out, src[i] ?? "");
1029
+ i += 1;
1030
+ }
1031
+ if (i + 1 < src.length) {
1032
+ out.push(" ", " ");
1033
+ i += 2;
1034
+ }
1035
+ continue;
1036
+ }
1037
+ if (ch === '"' || ch === "'" && allowSingle || ch === "`" && allowBacktick) {
1038
+ i = consumeQuoted(src, i, ch, out);
1039
+ continue;
1040
+ }
1041
+ out.push(ch);
1042
+ i += 1;
1043
+ }
1044
+ return out.join("");
1045
+ }
1046
+ function maskSourceForGuards(content, ext) {
1047
+ if (!content)
1048
+ return "";
1049
+ if (ext === PY_EXT)
1050
+ return maskPython(content);
1051
+ return maskCLike(content, ext);
1052
+ }
1053
+
1054
+ // packages/plugins/ast-scanner/src/polyglot.ts
1055
+ var TS_JS_EXTS = new Set([".ts", ".tsx", ".mts", ".js", ".mjs"]);
1056
+ function slugifyIdentifier(raw) {
1057
+ return raw.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64);
1058
+ }
1059
+ function normalizeGuardAnchor(raw) {
1060
+ return raw.replace(/\s+/g, " ").trim().slice(0, 140);
1061
+ }
1062
+ function hashAnchor(text) {
1063
+ let h = 2166136261;
1064
+ for (let i = 0;i < text.length; i += 1) {
1065
+ h ^= text.charCodeAt(i);
1066
+ h = Math.imul(h, 16777619);
1067
+ }
1068
+ return (h >>> 0).toString(16).padStart(8, "0");
1069
+ }
1070
+ function collectMatches(content, regex, limit) {
1071
+ const out = [];
1072
+ for (const m of content.matchAll(regex)) {
1073
+ const sym = (m[1] ?? "").trim();
1074
+ if (sym && !out.includes(sym))
1075
+ out.push(sym);
1076
+ if (out.length >= limit)
1077
+ break;
1078
+ }
1079
+ return out;
1080
+ }
1081
+ function extractExportedSymbols(file) {
1082
+ if (!file.content)
1083
+ return [];
1084
+ if (TS_JS_EXTS.has(file.ext)) {
1085
+ const parsed = parseSync(file.rel, file.content, { lang: file.ext === ".tsx" ? "tsx" : "ts" });
1086
+ const symbols = [];
1087
+ for (const exp of parsed.module.staticExports) {
1088
+ for (const entry of exp.entries) {
1089
+ const name = entry.exportName.name;
1090
+ if (name && name !== "default" && !symbols.includes(name))
1091
+ symbols.push(name);
1092
+ }
1093
+ }
1094
+ return symbols;
1095
+ }
1096
+ if (file.ext === ".rs") {
1097
+ return collectMatches(file.content, /^\s*pub\s+(?:async\s+)?(?:fn|struct|enum|trait|type|const)\s+([A-Za-z_][A-Za-z0-9_]*)/gm, 80);
1098
+ }
1099
+ if (file.ext === ".py") {
1100
+ return collectMatches(file.content, /^(?:async\s+def|def|class)\s+([A-Za-z][A-Za-z0-9_]*)\b/gm, 80);
1101
+ }
1102
+ if (file.ext === ".go") {
1103
+ return collectMatches(file.content, /^(?:func\s+(?:\([^)]+\)\s+)?|type\s+)([A-Z][A-Za-z0-9_]*)\b/gm, 80);
1104
+ }
1105
+ if (file.ext === ".cs") {
1106
+ return collectMatches(file.content, /\bpublic\s+(?:(?:static|sealed|abstract|partial|readonly|virtual|override|async)\s+)*(?:class|interface|record|struct|enum|void|[A-Za-z0-9_<>?]+)\s+([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]+>)?\s*(?:\(|\{|where|:)/g, 80);
1107
+ }
1108
+ return [];
1109
+ }
1110
+ function extractTestCases(file) {
1111
+ if (!file.content)
1112
+ return [];
1113
+ const cases = [];
1114
+ const push = (name, index) => {
1115
+ const clean = name.trim();
1116
+ if (!clean)
1117
+ return;
1118
+ const line = file.content.slice(0, index).split(`
1119
+ `).length;
1120
+ cases.push({ name: clean, line });
1121
+ };
1122
+ if (TS_JS_EXTS.has(file.ext)) {
1123
+ for (const m of file.content.matchAll(/\b(?:test|it|describe)\s*\(\s*(["'`])([^"'`\n]{3,140})\1/g)) {
1124
+ push(m[2] ?? "", m.index ?? 0);
1125
+ }
1126
+ return cases;
1127
+ }
1128
+ if (file.ext === ".rs") {
1129
+ for (const m of file.content.matchAll(/#\[(?:tokio::)?test(?:\([^)]*\))?\]\s*(?:#\[[^\]]*\]\s*)*(?:pub\s+)?(?:async\s+)?fn\s+([A-Za-z0-9_]+)/g)) {
1130
+ push(m[1] ?? "", m.index ?? 0);
1131
+ }
1132
+ return cases;
1133
+ }
1134
+ if (file.ext === ".py") {
1135
+ for (const m of file.content.matchAll(/^(?:async\s+)?def\s+(test_[A-Za-z0-9_]+)\s*\(/gm)) {
1136
+ push(m[1] ?? "", m.index ?? 0);
1137
+ }
1138
+ return cases;
1139
+ }
1140
+ if (file.ext === ".go") {
1141
+ for (const m of file.content.matchAll(/^func\s+(Test[A-Za-z0-9_]+)\s*\(/gm)) {
1142
+ push(m[1] ?? "", m.index ?? 0);
1143
+ }
1144
+ return cases;
1145
+ }
1146
+ if (file.ext === ".cs") {
1147
+ for (const m of file.content.matchAll(/\[(?:Fact|Theory|Test|TestMethod)\b[^\]]*\][\s\S]{0,180}?\b([A-Z][A-Za-z0-9_]+)\s*\(/g)) {
1148
+ push(m[1] ?? "", m.index ?? 0);
1149
+ }
1150
+ }
1151
+ return cases;
1152
+ }
1153
+ function makeInv(input) {
1154
+ const anchor = normalizeGuardAnchor(input.guardAnchor);
1155
+ return {
1156
+ id: `inv:ast:${input.suffix}:${slugifyIdentifier(input.file.rel)}:${hashAnchor(anchor)}`,
1157
+ featureId: input.featureId,
1158
+ kind: input.kind,
1159
+ statement: input.statement,
1160
+ file: input.file.rel,
1161
+ line: input.line,
1162
+ confidence: input.confidence,
1163
+ source: "ast",
1164
+ guardAnchor: anchor,
1165
+ status: "active"
1166
+ };
1167
+ }
1168
+ function windowSlice(lines, start, span) {
1169
+ return lines.slice(start, start + span).map((l) => l.trim()).join(" ");
1170
+ }
1171
+ function matchTsJsGuard(file, featureId, scan, i) {
1172
+ if (i < 0 || i >= scan.lines.length)
1173
+ throw new Error("Line index out of bounds.");
1174
+ const masked = (scan.lines[i] ?? "").trim();
1175
+ const raw = (scan.rawLines[i] ?? "").trim();
1176
+ const next3 = windowSlice(scan.lines, i, 3);
1177
+ const ln = i + 1;
1178
+ if (/\bCommand\.make\s*\(/.test(masked) && /\bCommand\.make\s*\(\s*["']([^"']+)["']/.test(raw)) {
1179
+ const cmd = /\bCommand\.make\s*\(\s*["']([^"']+)["']/.exec(raw)?.[1] ?? "command";
1180
+ return makeInv({ file, featureId, kind: "cli-contract", line: ln, confidence: 0.9, statement: `CLI subcommand '${cmd}' contract registered at ${file.rel}:${ln}`, guardAnchor: raw, suffix: `cli-${slugifyIdentifier(cmd)}` });
1181
+ }
1182
+ if (/\bif\s*\([^)]{2,140}\)/.test(masked) && /\bthrow\s+(?:new\s+(?:[A-Z]\w*)?(?:Error|Exception)|[A-Z]\w*(?:Error|Exception)\.[A-Za-z_]\w*)\s*\(/.test(next3)) {
1183
+ return makeInv({ file, featureId, kind: "precondition-guard", line: ln, confidence: 0.88, statement: `Precondition fail-closed guard: ${raw.slice(0, 110)}`, guardAnchor: raw, suffix: "precondition" });
1184
+ }
1185
+ if (/\bif\s*\([^)]{2,140}\)/.test(masked) && /\breturn\b[\s\S]{0,160}\b(?:[a-z]\w*(?:Rejection|Denied|Forbidden|Unauthorized|Invalid)\s*\(|new\s+Response\s*\([^)]*40[0134]\b)/.test(windowSlice(scan.lines, i, 5))) {
1186
+ return makeInv({ file, featureId, kind: "fail-closed-return-guard", line: ln, confidence: 0.86, statement: `Fail-closed rejection guard: ${raw.slice(0, 110)}`, guardAnchor: raw, suffix: "reject" });
1187
+ }
1188
+ if (/\b(?:assert\.ok|invariant)\s*\(/.test(masked)) {
1189
+ return makeInv({ file, featureId, kind: "runtime-invariant", line: ln, confidence: 0.88, statement: `Runtime invariant check: ${raw.slice(0, 110)}`, guardAnchor: raw, suffix: "invariant" });
1190
+ }
1191
+ return null;
1192
+ }
1193
+ function matchPolyglotLine(file, featureId, scan, i) {
1194
+ const { lines, rawLines } = scan;
1195
+ if (i < 0 || i >= lines.length)
1196
+ throw new Error("Line index out of bounds.");
1197
+ const text = (lines[i] ?? "").trim();
1198
+ const raw = (rawLines[i] ?? "").trim();
1199
+ const next3 = windowSlice(lines, i, 3);
1200
+ const ln = i + 1;
1201
+ if (/\bRAISE\s*\(\s*ABORT\b/i.test(text)) {
1202
+ return makeInv({ file, featureId, kind: "db-trigger-guard", line: ln, confidence: 0.95, statement: `SQLite trigger aborts disallowed mutation at ${file.rel}:${ln}`, guardAnchor: raw, suffix: "sql-trigger" });
1203
+ }
1204
+ if (TS_JS_EXTS.has(file.ext))
1205
+ return matchTsJsGuard(file, featureId, scan, i);
1206
+ if (file.ext === ".rs") {
1207
+ if (/\b(?:assert!|assert_eq!|assert_ne!|debug_assert!|ensure!|bail!)\s*\(/.test(text)) {
1208
+ return makeInv({ file, featureId, kind: "rust-assert-guard", line: ln, confidence: 0.9, statement: `Rust invariant assertion: ${raw.slice(0, 110)}`, guardAnchor: raw, suffix: "rs-assert" });
1209
+ }
1210
+ if (/^if\s+[^{]{2,120}\{/.test(text) && /\breturn\s+Err\s*\(/.test(windowSlice(lines, i, 5))) {
1211
+ return makeInv({ file, featureId, kind: "precondition-guard", line: ln, confidence: 0.84, statement: `Rust error guard: ${raw.slice(0, 110)}`, guardAnchor: raw, suffix: "rs-err" });
1212
+ }
1213
+ return null;
1214
+ }
1215
+ if (file.ext === ".py") {
1216
+ if (/^(?:if|elif)\s+[^:]{2,120}:/.test(text) && /\braise\s+[A-Z][A-Za-z0-9_]*\s*\(/.test(windowSlice(lines, i, 9))) {
1217
+ const anchor = raw.replace(/\s*#.*$/, "").trim();
1218
+ return makeInv({ file, featureId, kind: "precondition-guard", line: ln, confidence: 0.88, statement: `Python precondition guard: ${anchor.slice(0, 110)}`, guardAnchor: anchor, suffix: "py-raise" });
1219
+ }
1220
+ if (/^except\s+\(?[A-Za-z0-9_.,\s]+\)?(?:\s+as\s+\w+)?\s*:/.test(text) && /\braise\s+[A-Z][A-Za-z0-9_]*\s*\(/.test(windowSlice(lines, i, 4))) {
1221
+ const anchor = raw.replace(/\s*#.*$/, "").trim();
1222
+ return makeInv({ file, featureId, kind: "py-except-guard", line: ln, confidence: 0.87, statement: `Python exception translation guard: ${anchor.slice(0, 110)}`, guardAnchor: anchor, suffix: "py-except" });
1223
+ }
1224
+ if (/^assert\s+[^#]{3,120}/.test(text)) {
1225
+ return makeInv({ file, featureId, kind: "python-assert-guard", line: ln, confidence: 0.85, statement: `Python invariant assertion: ${raw.slice(0, 110)}`, guardAnchor: raw, suffix: "py-assert" });
1226
+ }
1227
+ return null;
1228
+ }
1229
+ if (file.ext === ".go") {
1230
+ const next5 = windowSlice(lines, i, 5);
1231
+ if (/^if\s+[^{]{2,120}\{/.test(text) && /\b(?:fmt\.Errorf|errors\.New|http\.Error)\s*\(/.test(next5)) {
1232
+ const isHttp = /\bhttp\.Error\s*\(/.test(next5);
1233
+ const kind = isHttp ? "go-http-guard" : "go-error-guard";
1234
+ return makeInv({ file, featureId, kind, line: ln, confidence: isHttp ? 0.94 : 0.84, statement: `Go guard: ${raw.slice(0, 110)}`, guardAnchor: raw, suffix: "go-err" });
1235
+ }
1236
+ return null;
1237
+ }
1238
+ if (file.ext === ".cs") {
1239
+ if (/\b(?:ArgumentNullException|ArgumentOutOfRangeException|ArgumentException|ObjectDisposedException)\.ThrowIf\w*\s*\(|\bGuard\.(?:NotNull|Range|NotNullOrEmpty)\s*\(/.test(text)) {
1240
+ return makeInv({ file, featureId, kind: "csharp-guard-clause", line: ln, confidence: 0.92, statement: `C# guard clause: ${raw.slice(0, 110)}`, guardAnchor: raw, suffix: "cs-guard" });
1241
+ }
1242
+ if (/^if\s*\([^)]{2,140}\)/.test(text) && /\bthrow\s+new\s+[A-Z]\w*Exception\s*\(/.test(next3)) {
1243
+ return makeInv({ file, featureId, kind: "precondition-guard", line: ln, confidence: 0.85, statement: `C# precondition guard: ${raw.slice(0, 110)}`, guardAnchor: raw, suffix: "cs-throw" });
1244
+ }
1245
+ }
1246
+ return null;
1247
+ }
1248
+ function scanFileInvariants(file, featureId) {
1249
+ if (!featureId)
1250
+ throw new Error("featureId is required for invariant scanning.");
1251
+ if (file.isTest)
1252
+ return [];
1253
+ const found = [];
1254
+ const seenIds = new Set;
1255
+ const rawLines = file.content.split(`
1256
+ `);
1257
+ const lines = maskSourceForGuards(file.content, file.ext).split(`
1258
+ `);
1259
+ const scan = { lines, rawLines };
1260
+ const isRust = file.ext === ".rs";
1261
+ for (let i = 0;i < lines.length; i += 1) {
1262
+ const text = (lines[i] ?? "").trim();
1263
+ if (!text)
1264
+ continue;
1265
+ if (isRust && text.startsWith("#[cfg(test)]"))
1266
+ break;
1267
+ const inv = matchPolyglotLine(file, featureId, scan, i);
1268
+ if (inv && !seenIds.has(inv.id)) {
1269
+ seenIds.add(inv.id);
1270
+ found.push(inv);
1271
+ }
1272
+ }
1273
+ if (found.length <= 24)
1274
+ return found;
1275
+ return found.toSorted((a, b) => {
1276
+ const diff = b.confidence - a.confidence;
1277
+ return diff !== 0 ? diff : a.line - b.line;
1278
+ }).slice(0, 24);
1279
+ }
1280
+
1281
+ // packages/plugins/ast-scanner/src/root-tests.ts
1282
+ import path4 from "path";
1283
+ function stemOf(relPath) {
1284
+ return path4.posix.basename(relPath, path4.posix.extname(relPath)).replace(/^_+/, "").replace(/\.(?:test|spec)$/i, "").replace(/(?:_test|tests?)$/i, "").replace(/^test_/, "").toLowerCase();
1285
+ }
1286
+ function addToBucket(map, key, item) {
1287
+ if (!key)
1288
+ return;
1289
+ const list = map.get(key);
1290
+ if (list)
1291
+ list.push(item);
1292
+ else
1293
+ map.set(key, [item]);
1294
+ }
1295
+ function extractTokens(text) {
1296
+ const tokens = new Set;
1297
+ for (const m of text.matchAll(/[a-z][a-z0-9]{3,40}/g)) {
1298
+ tokens.add(m[0]);
1299
+ if (tokens.size >= 500)
1300
+ break;
1301
+ }
1302
+ return tokens;
1303
+ }
1304
+ function buildTestIndex(allTestFiles) {
1305
+ if (!Array.isArray(allTestFiles))
1306
+ throw new Error("allTestFiles must be an array.");
1307
+ const all = [];
1308
+ const byDir = new Map;
1309
+ const byStem = new Map;
1310
+ const byToken = new Map;
1311
+ for (const file of allTestFiles) {
1312
+ const dir = path4.posix.dirname(file.rel);
1313
+ const stem = stemOf(file.rel);
1314
+ const relLower = file.rel.toLowerCase();
1315
+ const contentLower = file.content.toLowerCase();
1316
+ const item = { file, dir, stem, relLower, contentLower, cases: extractTestCases(file) };
1317
+ all.push(item);
1318
+ addToBucket(byDir, dir, item);
1319
+ addToBucket(byStem, stem, item);
1320
+ for (const part of stem.split(/[^a-z0-9]+/).filter((p) => p.length >= 4))
1321
+ addToBucket(byStem, part, item);
1322
+ for (const tok of extractTokens(`${relLower} ${contentLower.slice(0, 16000)}`))
1323
+ addToBucket(byToken, tok, item);
1324
+ }
1325
+ return { all, byDir, byStem, byToken };
1326
+ }
1327
+ function invariantKeywords(statement) {
1328
+ const stop = new Set(["precondition", "guard", "fail", "closed", "error", "return", "throw", "raise", "assert", "string", "typeof", "value", "const", "invalid", "python", "rust", "csharp", "clause", "invariant", "assertion"]);
1329
+ return statement.toLowerCase().replace(/[^a-z0-9]+/g, " ").split(" ").filter((tok) => tok.length >= 4 && !stop.has(tok)).slice(0, 6);
1330
+ }
1331
+ function findEnclosingSymbol(file, line) {
1332
+ const lines = file.content.split(`
1333
+ `);
1334
+ const start = Math.max(0, Math.min(lines.length - 1, line - 1));
1335
+ const floor = Math.max(0, start - 35);
1336
+ for (let i = start;i >= floor; i -= 1) {
1337
+ const raw = (lines[i] ?? "").trim();
1338
+ const m = /^(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(raw) ?? /^(?:export\s+)?const\s+([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?:async\s*)?\(/.exec(raw) ?? /^(?:pub\s+)?(?:async\s+)?fn\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(raw) ?? /^(?:async\s+)?def\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(raw) ?? /^func\s+(?:\([^)]+\)\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*\(/.exec(raw) ?? /\b(?:public|internal|private|protected)\s+(?:(?:static|sealed|abstract|virtual|override|async)\s+)*[A-Za-z0-9_<>?]+\s+([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]+>)?\s*\(/.exec(raw);
1339
+ if (m?.[1] && m[1].length >= 4)
1340
+ return m[1];
1341
+ }
1342
+ return null;
1343
+ }
1344
+ function scoreTestForRoot(ctx, tf) {
1345
+ if (!tf.file.rel)
1346
+ throw new Error("Test file path is required.");
1347
+ let score = 0;
1348
+ if (tf.dir === ctx.prodDir) {
1349
+ score += 8;
1350
+ if (ctx.prodStem && (tf.stem === ctx.prodStem || tf.stem.startsWith(`${ctx.prodStem}_`) || tf.stem.startsWith(ctx.prodStem))) {
1351
+ score += 12;
1352
+ }
1353
+ } else if (ctx.prodStem && ctx.prodStem !== "index" && ctx.prodStem !== "mod" && ctx.prodStem !== "lib") {
1354
+ if (tf.stem === ctx.prodStem || tf.stem.includes(ctx.prodStem))
1355
+ score += 10;
1356
+ }
1357
+ if (ctx.parentName && ctx.parentName.length >= 4 && ctx.parentName !== "src" && tf.relLower.includes(`/${ctx.parentName}/`)) {
1358
+ score += 8;
1359
+ } else if (ctx.parentName && ctx.parentName.length >= 3 && ctx.parentName !== "src" && tf.relLower.includes(ctx.parentName)) {
1360
+ score += 4;
1361
+ }
1362
+ if (ctx.enclosingSymbol && tf.contentLower.includes(ctx.enclosingSymbol.toLowerCase())) {
1363
+ score += 18;
1364
+ }
1365
+ let symHits = 0;
1366
+ for (const sym of ctx.symbols) {
1367
+ if (sym.length >= 4 && tf.contentLower.includes(sym.toLowerCase())) {
1368
+ symHits += 1;
1369
+ if (symHits >= 2)
1370
+ break;
1371
+ }
1372
+ }
1373
+ score += symHits * 5;
1374
+ let kwHits = 0;
1375
+ for (const kw of ctx.keywords) {
1376
+ if (tf.contentLower.includes(kw) || tf.relLower.includes(kw)) {
1377
+ kwHits += 1;
1378
+ if (kwHits >= 2)
1379
+ break;
1380
+ }
1381
+ }
1382
+ score += kwHits * 5;
1383
+ return score;
1384
+ }
1385
+ function gatherCandidates(ctx, index) {
1386
+ const seen = new Set;
1387
+ const out = [];
1388
+ const addList = (list) => {
1389
+ if (!list)
1390
+ return;
1391
+ for (const item of list) {
1392
+ if (seen.has(item.file.rel))
1393
+ continue;
1394
+ seen.add(item.file.rel);
1395
+ out.push(item);
1396
+ if (out.length >= 60)
1397
+ return;
1398
+ }
1399
+ };
1400
+ addList(index.byDir.get(ctx.prodDir));
1401
+ addList(index.byStem.get(ctx.prodStem));
1402
+ for (const part of ctx.parentName.split(/[^a-z0-9]+/).filter((p) => p.length >= 4)) {
1403
+ addList(index.byToken.get(part));
1404
+ }
1405
+ if (ctx.enclosingSymbol) {
1406
+ const cleanSym = ctx.enclosingSymbol.toLowerCase().replace(/^_+/, "");
1407
+ addList(index.byToken.get(cleanSym));
1408
+ for (const part of cleanSym.split(/[^a-z0-9]+/).filter((p) => p.length >= 4))
1409
+ addList(index.byToken.get(part));
1410
+ }
1411
+ for (const sym of ctx.symbols.slice(0, 6)) {
1412
+ const cleanSym = sym.toLowerCase().replace(/^_+/, "");
1413
+ addList(index.byToken.get(cleanSym));
1414
+ for (const part of cleanSym.split(/[^a-z0-9]+/).filter((p) => p.length >= 4))
1415
+ addList(index.byToken.get(part));
1416
+ }
1417
+ for (const kw of ctx.keywords)
1418
+ addList(index.byToken.get(kw));
1419
+ if (out.length === 0 && index.all.length <= 20)
1420
+ addList(index.all);
1421
+ return out;
1422
+ }
1423
+ function resolveRootTestForFile(query) {
1424
+ if (!query.prodFile.rel)
1425
+ throw new Error("prodFile.rel is required.");
1426
+ if (query.prodFile.ext === ".rs") {
1427
+ const inlineCases = extractTestCases(query.prodFile);
1428
+ if (inlineCases.length > 0) {
1429
+ return {
1430
+ file: query.prodFile,
1431
+ dir: path4.posix.dirname(query.prodFile.rel),
1432
+ stem: stemOf(query.prodFile.rel),
1433
+ relLower: query.prodFile.rel.toLowerCase(),
1434
+ contentLower: "",
1435
+ cases: inlineCases
1436
+ };
1437
+ }
1438
+ }
1439
+ const prodDir = path4.posix.dirname(query.prodFile.rel);
1440
+ const ctx = {
1441
+ prodDir,
1442
+ prodStem: stemOf(query.prodFile.rel),
1443
+ parentName: path4.posix.basename(prodDir).toLowerCase(),
1444
+ symbols: query.symbols,
1445
+ enclosingSymbol: findEnclosingSymbol(query.prodFile, query.invariantLine),
1446
+ keywords: invariantKeywords(query.invariantText)
1447
+ };
1448
+ const candidates = gatherCandidates(ctx, query.testIndex);
1449
+ let best;
1450
+ let bestScore = 0;
1451
+ for (const tf of candidates) {
1452
+ const score = scoreTestForRoot(ctx, tf);
1453
+ if (score > bestScore || score === bestScore && score > 0 && best && tf.file.rel.localeCompare(best.file.rel) < 0) {
1454
+ bestScore = score;
1455
+ best = tf;
1456
+ }
1457
+ }
1458
+ return bestScore >= 6 ? best : undefined;
1459
+ }
1460
+
1461
+ // packages/plugins/ast-scanner/src/index.ts
1462
+ var NON_PROD_PREFIX = /^(?:\.github|examples|samples|snippets|templates|fixtures|testdata|__fixtures__|bench|benchmarks|benchsuite|perf-measures|fuzz|docs|docs_src|tools|scripts|build|eng|pkg|ci|caddytest)\//i;
1463
+ var NON_PROD_SEGMENT = /(?:^|\/)(?:snippets|samples|benchmarks|__fixtures__|fixtures|testdata|examples|templates|caught|snapshots)\//i;
1464
+ var GENERATED_FILE_RE = /\.(?:d\.ts|pb\.go|g\.cs|generated\.[a-z]+)$|(?:^|\/)(?:cake\.cs|build\.rs|setup\.py|conftest\.py)$/i;
1465
+ var SRC_SUBFEATURE_CONTAINERS = new Set(["middleware", "helper", "router", "adapter", "plugins", "features", "services", "handlers"]);
1466
+ function areaFromPath(rel, ext) {
1467
+ const parts = rel.split("/");
1468
+ if (parts[0] === "packages" && parts[1] === "plugins" && parts[2])
1469
+ return `plugin:${parts[2]}`;
1470
+ if (parts[0] === "packages" && parts[1])
1471
+ return parts[1];
1472
+ if (parts[0] === "crates" && parts[1])
1473
+ return `crate:${parts[1]}`;
1474
+ if (parts[0] === "modules" && parts[1])
1475
+ return `module:${parts[1]}`;
1476
+ if ((parts[0] === "cmd" || parts[0] === "internal" || parts[0] === "caddyconfig") && parts.length >= 3 && parts[1]) {
1477
+ return `${parts[0]}:${parts[1]}`;
1478
+ }
1479
+ if (ext === ".py" && parts[0] === "src" && parts.length >= 5 && parts[1] && parts[2] === parts[1] && parts[3]) {
1480
+ return `${parts[1]}:${parts[3].replace(/^_+/, "") || "core"}`;
1481
+ }
1482
+ if (ext === ".py" && parts.length >= 4 && parts[0] && parts[1] && parts[0].startsWith(parts[1]) && parts[2]) {
1483
+ return `${parts[1]}:${parts[2].replace(/^_+/, "") || "core"}`;
1484
+ }
1485
+ if (parts[0] === "src" && parts.length >= 4 && parts[1] && parts[2] && SRC_SUBFEATURE_CONTAINERS.has(parts[1])) {
1486
+ return `${parts[1]}:${parts[2]}`;
1487
+ }
1488
+ if (parts[0] === "src" && parts.length >= 3 && parts[1])
1489
+ return parts[1];
1490
+ if (parts[0] === "tests" && parts.length >= 3 && parts[1])
1491
+ return parts[1];
1492
+ if (ext === ".py" && parts.length === 2 && parts[0] && parts[1]) {
1493
+ const stem = parts[1].replace(/\.py$/i, "").replace(/^_+/, "");
1494
+ if (stem && !["init", "version", "compat", "types", "main"].includes(stem))
1495
+ return `${parts[0]}:${stem}`;
1496
+ return `${parts[0]}:core`;
1497
+ }
1498
+ if (ext === ".py" && parts.length >= 3 && parts[0] && parts[1]) {
1499
+ return `${parts[0]}:${parts[1].replace(/^_+/, "") || "core"}`;
1500
+ }
1501
+ return path5.posix.dirname(rel) === "." ? "root" : parts[0] ?? "core";
1502
+ }
1503
+ function matchTestsForBucket(area, bucket, testIndex) {
1504
+ if (!area)
1505
+ throw new Error("area is required.");
1506
+ const matched = [];
1507
+ const seen = new Set;
1508
+ for (const tf of bucket.testFiles) {
1509
+ seen.add(tf.rel);
1510
+ matched.push({ file: tf, cases: extractTestCases(tf) });
1511
+ }
1512
+ for (const pf of bucket.prodFiles) {
1513
+ if (pf.ext !== ".rs")
1514
+ continue;
1515
+ const inlineCases = extractTestCases(pf);
1516
+ if (inlineCases.length > 0 && !seen.has(pf.rel)) {
1517
+ seen.add(pf.rel);
1518
+ matched.push({ file: pf, cases: inlineCases });
1519
+ }
1520
+ }
1521
+ for (const sym of bucket.symbols) {
1522
+ if (sym.length < 5)
1523
+ continue;
1524
+ for (const hit of testIndex.byStem.get(sym.toLowerCase()) ?? []) {
1525
+ if (seen.has(hit.file.rel))
1526
+ continue;
1527
+ seen.add(hit.file.rel);
1528
+ matched.push({ file: hit.file, cases: hit.cases });
1529
+ }
1530
+ }
1531
+ if (matched.length > 0)
1532
+ return matched.slice(0, 8);
1533
+ const cleanArea = area.replace(/^(?:plugin|crate|module|cmd|internal|caddyconfig):/, "").toLowerCase();
1534
+ const tailToken = cleanArea.split(":").pop() ?? cleanArea;
1535
+ const areaTokens = tailToken.split(/[^a-z0-9]+/).filter((t) => t.length >= 3);
1536
+ const symbolHints = bucket.symbols.filter((s) => s.length >= 4).slice(0, 6).map((s) => s.toLowerCase());
1537
+ const candidateSet = new Set;
1538
+ for (const key of [tailToken, slugifyIdentifier(tailToken), ...areaTokens, ...symbolHints]) {
1539
+ for (const hit of testIndex.byStem.get(key) ?? [])
1540
+ candidateSet.add(hit);
1541
+ for (const hit of testIndex.byToken.get(key) ?? [])
1542
+ candidateSet.add(hit);
1543
+ }
1544
+ const pool = candidateSet.size > 0 ? Array.from(candidateSet) : testIndex.all.slice(0, 120);
1545
+ for (const item of pool) {
1546
+ if (seen.has(item.file.rel))
1547
+ continue;
1548
+ const hitArea = item.relLower.includes(tailToken) || item.contentLower.includes(tailToken) || item.relLower.includes(slugifyIdentifier(tailToken)) || areaTokens.length > 0 && areaTokens.every((tok) => item.relLower.includes(tok) || item.contentLower.includes(tok));
1549
+ const hitSymbol = symbolHints.some((sym) => item.contentLower.includes(sym));
1550
+ if (hitArea || hitSymbol) {
1551
+ seen.add(item.file.rel);
1552
+ matched.push({ file: item.file, cases: item.cases });
1553
+ if (matched.length >= 5)
1554
+ break;
1555
+ }
1556
+ }
1557
+ return matched;
1558
+ }
1559
+ function buildFeatureRecords(area, bucket, testIndex) {
1560
+ if (bucket.prodFiles.length === 0)
1561
+ return { features: [], tests: [], invariants: [] };
1562
+ const featureId = `feat.${slugifyIdentifier(area)}`;
1563
+ const sampleSymbols = bucket.symbols.slice(0, 6).join(", ");
1564
+ const feature = {
1565
+ id: featureId,
1566
+ area,
1567
+ name: `${area} capability`,
1568
+ summary: `Extracted from ${bucket.prodFiles.length} source file(s)${sampleSymbols ? ` exporting ${sampleSymbols}` : ""}.`,
1569
+ acceptanceCriteria: `Exports and behaviors in ${area} remain covered by linked tests and preserve extracted invariants.`,
1570
+ status: "active",
1571
+ source: "ast"
1572
+ };
1573
+ const testMap = new Map;
1574
+ const addTestLink = (tf, cases) => {
1575
+ const pattern = cases[0]?.name ?? path5.posix.basename(tf.rel);
1576
+ const rung = tf.rel.includes(".mbt.") ? "R3" : "R2";
1577
+ testMap.set(`${tf.rel}|${pattern}`, { featureId, testPath: tf.rel, testPattern: pattern, rung });
1578
+ };
1579
+ for (const hit of matchTestsForBucket(area, bucket, testIndex))
1580
+ addTestLink(hit.file, hit.cases);
1581
+ const invariants = [];
1582
+ for (const pf of bucket.prodFiles) {
1583
+ const fileInvs = scanFileInvariants(pf, featureId);
1584
+ const fileSyms = bucket.fileSymbols.get(pf.rel) ?? [];
1585
+ for (const inv of fileInvs) {
1586
+ const rootHit = resolveRootTestForFile({
1587
+ prodFile: pf,
1588
+ symbols: fileSyms,
1589
+ invariantText: inv.statement,
1590
+ invariantLine: inv.line,
1591
+ testIndex
1592
+ });
1593
+ if (rootHit)
1594
+ addTestLink(rootHit.file, rootHit.cases);
1595
+ invariants.push(rootHit ? { ...inv, rootTestPath: rootHit.file.rel } : inv);
1596
+ if (invariants.length >= 250)
1597
+ break;
1598
+ }
1599
+ if (invariants.length >= 250)
1600
+ break;
1601
+ }
1602
+ return { features: [feature], tests: [...testMap.values()], invariants };
1603
+ }
1604
+ function extractFromRepo(ctx) {
1605
+ if (!ctx.repoRoot)
1606
+ throw new Error("ScanContext.repoRoot is required.");
1607
+ const byArea = new Map;
1608
+ for (const file of ctx.files) {
1609
+ if (file.rel === "features/registry.sql")
1610
+ continue;
1611
+ if (!file.isTest && (NON_PROD_PREFIX.test(file.rel) || NON_PROD_SEGMENT.test(file.rel) || GENERATED_FILE_RE.test(file.rel)))
1612
+ continue;
1613
+ const area = areaFromPath(file.rel, file.ext);
1614
+ const bucket = byArea.get(area) ?? { prodFiles: [], testFiles: [], symbols: [], fileSymbols: new Map };
1615
+ if (file.isTest) {
1616
+ bucket.testFiles.push(file);
1617
+ } else {
1618
+ bucket.prodFiles.push(file);
1619
+ const syms = extractExportedSymbols(file);
1620
+ bucket.fileSymbols.set(file.rel, syms);
1621
+ for (const sym of syms) {
1622
+ if (!bucket.symbols.includes(sym))
1623
+ bucket.symbols.push(sym);
1624
+ }
1625
+ }
1626
+ byArea.set(area, bucket);
1627
+ }
1628
+ const features = [];
1629
+ const tests = [];
1630
+ const invariants = [];
1631
+ const testIndex = buildTestIndex(ctx.files.filter((f) => f.isTest));
1632
+ for (const [area, bucket] of [...byArea.entries()].toSorted((a, b) => a[0].localeCompare(b[0]))) {
1633
+ const out = buildFeatureRecords(area, bucket, testIndex);
1634
+ features.push(...out.features);
1635
+ tests.push(...out.tests);
1636
+ invariants.push(...out.invariants);
1637
+ }
1638
+ return { features, tests, invariants };
1639
+ }
1640
+ var src_default2 = Plugin.define({
1641
+ id: "featlock.ast-scanner",
1642
+ async setup(ctx) {
1643
+ await ctx.extractor.transform((ed) => {
1644
+ ed.add({
1645
+ id: "featlock.ast-scanner.extractor",
1646
+ label: "Polyglot AST Feature, Test & Invariant Extractor",
1647
+ extract: extractFromRepo
1648
+ });
1649
+ });
1650
+ }
1651
+ });
1652
+
1653
+ // packages/plugins/config/src/index.ts
1654
+ var src_default3 = Plugin.define({
1655
+ id: "featlock.config",
1656
+ async setup(ctx) {
1657
+ await ctx.reporter.transform((ed) => {
1658
+ ed.add({
1659
+ id: "json",
1660
+ format: (payload) => JSON.stringify(payload, null, 2)
1661
+ });
1662
+ });
1663
+ }
1664
+ });
1665
+
1666
+ // packages/plugins/harnesses/src/index.ts
1667
+ import fs4 from "fs";
1668
+ import path6 from "path";
1669
+ var HOOK_SCRIPT_CONTENT = `#!/usr/bin/env node
1670
+ import { spawnSync } from "node:child_process";
1671
+ import fs from "node:fs";
1672
+ import path from "node:path";
1673
+
1674
+ const localBin = path.resolve("node_modules/.bin/featlock");
1675
+ const cmd = fs.existsSync(localBin) ? localBin : "bunx";
1676
+ const args = fs.existsSync(localBin) ? ["check", "."] : ["featlock", "check", "."];
1677
+ const res = spawnSync(cmd, args, { encoding: "utf8" });
1678
+ if (res.error || res.status !== 0) {
1679
+ process.stderr.write(res.stdout || "");
1680
+ process.stderr.write(res.stderr || "");
1681
+ if (res.error) process.stderr.write(String(res.error.message || res.error) + "\\n");
1682
+ process.stderr.write("\\nFEATLOCK GUARD: Feature/invariant integrity check failed. Do NOT silently delete features or invariants.\\n");
1683
+ process.exit(2);
1684
+ }
1685
+ `;
1686
+ var AGENT_RULE_BLOCK = `<!-- featlock:start -->
1687
+ ## FeatLock Feature & Invariant Guard Rules
1688
+ - Before implementing any new capability, run \`featlock query <topic>\` and \`featlock check-dup "<summary>"\` so you do not duplicate an existing feature.
1689
+ - On every change that adds or improves product behavior, automatically record it with \`featlock record-new\` or \`featlock record-improvement\` in \`features/registry.sql\`.
1690
+ - NEVER delete an active feature, unlink its tests, or delete an active invariant without explicit human confirmation, an ADR reference, and \`ALLOW_FEATURE_REMOVAL=1\`.
1691
+ <!-- featlock:end -->
1692
+ `;
1693
+ function readJsonObject(filePath) {
1694
+ if (!fs4.existsSync(filePath))
1695
+ return {};
1696
+ try {
1697
+ const parsed = JSON.parse(fs4.readFileSync(filePath, "utf8"));
1698
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
1699
+ } catch {
1700
+ return {};
1701
+ }
1702
+ }
1703
+ function entryHasMarker(entry, marker) {
1704
+ if (!entry || typeof entry !== "object")
1705
+ return false;
1706
+ return JSON.stringify(entry).includes(marker);
1707
+ }
1708
+ function wireJsonHookConfig(repoRoot, binding, relScript) {
1709
+ if (!repoRoot || !relScript)
1710
+ throw new Error("repoRoot and relScript are required.");
1711
+ const absConfig = path6.join(repoRoot, binding.configRel);
1712
+ const root = readJsonObject(absConfig);
1713
+ if (binding.format === "flat" && root.version === undefined)
1714
+ root.version = 1;
1715
+ const hooksObj = root.hooks && typeof root.hooks === "object" && !Array.isArray(root.hooks) ? { ...root.hooks } : {};
1716
+ const list = Array.isArray(hooksObj[binding.eventKey]) ? [...hooksObj[binding.eventKey]] : [];
1717
+ if (list.some((item) => entryHasMarker(item, relScript)))
1718
+ return false;
1719
+ const command = `node ${relScript}`;
1720
+ const entry = binding.format === "nested" ? { hooks: [{ type: "command", command }] } : { command };
1721
+ list.push(entry);
1722
+ hooksObj[binding.eventKey] = list;
1723
+ root.hooks = hooksObj;
1724
+ fs4.mkdirSync(path6.dirname(absConfig), { recursive: true });
1725
+ fs4.writeFileSync(absConfig, `${JSON.stringify(root, null, 2)}
1726
+ `, "utf8");
1727
+ return true;
1728
+ }
1729
+ function unwireJsonHookConfig(repoRoot, binding, relScript) {
1730
+ const absConfig = path6.join(repoRoot, binding.configRel);
1731
+ if (!fs4.existsSync(absConfig))
1732
+ return false;
1733
+ const root = readJsonObject(absConfig);
1734
+ const hooksObj = root.hooks && typeof root.hooks === "object" && !Array.isArray(root.hooks) ? { ...root.hooks } : null;
1735
+ if (!hooksObj || !Array.isArray(hooksObj[binding.eventKey]))
1736
+ return false;
1737
+ const before = hooksObj[binding.eventKey];
1738
+ const after = before.filter((item) => !entryHasMarker(item, relScript));
1739
+ if (after.length === before.length)
1740
+ return false;
1741
+ hooksObj[binding.eventKey] = after;
1742
+ root.hooks = hooksObj;
1743
+ fs4.writeFileSync(absConfig, `${JSON.stringify(root, null, 2)}
1744
+ `, "utf8");
1745
+ return true;
1746
+ }
1747
+ function isJsonHookWired(repoRoot, binding, relScript) {
1748
+ const absConfig = path6.join(repoRoot, binding.configRel);
1749
+ if (!fs4.existsSync(absConfig))
1750
+ return false;
1751
+ const root = readJsonObject(absConfig);
1752
+ const hooksObj = root.hooks && typeof root.hooks === "object" && !Array.isArray(root.hooks) ? root.hooks : null;
1753
+ if (!hooksObj || !Array.isArray(hooksObj[binding.eventKey]))
1754
+ return false;
1755
+ return hooksObj[binding.eventKey].some((item) => entryHasMarker(item, relScript));
1756
+ }
1757
+ function ensureAgentRule(filePath) {
1758
+ fs4.mkdirSync(path6.dirname(filePath), { recursive: true });
1759
+ const existing = fs4.existsSync(filePath) ? fs4.readFileSync(filePath, "utf8") : "";
1760
+ if (existing.includes("<!-- featlock:start -->"))
1761
+ return false;
1762
+ const next = existing.trim().length > 0 ? `${existing.trimEnd()}
1763
+
1764
+ ${AGENT_RULE_BLOCK}` : AGENT_RULE_BLOCK;
1765
+ fs4.writeFileSync(filePath, next, "utf8");
1766
+ return true;
1767
+ }
1768
+ function removeAgentRule(filePath) {
1769
+ if (!fs4.existsSync(filePath))
1770
+ return false;
1771
+ const existing = fs4.readFileSync(filePath, "utf8");
1772
+ if (!existing.includes("<!-- featlock:start -->"))
1773
+ return false;
1774
+ const cleaned = existing.replace(/\n*<!-- featlock:start -->[\s\S]*?<!-- featlock:end -->\n*/g, `
1775
+ `).trim();
1776
+ fs4.writeFileSync(filePath, cleaned ? `${cleaned}
1777
+ ` : "", "utf8");
1778
+ return true;
1779
+ }
1780
+ function makeFileHookHarness(spec) {
1781
+ if (!spec.id || !spec.relScript)
1782
+ throw new Error("Harness id and relScript are required.");
1783
+ const { id, label, relScript, docRel, binding } = spec;
1784
+ return {
1785
+ id,
1786
+ label,
1787
+ install: (repoRoot) => {
1788
+ const touched = [];
1789
+ const absHook = path6.join(repoRoot, relScript);
1790
+ fs4.mkdirSync(path6.dirname(absHook), { recursive: true });
1791
+ fs4.writeFileSync(absHook, HOOK_SCRIPT_CONTENT, { encoding: "utf8", mode: 493 });
1792
+ touched.push(relScript);
1793
+ if (binding && wireJsonHookConfig(repoRoot, binding, relScript))
1794
+ touched.push(binding.configRel);
1795
+ if (ensureAgentRule(path6.join(repoRoot, docRel)))
1796
+ touched.push(docRel);
1797
+ return touched;
1798
+ },
1799
+ uninstall: (repoRoot) => {
1800
+ const touched = [];
1801
+ const absHook = path6.join(repoRoot, relScript);
1802
+ if (fs4.existsSync(absHook)) {
1803
+ fs4.rmSync(absHook, { force: true });
1804
+ touched.push(relScript);
1805
+ }
1806
+ if (binding && unwireJsonHookConfig(repoRoot, binding, relScript))
1807
+ touched.push(binding.configRel);
1808
+ if (removeAgentRule(path6.join(repoRoot, docRel)))
1809
+ touched.push(docRel);
1810
+ return touched;
1811
+ },
1812
+ status: async (repoRoot) => {
1813
+ const scriptExists = fs4.existsSync(path6.join(repoRoot, relScript));
1814
+ const wired = binding ? isJsonHookWired(repoRoot, binding, relScript) : true;
1815
+ const installed = scriptExists && wired;
1816
+ const detail = installed ? binding ? `active (${relScript} + ${binding.configRel})` : `active (${relScript})` : scriptExists ? `unwired (${relScript} missing registration in ${binding?.configRel ?? "config"})` : `not installed (${relScript})`;
1817
+ return { installed, detail };
1818
+ }
1819
+ };
1820
+ }
1821
+ var BUILTIN_HARNESS_SPECS = [
1822
+ {
1823
+ id: "claude",
1824
+ label: "Claude Code",
1825
+ relScript: ".claude/hooks/feature-guard.mjs",
1826
+ docRel: "AGENTS.md",
1827
+ binding: { configRel: ".claude/settings.local.json", eventKey: "Stop", format: "nested" }
1828
+ },
1829
+ {
1830
+ id: "codex",
1831
+ label: "Codex CLI",
1832
+ relScript: ".codex/hooks/feature-guard.mjs",
1833
+ docRel: "AGENTS.md",
1834
+ binding: { configRel: ".codex/hooks.json", eventKey: "Stop", format: "nested" }
1835
+ },
1836
+ {
1837
+ id: "cursor",
1838
+ label: "Cursor",
1839
+ relScript: ".cursor/hooks/feature-guard.mjs",
1840
+ docRel: "AGENTS.md",
1841
+ binding: { configRel: ".cursor/hooks.json", eventKey: "stop", format: "flat" }
1842
+ },
1843
+ {
1844
+ id: "copilot",
1845
+ label: "GitHub Copilot",
1846
+ relScript: ".github/hooks/feature-guard.mjs",
1847
+ docRel: ".github/copilot-instructions.md"
1848
+ }
1849
+ ];
1850
+ var src_default4 = Plugin.define({
1851
+ id: "featlock.harnesses",
1852
+ async setup(ctx) {
1853
+ await ctx.harness.transform((ed) => {
1854
+ for (const spec of BUILTIN_HARNESS_SPECS)
1855
+ ed.add(makeFileHookHarness(spec));
1856
+ });
1857
+ }
1858
+ });
1859
+
1860
+ // packages/plugins/invariant-passes/src/index.ts
1861
+ function buildPass1Inventory(ctx, registry) {
1862
+ const registeredAreas = new Set(registry.features.map((f) => f.area));
1863
+ const prodFiles = ctx.files.filter((f) => !f.isTest).map((f) => f.rel);
1864
+ return {
1865
+ passId: "pass-1-feature-inventory",
1866
+ title: "Pass 1: Product Feature Surface Discovery",
1867
+ objective: "Identify every user-facing and system-level product capability from routes, CLI commands, exported APIs, jobs, and docs without duplicating existing features.",
1868
+ instructions: [
1869
+ `Already registered areas (${registeredAreas.size}): ${[...registeredAreas].toSorted().join(", ") || "none"}.`,
1870
+ "Run 'featlock check-dup <description>' before proposing any new feature.",
1871
+ "Ignore internal scaffolding; focus on observable behaviors users or downstream callers depend on.",
1872
+ "Record each new feature with concrete acceptance criteria and source evidence."
1873
+ ],
1874
+ targets: prodFiles.slice(0, 60),
1875
+ outputSchema: {
1876
+ features: [{ id: "feat.<area>.<slug>", area: "string", name: "string", summary: "string", acceptanceCriteria: "string" }]
1877
+ }
1878
+ };
1879
+ }
1880
+ function buildPass2TestBinding(ctx, registry) {
1881
+ const linkedPaths = new Set(registry.tests.map((t) => t.testPath));
1882
+ const unlinkedTests = ctx.files.filter((f) => f.isTest && !linkedPaths.has(f.rel)).map((f) => f.rel);
1883
+ const untestedFeatures = registry.features.filter((f) => f.status === "active" && !registry.tests.some((t) => t.featureId === f.id)).map((f) => f.id);
1884
+ return {
1885
+ passId: "pass-2-test-binding",
1886
+ title: "Pass 2: Feature-to-Test Traceability Binding",
1887
+ objective: "Bind every active feature to real, non-skipped tests (R0-R8) and surface untested feature gaps.",
1888
+ instructions: [
1889
+ `Active features lacking linked tests (${untestedFeatures.length}): ${untestedFeatures.join(", ") || "none"}.`,
1890
+ `Unlinked test files (${unlinkedTests.length}): inspect and bind to matching features.`,
1891
+ "Verify each linked test actually exercises the real behavior (not mocked theater)."
1892
+ ],
1893
+ targets: unlinkedTests.slice(0, 60),
1894
+ outputSchema: {
1895
+ links: [{ featureId: "string", testPath: "string", testPattern: "string", rung: "R0|R1|R2|R3|R4|R5|R6|R7|R8" }]
1896
+ }
1897
+ };
1898
+ }
1899
+ function buildPass3InvariantMining(ctx, registry) {
1900
+ const invCount = registry.invariants.filter((i) => i.status === "active").length;
1901
+ const criticalFiles = ctx.files.filter((f) => !f.isTest && /(?:guard|policy|state|machine|schema|auth|billing|payment|registry|pipeline|router|contract)/i.test(f.rel)).map((f) => f.rel);
1902
+ return {
1903
+ passId: "pass-3-invariant-mining",
1904
+ title: "Pass 3: Deep Invariant Mining (AST + RepoSpec + Veristack + Agent)",
1905
+ objective: "Discover hidden behavioral, state-machine, ordering, permission, and persistence invariants that must never regress.",
1906
+ instructions: [
1907
+ `Currently locked active invariants: ${invCount}.`,
1908
+ "Cross-check RepoSpec graphs/SQL rules and Veristack state-machine/law checks with deep code reading.",
1909
+ "For each invariant, state the exact condition that MUST ALWAYS HOLD, exact file:line, and the deterministic guard/test enforcing it.",
1910
+ "Prioritize fail-closed guards, monotonic state transitions, idempotency, anti-deletion locks, and wire-protocol parity."
1911
+ ],
1912
+ targets: (criticalFiles.length > 0 ? criticalFiles : ctx.files.filter((f) => !f.isTest).map((f) => f.rel)).slice(0, 60),
1913
+ outputSchema: {
1914
+ invariants: [{ id: "inv:agent:<slug>", featureId: "string", kind: "string", statement: "string", file: "string", line: 1, confidence: 0.9 }]
1915
+ }
1916
+ };
1917
+ }
1918
+ function buildPass4RegressionAudit(ctx, registry) {
1919
+ return {
1920
+ passId: "pass-4-regression-guard-audit",
1921
+ title: "Pass 4: Regression & Anti-Deletion Guard Verification",
1922
+ objective: "Audit all registered features and invariants for drift, duplicate capabilities, or weakened tests before shipping.",
1923
+ instructions: [
1924
+ `Audit ${registry.features.length} features, ${registry.tests.length} test links, and ${registry.invariants.length} invariants.`,
1925
+ "Run 'featlock check .' and confirm 0 error violations.",
1926
+ "Confirm agent hooks ('featlock hooks status') and CI gates are wired so future agents cannot silently drop features."
1927
+ ],
1928
+ targets: ["features/registry.sql", ...ctx.allRelPaths.filter((p) => /(?:AGENTS\.md|copilot-instructions\.md|rungs\.json)/i.test(p))],
1929
+ outputSchema: {
1930
+ status: "pass|fail",
1931
+ gaps: [{ featureId: "string", gap: "string", recommendedAction: "string" }]
1932
+ }
1933
+ };
1934
+ }
1935
+ var src_default5 = Plugin.define({
1936
+ id: "featlock.invariant-passes",
1937
+ async setup(ctx) {
1938
+ await ctx.agentPass.transform((ed) => {
1939
+ ed.add({ id: "pass-1-inventory", order: 1, title: "Feature Surface Inventory", buildPacket: buildPass1Inventory });
1940
+ ed.add({ id: "pass-2-tests", order: 2, title: "Feature-to-Test Binding", buildPacket: buildPass2TestBinding });
1941
+ ed.add({ id: "pass-3-invariants", order: 3, title: "Deep Invariant Mining", buildPacket: buildPass3InvariantMining });
1942
+ ed.add({ id: "pass-4-audit", order: 4, title: "Regression & Guard Audit", buildPacket: buildPass4RegressionAudit });
1943
+ });
1944
+ }
1945
+ });
1946
+
1947
+ // packages/plugins/registry-cli/src/index.ts
1948
+ function parseFlag(args, flag) {
1949
+ for (let i = 0;i < args.length; i += 1) {
1950
+ const cur = args[i] ?? "";
1951
+ if (cur === flag)
1952
+ return args[i + 1];
1953
+ if (cur.startsWith(`${flag}=`))
1954
+ return cur.slice(flag.length + 1);
1955
+ }
1956
+ return;
1957
+ }
1958
+ function mergeExtraction(existing, extracted) {
1959
+ if (!existing || !extracted)
1960
+ throw new Error("Existing and extracted snapshots are required.");
1961
+ const fMap = new Map(existing.features.map((f) => [f.id, f]));
1962
+ for (const f of extracted.features) {
1963
+ if (!fMap.has(f.id))
1964
+ fMap.set(f.id, f);
1965
+ }
1966
+ const tMap = new Map(existing.tests.map((t) => [`${t.featureId}|${t.testPath}|${t.testPattern}`, t]));
1967
+ for (const t of extracted.tests) {
1968
+ if (!fMap.has(t.featureId))
1969
+ continue;
1970
+ tMap.set(`${t.featureId}|${t.testPath}|${t.testPattern}`, t);
1971
+ }
1972
+ const iMap = new Map(existing.invariants.map((i) => [i.id, i]));
1973
+ for (const inv of extracted.invariants) {
1974
+ const featureId = fMap.has(inv.featureId) ? inv.featureId : extracted.features[0]?.id ?? existing.features[0]?.id;
1975
+ if (!featureId)
1976
+ continue;
1977
+ if (!iMap.has(inv.id))
1978
+ iMap.set(inv.id, { ...inv, featureId });
1979
+ }
1980
+ return {
1981
+ features: [...fMap.values()],
1982
+ tests: [...tMap.values()],
1983
+ invariants: [...iMap.values()],
1984
+ auditLog: [
1985
+ ...existing.auditLog,
1986
+ {
1987
+ featureId: "registry",
1988
+ action: "added",
1989
+ actor: "featlock-extract",
1990
+ summary: `Extracted ${extracted.features.length} feature(s), ${extracted.tests.length} test link(s), ${extracted.invariants.length} invariant(s).`
1991
+ }
1992
+ ]
1993
+ };
1994
+ }
1995
+ async function runExtract(ctx) {
1996
+ const extracted = await ctx.host.extract(ctx.repoRoot);
1997
+ const shouldWrite = ctx.args.includes("--write");
1998
+ if (shouldWrite) {
1999
+ const existing = await ctx.host.readRegistry(ctx.repoRoot);
2000
+ const merged = mergeExtraction(existing, extracted);
2001
+ const sqlPath = await ctx.host.writeRegistry(ctx.repoRoot, merged);
2002
+ if (ctx.asJson) {
2003
+ console.log(JSON.stringify({ sqlPath, extracted, total: { features: merged.features.length, tests: merged.tests.length, invariants: merged.invariants.length } }, null, 2));
2004
+ } else {
2005
+ console.log(`Wrote ${sqlPath}: ${merged.features.length} features, ${merged.tests.length} tests, ${merged.invariants.length} invariants.`);
2006
+ }
2007
+ return 0;
2008
+ }
2009
+ if (ctx.asJson) {
2010
+ console.log(JSON.stringify(extracted, null, 2));
2011
+ } else {
2012
+ console.log(`Extracted ${extracted.features.length} feature(s), ${extracted.tests.length} test link(s), ${extracted.invariants.length} invariant(s).`);
2013
+ for (const f of extracted.features.slice(0, 20))
2014
+ console.log(` - [${f.source}] ${f.id}: ${f.name}`);
2015
+ }
2016
+ return 0;
2017
+ }
2018
+ async function runCheck(ctx) {
2019
+ const allowRemoval = ctx.args.includes("--allow-removal") ? true : undefined;
2020
+ const strictDrift = ctx.args.includes("--strict-drift") ? true : undefined;
2021
+ const res = await ctx.host.check(ctx.repoRoot, allowRemoval !== undefined || strictDrift !== undefined ? { allowRemoval, strictDrift } : undefined);
2022
+ if (ctx.asJson) {
2023
+ console.log(JSON.stringify(res, null, 2));
2024
+ } else {
2025
+ console.log(`featlock check [${res.ok ? "PASS" : "FAIL"}]: ${res.counts.features} features, ${res.counts.tests} tests, ${res.counts.invariants} invariants | ${res.violations.length} error(s), ${res.warnings.length} warning(s)`);
2026
+ for (const v of res.violations)
2027
+ console.error(` [ERROR] ${v.rule}: ${v.message}`);
2028
+ for (const w of res.warnings)
2029
+ console.warn(` [WARN] ${w.rule}: ${w.message}`);
2030
+ }
2031
+ return res.ok ? 0 : 1;
2032
+ }
2033
+ async function runRecordNew(ctx) {
2034
+ const id = parseFlag(ctx.args, "--id");
2035
+ const area = parseFlag(ctx.args, "--area") ?? "core";
2036
+ const name = parseFlag(ctx.args, "--name") ?? id ?? "";
2037
+ const summary = parseFlag(ctx.args, "--summary") ?? name;
2038
+ const criteria = parseFlag(ctx.args, "--criteria") ?? `Verified by linked tests for ${name}.`;
2039
+ const testPath = parseFlag(ctx.args, "--test");
2040
+ const pattern = parseFlag(ctx.args, "--pattern") ?? name;
2041
+ const rung = parseFlag(ctx.args, "--rung") ?? "R2";
2042
+ if (!id || !testPath) {
2043
+ console.error("Usage: featlock record-new --id <id> --name <name> --area <area> --summary <summary> --test <testPath>");
2044
+ return 2;
2045
+ }
2046
+ const snap = await ctx.host.recordNew({
2047
+ repoRoot: ctx.repoRoot,
2048
+ feature: { id, area, name, summary, acceptanceCriteria: criteria, status: "active", source: "manual" },
2049
+ tests: [{ featureId: id, testPath, testPattern: pattern, rung }]
2050
+ });
2051
+ console.log(ctx.asJson ? JSON.stringify({ recorded: id, totalFeatures: snap.features.length }, null, 2) : `Recorded new feature '${id}' with test '${testPath}'.`);
2052
+ return 0;
2053
+ }
2054
+ async function runRecordImprovement(ctx) {
2055
+ const id = parseFlag(ctx.args, "--id");
2056
+ const summary = parseFlag(ctx.args, "--summary");
2057
+ const testPath = parseFlag(ctx.args, "--test");
2058
+ const pattern = parseFlag(ctx.args, "--pattern") ?? summary ?? "improvement";
2059
+ const rung = parseFlag(ctx.args, "--rung") ?? "R2";
2060
+ if (!id || !summary) {
2061
+ console.error("Usage: featlock record-improvement --id <featureId> --summary <summary> [--test <testPath>]");
2062
+ return 2;
2063
+ }
2064
+ const extraTests = testPath ? [{ featureId: id, testPath, testPattern: pattern, rung }] : [];
2065
+ await ctx.host.recordImprovement({ repoRoot: ctx.repoRoot, featureId: id, summary, extraTests });
2066
+ console.log(ctx.asJson ? JSON.stringify({ improved: id, summary }, null, 2) : `Logged improvement to '${id}': ${summary}`);
2067
+ return 0;
2068
+ }
2069
+ async function runHooks(ctx) {
2070
+ const action = ctx.args[0] ?? "status";
2071
+ const harnesses = ctx.host.getHarnesses();
2072
+ if (action === "on") {
2073
+ const installed = {};
2074
+ for (const h of harnesses)
2075
+ installed[h.id] = await h.install(ctx.repoRoot);
2076
+ console.log(ctx.asJson ? JSON.stringify({ action: "on", installed }, null, 2) : `Installed FeatLock hooks for: ${harnesses.map((h) => h.id).join(", ")}`);
2077
+ return 0;
2078
+ }
2079
+ if (action === "off") {
2080
+ const removed = {};
2081
+ for (const h of harnesses)
2082
+ removed[h.id] = await h.uninstall(ctx.repoRoot);
2083
+ console.log(ctx.asJson ? JSON.stringify({ action: "off", removed }, null, 2) : `Removed FeatLock hooks for: ${harnesses.map((h) => h.id).join(", ")}`);
2084
+ return 0;
2085
+ }
2086
+ const statuses = [];
2087
+ for (const h of harnesses) {
2088
+ const st = await h.status(ctx.repoRoot);
2089
+ statuses.push({ id: h.id, ...st });
2090
+ }
2091
+ if (ctx.asJson)
2092
+ console.log(JSON.stringify({ harnesses: statuses }, null, 2));
2093
+ else
2094
+ for (const st of statuses)
2095
+ console.log(` - ${st.id}: ${st.detail}`);
2096
+ return 0;
2097
+ }
2098
+ async function runSync(c) {
2099
+ const out = await c.host.sync(c.repoRoot);
2100
+ console.log(c.asJson ? JSON.stringify(out, null, 2) : `Synced ${out.dbPath} (${out.counts.features} features, ${out.counts.tests} tests, ${out.counts.invariants} invariants).`);
2101
+ return 0;
2102
+ }
2103
+ async function runQuery(c) {
2104
+ const term = c.args.filter((a) => !a.startsWith("-")).join(" ");
2105
+ const matches = await c.host.query(c.repoRoot, term);
2106
+ console.log(c.asJson ? JSON.stringify({ term, matches }, null, 2) : matches.map((m) => `${m.id} [${m.status}] ${m.name} \u2014 ${m.summary}`).join(`
2107
+ `) || "No matching features.");
2108
+ return 0;
2109
+ }
2110
+ async function runCheckDup(c) {
2111
+ const desc = c.args.filter((a) => !a.startsWith("-")).join(" ");
2112
+ const dups = await c.host.checkDup(c.repoRoot, desc);
2113
+ console.log(c.asJson ? JSON.stringify({ description: desc, duplicates: dups }, null, 2) : dups.map((d) => `${d.featureId} (score=${d.score}) \u2014 ${d.name} [${d.matchedTokens.join(", ")}]`).join(`
2114
+ `) || "No overlapping features detected.");
2115
+ return 0;
2116
+ }
2117
+ async function runAgentPass(c) {
2118
+ const packets = await c.host.buildAgentPasses(c.repoRoot);
2119
+ console.log(c.asJson ? JSON.stringify({ passes: packets }, null, 2) : packets.map((p) => `[${p.passId}] ${p.title} (${p.targets.length} targets)
2120
+ ${p.objective}`).join(`
2121
+
2122
+ `));
2123
+ return 0;
2124
+ }
2125
+ async function runPluginsList(c) {
2126
+ const list = c.host.listPlugins();
2127
+ console.log(c.asJson ? JSON.stringify({ plugins: list }, null, 2) : list.map((p) => `${p.id} [${p.state.status}] (${p.source}${p.guarded ? ", guarded" : ""})`).join(`
2128
+ `));
2129
+ return 0;
2130
+ }
2131
+ var src_default6 = Plugin.define({
2132
+ id: "featlock.registry-cli",
2133
+ async setup(ctx) {
2134
+ await ctx.command.transform((ed) => {
2135
+ ed.add({ id: "extract", description: "Extract features, tests & invariants (AST + RepoSpec + Veristack) [--write]", run: runExtract });
2136
+ ed.add({ id: "check", description: "Verify feature coverage, invariant liveness & anti-deletion guards", run: runCheck });
2137
+ ed.add({ id: "sync", description: "Materialize .featlock/registry.sqlite from features/registry.sql", run: runSync });
2138
+ ed.add({ id: "query", description: "Search registered features by keyword", run: runQuery });
2139
+ ed.add({ id: "check-dup", description: "Check whether a proposed feature overlaps an existing registered feature", run: runCheckDup });
2140
+ ed.add({ id: "record-new", description: "Record a newly added feature + linked test in features/registry.sql", run: runRecordNew });
2141
+ ed.add({ id: "record-improvement", description: "Log an improvement to an existing feature in features/registry.sql", run: runRecordImprovement });
2142
+ ed.add({ id: "agent-pass", description: "Emit structured multi-pass AI agent investigation packets for invariant discovery", run: runAgentPass });
2143
+ ed.add({ id: "hooks", description: "Install, remove, or inspect coding agent guard hooks (on|off|status)", run: runHooks });
2144
+ ed.add({ id: "plugins", description: "List active and failed FeatLock plugins", run: runPluginsList });
2145
+ });
2146
+ }
2147
+ });
2148
+
2149
+ // packages/plugins/repospec-bridge/src/index.ts
2150
+ import { Database as Database3 } from "bun:sqlite";
2151
+ import fs5 from "fs";
2152
+ import path7 from "path";
2153
+ function slugify(raw) {
2154
+ return raw.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64);
2155
+ }
2156
+ function findRepoSpecDb(repoRoot) {
2157
+ const candidates = [
2158
+ path7.join(repoRoot, "repospec.sqlite"),
2159
+ path7.join(repoRoot, ".repospec", "repospec.sqlite"),
2160
+ path7.join(repoRoot, "out", path7.basename(repoRoot), "repospec.sqlite")
2161
+ ];
2162
+ for (const c of candidates) {
2163
+ if (fs5.existsSync(c))
2164
+ return c;
2165
+ }
2166
+ return null;
2167
+ }
2168
+ function findRepoSpecJson(repoRoot) {
2169
+ const candidates = [
2170
+ path7.join(repoRoot, "repospec.json"),
2171
+ path7.join(repoRoot, ".repospec", "repospec.json"),
2172
+ path7.join(repoRoot, "out", path7.basename(repoRoot), "repospec.json")
2173
+ ];
2174
+ for (const c of candidates) {
2175
+ if (fs5.existsSync(c))
2176
+ return c;
2177
+ }
2178
+ return null;
2179
+ }
2180
+ function extractFromSqlite(dbPath) {
2181
+ if (!dbPath)
2182
+ throw new Error("RepoSpec SQLite path is required.");
2183
+ const db = new Database3(dbPath, { readonly: true });
2184
+ const features = [];
2185
+ const tests = [];
2186
+ const invariants = [];
2187
+ try {
2188
+ const tables = new Set(db.query("SELECT name FROM sqlite_master WHERE type='table'").all().map((r) => r.name));
2189
+ if (tables.has("module_cards")) {
2190
+ const rows = db.query("SELECT id, name, unit FROM module_cards ORDER BY id LIMIT 60").all();
2191
+ for (const r of rows) {
2192
+ features.push({
2193
+ id: `feat.rs.${slugify(r.id)}`,
2194
+ area: r.unit || "repospec",
2195
+ name: r.name || r.id,
2196
+ summary: `RepoSpec compiled module '${r.id}' in unit '${r.unit}'.`,
2197
+ acceptanceCriteria: `Module boundary and public API of '${r.id}' remain intact with zero RepoSpec invariant regressions.`,
2198
+ status: "active",
2199
+ source: "repospec"
2200
+ });
2201
+ }
2202
+ }
2203
+ if (tables.has("invariants")) {
2204
+ const rows = db.query("SELECT id, name, statement, status FROM invariants ORDER BY id LIMIT 60").all();
2205
+ for (const r of rows) {
2206
+ invariants.push({
2207
+ id: `inv:repospec:${slugify(r.id)}`,
2208
+ featureId: features[0]?.id ?? "feat.repospec-architecture",
2209
+ kind: "repospec-sql-invariant",
2210
+ statement: r.statement || r.name || r.id,
2211
+ file: path7.basename(dbPath),
2212
+ line: 1,
2213
+ confidence: 0.95,
2214
+ source: "repospec",
2215
+ guardRef: r.id,
2216
+ status: "active"
2217
+ });
2218
+ }
2219
+ }
2220
+ } finally {
2221
+ db.close();
2222
+ }
2223
+ return { features, tests, invariants };
2224
+ }
2225
+ function extractFromJson(jsonPath) {
2226
+ if (!jsonPath)
2227
+ throw new Error("RepoSpec JSON path is required.");
2228
+ const raw = JSON.parse(fs5.readFileSync(jsonPath, "utf8"));
2229
+ const features = [];
2230
+ const invariants = [];
2231
+ for (const ep of (raw.surfaces?.endpoints ?? []).slice(0, 40)) {
2232
+ const key = `${ep.method ?? "GET"} ${ep.path ?? "/"}`;
2233
+ features.push({
2234
+ id: `feat.http.${slugify(key)}`,
2235
+ area: "http-surface",
2236
+ name: `HTTP ${key}`,
2237
+ summary: `RepoSpec reconciled HTTP surface ${key}${ep.file ? ` (${ep.file})` : ""}.`,
2238
+ acceptanceCriteria: `Endpoint ${key} preserves contract shape and handler provenance.`,
2239
+ status: "active",
2240
+ source: "repospec"
2241
+ });
2242
+ }
2243
+ for (const sm of (raw.stateMachines ?? []).slice(0, 40)) {
2244
+ const name = sm.name ?? sm.id ?? "state-machine";
2245
+ invariants.push({
2246
+ id: `inv:repospec:sm:${slugify(name)}`,
2247
+ featureId: features[0]?.id ?? "feat.repospec-architecture",
2248
+ kind: "state-machine",
2249
+ statement: `State machine '${name}' preserves declared transitions and guards.`,
2250
+ file: sm.file ?? "repospec.json",
2251
+ line: sm.line ?? 1,
2252
+ confidence: 0.92,
2253
+ source: "repospec",
2254
+ status: "active"
2255
+ });
2256
+ }
2257
+ for (const inv of (raw.invariants ?? []).slice(0, 60)) {
2258
+ invariants.push({
2259
+ id: `inv:repospec:${slugify(inv.id)}`,
2260
+ featureId: features[0]?.id ?? "feat.repospec-architecture",
2261
+ kind: "repospec-sql-invariant",
2262
+ statement: inv.statement ?? inv.name ?? inv.id,
2263
+ file: path7.basename(jsonPath),
2264
+ line: 1,
2265
+ confidence: 0.95,
2266
+ source: "repospec",
2267
+ guardRef: inv.id,
2268
+ status: "active"
2269
+ });
2270
+ }
2271
+ return { features, tests: [], invariants };
2272
+ }
2273
+ function extractRepoSpecArtifacts(ctx) {
2274
+ const dbPath = findRepoSpecDb(ctx.repoRoot);
2275
+ if (dbPath)
2276
+ return extractFromSqlite(dbPath);
2277
+ const jsonPath = findRepoSpecJson(ctx.repoRoot);
2278
+ if (jsonPath)
2279
+ return extractFromJson(jsonPath);
2280
+ const sqlRuleFiles = ctx.files.filter((f) => f.ext === ".sql" && /(?:^|\/)rules\//.test(f.rel));
2281
+ const invariants = [];
2282
+ for (const rf of sqlRuleFiles) {
2283
+ const idMatch = /@id:\s*([^\n]+)/.exec(rf.content);
2284
+ const stmtMatch = /@statement:\s*([^\n]+)/.exec(rf.content);
2285
+ if (!idMatch?.[1])
2286
+ continue;
2287
+ invariants.push({
2288
+ id: `inv:repospec-rule:${slugify(idMatch[1].trim())}`,
2289
+ featureId: "feat.repospec-rules",
2290
+ kind: "repospec-sql-rule",
2291
+ statement: (stmtMatch?.[1] ?? idMatch[1]).trim(),
2292
+ file: rf.rel,
2293
+ line: 1,
2294
+ confidence: 0.96,
2295
+ source: "repospec",
2296
+ guardRef: rf.rel,
2297
+ status: "active"
2298
+ });
2299
+ }
2300
+ return { features: [], tests: [], invariants };
2301
+ }
2302
+ var src_default7 = Plugin.define({
2303
+ id: "featlock.repospec-bridge",
2304
+ async setup(ctx) {
2305
+ await ctx.extractor.transform((ed) => {
2306
+ ed.add({
2307
+ id: "featlock.repospec-bridge.extractor",
2308
+ label: "RepoSpec SQLite/JSON/SQL-Rule Bridge",
2309
+ extract: extractRepoSpecArtifacts
2310
+ });
2311
+ });
2312
+ await ctx.invariantScanner.transform((ed) => {
2313
+ ed.add({
2314
+ id: "featlock.repospec-bridge.invariants",
2315
+ source: "repospec",
2316
+ scan: (scanCtx) => extractRepoSpecArtifacts(scanCtx).invariants
2317
+ });
2318
+ });
2319
+ }
2320
+ });
2321
+
2322
+ // packages/plugins/veristack-bridge/src/index.ts
2323
+ import fs6 from "fs";
2324
+ import path8 from "path";
2325
+ function slugify2(raw) {
2326
+ return raw.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64);
2327
+ }
2328
+ function scanControlPlan(repoRoot) {
2329
+ if (!repoRoot)
2330
+ throw new Error("repoRoot is required.");
2331
+ const planPath = path8.join(repoRoot, ".verification", "control-plan.json");
2332
+ if (!fs6.existsSync(planPath))
2333
+ return [];
2334
+ const raw = JSON.parse(fs6.readFileSync(planPath, "utf8"));
2335
+ const out = [];
2336
+ for (const c of raw.controls ?? []) {
2337
+ if (!c.id)
2338
+ continue;
2339
+ out.push({
2340
+ id: `inv:veristack:cp:${slugify2(c.id)}`,
2341
+ featureId: `feat.${slugify2(c.seam ?? c.id)}`,
2342
+ kind: "veristack-control-plan",
2343
+ statement: `${c.seam ?? c.id}: prevent ${c.failureMode ?? "regression"}`,
2344
+ file: c.controlRef ?? ".verification/control-plan.json",
2345
+ line: 1,
2346
+ confidence: 0.98,
2347
+ source: "veristack",
2348
+ guardRef: c.reqId ?? c.id,
2349
+ status: "active"
2350
+ });
2351
+ }
2352
+ return out;
2353
+ }
2354
+ function scanLawsFiles(repoRoot) {
2355
+ const lawsDir = path8.join(repoRoot, ".verification", "laws");
2356
+ if (!fs6.existsSync(lawsDir))
2357
+ return [];
2358
+ const out = [];
2359
+ for (const entry of fs6.readdirSync(lawsDir).filter((f) => f.endsWith(".laws.json")).toSorted()) {
2360
+ const abs = path8.join(lawsDir, entry);
2361
+ const raw = JSON.parse(fs6.readFileSync(abs, "utf8"));
2362
+ for (const law of raw.laws ?? []) {
2363
+ if (!law.id)
2364
+ continue;
2365
+ out.push({
2366
+ id: `inv:veristack:law:${slugify2(law.id)}`,
2367
+ featureId: "feat.veristack-laws",
2368
+ kind: "veristack-formal-law",
2369
+ statement: law.statement ?? law.description ?? law.name ?? law.id,
2370
+ file: `.verification/laws/${entry}`,
2371
+ line: 1,
2372
+ confidence: 0.99,
2373
+ source: "veristack",
2374
+ guardRef: law.witness ?? law.id,
2375
+ status: "active"
2376
+ });
2377
+ }
2378
+ }
2379
+ return out;
2380
+ }
2381
+ function scanRungManifest(repoRoot) {
2382
+ const rungsPath = path8.join(repoRoot, ".verification", "rungs.json");
2383
+ if (!fs6.existsSync(rungsPath))
2384
+ return [];
2385
+ const raw = JSON.parse(fs6.readFileSync(rungsPath, "utf8"));
2386
+ const out = [];
2387
+ for (const [rungId, entry] of Object.entries(raw.rungs ?? {})) {
2388
+ if (!entry?.command)
2389
+ continue;
2390
+ out.push({
2391
+ id: `inv:veristack:rung:${slugify2(rungId)}`,
2392
+ featureId: "feat.verification-ladder",
2393
+ kind: "veristack-rung-gate",
2394
+ statement: `Verification rung ${rungId} remains wired and passing (${entry.command}).`,
2395
+ file: ".verification/rungs.json",
2396
+ line: 1,
2397
+ confidence: 0.97,
2398
+ source: "veristack",
2399
+ guardRef: rungId,
2400
+ status: "active"
2401
+ });
2402
+ }
2403
+ return out;
2404
+ }
2405
+ function scanVeristackArtifacts(ctx) {
2406
+ return [
2407
+ ...scanControlPlan(ctx.repoRoot),
2408
+ ...scanLawsFiles(ctx.repoRoot),
2409
+ ...scanRungManifest(ctx.repoRoot)
2410
+ ];
2411
+ }
2412
+ var src_default8 = Plugin.define({
2413
+ id: "featlock.veristack-bridge",
2414
+ async setup(ctx) {
2415
+ await ctx.invariantScanner.transform((ed) => {
2416
+ ed.add({
2417
+ id: "featlock.veristack-bridge.invariants",
2418
+ source: "veristack",
2419
+ scan: scanVeristackArtifacts
2420
+ });
2421
+ });
2422
+ }
2423
+ });
2424
+
2425
+ // packages/core/src/plugin/internal.ts
2426
+ var pre = [
2427
+ src_default2,
2428
+ src_default7,
2429
+ src_default8,
2430
+ src_default5,
2431
+ src_default,
2432
+ src_default4,
2433
+ src_default6
2434
+ ];
2435
+ var post = [src_default3];
2436
+ var GUARDED_PLUGIN_IDS = new Set([
2437
+ src_default.id
2438
+ ]);
2439
+ function getBuiltinPlugins() {
2440
+ return { pre, post };
2441
+ }
2442
+
2443
+ // packages/core/src/plugin/host.ts
2444
+ function createHostDomains() {
2445
+ return {
2446
+ extractors: State.createKeyedDomain("extractor"),
2447
+ scanners: State.createKeyedDomain("invariantScanner"),
2448
+ guards: State.createKeyedDomain("guard"),
2449
+ passes: State.createKeyedDomain("agentPass"),
2450
+ harnesses: State.createKeyedDomain("harness"),
2451
+ reporters: State.createKeyedDomain("reporter"),
2452
+ commands: State.createKeyedDomain("command"),
2453
+ checkHooks: State.createKeyedDomain("checkHook"),
2454
+ slots: new Map,
2455
+ hookSeq: 0
2456
+ };
2457
+ }
2458
+ function matchesSelector(selector, id) {
2459
+ if (selector === "*")
2460
+ return true;
2461
+ if (selector.endsWith(".*"))
2462
+ return id.startsWith(selector.slice(0, -1));
2463
+ return selector === id;
2464
+ }
2465
+ async function resolveExternalPlugin(target) {
2466
+ if (!target)
2467
+ throw new Error("Plugin target path is required.");
2468
+ const abs = path9.resolve(target);
2469
+ let entryFile = abs;
2470
+ if (fs7.existsSync(abs) && fs7.statSync(abs).isDirectory()) {
2471
+ const pkgFile = path9.join(abs, "package.json");
2472
+ if (fs7.existsSync(pkgFile)) {
2473
+ const pkg = JSON.parse(fs7.readFileSync(pkgFile, "utf8"));
2474
+ const dotExport = typeof pkg.exports === "string" ? pkg.exports : pkg.exports?.["."];
2475
+ const relEntry = typeof dotExport === "string" ? dotExport : typeof dotExport === "object" && dotExport !== null ? dotExport.import ?? dotExport.default ?? pkg.main ?? "index.ts" : pkg.main ?? "index.ts";
2476
+ entryFile = path9.resolve(abs, relEntry);
2477
+ } else {
2478
+ entryFile = path9.join(abs, "index.ts");
2479
+ }
2480
+ }
2481
+ const mod = await import(pathToFileURL(entryFile).href);
2482
+ const candidate = mod.default ?? mod.plugin;
2483
+ if (!isFeatlockPlugin(candidate)) {
2484
+ throw new Error(`Module '${target}' did not export a valid FeatLock plugin.`);
2485
+ }
2486
+ return candidate;
2487
+ }
2488
+ function makeDomainHandle(state, cleanups) {
2489
+ return {
2490
+ transform: async (cb) => {
2491
+ const reg = state.transform(cb);
2492
+ cleanups.push(reg.dispose);
2493
+ return reg;
2494
+ },
2495
+ reload: async () => {
2496
+ state.reload();
2497
+ }
2498
+ };
2499
+ }
2500
+ async function disposeSlot(slot) {
2501
+ for (const cleanup of slot.cleanups.toReversed()) {
2502
+ try {
2503
+ await cleanup();
2504
+ } catch {
2505
+ continue;
2506
+ }
2507
+ }
2508
+ slot.cleanups.length = 0;
2509
+ }
2510
+ async function disposeAllSlots(domains) {
2511
+ for (const slot of Array.from(domains.slots.values()).toReversed()) {
2512
+ await disposeSlot(slot);
2513
+ }
2514
+ domains.slots.clear();
2515
+ }
2516
+ function buildPluginContext(domains, opts, plugin, cleanups) {
2517
+ return {
2518
+ options: opts.optionsByPlugin?.[plugin.id] ?? {},
2519
+ extractor: makeDomainHandle(domains.extractors, cleanups),
2520
+ invariantScanner: makeDomainHandle(domains.scanners, cleanups),
2521
+ guard: makeDomainHandle(domains.guards, cleanups),
2522
+ agentPass: makeDomainHandle(domains.passes, cleanups),
2523
+ harness: makeDomainHandle(domains.harnesses, cleanups),
2524
+ reporter: makeDomainHandle(domains.reporters, cleanups),
2525
+ command: makeDomainHandle(domains.commands, cleanups),
2526
+ check: {
2527
+ hook: async (name, handler) => {
2528
+ const id = `${plugin.id}:hook:${++domains.hookSeq}`;
2529
+ const reg = domains.checkHooks.transform((ed) => ed.add({ id, name, handler }));
2530
+ cleanups.push(reg.dispose);
2531
+ return reg;
2532
+ }
2533
+ }
2534
+ };
2535
+ }
2536
+ async function mountPluginSlot(domains, opts, plugin, source) {
2537
+ if (!plugin.id)
2538
+ throw new Error("Plugin id is required.");
2539
+ const guarded = plugin.guarded === true || GUARDED_PLUGIN_IDS.has(plugin.id);
2540
+ const cleanups = [];
2541
+ const slot = { id: plugin.id, source, guarded, cleanups, lifecycle: { status: "active", group: null } };
2542
+ domains.slots.set(plugin.id, slot);
2543
+ const ctx = buildPluginContext(domains, opts, plugin, cleanups);
2544
+ try {
2545
+ const { group, result } = await State.groupAsync((failure) => {
2546
+ slot.lifecycle = {
2547
+ status: "failed",
2548
+ error: failure.cause instanceof Error ? failure.cause.message : String(failure.cause)
2549
+ };
2550
+ }, async () => await plugin.setup(ctx));
2551
+ if (typeof result === "function")
2552
+ cleanups.push(result);
2553
+ if (slot.lifecycle.status === "active")
2554
+ slot.lifecycle = { status: "active", group };
2555
+ domains.extractors.get();
2556
+ domains.scanners.get();
2557
+ domains.guards.get();
2558
+ domains.passes.get();
2559
+ domains.harnesses.get();
2560
+ domains.reporters.get();
2561
+ domains.commands.get();
2562
+ domains.checkHooks.get();
2563
+ } catch (err) {
2564
+ slot.lifecycle = { status: "failed", error: err instanceof Error ? err.message : String(err) };
2565
+ await disposeSlot(slot);
2566
+ }
2567
+ }
2568
+ async function activatePlugins(domains, opts, extraPlugins, operations) {
2569
+ if (!domains)
2570
+ throw new Error("HostDomains instance is required.");
2571
+ await disposeAllSlots(domains);
2572
+ const builtins = opts.includeBuiltins === false ? { pre: [], post: [] } : getBuiltinPlugins();
2573
+ const entries = [
2574
+ ...builtins.pre.map((plugin) => ({ plugin, source: "builtin" })),
2575
+ ...extraPlugins.filter(isFeatlockPlugin).map((plugin) => ({ plugin, source: "inline" }))
2576
+ ];
2577
+ for (const op of operations) {
2578
+ if (op.type !== "add" || entries.some((e) => e.plugin.id === op.target))
2579
+ continue;
2580
+ try {
2581
+ entries.push({ plugin: await resolveExternalPlugin(op.target), source: "package" });
2582
+ } catch (err) {
2583
+ domains.slots.set(op.target, {
2584
+ id: op.target,
2585
+ source: "package",
2586
+ guarded: false,
2587
+ cleanups: [],
2588
+ lifecycle: { status: "failed", error: err instanceof Error ? err.message : String(err) }
2589
+ });
2590
+ }
2591
+ }
2592
+ entries.push(...builtins.post.map((plugin) => ({ plugin, source: "builtin" })));
2593
+ const removedSelectors = operations.filter((o) => o.type === "remove").map((o) => o.target);
2594
+ const activeEntries = entries.filter((entry) => {
2595
+ const isGuarded = entry.plugin.guarded === true || GUARDED_PLUGIN_IDS.has(entry.plugin.id);
2596
+ if (isGuarded)
2597
+ return true;
2598
+ return !removedSelectors.some((sel) => matchesSelector(sel, entry.plugin.id));
2599
+ });
2600
+ for (const entry of activeEntries)
2601
+ await mountPluginSlot(domains, opts, entry.plugin, entry.source);
2602
+ }
2603
+ async function runExtractWithScan(domains, scanCtx) {
2604
+ const featuresMap = new Map;
2605
+ const testsMap = new Map;
2606
+ const invariantsMap = new Map;
2607
+ for (const ext of domains.extractors.get()) {
2608
+ const out = await ext.extract(scanCtx);
2609
+ for (const f of out.features)
2610
+ featuresMap.set(f.id, f);
2611
+ for (const t of out.tests)
2612
+ testsMap.set(`${t.featureId}|${t.testPath}|${t.testPattern}`, t);
2613
+ for (const inv of out.invariants)
2614
+ invariantsMap.set(inv.id, inv);
2615
+ }
2616
+ for (const scanner of domains.scanners.get()) {
2617
+ for (const inv of await scanner.scan(scanCtx))
2618
+ invariantsMap.set(inv.id, inv);
2619
+ }
2620
+ return {
2621
+ features: Array.from(featuresMap.values()).toSorted((a, b) => a.id.localeCompare(b.id)),
2622
+ tests: Array.from(testsMap.values()),
2623
+ invariants: Array.from(invariantsMap.values()).toSorted((a, b) => a.id.localeCompare(b.id))
2624
+ };
2625
+ }
2626
+ async function runExtract2(domains, repoDir) {
2627
+ return await runExtractWithScan(domains, discoverRepo(repoDir));
2628
+ }
2629
+ async function runCheck2(domains, repoDir, checkOpts) {
2630
+ if (!repoDir)
2631
+ throw new Error("repoDir is required for featlock check.");
2632
+ const scanCtx = discoverRepo(repoDir);
2633
+ const registry = Registry.readRepo(scanCtx.repoRoot);
2634
+ const liveExtraction = await runExtractWithScan(domains, scanCtx);
2635
+ const ctx = {
2636
+ repoRoot: scanCtx.repoRoot,
2637
+ registryPath: path9.join(scanCtx.repoRoot, REGISTRY_SQL_REL),
2638
+ registry,
2639
+ previousRegistry: Registry.readHead(scanCtx.repoRoot),
2640
+ stagedFiles: listStagedFiles(scanCtx.repoRoot),
2641
+ allowRemoval: checkOpts?.allowRemoval ?? process.env.ALLOW_FEATURE_REMOVAL === "1",
2642
+ strictDrift: checkOpts?.strictDrift ?? false,
2643
+ liveExtraction,
2644
+ files: scanCtx.files
2645
+ };
2646
+ const violations = [];
2647
+ const beforeEvent = { repoRoot: scanCtx.repoRoot, violations };
2648
+ for (const h of domains.checkHooks.get().filter((x) => x.name === "beforeCheck"))
2649
+ await h.handler(beforeEvent);
2650
+ for (const guard of domains.guards.get())
2651
+ violations.push(...await guard.evaluate(ctx));
2652
+ const afterEvent = { repoRoot: scanCtx.repoRoot, violations };
2653
+ for (const h of domains.checkHooks.get().filter((x) => x.name === "afterCheck"))
2654
+ await h.handler(afterEvent);
2655
+ const errors = violations.filter((v) => v.severity === "error");
2656
+ const warnings = violations.filter((v) => v.severity === "warn");
2657
+ return { ok: errors.length === 0, violations: errors, warnings, counts: Registry.count(registry) };
2658
+ }
2659
+ async function runBuildAgentPasses(domains, repoDir) {
2660
+ const scanCtx = discoverRepo(repoDir);
2661
+ const registry = Registry.readRepo(scanCtx.repoRoot);
2662
+ const packets = [];
2663
+ for (const p of domains.passes.get().toSorted((a, b) => a.order - b.order)) {
2664
+ packets.push(await p.buildPacket(scanCtx, registry));
2665
+ }
2666
+ return packets;
2667
+ }
2668
+ async function runCliCommand(domains, facade, argv, repoRoot) {
2669
+ const cmdName = argv[0];
2670
+ if (!cmdName || cmdName === "-h" || cmdName === "--help") {
2671
+ console.log(`featlock \u2014 Tight-core SQLite feature, test & invariant guard
2672
+ `);
2673
+ for (const cmd of domains.commands.get())
2674
+ console.log(` featlock ${cmd.id.padEnd(20)} ${cmd.description}`);
2675
+ return 0;
2676
+ }
2677
+ const found = domains.commands.get().find((c) => c.id === cmdName);
2678
+ if (!found) {
2679
+ console.error(`Unknown featlock command: ${cmdName}`);
2680
+ return 2;
2681
+ }
2682
+ const rest = argv.slice(1);
2683
+ return await found.run({ repoRoot: path9.resolve(repoRoot), args: rest, asJson: rest.includes("--json"), host: facade });
2684
+ }
2685
+ async function createPluginHost(opts = {}) {
2686
+ if (!opts)
2687
+ throw new Error("PluginHostOptions must be defined.");
2688
+ const domains = createHostDomains();
2689
+ const list = () => Array.from(domains.slots.values()).map((s) => ({
2690
+ id: s.id,
2691
+ source: s.source,
2692
+ state: s.lifecycle.status === "active" ? { status: "active" } : { status: "failed", error: s.lifecycle.error },
2693
+ guarded: s.guarded
2694
+ }));
2695
+ const facade = {
2696
+ listPlugins: list,
2697
+ extract: (repoDir) => runExtract2(domains, repoDir),
2698
+ check: (repoDir, checkOpts) => runCheck2(domains, repoDir, checkOpts),
2699
+ sync: async (repoDir) => {
2700
+ const out = Registry.materializeDb(path9.resolve(repoDir));
2701
+ return { sqlPath: out.sqlPath, dbPath: out.dbPath, counts: out.counts };
2702
+ },
2703
+ query: async (repoDir, term) => Registry.queryFeatures(Registry.readRepo(path9.resolve(repoDir)), term),
2704
+ checkDup: async (repoDir, description) => Registry.findDuplicates(Registry.readRepo(path9.resolve(repoDir)), description),
2705
+ recordNew: async (input) => Registry.recordNew({ ...input, repoRoot: path9.resolve(input.repoRoot) }),
2706
+ recordImprovement: async (input) => Registry.recordImprovement({ ...input, repoRoot: path9.resolve(input.repoRoot) }),
2707
+ writeRegistry: async (repoDir, snapshot) => {
2708
+ const sqlPath = Registry.writeSql(path9.resolve(repoDir), snapshot);
2709
+ Registry.materializeDb(path9.resolve(repoDir));
2710
+ return sqlPath;
2711
+ },
2712
+ readRegistry: async (repoDir) => Registry.readRepo(path9.resolve(repoDir)),
2713
+ buildAgentPasses: (repoDir) => runBuildAgentPasses(domains, repoDir),
2714
+ getHarnesses: () => domains.harnesses.get(),
2715
+ getCommands: () => domains.commands.get(),
2716
+ getReporters: () => domains.reporters.get()
2717
+ };
2718
+ await activatePlugins(domains, opts, opts.plugins ?? [], opts.operations ?? []);
2719
+ return {
2720
+ ...facade,
2721
+ list,
2722
+ activate: (extraPlugins, operations = []) => activatePlugins(domains, opts, extraPlugins, operations),
2723
+ dispose: () => disposeAllSlots(domains),
2724
+ runCli: (argv, repoRoot = process.cwd()) => runCliCommand(domains, facade, argv, repoRoot)
2725
+ };
2726
+ }
2727
+ // src/cli.ts
2728
+ var REPO_SCOPED_COMMANDS = new Set(["extract", "check", "sync", "agent-pass", "hooks", "plugins"]);
2729
+ function loadRepoOperations(repoDir) {
2730
+ const cfgPath = path10.join(repoDir, ".featlock", "config.json");
2731
+ if (!fs8.existsSync(cfgPath))
2732
+ return [];
2733
+ const raw = JSON.parse(fs8.readFileSync(cfgPath, "utf8"));
2734
+ const ops = [];
2735
+ for (const p of raw.plugins ?? [])
2736
+ ops.push({ type: "add", target: path10.isAbsolute(p) ? p : path10.resolve(repoDir, p) });
2737
+ for (const r of raw.remove ?? [])
2738
+ ops.push({ type: "remove", target: r });
2739
+ return ops;
2740
+ }
2741
+ function parseCliArgs(rawArgs) {
2742
+ const extraOps = [];
2743
+ const cleanedArgs = [];
2744
+ let explicitRepo = null;
2745
+ for (let i = 0;i < rawArgs.length; i += 1) {
2746
+ const cur = rawArgs[i] ?? "";
2747
+ if (cur === "--plugin" && rawArgs[i + 1]) {
2748
+ extraOps.push({ type: "add", target: rawArgs[i + 1] ?? "" });
2749
+ i += 1;
2750
+ } else if (cur === "--remove-plugin" && rawArgs[i + 1]) {
2751
+ extraOps.push({ type: "remove", target: rawArgs[i + 1] ?? "" });
2752
+ i += 1;
2753
+ } else if ((cur === "--repo" || cur === "-C") && rawArgs[i + 1]) {
2754
+ explicitRepo = rawArgs[i + 1] ?? null;
2755
+ i += 1;
2756
+ } else if (cur.startsWith("--repo=")) {
2757
+ explicitRepo = cur.slice("--repo=".length);
2758
+ } else {
2759
+ cleanedArgs.push(cur);
2760
+ }
2761
+ }
2762
+ return { extraOps, cleanedArgs, explicitRepo };
2763
+ }
2764
+ function resolveTargetRepoDir(cleanedArgs, explicitRepo) {
2765
+ if (explicitRepo)
2766
+ return path10.resolve(explicitRepo);
2767
+ const cmd = cleanedArgs[0] ?? "";
2768
+ if (!REPO_SCOPED_COMMANDS.has(cmd))
2769
+ return process.cwd();
2770
+ const targetArg = cleanedArgs.find((a, idx) => idx > 0 && !a.startsWith("-"));
2771
+ if (targetArg && fs8.existsSync(targetArg) && fs8.statSync(targetArg).isDirectory()) {
2772
+ return path10.resolve(targetArg);
2773
+ }
2774
+ return process.cwd();
2775
+ }
2776
+ var { extraOps, cleanedArgs, explicitRepo } = parseCliArgs(process.argv.slice(2));
2777
+ var repoDir = resolveTargetRepoDir(cleanedArgs, explicitRepo);
2778
+ var host = await createPluginHost({
2779
+ repoDir,
2780
+ includeBuiltins: true,
2781
+ operations: [...loadRepoOperations(repoDir), ...extraOps]
2782
+ });
2783
+ try {
2784
+ process.exitCode = await host.runCli(cleanedArgs, repoDir);
2785
+ } finally {
2786
+ await host.dispose();
2787
+ }