@mmerterden/multi-agent-pipeline 20.43.0 → 20.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +19 -3
  3. package/README.tr.md +19 -4
  4. package/docs/ecosystem.md +7 -7
  5. package/docs/facts.json +8 -8
  6. package/docs/features.md +1 -1
  7. package/manifest.json +58 -48
  8. package/package.json +1 -1
  9. package/pipeline/commands/multi-agent/review-priority/SKILL.md +10 -5
  10. package/pipeline/commands/multi-agent/setup/SKILL.md +1 -1
  11. package/pipeline/commands/multi-agent/update/SKILL.md +18 -7
  12. package/pipeline/contract/CHANGELOG.md +43 -3
  13. package/pipeline/contract/README.md +65 -63
  14. package/pipeline/contract/fixtures/error-invalid-request.json +1 -1
  15. package/pipeline/contract/fixtures/error-unauthorized.json +1 -1
  16. package/pipeline/contract/fixtures/error-unsigned.json +1 -1
  17. package/pipeline/contract/manifest.json +41 -4
  18. package/pipeline/contract/types/index.d.ts +112 -3
  19. package/pipeline/multi-agent-refs/features/office-remote-protocol.md +4 -2
  20. package/pipeline/multi-agent-refs/features/office-threat-model.md +3 -1
  21. package/pipeline/multi-agent-refs/features/usage-reporting.md +48 -7
  22. package/pipeline/multi-agent-refs/help/en.md +1 -1
  23. package/pipeline/multi-agent-refs/help/tr.md +1 -1
  24. package/pipeline/office/index.html +434 -28
  25. package/pipeline/office/toolkit.json +1 -1
  26. package/pipeline/rules/outside-the-pipeline.md +1 -1
  27. package/pipeline/schemas/contract-error.schema.json +2 -1
  28. package/pipeline/schemas/disk-clean-request.schema.json +66 -0
  29. package/pipeline/schemas/disk-clean.schema.json +243 -0
  30. package/pipeline/schemas/office-jobs.json +25 -0
  31. package/pipeline/schemas/office-jobs.schema.json +19 -0
  32. package/pipeline/schemas/skill-catalog.schema.json +91 -0
  33. package/pipeline/schemas/toolkit-path-params.json +23 -1
  34. package/pipeline/scripts/_contract-core.mjs +1 -1
  35. package/pipeline/scripts/_contract-routes-catalog.mjs +31 -3
  36. package/pipeline/scripts/_contract-routes-ops.mjs +11 -1
  37. package/pipeline/scripts/_stack-routing.mjs +2 -0
  38. package/pipeline/scripts/contract-server.mjs +4 -0
  39. package/pipeline/scripts/job-launch.mjs +50 -9
  40. package/pipeline/scripts/office-disk.mjs +262 -0
  41. package/pipeline/scripts/skill-catalog.mjs +302 -0
  42. package/pipeline/scripts/stack-toggle.mjs +104 -41
  43. package/pipeline/scripts/usage-register.mjs +86 -9
  44. package/pipeline/skills/.skill-manifest.json +13 -5
  45. package/pipeline/skills/.skills-index.json +23 -1
  46. package/pipeline/skills/shared/README.md +5 -3
  47. package/pipeline/skills/shared/core/multi-agent-review-priority/SKILL.md +3 -2
  48. package/pipeline/skills/shared/core/multi-agent-setup/SKILL.md +1 -1
  49. package/pipeline/skills/shared/core/multi-agent-update/SKILL.md +11 -5
  50. package/pipeline/skills/shared/external/release-video/SKILL.md +147 -0
  51. package/pipeline/skills/shared/external/release-video/evals/evals.json +45 -0
  52. package/pipeline/skills/shared/external/short-video-craft/SKILL.md +177 -0
  53. package/pipeline/skills/shared/external/short-video-craft/evals/evals.json +43 -0
  54. package/pipeline/skills/shared/external/short-video-craft/references/generated-defaults.md +24 -0
  55. package/pipeline/skills/skills-index.md +3 -1
