@triedotdev/mcp 1.0.101 → 1.0.103

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +21 -60
  2. package/dist/{chunk-OVRG5RP3.js → chunk-33WL3D7A.js} +3 -5
  3. package/dist/{chunk-OVRG5RP3.js.map → chunk-33WL3D7A.js.map} +1 -1
  4. package/dist/{chunk-JDHR5BDR.js → chunk-6JPPYG7F.js} +928 -258
  5. package/dist/chunk-6JPPYG7F.js.map +1 -0
  6. package/dist/{chunk-M4JCQO5G.js → chunk-CKYU5JOD.js} +579 -114
  7. package/dist/chunk-CKYU5JOD.js.map +1 -0
  8. package/dist/{chunk-B3MNN3XB.js → chunk-HFKOGW7H.js} +6 -8
  9. package/dist/{chunk-B3MNN3XB.js.map → chunk-HFKOGW7H.js.map} +1 -1
  10. package/dist/chunk-HIKONDDO.js +26 -0
  11. package/dist/chunk-HIKONDDO.js.map +1 -0
  12. package/dist/chunk-M4YMTHGG.js +2822 -0
  13. package/dist/chunk-M4YMTHGG.js.map +1 -0
  14. package/dist/{chunk-NIASHOAB.js → chunk-SPQJC7RA.js} +5 -5
  15. package/dist/cli/main.js +16 -18
  16. package/dist/cli/main.js.map +1 -1
  17. package/dist/cli/yolo-daemon.js +17 -64
  18. package/dist/cli/yolo-daemon.js.map +1 -1
  19. package/dist/{goal-manager-LAOT4QQX.js → goal-manager-AP4LTE6U.js} +3 -4
  20. package/dist/{guardian-agent-M352CBE5.js → guardian-agent-WB6LWRLM.js} +7 -8
  21. package/dist/index.js +41 -119
  22. package/dist/index.js.map +1 -1
  23. package/package.json +4 -1
  24. package/dist/chunk-AE2XLMZC.js +0 -6152
  25. package/dist/chunk-AE2XLMZC.js.map +0 -1
  26. package/dist/chunk-CCI6LKXZ.js +0 -526
  27. package/dist/chunk-CCI6LKXZ.js.map +0 -1
  28. package/dist/chunk-JDHR5BDR.js.map +0 -1
  29. package/dist/chunk-M4JCQO5G.js.map +0 -1
  30. package/dist/chunk-R3I2GCZC.js +0 -682
  31. package/dist/chunk-R3I2GCZC.js.map +0 -1
  32. package/dist/issue-store-W2X33X2X.js +0 -28
  33. package/dist/issue-store-W2X33X2X.js.map +0 -1
  34. /package/dist/{chunk-NIASHOAB.js.map → chunk-SPQJC7RA.js.map} +0 -0
  35. /package/dist/{goal-manager-LAOT4QQX.js.map → goal-manager-AP4LTE6U.js.map} +0 -0
  36. /package/dist/{guardian-agent-M352CBE5.js.map → guardian-agent-WB6LWRLM.js.map} +0 -0
@@ -3,241 +3,6 @@ import {
3
3
  getWorkingDirectory
4
4
  } from "./chunk-R4AAPFXC.js";
5
5
 
