feat(herdr): offer skillshare as a standalone mod (#857)

Preserve the complete Layout while adding a standalone Mod named skillshare. Generate both packages from one canonical mod and protect custom layouts and usage meters during installation and updates. Keep release versions aligned and route native Herdr instructions separately within existing context budgets.
This commit is contained in:
Willie
2026-11-11 21:49:34 +08:00
committed by GitHub
parent eb3ca528fc
commit e317483459
45 changed files with 2886 additions and 11 deletions
+1 -1
View File
@@ -22,7 +22,7 @@
],
"packages": {
".": {
"extra-files": ["herdr/skillshare/mods/skillshare/version.js"]
"extra-files": ["herdr/skillshare/mods/skillshare/version.js", "herdr/skillshare-mod/mods/skillshare/version.js"]
}
}
}
+2 -1
View File
@@ -54,7 +54,8 @@ The router runs on the host and needs only Python 3.8+. On Windows, use `py` or
| `cli-development` | Adding or changing Go CLI commands, flags, handlers, TUIs, or mutating behavior |
| `testing` | Building, testing, reproducing bugs, or using the devcontainer/ssenv |
| `e2e-runbooks` | Writing or running `ai_docs/tests` E2E runbooks, or verifying on a Windows guest |
| `frontend` | Changing React, CSS, layout, or visual behavior in `ui/`, `website/`, or `herdr/` |
| `frontend` | Changing React, CSS, layout, or visual behavior in `ui/` or `website/` |
| `herdr` | Changing the native Herdr panel, gallery packages, or layout integration |
| `documentation` | Updating README files, website docs, command flags, translations, or the built-in skill |
| `release` | Writing changelogs or release notes, bumping versions, tagging, or releasing |
| `audit` | Read-only consistency checks for flags, docs, tests, targets, handler splits, oplog, or Web API |
+2 -1
View File
@@ -2,7 +2,8 @@
A Herdr mod and layout for skillshare. Herdr runs mods in QuickJS with its own UI kit; nothing here is part of the Go build.
- `skillshare/` is one share folder: `RECIPE.md`, `preview.png`, `layouts/herdr-skillshare.json` (+ its png) and `mods/skillshare/`.
- `skillshare/` is the Layout share folder and canonical mod source. `skillshare-mod/` is the standalone Mod share folder: its own `RECIPE.md`, generated `preview.png` and `mods/skillshare/`, with no `layouts/`. After changing the canonical mod or `panels.png`, run `python3 scripts/herdr/package-mod.py` in the devcontainer; `make test-herdr` checks parity. Edit the generated mod only through its source.
- Installation recipes preserve existing layouts and unrelated nodes (including custom status bars and usage meters). A panel update replaces only its mod, never a complete layout.
- Only `main.js` imports Herdr. `model.js` (parsing, shell scripts), `jobs.js` (detached jobs), `channel.js` (requests, per-machine locks, notices), `operations.js` (what each request runs) and `loader.js` (what the panel reads) take Herdr's functions as arguments, so `herdr/tests/*.test.mjs` cover them with `make test-herdr` (part of `make check` and CI). Put new logic in one of them and test it; keep `main.js` to views.
- `main.js` imports `herdr`; check it with `herdr-app check <mod folder>` on a machine with Herdr. QuickJS rejects `??` mixed with `||`/`&&` without parentheses, which node accepts.
- Use Herdr theme tokens only. Never keep a `cx` past its callback, call `setShared`/`notify` during render, or pass `null` to `.child`.
+79
View File
@@ -0,0 +1,79 @@
# skillshare
A skillshare button and panel added to your existing Herdr window. See which skills, agents, MCP servers, plugins and hooks need an update or a sync in the focused project's source and your global source. Preview, install with an audit first, update, sync, enable or disable, uninstall, hand an audit to an agent, sync the source repository and check every machine. Your status bar, usage meters, sidebar, theme and other panels stay as they are.
![skillshare](preview.png)
## What you see
- A 118px **skillshare** button beside the existing tab bar. It uses the 16px skillshare mark and the selected background while the panel is open.
- A 400px panel beside the work area, resizable from 380 to 720px. Its 44px header shows the folder, machine, CLI version, Update panel when available and a close button.
- **Overview**, **Library** and **Machines** tabs. In a project, All · Project · Global selects the scope; outside one, Global is shown.
- Overview answers with Everything is in sync, targets/resources waiting, or Syncing. A Sync button handles pending work. Five counts open Library by kind; up to six target lines show what waits. Hovering a collapsed count opens the remaining target lines.
- Library has kind tabs, a filter, Sync and Install. Its scrollable list groups unknown, needs-attention, needs-sync, update, in-sync and disabled rows. In-sync skills and agents fold by source, with a List switch. Each row opens a preview; update rows also have Update.
- Machines shows one card per Herdr machine: version, remote/source/target state, doctor warnings and Pull and sync or Sync both ways. A newer CLI version offers Update.
- A 34px notice line appears during work or after an outcome. A 40px footer shows the source repository state and opens its actions.
- Previews use Document/Settings/About, Targets and Details tabs where applicable. Install, audit results, source actions, conflict resolution, enable/disable, uninstall and updates use confirmation overlays.
- Herdr theme tokens and fonts, with native pressed states, loading placeholders and short transitions; no window-wide look of its own.
## How it behaves
- The button toggles the panel and the close button hides it. Open/closed state survives space switches and restarts.
- The panel follows the shown space's machine and focused terminal's folder. `.skillshare/config.yaml` or `skillshare/config.yaml` enables project scope beside global scope.
- It refreshes every 20 seconds while shown, checks resource updates every 10 minutes and checks the latest published panel release hourly. Hidden panels do no work. Resource reads appear independently; pending or failed reads remain unconfirmed instead of claiming everything is in sync.
- Sync applies pending scopes and plugin changes. Hook conflicts block all resource sync until resolved. Hook notices do not inflate named-entry counts.
- Preview reads skill/agent files or MCP settings, hiding secret values. Skills and agents offer Update, Diff, Enable/Disable, Uninstall and Ask agent to audit; declared hooks offer Enable, Disable and Remove. Destructive actions and audit hand-offs ask first.
- Install takes a repository URL, uses the CLI's dry-run plan to choose skills, audits a separate clone and installs only after a passing audit or explicit Install anyway confirmation. A failed command remains a failure even when some items were installed.
- Source actions offer Pull, Commit and push and Sync both ways. Conflicting files show both versions for a per-file choice; skill metadata merges per entry.
- Requests show their intended outcomes while pending, then reconcile with CLI reads. Errors restore the last known rows. Work is serialized per machine; different machines can run independently.
- Update panel replaces only this mod's files and saves the previous files in `.bak-update-<version>`. It leaves every layout and unrelated mod untouched.
## Built from
This is a standalone mod share folder: `mods/skillshare/`, this recipe and `preview.png`. It contains no `layouts/`. The optional complete window is a separate [layout package](../skillshare/README.md).
### Add to the existing window
1. Read `~/.config/herdr-app/AGENTS.md` and every mod file first. Tell the person that the panel runs programs, reaches GitHub and resource repositories, and reads source files outside its own folder.
2. Copy `mods/skillshare/` into Herdr's home. If it already holds this panel, update that installation instead of installing a duplicate. For an unrelated name collision, follow Herdr's rename procedure; a renamed panel must be updated by hand.
3. Inspect the shown layout. Clone it first if it is Herdr-shipped; otherwise keep the user's layout name and edit only the two skillshare nodes. Preserve every unrelated node and property, especially custom status bars and CLI usage meters.
4. Add this block beside the existing tab bar (wrap the tab block in a row only if necessary; keep its existing properties):
```json
{ "id": "skillshare-toggle", "type": "block", "content": { "mod": "skillshare", "props": { "role": "toggle" } }, "size": { "px": 118 } }
```
5. Add this column beside the work area, outside the per-space Files/Changes `panel` stack:
```json
{ "id": "skillshare-panel", "type": "column", "children": [{ "id": "skillshare", "type": "block", "content": { "mod": "skillshare" } }], "size": { "px": 400 }, "min": 380, "max": 720 }
```
Reuse these nodes when they already belong to skillshare; do not append duplicates. If an ID belongs to something else, ask before changing it. The toggle and close button require `skillshare-panel` as the panel node ID.
6. Check the mod with `herdr-app check` and try it in the app. Keep the current layout selected unless a shipped layout had to be cloned. No key bindings are required.
### Modules and dependencies
- `main.js` imports `gpui-kit`, `gpui-base` and `herdr`. Its default role draws the panel; `toggle` draws the button. Dialog roles include `install`, `uninstall`, `audit`, `source`, `syncboth`, `conflict`, `upgrade`, `panelupdate`, `text`, `hook` and `able`.
- `model.js` parses CLI output and holds shell scripts; `jobs.js` runs detached work; `channel.js` carries requests, locks and notices; `operations.js` runs mutations; `loader.js` reads resources, checks and previews. `version.js` records the release. `mark.svg` and `icons/` supply the art.
- Herdr APIs: `exec`, `readTextFile`, `spaces`, `focused`, `machines`, `agents`, `knownAgents`, `layout`, `shared`, `setShared`, `settings`, `theme`, `props`, `openOverlay`, `closeOverlay`, `nextCommand`, `run` and `hc`. Commands: `layout.toggle`, `layout.hide` and `agent.focus`; `hc send` hands off audits.
- Programs: `skillshare`, `git`, `curl`, `sh` and standard filesystem/process tools. skillshare must be installed on every connected machine in `~/.local/bin`, `~/go/bin`, `/opt/homebrew/bin` or `/usr/local/bin`.
- Long work uses detached jobs and polled temp files. Preview reads up to 40 file names and 60 kB per file. MCP env/header/token values are redacted.
- Panel updates fetch `herdr/skillshare/mods/skillshare` from the latest published release. Both installation options use that same updater and version. The standalone files are generated from that source with `python3 scripts/herdr/package-mod.py`.
## Watch out
- **Update the mod, not the window.** For an agent-assisted update, back up the installed mod, then replace only its files. Preserve all layouts, settings, keys, other mods and layout state. If new skillshare nodes are needed, merge only those nodes into the existing layout. A request to update the panel is not a request to reinstall or switch to the complete layout.
- Keep the panel outside the per-space `panel` stack; otherwise switching spaces restores that stack and closes it.
- Renaming the mod requires rewriting its own asset/overlay paths too. The built-in updater checks the canonical `mods/skillshare` destination and refuses a renamed installation.
- Herdr ends an exec's process group and enforces a 30-second timeout. Detached jobs must drop `HC_SCOPE`, get their own process group, and report when killed rather than waiting indefinitely.
- Avoid `setShared` or `notify` during render. Do not retain `cx` beyond its callback. QuickJS rejects unparenthesized mixing of `??` and `||`/`&&`.
- Updating files reloads the mod. Copy dependencies before `main.js` and `version.js` last; the reloaded build reports the outcome through shared state. Changes to mod code are backed up, not merged into a new release.
## Done when
- `herdr-app check ~/.config/herdr-app/mods/skillshare` passes and Herdr reports no layout/mod errors.
- The existing window still has its original sidebar, status bar, usage meters, theme, panels and keys. Only the skillshare toggle and column were added.
- The toggle and close button work; switching spaces preserves open/closed state. Repeating installation does not duplicate nodes.
- Global and project scopes, previews, audit-before-install, per-machine work and source conflicts behave as described above.
- A panel update changes the mod version, keeps a backup and leaves custom layouts and unrelated mods byte-for-byte unchanged.
@@ -0,0 +1,68 @@
// How the panel and its dialogs talk: requests a dialog hands to the panel, one lock per machine,
// and the notice line. It all lives in Herdr's shared values, because a dialog is a separate view
// whose tasks end when it closes. No Herdr imports: main.js passes shared/setShared in, the tests
// a Map.
export const REQUEST = "skillshare.request.v1"; // { id, op, ... }
export const NOTICE = "skillshare.notice.v1"; // { kind, text, at }
export const BUSY = "skillshare.busy.v1"; // { [machine]: { text, at } }; "" is this computer
// Every machine at once, as `on` for claim, step, touch and release: the panel replacing its own
// files ends the work on all of them. It is taken only when nothing is locked, and while held
// every machine is busy.
export const EVERY = "*";
// createChannel({ get, set, now }): get(key) and set(key, value) read and write shared values.
// request(op): hands op to the panel.
// listen(): for the panel; returns next(), which gives each request made after listen() once,
// then null.
// claim(on, text): takes machine on's lock; false when something already holds it.
// step(on, text): says what the holder is doing now. release(on): gives the lock back.
// touch(on): the holder is still at work; call it before each command (it writes at most every
// 10 s). A lock untouched for staleMs is dropped: a dialog's task ends without a word when the
// dialog closes, and a lock outlives a Herdr restart in shared.
// busyAt(on), textAt(on), busyText(): read the locks.
// say(kind, text), notice(), clearNotice(): the notice line ("done", "info", "warn", "error").
// Writes must not happen while a view renders; reads may.
export function createChannel({ get, set, now = Date.now, staleMs = 60 * 1000 }) {
const key = (on) => on ?? "";
const locks = () => {
const b = get(BUSY);
if (!b || typeof b !== "object" || Array.isArray(b)) return {}; // older panels kept a string here
return Object.fromEntries(Object.entries(b).filter(([, l]) => l && now() - l.at < staleMs));
};
const held = (l, on) => l[key(on)] ?? l[EVERY] ?? null;
const busyAt = (on) => Boolean(held(locks(), on));
return {
request(op) { set(REQUEST, { ...op, id: `${now()}-${Math.random().toString(36).slice(2, 7)}` }); },
listen() {
let last = get(REQUEST)?.id ?? null;
return () => {
const r = get(REQUEST);
if (!r?.id || r.id === last) return null;
last = r.id;
return r;
};
},
busyAt,
textAt: (on) => held(locks(), on)?.text ?? null,
busyText: () => Object.values(locks()).map((l) => l.text).join(" · ") || null,
claim(on, text) {
const l = locks();
if (on === EVERY ? Object.keys(l).length : held(l, on)) return false;
set(BUSY, { ...l, [key(on)]: { text, at: now() } });
return true;
},
step(on, text) { set(BUSY, { ...locks(), [key(on)]: { text, at: now() } }); },
release(on) {
const l = locks();
delete l[key(on)];
set(BUSY, l);
},
touch(on) {
const l = locks(), held = l[key(on)];
if (held && now() - held.at >= 10 * 1000) set(BUSY, { ...l, [key(on)]: { ...held, at: now() } });
},
say(kind, text) { set(NOTICE, { kind, text, at: now() }); },
notice: () => get(NOTICE) ?? null,
clearNotice() { set(NOTICE, null); },
};
}
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7.5v5.5M12 16.5v.5"/></svg>

After

Width:  |  Height:  |  Size: 255 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 4v16M3 16l4 4 4-4M17 20V4M13 8l4-4 4 4"/></svg>

After

Width:  |  Height:  |  Size: 241 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="m5 12 5 5 9-10"/></svg>

After

Width:  |  Height:  |  Size: 216 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>

After

