repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi: clarify Linux boundaries and harden Nu and Mise diagnostics

724b6c4f6ccf3f76c7b8c65e57360ba358b2b596

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (17)

pi/agent/skills/archlinux/SKILL.md

Modified
64 64 ## Root Delegation
66 -Do not run root/admin mutations yourself unless user explicitly authorizes.
66 +Do not run root/admin mutations yourself.
67 +Follow [linux](../linux/SKILL.md) for system boundaries and human-run escalation, even when the user authorizes the change.
67 68 Give exact command for user to run.
68 69 Detect user's shell first for syntax compatibility:

pi/agent/skills/archlinux/scripts/archlinux-doc.test.mjs

Modified
44 44 test("root mutation guidance delegates instead of auto-running", () => {
45 - assert.match(all, /Do not run root\/admin mutations yourself/);
45 + assert.match(all, /Do not run root\/admin mutations yourself\./);
46 + assert.match(all, /\.\.\/linux\/SKILL\.md/);
46 47 assert.match(all, /sudoedit \/etc\/file/);

pi/agent/skills/linux-console/SKILL.md

Modified
25 25 ## First Probe
27 -Run before advice/changes:
27 +Identify the target host and VT from the user's report before probing.
28 +The agent's stdin and `TERM` describe its execution context, not necessarily the target console.
30 +Run these in the target session, or ask the user for their output there:
29 32 ```sh
31 -echo "$TERM"
32 -infocmp -1 "${TERM:-linux}"
34 +printf '%s\n' "$TERM"
35 37 Interpret:
37 -- `/dev/ttyN` + `TERM=linux` → real VT likely.
38 -- `/dev/pts/N` → terminal emulator/pty; stop unless user asks docs only.
39 -- Missing local man page → fetch current upstream man page.
39 +- Target `/dev/ttyN` + `TERM=linux` → real VT likely.
40 +- Agent `/dev/pts/N` or `not a tty` → target remains unknown; do not reject VT diagnosis.
41 +- Target `/dev/pts/N` → pty; clarify whether a separate VT is the actual target.
42 +- User reports `tty1`/`tty2` on another session/host → continue target-specific read-only diagnosis.
44 +Use `infocmp -1 linux` to inspect console capabilities; it does not detect the target.
45 +Do not send console escape sequences to the agent's terminal as a substitute for the target.
46 +Missing local man page → fetch current upstream man page.
41 48 ## Learn Locally First

pi/agent/skills/linux-console/references/model.md

Modified
16 16 ## Detection
18 -Strong signal:
18 +Evaluate the target session, not the agent's execution context.
19 +Strong signal from the target:
20 21 ```text
21 22 /dev/ttyN + TERM=linux
24 -Weak/negative signal:
26 -```text
27 -/dev/pts/N
28 -```
25 +`/dev/pts/N` identifies the probed session as a pty, not the user's separate VT.
26 +Agent output of `/dev/pts/N` or `not a tty` leaves the target unknown.
27 +Confirm the target host and VT; continue remote diagnosis rather than stopping.
30 29 Use exact user wording too:
31 30 `tty1`, `tty2`, `virtual console`, `linux console`, `Ctrl+Alt+F1`, `getty`,

pi/agent/skills/linux-console/references/research.md

Modified
1 1 # Research Pattern
3 -Local first:
3 +Identify the target host and VT first.
4 +Run session probes in that target session, or ask the user to run them there:
5 6 ```sh
7 -echo "$TERM"
8 -infocmp -1 "${TERM:-linux}"
8 +printf '%s\n' "$TERM"
11 +The agent's pty or missing tty does not rule out a separate target VT.
12 +Inspect capabilities with `infocmp -1 linux`; terminfo lookup is not target detection.
13 +Run device probes below only on the target host.
11 15 Man pages:
13 17 ```sh

pi/agent/skills/linux-userland/SKILL.md

Modified
94 94 ## Safe Edit Pattern
96 +For an existing regular config file, resolve symlinks first and confirm the target is inside the authorized user-owned boundary.
97 +Edit and restore the resolved target, leaving the original symlink intact.
98 +A `cp -a` backup of a symlink copies only the link, not a content snapshot.
96 100 ```bash
97 -file=/path/to/file
98 -backup="$file.bak.$(date +%Y%m%d-%H%M%S)"
99 -cp -a "$file" "$backup"
101 +file=$(realpath -e -- /path/to/file) || exit 1
102 +[ -f "$file" ] || exit 1
103 +backup=$(mktemp -- "$file.bak.XXXXXX") || exit 1
104 +cp -p -- "$file" "$backup" || exit 1
100 105 # edit "$file"
101 106 # run validator/reload
102 -# rollback if bad: cp -a "$backup" "$file"
107 +# rollback if bad: cp -p -- "$backup" "$file"
110 +Stop on resolution or backup failure; do not create a missing symlink target implicitly.
105 112 Validation examples:
107 114 - systemd user unit: `systemd-analyze --user verify FILE`

pi/agent/skills/linux-userland/package.json

Added
new file mode 100644
1 +{
2 + "name": "linux-userland-skill",
3 + "private": true,
4 + "type": "module",
5 + "scripts": {
6 + "test": "node --test scripts/*.test.mjs"
7 + }
8 +}

pi/agent/skills/linux-userland/scripts/backup.test.mjs

Added
new file mode 100644
1 +import assert from "node:assert/strict";
2 +import { spawnSync } from "node:child_process";
3 +import { lstatSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
4 +import { tmpdir } from "node:os";
5 +import { join } from "node:path";
6 +import { test } from "node:test";
8 +const doc = readFileSync(new URL("../SKILL.md", import.meta.url), "utf8");
9 +const snippet = doc.match(/## Safe Edit Pattern[\s\S]*?```bash\n([\s\S]*?)```/)[1];
11 +for (const symlink of [false, true]) {
12 + test(`backup and rollback preserve ${symlink ? "symlinked" : "regular"} config`, { skip: process.platform !== "linux" }, () => {
13 + const dir = mkdtempSync(join(tmpdir(), "linux-userland-backup-"));
14 + try {
15 + const target = join(dir, "config target");
16 + const file = symlink ? join(dir, "config link") : target;
17 + writeFileSync(target, "original\n");
18 + if (symlink) symlinkSync(target, file);
19 + const script = snippet
20 + .replace("/path/to/file", '"$CONFIG_FILE"')
21 + .replace('# edit "$file"', 'printf "changed\\n" > "$file"')
22 + .replace("# run validator/reload", 'test "$(cat "$backup")" = original || exit 1')
23 + .replace("# rollback if bad: ", "");
24 + const result = spawnSync("sh", ["-eu", "-c", script], {
25 + env: { ...process.env, CONFIG_FILE: file },
26 + encoding: "utf8",
27 + });
28 + assert.equal(result.status, 0, result.stderr);
29 + assert.equal(readFileSync(target, "utf8"), "original\n");
30 + assert.equal(lstatSync(file).isSymbolicLink(), symlink);
31 + const backups = readdirSync(dir).filter((name) => name.includes(".bak."));
32 + assert.equal(backups.length, 1);
33 + assert.ok(lstatSync(join(dir, backups[0])).isFile());
34 + } finally {
35 + rmSync(dir, { recursive: true, force: true });
36 + }
37 + });
40 +for (const kind of ["missing", "dangling symlink", "directory"]) {
41 + test(`refuse ${kind} without creating a backup`, { skip: process.platform !== "linux" }, () => {
42 + const dir = mkdtempSync(join(tmpdir(), "linux-userland-backup-"));
43 + try {
44 + const file = kind === "directory" ? dir : join(dir, "config");
45 + if (kind === "dangling symlink") symlinkSync(join(dir, "missing"), file);
46 + const before = readdirSync(dir);
47 + const result = spawnSync("sh", ["-eu", "-c", snippet.replace("/path/to/file", '"$CONFIG_FILE"')], {
48 + env: { ...process.env, CONFIG_FILE: file },
49 + encoding: "utf8",
50 + });
51 + assert.equal(result.status, 1, result.stderr);
52 + assert.deepEqual(readdirSync(dir), before);
53 + } finally {
54 + rmSync(dir, { recursive: true, force: true });
55 + }
56 + });

pi/agent/skills/linux/SKILL.md

Modified
12 12 ## Non-Negotiables
14 -- No `sudo`, `su`, `doas`, `pkexec`, package manager install/remove, service mutation, `/etc` edits, kernel/sysctl changes, or device writes from the agent.
14 +- No `sudo`, `su`, `doas`, `pkexec`, package manager install/remove, system-service mutation, `/etc` edits, kernel/sysctl changes, or device writes from the agent.
15 +- User-service changes follow [linux-userland](../linux-userland/SKILL.md); the system-service ban does not cover them.
15 16 - Read-only probes first. Prefer commands with `--no-pager`, `--full`, bounded output, and explicit units/time ranges.
16 17 - Prefer installed truth: `man`, `--help`, distro files. Web docs may not match host version.
17 18 - Redact secrets from env, tokens, key files, URLs, logs, and command output.

pi/agent/skills/mise/SKILL.md

Modified
2 2 name: mise
3 -description: "Use when editing/diagnosing mise: mise.toml, tools, env vars, tasks, activation, shims, trust, or backends."
3 +description: "Use when editing Mise config or diagnosing config discovery, activation, shims, trust, installs, or backends. Not for running documented repository tasks."
6 6 # Mise
8 8 Mise declares project tools, env, and tasks in TOML.
9 +For ordinary task execution, follow repo instructions without loading this skill.
10 11 ## Model
18 19 ## Workflow
20 -1. Read config and repo conventions.
21 -2. Ask local CLI first: `mise --help`, `mise <cmd> --help`, `mise doctor`, `mise config ls`, `mise env`, `mise ls`, `mise tasks ls`.
21 +1. Read repo conventions and inspect config directives without exposing secret values.
22 + Distinguish the agent's tool shell from the user's interactive shell and the configured task shell.
23 +2. Ask local CLI help first: `mise --help`, `mise <cmd> --help`.
24 + Use `--no-config` for config-free probes; these cannot establish project-effective state.
25 + After inspecting config effects and trust, select the relevant `doctor`, `config ls`, `ls`, or `tasks` diagnostic.
22 26 3. Fetch/cite docs for exact syntax, installs, backends, flags, or changed behavior.
23 -4. Probes: prefer `--no-config`; if loading config isolate `MISE_DATA_DIR`/`MISE_CACHE_DIR` and combine `MISE_AUTO_INSTALL=0`, `--dry-run`, `status`, `--path`/`--local`, `--skip-tools --no-deps`.
24 -5. Treat `use`, `settings`, aliases, bootstrap, dotfiles, prune/uninstall/implode as mutating unless dry-run/local.
25 -6. Make the smallest style-matching change; never print secrets from env files or `mise env`.
27 +4. Inspect task structure with `mise tasks ls`, `mise tasks info <task>`, and `mise tasks validate`.
28 + `mise run --dry-run <task>` previews execution, not a sandbox; config evaluation and output still need review.
29 + `MISE_AUTO_INSTALL=0`, `--skip-tools`, and `--no-deps` do not make task execution read-only.
30 + Isolate `MISE_DATA_DIR`/`MISE_CACHE_DIR` for temporary probes; local paths do not prevent other side effects.
31 +5. For activation warnings, identify all loaded activation files and their generators before editing.
32 + Fix the owning generator or confirmed duplicate, not the generated symptom; use `nushell` for `.nu` syntax and `linux-userland` for Linux HOME/XDG boundaries.
33 +6. Treat config writes, installs/removals, activation-file writes, bootstrap, and cleanup as mutations even with local scope.
34 + Make the smallest authorized change, validate config/task structure, and verify affected behavior.
36 +## Environment safety
38 +- Never dump `mise env`, `mise env --json`, dotenv files, or the full environment.
39 +- Inspect only named variables needed for diagnosis; redact before tool output reaches the transcript.
40 + Prefer presence, equality, or resolution checks over values; names alone do not make values safe.
27 42 ## Trust
34 49 ## More
36 -- Sources: `references/sources.md`.
37 -- Verified shape: `examples/patterns.md`.
51 +- [Sources](references/sources.md).
52 +- [Examples](examples/patterns.md).

pi/agent/skills/mise/examples/patterns.md

Modified
1 1 # Mise Examples
3 -Verified shape; choose real tools/versions from local help/docs. Inspect/trust first. For structure-only checks use `MISE_AUTO_INSTALL=0` and task flags `--skip-tools --no-deps`.
3 +Minimal shape; choose real tools/versions from local help/docs.
4 +Inspect config effects and trust before loading it; ask before trusting real config.
5 6 ```toml
6 7 [env]
12 13 run = "echo check-ok"
15 -Checks:
16 +Structure checks after config inspection:
17 18 ```sh
18 -mise env --json
19 19 mise tasks ls
20 -mise run --skip-tools --no-deps check
20 +mise tasks info check
21 +mise tasks validate
24 +Execution preview: `mise run --dry-run check`.
25 +Review config evaluation and possible sensitive output first; dry-run is not a sandbox.
26 +`--skip-tools --no-deps` alone still executes the task.
27 +Inspect only needed env variables, redacting values before output; never dump `mise env --json`.
23 29 Local-only values belong in local config:
25 31 ```toml

pi/agent/skills/mise/references/sources.md

Modified
2 2 # Mise Sources
4 4 Use in order:
6 -1. Installed CLI: `mise --help`, `mise <cmd> --help`, `mise doctor`, `mise config ls`, `mise env`, `mise ls`, `mise tasks ls`.
6 +1. Installed CLI: `mise --help`, `mise <cmd> --help`.
7 + After inspecting config effects and trust, choose `mise doctor`, `mise config ls`, `mise ls`, or `mise tasks` diagnostics.
8 + Never dump environment values; see [environment safety](../SKILL.md#environment-safety).
7 9 2. LLM docs if present: <https://mise.en.dev/llms.txt>, <https://mise.en.dev/llms-full.txt>.
8 10 3. Official docs: <https://mise.en.dev/>, <https://mise.en.dev/cli/>, <https://mise.en.dev/configuration.html>, <https://mise.en.dev/schema/mise.json>.
9 11 4. Source when docs/behavior disagree: <https://github.com/jdx/mise>.

pi/agent/skills/nushell/SKILL.md

Modified
2 2 name: nushell
3 -description: "Nushell shell and scripting — structured pipelines, current syntax, config, modules, redirection, errors, and Bash-to-Nu translation. Use when editing .nu files or converting shell snippets."
3 +description: "Use when writing, debugging, or modernizing Nu code/config, editing .nu files, or translating shell commands to Nushell. Not generic Bash or terminal work."
4 4 license: MIT
7 7 # Nushell
9 -Target the installed Nu, not this file. Nu changes quickly.
9 +Target installed Nu, not remembered syntax.
10 +Keep language guidance here; use `mise` for Mise integration
11 +and `linux-userland` for Linux HOME/XDG boundaries.
11 -## Source of truth
13 +## Discover
13 -Use local structured help first:
15 +Use `nu --no-config-file -c '<probe>'` for isolated language checks.
16 +This skips startup config, not inherited env or side effects in the probe.
17 +Never dump `$env`, source secret files,
18 +or run real login startup merely to check syntax.
15 20 ```nushell
16 -version | get version
21 +version | select version experimental_options
17 22 help commands | where name == "path type" | get input_output
18 -help commands | where name =~ "^str " | select name usage
19 23 help --find semver | select name usage
20 24 help <command>
23 -If behavior is version-specific, check official release notes after local help:
25 -```text
26 -https://www.nushell.sh/blog/
27 -https://www.nushell.sh/book/
28 -```
30 -Recent changelog check performed while refactoring: 0.114.0, 0.113.1, 0.113.0, 0.112.2. Result: keep current-feature details out of this skill; point to `help`/release notes instead.
32 -## Core model
34 -- Pipelines pass values: strings, records, lists, tables; not shell text lines.
35 -- Env vars live in `$env`: `$env.PATH`, `$env.LAST_EXIT_CODE`, `$env.config`.
36 -- Optional record/env fields use `?`: `$env.PWD?`, `$row.name?`.
37 -- `null` is `nothing`; path/file commands often reject it. Guard before calling.
38 -- External commands use `^cmd`; pass spread args as `^cmd ...$args`.
39 -- `help commands` is data; prefer filtering it over scraping docs.
41 -## Bash → Nu instincts
43 -- `$VAR` → `$env.VAR`
44 -- `export A=b` → `$env.A = "b"`
45 -- `$?` → `$env.LAST_EXIT_CODE`
46 -- `$(cmd)` → `(cmd)`
47 -- `cat file` → `open --raw file`
48 -- `grep x` on text → `lines | where $it =~ "x"`
49 -- `find . -name '*.nu'` → `ls **/*.nu`
50 -- `[ -f file ]` → `("file" | path type) == file`
51 -- `basename "$p"` → `$p | path basename`
52 -- `2>&1` for external commands → `o+e>|`
54 -No shell `&&`/`||`. Use `;` for sequencing, `and`/`or` for booleans, or inspect `$env.LAST_EXIT_CODE`.
56 -## Common traps
58 -`which` returns a table of records, not a string. Extract the `path` field before passing it to external commands:
27 +For deprecated syntax, inspect command metadata when available:
60 29 ```nushell
61 -let pi_path = (which pi | get 0.path)
62 -^readlink $pi_path
30 +scope commands | where name == "str upcase" | get deprecation_info
65 -For nullable paths:
33 +For migrations, follow [Modernize](references/modernize.md):
34 +local help, intervening release notes, then isolated behavior checks.
35 +Do not copy website examples without checking the installed CLI.
37 +## Code
39 +- Pipelines carry typed values; external programs exchange byte streams.
40 +- Use `$env.NAME` for environment variables and `$row.field?` for optional fields.
41 + `null` has type `nothing`; guard before passing optional paths to filesystem commands.
42 +- `which` returns records, possibly none;
43 + check emptiness before extracting `get 0.path`.
44 +- Use `^cmd` to bypass internal commands; pass argument lists as `^cmd ...$args`.
45 +- Use `and`/`or` for booleans, not `&&`/`||`.
46 + `;` sequences expressions, not conditional success;
47 + external failures can stop execution.
48 +- Use `save` for pipeline values, `o+e> file` for external output to a file,
49 + and `o+e>| filter` for combined output into a pipeline.
50 + Do not put a filename after `o+e>|`.
52 +## External failures
54 +Capture output and status together instead of assuming
55 +`$env.LAST_EXIT_CODE` behaves like Bash `$?` in every context:
67 57 ```nushell
68 -let q = [$p] | compact | first
69 -let t = if $q == null { null } else { try { $q | path type } catch { null } }
58 +let result = (^tool ...$args | complete)
59 +if $result.exit_code != 0 {
60 + error make {msg: $"tool exited ($result.exit_code)"}
62 +let data = try { $result.stdout | from json --strict } catch {
63 + error make {msg: "tool returned invalid JSON"}
72 -Redirection applies to external commands, not Nu internals:
67 +Use `from json --strict` when the external contract requires JSON;
68 +the default parser accepts non-JSON input too.
69 +Distinguish process failure, malformed data, and valid empty results.
70 +Do not replace failures with `null`, `[]`, or success
71 +unless the caller explicitly permits that fallback.
72 +Do not expose raw stderr or output that may contain secrets.
74 -```nushell
75 -"hello" | save out.txt
76 -"hello" | save --append out.txt
77 -^cmd e>| ignore
78 -^cmd o+e>| log.txt
79 -try { internal-command } catch {|err| $err.msg }
74 +## Config and scripts
76 +1. Identify the actual shell and launch mode:
77 + command string, script, interactive, or login.
78 + Use `$nu | columns`, then inspect only needed config paths,
79 + including `loginshell-path`, `vendor-autoload-dirs`, and `user-autoload-dirs`.
80 +2. Trace loaded files and their generators before editing activation warnings.
81 + Fix the owner or confirmed duplicate; do not patch generated output blindly.
82 +3. `source`, `use`, `run`, and `nu script.nu` are not interchangeable.
83 + Check local help for scope, pipeline input, `main` arguments,
84 + and top-level execution before switching invocation.
85 +4. Treat `$ans` as REPL state, not a script result store.
86 + Check local help before using version-specific argument annotations such as `external_arg`.
87 +5. Preserve typed signatures and error paths;
88 + reproduce type failures before blaming a release
89 + or disabling experimental checks.
91 +## Verify
93 +Read the target and its imports first; diagnostics may expose source literals.
94 +For reviewed, non-secret code, run the helper from this skill directory:
96 +```sh
97 +node scripts/check.mjs /absolute/path/to/file.nu
82 -## Verify snippets
100 +It runs `nu --no-config-file --ide-check 100`, reports Nu version and diagnostics,
101 +and fails on Error severity even when Nu exits zero.
102 +It does not run the script body; parsing can read imports and evaluate constants,
103 +so this is not a sandbox.
104 +Missing Nu, process failure, stderr, or malformed diagnostics fail closed.
105 +Warnings are reported when emitted, but a pass does not prove absence
106 +of deprecations; Nu 0.115.1 IDE mode omits some.
84 -Before giving version-sensitive Nu syntax, run a tiny `nu -c` probe when harmless:
108 +Then exercise positive and negative behavior with reviewed code
109 +in isolated temporary fixtures.
110 +Check exit codes, data shape, empty/missing inputs, and intended startup mode separately.
111 +Never execute a mutating script just to validate it.
86 -```nushell
87 -nu -c 'version | get version'
88 -nu -c 'help commands | where name == "path type" | length'
89 -nu -c '(which nu | get 0.path) | path type'
90 -```
113 +Helper regression tests: `npm test` in this skill directory;
114 +requires Node and Nu on PATH.

pi/agent/skills/nushell/package.json

Added
new file mode 100644
1 +{
2 + "name": "nushell-skill",
3 + "private": true,
4 + "type": "module",
5 + "scripts": {
6 + "test": "node --test scripts/check.test.mjs"
7 + }
8 +}

pi/agent/skills/nushell/references/modernize.md

Added
new file mode 100644
1 +# Modernize Nu
3 +Audit the requested code/config scope, not the whole machine.
4 +Review requests are read-only; obtain approval before implementing findings.
6 +## Procedure
8 +1. Record `nu --version`, build features and `experimental_options` from `version`.
9 + Compare the installed release with the last reviewed release;
10 + do not assume online docs match it.
11 +2. Read intervening [release notes](https://www.nushell.sh/blog/) and affected command help.
12 + Use the [book](https://www.nushell.sh/book/) for concepts;
13 + resolve conflicts with local probes or release-tagged source.
14 +3. Query `scope commands` for relevant `deprecation_info` when supported.
15 + Match command and flag metadata against actual code,
16 + not comments or generated text templates.
17 + Removed commands may no longer appear; check release notes too.
18 +4. Resolve imports, generators, and launch mode before diagnosing startup changes.
19 + Use `$nu` paths instead of hard-coded Linux paths.
20 + Keep secrets and real login side effects out of probes.
21 +5. Run [the checker](../scripts/check.mjs) on reviewed, non-secret files.
22 + Treat its `ok` as a static diagnostic result only,
23 + not proof of runtime correctness or freedom from deprecations.
24 +6. For every proposed migration, test old and replacement shapes
25 + against the same tiny fixtures.
26 + Include success, deliberate failure, missing/empty input, and output types.
27 + Record version, experimental options, commands, and results;
28 + delete temporary fixtures afterward.
29 +7. Report confirmed migration, unchanged behavior,
30 + or unresolved discrepancy with evidence.
31 + Separate source defects, upstream bugs, expected failures, and harness limitations.
32 + Do not install upgrades, disable type checks, or rewrite unrelated config automatically.
34 +## Reviewed checkpoint
36 +Nu 0.115.1 on Linux; also reviewed intervening 0.114.1 and 0.115.0 notes.
37 +This is an audit baseline, not a minimum supported version
38 +or a reason to load a feature catalogue.
40 +- [0.114.1](https://www.nushell.sh/blog/2026-07-11-nushell_v0_114_1.html):
41 + runtime annotation fixes; reproduce type mismatches before changing signatures.
42 +- [0.115.0](https://www.nushell.sh/blog/2026-08-15-nushell_v0_115_0.html):
43 + structured deprecation metadata; YAML/KDL semantics;
44 + reserved `$ans`; script arguments and scope changes.
45 +- [0.115.1](https://www.nushell.sh/blog/2026-08-23-nushell_v0_115_1.html):
46 + semver boolean comparisons, completion behavior, and keybinding merging fixes.
48 +Only investigate a change when the requested scope uses the affected feature.
49 +A newer feature is not automatically a better replacement.
51 +## Verified traps
53 +- On 0.115.1, `--ide-check` can emit Error diagnostics and exit zero.
54 + The helper parses diagnostics; a raw exit-code gate is insufficient.
55 +- The same IDE mode can omit `str upcase` deprecation warnings
56 + that normal execution emits.
57 + Use deprecation metadata and reviewed isolated runtime probes
58 + as independent checks.
59 +- On 0.115.1, `"not json" | from json` succeeds as a string.
60 + Use `--strict` when validating an external JSON contract.
61 +- `complete` captures external `stdout`, `stderr`, and `exit_code` in one record.
62 + A later `$env.LAST_EXIT_CODE` lookup is not a reliable substitute
63 + across pipelines and failure modes.
64 +- [File and pipe redirection][redirection] differ:
65 + `o+e> file` versus `o+e>| filter`.
66 +- [Startup configuration](https://www.nushell.sh/book/configuration.html) depends on flags and mode.
67 + A config-free syntax pass does not validate interactive/login wiring.
68 +- Use `help run`, `help source`, and `help use`
69 + before changing [script](https://www.nushell.sh/book/scripts.html) invocation.
70 + Probe pipeline input, top-level statements and `main` argument binding
71 + instead of assuming equivalence.
73 +[redirection]: https://www.nushell.sh/book/stdout_stderr_exit_codes.html

pi/agent/skills/nushell/scripts/check.mjs

Added
new file mode 100644
1 +#!/usr/bin/env node
2 +import { spawnSync } from "node:child_process";
3 +import { statSync } from "node:fs";
4 +import { dirname, resolve } from "node:path";
5 +import { fileURLToPath } from "node:url";
7 +// IDE diagnostics may contain source literals. Only check reviewed, non-secret inputs.
8 +export function checkFile(file, run = spawnSync) {
9 + const report = { file: resolve(file), version: null, ok: false, diagnostics: [] };
10 + try {
11 + if (!statSync(report.file).isFile()) throw new Error("Target must be a regular file");
12 + const options = {
13 + cwd: dirname(report.file), encoding: "utf8", shell: false,
14 + timeout: 30_000, maxBuffer: 1_048_576, windowsHide: true,
15 + };
16 + function invoke(args) {
17 + const process = run("nu", ["--no-config-file", ...args], options);
18 + if (process.error || process.status !== 0 || process.signal) {
19 + // Do not echo stderr or spawn errors: either can contain sensitive data.
20 + throw new Error("Nu failed, was unavailable, or exceeded time/output limits");
21 + }
22 + if (process.stderr?.trim()) throw new Error("Nu emitted stderr; validation is incomplete");
23 + return process.stdout;
24 + }
26 + const version = invoke(["--version"]).trim();
27 + if (!/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(version)) {
28 + throw new Error("Unrecognized Nu version output");
29 + }
30 + report.version = version;
31 + const output = invoke(["--ide-check", "100", report.file]);
32 + for (const line of output.split(/\r?\n/).filter((line) => line.trim())) {
33 + let entry;
34 + try { entry = JSON.parse(line); }
35 + catch { throw new Error("Malformed Nu diagnostic JSON"); }
36 + if (entry?.type !== "diagnostic" || typeof entry.message !== "string"
37 + || !["Error", "Warning", "Information", "Hint"].includes(entry.severity)) {
38 + throw new Error("Unsupported Nu diagnostic output");
39 + }
40 + report.diagnostics.push(entry);
41 + }
42 + report.ok = !report.diagnostics.some((entry) => entry.severity === "Error");
43 + } catch (error) {
44 + report.error = error.code ? "Cannot inspect target file" : error.message;
45 + }
46 + return report;
49 +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
50 + const args = process.argv.slice(2);
51 + const report = args.length === 1
52 + ? checkFile(args[0])
53 + : { ok: false, error: "Usage: node check.mjs <file.nu>" };
54 + console.log(JSON.stringify(report, null, 2));
55 + process.exitCode = args.length !== 1 ? 2 : report.ok ? 0 : 1;

pi/agent/skills/nushell/scripts/check.test.mjs

Added
new file mode 100644
1 +import assert from "node:assert/strict";
2 +import { spawnSync } from "node:child_process";
3 +import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
4 +import { tmpdir } from "node:os";
5 +import { dirname, join } from "node:path";
6 +import { fileURLToPath } from "node:url";
7 +import { afterEach, test } from "node:test";
8 +import { checkFile } from "./check.mjs";
10 +const dirs = [];
11 +const cli = fileURLToPath(new URL("./check.mjs", import.meta.url));
12 +const result = (stdout = "", status = 0, stderr = "") => ({ stdout, stderr, status });
13 +const diagnostic = (severity) => ({
14 + type: "diagnostic", severity, message: "fixture diagnostic", span: { start: 0, end: 1 },
15 +});
17 +function fixture(source = "1 + 2\n") {
18 + const dir = mkdtempSync(join(tmpdir(), "nu-check-"));
19 + dirs.push(dir);
20 + const file = join(dir, "script with spaces.nu");
21 + writeFileSync(file, source);
22 + return file;
25 +function fakeNu(response, calls = []) {
26 + return (command, args, options) => {
27 + calls.push({ command, args, options });
28 + return args.includes("--version") ? result("0.115.1\n") : response;
29 + };
32 +afterEach(() => {
33 + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
34 +});
36 +test("uses bounded config-free Nu diagnostics, never shell interpolation", () => {
37 + const file = fixture();
38 + const calls = [];
39 + const report = checkFile(file, fakeNu(result(), calls));
40 + assert.equal(report.ok, true);
41 + assert.equal(report.version, "0.115.1");
42 + assert.equal(calls.length, 2);
43 + assert.deepEqual(calls[1].args, ["--no-config-file", "--ide-check", "100", file]);
44 + assert.equal(calls[1].command, "nu");
45 + assert.equal(calls[1].options.cwd, dirname(file));
46 + assert.equal(calls[1].options.shell, false);
47 + assert.equal(calls[1].options.timeout, 30_000);
48 + assert.equal(calls[1].options.maxBuffer, 1_048_576);
49 +});
51 +test("Error diagnostics fail even when Nu exits zero", () => {
52 + const error = diagnostic("Error");
53 + const report = checkFile(fixture(), fakeNu(result(JSON.stringify(error))));
54 + assert.equal(report.ok, false);
55 + assert.deepEqual(report.diagnostics, [error]);
56 +});
58 +test("warnings are reported but are not errors", () => {
59 + const warning = diagnostic("Warning");
60 + const report = checkFile(fixture(), fakeNu(result(`${JSON.stringify(warning)}\r\n`)));
61 + assert.equal(report.ok, true);
62 + assert.deepEqual(report.diagnostics, [warning]);
63 +});
65 +for (const output of ["not json", "{}", '{"type":"diagnostic"}', JSON.stringify(diagnostic("Unknown"))]) {
66 + test(`fails closed on unsupported diagnostic output: ${output}`, () => {
67 + assert.equal(checkFile(fixture(), fakeNu(result(output))).ok, false);
68 + });
71 +for (const response of [
72 + result("", 2, "PRIVATE-STDERR"),
73 + result("", 0, "PRIVATE-STDERR"),
74 + { error: { code: "ENOENT", message: "PRIVATE-ERROR" }, status: null },
75 + { error: { code: "ETIMEDOUT" }, signal: "SIGTERM", status: null },
76 + { error: { code: "ENOBUFS" }, status: null },
77 +]) {
78 + test(`fails closed on process failure or stderr: ${JSON.stringify(response)}`, () => {
79 + const report = checkFile(fixture(), fakeNu(response));
80 + assert.equal(report.ok, false);
81 + assert.ok(report.error);
82 + assert.doesNotMatch(JSON.stringify(report), /PRIVATE-/);
83 + });
86 +test("version probe failure prevents checking", () => {
87 + let calls = 0;
88 + const report = checkFile(fixture(), () => { calls++; return result("bad-version"); });
89 + assert.equal(report.ok, false);
90 + assert.equal(calls, 1);
91 +});
93 +test("missing target fails before invoking Nu", () => {
94 + const report = checkFile(join(dirname(fixture()), "missing.nu"), () => assert.fail("spawned Nu"));
95 + assert.equal(report.ok, false);
96 +});
98 +test("real Nu: valid script passes without executing its body", () => {
99 + const file = fixture('"ran" | save sentinel.txt\n1 + 2\n');
100 + const report = checkFile(file);
101 + assert.equal(report.ok, true, JSON.stringify(report));
102 + assert.match(report.version, /^\d+\.\d+\.\d+/);
103 + assert.equal(existsSync(join(dirname(file), "sentinel.txt")), false);
104 +});
106 +test("real Nu: invalid script fails although raw IDE mode exits zero", () => {
107 + const file = fixture('1 + "wrong"\n');
108 + const raw = spawnSync("nu", ["--no-config-file", "--ide-check", "100", file], { encoding: "utf8" });
109 + assert.equal(raw.status, 0);
110 + const report = checkFile(file);
111 + assert.equal(report.ok, false);
112 + assert.ok(report.diagnostics.some((entry) => entry.severity === "Error"));
113 +});
115 +test("real Nu: passing IDE check does not prove deprecation-free code", () => {
116 + const file = fixture('"a" | str upcase\n');
117 + const report = checkFile(file);
118 + assert.equal(report.ok, true, JSON.stringify(report));
119 + const runtime = spawnSync("nu", ["--no-config-file", file], { encoding: "utf8" });
120 + assert.equal(runtime.status, 0);
121 + assert.match(runtime.stderr, /deprecated/);
122 +});
124 +test("CLI emits JSON and returns failure for invalid source and usage", () => {
125 + for (const args of [[fixture('1 + "wrong"\n')], []]) {
126 + const proc = spawnSync(process.execPath, [cli, ...args], { encoding: "utf8" });
127 + assert.notEqual(proc.status, 0);
128 + assert.equal(JSON.parse(proc.stdout).ok, false);
130 +});