Compare commits

...
Author SHA1 Message Date
hermes cff3c8873e Merge pull request 'feat(firstmate): add explicit fm-oc2 launcher alias' (#22) from fm/dotfiles-firstmate-explicit-aliases into main 2026-11-16 09:30:48 -05:00
Lap Tran 2e2578ead8 no-mistakes(document): Note fm-oc2 alias in AGENTS.md and test header 2026-11-16 09:28:25 -05:00
Lap Tran 208e6741f3 feat(firstmate): add explicit fm-oc2 launcher alias and test all three aliases
fm and fm-oc2 both run oc2 from the firstmate home. fm-pi stays the
explicit Pi fallback. The launcher check now sources the generated
zshrc, runs each alias against spies, and asserts the working directory
and that fm and fm-oc2 launch identically.

The readme records that the aliases share one firstmate home and its
task records but keep separate chat histories, so the running primary
must be quit before starting the other.
2026-11-16 09:21:44 -05:00
hermes 53206f0a7b Merge pull request 'fix(firstmate): keep OpenCode 2 as the permanent fm launcher and route docs to Beam Free' (#21) from fm/dotfiles-opencode2-launch-models into main 2026-11-16 09:05:09 -05:00
Lap Tran 055c2eed91 no-mistakes(document): update crew-dispatch check description in readme 2026-11-15 23:05:29 -05:00
Lap Tran 0aa25b27f0 fix(firstmate): route documentation to Beam Free and guard the OpenCode 2 launcher
Add a documentation dispatch rule that uses opencode-go/beam-free while the
default workers stay on opencode-go/deepseek-v4.1-flash. Preserve the existing
UI rule and the Pi/GPT design exception.

Add live checks for the two operator-facing contracts:
- tests/fm-launcher.sh sources the zshrc that home-manager generates, runs fm
  with harmless pi and oc2 spies, and requires OpenCode 2 through oc2.
- tests/crew-dispatch.sh reads the dispatch config through firstmate's own
  bootstrap validator and asserts the default, documentation, UI, and design
  profiles.

Document the permanent fm decision, the no-mistakes model split, and the
minimal install procedure after merge.
2026-11-15 22:46:25 -05:00
hermes 5566b982c2 Merge pull request 'Add wimlib for splitting Windows install images to USB media' (#20) from fm/dotfiles-wimlib into main 2026-11-12 21:18:44 -05:00
Lap Tran f905570156 Add wimlib for splitting Windows install images to USB media 2026-11-12 19:55:00 -05:00
hermes 8b3aa7ef3b Merge pull request 'fix(home): always converge backpass and acpx to the latest npm release on rebuild' (#19) from fm/dotfiles-backpass-latest into main 2026-11-11 13:15:53 -05:00
Lap Tran 5bf1e05091 no-mistakes(document): correct stale backpass skip reference in comment 2026-11-11 13:08:13 -05:00
Lap Tran 9598499dcf no-mistakes(review): match real backpass and acpx launch paths 2026-11-11 12:49:41 -05:00
Lap Tran 9addc502fa no-mistakes(review): always install latest backpass and acpx on rebuild 2026-11-11 12:39:56 -05:00
Lap Tran d4e8c24b2f fix(home): converge backpass and acpx to the latest npm release on rebuild
Both npm globals were installed only when the binary was missing, so a
rebuild never moved them and the installed copies drifted behind the
registry. Read the installed version and the registry's latest instead,
and install only when they differ.

The running-process guard skips a package while one of its own processes
is alive, the registry lookup and the install warn and continue on
failure so the switch never aborts, and one shared function serves both
packages.
2026-11-11 12:29:27 -05:00
Lap Tran f21d20e1f7 fix(opencode): drop the dead automaton-guard plugin reference
The global OpenCode config pointed at ~/.automaton/plugins/automaton-guard, which no longer exists, so every OpenCode session logged Plugin failed to load. The automaton guard now ships only for Pi as automaton-guard-pi.
2026-11-08 22:29:47 -05:00
hermes a2c6ef7152 Merge pull request 'Point the fm alias at OpenCode 2 and keep Pi as fm-pi' (#18) from fm/dotfiles-fm-opencode2 into main 2026-11-08 21:19:08 -05:00
Lap Tran cdceb1eb09 Point the fm alias at OpenCode 2 and keep Pi as fm-pi
The primary firstmate session now starts through the isolated-config oc2
wrapper so it loads the tracked .opencode/plugins. fm-pi keeps the old Pi
launch until the new launcher is confirmed on the captain's machine.

Verified with a scratch FM_HOME: oc2 v2.2.6 loads all five firstmate
plugins, and the isolated config already exposes the primary model
opencode-go/deepseek-v4.1-flash.
2026-11-08 20:52:31 -05:00
hermes 5becfd69aa Merge pull request 'Make the linked Homebrew OpenCode build the only OpenCode install' (#17) from fm/opencode-retire-v1 into main 2026-11-08 18:55:45 -05:00
Lap Tran 78f2928132 no-mistakes(document): Correct rebuild.sh npm guard comment 2026-11-08 18:39:19 -05:00
Lap Tran 877ee5d163 Leave OpenCode unpinned so the linked brew build tracks latest
State the upgrade-on-rebuild behavior at the formula and drop version labels from the rebuild comments.
2026-11-08 18:30:32 -05:00
Lap Tran ac7888c9a5 no-mistakes(document): Drop pinned OpenCode version from docs 2026-11-08 18:29:13 -05:00
Lap Tran 2787bcc9ac no-mistakes(review): Remove stale OpenCode npm shims and fix oc2 hint 2026-11-08 18:13:24 -05:00
Lap Tran 3c7d2662a4 Retire OpenCode 1.x so Homebrew OpenCode 2 is the only install
Link the Homebrew opencode formula at /opt/homebrew/bin/opencode, drop the npm 1.x install from rebuild.sh, and remove leftover npm packages. Update the agent notes and home.nix comments to match.
2026-11-08 18:06:38 -05:00
hermes b03d71dc81 Merge pull request 'Run OpenCode 2 from the stable Homebrew formula' (#16) from fm/dotfiles-opencode2-stable-brew into main 2026-11-08 18:03:11 -05:00
Lap Tran d9d0a2e849 no-mistakes(document): Align OpenCode 2 docs with stable brew formula 2026-11-08 12:37:34 -05:00
Lap Tran 2a147c911a no-mistakes(review): Remove retired OpenCode 2 npm beta during rebuild 2026-11-08 12:23:20 -05:00
Lap Tran 1fda5c09b7 Run OpenCode 2 from the stable Homebrew formula
Declare the opencode formula with link = false so it never replaces the
npm-installed OpenCode 1.x CLI at /opt/homebrew/bin/opencode. Drop the npm
beta install from home.activation.opencode2, point home/bin/oc2 at the keg
binary, and correct the related notes.
2026-11-08 12:15:22 -05:00
hermes ec34fc005c Merge pull request 'Route design tasks to Pi GPT-6.1 Sol and set herdr dracula theme' (#15) from fm/dotfiles-design-dispatch-rule into main 2026-11-08 11:03:33 -05:00
Lap Tran f49ba2a84b no-mistakes(document): Document design dispatch rule in agent notes 2026-11-08 10:55:37 -05:00
Lap Tran c84f536c76 no-mistakes(review): Declare codex provider for the Pi design dispatch rule 2026-11-08 10:46:13 -05:00
Lap Tran 2005db22e6 feat(home): route design tasks to Pi GPT-6.1 Sol and set herdr dracula theme 2026-11-08 10:31:34 -05:00
hermes 766b2bbaeb Merge pull request 'Install pinned pstack skills on activation' (#14) from fm/dotfiles-pstack-skills-pin into main 2026-11-07 18:12:43 -05:00
Lap Tran 550c94d58a no-mistakes(document): Correct pinned pstack commit record claim 2026-11-07 18:11:37 -05:00
Lap Tran a58546900f docs(pstack): use neutral third-person wording
Describe the existing tdd skill and the skill tree without
second-person address or a firstmate role name.
2026-11-07 18:03:15 -05:00
Lap Tran 1fb1a23eea no-mistakes(document): Document pinned pstack skill install 2026-11-07 18:00:40 -05:00
Lap Tran d4fd08cabe feat(home): install pinned pstack skills on activation
Add home.activation.pstackSkills plus a pinned cursor/plugins fetch.
It replaces the eleven adopted skill directories in ~/.agents/skills on
every rebuild and leaves all other skills untouched. pstack's tdd copy
stays skipped because the captain's own tdd skill owns that name.
2026-11-07 17:42:21 -05:00
Lap Tran 1214e00300 Merge remote-tracking branch 'origin/main' 2026-11-07 17:27:33 -05:00
Lap Tran 1dc582d689 chore(pi): record Pi 1.5.0 runtime settings state 2026-11-07 17:27:33 -05:00
hermes 366d6bb97a Merge pull request 'rebuild.sh: update pi extensions on every rebuild' (#13) from fm/dotfiles-rebuild-pi-extensions-update into main 2026-11-07 10:20:29 -05:00
Lap Tran 4d0662b09e rebuild.sh: update pi extensions on every rebuild 2026-11-07 09:50:12 -05:00
Lap Tran e71f7089d3 feat(home): launch firstmate in Pi 2026-11-06 21:21:18 -05:00
Lap Tran e427a4079c Merge remote-tracking branch 'origin/main' 2026-11-06 21:10:59 -05:00
Lap Tran 633bbf35a0 feat(home): sync the OpenCode Go key after account switches 2026-11-06 21:10:54 -05:00
Lap Tran f7411c2ade rebuild.sh: update flake inputs on every rebuild 2026-11-06 18:04:05 -05:00
Lap Tran b4120aaf88 rebuild.sh: update no-mistakes on every rebuild 2026-11-06 17:59:55 -05:00
hermes baae0d960c Merge pull request 'feat(darwin): install CotEditor cask' (#12) from fm/dotfiles-coteditor-cask into main 2026-10-30 12:25:20 -04:00
Lap Tran 61c4f20fe9 feat(darwin): install CotEditor cask 2026-10-30 12:00:03 -04:00
Lap Tran 10f5811d7f feat(patches): reclip history cards match UI design; thumbnails persisted
History section now renders reclip's own card components (thumbnail,
serif title, meta line with date/size, Save/Transcript pill buttons).
Frontend passes the video thumbnail to /api/download so history cards
show real artwork; pre-thumbnail entries keep the placeholder icon.
2026-10-25 20:41:31 -04:00
Lap Tran b8773b8fc2 feat(patches): vendor reclip transcript+history patch (base 1d161d1)
Full patched app.py/index.html plus rebaseable diff. Deployed via
bind-mounts from the share (documents/reclip/); this repo is the
versioned source of truth so container/image updates and new machines
cannot lose the patch. Rebase instructions in patches/reclip/README.md.
2026-10-25 16:02:44 -04:00
Lap Tran b4dfbd7540 chore: remove yt-transcribe-watcher 2026-10-25 15:49:56 -04:00
Lap Tran 62923e8344 refactor: drop yt-transcribe-watcher; transcripts belong at reclip download time
Per the captain: no watcher as primary. reclip gets the transcript patch
(bind-mounted app.py/index.html override on Unraid, see
data/documents/reclip/DEPLOY.md); yt-transcribe stays as the manual
fallback and for captionless media. Launchd agent removed.
2026-10-25 15:15:23 -04:00
Lap Tran 9821fde02b feat(home): yt-transcribe tool + watcher (captions-first, X via gallery-dl)
- yt-transcribe: YouTube/X/local-file transcription. Captions first
  (yt-dlp; X serves auto-captions via its twitter extractor), Whisper
  fallback (whisper-cli reusing OpenSuperWhisper's ggml model), reclip
  download reuse, INDEX.md + --list/--index for id->title mapping.
- watcher: launchd every 5 min over media/video on the Unraid share,
  sidecar .txt per download, marker-guarded, stale-marker purge.
- Code executes from the nix store via stable ~/.local/bin symlinks:
  launchd EPERMs on SMB exec; share stays data-only.
- brews: declare yt-dlp, whisper.cpp, gallery-dl (cleanup=zap removes
  undeclared formulas).
2026-10-25 13:08:25 -04:00
Lap Tran 9264bd0adf Revert "opencode2: hide OpenCode Console models after its key expired"
The Console key never expired: it still authenticates and the OpenCode
provider is reconnected, so the free models work again. Restore the
opencode provider and its free models in the OpenCode 2 config.

This reverts commit 14d6b0ecc145539e11656c5176a1b331ab4836a8.
2026-10-25 13:06:47 -04:00
Lap Tran 9cb78880ce opencode2: hide OpenCode Console models after its key expired
Deny provider.use for opencode and disable its free models, so the model
picker no longer offers models that need the removed Console credential.
2026-10-25 13:06:47 -04:00
hermes 1cd03f93c6 Merge pull request 'feat(home): add repeatable security-audit Docker sandbox' (#11) from fm/dotfiles-audit-sandbox into main 2026-10-25 13:03:31 -04:00
Lap Tran 8a35b39aa3 no-mistakes(document): Update stale security-audit sandbox note in home.nix 2026-10-25 12:49:13 -04:00
Lap Tran 78424d2778 no-mistakes(test): Verify timeout enforces limit before sandbox exec 2026-10-25 12:43:36 -04:00
Lap Tran 59bdaa6e2a no-mistakes(review): Remove silent stale run-dir deletion from start 2026-10-25 12:33:40 -04:00
Lap Tran c45d61387f no-mistakes(review): Fix stop guard order, accumulate EXCLUDE lines, drop run-parent override 2026-10-25 12:29:39 -04:00
Lap Tran 76ff344ff5 feat(home): add security-audit-sandbox wrapper 2026-10-25 12:22:48 -04:00
hermes a2968cdcef Merge pull request 'Put /usr/bin on the security-audit activation PATH' (#10) from fm/dotfiles-security-audit-git-path into main 2026-10-25 11:22:47 -04:00
21 changed files with 3409 additions and 78 deletions

No files matched your search

+3 -3
View File
@@ -8,9 +8,9 @@ Deliberate decisions in this repo - do NOT silently revert them:
- Pi is managed the same way: `home/.pi/agent/{settings,models}.json`, `themes/`, and custom extensions (`terminal-status-title`, `calm`). Do not symlink the whole `~/.pi/agent` tree - sessions, auth, npm cache, and herdr's `extensions/herdr-agent-state.ts` stay live.
- herdr stores runtime state beside its config, so `~/.config/herdr` stays a real directory and only `config.toml` is symlinked; `home.activation.herdrConfigDir` migrates the old whole-directory symlink and clears leaked artifacts. Do not symlink the whole directory - rationale and artifact list are in `home.nix`.
- Codex runs on the OpenCode Go subscription. The ChatGPT app owns and rewrites the live `~/.codex/config.toml`, so it is NOT symlinked; `home.activation.codexOpenCodeGo` merges the repo fragment `home/.codex/config.toml` into it on every rebuild, and the app's own sections (`[desktop]`, `[plugins]`, `[mcp_servers]`, ...) survive. Auth is command-backed via `~/.local/bin/opencode-go-token` (prints the key from the opencode store), so `~/.codex/auth.json` stays in ChatGPT mode and ChatGPT sign-in coexists with Go. Only Go models that speak the Responses API work (`deepseek-v4.1-flash`, `gpt-6-luna`, `gpt-5.6-luna`, `grok-4.7/4.6`); GLM/Kimi/MiMo/LongCat are chat-completions-only and need a proxy. Desktop Codex is now the `chatgpt` cask - do not use the deprecated `codex-app` cask.
- firstmate lives at `~/Documents/firstmate` as a mutable git clone (not in the Nix store). `home.activation.firstmate` clones it if missing and seeds `config/backend=herdr` + `config/crew-harness=opencode` only when those files are absent. Crew routing is `home/.config/firstmate/crew-dispatch.json` (symlinked in): per the captain's order 2026-10-21, every coding crewmate and scout uses `opencode` + `opencode-go/deepseek-v4.1-flash` through the OpenCode CLI. The free `deepseek-v4.1-flash-free` order of 2026-10-20 resumes when that lane resets. The validation pipeline stays on Pi with `opencode-go/deepseek-v4.1-flash` steps and the `opencode-go/glm-5.3-flash` reviewer. Avoid the `muse-spark-*-contributor` models, which train on prompts, and the `exo-free`, `mimo-*-free`, and `nemotron-*-free` models, whose data may be used to improve the model. `cat-jam-free` retains for 30 days. Crews inherit the primary's OpenCode login through the spawn-owned symlink (the isolated worker data root links the primary `<XDG_DATA_HOME>/opencode/auth.json`; no `~/.pi/agent/auth.json` reliance). Launch with shell alias `fm` (`cd` + OpenCode 2 via `~/.local/bin/oc2`); the primary stays OpenCode 2, only crews run on the opencode harness. Self-update via `/updatefirstmate`, not rebuild.
- OpenCode 2 is the firstmate primary. It is not a Homebrew formula: install `@opencode-ai/cli@beta` with Homebrew's npm (`home.activation.opencode2`). Launch through `home/bin/oc2` so `OPENCODE_CONFIG` stays at `home/.config/opencode2/opencode.json` and cannot rewrite OpenCode 1.x's `~/.config/opencode`. Do not add a brew `opencode` / `opencode2` formula; `zap` would fight the npm install. firstmate harness detection matches `*opencode*`, so the `opencode2` process name still classifies as OpenCode.
- Shell aliases: `cc` (Claude skip-permissions), `co` (Codex full-auto), `gb` (Grok --yolo), `fm` (firstmate via OpenCode 2), `oc2` (OpenCode 2, isolated). They are intentional high-agency shortcuts.
- firstmate lives at `~/Documents/firstmate` as a mutable git clone (not in the Nix store). `home.activation.firstmate` clones it if missing and seeds `config/backend=herdr` + `config/crew-harness=opencode` only when those files are absent. Crew routing is `home/.config/firstmate/crew-dispatch.json` (symlinked in): per the captain's order 2026-10-21, coding crewmates and scouts use `opencode` + `opencode-go/deepseek-v4.1-flash` through the OpenCode CLI. Design, architecture, and design-review tasks are the exception: the file's first rule sends them to Pi with `openai-codex/gpt-6.1-sol` at `xhigh`, and implementation tasks re-resolve their profile instead of keeping that model. The free `deepseek-v4.1-flash-free` order of 2026-10-20 resumes when that lane resets. The validation pipeline stays on Pi with `opencode-go/deepseek-v4.1-flash` steps and the `opencode-go/glm-5.3-flash` reviewer. Avoid the `muse-spark-*-contributor` models, which train on prompts, and the `exo-free`, `mimo-*-free`, and `nemotron-*-free` models, whose data may be used to improve the model. `cat-jam-free` retains for 30 days. Crews inherit the primary's OpenCode login through the spawn-owned symlink (the isolated worker data root links the primary `<XDG_DATA_HOME>/opencode/auth.json`; no `~/.pi/agent/auth.json` reliance). Launch with shell alias `fm` (`cd` + the `oc2` wrapper, so the primary runs OpenCode 2 on the OpenCode Go subscription and loads firstmate's `.opencode/plugins` by working directory), while crews run on the opencode harness unless a dispatch rule selects another harness. `oc2` remains the isolated-config OpenCode launcher, and `fm-pi` stays only as the explicit Pi fallback now that the OpenCode 2 launcher is the confirmed default. Self-update via `/updatefirstmate`, not rebuild.
- OpenCode is one install: the stable Homebrew `opencode` formula, linked so `/opt/homebrew/bin/opencode` is that build. It is both the firstmate crew harness and the `oc2` binary. `oc2` only isolates the config: `OPENCODE_CONFIG` stays at `home/.config/opencode2/opencode.json` and cannot rewrite `~/.config/opencode`, and `OPENCODE2_BIN` overrides the binary. firstmate harness detection matches `*opencode*`, so it still classifies as OpenCode.
- Shell aliases: `cc` (Claude skip-permissions), `co` (Codex full-auto), `gb` (Grok --yolo), `fm` / `fm-oc2` (firstmate via OpenCode 2), `fm-pi` (firstmate via Pi fallback), `oc2` (OpenCode with isolated config). They are intentional high-agency shortcuts.
- OpenSuperWhisper is installed by the `opensuperwhisper` cask, and `home.activation.openSuperWhisper` downloads its Whisper model (`ggml-large-v3-turbo.bin` under the app's Application Support directory, never the Nix store) and seeds the model selection only when it is missing or dangling. All other app settings (trigger, language, paste behavior) belong to the app and must not be rewritten by a rebuild, so `modifierOnlyHotkey = rightOption` on this machine stays the effective trigger. Microphone/Accessibility/Input Monitoring grants stay manual because macOS TCC cannot be declarative; do not kill a running app to apply defaults. The model is local-only.
## Maintaining this file
+11 -1
View File
@@ -45,6 +45,7 @@
onActivation.extraFlags = [ "--force" ];
brews = [
"ffmpeg"
"gallery-dl" # X/Twitter media download for yt-transcribe (X video needs auth yt-dlp can't get)
"gh"
"herdr"
# Client-only psql for read-only DB investigation. libpq is the keg-only
@@ -53,17 +54,24 @@
# resolves on the normal PATH. No server, service, database, or
# connection is configured.
{ name = "libpq"; link = true; }
"node" # required: opencode2 is an npm global, not a Homebrew formula
"node" # required: backpass and acpx are npm globals, not formulae
# Unpinned: onActivation.upgrade refreshes formulae each rebuild, so the
# linked binary tracks the latest opencode release. Crew harness and oc2.
"opencode"
"pi-coding-agent"
"tea" # Gitea CLI - PRs for firstmate crewmates on unraid.local:3003
"tmux"
"treehouse"
"whisper-cpp" # whisper-cli for yt-transcribe (reuses OpenSuperWhisper's model)
"wimlib" # wimlib-imagex: split install.wim to fit FAT32 for Windows USB media
"yt-dlp" # yt-transcribe engine; same engine reclip runs in its container
];
casks = [
# Codex desktop home: the standalone Codex.app was folded into the ChatGPT
# app (2026-07); the deprecated `codex-app` cask must not be used.
"chatgpt"
"codex" # Codex CLI; shares ~/.codex/config.toml with the desktop app
"coteditor" # plain-text editor; cask id is one lowercase word
"docker-desktop"
"grok-build"
"opensuperwhisper" # local Whisper dictation; model seed in home.nix
@@ -72,5 +80,7 @@
"wezterm"
];
};
launchd.user.agents = { };
}
Generated
+16 -16
View File
@@ -3,16 +3,16 @@
"brew-src": {
"flake": false,
"locked": {
"lastModified": 1788591592,
"narHash": "sha256-NbwVKwKLFl0oXub7oPjvmDaOygCtV2oboeKTu4xXFTk=",
"lastModified": 1793000687,
"narHash": "sha256-8mCor0DDjNhi+0e+FllfqiMABujBl+/RxYW+wgMpcto=",
"owner": "Homebrew",
"repo": "brew",
"rev": "08e85c4e42f5d8f1ea17c36cb59cf61c2ccb26c3",
"rev": "c6069d2a943b71b0a90d91fc1ac93cb9c1634dcc",
"type": "github"
},
"original": {
"owner": "Homebrew",
"ref": "6.0.22",
"ref": "7.0.11",
"repo": "brew",
"type": "github"
}
@@ -24,11 +24,11 @@
]
},
"locked": {
"lastModified": 1789267039,
"narHash": "sha256-LWiBv9yAYFi2LPbUhDGHPGKYskJQjj2fw12OlyO1uQo=",
"lastModified": 1792818383,
"narHash": "sha256-199i7ubVSXTMl+0AAlL7cVCXSjcI+jWByMcimYjeMX0=",
"owner": "nix-community",
"repo": "home-manager",
"rev": "ec172013fa62135f58fb58dd17ae9651e8f39727",
"rev": "24f2190587513b9c2f73db112a17844ae912d965",
"type": "github"
},
"original": {
@@ -45,11 +45,11 @@
]
},
"locked": {
"lastModified": 1783744694,
"narHash": "sha256-2cp6N3rrwnGYLTx9l6N+NI+kwrCWxvJUbj5WJhvB29A=",
"lastModified": 1792800221,
"narHash": "sha256-53jIZEWNh96irEXhsMZFoNhLJgGSU3nYl1i4wFQHAsU=",
"owner": "nix-darwin",
"repo": "nix-darwin",
"rev": "c3e90c89649b07d1a96e4b9dd6cd0d6e44b91a74",
"rev": "d31953cf55f9027a56e9be938daf5db8c5655663",
"type": "github"
},
"original": {
@@ -64,11 +64,11 @@
"brew-src": "brew-src"
},
"locked": {
"lastModified": 1788981439,
"narHash": "sha256-fEaFq0XgpgWFPLfpq1UK4/8ylHd2T0+fo6O3hKz1LUM=",
"lastModified": 1793543863,
"narHash": "sha256-oDYLVD8KGT/M57c8HziYSSj0le4wCyA+jZ7+/qUS91M=",
"owner": "zhaofengli",
"repo": "nix-homebrew",
"rev": "09a921d0181146cf6163ec2cc1db7b6fd539a885",
"rev": "52bc87da3f30c2261a6d1cfef3c892097b53daeb",
"type": "github"
},
"original": {
@@ -79,11 +79,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1789485310,
"narHash": "sha256-VsDMTLSkAAJmbNha6sGNzlF33X7RESWLl3SnjDQu+4U=",
"lastModified": 1793976852,
"narHash": "sha256-bWDN3JZcE9ovYoaD0/6WYbMtXYpUu0vd5onpK0pc/SE=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "0c32f40fe3e2a9adfc427fd5abc061a31043ea44",
"rev": "57f1c8965649ce5bcac5118a0d2e41f1fbdc56e5",
"type": "github"
},
"original": {
+157 -34
View File
@@ -4,6 +4,35 @@ let
home = config.home.homeDirectory;
dotfiles = "${home}/.dotfiles";
firstmateHome = "${home}/Documents/firstmate";
# yt-transcribe: captions-first transcription for YouTube/X/local media.
# Source of truth is this repo's home/bin scripts; nix copies them into the
# store so every context (launchd, shells) executes from local disk. Stable
# ~/.local/bin symlinks below survive store-path changes between rebuilds.
ytTranscribe = pkgs.runCommand "yt-transcribe" { } ''
install -Dm755 ${./home/bin/yt-transcribe} $out/bin/yt-transcribe
'';
# Pinned pstack skills tree (cursor/plugins). `tdd` is deliberately absent:
# an existing user-level tdd skill owns that name. See firstmate's
# docs/adopted-skills.md for why these eleven skills exist.
pstackSkillNames = [
"statechart"
"create-verification-skill"
"maintain-verification-skill"
"correct"
"benchmark-checklist"
"architect"
"technical-writing"
"unslop"
"recall"
"ketchup"
"blast-radius"
];
pstackSkills = pkgs.fetchFromGitHub {
owner = "cursor";
repo = "plugins";
rev = "6b0300214a09fd6029cfb7077043125758cd1fd2";
hash = "sha256-TDuZ1v+taPdqyvvCs1VHUjtpSy8zHxhQKJv/kIPTpK8=";
};
in
{
@@ -24,7 +53,7 @@ in
nerd-fonts.hack
ngrok # reverse TCP tunnel so the phone can SSH in over cellular (unfree)
beets # music tagger / library organizer + navidrome sync plugin
];
] ++ [ ytTranscribe ];
fonts.fontconfig.enable = true;
home.sessionVariables.EDITOR = "nvim";
@@ -34,6 +63,11 @@ in
syntaxHighlighting.enable = true; # commands turn green when valid
initContent = ''
bindkey '^f' autosuggest-accept
# Keep the OpenCode Go CLI, Pi, no-mistakes, and Hermes key aligned with
# the desktop app login after an account switch.
if [ -x "$HOME/.local/bin/opencode-go-key-sync" ]; then
"$HOME/.local/bin/opencode-go-key-sync" >/dev/null 2>&1 || true
fi
'';
shellAliases = {
".." = "cd ..";
@@ -46,11 +80,21 @@ in
cc = "claude --dangerously-skip-permissions";
co = "codex --full-auto";
gb = "grok --yolo";
# firstmate primary session via OpenCode 2 (isolated config; crewmates = OpenCode)
# firstmate primary session in OpenCode 2 on the OpenCode Go subscription,
# launched through the isolated-config oc2 wrapper; crewmates = OpenCode by
# default. Permanent since 2026-11-15: fm-pi stays only as the explicit Pi
# fallback, never as the default launcher. fm-oc2 is the explicit
# OpenCode 2 name and stays byte-identical to fm.
fm = "cd ${firstmateHome} && exec ${home}/.local/bin/oc2";
fm-oc2 = "cd ${firstmateHome} && exec ${home}/.local/bin/oc2";
fm-pi = "cd ${firstmateHome} && exec pi";
oc2 = "${home}/.local/bin/oc2";
# Sync ~/Music into the beets library on Unraid (requires NAS mounted).
sync-music = "~/.local/bin/sync-music";
# Transcribe a YouTube/X URL or a local media file. Tool code lives in
# this repo (nix store); the Unraid share holds only data — mount it at
# /Volumes/data (or set YT_SHARE_ROOT for a different mount point).
yt-transcribe = "${home}/.local/bin/yt-transcribe";
# Start the reverse tunnel so you can SSH into this Mac from your phone.
# Run once when you go remote: `ngrok-tunnel`. Reads authtoken from
# ~/.config/ngrok (set once per machine with `ngrok config add-authtoken <TOK>`)
@@ -157,6 +201,12 @@ in
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/bin/opencode-go-token";
force = true;
};
# Copy the desktop app's OpenCode Go login into the CLI, Pi, and Hermes stores.
# The app writes opencode.db only; those tools read auth.json and .env.
home.file.".local/bin/opencode-go-key-sync" = {
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/bin/opencode-go-key-sync";
force = true;
};
# Codex 0.160+ profiles live in $CODEX_HOME/<name>.config.toml. The app does not
# touch these, so they can be symlinked normally.
home.file.".codex/luna.config.toml" = {
@@ -175,7 +225,7 @@ in
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/.config/opencode/skills";
force = true;
};
# OpenCode 2 isolated config - never share ~/.config/opencode with 1.x
# OpenCode isolated config - keep it separate from ~/.config/opencode
home.file.".config/opencode2/opencode.json" = {
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/.config/opencode2/opencode.json";
force = true;
@@ -188,6 +238,16 @@ in
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/bin/oc2";
force = true;
};
home.file.".local/bin/security-audit-sandbox" = {
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/bin/security-audit-sandbox";
force = true;
};
# Stable symlink for yt-transcribe: shells exec it from local disk. The
# repo's home/bin script is the source of truth — a repo edit takes effect
# on the next rebuild; the Unraid share holds only data.
home.file.".local/bin/yt-transcribe" = {
source = "${ytTranscribe}/bin/yt-transcribe";
};
home.file.".grok/AGENTS.md" = {
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/AGENTS.md";
force = true;
@@ -315,23 +375,9 @@ in
"$HOME/.codex/config.toml"
'';
# OpenCode 2 is not on Homebrew (beta). Install via Homebrew's npm, never
# Nix's npm (EACCES on the store). Skip when already present so a rebuild
# does not pull a new beta under a live TUI. Activation blocks are inlined
# into one flat script, so never `exit 0` here: that would skip every later
# block (securityAuditSkill, setupLaunchAgents, syncMusic).
home.activation.opencode2 = lib.hm.dag.entryAfter [ "writeBoundary" ] ''
set -euo pipefail
npm=/opt/homebrew/bin/npm
bin=/opt/homebrew/bin/opencode2
if [ ! -x "$bin" ]; then
if [ ! -x "$npm" ]; then
echo "opencode2: /opt/homebrew/bin/npm missing (declare node in homebrew.brews)" >&2
exit 1
fi
"$npm" install -g --allow-scripts=@opencode-ai/cli @opencode-ai/cli@beta
fi
'';
# OpenCode is the stable Homebrew `opencode` formula, linked in
# configuration.nix; home/bin/oc2 runs its keg binary with an isolated config.
# Nothing to install here.
# backpass (kunchenguid/backpass) - gradient descent for agent memory: reads
# the transcript stores of the harnesses this config already declares
@@ -340,9 +386,15 @@ in
# to a harness you already authenticated, so acpx is a hard runtime dep and
# must be on PATH. Homebrew node v26 satisfies backpass (>= 22.5) and acpx
# (>= 22.13). Neither is a Homebrew formula: install via Homebrew's npm,
# never Nix's npm (EACCES on the store). Skip-if-present like opencode2 so a
# rebuild never pulls a new version mid-session; refresh manually with
# /opt/homebrew/bin/npm update -g backpass acpx
# never Nix's npm (EACCES on the store). Both track the registry's latest on
# every rebuild: for each package the installed version is compared with the
# published one, and an install runs only when they differ, so a current copy
# is left alone and a stale one converges. The switch therefore always brings
# both packages to the latest published version, whether or not a process of
# that package is running: a running process keeps the code it already loaded
# and picks the new version up at its next start, so the switch prints that as
# a notice and still installs. The registry lookup and the install are optional
# steps - a failure there warns and the switch continues.
home.activation.backpass = lib.hm.dag.entryAfter [ "writeBoundary" ] ''
set -euo pipefail
# Activation PATH lacks /opt/homebrew/bin, so npm's `#!/usr/bin/env node`
@@ -354,12 +406,45 @@ in
echo "backpass: /opt/homebrew/bin/npm missing (declare node in homebrew.brews)" >&2
exit 1
fi
if [ ! -x /opt/homebrew/bin/acpx ]; then
"$npm" install -g acpx@latest
fi
if [ ! -x /opt/homebrew/bin/backpass ]; then
"$npm" install -g backpass
fi
# Converge one npm global to the registry's latest. $1 is the package name,
# $2 is the pgrep pattern matching that package's command line as launched
# from the global bin, used only to explain that a live process keeps its
# loaded code. Every optional failure returns 0, so `set -e` never aborts the
# switch and later blocks still run.
converge_npm_global() {
pkg="$1"
live="$2"
# Installed version from npm's own global record; empty means absent. The
# `|| true` keeps `set -e` quiet when npm exits non-zero over extraneous
# packages.
installed="$("$npm" ls -g --depth=0 2>/dev/null | sed -n "s/.*[[:space:]]$pkg@\([^[:space:]]*\).*/\1/p" | head -n 1 || true)"
# Registry lookup is optional: an offline or timed-out lookup warns and
# keeps the installed copy.
latest="$("$npm" view "$pkg" version --fetch-timeout=15000 --fetch-retries=1 2>/dev/null | tr -d "[:space:]" || true)"
if [ -z "$latest" ]; then
echo "$pkg: cannot read the latest version from the npm registry (offline?) - keeping the installed copy, rebuild continues" >&2
return 0
fi
if [ "$installed" = "$latest" ]; then
echo "$pkg: already at $latest"
else
current="$installed"
[ -n "$current" ] || current=none
echo "$pkg: updating $current -> $latest"
# Install failure is optional too: warn and keep the old copy.
if "$npm" install -g "$pkg@$latest"; then
echo "$pkg: installed $latest"
else
echo "$pkg: install of $latest failed - keeping the installed copy, rebuild continues" >&2
return 0
fi
fi
if pgrep -f "$live" >/dev/null 2>&1; then
echo "$pkg: a running process keeps the code it already loaded - $latest takes effect at its next start" >&2
fi
}
converge_npm_global backpass "/opt/homebrew/bin/backpass"
converge_npm_global acpx "/opt/homebrew/bin/acpx"
'';
# kunchenguid/no-mistakes gate (git push no-mistakes) - declarative install + daemon + global config
@@ -414,11 +499,13 @@ in
# ~/.config/opencode/skills: home-manager owns that path with force = true and
# mkOutOfStoreSymlink into the mutable dotfiles checkout, so a rebuild would
# clobber the CLI's link and CLI writes would land in the git checkout. Skip
# when installed, like opencode2/backpass, so a rebuild never pulls a new skill
# version mid-session. The skill's own README still requires an OS-enforced
# sandbox before it may run target-controlled builds, tests, browsers, or
# fuzzers; this machine has none, so those leads stay `needs_validation`.
# Install and refresh commands, plus the sandbox note, are in readme.md.
# when installed, unlike backpass which tracks the latest release, so a
# rebuild never pulls a new skill version mid-session. The skill's own README
# still requires an OS-enforced sandbox before it may run target-controlled
# builds, tests, browsers, or fuzzers. That sandbox is
# home/bin/security-audit-sandbox; without it, those leads stay
# `needs_validation`.
# Install and refresh commands, plus the sandbox docs, are in readme.md.
home.activation.securityAuditSkill = lib.hm.dag.entryAfter [ "writeBoundary" ] ''
set -euo pipefail
# Activation PATH lacks /opt/homebrew/bin, so npx's `#!/usr/bin/env node`
@@ -448,6 +535,42 @@ in
fi
'';
# pstack skills installed from the pinned `pstackSkills` source above (folder
# pstack/skills). The record of why these eleven skills exist is firstmate's
# docs/adopted-skills.md. They live only in ~/.agents/skills, which is outside
# git and Nix, so this block restores them on a fresh machine.
# `tdd` is skipped on purpose: an existing user-level tdd skill owns that
# name, so the pstack copy is never installed.
# Each run replaces only the eleven target directories; every other skill,
# including an existing tdd skill, stays untouched. No `exit 0` here,
# because activation blocks are inlined into one flat script, so an early
# exit would skip the blocks that follow.
home.activation.pstackSkills = lib.hm.dag.entryAfter [ "writeBoundary" ] ''
set -euo pipefail
src="${pstackSkills}/pstack/skills"
dest="$HOME/.agents/skills"
if [ ! -d "$src" ]; then
echo "pstackSkills: pinned source tree missing at $src" >&2
exit 1
fi
mkdir -p "$dest"
for name in ${lib.concatStringsSep " " pstackSkillNames}; do
if [ ! -d "$src/$name" ]; then
echo "pstackSkills: pinned source is missing skill $name" >&2
exit 1
fi
# Remove first so a renamed source file never lingers in the old copy.
rm -rf "$dest/$name"
if ! cp -R "$src/$name" "$dest/$name"; then
echo "pstackSkills: failed to install $name" >&2
exit 1
fi
# Store files are read-only; make the installed copy writable again.
chmod -R u+w "$dest/$name"
done
echo "pstackSkills: installed ${toString (lib.length pstackSkillNames)} pinned skills into $dest"
'';
# OpenSuperWhisper - local voice-first prompting (cask in configuration.nix).
# The app reads its model from its own Application Support directory, so the
# 1.6 GB Whisper model is downloaded here once and kept outside the Nix store.
+19
View File
@@ -1,5 +1,15 @@
{
"rules": [
{
"when": "Design, architecture, architectural review, or design review tasks. This includes product design, UI/UX design, system design, and design investigations. For design tasks with screenshots or other image context, this rule takes precedence over the UI implementation rule. Ordinary implementation and routine code validation do not match this rule. When a task moves from design to implementation, resolve the implementation profile again rather than retaining this model for continuity.",
"use": {
"harness": "pi",
"model": "openai-codex/gpt-6.1-sol",
"effort": "xhigh",
"provider": "codex"
},
"why": "Captain's order: use GPT-6.1 Sol through openai-codex in Pi for design and architectural review tasks. Other task types retain their existing profiles."
},
{
"when": "UI work where supplied screenshots or other image context materially affect the implementation or verification.",
"use": [
@@ -10,6 +20,15 @@
}
],
"why": "Captain's order 2026-10-21: paid Go for every crewmate and scout after the free lane hit 'Free usage exceeded' with a 10.5 hour retry, which ended five sessions in forty minutes. The free deepseek-v4.1-flash-free order of 2026-10-20 resumes when that lane resets; paid Go had 5 percent of its monthly window left, projected empty 2026-10-22T05:43Z."
},
{
"when": "Documentation tasks: writing, updating, or reviewing documentation, docs, READMEs, or technical writing.",
"use": {
"harness": "opencode",
"model": "opencode-go/beam-free",
"provider": "opencode-go"
},
"why": "Captain's order 2026-11-15: documentation tasks use the free beam-free model to conserve paid quota."
}
],
"default": [
+4
View File
@@ -16,3 +16,7 @@ copy_mode = "prefix+y" # herdr's copy-mode entry key; copy-mode's own internal
[ui]
# Agents panel order: explicit choice of "spaces" (grouped by space, the default) over "priority".
agent_panel_sort = "spaces"
[theme]
name = "dracula"
auto_switch = false
-1
View File
@@ -80,7 +80,6 @@
}
}
},
"plugin": ["/Users/laptran/.automaton/plugins/automaton-guard"],
"command": {
"no-mistakes": {
"description": "Validate code changes through the no-mistakes pipeline",
+7 -3
View File
@@ -1,5 +1,5 @@
{
"lastChangelogVersion": "1.0.4",
"lastChangelogVersion": "1.5.0",
"theme": "rose-pine-moon",
"defaultProvider": "opencode-go",
"defaultModel": "deepseek-v4.1-flash",
@@ -33,5 +33,9 @@
"quietStartup": true,
"steeringMode": "all",
"followUpMode": "all",
"collapseChangelog": true
}
"collapseChangelog": true,
"extensionChangelogVersions": {
"{\"source\":\"npm:pi-web-access@0.36.0\",\"scope\":\"user\"}": "0.36.0",
"{\"source\":\"git:github.com/algal/pi-openai-server-compaction@c6d593087709e9481223dc6c6c2269b371b5e055\",\"scope\":\"user\"}": "0.1.0"
}
}
+5 -5
View File
@@ -1,14 +1,14 @@
#!/usr/bin/env bash
# Launch OpenCode 2 with an isolated config so it cannot rewrite
# ~/.config/opencode/opencode.json (OpenCode 1 / firstmate).
# Launch OpenCode with an isolated config so it cannot rewrite
# ~/.config/opencode/opencode.json (firstmate).
set -euo pipefail
bin="${OPENCODE2_BIN:-/opt/homebrew/bin/opencode2}"
bin="${OPENCODE2_BIN:-/opt/homebrew/opt/opencode/bin/opencode}"
cfg="${OPENCODE_CONFIG:-$HOME/.config/opencode2/opencode.json}"
if [ ! -x "$bin" ]; then
echo "oc2: opencode2 not installed. Rebuild, or run:" >&2
echo " /opt/homebrew/bin/npm install -g --allow-scripts=@opencode-ai/cli @opencode-ai/cli@beta" >&2
echo "oc2: stable opencode not installed. Rebuild, or run:" >&2
echo " brew install opencode" >&2
exit 1
fi
if [ ! -e "$cfg" ]; then
+178
View File
@@ -0,0 +1,178 @@
#!/usr/bin/env python3
"""Copy the OpenCode Go key from the desktop app store into the CLI auth files.
The OpenCode desktop app writes its login to
<XDG_DATA_HOME>/opencode/opencode.db (table credential, integration opencode-go)
but the opencode CLI, firstmate workers, pi, and no-mistakes read
<XDG_DATA_HOME>/opencode/auth.json (opencode-go.key)
~/.pi/agent/auth.json (opencode-go.key)
After an account switch the app store is current and those JSON files still hold
the old key, so workers and the validation pipeline fail with a usage or auth
error. Run this after switching accounts.
Safety:
* The app credential is the source only when it is newer than the target file.
* If a target file is newer than the app credential, it is left alone and the
command reports a conflict instead of overwriting a manual login.
* The key is never printed.
Exit status: 0 in sync or updated, 2 conflict, 1 no source credential.
"""
import argparse
import json
import os
import sqlite3
import sys
import tempfile
import time
def data_home():
return os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share")
def app_credential():
db = os.path.join(data_home(), "opencode", "opencode.db")
if not os.path.exists(db):
return None
con = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
try:
row = con.execute(
"select value, time_updated from credential"
" where integration_id='opencode-go' order by time_updated desc limit 1"
).fetchone()
finally:
con.close()
if not row:
return None
try:
payload = json.loads(row[0])
except Exception:
return None
key = payload.get("key") if isinstance(payload, dict) else None
if not key:
return None
return key, int(row[1]) / 1000.0
def read_target(path):
with open(path) as fh:
data = json.load(fh)
entry = data.get("opencode-go")
key = entry.get("key") if isinstance(entry, dict) else None
return data, key
def write_target(path, data):
directory = os.path.dirname(path)
fd, tmp = tempfile.mkstemp(dir=directory, prefix=".auth.", suffix=".json")
try:
with os.fdopen(fd, "w") as fh:
json.dump(data, fh)
os.chmod(tmp, 0o600)
os.replace(tmp, path)
finally:
if os.path.exists(tmp):
os.unlink(tmp)
def target_paths():
return [
os.path.join(data_home(), "opencode", "auth.json"),
os.path.expanduser("~/.pi/agent/auth.json"),
]
def sync_hermes(source_key, check):
"""Update OPENCODE_GO_API_KEY in the Hermes env file when it differs."""
path = os.path.expanduser("~/.hermes/.env")
if not os.path.exists(path):
return 0
with open(path) as fh:
lines = fh.readlines()
current = None
for line in lines:
stripped = line.rstrip("\n")
if stripped.startswith("OPENCODE_GO_API_KEY="):
current = stripped.split("=", 1)[1]
break
if current is None:
return 0
label = "hermes/.env"
if current == source_key:
print(f"{label}: in sync")
return 0
if check:
print(f"{label}: stale, would update", file=sys.stderr)
return 2
rewritten = []
for line in lines:
if line.startswith("OPENCODE_GO_API_KEY="):
rewritten.append(f"OPENCODE_GO_API_KEY={source_key}\n")
else:
rewritten.append(line)
with open(path, "w") as fh:
fh.writelines(rewritten)
os.chmod(path, 0o600)
print(f"{label}: updated")
return 0
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--check",
action="store_true",
help="report drift and exit 2 instead of updating",
)
args = parser.parse_args()
source = app_credential()
if not source:
print(
"opencode-go-key-sync: no opencode-go credential in the app store",
file=sys.stderr,
)
return 1
source_key, source_time = source
status = 0
for path in target_paths():
label = os.path.basename(os.path.dirname(path)) + "/" + os.path.basename(path)
if not os.path.exists(path):
print(f"{label}: missing, skipped", file=sys.stderr)
status = max(status, 2)
continue
data, current_key = read_target(path)
if current_key == source_key:
print(f"{label}: in sync")
continue
target_time = os.path.getmtime(path)
if target_time > source_time:
print(
f"{label}: has a newer key than the app store, left unchanged"
" (log in again in the app, or update this file by hand)",
file=sys.stderr,
)
status = max(status, 2)
continue
if args.check:
print(f"{label}: stale, would update", file=sys.stderr)
status = max(status, 2)
continue
entry = data.get("opencode-go")
if not isinstance(entry, dict):
entry = {"type": "api"}
entry["key"] = source_key
data["opencode-go"] = entry
write_target(path, data)
print(f"{label}: updated")
status = max(status, sync_hermes(source_key, args.check))
return status
if __name__ == "__main__":
raise SystemExit(main())
+576
View File
@@ -0,0 +1,576 @@
#!/usr/bin/env bash
# security-audit-sandbox - OS-enforced Docker sandbox for the security-audit skill.
#
# Copies target code into a scratch directory and runs it in a locked-down
# container: no network, read-only root, scratch-only writes, dropped
# capabilities, no-new-privileges, and CPU/memory/PID limits.
#
# Usage:
# security-audit-sandbox start <app> [--image <image>] [--exclude <pattern>]...
# security-audit-sandbox exec <app> [--timeout <seconds>] -- <command>...
# security-audit-sandbox stop <app> [--keep]
# security-audit-sandbox status <app>
# security-audit-sandbox --help
#
# Optional <app>/security-audit.conf (simple KEY=value lines, never sourced):
# IMAGE=node:22-bookworm
# EXCLUDE="node_modules dist coverage"
#
# Default exclusions: .git, .env*, and the top-level /data directory.
# The original app directory is never mounted into the container.
set -euo pipefail
PROG=security-audit-sandbox
RUN_PARENT="$HOME/security-audit-runs"
STATE_ROOT="${XDG_STATE_HOME:-$HOME/.local/state}/security-audit-sandbox"
CONF_NAME=security-audit.conf
DEFAULT_TIMEOUT=600
die() {
printf '%s: %s\n' "$PROG" "$*" >&2
exit 1
}
usage() {
cat <<'EOF'
Copy target code into a scratch directory and run it in a locked-down Docker
container: no network, read-only root, scratch-only writes, dropped
capabilities, no-new-privileges, and CPU/memory/PID limits.
Usage:
security-audit-sandbox start <app> [--image <image>] [--exclude <pattern>]...
Copy <app> to $HOME/security-audit-runs/<slug>.XXXXXX and start the
container. Repeat --exclude to add rsync exclusions.
security-audit-sandbox exec <app> [--timeout <seconds>] -- <command>...
Run <command> inside the running container from /scratch/app under
`timeout --signal=KILL`. Default timeout: 600 seconds.
security-audit-sandbox stop <app> [--keep]
Remove the container and state file. Remove the run directory too,
unless --keep is given.
security-audit-sandbox status <app>
Print the container name, run directory, and whether it is running.
security-audit-sandbox --help
Show this help.
Optional <app>/security-audit.conf (simple KEY=value lines, never sourced):
IMAGE=node:22-bookworm
EXCLUDE="node_modules dist coverage"
Image resolution order:
1. --image
2. IMAGE= in security-audit.conf
3. package.json -> node:22-bookworm
pyproject.toml or requirements.txt -> python:3.12-slim
go.mod -> golang:1.24-bookworm
Cargo.toml -> rust:1-bookworm
Gemfile -> ruby:3.3-bookworm
Always excluded from the copy: .git, .env*, and the top-level /data directory.
The original app directory is never mounted into the container.
Docker Desktop on macOS may refuse the fsize ulimit. The wrapper then starts
the container without that one limit and prints a warning; nofile stays in
place. On Linux hosts that accept fsize, the 100 MiB file-size cap is applied.
EOF
}
need_docker() {
command -v docker >/dev/null 2>&1 || die "docker is not installed or not on PATH"
docker info >/dev/null 2>&1 || die "cannot reach the Docker daemon; is Docker running?"
}
canonical_app() {
local app=$1
[ -d "$app" ] || die "app directory not found: $app"
(cd -P "$app" && pwd -P)
}
app_slug() {
local name
name=$(basename "$1")
name=${name//[^A-Za-z0-9_.-]/-}
[ -n "$name" ] || name=app
printf '%s' "$name"
}
app_hash() {
printf '%s' "$1" | shasum -a 256 | cut -c1-8
}
state_file_for() {
local app=$1 slug hash
slug=$(app_slug "$app")
hash=$(app_hash "$app")
printf '%s/state-%s-%s' "$STATE_ROOT" "$slug" "$hash"
}
container_name_for() {
local app=$1 slug hash
slug=$(app_slug "$app")
hash=$(app_hash "$app")
printf 'security-audit-%s-%s' "$slug" "$hash"
}
strip_quotes() {
local value=$1
case $value in
\"*\") value=${value#\"}; value=${value%\"} ;;
\'*\') value=${value#\'}; value=${value%\'} ;;
esac
printf '%s' "$value"
}
trim() {
local value=$1
value=${value#"${value%%[![:space:]]*}"}
value=${value%"${value##*[![:space:]]}"}
printf '%s' "$value"
}
CONF_IMAGE=""
CONF_EXCLUDE=""
load_conf() {
local app=$1 conf line key value
conf="$app/$CONF_NAME"
[ -f "$conf" ] || return 0
while IFS= read -r line || [ -n "$line" ]; do
line=${line%$'\r'}
line=$(trim "$line")
case $line in
''|'#'*) continue ;;
esac
case $line in
*=*) ;;
*) continue ;;
esac
key=$(trim "${line%%=*}")
value=$(trim "${line#*=}")
value=$(strip_quotes "$value")
case $key in
IMAGE) CONF_IMAGE=$value ;;
EXCLUDE) CONF_EXCLUDE="${CONF_EXCLUDE:+$CONF_EXCLUDE }$value" ;;
esac
done < "$conf"
}
infer_image() {
local app=$1
if [ -f "$app/package.json" ]; then
printf 'node:22-bookworm'
elif [ -f "$app/pyproject.toml" ] || [ -f "$app/requirements.txt" ]; then
printf 'python:3.12-slim'
elif [ -f "$app/go.mod" ]; then
printf 'golang:1.24-bookworm'
elif [ -f "$app/Cargo.toml" ]; then
printf 'rust:1-bookworm'
elif [ -f "$app/Gemfile" ]; then
printf 'ruby:3.3-bookworm'
else
printf ''
fi
}
load_state() {
local app=$1 file key value
file=$(state_file_for "$app")
[ -f "$file" ] || return 1
STATE_CONTAINER=""
STATE_RUN_DIR=""
STATE_APP=""
STATE_IMAGE=""
STATE_FSIZE=""
while IFS='=' read -r key value || [ -n "$key" ]; do
case $key in
CONTAINER) STATE_CONTAINER=$value ;;
RUN_DIR) STATE_RUN_DIR=$value ;;
APP) STATE_APP=$value ;;
IMAGE) STATE_IMAGE=$value ;;
FSIZE) STATE_FSIZE=$value ;;
esac
done < "$file"
[ -n "$STATE_CONTAINER" ] && [ -n "$STATE_RUN_DIR" ]
}
container_running() {
local name=$1 state
state=$(docker inspect -f '{{.State.Running}}' "$name" 2>/dev/null) || return 1
[ "$state" = "true" ]
}
container_exists() {
docker inspect "$1" >/dev/null 2>&1
}
WALL_CLOCK_PROBE_SECS=2
check_wall_clock_guard() {
local container=$1 status elapsed out
SECONDS=0
set +e
out=$(docker exec "$container" timeout --signal=KILL "$WALL_CLOCK_PROBE_SECS" sleep 10 2>&1)
status=$?
set -e
elapsed=$SECONDS
case $status in
124|137) ;;
*)
[ -z "$out" ] || printf '%s\n' "$out" >&2
die "image $STATE_IMAGE's 'timeout' does not enforce '--signal=KILL'; refusing to run without a wall-clock limit"
;;
esac
if [ "$elapsed" -lt 1 ] || [ "$elapsed" -gt $((WALL_CLOCK_PROBE_SECS + 4)) ]; then
die "image $STATE_IMAGE's 'timeout' did not stop the probe after ${WALL_CLOCK_PROBE_SECS}s; refusing to run without a wall-clock limit"
fi
}
check_run_dir() {
local dir=$1
case $dir in
"$RUN_PARENT"/*) ;;
*) die "refusing to remove unexpected run directory: $dir" ;;
esac
}
rm_run_dir() {
local dir=$1
check_run_dir "$dir"
rm -rf "$dir"
}
cleanup_failed_start() {
local run_dir=$1 state_file=$2
[ -n "$run_dir" ] && [ -d "$run_dir" ] && rm_run_dir "$run_dir"
[ -n "$state_file" ] && rm -f "$state_file"
}
cmd_start() {
local app_arg="" image_opt="" conf_image inferred
local app app_dir run_dir container state_file fsize_note out
local -a cli_excludes rsync_cmd docker_cmd
cli_excludes=()
while [ $# -gt 0 ]; do
case $1 in
--image)
[ $# -ge 2 ] || die "--image needs a value"
image_opt=$2
shift 2
;;
--image=*)
image_opt=${1#--image=}
shift
;;
--exclude)
[ $# -ge 2 ] || die "--exclude needs a value"
cli_excludes+=("$2")
shift 2
;;
--exclude=*)
cli_excludes+=("${1#--exclude=}")
shift
;;
-h|--help)
usage
exit 0
;;
-*)
die "unknown option for start: $1"
;;
*)
[ -z "$app_arg" ] || die "unexpected argument for start: $1"
app_arg=$1
shift
;;
esac
done
[ -n "$app_arg" ] || die "start needs an app directory"
need_docker
app_dir=$(canonical_app "$app_arg")
load_conf "$app_dir"
conf_image=$CONF_IMAGE
if [ -n "$image_opt" ]; then
image=$image_opt
elif [ -n "$conf_image" ]; then
image=$conf_image
else
inferred=$(infer_image "$app_dir")
[ -n "$inferred" ] || die "cannot infer an image for $app_dir; pass --image or set IMAGE= in $CONF_NAME"
image=$inferred
fi
state_file=$(state_file_for "$app_dir")
container=$(container_name_for "$app_dir")
if load_state "$app_dir"; then
if container_running "$STATE_CONTAINER"; then
die "a sandbox for $app_dir is already running (container $STATE_CONTAINER); run '$PROG stop $app_arg' first"
fi
if container_exists "$STATE_CONTAINER"; then
docker rm -f "$STATE_CONTAINER" >/dev/null 2>&1 || true
fi
rm -f "$state_file"
printf '%s: removed stale state for stopped container %s\n' "$PROG" "$STATE_CONTAINER" >&2
fi
if container_exists "$container"; then
die "container $container already exists but is not recorded in state; remove it with 'docker rm -f $container'"
fi
mkdir -p "$RUN_PARENT" || die "cannot create $RUN_PARENT"
run_dir=$(mktemp -d "$RUN_PARENT/$(app_slug "$app_dir").XXXXXX") || die "cannot create run directory under $RUN_PARENT"
mkdir -p "$run_dir/app" "$run_dir/home" "$run_dir/tmp" "$run_dir/cache" || {
cleanup_failed_start "$run_dir" "$state_file"
die "cannot prepare run directory $run_dir"
}
rsync_cmd=(rsync -a --exclude=.git --exclude='.env*' --exclude=/data)
if [ -n "$CONF_EXCLUDE" ]; then
local conf_pat
local -a conf_pats
read -r -a conf_pats <<< "$CONF_EXCLUDE"
for conf_pat in "${conf_pats[@]}"; do
rsync_cmd+=("--exclude=$conf_pat")
done
fi
if [ ${#cli_excludes[@]} -gt 0 ]; then
local cli_pat
for cli_pat in "${cli_excludes[@]}"; do
rsync_cmd+=("--exclude=$cli_pat")
done
fi
if ! "${rsync_cmd[@]}" "$app_dir/" "$run_dir/app/"; then
cleanup_failed_start "$run_dir" "$state_file"
die "rsync failed while copying $app_dir"
fi
docker_cmd=(docker run -d --name "$container"
--network none
--read-only
-v "$run_dir:/scratch"
--tmpfs '/tmp:rw,nosuid,size=512m'
-e HOME=/scratch/home
-e TMPDIR=/scratch/tmp
-e XDG_CACHE_HOME=/scratch/cache
--user "$(id -u):$(id -g)"
--memory 4g
--cpus 2
--pids-limit 256
--cap-drop ALL
--security-opt no-new-privileges
--init
--ulimit nofile=1024:1024
--workdir /scratch/app)
fsize_note=""
if out=$("${docker_cmd[@]}" --ulimit fsize=104857600 "$image" sleep infinity 2>&1); then
STATE_FSIZE=on
fsize_note=on
else
case $out in
*fsize*|*FSIZE*)
printf '%s: Docker refused the fsize ulimit; starting without the file-size cap\n' "$PROG" >&2
if out=$("${docker_cmd[@]}" "$image" sleep infinity 2>&1); then
STATE_FSIZE=off
fsize_note=off
else
cleanup_failed_start "$run_dir" "$state_file"
die "docker run failed: $out"
fi
;;
*)
cleanup_failed_start "$run_dir" "$state_file"
die "docker run failed: $out"
;;
esac
fi
mkdir -p "$STATE_ROOT" || {
docker rm -f "$container" >/dev/null 2>&1 || true
cleanup_failed_start "$run_dir" "$state_file"
die "cannot create state directory $STATE_ROOT"
}
if ! {
printf 'CONTAINER=%s\n' "$container"
printf 'RUN_DIR=%s\n' "$run_dir"
printf 'APP=%s\n' "$app_dir"
printf 'IMAGE=%s\n' "$image"
printf 'FSIZE=%s\n' "$STATE_FSIZE"
} > "$state_file"; then
docker rm -f "$container" >/dev/null 2>&1 || true
cleanup_failed_start "$run_dir" "$state_file"
die "cannot write state file $state_file"
fi
printf 'container: %s\n' "$container"
printf 'run dir: %s\n' "$run_dir"
printf 'scratch: %s\n' "$run_dir (mounted at /scratch)"
printf 'app copy: %s/app (mounted at /scratch/app)\n' "$run_dir"
printf 'image: %s\n' "$image"
if [ "$fsize_note" = off ]; then
printf 'note: fsize ulimit refused by Docker; no file-size cap applied\n'
fi
}
cmd_exec() {
local app_arg="" timeout_secs=$DEFAULT_TIMEOUT saw_sep=0
local app_dir container
while [ $# -gt 0 ]; do
case $1 in
--timeout)
[ $# -ge 2 ] || die "--timeout needs a value"
timeout_secs=$2
shift 2
;;
--timeout=*)
timeout_secs=${1#--timeout=}
shift
;;
--)
shift
saw_sep=1
break
;;
-h|--help)
usage
exit 0
;;
-*)
die "unknown option for exec: $1"
;;
*)
[ -z "$app_arg" ] || die "unexpected argument for exec: $1"
app_arg=$1
shift
;;
esac
done
[ -n "$app_arg" ] || die "exec needs an app directory"
[ "$saw_sep" = 1 ] || die "exec needs -- before the command"
[ $# -gt 0 ] || die "exec needs a command after --"
case $timeout_secs in
''|*[!0-9]*) die "--timeout must be a positive integer number of seconds" ;;
esac
[ "$timeout_secs" -gt 0 ] || die "--timeout must be greater than zero"
need_docker
app_dir=$(canonical_app "$app_arg")
load_state "$app_dir" || die "no sandbox recorded for $app_dir; run '$PROG start $app_arg' first"
container=$STATE_CONTAINER
container_running "$container" || die "container $container is not running; run '$PROG stop $app_arg' and start again"
check_wall_clock_guard "$container"
docker exec --workdir /scratch/app "$container" timeout --signal=KILL "$timeout_secs" "$@"
}
cmd_stop() {
local app_arg="" keep=0 app_dir run_dir
while [ $# -gt 0 ]; do
case $1 in
--keep)
keep=1
shift
;;
-h|--help)
usage
exit 0
;;
-*)
die "unknown option for stop: $1"
;;
*)
[ -z "$app_arg" ] || die "unexpected argument for stop: $1"
app_arg=$1
shift
;;
esac
done
[ -n "$app_arg" ] || die "stop needs an app directory"
app_dir=$(canonical_app "$app_arg")
load_state "$app_dir" || die "no sandbox recorded for $app_dir"
run_dir=$STATE_RUN_DIR
[ "$keep" = 1 ] || check_run_dir "$run_dir"
docker rm -f "$STATE_CONTAINER" >/dev/null 2>&1 || true
rm -f "$(state_file_for "$app_dir")"
if [ "$keep" = 1 ]; then
printf 'removed container %s; kept run dir %s\n' "$STATE_CONTAINER" "$run_dir"
else
rm_run_dir "$run_dir"
printf 'removed container %s and run dir %s\n' "$STATE_CONTAINER" "$run_dir"
fi
}
cmd_status() {
local app_arg="" app_dir running
while [ $# -gt 0 ]; do
case $1 in
-h|--help)
usage
exit 0
;;
-*)
die "unknown option for status: $1"
;;
*)
[ -z "$app_arg" ] || die "unexpected argument for status: $1"
app_arg=$1
shift
;;
esac
done
[ -n "$app_arg" ] || die "status needs an app directory"
app_dir=$(canonical_app "$app_arg")
load_state "$app_dir" || die "no sandbox recorded for $app_dir"
if container_running "$STATE_CONTAINER"; then
running=running
elif container_exists "$STATE_CONTAINER"; then
running=stopped
else
running=missing
fi
printf 'container: %s\n' "$STATE_CONTAINER"
printf 'run dir: %s\n' "$STATE_RUN_DIR"
printf 'app: %s\n' "$STATE_APP"
printf 'image: %s\n' "$STATE_IMAGE"
printf 'fsize cap: %s\n' "$STATE_FSIZE"
printf 'state: %s\n' "$running"
}
main() {
[ $# -gt 0 ] || {
usage >&2
exit 1
}
local cmd=$1
shift
case $cmd in
start) cmd_start "$@" ;;
exec) cmd_exec "$@" ;;
stop) cmd_stop "$@" ;;
status) cmd_status "$@" ;;
-h|--help|help) usage ;;
*)
die "unknown command: $cmd (try --help)"
;;
esac
}
main "$@"
+339
View File
@@ -0,0 +1,339 @@
#!/usr/bin/env bash
# ============================================================================
# yt-transcribe — repeatable YouTube/X transcription
#
# Strategy: captions first (exact text, fast); Whisper fallback ONLY when no
# captions exist, reusing the OpenSuperWhisper model already on this Mac.
# Accepts a URL (YouTube, X/Twitter, anything yt-dlp supports) OR a local
# media file (skips straight to Whisper; used by the watcher for reclip
# downloads).
#
# Usage:
# yt-transcribe <url-or-file> # transcript → media/transcripts/<id>/ (URL)
# # or <file>.txt sidecar (file)
# yt-transcribe <url> --lang de # prefer German captions
# yt-transcribe <url> --srt # also produce an .srt (whisper path)
# yt-transcribe <url> --force # redo even if transcript exists
#
# X/Twitter: X has no public captions and now requires auth for most video
# extraction, so URLs on x.com/twitter.com go through gallery-dl (set
# YT_COOKIES=/path/to/cookies.txt for locked/NSFW/older tweets; exported
# cookies.txt format from a browser extension works for both yt-dlp and
# gallery-dl).
#
# Outputs (URL mode) in <share>/media/transcripts/<id>/:
# <id>.txt plain transcript (always)
# <id>.vtt raw captions (captions path)
# <id>.srt subtitles (whisper path, with --srt)
# <id>.metadata.json provenance: title, channel, source, date
#
# Dependencies (declared in dotfiles configuration.nix homebrew.brews):
# yt-dlp, gallery-dl (X only), whisper-cli (whisper-cpp), ffmpeg (fallback only)
# Whisper model: auto-detected from OpenSuperWhisper's model store,
# or WHISPER_MODEL=/path/to/ggml-*.bin, or --model.
# Env overrides: YT_SHARE_ROOT (data share mount, default /Volumes/data),
# YT_TRANSCRIBE_ROOT (transcript root), YT_MEDIA_DIR (reclip download dir),
# YT_COOKIES (cookies.txt for yt-dlp/gallery-dl).
# Index: `yt-transcribe --list` prints id->title mapping; --index rewrites
# INDEX.md next to the transcripts; both modes refresh it after each run.
# ============================================================================
set -euo pipefail
# --- locate the data share ---------------------------------------------------
# The tool lives in this repo (installed into the nix store by the dotfiles
# rebuild; stable symlink at ~/.local/bin/yt-transcribe). The Unraid share
# holds only data — media and transcripts.
SHARE_ROOT="${YT_SHARE_ROOT:-/Volumes/data}"
OUT_ROOT="${YT_TRANSCRIBE_ROOT:-$SHARE_ROOT/media/transcripts}"
# --- PATH: cover Homebrew on Apple Silicon / Intel (launchd PATH too) ------
for p in /opt/homebrew/bin /usr/local/bin; do
[ -d "$p" ] && [[ ":$PATH:" != *":$p:"* ]] && PATH="$p:$PATH"
done
LANG_PREF="en"
KEEP_SRT=false
FORCE=false
DO_INDEX=false
DO_LIST=false
WHISPER_MODEL_ARG=""
INPUT=""
while [ $# -gt 0 ]; do
case "$1" in
--lang) LANG_PREF="$2"; shift 2 ;;
--srt) KEEP_SRT=true; shift ;;
--force) FORCE=true; shift ;;
--model) WHISPER_MODEL_ARG="$2"; shift 2 ;;
--index) DO_INDEX=true; shift ;;
--list) DO_LIST=true; shift ;;
-h|--help) grep '^# ' "$0" | sed 's/^# //'; exit 0 ;;
*) INPUT="$1"; shift ;;
esac
done
[ -n "$INPUT" ] || $DO_INDEX || $DO_LIST || { echo "usage: yt-transcribe <url-or-file> [--lang L] [--srt] [--force] [--model ggml.bin] [--index|--list]" >&2; exit 1; }
# --- transcript index (INDEX.md / --list) -----------------------------------
rebuild_index() {
python3 - "$OUT_ROOT" "${YT_MEDIA_DIR:-$SHARE_ROOT/media/video}" <<'PY'
import json, os, sys, time
out_root, scan_dir = sys.argv[1], sys.argv[2]
rows = []
for dirpath, _, files in os.walk(out_root):
for fn in files:
if fn.endswith(".metadata.json"):
try:
d = json.load(open(os.path.join(dirpath, fn), encoding="utf-8"))
except Exception:
continue
rows.append((d.get("transcribed_at") or "", d))
rows.sort(key=lambda r: r[0], reverse=True)
clean = lambda s: (s or "").replace("|", "/").replace("`", "/")
L = ["# Transcript Index", "",
"URL transcripts live in `media/transcripts/<id>/` — the `<id>.txt` is the",
"transcript, `<id>.metadata.json` has full provenance. Local files keep their",
"`.txt` sidecar next to the media file.", "",
"## URL transcripts", "", "| transcribed | id | title | channel | source |", "|---|---|---|---|---|"]
for ts, d in rows:
L.append(f'| {ts} | `{clean(d.get("id"))}` | {clean(d.get("title"))} | {clean(d.get("channel"))} | {clean(d.get("source"))} |')
L += ["", "## Local media files (sidecar .txt in media/video)", "", "| file | modified |", "|---|---|"]
found = False
for dirpath, dirs, files in os.walk(scan_dir):
dirs[:] = [d for d in dirs if not d.startswith(".")]
for fn in sorted(files):
if fn.endswith(".txt"):
found = True
p = os.path.join(dirpath, fn)
mt = time.strftime("%Y-%m-%d", time.localtime(os.path.getmtime(p)))
L.append(f"| `{clean(fn)}` | {mt} |")
if not found:
L.append("| _(none yet — patched reclip or manual file-mode runs add one per download)_ | |")
print("\n".join(L))
PY
}
if $DO_INDEX || $DO_LIST; then
mkdir -p "$OUT_ROOT"
if $DO_LIST; then
rebuild_index
else
rebuild_index > "$OUT_ROOT/INDEX.md"
echo "== index rebuilt: $OUT_ROOT/INDEX.md"
fi
exit 0
fi
need() { command -v "$1" >/dev/null || { echo "MISSING DEP: $1 — install it first" >&2; exit 2; }; }
DL_ARGS=()
[ -n "${YT_COOKIES:-}" ] && DL_ARGS=(--cookies "$YT_COOKIES")
resolve_model() {
local MODEL="${WHISPER_MODEL_ARG:-${WHISPER_MODEL:-}}"
if [ -z "$MODEL" ]; then
MODEL="$(find "$HOME/Library/Application Support/ru.starmel.OpenSuperWhisper/whisper-models" \
-name 'ggml-*.bin' 2>/dev/null | head -1 || true)"
fi
printf '%s' "$MODEL"
}
# whisper_transcribe <wav> <out-stem> — writes <out-stem>.txt (and .srt w/ --srt)
whisper_transcribe() {
local WAV="$1" STEM="$2" MODEL
MODEL="$(resolve_model)"
[ -n "$MODEL" ] && [ -f "$MODEL" ] || {
echo "ERROR: no whisper model. Download one (e.g. ggml-large-v3-turbo.bin from huggingface.co/ggerganov/whisper.cpp)" >&2
echo " and pass --model or set WHISPER_MODEL." >&2; exit 4; }
echo ">> model: $MODEL"
local WARGS=(-m "$MODEL" -f "$WAV" -of "$STEM" -otxt)
$KEEP_SRT && WARGS+=(-osrt)
echo ">> transcribing with whisper-cli (this is the slow part)..."
whisper-cli "${WARGS[@]}" 2>>"$(dirname "$STEM")/whisper.log"
[ -s "$STEM.txt" ] || { echo "ERROR: whisper produced no text" >&2; exit 6; }
}
TMPD="$(mktemp -d)"
cleanup() { rm -rf "$TMPD"; }
trap cleanup EXIT
SOURCE=""
SOURCE_PREFIX=""
if [ -f "$INPUT" ]; then
# ==========================================================================
# FILE MODE — local media (reclip download, screen recording, anything)
# ==========================================================================
need ffmpeg; need whisper-cli
SRC_FILE="$INPUT"
STEM="$(basename "$SRC_FILE")"
STEM="${STEM%.*}"
OUT_DIR="$(cd "$(dirname "$SRC_FILE")" && pwd)"
TXT="$OUT_DIR/$STEM.txt"
if [ -s "$TXT" ] && ! $FORCE; then
echo "== already transcribed: $TXT (use --force to redo)"
exit 0
fi
echo ">> file mode: $SRC_FILE"
echo ">> converting to 16 kHz mono wav..."
ffmpeg -y -loglevel error -i "$SRC_FILE" -ac 1 -ar 16000 "$TMPD/in.wav"
whisper_transcribe "$TMPD/in.wav" "$OUT_DIR/$STEM"
SOURCE="whisper-local"
rebuild_index > "$OUT_ROOT/INDEX.md" 2>/dev/null || true
echo "== done: $TXT (source: $SOURCE)"
exit 0
fi
# ==========================================================================
# URL MODE
# ==========================================================================
need yt-dlp
URL="$INPUT"
IS_X=false
case "$URL" in
*x.com/*|*twitter.com/*|*//t.co/*) IS_X=true ;;
esac
# --- metadata (yt-dlp; gallery-dl for X when yt-dlp can't) -------------------
VIDEO_ID=""; TITLE=""; CHANNEL=""
if META="$(yt-dlp --no-playlist --skip-download --no-warnings "${DL_ARGS[@]}" \
--print "id=%(id)s" --print "title=%(title)s" --print "channel=%(channel|uploader)s" "$URL" 2>/dev/null)"; then
VIDEO_ID="$(printf '%s\n' "$META" | sed -n 's/^id=//p')"
TITLE="$(printf '%s\n' "$META" | sed -n 's/^title=//p')"
CHANNEL="$(printf '%s\n' "$META" | sed -n 's/^channel=//p')"
fi
if $IS_X && [ -z "$VIDEO_ID" ]; then
# X/Twitter via gallery-dl
need gallery-dl
echo ">> X URL — resolving via gallery-dl: $URL"
VIDEO_ID="$(printf '%s' "$URL" | grep -oE 'status(es)?/[0-9]+' | grep -oE '[0-9]+' | head -1 || true)"
if [ -z "$VIDEO_ID" ] && GJ="$(gallery-dl -j "$URL" 2>/dev/null | head -1)"; then
VIDEO_ID="$(printf '%s' "$GJ" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('tweet_id',''))" 2>/dev/null || true)"
TITLE="$(printf '%s' "$GJ" | python3 -c "import json,sys; d=json.load(sys.stdin); print((d.get('content') or '')[:200])" 2>/dev/null || true)"
CHANNEL="$(printf '%s' "$GJ" | python3 -c "import json,sys; d=json.load(sys.stdin); a=d.get('author') or {}; print(a.get('nick') or a.get('name') or '')" 2>/dev/null || true)"
fi
[ -n "$VIDEO_ID" ] || { echo "ERROR: could not resolve a tweet id from: $URL" >&2; exit 3; }
fi
# Fill X title/channel from gallery-dl metadata when yt-dlp gave none
if $IS_X && { [ -z "$TITLE" ] || [ -z "$CHANNEL" ] || [ "$CHANNEL" = "uploader" ]; } && command -v gallery-dl >/dev/null; then
GJ="$(gallery-dl -j "$URL" 2>/dev/null | head -1 || true)"
if [ -n "$GJ" ]; then
XMETA="$(printf '%s' "$GJ" | python3 -c '
import json, sys
def walk(o):
if isinstance(o, dict):
if "author" in o or "tweet_id" in o:
yield o
for v in o.values(): yield from walk(v)
elif isinstance(o, list):
for v in o: yield from walk(v)
items = list(walk(json.load(sys.stdin)))
d = items[-1] if items else {}
a = d.get("author") or {}
print(d.get("tweet_id") or "")
print((d.get("content") or "").replace("\n", " ")[:200])
print(a.get("nick") or a.get("name") or "")
' 2>/dev/null || true)"
if [ -n "$XMETA" ]; then
[ -z "$VIDEO_ID" ] && VIDEO_ID="$(printf '%s\n' "$XMETA" | sed -n '1p')"
[ -z "$TITLE" ] && TITLE="$(printf '%s\n' "$XMETA" | sed -n '2p')"
if [ -z "$CHANNEL" ] || [ "$CHANNEL" = "uploader" ]; then
CHANNEL="$(printf '%s\n' "$XMETA" | sed -n '3p')"
fi
fi
fi
TITLE="${TITLE:-x.com post}"
CHANNEL="${CHANNEL:-x.com}"
OUT_DIR="$OUT_ROOT/$VIDEO_ID"
mkdir -p "$OUT_DIR"
TXT="$OUT_DIR/$VIDEO_ID.txt"
else
[ -n "$VIDEO_ID" ] || { echo "ERROR: yt-dlp could not resolve the URL (private, geo-blocked, or unsupported?)" >&2; exit 3; }
OUT_DIR="$OUT_ROOT/$VIDEO_ID"
mkdir -p "$OUT_DIR"
TXT="$OUT_DIR/$VIDEO_ID.txt"
fi
if [ -s "$TXT" ] && ! $FORCE; then
echo "== already transcribed: $TXT (use --force to redo)"
exit 0
fi
# --- path 1: captions -------------------------------------------------------
echo ">> trying captions ($LANG_PREF)..."
yt-dlp --no-playlist --skip-download --no-warnings "${DL_ARGS[@]}" \
--write-subs --write-auto-subs \
--sub-langs "$LANG_PREF" --sub-format "vtt" \
-o "$OUT_DIR/%(id)s.%(ext)s" "$URL" 2>/dev/null || true
VTT="$(find "$OUT_DIR" -maxdepth 1 -name "$VIDEO_ID.$LANG_PREF.vtt" | head -1)"
if [ -z "$VTT" ]; then
# exact code missing (e.g. video tagged en-US only) — broaden once, keep best, delete the rest
yt-dlp --no-playlist --skip-download --no-warnings "${DL_ARGS[@]}" \
--write-subs --write-auto-subs \
--sub-langs "$LANG_PREF.*" --sub-format "vtt" \
-o "$OUT_DIR/%(id)s.%(ext)s" "$URL" 2>/dev/null || true
VTT="$(find "$OUT_DIR" -maxdepth 1 -name "$VIDEO_ID.$LANG_PREF-*.vtt" | sort | head -1)"
find "$OUT_DIR" -maxdepth 1 -name "$VIDEO_ID.*.vtt" ! -path "$VTT" -delete 2>/dev/null || true
fi
if [ -n "$VTT" ]; then
echo ">> captions found: $(basename "$VTT") -> converting"
python3 - "$VTT" "$TXT" <<'PY'
import re, sys
src, dst = sys.argv[1], sys.argv[2]
out, prev = [], None
for raw in open(src, encoding="utf-8", errors="replace"):
line = raw.strip()
if (not line or "-->" in line or line.startswith(("WEBVTT", "Kind:", "Language:", "NOTE", "STYLE"))
or re.match(r"^\d+$", line)):
continue
line = re.sub(r"<[^>]+>", "", line) # strip inline tags
if line and line != prev:
out.append(line); prev = line
text = " ".join(out)
open(dst, "w", encoding="utf-8").write(text + "\n")
print(f" {len(text.split())} words")
PY
if $IS_X; then SOURCE="x-captions"; else SOURCE="youtube-captions"; fi
else
# --- path 2: Whisper fallback --------------------------------------------
echo ">> no captions — falling back to Whisper"
need ffmpeg; need whisper-cli
MEDIA_DIR="${YT_MEDIA_DIR:-$SHARE_ROOT/media/video}" # e.g. reclip's downloads on the share
echo ">> checking $MEDIA_DIR for an existing download..."
LOCAL_MEDIA="$(find "$MEDIA_DIR" -maxdepth 4 -iname "*$VIDEO_ID*" \
\( -iname '*.mp4' -o -iname '*.mkv' -o -iname '*.webm' -o -iname '*.m4a' \
-o -iname '*.mp3' -o -iname '*.flac' -o -iname '*.mov' -o -iname '*.avi' -o -iname '*.wav' \) \
2>/dev/null | head -1 || true)"
WAV="$TMPD/in.wav"
if [ -n "$LOCAL_MEDIA" ]; then
echo ">> reusing existing file: $LOCAL_MEDIA"
ffmpeg -y -loglevel error -i "$LOCAL_MEDIA" -ac 1 -ar 16000 "$WAV"
elif $IS_X && command -v gallery-dl >/dev/null; then
echo ">> downloading X media via gallery-dl..."
gallery-dl "${DL_ARGS[@]}" \
--filter "extension not in ('jpg','jpeg','png','webp','gif')" \
-o "filename={tweet_id}.{extension}" \
-D "$TMPD" "$URL"
XMEDIA="$(find "$TMPD" -maxdepth 1 -type f \( -iname '*.mp4' -o -iname '*.m4a' -o -iname '*.mov' -o -iname '*.webm' \) | sort | tail -1)"
[ -n "$XMEDIA" ] || { echo "ERROR: gallery-dl found no video (private tweet? set YT_COOKIES=/path/to/cookies.txt)" >&2; exit 5; }
ffmpeg -y -loglevel error -i "$XMEDIA" -ac 1 -ar 16000 "$WAV"
SOURCE_PREFIX="gallery-dl"
else
echo ">> not found — downloading audio (16 kHz mono)..."
yt-dlp --no-playlist --no-warnings "${DL_ARGS[@]}" -x --audio-format wav \
--postprocessor-args "ffmpeg:-ac 1 -ar 16000" \
-o "$TMPD/%(id)s.%(ext)s" "$URL"
fi
[ -f "$WAV" ] || { echo "ERROR: audio acquisition failed" >&2; exit 5; }
whisper_transcribe "$WAV" "$OUT_DIR/$VIDEO_ID"
SOURCE="${SOURCE_PREFIX:+$SOURCE_PREFIX+}whisper-local"
fi
# --- provenance --------------------------------------------------------------
TRANSCRIBED_AT="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
python3 - "$VIDEO_ID" "$TITLE" "$CHANNEL" "$URL" "$SOURCE" "$LANG_PREF" "$TRANSCRIBED_AT" \
> "$OUT_DIR/$VIDEO_ID.metadata.json" <<'PY'
import json, sys
keys = ["id", "title", "channel", "url", "source", "lang_pref", "transcribed_at"]
print(json.dumps(dict(zip(keys, sys.argv[1:])), indent=2, ensure_ascii=False))
PY
echo "== done: $TXT (source: $SOURCE)"
rebuild_index > "$OUT_ROOT/INDEX.md" 2>/dev/null || true
+44
View File
@@ -0,0 +1,44 @@
# Patched reclip — source of truth
Our transcription + history additions to [averygan/reclip](https://github.com/averygan/reclip),
kept here so container updates and new machines can't lose them.
- `app.py`, `index.html` — the full patched files (deployed via bind-mounts
from `documents/reclip/` on the Unraid share; see that dir's DEPLOY.md)
- `reclip-transcript.patch` — the same delta as a diff against upstream,
for rebasing onto future upstream versions
Patch base: upstream `1d161d1` (cloned 2026-10-25).
## What the patch adds
1. `fetch_transcript()` — after each download, pull yt-dlp captions
(YouTube subs; X auto-captions) → `<stem>.txt` sidecar, never fails the job
2. `/api/transcript/<job_id>` + Transcript button + auto-save in the UI
3. Persisted download history (`history.json` in the downloads volume) +
`/api/history` + History section with a live transcript-available flag
(manual `yt-transcribe` sidecars are detected at read time)
4. `/api/file` + `/api/transcript` fall back to history, so old links
survive restarts
## Updating reclip (when upstream changes)
git clone --depth 1 https://github.com/averygan/reclip.git /tmp/reclip-new
cd /tmp/reclip-new
git apply --3way ~/Documents/dotfiles/patches/reclip/reclip-transcript.patch
Resolve any conflicts (the additions are mostly self-contained: one new
function, two routes, one status field, UI button + History section), then
copy the updated `app.py` + `templates/index.html`:
- into this directory (commit — new source of truth)
- to the share: `/Volumes/data/documents/reclip/{app.py,index.html}`
- restart the reclip container (gunicorn reloads at start; the entrypoint
also pip-updates yt-dlp at every container start)
If `git apply` fails on a drifted file, the fastest path is re-porting by
hand from the conflict markers — the four additions are small and greppable
(`fetch_transcript`, `history.json`, `resolve_download`, `saveTranscript`).
If an image update happens WITHOUT re-porting: the old patched files keep
working (bind-mounts win), you just may miss upstream improvements.
+403
View File
@@ -0,0 +1,403 @@
import os
import uuid
import glob
import json
import re
import hashlib
import subprocess
import threading
import time
from flask import Flask, request, jsonify, send_file, render_template
app = Flask(__name__)
DOWNLOAD_DIR = os.path.join(os.path.dirname(__file__), "downloads")
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
jobs = {}
HISTORY_FILE = os.path.join(DOWNLOAD_DIR, "history.json")
_history_lock = threading.Lock()
def load_history():
try:
with open(HISTORY_FILE, encoding="utf-8") as fh:
data = json.load(fh)
return data if isinstance(data, list) else []
except Exception:
return []
def save_history(history):
try:
tmp = HISTORY_FILE + ".tmp"
with open(tmp, "w", encoding="utf-8") as fh:
json.dump(history, fh, indent=2)
os.replace(tmp, HISTORY_FILE)
except OSError:
pass
def sidecar_transcript(file_path):
"""Manual-fallback transcripts (yt-transcribe <file>) live beside the
media as <stem>.txt — recognize them at read time so history stays
truthful without re-downloading anything."""
if not file_path:
return None
stem = os.path.splitext(file_path)[0] + ".txt"
return stem if os.path.exists(stem) else None
def record_history(job):
"""Persist the completed job so history + file/transcript downloads
survive process restarts (downloads dir is the mapped volume)."""
with _history_lock:
history = [h for h in load_history() if h.get("job_id") != job.get("job_id")]
history.insert(0, {
"job_id": job.get("job_id"),
"url": job.get("url", ""),
"title": job.get("title", ""),
"thumbnail": job.get("thumbnail", ""),
"filename": job.get("filename", ""),
"file": job.get("file", ""),
"transcript": job.get("transcript") or "",
"transcript_name": job.get("transcript_name", ""),
"has_transcript": bool(job.get("transcript")),
"size": os.path.getsize(job["file"]) if job.get("file") and os.path.exists(job["file"]) else 0,
"date": time.strftime("%Y-%m-%d %H:%M:%S"),
})
save_history(history[:200])
MEDIA_EXTS = (".mp4", ".mkv", ".webm", ".m4a", ".mp3", ".flac", ".mov", ".avi", ".wav", ".ts")
def backfill_history():
"""Add on-disk downloads that predate history.json (or were dropped into
the downloads dir manually) so the whole library shows up on the page.
The transcript flag is resolved live at read time, so backfilled entries
pick up manual yt-transcribe sidecars automatically."""
for name in sorted(os.listdir(DOWNLOAD_DIR)):
path = os.path.join(DOWNLOAD_DIR, name)
if not os.path.isfile(path) or not name.lower().endswith(MEDIA_EXTS):
continue
with _history_lock:
history = load_history()
if any(h.get("file") == path for h in history):
continue
stem = os.path.splitext(name)[0]
# a 10-hex stem is a reclip job id — the real title wasn't kept
title = "" if re.fullmatch(r"[0-9a-f]{10}", stem) else stem
history.insert(0, {
"job_id": hashlib.sha1(path.encode()).hexdigest()[:10],
"url": "",
"title": title,
"filename": name,
"file": path,
"transcript": "",
"transcript_name": "",
"has_transcript": False,
"size": os.path.getsize(path),
"date": time.strftime("%Y-%m-%d %H:%M:%S",
time.localtime(os.path.getmtime(path))),
})
save_history(history[:200])
backfill_history()
def parse_ytdlp_json(stdout):
"""Parse yt-dlp JSON output.
With ``-j`` yt-dlp prints one JSON object per line. Some extractors
emit multiple videos even with ``--no-playlist``, so stdout contains
several objects and a plain ``json.loads`` raises "Extra data".
Return the first valid object.
"""
for line in stdout.splitlines():
line = line.strip()
if not line:
continue
return json.loads(line)
raise ValueError("yt-dlp returned no data")
def fetch_transcript(url, chosen_path):
"""Best-effort transcript via yt-dlp captions (manual or auto-generated;
includes X's auto-captions). Writes <video stem>.txt beside the download.
Returns the .txt path, or None when the video has no captions. Never
raises — a transcript is a bonus, not a download requirement."""
stem = os.path.splitext(chosen_path)[0]
try:
cmd = ["yt-dlp", "--no-playlist", "--skip-download", "--no-warnings",
"--write-subs", "--write-auto-subs",
"--sub-langs", "en,en-orig",
"--sub-format", "vtt",
"-o", stem + ".%(ext)s", url]
subprocess.run(cmd, capture_output=True, text=True, timeout=180)
vtts = glob.glob(stem + ".*.vtt")
if not vtts:
return None
vtts.sort(key=lambda p: (0 if p.endswith(".en.vtt") else 1, p))
lines, prev = [], None
with open(vtts[0], encoding="utf-8", errors="replace") as fh:
for raw in fh:
line = raw.strip()
if (not line or "-->" in line
or line.startswith(("WEBVTT", "Kind:", "Language:", "NOTE", "STYLE"))
or re.match(r"^\d+$", line)):
continue
line = re.sub(r"<[^>]+>", "", line)
if line and line != prev:
lines.append(line)
prev = line
txt = stem + ".txt"
with open(txt, "w", encoding="utf-8") as out:
out.write(" ".join(lines) + "\n")
for f in vtts:
try:
os.remove(f)
except OSError:
pass
return txt if lines else None
except Exception:
return None
def run_download(job_id, url, format_choice, format_id):
job = jobs[job_id]
out_template = os.path.join(DOWNLOAD_DIR, f"{job_id}.%(ext)s")
cmd = ["yt-dlp", "--no-playlist", "-o", out_template]
if format_choice == "audio":
cmd += ["-x", "--audio-format", "mp3"]
elif format_id:
cmd += ["-f", f"{format_id}+bestaudio/best", "--merge-output-format", "mp4"]
else:
cmd += ["-f", "bestvideo+bestaudio/best", "--merge-output-format", "mp4"]
cmd.append(url)
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
if result.returncode != 0:
job["status"] = "error"
job["error"] = result.stderr.strip().split("\n")[-1]
return
files = glob.glob(os.path.join(DOWNLOAD_DIR, f"{job_id}.*"))
if not files:
job["status"] = "error"
job["error"] = "Download completed but no file was found"
return
if format_choice == "audio":
target = [f for f in files if f.endswith(".mp3")]
chosen = target[0] if target else files[0]
else:
target = [f for f in files if f.endswith(".mp4")]
chosen = target[0] if target else files[0]
for f in files:
if f != chosen:
try:
os.remove(f)
except OSError:
pass
job["status"] = "done"
job["file"] = chosen
ext = os.path.splitext(chosen)[1]
title = job.get("title", "").strip()
# Sanitize title for filename
if title:
safe_title = "".join(c for c in title if c not in r'\/:*?"<>|').strip()[:100].strip()
job["filename"] = f"{safe_title}{ext}" if safe_title else os.path.basename(chosen)
else:
job["filename"] = os.path.basename(chosen)
# Best-effort transcript sidecar: yt-dlp captions (X auto-captions
# included) -> plain .txt next to the chosen file. Never fails the job.
job["transcript"] = fetch_transcript(url, chosen)
job["transcript_name"] = os.path.splitext(job["filename"])[0] + ".txt"
record_history(job)
except subprocess.TimeoutExpired:
job["status"] = "error"
job["error"] = "Download timed out (5 min limit)"
except Exception as e:
job["status"] = "error"
job["error"] = str(e)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/api/info", methods=["POST"])
def get_info():
data = request.json
url = data.get("url", "").strip()
if not url:
return jsonify({"error": "No URL provided"}), 400
cmd = ["yt-dlp", "--no-playlist", "-j", url]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
if result.returncode != 0:
return jsonify({"error": result.stderr.strip().split("\n")[-1]}), 400
info = parse_ytdlp_json(result.stdout)
# Build quality options — keep best format per resolution
best_by_height = {}
for f in info.get("formats", []):
height = f.get("height")
if height and f.get("vcodec", "none") != "none":
tbr = f.get("tbr") or 0
if height not in best_by_height or tbr > (best_by_height[height].get("tbr") or 0):
best_by_height[height] = f
formats = []
for height, f in best_by_height.items():
formats.append({
"id": f["format_id"],
"label": f"{height}p",
"height": height,
})
formats.sort(key=lambda x: x["height"], reverse=True)
return jsonify({
"title": info.get("title", ""),
"thumbnail": info.get("thumbnail", ""),
"duration": info.get("duration"),
"uploader": info.get("uploader", ""),
"formats": formats,
})
except subprocess.TimeoutExpired:
return jsonify({"error": "Timed out fetching video info"}), 400
except Exception as e:
return jsonify({"error": str(e)}), 400
@app.route("/api/playlist", methods=["POST"])
def get_playlist_info():
data = request.json
url = data.get("url", "").strip()
if not url:
return jsonify({"error": "No URL provided"}), 400
cmd = ["yt-dlp", "--flat-playlist", "-J", url]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
if result.returncode != 0:
return jsonify({"error": result.stderr.strip().split("\n")[-1]}), 400
info = json.loads(result.stdout)
entries = info.get("entries", [])
urls = [entry.get("url") for entry in entries if entry.get("url")]
return jsonify({"urls": urls})
except subprocess.TimeoutExpired:
return jsonify({"error": "Timed out fetching playlist info"}), 400
except Exception as e:
return jsonify({"error": str(e)}), 400
@app.route("/api/download", methods=["POST"])
def start_download():
data = request.json
url = data.get("url", "").strip()
format_choice = data.get("format", "video")
format_id = data.get("format_id")
title = data.get("title", "")
if not url:
return jsonify({"error": "No URL provided"}), 400
job_id = uuid.uuid4().hex[:10]
jobs[job_id] = {"job_id": job_id, "status": "downloading", "url": url, "title": title,
"thumbnail": (data.get("thumbnail") or "")[:500]}
thread = threading.Thread(target=run_download, args=(job_id, url, format_choice, format_id))
thread.daemon = True
thread.start()
return jsonify({"job_id": job_id})
def resolve_download(job_id, key):
"""Find a completed job in memory, falling back to the on-disk history
(paths point into DOWNLOAD_DIR, so they survive restarts)."""
job = jobs.get(job_id)
if job and job.get("status") == "done" and job.get(key):
return job
for entry in load_history():
if entry.get("job_id") == job_id and entry.get(key):
return entry
return None
@app.route("/api/status/<job_id>")
def check_status(job_id):
job = jobs.get(job_id)
if not job:
return jsonify({"error": "Job not found"}), 404
return jsonify({
"status": job["status"],
"error": job.get("error"),
"filename": job.get("filename"),
"transcript": bool(job.get("transcript")),
})
@app.route("/api/history")
def get_history():
rows = load_history()[:50]
for r in rows:
# Truth at read time: a recorded caption-transcript may have been
# deleted, and a manual yt-transcribe sidecar may have appeared since.
path = r.get("transcript") or sidecar_transcript(r.get("file"))
if path and os.path.exists(path):
r["transcript"] = path
r["has_transcript"] = True
if not r.get("transcript_name"):
r["transcript_name"] = os.path.splitext(os.path.basename(path))[0] + ".txt"
else:
r["transcript"] = ""
r["has_transcript"] = False
return jsonify(rows)
@app.route("/api/transcript/<job_id>")
def download_transcript(job_id):
rec = resolve_download(job_id, "file") or resolve_download(job_id, "transcript")
path = (rec.get("transcript") if rec else None) \
or (sidecar_transcript(rec.get("file")) if rec else None)
if not rec or not path or not os.path.exists(path):
return jsonify({"error": "Transcript not found"}), 404
default_name = os.path.splitext(os.path.basename(path))[0] + ".txt"
return send_file(path, as_attachment=True,
download_name=rec.get("transcript_name") or default_name)
@app.route("/api/file/<job_id>")
def download_file(job_id):
rec = resolve_download(job_id, "file")
path = rec.get("file") if rec else None
if not rec or not path or not os.path.exists(path):
return jsonify({"error": "File not found"}), 404
return send_file(path, as_attachment=True,
download_name=rec.get("filename") or os.path.basename(path))
if __name__ == "__main__":
port = int(os.environ.get("PORT", 8899))
host = os.environ.get("HOST", "127.0.0.1")
app.run(host=host, port=port)
+772
View File
@@ -0,0 +1,772 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ReClip — Free Media Downloader</title>
<link rel="icon" href="/static/favicon.svg" type="image/svg+xml">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
:root {
--bg: #f4f1eb;
--fg: #3a3a38;
--accent: #e85d2a;
--accent-hover: #d04e1f;
--muted: #9c9889;
--card: #fff;
--card-border: #e2ded6;
--success: #2d8a4e;
--error: #c43d3d;
--radius: 14px;
--shimmer: linear-gradient(90deg, #ebe8e2 25%, #f0ede7 50%, #ebe8e2 75%);
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'DM Mono', monospace;
background: var(--bg);
color: var(--fg);
min-height: 100vh;
overflow-x: hidden;
}
body::after {
content: '';
position: fixed;
inset: 0;
opacity: 0.03;
pointer-events: none;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E");
background-size: 128px;
}
.page {
max-width: 620px;
margin: 0 auto;
padding: 60px 24px 80px;
}
.brand { margin-bottom: 48px; }
.brand h1 {
font-family: 'Instrument Serif', serif;
font-size: 4.2rem;
font-weight: 400;
letter-spacing: -0.03em;
line-height: 1;
color: var(--fg);
}
.brand h1 em { font-style: italic; color: var(--accent); }
.brand p {
margin-top: 10px;
font-size: 0.78rem;
color: var(--muted);
letter-spacing: 0.04em;
text-transform: uppercase;
}
textarea {
width: 100%;
padding: 18px 20px;
border: 1.5px solid var(--card-border);
border-radius: var(--radius);
background: var(--card);
color: var(--fg);
font-family: 'DM Mono', monospace;
font-size: 0.88rem;
outline: none;
resize: none;
min-height: 56px;
transition: border-color 0.25s, box-shadow 0.25s;
margin-bottom: 6px;
}
textarea:focus {
border-color: var(--accent);
box-shadow: 0 0 0 3px rgba(232, 93, 42, 0.08);
}
textarea::placeholder { color: var(--muted); }
.hint {
font-size: 0.7rem;
color: var(--muted);
margin-bottom: 20px;
letter-spacing: 0.02em;
}
.controls {
display: flex;
gap: 10px;
margin-bottom: 6px;
align-items: center;
}
.pill-group {
display: flex;
border: 1.5px solid var(--card-border);
border-radius: 10px;
overflow: hidden;
background: var(--card);
}
.pill {
padding: 9px 18px;
font-family: 'DM Mono', monospace;
font-size: 0.76rem;
border: none;
background: transparent;
color: var(--muted);
cursor: pointer;
transition: all 0.2s;
letter-spacing: 0.03em;
text-transform: uppercase;
}
.pill.active { background: var(--fg); color: var(--bg); }
.pill:not(.active):hover { color: var(--fg); }
.fetch-btn {
flex: 1;
padding: 10px 20px;
border: none;
border-radius: 10px;
background: var(--accent);
color: #fff;
font-family: 'DM Mono', monospace;
font-size: 0.82rem;
font-weight: 500;
cursor: pointer;
transition: background 0.2s, transform 0.1s;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.fetch-btn:hover { background: var(--accent-hover); }
.fetch-btn:active { transform: scale(0.98); }
.fetch-btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
/* Cards */
.cards { margin-top: 24px; }
.card {
display: flex;
gap: 14px;
border: 1.5px solid var(--card-border);
border-radius: var(--radius);
background: var(--card);
padding: 14px;
margin-bottom: 10px;
animation: slideUp 0.4s cubic-bezier(0.16, 1, 0.3, 1);
}
@keyframes slideUp {
from { opacity: 0; transform: translateY(12px); }
to { opacity: 1; transform: translateY(0); }
}
.card-thumb {
width: 120px;
min-width: 120px;
height: 80px;
border-radius: 8px;
overflow: hidden;
background: var(--card-border);
flex-shrink: 0;
position: relative;
}
.card-thumb img {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
/* No-thumbnail icon */
.card-thumb .no-thumb {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
color: var(--muted);
}
.card-thumb .no-thumb svg {
width: 28px;
height: 28px;
opacity: 0.5;
}
/* Shimmer skeleton for loading state */
.card-thumb.loading {
background: var(--shimmer);
background-size: 200% 100%;
animation: shimmer 1.5s infinite;
}
.skeleton-line {
height: 12px;
border-radius: 4px;
background: var(--shimmer);
background-size: 200% 100%;
animation: shimmer 1.5s infinite;
margin-bottom: 6px;
}
.skeleton-line.short { width: 40%; height: 10px; }
.skeleton-line.medium { width: 75%; }
@keyframes shimmer {
0% { background-position: 200% 0; }
100% { background-position: -200% 0; }
}
.card-body {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
justify-content: center;
}
.card-title {
font-family: 'Instrument Serif', serif;
font-size: 1rem;
line-height: 1.3;
color: var(--fg);
margin-bottom: 2px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.card-meta {
font-size: 0.68rem;
color: var(--muted);
letter-spacing: 0.03em;
text-transform: uppercase;
margin-bottom: 8px;
}
.card-actions {
display: flex;
gap: 6px;
align-items: center;
flex-wrap: wrap;
}
.card-dl-btn {
padding: 6px 14px;
border: none;
border-radius: 7px;
background: var(--fg);
color: var(--bg);
font-family: 'DM Mono', monospace;
font-size: 0.7rem;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
letter-spacing: 0.03em;
text-transform: uppercase;
}
.card-dl-btn:hover { background: #2d2d2a; }
.card-dl-btn:disabled { opacity: 0.4; cursor: not-allowed; }
.card-dl-btn.done { background: var(--success); color: #fff; }
.card-dl-btn.error { background: var(--error); color: #fff; }
.card-status {
font-size: 0.68rem;
color: var(--muted);
}
.card-status.downloading { color: var(--accent); }
.card-status.done { color: var(--success); }
.card-status.error { color: var(--error); }
.q-chip {
padding: 4px 10px;
border: 1.5px solid var(--card-border);
border-radius: 6px;
background: transparent;
color: var(--muted);
font-family: 'DM Mono', monospace;
font-size: 0.65rem;
cursor: pointer;
transition: all 0.2s;
}
.q-chip.active {
border-color: var(--fg);
color: var(--fg);
background: rgba(26,26,24,0.04);
}
.q-chip:hover:not(.active) { border-color: var(--muted); }
/* Error card */
.card.card-error {
border-color: rgba(196, 61, 61, 0.2);
background: rgba(196, 61, 61, 0.03);
}
.card-error-icon {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background: rgba(196, 61, 61, 0.08);
color: var(--error);
}
.card-error-icon svg {
width: 24px;
height: 24px;
}
.card-error-msg {
font-size: 0.72rem;
color: var(--error);
margin-top: 2px;
line-height: 1.4;
}
.card-error-url {
font-size: 0.65rem;
color: var(--muted);
word-break: break-all;
margin-top: 4px;
}
/* Download all bar */
.dl-all-bar {
display: flex;
gap: 10px;
margin-top: 16px;
}
.dl-all-btn {
flex: 1;
padding: 12px;
border: none;
border-radius: 10px;
background: var(--fg);
color: var(--bg);
font-family: 'DM Mono', monospace;
font-size: 0.82rem;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.dl-all-btn:hover { background: #2d2d2a; }
.dl-all-btn:disabled { opacity: 0.4; cursor: not-allowed; }
/* History — same card language as the fetch results */
.hist-h {
font-family: 'Instrument Serif', serif;
font-size: 1.9rem;
font-weight: 400;
letter-spacing: -0.02em;
margin: 44px 0 14px;
color: var(--fg);
}
#history .card { animation: slideUp 0.4s cubic-bezier(0.16, 1, 0.3, 1); }
a.card-dl-btn { text-decoration: none; display: inline-block; }
.spin {
display: inline-block;
width: 10px; height: 10px;
border: 2px solid currentColor;
border-right-color: transparent;
border-radius: 50%;
animation: spin 0.6s linear infinite;
vertical-align: middle;
}
@keyframes spin { to { transform: rotate(360deg); } }
.footer {
margin-top: 48px;
text-align: center;
font-size: 0.68rem;
color: var(--muted);
letter-spacing: 0.05em;
text-transform: uppercase;
line-height: 1.8;
}
/* Mobile */
@media (max-width: 500px) {
.brand h1 { font-size: 3rem; }
.page { padding: 40px 16px 60px; }
.card { flex-direction: column; gap: 10px; }
.card-thumb {
width: 100%;
min-width: unset;
height: 160px;
}
.card-title { white-space: normal; }
.controls { flex-wrap: wrap; }
.fetch-btn { width: 100%; }
}
</style>
</head>
<body>
<div class="page">
<div class="brand">
<h1>Re<em>Clip</em></h1>
<p>Free media downloader</p>
</div>
<textarea id="urls" placeholder="Paste one or more URLs..." rows="2"></textarea>
<p class="hint">Multiple links? Separate with spaces, commas, or newlines.</p>
<div class="controls">
<div class="pill-group">
<button class="pill active" data-format="video" onclick="setFormat(this)">MP4</button>
<button class="pill" data-format="audio" onclick="setFormat(this)">MP3</button>
</div>
<button class="fetch-btn" id="goBtn" onclick="go()">Fetch</button>
</div>
<div id="cards" class="cards"></div>
<div id="history"></div>
<div class="footer">
YouTube &middot; TikTok &middot; Instagram &middot; Twitter/X &middot; Reddit &middot; Facebook<br>
Vimeo &middot; Twitch &middot; Dailymotion &middot; SoundCloud &middot; Loom &middot; Streamable<br>
Pinterest &middot; Tumblr &middot; Threads &middot; LinkedIn &middot; 1000+ more
</div>
</div>
<script>
let currentFormat = 'video';
let cardData = [];
function setFormat(btn) {
document.querySelectorAll('.pill').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
currentFormat = btn.dataset.format;
}
function parseUrls(text) {
return [...new Set(text.split(/[\s,]+/).map(u => u.trim()).filter(u => u.startsWith('http')))];
}
function fmtDur(s) {
if (!s) return '';
const m = Math.floor(s / 60);
const sec = Math.floor(s % 60);
return `${m}:${sec.toString().padStart(2, '0')}`;
}
function esc(s) {
const d = document.createElement('div');
d.textContent = s;
return d.innerHTML;
}
function friendlyError(err) {
if (err.includes('Unsupported URL')) return 'This URL is not supported';
if (err.includes('Video unavailable')) return 'Video is unavailable or private';
if (err.includes('Private video')) return 'This video is private';
if (err.includes('HTTP Error 403')) return 'Access denied by the platform';
if (err.includes('HTTP Error 404')) return 'Video not found';
if (err.includes('copyright')) return 'Video blocked due to copyright';
if (err.includes('geo')) return 'Video not available in your region';
if (err.includes('timed out') || err.includes('Timed out')) return 'Request timed out — try again';
if (err.includes('network') || err.includes('Network')) return 'Network error — check your connection';
return err.length > 80 ? err.slice(0, 80) + '...' : err;
}
document.getElementById('urls').addEventListener('keydown', e => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); go(); }
});
async function go() {
const urls = parseUrls(document.getElementById('urls').value);
if (!urls.length) return;
const btn = document.getElementById('goBtn');
const container = document.getElementById('cards');
btn.disabled = true;
btn.textContent = 'Loading...';
container.innerHTML = '';
cardData = [];
// Check if youtube playlist URL
for (let i = 0; i < urls.length; i++) {
if (urls[i].includes('list=')) {
const res = await fetch('/api/playlist', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url: urls[i] }),
});
const data = await res.json();
if (data.urls) {
// replace playlist URL with individual video URLs
urls.splice(i, 1, ...data.urls);
}
}
}
for (let i = 0; i < urls.length; i++) {
const url = urls[i];
const idx = cardData.length;
cardData.push({ url, status: 'loading' });
renderCard(idx);
try {
const res = await fetch('/api/info', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url }),
});
const data = await res.json();
if (data.error) {
cardData[idx] = { ...cardData[idx], status: 'info-error', error: data.error };
} else {
cardData[idx] = {
...cardData[idx],
status: 'ready',
title: data.title || '',
thumbnail: data.thumbnail || '',
duration: data.duration,
uploader: data.uploader || '',
formats: data.formats || [],
selectedFormatId: data.formats?.[0]?.id || null,
};
}
} catch (err) {
cardData[idx] = { ...cardData[idx], status: 'info-error', error: err.message };
}
renderCard(idx);
}
if (cardData.filter(c => c.status === 'ready').length > 1) {
renderDownloadAll();
}
btn.disabled = false;
btn.textContent = 'Fetch';
}
function renderCard(idx) {
const c = cardData[idx];
let el = document.getElementById(`card-${idx}`);
if (!el) {
el = document.createElement('div');
el.id = `card-${idx}`;
el.className = 'card';
document.getElementById('cards').appendChild(el);
}
// Loading skeleton
if (c.status === 'loading') {
el.className = 'card';
el.innerHTML = `
<div class="card-thumb loading"></div>
<div class="card-body">
<div class="skeleton-line medium"></div>
<div class="skeleton-line short"></div>
</div>
`;
return;
}
// Error state
if (c.status === 'info-error') {
el.className = 'card card-error';
el.innerHTML = `
<div class="card-thumb">
<div class="card-error-icon">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
</div>
</div>
<div class="card-body">
<div class="card-title" style="color:var(--error)">Could not fetch video</div>
<div class="card-error-msg">${esc(friendlyError(c.error || ''))}</div>
<div class="card-error-url">${esc(c.url)}</div>
</div>
`;
return;
}
// Ready / downloading / done / error states
el.className = 'card';
const isAudio = currentFormat === 'audio';
let thumbHtml;
if (isAudio) {
thumbHtml = `<div class="no-thumb" style="color:var(--accent)"><svg viewBox="0 0 24 24" fill="currentColor" stroke="none"><polygon points="5 3 19 12 5 21 5 3"/></svg></div>`;
} else if (c.thumbnail) {
thumbHtml = `<img src="${c.thumbnail}" alt="">`;
} else {
thumbHtml = `<div class="no-thumb"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="2"/><circle cx="8" cy="8" r="1.5"/><path d="m21 15-5-5L5 21"/></svg></div>`;
}
let qualityChips = '';
if (!isAudio && c.formats && c.formats.length > 1) {
qualityChips = c.formats.map(f =>
`<button class="q-chip${f.id === c.selectedFormatId ? ' active' : ''}" onclick="pickFormat(${idx}, '${f.id}')">${f.label}</button>`
).join('');
}
let actionHtml = '';
if (c.status === 'ready') {
actionHtml = `<button class="card-dl-btn" onclick="dlCard(${idx})">Download</button>${qualityChips}`;
} else if (c.status === 'downloading') {
actionHtml = `<span class="card-status downloading"><span class="spin"></span> Downloading...</span>`;
} else if (c.status === 'done') {
actionHtml = `<button class="card-dl-btn done" onclick="saveCard(${idx})">Save</button>` +
(c.hasTranscript ? `<button class="card-dl-btn" onclick="saveTranscript(${idx})">Transcript</button>` : '') +
`<span class="card-status done">${esc(c.filename || '')}</span>`;
} else if (c.status === 'error') {
actionHtml = `<button class="card-dl-btn" onclick="dlCard(${idx})">Retry</button>
<span class="card-status error">${esc(friendlyError(c.error || 'Download failed'))}</span>`;
}
el.innerHTML = `
<div class="card-thumb">${thumbHtml}</div>
<div class="card-body">
<div class="card-title">${esc(c.title || 'Untitled')}</div>
<div class="card-meta">${esc(c.uploader)}${c.duration ? ' · ' + fmtDur(c.duration) : ''}</div>
<div class="card-actions">${actionHtml}</div>
</div>
`;
}
function renderDownloadAll() {
const existing = document.getElementById('dl-all-bar');
if (existing) existing.remove();
const bar = document.createElement('div');
bar.id = 'dl-all-bar';
bar.className = 'dl-all-bar';
bar.innerHTML = `<button class="dl-all-btn" onclick="dlAll()">Download All</button>`;
document.getElementById('cards').appendChild(bar);
}
function pickFormat(idx, formatId) {
cardData[idx].selectedFormatId = formatId;
renderCard(idx);
}
async function dlCard(idx) {
const c = cardData[idx];
c.status = 'downloading';
c.error = null;
renderCard(idx);
try {
const res = await fetch('/api/download', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
url: c.url,
format: currentFormat,
format_id: c.selectedFormatId,
title: c.title || '',
thumbnail: c.thumbnail || '',
}),
});
const data = await res.json();
if (data.error) {
c.status = 'error';
c.error = data.error;
renderCard(idx);
return;
}
c.jobId = data.job_id;
pollCard(idx);
} catch (err) {
c.status = 'error';
c.error = err.message;
renderCard(idx);
}
}
function pollCard(idx) {
const c = cardData[idx];
const iv = setInterval(async () => {
try {
const res = await fetch(`/api/status/${c.jobId}`);
const data = await res.json();
if (data.status === 'done') {
clearInterval(iv);
c.status = 'done';
c.filename = data.filename;
c.hasTranscript = !!data.transcript;
renderCard(idx);
saveCard(idx);
if (c.hasTranscript) saveTranscript(idx);
} else if (data.status === 'error') {
clearInterval(iv);
c.status = 'error';
c.error = data.error;
renderCard(idx);
}
} catch {
clearInterval(iv);
c.status = 'error';
c.error = 'Lost connection to server';
renderCard(idx);
}
}, 1000);
}
function saveCard(idx) {
const c = cardData[idx];
if (!c.jobId) return;
const a = document.createElement('a');
a.href = `/api/file/${c.jobId}`;
a.download = c.filename || '';
a.click();
}
function saveTranscript(idx) {
const c = cardData[idx];
if (!c.jobId || !c.hasTranscript) return;
const a = document.createElement('a');
a.href = `/api/transcript/${c.jobId}`;
a.download = (c.filename || 'transcript').replace(/\.[^.]+$/, '') + '.txt';
a.click();
}
async function dlAll() {
const btn = document.querySelector('.dl-all-btn');
if (btn) { btn.disabled = true; btn.textContent = 'Downloading...'; }
for (let i = 0; i < cardData.length; i++) {
if (cardData[i].status === 'ready') {
await dlCard(i);
}
}
if (btn) { btn.disabled = false; btn.textContent = 'Download All'; }
}
function fmtSize(bytes) {
if (!bytes) return '';
const mb = bytes / 1048576;
return mb >= 1024 ? (mb / 1024).toFixed(2) + ' GB' : mb.toFixed(1) + ' MB';
}
async function loadHistory() {
try {
const res = await fetch('/api/history');
const rows = await res.json();
const box = document.getElementById('history');
if (!Array.isArray(rows) || !rows.length) return;
const items = rows.map(r => {
let thumbHtml;
if (r.thumbnail) {
thumbHtml = `<img src="${r.thumbnail}" alt="">`;
} else {
thumbHtml = `<div class="no-thumb"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="2"/><circle cx="8" cy="8" r="1.5"/><path d="m21 15-5-5L5 21"/></svg></div>`;
}
const flag = r.has_transcript
? `<span class="card-status done">transcript ✓</span>`
: `<span class="card-status">no transcript</span>`;
return `
<div class="card">
<div class="card-thumb">${thumbHtml}</div>
<div class="card-body">
<div class="card-title">${esc(r.title || r.filename || r.url || 'Untitled')}</div>
<div class="card-meta">${esc(r.date || '')}${r.size ? ' · ' + fmtSize(r.size) : ''} · <span class="${r.has_transcript ? 'card-status done' : ''}">${r.has_transcript ? 'transcript ✓' : 'no transcript'}</span></div>
<div class="card-actions">
<a class="card-dl-btn" href="/api/file/${r.job_id}" download>Save</a>
${r.has_transcript ? `<a class="card-dl-btn" href="/api/transcript/${r.job_id}" download>Transcript</a>` : ''}
</div>
</div>
</div>`;
}).join('');
box.innerHTML = `<h2 class="hist-h">History</h2>${items}`;
} catch { /* history unavailable */ }
}
loadHistory();
</script>
</body>
</html>
+389
View File
@@ -0,0 +1,389 @@
diff --git a/app.py b/app.py
index 2b5eaa5..1dfbbd0 100644
--- a/app.py
+++ b/app.py
@@ -2,8 +2,11 @@ import os
import uuid
import glob
import json
+import re
+import hashlib
import subprocess
import threading
+import time
from flask import Flask, request, jsonify, send_file, render_template
app = Flask(__name__)
@@ -12,6 +15,97 @@ os.makedirs(DOWNLOAD_DIR, exist_ok=True)
jobs = {}
+HISTORY_FILE = os.path.join(DOWNLOAD_DIR, "history.json")
+_history_lock = threading.Lock()
+
+
+def load_history():
+ try:
+ with open(HISTORY_FILE, encoding="utf-8") as fh:
+ data = json.load(fh)
+ return data if isinstance(data, list) else []
+ except Exception:
+ return []
+
+
+def save_history(history):
+ try:
+ tmp = HISTORY_FILE + ".tmp"
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump(history, fh, indent=2)
+ os.replace(tmp, HISTORY_FILE)
+ except OSError:
+ pass
+
+
+def sidecar_transcript(file_path):
+ """Manual-fallback transcripts (yt-transcribe <file>) live beside the
+ media as <stem>.txt — recognize them at read time so history stays
+ truthful without re-downloading anything."""
+ if not file_path:
+ return None
+ stem = os.path.splitext(file_path)[0] + ".txt"
+ return stem if os.path.exists(stem) else None
+
+
+def record_history(job):
+ """Persist the completed job so history + file/transcript downloads
+ survive process restarts (downloads dir is the mapped volume)."""
+ with _history_lock:
+ history = [h for h in load_history() if h.get("job_id") != job.get("job_id")]
+ history.insert(0, {
+ "job_id": job.get("job_id"),
+ "url": job.get("url", ""),
+ "title": job.get("title", ""),
+ "thumbnail": job.get("thumbnail", ""),
+ "filename": job.get("filename", ""),
+ "file": job.get("file", ""),
+ "transcript": job.get("transcript") or "",
+ "transcript_name": job.get("transcript_name", ""),
+ "has_transcript": bool(job.get("transcript")),
+ "size": os.path.getsize(job["file"]) if job.get("file") and os.path.exists(job["file"]) else 0,
+ "date": time.strftime("%Y-%m-%d %H:%M:%S"),
+ })
+ save_history(history[:200])
+
+
+MEDIA_EXTS = (".mp4", ".mkv", ".webm", ".m4a", ".mp3", ".flac", ".mov", ".avi", ".wav", ".ts")
+
+
+def backfill_history():
+ """Add on-disk downloads that predate history.json (or were dropped into
+ the downloads dir manually) so the whole library shows up on the page.
+ The transcript flag is resolved live at read time, so backfilled entries
+ pick up manual yt-transcribe sidecars automatically."""
+ for name in sorted(os.listdir(DOWNLOAD_DIR)):
+ path = os.path.join(DOWNLOAD_DIR, name)
+ if not os.path.isfile(path) or not name.lower().endswith(MEDIA_EXTS):
+ continue
+ with _history_lock:
+ history = load_history()
+ if any(h.get("file") == path for h in history):
+ continue
+ stem = os.path.splitext(name)[0]
+ # a 10-hex stem is a reclip job id — the real title wasn't kept
+ title = "" if re.fullmatch(r"[0-9a-f]{10}", stem) else stem
+ history.insert(0, {
+ "job_id": hashlib.sha1(path.encode()).hexdigest()[:10],
+ "url": "",
+ "title": title,
+ "filename": name,
+ "file": path,
+ "transcript": "",
+ "transcript_name": "",
+ "has_transcript": False,
+ "size": os.path.getsize(path),
+ "date": time.strftime("%Y-%m-%d %H:%M:%S",
+ time.localtime(os.path.getmtime(path))),
+ })
+ save_history(history[:200])
+
+
+backfill_history()
+
def parse_ytdlp_json(stdout):
"""Parse yt-dlp JSON output.
@@ -29,6 +123,53 @@ def parse_ytdlp_json(stdout):
raise ValueError("yt-dlp returned no data")
+def fetch_transcript(url, chosen_path):
+ """Best-effort transcript via yt-dlp captions (manual or auto-generated;
+ includes X's auto-captions). Writes <video stem>.txt beside the download.
+ Returns the .txt path, or None when the video has no captions. Never
+ raises — a transcript is a bonus, not a download requirement."""
+ stem = os.path.splitext(chosen_path)[0]
+ try:
+ cmd = ["yt-dlp", "--no-playlist", "--skip-download", "--no-warnings",
+ "--write-subs", "--write-auto-subs",
+ "--sub-langs", "en,en-orig",
+ "--sub-format", "vtt",
+ "-o", stem + ".%(ext)s", url]
+ subprocess.run(cmd, capture_output=True, text=True, timeout=180)
+
+ vtts = glob.glob(stem + ".*.vtt")
+ if not vtts:
+ return None
+ vtts.sort(key=lambda p: (0 if p.endswith(".en.vtt") else 1, p))
+
+ lines, prev = [], None
+ with open(vtts[0], encoding="utf-8", errors="replace") as fh:
+ for raw in fh:
+ line = raw.strip()
+ if (not line or "-->" in line
+ or line.startswith(("WEBVTT", "Kind:", "Language:", "NOTE", "STYLE"))
+ or re.match(r"^\d+$", line)):
+ continue
+ line = re.sub(r"<[^>]+>", "", line)
+ if line and line != prev:
+ lines.append(line)
+ prev = line
+
+ txt = stem + ".txt"
+ with open(txt, "w", encoding="utf-8") as out:
+ out.write(" ".join(lines) + "\n")
+
+ for f in vtts:
+ try:
+ os.remove(f)
+ except OSError:
+ pass
+
+ return txt if lines else None
+ except Exception:
+ return None
+
+
def run_download(job_id, url, format_choice, format_id):
job = jobs[job_id]
out_template = os.path.join(DOWNLOAD_DIR, f"{job_id}.%(ext)s")
@@ -81,6 +222,12 @@ def run_download(job_id, url, format_choice, format_id):
job["filename"] = f"{safe_title}{ext}" if safe_title else os.path.basename(chosen)
else:
job["filename"] = os.path.basename(chosen)
+
+ # Best-effort transcript sidecar: yt-dlp captions (X auto-captions
+ # included) -> plain .txt next to the chosen file. Never fails the job.
+ job["transcript"] = fetch_transcript(url, chosen)
+ job["transcript_name"] = os.path.splitext(job["filename"])[0] + ".txt"
+ record_history(job)
except subprocess.TimeoutExpired:
job["status"] = "error"
job["error"] = "Download timed out (5 min limit)"
@@ -175,7 +322,8 @@ def start_download():
return jsonify({"error": "No URL provided"}), 400
job_id = uuid.uuid4().hex[:10]
- jobs[job_id] = {"status": "downloading", "url": url, "title": title}
+ jobs[job_id] = {"job_id": job_id, "status": "downloading", "url": url, "title": title,
+ "thumbnail": (data.get("thumbnail") or "")[:500]}
thread = threading.Thread(target=run_download, args=(job_id, url, format_choice, format_id))
thread.daemon = True
@@ -184,6 +332,18 @@ def start_download():
return jsonify({"job_id": job_id})
+def resolve_download(job_id, key):
+ """Find a completed job in memory, falling back to the on-disk history
+ (paths point into DOWNLOAD_DIR, so they survive restarts)."""
+ job = jobs.get(job_id)
+ if job and job.get("status") == "done" and job.get(key):
+ return job
+ for entry in load_history():
+ if entry.get("job_id") == job_id and entry.get(key):
+ return entry
+ return None
+
+
@app.route("/api/status/<job_id>")
def check_status(job_id):
job = jobs.get(job_id)
@@ -193,15 +353,48 @@ def check_status(job_id):
"status": job["status"],
"error": job.get("error"),
"filename": job.get("filename"),
+ "transcript": bool(job.get("transcript")),
})
+@app.route("/api/history")
+def get_history():
+ rows = load_history()[:50]
+ for r in rows:
+ # Truth at read time: a recorded caption-transcript may have been
+ # deleted, and a manual yt-transcribe sidecar may have appeared since.
+ path = r.get("transcript") or sidecar_transcript(r.get("file"))
+ if path and os.path.exists(path):
+ r["transcript"] = path
+ r["has_transcript"] = True
+ if not r.get("transcript_name"):
+ r["transcript_name"] = os.path.splitext(os.path.basename(path))[0] + ".txt"
+ else:
+ r["transcript"] = ""
+ r["has_transcript"] = False
+ return jsonify(rows)
+
+
+@app.route("/api/transcript/<job_id>")
+def download_transcript(job_id):
+ rec = resolve_download(job_id, "file") or resolve_download(job_id, "transcript")
+ path = (rec.get("transcript") if rec else None) \
+ or (sidecar_transcript(rec.get("file")) if rec else None)
+ if not rec or not path or not os.path.exists(path):
+ return jsonify({"error": "Transcript not found"}), 404
+ default_name = os.path.splitext(os.path.basename(path))[0] + ".txt"
+ return send_file(path, as_attachment=True,
+ download_name=rec.get("transcript_name") or default_name)
+
+
@app.route("/api/file/<job_id>")
def download_file(job_id):
- job = jobs.get(job_id)
- if not job or job["status"] != "done":
- return jsonify({"error": "File not ready"}), 404
- return send_file(job["file"], as_attachment=True, download_name=job["filename"])
+ rec = resolve_download(job_id, "file")
+ path = rec.get("file") if rec else None
+ if not rec or not path or not os.path.exists(path):
+ return jsonify({"error": "File not found"}), 404
+ return send_file(path, as_attachment=True,
+ download_name=rec.get("filename") or os.path.basename(path))
if __name__ == "__main__":
diff --git a/templates/index.html b/templates/index.html
index 1f566d1..4807aa1 100644
--- a/templates/index.html
+++ b/templates/index.html
@@ -343,6 +343,18 @@
.dl-all-btn:hover { background: #2d2d2a; }
.dl-all-btn:disabled { opacity: 0.4; cursor: not-allowed; }
+ /* History — same card language as the fetch results */
+ .hist-h {
+ font-family: 'Instrument Serif', serif;
+ font-size: 1.9rem;
+ font-weight: 400;
+ letter-spacing: -0.02em;
+ margin: 44px 0 14px;
+ color: var(--fg);
+ }
+ #history .card { animation: slideUp 0.4s cubic-bezier(0.16, 1, 0.3, 1); }
+ a.card-dl-btn { text-decoration: none; display: inline-block; }
+
.spin {
display: inline-block;
width: 10px; height: 10px;
@@ -399,6 +411,7 @@
</div>
<div id="cards" class="cards"></div>
+ <div id="history"></div>
<div class="footer">
YouTube &middot; TikTok &middot; Instagram &middot; Twitter/X &middot; Reddit &middot; Facebook<br>
@@ -586,8 +599,9 @@
} else if (c.status === 'downloading') {
actionHtml = `<span class="card-status downloading"><span class="spin"></span> Downloading...</span>`;
} else if (c.status === 'done') {
- actionHtml = `<button class="card-dl-btn done" onclick="saveCard(${idx})">Save</button>
- <span class="card-status done">${esc(c.filename || '')}</span>`;
+ actionHtml = `<button class="card-dl-btn done" onclick="saveCard(${idx})">Save</button>` +
+ (c.hasTranscript ? `<button class="card-dl-btn" onclick="saveTranscript(${idx})">Transcript</button>` : '') +
+ `<span class="card-status done">${esc(c.filename || '')}</span>`;
} else if (c.status === 'error') {
actionHtml = `<button class="card-dl-btn" onclick="dlCard(${idx})">Retry</button>
<span class="card-status error">${esc(friendlyError(c.error || 'Download failed'))}</span>`;
@@ -634,6 +648,7 @@
format: currentFormat,
format_id: c.selectedFormatId,
title: c.title || '',
+ thumbnail: c.thumbnail || '',
}),
});
const data = await res.json();
@@ -662,8 +677,10 @@
clearInterval(iv);
c.status = 'done';
c.filename = data.filename;
+ c.hasTranscript = !!data.transcript;
renderCard(idx);
saveCard(idx);
+ if (c.hasTranscript) saveTranscript(idx);
} else if (data.status === 'error') {
clearInterval(iv);
c.status = 'error';
@@ -688,6 +705,15 @@
a.click();
}
+ function saveTranscript(idx) {
+ const c = cardData[idx];
+ if (!c.jobId || !c.hasTranscript) return;
+ const a = document.createElement('a');
+ a.href = `/api/transcript/${c.jobId}`;
+ a.download = (c.filename || 'transcript').replace(/\.[^.]+$/, '') + '.txt';
+ a.click();
+ }
+
async function dlAll() {
const btn = document.querySelector('.dl-all-btn');
if (btn) { btn.disabled = true; btn.textContent = 'Downloading...'; }
@@ -700,6 +726,47 @@
if (btn) { btn.disabled = false; btn.textContent = 'Download All'; }
}
+
+ function fmtSize(bytes) {
+ if (!bytes) return '';
+ const mb = bytes / 1048576;
+ return mb >= 1024 ? (mb / 1024).toFixed(2) + ' GB' : mb.toFixed(1) + ' MB';
+ }
+
+ async function loadHistory() {
+ try {
+ const res = await fetch('/api/history');
+ const rows = await res.json();
+ const box = document.getElementById('history');
+ if (!Array.isArray(rows) || !rows.length) return;
+ const items = rows.map(r => {
+ let thumbHtml;
+ if (r.thumbnail) {
+ thumbHtml = `<img src="${r.thumbnail}" alt="">`;
+ } else {
+ thumbHtml = `<div class="no-thumb"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="2"/><circle cx="8" cy="8" r="1.5"/><path d="m21 15-5-5L5 21"/></svg></div>`;
+ }
+ const flag = r.has_transcript
+ ? `<span class="card-status done">transcript ✓</span>`
+ : `<span class="card-status">no transcript</span>`;
+ return `
+ <div class="card">
+ <div class="card-thumb">${thumbHtml}</div>
+ <div class="card-body">
+ <div class="card-title">${esc(r.title || r.filename || r.url || 'Untitled')}</div>
+ <div class="card-meta">${esc(r.date || '')}${r.size ? ' · ' + fmtSize(r.size) : ''} · <span class="${r.has_transcript ? 'card-status done' : ''}">${r.has_transcript ? 'transcript ✓' : 'no transcript'}</span></div>
+ <div class="card-actions">
+ <a class="card-dl-btn" href="/api/file/${r.job_id}" download>Save</a>
+ ${r.has_transcript ? `<a class="card-dl-btn" href="/api/transcript/${r.job_id}" download>Transcript</a>` : ''}
+ </div>
+ </div>
+ </div>`;
+ }).join('');
+ box.innerHTML = `<h2 class="hist-h">History</h2>${items}`;
+ } catch { /* history unavailable */ }
+ }
+
+ loadHistory();
</script>
</body>
</html>
+115 -2
View File
@@ -13,7 +13,67 @@ The firstmate crew dispatch + Gitea PR helper are wired by `darwin-rebuild`, but
cd ~/Documents/investor-flow
git remote set-url origin http://unraid.local:3003/transnet/investor-flow
Verify: `fm` launches OpenCode 2 as the first mate (isolated `~/.config/opencode2`); `oc2 --version` prints an OpenCode 2 version; `pi --list-models mimo` shows `opencode-go/mimo-v2.5-pro`; `tea pulls list --repo transnet/investor-flow` works.
Verify: `fm` and `fm-oc2` launch OpenCode 2 as the first mate and `fm-pi` is the explicit Pi fallback; `oc2 --version` prints the Homebrew opencode version; `pi --list-models mimo` shows `opencode-go/mimo-v2.5-pro`; `tea pulls list --repo transnet/investor-flow` works.
## firstmate launcher and crew model routing
`fm` is the permanent firstmate launcher. `fm-oc2` is the same launcher under its explicit OpenCode 2 name, so both aliases expand to the same command. They change to `~/Documents/firstmate` and execute `~/.local/bin/oc2`, which runs the Homebrew OpenCode build with the isolated `~/.config/opencode2/opencode.json` config. `fm-pi` starts Pi instead and remains only an explicit fallback. Never make Pi the default launcher.
The three aliases share one firstmate home. They read the same task records, inbox, and state. Each tool keeps its own chat history, so a conversation in OpenCode 2 does not appear in Pi, and the reverse. Quit the running primary before you start the other one. A single firstmate home serves one primary at a time.
`home.nix` owns all three aliases, so a rebuild regenerates them. The installed `~/.zshrc` changes only at the next activation.
Worker routing lives in `home/.config/firstmate/crew-dispatch.json`, which is symlinked to `~/Documents/firstmate/config/crew-dispatch.json`:
| Task | Harness | Model |
| --- | --- | --- |
| Default crewmates and scouts | opencode | opencode-go/deepseek-v4.1-flash |
| Documentation writing, updating, or review | opencode | opencode-go/beam-free |
| UI work with image context | opencode | opencode-go/deepseek-v4.1-flash |
| Design, architecture, and design review (preserved exception) | pi | openai-codex/gpt-6.1-sol at xhigh |
Firstmate matches the `when` text with judgment. It then passes concrete `--harness` and `--model` flags to `fm-spawn.sh`. The file has no Pi default.
`~/Documents/firstmate/config/crew-harness` stays `opencode`. `home.activation.firstmate` seeds it only when the file is absent, so a captain edit survives a rebuild.
The model IDs above were listed from a neutral directory with `OPENCODE_CONFIG=~/.config/opencode2/opencode.json opencode models`. Both `opencode-go/deepseek-v4.1-flash` and `opencode-go/beam-free` are exact IDs.
### no-mistakes pipeline models
The captain confirmed the split on 2026-11-15. Leave it unchanged:
- execution tool: Pi (`agent: [pi]`)
- general steps and fixers: `opencode-go/deepseek-v4.1-flash`
- reviewer: `opencode-go/glm-5.3-flash`
`home.activation.noMistakes` adds `agent_config` and `review_agents` only when those keys are absent. The live `~/.no-mistakes/config.yaml` also sets `agent_path_override.opencode`, which stays inactive while the execution tool is Pi. This repository has no `.no-mistakes.yaml`, so no repo-level override applies. Firstmate's own `.no-mistakes.yaml` applies only to the firstmate repository. Do not edit the live no-mistakes config by hand.
### Checks
```bash
./tests/fm-launcher.sh --live # installed zshrc; fails while it still launches Pi
./tests/fm-launcher.sh # generated zshrc; must pass
./tests/crew-dispatch.sh # routing via firstmate, model IDs via opencode models
./tests/run.sh # all checks
```
The launcher check sources the real generated zshrc in an interactive zsh. A `pi` spy on PATH and an `OPENCODE2_BIN` spy capture the launch of `fm`, `fm-oc2`, and `fm-pi`, record the working directory, and exit at once, so no firstmate session starts.
### Install after merge
The Nix sources in this repository are the durable record. The live files are generated, so do not edit them.
1. Merge the reviewed branch into the default branch.
2. Confirm `readlink ~/.dotfiles` names the checkout that holds the merged commit.
3. Run `./rebuild.sh` from that checkout.
4. Run `./tests/fm-launcher.sh --live` and `./tests/crew-dispatch.sh`.
5. Open a fresh shell and run `alias fm fm-oc2 fm-pi`. `fm` and `fm-oc2` must show `exec /Users/laptran/.local/bin/oc2`, and `fm-pi` must show `exec pi`.
### Checkout topology and safe installation
`rebuild.sh` points `~/.dotfiles` at its own directory and then builds `~/.dotfiles#lt-mbp`. On 2026-11-15, `~/.dotfiles` resolved to `/Users/laptran/Documents/firstmate/projects/dotfiles`. A second checkout at `/Users/laptran/Documents/dotfiles` carried an uncommitted `home.nix` that changed `fm` back to `pi` and seeded `crew-harness` as `pi`. A rebuild from that checkout would restore the Pi default. Do not run `rebuild.sh` from a checkout with that edit, and do not repoint `~/.dotfiles` by hand.
This follows the NIST SP 800-128 Rev. 1 (2019) Section 3.3 "Controlling Configuration Change" (CM-3) practice: route every change through review and approval, test it, record it in version control, and restrict who can change the operational configuration. The 2011 edition is withdrawn and superseded by Revision 1.
## security-audit skill (agent security reviews)
@@ -35,7 +95,60 @@ Agent scope: the Skills CLI installs the bundle once under `~/.agents/skills/sec
The activation is idempotent and non-interactive: it skips the install when both the canonical copy and the Claude Code link exist, and a failed download only warns so the rebuild still completes. Trigger it in an agent with "security audit this codebase".
Sandbox limitation: the skill's README requires an OS-enforced sandbox (no external network, sanitized environment, resource limits, scratch-only writes) before it may run target-controlled builds, tests, browser automation, emulators, fuzzers, or fixtures. This Nix setup installs the skill only and creates no sandbox. Without one, the workflow keeps such leads as `needs_validation` rather than executing target code.
Sandbox: the skill's README requires an OS-enforced sandbox (no external network, sanitized environment, resource limits, scratch-only writes) before it may run target-controlled builds, tests, browser automation, emulators, fuzzers, or fixtures. `security-audit-sandbox` below provides that sandbox. Run target code only through it; otherwise the workflow keeps such leads as `needs_validation` rather than executing target code.
## Security audit sandbox
`security-audit-sandbox` (installed as `~/.local/bin/security-audit-sandbox`) runs untrusted target code in a Docker container. It is for target code only: do not run the audit agent or your own tools inside it.
```bash
security-audit-sandbox start ~/code/myapp [--image node:22-bookworm] [--exclude dist]...
security-audit-sandbox exec ~/code/myapp [--timeout 600] -- npm test
security-audit-sandbox stop ~/code/myapp [--keep]
security-audit-sandbox status ~/code/myapp
```
`start` canonicalizes the app path, copies the app to `~/security-audit-runs/<slug>.XXXXXX`, and starts a detached container. The original app directory is never mounted into the container, so the copy is the only thing the target code can see.
Image resolution order:
1. `--image`
2. `IMAGE=` in the app's `security-audit.conf`
3. Inference: `package.json` gives `node:22-bookworm`, `pyproject.toml` or `requirements.txt` gives `python:3.12-slim`, `go.mod` gives `golang:1.24-bookworm`, `Cargo.toml` gives `rust:1-bookworm`, and `Gemfile` gives `ruby:3.3-bookworm`.
`start` stops with an error when nothing resolves an image. To support another runtime, add a marker file mapping or pass `--image`.
The optional `security-audit.conf` in the app root holds simple `KEY=value` lines. It is parsed, never sourced:
```ini
IMAGE=node:22-bookworm
EXCLUDE="node_modules dist coverage"
```
`EXCLUDE=` is a whitespace-separated list, and the key may be repeated: every `EXCLUDE=` line applies. CLI `--exclude` patterns are added on top of it. The copy always excludes `.git`, `.env*`, and the top-level `/data` directory, so secrets and live data stay on the host.
Container controls:
- `--network none`: no external network, only loopback for local tests.
- `--read-only` root with writes limited to the bind-mounted scratch directory at `/scratch`, plus a 512 MiB tmpfs at `/tmp`.
- `HOME=/scratch/home`, `TMPDIR=/scratch/tmp`, and `XDG_CACHE_HOME=/scratch/cache`.
- Runs as your host UID:GID, with `--cap-drop ALL`, `no-new-privileges`, and `--init`.
- `--memory 4g`, `--cpus 2`, `--pids-limit 256`, and `nofile=1024:1024`.
- `fsize=104857600` (100 MiB) when the Docker host accepts it. Docker Desktop on macOS may refuse `fsize`; the wrapper then starts without only that cap and prints a warning.
`exec` runs the command from `/scratch/app` under `timeout --signal=KILL`, default 600 seconds. It passes no host environment variables. If the image has no `timeout` binary, or its `timeout` does not enforce the `--signal=KILL` wall-clock limit, `exec` refuses to run rather than dropping the limit.
`stop` removes the container, the state file, and the run directory. Pass `--keep` to keep the run directory for inspection. State lives under `${XDG_STATE_HOME:-~/.local/state}/security-audit-sandbox` and is keyed by the canonical app path, so `exec`, `stop`, and `status` find the same run.
Use dummy data only. The exclusions cover common secrets and the top-level `data` directory, not every possible secret path. Review the copied tree, or add `--exclude` patterns, before you run a target that reads credentials from unexpected places. Audit findings do not belong in this repo or in the run directory.
## pstack skills (pinned on every rebuild)
`home.activation.pstackSkills` restores the eleven adopted pstack skills into `~/.agents/skills`, the shared user-level skill directory that the security-audit section describes. The source is `https://github.com/cursor/plugins` at a fixed commit (folder `pstack/skills`), pinned by the `pstackSkills` `fetchFromGitHub` in `home.nix`. That pin is the only record of the commit in this repo: to move to newer upstream content, change `rev` and `hash` together, then rerun `./rebuild.sh`.
Each run removes and recopies only those eleven directories, so a renamed upstream file never lingers and every other skill in `~/.agents/skills` stays untouched, including an existing tdd skill. `tdd` is skipped on purpose: an existing user-level tdd skill owns that name, so the pstack copy is never installed. The block adds no `~/.claude/skills` link, so Claude Code does not see these eleven skills.
Why these eleven skills exist is recorded in firstmate's `docs/adopted-skills.md`, outside this repo.
## OpenSuperWhisper (local voice input)
+64 -13
View File
@@ -1,7 +1,8 @@
#!/usr/bin/env bash
# Rebuild nix-darwin + home-manager. Rotates stale home-manager *.backup files
# so a second switch never fails with "would be clobbered".
# Also upgrades grok-build and installs OpenCode 1.x (stable CLI for free-tier).
# Also updates flake inputs, upgrades grok-build, removes retired npm OpenCode
# packages, updates no-mistakes, and updates pi extensions.
set -euo pipefail
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
ln -sfn "$DIR" ~/.dotfiles
@@ -15,20 +16,51 @@ else
echo "==> WARNING: grok-build upgrade failed (network issue). Skipping."
fi
# Install OpenCode 1.x (stable CLI, binary "opencode") if absent.
# Required for free-tier models; opencode2 beta returns HTTP 426 on those endpoints.
# Uses Homebrew's npm (not Nix's npm) to avoid EACCES on the store.
# Skip if npm is unavailable (e.g., network issues preventing fetch).
OPENCODE_BIN=/opt/homebrew/bin/opencode
if [ ! -x "$OPENCODE_BIN" ]; then
echo "==> Installing OpenCode 1.x (stable) via Homebrew npm..."
if /opt/homebrew/bin/npm install -g --allow-scripts=opencode-ai opencode-ai@1.18 2>&1; then
echo "==> OpenCode 1.x installed successfully"
# Remove retired npm OpenCode installs if an older rebuild installed them:
# the `@opencode-ai/cli` beta and the older `opencode-ai` CLI. The Homebrew
# `opencode` formula declared in configuration.nix is now the only OpenCode
# install, unpinned so it tracks the latest release. The guard is a local check
# for npm, so a rebuild without npm skips this instead of failing.
NPM=/opt/homebrew/bin/npm
if [ -x "$NPM" ] && npm_root="$("$NPM" root -g 2>/dev/null)"; then
for pkg in @opencode-ai/cli opencode-ai; do
if [ -d "$npm_root/$pkg" ]; then
if "$NPM" uninstall -g "$pkg" >/dev/null 2>&1; then
echo "==> Removed retired npm package $pkg"
else
echo "==> WARNING: $pkg removal failed. Remove it manually: $NPM uninstall -g $pkg"
fi
fi
done
fi
# `opencode` links without --overwrite, so any npm shim left in the Homebrew
# prefix aborts the switch's brew bundle link step. Drop the retired packages'
# shims directly, which also covers a failed uninstall and a missing npm.
for link in /opt/homebrew/bin/*; do
case "$(readlink "$link" 2>/dev/null || true)" in
*/node_modules/@opencode-ai/cli/* | */node_modules/opencode-ai/*)
rm -f "$link"
echo "==> Removed stale OpenCode npm shim $link"
;;
esac
done
echo "==> Updating no-mistakes..."
NO_MISTAKES_BIN="$HOME/.no-mistakes/bin/no-mistakes"
if [ -x "$NO_MISTAKES_BIN" ]; then
if "$NO_MISTAKES_BIN" update 2>&1; then
echo "==> no-mistakes update complete"
else
echo "==> WARNING: OpenCode 1.x installation failed (network issue). Skipping."
echo "==> WARNING: no-mistakes update failed. Skipping."
fi
elif command -v no-mistakes >/dev/null 2>&1; then
if no-mistakes update 2>&1; then
echo "==> no-mistakes update complete"
else
echo "==> WARNING: no-mistakes update failed. Skipping."
fi
else
echo "==> OpenCode 1.x already installed: $(${OPENCODE_BIN} --version)"
echo "==> WARNING: no-mistakes not found. Skipping update."
fi
stamp="$(date +%Y%m%d-%H%M%S)"
@@ -47,6 +79,7 @@ managed=(
"$HOME/.config/opencode2/AGENTS.md"
"$HOME/.local/bin/oc2"
"$HOME/.local/bin/opencode-go-token"
"$HOME/.local/bin/opencode-go-key-sync"
"$HOME/.pi/agent/settings.json"
"$HOME/.pi/agent/models.json"
"$HOME/.pi/agent/AGENTS.md"
@@ -74,4 +107,22 @@ do
fi
done
exec sudo darwin-rebuild switch --flake ~/.dotfiles#lt-mbp
echo "==> Updating flake inputs..."
if nix flake update --flake ~/.dotfiles 2>&1; then
echo "==> flake update complete"
else
echo "==> WARNING: flake update failed. Continuing with locked inputs."
fi
sudo darwin-rebuild switch --flake ~/.dotfiles#lt-mbp
# Update installed pi packages after the switch, because the Homebrew bundle
# may have upgraded the pi binary.
echo "==> Updating pi extensions..."
if ! command -v pi >/dev/null 2>&1; then
echo "==> WARNING: pi not found. Skipping extension update."
elif pi update --extensions --no-approve 2>&1; then
echo "==> pi extension update complete"
else
echo "==> WARNING: pi extension update failed. Skipping."
fi
+120
View File
@@ -0,0 +1,120 @@
#!/usr/bin/env bash
# Behavior check: the dotfiles crew dispatch sends ordinary workers to
# DeepSeek v4.1 Flash on OpenCode, documentation tasks to Beam Free, and keeps
# the design exception. It reads the config through firstmate's own bootstrap
# validator and verbose facts, which is the supported surface that reports the
# effective dispatch profile.
#
# Firstmate matches the natural-language `when` text with its own judgment, so
# this check pins the declared routing and the schema, not a model call. It then
# confirms every OpenCode-harness model ID against OpenCode's own catalog, so a
# mistyped ID fails here instead of when a crew spawns.
# It skips the parts that need firstmate or OpenCode when they are not installed.
set -euo pipefail
ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)
CONFIG="$ROOT/home/.config/firstmate/crew-dispatch.json"
FM_ROOT=${FM_ROOT:-"$HOME/Documents/firstmate"}
BOOTSTRAP="$FM_ROOT/bin/fm-bootstrap.sh"
[ -f "$CONFIG" ] || { echo "FAIL: missing $CONFIG" >&2; exit 1; }
if [ ! -x "$BOOTSTRAP" ]; then
echo "SKIP: firstmate bootstrap not found at $BOOTSTRAP"
exit 0
fi
TMP=$(mktemp -d "${TMPDIR:-/tmp}/crew-dispatch.XXXXXX")
cleanup() { rm -rf "$TMP"; }
trap cleanup EXIT
mkdir -p "$TMP/home/config"
cp "$CONFIG" "$TMP/home/config/crew-dispatch.json"
printf 'manual\n' > "$TMP/home/config/backlog-backend"
out=$(FM_HOME="$TMP/home" FM_ROOT_OVERRIDE="$TMP/home" FM_BOOTSTRAP_VERBOSE_FACTS=1 \
"$BOOTSTRAP" 2>"$TMP/stderr")
fail() {
echo "FAIL: $1"
printf '%s\n' "$out" | sed 's/^/ /'
sed 's/^/ /' "$TMP/stderr"
exit 1
}
if printf '%s\n' "$out" | grep -q '^CREW_DISPATCH: invalid'; then
fail "firstmate rejected the crew dispatch config"
fi
default=$(printf '%s\n' "$out" | grep '^BOOTSTRAP_INFO: crew dispatch default: ' || true)
[ -n "$default" ] || fail "firstmate reported no default dispatch profile"
case "$default" in
*opencode/opencode-go/deepseek-v4.1-flash*) ;;
*) fail "default workers are not OpenCode + DeepSeek v4.1 Flash" ;;
esac
case "$default" in
*pi/*|*codex/*) fail "default workers still resolve to a Pi/Codex profile" ;;
esac
docs=$(printf '%s\n' "$out" | grep '^BOOTSTRAP_INFO: crew dispatch rule: Documentation tasks' || true)
[ -n "$docs" ] || fail "no documentation dispatch rule"
case "$docs" in
*'-> opencode/opencode-go/beam-free') ;;
*) fail "documentation tasks do not resolve to opencode/opencode-go/beam-free" ;;
esac
design=$(printf '%s\n' "$out" | grep '^BOOTSTRAP_INFO: crew dispatch rule: Design, architecture' || true)
[ -n "$design" ] || fail "the preserved design rule is missing"
case "$design" in
*'-> pi/openai-codex/gpt-6.1-sol/xhigh') ;;
*) fail "the design exception no longer resolves to Pi + GPT-6.1 Sol" ;;
esac
ui=$(printf '%s\n' "$out" | grep '^BOOTSTRAP_INFO: crew dispatch rule: UI work' || true)
[ -n "$ui" ] || fail "the UI image-context rule is missing"
case "$ui" in
*opencode-go/deepseek-v4.1-flash*) ;;
*) fail "the UI rule no longer resolves to DeepSeek v4.1 Flash" ;;
esac
# The model IDs above come from the same file the routing check reads, so a
# typo would still pass them. OpenCode's own catalog is the independent oracle:
# a model it does not list fails only when a crew spawns. Confirm each
# OpenCode-harness model against that catalog.
OPENCODE_JSON=${OPENCODE_CONFIG:-$HOME/.config/opencode2/opencode.json}
if ! command -v opencode >/dev/null 2>&1 || ! command -v python3 >/dev/null 2>&1; then
echo "SKIP: opencode or python3 not on PATH, cannot confirm the model IDs"
elif [ ! -e "$OPENCODE_JSON" ]; then
echo "SKIP: no isolated OpenCode config at $OPENCODE_JSON, cannot confirm the model IDs"
else
catalog=$(OPENCODE_CONFIG="$OPENCODE_JSON" timeout 120 opencode models 2>/dev/null || true)
if [ -z "$catalog" ]; then
echo "SKIP: opencode models printed nothing, cannot confirm the model IDs"
else
models=$(python3 - "$CONFIG" <<'PY'
import json, sys
config = json.load(open(sys.argv[1]))
uses = list(config.get("default") or [])
for rule in config.get("rules") or []:
use = rule.get("use")
uses.extend(use if isinstance(use, list) else [use])
for use in uses:
if isinstance(use, dict) and use.get("harness") == "opencode" and use.get("model"):
print(use["model"])
PY
)
# Deduplicate so a model named by two profiles is confirmed once.
models=$(printf '%s\n' "$models" | awk 'NF && !seen[$0]++')
while IFS= read -r model; do
[ -n "$model" ] || continue
printf '%s\n' "$catalog" | grep -qxF "$model" \
|| fail "$model is not in the OpenCode catalog (opencode models)"
echo "PASS: $model exists in the OpenCode catalog"
done <<< "$models"
fi
fi
echo "PASS: default workers -> opencode/opencode-go/deepseek-v4.1-flash"
echo "PASS: documentation -> opencode/opencode-go/beam-free"
echo "PASS: design exception preserved -> pi/openai-codex/gpt-6.1-sol/xhigh"
+171
View File
@@ -0,0 +1,171 @@
#!/usr/bin/env bash
# Behavior check: a fresh interactive zsh runs the firstmate launchers and each
# one starts the tool its name promises, from the firstmate home directory.
#
# fm -> OpenCode 2 through ~/.local/bin/oc2
# fm-oc2 -> OpenCode 2 through ~/.local/bin/oc2, identical to fm
# fm-pi -> Pi
#
# The check reads the zshrc that the real home-manager configuration generates
# (the same file a rebuild installs), sources it in an interactive zsh, and runs
# each launcher with three harmless spies:
# - a `pi` spy first on PATH, which catches a Pi launch;
# - a spy named by OPENCODE2_BIN, which the real ~/.local/bin/oc2 wrapper
# execs instead of the OpenCode binary;
# - the spies record their working directory, so a launcher that forgets the
# `cd` into the firstmate home fails here.
# Nothing here launches a real firstmate primary, Pi, or OpenCode, and the spies
# exit at once, so no session lock is taken and the primary stays alive.
#
# Usage:
# tests/fm-launcher.sh # check the configuration source (default)
# tests/fm-launcher.sh --live # check the installed ~/.zshrc
# tests/fm-launcher.sh --zshrc F # check a specific generated zshrc
set -euo pipefail
ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)
MODE=source
ZSHRC=''
LAUNCHERS='fm:oc2 fm-oc2:oc2 fm-pi:pi'
FM_HOME=${FM_HOME:-"$HOME/Documents/firstmate"}
while [ $# -gt 0 ]; do
case "$1" in
--live) MODE=live; shift ;;
--zshrc)
[ $# -ge 2 ] || { echo "fm-launcher: --zshrc needs a path" >&2; exit 2; }
MODE="file"; ZSHRC=$2; shift 2 ;;
-h|--help)
awk 'NR == 1 { next } /^#/ { sub(/^# ?/, ""); print; next } { exit }' "$0"
exit 0 ;;
*) echo "fm-launcher: unknown argument $1" >&2; exit 2 ;;
esac
done
TMP=$(mktemp -d "${TMPDIR:-/tmp}/fm-launcher.XXXXXX")
cleanup() { rm -rf "$TMP"; }
trap cleanup EXIT
mkdir -p "$TMP/bin"
cat > "$TMP/bin/pi" <<'SH'
#!/usr/bin/env bash
printf 'pi|%s' "$PWD" >> "$FM_TEST_SPY_LOG"
for arg in "$@"; do printf '|%s' "$arg" >> "$FM_TEST_SPY_LOG"; done
printf '\n' >> "$FM_TEST_SPY_LOG"
exit 0
SH
cat > "$TMP/bin/opencode2-spy" <<'SH'
#!/usr/bin/env bash
printf 'oc2|%s' "$PWD" >> "$FM_TEST_SPY_LOG"
for arg in "$@"; do printf '|%s' "$arg" >> "$FM_TEST_SPY_LOG"; done
printf '\n' >> "$FM_TEST_SPY_LOG"
exit 0
SH
chmod +x "$TMP/bin/pi" "$TMP/bin/opencode2-spy"
printf '{}\n' > "$TMP/opencode.json"
case "$MODE" in
live)
ZSHRC="$HOME/.zshrc"
LABEL="installed ~/.zshrc"
;;
file)
LABEL="$ZSHRC"
;;
source)
command -v nix >/dev/null 2>&1 \
|| { echo "fm-launcher: nix is required to build the configured zshrc" >&2; exit 2; }
ZSHRC="$TMP/zshrc"
nix eval --raw --impure --expr \
"(builtins.getFlake (toString $ROOT)).darwinConfigurations.\"lt-mbp\".config.home-manager.users.laptran.home.file.\"./.zshrc\".text" \
> "$ZSHRC"
LABEL="home-manager zshrc generated from $ROOT"
;;
esac
[ -r "$ZSHRC" ] || { echo "fm-launcher: cannot read $ZSHRC" >&2; exit 2; }
# Run one launcher in a fresh interactive zsh and print what the spies saw.
launch() {
local launcher=$1
: > "$TMP/spy.log"
: > "$TMP/stderr"
set +e
# shellcheck disable=SC2016 # the snippet expands inside the interactive zsh
FM_TEST_ZSHRC="$ZSHRC" \
FM_TEST_LAUNCHER="$launcher" \
FM_TEST_SPY_LOG="$TMP/spy.log" \
OPENCODE2_BIN="$TMP/bin/opencode2-spy" \
OPENCODE_CONFIG="$TMP/opencode.json" \
PATH="$TMP/bin:$PATH" \
timeout 60 zsh -f -i -c '
source "$FM_TEST_ZSHRC" || exit 4
if ! alias "$FM_TEST_LAUNCHER" >/dev/null 2>&1; then
echo "fm-launcher: no $FM_TEST_LAUNCHER alias in the sourced zshrc" >&2
exit 3
fi
eval "$FM_TEST_LAUNCHER"
' >/dev/null 2>"$TMP/stderr"
LAUNCH_STATUS=$?
set -e
}
for pair in $LAUNCHERS; do
launcher=${pair%%:*}
expected=${pair##*:}
launch "$launcher"
status=$LAUNCH_STATUS
if [ "$status" -eq 3 ]; then
echo "FAIL: $LABEL does not define a $launcher alias"
exit 1
fi
if [ "$status" -ne 0 ]; then
echo "FAIL: $launcher from $LABEL exited $status"
sed 's/^/ /' "$TMP/stderr"
exit 1
fi
if [ ! -s "$TMP/spy.log" ]; then
echo "FAIL: $launcher from $LABEL launched nothing the spies could see"
sed 's/^/ /' "$TMP/stderr"
exit 1
fi
record=$(head -n 1 "$TMP/spy.log")
tool=${record%%|*}
dir=$(printf '%s' "${record#*|}" | cut -d'|' -f1)
if [ "$tool" != "$expected" ]; then
echo "FAIL: $launcher from $LABEL launched $tool instead of $expected"
echo " recorded launch: $record"
exit 1
fi
if [ "$dir" != "$FM_HOME" ]; then
echo "FAIL: $launcher from $LABEL ran in $dir instead of the firstmate home $FM_HOME"
echo " recorded launch: $record"
exit 1
fi
if [ "$expected" = oc2 ] && grep -q '^pi' "$TMP/spy.log"; then
echo "FAIL: $launcher from $LABEL also launched Pi"
sed 's/^/ /' "$TMP/spy.log"
exit 1
fi
case "$launcher" in
fm) fm_record=$record ;;
fm-oc2) fm_oc2_record=$record ;;
esac
echo "PASS: $launcher from $LABEL launched $expected in $dir ($record)"
done
if [ "$fm_record" != "$fm_oc2_record" ]; then
echo "FAIL: fm and fm-oc2 are not identical launchers"
echo " fm: $fm_record"
echo " fm-oc2: $fm_oc2_record"
exit 1
fi
echo "PASS: fm and fm-oc2 are identical launchers"
Executable
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
# Run the dotfiles configuration checks that need the live machine.
#
# The launcher check builds the zshrc from the home-manager configuration and
# runs `fm`, `fm-oc2`, and `fm-pi` with spies. The dispatch check reads the crew
# dispatch config through firstmate's bootstrap validator. Neither starts a real
# agent session.
set -euo pipefail
ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)
status=0
"$ROOT/tests/fm-launcher.sh" || status=1
"$ROOT/tests/crew-dispatch.sh" || status=1
exit "$status"