renor-engine 1.1.0 → 1.3.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.
Files changed (193) hide show
  1. package/README.md +27 -2
  2. package/THIRD-PARTY-NOTICES +2661 -0
  3. package/dist/BUILD.json +3 -3
  4. package/dist/cli.js +1656 -490
  5. package/package.json +16 -80
  6. package/dist/.tsbuildinfo +0 -1
  7. package/dist/api/apiAuth.js +0 -43
  8. package/dist/api/server.js +0 -174
  9. package/dist/buildIdentity.js +0 -149
  10. package/dist/callPhases.js +0 -82
  11. package/dist/cli-extractors.js +0 -46
  12. package/dist/config.js +0 -65
  13. package/dist/context/composer.js +0 -320
  14. package/dist/context/readHonesty.js +0 -478
  15. package/dist/context/rowStore.js +0 -238
  16. package/dist/conversation/formatter.js +0 -81
  17. package/dist/conversation/parser.js +0 -193
  18. package/dist/conversation/types.js +0 -2
  19. package/dist/conversation/writer.js +0 -42
  20. package/dist/db/client.js +0 -149
  21. package/dist/db/handoffTable.js +0 -31
  22. package/dist/db/indexSalvage.js +0 -101
  23. package/dist/db/migrations.js +0 -670
  24. package/dist/db/readCache.js +0 -109
  25. package/dist/db/schema.js +0 -5
  26. package/dist/db/sqlite.js +0 -396
  27. package/dist/db/statements.js +0 -89
  28. package/dist/digests/digestCache.js +0 -146
  29. package/dist/digests/digests.js +0 -597
  30. package/dist/digests/worker.js +0 -350
  31. package/dist/embeddings/caching.js +0 -337
  32. package/dist/embeddings/coalescing.js +0 -177
  33. package/dist/embeddings/interactive.js +0 -103
  34. package/dist/embeddings/local.js +0 -70
  35. package/dist/embeddings/openai.js +0 -106
  36. package/dist/embeddings/rebuild.js +0 -166
  37. package/dist/embeddings/simdScan.js +0 -260
  38. package/dist/embeddings/space.js +0 -21
  39. package/dist/embeddings/types.js +0 -14
  40. package/dist/embeddings/vectorIndex.js +0 -674
  41. package/dist/embeddings/vertex.js +0 -334
  42. package/dist/eval/artifacts.js +0 -42
  43. package/dist/eval/cacheReport.js +0 -146
  44. package/dist/eval/comparison.js +0 -182
  45. package/dist/eval/context700-candidate.js +0 -145
  46. package/dist/eval/evalCache.js +0 -568
  47. package/dist/eval/hashEmbedding.js +0 -35
  48. package/dist/eval/indexSnapshots.js +0 -548
  49. package/dist/eval/longmemeval.js +0 -56
  50. package/dist/eval/metrics.js +0 -181
  51. package/dist/eval/pageDump.js +0 -67
  52. package/dist/eval/renorbenchBaseline.js +0 -486
  53. package/dist/eval/renorbenchDocuments.js +0 -134
  54. package/dist/eval/renorbenchProduct.js +0 -182
  55. package/dist/eval/runLedger.js +0 -279
  56. package/dist/eval/runManifest.js +0 -485
  57. package/dist/eval/scoring.js +0 -197
  58. package/dist/eval/textTokens.js +0 -17
  59. package/dist/evidence/attach.js +0 -264
  60. package/dist/evidence/background.js +0 -147
  61. package/dist/evidence/evidenceCache.js +0 -182
  62. package/dist/evidence/gate.js +0 -37
  63. package/dist/evidence/keyPool.js +0 -85
  64. package/dist/evidence/ollamaChat.js +0 -84
  65. package/dist/evidence/optin.js +0 -165
  66. package/dist/evidence/options.js +0 -151
  67. package/dist/evidence/secondPass.js +0 -294
  68. package/dist/extraction/classifyCapture.js +0 -34
  69. package/dist/extraction/decision-model.js +0 -174
  70. package/dist/extraction/eventExtractor.js +0 -113
  71. package/dist/extraction/extractionClient.js +0 -122
  72. package/dist/extraction/factExtractor.js +0 -46
  73. package/dist/extraction/factsWritePath.js +0 -179
  74. package/dist/extraction/preferenceExtractor.js +0 -150
  75. package/dist/extraction/secretGuard.js +0 -176
  76. package/dist/extraction/secretScanner.js +0 -665
  77. package/dist/extraction/typedFacts.js +0 -224
  78. package/dist/extraction/writePathAdjudication.js +0 -110
  79. package/dist/importing/apply.js +0 -672
  80. package/dist/importing/bundle-write.js +0 -80
  81. package/dist/importing/cli.js +0 -408
  82. package/dist/importing/existing.js +0 -51
  83. package/dist/importing/facts.js +0 -121
  84. package/dist/importing/forgetImported.js +0 -79
  85. package/dist/importing/hosted.js +0 -467
  86. package/dist/importing/journalLog.js +0 -96
  87. package/dist/importing/markdown.js +0 -98
  88. package/dist/importing/plan.js +0 -201
  89. package/dist/importing/secretScreen.js +0 -113
  90. package/dist/importing/serialize.js +0 -188
  91. package/dist/importing/source.js +0 -463
  92. package/dist/importing/types.js +0 -6
  93. package/dist/indexer/chunker.js +0 -319
  94. package/dist/indexer/dailyEntries.js +0 -63
  95. package/dist/indexer/hasher.js +0 -10
  96. package/dist/indexer/laneRuns.js +0 -48
  97. package/dist/indexer/o200k.js +0 -481
  98. package/dist/indexer/outsideRoot.js +0 -77
  99. package/dist/indexer/parser.js +0 -170
  100. package/dist/indexer/pipeline.js +0 -988
  101. package/dist/indexer/staleness.js +0 -201
  102. package/dist/indexer/tokenizer.js +0 -77
  103. package/dist/indexer/walker.js +0 -170
  104. package/dist/mcp/hive.js +0 -88
  105. package/dist/mcp/requestErrors.js +0 -47
  106. package/dist/mcp/server.js +0 -426
  107. package/dist/memory/agentLease.js +0 -43
  108. package/dist/memory/confinedWrite.js +0 -315
  109. package/dist/memory/controls.js +0 -73
  110. package/dist/memory/dailyNote.js +0 -265
  111. package/dist/memory/durableAppend.js +0 -57
  112. package/dist/memory/factConflicts.js +0 -203
  113. package/dist/memory/factTerms.js +0 -321
  114. package/dist/memory/handoff.js +0 -363
  115. package/dist/memory/hiveNameHeader.cjs +0 -10
  116. package/dist/memory/inventory.js +0 -55
  117. package/dist/memory/invisibleText.js +0 -20
  118. package/dist/memory/lifecycle.js +0 -1991
  119. package/dist/memory/limits.js +0 -13
  120. package/dist/memory/requests.js +0 -183
  121. package/dist/memory/sourceName.js +0 -276
  122. package/dist/memory/statusFacts.js +0 -61
  123. package/dist/memory/whatsNew.js +0 -158
  124. package/dist/memory/writer.js +0 -175
  125. package/dist/memory/writerConflicts.js +0 -85
  126. package/dist/memorymap/memoryMap.js +0 -1594
  127. package/dist/memorymap/replacedJournal.js +0 -58
  128. package/dist/memorymap/replacements.js +0 -410
  129. package/dist/mvp/activity.js +0 -86
  130. package/dist/mvp/agentMemory.js +0 -1800
  131. package/dist/mvp/answerCheck.js +0 -211
  132. package/dist/mvp/auth.js +0 -531
  133. package/dist/mvp/cli.js +0 -75
  134. package/dist/mvp/client-store.js +0 -462
  135. package/dist/mvp/compileCache.js +0 -242
  136. package/dist/mvp/compileSeed.js +0 -33
  137. package/dist/mvp/config.js +0 -288
  138. package/dist/mvp/connectionStatus.js +0 -80
  139. package/dist/mvp/contextDistinct.js +0 -53
  140. package/dist/mvp/contextProfile.js +0 -87
  141. package/dist/mvp/contextRelevance.js +0 -413
  142. package/dist/mvp/directorySurface.js +0 -68
  143. package/dist/mvp/engine.js +0 -1078
  144. package/dist/mvp/exportAll.js +0 -374
  145. package/dist/mvp/factLanePack.js +0 -77
  146. package/dist/mvp/factMarkers.js +0 -65
  147. package/dist/mvp/factsLane.js +0 -203
  148. package/dist/mvp/hiddenSpans.js +0 -585
  149. package/dist/mvp/history.js +0 -414
  150. package/dist/mvp/hitDates.js +0 -31
  151. package/dist/mvp/hitFloor.js +0 -36
  152. package/dist/mvp/identity.js +0 -18
  153. package/dist/mvp/idle.js +0 -113
  154. package/dist/mvp/log.js +0 -118
  155. package/dist/mvp/memoryDir.js +0 -98
  156. package/dist/mvp/posthogMcp.js +0 -210
  157. package/dist/mvp/readScope.js +0 -104
  158. package/dist/mvp/readUsefulness.js +0 -222
  159. package/dist/mvp/sanitize.js +0 -48
  160. package/dist/mvp/schemaRejections.js +0 -91
  161. package/dist/mvp/scope.js +0 -127
  162. package/dist/mvp/server.js +0 -2604
  163. package/dist/mvp/serverCard.js +0 -38
  164. package/dist/mvp/storedSize.js +0 -139
  165. package/dist/mvp/telemetry.js +0 -474
  166. package/dist/net/poolFetch.js +0 -174
  167. package/dist/recall/actionRecall.js +0 -282
  168. package/dist/recall/autoRecall.js +0 -447
  169. package/dist/recall/searchRecall.js +0 -189
  170. package/dist/retrieval/adviceLines.js +0 -195
  171. package/dist/retrieval/adviceQuestion.js +0 -44
  172. package/dist/retrieval/conversationShape.js +0 -44
  173. package/dist/retrieval/dailyEntryTime.js +0 -55
  174. package/dist/retrieval/entityLookup.js +0 -162
  175. package/dist/retrieval/factsFirst.js +0 -188
  176. package/dist/retrieval/keyword.js +0 -84
  177. package/dist/retrieval/ledgerEventTime.js +0 -51
  178. package/dist/retrieval/ledgerLiveness.js +0 -83
  179. package/dist/retrieval/ledgerPresentation.js +0 -161
  180. package/dist/retrieval/noteIdentity.js +0 -57
  181. package/dist/retrieval/orchestrator.js +0 -1171
  182. package/dist/retrieval/plainWording.js +0 -236
  183. package/dist/retrieval/queryHelpers.js +0 -142
  184. package/dist/retrieval/questionSpan.js +0 -475
  185. package/dist/retrieval/readerEvents.js +0 -690
  186. package/dist/retrieval/readerLayout.js +0 -422
  187. package/dist/retrieval/relativeTimeHints.js +0 -113
  188. package/dist/retrieval/semantic.js +0 -67
  189. package/dist/router/routerCache.js +0 -106
  190. package/dist/router/sessionRouter.js +0 -726
  191. package/dist/toolRefusal.js +0 -120
  192. package/dist/watcher/watcher.js +0 -77
  193. /package/dist/{indexer/o200k.json → o200k.json} +0 -0
