@yasaswy.nagavolu/agents 0.24.0 → 0.26.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.
package/README.md CHANGED
@@ -73,6 +73,15 @@ agents-cli install
73
73
  secrets --list` — see [Secrets](#secrets) below.
74
74
  - `agents-cli update --yes` / `agents-cli update --bundle <key> --yes` — see
75
75
  [Updating](#updating) below.
76
+ - `agents-cli runner install --group-id <id> | --project-id <id>` — install a
77
+ ready GitLab CI runner on this machine (`linux-docker`, or `macos-shell` on
78
+ a Mac). `runner status` / `runner doctor` / `runner uninstall` check,
79
+ diagnose or remove it; `runner attach|detach --project-id <id>` enable the
80
+ saved runners on a project (`--no-cloud` also turns off cloud runners);
81
+ `runner init-project [--write] [--attach --project-id <id>]` writes a
82
+ `.gitlab-ci.yml`. Needs `GITLAB_RUNNER_PAT` (set it with `agents-cli
83
+ secrets`). Add `--json` for a machine-readable result that never contains a
84
+ token. Exit codes: 0 ok, 1 a step failed, 2 usage error.
76
85
  - `agents-cli --help` — show usage
77
86
 
78
87
  ### The interactive menu
package/bin/cli.js CHANGED
@@ -32,6 +32,7 @@ const { collectBundleSecrets, collectComponentSecrets, isResolved, promptForMiss
32
32
  const { envPath, readSecrets, removeSecret } = require('../lib/secretsStore');
33
33
  const { runSelfProfilePostInstall } = require('../lib/selfProfile');
34
34
  const { checkHealth, DoctorError } = require('../lib/doctor');
35
+ const { checkModVersions } = require('../lib/claudeVersion');
35
36
 
36
37
  const PACKAGE_ROOT = path.join(__dirname, '..');
37
38
  // One styler for the whole process: colors on only for a real TTY stdout
@@ -63,6 +64,7 @@ Usage:
63
64
  agents-cli secrets --bundle <key> Prompt for missing secrets for one bundle
64
65
  agents-cli secrets --list Show which secrets are set/missing (names only — never values)
65
66
  agents-cli doctor Report orphaned/missing/drifted files under the install target
67
+ agents-cli runner <sub> [flags] Install and manage a self-hosted GitLab CI runner (see "Flags for runner")
66
68
  agents-cli --help Show this help
67
69
 
68
70
  Flags for install:
@@ -133,6 +135,19 @@ Python is installed to wire it. Duplicate hook registrations that predate this C
133
135
  (or otherwise accumulate outside its per-block dedupe) are collapsed automatically on
134
136
  every install/update — see "doctor" below to inspect settings.json wiring separately.
135
137
 
138
+ Flags for runner:
139
+ runner install --group-id <id> | --project-id <id> Install a ready runner on this machine (idempotent)
140
+ runner status | doctor | uninstall Check, diagnose (docker, PAT scopes, online) or remove it
141
+ runner attach | detach --project-id <id> Enable/disable the saved runners on a project (--no-cloud on
142
+ attach also turns off cloud runners for it)
143
+ runner init-project [--profile node|python|docker|macos|blank] [--write] [--attach --project-id <id>]
144
+ Write a .gitlab-ci.yml that uses the shared templates (dry run unless --write)
145
+ --profile <auto|linux|macos> Install profile (default auto); --name, --tags, --concurrent, --url, --image,
146
+ --cache-volume, --protected, --run-untagged/--no-run-untagged, --dry-run
147
+ --json Print a machine-readable result (never contains a token or PAT)
148
+ Needs a GitLab PAT in GITLAB_RUNNER_PAT (or GITLAB_TOKEN): set it with "agents-cli secrets".
149
+ Exit codes: 0 ok, 1 a step failed, 2 usage error.
150
+
136
151
  Flags for doctor:
137
152
  --target-dir <path> Install target base, default ~/.claude (use for testing)
138
153
  --json Print a machine-readable report instead of prose
@@ -143,6 +158,8 @@ by a renamed/retired item), missing (a ledger-tracked file no longer on disk), a
143
158
  drifted (a ledger-tracked file whose on-disk hash no longer matches what was installed).
144
159
  It never scans anywhere the manifest doesn't declare a file/directory item into, so the
145
160
  rest of <target> (Claude Code's own state, caches, logs, your own files) is left alone.
161
+ It also compares the local "claude --version" with each installed mod's minClaudeCodeVersion:
162
+ a too-old Claude Code is a finding (exit 1); a missing claude binary only warns.
146
163
  Exit code is 0 when clean, 1 otherwise — safe to use as a CI/scripted gate. It never
147
164
  deletes or modifies anything; deciding what to do about a finding is a separate step.
148
165
  `);
