@causyne/agent 1.20.100 → 1.20.104

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.
@@ -0,0 +1,354 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ import { COMPILED_SKILLS } from './compiledSkills.js';
5
+ import { loadUserSkills, type UserSkill } from './userSkills.js';
6
+ import { getPluginSkills } from './plugins/pluginManager.js';
7
+
8
+ export interface SkillDescriptor {
9
+ domain: string;
10
+ id: string;
11
+ name: string;
12
+ description: string;
13
+ source: 'native' | 'user' | 'plugin';
14
+ }
15
+
16
+ interface CompiledSkillItem {
17
+ name?: string;
18
+ description?: string;
19
+ content: string;
20
+ }
21
+
22
+ const compiledSkillsCatalog = COMPILED_SKILLS as unknown as Record<string, Record<string, CompiledSkillItem>>;
23
+
24
+ // User skills are read from disk, and the disk is slow relative to how often
25
+ // these functions are called (every completion keystroke asks for the
26
+ // catalogue). Cache for a moment so typing stays instant, but keep the window
27
+ // short enough that a skill the agent just wrote shows up without a restart.
28
+ const USER_CACHE_MS = 2000;
29
+ let userCache: { at: number; skills: UserSkill[]; problems: string[] } = { at: 0, skills: [], problems: [] };
30
+
31
+ export function invalidateUserSkills(): void {
32
+ userCache = { at: 0, skills: [], problems: [] };
33
+ }
34
+
35
+ function userSkills(): { at: number; skills: UserSkill[]; problems: string[] } {
36
+ const now = Date.now();
37
+ if (now - userCache.at < USER_CACHE_MS) return userCache;
38
+ try {
39
+ const loaded = loadUserSkills();
40
+ userCache = { at: now, skills: loaded.skills, problems: loaded.problems };
41
+ } catch (e: unknown) {
42
+ // A broken skills directory must never stop a session from starting.
43
+ const msg = e instanceof Error ? e.message : String(e);
44
+ userCache = { at: now, skills: [], problems: [`user skills unavailable: ${msg}`] };
45
+ }
46
+ return userCache;
47
+ }
48
+
49
+ export function userSkillProblems(): string[] {
50
+ return userSkills().problems;
51
+ }
52
+
53
+ // What a workspace looks like from the outside.
54
+ //
55
+ // This used to name four domains, which meant that of the compiled skills only
56
+ // android, web, python and devops could EVER be surfaced — every other one was
57
+ // compiled into the artefact and unreachable. Detection is what decides whether
58
+ // a skill exists as far as the model is concerned.
59
+ //
60
+ // Marker files only; no globbing and no directory walking, so detection stays a
61
+ // handful of stat calls whatever the size of the repository.
62
+ const DOMAIN_INDICATORS: Record<string, string[]> = {
63
+ android: ['build.gradle', 'build.gradle.kts', 'app/build.gradle', 'app/build.gradle.kts',
64
+ 'app/src/main/AndroidManifest.xml', 'settings.gradle.kts', 'gradlew'],
65
+ mobile: ['pubspec.yaml', 'ios/Podfile', 'Podfile', 'app.json', 'metro.config.js',
66
+ 'react-native.config.js', 'expo.json'],
67
+ web: ['next.config.js', 'next.config.mjs', 'next.config.ts', 'nuxt.config.ts',
68
+ 'svelte.config.js', 'vue.config.js', 'astro.config.mjs', 'vite.config.js',
69
+ 'vite.config.ts', 'angular.json', 'index.html', 'tailwind.config.js'],
70
+ backend: ['package.json', 'go.mod', 'Cargo.toml', 'pom.xml', 'build.sbt',
71
+ 'Gemfile', 'composer.json', 'nest-cli.json'],
72
+ python: ['requirements.txt', 'pyproject.toml', 'Pipfile', 'setup.py', 'setup.cfg',
73
+ 'uv.lock', 'poetry.lock', 'environment.yml'],
74
+ devops: ['Dockerfile', 'docker-compose.yml', 'docker-compose.yaml', '.github/workflows',
75
+ '.gitlab-ci.yml', 'Jenkinsfile', 'Makefile', '.circleci/config.yml'],
76
+ cloud: ['main.tf', 'terraform.tf', 'serverless.yml', 'template.yaml', 'Pulumi.yaml',
77
+ 'cdk.json', 'k8s', 'kubernetes', 'helm', 'skaffold.yaml'],
78
+ database: ['prisma/schema.prisma', 'migrations', 'alembic.ini', 'knexfile.js',
79
+ 'schema.sql', 'db/schema.rb', 'drizzle.config.ts', 'flyway.conf'],
80
+ testing: ['jest.config.js', 'jest.config.ts', 'vitest.config.ts', 'playwright.config.ts',
81
+ 'cypress.config.js', 'pytest.ini', 'tox.ini', 'tests', 'test', '__tests__'],
82
+ security: ['.github/dependabot.yml', 'SECURITY.md', '.snyk', 'socket.yml', 'socket.json'],
83
+ design: ['tailwind.config.js', 'tailwind.config.ts', 'styles', 'src/styles',
84
+ 'theme.js', 'theme.ts', 'tokens.json', 'postcss.config.js'],
85
+ // A 3D/video workspace. Without a rule here the media skills compile into
86
+ // the artefact and are unreachable by domain detection — tool_search still
87
+ // finds them, but the workspace never volunteers them.
88
+ media: ['.blend', 'assets/3d', 'renders', 'blender', 'shots', 'Resolve Projects'],
89
+ git: ['.git', '.gitignore', '.gitattributes'],
90
+ performance: ['lighthouserc.js', 'lighthouserc.json', '.lighthouserc.yml', 'k6.js',
91
+ 'benchmark', 'benchmarks'],
92
+ 'ai-engineering': ['.env.example', 'prompts', 'evals', 'langchain.json',
93
+ 'llm.config.js', 'openai.json'],
94
+ data: ['dbt_project.yml', 'airflow.cfg', 'dags', 'notebooks', '*.ipynb',
95
+ 'dvc.yaml', 'great_expectations']
96
+ };
97
+
98
+ // Domains that apply to every task regardless of what the workspace looks like.
99
+ //
100
+ // Design and security are not properties of a file layout — an agent writing a
101
+ // UI needs the anti-slop direction whether or not a tailwind config exists, and
102
+ // input validation matters whether or not the repository has a SECURITY.md.
103
+ const UNIVERSAL_DOMAINS = ['design', 'security'];
104
+
105
+ // Ceiling on how many skill descriptions may enter the system prompt.
106
+ //
107
+ // With 100 skills, injecting every description of every detected domain would
108
+ // spend thousands of tokens on an index before the task has even been read.
109
+ // This is the progressive-disclosure contract: the model sees names and routing
110
+ // conditions, and pulls a body with fs_read_skill only when one is relevant.
111
+ const MAX_INDEXED_SKILLS = 40;
112
+
113
+ export function detectWorkspaceDomains(workspaceRoot?: string): string[] {
114
+ if (!workspaceRoot || !fs.existsSync(workspaceRoot)) return UNIVERSAL_DOMAINS.slice();
115
+
116
+ const detectedDomains: string[] = [];
117
+
118
+ for (const [domain, indicators] of Object.entries(DOMAIN_INDICATORS)) {
119
+ for (const indicator of indicators) {
120
+ // A glob marker means "any file with this extension at the root". Kept to
121
+ // one readdir rather than a walk — a recursive search of a large monorepo
122
+ // on every task start is not worth one extra domain.
123
+ if (indicator.startsWith('*.')) {
124
+ try {
125
+ const extension = indicator.slice(1);
126
+ if (fs.readdirSync(workspaceRoot).some((name) => name.endsWith(extension))) {
127
+ detectedDomains.push(domain);
128
+ break;
129
+ }
130
+ } catch { /* unreadable directory is simply not a match */ }
131
+ continue;
132
+ }
133
+ if (fs.existsSync(path.join(workspaceRoot, indicator))) {
134
+ detectedDomains.push(domain);
135
+ break;
136
+ }
137
+ }
138
+ }
139
+
140
+ // Shallow check of immediate subdirectories for Android projects located in subfolders
141
+ if (!detectedDomains.includes('android')) {
142
+ try {
143
+ const entries = fs.readdirSync(workspaceRoot, { withFileTypes: true });
144
+ for (const entry of entries) {
145
+ if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules' && entry.name !== 'Library') {
146
+ const subDir = path.join(workspaceRoot, entry.name);
147
+ if (fs.existsSync(path.join(subDir, 'build.gradle')) ||
148
+ fs.existsSync(path.join(subDir, 'build.gradle.kts')) ||
149
+ fs.existsSync(path.join(subDir, 'gradlew')) ||
150
+ fs.existsSync(path.join(subDir, 'app/build.gradle')) ||
151
+ fs.existsSync(path.join(subDir, 'app/build.gradle.kts')) ||
152
+ fs.existsSync(path.join(subDir, 'app/src/main/AndroidManifest.xml'))) {
153
+ detectedDomains.push('android');
154
+ break;
155
+ }
156
+ }
157
+ }
158
+ } catch { /* unreadable directory is simply skipped */ }
159
+ }
160
+
161
+ for (const domain of UNIVERSAL_DOMAINS) {
162
+ if (!detectedDomains.includes(domain)) detectedDomains.push(domain);
163
+ }
164
+
165
+ return detectedDomains;
166
+ }
167
+
168
+ export { MAX_INDEXED_SKILLS, UNIVERSAL_DOMAINS };
169
+
170
+ export function ensureSkillRepo(domain: string): boolean {
171
+ if (compiledSkillsCatalog[domain]) {
172
+ return true;
173
+ }
174
+ return false;
175
+ }
176
+
177
+ /**
178
+ * The index the model sees: names and routing conditions, never bodies.
179
+ *
180
+ * Progressive disclosure. 100 skills is roughly 250 KB of markdown; injecting it
181
+ * would consume the context window before the task was read. What goes in is one
182
+ * line per skill — the name and WHEN TO USE IT — and the model pulls the body
183
+ * with fs_read_skill only for the one it needs. This is the same contract
184
+ * claude-code and openclaw use, and it is what makes a large skill library
185
+ * possible at all.
186
+ *
187
+ * Capped at MAX_INDEXED_SKILLS. A workspace matching eight domains would
188
+ * otherwise inject fifty-odd descriptions; the detected domains come first so
189
+ * the cut falls on the least relevant.
190
+ */
191
+ export function getUniversalSkillsIndex(domains: string[]): string {
192
+ let indexText = '';
193
+ let totalSkillsCount = 0;
194
+
195
+ // One catalogue, so a user skill is as visible to the agent as a compiled one.
196
+ const catalogue = new Map<string, SkillDescriptor[]>();
197
+ for (const skill of listCompiledSkills()) {
198
+ if (!catalogue.has(skill.domain)) catalogue.set(skill.domain, []);
199
+ catalogue.get(skill.domain)!.push(skill);
200
+ }
201
+
202
+ // A user's own domains are always offered: someone who wrote a `team/` skill
203
+ // wants it considered, and no marker file in the workspace announces it.
204
+ const ownDomains = [...new Set(userSkills().skills.map((skill) => skill.domain))];
205
+ const wanted = [...new Set([...ownDomains, ...domains])];
206
+
207
+ for (const domain of wanted) {
208
+ const domainSkills = catalogue.get(domain);
209
+ if (!domainSkills || domainSkills.length === 0) continue;
210
+ if (totalSkillsCount >= MAX_INDEXED_SKILLS) break;
211
+
212
+ let domainSkillsCount = 0;
213
+ let domainIndexText = `### ${domain.toUpperCase()} SKILLS\n`;
214
+
215
+ for (const skill of domainSkills) {
216
+ if (totalSkillsCount + domainSkillsCount >= MAX_INDEXED_SKILLS) break;
217
+ const mark = skill.source === 'user' ? ' [your own]' : '';
218
+ const safeName = String(skill.name || skill.id).replace(/[<>]/g, '');
219
+ const safeDesc = String(skill.description || '').replace(/[<>]/g, '');
220
+ domainIndexText += `- **${safeName}**${mark} (ID: ${domain}/${skill.id}): ${safeDesc}\n`;
221
+ domainSkillsCount++;
222
+ }
223
+
224
+ if (domainSkillsCount > 0) {
225
+ indexText += domainIndexText + '\n';
226
+ totalSkillsCount += domainSkillsCount;
227
+ }
228
+ }
229
+
230
+ if (totalSkillsCount === 0) return '';
231
+
232
+ let finalOutput = `\n<causyne_universal_skills>\n`;
233
+ finalOutput += `You have access to highly-curated, domain-specific intelligence skills provided as readable local skill data. If a skill is relevant to the user's task, you MUST use the \`fs_read_skill\` tool (passing the ID) to read its full instruction BEFORE proceeding with your plan. NEVER guess syntax if a skill exists for it.\n\n`;
234
+ finalOutput += indexText;
235
+ finalOutput += `</causyne_universal_skills>\n`;
236
+
237
+ return finalOutput;
238
+ }
239
+
240
+ /**
241
+ * The compact form of the skills index: what domains exist and how to search
242
+ * them, instead of forty name-and-description lines.
243
+ *
244
+ * WHY: `getUniversalSkillsIndex()` costs ~841 tokens for two domains and ~1,092
245
+ * for web+android, injected into a cached system block on EVERY request of
246
+ * EVERY task — a bare "hi" paid for a catalogue of skills it would never read.
247
+ *
248
+ * WHY IT IS SAFE NOW AND WAS NOT BEFORE: until `tool_search` learned to score
249
+ * the skill catalogue, this index was the ONLY way a model could discover a
250
+ * skill id. Shrinking it would have made 100 compiled skills unreachable —
251
+ * a capability regression wearing an optimisation's clothes. Retrieval replaces
252
+ * a catalogue only once the retrieval exists.
253
+ *
254
+ * @param domains Workspace domains detected for this task.
255
+ * @returns System-prompt fragment, '' when nothing exists.
256
+ */
257
+ export function getSkillDomainHeader(domains?: Iterable<string> | string[]): string {
258
+ const catalogue = new Map<string, number>();
259
+ for (const skill of listCompiledSkills()) {
260
+ catalogue.set(skill.domain, (catalogue.get(skill.domain) || 0) + 1);
261
+ }
262
+ if (catalogue.size === 0) return '';
263
+
264
+ const total = [...catalogue.values()].reduce((sum, n) => sum + n, 0);
265
+ const relevant = [...new Set(domains || [])].filter((d) => catalogue.has(d));
266
+ const all = [...catalogue.keys()].sort();
267
+
268
+ let out = `\n<causyne_universal_skills>\n`;
269
+ out += `${total} curated engineering skills are compiled into you, across: ${all.join(', ')}.\n`;
270
+ if (relevant.length > 0) {
271
+ out += `This workspace looks like: ${relevant.join(', ')}.\n`;
272
+ }
273
+ out += `Call \`tool_search\` with what you are trying to do to find the relevant skill ids, then read one with \`fs_read_skill\`. Do this BEFORE planning anything the skills cover. NEVER guess syntax a skill documents.\n`;
274
+ out += `</causyne_universal_skills>\n`;
275
+ return out;
276
+ }
277
+
278
+ /**
279
+ * The whole catalogue as a flat list, for the picker and for `/skills`.
280
+ *
281
+ * One shape for every consumer, so the terminal picker and the text listing can
282
+ * never disagree about what exists.
283
+ */
284
+ export function listCompiledSkills(): SkillDescriptor[] {
285
+ const out: SkillDescriptor[] = [];
286
+ const seen = new Set<string>();
287
+
288
+ // The user's own skills come first and SHADOW a compiled skill of the same
289
+ // id. That is the customisation: someone whose deployment genuinely differs
290
+ // from the shipped procedure writes their own `devops/zero-downtime-deploys`
291
+ // and theirs is the one the agent reads. Shipping a library that cannot be
292
+ // corrected is shipping an opinion.
293
+ for (const skill of userSkills().skills) {
294
+ const key = `${skill.domain}/${skill.id}`;
295
+ seen.add(key);
296
+ out.push({
297
+ domain: skill.domain,
298
+ id: skill.id,
299
+ name: skill.name,
300
+ description: skill.description,
301
+ source: 'user'
302
+ });
303
+ }
304
+
305
+ // Plugin skills live in a plugin-owned namespace (`plugin-<name>/...`) and
306
+ // appear only after explicit digest-pinned enablement. A user's own skill can
307
+ // still shadow one, which preserves local authority over every instruction.
308
+ for (const skill of getPluginSkills() as Array<{ domain: string; id: string; name?: string; description?: string; content: string }>) {
309
+ const key = `${skill.domain}/${skill.id}`;
310
+ if (seen.has(key)) continue;
311
+ seen.add(key);
312
+ out.push({
313
+ domain: skill.domain,
314
+ id: skill.id,
315
+ name: skill.name || skill.id,
316
+ description: skill.description || '',
317
+ source: 'plugin'
318
+ });
319
+ }
320
+
321
+ for (const [domain, skills] of Object.entries(compiledSkillsCatalog)) {
322
+ for (const [id, data] of Object.entries(skills)) {
323
+ if (seen.has(`${domain}/${id}`)) continue;
324
+ out.push({
325
+ domain,
326
+ id,
327
+ name: data.name || id,
328
+ description: data.description || '',
329
+ source: 'native'
330
+ });
331
+ }
332
+ }
333
+ return out;
334
+ }
335
+
336
+ export function readCompiledSkill(domain: string, skillId: string): string {
337
+ // A user skill of the same id wins, for the same reason it does in the
338
+ // listing: the user's version is the corrected one.
339
+ const own = userSkills().skills
340
+ .find((skill) => skill.domain === domain && skill.id === skillId);
341
+ if (own) return own.content;
342
+
343
+ const pluginSkill = (getPluginSkills() as Array<{ domain: string; id: string; content: string }>)
344
+ .find((skill) => skill.domain === domain && skill.id === skillId);
345
+ if (pluginSkill) return pluginSkill.content;
346
+
347
+ const domainSkills = compiledSkillsCatalog[domain];
348
+ if (!domainSkills) return `Error: Domain ${domain} not found in compiled skills.`;
349
+
350
+ const skillData = domainSkills[skillId];
351
+ if (!skillData) return `Error: Skill ${skillId} not found in domain ${domain}.`;
352
+
353
+ return skillData.content;
354
+ }
@@ -24,11 +24,15 @@ function record(value) {
24
24
  }