Width:  |  Height:  |  Size: 214 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="m9 6 6 6-6 6"/></svg>

After

Width:  |  Height:  |  Size: 214 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 6l12 12M18 6 6 18"/></svg>

After

Width:  |  Height:  |  Size: 220 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 4h6v6M20 4l-9 9M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"/></svg>

After

Width:  |  Height:  |  Size: 277 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>

After

Width:  |  Height:  |  Size: 273 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/><circle cx="18" cy="9" r="2.5"/><path d="M6 8.5v7M18 11.5c0 3-4 3.5-10 5"/></svg>

After

Width:  |  Height:  |  Size: 326 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><title>Oh My Pi</title><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#f24fb8"/><stop offset=".5" stop-color="#8b5cf6"/><stop offset="1" stop-color="#3fd4d8"/></linearGradient></defs><path fill="url(#g)" d="M10 14h44v9H43v33h-9V23h-9v22h-9V23H10z"/></svg>

After

Width:  |  Height:  |  Size: 355 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14M5 12h14"/></svg>

After

Width:  |  Height:  |  Size: 218 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3a9 9 0 1 0 9 9"/></svg>

After

Width:  |  Height:  |  Size: 221 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><circle cx="11" cy="11" r="6"/><path d="m20 20-4.5-4.5"/></svg>

After

Width:  |  Height:  |  Size: 223 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3l7 3v6c0 4.5-3 7.5-7 9-4-1.5-7-4.5-7-9V6z"/></svg>

After

Width:  |  Height:  |  Size: 246 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 0 1-15.5 6.2M3 12a9 9 0 0 1 15.5-6.2M18 3v3h-3M6 21v-3h3"/></svg>

After

Width:  |  Height:  |  Size: 269 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 7h16M10 11v6M14 11v6M6 7l1 12a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2l1-12M9 7V4h6v3"/></svg>

After

Width:  |  Height:  |  Size: 277 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><title>Agent Skills</title><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#dc4538"/><stop offset=".5" stop-color="#f0b840"/><stop offset="1" stop-color="#5cc98a"/></linearGradient></defs><path fill="url(#g)" d="M32 1.3 58.9 16.6v30.8L32 62.7 5.1 47.4V16.6z"/></svg>

After

Width:  |  Height:  |  Size: 365 B