@@ -0,0 +1,302 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @file skill-catalog.mjs - one index of everything a person can invoke:
4
+ * the /multi-agent commands, the marketplace plugin skills and the routines
5
+ * saved with /multi-agent:save. The office's skill catalog window renders it
6
+ * (GET /v1/skills); shape: pipeline/schemas/skill-catalog.schema.json.
7
+ *
8
+ * Every file read sits under a fixed root:
9
+ *
10
+ * commands the command tree commands.mjs reads (the source tree
11
+ * beside this script, else the installed copy), plus the
12
+ * `local-only: true` directories of
13
+ * ~/.claude/commands/multi-agent that are not routines;
14
+ * plugin skills ~/.claude/plugins/marketplaces/multi-agent-plugins, the
15
+ * same clone and skill walk stack-toggle.mjs uses, so a
16
+ * symlink out of the clone is never followed;
17
+ * routines prefs `global.routines` through routine-registry.mjs, with
18
+ * the Turkish description from the routine's own SKILL.md.
19
+ *
20
+ * A repository only decides `enabled` for plugin skills: its
21
+ * `.claude/settings.json` enabledPlugins, read by stack-toggle.mjs, plus the
22
+ * always-on plugins. Without one, a plugin skill is `enabled: true` when its
23
+ * plugin is always on and `null` (unknown) otherwise. Commands and routines
24
+ * are always `enabled: true`.
25
+ *
26
+ * A missing source is a note, never an error: no clone means no plugin skills
27
+ * and `{section: "plugin-skill", code: "no-clone"}`; an unreadable routine
28
+ * registry means `{section: "routine", code: "unreadable"}`; no command tree
29
+ * means `{section: "command", code: "no-tree"}`.
30
+ *
31
+ * Both description fields come from SKILL.md frontmatter (`description`,
32
+ * `description-tr`), read with the frontmatter readers the command contract
33
+ * and the skill router already use. Routine text is the user's own and is
34
+ * scrubbed like GET /v1/routines scrubs it.
35
+ *
36
+ * Usage:
37
+ * node skill-catalog.mjs --json [--repo <absolute path>]
38
+ *
39
+ * Exit: 0 printed, 2 usage error, 1 unreadable repository settings.
40
+ *
41
+ * @module pipeline/scripts/skill-catalog
42
+ */
43
+
44
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
45
+ import { homedir } from "node:os";
46
+ import { join } from "node:path";
47
+ import { commandsDir } from "./commands.mjs";
48
+ import { frontmatterFields, yamlScalar } from "./_command-contract.mjs";
49
+ import { frontmatter } from "./skill-candidates.mjs";
50
+ import { scrub } from "./_redact.mjs";
51
+ import { RoutineError, listRoutines } from "./routine-registry.mjs";
52
+ import {
53
+ StackError,
54
+ marketplaceClone,
55
+ marketplacePlugins,
56
+ pluginSkillFiles,
57
+ repoEnabledPlugins,
58
+ } from "./stack-toggle.mjs";
59
+ import { runMain } from "../lib/fatal.mjs";
60
+ import { invokedDirectly } from "../lib/invoked-directly.mjs";
61
+ import { ArgsError, parseArgs } from "../lib/args.mjs";
62
+ import { exitOnHelp } from "../lib/cli-help.mjs";
63
+
64
+ exitOnHelp(import.meta.url);
65
+
66
+ export const CONTRACT_VERSION = "1.0.0";
67
+ export const KINDS = ["command", "plugin-skill", "routine"];
68
+
69
+ const NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
70
+ const MAX_TEXT = 2000;
71
+ const ROOT_COMMAND = "multi-agent";
72
+
73
+ const home = (env) => env.HOME || homedir();
74
+ const cut = (s) => (s.length > MAX_TEXT ? s.slice(0, MAX_TEXT) : s);
75
+
76
+ /**
77
+ * `description`, `description-tr` and `local-only` of one SKILL.md. A quoted
78
+ * one-line value is unquoted by yamlScalar (escapes included); a `|` or `>`
79
+ * block scalar is folded by the skill router's reader.
80
+ */
81
+ function skillFront(file) {
82
+ let raw;
83
+ try {
84
+ raw = readFileSync(file, "utf8");
85
+ } catch {
86
+ return null;
87
+ }
88
+ const fields = frontmatterFields(raw.replace(/\r\n/g, "\n"));
89
+ if (!fields) return null;
90
+ let folded = null;
91
+ const text = (key) => {
92
+ const v = fields[key];
93
+ if (v === undefined) return null;
94
+ if (/^[|>][+-]?$/.test(v.trim())) {
95
+ folded ??= frontmatter(raw);
96
+ return folded[key] ? cut(folded[key]) : null;
97
+ }
98
+ const out = yamlScalar(v);
99
+ return out ? cut(out) : null;
100
+ };
101
+ return {
102
+ description: text("description"),
103
+ descriptionTr: text("description-tr"),
104
+ localOnly: yamlScalar(fields["local-only"]) === "true",
105
+ };
106
+ }
107
+
108
+ function item(kind, name, invoke, source, front, extra = {}) {
109
+ return {
110
+ id: kind === "plugin-skill" ? `${kind}:${source}:${name}` : `${kind}:${name}`,
111
+ name,
112
+ invoke,
113
+ kind,
114
+ source,
115
+ description: front?.description ?? "",
116
+ descriptionTr: front?.descriptionTr ?? null,
117
+ enabled: true,
118
+ alwaysOn: false,
119
+ localOnly: false,
120
+ ...extra,
121
+ };
122
+ }
123
+
124
+ const dirsIn = (root) => {
125
+ try {
126
+ return readdirSync(root, { withFileTypes: true })
127
+ .filter((e) => e.isDirectory() && NAME.test(e.name))
128
+ .map((e) => e.name)
129
+ .sort();
130
+ } catch {
131
+ return [];
132
+ }
133
+ };
134
+
135
+ function commandItems(commandsRoot, homeCommands, routineNames, notes) {
136
+ const out = [];
137
+ const seen = new Set();
138
+ if (commandsRoot && existsSync(commandsRoot)) {
139
+ const root = skillFront(join(commandsRoot, "SKILL.md"));
140
+ if (root) {
141
+ out.push(item("command", ROOT_COMMAND, "/multi-agent", "pipeline", root));
142
+ seen.add(ROOT_COMMAND);
143
+ }
144
+ for (const id of dirsIn(commandsRoot)) {
145
+ const front = skillFront(join(commandsRoot, id, "SKILL.md"));
146
+ if (!front || routineNames.has(id)) continue;
147
+ out.push(
148
+ item("command", id, `/multi-agent:${id}`, front.localOnly ? "local" : "pipeline", front, {
149
+ localOnly: front.localOnly,
150
+ }),
151
+ );
152
+ seen.add(id);
153
+ }
154
+ } else notes.push({ section: "command", code: "no-tree" });
155
+ for (const id of dirsIn(homeCommands)) {
156
+ if (seen.has(id) || routineNames.has(id)) continue;
157
+ const front = skillFront(join(homeCommands, id, "SKILL.md"));
158
+ if (!front?.localOnly) continue;
159
+ out.push(item("command", id, `/multi-agent:${id}`, "local", front, { localOnly: true }));
160
+ }
161
+ return out;
162
+ }
163
+
164
+ function pluginItems(enabled, repoGiven, env, notes) {
165
+ if (!existsSync(join(marketplaceClone(env), "plugins"))) {
166
+ notes.push({ section: "plugin-skill", code: "no-clone" });
167
+ return [];
168
+ }
169
+ const { verified, plugins } = marketplacePlugins(enabled ?? {}, env);
170
+ if (!verified) notes.push({ section: "plugin-skill", code: "no-manifest" });
171
+ const out = [];
172
+ for (const p of plugins) {
173
+ for (const s of pluginSkillFiles(p.name, env)) {
174
+ const on = p.alwaysOn || (repoGiven ? p.enabled : null);
175
+ out.push(
176
+ item("plugin-skill", s.name, `${p.name}:${s.name}`, p.name, skillFront(s.file), {
177
+ enabled: on === null ? null : on === true,
178
+ alwaysOn: p.alwaysOn,
179
+ }),
180
+ );
181
+ }
182
+ }
183
+ return out;
184
+ }
185
+
186
+ function routineItems(h, homeCommands, notes) {
187
+ let entries;
188
+ try {
189
+ entries = listRoutines(h);
190
+ } catch (err) {
191
+ if (!(err instanceof RoutineError)) throw err;
192
+ notes.push({ section: "routine", code: "unreadable" });
193
+ return [];
194
+ }
195
+ const out = [];
196
+ for (const r of entries) {
197
+ const name = typeof r?.name === "string" ? r.name : "";
198
+ if (!NAME.test(name) || out.some((x) => x.name === name)) continue;
199
+ const own = skillFront(join(homeCommands, name, "SKILL.md"));
200
+ const description = typeof r.description === "string" ? r.description : own?.description;
201
+ out.push(
202
+ item(
203
+ "routine",
204
+ name,
205
+ `/multi-agent:${name}`,
206
+ "local",
207
+ {
208
+ description: cut(scrub(description ?? "")),
209
+ descriptionTr: own?.descriptionTr ? scrub(own.descriptionTr) : null,
210
+ },
211
+ { localOnly: true },
212
+ ),
213
+ );
214
+ }
215
+ return out;
216
+ }
217
+
218
+ /**
219
+ * The catalog document.
220
+ *
221
+ * @param {object} [opts]
222
+ * @param {string|null} [opts.repoPath] absolute path of an accepted repository
223
+ * @param {string|null} [opts.repoLabel] what to echo as `repo` (the caller's reference)
224
+ * @param {string|null} [opts.commandsRoot] the command tree; undefined finds it, null means none
225
+ * @param {Record<string,string|undefined>} [opts.env]
226
+ */
227
+ export function skillCatalog({
228
+ repoPath = null,
229
+ repoLabel = null,
230
+ commandsRoot,
231
+ env = process.env,
232
+ } = {}) {
233
+ const h = home(env);
234
+ const homeCommands = join(h, ".claude", "commands", "multi-agent");
235
+ const root = commandsRoot === undefined ? commandsDir() : commandsRoot;
236
+ const enabled = repoPath ? repoEnabledPlugins(repoPath) : null;
237
+ const notes = [];
238
+ const routines = routineItems(h, homeCommands, notes);
239
+ const names = new Set(routines.map((r) => r.name));
240
+ const items = [
241
+ ...commandItems(root, homeCommands, names, notes),
242
+ ...pluginItems(enabled, repoPath !== null, env, notes),
243
+ ...routines,
244
+ ];
245
+ return {
246
+ contractVersion: CONTRACT_VERSION,
247
+ repo: repoPath ? (repoLabel ?? repoPath) : null,
248
+ items,
249
+ notes,
250
+ };
251
+ }
252
+
253
+ const USAGE = "usage: skill-catalog.mjs --json [--repo <absolute path>]\n";
254
+
255
+ function main(argv) {
256
+ let flags;
257
+ try {
258
+ ({ flags } = parseArgs(argv, {
259
+ booleans: ["json"],
260
+ values: ["repo"],
261
+ unknown: "error",
262
+ positionals: false,
263
+ equals: false,
264
+ terminator: false,
265
+ valuePrefix: null,
266
+ }));
267
+ } catch (err) {
268
+ if (!(err instanceof ArgsError)) throw err;
269
+ process.stderr.write(`skill-catalog: unknown argument ${err.token}\n${USAGE}`);
270
+ return 2;
271
+ }
272
+ if (flags.repo === true) {
273
+ process.stderr.write(`skill-catalog: --repo needs a value\n${USAGE}`);
274
+ return 2;
275
+ }
276
+ const json = flags.json === true;
277
+ const repo = Object.hasOwn(flags, "repo") ? flags.repo : null;
278
+ try {
279
+ const doc = skillCatalog({ repoPath: repo });
280
+ if (json) process.stdout.write(JSON.stringify(doc, null, 2) + "\n");
281
+ else {
282
+ for (const i of doc.items) {
283
+ const on = i.enabled === null ? "?" : i.enabled ? "on" : "off";
284
+ process.stdout.write(`${i.kind.padEnd(13)} ${on.padEnd(3)} ${i.invoke}\n`);
285
+ }
286
+ for (const n of doc.notes) process.stdout.write(`note: ${n.section} ${n.code}\n`);
287
+ }
288
+ return 0;
289
+ } catch (err) {
290
+ if (err instanceof StackError) {
291
+ process.stderr.write(`skill-catalog: ${err.message}\n`);
292
+ return 1;
293
+ }
294
+ throw err;
295
+ }
296
+ }
297
+
298
+ if (invokedDirectly(import.meta.url)) {
299
+ runMain("skill-catalog", () => {
300
+ process.exitCode = main(process.argv.slice(2));
301
+ });
302
+ }
@@ -36,12 +36,13 @@ import {
36
36
  mkdirSync,
37
37
  readFileSync,
38
38
  readdirSync,
39
+ realpathSync,
39
40
  renameSync,
40
41
  statSync,
41
42
  writeFileSync,
42
43
  } from "node:fs";