@@ -378,12 +395,28 @@ function printFinalSummary({ installed, skipped, targetBase }) {
378
395
  console.log(` ${mark('skip')} ${label}`);
379
396
  }
380
397
  printPythonSyncIssues(installed.map(({ result }) => result));
398
+ printModVersionWarnings(installed.map(({ bundle }) => bundle.key), targetBase);
381
399
  console.log(
382
400
  `\nInstalled to ${ansi.bold(targetBase)}. Next: ${ansi.dim('agents-cli secrets')} to fill in any skipped ` +
383
401
  `secrets, ${ansi.dim('agents-cli update --yes')} to refresh later.`
384
402
  );
385
403
  }
386
404
 
405
+ /** Print one warning line per just-installed mod whose minClaudeCodeVersion the local Claude Code does not meet; never fails the run. */
406
+ function printModVersionWarnings(bundleKeys, targetBase) {
407
+ try {
408
+ const { manifest } = loadManifest(PACKAGE_ROOT);
409
+ const items = [...new Set(bundleKeys)].flatMap((key) => {
410
+ const bundle = findBundle(manifest, key);
411
+ return bundle ? bundle.items.filter((item) => item.kind === 'mod') : [];
412
+ });
413
+ const checks = checkModVersions({ items, targetBase: targetBase || defaultTargetBase() });
414
+ for (const c of checks) {
415
+ if (c.status === 'too-old') console.log(` ${mark('skip')} ${c.line}`);
416
+ }
417
+ } catch { /* advisory only — never fail an install or update */ }
418
+ }
419
+
387
420
  /**
388
421
  * A python item's missing-uv/failed status is easy to miss among per-bundle
389
422
  * component/hook bullets — surface it again as the last thing printed before
@@ -588,6 +621,7 @@ async function runInstall(argv) {
588
621
  });
589
622
  runSelfProfileStepsIfNeeded({ profile: args.profile, targetDir: args.targetDir });
590
623
  printPythonSyncIssues([result]);
624
+ printModVersionWarnings([args.bundle], result.targetBase);
591
625
  return 0;
592
626
  } catch (err) {
593
627
  if (err instanceof InstallError || err instanceof ManifestError || err instanceof LedgerError || err instanceof WiringError) {
@@ -1001,6 +1035,7 @@ async function runUpdate(argv) {
1001
1035
  }
1002
1036
 
1003
1037
  printPythonSyncIssues(result.bundles);
1038
+ printModVersionWarnings(result.bundles.map((b) => b.bundle), result.targetBase);
1004
1039
 
1005
1040
  if (result.exitCode !== 0) {
1006
1041
  console.error(
@@ -1060,8 +1095,15 @@ function runDoctor(argv) {
1060
1095
  return result.healthy ? 0 : 1;
1061
1096
  }
1062
1097
 
1098
+ const printModVersions = () => {
1099
+ if (result.modVersions.length === 0) return;
1100
+ console.log('\nClaude Code version vs. installed mods:');
1101
+ for (const c of result.modVersions) console.log(` ${c.line}`);
1102
+ };
1103
+
1063
1104
  if (result.healthy) {
1064
1105
  console.log(`${result.targetBase}: healthy — no orphans, no missing files, no drift.`);
1106
+ printModVersions();
1065
1107
  return 0;
1066
1108
  }
1067
1109
 
@@ -1078,6 +1120,7 @@ function runDoctor(argv) {
1078
1120
  console.log(`\nDrifted (on-disk hash no longer matches the ledger, ${result.drifted.length}):`);
1079
1121
  for (const d of result.drifted) console.log(` ${d.relTarget} (bundle: ${d.bundle})`);
1080
1122
  }
1123
+ printModVersions();
1081
1124
  return 1;
1082
1125
  } catch (err) {
1083
1126
  if (err instanceof DoctorError || err instanceof ManifestError || err instanceof LedgerError) {
@@ -1121,6 +1164,10 @@ async function main(argv) {
1121
1164
  return runDoctor(rest);
1122
1165
  }
1123
1166
 
1167
+ if (command === 'runner') {
1168
+ return require('../lib/runner').runRunnerCommand(rest);
1169
+ }
1170
+
1124
1171
  console.error(`Unknown command: ${command}`);
1125
1172
  printHelp();
1126
1173
  return 1;
@@ -540,6 +540,11 @@
540
540
  "path": "proxy/git_shell_parse.py",
541
541
  "kind": "hook",
542
542
  "note": "Shared shell-command parsing helpers imported by execution_worker_review_gate.py (without it that hook dies with ModuleNotFoundError on every Bash call) — not wired to an event itself. Also claimed by self-infra; safe to double-claim."
543
+ },
544
+ {
545
+ "path": "proxy/shell_parse.py",
546
+ "kind": "hook",
547
+ "note": "Generic parsing layer git_shell_parse.py imports from (task #73) — without it git_shell_parse.py dies with ModuleNotFoundError on every Bash call. Not wired to an event itself. Also claimed by self-infra; safe to double-claim."
543
548
  }
544
549
  ],
545
550
  "deps": [
@@ -782,6 +787,11 @@
782
787
  "kind": "infra",
783
788
  "note": "Registered PreToolUse Bash hook in settings.json, unscoped like publish_guard.py — blocks credential mutation/exposure for main session and every subagent."
784
789
  },
790
+ {
791
+ "path": "proxy/shell_parse.py",
792
+ "kind": "hook",
793
+ "note": "Shared, project-agnostic shell-command parsing helpers (task #73), imported by credential_mutation_guard.py for heredoc-body stripping — not wired to an event itself. Also claimed by agent-orchestration and self-infra; safe to double-claim."
794
+ },
785
795
  {
786
796
  "path": "proxy/headless_spawn_guard.py",
787
797
  "kind": "infra",
@@ -932,6 +942,11 @@
932
942
  "kind": "hook",
933
943
  "note": "Shared, project-agnostic shell-command parsing helpers (quote/heredoc/substitution-aware segment split, cd tracking, MSYS path normalization) — not wired to an event itself. Used by shared_worktree_revert_guard.py."
934
944
  },
945
+ {
946
+ "path": "proxy/shell_parse.py",
947
+ "kind": "hook",
948
+ "note": "Generic parsing layer git_shell_parse.py imports from (task #73), and imported directly by credential_mutation_guard.py for heredoc-body stripping — not wired to an event itself."
949
+ },
935
950
  {
936
951
  "path": "proxy/shared_worktree_revert_guard.py",
937
952
  "kind": "hook",
@@ -1305,6 +1320,11 @@
1305
1320
  "path": "proxy/git_shell_parse.py",
1306
1321
  "kind": "hook",
1307
1322
  "note": "Shared, project-agnostic shell-command parsing helpers (quote/heredoc/substitution-aware segment split) used by resolve_policy_guard.py to split Bash/PowerShell commands before scanning them — not wired to an event itself. Also claimed by agent-orchestration and self-infra; safe to double-claim."
1323
+ },
1324
+ {
1325
+ "path": "proxy/shell_parse.py",
1326
+ "kind": "hook",
1327
+ "note": "Generic parsing layer git_shell_parse.py imports from (task #73) — not wired to an event itself. Also claimed by self-infra; safe to double-claim."
1308
1328
  }
1309
1329
  ],
1310
1330
  "deps": [],
@@ -1336,6 +1356,27 @@
1336
1356
  ],
1337
1357
  "deps": [],
1338
1358
  "secrets": []
1359
+ },
1360
+ {
1361
+ "key": "runner",
1362
+ "title": "CI runner",
1363
+ "summary": "Thin ci-runner skill: set up GitLab CI on a self-hosted runner (linux-docker or macos-shell) with `npx @yasaswy.nagavolu/agents runner install`, write a .gitlab-ci.yml with `runner init-project`, and attach projects with `runner attach` so pipelines avoid cloud minutes",
1364
+ "profile": "public",
1365
+ "advanced": false,
1366
+ "items": [
1367
+ {
1368
+ "path": "skills/ci-runner",
1369
+ "kind": "skill"
1370
+ }
1371
+ ],
1372
+ "deps": [],
1373
+ "secrets": [
1374
+ {
1375
+ "name": "GITLAB_RUNNER_PAT",
1376
+ "prompt": "GitLab personal access token for installing runners (api scope, or create_runner + manage_runner) - optional, falls back to GITLAB_TOKEN",
1377
+ "validationHint": "starts with glpat-; optional, skip if you do not install runners"
1378
+ }
1379
+ ]
1339
1380
  }
1340
1381
  ],
1341
1382
  "internal": [
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "handoff",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "One-click session handoff: prepares the work, writes a lean handoff file, verifies it, clears the session and submits the handoff as the first message",
5
5
  "author": { "name": "Yasaswy Nagavolu" },
6
6
  "metadata": { "minClaudeCodeVersion": "2.1.287" }
@@ -60,7 +60,7 @@ an unattended session's prompt cache warm. Needs Claude Code 2.1.287 or later (m
60
60
 
61
61
  - On by default each session. `/keepwarm on|off|status`. No status-bar marker.
62
62
  - When the main chat is idle, no handoff runs, and the cache has 1 to 75 s left, the mod submits
63
- `prompts/keepwarm-nudge.md`. Max 6 in a row; a real user prompt resets the count.
63
+ `prompts/keepwarm-nudge.md`. Max 6 in a row; a real user prompt resets the count. Each submitted nudge toasts `Keep-warm nudge sent (N of 6)`.
64
64
  - A nudge is never sent while a user prompt waits for its turn to start, within 3 s of any turn end,
65
65
  or while the prompt box holds text (checked again right before the submit).
66
66
  - The nudge reply is the turn whose start text carries the nudge marker; its turn id is the only turn
@@ -210,6 +210,7 @@ const nudgeToolCount = ($) => tryOr($, 'nudge tool count', async () => toolUseCo
210
210
 
211
211
  async function sendNudge($, now) {
212
212
  state = onNudgeSent(state, now)
213
+ const sent = state.count
213
214
  try {
214
215
  const text = normalize(await $.fs.read($.plugin.root.replace(/\\/g, '/') + '/prompts/keepwarm-nudge.md')).trim()
215
216
  if (String((await $.prompt.read()).text || '').trim() !== '') {
@@ -218,6 +219,7 @@ async function sendNudge($, now) {
218
219
  }
219
220
  if (state.nudgeSentAt !== now) return
220
221
  await $.prompt.submit({ text })
222
+ $.ui.toast('Keep-warm nudge sent (' + sent + ' of ' + state.max + ')', { timeoutMs: TOAST_MS })
221
223
  } catch (err) {
222
224
  state = onNudgeFailed(state)
223
225
  $.ui.log('keepwarm nudge failed: ' + err, { to: 'debug' })
@@ -184,6 +184,46 @@ test('count rises per nudge and the cap pauses at six with a toast', async () =>
184
184
  assert.ok(h.toasts.some((t) => /nudge limit/.test(t)))
185
185
  })
186
186
 
187
+ test('each nudge toasts its count of the maximum once', async () => {
188
+ const h = await harness({ cache: FIVE_MIN })
189
+ await h.start()
190
+ await h.reply()
191
+ for (let i = 0; i < 3; i += 1) {
192
+ advance(h, 240 * 1000)
193
+ await h.tick()
194
+ await h.nudgeReply('Working.\nKEEPWARM_STATUS: working')
195
+ }
196
+ assert.deepEqual(h.toasts, ['Keep-warm nudge sent (1 of 6)', 'Keep-warm nudge sent (2 of 6)', 'Keep-warm nudge sent (3 of 6)'])
197
+ })
198
+
199
+ test('a failed nudge submit shows no sent toast', async () => {
200
+ const h = await harness({ cache: FIVE_MIN })
201
+ await h.start()
202
+ await h.reply()
203
+ h.$.prompt.submit = async () => {
204
+ throw new Error('submit refused')
205
+ }
206
+ advance(h, 240 * 1000)
207
+ await h.tick()
208
+ assert.deepEqual(h.toasts, [])
209
+ const status = await h.fire('command.run', { args: 'status' }, 'keepwarm')
210
+ assert.match(status.text, /nudges 0\/6/)
211
+ })
212
+
213
+ test('a nudge skipped for a draft shows no sent toast', async () => {
214
+ const h = await harness({ cache: FIVE_MIN })
215
+ await h.start()
216
+ await h.reply()
217
+ advance(h, 240 * 1000)
218
+ let reads = 0
219
+ h.$.prompt.read = async () => {
220
+ reads += 1
221
+ return { text: reads === 1 ? '' : 'started typing' }
222
+ }
223
+ await h.tick()
224
+ assert.deepEqual(h.toasts, [])
225
+ })
226
+
187
227
  async function nudgeOnce(h, reply, over = {}) {
188
228
  await h.start()
189
229
  await h.reply()
@@ -204,7 +244,7 @@ async function nudgeOnce(h, reply, over = {}) {
204
244
  test('idle reply with no tools and nothing running pauses silently', async () => {
205
245
  const h = await harness({ cache: FIVE_MIN })
206
246
  assert.equal(await nudgeOnce(h, 'Nothing left.\nKEEPWARM_STATUS: idle'), 1)
207
- assert.deepEqual(h.toasts, [])
247
+ assert.deepEqual(h.toasts, ['Keep-warm nudge sent (1 of 6)'])
208
248
  })
209
249
 
210
250
  test('blocked reply pauses with a toast', async () => {
@@ -218,6 +218,15 @@ import json
218
218
  import re
219
219
  import shlex
220
220
 
221
+ from shell_parse import (
222
+ binary_name,
223
+ is_shell_like_binary,
224
+ strip_command_timeout_prefix,
225
+ strip_heredoc_bodies,
226
+ strip_quotes,
227
+ unwind_shell_wrapper,
228
+ )
229
+
221
230
  _SHELL_OPERATORS = {"&&", "||", "|", "&", ";", "(", ")", "<", "<<", ">", ">>"}
222
231
 
223
232
  HTTP_TOOL = re.compile(r"\b(curl|wget|glab|Invoke-RestMethod|Invoke-WebRequest|iwr|irm)\b", re.I)
@@ -377,10 +386,14 @@ def _split_glued_punctuation(cmd: str) -> str:
377
386
 
378
387
  def _preprocess(cmd: str) -> str:
379
388
  """Shared normalization pipeline for both `_segments` and
380
- `_env_segments`: real-newline-to-`;` normalization, then glued-
381
- punctuation splitting, then the existing backslash-to-forward-slash
382
- pass — in that order, all quote-aware."""
383
- return _split_glued_punctuation(_normalize_newlines(cmd).replace("\\", "/"))
389
+ `_env_segments`: heredoc-body stripping (shared
390
+ `shell_parse.strip_heredoc_bodies` — an inert heredoc body is DATA,
391
+ e.g. prose in a `cat <<'EOF' >> docs/notes.md` write that merely
392
+ mentions a guarded filename, and must never be scanned as if it were
393
+ command text), then real-newline-to-`;` normalization, then
394
+ glued-punctuation splitting, then the existing backslash-to-forward-
395
+ slash pass — in that order, all quote-aware."""
396
+ return _split_glued_punctuation(_normalize_newlines(strip_heredoc_bodies(cmd)).replace("\\", "/"))
384
397
 
385
398
 
386
399
  def _segments(cmd: str) -> list[str] | None:
@@ -490,11 +503,78 @@ _EGRESS_TOOL = re.compile(
490
503
  _REDIRECT_OPERATORS = {"<", "<<", ">", ">>"}
491
504
 
492
505
 
493
- def _env_segments(cmd: str) -> list[tuple[str, bool]] | None:
506
+ _CODE_INTERPRETER_NAMES = {"python", "python3", "python2", "perl", "ruby", "node", "nodejs", "php"}
507
+
508
+
509
+ def _is_code_reader(name: str) -> bool:
510
+ """True for a binary whose stdin/argument is executed as code, not
511
+ read as data — a shell (`is_shell_like_binary`) or a common scripting
512
+ interpreter. Used both for wrapper-argument unwinding (`bash -c ...`)
513
+ and for the "piped into a shell" shape (`echo ... | bash`), where the
514
+ PRECEDING segment's own output becomes code the reader executes."""
515
+ return is_shell_like_binary(name) or name in _CODE_INTERPRETER_NAMES
516
+
517
+
518
+ def _wrapper_expanded_tokens(tokens: list[str]) -> list[str]:
519
+ """Returns extra candidate words hidden inside a code-taking wrapper's
520
+ payload argument, so the file-operand check (`_env_file_touch`) can
521
+ still find a guarded filename that only appears once that payload is
522
+ treated as the real (executed) shell text it is — `bash -c 'cat
523
+ .env'`, `eval "cat .env"`, `python3 -c "open('.env').read()"`, `cmd /c
524
+ type .env` are all covered by `shell_parse.unwind_shell_wrapper`;
525
+ `su -c`, `ssh <host> <cmd>`, and `watch <cmd>` are not wrappers that
526
+ module recognizes (they don't re-parse as shell syntax), so they get
527
+ their own narrow handling here. Every extra word is ADDED to the
528
+ caller's token list, never REMOVES a token — this only widens what
529
+ counts as a possible file-operand, it never narrows the existing
530
+ per-token check, so it cannot reintroduce a prose false positive on
531
+ its own (prose tokens still never enter this function's wrapper-name
532
+ branches)."""
533
+ extra: list[str] = []
534
+ kind, payload = unwind_shell_wrapper(tokens)
535
+ if kind in ("string", "text") and payload:
536
+ extra.extend(str(payload).split())
537
+ elif kind == "tokens" and payload:
538
+ extra.extend(payload)
539
+
540
+ probe = strip_command_timeout_prefix(tokens)
541
+ if not probe:
542
+ return extra
543
+ name = binary_name(probe[0])
544
+ rest = probe[1:]
545
+
546
+ if name == "su":
547
+ for i, t in enumerate(rest):
548
+ if strip_quotes(t) == "-c" and i + 1 < len(rest):
549
+ extra.extend(strip_quotes(rest[i + 1]).split())
550
+ break
551
+
552
+ elif name == "ssh":
553
+ positionals = [t for t in rest if not strip_quotes(t).startswith("-")]
554
+ if len(positionals) >= 2:
555
+ host_idx = rest.index(positionals[0])
556
+ for t in rest[host_idx + 1 :]:
557
+ extra.extend(strip_quotes(t).split())
558
+
559
+ elif name == "watch":
560
+ i = 0
561
+ while i < len(rest) and strip_quotes(rest[i]).startswith("-"):
562
+ i += 1
563
+ for t in rest[i:]:
564
+ extra.extend(strip_quotes(t).split())
565
+
566
+ return extra
567
+
568
+
569
+ def _env_segments(cmd: str) -> list[tuple[str, bool, list[str]]] | None:
494
570
  """Like _segments(), but additionally tags each segment with whether it
495
571
  sits inside a real `$(...)` command substitution that is ALSO actually
496
572
  captured (in_subst=True) — the capture-vs-emission distinction the .env
497
- checks need. A bare `(cmd)` grouping subshell (no leading `$`) still
573
+ checks need — and with the segment's own raw shlex token list (task
574
+ #73: the file-operand check must run against real tokens, never a
575
+ whitespace re-split of the joined text, which would destroy the fact
576
+ that a quoted multi-word argument was one token, not several). A bare
577
+ `(cmd)` grouping subshell (no leading `$`) still
498
578
  writes straight to real stdout, so it is NOT treated as captured; nor
499
579
  is a `$(...)` whose surrounding text isn't a capture context (see
500
580
  _is_capture_pending). in_subst is True only when EVERY enclosing paren
@@ -521,15 +601,40 @@ def _env_segments(cmd: str) -> list[tuple[str, bool]] | None:
521
601
  except ValueError:
522
602
  return None
523
603
 
524
- segments: list[tuple[str, bool]] = []
604
+ segments: list[tuple[str, bool, list[str]]] = []
525
605
  current: list[str] = []
526
606
  subst_stack: list[bool] = [] # one entry per open paren; True = genuinely-captured "$(" substitution
527
607
  prev_tok = ""
528
608
 
609
+ pending_piped_to_code = False
610
+
529
611
  def flush() -> None:
612
+ nonlocal pending_piped_to_code
530
613
  if current:
531
614
  captured = bool(subst_stack) and all(subst_stack)
532
- segments.append((" ".join(current), captured))
615
+ # `tokens` preserves each shlex token's own boundary —
616
+ # `_env_file_touch`'s file-operand check must never re-derive
617
+ # tokens by whitespace-splitting the joined `" ".join(current)`
618
+ # text, because that destroys the fact that a quoted multi-word
619
+ # argument (a grep pattern, an echo message, a `--note` value)
620
+ # was ONE token, not several — re-splitting it can turn an
621
+ # innocuous word inside that phrase (`... in .env, ...`) into
622
+ # what looks like its own bare file-operand token.
623
+ #
624
+ # Two shapes of hidden operand still need MORE than the raw
625
+ # token list, though: `bash -c 'cat .env'` etc. hide it inside
626
+ # one wrapper-argument token that IS real, executed shell
627
+ # syntax, not prose — added via `_wrapper_expanded_tokens`.
628
+ # `echo "cat .env" | bash` hides it in a segment whose own
629
+ # stdout becomes the NEXT segment's executed code — added when
630
+ # `pending_piped_to_code` is set by the `|` handling below,
631
+ # right before this flush.
632
+ expanded = list(current) + _wrapper_expanded_tokens(current)
633
+ if pending_piped_to_code:
634
+ for t in current:
635
+ expanded.extend(strip_quotes(t).split())
636
+ segments.append((" ".join(current), captured, expanded))
637
+ pending_piped_to_code = False
533
638
 
534
639
  def poison_top() -> None:
535
640
  if subst_stack:
@@ -562,6 +667,8 @@ def _env_segments(cmd: str) -> list[tuple[str, bool]] | None:
562
667
  nxt = tokens[idx + 1] if idx + 1 < n_tokens else ""
563
668
  if _EGRESS_TOOL.match(nxt):
564
669
  poison_top()
670
+ if _is_code_reader(binary_name(strip_quotes(nxt))):
671
+ pending_piped_to_code = True
565
672
  flush()
566
673
  current.clear()
567
674
  elif tok in _SHELL_OPERATORS:
@@ -695,9 +802,29 @@ _ENV_EXPOSURE_MSG = (
695
802
  )
696
803
 
697
804
 
698
- def _env_file_touch(seg: str, in_subst: bool, parsed: bool) -> str | None:
699
- tokens = seg.split()
700
- if not any(_is_env_credential_path(tok) for tok in tokens):
805
+ def _env_file_touch(seg: str, in_subst: bool, parsed: bool, tokens: list[str] | None) -> str | None:
806
+ # Task #73: `tokens` is the segment's OWN raw shlex token list (one
807
+ # entry per real shell argument, quotes already consumed by shlex) when
808
+ # available — never `seg.split()`, which re-splits the joined text on
809
+ # whitespace and can turn one word INSIDE a quoted multi-word argument
810
+ # (a grep pattern, an echo message, a `--note` value) into what looks
811
+ # like its own bare `.env` file-operand token. `tokens` is None only on
812
+ # the unparsed/fail-closed path (`parsed=False`), where the `seg.split()`
813
+ # fallback is fine because that path denies unconditionally anyway.
814
+ check_tokens = list(tokens) if tokens is not None else seg.split()
815
+ # A DOUBLE-QUOTED `$(...)` (`echo "$(cat .env)"`) is one shlex token —
816
+ # quoting hides the substitution from the `(`/`)` operator handling in
817
+ # `_env_segments`, so the whole `$(cat .env)` text survives as a single
818
+ # token instead of being walked into its own paren level. That token IS
819
+ # real shell syntax (a substitution, still executed), unlike a plain
820
+ # prose token — so it additionally gets word-split and re-checked, but
821
+ # ONLY when it actually contains `$(`/backtick syntax; an ordinary
822
+ # multi-word prose token (a grep pattern, an echo message, a `--note`
823
+ # value) never does, so it is never word-split and stays exempt.
824
+ for tok in list(check_tokens):
825
+ if "$(" in tok or "`" in tok:
826
+ check_tokens.extend(tok.split())
827
+ if not any(_is_env_credential_path(tok) for tok in check_tokens):
701
828
  return None
702
829
 
703
830
  if not parsed:
@@ -758,8 +885,17 @@ def _safe_main() -> None:
758
885
  if not cmd.strip():
759
886
  return
760
887
 
761
- # .env credential-literal write check — whole-command scan (see comment above).
762
- if ENV_REDIRECT_TARGET.search(cmd) and CRED_LITERAL.search(cmd):
888
+ # .env credential-literal write check — whole-command scan (see comment
889
+ # above). ENV_REDIRECT_TARGET runs on the heredoc-body-stripped text: a
890
+ # heredoc write whose PROSE merely mentions a redirect-looking ".env"
891
+ # string must never trip this on its own. CRED_LITERAL runs on the
892
+ # RAW, unstripped `cmd`: the redirect target match already proves a
893
+ # real `.env`-shaped write exists in the
894
+ # command, so the literal-shape check must not depend on
895
+ # `strip_heredoc_bodies` also being correct for this exact command —
896
+ # any literal actually present in `cmd` is real regardless of what
897
+ # heredoc handling did or didn't do to a copy of the text.
898
+ if ENV_REDIRECT_TARGET.search(strip_heredoc_bodies(cmd)) and CRED_LITERAL.search(cmd):
763
899
  _deny(
764
900
  "Blocked by code-is-law (credential-mutation-guard). This command writes a "
765
901
  "live-looking credential literal into a .env-shaped file. Credentials must "
@@ -785,10 +921,10 @@ def _safe_main() -> None:
785
921
  # segment, never granted the substitution exemption.
786
922
  env_segments = _env_segments(cmd)
787
923
  env_parsed = env_segments is not None
788
- env_seg_texts = env_segments if env_parsed else [(cmd, False)]
924
+ env_seg_texts = env_segments if env_parsed else [(cmd, False, None)]
789
925
 
790
- for seg, in_subst in env_seg_texts:
791
- reason = _env_file_touch(seg, in_subst, env_parsed)
926
+ for seg, in_subst, seg_tokens in env_seg_texts:
927
+ reason = _env_file_touch(seg, in_subst, env_parsed, seg_tokens)
792
928
  if reason:
793
929
  _deny(reason)
794
930
  return