@picassohq/cli 1.0.4 → 1.0.5

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 (40) hide show
  1. package/dist/build-info.json +2 -1
  2. package/dist/index.js +1557 -1353
  3. package/package.json +1 -1
  4. package/runtime/dsh/picasso-ecosystem.cordis.patch.yml +4 -7
  5. package/runtime/dsh/picasso-sdk.patch.yml +47 -0
  6. package/runtime/engine-manifest.json +20 -10
  7. package/runtime/packages/picasso-compaction/index.js +257 -5
  8. package/runtime/packages/picasso-hooks/cordis.patch.yml +4 -0
  9. package/runtime/packages/picasso-hooks/index.js +302 -0
  10. package/runtime/packages/picasso-hooks/lifecycle-events.js +651 -0
  11. package/runtime/packages/picasso-hooks/package.json +29 -0
  12. package/runtime/packages/picasso-lean-context/glob-walk.js +518 -0
  13. package/runtime/packages/picasso-lean-context/index.js +136 -9
  14. package/runtime/packages/picasso-memory/index.js +66 -24
  15. package/runtime/packages/picasso-model-router/connections.js +164 -7
  16. package/runtime/packages/picasso-model-router/index.js +97 -1
  17. package/runtime/packages/picasso-model-router/thinking-default.js +29 -5
  18. package/runtime/packages/picasso-progress-reports/index.js +128 -18
  19. package/runtime/packages/picasso-sdk-server/command-runs.js +37 -0
  20. package/runtime/packages/picasso-sdk-server/ignore-file.js +5 -1
  21. package/runtime/packages/picasso-sdk-server/index.js +11 -3
  22. package/runtime/packages/picasso-sdk-server/package.json +1 -0
  23. package/runtime/packages/picasso-sdk-server/wave2-hooks.js +26 -6
  24. package/runtime/packages/picasso-x-reader/settings.js +4 -1
  25. package/runtime/plugins/picasso-auto-approve/index.js +21 -8
  26. package/runtime/plugins/picasso-compaction/index.js +257 -5
  27. package/runtime/plugins/picasso-hooks/index.js +302 -0
  28. package/runtime/plugins/picasso-hooks/lifecycle-events.js +651 -0
  29. package/runtime/plugins/picasso-hooks/package.json +29 -0
  30. package/runtime/plugins/picasso-lean-context/glob-walk.js +518 -0
  31. package/runtime/plugins/picasso-lean-context/index.js +136 -9
  32. package/runtime/plugins/picasso-memory/index.js +66 -24
  33. package/runtime/plugins/picasso-model-router/connections.js +164 -7
  34. package/runtime/plugins/picasso-model-router/index.js +97 -1
  35. package/runtime/plugins/picasso-model-router/thinking-default.js +29 -5
  36. package/runtime/plugins/picasso-progress-reports/index.js +128 -18
  37. package/runtime/plugins/picasso-trackers/index.js +12 -2
  38. package/runtime/plugins/picasso-x-reader/settings.js +4 -1
  39. package/runtime/relay/main.mjs +2254 -1648
  40. package/runtime/relay/versions-routes.mjs +24 -20
@@ -28,7 +28,7 @@ import { readFileSync, statSync } from 'node:fs';
28
28
  import { userInfo } from 'node:os';
29
29
  import { join } from 'node:path';
30
30
 
31
- import { isProgressReport } from './report.js';
31
+ import { isProgressReport, parseProgressReport } from './report.js';
32
32
 
33
33
  export { formatReportMarkdown, isProgressReport, parseProgressReport, splitReportItems } from './report.js';
34
34
 
@@ -131,11 +131,24 @@ function freshState() {
131
131
  openerSeen: true,
132
132
  /** A reminder is in history with no report after it yet. */
133
133
  reminderPending: false,
134
+ /** Reminders in history since the newest report (the ones the model has not answered). */
135
+ unanswered: 0,
134
136
  /** The model has reported without being reminded (its own instructions ask for reports). */
135
137
  selfReporting: false,
138
+ /** The last `todo/write` list (`[]` before any). */
139
+ todos: [],
140
+ /** The newest report's percent written after the last `todo/write` (undefined when none since). */
141
+ reportPercentSincePlan: undefined,
142
+ /** A plan-drift nudge is in history since the last `todo/write`. */
143
+ driftNudged: false,
136
144
  };
137
145
  }