43
44
  import { homedir } from "node:os";
44
- import { isAbsolute, join } from "node:path";
45
+ import { isAbsolute, join, relative, sep } from "node:path";
45
46
  import {
46
47
  ALWAYS_ON,
47
48
  KNOWN_STACKS,
@@ -60,6 +61,7 @@ export const CONTRACT_VERSION = "1.0.0";
60
61
  const SUFFIX = `@${PLUGIN_MARKETPLACE}`;
61
62
  const XCODE_KEY = "xcode-integration@xcode-apple";
62
63
  const RETIRED = /^ai-[a-z]+-engineering-toolkit@multi-agent-plugins$/;
64
+ const PLUGIN_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
63
65
 
64
66
  export class StackError extends Error {
65
67
  constructor(code, message) {
@@ -91,50 +93,119 @@ function readSettings(repo) {
91
93
  }
92
94
  }
93
95
 
96
+ /** The marketplace clone on this machine, the root every plugin skill is read under. */
97
+ export function marketplaceClone(env = process.env) {
98
+ return join(home(env), ".claude", "plugins", "marketplaces", PLUGIN_MARKETPLACE);
99
+ }
100
+
94
101
  function marketplaceNames(env) {
95
- const path = join(
96
- home(env),
97
- ".claude",
98
- "plugins",
99
- "marketplaces",
100
- PLUGIN_MARKETPLACE,
101
- ".claude-plugin",
102
- "marketplace.json",
103
- );
102
+ const path = join(marketplaceClone(env), ".claude-plugin", "marketplace.json");
104
103
  try {
105
104
  return (JSON.parse(readFileSync(path, "utf8")).plugins || [])
106
- .map((p) => p.name)
107
- .filter(Boolean);
105
+ .map((p) => p?.name)
106
+ .filter((n) => typeof n === "string" && PLUGIN_NAME.test(n));
108
107
  } catch {
109
108
  return null;
110
109
  }
111
110
  }
112
111
 
113
- /** The skill names a plugin ships, from its best local root. */
114
- function skillsOf(plugin, env) {
115
- // Marketplace checkout first, then the plugin cache, newest version first.
116
- const marketplaceCopy = join(
117
- home(env),
118
- ".claude",
119
- "plugins",
120
- "marketplaces",
121
- PLUGIN_MARKETPLACE,
122
- "plugins",
123
- plugin,
124
- "skills",
125
- );
126
- for (const root of [marketplaceCopy, ...pluginSkillRootCandidates(home(env), [plugin])]) {
112
+ const SKILL_DEPTH = 3;
113
+ const inside = (root, p) => {
114
+ const rel = relative(root, p);
115
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
116
+ };
117
+ const realOrNull = (p) => {
118
+ try {
119
+ return realpathSync(p);
120
+ } catch {
121
+ return null;
122
+ }
123
+ };
124
+
125
+ /**
126
+ * Every skill under one `skills/` root: `skills/<name>/SKILL.md` and the
127
+ * grouped layout `skills/<group>/<name>/SKILL.md`. A directory or SKILL.md
128
+ * whose real path leaves the root is skipped, so a symlink cannot pull a file
129
+ * from elsewhere into the list.
130
+ *
131
+ * @returns {{name: string, file: string}[]|null} null when the root is unreadable
132
+ */
133
+ function skillsUnder(root) {
134
+ const realRoot = realOrNull(root);
135
+ if (!realRoot) return null;
136
+ const out = [];
137
+ const walk = (dir, left) => {
138
+ let entries;
127
139
  try {
128
- return readdirSync(root)
129
- .filter((d) => existsSync(join(root, d, "SKILL.md")))
130
- .sort();
140
+ entries = readdirSync(dir, { withFileTypes: true });
131
141
  } catch {
132
- // The next root may be readable.
142
+ return;
143
+ }
144
+ for (const e of entries) {
145
+ const p = join(dir, e.name);
146
+ const real = realOrNull(p);
147
+ if (!real || !inside(realRoot, real) || !statSync(real).isDirectory()) continue;
148
+ const file = join(p, "SKILL.md");
149
+ const realFile = realOrNull(file);
150
+ if (realFile && inside(realRoot, realFile) && statSync(realFile).isFile()) {
151
+ out.push({ name: e.name, file: realFile });
152
+ } else if (left > 1) walk(p, left - 1);
133
153
  }
154
+ };
155
+ walk(root, SKILL_DEPTH);
156
+ const seen = new Set();
157
+ return out
158
+ .sort((a, b) => a.name.localeCompare(b.name) || a.file.localeCompare(b.file))
159
+ .filter((s) => !seen.has(s.name) && seen.add(s.name));
160
+ }
161
+
162
+ /**
163
+ * The skills a plugin ships, from its best local root: the marketplace clone
164
+ * first, then the plugin cache, newest version first.
165
+ *
166
+ * @returns {{name: string, file: string}[]}
167
+ */
168
+ export function pluginSkillFiles(plugin, env = process.env) {
169
+ const marketplaceCopy = join(marketplaceClone(env), "plugins", plugin, "skills");
170
+ for (const root of [marketplaceCopy, ...pluginSkillRootCandidates(home(env), [plugin])]) {
171
+ const found = skillsUnder(root);
172
+ if (found) return found;
134
173
  }
135
174
  return [];
136
175
  }
137
176
 
177
+ const skillsOf = (plugin, env) => pluginSkillFiles(plugin, env).map((s) => s.name);
178
+
179
+ /**
180
+ * Every marketplace plugin with its enablement in `enabled` (an
181
+ * enabledPlugins block) and its skill names. `verified` is false when the
182
+ * marketplace manifest could not be read and the list is the convention.
183
+ */
184
+ export function marketplacePlugins(enabled = {}, env = process.env) {
185
+ const listed = marketplaceNames(env);
186
+ const names = listed ?? [...ALWAYS_ON, ...KNOWN_STACKS.map(stackPlugin)];
187
+ return {
188
+ verified: listed !== null,
189
+ plugins: names.map((name) => ({
190
+ name,
191
+ enabled: enabled[`${name}${SUFFIX}`] === true,
192
+ alwaysOn: ALWAYS_ON.includes(name),
193
+ stack: KNOWN_STACKS.find((s) => stackPlugin(s) === name) ?? null,
194
+ skills: skillsOf(name, env),
195
+ })),
196
+ };
197
+ }
198
+
199
+ /**
200
+ * The repository's enabledPlugins block, `{}` when it has none.
201
+ *
202
+ * @param {string} repo absolute path
203
+ */
204
+ export function repoEnabledPlugins(repo) {
205
+ if (!isAbsolute(repo)) throw new StackError("bad-repo", "the repository path must be absolute");
206
+ return readSettings(repo).enabledPlugins ?? {};
207
+ }
208
+
138
209
  /**
139
210
  * The repository's current state: which stacks are on, every marketplace
140
211
  * plugin with its enablement and skills.
@@ -142,22 +213,14 @@ function skillsOf(plugin, env) {
142
213
  * @param {string} repo absolute path
143
214
  */
144
215
  export function stackStatus(repo, env = process.env) {
145
- if (!isAbsolute(repo)) throw new StackError("bad-repo", "the repository path must be absolute");
146
- const enabled = readSettings(repo).enabledPlugins ?? {};
147
- const names = marketplaceNames(env) ?? [...ALWAYS_ON, ...KNOWN_STACKS.map(stackPlugin)];
148
- const plugins = names.map((name) => ({
149
- name,
150
- enabled: enabled[`${name}${SUFFIX}`] === true,
151
- alwaysOn: ALWAYS_ON.includes(name),
152
- stack: KNOWN_STACKS.find((s) => stackPlugin(s) === name) ?? null,
153
- skills: skillsOf(name, env),
154
- }));
216
+ const enabled = repoEnabledPlugins(repo);
217
+ const { verified, plugins } = marketplacePlugins(enabled, env);
155
218
  return {
156
219
  contractVersion: CONTRACT_VERSION,
157
220
  stacks: KNOWN_STACKS.filter((s) => enabled[`${stackPlugin(s)}${SUFFIX}`] === true),
158
221
  knownStacks: KNOWN_STACKS,
159
222
  plugins,
160
- manifestVerified: marketplaceNames(env) !== null,
223
+ manifestVerified: verified,
161
224
  };
162
225
  }
163
226
 
@@ -47,6 +47,13 @@
47
47
  * `--login <name>` records the person's GitHub username, for a machine that
48
48
  * proves no account (a work machine), and implies `--refresh`.
49
49
  *
50
+ * A stored token is checked first (`POST <register url>/check`, the token in
51
+ * the `x-usage-token` header). Only an explicit `valid: false` treats it as
52
+ * gone and registers again; an unreachable or undecided check keeps it.
53
+ * `--json` carries the outcome as `tokenCheck`: valid, invalid, unknown or
54
+ * skipped (no stored token, opted out, a token in the environment or prefs, a
55
+ * dry run, or an endpoint the token may not go to).
56
+ *
50
57
  * Exit: always 0. `--json` says what happened; the shell does not need to care.
51
58
  *
52
59
  * @module pipeline/scripts/usage-register
@@ -89,6 +96,7 @@ exitOnHelp(import.meta.url);
89
96
  const DEFAULT_ENDPOINT = "https://mmerterden.com/api/usage/ingest";
90
97
  const BUILT_IN_HOSTS = ["mmerterden.com"];
91
98
  const TIMEOUT_MS = 10000;
99
+ const CHECK_TIMEOUT_MS = 4000;
92
100
 
93
101
  function readJson(file) {
94
102
  try {
@@ -288,6 +296,42 @@ function refusal(status, json, body, method) {
288
296
  return `endpoint answered ${status}${detail}`;
289
297
  }
290
298
 
299
+ /** The check URL next to the register URL. */
300
+ export function checkUrl(url) {
301
+ return `${url.replace(/\/+$/, "")}/check`;
302
+ }
303
+
304
+ /**
305
+ * Ask the server whether the stored ingest token still works. The token goes
306
+ * only in the `x-usage-token` header (from memory, never an argv), and only to
307
+ * a URL `registerUrlAllowed` accepts; the caller checks that first.
308
+ * Returns "valid", "invalid" (an explicit `valid: false`), or "unknown" for a
309
+ * transport failure, a timeout, a redirect or any answer without a verdict.
310
+ */
311
+ export async function checkStoredToken(url, token, post = postHttp) {
312
+ let r;
313
+ try {
314
+ r = await post({
315
+ url: checkUrl(url),
316
+ headers: { "x-usage-token": token },
317
+ body: "{}",
318
+ timeoutMs: CHECK_TIMEOUT_MS,
319
+ });
320
+ } catch {
321
+ return "unknown";
322
+ }
323
+ if (!r || r.failure || r.status !== 200) return "unknown";
324
+ let json;
325
+ try {
326
+ json = JSON.parse(r.body);
327
+ } catch {
328
+ return "unknown";
329
+ }
330
+ if (json?.valid === true) return "valid";
331
+ if (json?.valid === false) return "invalid";
332
+ return "unknown";
333
+ }
334
+
291
335
  async function requestToken(url, body, proof, method) {
292
336
  const { res, json, failure, reason } = await postJson(url, body, proof);
293
337
  if (failure) return { token: null, why: failure, reason };
@@ -658,6 +702,7 @@ async function main(argv) {
658
702
  };
659
703
  const identity = { login: undefined };
660
704
  const beacon = { login: null };
705
+ const outcome = { tokenCheck: "skipped", refusal: null };
661
706
  const done = (status, detail, reason = null) => {
662
707
  if (!opts.dryRun) recordRegister(HOME, status, detail);
663
708
  sendFailureBeacon({
@@ -669,7 +714,9 @@ async function main(argv) {
669
714
  });
670
715
  if (opts.json) {
671
716
  const needsPersonalAccount = personalAccountMissing(readJson(prefsPath), identity.login);
672
- process.stdout.write(`${JSON.stringify({ status, detail, needsPersonalAccount })}\n`);
717
+ const out = { status, detail, needsPersonalAccount, tokenCheck: outcome.tokenCheck };
718
+ if (outcome.refusal) out.refusal = outcome.refusal;
719
+ process.stdout.write(`${JSON.stringify(out)}\n`);
673
720
  }
674
721
  if (opts.quiet && reportingStaysOff(status, detail)) {
675
722
  process.stderr.write(`multi-agent: usage reporting is off - ${detail}\n`);
@@ -715,16 +762,35 @@ async function main(argv) {
715
762
  const identityMatters = !["opted out", "token in environment", "token in prefs"].includes(
716
763
  pre.reason,
717
764
  );
718
- const has = identityMatters ? Boolean(storedToken(prefs, credStore)) : false;
765
+ // The stored token stays in memory and is sent only in the check's header.
766
+ const stored = identityMatters ? storedToken(prefs, credStore) : null;
767
+ const checkAt = registerUrl(prefs.global?.usageLog?.endpoint);
768
+ if (
769
+ stored &&
770
+ !opts.dryRun &&
771
+ registerUrlAllowed(checkAt, prefs.global?.usageLog?.trustedHosts || [])
772
+ ) {
773
+ outcome.tokenCheck = await checkStoredToken(checkAt, stored);
774
+ }
775
+ const rejected = outcome.tokenCheck === "invalid";
776
+ if (rejected) {
777
+ say(" -> operational reporting: the stored token is no longer accepted; registering again");
778
+ }
779
+ const has = Boolean(stored) && !rejected;
719
780
  let who = identityMatters
720
781
  ? reportingUser(prefsPath, { refresh: opts.refresh, write: !opts.dryRun })
721
782
  : { login: undefined, reason: null };
722
783
  const current = readJson(prefsPath) || prefs;
784
+ const cu = current.global?.usageLog || {};
785
+ // With no usable token, the login this machine was pinned to is a name
786
+ // already known, so it is registered as declared rather than asked for.
787
+ const known = !has && pinned(cu) && LOGIN_RE.test(cu.registeredAs) ? cu.registeredAs : null;
723
788
  const declared =
724
- opts.dryRun && opts.login !== null ? String(opts.login).trim() : declaredLoginOf(current);
789
+ opts.dryRun && opts.login !== null
790
+ ? String(opts.login).trim()
791
+ : declaredLoginOf(current) || known;
725
792
  // A typed name is used only when this machine proves no account at all; a
726
793
  // proof, for that name or another, is evidence and a declaration is not.
727
- const cu = current.global?.usageLog || {};
728
794
  const provenPin = has && pinned(cu) && cu.registeredClaim !== true;
729
795
  if (identityMatters && declared && !who.login && !provenPin && !opts.feedback) {
730
796
  who = { login: declared, method: "claim", key: null, reason: "declared by the person" };
@@ -761,8 +827,9 @@ async function main(argv) {
761
827
  ) {
762
828
  sendInstalledVersion(prefsPath);
763
829
  }
764
- say(` -> operational reporting: unchanged (${decision.reason})`);
765
- return done("skipped", decision.reason);
830
+ const detail = rejected ? `stored token rejected; ${decision.reason}` : decision.reason;
831
+ say(` -> operational reporting: unchanged (${detail})`);
832
+ return done("skipped", detail);
766
833
  }
767
834
 
768
835
  const url = registerUrl(current.global?.usageLog?.endpoint);
@@ -810,9 +877,14 @@ async function main(argv) {
810
877
  result = await requestToken(url, { u: user, c: host }, proof, who.method || "gh");
811
878
  }
812
879
  const { token, why, declined, code, reason, login: pinnedLogin } = result;
813
- if (who.method === "claim" && ["not_collaborator", "proof_required"].includes(code))
880
+ if (who.method === "claim" && ["not_collaborator", "proof_required"].includes(code)) {
881
+ outcome.refusal = code;
814
882
  declareLogin(prefsPath, null);
815
- else if (who.method === "claim" && !token && !declined)
883
+ identity.login = null;
884
+ // A rejected token pins nothing, so the refused name is not kept as one.
885
+ if (rejected || known)
886
+ patchUsageLog(prefsPath, { registeredAs: undefined, registeredClaim: undefined });
887
+ } else if (who.method === "claim" && !token && !declined)
816
888
  patchUsageLog(prefsPath, { claimFailedAt: new Date().toISOString() });
817
889
  if (declined) {
818
890
  say(` -> operational reporting left off (${why})`);
@@ -824,7 +896,12 @@ async function main(argv) {
824
896
  }
825
897
 
826
898
  const optedOut = prefs.global?.usageLog?.optOut === true;
827
- const entry = `${process.env.USER || user}_Usage_Ingest_Token`;
899
+ // A rejected token is overwritten in its own entry rather than left beside a new one.
900
+ const mapped = current.global?.keychainMapping?.usage_ingest;
901
+ const entry =
902
+ rejected && typeof mapped === "string" && /^[A-Za-z0-9._-]{1,128}$/.test(mapped)
903
+ ? mapped
904
+ : `${process.env.USER || user}_Usage_Ingest_Token`;
828
905
  const set = spawnSync("bash", [credStore, "set", entry, "-"], {
829
906
  input: token,
830
907
  encoding: "utf8",