6
- // src/memory/issue-store.ts
7
- import { mkdir as mkdir4, writeFile as writeFile2, readFile as readFile4, readdir as readdir2 } from "fs/promises";
8
- import { createHash as createHash2 } from "crypto";
9
- import { existsSync as existsSync4 } from "fs";
10
- import { join as join4 } from "path";
11
-
12
- // src/memory/bm25.ts
13
- var BM25Index = class _BM25Index {
14
- documents = /* @__PURE__ */ new Map();
15
- termFrequencies = /* @__PURE__ */ new Map();
16
- documentFrequencies = /* @__PURE__ */ new Map();
17
- documentLengths = /* @__PURE__ */ new Map();
18
- avgDocLength = 0;
19
- k1 = 1.5;
20
- b = 0.75;
21
- /**
22
- * Add a document to the index
23
- */
24
- addDocument(doc) {
25
- const tokens = this.tokenize(doc.text);
26
- this.documents.set(doc.id, doc);
27
- this.documentLengths.set(doc.id, tokens.length);
28
- const termFreq = /* @__PURE__ */ new Map();
29
- const seenTerms = /* @__PURE__ */ new Set();
30
- for (const token of tokens) {
31
- termFreq.set(token, (termFreq.get(token) || 0) + 1);
32
- if (!seenTerms.has(token)) {
33
- seenTerms.add(token);
34
- this.documentFrequencies.set(token, (this.documentFrequencies.get(token) || 0) + 1);
35
- }
36
- }
37
- this.termFrequencies.set(doc.id, termFreq);
38
- this.updateAvgDocLength();
39
- }
40
- /**
41
- * Add multiple documents
42
- */
43
- addDocuments(docs) {
44
- for (const doc of docs) {
45
- this.addDocument(doc);
46
- }
47
- }
48
- /**
49
- * Search the index
50
- */
51
- search(query, limit = 10) {
52
- const queryTokens = this.tokenize(query);
53
- const scores = /* @__PURE__ */ new Map();
54
- const N = this.documents.size;
55
- for (const [docId] of this.documents) {
56
- let score = 0;
57
- const docLength = this.documentLengths.get(docId) || 0;
58
- const termFreqs = this.termFrequencies.get(docId);
59
- if (!termFreqs) continue;
60
- for (const term of queryTokens) {
61
- const tf = termFreqs.get(term) || 0;
62
- if (tf === 0) continue;
63
- const df = this.documentFrequencies.get(term) || 0;
64
- const idf = Math.log((N - df + 0.5) / (df + 0.5) + 1);
65
- const numerator = tf * (this.k1 + 1);
66
- const denominator = tf + this.k1 * (1 - this.b + this.b * (docLength / this.avgDocLength));
67
- score += idf * (numerator / denominator);
68
- }
69
- if (score > 0) {
70
- scores.set(docId, score);
71
- }
72
- }
73
- return Array.from(scores.entries()).sort((a, b) => b[1] - a[1]).slice(0, limit).map(([id, score]) => {
74
- const metadata = this.documents.get(id)?.metadata;
75
- const result = { id, score };
76
- if (metadata !== void 0) {
77
- result.metadata = metadata;
78
- }
79
- return result;
80
- });
81
- }
82
- /**
83
- * Get document count
84
- */
85
- get size() {
86
- return this.documents.size;
87
- }
88
- /**
89
- * Clear the index
90
- */
91
- clear() {
92
- this.documents.clear();
93
- this.termFrequencies.clear();
94
- this.documentFrequencies.clear();
95
- this.documentLengths.clear();
96
- this.avgDocLength = 0;
97
- }
98
- /**
99
- * Serialize the index to JSON
100
- */
101
- serialize() {
102
- return JSON.stringify({
103
- documents: Array.from(this.documents.entries()),
104
- termFrequencies: Array.from(this.termFrequencies.entries()).map(([k, v]) => [k, Array.from(v.entries())]),
105
- documentFrequencies: Array.from(this.documentFrequencies.entries()),
106
- documentLengths: Array.from(this.documentLengths.entries()),
107
- avgDocLength: this.avgDocLength
108
- });
109
- }
110
- /**
111
- * Load from serialized JSON
112
- */
113
- static deserialize(json) {
114
- const data = JSON.parse(json);
115
- const index = new _BM25Index();
116
- index.documents = new Map(data.documents);
117
- index.termFrequencies = new Map(data.termFrequencies.map(([k, v]) => [k, new Map(v)]));
118
- index.documentFrequencies = new Map(data.documentFrequencies);
119
- index.documentLengths = new Map(data.documentLengths);
120
- index.avgDocLength = data.avgDocLength;
121
- return index;
122
- }
123
- tokenize(text) {
124
- return text.toLowerCase().replace(/[^\w\s]/g, " ").split(/\s+/).filter((token) => token.length > 2 && !this.isStopWord(token));
125
- }
126
- isStopWord(word) {
127
- const stopWords = /* @__PURE__ */ new Set([
128
- "the",
129
- "be",
130
- "to",
131
- "of",
132
- "and",
133
- "a",
134
- "in",
135
- "that",
136
- "have",
137
- "i",
138
- "it",
139
- "for",
140
- "not",
141
- "on",
142
- "with",
143
- "he",
144
- "as",
145
- "you",
146
- "do",
147
- "at",
148
- "this",
149
- "but",
150
- "his",
151
- "by",
152
- "from",
153
- "they",
154
- "we",
155
- "say",
156
- "her",
157
- "she",
158
- "or",
159
- "an",
160
- "will",
161
- "my",
162
- "one",
163
- "all",
164
- "would",
165
- "there",
166
- "their",
167
- "what",
168
- "so",
169
- "up",
170
- "out",
171
- "if",
172
- "about",
173
- "who",
174
- "get",
175
- "which",
176
- "go",
177
- "me",
178
- "when",
179
- "make",
180
- "can",
181
- "like",
182
- "time",
183
- "no",
184
- "just",
185
- "him",
186
- "know",
187
- "take",
188
- "into",
189
- "year",
190
- "your",
191
- "some",
192
- "could",
193
- "them",
194
- "see",
195
- "other",
196
- "than",
197
- "then",
198
- "now",
199
- "look",
200
- "only",
201
- "come",
202
- "its",
203
- "over",
204
- "also",
205
- "back",
206
- "after",
207
- "use",
208
- "two",
209
- "how",
210
- "our",
211
- "first",
212
- "way",
213
- "even",
214
- "new",
215
- "want",
216
- "because",
217
- "any",
218
- "these",
219
- "give",
220
- "day",
221
- "most",
222
- "us",
223
- "should",
224
- "been",
225
- "has",
226
- "was",
227
- "are"
228
- ]);
229
- return stopWords.has(word);
230
- }
231
- updateAvgDocLength() {
232
- if (this.documentLengths.size === 0) {
233
- this.avgDocLength = 0;
234
- return;
235
- }
236
- const total = Array.from(this.documentLengths.values()).reduce((a, b) => a + b, 0);
237
- this.avgDocLength = total / this.documentLengths.size;
238
- }
239
- };
240
-
241
6
  // src/memory/compactor.ts
242
7
  import { mkdir as mkdir2, readFile as readFile2 } from "fs/promises";
243
8
  import { existsSync as existsSync2 } from "fs";
@@ -682,27 +447,262 @@ async function getHistoricalInsights(projectDir) {
682
447
  };
683
448
  }
684
449
 