@@ -0,0 +1,49 @@
// Runs skillshare on a machine: short reads as one exec, longer work as a detached job that is
// polled until it writes its exit code. No Herdr imports: main.js passes Herdr's exec and file
// reads in, and the tests pass real sh and fs.
import { START, START_SCRIPT, ALIVE, SWEEP, JOB_MINUTES, lastLine } from "./model.js";
// createRunner({ exec, readText }):
// exec(script, args, on) runs `sh -c script` on machine `on` (null: this computer) and resolves
// to { code, stdout, stderr }; it must not reject. Herdr stops an exec after 30 s.
// readText(path, on) resolves to the file's text, or null when it can't be read.
// The returned runner:
// sh(script, args, on): one exec of a script of ours.
// run(args, { on, cwd }): one exec of `skillshare args` in cwd (home when null). Short reads only.
// job(args, { on, cwd, script, sleep }): `skillshare args`, or with `script` a script of ours
// given args, run detached. Resolves when it ends to { code, stdout, stderr }; a job that
// dies without an exit code, or runs past JOB_MINUTES, resolves with code 1 and the reason.
// `sleep(ms)` waits between polls (a Herdr view passes cx.sleep).
// The first job on each machine also removes job folders that a closed panel never collected.
export function createRunner({ exec, readText, pollMs = 500, aliveEvery = 10, budgetMs = JOB_MINUTES * 60 * 1000 }) {
const swept = new Set();
const read = (path, on) => Promise.resolve().then(() => readText(path, on)).catch(() => null);
const sh = (script, args = [], on = null) => exec(script, args, on);
const run = (args, { on = null, cwd = null } = {}) =>
sh('cd "$1" 2>/dev/null || cd; shift; exec skillshare "$@"', [cwd ?? "", ...args], on);
async function job(args, { on = null, cwd = null, script = null, sleep }) {
if (!swept.has(on ?? "")) { swept.add(on ?? ""); sh(SWEEP, [], on); }
const s = script ? await sh(START_SCRIPT, [cwd ?? "", script, ...args], on) : await sh(START, [cwd ?? "", ...args], on);
const d = s.stdout.trim();
if (s.code !== 0 || !d) return { code: s.code || 1, stdout: "", stderr: s.stderr || "Could not start skillshare" };
const done = async (result) => { sh('rm -rf "$1"', [d], on); return result; };
const polls = Math.ceil(budgetMs / pollMs);
for (let i = 1; i <= polls; i++) {
await sleep(pollMs);
const code = await read(`${d}/code`, on);
if (code !== null && code.trim() !== "") {
const [stdout, stderr] = await Promise.all([read(`${d}/out`, on), read(`${d}/err`, on)]);
return done({ code: Number(code.trim()), stdout: stdout ?? "", stderr: stderr ?? "" });
}
// A job that was killed never writes its code, so check now and then that it still runs.
if (i % aliveEvery === 0 && (await sh(ALIVE, [d], on)).code === 1) {
const err = await read(`${d}/err`, on);
return done({ code: 1, stdout: "", stderr: lastLine(err) || "skillshare stopped before it finished" });
}
}
return { code: 1, stdout: "", stderr: `skillshare took longer than ${JOB_MINUTES} minutes` };
}
return { sh, run, job };
}
@@ -0,0 +1,123 @@
// What the panel reads from a machine: the Resources tab's data and one Machines card. No Herdr
// imports and no view state: main.js decides when to load and whether a result is still wanted,
// and the tests pass a fake machine.
// io.job(args, { on, cwd, script }): skillshare (or a script of ours) run detached;
// io.run(args, { on, cwd }): a short read; io.sh(script, args, on): one exec of a script.
import { GIT_STATUS, PROJECT, READ_SKILL, READ_FILE, LATEST_RELEASE, releaseTag, parseJSON, failure, flag, parseGitStatus, driftFrom, targetDrift, splitFrontmatter, mcpServer } from "./model.js";
const scopesOf = (project) => (project ? ["project", "global"] : ["global"]);
const at = (on, project, scope) => ({ on, cwd: scope === "project" ? project : null });
// The project skillshare uses for the first of folders that is one, or null.
export async function findProject({ sh }, on, folders) {
const r = await sh(`for d in "$@"; do [ -n "$d" ] || continue; ${PROJECT.replace(/\$1/g, "$d")} && exit 0; done; true`, folders, on);
return r.stdout.trim() || null;
}
// Each read publishes independently. Keep the previous values during refresh, but track
// pending and failed sections separately so a stale value never claims a fresh sync verdict.
export async function loadResources(io, on, project, network, progress = () => {}, previous = {}) {
const commands = { list: ["list", "--all"], diff: ["diff"], mcp: ["mcp", "list"], plugins: ["plugin", "list"], hooks: ["hooks", "list"], status: ["status"] };
const raw = {};
for (const scope of scopesOf(project)) raw[scope] = { ...previous[scope], pending: Object.keys(commands), errors: {}, took: {}, error: null };
let git = null, version = null;
const snapshot = () => ({ raw: Object.fromEntries(Object.entries(raw).map(([scope, one]) => [scope, { ...one, pending: [...one.pending], errors: { ...one.errors }, took: { ...one.took } }])), git, version,
error: Object.entries(raw).flatMap(([scope, one]) => Object.entries(one.errors).map(([name, message]) => `${scope} ${name}: ${message}`)).join("\n") || null });
const publish = () => progress(snapshot());
const names = (list) => (list ?? []).map((x) => x.name).filter(Boolean);
publish();
await Promise.all(scopesOf(project).flatMap((scope) => Object.entries(commands).map(async ([name, args]) => {
const one = raw[scope], start = Date.now(), opt = at(on, project, scope);
let status;
try {
const r = await (name === "status" ? io.run([...args, "--json", flag(scope)], opt) : io.job([...args, "--json", flag(scope)], opt));
const value = parseJSON(r.stdout);
if (r.code !== 0 || value == null || (name === "list" && !Array.isArray(value))) throw new Error(failure(r, `skillshare ${args.join(" ")}`));
if (name === "status") {
status = value;
Object.assign(one, { targets: names(value.targets), skillTargets: names((value.targets ?? []).filter((x) => x.skills_enabled !== false)), agentTargets: names(value.agents?.targets) });
if (scope === "global") version = value.version ?? null;
} else one[name] = value;
} catch (e) {
one.errors[name] = String(e?.message ?? e);
if (name === "list") one.error = one.errors[name];
} finally {
one.pending = one.pending.filter((key) => key !== name);
one.took[name] = (Date.now() - start) / 1000;
publish();
}
// Source state does not wait for any resource inventory (especially native plugins).
if (name === "status" && scope === "global") {
try {
if (one.errors.status) git = { error: one.errors.status };
else if (!status?.source?.path) git = { repo: false };
else {
const r = await io.sh(GIT_STATUS, [status.source.path, network ? "fetch" : ""], on);
git = r.code === 0 ? parseGitStatus(r.stdout) : { error: failure(r, "git status") };
}
} catch (e) { git = { error: String(e?.message ?? e) }; }
publish();
}
})));
return snapshot();
}
// What has an update upstream, per scope: { [scope]: { check, checkAgents } }. Slow: it asks
// every source's remote.
export async function loadChecks(io, on, project) {
const out = {};
for (const scope of scopesOf(project)) {
const opt = at(on, project, scope), f = flag(scope);
const [check, checkAgents] = await Promise.all([io.job(["check", "--json", f], opt), io.job(["check", "agents", "--json", f], opt)]);
out[scope] = { check: parseJSON(check.stdout), checkAgents: parseJSON(checkAgents.stdout) };
}
return out;
}
// One Machines card: the CLI's version and health, drift, and the source's git state.
export async function loadMachine(io, on) {
const [host, doctor, diff, status] = await Promise.all([
on ? Promise.resolve({ stdout: on }) : io.sh("hostname -s"),
io.job(["doctor", "--json", "-g"], { on }), io.run(["diff", "--json", "-g"], { on }), io.run(["status", "--json", "-g"], { on }),
]);
const st = parseJSON(status.stdout), d = parseJSON(doctor.stdout), df = parseJSON(diff.stdout);
const git = st?.source?.path ? parseGitStatus((await io.sh(GIT_STATUS, [st.source.path], on)).stdout) : null;
return {
on, label: on ?? (host.stdout.trim() || "this computer"), here: !on, missing: status.code === 127 || /not found/.test(status.stderr),
version: d?.version?.current ?? st?.version ?? null, latest: d?.version?.latest ?? null, update: Boolean(d?.version?.update_available),
doctor: d?.summary ?? null, targets: (st?.targets ?? []).filter((x) => x.skills_enabled !== false).length,
drift: driftFrom(df).size, pending: targetDrift(df).filter((x) => x.n), git,
};
}
// The latest published skillshare release ("v1.2.3"), asked from this computer; null when GitHub
// can't be reached.
export async function loadLatestRelease({ sh }) {
return releaseTag((await sh(LATEST_RELEASE)).stdout);
}
// What a preview shows beyond the row: a skill's files and SKILL.md, an agent's file, or an MCP
// server's settings (mcpPath is the MCP source file). { files, dir, meta, body } | { server } | { error }.
export async function loadPreview(io, on, project, item, mcpPath) {
if (item.kind === "mcp") return { server: mcpPath ? mcpServer((await io.sh(READ_FILE, [mcpPath], on)).stdout, item.name) : null };
const st = parseJSON((await io.run(["status", "--json", flag(item.scope)], at(on, project, item.scope))).stdout);
const base = item.kind === "agents" ? st?.agents?.source : st?.source?.path;
if (!base) return { error: "skillshare did not say where this source is." };
if (item.kind === "agents") {
const r = await io.sh(READ_FILE, [`${base}/${item.rel}.md`], on);
return r.stdout ? { files: [`${item.label}.md`], dir: null, ...splitFrontmatter(r.stdout) } : { error: `${item.rel}.md could not be read.` };
}
const dir = `${base}/${item.rel}`, r = await io.sh(READ_SKILL, [dir], on);
const cut = r.stdout.indexOf("@@\n");
if (r.code !== 0 || cut < 0) return { error: `${dir} could not be read.` };
const files = r.stdout.slice(0, cut).split("\n").filter(Boolean), text = r.stdout.slice(cut + 3);
// The list stops at 40 names; the document it shows is always one of them.
if (text && !files.includes("SKILL.md")) files.unshift("SKILL.md");
return { files, dir, ...splitFrontmatter(text) };
}
// Another file of a previewed skill.
export async function loadFile(io, on, dir, file) {
const text = (await io.sh(READ_FILE, [`${dir}/${file}`], on)).stdout;
return /\.md$/i.test(file) ? splitFrontmatter(text) : { meta: [], body: text, plain: true };
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<path d="M2.56 10.54A6 6 0 0 1 10.54 2.56" fill="none" stroke="#3B9BFF" stroke-width="1.6" stroke-linecap="round"/>
<path d="M11.22 1.11L12.17 3.32L9.86 4.01Z" fill="#3B9BFF" stroke="#3B9BFF" stroke-width="0.6" stroke-linejoin="round"/>
<path d="M13.44 5.46A6 6 0 0 1 5.46 13.44" fill="none" stroke="#FFA81F" stroke-width="1.6" stroke-linecap="round"/>
<path d="M4.78 14.89L3.83 12.68L6.14 11.99Z" fill="#FFA81F" stroke="#FFA81F" stroke-width="0.6" stroke-linejoin="round"/>
<circle cx="8" cy="7.2" r="2.6" fill="#FFD43B"/>
<rect x="6.7" y="9.4" width="2.6" height="1.8" rx="0.5" fill="#B9BEC7"/>
</svg>

After

Width:  |  Height:  |  Size: 700 B

@@ -0,0 +1 @@
{ "place": "none", "title": "skillshare", "focusable": true }
@@ -0,0 +1,792 @@
// What the panel shows, built from the skillshare CLI's JSON and git's porcelain output.
// No Herdr imports, so `node --test herdr/tests` runs it.
export const KINDS = [["skills", "Skills"], ["agents", "Agents"], ["mcp", "MCP"], ["plugins", "Plugins"], ["hooks", "Hooks"]];
export const SCOPES = [["all", "All"], ["project", "Project"], ["global", "Global"]];
// Long work runs detached, its output kept in a temp folder (out, err, code, pid) that the
// panel polls. Herdr ends an exec's whole process group when the exec returns, so the job
// gets its own: setsid where it exists (Linux), or sh job control (macOS, whose sh is bash;
// dash turns job control off without a terminal, but Linux has setsid). Never both: a job
// that already leads its group makes setsid fork and exit. The job writes its own pid once
// detached, and the starter waits for it (up to 5 s) so it is not ended before then. Herdr also
// hangs up programs that carry the exec's HC_SCOPE once the exec returns (git and gh, which
// skillshare runs, died with exit 129), so the job drops it.
const DETACH = 'unset HC_SCOPE; if command -v setsid >/dev/null 2>&1; then bg() { exec setsid "$@"; }; else set -m; bg() { exec "$@"; }; fi';
// Named so SWEEP can tell the panel's job folders from anything else in the temp folder.
const TEMP = 'd=$(mktemp -d "${TMPDIR:-/tmp}/skillshare-panel.XXXXXX")';
const READY = 'i=0; while [ ! -s "$d/pid" ] && [ $i -lt 50 ]; do sleep 0.1; i=$((i+1)); done; printf %s "$d"';
// sh -c START <name> <dir> <args...>: runs skillshare <args> in <dir>; prints the temp folder.
export const START = `${DETACH}; ${TEMP}; dir=$1; shift
bg sh -c 'echo $$ >"$2/pid"; cd "$1" 2>/dev/null || cd; d=$2; shift 2; skillshare "$@" >"$d/out" 2>"$d/err" </dev/null; echo $? >"$d/code"' job "$dir" "$d" "$@" >/dev/null 2>&1 </dev/null &
${READY}`;
// The same for a script of ours: sh -c START_SCRIPT <name> <dir> <script> <args...>.
export const START_SCRIPT = `${DETACH}; ${TEMP}; dir=$1; script=$2; shift 2
bg sh -c 'echo $$ >"$1/pid"; d=$1; script=$2; shift 2; sh -c "$script" snapshot "$@" >"$d/out" 2>"$d/err" </dev/null; echo $? >"$d/code"' job "$d" "$script" "$dir" "$@" >/dev/null 2>&1 </dev/null &
${READY}`;
// sh -c ALIVE <name> <temp folder>: fails when the job stopped without writing its exit code.
// A killed job nobody reaps stays a zombie (a container without init) that kill -0 still finds,
// so a zombie counts as stopped. Where ps has no -p (busybox), only kill -0 decides.
export const ALIVE = '[ -s "$1/code" ] || { p=$(cat "$1/pid" 2>/dev/null); kill -0 "$p" 2>/dev/null && ! ps -o stat= -p "$p" 2>/dev/null | grep -q Z; } || [ -s "$1/code" ]';
// The longest the panel waits for one job (jobs.js), and so how old a job folder must be before
// SWEEP may remove it.
export const JOB_MINUTES = 15;
// sh -c SWEEP: removes job folders nobody will read: a panel that closed mid-job never collects
// its result. Keeps a job that still runs and any folder changed in the last JOB_MINUTES.
export const SWEEP = `for d in "\${TMPDIR:-/tmp}"/skillshare-panel.*; do
[ -d "$d" ] && [ -n "$(find "$d" -prune -mmin +${JOB_MINUTES})" ] || continue
[ ! -s "$d/code" ] && sh -c '${ALIVE}' alive "$d" && continue
rm -rf "$d"
done; exit 0`;
// sh -c GIT_STATUS <name> <source dir> [fetch]: the repo holding the source, its branch line and
// changed files. Prints "norepo" when the source is not in a git repository.
export const GIT_STATUS = `cd "$1" 2>/dev/null || { echo norepo; exit 0; }
top=$(git rev-parse --show-toplevel 2>/dev/null) || { echo norepo; exit 0; }
cd "$top"
[ "$2" = fetch ] && git fetch -q 2>/dev/null
echo "top $top"
git status --porcelain=v1 --branch --untracked-files=all`;
// sh -c PROJECT <name> <folder>: prints the folder when skillshare treats it as a project.
export const PROJECT = '[ -f "$1/.skillshare/config.yaml" ] || [ -f "$1/skillshare/config.yaml" ] && printf "%s" "$1"';
// Through START_SCRIPT: DISCOVER <cwd> <source> <git url> <branch> <-g|-p>.
// Keep a clone for audit, then ask the CLI for canonical names and repository-relative paths.
export const DISCOVER = `${TEMP}
GIT_TERMINAL_PROMPT=0 git clone -q --depth 1 \${4:+-b "$4"} "$3" "$d/r" >/dev/null 2>"$d/err" || { tail -n 1 "$d/err" >&2; rm -rf "$d"; exit 1; }
echo "@dir $d"
cd "$1" 2>/dev/null || cd
skillshare install "$2" --dry-run --json --kind skill "$5"`;
// Through START_SCRIPT: AUDIT <cwd> <temp folder> <-g|-p> <skill folders...>. One
// "@@ <folder>" line, then that folder's `skillshare audit <path> --json`, per folder.
export const AUDIT = `cd "$1" 2>/dev/null || cd; dir=$2; fl=$3; shift 3
for p; do echo "@@ $p"; skillshare audit "$dir/r/$p" --json "$fl" 2>/dev/null; echo; done`;
// sh -c PREVIEW <name> <repo> <files...>: each conflicting file as this computer committed it and
// as the remote has it ("@@gone" when that side deleted it), capped at 2000 lines.
export const PREVIEW = `cd "$1" || exit 1; shift
for p; do
for side in local remote; do
if [ $side = local ]; then rev=HEAD; else rev='@{u}'; fi
printf '@@%s %s\\n' "$side" "$p"
if git cat-file -e "$rev:$p" 2>/dev/null; then git show "$rev:$p" | head -n 2000; else echo "@@gone"; fi
done
done`;
// sh -c CONFLICTS <name> <repo>: replays the merge that push --pull undid and lists the files
// both sides changed. The merge stays in progress until RESOLVE or ABORT.
export const CONFLICTS = `cd "$1" || exit 1
git merge --abort 2>/dev/null || true
git merge --no-ff --no-commit @{u} >/dev/null 2>&1 || true
git -c core.quotePath=false diff --name-only --diff-filter=U`;
// sh -c RESOLVE <name> <repo> <path=local|remote>...: takes one side of each file and commits the
// merge. .metadata.json is merged per entry first (mergeMetadata, METADATA_*); any other file
// still unmerged stops it, so nothing is resolved without a choice.
export const RESOLVE = `set -e
cd "$1"; shift
for c in "$@"; do
p=\${c%=*}; side=\${c##*=}
if [ "$side" = remote ]; then flag=--theirs; else flag=--ours; fi
git checkout "$flag" -- "$p" 2>/dev/null && git add -- "$p" || git rm -q -- "$p"
done
if [ -n "$(git diff --name-only --diff-filter=U)" ]; then echo "unchosen conflicts remain" >&2; exit 1; fi
git commit -q --no-edit`;
// sh -c METADATA_STAGES <name> <repo> <path>: the file at the merge base, here and on the remote,
// each after an "@@stage N" line (empty when that side lacks it).
export const METADATA_STAGES = `cd "$1" || exit 1
for n in 1 2 3; do echo "@@stage $n"; git show ":$n:$2" 2>/dev/null; done`;
// sh -c METADATA_WRITE <name> <repo> <path> <content>: writes the merged file and stages it.
export const METADATA_WRITE = `cd "$1" && printf '%s' "$3" > "$2" && git add -- "$2"`;
export const ABORT = 'cd "$1" && git merge --abort 2>/dev/null; true';
// ---- Parsing ----
// The same per-entry merge skillshare's own pull does (internal/install/metadata_merge.go): an
// entry changed on one side takes that side; changed on both, the later installed_at wins (the
// remote on a tie) and an edit beats a delete; a local delete of an entry the remote left alone sticks.
export function mergeMetadata(base, ours, theirs) {
const parse = (text) => { const j = String(text ?? "").trim() ? JSON.parse(text) : {}; j.entries ??= {}; return j; };
const b = parse(base), o = parse(ours), th = parse(theirs);
const canon = (v) => JSON.stringify(v, (_k, x) => (x && typeof x === "object" && !Array.isArray(x) ? Object.fromEntries(Object.entries(x).sort()) : x));
const same = (x, y) => canon(x ?? null) === canon(y ?? null);
const at = (e) => Date.parse(e?.installed_at ?? "") || 0;
const merged = th;
for (const [name, mine] of Object.entries(o.entries)) {
const old = b.entries[name], remote = th.entries[name];
if (same(mine, old)) continue;
if (same(remote, old) || remote == null || at(mine) > at(remote)) merged.entries[name] = mine;
}
for (const name of Object.keys(th.entries)) {
if (!(name in o.entries) && b.entries[name] != null && same(th.entries[name], b.entries[name])) delete merged.entries[name];
}
return JSON.stringify(merged, null, 2) + "\n";
}
export function parseStages(text) {
const out = ["", "", ""];
let cur = -1;
for (const line of String(text ?? "").split("\n")) {
const m = line.match(/^@@stage ([123])$/);
if (m) { cur = Number(m[1]) - 1; continue; }
if (cur >= 0) out[cur] += `${line}\n`;
}
return out;
}
// The CLI flag for a scope.
export const flag = (scope) => (scope === "project" ? "-p" : "-g");
export function parseJSON(text, fallback = null) {
try { return JSON.parse(text); } catch { return fallback; }
}
// The last useful line of a command's output, for a notice.
export function lastLine(text) {
return String(text ?? "").replace(/\x1b\[[0-9;]*m/g, "").trim().split("\n").filter((l) => l.trim()).pop()?.trim() ?? "";
}
// An error JSON ({"error": "..."}) or the last line of stderr.
export function failure(r, what) {
const j = parseJSON(r?.stdout ?? "");
return j?.error || lastLine(r?.stderr) || lastLine(r?.stdout) || `${what} exited with ${r?.code}`;
}
// "## main...origin/main [ahead 1, behind 2]" and the changed files.
export function parseGitStatus(text) {
const lines = String(text ?? "").split("\n");
if (lines[0]?.trim() === "norepo") return { repo: false };
if (!lines.some((l) => l.startsWith("## "))) return null; // the read failed: unknown, not clean
const out = { repo: true, top: null, branch: null, upstream: null, ahead: 0, behind: 0, files: [] };
for (const line of lines) {
if (line.startsWith("top ")) out.top = line.slice(4);
else if (line.startsWith("## ")) {
const m = line.slice(3).match(/^(?:No commits yet on )?(\S+?)(?:\.\.\.(\S+))?(?: \[(.*)\])?$/);
if (m) {
out.branch = m[1]; out.upstream = m[2] ?? null;
const a = m[3]?.match(/ahead (\d+)/), b = m[3]?.match(/behind (\d+)/);
out.ahead = a ? Number(a[1]) : 0; out.behind = b ? Number(b[1]) : 0;
}
} else if (line.length > 3) out.files.push({ code: line.slice(0, 2).trim() || "?", path: line.slice(3) });
}
return out;
}
// The source line in the footer, and whether it needs attention.
export function sourceLine(git) {
if (!git) return { text: "Source · checking…", warn: false };
if (git.error) return { text: "Source · could not be read", warn: true };
if (!git.repo) return { text: "Source · not a git repository", warn: false };
const parts = [];
if (git.files.length) parts.push(`${git.files.length} uncommitted`);
if (git.ahead) parts.push(`↑${git.ahead}`);
if (git.behind) parts.push(`↓${git.behind}`);
if (!git.upstream) parts.push("no remote");
return { text: `Source · ${parts.length ? parts.join(" · ") : "up to date"}`, warn: Boolean(git.files.length || git.behind) };
}
// Resource names the targets still need, per kind, from `diff --json`. Items a sync would not
// touch (is_sync false: local-only in a target) are left out.
export function driftFrom(diff) {
const out = new Map();
for (const t of diff?.targets ?? []) {
for (const item of t.items ?? []) {
if (!item.is_sync) continue;
const kind = item.kind === "agent" ? "agents" : "skills";
const key = `${kind}:${item.name.replace(/\.md$/, "")}`;
const was = out.get(key);
out.set(key, { action: was?.action === "modify" ? "modify" : item.action, reason: was?.reason ?? item.reason, targets: [...(was?.targets ?? []), t.name] });
}
}
return out;
}
// What each target still needs, most first: [{ name, n }]; n is 0 for a target in sync.
export function targetDrift(diff) {
return (diff?.targets ?? []).map((t) => ({ name: t.name, n: (t.items ?? []).filter((i) => i.is_sync).length }))
.sort((a, b) => b.n - a.n || a.name.localeCompare(b.name));
}
// Every target of the shown scopes and what still waits on it, most waiting first:
// { known, list: [{ name, n }], scopes }. raw: { [scope]: { diff, targets } }; diff leaves out targets
// that share another's folder, so targets adds the configured names. diff counts skills and agents only, so a waiting MCP
// server, plugin or hook in items adds one to each target it waits on. known: a diff answered;
// scopes: the ones with a waiting target.
export function targetList(raw, scope = "all", items = []) {
const by = new Map();
let known = false;
const scopes = [];
for (const s of Object.keys(raw ?? {})) {
if (scope !== "all" && s !== scope) continue;
if (raw[s]?.diff?.targets) known = true;
const unknown = raw[s]?.pending?.includes("diff") || raw[s]?.errors?.diff;
for (const x of targetDrift(raw[s]?.diff)) {
const n = unknown ? 0 : x.n;
by.set(x.name, (by.get(x.name) ?? 0) + n);
if (n && !scopes.includes(s)) scopes.push(s);
}
for (const name of raw[s]?.targets ?? []) if (!by.has(name)) by.set(name, 0);
}
for (const i of items) {
if (!(scope === "all" || i.scope === scope) || i.notice || !waitsForSync(i) || !["mcp", "plugins", "hooks"].includes(i.kind)) continue;
for (const r of previewTargets(i)) if (r.warn && by.has(r.name)) by.set(r.name, by.get(r.name) + 1);
}
return { known, scopes, list: [...by].map(([name, n]) => ({ name, n })).sort((a, b) => b.n - a.n || a.name.localeCompare(b.name)) };
}
// A row Sync would act on: a waiting resource, or a hook notice with native changes.
export const waitsForSync = (i) => (i.notice ? Boolean(i.pending) : i.state === "sync" || i.state === "missing");
// The scopes Sync runs in for the shown scope: every one with a waiting row or a waiting target
// (a target can wait with no row left, as after an uninstall); with nothing waiting, the shown ones.
export function syncScopes(items, raw, scope = "all") {
const shown = (s) => scope === "all" || s === scope;
const out = new Set(items.filter((i) => shown(i.scope) && waitsForSync(i)).map((i) => i.scope));
for (const s of targetList(raw, scope).scopes) out.add(s);
if (!out.size) for (const s of Object.keys(raw ?? {})) if (shown(s)) out.add(s);
return [...out].sort();
}
// The map's lines, max at most: waiting targets first, then the ones in sync. What does not fit
// becomes a count: [{ name, n, wait } | { more, wait }].
export function mapLanes(targets, max = 6) {
const pending = targets.filter((x) => x.n), fine = targets.filter((x) => !x.n);
const slots = fine.length ? max - 1 : max;
const rows = (pending.length <= slots ? pending : pending.slice(0, slots - 1)).map((x) => ({ name: x.name, n: x.n, wait: true }));
if (pending.length > rows.length) rows.push({ more: pending.length - rows.length, wait: true, rest: pending.slice(rows.length) });
const room = max - rows.length, named = fine.length <= room ? fine : fine.slice(0, room - 1);
rows.push(...named.map((x) => ({ name: x.name, n: 0, wait: false })));
if (fine.length > named.length) rows.push({ more: fine.length - named.length, wait: false, rest: fine.slice(named.length) });
return rows;
}
const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
const andMore = (list) => (list.length <= 2 ? list.map((x) => x.name).join(" and ") : `${list[0].name}, ${list[1].name} and ${list.length - 2} more`);
// Overview's answer in two lines: { kind, headline, sub }, kind one of loading, failed, moving,
// waiting, ok. pending: rows Sync would act on; lag: targets with something waiting.
export function overviewAnswer({ loading, failed, error, moving, reading = [], incomplete = false, pending = 0, lag = [], total = 0, targets = 0 }) {
if (loading) return { kind: "loading", headline: "Reading skillshare", sub: "one moment" };
if (failed) return { kind: "failed", headline: "skillshare could not be read", sub: error ?? "" };
if (moving) return { kind: "moving", headline: lag.length ? `Syncing ${plural(lag.length, "target")}` : "Syncing", sub: lag.length ? andMore(lag) : "every target" };
if (reading.length) return { kind: "loading", headline: "Reading skillshare", sub: `Still reading ${reading.join(", ")} · other resources are available` };
if (incomplete) return { kind: "failed", headline: "Some sync states are unconfirmed", sub: "Available resources are shown below" };
if (pending || lag.length) {
return { kind: "waiting", headline: lag.length ? `${plural(lag.length, "target")} need${lag.length === 1 ? "s" : ""} a sync` : `${plural(pending, "resource")} to sync`,
sub: pending ? `${plural(pending, "resource")} waiting${lag.length ? ` for ${andMore(lag)}` : ""}` : `waiting on ${andMore(lag)}` };
}
return { kind: "ok", headline: "Everything is in sync", sub: `${plural(total, "resource")} · ${plural(targets, "target")}` };
}
// Loading/error state for the shown scopes. A kind's count is unknown until all its
// inventories answer; diff/status affect sync confidence but not inventory counts.
export function resourceProgress(raw, scope = "all") {
const pending = new Set(), errors = [], unknown = new Set();
let available = false;
const kinds = { list: ["skills", "agents"], mcp: ["mcp"], plugins: ["plugins"], hooks: ["hooks"] };
for (const [s, one] of Object.entries(raw)) {
if (scope !== "all" && scope !== s) continue;
available ||= Object.keys(kinds).some((key) => one[key] != null);
for (const key of one.pending ?? []) pending.add(key);
for (const [key, message] of Object.entries(one.errors ?? {})) errors.push(`${s} ${key}: ${message}`);
for (const [key, names] of Object.entries(kinds)) if ((one.pending ?? []).includes(key) || one.errors?.[key]) for (const name of names) unknown.add(name);
}
return { pending: [...pending], errors, unknown, available, incomplete: Boolean(pending.size || errors.length) };
}
// A machine card's remote line, and the targets that wait on it by name (max at most).
export function remoteLine(git) {
const dirty = git?.files?.length ?? 0;
return [git?.behind ? `↓${git.behind} behind` : null, dirty ? `${dirty} uncommitted` : null, git?.ahead ? `↑${git.ahead} to push` : null].filter(Boolean).join(" · ") || "up to date";
}
export const waitingNames = (waits, max = 3) => waits.slice(0, max).map((x) => `${x.name} ${x.n}`).join(" · ") + (waits.length > max ? ` · +${waits.length - max} more` : "");
// A machine with uncommitted or unpushed work and an upstream: a plain pull would refuse, so it syncs both ways.
export const needsBothWays = (git) => Boolean((git?.files?.length || git?.ahead) && git?.upstream);
const shortSource = (s) => String(s ?? "").replace(/^https?:\/\//, "").replace(/\.git(\/|$)/, "$1").replace(/\/$/, "");
// One scope's rows for every kind. `raw` holds each command's parsed JSON (missing ones are null).
export function buildItems(scope, raw) {
const items = [];
const drift = driftFrom(raw.diff);
const checks = new Map();
for (const s of raw.check?.skills ?? []) checks.set(`skills:${s.name}`, s);
for (const s of Array.isArray(raw.checkAgents) ? raw.checkAgents : []) checks.set(`agents:${s.name}`, s);
const behind = new Map((raw.check?.tracked_repos ?? []).map((r) => [r.name, r]));
for (const s of Array.isArray(raw.list) ? raw.list : []) {
const kind = s.kind === "agent" ? "agents" : "skills";
const flat = kind === "agents" ? s.name.replace(/\.md$/, "") : s.name;
const rel = String(s.relPath ?? s.name).replace(/\.md$/, "");
const check = checks.get(`${kind}:${rel}`) ?? checks.get(`${kind}:${flat}`);
const repo = s.repoName ? behind.get(s.repoName) : null;
const d = drift.get(`${kind}:${flat}`);
const item = {
key: `${scope}:${kind}:${flat}`, kind, scope, name: flat, label: rel.split("/").pop(), rel, path: String(s.relPath ?? s.name),
src: shortSource(check?.source ?? s.source) || (s.repoName ? `tracked repo ${s.repoName}` : rel.includes("/") ? rel : "local"),
disabled: Boolean(s.disabled), version: check?.version ?? null, state: "ok", repo: s.repoName || null,
};
if (item.disabled) item.state = "off";
else if (check?.status === "update_available" || repo?.status === "behind") {
item.state = "update"; item.behind = repo?.behind ?? 0; item.update = repo ? repo.name : rel;
} else if (d) { item.state = d.action === "add" ? "missing" : "sync"; item.reason = d.reason; item.targets = d.targets; }
items.push(item);
}
const mcp = new Map();
for (const c of raw.mcp?.changes ?? []) {
const m = mcp.get(c.name) ?? { targets: [], pending: [] };
m.targets.push(c.target);
if (c.action && c.action !== "unchanged") m.pending.push(`${c.target}: ${c.action}`);
mcp.set(c.name, m);
}
for (const [name, m] of mcp) {
items.push({ key: `${scope}:mcp:${name}`, kind: "mcp", scope, name, label: name, src: "MCP server",
state: m.pending.length ? "sync" : "ok", reason: m.pending.join(", "), targets: m.targets });
}
for (const [name, p] of Object.entries(raw.plugins?.packages ?? {})) {
const bindings = Object.values(p.bindings ?? {});
const pending = Object.entries(p.bindings ?? {}).filter(([, b]) => b.pending || b.sync === false).map(([t]) => t);
items.push({ key: `${scope}:plugins:${name}`, kind: "plugins", scope, name, label: name,
src: shortSource(p.source ?? bindings[0]?.id ?? "") || "plugin", version: p.version ?? bindings[0]?.version ?? null,
state: pending.length ? "sync" : bindings.length ? "ok" : "missing", reason: pending.length ? `pending in ${pending.join(", ")}` : "", targets: Object.keys(p.bindings ?? {}) });
}
const hooks = new Map();
const status = (id, root = "") => {
const item = { key: `${scope}:hooks:status:${id}`, kind: "hooks", scope, root, name: "Hook status", label: "Hook status", targets: [], changes: [], declared: false, notice: true, pending: false };
hooks.set(item.key, item);
return item;
};
const hook = (root, name) => {
const key = `${scope}:hooks:${root ? root + "/" : ""}${name}`;
if (!hooks.has(key)) hooks.set(key, { key, kind: "hooks", scope, root, name, label: name, targets: [], changes: [], declared: false });
return hooks.get(key);
};
for (const [root, source] of [["", raw.hooks?.source], ...Object.entries(raw.hooks?.source?.projects ?? {})]) {
for (const [name, entry] of Object.entries(source?.entries ?? {})) {
Object.assign(hook(root, name), { declared: true, disabled: entry.enabled === false, description: entry.description, targets: Object.keys(entry.bindings ?? {}) });
}
}
for (const [index, c] of (raw.hooks?.plan?.changes ?? []).entries()) {
const item = c.name ? hook(c.root ?? "", c.name) : status(index, c.root ?? "");
if (c.target && !item.targets.includes(c.target)) item.targets.push(c.target);
item.changes.push(c);
}
for (const c of raw.hooks?.plan?.changes ?? []) {
if (!c.name && !c.target && c.action === "conflict") {
for (const row of hooks.values()) if (!row.notice && row.root === (c.root ?? "")) row.changes.push(c);
}
}
const error = raw.hooks?.error || raw.hooks?.previewError;
if (error && Array.isArray(raw.list)) status("error");
for (const [index, warning] of (raw.hooks?.plan?.warnings ?? []).entries()) status(`warning:${index}`).warnings = [warning];
const changeLine = (c) => [[c.target, c.action].filter(Boolean).join(": "),
...new Set([c.message, c.inactiveReason].filter(Boolean))].join(" · ");
for (const item of hooks.values()) {
item.src = item.targets.join(", ") || "no agents";
const pending = item.changes.filter((c) => !["unchanged", "inactive"].includes(c.action));
item.lines = error ? (item.notice ? [error] : []) : [...item.changes.map(changeLine), ...(item.warnings ?? [])];
item.diagnostic = Boolean(item.changes.some((c) => c.action === "inactive" || c.inactiveReason));
const summary = pending.length ? item.changes.filter((c) => c.action !== "unchanged" || c.inactiveReason) : item.changes;
item.reason = item.notice ? item.lines.join("; ") : summary.map(changeLine).join("; ");
if (item.notice) {
item.pending = item.changes.some((c) => ["add", "update", "remove", "adopt", "release"].includes(c.action));
item.blocker = Boolean(error || item.changes.some((c) => c.action === "conflict"));
}
item.state = !raw.hooks?.plan ? "unknown" : pending.length ? "sync" : item.disabled ? "off" : "ok";
items.push(item);
}
if (raw.pending || raw.errors) {
for (const item of items) {
const keys = item.kind === "skills" || item.kind === "agents" ? ["list", "diff", "status"] : [item.kind];
if (!item.notice && item.state !== "off" && keys.some((key) => raw.pending?.includes(key) || raw.errors?.[key])) {
item.cachedState = item.state;
item.state = "unknown";
}
}
}
return items;
}
// Only top-level declared hooks can be changed with the panel's scoped CLI actions.
export function hookArgs(item, action) {
if (item.kind !== "hooks" || !item.declared || item.root || !["enable", "disable", "remove"].includes(action)) return null;
if ((action === "enable" && !item.disabled) || (action === "disable" && item.disabled)) return null;
return ["hooks", action, item.name, item.scope === "project" ? "-p" : "-g"];
}
// Enabling or disabling a skill or agent → skillshare's args, or null when the row can't take
// that change. The pattern is the entry's own path (an agent's keeps its .md), as the dashboard
// writes it, so enable removes exactly what disable added.
export function toggleArgs(item, action) {
if (!["skills", "agents"].includes(item.kind) || !item.path) return null;
if (action !== (item.disabled ? "enable" : "disable")) return null;
return [action, item.path, ...(item.kind === "agents" ? ["--kind", "agent"] : []), flag(item.scope)];
}
// The rows as they will be once a running request lands, so the list answers the click and not
// the read that follows it. req: what the panel was asked ({ op, item, action, updates, scopes,
// plugins, added, project }); project: the folder the rows are for, since project rows of
// another folder are not these rows. What cannot fail quietly is shown done: a disable, an
// enable, a removal. An update and a sync can be stopped (an audit, a conflict), so their rows
// only say they are running (`doing`). The read after the request replaces all of it; a request
// that fails is simply dropped, and the rows are back as they were.
export function optimistic(items, req, project = req.project) {
const ours = (i) => i.scope !== "project" || (req.project ?? null) === (project ?? null);
const one = (change) => items.flatMap((i) => (i.key === req.item?.key && ours(i) ? change(i) : [i]));
const doing = (text, hit) => items.map((i) => (ours(i) && hit(i) ? { ...i, doing: text } : i));
const able = (i) => [{ ...i, disabled: req.action === "disable", state: req.action === "disable" ? "off" : "ok" }];
if (req.op === "toggle") return one(able);
if (req.op === "hook") return one(req.action === "remove" ? () => [] : able);
if (req.op === "uninstall") return one(() => []);
if (req.op === "update") return doing("updating", (i) => i.state === "update" && (req.updates ?? []).some((u) => u.kind === i.kind && u.scope === i.scope && (u.all || u.name === i.update)));
if (req.op === "sync") return doing("syncing", (i) => !i.notice && waitsForSync(i) && (req.scopes ?? []).includes(i.scope) && (i.kind !== "plugins" || req.plugins));
if (req.op === "refresh" && req.added?.length) {
const fresh = req.added.filter((a) => ours(a) && !items.some((i) => i.kind === "skills" && i.scope === a.scope && i.label === a.name));
return [...items, ...fresh.map((a) => ({ key: `${a.scope}:skills:${a.name}`, kind: "skills", scope: a.scope, name: a.name, label: a.name, rel: a.name, path: a.name, src: shortSource(a.source) || "local", disabled: false, version: null, state: "ok", repo: null }))];
}
return items;
}
// The panel keeps every request from the click until a read newer than its end has landed.
// These four decide what that list holds; main.js only stores it.
// The rows to show on machine `on`: what was read, with that machine's requests laid over it.
export const shownRows = (read, pending, on, project) => pending.filter((r) => (r.on ?? null) === (on ?? null)).reduce((items, r) => optimistic(items, r, project), read);
// The requests a read starting now is newer than. One that ends later is not in that read.
export const endedRequests = (pending) => pending.filter((r) => r.ended);
// After a read's list has landed. ended: endedRequests when it started; checking: the same read
// also runs the update checks. An update shows in the checks, so its request stays (late) until
// afterChecks. Anything still ended in what is left needs one more read.
export function afterRead(pending, ended, checking) {
const late = checking ? ended.filter((r) => r.op === "update") : [];
return { pending: pending.filter((r) => !ended.includes(r) || late.includes(r)), late };
}
export const afterChecks = (pending, late) => pending.filter((r) => !late.includes(r));
// A row's one short state; everything longer is in its preview.
export function rowState(item, showScope) {
const pre = showScope ? `${item.scope} · ` : "";
if (item.notice) return item.scope;
if (item.doing) return `${pre}${item.doing}…`;
const state = { update: "update available", missing: "new", sync: "changed", unknown: "sync status unknown" }[item.state];
if (state) return pre + state;
if (item.state === "off") return `${pre}disabled`;
if (item.diagnostic) return `${pre}inactive on an agent`;
if (item.kind === "mcp" || item.kind === "hooks") { const n = item.targets?.length ?? 0; return `${pre}${n} ${item.kind === "mcp" ? "target" : "agent"}${n === 1 ? "" : "s"}`; }
const src = sourceLabel(item).label;
return `${pre}${src}${item.version && item.kind === "plugins" ? ` · ${item.version}` : ""}`;
}
// The targets a skill or an agent can go to in its scope, by name. one: raw[scope], whose
// skillTargets and agentTargets come from status; a target the item waits on is always one.
// diff's targets stand in only when status named none: diff also lists targets that take agents alone.
export function eligibleTargets(item, one) {
const base = item.kind === "agents" ? one?.agentTargets ?? [] : one?.skillTargets?.length ? one.skillTargets : (one?.diff?.targets ?? []).map((x) => x.name);
return [...new Set([...base, ...(item.state === "off" ? [] : item.targets ?? [])])].sort();
}
// Who gets an item and what each still needs, waiting first: [{ name, text, warn }].
// names: every target of the item's scope, for skills and agents (their rows name only the waiting ones).
export function previewTargets(item, names = []) {
let rows;
if (item.kind === "hooks") {
const by = new Map((item.targets ?? []).map((n) => [n, { name: n, text: "in sync", warn: false }]));
for (const c of item.changes ?? []) if (c.target) by.set(c.target, { name: c.target, text: c.action === "unchanged" ? "in sync" : c.action, warn: !["unchanged", "inactive"].includes(c.action) });
rows = [...by.values()];
} else if (item.kind === "mcp" || item.kind === "plugins") {
const waits = new Map(String(item.reason ?? "").replace(/^pending in /, "").split(", ").filter(Boolean).map((x) => { const [n, a] = x.split(": "); return [n, a ?? "pending"]; }));
rows = (item.targets ?? []).map((n) => ({ name: n, text: waits.get(n) ?? "in sync", warn: waits.has(n) }));
} else {
const waits = new Set(item.targets ?? []);
rows = names.map((n) => ({ name: n, text: item.state === "off" ? "disabled" : waits.has(n) ? "needs sync" : "in sync", warn: item.state !== "off" && waits.has(n) }));
}
if (item.state === "unknown") rows = rows.map((row) => ({ ...row, text: "sync status unknown", warn: false }));
return rows.sort((a, b) => Number(b.warn) - Number(a.warn) || a.name.localeCompare(b.name));
}
// sh -c READ_SKILL <name> <dir>: its files (40 at most), "@@", then SKILL.md's first 60 kB.
export const READ_SKILL = `cd "$1" 2>/dev/null || exit 3
find . -type f -not -path './.git/*' | sed 's|^\\./||' | sort | head -40
echo @@
head -c 60000 SKILL.md 2>/dev/null`;
// sh -c READ_FILE <name> <path>: a file's first 60 kB.
export const READ_FILE = 'head -c 60000 "$1" 2>/dev/null';
// A Markdown file's frontmatter as rows, and the text after it: { meta: [{ key, value }], body }.
export function splitFrontmatter(text) {
const m = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(String(text ?? ""));
if (!m) return { meta: [], body: String(text ?? "") };
const meta = [];
for (const line of m[1].split(/\r?\n/)) {
const top = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
if (top) meta.push({ key: top[1], value: /^[>|][+-]?$/.test(top[2]) ? "" : top[2].replace(/^(["'])(.*)\1$/, "$2") });
else if (meta.length && /^\s+\S/.test(line)) { const last = meta[meta.length - 1]; last.value = `${last.value} ${line.trim().replace(/^- /, "")}`.trim(); }
}
return { meta, body: String(text ?? "").slice(m[0].length) };
}
// One server's settings out of the MCP source file, as rows. Values under env, headers and
// bearerToken are never returned: only their names.
const SECRET = /^(env|headers|bearerToken)$/, MASK = "••••••••";
export function mcpServer(text, name) {
const lines = String(text ?? "").split(/\r?\n/).filter((l) => l.trim() && !l.trim().startsWith("#"));
const depth = (l) => l.match(/^ */)[0].length, bare = (k) => k.trim().replace(/^(["'])(.*)\1$/, "$2");
// The file can hold several server lists (the global one, and one per project root): the first that names it wins.
let start = -1, child = null;
for (let at = 0; at < lines.length && start < 0; at++) {
if (!/^\s*servers:\s*$/.test(lines[at])) continue;
child = null;
for (let j = at + 1; j < lines.length && depth(lines[j]) > depth(lines[at]); j++) {
child ??= depth(lines[j]);
if (depth(lines[j]) === child && bare(lines[j].replace(/:\s*$/, "")) === name) { start = j; break; }
}
}
if (start < 0) return null;
const rows = [];
let field = null;
for (let j = start + 1; j < lines.length && depth(lines[j]) > child; j++) {
field ??= depth(lines[j]);
const s = lines[j].trim(), last = rows[rows.length - 1];
if (depth(lines[j]) === field) {
const m = /^([^:]+):\s*(.*)$/.exec(s);
if (m) rows.push({ key: bare(m[1]), secret: SECRET.test(bare(m[1])), parts: m[2] ? [SECRET.test(bare(m[1])) ? MASK : m[2].replace(/^\[(.*)\]$/, "$1")] : [], inner: null });
} else if (last) {
last.inner ??= depth(lines[j]);
if (depth(lines[j]) !== last.inner) continue;
last.parts.push(last.secret ? `${bare(s.replace(/^- /, "").split(":")[0])} = ${MASK}` : bare(s.replace(/^- /, "")));
}
}
return rows.map((r) => ({ key: r.key, value: r.parts.join(r.secret ? ", " : " ") }));
}
export function filterItems(items, { scope, kind, query }) {
const q = String(query ?? "").trim().toLowerCase();
return items.filter((i) => (scope === "all" || i.scope === scope) && (!kind || i.kind === kind)
&& (!q || i.name.toLowerCase().includes(q) || i.src.toLowerCase().includes(q)
|| (i.kind === "hooks" && `${i.root ?? ""} ${i.reason ?? ""}`.toLowerCase().includes(q))));
}
export function groupItems(items) {
const by = (s) => items.filter((i) => !i.notice && s.includes(i.state)).sort((a, b) => a.label.localeCompare(b.label));
return { update: by(["update"]), sync: by(["sync", "missing"]), ok: by(["ok", "off"]) };
}
// The repository a row came from: a tracked repo by name, a URL source by host/owner/repo
// (github.com left out), anything else by its source text.
function sourceLabel(item) {
if (item.repo) return { label: item.repo, repo: true };
const m = /^([^/\s]+\.[^/\s]+)\/([^/]+)\/([^/]+)/.exec(item.src);
if (!m) return { label: item.src, repo: false };
return { label: m[1] === "github.com" ? `${m[2]}/${m[3]}` : `${m[1]}/${m[2]}/${m[3]}`, repo: true };
}
// Sources with two or more rows become groups; the rest stay plain rows. Both sorted by label.
// `repo` is false for a group of local rows.
export function sourceGroups(items) {
const by = new Map();
for (const i of items) {
const { label, repo } = sourceLabel(i);
if (!by.has(label)) by.set(label, { repo, list: [] });
by.get(label).list.push(i);
}
const byLabel = (a, b) => a.label.localeCompare(b.label);
const groups = [], rows = [];
for (const [label, { repo, list }] of by) {
if (list.length > 1) groups.push({ key: `source:${label}`, label, repo, items: list.sort(byLabel) });
else rows.push(list[0]);
}
return { groups: groups.sort(byLabel), rows: rows.sort(byLabel) };
}
export function counts(items) {
const c = { all: 0, project: 0, global: 0, skills: 0, agents: 0, mcp: 0, plugins: 0, hooks: 0 };
for (const i of items) { if (!i.notice) { c.all++; c[i.scope]++; c[i.kind]++; } }
return c;
}
// "owner/repo", "github.com/owner/repo" or a URL → something git can clone, and whether the
// source names one skill inside the repo (then there is nothing to pick).
export function cloneUrl(source) {
const s = String(source ?? "").trim().replace(/\/$/, "");
if (!s) return null;
if (/^(git@|ssh:\/\/|file:\/\/|\/|~)/.test(s)) return { url: s, single: false };
let rest = s.replace(/^https?:\/\//, "");
if (/^[\w.-]+\/[\w.-]+$/.test(rest)) rest = `github.com/${rest}`;
const parts = rest.split("/");
if (parts.length < 3) return null;
const repo = parts.slice(0, 3).join("/").replace(/\.git$/, "");
const single = parts.length > 3 && !(parts[3] === "tree" && parts.length <= 5);
const onBranch = ["tree", "blob"].includes(parts[3]);
const path = !single ? "" : (onBranch ? parts.slice(5) : parts.slice(3)).join("/");
return { url: `https://${repo}.git`, single, path, branch: onBranch && parts[4] ? parts[4] : "" };
}
// Keep exit status authoritative even with valid JSON from an older CLI.
export function installResult(r) {
const j = parseJSON(r.stdout), done = j?.skills ?? [], failed = j?.failed ?? [];
if (j?.error) return { done: null, error: j.error };
if (r.code !== 0) {
const details = [done.length ? `Installed: ${done.join(", ")}.` : "", failed.length ? `Failed: ${failed.join(", ")}.` : "", lastLine(r.stderr)].filter(Boolean);
details.push(`skillshare install exited with ${r.code}.`);
return { done: null, error: details.join(" ") };
}
if (failed.length) return { done: null, error: `Installed ${done.length} skill(s); ${failed.join(", ")} failed. The install's own audit can stop one.` };
if (!j) return { done: null, error: failure(r, "skillshare install returned no JSON") };
return { done, error: null };
}
export function newerVersion(a, b) {
const n = (v) => String(v ?? "").replace(/^v/, "").split(".").map((x) => parseInt(x, 10) || 0);
const x = n(a), y = n(b);
for (let i = 0; i < 3; i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) > (y[i] ?? 0) ? a : b;
return a;
}
// ---- The panel's own update ----
const REPO = "https://github.com/runkids/skillshare";
// sh -c LATEST_RELEASE: prints where GitHub's "latest release" link lands (…/releases/tag/vX.Y.Z).
// The link instead of the API: it has no rate limit, and it names only a published release, never
// the tag of a draft.
export const LATEST_RELEASE = `curl -fsSLI --max-time 15 -o /dev/null -w '%{url_effective}' ${REPO}/releases/latest`;
export const releaseTag = (url) => /\/releases\/tag\/(v\d+\.\d+\.\d+)\s*$/.exec(String(url ?? ""))?.[1] ?? null;
// The release to offer: `latest` when it is newer than this panel, else null.
export const panelUpdate = (version, latest) => (latest && newerVersion(version, latest) !== version ? latest : null);
// sh -c PANEL_UPDATE <name> <dir> <tag> <from> [repo]: replaces the panel's files in Herdr's home
// on this computer with the ones release <tag> ships. It first checks the folder holds the
// running panel (version <from>): a renamed panel leaves another mod under this name. The files it
// replaces are copied once to .bak-update-<from> inside the folder (hidden, so Herdr does not load
// it), so a retry keeps the first copy. Herdr reloads the panel on every file it saves, so
// main.js goes after the modules it imports and version.js last: the build that reads the new
// version has every new file.
export const PANEL_UPDATE = `set -e
tag=$2; from=$3; repo=\${4:-${REPO}.git}; dest="\${HERDR_APP_HOME:-$HOME/.config/herdr-app}/mods/skillshare"
grep -qsF '"'"$from"'"' "$dest/version.js" || { echo "The panel is not in $dest; update it by hand" >&2; exit 1; }
t=$(mktemp -d "\${TMPDIR:-/tmp}/skillshare-panel.XXXXXX"); trap 'rm -rf "$t"' EXIT
export GIT_TERMINAL_PROMPT=0
{ git clone -q --depth 1 --filter=blob:none --sparse --branch "$tag" "$repo" "$t/repo" && git -C "$t/repo" sparse-checkout set herdr/skillshare/mods/skillshare; } >/dev/null 2>&1 || {
rm -rf "$t/repo"; git clone -q --depth 1 --branch "$tag" "$repo" "$t/repo"; }
src="$t/repo/herdr/skillshare/mods/skillshare"
[ -f "$src/main.js" ] && [ -f "$src/version.js" ] || { echo "Release $tag has no panel update" >&2; exit 1; }
bak="$dest/.bak-update-$from"
[ -d "$bak" ] || { rm -rf "$bak.tmp"; mkdir "$bak.tmp"; cp -R "$dest"/* "$bak.tmp/"; mv "$bak.tmp" "$bak"; }
for f in "$src"/*; do case "\${f##*/}" in main.js|version.js) ;; *) cp -R "$f" "$dest/" ;; esac; done
cp "$src/main.js" "$dest/main.js"; cp "$src/version.js" "$dest/version.js"`;
// What a panel update left in shared for the build that loads after it ({ to, at }): "done" when
// this build is the one it installed, "stale" when the update never finished, else null (it is
// still copying files).
export function updateState(record, version, now = Date.now()) {
if (!record?.to) return null;
if (String(record.to).replace(/^v/, "") === version) return "done";
return now - (record.at ?? 0) > JOB_MINUTES * 60 * 1000 ? "stale" : null;
}
export function ago(ms) {
const s = Math.max(0, Math.round(ms / 1000));
if (s < 60) return `${s}s ago`;
if (s < 3600) return `${Math.round(s / 60)}m ago`;
return `${Math.round(s / 3600)}h ago`;
}
// The message an agent gets when asked to audit a resource.
export function auditMessage(item) {
const flag = item.scope === "project" ? " -p" : " -g";
const kind = item.kind === "agents" ? "agents " : "";
return `Audit the ${item.kind === "agents" ? "agent" : "skill"} "${item.name}": run \`skillshare audit ${kind}${item.name}${flag} --json\` and \`skillshare diff${flag}\`. Summarize what changed and any findings, then wait for me.`;
}
// DISCOVER's output → the audit clone and the CLI's exact install plan. Never fall back
// to filesystem discovery: it can audit one directory and install a different one.
export function parseDiscover(text) {
const lines = String(text ?? "").trim().split("\n");
const dir = lines[0]?.startsWith("@dir ") ? lines.shift().slice(5) : null;
const j = parseJSON(lines.join("\n"));
const fail = (error) => ({ dir, choices: [], error });
if (j?.error) return fail(j.error);
if (!Array.isArray(j?.planned)) return fail("Upgrade skillshare on this machine: this CLI does not provide an install plan.");
const names = new Set();
for (const skill of j.planned) {
if (!skill.name || !skill.path) return fail("The CLI returned an incomplete install plan.");
const key = skill.name.toLowerCase();
if (names.has(key)) return fail(`Ambiguous install name: ${skill.name}. Use an explicit skill URL instead.`);
names.add(key);
}
return { dir, choices: j.planned, error: null };
}
const SEVERITY = ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO"];
// AUDIT's output → whether the audit would stop the install, and the findings that stop it.
// No readable result (an older CLI) is "unknown": install still audits on its own.
export function parseAudit(text, dir) {
const prefix = dir ? `${dir}/r/` : null;
const findings = [], blocked = [];
let read = 0;
for (const part of String(text ?? "").split(/^@@ /m).slice(1)) {
const nl = part.indexOf("\n");
const folder = part.slice(0, nl).trim();
const j = parseJSON(part.slice(nl + 1));
if (!j?.results) continue;
read++;
for (const r of j.results) {
if (!r.isBlocked) continue;
const skill = folder === "." ? "." : folder.split("/").pop(); // "." is the repository root; the caller names it
blocked.push(skill);
for (const f of r.findings ?? []) {
const file = prefix && String(f.file ?? "").startsWith(prefix) ? f.file.slice(prefix.length) : f.file;
findings.push({ skill, severity: f.severity, pattern: f.pattern, file, line: f.line, snippet: f.snippet ?? f.message ?? "" });
}
}
}
findings.sort((a, b) => SEVERITY.indexOf(a.severity) - SEVERITY.indexOf(b.severity));
return { unknown: read === 0, blocked, findings };
}
// PREVIEW's output → { path: { local, remote } }, null for a side that deleted the file.
export function parsePreview(text) {
const out = {};
let cur = null;
for (const line of String(text ?? "").split("\n")) {
const m = line.match(/^@@(local|remote) (.+)$/);
if (m) { cur = { path: m[2], side: m[1] }; (out[m[2]] ??= { local: [], remote: [] })[m[1]] = []; continue; }
if (!cur) continue;
const side = out[cur.path];
if (line === "@@gone") side[cur.side] = null;
else if (side[cur.side]) side[cur.side].push(line);
}
for (const v of Object.values(out)) for (const k of ["local", "remote"]) if (v[k]) v[k] = v[k].join("\n").replace(/\n$/, "");
return out;
}
// Two versions of a file → each side's lines with the ones the other lacks marked, unchanged
// runs folded to `context` lines around each change.
export function diffSides(a, b, context = 2) {
const x = a == null ? [] : String(a).split("\n"), y = b == null ? [] : String(b).split("\n");
const n = x.length, m = y.length;
const L = Array.from({ length: n + 1 }, () => new Uint16Array(m + 1));
for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) L[i][j] = x[i] === y[j] ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1]);
const markX = new Array(n).fill(true), markY = new Array(m).fill(true);
for (let i = 0, j = 0; i < n && j < m;) {
if (x[i] === y[j]) { markX[i++] = false; markY[j++] = false; } else if (L[i + 1][j] >= L[i][j + 1]) i++; else j++;
}
const fold = (lines, marks) => {
const keep = marks.map((_, i) => marks.slice(Math.max(0, i - context), i + context + 1).some(Boolean));
const out = [];
lines.forEach((text, i) => {
if (keep[i]) out.push({ text, mark: marks[i] });
else if (out.at(-1)?.gap !== true) out.push({ text: "…", gap: true });
});
return out;
};
const differ = Math.max(markX.filter(Boolean).length, markY.filter(Boolean).length);
return { local: a == null ? null : fold(x, markX), remote: b == null ? null : fold(y, markY), differ };
}
@@ -0,0 +1,218 @@
// What each request the panel performs does on a machine: the skillshare commands in order, how
// their output reads, and what to tell the person. No Herdr imports and no view state: main.js
// takes the lock, shows progress and the result, and the tests pass a fake machine.
import {
hookArgs, toggleArgs, failure, parseJSON, lastLine, flag, PANEL_UPDATE, CONFLICTS, ABORT, RESOLVE, PREVIEW, METADATA_STAGES, METADATA_WRITE,
mergeMetadata, parseStages, parsePreview, diffSides,
} from "./model.js";
const isMetadata = (f) => f === ".metadata.json" || f.endsWith("/.metadata.json");
const lines = (r) => String(r.stdout ?? "").split("\n").map((s) => s.trim()).filter(Boolean);
const BOTH_WAYS = ["push", "--pull", "-m", "Update skills from Herdr"];
const done = (text) => ({ kind: "done", text });
const warn = (text) => ({ kind: "warn", text });
const error = (text) => ({ kind: "error", text });
const outcome = (r, ok, what) => (r.code === 0 ? done(ok) : error(failure(r, what)));
// operate(req, io) performs one request on machine req.on.
// io.job(args, { on, cwd }): skillshare run detached; io.run(args, { on, cwd }): a short read;
// io.sh(script, args, on): a script of ours; io.step(text): what it is doing now.
// Resolves to { kind, text } for the notice (kind null: none), and when they apply:
// conflict: the stopped pull to ask about ({ on, repo, files, previews, push }), or null when
// no stopped pull is left;
// overlay: { title, text } to show; machines: true when the Machines tab should reload.
export async function operate(req, io) {
const op = OPS[req.op];
return op ? op(req, io, req.on ?? null) : { kind: null };
}
const at = (req, scope) => ({ on: req.on ?? null, cwd: scope === "project" ? req.project : null });
const OPS = {
async sync(req, { job, step }) {
for (const scope of req.scopes) {
step(`Syncing ${scope}…`);
const r = await job(["sync", "--all", "--json", flag(scope)], at(req, scope));
if (r.code !== 0) return error(failure(r, "skillshare sync"));
if (req.plugins) {
const p = await job(["sync", "plugins", "--json", flag(scope)], at(req, scope));
if (p.code !== 0) return error(failure(p, "skillshare sync plugins"));
}
}
return done(req.scopes.length > 1 ? "Synced project and global" : `Synced ${req.scopes[0]}`);
},
async update(req, { job, step }) {
let updated = 0;
for (const u of req.updates) {
step(u.all ? `Updating all ${u.kind === "agents" ? "agents" : "skills"} (${u.scope})…` : `Updating ${u.label}…`);
const args = ["update", ...(u.kind === "agents" ? ["agents"] : []), ...(u.all ? ["--all"] : [u.name]), "--json", flag(u.scope)];
const r = await job(args, at(req, u.scope));
const j = parseJSON(r.stdout);
const blocked = (j?.items ?? []).filter((i) => i.status === "security_blocked").map((i) => i.name);
if (blocked.length) return error(`Audit blocked ${blocked.join(", ")}. Ask an agent to audit it before updating.`);
if (r.code !== 0 && !j) return error(failure(r, "skillshare update"));
const failed = [...(j?.items ?? []), ...(j?.agents ?? [])].filter((i) => i.status === "failed");
if (failed.length) return error(`Could not update ${failed.map((i) => i.name).join(", ")}: ${failed[0].error ?? failed[0].message ?? "see skillshare update"}`);
updated += j?.updated ?? (j?.agents ?? []).filter((a) => a.status === "updated").length ?? 0;
}
return done(updated ? `Updated ${updated}. Targets get it on the next sync.` : "Already up to date");
},
async hook(req, { job, step }) {
const args = hookArgs(req.item, req.action);
if (!args) return error("This hook action is unavailable.");
step(`Saving ${req.item.label}…`);
const r = await job(args, at(req, req.item.scope));
return outcome(r, "Saved. Sync applies it.", "skillshare hooks");
},
async toggle(req, { job, step }) {
const it = req.item, args = toggleArgs(it, req.action);
if (!args) return error("This action is unavailable.");
step(`${req.action === "enable" ? "Enabling" : "Disabling"} ${it.label}…`);
const r = await job(args, at(req, it.scope));
if (r.code !== 0) return error(failure(r, `skillshare ${req.action}`));
// Exit 0 only says the entry's own line was written. A glob, a folder pattern or a negation in
// the .local file can still decide the other way, so the list is what answers.
const kind = it.kind === "agents" ? "agent" : "skill", want = req.action === "disable";
const now = (parseJSON((await job(["list", "--all", "--json", flag(it.scope)], at(req, it.scope))).stdout) ?? []).find?.((x) => (x.kind ?? "skill") === kind && (x.relPath ?? x.name) === it.path);
if (now && Boolean(now.disabled) !== want) {
const file = kind === "agent" ? ".agentignore" : ".skillignore";
return error(`${it.label} is still ${want ? "enabled" : "disabled"}: another pattern in ${file} or ${file}.local decides it. Edit that file.`);
}
return done(want ? `Disabled ${it.label}. The next sync removes it from your targets.` : `Enabled ${it.label}. The next sync sends it to your targets.`);
},
async uninstall(req, { job, step }) {
const it = req.item;
step(`Uninstalling ${it.label}…`);
const kind = it.kind === "agents" ? ["agents"] : [];
const args = it.scope === "project" ? ["uninstall", ...kind, it.rel, "-p", "--force", "--json"] : ["uninstall", ...kind, it.rel, "--json", "-g"];
const r = await job(args, at(req, it.scope));
if (r.code !== 0) return error(failure(r, "skillshare uninstall"));
const failed = parseJSON(r.stdout)?.failed;
if (failed?.length) return error(`Could not uninstall ${failed.join(", ")}`);
return done(`Moved ${it.label} to the skillshare trash`);
},
async syncboth(req, io, on) {
io.step("Syncing both ways…");
const r = await io.job(BOTH_WAYS, { on });
if (r.code === 0) return { ...done("Synced both ways: pushed, pulled and synced targets"), conflict: null };
const stop = await stopOnConflict(r, req.repo, on, io, true);
if (stop === "merged") {
io.step("Pushing…");
const p = await io.job(BOTH_WAYS, { on });
return { ...outcome(p, "Merged skill records from both machines and synced both ways", "skillshare push"), ...(p.code === 0 ? { conflict: null } : {}) };
}
if (stop) return { ...warn("Pull stopped: both sides changed the same files. Nothing was pushed."), conflict: stop };
return error(failure(r, "skillshare push --pull"));
},
async pull(req, io, on) {
io.step("Pulling…");
const r = await io.job(["pull"], { on });
if (r.code === 0) return { ...done("Pulled and synced targets"), conflict: null };
const stop = await stopOnConflict(r, req.repo, on, io, false);
if (stop === "merged") {
io.step("Syncing targets…");
const sy = await io.job(["sync", "--all", "--json", "-g"], { on });
return outcome(sy, "Pulled, merged skill records from both machines, and synced targets", "skillshare sync");
}
if (stop) return { ...warn("Pull stopped: both sides changed the same files. Nothing changed yet."), conflict: stop };
return error(failure(r, "skillshare pull"));
},
async push(req, { job, step }, on) {
step(req.commit ? "Committing and pushing…" : "Pushing…");
return outcome(await job(["push", "-m", req.message], { on }), "Pushed to the remote", "skillshare push");
},
// Replays the stopped pull with the person's choice for each file.
async resolve(req, io, on) {
const { sh, job, step } = io;
step("Applying your choices…");
const now = lines(await sh(CONFLICTS, [req.repo], on)).filter((f) => !isMetadata(f));
if (now.some((f) => !req.choices[f])) {
// The remote moved since the preview: other files conflict now. Ask again instead of guessing.
await sh(ABORT, [req.repo], on);
const stop = await stopOnConflict({ stdout: "conflict", stderr: "" }, req.repo, on, io, req.push);
if (stop && stop !== "merged") return { ...warn("The remote changed since you chose. Pick again."), conflict: stop };
return { ...error("The remote changed since you chose; nothing changed"), conflict: null };
}
const meta = await mergeMetadataFiles(req.repo, on, sh);
if (meta) { await sh(ABORT, [req.repo], on); return error(meta); }
const r = await sh(RESOLVE, [req.repo, ...Object.entries(req.choices).map(([p, side]) => `${p}=${side}`)], on);
if (r.code !== 0) { await sh(ABORT, [req.repo], on); return error(lastLine(r.stderr) || "Could not apply the choices; nothing changed"); }
if (!req.push) {
// Stopped by a plain pull: merge the choices and sync, but leave pushing to the person.
step("Syncing targets…");
const sy = await job(["sync", "--all", "--json", "-g"], { on });
return { ...outcome(sy, "Merged your choices and synced targets. Push when you're ready.", "skillshare sync"), conflict: null };
}
step("Pushing…");
const p = await job(BOTH_WAYS, { on });
return { ...outcome(p, "Resolved and synced both ways", "skillshare push"), ...(p.code === 0 ? { conflict: null } : {}) };
},
async pullsync(req, { job, step }, on) {
step(`Pulling on ${req.label}…`);
return { ...outcome(await job(["pull"], { on }), `Pulled and synced on ${req.label}`, "skillshare pull"), machines: true };
},
async upgrade(req, { job, step }, on) {
step(`Updating skillshare on ${req.label}…`);
return { ...outcome(await job(["upgrade", "--cli", "--force"], { on }), `Updated skillshare on ${req.label}`, "skillshare upgrade"), machines: true };
},
// The panel's own files, always on this computer: Herdr's home is here, whatever machine is shown.
async panel(req, { job, step }) {
step(`Updating the panel to ${req.to}…`);
return outcome(await job([req.to, req.from], { on: null, script: PANEL_UPDATE }), `Updated the panel to ${req.to}`, "The panel update");
},
async text(req, { run, step }, on) {
step(req.busy);
const r = await run(req.args, { on, cwd: req.cwd ?? null });
return { kind: null, overlay: { title: req.title, text: String(r.stdout || r.stderr || "No output").replace(/\x1b\[[0-9;]*m/g, "") } };
},
};
// A pull that both sides changed: read the files both ways, put the repository back as it was,
// and return what to ask about. Only .metadata.json changed on both sides: merge it per entry the
// way skillshare's pull does, commit, and return "merged". Not a conflict, or one that can't be
// read: false.
async function stopOnConflict(r, repo, on, { sh, step }, push) {
if (!repo || !/both changed|merge was undone|conflict/i.test(`${r.stdout}\n${r.stderr}`)) return false;
step("Reading conflicts…");
const all = lines(await sh(CONFLICTS, [repo], on));
const files = all.filter((f) => !isMetadata(f));
if (!files.length && all.length) {
step("Merging skill records…");
let err = await mergeMetadataFiles(repo, on, sh);
if (!err && (await sh(RESOLVE, [repo], on)).code !== 0) err = "Could not commit the merged skill records";
if (err) { await sh(ABORT, [repo], on); return false; }
return "merged";
}
await sh(ABORT, [repo], on);
if (!files.length) return false;
const shown = (l) => l && { lines: l.slice(0, 120), cut: l.length > 120 };
const previews = Object.fromEntries(Object.entries(parsePreview((await sh(PREVIEW, [repo, ...files], on)).stdout)).map(([f, v]) => {
const d = diffSides(v.local, v.remote);
return [f, { differ: d.differ, local: shown(d.local), remote: shown(d.remote) }];
}));
return { on, repo, files, previews, push };
}
// Merges every conflicted .metadata.json in the merge in progress. Returns an error, or null.
async function mergeMetadataFiles(repo, on, sh) {
const files = lines(await sh('cd "$1" && git -c core.quotePath=false diff --name-only --diff-filter=U', [repo], on)).filter(isMetadata);
for (const f of files) {
let merged;
try { merged = mergeMetadata(...parseStages((await sh(METADATA_STAGES, [repo, f], on)).stdout)); } catch (e) { return `Could not merge ${f}: ${e.message ?? e}`; }
const w = await sh(METADATA_WRITE, [repo, f, merged], on);
if (w.code !== 0) return `Could not write ${f}: ${lastLine(w.stderr)}`;
}
return null;
}
@@ -0,0 +1,3 @@
// The skillshare release this panel shipped with. Release Please rewrites it in every release
// (.github/release-please-config.json), so the panel can tell when a newer release has one.
export const VERSION = "0.30.5"; // x-release-please-version
Binary file not shown.

After

Width:  |  Height:  |  Size: 419 KiB

+46 -3
View File
@@ -26,18 +26,43 @@ New to skillshare? Start with the [main README](../../README.md) or the
## Install
Choose **Mod** to add the panel to your current window (recommended), or **Layout** for a
separate complete window. Both use the same panel and updater.
### Mod: keep your current window
The standalone package is [`herdr/skillshare-mod`](../skillshare-mod/RECIPE.md). Paste this
prompt into an agent in Herdr:
```text
Read ~/.config/herdr-app/AGENTS.md, then add this mod from https://github.com/runkids/skillshare/tree/main/herdr/skillshare-mod. Follow its RECIPE.md: add only the skillshare toggle and panel to my current layout, preserving my status bar, usage meters and all other customizations. Reuse existing skillshare nodes instead of duplicating them.
```
It contains no layout file. The agent clones a Herdr-shipped layout before editing it, or
adds just the two nodes to your existing custom layout. It does not switch to the complete
skillshare layout. The recipe explains network access, commands and files to review first.
### Layout: a separate complete window
From [Herdr layouts](https://herdr.dev/layouts/runkids/skillshare--herdr--skillshare/), paste this prompt into an agent in Herdr:
```text
Read ~/.config/herdr-app/AGENTS.md, then add this layout: herdr.dev/layouts/runkids/skillshare--herdr--skillshare
```
By hand:
### By hand
For either option, review every mod file before copying it. Preserve an unrelated installed
mod of the same name by following Herdr's rename procedure; for this panel already installed,
use the update instructions below instead.
1. Copy `mods/skillshare/` to `~/.config/herdr-app/mods/skillshare/`.
2. Copy `layouts/herdr-skillshare.json` and `layouts/herdr-skillshare.png` to
`~/.config/herdr-app/layouts/` and switch to it (`layout.switch {name: "herdr-skillshare"}`).
`RECIPE.md` describes it in full and `preview.png` shows it. Or, in your own layout, add:
`RECIPE.md` describes it in full and `preview.png` shows it. Keep any existing layout of
that name: add the new layout under another name instead of replacing it.
For the **Mod** option, skip copying layouts. Clone a Herdr-shipped layout first, or edit
your existing custom layout, preserving all unrelated nodes and properties. Add or reuse:
- a toggle block to the tab bar row:
`{ "id": "skillshare-toggle", "type": "block", "content": { "mod": "skillshare", "props": { "role": "toggle" } }, "size": { "px": 118 } }`
- a column beside the work area:
@@ -54,13 +79,20 @@ When a newer skillshare release is published, the panel's header shows **Update
first, then replaces the files in `~/.config/herdr-app/mods/skillshare/` with the ones that release
ships, and Herdr reloads the panel. The files it replaced are kept in that folder's
`.bak-update-<version>`; changes you made to them are not carried over. The layout is not touched.
This is the same update path for both the Mod and Layout options.
For an agent-assisted update, use this prompt instead of the installation prompt:
```text
Read ~/.config/herdr-app/AGENTS.md, then update only the installed skillshare mod from herdr/skillshare/mods/skillshare of the latest published release of https://github.com/runkids/skillshare. Back up the mod first. Preserve every layout, including custom status bars and CLI usage meters, plus settings, keys and unrelated mods. Keep the current layout selected. If skillshare needs a layout change, merge only its own nodes; do not replace the layout.
```
A panel installed before this button existed has no update check. Update it once by hand: copy
`mods/skillshare/` from the latest release over `~/.config/herdr-app/mods/skillshare/`, or paste this prompt into an
agent in Herdr:
```text
Read ~/.config/herdr-app/AGENTS.md, then replace the files in mods/skillshare with the ones in herdr/skillshare/mods/skillshare of the latest release of https://github.com/runkids/skillshare (the tag that /releases/latest lands on), overwriting the mod that is there.
Read ~/.config/herdr-app/AGENTS.md, then update only the installed skillshare mod using the Update section of https://github.com/runkids/skillshare/blob/main/herdr/skillshare/README.md. Preserve my current layout and all customizations.
```
## How it reads
@@ -113,6 +145,17 @@ fails, named entries stay listed as “sync status unknown”; they do not count
sync. Hook conflicts block `sync --all` for every resource kind; resolve them with the CLI or
dashboard, then Sync again.
## Maintaining the gallery packages
`herdr/skillshare/` remains the Layout package and canonical mod source. `herdr/skillshare-mod/`
is the standalone Mod package, with no `layouts/`. After changing the canonical mod or
`panels.png`, run `python3 scripts/herdr/package-mod.py` inside the devcontainer to refresh the
standalone files; `make test-herdr` checks that both packages match. Release Please updates
both copies of `version.js`.
Gallery discovery uses the public repository topics `herdr-layout` and `herdr-mod`, respectively.
Keep both topics to offer both packages. Adding a topic or publishing is a separate maintainer action.
## Tests
`make test-herdr` (`node --test herdr/tests/*.test.mjs`) covers `model.js`, `jobs.js`,
+15 -1
View File
@@ -6,6 +6,20 @@ skillshare beside your agents. Herdr's default window gains a skillshare button
skillshare keeps one source of skills, agents, MCP servers, plugins and hooks and syncs it to Claude Code, Codex, Gemini CLI and the other AI coding tools you use. New to it? Start with the [main README](../../README.md); this folder's [README](README.md) covers installing the panel.
## Installation and updates
This folder is the optional **complete Layout**, not an update payload. To add the panel to
an existing window, use the standalone [Mod package](../skillshare-mod/RECIPE.md) instead.
Keep the user's original layout intact; install this layout separately, under a new name if
`herdr-skillshare` already exists. If this panel is already installed, update its mod rather
than adding another copy.
For an update requested by an agent, back up and replace only `mods/skillshare/`. Preserve
all layouts, custom status bars and CLI usage meters, settings, keys, unrelated mods and the
selected layout. If a new panel version needs a layout change, merge only its skillshare
nodes into the existing tree. Reuse existing skillshare nodes; a panel update does not
replace or switch layouts.
## What you see
Left to right, everything as in Herdr's `main` layout, plus two blocks:
@@ -114,7 +128,7 @@ Left to right, everything as in Herdr's `main` layout, plus two blocks:
- The dialog's role is `panelupdate`: `panel` is the role a block without one gets, so a dialog with it would draw a second panel.
- `enable` and `disable` exit 0 once the entry's own line in `.skillignore` or `.agentignore` is written or was not there. A glob, a folder pattern or a negation in the `.local` file can still decide the other way, so the panel reads `list --all --json` afterwards and reports an entry that did not change.
- The dialog role for enabling or disabling a skill or agent is `able`, not `toggle`: `toggle` is the tab-bar button's role.
- A layout clone is never updated: rebuild from this recipe on a new Herdr version.
- Herdr does not update layout clones. On a new Herdr version, preserve the user's clone and merge only necessary compatibility changes; rebuilding this entire example is an explicit choice, not part of a panel update.
## Done when
+14 -1
View File
@@ -653,12 +653,13 @@ test("the panel's version is the release Release Please last wrote", () => {
// Runs PANEL_UPDATE from 0.0.1 to a local release v9.9.9 holding `shipped`, over a Herdr home
// whose mods/skillshare holds `installed`. Returns the result, the folder, and a reader.
function panelUpdate999(t, shipped, installed) {
function panelUpdate999(t, shipped, installed, homeFiles = {}) {
const root = mkdtempSync(join(tmpdir(), "ss-panel-"));
t.after(() => rmSync(root, { recursive: true, force: true }));
const repo = join(root, "repo"), dest = join(root, "home/mods/skillshare");
const put = (dir, files) => { for (const [f, text] of Object.entries(files)) { mkdirSync(join(dir, f, ".."), { recursive: true }); writeFileSync(join(dir, f), text); } };
put(repo, { "README.md": "repo", ...shipped }); put(dest, installed);
put(join(root, "home"), homeFiles);
const git = (...a) => spawnSync("git", ["-C", repo, "-c", "user.name=t", "-c", "user.email=t@example.com", ...a]);
git("init", "-q"); git("add", "."); git("commit", "-qm", "release"); git("tag", "v9.9.9");
const r = spawnSync("sh", ["-c", PANEL_UPDATE, "test", "", "v9.9.9", "0.0.1", repo], { env: { ...process.env, HERDR_APP_HOME: join(root, "home"), TMPDIR: root }, encoding: "utf8" });
@@ -674,6 +675,18 @@ test("PANEL_UPDATE installs the release's panel and keeps the files it replaced"
[0, "new", 'VERSION = "9.9.9"', "icon", "old", ["home", "repo"]]);
});
test("PANEL_UPDATE preserves custom layouts and unrelated mods for either installation", (t) => {
const custom = {
"layouts/herdr-skillshare.json": '{"id":"status","content":{"mod":"status-usage"}}',
"layouts/my-layout.json": '{"id":"my-layout","children":[]}',
"mods/status-usage/main.js": "custom usage meters",
};
const shipped = { ...SHIPPED, "herdr/skillshare/layouts/herdr-skillshare.json": "default layout" };
const { r, root } = panelUpdate999(t, shipped, INSTALLED, custom);
assert.equal(r.status, 0, r.stderr);
for (const [name, content] of Object.entries(custom)) assert.equal(readFileSync(join(root, "home", name), "utf8"), content);
});
test("PANEL_UPDATE keeps the copy an earlier attempt made", (t) => {
const { r, read } = panelUpdate999(t, SHIPPED, { ...INSTALLED, "main.js": "half", ".bak-update-0.0.1/main.js": "old" });
assert.deepEqual([r.status, read(".bak-update-0.0.1/main.js")], [0, "old"]);
+45
View File
@@ -0,0 +1,45 @@
import { test } from "node:test";
import { execFileSync } from "node:child_process";
import assert from "node:assert/strict";
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
const root = fileURLToPath(new URL("../", import.meta.url));
const source = join(root, "skillshare"), standalone = join(root, "skillshare-mod");
// Herdr checks create ignored editor files; compare only files Git would publish.
const files = (path) => execFileSync("git", ["ls-files", "--cached", "--others", "--exclude-standard", "-z", "--", `${path}/`], { cwd: join(root, ".."), encoding: "utf8" })
.split("\0").filter((name) => name && existsSync(join(root, "..", name))).map((name) => name.slice(`${path}/`.length)).sort();
test("the package generator handles an unstaged canonical asset deletion", (t) => {
const dir = mkdtempSync(join(tmpdir(), "ss-herdr-package-"));
t.after(() => rmSync(dir, { recursive: true, force: true }));
const put = (name, content) => { mkdirSync(join(dir, name, ".."), { recursive: true }); writeFileSync(join(dir, name), content); };
put("herdr/skillshare/mods/skillshare/main.js", "panel");
put("herdr/skillshare/mods/skillshare/old.svg", "old asset");
put("herdr/skillshare/panels.png", "preview");
put("scripts/herdr/package-mod.py", "");
copyFileSync(join(root, "../scripts/herdr/package-mod.py"), join(dir, "scripts/herdr/package-mod.py"));
const run = (...args) => execFileSync("python3", ["scripts/herdr/package-mod.py", ...args], { cwd: dir });
execFileSync("git", ["init", "-q"], { cwd: dir });
run();
execFileSync("git", ["add", "."], { cwd: dir });
unlinkSync(join(dir, "herdr/skillshare/mods/skillshare/old.svg"));
run();
assert.ok(!existsSync(join(dir, "herdr/skillshare-mod/mods/skillshare/old.svg")));
run("--check");
});
test("the standalone mod is a complete gallery package without a layout", () => {
assert.ok(existsSync(join(standalone, "RECIPE.md")), "standalone mod recipe is missing");
assert.ok(!existsSync(join(standalone, "layouts")), "a mod share folder must not include layouts");
assert.deepEqual(readFileSync(join(standalone, "preview.png")), readFileSync(join(source, "panels.png")));
const path = "mods/skillshare", expected = files(`herdr/skillshare/${path}`), actual = files(`herdr/skillshare-mod/${path}`);
assert.ok(!actual.includes("gpui-kit.d.ts"), "local editor files must not ship");
assert.ok(!actual.includes("jsconfig.json"), "local editor files must not ship");
assert.deepEqual(actual, expected);
for (const name of expected) {
assert.deepEqual(readFileSync(join(standalone, path, name)), readFileSync(join(source, path, name)), `${name}: regenerate with python3 scripts/herdr/package-mod.py`);
}
});
+47
View File
@@ -0,0 +1,47 @@
"""Build the standalone Herdr mod package from the layout's canonical mod."""
import argparse
import shutil
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
SOURCE = ROOT / "herdr" / "skillshare"
DEST = ROOT / "herdr" / "skillshare-mod"
def git_files(path):
# Git excludes local editor files while including new, not-yet-staged assets.
names = subprocess.check_output(
["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z", "--",
str(path.relative_to(ROOT)) + "/"], cwd=ROOT, text=True).split("\0")
return [ROOT / name for name in names if name and (ROOT / name).is_file()]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true", help="check without writing files")
args = parser.parse_args()
expected = {Path("preview.png"): SOURCE / "panels.png"}
expected.update({path.relative_to(SOURCE): path for path in git_files(SOURCE / "mods")})
actual = {path.relative_to(DEST) for path in git_files(DEST / "mods")}
stale = actual - expected.keys()
changed = [name for name, source in expected.items()
if not (DEST / name).is_file() or (DEST / name).read_bytes() != source.read_bytes()]
if args.check:
if changed or stale:
parser.exit(1, "Herdr mod package is stale; run python3 scripts/herdr/package-mod.py\n")
print("Herdr mod package is up to date")
return
for name in stale:
(DEST / name).unlink()
for name in changed:
target = DEST / name
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(expected[name], target)
print(f"Updated {len(changed)} Herdr mod package files")
if __name__ == "__main__":
main()
+12
View File
@@ -15,6 +15,16 @@ sidebar_position: 8
## Setup
### Mod: keep your current layout (recommended)
Use the standalone [Mod package](https://github.com/runkids/skillshare/tree/main/herdr/skillshare-mod) to add the panel without replacing your window. Paste this prompt into an agent in Herdr:
```text
Read ~/.config/herdr-app/AGENTS.md, then add this mod from https://github.com/runkids/skillshare/tree/main/herdr/skillshare-mod. Follow its RECIPE.md: add only the skillshare toggle and panel to my current layout, preserving my status bar, usage meters and all other customizations. Reuse existing skillshare nodes instead of duplicating them.
```
The package has no `layouts/` folder. Its recipe adds or reuses only the skillshare toggle and panel, preserving your status bar, CLI usage meters, theme and other customizations. A Herdr-shipped layout is cloned before editing.
### From Herdr layouts
The layout is listed at [Herdr layouts](https://herdr.dev/layouts/runkids/skillshare--herdr--skillshare/). Paste this prompt into an agent in Herdr:
@@ -37,6 +47,8 @@ A **skillshare** button appears in the tab bar. It shows and hides the panel, an
## Updating the Panel
For either installation option, an agent-assisted update should back up and replace only the installed skillshare mod. Keep the current layout selected; preserve every layout, custom status bar, usage meter, setting, key binding and unrelated mod. If a layout adjustment is necessary, merge only skillshare's own nodes instead of reapplying the complete layout.
While it is shown, the panel asks GitHub once an hour for the latest skillshare release. When a newer one is published, its header shows **Update panel**. It asks first, replaces the files in `~/.config/herdr-app/mods/skillshare/` with the ones that release ships, and Herdr reloads the panel. The files it replaced are kept in that folder's `.bak-update-<version>`; changes you made to them are not carried over. Your layout is not touched.
A panel installed before this button existed has no update check. Copy `mods/skillshare/` from the latest release over `~/.config/herdr-app/mods/skillshare/` once by hand; later updates come from the button.
@@ -15,6 +15,16 @@ sidebar_position: 8
## セットアップ
### Mod:今のレイアウトを保つ(推奨)
独立した [Mod パッケージ](https://github.com/runkids/skillshare/tree/main/herdr/skillshare-mod) を使えば、ウィンドウ全体を置き換えずにパネルを追加できます。Herdr 内のエージェントに次のプロンプトを貼り付けます。
```text
Read ~/.config/herdr-app/AGENTS.md, then add this mod from https://github.com/runkids/skillshare/tree/main/herdr/skillshare-mod. Follow its RECIPE.md: add only the skillshare toggle and panel to my current layout, preserving my status bar, usage meters and all other customizations. Reuse existing skillshare nodes instead of duplicating them.
```
このパッケージに `layouts/` フォルダーはありません。レシピは skillshare のボタンとパネルだけを追加または再利用し、ステータスバー、CLI の使用量表示、テーマなどのカスタマイズを保ちます。Herdr 標準のレイアウトは複製してから編集します。
### Herdr layouts から
このレイアウトは [Herdr layouts](https://herdr.dev/layouts/runkids/skillshare--herdr--skillshare/) に掲載されています。Herdr 内のエージェントに次のプロンプトを貼り付けます。
@@ -37,6 +47,8 @@ Read ~/.config/herdr-app/AGENTS.md, then add this layout: herdr.dev/layouts/runk
## パネルの更新
どちらの方法でインストールした場合も、エージェントによる更新ではインストール済みの skillshare mod だけをバックアップして置き換えます。選択中のレイアウト、すべてのレイアウト、独自のステータスバー、使用量表示、設定、キー割り当て、他の mod を保ってください。レイアウトの調整が必要な場合も、完全なレイアウトを再適用せず、skillshare 自身のノードだけをマージします。
パネルは表示中、1 時間に 1 回 GitHub に最新の skillshare リリースを問い合わせます。新しいリリースが公開されると、パネルのヘッダーに **Update panel** が表示されます。確認のあと、`~/.config/herdr-app/mods/skillshare/` のファイルをそのリリースに含まれるものに置き換え、Herdr がパネルを再読み込みします。置き換えられたファイルはそのフォルダーの `.bak-update-<version>` に残ります。それらのファイルに加えた変更は引き継がれません。レイアウトは変更されません。
このボタンが追加される前にインストールしたパネルは更新を確認しません。一度だけ手動で最新リリースの `mods/skillshare/` を `~/.config/herdr-app/mods/skillshare/` に上書きコピーしてください。以降の更新はボタンから行えます。
@@ -15,6 +15,16 @@ sidebar_position: 8
## 설정
### Mod: 현재 레이아웃 유지 (권장)
독립 [Mod 패키지](https://github.com/runkids/skillshare/tree/main/herdr/skillshare-mod)를 사용하면 전체 창을 교체하지 않고 패널을 추가할 수 있습니다. Herdr 안의 에이전트에 다음 프롬프트를 붙여 넣습니다.
```text
Read ~/.config/herdr-app/AGENTS.md, then add this mod from https://github.com/runkids/skillshare/tree/main/herdr/skillshare-mod. Follow its RECIPE.md: add only the skillshare toggle and panel to my current layout, preserving my status bar, usage meters and all other customizations. Reuse existing skillshare nodes instead of duplicating them.
```
이 패키지에는 `layouts/` 폴더가 없습니다. 레시피는 skillshare 버튼과 패널만 추가하거나 재사용하며, 상태 표시줄, CLI 사용량 표시, 테마와 다른 사용자 설정을 보존합니다. Herdr 기본 레이아웃은 복제한 뒤 수정합니다.
### Herdr layouts에서
이 레이아웃은 [Herdr layouts](https://herdr.dev/layouts/runkids/skillshare--herdr--skillshare/)에 등록되어 있습니다. Herdr 안의 에이전트에 다음 프롬프트를 붙여 넣습니다.
@@ -37,6 +47,8 @@ Read ~/.config/herdr-app/AGENTS.md, then add this layout: herdr.dev/layouts/runk
## 패널 업데이트
어느 방법으로 설치했든 에이전트로 업데이트할 때는 설치된 skillshare mod만 백업하고 교체합니다. 현재 선택된 레이아웃, 모든 레이아웃, 사용자 상태 표시줄, 사용량 표시, 설정, 키 바인딩과 다른 mod를 보존하세요. 레이아웃 조정이 필요해도 전체 레이아웃을 다시 적용하지 말고 skillshare 자체 노드만 병합합니다.
패널은 표시되는 동안 한 시간에 한 번 GitHub에 최신 skillshare 릴리스를 확인합니다. 새 릴리스가 게시되면 패널 헤더에 **Update panel**이 나타납니다. 먼저 확인을 받은 뒤 `~/.config/herdr-app/mods/skillshare/`의 파일을 해당 릴리스에 포함된 파일로 교체하고, Herdr가 패널을 다시 불러옵니다. 교체된 파일은 그 폴더의 `.bak-update-<version>`에 보관됩니다. 그 파일에 직접 한 변경은 유지되지 않습니다. 레이아웃은 바뀌지 않습니다.
이 버튼이 생기기 전에 설치한 패널은 업데이트를 확인하지 않습니다. 최신 릴리스의 `mods/skillshare/`를 `~/.config/herdr-app/mods/skillshare/`에 한 번 직접 덮어써 주세요. 이후 업데이트는 버튼으로 할 수 있습니다.
@@ -15,6 +15,16 @@ sidebar_position: 8
## 设置
### Mod:保留当前 layout(推荐)
使用独立的 [Mod 分享包](https://github.com/runkids/skillshare/tree/main/herdr/skillshare-mod),添加面板而不替换整个窗口。把下面这段 prompt 贴给 Herdr 里的 agent:
```text
Read ~/.config/herdr-app/AGENTS.md, then add this mod from https://github.com/runkids/skillshare/tree/main/herdr/skillshare-mod. Follow its RECIPE.md: add only the skillshare toggle and panel to my current layout, preserving my status bar, usage meters and all other customizations. Reuse existing skillshare nodes instead of duplicating them.
```
这个分享包没有 `layouts/` 文件夹。Recipe 只添加或复用 skillshare 开关和面板,保留你的状态栏、CLI 额度、主题及其他自定义设置。Herdr 内置的 layout 会先复制再修改。
### 从 Herdr layouts 安装
这个 layout 已上架到 [Herdr layouts](https://herdr.dev/layouts/runkids/skillshare--herdr--skillshare/)。把下面这段 prompt 贴给 Herdr 里的 agent:
@@ -37,6 +47,8 @@ tab bar 会出现 **skillshare** 按钮,用来显示或隐藏面板。切换 s
## 更新面板
无论使用哪种安装方式,请 agent 更新时,都只备份并替换已安装的 skillshare mod。保持当前选中的 layout,保留所有 layout、自定义状态栏、额度显示、设置、快捷键及其他 mod。如需调整 layout,只合并 skillshare 自己的节点,不重新应用完整 layout。
面板显示时,每小时向 GitHub 查询一次最新的 skillshare release。有新的 release 发布时,面板标题栏会出现 **Update panel**。它会先询问,再用该 release 附带的文件替换 `~/.config/herdr-app/mods/skillshare/` 里的文件,随后 Herdr 会重新加载面板。被替换的文件保留在该文件夹的 `.bak-update-<version>`;你对这些文件做的修改不会保留。你的 layout 不会被改动。
在这个按钮出现之前安装的面板不会检查更新。请手动把最新 release 的 `mods/skillshare/` 复制到 `~/.config/herdr-app/mods/skillshare/` 一次;之后的更新就能用按钮完成。
@@ -15,6 +15,16 @@ sidebar_position: 8
## 設定
### Mod:保留目前的 layout(建議)
使用獨立的 [Mod 分享包](https://github.com/runkids/skillshare/tree/main/herdr/skillshare-mod),加入面板而不取代整個視窗。把下面這段 prompt 貼給 Herdr 裡的 agent:
```text
Read ~/.config/herdr-app/AGENTS.md, then add this mod from https://github.com/runkids/skillshare/tree/main/herdr/skillshare-mod. Follow its RECIPE.md: add only the skillshare toggle and panel to my current layout, preserving my status bar, usage meters and all other customizations. Reuse existing skillshare nodes instead of duplicating them.
```
這個分享包沒有 `layouts/` 資料夾。Recipe 只加入或沿用 skillshare 開關和面板,保留你的狀態列、CLI 額度、主題及其他自訂設定。Herdr 內建的 layout 會先複製再修改。
### 從 Herdr layouts 安裝
這個 layout 已上架到 [Herdr layouts](https://herdr.dev/layouts/runkids/skillshare--herdr--skillshare/)。把下面這段 prompt 貼給 Herdr 裡的 agent:
@@ -37,6 +47,8 @@ tab bar 會出現 **skillshare** 按鈕,用來顯示或隱藏面板。切換 s
## 更新面板
無論使用哪種安裝方式,請 agent 更新時,都只備份並替換已安裝的 skillshare mod。維持目前選用的 layout,保留所有 layout、自訂狀態列、額度顯示、設定、快捷鍵及其他 mod。若必須調整 layout,只合併 skillshare 自己的節點,不重新套用完整 layout。
面板顯示時,每小時向 GitHub 查詢一次最新的 skillshare release。有新的 release 發布時,面板標題列會出現 **Update panel**。它會先詢問,再用該 release 附帶的檔案取代 `~/.config/herdr-app/mods/skillshare/` 裡的檔案,接著 Herdr 會重新載入面板。被取代的檔案保留在該資料夾的 `.bak-update-<version>`;你對這些檔案做的修改不會保留。你的 layout 不會被更動。
在這個按鈕出現之前安裝的面板不會檢查更新。請手動把最新 release 的 `mods/skillshare/` 複製到 `~/.config/herdr-app/mods/skillshare/` 一次;之後的更新就能用按鈕完成。
+2 -1
View File
@@ -15,7 +15,8 @@ python3 scripts/ai-context.py <topic>
| `cli-development` | Adding or changing Go CLI commands, flags, handlers, TUIs, or mutating behavior | `cli-development.md` |
| `testing` | Building, testing, reproducing bugs, or using the devcontainer/ssenv | `testing.md`, `CONTRIBUTING.md` |
| `e2e-runbooks` | Writing or running `ai_docs/tests` E2E runbooks, or verifying on a Windows guest | `e2e-runbooks.md` |
| `frontend` | Changing React, CSS, layout, or visual behavior in the dashboard, website, or Herdr panel | `frontend.md`, `website/AGENTS.md`, `herdr/AGENTS.md` |
| `frontend` | Changing React, CSS, layout, or visual behavior in the dashboard or website | `frontend.md`, `website/AGENTS.md` |
| `herdr` | Changing the native Herdr panel, gallery packages, or layout integration | `herdr.md`, `herdr/AGENTS.md` |
| `documentation` | Updating README files, website docs, flags, translations, or the built-in skill | `documentation.md`, `CONTRIBUTING.md` |
| `release` | Writing changelogs or release notes, bumping versions, tagging, or releasing | `release.md` |
| `audit` | Running read-only consistency audits | `audit.md` |
+9 -1
View File
@@ -42,13 +42,21 @@
]
},
"frontend": {
"description": "Change React, CSS, layout, or visual behavior in the dashboard, website, or Herdr panel.",
"description": "Change React, CSS, layout, or visual behavior in the dashboard or website.",
"sources": [
{
"path": "wiki/frontend.md"
},
{
"path": "website/AGENTS.md"
}
]
},
"herdr": {
"description": "Change the native Herdr panel, its gallery packages, or layout integration.",
"sources": [
{
"path": "wiki/herdr.md"
},
{
"path": "herdr/AGENTS.md"
+7
View File
@@ -0,0 +1,7 @@
# Herdr Integration
Use when changing the native QuickJS panel, its Mod or Layout gallery package, or integration with a user's existing window. This is not a React frontend; the topic also loads `herdr/AGENTS.md` for its implementation rules.
Load `testing` before running package generation or Node tests in the devcontainer. Load `documentation` when changing public installation instructions, including the translated `learn/with-herdr.md` pages.
The complete Layout and standalone Mod share the canonical implementation in `herdr/skillshare/mods/skillshare/`. `herdr/skillshare/README.md` describes both installation paths, mod-only updates, gallery discovery and how to regenerate the standalone package. Each share folder has its own agent-facing recipe; keep installation and update boundaries consistent in both.
+1 -1
View File
@@ -26,7 +26,7 @@ For `0.x`, fixes and performance changes increment patch; new features and break
For an explicit version such as `0.23.3`, put `Release-As: 0.23.3` after a blank line in a normal development commit that will reach `main` before merging the Release PR. A single footer on the final commit of a batch is sufficient for the entire pending release; intermediate versions may be skipped. Preserve the footer when merging or rebasing. For squash-merge, copy it into the final squash commit message on GitHub. If pending commits contain conflicting version requests, the newest override wins. Verify the resulting Release PR's proposed version before merging; the footer itself neither tags nor publishes a release. See the [Release Please version override documentation](https://github.com/googleapis/release-please#how-do-i-change-the-version-number).
1. A push to `main` runs **Release Please**. With no merged release pending, it creates or updates a Release PR and synchronizes its manifest version, built-in skill version and newest changelog entry in both files. Release Please also writes the version into the Herdr panel's `herdr/skillshare/mods/skillshare/version.js` (`extra-files`); the panel offers its own update from the latest published release, and `make test-herdr` checks the file against the manifest.
1. A push to `main` runs **Release Please**. With no merged release pending, it creates or updates a Release PR and synchronizes its manifest version, built-in skill version and newest changelog entry in both files. Release Please also writes the version into both Herdr panel packages' `mods/skillshare/version.js` (`herdr/skillshare/` and `herdr/skillshare-mod/`, via `extra-files`); the panel offers its own update from the latest published release, and `make test-herdr` checks the file against the manifest.
2. Review the proposed version and user-facing notes on the Release PR branch. `python3 scripts/release/release.py sync` normalizes the heading and syncs the files; `check` verifies their agreement. Run these helpers inside the devcontainer. Bot PR creation and updates using `GITHUB_TOKEN` may leave PR CI awaiting the maintainer's native **Approve workflows to run** prompt.
3. Merging the Release PR selects its exact merge SHA for the reusable Test workflow. Formatting, lint, Go unit/integration tests, release helper tests, Docker sandbox tests and applicable red-team jobs must pass before tagging. If another merged pending release appears during testing, the tag job stops. The ordinary push run of Test skips that merge commit, because this gate already tests it; the Release PR's own runs still execute as required checks.
4. Release Please creates the stable tag and an unpublished draft with `force-tag-creation`. The workflow explicitly calls **Build Release Draft**; it does not depend on a `GITHUB_TOKEN` tag push triggering another workflow.