paperthin
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/lilmgenius/paperthin with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/lilmgenius/paperthin'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/lilmgenius-paperthin)HTML
<a href="/listings/lilmgenius-paperthin"><img src="/api/listings/lilmgenius-paperthin/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
Pick **one route per agent**; installing two loads every skill twice.
1. **Codex**: it updates itself at every session start.
codex plugin marketplace add LilMGenius/paperthin && codex plugin add paperthin@paperthin
2. **Claude Code**:
claude plugin marketplace add LilMGenius/paperthin && claude plugin install paperthin@paperthin
Then, in Claude Code, run `/plugin`, open **Marketplaces**, select `paperthin` and choose **Enable auto-update**, once. 3. **Every other agent**: one line installs the skills and a daily update.
npx skills@latest add LilMGenius/paperthin --global --agent '*' && node "$HOME/.agents/skills/re0-upgrade/scripts/schedule/schedule.mjs" install
4. **Use it**: type `/paperthin`, then your dream. That's it. Want the mechanism? Relax, there's `/re0-tutorial`. 5. **Paid in stars**: if it helped, the fee is one [GitHub star](https://github.com/LilMGenius/paperthin). Cheap, I know.
**Installed it before?** Run `/re0-upgrade` once in a fresh session.
**Not sure?** Tell your agent [`install https://github.com/LilMGenius/paperthin`](./.agents/install-block.md#handed-only-this-repository). A web chat takes [llms-full.txt](https://raw.githubusercontent.com/LilMGenius/paperthin/main/llms-full.txt).
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/marketplace.json · Manifest · 17 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- {
- "name": "paperthin",
- "owner": {
- "name": "LilMGenius",
- "url": "https://github.com/LilMGenius"
- },
- "metadata": {
- "description": "The skillbook for recursive self-improvement (RSI). NVIDIA's latest proof, unpacked with timeless engineering. Distilled from the OpenAI harness engineering hackathon winner's zero-touch method."
- },
- "plugins": [
- {
- "name": "paperthin",
- "source": "./",
- "description": "The skillbook for recursive self-improvement (RSI). NVIDIA's latest proof, unpacked with timeless engineering. Distilled from the OpenAI harness engineering hackathon winner's zero-touch method."
- }
- ]
- }
README.md · README · 169 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- <div align="center">
- # Paperthin: low-level agentic design patterns
- <img src="https://raw.githubusercontent.com/LilMGenius/paperthin/main/assets/banner.svg" alt="Paperthin: low-level agentic design patterns" width="820">
- The skillbook for recursive self-improvement (**RSI**).<br>**NVIDIA**'s latest proof, unpacked with timeless engineering.<br>Distilled from the **OpenAI** harness engineering hackathon winner's zero-touch method.
- On **any** agent | Codex, Claude Code, OpenCode, Cursor, Grok Build, Grok Bot, Muse, Pi, etc.
- *"Best part is no part."* Elon Musk[^musk]
- **Built by [Bran Lee](https://github.com/LilMGenius)**<br>2026: **OpenAI** harness engineering hackathon (Ralphthon Seoul #2, held simultaneously in Seoul and SF), *1st place*, the only solo team against big-tech and top-university PhD teams<br>2026: **Claude Code** official meetup invited speaker, *twice*<br>2026: **Google DeepMind** AI hackathon invited *judge*<br>2014: Korea Olympiad in Informatics (KOI) national contest, *silver award*<br>2009~: coding since age *9*
- [Quickstart](#quickstart-30-seconds) · [The Map](#the-map) · [The Index](#the-index) · [The Problem](#the-problem) · [The Proof](#the-proof) · [Credits](#credits)
- <sub>Read in: English · [中文](./assets/i18n/README.zh-CN.md) · [हिन्दी](./assets/i18n/README.hi.md) · [Español](./assets/i18n/README.es.md) · [العربية](./assets/i18n/README.ar.md) · [Português](./assets/i18n/README.pt.md) · [Русский](./assets/i18n/README.ru.md) · [日本語](./assets/i18n/README.ja.md) · [Français](./assets/i18n/README.fr.md) · [Deutsch](./assets/i18n/README.de.md) · [한국어](./assets/i18n/README.ko.md)</sub>
- </div>
- ---
- ## Quickstart (30 seconds)
- Pick **one route per agent**; installing two loads every skill twice.
- 1. **Codex**: it updates itself at every session start.
- ```bash
- codex plugin marketplace add LilMGenius/paperthin && codex plugin add paperthin@paperthin
- ```
- 2. **Claude Code**:
- ```bash
- claude plugin marketplace add LilMGenius/paperthin && claude plugin install paperthin@paperthin
- ```
- Then, in Claude Code, run `/plugin`, open **Marketplaces**, select `paperthin` and choose **Enable auto-update**, once.
- 3. **Every other agent**: one line installs the skills and a daily update.
- ```bash
- npx skills@latest add LilMGenius/paperthin --global --agent '*' && node "$HOME/.agents/skills/re0-upgrade/scripts/schedule/schedule.mjs" install
- ```
- 4. **Use it**: type `/paperthin`, then your dream. That's it. Want the mechanism? Relax, there's `/re0-tutorial`.
- 5. **Paid in stars**: if it helped, the fee is one [GitHub star](https://github.com/LilMGenius/paperthin). Cheap, I know.
- **Installed it before?** Run `/re0-upgrade` once in a fresh session.
- **Not sure?** Tell your agent [`install https://github.com/LilMGenius/paperthin`](./.agents/install-block.md#handed-only-this-repository). A web chat takes [llms.txt](https://raw.githubusercontent.com/LilMGenius/paperthin/main/llms.txt).
- ## The Map
- **How many artifacts, and across how much time?**
- <div align="center">
- <img src="https://raw.githubusercontent.com/LilMGenius/paperthin/main/assets/map.svg" alt="The Paperthin map by LilMGenius/paperthin, a two-by-two matrix. Horizontal axis cardinality (one, then many); vertical axis time (now, then across iterations); four regions. Top-left, depth: one artifact, now; is this one thing clean and true? Top-right, breadth: many artifacts, now; is one truth consistent everywhere? Bottom-left, coil: one project, across iterations; did each pass teach the next? Bottom-right, mesh: many minds, across rounds; does the crowd converge on truth?" width="820">
- </div>
- ## The Index
- ### `depth/`
- | Skill | What it does | Invoker | Read-only |
- |---|---|---|---|
- | ♻️ **[re0](./skills/depth/re0/SKILL.md)** | Rewrites a messy, much-patched document or file as a clean first version instead of patching it again | model | |
- | 🗜️ **[debloat](./skills/depth/debloat/SKILL.md)** | Trims bloated writing or code down to what carries weight, without losing a rule or a behavior | model | |
- | 🔃 **[re0-order](./skills/depth/re0-order/SKILL.md)** | Puts a jumbled list back in a sensible order under one stated rule; it moves items and rewords nothing | model | |
- | 🧰 **[detool](./skills/depth/detool/SKILL.md)** | Replaces brand and tool names in lasting docs with what they actually do, so the docs outlive the tools | model | |
- | 🎨 **[re0-style](./skills/depth/re0-style/SKILL.md)** | Fixes code to match the project's own style, and asks where the project itself does it two ways | model | |
- | ✂️ **[dedash](./skills/depth/dedash/SKILL.md)** | Removes the long dashes an agent sprinkles into sentences, and keeps hyphens, ranges and label dashes | user | |
- | ⸱ **[dedot](./skills/depth/dedot/SKILL.md)** | In Korean text, suggests a comma or a linking word, with a reason, for each middle dot that joins a list | user | ✔ |
- | 🧭 **[readback](./skills/depth/readback/SKILL.md)** | Checks it understood your request before working, and asks only when two readings really differ | model | ✔ |
- | 🏹 **[aim](./skills/depth/aim/SKILL.md)** | Reads the files or text you hand over and suggests what you likely want, so you only confirm | model | ✔ |
- | 📏 **[modelchk](./skills/depth/modelchk/SKILL.md)** | Picks the cheapest model tier and thinking effort that still do the job well | model | ✔ |
- | 🧹 **[elon](./skills/depth/elon/SKILL.md)** | Suggests dropping or deferring requirements and commitments kept only out of habit, with where each came from; never touches rules set from outside | model | ✔ |
- | 🧩 **[scopechk](./skills/depth/scopechk/SKILL.md)** | Checks, by the target's own written scope, whether a new piece belongs where you want to put it, and names a better home if not | model | ✔ |
- | 😈 **[hate](./skills/depth/hate/SKILL.md)** | Plays the hostile critic: the one objection that could sink your plan, and the cheapest test to settle it | user | |
- | 🧠 **[macrothink](./skills/depth/macrothink/SKILL.md)** | Asks several fresh minds the question without your framing and shows first where they disagree | user | ✔ |
- | 🔀 **[crossthink](./skills/depth/crossthink/SKILL.md)** | When every option looks alike, borrows working ideas from five or more unrelated fields and keeps only the new ones | model | ✔ |
- | ⚖️ **[re0-decide](./skills/depth/re0-decide/SKILL.md)** | Turns the material behind a decision into a checklist whose verdict comes from your own answers; it never picks for you | user | ✔ |
- | 🧐 **[whychk](./skills/depth/whychk/SKILL.md)** | Questions a decision you just made until you can explain it, or shows where the reasoning has a hole | user | ✔ |
- | 🛣️ **[autobahn](./skills/depth/autobahn/SKILL.md)** | Sets the risky parts of a task aside first with safer alternatives, runs the rest at full speed, and logs what was left out | model | |
- | 🥄 **[sip](./skills/depth/sip/SKILL.md)** | Right after any change, before you call it done, runs paperthin's own checks on your output | model | |
- | 🚿 **[shower](./skills/depth/shower/SKILL.md)** | Hands your work to a fresh reader with no background and asks whether it makes sense on its own | model | ✔ |
- | 🔬 **[factchk](./skills/depth/factchk/SKILL.md)** | Checks claims against real sources both ways: the absurd may be true, and the obvious may be false | model | |
- | 🧪 **[mandela](./skills/depth/mandela/SKILL.md)** | Checks whether a test or metric is grading itself, or whether real outside truth decides the result | model | ✔ |
- | 🎭 **[demock](./skills/depth/demock/SKILL.md)** | Finds fakes and silent fallbacks in live code that make a success report false, and suggests the real fix | model | |
- | 🥸 **[deid](./skills/depth/deid/SKILL.md)** | Finds one person's or company's data in shared files, replaces it with the role it plays, and lists the old commits that still hold it | model | |
- | 🧾 **[re0-git](./skills/depth/re0-git/SKILL.md)** | Rewrites a finished commit's message with its dates and place kept, so the git history alone lets anyone take over | user | |
- | 🚀 **[re0-release](./skills/depth/re0-release/SKILL.md)** | Runs the release checklist, then tags and publishes once you confirm | user | |
- | 🤝 **[re0-merge](./skills/depth/re0-merge/SKILL.md)** | Reviews and lands someone else's contribution, keeps their credit, and explains any change made to it | user | |
- | 🧨 **[re0-squash](./skills/depth/re0-squash/SKILL.md)** | Republishes a GitHub repository as one signed commit with the same files, leaving no old commit reachable | user | |
- ### `breadth/`
- | Skill | What it does | Invoker | Read-only |
- |---|---|---|---|
- | 🧲 **[ssotize](./skills/breadth/ssotize/SKILL.md)** | Finds a fact copied in many places, gives it one home once you approve, and points the rest there | model | |
- | 🔗 **[ssotize-local](./skills/breadth/ssotize-local/SKILL.md)** | Merges duplicate files or folders into one real copy the others link to, with a tested way back | model | |
- | 📖 **[re0-readme](./skills/breadth/re0-readme/SKILL.md)** | Sorts a README and its AGENTS.md so each line sits in the file whose reader needs it | model | |
- | 📥 **[re0-import](./skills/breadth/re0-import/SKILL.md)** | Files handed-over material into the right page of an existing knowledge base, by that base's own rules, and reports what has no home | user | |
- | 🆙 **[re0-upgrade](./skills/breadth/re0-upgrade/SKILL.md)** | Brings your install up to the full current catalog in one confirmed step: retires renamed skills and adds new ones | user | |
- ### `coil/`
- | Skill | What it does | Invoker | Read-only |
- |---|---|---|---|
- | 🚪 **[paperthin](./skills/coil/paperthin/SKILL.md)** | The one command to remember: type your dream after it | user | |
- | 🪜 **[re0-workflow](./skills/coil/re0-workflow/SKILL.md)** | For one goal, picks which skills to run in which order, shows you, then runs them and stops where you must act | model | |
- | 📝 **[re0-memo](./skills/coil/re0-memo/SKILL.md)** | Pulls the lessons, and the mistakes to avoid, out of a finished or failed cycle | model | |
- | 🔁 **[backprop](./skills/coil/backprop/SKILL.md)** | Takes what a correction taught and fixes the docs and rules that caused it, then tidies them up | model | |
- | 🧱 **[re0-work](./skills/coil/re0-work/SKILL.md)** | Starts over from scratch, keeping only the lessons that proved worth reusing | model | |
- | 🗺️ **[catchup](./skills/coil/catchup/SKILL.md)** | Catches you up after time away: what needs you, what changed, and what new terms mean | model | ✔ |
- | 🎯 **[nba](./skills/coil/nba/SKILL.md)** | Reads where the work stands and names the one best next step, not a menu | model | ✔ |
- | 🗂️ **[re0-plan](./skills/coil/re0-plan/SKILL.md)** | Before a new work cycle starts, opens its folder with the design, workflow and evidence files | user | |
- | 🌀 **[re0-loop](./skills/coil/re0-loop/SKILL.md)** | Keeps a build, test, learn and restart cycle running, so lessons pile up instead of code | model | |
- | 👁️ **[re0-watch](./skills/coil/re0-watch/SKILL.md)** | Watches a long agent job for stalls and alerts you; any fix is only a proposal you approve | user | |
- | 🎓 **[re0-tutorial](./skills/coil/re0-tutorial/SKILL.md)** | Teaches one skill in three graded levels, each passed on work you submit yourself | user | |
- ### `mesh/`
- | Skill | What it does | Invoker | Read-only |
- |---|---|---|---|
- | 🕸️ **[multithink](./skills/mesh/multithink/SKILL.md)** | Weighs several independent opinions by the evidence they cite, never by how many agree | user | ✔ |
- *More on invocation: [.agents/invocation.md](./.agents/invocation.md)*
- ## The Problem
- **Most agent skills are slop.**
- Point an agent at a goal and it **adds**: more files, more options, more "helpful" boilerplate. Adding looks like progress, and nothing ever makes it go back and delete.
- > [!WARNING]
- > Repeat that across a project and you get the familiar AI-generated toolkit: near-duplicate skills, dead settings, a markdown that says the same thing three times. Plausible, busy, and quietly unmaintainable.
- These skills bet the other way: **every one of them removes something**, and [the Index](#the-index) says what.
- > [!TIP]
- > The hard part isn't adding features; it's restraint. A pass that finds nothing to improve changes nothing. **That restraint is the product.**
- ## The Proof
- **NVIDIA measured it: an agent that drops its long history and works from a short note keeps its score.**
- | What NVIDIA measured | Long context | Short note |
- |---|---|---|
- | SWE-bench Verified, Claude Opus 4.5 | 70.0 | 70.2 |
- | Largest context the run needed | 200K tokens | 16K tokens |
- | Open-weight serving throughput, H100 | 256K window | up to 7x higher at 16K |
- <sub>Belcak et al. (NVIDIA), [You don't need long context](https://arxiv.org/abs/2611.05306), arXiv 2611.05306, 2026-11-03. Rows one and two are Table 2, Opus 4.5 acting one step at a time on a state note; row three is Figure 1 (GLM 5.2 3.6x, Kimi K2.6 5.6x, Qwen 3 Coder Next 7x).</sub>
- **Where each finding lands in Paperthin:**
- | The paper found | Skills that act on it |
- |---|---|
- | Long work needs no long context: when the conversation fills, write a note and go on in a fresh one | `re0-work` restarts from v0 with only proven lessons, `re0-git` leaves the handoff in the git log for the next session |
- | A good note keeps the task close to its original words | `re0-loop` keeps every open request on the list when the session compacts or starts fresh |
- | A good note keeps what is being done, why, and what comes next | `re0-memo` turns a finished cycle into the next one's gate, `nba` names the one next step |
- | A good note keeps the plan, the done conditions and where things are | `re0-plan` opens the cycle with its design, workflow and evidence files, `re0-workflow` keeps the skill order and its done condition in the report it resumes from |
- | One action at a time on a state note keeps the full-history score | `shower` hands the note alone to a reader with no history and asks whether it stands on its own |
- | A smaller window serves up to 7x faster | `elon` drops what is kept only by habit, `debloat` cuts to what carries weight, `re0` rewrites instead of piling on |
- ## Credits
- - **Built on** [mattpocock/skills](https://github.com/mattpocock/skills) (MIT): its architecture and philosophy.
- - **Not a fork** — these are [LilMGenius](https://github.com/LilMGenius)'s own, non-overlapping workflows.
- - **Vendored verbatim** — a few shared building blocks, kept as-is with per-source attribution in [NOTICE](./NOTICE).
- - **Authoring guide** — conventions and philosophy live in [AGENTS.md](./AGENTS.md).
- [^musk]: Elon Musk, [reply on X](https://x.com/elonmusk/status/2103537444910248312), 2026-09-25, to @Erdayastronaut on SpaceX removing one grid fin from the V3 booster. He said it about engineering, not about Paperthin.
skills/breadth/re0-upgrade/scripts/schedule/schedule.mjs · Bundled script · 415 lines · 1 finding marked
- #!/usr/bin/env node
- // Keep a skills.sh install of paperthin current with one per-user OS job, so nobody runs a follow-up step after the
- // first install. Claude Code and Codex plugin installs need none of this: each host updates its own marketplace plugins.
- // The job runs daily at the user's local 00:00, the day boundary on a round clock mark, so it runs once per calendar day,
- // and each adapter catches a missed midnight up at the next login or wake (StartWhenAvailable, Persistent=true, launchd's
- // own coalescing). Each run updates every global skill, then adds the latest release's catalog skills that are not
- // installed yet, since skills update never adds a skill shipped after the install. No dependencies; per-OS adapters below.
- // Usage: node schedule.mjs install [--name <job>] [--home <dir>]
- // node schedule.mjs status [--name <job>]
- // node schedule.mjs run [--name <job>] [--home <dir>]
- // node schedule.mjs uninstall [--name <job>]
- // --home points the skills CLI at another home directory (a throwaway one in a test); it is written into the job.
- // Exit codes: 0 done (status: the job is registered); 1 a run, a scheduler command or a status lookup failed; 2 usage.
- import { spawnSync } from 'node:child_process';
- import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
- import { homedir, userInfo } from 'node:os';
- import { delimiter, dirname, join, resolve } from 'node:path';
- import { fileURLToPath } from 'node:url';
- import { parseArgs } from 'node:util';
- import { readInstalled, readRules } from '../upgrade.mjs';
- const USAGE = 'usage: node schedule.mjs install|status|run|uninstall [--name <job>] [--home <dir>] (--home: install and run only)';
- const DEFAULT_NAME = 'paperthin-update';
- const JOB_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
- const KEEP = 10;
- const OUTPUT_CAP = 4000;
- const STEP_TIMEOUT = 30 * 60 * 1000;
- const UPSTREAM = 'LilMGenius/paperthin';
- // github.com answers /releases/latest with a redirect to the newest release's tag page. The REST API answers the same
- // question but allows an unauthenticated IP 60 requests an hour, which a shared egress (a CI runner, an office NAT) spends:
- // a macOS runner's call answered 403 on 2026-11-02.
- const LATEST = 'https://github.com/' + UPSTREAM + '/releases/latest';
- const CATALOG_AT = (tag) => 'https://raw.githubusercontent.com/' + UPSTREAM + '/' + encodeURIComponent(tag) + '/skills/breadth/re0-upgrade/SKILL.md';
- const CRON_MARK = ' # paperthin-job:';
- class Usage extends Error {}
- export const jobArgs = ({ node, script, name, home }) => [node, script, 'run', '--name', name, ...(home ? ['--home', home] : [])];
- // Element text only, so quotes stay literal.
- const xml = (text) => String(text).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
- // The quoting CommandLineToArgvW reads: a run of backslashes is doubled only before a quote.
- function winQuote(arg) {
- if (arg && !/[\s"]/.test(arg)) return arg;
- return '"' + arg.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, '$1$1') + '"';
- }
- // Task Scheduler: a calendar trigger with no offset is local time. InteractiveToken runs only while the user is signed in
- // and needs no stored password or elevation; conhost --headless keeps node's console window from opening.
- export function windowsTask({ user, conhost, ...job }) {
- return [
- '<?xml version="1.0" encoding="UTF-16"?>',
- '<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">',
- ' <RegistrationInfo>',
- ' <Description>' + xml('Keeps paperthin installed through skills.sh current: daily at local 00:00 it updates global skills and adds new catalog skills. Remove with: node ' + job.script + ' uninstall --name ' + job.name) + '</Description>',
- ' </RegistrationInfo>',
- ' <Triggers>',
- ' <CalendarTrigger>',
- ' <StartBoundary>2026-01-01T00:00:00</StartBoundary>',
- ' <Enabled>true</Enabled>',
- ' <ScheduleByDay>',
- ' <DaysInterval>1</DaysInterval>',
- ' </ScheduleByDay>',
- ' </CalendarTrigger>',
- ' </Triggers>',
- ' <Principals>',
- ' <Principal id="Author">',
- ' <UserId>' + xml(user) + '</UserId>',
- ' <LogonType>InteractiveToken</LogonType>',
- ' <RunLevel>LeastPrivilege</RunLevel>',
- ' </Principal>',
- ' </Principals>',
- ' <Settings>',
- ' <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>',
- ' <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>',
- ' <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>',
- ' <StartWhenAvailable>true</StartWhenAvailable>',
- ' <Hidden>true</Hidden>',
- Note: Usual in code (tag names in paths and patterns): Contains a <hidden> block, a common wrapper for instructions hidden in a tool description
- Line 79 on GitHub
- ' <ExecutionTimeLimit>PT1H</ExecutionTimeLimit>',
- ' <Enabled>true</Enabled>',
- ' </Settings>',
- ' <Actions Context="Author">',
- ' <Exec>',
- ' <Command>' + xml(conhost) + '</Command>',
- ' <Arguments>' + xml(['--headless', ...jobArgs(job).map(winQuote)].join(' ')) + '</Arguments>',
- ' </Exec>',
- ' </Actions>',
- '</Task>',
- '',
- ].join('\r\n');
- }
- export const launchdLabel = (name) => 'com.lilmgenius.' + name;
- export function launchdPlist(job) {
- return [
- '<?xml version="1.0" encoding="UTF-8"?>',
- '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
- '<plist version="1.0">',
- '<dict>',
- ' <key>Label</key>',
- ' <string>' + xml(launchdLabel(job.name)) + '</string>',
- ' <key>ProgramArguments</key>',
- ' <array>',
- ...jobArgs(job).map((arg) => ' <string>' + xml(arg) + '</string>'),
- ' </array>',
- ' <key>StartCalendarInterval</key>',
- ' <dict>',
- ' <key>Hour</key>',
- ' <integer>0</integer>',
- ' <key>Minute</key>',
- ' <integer>0</integer>',
- ' </dict>',
- ' <key>ProcessType</key>',
- ' <string>Background</string>',
- '</dict>',
- '</plist>',
- '',
- ].join('\n');
- }
- // systemd unit quoting: double quotes with backslash and quote escaped, % and $ doubled so no specifier or variable expands.
- const unitQuote = (arg) => '"' + arg.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/%/g, '%%').replace(/\$/g, '$$$$') + '"';
- export function systemdUnits(job) {
- return {
- service: ['[Unit]', 'Description=Update paperthin skills installed through skills.sh', '', '[Service]', 'Type=oneshot', 'ExecStart=' + jobArgs(job).map(unitQuote).join(' '), ''].join('\n'),
- timer: ['[Unit]', 'Description=Run ' + job.name + ' daily at local 00:00', '', '[Timer]', 'OnCalendar=*-*-* 00:00:00', 'Persistent=true', 'Unit=' + job.name + '.service', '', '[Install]', 'WantedBy=timers.target', ''].join('\n'),
- };
- }
- const shQuote = (arg) => "'" + arg.replace(/'/g, "'\\''") + "'";
- const marked = (name) => (line) => line.endsWith(CRON_MARK + name);
- export function cronRemove(table, name) {
- return table.split('\n').filter((line) => !marked(name)(line)).join('\n');
- }
- export function cronInstall(table, job) {
- const kept = cronRemove(table, job.name).replace(/\n*$/, '');
- return (kept ? kept + '\n' : '') + '0 0 * * * ' + jobArgs(job).map(shQuote).join(' ') + CRON_MARK + job.name + '\n';
- }
- // The job only keeps an existing install current: where no catalog skill is installed it adds nothing.
- export function namesToAdd(catalog, installed) {
- const have = new Set(installed);
- return catalog.some((name) => have.has(name)) ? catalog.filter((name) => !have.has(name)) : [];
- }
- const RUN_LINE = /^=== run (\S+)$/;
- const EXIT_LINE = /^=== exit (-?\d+) (\S+)$/;
- function blocks(log) {
- const out = [];
- for (const line of log.split('\n')) {
- if (RUN_LINE.test(line)) out.push([]);
- if (out.length) out[out.length - 1].push(line);
- }
- return out.map((lines) => lines.join('\n').replace(/\n*$/, '\n'));
- }
- export const rotate = (log, block, keep = KEEP) => [...blocks(log), block.replace(/\n*$/, '\n')].slice(-keep).join('');
- export function lastRun(log) {
- const last = blocks(log).at(-1);
- if (!last) return null;
- const lines = last.trimEnd().split('\n');
- const exit = EXIT_LINE.exec(lines.at(-1));
- return { started: RUN_LINE.exec(lines[0])[1], ended: exit ? exit[2] : null, exit: exit ? Number(exit[1]) : null };
- }
- export function logFile(platform, env, home, name) {
- if (platform === 'win32') return join(env.LOCALAPPDATA || join(home, 'AppData', 'Local'), 'paperthin', 'logs', name + '.log');
- if (platform === 'darwin') return join(home, 'Library', 'Logs', 'paperthin', name + '.log');
- return join(env.XDG_STATE_HOME || join(home, '.local', 'state'), 'paperthin', name + '.log');
- }
- // Node's spawn refuses a .cmd file without a shell, so npx runs as node plus npm's npx-cli.js wherever npm sits beside node;
- // only a node with no npm beside it falls back to npx through a shell.
- export function npxCommand(execPath, platform, exists = existsSync) {
- const candidates = [join(dirname(execPath), 'node_modules', 'npm', 'bin', 'npx-cli.js'), join(dirname(execPath), '..', 'lib', 'node_modules', 'npm', 'bin', 'npx-cli.js')];
- const cli = candidates.find((path) => exists(path));
- if (cli) return { file: execPath, args: [cli], shell: false };
- return platform === 'win32' ? { file: 'npx.cmd', args: [], shell: true } : { file: 'npx', args: [], shell: false };
- }
- const ANSI = /\x1b\[[0-9;?]*[A-Za-z]/g;
- const tail = (text) => (text.length > OUTPUT_CAP ? '[... ' + (text.length - OUTPUT_CAP) + ' characters cut]\n' + text.slice(-OUTPUT_CAP) : text);
- function exec(file, args, options = {}) {
- const result = spawnSync(file, args, { encoding: 'utf8', windowsHide: true, ...options });
- return { status: result.error ? null : result.status, error: result.error?.message, out: ((result.stdout || '') + (result.stderr || '')).replace(ANSI, '') };
- }
- // One step through npx: the child's PATH starts with node's own folder, since a scheduler's PATH may not hold it and the
- // skills bin is a node script.
- function npx(args, home) {
- const command = npxCommand(process.execPath, process.platform);
- const env = { ...process.env, PATH: dirname(process.execPath) + delimiter + (process.env.PATH || process.env.Path || '') };
- if (home) Object.assign(env, { HOME: home, USERPROFILE: home });
- delete env.Path;
- return exec(command.file, [...command.args, ...args], { cwd: home || homedir(), env, shell: command.shell, timeout: STEP_TIMEOUT, maxBuffer: 64 * 1024 * 1024 });
- }
- export function tagFromRedirect(location) {
- const tag = /\/releases\/tag\/([^/?#]+)$/.exec(location || '')?.[1];
- return tag ? decodeURIComponent(tag) : null;
- }
- async function latestCatalog() {
- const headers = { 'user-agent': 're0-upgrade-schedule' };
- const release = await fetch(LATEST, { headers, redirect: 'manual', signal: AbortSignal.timeout(30000) });
- const tag = tagFromRedirect(release.headers.get('location'));
- if (!tag) throw new Error('GET ' + LATEST + ' answered ' + release.status + ' with no release tag to follow');
- const raw = await fetch(CATALOG_AT(tag), { headers, signal: AbortSignal.timeout(30000) });
- if (raw.status !== 200) throw new Error('GET ' + CATALOG_AT(tag) + ' answered ' + raw.status);
- return { tag, catalog: readRules(await raw.text()).catalog };
- }
- async function runOnce({ name, home }) {
- const file = logFile(process.platform, process.env, homedir(), name);
- const lines = ['=== run ' + new Date().toISOString()];
- const note = (text) => lines.push(text.replace(/\n*$/, ''));
- let code = 0;
- try {
- note('$ npx -y skills@latest update -g -y' + (home ? ' (home ' + home + ')' : ''));
- const update = npx(['-y', 'skills@latest', 'update', '-g', '-y'], home);
- note(tail(update.out) + (update.error ? '\n' + update.error : ''));
- if (update.status !== 0) throw new Error('skills update exited ' + update.status);
- const { tag, catalog } = await latestCatalog();
- const skillsDir = join(home || homedir(), '.agents', 'skills');
- const installed = existsSync(skillsDir) ? readInstalled(skillsDir) : [];
- const add = namesToAdd(catalog, installed);
- note('catalog of ' + tag + ': ' + catalog.length + ' skills; installed in ' + skillsDir + ': ' + installed.length + '; to add: ' + (add.length ? add.join(', ') : 'none'));
- if (add.length) {
- const args = ['-y', 'skills@latest', 'add', UPSTREAM, '-g', '-y', ...add.flatMap((skill) => ['-s', skill])];
- note('$ npx ' + args.join(' '));
- const added = npx(args, home);
- note(tail(added.out) + (added.error ? '\n' + added.error : ''));
- if (added.status !== 0) throw new Error('skills add exited ' + added.status);
- }
- } catch (error) {
- note('failed: ' + error.message);
- code = 1;
- }
- lines.push('=== exit ' + code + ' ' + new Date().toISOString());
- mkdirSync(dirname(file), { recursive: true });
- writeFileSync(file, rotate(existsSync(file) ? readFileSync(file, 'utf8') : '', lines.join('\n') + '\n'));
- console.log(JSON.stringify({ name, exit: code, log: file }, null, 2));
- return code;
- }
- // A file is rewritten only when its content changed.
- function writeIfChanged(file, content) {
- if (existsSync(file) && readFileSync(file, 'utf8') === content) return false;
- mkdirSync(dirname(file), { recursive: true });
- writeFileSync(file, content);
- return true;
- }
- function must(result, what) {
- if (result.status !== 0) throw new Error(what + ' exited ' + result.status + ': ' + (result.error || result.out.trim()));
- return result;
- }
- const ps = (script) => exec('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script]);
- const hasSystemd = () => exec('systemctl', ['--user', 'show-environment']).status === 0;
- const unitDir = () => join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'systemd', 'user');
- const plistPath = (name) => join(homedir(), 'Library', 'LaunchAgents', launchdLabel(name) + '.plist');
- const gui = () => 'gui/' + userInfo().uid;
- function nextMidnight() {
- const next = new Date();
- next.setHours(24, 0, 0, 0);
- return next.toISOString();
- }
- // Each adapter: install writes and registers the job, remove unregisters it and deletes only its own files, and query
- // reports whether the scheduler holds it and its next run.
- const ADAPTERS = {
- windows: {
- install(job) {
- const file = join(dirname(logFile('win32', process.env, homedir(), job.name)), job.name + '.task.xml');
- const user = (process.env.USERDOMAIN ? process.env.USERDOMAIN + '\\' : '') + (process.env.USERNAME || userInfo().username);
- const conhost = join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'conhost.exe');
- mkdirSync(dirname(file), { recursive: true });
- writeFileSync(file, Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(windowsTask({ ...job, user, conhost }), 'utf16le')]));
- try {
- must(exec('schtasks.exe', ['/Create', '/TN', job.name, '/XML', file, '/F']), 'schtasks /Create');
- } finally {
- rmSync(file, { force: true });
- }
- },
- remove: (name) => must(exec('schtasks.exe', ['/Delete', '/TN', name, '/F']), 'schtasks /Delete'),
- query(name) {
- const got = ps("$t = Get-ScheduledTask -TaskName '" + name + "' -ErrorAction Stop; $i = $t | Get-ScheduledTaskInfo; [pscustomobject]@{ state = [string]$t.State; last = if ($i.LastRunTime -and $i.LastRunTime.Year -gt 2000) { $i.LastRunTime.ToString('o') } else { $null }; result = $i.LastTaskResult; next = if ($i.NextRunTime) { $i.NextRunTime.ToString('o') } else { $null } } | ConvertTo-Json -Compress");
- if (got.status !== 0) return { registered: false };
- const info = JSON.parse(got.out.trim());
- // 267011 (0x41303) is Task Scheduler's "has not yet run".
- return { registered: true, next: info.next, nextFrom: 'scheduler', scheduler: { state: info.state, lastRun: info.last, lastResult: info.result === 267011 ? 'not run yet' : info.result } };
- },
- },
- launchd: {
- install(job) {
- writeIfChanged(plistPath(job.name), launchdPlist(job));
- exec('launchctl', ['bootout', gui() + '/' + launchdLabel(job.name)]);
- must(exec('launchctl', ['bootstrap', gui(), plistPath(job.name)]), 'launchctl bootstrap');
- },
- remove(name) {
- exec('launchctl', ['bootout', gui() + '/' + launchdLabel(name)]);
- rmSync(plistPath(name), { force: true });
- },
- query(name) {
- const got = exec('launchctl', ['print', gui() + '/' + launchdLabel(name)]);
- if (got.status !== 0) return { registered: false };
- const exit = /last exit code = (\S+)/.exec(got.out);
- return { registered: true, next: nextMidnight(), nextFrom: 'computed', scheduler: { lastExit: exit ? exit[1] : 'not run yet' } };
- },
- },
- systemd: {
- install(job) {
- const { service, timer } = systemdUnits(job);
- writeIfChanged(join(unitDir(), job.name + '.service'), service);
- writeIfChanged(join(unitDir(), job.name + '.timer'), timer);
- must(exec('systemctl', ['--user', 'daemon-reload']), 'systemctl --user daemon-reload');
- must(exec('systemctl', ['--user', 'enable', '--now', job.name + '.timer']), 'systemctl --user enable');
- },
- remove(name) {
- exec('systemctl', ['--user', 'disable', '--now', name + '.timer']);
- rmSync(join(unitDir(), name + '.service'), { force: true });
- rmSync(join(unitDir(), name + '.timer'), { force: true });
- must(exec('systemctl', ['--user', 'daemon-reload']), 'systemctl --user daemon-reload');
- },
- query(name) {
- if (!existsSync(join(unitDir(), name + '.timer'))) return { registered: false };
- const got = exec('systemctl', ['--user', 'show', name + '.timer', '-p', 'ActiveState', '-p', 'NextElapseUSecRealtime']);
- const field = (key) => new RegExp('^' + key + '=(.*)$', 'm').exec(got.out)?.[1] || null;
- return { registered: field('ActiveState') === 'active', next: field('NextElapseUSecRealtime'), nextFrom: 'scheduler', scheduler: { timer: field('ActiveState') } };
- },
- },
- cron: {
- install(job) {
- const now = exec('crontab', ['-l']);
- must(exec('crontab', ['-'], { input: cronInstall(now.status === 0 ? now.out : '', job) }), 'crontab -');
- },
- remove(name) {
- const now = exec('crontab', ['-l']);
- if (now.status === 0) must(exec('crontab', ['-'], { input: cronRemove(now.out, name) }), 'crontab -');
- },
- query(name) {
- const now = exec('crontab', ['-l']);
- return now.status === 0 && now.out.split('\n').some(marked(name)) ? { registered: true, next: nextMidnight(), nextFrom: 'computed', scheduler: {} } : { registered: false };
- },
- },
- };
- function adapter() {
- if (process.platform === 'win32') return ['windows', ADAPTERS.windows];
- if (process.platform === 'darwin') return ['launchd', ADAPTERS.launchd];
- if (hasSystemd()) return ['systemd', ADAPTERS.systemd];
- if (exec('crontab', ['-l']).error) throw new Error('neither systemd --user nor crontab is available, so no job can be scheduled');
- return ['cron', ADAPTERS.cron];
- }
- function status(name) {
- const [platform, os] = adapter();
- const log = logFile(process.platform, process.env, homedir(), name);
- const job = os.query(name);
- const report = { name, platform, ...job, log, lastRun: existsSync(log) ? lastRun(readFileSync(log, 'utf8')) : null };
- console.log(JSON.stringify(report, null, 2));
- return job.registered ? 0 : 1;
- }
- export async function main(argv) {
- let values;
- let verb;
- try {
- ({ values, positionals: [verb] } = parseArgs({ args: argv, allowPositionals: true, options: { name: { type: 'string' }, home: { type: 'string' }, help: { type: 'boolean' } } }));
- if (values.help) {
- console.log(USAGE);
- return 0;
- }
- if (!['install', 'status', 'run', 'uninstall'].includes(verb)) throw new Usage('name install, status, run or uninstall');
- if (values.name !== undefined && !JOB_NAME.test(values.name)) throw new Usage('--name ' + values.name + ' is not a plain job name (letters, digits, dot, dash, underscore)');
- if (values.home !== undefined && !['install', 'run'].includes(verb)) throw new Usage('--home is for install and run only');
- if (values.home !== undefined && !statSync(values.home, { throwIfNoEntry: false })?.isDirectory()) throw new Usage('--home ' + values.home + ' is not a directory');
- } catch (error) {
- if (error instanceof TypeError || error instanceof Usage) {
- console.error('re0-upgrade schedule: ' + error.message + '\n' + USAGE);
- return 2;
- }
- throw error;
- }
- const name = values.name || DEFAULT_NAME;
- const home = values.home && resolve(values.home);
- try {
- if (verb === 'run') return await runOnce({ name, home });
- if (verb === 'status') return status(name);
- const [platform, os] = adapter();
- // The job keeps the path it was installed from: an installed skill's link path survives every skills update.
- if (verb === 'install') os.install({ name, home, node: process.execPath, script: resolve(process.argv[1]) });
- else if (os.query(name).registered) os.remove(name);
- console.log(JSON.stringify({ name, platform, [verb === 'install' ? 'installed' : 'uninstalled']: true }, null, 2));
- return 0;
- } catch (error) {
- console.error('re0-upgrade schedule: ' + error.message);
- return 1;
- }
- }
- // An installed skill is often a link to its source folder; Node resolves import.meta.url through the link while argv keeps
- // the link path, so both sides are compared as real paths or a call through the link exits 0 having done nothing.
- if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) process.exitCode = await main(process.argv.slice(2));
skills/breadth/re0-upgrade/scripts/schedule/schedule.test.mjs · Bundled script · 117 lines · 1 finding marked
- import { test } from 'node:test';
- import assert from 'node:assert/strict';
- import { spawnSync } from 'node:child_process';
- import { mkdtempSync, rmSync, symlinkSync } from 'node:fs';
- import { tmpdir } from 'node:os';
- import { dirname, join } from 'node:path';
- import { fileURLToPath } from 'node:url';
- import { cronInstall, cronRemove, jobArgs, lastRun, launchdPlist, logFile, namesToAdd, npxCommand, rotate, systemdUnits, tagFromRedirect, windowsTask } from './schedule.mjs';
- const here = dirname(fileURLToPath(import.meta.url));
- const scratch = mkdtempSync(join(tmpdir(), 're0-schedule-'));
- // Every CLI call goes through a junction to this folder, the way an installed skill links its source.
- symlinkSync(here, join(scratch, 'schedule'), process.platform === 'win32' ? 'junction' : 'dir');
- const cli = join(scratch, 'schedule', 'schedule.mjs');
- process.on('exit', () => rmSync(scratch, { recursive: true, force: true }));
- const run = (args) => spawnSync(process.execPath, [cli, ...args], { encoding: 'utf8' });
- const job = { name: 'paperthin-update', node: '/opt/node 26/bin/node', script: '/home/u/.agents/skills/re0-upgrade/scripts/schedule/schedule.mjs' };
- const argv = jobArgs(job);
- test('the job runs the script verb run under its own name, carrying --home only when one is given', () => {
- assert.deepEqual(argv, [job.node, job.script, 'run', '--name', 'paperthin-update']);
- assert.deepEqual(jobArgs({ ...job, home: '/tmp/h' }).slice(-2), ['--home', '/tmp/h']);
- });
- test('the latest tag is read from the redirect github.com answers, and a page with no release names none', () => {
- assert.equal(tagFromRedirect('https://github.com/LilMGenius/paperthin/releases/tag/v0.17.7'), 'v0.17.7');
- assert.equal(tagFromRedirect('https://github.com/o/r/releases/tag/release%2F1.0'), 'release/1.0');
- assert.equal(tagFromRedirect('https://github.com/LilMGenius/paperthin/releases'), null, 'a repository with no release redirects to the list');
- assert.equal(tagFromRedirect(null), null);
- });
- test('the Windows task fires daily at local 00:00, hidden, unelevated, through a headless console', () => {
- const xml = windowsTask({ ...job, node: 'C:\\Program Files\\nodejs\\node.exe', script: 'C:\\Users\\a b\\x & y\\schedule.mjs', user: 'PC\\u', conhost: 'C:\\Windows\\System32\\conhost.exe' });
- assert.match(xml, /<StartBoundary>\d{4}-\d\d-\d\dT00:00:00<\/StartBoundary>/, 'a local time carries no Z or offset');
- assert.match(xml, /<ScheduleByDay>\s*<DaysInterval>1<\/DaysInterval>\s*<\/ScheduleByDay>/);
- assert.match(xml, /<LogonType>InteractiveToken<\/LogonType>/);
- assert.match(xml, /<RunLevel>LeastPrivilege<\/RunLevel>/);
- assert.match(xml, /<UserId>PC\\u<\/UserId>/);
- assert.match(xml, /<Hidden>true<\/Hidden>/);
- Note: Usual in code (tag names in paths and patterns): Contains a <hidden> block, a common wrapper for instructions hidden in a tool description
- Line 40 on GitHub
- assert.match(xml, /<StartWhenAvailable>true<\/StartWhenAvailable>/, 'a machine asleep at midnight runs at wake');
- assert.match(xml, /<Command>C:\\Windows\\System32\\conhost\.exe<\/Command>/);
- assert.match(xml, /<Arguments>--headless "C:\\Program Files\\nodejs\\node\.exe" "C:\\Users\\a b\\x & y\\schedule\.mjs" run --name paperthin-update<\/Arguments>/);
- });
- test('the launchd agent fires at Hour 0 Minute 0 with each argument as its own string', () => {
- const plist = launchdPlist({ ...job, script: '/a/<b>.mjs' });
- assert.match(plist, /<key>Label<\/key>\s*<string>com\.lilmgenius\.paperthin-update<\/string>/);
- assert.match(plist, /<key>StartCalendarInterval<\/key>\s*<dict>\s*<key>Hour<\/key>\s*<integer>0<\/integer>\s*<key>Minute<\/key>\s*<integer>0<\/integer>\s*<\/dict>/);
- assert.match(plist, /<string>\/opt\/node 26\/bin\/node<\/string>\s*<string>\/a\/<b>\.mjs<\/string>\s*<string>run<\/string>/);
- assert.doesNotMatch(plist, /RunAtLoad/);
- });
- test('the systemd timer fires on calendar 00:00 local, catches up after downtime and starts a oneshot service', () => {
- const { service, timer } = systemdUnits({ ...job, script: '/a/100%/$x.mjs' });
- assert.match(timer, /^OnCalendar=\*-\*-\* 00:00:00$/m);
- assert.match(timer, /^Persistent=true$/m);
- assert.match(timer, /^Unit=paperthin-update\.service$/m);
- assert.match(timer, /^WantedBy=timers\.target$/m);
- assert.match(service, /^Type=oneshot$/m);
- assert.match(service, /^ExecStart="\/opt\/node 26\/bin\/node" "\/a\/100%%\/\$\$x\.mjs" "run" "--name" "paperthin-update"$/m);
- });
- test('the cron line runs at minute 0 hour 0, replaces only its own marked line and removes only that line', () => {
- const others = '# mine\n5 4 * * * backup\n';
- const once = cronInstall(others, job);
- assert.equal(once, others + "0 0 * * * '/opt/node 26/bin/node' '" + job.script + "' 'run' '--name' 'paperthin-update' # paperthin-job:paperthin-update\n");
- assert.equal(cronInstall(once, job), once, 'a second install leaves one line');
- assert.ok(cronInstall('', { ...job, script: "/it's.mjs" }).includes(" '/it'\\''s.mjs' "), 'a quote in a path is closed, escaped and reopened');
- assert.equal(cronRemove(once + '1 1 * * * x # paperthin-job:other\n', 'paperthin-update'), others + '1 1 * * * x # paperthin-job:other\n');
- });
- test('the catalog diff adds every latest catalog name not installed, and nothing where paperthin is not installed at all', () => {
- const catalog = ['re0', 'sip', 'new-one', 're0-upgrade'];
- assert.deepEqual(namesToAdd(catalog, ['re0', 'sip', 're0-upgrade', 'someone-else']), ['new-one']);
- assert.deepEqual(namesToAdd(catalog, ['re0', 'sip', 'new-one', 're0-upgrade']), []);
- assert.deepEqual(namesToAdd(catalog, ['someone-else']), [], 'the job never installs paperthin from nothing');
- });
- const block = (n, exit) => '=== run 2026-11-0' + n + 'T00:00:00.000Z\nout ' + n + '\n' + (exit === undefined ? '' : '=== exit ' + exit + ' 2026-11-0' + n + 'T00:01:00.000Z\n');
- test('the log keeps the last N runs and reports the newest, a crashed run without an exit line included', () => {
- let log = '';
- for (let n = 1; n <= 5; n += 1) log = rotate(log, block(n, n === 4 ? 1 : 0), 3);
- assert.equal(log, block(3, 0) + block(4, 1) + block(5, 0));
- assert.deepEqual(lastRun(log), { started: '2026-11-05T00:00:00.000Z', ended: '2026-11-05T00:01:00.000Z', exit: 0 });
- assert.deepEqual(lastRun(rotate(log, block(6), 3)), { started: '2026-11-06T00:00:00.000Z', ended: null, exit: null });
- assert.equal(lastRun(''), null);
- });
- test('one known log path per OS', () => {
- assert.equal(logFile('win32', { LOCALAPPDATA: 'C:\\L' }, 'C:\\U', 'n'), join('C:\\L', 'paperthin', 'logs', 'n.log'));
- assert.equal(logFile('darwin', {}, '/Users/u', 'n'), join('/Users/u', 'Library', 'Logs', 'paperthin', 'n.log'));
- assert.equal(logFile('linux', {}, '/home/u', 'n'), join('/home/u', '.local', 'state', 'paperthin', 'n.log'));
- assert.equal(logFile('linux', { XDG_STATE_HOME: '/s' }, '/home/u', 'n'), join('/s', 'paperthin', 'n.log'));
- });
- test('npx runs as node plus npm npx-cli.js beside the node binary, never a bare npx.cmd without a shell', () => {
- const win = 'C:\\Program Files\\nodejs\\node.exe';
- const winCli = join(dirname(win), 'node_modules', 'npm', 'bin', 'npx-cli.js');
- assert.deepEqual(npxCommand(win, 'win32', (p) => p === winCli), { file: win, args: [winCli], shell: false });
- const posixCli = join(dirname('/usr/local/bin/node'), '..', 'lib', 'node_modules', 'npm', 'bin', 'npx-cli.js');
- assert.deepEqual(npxCommand('/usr/local/bin/node', 'linux', (p) => p === posixCli), { file: '/usr/local/bin/node', args: [posixCli], shell: false });
- assert.deepEqual(npxCommand(win, 'win32', () => false), { file: 'npx.cmd', args: [], shell: true });
- assert.deepEqual(npxCommand(process.execPath, process.platform).file, process.execPath, 'this machine resolves npx-cli.js');
- });
- test('usage errors exit 2 and help exits 0 through the junction', () => {
- assert.equal(run(['--help']).status, 0);
- for (const args of [[], ['frobnicate'], ['status', '--name', '../x'], ['status', '--home', scratch], ['uninstall', '--home', scratch], ['install', '--bogus']]) {
- const out = run(args);
- assert.equal(out.status, 2, args.join(' ') + ': ' + out.stdout + out.stderr);
- assert.match(out.stderr, /^re0-upgrade schedule: /);
- }
- assert.equal(run(['run', '--home', join(scratch, 'missing')]).status, 2, 'a --home that does not exist');
- });
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.