token-goat 2.9.28 → 2.9.30

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 (134) hide show
  1. package/README.md +36 -40
  2. package/SECURITY.md +28 -10
  3. package/THIRD_PARTY_NOTICES.md +40 -3
  4. package/dist/native/linux-arm64/tg-hook +0 -0
  5. package/dist/native/linux-x64/tg-hook +0 -0
  6. package/dist/ort-wasm-simd-threaded.mjs +59 -0
  7. package/dist/token-goat-chunk-3CHUNJ2O.mjs +53 -0
  8. package/dist/token-goat-chunk-3Z5S4KGM.mjs +918 -0
  9. package/dist/token-goat-chunk-4FVIAHSI.mjs +211 -0
  10. package/dist/{token-goat-chunk-66LODAUT.mjs → token-goat-chunk-4JJS54TR.mjs} +4 -3
  11. package/dist/token-goat-chunk-4LCCNRTG.mjs +313 -0
  12. package/dist/token-goat-chunk-54K3EUV3.mjs +35 -0
  13. package/dist/token-goat-chunk-56EIMS3E.mjs +159 -0
  14. package/dist/token-goat-chunk-5BCIJXMO.mjs +609 -0
  15. package/dist/token-goat-chunk-5KDMCMF2.mjs +362 -0
  16. package/dist/token-goat-chunk-5RG5SBL6.mjs +221 -0
  17. package/dist/{token-goat-chunk-RRNZMM3A.mjs → token-goat-chunk-5Y6ZYL6U.mjs} +21 -2
  18. package/dist/{token-goat-chunk-NILVK7XM.mjs → token-goat-chunk-64FBPDTK.mjs} +12 -6
  19. package/dist/{token-goat-chunk-LEG3JNJ6.mjs → token-goat-chunk-664RTTUV.mjs} +31 -15
  20. package/dist/token-goat-chunk-67TQJ76B.mjs +57 -0
  21. package/dist/token-goat-chunk-6QMAS7AB.mjs +42 -0
  22. package/dist/token-goat-chunk-7BXSNBY5.mjs +253 -0
  23. package/dist/{token-goat-chunk-F7QZRIWM.mjs → token-goat-chunk-7F2UBPD3.mjs} +42 -35
  24. package/dist/{token-goat-chunk-CC2PYJM7.mjs → token-goat-chunk-7IN2MKDS.mjs} +718 -595
  25. package/dist/token-goat-chunk-7NADEDKJ.mjs +124 -0
  26. package/dist/{token-goat-chunk-6SGLIPQB.mjs → token-goat-chunk-A3CK6N5Z.mjs} +621 -72
  27. package/dist/{token-goat-chunk-HXNAC4ZF.mjs → token-goat-chunk-AFLYLHDH.mjs} +48 -33
  28. package/dist/token-goat-chunk-AM5V6GSX.mjs +367 -0
  29. package/dist/{token-goat-chunk-I7CB3X4K.mjs → token-goat-chunk-APGZXSPS.mjs} +44 -148
  30. package/dist/{token-goat-chunk-BJBRGPBX.mjs → token-goat-chunk-ARDNEC2U.mjs} +11 -7
  31. package/dist/token-goat-chunk-ATCPY7EQ.mjs +134 -0
  32. package/dist/token-goat-chunk-B2RZZCSS.mjs +354 -0
  33. package/dist/{token-goat-chunk-QM76S6YS.mjs → token-goat-chunk-B45VMIIH.mjs} +6 -5
  34. package/dist/token-goat-chunk-BPGCUMR7.mjs +30 -0
  35. package/dist/{token-goat-chunk-GGLEE35R.mjs → token-goat-chunk-C63JQV5K.mjs} +49 -10
  36. package/dist/{token-goat-chunk-RJH64KQH.mjs → token-goat-chunk-COBQGL5S.mjs} +2661 -2440
  37. package/dist/token-goat-chunk-COTXZHTS.mjs +39 -0
  38. package/dist/token-goat-chunk-CYCEYAEO.mjs +265 -0
  39. package/dist/token-goat-chunk-CZ3LUXYZ.mjs +4115 -0
  40. package/dist/token-goat-chunk-DZX2YDPT.mjs +15 -0
  41. package/dist/token-goat-chunk-E3OQX2XT.mjs +824 -0
  42. package/dist/token-goat-chunk-EFHMMIGP.mjs +68 -0
  43. package/dist/token-goat-chunk-ETBHVDB6.mjs +328 -0
  44. package/dist/token-goat-chunk-EVMZJ27Z.mjs +147 -0
  45. package/dist/token-goat-chunk-EXKGNHEG.mjs +2096 -0
  46. package/dist/{token-goat-chunk-6Z5ULNE5.mjs → token-goat-chunk-FBNQNSJK.mjs} +2490 -4957
  47. package/dist/{token-goat-chunk-NMTKNYGF.mjs → token-goat-chunk-FNFBKLRD.mjs} +74 -9
  48. package/dist/{token-goat-chunk-XI2VFAV6.mjs → token-goat-chunk-FZ3NEW5O.mjs} +33 -19
  49. package/dist/token-goat-chunk-G5PJ7AGM.mjs +36 -0
  50. package/dist/{token-goat-chunk-VE27HPIF.mjs → token-goat-chunk-GFBSN7BD.mjs} +30 -398
  51. package/dist/{token-goat-chunk-L45ZQRT7.mjs → token-goat-chunk-GOLEOXZP.mjs} +780 -786
  52. package/dist/token-goat-chunk-H2K3QP6H.mjs +24 -0
  53. package/dist/token-goat-chunk-H2PHHGM5.mjs +188 -0
  54. package/dist/token-goat-chunk-HAVAOB3S.mjs +87 -0
  55. package/dist/token-goat-chunk-HG45AF2B.mjs +2228 -0
  56. package/dist/{token-goat-chunk-CBMY2FGI.mjs → token-goat-chunk-HOJLCGDP.mjs} +17113 -15554
  57. package/dist/{token-goat-chunk-HUDC5GS5.mjs → token-goat-chunk-HYBFA5X3.mjs} +120 -19
  58. package/dist/token-goat-chunk-IVALLT3S.mjs +48 -0
  59. package/dist/token-goat-chunk-IVE6U7KV.mjs +53 -0
  60. package/dist/{token-goat-chunk-UBUKHVYW.mjs → token-goat-chunk-IVKIZWAB.mjs} +3 -3
  61. package/dist/{token-goat-chunk-4JMWPWCS.mjs → token-goat-chunk-JB6QN6VF.mjs} +6 -4
  62. package/dist/{token-goat-chunk-Q4S3UQGO.mjs → token-goat-chunk-JDHE26RP.mjs} +10 -3
  63. package/dist/{token-goat-chunk-7R2XYKC5.mjs → token-goat-chunk-JDU3EXSU.mjs} +14 -10
  64. package/dist/token-goat-chunk-JDWCRD6M.mjs +253 -0
  65. package/dist/{token-goat-chunk-XBESNWEX.mjs → token-goat-chunk-JN4XMLSD.mjs} +7 -4
  66. package/dist/token-goat-chunk-JTQQGXZH.mjs +733 -0
  67. package/dist/token-goat-chunk-KKUFXAPD.mjs +25 -0
  68. package/dist/token-goat-chunk-KQNZDCBD.mjs +47 -0
  69. package/dist/{token-goat-chunk-4RN64ZND.mjs → token-goat-chunk-KWPNJBDH.mjs} +28 -3
  70. package/dist/token-goat-chunk-LOBGHXPB.mjs +242 -0
  71. package/dist/token-goat-chunk-MKPF4CL5.mjs +37 -0
  72. package/dist/token-goat-chunk-MNWKPRAL.mjs +13 -0
  73. package/dist/{token-goat-chunk-YWSP6IU7.mjs → token-goat-chunk-N2NMER56.mjs} +25 -15
  74. package/dist/token-goat-chunk-NYKZLXMK.mjs +218 -0
  75. package/dist/token-goat-chunk-OJBNYTJP.mjs +3087 -0
  76. package/dist/token-goat-chunk-P4QMM4WK.mjs +295 -0
  77. package/dist/token-goat-chunk-PD5VKH46.mjs +184 -0
  78. package/dist/token-goat-chunk-PEPTHRFF.mjs +129 -0
  79. package/dist/{token-goat-chunk-VWZKZPSR.mjs → token-goat-chunk-PU7V3FD6.mjs} +8752 -11098
  80. package/dist/token-goat-chunk-PY533T7F.mjs +46 -0
  81. package/dist/token-goat-chunk-Q5VTGRH7.mjs +761 -0
  82. package/dist/{token-goat-chunk-IHKZ3QNA.mjs → token-goat-chunk-QCLDAQTS.mjs} +33 -19
  83. package/dist/{token-goat-chunk-LKSXAMJB.mjs → token-goat-chunk-QSBRTGM2.mjs} +9 -2
  84. package/dist/{token-goat-chunk-4STDIGYC.mjs → token-goat-chunk-RC35RBUL.mjs} +7 -5
  85. package/dist/{token-goat-chunk-D5ICEPSB.mjs → token-goat-chunk-RHXKCZX3.mjs} +887 -507
  86. package/dist/{token-goat-chunk-RSS3TLXU.mjs → token-goat-chunk-RZRTDST7.mjs} +17 -7
  87. package/dist/{token-goat-chunk-MAMQPC43.mjs → token-goat-chunk-SJHWVNDQ.mjs} +15 -21
  88. package/dist/token-goat-chunk-SMVRN2HU.mjs +188 -0
  89. package/dist/{token-goat-chunk-EL7M26WP.mjs → token-goat-chunk-SQSSNQPE.mjs} +2100 -1442
  90. package/dist/{token-goat-chunk-OZRSREKR.mjs → token-goat-chunk-T4FK7VOV.mjs} +3 -3
  91. package/dist/token-goat-chunk-U4N3BN2W.mjs +92 -0
  92. package/dist/token-goat-chunk-UA5V6P3P.mjs +122 -0
  93. package/dist/{token-goat-chunk-XKY4VKJ4.mjs → token-goat-chunk-UQ5UK2T7.mjs} +15 -4
  94. package/dist/token-goat-chunk-USILZ3T3.mjs +53 -0
  95. package/dist/token-goat-chunk-VES7EL7O.mjs +205 -0
  96. package/dist/{token-goat-chunk-M56BWPBN.mjs → token-goat-chunk-VL3YIFHZ.mjs} +550 -49
  97. package/dist/{token-goat-chunk-IZXKVT4A.mjs → token-goat-chunk-VPBBTSJR.mjs} +362 -128
  98. package/dist/{token-goat-chunk-F2ARFHLJ.mjs → token-goat-chunk-W3QCJS6G.mjs} +10 -2
  99. package/dist/{token-goat-chunk-FSTWAOW6.mjs → token-goat-chunk-WY3L4DVT.mjs} +11 -5
  100. package/dist/{token-goat-chunk-OSUFN2FV.mjs → token-goat-chunk-XB5KKOCG.mjs} +5 -25
  101. package/dist/token-goat-chunk-XKI4SEMX.mjs +66 -0
  102. package/dist/token-goat-chunk-XU4P6Z24.mjs +133 -0
  103. package/dist/{token-goat-chunk-6CCQDAYY.mjs → token-goat-chunk-Y776AENC.mjs} +138 -33
  104. package/dist/token-goat-chunk-YARZFCZS.mjs +359 -0
  105. package/dist/{token-goat-chunk-EEIDFMEM.mjs → token-goat-chunk-YZAAZU2S.mjs} +12 -3
  106. package/dist/{token-goat-chunk-E3K3BTEQ.mjs → token-goat-chunk-Z44YO3QZ.mjs} +12 -6
  107. package/dist/token-goat-chunk-Z57YODA2.mjs +35 -0
  108. package/dist/{token-goat-chunk-DA43OE7L.mjs → token-goat-chunk-ZCDTCVIS.mjs} +49 -30
  109. package/dist/token-goat-chunk-ZEJVMUQH.mjs +48 -0
  110. package/dist/{token-goat-chunk-BGHSSJUA.mjs → token-goat-chunk-ZFOBKUWH.mjs} +1 -1
  111. package/dist/token-goat-chunk-ZMBL6UVV.mjs +110 -0
  112. package/dist/{token-goat-chunk-SJEKA7Y2.mjs → token-goat-chunk-ZQSJMO2R.mjs} +381 -201
  113. package/dist/token-goat-hook-client.cjs +539 -0
  114. package/dist/token-goat-hook-client.mjs +26 -0
  115. package/dist/token-goat-hook.mjs +48 -28
  116. package/dist/token-goat.core.mjs +10 -45
  117. package/docs/C4_RUNTIME_ARCHITECTURE.md +3 -3
  118. package/docs/cli.md +82 -47
  119. package/docs/install.md +58 -23
  120. package/docs/security.md +7 -7
  121. package/package.json +17 -7
  122. package/scripts/verify-native-dist.mjs +386 -0
  123. package/dist/token-goat-chunk-4JJBFT7V.mjs +0 -20
  124. package/dist/token-goat-chunk-5NNYIUGV.mjs +0 -143
  125. package/dist/token-goat-chunk-6DQNNFJ6.mjs +0 -294
  126. package/dist/token-goat-chunk-7MAFDRVR.mjs +0 -47
  127. package/dist/token-goat-chunk-BCN2YQC6.mjs +0 -32
  128. package/dist/token-goat-chunk-D7GHQKQD.mjs +0 -30
  129. package/dist/token-goat-chunk-GMOUBOX4.mjs +0 -386
  130. package/dist/token-goat-chunk-IFORDBGC.mjs +0 -192
  131. package/dist/token-goat-chunk-JXK2HQXS.mjs +0 -318
  132. package/dist/token-goat-chunk-L7SDVGBT.mjs +0 -430
  133. package/dist/token-goat-chunk-MMLMALWK.mjs +0 -1381
  134. package/dist/token-goat-chunk-MVSWBNMD.mjs +0 -1985