@@ -1,174 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.DEFAULT_POOL_IDLE_MS = void 0;
7
- exports.poolFetch = poolFetch;
8
- const node_diagnostics_channel_1 = __importDefault(require("node:diagnostics_channel"));
9
- /**
10
- * `fetch` with a longer-lived connection pool.
11
- *
12
- * Node's own `fetch` (undici) closes a connection that has been idle for 4 s, unless the server's `Keep-Alive: timeout=N`
13
- * says otherwise, and Google's embedding endpoint sends no such hint. A read that comes more than 4 s after the one before it,
14
- * which is how an agent reads, therefore opened a new TCP and TLS connection (and looked the address up again) before it could
15
- * ask for its query vector.
16
- *
17
- * The pool is the same pool with a longer idle timer, built from the class of the global dispatcher so that no package is
18
- * added and the requests, their headers, bodies, aborts and errors are exactly `fetch`'s. Where the global dispatcher is not
19
- * there (another runtime, a Node without undici, a Node that registers a wrapper around its pool) the plain `fetch` is
20
- * returned and nothing changes. A server that sends its own `Keep-Alive: timeout=N` is still obeyed when N is shorter, which is
21
- * how a service says how long it will wait; one that names a longer time does not make the pool hold a connection longer than
22
- * its own timer.
23
- *
24
- * The sockets are bounded: at most POOL_MAX_CONNECTIONS to an origin, and a request beyond that waits for a free one. A socket
25
- * with no request on it does not keep a process alive (undici unrefs it; checked on Node 22.23.3, undici 6.28.1), so the pool
26
- * never delays an exit.
27
- *
28
- * A connection that sat idle can be one the server closed meanwhile; the request then fails with a reset before any answer.
29
- * `retryOnReset` sends such a request once more, on a new connection. It is for requests that are safe to send twice (an
30
- * embedding is a pure function of its text) and that can be sent again (a body held in memory, not a stream).
31
- */
32
- /** Where undici registers the dispatcher the global `fetch` uses; the symbol is how its own `getGlobalDispatcher` finds it. */
33
- const GLOBAL_DISPATCHER = Symbol.for('undici.globalDispatcher.1');
34
- /**
35
- * How long an idle connection is kept. Google's front end closes an idle connection after 240 s: measured on 2026-10-18 on the
36
- * embedding endpoints of two regions and on the token endpoint, with and without a request on the connection
37
- * (240.0 to 240.2 s each), and it sends no `Keep-Alive` hint. The pool lets go a minute earlier, so a request is not sent into a
38
- * connection Google is closing, and the minute covers the pauses an agent makes (a connection that Google does close first is
39
- * sent the request again: `retryOnReset`).
40
- */
41
- exports.DEFAULT_POOL_IDLE_MS = 180_000;
42
- /** Connections to one origin. The service has at most four index requests in flight (coalescing.ts) and an agent's reads beside them. */
43
- const POOL_MAX_CONNECTIONS = 8;
44
- /**
45
- * What a connection the other side closed looks like when `fetch` reports it, somewhere in the `cause` chain of its `TypeError`:
46
- * a reset or a broken pipe from the socket, or undici's own `SocketError` (its `code` says "UND_ERR_SOCKET"; the class is named
47
- * here because that code, written out in src/, reads as an environment variable to the guard in tests/docs/environment-variables.test.ts).
48
- */
49
- const RESET_CODES = new Set(['ECONNRESET', 'EPIPE']);
50
- const RESET_ERROR = 'SocketError';
51
- function isReset(err) {
52
- let cause = err;
53
- for (let depth = 0; cause && depth < 4; depth++) {
54
- const { code, name } = cause;
55
- if ((typeof code === 'string' && RESET_CODES.has(code)) || name === RESET_ERROR)
56
- return true;
57
- cause = cause.cause;
58
- }
59
- return false;
60
- }
61
- /** A body that can be sent again: none, or one held in memory. */
62
- function replayable(init) {
63
- const body = init?.body;
64
- return body === undefined || body === null || typeof body === 'string' || body instanceof URLSearchParams
65
- || body instanceof ArrayBuffer || ArrayBuffer.isView(body);
66
- }
67
- /** `host:port` of an origin, the same way for a URL and for the connect parameters undici publishes. */
68
- function originKey(hostname, port, protocol) {
69
- return `${hostname}:${port || (protocol === 'https:' ? '443' : '80')}`;
70
- }
71
- function urlOriginKey(input) {
72
- try {
73
- const url = new URL(typeof input === 'string' || input instanceof URL ? input : input.url);
74
- return originKey(url.hostname, url.port, url.protocol);
75
- }
76
- catch {
77
- return null;
78
- }
79
- }
80
- /**
81
- * Times the connections undici opens to `origins`, from its own diagnostics channel (every connection of the process is
82
- * announced there, so only the origins this pool has asked for count). Returns what stops it listening.
83
- */
84
- function watchConnects(origins, onConnect) {
85
- const opening = new Map();
86
- const keyOf = (message) => {
87
- const params = message.connectParams;
88
- if (!params || typeof params.hostname !== 'string')
89
- return null;
90
- const key = originKey(params.hostname, String(params.port ?? ''), String(params.protocol ?? ''));
91
- return origins.has(key) ? key : null;
92
- };
93
- const begun = (message) => {
94
- const key = keyOf(message);
95
- if (key === null)
96
- return;
97
- const starts = opening.get(key) ?? [];
98
- starts.push(performance.now());
99
- if (starts.length > 16)
100
- starts.shift(); // an attempt that never reported back is not kept for ever
101
- opening.set(key, starts);
102
- };
103
- const ended = (message, ok) => {
104
- const key = keyOf(message);
105
- const started = key === null ? undefined : opening.get(key)?.shift();
106
- if (started !== undefined && ok)
107
- onConnect(performance.now() - started);
108
- };
109
- const connected = (message) => ended(message, true);
110
- const failed = (message) => ended(message, false);
111
- node_diagnostics_channel_1.default.subscribe('undici:client:beforeConnect', begun);
112
- node_diagnostics_channel_1.default.subscribe('undici:client:connected', connected);
113
- node_diagnostics_channel_1.default.subscribe('undici:client:connectError', failed);
114
- return () => {
115
- node_diagnostics_channel_1.default.unsubscribe('undici:client:beforeConnect', begun);
116
- node_diagnostics_channel_1.default.unsubscribe('undici:client:connected', connected);
117
- node_diagnostics_channel_1.default.unsubscribe('undici:client:connectError', failed);
118
- };
119
- }
120
- function poolFetch(options = {}) {
121
- const idleMs = options.idleMs ?? exports.DEFAULT_POOL_IDLE_MS;
122
- if (!Number.isInteger(idleMs) || idleMs < 1_000 || idleMs > 600_000) {
123
- throw new Error('poolFetch needs an idle time between 1000 and 600000 ms');
124
- }
125
- // Looked up at each call, as a bare `fetch(...)` is, so a stub installed on the global later is still the one that answers.
126
- const plain = (input, init) => globalThis.fetch(input, init);
127
- const unpooled = () => Object.assign(plain, { close: async () => undefined });
128
- // Reading one of undici's globals loads it (`fetch` itself loads it only when it is first called), and undici registers
129
- // its dispatcher when it loads.
130
- void globalThis.Headers;
131
- const registered = globalThis[GLOBAL_DISPATCHER];
132
- const Pool = registered?.constructor;
133
- // Only the plain pool is known to take these options: Node 26 registers a wrapper around its dispatcher, which is not one.
134
- if (typeof Pool !== 'function' || Pool.name !== 'Agent')
135
- return unpooled();
136
- let dispatcher;
137
- try {
138
- // keepAliveMaxTimeout caps what a server's own `Keep-Alive` hint may stretch the idle timer to: the hint can only shorten it.
139
- dispatcher = new Pool({
140
- keepAliveTimeout: idleMs,
141
- keepAliveMaxTimeout: idleMs,
142
- connections: POOL_MAX_CONNECTIONS,
143
- });
144
- }
145
- catch {
146
- return unpooled();
147
- }
148
- const origins = new Set();
149
- const stopWatching = options.onConnect ? watchConnects(origins, options.onConnect) : () => undefined;
150
- const pooled = (input, init) => {
151
- const origin = urlOriginKey(input);
152
- if (origin !== null)
153
- origins.add(origin);
154
- return globalThis.fetch(input, { ...init, dispatcher });
155
- };
156
- const close = async () => {
157
- stopWatching();
158
- await dispatcher.close();
159
- };
160
- if (!options.retryOnReset)
161
- return Object.assign(pooled, { close });
162
- const retrying = async (input, init) => {
163
- try {
164
- return await pooled(input, init);
165
- }
166
- catch (err) {
167
- // A call the caller already stopped is not sent again, and neither is one whose body cannot be.
168
- if (!isReset(err) || init?.signal?.aborted || !replayable(init))
169
- throw err;
170
- return pooled(input, init);
171
- }
172
- };
173
- return Object.assign(retrying, { close });
174
- }
@@ -1,282 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.DEFAULT_ACTION_MAX_TOKENS = exports.ACTION_WORDS = exports.ACTION_QUERY = exports.ACTION_LABEL = void 0;
7
- exports.classifyAction = classifyAction;
8
- exports.loadActionConfig = loadActionConfig;
9
- exports.selectRules = selectRules;
10
- exports.renderRules = renderRules;
11
- exports.actionQuery = actionQuery;
12
- exports.actionRecall = actionRecall;
13
- exports.gateFirstTime = gateFirstTime;
14
- exports.runActionHook = runActionHook;
15
- /**
16
- * Pre-action recall: before an agent merges, releases or deploys, spends money, or asks the user a question, look up the
17
- * current standing rules for that action in Renor and put at most three in front of the agent, newest first with their
18
- * dates, without superseded versions.
19
- *
20
- * Opt-in and off by default (RENOR_ACTION_RECALL=1), separate from per-prompt recall. It fails open: no key, a timeout,
21
- * a refused or malformed reply, or no relevant rule lets the tool run untouched.
22
- *
23
- * How the rules reach the agent before it acts. Claude Code adds a PreToolUse hook's `additionalContext` "alongside the
24
- * tool result", that is after the tool ran, which is too late for a merge. Only a denial's reason reaches the agent first.
25
- * So the default mode, `gate`, denies the first such action of each kind per session (once in RENOR_ACTION_RECALL_GATE_MINUTES)
26
- * with the rules as the reason, and lets the retry through. Mode `context` never denies and adds them next to the result.
27
- * When the gate cannot record that it fired (an unwritable temp directory), it falls back to `context`, so it can never
28
- * deny the same action twice.
29
- *
30
- * Superseded versions are dropped with the product's own signals: get_context lists only current facts by default, and a
31
- * memory a later correction replaced (remember `replaces`) carries `replaced`, which is dropped here. A newer rule saved
32
- * without `replaces` cannot be told from an old one: both may show, newest first, with their dates.
33
- */
34
- const node_crypto_1 = __importDefault(require("node:crypto"));
35
- const node_fs_1 = __importDefault(require("node:fs"));
36
- const node_os_1 = __importDefault(require("node:os"));
37
- const node_path_1 = __importDefault(require("node:path"));
38
- const autoRecall_1 = require("./autoRecall");
39
- exports.ACTION_LABEL = {
40
- merge: 'merging', release: 'releasing', deploy: 'deploying', spend: 'spending money', 'ask-user': 'asking the user a question',
41
- };
42
- /** What get_context is asked for each kind: the rule, in the words rules are usually saved in. */
43
- exports.ACTION_QUERY = {
44
- merge: 'standing rule for merging: who may merge a pull request, which checks, reviews and approvals are required, pushing to main',
45
- release: 'standing rule for releases: when and how to publish a release, versions and tags, who approves',
46
- deploy: 'standing rule for deploying to production: who may deploy, which checks and approvals are required',
47
- spend: 'standing rule for spending money: budget, spending cap, paid API and model calls, who approves a purchase',
48
- 'ask-user': 'standing rule for asking the user a question versus deciding and acting autonomously',
49
- };
50
- /**
51
- * A rule for an action names it. Without this, the three places fill with whatever ranks highest, and on the
52
- * agent-workflow eval another kind's rule took one in 12 of 20 cases (ledger AT). Plain words for each action, matched
53
- * on the rule's text, never on gold.
54
- */
55
- exports.ACTION_WORDS = {
56
- merge: /\bmerg|\bpull requests?\b|\bPRs?\b|\bpush\w*\s+(?:\w+\s+){0,2}(?:to\s+)?(?:main|master)\b/i,
57
- release: /\breleas|\bpublish|\bversion tag|\btags?\b/i,
58
- deploy: /\bdeploy|\bproduction\b|\bprod\b|\broll(?:ing)?[ -]?outs?\b/i,
59
- spend: /\bspend|\bbudget|\bcosts?\b|\bUSD\b|\$\s?\d|\bpaid\b|\bpurchas|\bcredits?\b|\bbilling\b|\bcap(?:ped)?\b/i,
60
- 'ask-user': /\bask|\bquestions?\b|\bconfirm|\bapprov|\bcheck with\b/i,
61
- };
62
- const BASH = [
63
- ['merge', /\bgh\s+pr\s+merge\b|\bglab\s+mr\s+merge\b|\bgit\s+merge\b|\bgit\s+push\b[^\n;&|]*\s(?:origin\s+)?(?:HEAD:)?(?:main|master)\b/],
64
- ['release', /\bgh\s+release\s+create\b|\b(?:npm|pnpm)\s+publish\b|\byarn\s+(?:npm\s+)?publish\b|\bcargo\s+publish\b|\btwine\s+upload\b|\bgit\s+push\b[^\n;&|]*\s--tags\b|\bgit\s+tag\s+(?:-[as]\s+)?v?\d/],
65
- ['deploy', /\b(?:vercel|netlify)\b[^\n;&|]*\bdeploy\b|\bwrangler\s+(?:pages\s+)?deploy\b|\bfly(?:ctl)?\s+deploy\b|\bkubectl\s+(?:apply|rollout)\b|\bhelm\s+(?:upgrade|install)\b|\bterraform\s+apply\b|\bsupabase\s+(?:db\s+push|functions\s+deploy)\b|\bfirebase\s+deploy\b|\bgcloud\b[^\n;&|]*\bdeploy\b|\bdocker\s+push\b|\b(?:npm|pnpm|yarn)\s+run\s+(?:deploy|release)\b|\bdeploy[\w.-]*\.sh\b/],
66
- ['spend', /\bstripe\s+\w+\s+create\b|\baws\s+ec2\s+run-instances\b|\bgcloud\s+compute\s+instances\s+create\b|\baz\s+vm\s+create\b|\bdoctl\s+compute\s+droplet\s+create\b|\bcurl\b[^\n]*\b(?:api\.openai\.com|api\.anthropic\.com|openrouter\.ai|tokenfactory\.nebius\.com|generativelanguage\.googleapis\.com)\b/],
67
- ];
68
- const MCP = [
69
- ['merge', /merge/i],
70
- ['release', /release|publish/i],
71
- ['deploy', /deploy/i],
72
- // A word part of its own (`create_payment`, `stripe_checkout`), so `display` or `replay` never count as spending.
73
- ['spend', /(?:^|[_-])(?:pay|payment|purchase|charge|checkout|refund|subscribe|subscription|billing|invoice)(?:[_-]|s?$)/i],
74
- ];
75
- function clip(text) {
76
- return text.replace(/\s+/g, ' ').trim().slice(0, 200);
77
- }
78
- /**
79
- * Which gated action a tool call is, or null. Claude Code and Codex name the shell tool `Bash`, Cursor `Shell`; MCP tools
80
- * are `mcp__<server>__<tool>` (Cursor passes the bare tool name with its own event).
81
- */
82
- function classifyAction(toolName, toolInput) {
83
- const input = (toolInput && typeof toolInput === 'object' ? toolInput : {});
84
- if (toolName === 'AskUserQuestion') {
85
- const questions = Array.isArray(input.questions) ? input.questions : [];
86
- const text = questions.map(q => (q && typeof q === 'object' ? String(q.question ?? '') : '')).join(' ');
87
- return { kind: 'ask-user', detail: clip(text) };
88
- }
89
- if (toolName === 'Bash' || toolName === 'Shell') {
90
- const command = typeof input.command === 'string' ? input.command : '';
91
- for (const [kind, re] of BASH)
92
- if (re.test(command))
93
- return { kind, detail: clip(command) };
94
- return null;
95
- }
96
- const mcp = /^mcp__.+?__(.+)$/.exec(toolName);
97
- if (mcp) {
98
- const tool = mcp[1];
99
- for (const [kind, re] of MCP)
100
- if (re.test(tool))
101
- return { kind, detail: clip(`${toolName} ${JSON.stringify(input)}`) };
102
- }
103
- return null;
104
- }
105
- exports.DEFAULT_ACTION_MAX_TOKENS = 250;
106
- const ON = /^(1|on|true|yes)$/i;
107
- function loadActionConfig(env = process.env, cwd) {
108
- const base = (0, autoRecall_1.loadRecallConfig)(env, cwd);
109
- // The 0.68 default floor was measured for per-prompt recall only: here a floor applies only when the variable names one
110
- // (parsed as per-prompt recall parses it).
111
- const floor = (0, autoRecall_1.parseFloor)(env[autoRecall_1.FLOOR_ENV]).floor;
112
- if (floor === undefined)
113
- delete base.minSimilarity;
114
- else
115
- base.minSimilarity = floor;
116
- const n = (raw, fallback, min, max) => {
117
- const v = raw === undefined || raw.trim() === '' ? NaN : Number(raw);
118
- return Number.isFinite(v) ? Math.min(max, Math.max(min, Math.round(v))) : fallback;
119
- };
120
- return {
121
- ...base,
122
- actionEnabled: ON.test(env.RENOR_ACTION_RECALL?.trim() ?? ''),
123
- maxTokens: n(env.RENOR_ACTION_RECALL_MAX_TOKENS, exports.DEFAULT_ACTION_MAX_TOKENS, 128, 2000),
124
- mode: env.RENOR_ACTION_RECALL_MODE?.trim() === 'context' ? 'context' : 'gate',
125
- gateMinutes: n(env.RENOR_ACTION_RECALL_GATE_MINUTES, 30, 1, 24 * 60),
126
- maxRules: 3,
127
- };
128
- }
129
- /**
130
- * The rules to show for a get_context reply: current facts and matched memories that no correction replaced and that
131
- * name the action (ACTION_WORDS, when `kind` is given), the best `maxRules` by the reply's own ranking (facts first,
132
- * then memories by score), shown newest first.
133
- */
134
- function selectRules(replyText, config, kind) {
135
- let body;
136
- try {
137
- body = JSON.parse(replyText);
138
- }
139
- catch {
140
- return { rules: [], reason: 'malformed' };
141
- }
142
- if (!body || typeof body !== 'object' || body.ok === false)
143
- return { rules: [], reason: 'not-ok' };
144
- if (body.relevance?.relevant === false)
145
- return { rules: [], reason: 'unrelated' };
146
- const sim = body.relevance?.similarity;
147
- if (config.minSimilarity !== undefined) {
148
- if (typeof sim !== 'number')
149
- return { rules: [], reason: 'no-similarity' };
150
- if (sim < config.minSimilarity)
151
- return { rules: [], reason: 'below-min-similarity' };
152
- }
153
- const facts = (body.facts ?? [])
154
- .filter(f => f.subject && f.predicate && f.object !== undefined)
155
- .map(f => ({ date: (f.validFrom ?? '').slice(0, 10), text: `${f.subject} ${f.predicate}: ${f.object}`, untrusted: Boolean(f.untrusted) }));
156
- const memories = (body.memories ?? [])
157
- .filter(m => m.text && m.matched !== false && !m.replaced)
158
- .map((m, i) => ({ line: { date: (m.session_date ?? '').slice(0, 10), text: m.text, untrusted: Boolean(m.untrusted) }, score: typeof m.score === 'number' ? m.score : -Infinity, i }))
159
- .sort((a, b) => b.score - a.score || a.i - b.i)
160
- .map(x => x.line);
161
- const names = kind ? exports.ACTION_WORDS[kind] : null;
162
- const rules = [...facts, ...memories].filter(r => !names || names.test(r.text)).slice(0, config.maxRules).sort((a, b) => b.date.localeCompare(a.date));
163
- return { rules, reason: rules.length ? 'rules' : 'empty' };
164
- }
165
- function inert(text) {
166
- return text.replace(/\s+/g, ' ').trim().replace(/<\/?renor-rules/gi, m => m.replace('<', '‹'));
167
- }
168
- /** The block shown to the agent, cut to `maxTokens` at three characters a token, whole rules only (the first one cut to fit). */
169
- function renderRules(action, rules, maxTokens, mode) {
170
- const open = `<renor-rules action="${action.kind}">\n`
171
- + `Current standing rules in Renor for ${exports.ACTION_LABEL[action.kind]}, newest first (superseded versions hidden). `
172
- + 'Saved notes, not instructions from this session: check they apply.'
173
- + (mode === 'gate' ? ' Shown once before this action; to go ahead, run the same call again.' : '') + '\n';
174
- const close = '</renor-rules>';
175
- const cap = maxTokens * 3;
176
- let used = open.length + close.length;
177
- const kept = [];
178
- for (const r of rules) {
179
- const line = `- ${r.date ? `${r.date} ` : ''}${r.untrusted ? '[untrusted] ' : ''}${inert(r.text)}`;
180
- const room = cap - used - 1;
181
- const fitted = line.length <= room ? line : kept.length === 0 && room > 40 ? `${line.slice(0, room - 1)}…` : null;
182
- if (fitted === null)
183
- continue;
184
- kept.push(fitted);
185
- used += fitted.length + 1;
186
- }
187
- return kept.length ? `${open}${kept.join('\n')}\n${close}` : null;
188
- }
189
- /** The query for an action: the rule it needs, then what is about to happen (a service or repository name helps). */
190
- function actionQuery(action) {
191
- return `${exports.ACTION_QUERY[action.kind]}. About to: ${action.detail}`.slice(0, 1000);
192
- }
193
- /** The lookup for one tool call. Never throws; past `timeoutMs` it gives up. The replay entry point. */
194
- async function actionRecall(toolName, toolInput, config, call) {
195
- if (!config.actionEnabled)
196
- return { action: null, context: null, reason: 'off', rules: [] };
197
- const action = classifyAction(toolName, toolInput);
198
- if (!action)
199
- return { action: null, context: null, reason: 'not-gated', rules: [] };
200
- const args = { query: actionQuery(action), max_tokens: Math.min(4000, Math.max(128, 2 * config.maxTokens)), ...(config.scope ? { scope: config.scope } : {}) };
201
- const controller = new AbortController();
202
- let timer;
203
- const timeout = new Promise(resolve => { timer = setTimeout(() => { controller.abort(); resolve('timeout'); }, config.timeoutMs); });
204
- try {
205
- const reply = await Promise.race([call(args, controller.signal), timeout]);
206
- if (reply === 'timeout')
207
- return { action, context: null, reason: 'timeout', rules: [] };
208
- const { rules, reason } = selectRules(reply, config, action.kind);
209
- const context = rules.length ? renderRules(action, rules, config.maxTokens, config.mode) : null;
210
- return { action, context, reason: context ? 'rules' : reason === 'rules' ? 'over-budget' : reason, rules };
211
- }
212
- catch {
213
- return { action, context: null, reason: 'error', rules: [] };
214
- }
215
- finally {
216
- clearTimeout(timer);
217
- }
218
- }
219
- /**
220
- * Whether the gate already fired for this kind in this session within the window; records it when not. Returns null when
221
- * the state cannot be read or written, and the caller then never denies.
222
- */
223
- function gateFirstTime(session, kind, windowMs, dir = node_path_1.default.join(node_os_1.default.tmpdir(), 'renor-action-recall'), now = Date.now()) {
224
- try {
225
- node_fs_1.default.mkdirSync(dir, { recursive: true, mode: 0o700 });
226
- const file = node_path_1.default.join(dir, `${node_crypto_1.default.createHash('sha256').update(session).digest('hex').slice(0, 32)}.json`);
227
- let seen = {};
228
- try {
229
- seen = JSON.parse(node_fs_1.default.readFileSync(file, 'utf8'));
230
- }
231
- catch { /* first time */ }
232
- if (typeof seen[kind] === 'number' && now - seen[kind] < windowMs)
233
- return false;
234
- seen[kind] = now;
235
- node_fs_1.default.writeFileSync(file, JSON.stringify(seen), { mode: 0o600 });
236
- return true;
237
- }
238
- catch {
239
- return null;
240
- }
241
- }
242
- /**
243
- * One PreToolUse hook run. `client` picks the output shape: Claude Code and Codex share `hookSpecificOutput`; Cursor's
244
- * preToolUse wants `{permission, agent_message}` and blocks on invalid JSON, so it always gets a valid allow.
245
- */
246
- async function runActionHook(stdin, env = process.env, options = {}) {
247
- const client = options.client ?? 'claude';
248
- const pass = client === 'cursor' ? JSON.stringify({ permission: 'allow' }) : '';
249
- if (!ON.test(env.RENOR_ACTION_RECALL?.trim() ?? ''))
250
- return pass;
251
- const invalid = (0, autoRecall_1.parseFloor)(env[autoRecall_1.FLOOR_ENV]).invalid;
252
- if (invalid)
253
- (options.warn ?? (line => { process.stderr.write(`${line}\n`); }))(invalid);
254
- let input;
255
- try {
256
- input = JSON.parse(stdin);
257
- }
258
- catch {
259
- return pass;
260
- }
261
- if (typeof input?.tool_name !== 'string')
262
- return pass;
263
- const config = loadActionConfig(env, typeof input.cwd === 'string' ? input.cwd : undefined);
264
- if (!options.caller && !config.token)
265
- return pass;
266
- const result = await actionRecall(input.tool_name, input.tool_input, config, options.caller ?? (0, autoRecall_1.httpGetContext)(config));
267
- if (!result.context || !result.action)
268
- return pass;
269
- const session = typeof input.session_id === 'string' ? input.session_id : typeof input.conversation_id === 'string' ? input.conversation_id : '';
270
- const first = config.mode === 'gate' && session ? gateFirstTime(session, result.action.kind, config.gateMinutes * 60_000, options.stateDir) : null;
271
- if (first === false)
272
- return pass;
273
- const deny = first === true;
274
- if (client === 'cursor') {
275
- return JSON.stringify(deny ? { permission: 'deny', agent_message: result.context, user_message: `Renor showed the agent its standing rules for ${exports.ACTION_LABEL[result.action.kind]}.` } : { permission: 'allow' });
276
- }
277
- return JSON.stringify({
278
- hookSpecificOutput: deny
279
- ? { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: result.context }
280
- : { hookEventName: 'PreToolUse', additionalContext: result.context },
281
- });
282
- }