138
146
 
147
+ function todosFrom(data) {
148
+ const list = isRecord(data) && Array.isArray(data.todos) ? data.todos : [];
149
+ return list.filter(isRecord).map((todo) => ({ status: typeof todo.status === 'string' ? todo.status : 'pending' }));
150
+ }
151
+
139
152
  /** Fold one durable session event into the timing state. */
140
153
  export function foldEvent(state, event) {
141
154
  if (!isRecord(event)) return state;
@@ -155,16 +168,27 @@ export function foldEvent(state, event) {
155
168
  if (message?.source?.kind === SOURCE_KIND && time !== undefined) {
156
169
  state.lastReminder = time;
157
170
  state.reminderPending = true;
171
+ state.unanswered += 1;
158
172
  }
173
+ if (message?.source?.kind === DRIFT_SOURCE_KIND) state.driftNudged = true;
159
174
  break;
160
175
  }
161
- case 'assistant/message':
162
- if (time !== undefined && isProgressReport(textOf(event.data?.message))) {
176
+ case 'todo/write':
177
+ state.todos = todosFrom(event.data);
178
+ state.reportPercentSincePlan = undefined;
179
+ state.driftNudged = false;
180
+ break;
181
+ case 'assistant/message': {
182
+ const report = parseProgressReport(textOf(event.data?.message));
183
+ if (report !== undefined && report.percent !== undefined) state.reportPercentSincePlan = report.percent;
184
+ if (time !== undefined && report !== undefined) {
163
185
  state.lastReport = time;
164
186
  if (!state.reminderPending) state.selfReporting = true;
165
187
  state.reminderPending = false;
188
+ state.unanswered = 0;
166
189
  }
167
190
  break;
191
+ }
168
192
  default:
169
193
  break;
170
194
  }
@@ -209,12 +233,36 @@ export function reminderDue(state, now, intervalMs, proposed = []) {
209
233
  return now - baseline >= (state.selfReporting ? intervalMs * SELF_REPORT_GRACE : intervalMs);
210
234
  }
211
235
 
212
- /** The reminder's text. `minutes` is the elapsed wall time it reports. */
213
- export function renderReminder(minutes) {
236
+ /** "10 minutes" / "30 seconds" for an interval in ms (the dev/test overrides go below a minute). */
237
+ export function intervalLabel(intervalMs) {
238
+ const ms = Number.isFinite(intervalMs) && intervalMs > 0 ? intervalMs : DEFAULT_INTERVAL_MINUTES * 60_000;
239
+ if (ms < 60_000) {
240
+ const seconds = Math.max(1, Math.round(ms / 1000));
241
+ return `${seconds} second${seconds === 1 ? '' : 's'}`;
242
+ }
243
+ const minutes = Math.round(ms / 60_000);
244
+ return `${minutes} minute${minutes === 1 ? '' : 's'}`;
245
+ }
246
+
247
+ /**
248
+ * The reminder's text. `minutes` is the elapsed wall time it reports; `intervalMs` the configured cadence;
249
+ * `unanswered` how many earlier reminders since the last report got none (from history, so resume-safe).
250
+ *
251
+ * Owner 2026-11-17: on managed Claude Fable 5.1 four reminders in a row (16:55–17:37) reached the model and got no
252
+ * report, because the run's prompt said "No unnecessary progress reports" and the old text read as an optional harness
253
+ * nudge ("In your next reply … do not mention this reminder"). The text now says whose request it is (the user's
254
+ * setting, shown in the status panel), that a general "fewer status messages" instruction does not cover it, and to
255
+ * write it before the next tool call (a Claude-style model reads "reply" as its final answer).
256
+ */
257
+ export function renderReminder(minutes, options = {}) {
214
258
  const elapsed = minutes >= 1 ? `about ${Math.round(minutes)} minute${Math.round(minutes) === 1 ? '' : 's'}` : 'a while';
259
+ const unanswered = Number.isSafeInteger(options.unanswered) && options.unanswered > 0 ? options.unanswered : 0;
215
260
  return [
216
261
  '<system-reminder>',
217
- `Progress check: you have been working for ${elapsed} without a progress report. In your next reply, post a brief progress report as a normal message in exactly this shape, then keep working — do not stop, wait, or ask for confirmation:`,
262
+ `Progress check: you have been working for ${elapsed} without a progress report.`,
263
+ `The user's Picasso settings ask for a progress report every ${intervalLabel(options.intervalMs)} of work; Picasso shows it in the status panel so the user can follow a long run without interrupting it. This is that scheduled report, not an unnecessary update: a general instruction to keep status messages down does not cover it (to stop these, the user switches Progress reports off in Picasso settings).`,
264
+ ...(unanswered > 0 ? [`The last ${unanswered === 1 ? 'progress check' : `${unanswered} progress checks`} got no report.`] : []),
265
+ 'In your next message, before any further tool call, post the report as a normal message in exactly this shape, then keep working — do not stop, wait, or ask for confirmation:',
218
266
  '',
219
267
  '**Progress report** · <overall %> (<how you measured it, e.g. 3 of 7 steps done>)',
220
268
  'Goal: <the original request, one line>',
@@ -223,14 +271,14 @@ export function renderReminder(minutes) {
223
271
  'Next: <the next steps>',
224
272
  'Blockers: <blockers, or none>',
225
273
  '',
226
- 'Keep it under eight short lines, report only what actually happened, and do not mention this reminder.',
274
+ 'Keep it under eight short lines and report only what actually happened. Write it straight to the user, with no preamble about this check.',
227
275
  '</system-reminder>',
228
276
  ].join('\n');
229
277
  }
230
278
 
231
279
  /** A frozen user-role message shaped like dsh-llm's `createUserMessage` output. */
232
- export function reminderMessage(minutes) {
233
- const text = renderReminder(minutes);
280
+ export function reminderMessage(minutes, options = {}) {
281
+ const text = renderReminder(minutes, options);
234
282
  return Object.freeze({
235
283
  role: 'user',
236
284
  content: Object.freeze([Object.freeze({ type: 'text', text })]),
@@ -239,6 +287,60 @@ export function reminderMessage(minutes) {
239
287
  });
240
288
  }
241
289
 
290
+ // ── Plan drift (Tier 2) ───────────────────────────────────────────────────────────────────────────────────────
291
+ //
292
+ // Owner 2026-11-17: the status panel showed a report's "95%" over "Plan 0/6": the model kept reporting but never
293
+ // updated its todo list. When the newest report written since the last `todo/write` claims at least
294
+ // PLAN_DRIFT_POINTS more than the list's own completion (completed steps whole, the step in progress half), the next
295
+ // step gets ONE sourced `<system-reminder>` at the tail of its messages asking it to update the list. Once per
296
+ // `todo/write`; top-level agents only; the text depends only on history (the two percents and counts), so identical
297
+ // history yields identical bytes. Tier 1 is never touched.
298
+
299
+ export const DRIFT_SOURCE_KIND = 'picasso-plan-drift';
300
+ export const PLAN_DRIFT_POINTS = 50;
301
+
302
+ /** The list's completion (0–100): completed steps whole, the step in progress half. */
303
+ export function planCompletion(todos) {
304
+ const list = Array.isArray(todos) ? todos : [];
305
+ if (list.length === 0) return 0;
306
+ const credit = list.reduce((sum, todo) => sum + (todo?.status === 'completed' ? 1 : todo?.status === 'in_progress' ? 0.5 : 0), 0);
307
+ return (credit / list.length) * 100;
308
+ }
309
+
310
+ /**
311
+ * The report percent that makes the drift nudge due, else undefined: a list with steps, a report since its last write
312
+ * (this step's proposed assistant text counts as the newest), ≥ PLAN_DRIFT_POINTS above the list, no nudge yet.
313
+ */
314
+ export function planDriftDue(state, proposed = []) {
315
+ if (!isRecord(state) || state.driftNudged === true || !Array.isArray(state.todos) || state.todos.length === 0) return undefined;
316
+ let reported = state.reportPercentSincePlan;
317
+ for (const message of proposed) {
318
+ if (message?.role !== 'assistant') continue;
319
+ const report = parseProgressReport(textOf(message));
320
+ if (report?.percent !== undefined) reported = report.percent;
321
+ }
322
+ if (reported === undefined) return undefined;
323
+ return reported - planCompletion(state.todos) >= PLAN_DRIFT_POINTS ? reported : undefined;
324
+ }
325
+
326
+ /** The nudge text: the report's percent against the list's, with the list's counts. */
327
+ export function renderPlanDrift(reported, todos) {
328
+ const list = Array.isArray(todos) ? todos : [];
329
+ const done = list.filter((todo) => todo?.status === 'completed').length;
330
+ const plan = Math.round(planCompletion(list));
331
+ return `<system-reminder>\nYour latest progress report says ${reported}% done, but your todo list shows ${plan}% (${done} of ${list.length} step${list.length === 1 ? '' : 's'} completed). Update it with todo_write so the plan matches the work, then keep going.\n</system-reminder>`;
332
+ }
333
+
334
+ /** A frozen sourced user-role reminder carrying the plan-drift nudge. */
335
+ export function planDriftMessage(reported, todos) {
336
+ return Object.freeze({
337
+ role: 'user',
338
+ content: Object.freeze([Object.freeze({ type: 'text', text: renderPlanDrift(reported, todos) })]),
339
+ source: Object.freeze({ kind: DRIFT_SOURCE_KIND, form: 'reminder' }),
340
+ id: randomUUID(),
341
+ });
342
+ }
343
+
242
344
  export function apply(ctx, config = {}, deps = {}) {
243
345
  const readSettings = deps.settings ?? settingsReader(config, deps.env ?? process.env);
244
346
  const clock = deps.now ?? Date.now;
@@ -251,17 +353,25 @@ export function apply(ctx, config = {}, deps = {}) {
251
353
  const agent = args?.agent;
252
354
  const session = agent?.session;
253
355
  if (!session || typeof session.eventAt !== 'function' || isChildAgent(agent)) return decision;
254
- const { enabled, intervalMs } = readSettings();
255
- if (!enabled) return decision;
256
- if (decision.messages.some((message) => message?.source?.kind === SOURCE_KIND)) return decision;
257
356
  const state = scanSession(states, session);
357
+ // The plan-drift nudge reads only history; it is not the timed report reminder, so that setting does not gate it.
358
+ const drift = decision.messages.some((message) => message?.source?.kind === DRIFT_SOURCE_KIND) ? undefined : planDriftDue(state, decision.messages);
359
+ const extra = [];
360
+ if (drift !== undefined) {
361
+ // Recorded now so a step that is rejected downstream cannot send it twice before its event lands.
362
+ state.driftNudged = true;
363
+ extra.push(planDriftMessage(drift, state.todos));
364
+ }
365
+ const { enabled, intervalMs } = readSettings();
258
366
  const now = clock();
259
- if (!reminderDue(state, now, intervalMs, decision.messages)) return decision;
260
- const baseline = Math.max(state.runStart ?? now, state.lastReport ?? 0, state.lastReminder ?? 0);
261
- // Recorded now so a step that is rejected downstream cannot re-arm it before its event lands.
262
- state.lastReminder = now;
263
- state.reminderPending = true;
264
- return { ...decision, messages: [...decision.messages, reminderMessage((now - baseline) / 60_000)] };
367
+ if (enabled && !decision.messages.some((message) => message?.source?.kind === SOURCE_KIND) && reminderDue(state, now, intervalMs, decision.messages)) {
368
+ const baseline = Math.max(state.runStart ?? now, state.lastReport ?? 0, state.lastReminder ?? 0);
369
+ // Recorded now so a step that is rejected downstream cannot re-arm it before its event lands.
370
+ state.lastReminder = now;
371
+ state.reminderPending = true;
372
+ extra.push(reminderMessage((now - baseline) / 60_000, { intervalMs, unanswered: state.unanswered }));
373
+ }
374
+ return extra.length === 0 ? decision : { ...decision, messages: [...decision.messages, ...extra] };
265
375
  });
266
376
  }
267
377
 
@@ -0,0 +1,37 @@
1
+ // Slash commands run through `command/run` (`/compact`, `/review --fresh`, `/init`, …) have no short clock: a command
2
+ // runs until it finishes, the caller's own `timeoutMs` passes, or `session/cancel` stops it. The old fixed 120 s cut off
3
+ // a `/compact` of a long history and a fresh review with several reviewers (owner 2026-11-17).
4
+
5
+ /**
6
+ * Upper bound on one `command/run` when the caller names none (was 120 s). A command normally ends by itself or is
7
+ * stopped by `session/cancel`; this only frees a command that never settles.
8
+ */
9
+ export const COMMAND_RUN_TIMEOUT_MS = 6 * 60 * 60 * 1000;
10
+
11
+ /** Tracks the commands running per session so `session/cancel` can stop them. */
12
+ export function createCommandRuns() {
13
+ /** sessionId → AbortControllers of the commands running in it. */
14
+ const running = new Map();
15
+ return {
16
+ /** Runs `execute(signal)` with a signal that aborts on cancel or after `timeoutMs` (default `COMMAND_RUN_TIMEOUT_MS`). */
17
+ async run(sessionId, timeoutMs, execute) {
18
+ const controller = new AbortController();
19
+ const set = running.get(sessionId) ?? new Set();
20
+ set.add(controller);
21
+ running.set(sessionId, set);
22
+ try {
23
+ return await execute(AbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs ?? COMMAND_RUN_TIMEOUT_MS)]));
24
+ } finally {
25
+ set.delete(controller);
26
+ if (set.size === 0) running.delete(sessionId);
27
+ }
28
+ },
29
+ /** Stops every command running in the session. */
30
+ cancel(sessionId) {
31
+ for (const controller of running.get(sessionId) ?? []) controller.abort(new Error('cancelled'));
32
+ },
33
+ size(sessionId) {
34
+ return running.get(sessionId)?.size ?? 0;
35
+ },
36
+ };
37
+ }
@@ -150,7 +150,11 @@ export function findIgnoreFile(cwd) {
150
150
  }
151
151
  }