@@ -0,0 +1,761 @@
1
+ import { createRequire as __cjsRequire } from 'node:module';
2
+ const require = __cjsRequire(import.meta.url);
3
+ import {
4
+ computeAdaptiveBudget,
5
+ formatAge,
6
+ getContextPressure,
7
+ isNoisePath,
8
+ listSiblingSessionStates,
9
+ loadSessionCache,
10
+ sessionSidecarPath
11
+ } from "./token-goat-chunk-Y776AENC.mjs";
12
+ import {
13
+ getBashOutput,
14
+ indexRecallEntry
15
+ } from "./token-goat-chunk-AFLYLHDH.mjs";
16
+ import {
17
+ WEB_FETCH_KEY_SEP,
18
+ getSessionBashOutputs,
19
+ getSessionBashReruns,
20
+ getSessionFiles,
21
+ getSessionWebFetches
22
+ } from "./token-goat-chunk-C63JQV5K.mjs";
23
+ import {
24
+ blobPath,
25
+ isBlobStale,
26
+ loadBlob,
27
+ storeBlob
28
+ } from "./token-goat-chunk-ARDNEC2U.mjs";
29
+ import {
30
+ redactSecrets
31
+ } from "./token-goat-chunk-4FVIAHSI.mjs";
32
+ import {
33
+ findProject,
34
+ loadConfig,
35
+ shortFingerprint
36
+ } from "./token-goat-chunk-7IN2MKDS.mjs";
37
+ import {
38
+ registerReset
39
+ } from "./token-goat-chunk-YZAAZU2S.mjs";
40
+ import {
41
+ LOCK_WAIT_MS_HARDENED,
42
+ atomicWriteText,
43
+ ensureDirSync,
44
+ runGit,
45
+ toKB,
46
+ withFileLock,
47
+ withRetryOnLock
48
+ } from "./token-goat-chunk-GOLEOXZP.mjs";
49
+ import {
50
+ foldPath,
51
+ resolveOnPath,
52
+ sleepSync,
53
+ spawnResolvedSync
54
+ } from "./token-goat-chunk-AM5V6GSX.mjs";
55
+ import {
56
+ UNTRUSTED_FILE_TAG,
57
+ displaySafePath,
58
+ displaySafeText,
59
+ fenceUntrustedFileContent,
60
+ neutralizeSpokenMarkers
61
+ } from "./token-goat-chunk-FNFBKLRD.mjs";
62
+ import {
63
+ dataDir
64
+ } from "./token-goat-chunk-VES7EL7O.mjs";
65
+ import {
66
+ init_define_import_meta_env
67
+ } from "./token-goat-chunk-A37V4PBF.mjs";
68
+
69
+ // src/manifest.ts
70
+ init_define_import_meta_env();
71
+
72
+ // src/web_cache.ts
73
+ init_define_import_meta_env();
74
+ import * as fs from "node:fs";
75
+ var WEB_OUTPUT_SUBDIR = "web_outputs";
76
+ var _byId = /* @__PURE__ */ new Map();
77
+ var _rawById = /* @__PURE__ */ new Map();
78
+ var _urlIndex = /* @__PURE__ */ new Map();
79
+ function cacheIdForUrl(url) {
80
+ return shortFingerprint(url);
81
+ }
82
+ function storeWebOutput(url, content, dedupKey = url, rawContent) {
83
+ const cacheId = cacheIdForUrl(dedupKey);
84
+ const redactedContent = redactSecrets(content).text;
85
+ _byId.set(cacheId, redactedContent);
86
+ _urlIndex.set(url, cacheId);
87
+ const redactedRaw = rawContent !== void 0 && rawContent !== content ? redactSecrets(rawContent).text : void 0;
88
+ if (redactedRaw !== void 0) _rawById.set(cacheId, redactedRaw);
89
+ else _rawById.delete(cacheId);
90
+ storeBlob(WEB_OUTPUT_SUBDIR, cacheId, redactedRaw !== void 0 ? { url, content: redactedContent, raw: redactedRaw } : { url, content: redactedContent });
91
+ const redactedUrl = redactSecrets(url).text;
92
+ indexRecallEntry("web", cacheId, redactedUrl, `${redactedUrl}
93
+ ${redactedContent}`, Date.now());
94
+ return cacheId;
95
+ }
96
+ function coerceWebBlob(raw) {
97
+ if (raw === null || typeof raw !== "object") return null;
98
+ const o = raw;
99
+ if (typeof o["content"] !== "string") return null;
100
+ return { url: typeof o["url"] === "string" ? o["url"] : null, content: o["content"], raw: typeof o["raw"] === "string" ? o["raw"] : null };
101
+ }
102
+ function getWebOutput(cacheId) {
103
+ const hit = _byId.get(cacheId);
104
+ if (hit !== void 0) return hit;
105
+ if (isBlobStale(WEB_OUTPUT_SUBDIR, cacheId)) return null;
106
+ const blob = coerceWebBlob(loadBlob(WEB_OUTPUT_SUBDIR, cacheId));
107
+ if (blob === null) return null;
108
+ _byId.set(cacheId, blob.content);
109
+ if (blob.raw !== null) _rawById.set(cacheId, blob.raw);
110
+ if (blob.url !== null) _urlIndex.set(blob.url, cacheId);
111
+ return blob.content;
112
+ }
113
+ function hasWebOutput(cacheId) {
114
+ if (_byId.has(cacheId)) return true;
115
+ const p = blobPath(WEB_OUTPUT_SUBDIR, cacheId);
116
+ if (p === null || isBlobStale(WEB_OUTPUT_SUBDIR, cacheId)) return false;
117
+ return fs.existsSync(p);
118
+ }
119
+ function getWebOutputRaw(cacheId) {
120
+ const cleaned = getWebOutput(cacheId);
121
+ if (cleaned === null) return null;
122
+ return _rawById.get(cacheId) ?? cleaned;
123
+ }
124
+ function getWebOutputByUrlFromDisk(url, dedupKey = url) {
125
+ const cacheId = cacheIdForUrl(dedupKey);
126
+ const content = getWebOutput(cacheId);
127
+ if (content === null) return null;
128
+ return { cacheId, content };
129
+ }
130
+ registerReset(() => {
131
+ _byId = /* @__PURE__ */ new Map();
132
+ _rawById = /* @__PURE__ */ new Map();
133
+ _urlIndex = /* @__PURE__ */ new Map();
134
+ }, { perRequest: true });
135
+
136
+ // src/project_memory.ts
137
+ init_define_import_meta_env();
138
+ import * as fs2 from "node:fs";
139
+ import * as path from "node:path";
140
+ var MAX_ENTRIES = 30;
141
+ var MAX_VALUE_LEN = 300;
142
+ var MAX_TOTAL_CHARS = 4e3;
143
+ var KEY_RE = /^[A-Za-z0-9_-]{1,80}$/;
144
+ var SET_AT_RE = /^#\s*set\s+(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)$/;
145
+ var ANCHOR_RE = /^#\s*anchor:\s*(\S.*)::([^:@\s]+)@([0-9a-f]{64})$/;
146
+ function anchorLabel(status) {
147
+ if (status === "changed") return " (changed since note)";
148
+ if (status === "gone") return " (anchored symbol gone)";
149
+ return "";
150
+ }
151
+ function anchorLine(anchor) {
152
+ const line = `# anchor: ${anchor.file}::${anchor.symbol}@${anchor.sha}`;
153
+ const back = ANCHOR_RE.exec(line);
154
+ return back !== null && back[1] === anchor.file && back[2] === anchor.symbol ? line : null;
155
+ }
156
+ function noteMap() {
157
+ return /* @__PURE__ */ Object.create(null);
158
+ }
159
+ function ordinal(a, b) {
160
+ return a < b ? -1 : a > b ? 1 : 0;
161
+ }
162
+ function memoryPath(projectHash) {
163
+ return path.join(dataDir(), "projects", `${projectHash}_memory.toml`);
164
+ }
165
+ function validateKey(key) {
166
+ if (!KEY_RE.test(key)) {
167
+ throw new Error(
168
+ `Invalid memory key ${JSON.stringify(key)}: use only letters, digits, hyphens, underscores (max 80 chars)`
169
+ );
170
+ }
171
+ }
172
+ function parseTOML(content, unparsed = [], setAt = /* @__PURE__ */ new Map(), anchors = /* @__PURE__ */ new Map()) {
173
+ const result = noteMap();
174
+ let pendingSetAt;
175
+ let pendingAnchor;
176
+ for (const [i, line] of content.split("\n").entries()) {
177
+ const trimmed = line.trim();
178
+ if (!trimmed) {
179
+ continue;
180
+ }
181
+ if (trimmed.startsWith("#")) {
182
+ const time = SET_AT_RE.exec(trimmed)?.[1];
183
+ if (time !== void 0 && !Number.isNaN(Date.parse(time))) pendingSetAt = time;
184
+ const anchor = ANCHOR_RE.exec(trimmed);
185
+ if (anchor !== null) pendingAnchor = { file: anchor[1], symbol: anchor[2], sha: anchor[3] };
186
+ continue;
187
+ }
188
+ const entrySetAt = pendingSetAt;
189
+ const entryAnchor = pendingAnchor;
190
+ pendingSetAt = void 0;
191
+ pendingAnchor = void 0;
192
+ const match = trimmed.match(/^([A-Za-z0-9_-]+)\s*=\s*"(.*)"\s*$/s);
193
+ if (match) {
194
+ const [, key, value] = match;
195
+ if (key && value !== void 0) {
196
+ const unescaped = value.replace(/\\(u202[89]|[\\nrt"])/g, (_, c) => {
197
+ switch (c) {
198
+ case "u2028":
199
+ return "\u2028";
200
+ case "u2029":
201
+ return "\u2029";
202
+ case "\\":
203
+ return "\\";
204
+ case "n":
205
+ return "\n";
206
+ case "r":
207
+ return "\r";
208
+ case '"':
209
+ return '"';
210
+ default:
211
+ return _;
212
+ }
213
+ });
214
+ result[key] = unescaped;
215
+ if (entrySetAt === void 0) setAt.delete(key);
216
+ else setAt.set(key, entrySetAt);
217
+ if (entryAnchor === void 0) anchors.delete(key);
218
+ else anchors.set(key, entryAnchor);
219
+ }
220
+ } else {
221
+ unparsed.push(i + 1);
222
+ }
223
+ }
224
+ return result;
225
+ }
226
+ function loadRaw(filePath, forUpdate = false, setAt, anchors) {
227
+ let content = "";
228
+ try {
229
+ withRetryOnLock(() => {
230
+ content = fs2.readFileSync(filePath, "utf-8");
231
+ });
232
+ } catch (err) {
233
+ if (err.code === "ENOENT") return noteMap();
234
+ throw err;
235
+ }
236
+ const unparsed = [];
237
+ const entries = parseTOML(content, unparsed, setAt, anchors);
238
+ if (forUpdate && unparsed.length > 0) {
239
+ const one = unparsed.length === 1;
240
+ throw new Error(`Not updating ${filePath}: ${one ? "line" : "lines"} ${unparsed.join(", ")} ${one ? "is" : "are"} not in the key = "value" form, and saving would drop ${one ? "it" : "them"}. Fix or remove ${one ? "it" : "them"}, then try again.`);
241
+ }
242
+ return entries;
243
+ }
244
+ function save(filePath, entries, setAt = /* @__PURE__ */ new Map(), anchors = /* @__PURE__ */ new Map()) {
245
+ const lines = [];
246
+ const sorted = Object.entries(entries).sort(([a], [b]) => ordinal(a, b));
247
+ for (const [k, v] of sorted) {
248
+ const escaped = v.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
249
+ const time = setAt.get(k);
250
+ if (time !== void 0) lines.push(`# set ${time}`);
251
+ const anchor = anchors.get(k);
252
+ const anchored = anchor === void 0 ? null : anchorLine(anchor);
253
+ if (anchored !== null) lines.push(anchored);
254
+ lines.push(`${k} = "${escaped}"`);
255
+ }
256
+ const content = lines.length > 0 ? lines.join("\n") + "\n" : "";
257
+ const dir = path.dirname(filePath);
258
+ ensureDirSync(dir);
259
+ atomicWriteText(filePath, content);
260
+ }
261
+ function loadEntries(projectHash) {
262
+ return loadRaw(memoryPath(projectHash));
263
+ }
264
+ function loadDatedEntries(projectHash) {
265
+ const setAt = /* @__PURE__ */ new Map();
266
+ const anchors = /* @__PURE__ */ new Map();
267
+ const entries = loadRaw(memoryPath(projectHash), false, setAt, anchors);
268
+ const result = noteMap();
269
+ for (const [key, value] of Object.entries(entries)) {
270
+ const note = { value };
271
+ const time = setAt.get(key);
272
+ if (time !== void 0) note.setAt = time;
273
+ const anchor = anchors.get(key);
274
+ if (anchor !== void 0) note.anchor = anchor;
275
+ result[key] = note;
276
+ }
277
+ return result;
278
+ }
279
+ function noteAgeLabel(note, now = Date.now()) {
280
+ if (note.setAt === void 0) return "";
281
+ return ` (set ${formatAge(Math.max(0, now - Date.parse(note.setAt)))} ago)`;
282
+ }
283
+ function oneLineNoteValue(value) {
284
+ return value.replace(/\r\n|[\r\n\u0085\u2028\u2029]/g, "\\n");
285
+ }
286
+ function byRecency(a, aSetAt, b, bSetAt) {
287
+ const ta = aSetAt === void 0 ? Number.NEGATIVE_INFINITY : Date.parse(aSetAt);
288
+ const tb = bSetAt === void 0 ? Number.NEGATIVE_INFINITY : Date.parse(bSetAt);
289
+ return ta !== tb ? ta > tb ? -1 : 1 : ordinal(a, b);
290
+ }
291
+ function setEntry(projectHash, key, value, anchor) {
292
+ validateKey(key);
293
+ const p = memoryPath(projectHash);
294
+ const dir = path.dirname(p);
295
+ ensureDirSync(dir);
296
+ const result = { evicted: [] };
297
+ const doSet = () => {
298
+ const setAt = /* @__PURE__ */ new Map();
299
+ const anchors = /* @__PURE__ */ new Map();
300
+ const entries = loadRaw(p, true, setAt, anchors);
301
+ const old = Object.hasOwn(entries, key) ? entries[key] : void 0;
302
+ if (old !== void 0) result.previous = old;
303
+ const isNewKey = !Object.hasOwn(entries, key);
304
+ if (isNewKey && Object.keys(entries).length >= MAX_ENTRIES) {
305
+ const keysToKeep = MAX_ENTRIES - 1;
306
+ const allKeys = Object.keys(entries).sort((a, b) => byRecency(a, setAt.get(a), b, setAt.get(b)));
307
+ for (const k of allKeys.slice(keysToKeep)) {
308
+ result.evicted.push(k);
309
+ delete entries[k];
310
+ setAt.delete(k);
311
+ anchors.delete(k);
312
+ }
313
+ }
314
+ entries[key] = value;
315
+ setAt.set(key, (/* @__PURE__ */ new Date()).toISOString());
316
+ if (anchor === void 0) anchors.delete(key);
317
+ else anchors.set(key, anchor);
318
+ save(p, entries, setAt, anchors);
319
+ return true;
320
+ };
321
+ underNotesLock(p, doSet);
322
+ return result;
323
+ }
324
+ function underNotesLock(p, update) {
325
+ const lockPath = `${p}.lock`;
326
+ ensureDirSync(path.dirname(p));
327
+ for (let attempt = 1; attempt <= 3; attempt++) {
328
+ if (withFileLock(lockPath, update, { waitMs: LOCK_WAIT_MS_HARDENED }) !== void 0) return;
329
+ if (fs2.existsSync(lockPath)) break;
330
+ if (attempt < 3) sleepSync(50 * attempt);
331
+ }
332
+ throw new Error(`Could not lock ${p} for writing; no note was changed. Another token-goat process may be writing notes: try again.`);
333
+ }
334
+ function unsetEntry(projectHash, key) {
335
+ validateKey(key);
336
+ const p = memoryPath(projectHash);
337
+ let removed = false;
338
+ const doUnset = () => {
339
+ const setAt = /* @__PURE__ */ new Map();
340
+ const anchors = /* @__PURE__ */ new Map();
341
+ const entries = loadRaw(p, true, setAt, anchors);
342
+ if (Object.hasOwn(entries, key)) {
343
+ delete entries[key];
344
+ save(p, entries, setAt, anchors);
345
+ removed = true;
346
+ }
347
+ return true;
348
+ };
349
+ underNotesLock(p, doUnset);
350
+ return removed;
351
+ }
352
+ function clearAll(projectHash) {
353
+ const p = memoryPath(projectHash);
354
+ const doClear = () => {
355
+ if (fs2.existsSync(p)) {
356
+ save(p, {});
357
+ }
358
+ return true;
359
+ };
360
+ underNotesLock(p, doClear);
361
+ }
362
+ function buildInjection(projectHash, root, statusOf) {
363
+ try {
364
+ const entries = loadDatedEntries(projectHash);
365
+ if (Object.keys(entries).length === 0) {
366
+ return null;
367
+ }
368
+ const now = Date.now();
369
+ const header = '### Project notes (`token-goat note set <key> "<finding>"`)';
370
+ const render2 = (shown2, skipped) => {
371
+ const parts = [header];
372
+ if (shown2.length > 0) parts.push(fenceUntrustedFileContent(shown2.join("\n")));
373
+ if (skipped > 0) parts.push(`- (+${skipped} more memory entries omitted)`);
374
+ return parts.join("\n");
375
+ };
376
+ const entries_list = Object.entries(entries).sort(([a, na], [b, nb]) => byRecency(a, na.setAt, b, nb.setAt));
377
+ const shown = [];
378
+ for (const [key, note] of entries_list.slice(0, MAX_ENTRIES)) {
379
+ const val = note.value;
380
+ const display = val.length <= MAX_VALUE_LEN ? val : val.slice(0, MAX_VALUE_LEN) + "\u2026";
381
+ const flag = root === void 0 || statusOf === void 0 || note.anchor === void 0 ? "" : anchorLabel(statusOf(root, note.anchor));
382
+ const line = `- **${key}**${noteAgeLabel(note, now)}${flag}: ${oneLineNoteValue(display)}`;
383
+ if (render2([...shown, line], entries_list.length - shown.length - 1).length > MAX_TOTAL_CHARS) break;
384
+ shown.push(line);
385
+ }
386
+ return render2(shown, entries_list.length - shown.length);
387
+ } catch {
388
+ return null;
389
+ }
390
+ }
391
+ function projectNotesFor(cwd, statusOf) {
392
+ if (cwd === void 0) return null;
393
+ try {
394
+ const project = findProject(cwd);
395
+ return project === null ? null : buildInjection(project.hash, project.root, statusOf);
396
+ } catch {
397
+ return null;
398
+ }
399
+ }
400
+
401
+ // src/manifest_fit.ts
402
+ init_define_import_meta_env();
403
+ var RESERVE_SHARE = 0.25;
404
+ function cost(lines) {
405
+ let n = 0;
406
+ for (const line of lines) n += line.length + 1;
407
+ return n;
408
+ }
409
+ var moreLine = (n) => `- ...and ${n} more`;
410
+ function rowsThatFit(s, room) {
411
+ const rows = s.rows ?? [];
412
+ const fixed = cost(s.header) + cost(s.footer ?? []);
413
+ if (rows.length === 0) return fixed <= room ? 0 : null;
414
+ const limit = Math.min(rows.length, s.maxRows ?? rows.length);
415
+ const prefix = [0];
416
+ for (let i = 0; i < limit; i++) prefix.push(prefix[i] + rows[i].length + 1);
417
+ for (let k = limit; k >= 1; k--) {
418
+ const tail = k < rows.length ? moreLine(rows.length - k).length + 1 : 0;
419
+ if (fixed + prefix[k] + tail <= room) return k;
420
+ }
421
+ return null;
422
+ }
423
+ function render(s, k) {
424
+ const rows = s.rows ?? [];
425
+ const lines = [...s.header, ...rows.slice(0, k), ...s.footer ?? []];
426
+ if (rows.length > 0 && k < rows.length) lines.push(moreLine(rows.length - k));
427
+ return lines;
428
+ }
429
+ function fitSections(sections, budget) {
430
+ const shown = sections.map(() => null);
431
+ let room = budget + 1;
432
+ const place = (indices2, limit) => {
433
+ let spent = 0;
434
+ for (const i of indices2) {
435
+ const k = rowsThatFit(sections[i], Math.min(limit, room) - spent);
436
+ if (k === null) continue;
437
+ shown[i] = k;
438
+ spent += cost(render(sections[i], k));
439
+ }
440
+ room -= spent;
441
+ };
442
+ const indices = sections.map((_, i) => i);
443
+ place(indices.filter((i) => sections[i].priority === 0 && sections[i].reserved !== true), room);
444
+ place(indices.filter((i) => sections[i].reserved === true), Math.floor(budget * RESERVE_SHARE));
445
+ const rest = indices.filter((i) => sections[i].priority !== 0 && sections[i].reserved !== true);
446
+ rest.sort((a, b) => sections[a].priority - sections[b].priority || a - b);
447
+ place(rest, room);
448
+ const lines = [];
449
+ const omitted = [];
450
+ sections.forEach((s, i) => {
451
+ const k = shown[i];
452
+ if (k === null || k === void 0) omitted.push(s.header.find((l) => l !== "") ?? "");
453
+ else lines.push(...render(s, k));
454
+ });
455
+ return { text: lines.join("\n"), shown: shown.map((k) => k ?? 0), omitted };
456
+ }
457
+
458
+ // src/manifest.ts
459
+ var MEM_EPOCH_TIMEOUT_MS = 800;
460
+ var MAX_ROWS = 40;
461
+ function renderReadRow(entry) {
462
+ const kb = Math.max(1, toKB(entry.sizeBytes));
463
+ const plural = entry.readCount === 1 ? "read" : "reads";
464
+ const edited = entry.wasEdited ? ", edited" : "";
465
+ return `- ${displaySafePath(entry.path)} (${kb}kb, ${entry.readCount} ${plural}${edited})`;
466
+ }
467
+ function renderSymbolReadRow(entry) {
468
+ return `- ${displaySafePath(entry.path)} (symbols: ${(entry.symbols_read ?? []).map(displaySafeText).join(", ")})`;
469
+ }
470
+ function mergeManifestFiles(parent, siblingFiles) {
471
+ const byPath = /* @__PURE__ */ new Map();
472
+ for (const f of parent) byPath.set(foldPath(f.path), f);
473
+ for (const f of siblingFiles) {
474
+ const key = foldPath(f.path);
475
+ const prev = byPath.get(key);
476
+ if (prev === void 0) {
477
+ byPath.set(key, f);
478
+ continue;
479
+ }
480
+ const mergedSymbols = [.../* @__PURE__ */ new Set([...prev.symbols_read ?? [], ...f.symbols_read ?? []])];
481
+ byPath.set(key, {
482
+ path: prev.path,
483
+ readCount: Math.max(prev.readCount, f.readCount),
484
+ lastReadAt: Math.max(prev.lastReadAt, f.lastReadAt),
485
+ wasEdited: prev.wasEdited || f.wasEdited,
486
+ sizeBytes: f.lastReadAt >= prev.lastReadAt ? f.sizeBytes : prev.sizeBytes,
487
+ ...prev.wasTruncated || f.wasTruncated ? { wasTruncated: true } : {},
488
+ ...mergedSymbols.length > 0 ? { symbols_read: mergedSymbols } : {}
489
+ });
490
+ }
491
+ return Array.from(byPath.values());
492
+ }
493
+ function renderWebFetchRow(key, cacheId, live = true) {
494
+ const [url = key, prompt = ""] = key.split(WEB_FETCH_KEY_SEP);
495
+ if (!live) return `- ${displaySafeText(url)} (cache expired)`;
496
+ const promptSuffix = prompt ? `, prompt: ${neutralizeSpokenMarkers(JSON.stringify(prompt))}` : "";
497
+ return `- ${displaySafeText(url)} (cacheId: ${cacheId}${promptSuffix})`;
498
+ }
499
+ function renderWebFetchRows(entries) {
500
+ const live = entries.map(([, cacheId]) => hasWebOutput(cacheId));
501
+ if (entries.length > 0 && !live.includes(true)) {
502
+ const urls = entries.map(([key]) => displaySafeText(key.split(WEB_FETCH_KEY_SEP)[0] ?? key));
503
+ return [`- ${entries.length} fetched page${entries.length === 1 ? "" : "s"}, cache expired: ${urls.join(", ")}`];
504
+ }
505
+ return entries.map(([key, cacheId], n) => renderWebFetchRow(key, cacheId, live[n]));
506
+ }
507
+ function selectManifestFiles(siblings) {
508
+ const ownFiles = [...getSessionFiles().values()];
509
+ const siblingFiles = siblings.flatMap((s) => s.files);
510
+ const files = siblingFiles.length > 0 ? mergeManifestFiles(ownFiles, siblingFiles) : ownFiles;
511
+ const editedFiles = files.filter((f) => f.wasEdited);
512
+ const readFiles = files.filter((f) => f.readCount > 0 && !f.wasEdited && !isNoisePath(f.path));
513
+ const symbolOnlyFiles = files.filter((f) => f.readCount === 0 && !f.wasEdited && (f.symbols_read?.length ?? 0) > 0);
514
+ return { files, readFiles, editedFiles, symbolOnlyFiles };
515
+ }
516
+ function selectManifestWebFetches(siblings) {
517
+ const merged = /* @__PURE__ */ new Map();
518
+ for (const sibling of siblings) for (const [key, cacheId] of sibling.webFetches) merged.set(key, cacheId);
519
+ for (const [key, cacheId] of getSessionWebFetches()) merged.set(key, cacheId);
520
+ return [...merged.entries()];
521
+ }
522
+ function manifestPrintedPaths(sessionId, limit, cwd, transcriptPath) {
523
+ const { printed } = buildManifestParts(sessionId, cwd, transcriptPath);
524
+ return printed.slice(0, limit);
525
+ }
526
+ function buildManifestParts(sessionId, cwd, transcriptPath) {
527
+ const siblings = sessionId !== void 0 ? listSiblingSessionStates(sessionId) : [];
528
+ const { files, readFiles, editedFiles, symbolOnlyFiles } = selectManifestFiles(siblings);
529
+ const webFetches = selectManifestWebFetches(siblings);
530
+ const fileSections = [];
531
+ const fileSection = (header, entries, render2, priority) => {
532
+ if (entries.length === 0) return [];
533
+ const section = { header: ["", header], rows: entries.map(render2), priority, maxRows: MAX_ROWS };
534
+ fileSections.push({ entries, section });
535
+ return [section];
536
+ };
537
+ const notes = projectNotesFor(cwd);
538
+ const webRows = renderWebFetchRows(webFetches);
539
+ const sections = [
540
+ { header: ["## Session context", `Files read: ${readFiles.length}`, `Files edited: ${editedFiles.length}`], priority: 0 },
541
+ ...fileSection("### Edited files", editedFiles, (entry) => `- ${displaySafePath(entry.path)}`, 1),
542
+ ...notes === null ? [] : [notesSection(notes)],
543
+ ...fileSection("### Surgically read files (symbol/section reads, never read whole)", symbolOnlyFiles, renderSymbolReadRow, 3),
544
+ ...fileSection("### Read files", readFiles, renderReadRow, 4),
545
+ ...webRows.length === 0 ? [] : [{ header: ["", "### Web URLs fetched"], rows: webRows, priority: 5, maxRows: MAX_ROWS }],
546
+ ...buildSafeToDiscardSection(files),
547
+ ...buildMemEpochSection()
548
+ ];
549
+ const fit = fitManifest(sections, sessionId, cwd, transcriptPath);
550
+ const seen = /* @__PURE__ */ new Set();
551
+ const printed = [];
552
+ for (const { entries, section } of fileSections) {
553
+ const count = fit.shown[sections.indexOf(section)] ?? 0;
554
+ for (const entry of entries.slice(0, count)) {
555
+ const path2 = displaySafePath(entry.path);
556
+ if (seen.has(path2)) continue;
557
+ seen.add(path2);
558
+ printed.push(path2);
559
+ }
560
+ }
561
+ return { text: fit.text, printed };
562
+ }
563
+ function buildManifest(sessionId, cwd, transcriptPath) {
564
+ return buildManifestParts(sessionId, cwd, transcriptPath).text;
565
+ }
566
+ function gitDirtySignals(cwd) {
567
+ const timeoutMs = loadConfig().hints.git_hint_max_ms;
568
+ let hasPendingDiff = false;
569
+ try {
570
+ const diffResult = runGit(["diff", "--no-color", "--stat", "HEAD"], { cwd, timeoutMs });
571
+ hasPendingDiff = diffResult.exitCode === 0 && diffResult.stdout.trim() !== "";
572
+ } catch {
573
+ }
574
+ let hasUncommittedChanges = false;
575
+ try {
576
+ const statusResult = runGit(["status", "--porcelain"], { cwd, timeoutMs });
577
+ hasUncommittedChanges = statusResult.exitCode === 0 && statusResult.stdout.trim() !== "";
578
+ } catch {
579
+ }
580
+ return { hasPendingDiff, hasUncommittedChanges };
581
+ }
582
+ function adaptiveCharBonus(sessionId, cwd, transcriptPath) {
583
+ if (!cwd) return 0;
584
+ const cache = loadSessionCache(sessionId ?? "") ?? {};
585
+ const ageSecs = cache.created_ts !== void 0 ? Math.max(0, Date.now() / 1e3 - cache.created_ts) : 0;
586
+ const contextPressure = getContextPressure(cache, transcriptPath);
587
+ const { hasPendingDiff, hasUncommittedChanges } = gitDirtySignals(cwd);
588
+ if (!hasPendingDiff && !hasUncommittedChanges) return 0;
589
+ const baseline = computeAdaptiveBudget(cache, ageSecs, { contextPressure });
590
+ const withGitSignal = computeAdaptiveBudget(cache, ageSecs, { hasPendingDiff, hasUncommittedChanges, contextPressure });
591
+ const deltaTokens = Math.max(0, withGitSignal - baseline);
592
+ return deltaTokens * 3;
593
+ }
594
+ function fitManifest(sections, sessionId, cwd, transcriptPath) {
595
+ const full = fitSections(sections, Infinity);
596
+ const cap = loadConfig().compact_assist.max_manifest_chars;
597
+ if (cap <= 0 || full.text.length <= cap) return full;
598
+ const effectiveCap = cap + adaptiveCharBonus(sessionId, cwd, transcriptPath);
599
+ if (full.text.length <= effectiveCap) return full;
600
+ const fit = fitSections(sections, effectiveCap);
601
+ const gone = fit.omitted.length > 0 ? `; sections omitted: ${fit.omitted.map((h) => h.replace(/^#+\s*/, "")).join(", ")}` : "";
602
+ const notice = `
603
+ ...(manifest truncated at ${effectiveCap} chars; ${full.text.length - fit.text.length} chars omitted${gone})`;
604
+ return { text: closeCutFence(fit.text) + notice, shown: fit.shown };
605
+ }
606
+ function closeCutFence(kept) {
607
+ const open = `<${UNTRUSTED_FILE_TAG}>`;
608
+ const close = `
609
+ </${UNTRUSTED_FILE_TAG}>`;
610
+ const lastOpen = kept.lastIndexOf(open);
611
+ if (lastOpen === -1 || kept.includes(close, lastOpen)) return kept;
612
+ let body = kept;
613
+ for (let n = close.length - 1; n > 0; n--) {
614
+ if (body.endsWith(close.slice(0, n))) {
615
+ body = body.slice(0, -n);
616
+ break;
617
+ }
618
+ }
619
+ return body + close;
620
+ }
621
+ function notesSection(notes) {
622
+ const lines = notes.split("\n");
623
+ const open = lines.indexOf(`<${UNTRUSTED_FILE_TAG}>`);
624
+ const close = lines.lastIndexOf(`</${UNTRUSTED_FILE_TAG}>`);
625
+ if (open === -1 || close < open) return { header: ["", ...lines], priority: 2 };
626
+ const rows = [];
627
+ for (const line of lines.slice(open + 1, close)) {
628
+ if (rows.length > 0 && !line.startsWith("- ")) rows[rows.length - 1] += "\n" + line;
629
+ else rows.push(line);
630
+ }
631
+ return { header: ["", ...lines.slice(0, open + 1)], rows, footer: lines.slice(close), priority: 2, maxRows: MAX_ROWS };
632
+ }
633
+ function buildSafeToDiscardSection(files) {
634
+ const rerunHashes = getSessionBashReruns();
635
+ const bashOutputs = getSessionBashOutputs();
636
+ const rerunHashSet = new Set(rerunHashes);
637
+ const rerunRows = [];
638
+ for (const hash of rerunHashes) {
639
+ const id = bashOutputs.find(([h]) => h === hash)?.[1];
640
+ if (id === void 0) continue;
641
+ const entry = getBashOutput(id);
642
+ if (entry === null) continue;
643
+ const flatCommand = neutralizeSpokenMarkers(entry.command.replace(/[\t\r\n]+/g, " "));
644
+ rerunRows.push("- `" + flatCommand + "` \u2014 an older run of this exact command was superseded; recall the surviving copy with `bash-output " + id + " --full`");
645
+ }
646
+ const supersededReadRows = [];
647
+ for (const f of files) {
648
+ if (f.readCount > 1 || f.wasEdited && f.readCount > 0) {
649
+ const reason = f.wasEdited ? "edited after being read" : "re-read " + f.readCount + "x";
650
+ supersededReadRows.push("- " + displaySafePath(f.path) + " (" + reason + " \u2014 only the latest content already in context is current)");
651
+ }
652
+ }
653
+ const cachedOutputRows = [];
654
+ for (const [hash, id] of bashOutputs) {
655
+ if (rerunHashSet.has(hash)) continue;
656
+ const entry = getBashOutput(id);
657
+ if (entry === null) continue;
658
+ const flatCommand = neutralizeSpokenMarkers(entry.command.replace(/[\t\r\n]+/g, " "));
659
+ cachedOutputRows.push("- `" + flatCommand + "` \u2014 recallable via `bash-output " + id + " --full`");
660
+ }
661
+ const total = rerunRows.length + supersededReadRows.length + cachedOutputRows.length;
662
+ if (total === 0) return [];
663
+ const title = "### SAFE_TO_DISCARD (" + total + " items \u2014 provably inert; each is recallable, not gone)";
664
+ const groups = [
665
+ ["Superseded reruns (" + rerunRows.length + "):", rerunRows],
666
+ ["Superseded file reads (" + supersededReadRows.length + "):", supersededReadRows],
667
+ ["Other cached bash outputs (" + cachedOutputRows.length + "):", cachedOutputRows]
668
+ ];
669
+ const sections = [];
670
+ for (const [header, rows] of groups) {
671
+ if (rows.length === 0) continue;
672
+ sections.push({ header: sections.length === 0 ? ["", title, "", header] : ["", header], rows, priority: 9, reserved: true, maxRows: MAX_ROWS });
673
+ }
674
+ return sections;
675
+ }
676
+ function buildMemEpochSection() {
677
+ let result;
678
+ try {
679
+ const resolved = resolveOnPath("mem");
680
+ if (resolved === null) return [];
681
+ result = spawnResolvedSync(resolved, ["epoch"], {
682
+ encoding: "utf-8",
683
+ timeout: MEM_EPOCH_TIMEOUT_MS,
684
+ windowsHide: true
685
+ });
686
+ } catch {
687
+ return [];
688
+ }
689
+ if (result.error !== void 0 || result.status !== 0) return [];
690
+ const stdout = typeof result.stdout === "string" ? result.stdout.trim() : "";
691
+ if (!/^\d+$/.test(stdout)) return [];
692
+ return [{
693
+ header: ["", "### mem epoch", `mem epoch: ${stdout} (no live TGMEM block is tracked in this session -- only the epoch counter is folded in; see buildMemEpochSection's doc comment)`],
694
+ priority: 9,
695
+ reserved: true
696
+ }];
697
+ }
698
+ var MANIFEST_PREAMBLE = "When summarizing this session, keep the file paths and symbol names below exactly as written -- they are the handles the next turn needs to resume work. Do not paraphrase them into prose.";
699
+ var MANIFEST_RECOVERY_PREAMBLE = "The conversation was just compacted. Below is what this session touched, recovered from token-goat's own ledger rather than from the summary -- use it to re-establish paths and symbol names the summary may have dropped.";
700
+ var BUDGET_ESCALATION_MARKER = "TG-BUDGET-ESCALATION:";
701
+ function summaryBudgetDirective(budgetChars) {
702
+ if (budgetChars <= 0) return "";
703
+ return ` Aim for at most ${budgetChars} characters. Prefer a shorter summary that keeps every path, symbol, command and decision over a longer one that reproduces tool output verbatim: cite the recall id (\`token-goat bash-output <id> --full\`) rather than quoting the output again. If this session genuinely cannot be summarized within that target without losing state the next turn needs, exceed it and open the summary with a single line reading \`${BUDGET_ESCALATION_MARKER} <one-sentence reason>\`.`;
704
+ }
705
+
706
+ // src/compact_dropped.ts
707
+ init_define_import_meta_env();
708
+ import { readFileSync as readFileSync2, rmSync, writeFileSync } from "node:fs";
709
+ import { dirname as dirname2 } from "node:path";
710
+ var DROPPED_SUFFIX = ".compact-dropped";
711
+ function recordCompactDroppedPaths(stateKey, paths) {
712
+ const target = sessionSidecarPath(stateKey, DROPPED_SUFFIX);
713
+ if (target === null) return;
714
+ try {
715
+ if (paths === null || paths.length === 0) {
716
+ rmSync(target, { force: true });
717
+ return;
718
+ }
719
+ ensureDirSync(dirname2(target));
720
+ writeFileSync(target, JSON.stringify(paths), "utf8");
721
+ } catch {
722
+ }
723
+ }
724
+ function readCompactDroppedPaths(stateKey) {
725
+ const target = sessionSidecarPath(stateKey, DROPPED_SUFFIX);
726
+ if (target === null) return [];
727
+ try {
728
+ const parsed = JSON.parse(readFileSync2(target, "utf8"));
729
+ return Array.isArray(parsed) ? parsed.filter((p) => typeof p === "string" && p !== "") : [];
730
+ } catch {
731
+ return [];
732
+ }
733
+ }
734
+
735
+ export {
736
+ WEB_OUTPUT_SUBDIR,
737
+ storeWebOutput,
738
+ getWebOutput,
739
+ getWebOutputRaw,
740
+ getWebOutputByUrlFromDisk,
741
+ MAX_ENTRIES,
742
+ anchorLabel,
743
+ anchorLine,
744
+ loadEntries,
745
+ loadDatedEntries,
746
+ noteAgeLabel,
747
+ oneLineNoteValue,
748
+ setEntry,
749
+ unsetEntry,
750
+ clearAll,
751
+ projectNotesFor,
752
+ renderWebFetchRows,
753
+ manifestPrintedPaths,
754
+ buildManifest,
755
+ MANIFEST_PREAMBLE,
756
+ MANIFEST_RECOVERY_PREAMBLE,
757
+ BUDGET_ESCALATION_MARKER,
758
+ summaryBudgetDirective,
759
+ recordCompactDroppedPaths,
760
+ readCompactDroppedPaths
761
+ };