685
- // src/memory/ledger.ts
686
- import { createHash } from "crypto";
687
- import { mkdir as mkdir3, readFile as readFile3 } from "fs/promises";
688
- import { existsSync as existsSync3 } from "fs";
689
- import { join as join3 } from "path";
690
- var LEDGER_FILENAME = "ledger.json";
691
- var GENESIS_HASH = "0".repeat(64);
692
- var LEDGER_VERSION = 1;
693
- async function appendIssuesToLedger(issues, workDir) {
694
- if (issues.length === 0) return null;
695
- const projectDir = workDir || getWorkingDirectory(void 0, true);
696
- const memoryDir = join3(getTrieDirectory(projectDir), "memory");
697
- await mkdir3(memoryDir, { recursive: true });
698
- const blocks = await loadLedger(projectDir);
699
- const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
700
- const now = (/* @__PURE__ */ new Date()).toISOString();
701
- const entries = issues.map((issue) => ({
702
- id: issue.id,
703
- hash: issue.hash,
704
- severity: issue.severity,
705
- file: issue.file,
450
+ // src/memory/issue-store.ts
451
+ import { mkdir as mkdir4, writeFile as writeFile2, readFile as readFile4, readdir as readdir2 } from "fs/promises";
452
+ import { createHash as createHash2 } from "crypto";
453
+ import { existsSync as existsSync4 } from "fs";
454
+ import { join as join4 } from "path";
455
+
456
+ // src/memory/bm25.ts
457
+ var BM25Index = class _BM25Index {
458
+ documents = /* @__PURE__ */ new Map();
459
+ termFrequencies = /* @__PURE__ */ new Map();
460
+ documentFrequencies = /* @__PURE__ */ new Map();
461
+ documentLengths = /* @__PURE__ */ new Map();
462
+ avgDocLength = 0;
463
+ k1 = 1.5;
464
+ b = 0.75;
465
+ /**
466
+ * Add a document to the index
467
+ */
468
+ addDocument(doc) {
469
+ const tokens = this.tokenize(doc.text);
470
+ this.documents.set(doc.id, doc);
471
+ this.documentLengths.set(doc.id, tokens.length);
472
+ const termFreq = /* @__PURE__ */ new Map();
473
+ const seenTerms = /* @__PURE__ */ new Set();
474
+ for (const token of tokens) {
475
+ termFreq.set(token, (termFreq.get(token) || 0) + 1);
476
+ if (!seenTerms.has(token)) {
477
+ seenTerms.add(token);
478
+ this.documentFrequencies.set(token, (this.documentFrequencies.get(token) || 0) + 1);
479
+ }
480
+ }
481
+ this.termFrequencies.set(doc.id, termFreq);
482
+ this.updateAvgDocLength();
483
+ }
484
+ /**
485
+ * Add multiple documents
486
+ */
487
+ addDocuments(docs) {
488
+ for (const doc of docs) {
489
+ this.addDocument(doc);
490
+ }
491
+ }
492
+ /**
493
+ * Search the index
494
+ */
495
+ search(query, limit = 10) {
496
+ const queryTokens = this.tokenize(query);
497
+ const scores = /* @__PURE__ */ new Map();
498
+ const N = this.documents.size;
499
+ for (const [docId] of this.documents) {
500
+ let score = 0;
501
+ const docLength = this.documentLengths.get(docId) || 0;
502
+ const termFreqs = this.termFrequencies.get(docId);
503
+ if (!termFreqs) continue;
504
+ for (const term of queryTokens) {
505
+ const tf = termFreqs.get(term) || 0;
506
+ if (tf === 0) continue;
507
+ const df = this.documentFrequencies.get(term) || 0;
508
+ const idf = Math.log((N - df + 0.5) / (df + 0.5) + 1);
509
+ const numerator = tf * (this.k1 + 1);
510
+ const denominator = tf + this.k1 * (1 - this.b + this.b * (docLength / this.avgDocLength));
511
+ score += idf * (numerator / denominator);
512
+ }
513
+ if (score > 0) {
514
+ scores.set(docId, score);
515
+ }
516
+ }
517
+ return Array.from(scores.entries()).sort((a, b) => b[1] - a[1]).slice(0, limit).map(([id, score]) => {
518
+ const metadata = this.documents.get(id)?.metadata;
519
+ const result = { id, score };
520
+ if (metadata !== void 0) {
521
+ result.metadata = metadata;
522
+ }
523
+ return result;
524
+ });
525
+ }
526
+ /**
527
+ * Get document count
528
+ */
529
+ get size() {
530
+ return this.documents.size;
531
+ }
532
+ /**
533
+ * Clear the index
534
+ */
535
+ clear() {
536
+ this.documents.clear();
537
+ this.termFrequencies.clear();
538
+ this.documentFrequencies.clear();
539
+ this.documentLengths.clear();
540
+ this.avgDocLength = 0;
541
+ }
542
+ /**
543
+ * Serialize the index to JSON
544
+ */
545
+ serialize() {
546
+ return JSON.stringify({
547
+ documents: Array.from(this.documents.entries()),
548
+ termFrequencies: Array.from(this.termFrequencies.entries()).map(([k, v]) => [k, Array.from(v.entries())]),
549
+ documentFrequencies: Array.from(this.documentFrequencies.entries()),
550
+ documentLengths: Array.from(this.documentLengths.entries()),
551
+ avgDocLength: this.avgDocLength
552
+ });
553
+ }
554
+ /**
555
+ * Load from serialized JSON
556
+ */
557
+ static deserialize(json) {
558
+ const data = JSON.parse(json);
559
+ const index = new _BM25Index();
560
+ index.documents = new Map(data.documents);
561
+ index.termFrequencies = new Map(data.termFrequencies.map(([k, v]) => [k, new Map(v)]));
562
+ index.documentFrequencies = new Map(data.documentFrequencies);
563
+ index.documentLengths = new Map(data.documentLengths);
564
+ index.avgDocLength = data.avgDocLength;
565
+ return index;
566
+ }
567
+ tokenize(text) {
568
+ return text.toLowerCase().replace(/[^\w\s]/g, " ").split(/\s+/).filter((token) => token.length > 2 && !this.isStopWord(token));
569
+ }
570
+ isStopWord(word) {
571
+ const stopWords = /* @__PURE__ */ new Set([
572
+ "the",
573
+ "be",
574
+ "to",
575
+ "of",
576
+ "and",
577
+ "a",
578
+ "in",
579
+ "that",
580
+ "have",
581
+ "i",
582
+ "it",
583
+ "for",
584
+ "not",
585
+ "on",
586
+ "with",
587
+ "he",
588
+ "as",
589
+ "you",
590
+ "do",
591
+ "at",
592
+ "this",
593
+ "but",
594
+ "his",
595
+ "by",
596
+ "from",
597
+ "they",
598
+ "we",
599
+ "say",
600
+ "her",
601
+ "she",
602
+ "or",
603
+ "an",
604
+ "will",
605
+ "my",
606
+ "one",
607
+ "all",
608
+ "would",
609
+ "there",
610
+ "their",
611
+ "what",
612
+ "so",
613
+ "up",
614
+ "out",
615
+ "if",
616
+ "about",
617
+ "who",
618
+ "get",
619
+ "which",
620
+ "go",
621
+ "me",
622
+ "when",
623
+ "make",
624
+ "can",
625
+ "like",
626
+ "time",
627
+ "no",
628
+ "just",
629
+ "him",
630
+ "know",
631
+ "take",
632
+ "into",
633
+ "year",
634
+ "your",
635
+ "some",
636
+ "could",
637
+ "them",
638
+ "see",
639
+ "other",
640
+ "than",
641
+ "then",
642
+ "now",
643
+ "look",
644
+ "only",
645
+ "come",
646
+ "its",
647
+ "over",
648
+ "also",
649
+ "back",
650
+ "after",
651
+ "use",
652
+ "two",
653
+ "how",
654
+ "our",
655
+ "first",
656
+ "way",
657
+ "even",
658
+ "new",
659
+ "want",
660
+ "because",
661
+ "any",
662
+ "these",
663
+ "give",
664
+ "day",
665
+ "most",
666
+ "us",
667
+ "should",
668
+ "been",
669
+ "has",
670
+ "was",
671
+ "are"
672
+ ]);
673
+ return stopWords.has(word);
674
+ }
675
+ updateAvgDocLength() {
676
+ if (this.documentLengths.size === 0) {
677
+ this.avgDocLength = 0;
678
+ return;
679
+ }
680
+ const total = Array.from(this.documentLengths.values()).reduce((a, b) => a + b, 0);
681
+ this.avgDocLength = total / this.documentLengths.size;
682
+ }
683
+ };
684
+
685
+ // src/memory/ledger.ts
686
+ import { createHash } from "crypto";
687
+ import { mkdir as mkdir3, readFile as readFile3 } from "fs/promises";
688
+ import { existsSync as existsSync3 } from "fs";
689
+ import { join as join3 } from "path";
690
+ var LEDGER_FILENAME = "ledger.json";
691
+ var GENESIS_HASH = "0".repeat(64);
692
+ var LEDGER_VERSION = 1;
693
+ async function appendIssuesToLedger(issues, workDir) {
694
+ if (issues.length === 0) return null;
695
+ const projectDir = workDir || getWorkingDirectory(void 0, true);
696
+ const memoryDir = join3(getTrieDirectory(projectDir), "memory");
697
+ await mkdir3(memoryDir, { recursive: true });
698
+ const blocks = await loadLedger(projectDir);
699
+ const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
700
+ const now = (/* @__PURE__ */ new Date()).toISOString();
701
+ const entries = issues.map((issue) => ({
702
+ id: issue.id,
703
+ hash: issue.hash,
704
+ severity: issue.severity,
705
+ file: issue.file,
706
706
  agent: issue.agent,
707
707
  timestamp: issue.timestamp
708
708
  }));
@@ -1123,6 +1123,675 @@ function hashIssue(issue) {
1123
1123
  return createHash2("sha256").update(content).digest("hex").slice(0, 16);
1124
1124
  }
1125
1125
 
1126
+ // src/guardian/guardian-state.ts
1127
+ import { mkdir as mkdir5, readFile as readFile5 } from "fs/promises";
1128
+ import { existsSync as existsSync5 } from "fs";
1129
+ import { join as join5 } from "path";
1130
+ import { z as z2 } from "zod";
1131
+ var GoalSchema = z2.object({
1132
+ id: z2.string(),
1133
+ description: z2.string(),
1134
+ type: z2.enum(["streak", "reduction", "score", "custom"]),
1135
+ metric: z2.string(),
1136
+ target: z2.number(),
1137
+ currentValue: z2.number(),
1138
+ startValue: z2.number().optional(),
1139
+ status: z2.enum(["active", "achieved", "failed", "paused", "rejected"]),
1140
+ autoGenerated: z2.boolean(),
1141
+ confidence: z2.number().min(0).max(1).optional(),
1142
+ // For auto-generated goals
1143
+ createdAt: z2.string(),
1144
+ updatedAt: z2.string(),
1145
+ achievedAt: z2.string().optional(),
1146
+ deadline: z2.string().optional(),
1147
+ category: z2.enum(["security", "quality", "performance", "coverage", "general"]).optional(),
1148
+ evidence: z2.array(z2.string()).optional()
1149
+ // Why this goal was generated
1150
+ });
1151
+ var HypothesisSchema = z2.object({
1152
+ id: z2.string(),
1153
+ statement: z2.string(),
1154
+ confidence: z2.number().min(0).max(1),
1155
+ // 0-1, adjusts based on validation
1156
+ status: z2.enum(["proposed", "testing", "validated", "invalidated", "retired"]),
1157
+ evidence: z2.array(z2.object({
1158
+ type: z2.enum(["supporting", "contradicting"]),
1159
+ description: z2.string(),
1160
+ timestamp: z2.string(),
1161
+ weight: z2.number().min(0).max(1).optional()
1162
+ })),
1163
+ createdAt: z2.string(),
1164
+ updatedAt: z2.string(),
1165
+ validatedAt: z2.string().optional(),
1166
+ testCriteria: z2.string().optional(),
1167
+ category: z2.enum(["timing", "pattern", "team", "code", "general"]).optional()
1168
+ });
1169
+ var RiskBudgetSchema = z2.object({
1170
+ daily: z2.number(),
1171
+ weekly: z2.number(),
1172
+ usedToday: z2.number(),
1173
+ usedThisWeek: z2.number(),
1174
+ lastResetDay: z2.string(),
1175
+ // ISO date (YYYY-MM-DD)
1176
+ lastResetWeek: z2.string()
1177
+ // ISO week (YYYY-WNN)
1178
+ });
1179
+ var AgentMetricsSchema = z2.object({
1180
+ predictiveAccuracy: z2.number().min(0).max(1),
1181
+ falsePositiveRate: z2.number().min(0).max(1),
1182
+ userSatisfaction: z2.number().min(0).max(1),
1183
+ hypothesisAccuracy: z2.number().min(0).max(1),
1184
+ totalPredictions: z2.number(),
1185
+ correctPredictions: z2.number(),
1186
+ totalInsights: z2.number(),
1187
+ helpfulInsights: z2.number(),
1188
+ dismissedInsights: z2.number(),
1189
+ actedOnInsights: z2.number()
1190
+ });
1191
+ var TimingContextSchema = z2.object({
1192
+ quietHoursStart: z2.number().min(0).max(23),
1193
+ // Hour of day (0-23)
1194
+ quietHoursEnd: z2.number().min(0).max(23),
1195
+ quietHoursEnabled: z2.boolean(),
1196
+ workDays: z2.array(z2.number().min(0).max(6)),
1197
+ // 0 = Sunday
1198
+ lastActiveTimestamp: z2.number(),
1199
+ timezone: z2.string().optional(),
1200
+ crunchMode: z2.boolean(),
1201
+ // During crunch, defer low-priority items
1202
+ crunchModeUntil: z2.string().optional()
1203
+ });
1204
+ var GuardianStateDataSchema = z2.object({
1205
+ version: z2.literal(1),
1206
+ goals: z2.array(GoalSchema),
1207
+ hypotheses: z2.array(HypothesisSchema),
1208
+ riskBudget: RiskBudgetSchema,
1209
+ metrics: AgentMetricsSchema,
1210
+ timing: TimingContextSchema,
1211
+ scanFrequencyMs: z2.number(),
1212
+ // Current scan frequency
1213
+ lastScanTimestamp: z2.number().optional(),
1214
+ lastUpdated: z2.string()
1215
+ });
1216
+ var GuardianState = class {
1217
+ projectPath;
1218
+ data;
1219
+ loaded = false;
1220
+ dirty = false;
1221
+ constructor(projectPath) {
1222
+ this.projectPath = projectPath;
1223
+ this.data = this.createDefaultState();
1224
+ }
1225
+ /**
1226
+ * Get the storage file path
1227
+ */
1228
+ getStorePath() {
1229
+ return join5(getTrieDirectory(this.projectPath), "memory", "guardian-state.json");
1230
+ }
1231
+ /**
1232
+ * Create default state
1233
+ */
1234
+ createDefaultState() {
1235
+ const now = /* @__PURE__ */ new Date();
1236
+ const today = now.toISOString().split("T")[0];
1237
+ const week = this.getISOWeek(now);
1238
+ return {
1239
+ version: 1,
1240
+ goals: [],
1241
+ hypotheses: [],
1242
+ riskBudget: {
1243
+ daily: 10,
1244
+ weekly: 50,
1245
+ usedToday: 0,
1246
+ usedThisWeek: 0,
1247
+ lastResetDay: today,
1248
+ lastResetWeek: week
1249
+ },
1250
+ metrics: {
1251
+ predictiveAccuracy: 0.5,
1252
+ // Start neutral
1253
+ falsePositiveRate: 0.5,
1254
+ userSatisfaction: 0.5,
1255
+ hypothesisAccuracy: 0.5,
1256
+ totalPredictions: 0,
1257
+ correctPredictions: 0,
1258
+ totalInsights: 0,
1259
+ helpfulInsights: 0,
1260
+ dismissedInsights: 0,
1261
+ actedOnInsights: 0
1262
+ },
1263
+ timing: {
1264
+ quietHoursStart: 21,
1265
+ // 9 PM
1266
+ quietHoursEnd: 8,
1267
+ // 8 AM
1268
+ quietHoursEnabled: true,
1269
+ workDays: [1, 2, 3, 4, 5],
1270
+ // Mon-Fri
1271
+ lastActiveTimestamp: Date.now(),
1272
+ crunchMode: false
1273
+ },
1274
+ scanFrequencyMs: 3e5,
1275
+ // 5 minutes default
1276
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString()
1277
+ };
1278
+ }
1279
+ /**
1280
+ * Get ISO week string (YYYY-WNN)
1281
+ */
1282
+ getISOWeek(date) {
1283
+ const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
1284
+ const dayNum = d.getUTCDay() || 7;
1285
+ d.setUTCDate(d.getUTCDate() + 4 - dayNum);
1286
+ const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
1287
+ const weekNo = Math.ceil(((d.getTime() - yearStart.getTime()) / 864e5 + 1) / 7);
1288
+ return `${d.getUTCFullYear()}-W${weekNo.toString().padStart(2, "0")}`;
1289
+ }
1290
+ /**
1291
+ * Load state from disk
1292
+ */
1293
+ async load() {
1294
+ if (this.loaded) {
1295
+ return this.data;
1296
+ }
1297
+ const storePath = this.getStorePath();
1298
+ try {
1299
+ if (existsSync5(storePath)) {
1300
+ const content = await readFile5(storePath, "utf-8");
1301
+ const result = safeParseAndValidate(content, GuardianStateDataSchema);
1302
+ if (result.success) {
1303
+ this.data = result.data;
1304
+ this.loaded = true;
1305
+ await this.checkAndResetBudgets();
1306
+ return this.data;
1307
+ }
1308
+ console.error(` Guardian state corrupted: ${result.error}`);
1309
+ const backupManager = new BackupManager(storePath);
1310
+ if (await backupManager.recoverFromBackup()) {
1311
+ console.error(" \u2705 Recovered from backup");
1312
+ const recovered = await readFile5(storePath, "utf-8");
1313
+ const recoveredResult = safeParseAndValidate(recovered, GuardianStateDataSchema);
1314
+ if (recoveredResult.success) {
1315
+ this.data = recoveredResult.data;
1316
+ this.loaded = true;
1317
+ return this.data;
1318
+ }
1319
+ }
1320
+ console.error(" No valid backup found, starting fresh");
1321
+ }
1322
+ } catch (error) {
1323
+ console.error(` Could not load guardian state: ${error}`);
1324
+ }
1325
+ this.data = this.createDefaultState();
1326
+ this.loaded = true;
1327
+ return this.data;
1328
+ }
1329
+ /**
1330
+ * Save state to disk
1331
+ */
1332
+ async save() {
1333
+ if (!this.dirty && this.loaded) {
1334
+ return;
1335
+ }
1336
+ const storePath = this.getStorePath();
1337
+ const memoryDir = join5(getTrieDirectory(this.projectPath), "memory");
1338
+ await mkdir5(memoryDir, { recursive: true });
1339
+ const backupManager = new BackupManager(storePath);
1340
+ await backupManager.createBackup();
1341
+ this.data.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
1342
+ await atomicWriteJSON(storePath, this.data);
1343
+ this.dirty = false;
1344
+ }
1345
+ /**
1346
+ * Check and reset daily/weekly budgets if needed
1347
+ */
1348
+ async checkAndResetBudgets() {
1349
+ const now = /* @__PURE__ */ new Date();
1350
+ const today = now.toISOString().split("T")[0];
1351
+ const week = this.getISOWeek(now);
1352
+ let needsSave = false;
1353
+ if (this.data.riskBudget.lastResetDay !== today) {
1354
+ this.data.riskBudget.usedToday = 0;
1355
+ this.data.riskBudget.lastResetDay = today;
1356
+ needsSave = true;
1357
+ }
1358
+ if (this.data.riskBudget.lastResetWeek !== week) {
1359
+ this.data.riskBudget.usedThisWeek = 0;
1360
+ this.data.riskBudget.lastResetWeek = week;
1361
+ needsSave = true;
1362
+ }
1363
+ if (needsSave) {
1364
+ this.dirty = true;
1365
+ await this.save();
1366
+ }
1367
+ }
1368
+ // ========================================================================
1369
+ // Goals
1370
+ // ========================================================================
1371
+ /**
1372
+ * Add a goal
1373
+ */
1374
+ async addGoal(goal) {
1375
+ await this.load();
1376
+ if (this.data.goals.some((g) => g.id === goal.id)) {
1377
+ return false;
1378
+ }
1379
+ this.data.goals.push(goal);
1380
+ this.dirty = true;
1381
+ await this.save();
1382
+ return true;
1383
+ }
1384
+ /**
1385
+ * Update a goal
1386
+ */
1387
+ async updateGoal(goalId, updates) {
1388
+ await this.load();
1389
+ const goal = this.data.goals.find((g) => g.id === goalId);
1390
+ if (!goal) {
1391
+ return false;
1392
+ }
1393
+ Object.assign(goal, updates, { updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
1394
+ this.dirty = true;
1395
+ await this.save();
1396
+ return true;
1397
+ }
1398
+ /**
1399
+ * Get active goals
1400
+ */
1401
+ getActiveGoals() {
1402
+ return this.data.goals.filter((g) => g.status === "active");
1403
+ }
1404
+ /**
1405
+ * Get all goals
1406
+ */
1407
+ getAllGoals() {
1408
+ return [...this.data.goals];
1409
+ }
1410
+ /**
1411
+ * Get goal by ID
1412
+ */
1413
+ getGoal(goalId) {
1414
+ return this.data.goals.find((g) => g.id === goalId);
1415
+ }
1416
+ /**
1417
+ * Remove a goal
1418
+ */
1419
+ async removeGoal(goalId) {
1420
+ await this.load();
1421
+ const index = this.data.goals.findIndex((g) => g.id === goalId);
1422
+ if (index === -1) {
1423
+ return false;
1424
+ }
1425
+ this.data.goals.splice(index, 1);
1426
+ this.dirty = true;
1427
+ await this.save();
1428
+ return true;
1429
+ }
1430
+ /**
1431
+ * Get auto-generated goals
1432
+ */
1433
+ getAutoGeneratedGoals() {
1434
+ return this.data.goals.filter((g) => g.autoGenerated);
1435
+ }
1436
+ /**
1437
+ * Accept or reject an auto-generated goal
1438
+ */
1439
+ async respondToGoal(goalId, accept) {
1440
+ return this.updateGoal(goalId, {
1441
+ status: accept ? "active" : "rejected"
1442
+ });
1443
+ }
1444
+ // ========================================================================
1445
+ // Hypotheses
1446
+ // ========================================================================
1447
+ /**
1448
+ * Add a hypothesis
1449
+ */
1450
+ async addHypothesis(hypothesis) {
1451
+ await this.load();
1452
+ if (this.data.hypotheses.some((h) => h.id === hypothesis.id)) {
1453
+ return false;
1454
+ }
1455
+ this.data.hypotheses.push(hypothesis);
1456
+ this.dirty = true;
1457
+ await this.save();
1458
+ return true;
1459
+ }
1460
+ /**
1461
+ * Update a hypothesis
1462
+ */
1463
+ async updateHypothesis(hypothesisId, updates) {
1464
+ await this.load();
1465
+ const hypothesis = this.data.hypotheses.find((h) => h.id === hypothesisId);
1466
+ if (!hypothesis) {
1467
+ return false;
1468
+ }
1469
+ Object.assign(hypothesis, updates, { updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
1470
+ this.dirty = true;
1471
+ await this.save();
1472
+ return true;
1473
+ }
1474
+ /**
1475
+ * Add evidence to a hypothesis
1476
+ */
1477
+ async addEvidence(hypothesisId, evidence) {
1478
+ await this.load();
1479
+ const hypothesis = this.data.hypotheses.find((h) => h.id === hypothesisId);
1480
+ if (!hypothesis) {
1481
+ return false;
1482
+ }
1483
+ hypothesis.evidence.push({
1484
+ ...evidence,
1485
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1486
+ });
1487
+ if (hypothesis.status === "proposed" && hypothesis.evidence.length === 1) {
1488
+ hypothesis.status = "testing";
1489
+ }
1490
+ const supportingCount = hypothesis.evidence.filter((e) => e.type === "supporting").length;
1491
+ const contradictingCount = hypothesis.evidence.filter((e) => e.type === "contradicting").length;
1492
+ const total = supportingCount + contradictingCount;
1493
+ if (total > 0) {
1494
+ hypothesis.confidence = supportingCount / total;
1495
+ if (hypothesis.status === "testing") {
1496
+ if (hypothesis.confidence > 0.8 && supportingCount >= 3) {
1497
+ hypothesis.status = "validated";
1498
+ hypothesis.validatedAt = (/* @__PURE__ */ new Date()).toISOString();
1499
+ } else if (hypothesis.confidence < 0.2 && contradictingCount >= 3) {
1500
+ hypothesis.status = "invalidated";
1501
+ }
1502
+ }
1503
+ }
1504
+ hypothesis.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1505
+ this.dirty = true;
1506
+ await this.save();
1507
+ return true;
1508
+ }
1509
+ /**
1510
+ * Get active hypotheses
1511
+ */
1512
+ getActiveHypotheses() {
1513
+ return this.data.hypotheses.filter(
1514
+ (h) => h.status === "proposed" || h.status === "testing"
1515
+ );
1516
+ }
1517
+ /**
1518
+ * Get validated hypotheses
1519
+ */
1520
+ getValidatedHypotheses() {
1521
+ return this.data.hypotheses.filter((h) => h.status === "validated");
1522
+ }
1523
+ /**
1524
+ * Get all hypotheses
1525
+ */
1526
+ getAllHypotheses() {
1527
+ return [...this.data.hypotheses];
1528
+ }
1529
+ /**
1530
+ * Get hypothesis by ID
1531
+ */
1532
+ getHypothesis(hypothesisId) {
1533
+ return this.data.hypotheses.find((h) => h.id === hypothesisId);
1534
+ }
1535
+ // ========================================================================
1536
+ // Risk Budget
1537
+ // ========================================================================
1538
+ /**
1539
+ * Get current risk budget
1540
+ */
1541
+ getRiskBudget() {
1542
+ return { ...this.data.riskBudget };
1543
+ }
1544
+ /**
1545
+ * Use risk budget
1546
+ */
1547
+ async useRiskBudget(amount) {
1548
+ await this.load();
1549
+ await this.checkAndResetBudgets();
1550
+ if (this.data.riskBudget.usedToday + amount > this.data.riskBudget.daily) {
1551
+ return false;
1552
+ }
1553
+ if (this.data.riskBudget.usedThisWeek + amount > this.data.riskBudget.weekly) {
1554
+ return false;
1555
+ }
1556
+ this.data.riskBudget.usedToday += amount;
1557
+ this.data.riskBudget.usedThisWeek += amount;
1558
+ this.dirty = true;
1559
+ await this.save();
1560
+ return true;
1561
+ }
1562
+ /**
1563
+ * Check if risk budget is available
1564
+ */
1565
+ hasRiskBudget(amount = 1) {
1566
+ return this.data.riskBudget.usedToday + amount <= this.data.riskBudget.daily && this.data.riskBudget.usedThisWeek + amount <= this.data.riskBudget.weekly;
1567
+ }
1568
+ /**
1569
+ * Update risk budget limits
1570
+ */
1571
+ async setRiskBudget(daily, weekly) {
1572
+ await this.load();
1573
+ this.data.riskBudget.daily = daily;
1574
+ this.data.riskBudget.weekly = weekly;
1575
+ this.dirty = true;
1576
+ await this.save();
1577
+ }
1578
+ // ========================================================================
1579
+ // Metrics
1580
+ // ========================================================================
1581
+ /**
1582
+ * Get agent metrics
1583
+ */
1584
+ getMetrics() {
1585
+ return { ...this.data.metrics };
1586
+ }
1587
+ /**
1588
+ * Record a prediction outcome
1589
+ */
1590
+ async recordPrediction(correct) {
1591
+ await this.load();
1592
+ this.data.metrics.totalPredictions++;
1593
+ if (correct) {
1594
+ this.data.metrics.correctPredictions++;
1595
+ }
1596
+ this.data.metrics.predictiveAccuracy = this.data.metrics.correctPredictions / this.data.metrics.totalPredictions;
1597
+ this.dirty = true;
1598
+ await this.save();
1599
+ }
1600
+ /**
1601
+ * Record user feedback on an insight
1602
+ */
1603
+ async recordInsightFeedback(feedback) {
1604
+ await this.load();
1605
+ this.data.metrics.totalInsights++;
1606
+ switch (feedback) {
1607
+ case "helpful":
1608
+ this.data.metrics.helpfulInsights++;
1609
+ break;
1610
+ case "dismissed":
1611
+ this.data.metrics.dismissedInsights++;
1612
+ break;
1613
+ case "acted":
1614
+ this.data.metrics.actedOnInsights++;
1615
+ this.data.metrics.helpfulInsights++;
1616
+ break;
1617
+ }
1618
+ if (this.data.metrics.totalInsights > 0) {
1619
+ this.data.metrics.userSatisfaction = this.data.metrics.helpfulInsights / this.data.metrics.totalInsights;
1620
+ this.data.metrics.falsePositiveRate = this.data.metrics.dismissedInsights / this.data.metrics.totalInsights;
1621
+ }
1622
+ this.dirty = true;
1623
+ await this.save();
1624
+ }
1625
+ /**
1626
+ * Update hypothesis accuracy
1627
+ */
1628
+ async updateHypothesisAccuracy() {
1629
+ await this.load();
1630
+ const validated = this.data.hypotheses.filter((h) => h.status === "validated").length;
1631
+ const invalidated = this.data.hypotheses.filter((h) => h.status === "invalidated").length;
1632
+ const total = validated + invalidated;
1633
+ if (total > 0) {
1634
+ this.data.metrics.hypothesisAccuracy = validated / total;
1635
+ this.dirty = true;
1636
+ await this.save();
1637
+ }
1638
+ }
1639
+ // ========================================================================
1640
+ // Timing Context
1641
+ // ========================================================================
1642
+ /**
1643
+ * Get timing context
1644
+ */
1645
+ getTimingContext() {
1646
+ return { ...this.data.timing };
1647
+ }
1648
+ /**
1649
+ * Check if currently in quiet hours
1650
+ */
1651
+ isQuietHours() {
1652
+ if (!this.data.timing.quietHoursEnabled) {
1653
+ return false;
1654
+ }
1655
+ const now = /* @__PURE__ */ new Date();
1656
+ const hour = now.getHours();
1657
+ const start = this.data.timing.quietHoursStart;
1658
+ const end = this.data.timing.quietHoursEnd;
1659
+ if (start > end) {
1660
+ return hour >= start || hour < end;
1661
+ }
1662
+ return hour >= start && hour < end;
1663
+ }
1664
+ /**
1665
+ * Check if today is a work day
1666
+ */
1667
+ isWorkDay() {
1668
+ const dayOfWeek = (/* @__PURE__ */ new Date()).getDay();
1669
+ return this.data.timing.workDays.includes(dayOfWeek);
1670
+ }
1671
+ /**
1672
+ * Check if in crunch mode
1673
+ */
1674
+ isInCrunchMode() {
1675
+ if (!this.data.timing.crunchMode) {
1676
+ return false;
1677
+ }
1678
+ if (this.data.timing.crunchModeUntil) {
1679
+ const until = new Date(this.data.timing.crunchModeUntil);
1680
+ if (Date.now() > until.getTime()) {
1681
+ this.data.timing.crunchMode = false;
1682
+ this.data.timing.crunchModeUntil = void 0;
1683
+ this.dirty = true;
1684
+ return false;
1685
+ }
1686
+ }
1687
+ return true;
1688
+ }
1689
+ /**
1690
+ * Enable crunch mode
1691
+ */
1692
+ async setCrunchMode(enabled, until) {
1693
+ await this.load();
1694
+ this.data.timing.crunchMode = enabled;
1695
+ this.data.timing.crunchModeUntil = until?.toISOString();
1696
+ this.dirty = true;
1697
+ await this.save();
1698
+ }
1699
+ /**
1700
+ * Update quiet hours settings
1701
+ */
1702
+ async setQuietHours(start, end, enabled = true) {
1703
+ await this.load();
1704
+ this.data.timing.quietHoursStart = start;
1705
+ this.data.timing.quietHoursEnd = end;
1706
+ this.data.timing.quietHoursEnabled = enabled;
1707
+ this.dirty = true;
1708
+ await this.save();
1709
+ }
1710
+ /**
1711
+ * Update work days
1712
+ */
1713
+ async setWorkDays(days) {
1714
+ await this.load();
1715
+ this.data.timing.workDays = days;
1716
+ this.dirty = true;
1717
+ await this.save();
1718
+ }
1719
+ /**
1720
+ * Update last active timestamp
1721
+ */
1722
+ async touchActive() {
1723
+ await this.load();
1724
+ this.data.timing.lastActiveTimestamp = Date.now();
1725
+ this.dirty = true;
1726
+ await this.save();
1727
+ }
1728
+ // ========================================================================
1729
+ // Scan Frequency
1730
+ // ========================================================================
1731
+ /**
1732
+ * Get current scan frequency in milliseconds
1733
+ */
1734
+ getScanFrequencyMs() {
1735
+ return this.data.scanFrequencyMs;
1736
+ }
1737
+ /**
1738
+ * Set scan frequency
1739
+ */
1740
+ async setScanFrequency(ms) {
1741
+ await this.load();
1742
+ this.data.scanFrequencyMs = Math.max(1e4, ms);
1743
+ this.dirty = true;
1744
+ await this.save();
1745
+ }
1746
+ /**
1747
+ * Record a scan timestamp
1748
+ */
1749
+ async recordScan() {
1750
+ await this.load();
1751
+ this.data.lastScanTimestamp = Date.now();
1752
+ this.dirty = true;
1753
+ await this.save();
1754
+ }
1755
+ /**
1756
+ * Get last scan timestamp
1757
+ */
1758
+ getLastScanTimestamp() {
1759
+ return this.data.lastScanTimestamp;
1760
+ }
1761
+ // ========================================================================
1762
+ // Utility
1763
+ // ========================================================================
1764
+ /**
1765
+ * Get full state data
1766
+ */
1767
+ getData() {
1768
+ return { ...this.data };
1769
+ }
1770
+ /**
1771
+ * Force reload from disk
1772
+ */
1773
+ async reload() {
1774
+ this.loaded = false;
1775
+ this.dirty = false;
1776
+ return this.load();
1777
+ }
1778
+ /**
1779
+ * Check if loaded
1780
+ */
1781
+ isLoaded() {
1782
+ return this.loaded;
1783
+ }
1784
+ };
1785
+ var guardianStates = /* @__PURE__ */ new Map();
1786
+ function getGuardianState(projectPath) {
1787
+ let state = guardianStates.get(projectPath);
1788
+ if (!state) {
1789
+ state = new GuardianState(projectPath);
1790
+ guardianStates.set(projectPath, state);
1791
+ }
1792
+ return state;
1793
+ }
1794
+
1126
1795
  export {
1127
1796
  atomicWriteJSON,
1128
1797
  BackupManager,
@@ -1138,6 +1807,7 @@ export {
1138
1807
  getMemoryStats,
1139
1808
  getRecentIssues,
1140
1809
  purgeIssues,
1141
- getDailyLogs
1810
+ getDailyLogs,
1811
+ getGuardianState
1142
1812
  };
1143
- //# sourceMappingURL=chunk-JDHR5BDR.js.map
1813
+ //# sourceMappingURL=chunk-6JPPYG7F.js.map