25
25
  function operationFamily(args) {
26
26
  const command = typeof args.command === 'string' ? args.command
27
- : typeof args.cmd === 'string' ? args.cmd : '';
27
+ : typeof args.cmd === 'string' ? args.cmd
28
+ : typeof args.CommandLine === 'string' ? args.CommandLine
29
+ : typeof args.commandLine === 'string' ? args.commandLine
30
+ : typeof args.script === 'string' ? args.script : '';
28
31
  if (!command) {
29
- if (typeof args.url === 'string') {
32
+ const endpoint = typeof args.url === 'string' ? args.url : typeof args.endpoint === 'string' ? args.endpoint : '';
33
+ if (endpoint) {
30
34
  try {
31
- return new URL(args.url).hostname.toLowerCase();
35
+ return new URL(endpoint).hostname.toLowerCase();
32
36
  }
33
37
  catch {
34
38
  return '';
@@ -46,15 +50,16 @@ function operationFamily(args) {
46
50
  }
47
51
  function issueKey(tool, args) {
48
52
  const family = operationFamily(args);
49
- const target = String(args.path ?? args.file_path ?? args.filePath ?? '');
53
+ const target = String(args.path ?? args.file_path ?? args.filePath ?? args.target ?? args.endpoint ?? args.url ?? '');
54
+ const workspace = String(args.cwd ?? '');
50
55
  // Changing error text/class does not buy another three attempts at the same
51
56
  // operation. Targets are hashed and never included in recovery messages.
52
- return createHash('sha256').update(`${tool}\0${family}\0${target}`).digest('hex');
57
+ return createHash('sha256').update(`${tool}\0${family}\0${target}\0${workspace}`).digest('hex');
53
58
  }
54
59
  function lastGoodTool(outcomes) {
55
60
  for (let index = outcomes.length - 1; index >= 0; index--) {
56
61
  const outcome = outcomes[index];
57
- if (outcome?.success)
62
+ if (outcome?.success && (outcome.exitCode == null || outcome.exitCode === 0) && !outcome.error?.trim())
58
63
  return outcome.tool;
59
64
  }
60
65
  return null;
@@ -91,7 +96,9 @@ export class TimeMachine {
91
96
  }
92
97
  observe(tool, args, result, outcomes = []) {
93
98
  const value = record(result);
94
- const failed = value.success === false || typeof value.error === 'string';
99
+ const failed = value.success === false || (typeof value.error === 'string' && value.error.trim().length > 0)
100
+ || (typeof value.exitCode === 'number' && (!Number.isFinite(value.exitCode) || value.exitCode !== 0))
101
+ || value.failureKind === 'site_refusal';
95
102
  const classification = failed ? failureClass(value) || 'failed' : '';
96
103
  const key = issueKey(tool, args);
97
104
  const good = lastGoodTool(outcomes);
@@ -117,7 +124,7 @@ export class TimeMachine {
117
124
  }
118
125
  const error = typeof value.error === 'string' ? value.error : '';
119
126
  const needsHuman = classification === 'permission' || /user denied|approval required|authentication required/i.test(error);
120
- const attempt = (this.failures.get(key) || 0) + 1;
127
+ const attempt = Math.min(TIME_MACHINE_MAX_ATTEMPTS, (this.failures.get(key) || 0) + 1);
121
128
  this.failures.set(key, attempt);
122
129
  const checkpoint = good ? ` Last successful tool: ${good}.` : '';
123
130
  if (needsHuman) {
@@ -142,6 +149,11 @@ export class TimeMachine {
142
149
  failureClass: classification, lastGoodTool: good,
143
150
  guidance: `Further attempts were not approved. Stop this task. Give a brief evidence-based report and state what remains unresolved.${checkpoint}` };
144
151
  }
152
+ if (classification === 'rate_limited' && attempt < TIME_MACHINE_CONSENT_AT) {
153
+ return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
154
+ failureClass: classification, lastGoodTool: good,
155
+ guidance: `Rate limit reached. Respect the provider's retry/reset window; do not immediately resend the same request.${checkpoint}` };
156
+ }
145
157
  if (value.failureKind === 'site_refusal' && attempt < TIME_MACHINE_MAX_ATTEMPTS) {
146
158
  return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
147
159
  failureClass: classification, lastGoodTool: good,
@@ -43,10 +43,14 @@ function record(value: unknown): Record<string, unknown> {
43
43
 
44
44
  function operationFamily(args: Record<string, unknown>): string {
45
45
  const command = typeof args.command === 'string' ? args.command
46
- : typeof args.cmd === 'string' ? args.cmd : '';
46
+ : typeof args.cmd === 'string' ? args.cmd
47
+ : typeof args.CommandLine === 'string' ? args.CommandLine
48
+ : typeof args.commandLine === 'string' ? args.commandLine
49
+ : typeof args.script === 'string' ? args.script : '';
47
50
  if (!command) {
48
- if (typeof args.url === 'string') {
49
- try { return new URL(args.url).hostname.toLowerCase(); } catch { return ''; }
51
+ const endpoint = typeof args.url === 'string' ? args.url : typeof args.endpoint === 'string' ? args.endpoint : '';
52
+ if (endpoint) {
53
+ try { return new URL(endpoint).hostname.toLowerCase(); } catch { return ''; }
50
54
  }
51
55
  return '';
52
56
  }
@@ -61,16 +65,17 @@ function operationFamily(args: Record<string, unknown>): string {
61
65
 
62
66
  function issueKey(tool: string, args: Record<string, unknown>): string {
63
67
  const family = operationFamily(args);
64
- const target = String(args.path ?? args.file_path ?? args.filePath ?? '');
68
+ const target = String(args.path ?? args.file_path ?? args.filePath ?? args.target ?? args.endpoint ?? args.url ?? '');
69
+ const workspace = String(args.cwd ?? '');
65
70
  // Changing error text/class does not buy another three attempts at the same
66
71
  // operation. Targets are hashed and never included in recovery messages.
67
- return createHash('sha256').update(`${tool}\0${family}\0${target}`).digest('hex');
72
+ return createHash('sha256').update(`${tool}\0${family}\0${target}\0${workspace}`).digest('hex');
68
73
  }
69
74
 
70
75
  function lastGoodTool(outcomes: readonly ToolOutcome[]): string | null {
71
76
  for (let index = outcomes.length - 1; index >= 0; index--) {
72
77
  const outcome = outcomes[index];
73
- if (outcome?.success) return outcome.tool;
78
+ if (outcome?.success && (outcome.exitCode == null || outcome.exitCode === 0) && !outcome.error?.trim()) return outcome.tool;
74
79
  }
75
80
  return null;
76
81
  }
@@ -112,7 +117,9 @@ export class TimeMachine {
112
117
  observe(tool: string, args: Record<string, unknown>, result: unknown,
113
118
  outcomes: readonly ToolOutcome[] = []): RecoveryDecision {
114
119
  const value = record(result);
115
- const failed = value.success === false || typeof value.error === 'string';
120
+ const failed = value.success === false || (typeof value.error === 'string' && value.error.trim().length > 0)
121
+ || (typeof value.exitCode === 'number' && (!Number.isFinite(value.exitCode) || value.exitCode !== 0))
122
+ || value.failureKind === 'site_refusal';
116
123
  const classification = failed ? failureClass(value) || 'failed' : '';
117
124
  const key = issueKey(tool, args);
118
125
  const good = lastGoodTool(outcomes);
@@ -140,7 +147,7 @@ export class TimeMachine {
140
147
 
141
148
  const error = typeof value.error === 'string' ? value.error : '';
142
149
  const needsHuman = classification === 'permission' || /user denied|approval required|authentication required/i.test(error);
143
- const attempt = (this.failures.get(key) || 0) + 1;
150
+ const attempt = Math.min(TIME_MACHINE_MAX_ATTEMPTS, (this.failures.get(key) || 0) + 1);
144
151
  this.failures.set(key, attempt);
145
152
  const checkpoint = good ? ` Last successful tool: ${good}.` : '';
146
153
 
@@ -167,6 +174,11 @@ export class TimeMachine {
167
174
  failureClass: classification, lastGoodTool: good,
168
175
  guidance: `Further attempts were not approved. Stop this task. Give a brief evidence-based report and state what remains unresolved.${checkpoint}` };
169
176
  }
177
+ if (classification === 'rate_limited' && attempt < TIME_MACHINE_CONSENT_AT) {
178
+ return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
179
+ failureClass: classification, lastGoodTool: good,
180
+ guidance: `Rate limit reached. Respect the provider's retry/reset window; do not immediately resend the same request.${checkpoint}` };
181
+ }
170
182
  if (value.failureKind === 'site_refusal' && attempt < TIME_MACHINE_MAX_ATTEMPTS) {
171
183
  return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
172
184
  failureClass: classification, lastGoodTool: good,