152
152
 
153
- const SCAN_LIMIT = 100000;
153
+ /**
154
+ * Entries one `.picassoignore` scan walks before it stops (cached per ignore file and mtime). Was 100 000: past it the
155
+ * guard cannot prove a tree is clean and refuses the read, so glob/grep failed in large monorepos with nothing ignored.
156
+ */
157
+ const SCAN_LIMIT = 2_000_000;
154
158
 
155
159
  /**
156
160
  * Ignore lookups for working directories, cached per ignore file and mtime so
@@ -18,6 +18,7 @@
18
18
  // announced the capability the waterfall falls through (fail-closed, as stock).
19
19
  //
20
20
  // Mounted by dsh/picasso-sdk.patch.yml, which disables the stock server entry.
21
+ import { createCommandRuns } from './command-runs.js';
21
22
  import { existsSync, readdirSync, realpathSync } from 'node:fs';
22
23
  import { approvalRequester, requesterFields } from './requester.js';
23
24
  import { homedir, tmpdir } from 'node:os';
@@ -488,6 +489,8 @@ export function apply(ctx, config = {}) {
488
489
  return { answers: answer.answers };
489
490
  });
490
491
 
492
+ /** The slash commands running per session (`session/cancel` stops them). */
493
+ const commandRuns = createCommandRuns();
491
494
  const requireSession = (params) => {
492
495
  if (typeof params?.sessionId !== 'string' || params.sessionId.length === 0) {
493
496
  throw new TypeError('a non-empty sessionId is required');
@@ -710,6 +713,8 @@ export function apply(ctx, config = {}) {
710
713
  async 'session/cancel'(params) {
711
714
  const agent = requireSession(params);
712
715
  agent.cancel({ kind: 'user' }, { keepInbox: params.keepInbox === true });
716
+ // A running slash command (`/compact`, `/review --fresh`, …) stops with the turn: it has no clock of its own.
717
+ commandRuns.cancel(params.sessionId);
713
718
  return {};
714
719
  },
715
720
  async 'session/fork'(params) {
@@ -746,9 +751,12 @@ export function apply(ctx, config = {}) {
746
751
  const line = typeof params.line === 'string'
747
752
  ? params.line
748
753
  : `/${String(params.name ?? '').replace(/^\//u, '')}${params.args ? ` ${params.args}` : ''}`;
749
- const execution = await commands.execute(agent, line, [], AbortSignal.timeout(params.timeoutMs ?? 120000));
750
- if (execution === undefined) throw new Error(`unknown command: ${line.split(/\s/u)[0]}`);
751
- return { commandId: execution.commandId, result: execution.result };
754
+ // No short clock on a command (command-runs.js): it runs until it ends, `timeoutMs` passes or the turn is cancelled.
755
+ return commandRuns.run(params.sessionId, params.timeoutMs, async (signal) => {
756
+ const execution = await commands.execute(agent, line, [], signal);
757
+ if (execution === undefined) throw new Error(`unknown command: ${line.split(/\s/u)[0]}`);
758
+ return { commandId: execution.commandId, result: execution.result };
759
+ });
752
760
  },
753
761
  async 'workspace/changes/get'(params) {
754
762
  requireSession(params);
@@ -11,6 +11,7 @@
11
11
  },
12
12
  "files": [
13
13
  "index.js",
14
+ "command-runs.js",
14
15
  "aside.js",
15
16
  "context-timeline.js",
16
17
  "instructions.js",
@@ -232,14 +232,31 @@ export function createAutoCommit({
232
232
  // external-directory guard: a call that asks the sandbox for an escalation
233
233
  // (`sandbox_permissions`) while referencing paths outside the session
234
234
  // workspace is denied; escapes must go through ordinary approval.
235
- // doom-loop guard: the same tool with identical arguments more than twice in
236
- // a row within one turn is denied.
235
+ // doom-loop guard: the same tool with identical arguments DOOM_LOOP_LIMIT
236
+ // times in a row within one turn is denied. Waiting and polling (a job's
237
+ // output, a subagent, a background check) repeats a call on purpose and is
238
+ // never counted; the engine's repeat-tool reminder already nudges the model
239
+ // at 3, 5 and 8 repeats, so this is only the backstop for a real loop.
237
240
 
238
- export const DOOM_LOOP_LIMIT = 3;
241
+ /** Was 3, which refused the third identical `job_output({wait: true})` or an unchanged `git status` (owner 2026-11-17). */
242
+ export const DOOM_LOOP_LIMIT = 20;
239
243
 
240
- /** Whether `path` names a dotenv file (`.env`, `.env.*`, `*.env`). */
244
+ /** Tools whose whole job is to wait or poll: repeating them with the same arguments is progress, not a loop. */
245
+ const WAIT_TOOLS = new Set(['job_output', 'job_wait', 'wait_agent', 'wait', 'sleep', 'subagent_wait', 'session_wait']);
246
+
247
+ /** Whether a call waits on something (a wait tool, or any call that asks to `wait`/`block`). */
248
+ export function isWaitCall(name, args) {
249
+ if (WAIT_TOOLS.has(String(name ?? ''))) return true;
250
+ return args !== null && typeof args === 'object' && (args.wait === true || args.block === true);
251
+ }
252
+
253
+ /** Dotenv templates hold placeholders, never secrets: `.env.example`, `.env.sample`, `.env.template`, … */
254
+ const ENV_TEMPLATE = /^\.env\.(?:example|sample|template|dist|defaults|schema|tmpl|tpl)$|\.env\.(?:example|sample|template)$/iu;
255
+
256
+ /** Whether `path` names a dotenv file (`.env`, `.env.*`, `*.env`) that can hold secrets (templates excluded). */
241
257
  export function isEnvPath(path) {
242
258
  const base = basename(path);
259
+ if (ENV_TEMPLATE.test(base)) return false;
243
260
  return base === '.env' || base.startsWith('.env.') || base.endsWith('.env');
244
261
  }
245
262
 
@@ -312,7 +329,10 @@ export function createWave2Guards({
312
329
  };
313
330
  }
314
331
  }
315
- if (session !== undefined) {
332
+ if (session !== undefined && isWaitCall(exec?.name, args)) {
333
+ // A wait breaks no streak and starts none.
334
+ doomLoop.delete(session.id);
335
+ } else if (session !== undefined) {
316
336
  const signature = `${exec?.name}:${stableJson(args)}`;
317
337
  const entry = doomLoop.get(session.id);
318
338
  if (entry !== undefined && entry.signature === signature) {
@@ -320,7 +340,7 @@ export function createWave2Guards({
320
340
  if (entry.count >= doomLimit) {
321
341
  return {
322
342
  kind: 'deny',
323
- reason: `Picasso doom-loop guard: tool "${exec?.name}" was called with identical arguments ${entry.count} times in this turn; denied.`,
343
+ reason: `Picasso loop guard: tool "${exec?.name}" was called with identical arguments ${entry.count} times in a row in this turn, with nothing else in between; this call was not run. Change the arguments, try a different approach, or tell the user what is blocking you.`,
324
344
  };
325
345
  }
326
346
  } else {
@@ -89,7 +89,10 @@ function run(cmd, args) {
89
89
  }
90
90
 
91
91
  /** Read the stored key from the system keychain; `undefined` when there is none. */
92
- export async function readKeychainApiKey({ platform = process.platform, runner = run } = {}) {
92
+ export async function readKeychainApiKey({ platform = process.platform, runner } = {}) {
93
+ // Test-only hermetic mode (`PICASSO_TEST_HERMETIC=1`): no key in the login Keychain, unless a test passes a runner.
94
+ if (runner === undefined && process.env.PICASSO_TEST_HERMETIC?.trim() === '1') return undefined;
95
+ runner ??= run;
93
96
  if (platform === 'darwin') {
94
97
  const result = await runner('/usr/bin/security', ['find-generic-password', '-s', X_READER_KEYCHAIN_SERVICE, '-a', X_READER_KEYCHAIN_ACCOUNT, '-w']);
95
98
  const key = result.ok ? result.stdout.trim() : '';
@@ -322,26 +322,36 @@ const leafExcerpt = (leaf) => (leaf.length > SCAN_EXCERPT_MAX ? `${leaf.slice(0,
322
322
  * (objects and arrays recursed, cycles and depth > 24 pruned). Caps are generous — 256 leaves, 1 MiB of text —
323
323
  * and what fits is still scanned whole when the caps cut collection short.
324
324
  */
325
+ /**
326
+ * Argument keys whose string is the text of a file being written or edited, not a command or a path: a README that
327
+ * mentions `.env`, a script that documents `curl … | sh`, code that loads `credentials.json`. The built-in rules do
328
+ * not fire on these (owner 2026-11-17: ordinary edits were refused for naming a file); a rule the person added still
329
+ * scans everything, and the same text run as a command is still caught.
330
+ */
331
+ const CONTENT_KEYS = new Set(['content', 'contents', 'new_string', 'old_string', 'new_str', 'old_str', 'file_text', 'text', 'patch', 'diff', 'body', 'edits']);
332
+
333
+ /** String leaves to scan, each `{text, content}`; `content` marks text under a CONTENT_KEYS argument. */
325
334
  function collectScanLeaves(args, command) {
326
335
  const leaves = [];
327
336
  const budget = { bytes: SCAN_MAX_BYTES };
328
- const push = (value) => {
337
+ const push = (value, content) => {
329
338
  if (leaves.length >= SCAN_MAX_LEAVES || budget.bytes <= 0 || value === '') return;
330
339
  const piece = value.length > budget.bytes ? value.slice(0, budget.bytes) : value;
331
340
  budget.bytes -= piece.length;
332
- leaves.push(piece);
341
+ leaves.push({ text: piece, content });
333
342
  };
334
- if (typeof command === 'string') push(command);
343
+ if (typeof command === 'string') push(command, false);
335
344
  const seen = new Set();
336
- const walk = (value, depth) => {
345
+ const walk = (value, depth, content) => {
337
346
  if (depth > SCAN_MAX_DEPTH || leaves.length >= SCAN_MAX_LEAVES || budget.bytes <= 0) return;
338
- if (typeof value === 'string') return push(value);
347
+ if (typeof value === 'string') return push(value, content);
339
348
  if (!isRecord(value) && !Array.isArray(value)) return;
340
349
  if (seen.has(value)) return;
341
350
  seen.add(value);
342
- for (const item of Array.isArray(value) ? value : Object.values(value)) walk(item, depth + 1);
351
+ if (Array.isArray(value)) for (const item of value) walk(item, depth + 1, content);
352
+ else for (const [key, item] of Object.entries(value)) walk(item, depth + 1, content || CONTENT_KEYS.has(key));
343
353
  };
344
- walk(args, 0);
354
+ walk(args, 0, false);
345
355
  return leaves;
346
356
  }
347
357
 
@@ -464,8 +474,11 @@ export class ContentGuard {
464
474
  */
465
475
  scan(leaves, toolName) {
466
476
  for (const rule of this.policy) {
477
+ const builtin = this.ruleSources?.get(rule.id) === 'builtin';
467
478
  for (const leaf of leaves) {
468
- if (rule.regex.test(leaf)) return { rule: { id: rule.id, pattern: rule.pattern, description: rule.description }, leaf: leafExcerpt(leaf), toolName };
479
+ const text = typeof leaf === 'string' ? leaf : leaf.text;
480
+ if (builtin && typeof leaf !== 'string' && leaf.content) continue;
481
+ if (rule.regex.test(text)) return { rule: { id: rule.id, pattern: rule.pattern, description: rule.description }, leaf: leafExcerpt(text), toolName };
469
482
  }
470
483
  }
471
484
  return undefined;