introsio 0.0.0-stage → 0.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.
@@ -0,0 +1,134 @@
1
+ // Features `test-gate` and `shipped-gate`: what must be true on disk before a claimed task can be completed.
2
+ import crypto from 'node:crypto';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { runCommand } from '../../lib/processTree.mjs';
6
+ import { relativeInside } from '../../lib/paths.mjs';
7
+
8
+ /** Agents kill a hook after 900 s (the timeout setup writes); the gate must finish well before. */
9
+ export const MAX_GATE_TIMEOUT_SEC = 840;
10
+
11
+ /** The repo mode: configured, else github when the claim named a repository, else local. */
12
+ export function resolveMode(settings, claim) {
13
+ return settings.mode ?? (claim?.repository ? 'github' : 'local');
14
+ }
15
+
16
+ /** Paths from `git status --porcelain` lines ("XY path", "R old -> new", quoted when unusual). */
17
+ export function porcelainPaths(line) {
18
+ const body = line.slice(3);
19
+ const unquote = (value) => (value.startsWith('"') && value.endsWith('"') ? value.slice(1, -1).replace(/\\(.)/g, '$1') : value);
20
+ return body.includes(' -> ') ? body.split(' -> ').map(unquote) : [unquote(body)];
21
+ }
22
+
23
+ /**
24
+ * The files this task is about: what the agent edited in this session plus what
25
+ * it lists in outcome.files. Uncommitted changes elsewhere — the person's own
26
+ * work in progress — are none of the gate's business.
27
+ */
28
+ export function taskFiles({ session, args, root }) {
29
+ const files = new Set();
30
+ for (const file of session?.editedFiles ?? []) files.add(file);
31
+ for (const file of args?.outcome?.files ?? []) if (typeof file === 'string' && file.trim()) { const rel = relativeInside(root, file.trim()); if (rel) files.add(rel); }
32
+ return [...files].filter(Boolean);
33
+ }
34
+
35
+ const touches = (dirtyPath, files) => files.some((file) => dirtyPath === file || dirtyPath.startsWith(`${file.replace(/\/$/, '')}/`) || file.startsWith(`${dirtyPath.replace(/\/$/, '')}/`));
36
+
37
+ /**
38
+ * `shipped-gate`: in local mode the task's work must be committed; in github mode
39
+ * it must also be pushed, off the default branch, with the branch recorded.
40
+ */
41
+ export function shippedDecision({ git, settings, claim, args, session }) {
42
+ const mode = resolveMode(settings, claim);
43
+ const root = git.root();
44
+ if (mode === 'off' || !root) return { type: 'none' };
45
+ const dirty = git.dirty();
46
+ const files = taskFiles({ session, args, root });
47
+ const relevant = files.length ? dirty.filter((line) => porcelainPaths(line).some((p) => touches(p, files))) : dirty;
48
+ if (relevant.length > 0) {
49
+ const list = relevant.slice(0, 6).map((line) => ` ${line.trim()}`).join('\n');
50
+ return {
51
+ type: 'deny',
52
+ message: `Introsio (${mode} mode): commit your work before completing "${claim.title}" — uncommitted changes:\n${list}${relevant.length > 6 ? `\n …and ${relevant.length - 6} more` : ''}` +
53
+ (files.length ? '' : '\nIf some of these are not yours, list exactly the files you changed in outcome.files and only those are checked.'),
54
+ };
55
+ }
56
+ if (mode === 'local') return { type: 'none' };
57
+
58
+ const branch = git.branch();
59
+ if (!branch || branch === 'HEAD') {
60
+ return { type: 'deny', message: 'Introsio (github mode): you are on a detached HEAD. Create a branch for the work (git switch -c <name>), push it, then complete.' };
61
+ }
62
+ const defaultBranch = claim.repository?.defaultBranch ?? git.defaultBranch();
63
+ if (defaultBranch && branch === defaultBranch) {
64
+ return { type: 'deny', message: `Introsio (github mode): the work is on the default branch "${branch}". Move it to a branch of its own (git switch -c <name>), push that, then complete.` };
65
+ }
66
+ if (!git.upstream()) {
67
+ return { type: 'deny', message: `Introsio (github mode): branch "${branch}" is not pushed. Run git push -u origin ${branch}, then complete with outcome.branch "${branch}".` };
68
+ }
69
+ const ahead = git.aheadOfUpstream();
70
+ if (ahead && ahead > 0) {
71
+ return { type: 'deny', message: `Introsio (github mode): ${ahead} commit(s) on "${branch}" are not pushed. Push them, then complete.` };
72
+ }
73
+ if (!args.outcome?.branch && !claim.branch) {
74
+ return { type: 'deny', message: `Introsio (github mode): add outcome.branch "${branch}" to the completion so the app can show its pull request.` };
75
+ }
76
+ return { type: 'none' };
77
+ }
78
+
79
+ /**
80
+ * What the gate's verdict depends on: the command, the commit, every tracked
81
+ * change (`git stash create` snapshots them as one object id, whatever their
82
+ * size) and every untracked file (path, size, mtime). Null when any part cannot
83
+ * be read — then nothing is cached and the gate always runs.
84
+ */
85
+ export function workTreeKey(git, command) {
86
+ const head = git.head();
87
+ const dirty = git.run(['status', '--porcelain', '--untracked-files=no']);
88
+ // A stash commit carries a timestamp; its tree id is what is deterministic.
89
+ const stash = dirty.ok && dirty.out.trim() ? git.run(['stash', 'create']) : { ok: true, out: '' };
90
+ const snapshot = stash.ok && stash.out.trim() ? git.run(['rev-parse', `${stash.out.trim()}^{tree}`]) : stash;
91
+ const untracked = git.run(['ls-files', '--others', '--exclude-standard', '-z'], { maxBuffer: 64 * 1024 * 1024 });
92
+ if (!dirty.ok || !snapshot.ok || !untracked.ok) return null;
93
+ const root = git.root();
94
+ const hash = crypto.createHash('sha1');
95
+ hash.update(`${command}\0${head ?? 'no-head'}\0${snapshot.out}\0`);
96
+ for (const file of untracked.out.split('\0').filter(Boolean)) {
97
+ let stat = null;
98
+ try { stat = fs.statSync(path.join(root, file)); } catch { /* removed meanwhile */ }
99
+ hash.update(`${file}\0${stat?.size ?? -1}\0${stat?.mtimeMs ?? -1}\0`);
100
+ }
101
+ return hash.digest('hex');
102
+ }
103
+
104
+ export function runGateCommand(command, cwd, timeoutSec) {
105
+ return runCommand(command, { cwd, timeoutSec: Math.min(timeoutSec, MAX_GATE_TIMEOUT_SEC), env: { ...process.env, CI: process.env.CI ?? '1' } });
106
+ }
107
+
108
+ /**
109
+ * `test-gate`, step 1 (cheap, under the session lock): nothing to do, a cached
110
+ * pass, or a plan to run the command.
111
+ */
112
+ export function planTestGate({ git, settings, cache }) {
113
+ if (!settings.gate) return null;
114
+ const root = git.root();
115
+ if (!root) return null;
116
+ const key = workTreeKey(git, settings.gate);
117
+ if (key && cache.get(root)?.key === key) return null;
118
+ return { root, key, command: settings.gate, timeoutSec: Math.min(settings.gateTimeoutSec, MAX_GATE_TIMEOUT_SEC) };
119
+ }
120
+
121
+ /** `test-gate`, step 2 (outside the lock — it can take minutes): run it and decide. */
122
+ export async function runTestGate(plan, { claim, cache, runGate = runGateCommand, now }) {
123
+ const run = await runGate(plan.command, plan.root, plan.timeoutSec);
124
+ if (run.ok) {
125
+ if (plan.key) cache.set(plan.root, { key: plan.key, passedAt: now, ms: run.ms });
126
+ return { type: 'none', ran: true };
127
+ }
128
+ return {
129
+ type: 'deny',
130
+ message: run.timedOut
131
+ ? `Introsio: the check "${plan.command}" did not finish in ${plan.timeoutSec}s, so "${claim.title}" cannot be completed yet. Make it faster or change the limit (int gate set "<cmd>" --timeout <sec>, at most ${MAX_GATE_TIMEOUT_SEC}).`
132
+ : `Introsio: "${plan.command}" failed (exit ${run.code}), so "${claim.title}" cannot be completed. Fix it, then complete again. Last lines:\n${run.output}`,
133
+ };
134
+ }
@@ -0,0 +1,243 @@
1
+ // Features `push-guard` and `secrets`: what a shell command may do with git.
2
+
3
+ /** Splits a shell line into commands (on && || ; | and newlines outside quotes), each as unquoted words. */
4
+ export function shellCommands(command) {
5
+ const commands = [];
6
+ let words = [];
7
+ let word = '';
8
+ let quote = null;
9
+ let started = false;
10
+ const endWord = () => {
11
+ if (started) words.push(word);
12
+ word = '';
13
+ started = false;
14
+ };
15
+ const endCommand = () => {
16
+ endWord();
17
+ if (words.length) commands.push(words);
18
+ words = [];
19
+ };
20
+ const text = String(command ?? '');
21
+ for (let i = 0; i < text.length; i += 1) {
22
+ const ch = text[i];
23
+ if (quote) {
24
+ if (ch === quote) quote = null;
25
+ else if (ch === '\\' && quote === '"' && i + 1 < text.length) word += text[(i += 1)];
26
+ else word += ch;
27
+ continue;
28
+ }
29
+ if (ch === '"' || ch === "'") { quote = ch; started = true; continue; }
30
+ if (ch === '\\' && i + 1 < text.length) { word += text[(i += 1)]; started = true; continue; }
31
+ if (ch === ';' || ch === '\n' || ch === '|' || (ch === '&' && text[i + 1] === '&')) {
32
+ if (ch === '&' || (ch === '|' && text[i + 1] === '|')) i += 1;
33
+ endCommand();
34
+ continue;
35
+ }
36
+ if (/\s/.test(ch)) { endWord(); continue; }
37
+ word += ch;
38
+ started = true;
39
+ }
40
+ endCommand();
41
+ return commands;
42
+ }
43
+
44
+ const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh']);
45
+ /** Words that run the rest of the line as a command (`env A=1 git …`, `sudo git …`). */
46
+ const PREFIXES = new Set(['env', 'sudo', 'command', 'exec', 'nohup', 'time', 'nice']);
47
+ const MAX_WRAPPER_DEPTH = 3;
48
+
49
+ /**
50
+ * The script a wrapper runs, when the command is one: `bash -c "…"`, `sh -lc '…'`,
51
+ * `eval "…"` (also behind env/sudo prefixes). Its text is checked like a command
52
+ * line of its own, so `bash -c "git push origin main"` is guarded the same as the
53
+ * bare push. A guard-rail for agents, not a sandbox: a script file or another
54
+ * interpreter (`python -c`) is not looked into.
55
+ */
56
+ function wrappedScript(words) {
57
+ let i = 0;
58
+ while (i < words.length && (PREFIXES.has(words[i].split('/').pop()) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]))) i += 1;
59
+ const head = words[i]?.split('/').pop();
60
+ if (head === 'eval') return words.slice(i + 1).join(' ');
61
+ if (!SHELLS.has(head)) return null;
62
+ for (let j = i + 1; j < words.length; j += 1) {
63
+ // `-c` alone or in a cluster (`-lc`, `-ec`); the script is the next word.
64
+ if (/^-[a-zA-Z]*c[a-zA-Z]*$/.test(words[j])) return words[j + 1] ?? null;
65
+ if (!words[j].startsWith('-')) return null;
66
+ }
67
+ return null;
68
+ }
69
+
70
+ /** Every `git … <sub>` invocation in a shell command line, as argv arrays after `git`. */
71
+ export function gitInvocations(command, depth = 0) {
72
+ const out = [];
73
+ for (const words of shellCommands(command)) {
74
+ const script = depth < MAX_WRAPPER_DEPTH ? wrappedScript(words) : null;
75
+ if (script !== null) {
76
+ out.push(...gitInvocations(script, depth + 1));
77
+ continue;
78
+ }
79
+ const gitAt = words.findIndex((token) => token === 'git' || token.endsWith('/git'));
80
+ if (gitAt < 0) continue;
81
+ const args = words.slice(gitAt + 1);
82
+ // Skip global options (-C dir, -c k=v, --no-pager …) to find the subcommand.
83
+ let i = 0;
84
+ while (i < args.length && args[i].startsWith('-')) i += ['-C', '-c', '--git-dir', '--work-tree'].includes(args[i]) ? 2 : 1;
85
+ if (i < args.length) out.push({ sub: args[i], args: args.slice(i + 1) });
86
+ }
87
+ return out;
88
+ }
89
+
90
+ /**
91
+ * `push-guard`: local mode pushes nothing; otherwise no force push, no mirror,
92
+ * and nothing lands on (or deletes) the default branch.
93
+ */
94
+ export function pushDecision({ command, mode, git, defaultBranch }) {
95
+ const pushes = gitInvocations(command).filter((call) => call.sub === 'push');
96
+ if (pushes.length === 0) return { type: 'none' };
97
+ // Pause snapshots (refs/introsio/paused/*) hold unfinished work and stay on this computer, whatever the mode.
98
+ if (pushes.some(({ args }) => args.some((arg) => /(^|:|\+)refs\/introsio\//.test(arg)))) {
99
+ return { type: 'deny', message: 'Introsio: refs/introsio/* are local pause snapshots of unfinished work — they are never pushed. To hand work over, commit it on a branch and push that (or /introsio-pause --release).' };
100
+ }
101
+ if (mode === 'off') return { type: 'none' };
102
+ if (mode === 'local') {
103
+ return { type: 'deny', message: 'Introsio (local mode): this repository stays on this computer — git push is blocked. Commit locally; switch with `int mode github` if it should go to GitHub.' };
104
+ }
105
+ const current = git.branch();
106
+ const main = defaultBranch ?? git.defaultBranch();
107
+ for (const { args } of pushes) {
108
+ if (args.some((arg) => arg === '--force' || arg === '-f' || /^-[a-zA-Z]*f[a-zA-Z]*$/.test(arg) && !arg.startsWith('--'))) {
109
+ return { type: 'deny', message: 'Introsio: force push is blocked. Use --force-with-lease on your own branch if you really must rewrite it.' };
110
+ }
111
+ if (args.includes('--mirror')) return { type: 'deny', message: 'Introsio: git push --mirror is blocked.' };
112
+ // Every local branch — the default one included — so it cannot be checked target by target.
113
+ if (args.includes('--all') || args.includes('--branches')) {
114
+ return { type: 'deny', message: `Introsio: git push --all is blocked — it pushes every local branch, "${main || 'the default branch'}" included. Push your own branch by name (git push -u origin <name>).` };
115
+ }
116
+ const positional = args.filter((arg) => !arg.startsWith('-'));
117
+ const deleting = args.includes('--delete') || args.includes('-d');
118
+ const refspecs = positional.slice(1);
119
+ if (args.includes('--tags')) continue;
120
+ // A bare push goes where push.default sends it — possibly main from a branch with another name.
121
+ const bareTarget = () => {
122
+ const push = git.pushTarget?.();
123
+ return push ? push.replace(/^[^/]+\//, '') : current;
124
+ };
125
+ const targets = refspecs.length === 0 ? [bareTarget()] : refspecs.map((spec) => {
126
+ const cleaned = spec.replace(/^\+/, '');
127
+ const dest = cleaned.includes(':') ? cleaned.split(':').pop() : cleaned;
128
+ return dest === 'HEAD' || dest === '' ? current : dest;
129
+ });
130
+ if (refspecs.some((spec) => spec.startsWith('+'))) {
131
+ return { type: 'deny', message: 'Introsio: force push (a "+" refspec) is blocked.' };
132
+ }
133
+ const hitsMain = main && targets.some((target) => String(target ?? '').replace(/^refs\/heads\//, '') === main);
134
+ if (hitsMain) {
135
+ return {
136
+ type: 'deny',
137
+ message: deleting
138
+ ? `Introsio: deleting the default branch "${main}" is blocked.`
139
+ : `Introsio: pushing to the default branch "${main}" is blocked. Push your own branch (git switch -c <name>; git push -u origin <name>) and open a pull request.`,
140
+ };
141
+ }
142
+ }
143
+ return { type: 'none' };
144
+ }
145
+
146
+ const SECRET_PATTERNS = [
147
+ ['private key', /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----/],
148
+ ['AWS access key', /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/],
149
+ ['GitHub token', /\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{60,})\b/],
150
+ ['Anthropic API key', /\bsk-ant-[A-Za-z0-9_-]{32,}/],
151
+ ['OpenAI API key', /\bsk-(?:proj-|svcacct-)?[A-Za-z0-9_-]{40,}/],
152
+ ['Stripe live key', /\b(?:sk|rk)_live_[A-Za-z0-9]{20,}\b/],
153
+ ['Slack token', /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/],
154
+ ['Google API key', /\bAIza[0-9A-Za-z_-]{35}\b/],
155
+ ];
156
+
157
+ const SECRET_FILE = /(^|\/)(\.env(\.[\w-]+)?|id_rsa|id_ed25519|[^/]+\.pem|[^/]+\.p12|credentials\.json)$/;
158
+ const SAFE_ENV_FILE = /\.env\.(example|sample|template|defaults?)$/;
159
+
160
+ /**
161
+ * Lines that are explicitly not secrets: the vendors' own documented examples
162
+ * (AWS's AKIAIOSFODNN7EXAMPLE …) and an allow comment on the line itself.
163
+ */
164
+ const ALLOWED_LINE = /EXAMPLE|int:allow-secret|pragma:\s*allowlist secret|gitleaks:allow|nosec/i;
165
+
166
+ function secretKind(content) {
167
+ if (ALLOWED_LINE.test(content)) return null;
168
+ for (const [kind, pattern] of SECRET_PATTERNS) if (pattern.test(content)) return kind;
169
+ return null;
170
+ }
171
+
172
+ /** Secrets in the added lines of a unified diff. Never returns the value — file, line and kind only. */
173
+ export function scanDiff(diff) {
174
+ const findings = [];
175
+ let file = null;
176
+ let line = 0;
177
+ for (const raw of String(diff ?? '').split('\n')) {
178
+ if (raw.startsWith('+++ ')) {
179
+ file = raw.slice(4).replace(/^b\//, '');
180
+ if (file !== '/dev/null' && SECRET_FILE.test(file) && !SAFE_ENV_FILE.test(file)) findings.push({ file, line: null, kind: 'secret file' });
181
+ continue;
182
+ }
183
+ const hunk = raw.match(/^@@ -\d+(?:,\d+)? \+(\d+)/);
184
+ if (hunk) { line = Number(hunk[1]); continue; }
185
+ if (raw.startsWith('+')) {
186
+ const kind = secretKind(raw);
187
+ if (kind) findings.push({ file, line, kind });
188
+ line += 1;
189
+ } else if (!raw.startsWith('-')) {
190
+ line += 1;
191
+ }
192
+ }
193
+ return findings;
194
+ }
195
+
196
+ export function scanText(file, text) {
197
+ const findings = [];
198
+ if (SECRET_FILE.test(file) && !SAFE_ENV_FILE.test(file)) findings.push({ file, line: null, kind: 'secret file' });
199
+ String(text ?? '').split('\n').forEach((content, index) => {
200
+ const kind = secretKind(content);
201
+ if (kind) findings.push({ file, line: index + 1, kind });
202
+ });
203
+ return findings;
204
+ }
205
+
206
+ /** `secrets`: scan what a commit / push would publish. `readFile` reads untracked files when the command also stages. */
207
+ export function secretsDecision({ command, git, readFile }) {
208
+ const calls = gitInvocations(command);
209
+ const commit = calls.find((call) => call.sub === 'commit');
210
+ const push = calls.find((call) => call.sub === 'push');
211
+ if (!commit && !push) return { type: 'none' };
212
+ const stagesFirst = calls.some((call) => call.sub === 'add') || (commit && commit.args.some((arg) => /^-[a-zA-Z]*a/.test(arg) || arg === '--all'));
213
+ let findings = [];
214
+ let unreadable = false;
215
+ const scan = (diff) => {
216
+ if (diff === null) unreadable = true;
217
+ else findings = findings.concat(scanDiff(diff));
218
+ };
219
+ if (commit) {
220
+ scan(git.diff(stagesFirst ? ['HEAD'] : ['--cached']));
221
+ if (calls.some((call) => call.sub === 'add')) {
222
+ const untracked = git.run(['ls-files', '--others', '--exclude-standard']).out.split('\n').filter(Boolean).slice(0, 200);
223
+ for (const file of untracked) findings = findings.concat(scanText(file, readFile(file)));
224
+ }
225
+ }
226
+ if (push) {
227
+ const range = git.upstream() ? ['@{u}..HEAD'] : (() => {
228
+ const main = git.defaultBranch();
229
+ return main && main !== git.branch() ? [`${main}...HEAD`] : null;
230
+ })();
231
+ if (range) scan(git.diff(range));
232
+ }
233
+ if (findings.length === 0) {
234
+ // Too large to read whole (over 128 MB): say so instead of passing it as clean.
235
+ return unreadable ? { type: 'none', note: 'Introsio: this change is too large to scan for secrets; check it yourself before it is pushed.' } : { type: 'none' };
236
+ }
237
+ const unique = [...new Map(findings.map((item) => [`${item.file}:${item.line}:${item.kind}`, item])).values()];
238
+ const list = unique.slice(0, 8).map((item) => ` ${item.file}${item.line ? `:${item.line}` : ''} — ${item.kind}`).join('\n');
239
+ return {
240
+ type: 'deny',
241
+ message: `Introsio: this ${commit ? 'commit' : 'push'} would publish what looks like a secret:\n${list}\nMove it to an environment variable or an ignored file, remove it from the change (and from earlier commits if it is already in one), then retry. A false positive: add the comment int:allow-secret on that line, or turn the check off with: int disable secrets`,
242
+ };
243
+ }
@@ -0,0 +1,70 @@
1
+ // Feature `log`: one line per Introsio call in ~/.introsio/log.jsonl, summed up by `int stats`.
2
+ import fs from 'node:fs';
3
+ import { logPath } from '../../lib/paths.mjs';
4
+ import { appendLine } from '../../lib/jsonFile.mjs';
5
+
6
+ const MAX_LOG_BYTES = 20 * 1024 * 1024;
7
+
8
+ export function logRow(session, evt, { name, args = {}, result }, now) {
9
+ const started = session.pending?.[name];
10
+ if (started) delete session.pending[name];
11
+ const data = result?.data ?? {};
12
+ const error = result?.ok ? null : String(data.error ?? data.message ?? (result?.isError ? 'error' : 'refused')).slice(0, 200);
13
+ return {
14
+ at: new Date(now).toISOString(),
15
+ agent: evt.agent,
16
+ session: session.sessionId,
17
+ tool: name,
18
+ ok: !!result?.ok,
19
+ ...(error ? { error } : {}),
20
+ ...(data.code ? { code: data.code } : {}),
21
+ ...(args.taskId || data.task?.id ? { taskId: String(args.taskId ?? data.task.id) } : {}),
22
+ ...(args.projectId || data.project?.id ? { projectId: String(args.projectId ?? data.project.id) } : {}),
23
+ ...(Number.isFinite(evt.durationMs) ? { ms: evt.durationMs } : started ? { ms: now - started } : {}),
24
+ };
25
+ }
26
+
27
+ export function writeLog(row, env) {
28
+ const file = logPath(env);
29
+ try {
30
+ if (fs.statSync(file).size > MAX_LOG_BYTES) fs.renameSync(file, `${file}.1`);
31
+ } catch { /* no log yet */ }
32
+ appendLine(file, JSON.stringify(row));
33
+ }
34
+
35
+ /** Pure summary of log rows, for `int stats`. */
36
+ export function summarize(rows) {
37
+ const byTool = new Map();
38
+ const byTask = new Map();
39
+ const errors = new Map();
40
+ const streaks = new Map();
41
+ const loops = [];
42
+ for (const row of rows) {
43
+ const tool = byTool.get(row.tool) ?? { tool: row.tool, calls: 0, refused: 0, totalMs: 0, timed: 0 };
44
+ tool.calls += 1;
45
+ if (!row.ok) tool.refused += 1;
46
+ if (Number.isFinite(row.ms)) { tool.totalMs += row.ms; tool.timed += 1; }
47
+ byTool.set(row.tool, tool);
48
+ if (!row.ok && row.error) errors.set(row.error, (errors.get(row.error) ?? 0) + 1);
49
+ if (row.taskId) {
50
+ const task = byTask.get(row.taskId) ?? { taskId: row.taskId, calls: 0, refused: 0, first: row.at, last: row.at, completed: false };
51
+ task.calls += 1;
52
+ if (!row.ok) task.refused += 1;
53
+ task.last = row.at;
54
+ if (row.ok && row.tool === 'completeTask') task.completed = true;
55
+ byTask.set(row.taskId, task);
56
+ const key = `${row.session}|${row.tool}|${row.taskId}`;
57
+ const streak = row.ok ? 0 : (streaks.get(key) ?? 0) + 1;
58
+ streaks.set(key, streak);
59
+ if (streak === 3) loops.push({ tool: row.tool, taskId: row.taskId, session: row.session, error: row.error });
60
+ }
61
+ }
62
+ return {
63
+ calls: rows.length,
64
+ refused: rows.filter((row) => !row.ok).length,
65
+ tools: [...byTool.values()].map((tool) => ({ tool: tool.tool, calls: tool.calls, refused: tool.refused, avgMs: tool.timed ? Math.round(tool.totalMs / tool.timed) : null })).sort((a, b) => b.calls - a.calls),
66
+ topErrors: [...errors.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5).map(([error, count]) => ({ error, count })),
67
+ tasks: [...byTask.values()].map((task) => ({ ...task, minutes: Math.round((Date.parse(task.last) - Date.parse(task.first)) / 60000) })).sort((a, b) => b.refused - a.refused || b.calls - a.calls),
68
+ retryLoops: loops,
69
+ };
70
+ }
@@ -0,0 +1,88 @@
1
+ // Features `scope`, `lease`, `compact-recovery` and `reread`: short notes that save the agent work.
2
+ import path from 'node:path';
3
+ import { relativeInside } from '../../lib/paths.mjs';
4
+
5
+ const IGNORED = /(^|\/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb?|Cargo\.lock|poetry\.lock|go\.sum)$/;
6
+
7
+ /** `scope`: a soft warning when an edit lands outside the files the claimed task names. */
8
+ export function scopeNote(session, files, root) {
9
+ const claims = Object.values(session.claims ?? {}).filter((claim) => claim.files?.length);
10
+ if (claims.length === 0 || !root) return null;
11
+ const named = claims.flatMap((claim) => claim.files);
12
+ const outside = [];
13
+ for (const file of files) {
14
+ const rel = relativeInside(root, file);
15
+ if (!rel || IGNORED.test(rel) || session.warnedFiles.includes(rel)) continue;
16
+ const inScope = named.some((entry) => {
17
+ const clean = entry.replace(/\/$/, '');
18
+ return rel === clean || rel.startsWith(`${clean}/`) || rel.endsWith(`/${clean}`) || path.posix.basename(rel) === clean;
19
+ });
20
+ if (!inScope) {
21
+ outside.push(rel);
22
+ session.warnedFiles.push(rel);
23
+ }
24
+ }
25
+ if (outside.length === 0) return null;
26
+ return `Introsio: ${outside.join(', ')} ${outside.length === 1 ? 'is' : 'are'} not among the files "${claims[0].title}" names. Fine if the task needs it — otherwise keep the change to the task's scope, and list every file you touched in outcome.files.`;
27
+ }
28
+
29
+ const clock = (ms) => new Date(ms).toISOString().slice(11, 16) + ' UTC';
30
+
31
+ /** `lease`: one reminder per write when a claim is 60% through its lease. */
32
+ export function leaseNote(session, now) {
33
+ const notes = [];
34
+ for (const claim of Object.values(session.claims ?? {})) {
35
+ if (!claim.expiresAt) continue;
36
+ if (claim.nudgedAt && claim.nudgedAt >= claim.lastWriteAt) continue;
37
+ const lease = claim.leaseMs || claim.expiresAt - claim.lastWriteAt;
38
+ if (now >= claim.expiresAt) {
39
+ notes.push(`Introsio: your claim on "${claim.title}" expired at ${clock(claim.expiresAt)} — another worker may take it. Call claimTask { taskId: "${claim.taskId}", workerId: "${claim.workerId}" } to hold it again before you continue.`);
40
+ claim.nudgedAt = now;
41
+ } else if (now - claim.lastWriteAt > 0.6 * lease) {
42
+ notes.push(`Introsio: your claim on "${claim.title}" expires at ${clock(claim.expiresAt)}. Report progress (updateSubtask, or updateTask with workerId "${claim.workerId}") to keep it.`);
43
+ claim.nudgedAt = now;
44
+ }
45
+ }
46
+ return notes.length ? notes.join('\n') : null;
47
+ }
48
+
49
+ /** `compact-recovery`: what the agent needs to carry on after its context was compacted. */
50
+ export function recoveryNote(session) {
51
+ const claims = Object.values(session.claims ?? {});
52
+ if (!session.introsio && claims.length === 0) return null;
53
+ const lines = [`Introsio (restored after compaction): your workerId is "${session.workerId ?? claims[0]?.workerId ?? 'unset'}".`];
54
+ for (const claim of claims) {
55
+ const revision = claim.projectId != null ? session.contextRevision?.[claim.projectId] : undefined;
56
+ const parts = [
57
+ claim.subtasks?.total ? `subtasks ${claim.subtasks.done}/${claim.subtasks.total} done` : null,
58
+ revision !== undefined ? `context revision ${revision}` : null,
59
+ claim.expiresAt ? `lease until ${clock(claim.expiresAt)}` : null,
60
+ ].filter(Boolean);
61
+ lines.push(`You hold "${claim.title}" (taskId ${claim.taskId}${claim.projectId ? `, project ${claim.projectId}` : ''})${parts.length ? ` — ${parts.join(', ')}` : ''}. Continue it (getReadySubtasks shows the next step), then completeTask with outcome.`);
62
+ }
63
+ const paused = Object.entries(session.paused ?? {});
64
+ if (paused.length) lines.push(`You paused: ${paused.map(([id, item]) => `"${item.title}" (taskId ${id})`).join(', ')} — /introsio-resume takes them back after checking the repository.`);
65
+ if (claims.length === 0) lines.push('You hold no task. claimTask { projectId, workerId } takes the next one.');
66
+ return lines.join('\n');
67
+ }
68
+
69
+ /** `reread`: refuse once a read whose answer the agent already has; a second identical call goes through. */
70
+ export function rereadDecision(session, { name, args = {} }) {
71
+ if (session.contextLost) return { type: 'none' };
72
+ if (name === 'getProjectContext') {
73
+ const pid = args.projectId;
74
+ const read = session.contextRead?.[pid];
75
+ const latest = session.contextRevision?.[pid];
76
+ if (read === undefined || latest === undefined || read !== latest) return { type: 'none' };
77
+ const key = `context:${pid}:${latest}`;
78
+ session.rereadDenied = session.rereadDenied ?? {};
79
+ if (session.rereadDenied[key]) return { type: 'none' };
80
+ session.rereadDenied[key] = true;
81
+ return { type: 'deny', message: `Introsio: revision ${latest} of this project's context was already read in this session and has not changed — use what you have. If it is not in your context (you are a subagent, or it was trimmed), call again and it goes through.` };
82
+ }
83
+ if ((name === 'getExecutionWaves' || name === 'getProjectPlan') && session.lastCompletion?.nowReady?.length && !session.lastCompletion.rereadDenied) {
84
+ session.lastCompletion.rereadDenied = true;
85
+ return { type: 'deny', message: `Introsio: your last completeTask already said what is next — nowReady: ${session.lastCompletion.nowReady.join(', ')}. Call claimTask { projectId, workerId } instead of re-reading the schedule. (Call again if you really need the whole schedule.)` };
86
+ }
87
+ return { type: 'none' };
88
+ }