toolroll 0.9.120 → 0.9.123

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 (54) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/README.md +10 -23
  3. package/dist/agent-fence.js +57 -9
  4. package/dist/batch-checks.js +2 -2
  5. package/dist/builder.js +10 -7
  6. package/dist/central-recovery-stage.js +3 -3
  7. package/dist/codex-limits.js +2 -2
  8. package/dist/coding-provider.js +3 -3
  9. package/dist/contracts/console-api.js +1 -0
  10. package/dist/direct-chat-fence.js +9 -3
  11. package/dist/direct-chat.js +82 -10
  12. package/dist/first-run.js +1 -1
  13. package/dist/flexible-agents.js +16 -2
  14. package/dist/flexible-save.js +8 -8
  15. package/dist/flexible-session.js +2 -1
  16. package/dist/flexible-thread.js +5 -1
  17. package/dist/install-method.js +1 -3
  18. package/dist/invoke.js +11 -9
  19. package/dist/lead-tools.js +3 -2
  20. package/dist/live-terminal.js +24 -3
  21. package/dist/local-landing.js +48 -8
  22. package/dist/local-owner.js +1 -0
  23. package/dist/operate.js +40 -10
  24. package/dist/plan-limits-demand.js +32 -10
  25. package/dist/planner.js +2 -0
  26. package/dist/project-delete.js +1 -1
  27. package/dist/project-skills.js +105 -17
  28. package/dist/result-follow-ups.js +2 -2
  29. package/dist/scout.js +2 -1
  30. package/dist/serve.js +8 -1
  31. package/dist/server/direct-chat.js +1 -0
  32. package/dist/server/engine-api.js +6 -5
  33. package/dist/server/render-release.js +27 -15
  34. package/dist/server/route-table.js +2 -0
  35. package/dist/server/settings.js +151 -3
  36. package/dist/server/task-views.js +4 -3
  37. package/dist/server/tasks.js +11 -10
  38. package/dist/server/terminals.js +3 -1
  39. package/dist/skill-library-schema.js +70 -0
  40. package/dist/skill-library.js +693 -0
  41. package/dist/skill-local-sync.js +334 -0
  42. package/dist/skills-manifest.js +6 -3
  43. package/dist/skills-ui.js +122 -1
  44. package/dist/store.js +22 -4
  45. package/dist/surface.js +1 -1
  46. package/dist/task-status.js +2 -1
  47. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  48. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  49. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  50. package/dist/tui/linux-x64/toolroll-tui +0 -0
  51. package/dist/work-index.js +5 -2
  52. package/dist/work-summary.js +77 -1
  53. package/dist/workspace-ui.js +12 -6
  54. package/package.json +2 -1
@@ -0,0 +1,334 @@
1
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmdirSync, unlinkSync, writeFileSync, } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, isAbsolute, join, resolve } from "node:path";
4
+ import { within } from "./skills-manifest.js";
5
+ export const LOCAL_SKILL_TOOLS = ["claude", "codex", "gemini"];
6
+ export const LOCAL_TOOL_LABELS = {
7
+ claude: "Claude Code",
8
+ codex: "Codex",
9
+ gemini: "Gemini CLI",
10
+ };
11
+ const MANAGED_MARKER_FILE = ".toolroll-managed.json";
12
+ const RESERVED_NAMES = new Set(["toolroll", "standing-orders"]);
13
+ function isRealDir(path) {
14
+ try {
15
+ const held = lstatSync(path);
16
+ return held.isDirectory() && !held.isSymbolicLink();
17
+ }
18
+ catch {
19
+ return false;
20
+ }
21
+ }
22
+ function noSymlinkBelow(base, target) {
23
+ if (target !== base && !within(target, base))
24
+ return false;
25
+ let at = base;
26
+ if (!isRealDir(at))
27
+ return false;
28
+ if (target === base)
29
+ return true;
30
+ const rel = target.slice(base.length + 1).split("/");
31
+ for (const part of rel) {
32
+ at = join(at, part);
33
+ if (existsSync(at)) {
34
+ try {
35
+ const held = lstatSync(at);
36
+ if (held.isSymbolicLink())
37
+ return false;
38
+ }
39
+ catch {
40
+ return false;
41
+ }
42
+ }
43
+ }
44
+ return true;
45
+ }
46
+ export function detectLocalSkillDirs(home = homedir(), env = process.env) {
47
+ const realHome = existsSync(home) ? realpathSync(home) : resolve(home);
48
+ const envDir = (key, fallback) => {
49
+ const raw = env[key]?.trim();
50
+ if (!raw)
51
+ return join(realHome, fallback);
52
+ return isAbsolute(raw) ? resolve(raw) : resolve(realHome, raw);
53
+ };
54
+ const homes = {
55
+ claude: envDir("CLAUDE_CONFIG_DIR", ".claude"),
56
+ codex: envDir("CODEX_HOME", ".codex"),
57
+ gemini: envDir("GEMINI_CLI_HOME", ".gemini"),
58
+ };
59
+ const out = {};
60
+ for (const tool of LOCAL_SKILL_TOOLS) {
61
+ const toolHome = homes[tool];
62
+ const detected = isRealDir(toolHome);
63
+ const skillsDir = detected ? join(realpathSync(toolHome), "skills") : null;
64
+ const validSkills = skillsDir !== null && (!existsSync(skillsDir) || isRealDir(skillsDir));
65
+ out[tool] = {
66
+ toolHome,
67
+ skillsDir: validSkills ? skillsDir : null,
68
+ detected: detected && validSkills,
69
+ };
70
+ }
71
+ return out;
72
+ }
73
+ function readManagedMarker(skillDir) {
74
+ const markerPath = join(skillDir, MANAGED_MARKER_FILE);
75
+ try {
76
+ const held = lstatSync(markerPath);
77
+ if (!held.isFile() || held.isSymbolicLink() || held.size > 256 * 1024)
78
+ return null;
79
+ const parsed = JSON.parse(readFileSync(markerPath, "utf8"));
80
+ if (parsed.managedBy !== "toolroll-skill-library" ||
81
+ parsed.version !== 1 ||
82
+ typeof parsed.name !== "string" ||
83
+ typeof parsed.sha !== "string" ||
84
+ !Array.isArray(parsed.files) ||
85
+ parsed.files.some((f) => typeof f !== "string")) {
86
+ return null;
87
+ }
88
+ return parsed;
89
+ }
90
+ catch {
91
+ return null;
92
+ }
93
+ }
94
+ function removeEmptyAncestors(from, stopAt) {
95
+ let at = from;
96
+ while (at !== stopAt && within(at, stopAt)) {
97
+ try {
98
+ if (!isRealDir(at))
99
+ break;
100
+ if (readdirSync(at).length > 0)
101
+ break;
102
+ rmdirSync(at);
103
+ at = dirname(at);
104
+ }
105
+ catch {
106
+ break;
107
+ }
108
+ }
109
+ }
110
+ function removeManagedSkillDir(skillsDir, skillName) {
111
+ const skillDir = join(skillsDir, skillName);
112
+ if (!existsSync(skillDir) || !isRealDir(skillDir))
113
+ return false;
114
+ const marker = readManagedMarker(skillDir);
115
+ if (marker === null)
116
+ return false;
117
+ for (const rel of marker.files) {
118
+ const full = join(skillDir, rel);
119
+ if (!within(full, skillDir))
120
+ continue;
121
+ try {
122
+ const held = lstatSync(full);
123
+ if (held.isFile() && !held.isSymbolicLink()) {
124
+ unlinkSync(full);
125
+ removeEmptyAncestors(dirname(full), skillDir);
126
+ }
127
+ }
128
+ catch {
129
+ }
130
+ }
131
+ try {
132
+ unlinkSync(join(skillDir, MANAGED_MARKER_FILE));
133
+ }
134
+ catch {
135
+ }
136
+ removeEmptyAncestors(skillDir, skillsDir);
137
+ return true;
138
+ }
139
+ export function syncSkillsToDirectory(tool, skillsDir, skills, previouslyInstalled) {
140
+ const parent = dirname(skillsDir);
141
+ if (!isRealDir(parent))
142
+ throw Error(`${LOCAL_TOOL_LABELS[tool]} home folder was not found on this computer.`);
143
+ if (existsSync(skillsDir) && !isRealDir(skillsDir)) {
144
+ throw Error(`${skillsDir} is not a real folder — refusing to sync skills there.`);
145
+ }
146
+ if (!existsSync(skillsDir))
147
+ mkdirSync(skillsDir, { mode: 0o700 });
148
+ const realSkillsDir = realpathSync(skillsDir);
149
+ const written = [];
150
+ const removed = [];
151
+ const skippedForeign = [];
152
+ const nextInstalled = {};
153
+ const wantedNames = new Set();
154
+ for (const skill of skills) {
155
+ if (RESERVED_NAMES.has(skill.name))
156
+ continue;
157
+ wantedNames.add(skill.name);
158
+ const skillDir = join(realSkillsDir, skill.name);
159
+ if (!within(skillDir, realSkillsDir))
160
+ continue;
161
+ if (existsSync(skillDir)) {
162
+ if (!isRealDir(skillDir) || readManagedMarker(skillDir) === null) {
163
+ skippedForeign.push(skill.name);
164
+ continue;
165
+ }
166
+ }
167
+ const existingMarker = existsSync(skillDir) ? readManagedMarker(skillDir) : null;
168
+ if (existingMarker !== null && existingMarker.sha === skill.sha) {
169
+ nextInstalled[skill.name] = { sha: skill.sha, files: existingMarker.files };
170
+ continue;
171
+ }
172
+ if (existingMarker !== null) {
173
+ for (const oldRel of existingMarker.files) {
174
+ const oldPath = join(skillDir, oldRel);
175
+ if (!within(oldPath, skillDir))
176
+ continue;
177
+ try {
178
+ const held = lstatSync(oldPath);
179
+ if (held.isFile() && !held.isSymbolicLink()) {
180
+ unlinkSync(oldPath);
181
+ removeEmptyAncestors(dirname(oldPath), skillDir);
182
+ }
183
+ }
184
+ catch {
185
+ }
186
+ }
187
+ }
188
+ if (!existsSync(skillDir))
189
+ mkdirSync(skillDir, { mode: 0o700 });
190
+ if (!noSymlinkBelow(realSkillsDir, skillDir)) {
191
+ skippedForeign.push(skill.name);
192
+ continue;
193
+ }
194
+ const fileList = [];
195
+ for (const file of skill.files) {
196
+ const target = join(skillDir, file.path);
197
+ if (!within(target, skillDir) || !noSymlinkBelow(skillDir, dirname(target)))
198
+ continue;
199
+ mkdirSync(dirname(target), { recursive: true, mode: 0o700 });
200
+ if (existsSync(target) && lstatSync(target).isSymbolicLink())
201
+ continue;
202
+ writeFileSync(target, Buffer.from(file.base64, "base64"), { mode: 0o600 });
203
+ fileList.push(file.path);
204
+ }
205
+ const marker = {
206
+ managedBy: "toolroll-skill-library",
207
+ version: 1,
208
+ name: skill.name,
209
+ sha: skill.sha,
210
+ files: fileList.sort(),
211
+ };
212
+ writeFileSync(join(skillDir, MANAGED_MARKER_FILE), JSON.stringify(marker, null, 2) + "\n", { mode: 0o600 });
213
+ nextInstalled[skill.name] = { sha: skill.sha, files: marker.files };
214
+ written.push(skill.name);
215
+ }
216
+ for (const oldName of Object.keys(previouslyInstalled)) {
217
+ if (wantedNames.has(oldName) || RESERVED_NAMES.has(oldName))
218
+ continue;
219
+ if (removeManagedSkillDir(realSkillsDir, oldName))
220
+ removed.push(oldName);
221
+ }
222
+ for (const entry of readdirSync(realSkillsDir)) {
223
+ if (wantedNames.has(entry) || RESERVED_NAMES.has(entry))
224
+ continue;
225
+ if (removeManagedSkillDir(realSkillsDir, entry) && !removed.includes(entry))
226
+ removed.push(entry);
227
+ }
228
+ return {
229
+ outcome: { tool, targetDir: realSkillsDir, written, removed, skippedForeign },
230
+ installed: nextInstalled,
231
+ };
232
+ }
233
+ export function localSyncStatus(store, options = {}) {
234
+ const detected = detectLocalSkillDirs(options.home, options.env);
235
+ const rows = new Map();
236
+ for (const row of store.handle.prepare("SELECT * FROM skill_local_sync").all()) {
237
+ rows.set(String(row["tool"]), row);
238
+ }
239
+ return LOCAL_SKILL_TOOLS.map((tool) => {
240
+ const found = detected[tool];
241
+ const row = rows.get(tool);
242
+ let installedCount = 0;
243
+ if (row && typeof row["installed_json"] === "string") {
244
+ try {
245
+ installedCount = Object.keys(JSON.parse(row["installed_json"])).length;
246
+ }
247
+ catch {
248
+ installedCount = 0;
249
+ }
250
+ }
251
+ return {
252
+ tool,
253
+ label: LOCAL_TOOL_LABELS[tool],
254
+ detected: found.detected,
255
+ toolHome: found.toolHome,
256
+ skillsDir: found.skillsDir,
257
+ enabled: row !== undefined && Number(row["enabled"]) === 1,
258
+ syncedRevision: row !== undefined ? Number(row["synced_revision"]) : 0,
259
+ syncedAt: row !== undefined && typeof row["synced_at"] === "string" ? row["synced_at"] : null,
260
+ installedCount,
261
+ };
262
+ });
263
+ }
264
+ export function setLocalSkillSync(store, args, now = new Date()) {
265
+ if (!LOCAL_SKILL_TOOLS.includes(args.tool))
266
+ throw Error("Choose Claude Code, Codex, or Gemini CLI.");
267
+ const detected = detectLocalSkillDirs(args.home, args.env)[args.tool];
268
+ const existing = store.handle.prepare("SELECT * FROM skill_local_sync WHERE tool=?").get(args.tool);
269
+ const previousInstalled = (() => {
270
+ if (!existing || typeof existing["installed_json"] !== "string")
271
+ return {};
272
+ try {
273
+ return JSON.parse(existing["installed_json"]);
274
+ }
275
+ catch {
276
+ return {};
277
+ }
278
+ })();
279
+ if (args.enabled) {
280
+ if (!detected.detected || detected.skillsDir === null) {
281
+ throw Error(`${LOCAL_TOOL_LABELS[args.tool]} was not detected at ${detected.toolHome}. Install or open ${LOCAL_TOOL_LABELS[args.tool]} first so Toolroll only writes where it reads.`);
282
+ }
283
+ const { outcome, installed } = syncSkillsToDirectory(args.tool, detected.skillsDir, args.skills, previousInstalled);
284
+ const when = now.toISOString();
285
+ store.handle
286
+ .prepare(`INSERT INTO skill_local_sync (tool, enabled, target_dir, installed_json, synced_revision, synced_at, updated_by, updated_at)
287
+ VALUES (?, 1, ?, ?, ?, ?, ?, ?)
288
+ ON CONFLICT(tool) DO UPDATE SET enabled=1, target_dir=excluded.target_dir, installed_json=excluded.installed_json,
289
+ synced_revision=excluded.synced_revision, synced_at=excluded.synced_at, updated_by=excluded.updated_by, updated_at=excluded.updated_at`)
290
+ .run(args.tool, outcome.targetDir, JSON.stringify(installed), args.libraryRevision, when, args.actor, when);
291
+ return outcome;
292
+ }
293
+ const targetDir = detected.skillsDir ?? (typeof existing?.["target_dir"] === "string" ? existing["target_dir"] : null);
294
+ let outcome = null;
295
+ if (targetDir !== null && isRealDir(targetDir)) {
296
+ const synced = syncSkillsToDirectory(args.tool, targetDir, [], previousInstalled);
297
+ outcome = synced.outcome;
298
+ }
299
+ const when = now.toISOString();
300
+ store.handle
301
+ .prepare(`INSERT INTO skill_local_sync (tool, enabled, target_dir, installed_json, synced_revision, synced_at, updated_by, updated_at)
302
+ VALUES (?, 0, ?, '{}', 0, NULL, ?, ?)
303
+ ON CONFLICT(tool) DO UPDATE SET enabled=0, installed_json='{}', synced_revision=0, synced_at=NULL, updated_by=excluded.updated_by, updated_at=excluded.updated_at`)
304
+ .run(args.tool, targetDir, args.actor, when);
305
+ return outcome;
306
+ }
307
+ export function syncEnabledLocalTools(store, args, now = new Date()) {
308
+ const rows = store.handle.prepare("SELECT * FROM skill_local_sync WHERE enabled=1").all();
309
+ const outcomes = [];
310
+ for (const row of rows) {
311
+ const tool = String(row["tool"]);
312
+ if (!LOCAL_SKILL_TOOLS.includes(tool))
313
+ continue;
314
+ const detected = detectLocalSkillDirs(args.home, args.env)[tool];
315
+ if (!detected.detected || detected.skillsDir === null)
316
+ continue;
317
+ let previousInstalled = {};
318
+ if (typeof row["installed_json"] === "string") {
319
+ try {
320
+ previousInstalled = JSON.parse(row["installed_json"]);
321
+ }
322
+ catch {
323
+ previousInstalled = {};
324
+ }
325
+ }
326
+ const { outcome, installed } = syncSkillsToDirectory(tool, detected.skillsDir, args.skills, previousInstalled);
327
+ const when = now.toISOString();
328
+ store.handle
329
+ .prepare(`UPDATE skill_local_sync SET target_dir=?, installed_json=?, synced_revision=?, synced_at=?, updated_by=?, updated_at=? WHERE tool=?`)
330
+ .run(outcome.targetDir, JSON.stringify(installed), args.libraryRevision, when, args.actor, when, tool);
331
+ outcomes.push(outcome);
332
+ }
333
+ return outcomes;
334
+ }
@@ -42,7 +42,7 @@ export function checkSkillsManifest(manifest) {
42
42
  }
43
43
  export function skillsGrant(skills) {
44
44
  if (skills === null)
45
- return { deny: [], files: [], problem: null };
45
+ return { deny: [], files: [], digests: {}, folders: [], problem: null };
46
46
  const canonical = (path) => { try {
47
47
  return realpathSync(path);
48
48
  }
@@ -51,7 +51,10 @@ export function skillsGrant(skills) {
51
51
  } };
52
52
  const deny = [...new Set([skills.root, ...(skills.manifest === null ? [] : [dirname(skills.manifest.directory)])].flatMap(path => [path, canonical(path)]))].sort();
53
53
  if (skills.manifest === null)
54
- return { deny, files: [], problem: null };
54
+ return { deny, files: [], digests: {}, folders: [], problem: null };
55
55
  const checked = checkSkillsManifest(skills.manifest);
56
- return checked.ok ? { deny, files: checked.files, problem: null } : { deny, files: [], problem: checked.problem };
56
+ if (!checked.ok)
57
+ return { deny, files: [], digests: {}, folders: [], problem: checked.problem };
58
+ const digests = Object.fromEntries(skills.manifest.files.map(file => [file.path, file.sha256]));
59
+ return { deny, files: checked.files, digests, folders: [...skills.manifest.folders], problem: null };
57
60
  }
package/dist/skills-ui.js CHANGED
@@ -100,8 +100,129 @@ export function skillsSnapshotHtml(snapshot) {
100
100
  return html `<details class="skills"><summary>Skills supplied (${snapshot.packages.length})</summary><p class="meta">Exact versions supplied to this run. This does not confirm the agent read or applied them.</p>${snapshot.packages.map((s) => html `<details><summary>${s.name} · ${s.sha.slice(0, 10)}</summary>${source(s)}</details>`)}</details>`;
101
101
  }
102
102
  export function skillsScript() {
103
- return `(()=>{const search=document.querySelector('[data-skill-search]');if(search)search.addEventListener('input',()=>{let found=0;document.querySelectorAll('[data-skill-group]').forEach(el=>{el.hidden=!el.dataset.skillQuery.toLowerCase().includes(search.value.trim().toLowerCase());if(!el.hidden)found++;});document.querySelector('[data-skill-no-matches]').hidden=found>0;});const form=document.querySelector('[data-skill-import]');if(!form)return;const method=form.querySelector('[data-skill-method]'),error=form.querySelector('[data-skill-error]');function sync(){form.querySelectorAll('[data-skill-input]').forEach(el=>{el.hidden=el.dataset.skillInput!==method.value;el.querySelectorAll('input,textarea').forEach(i=>i.disabled=el.hidden);});}method.addEventListener('change',sync);sync();form.addEventListener('submit',async event=>{if(method.value!=='folder')return;if(form.dataset.prepared==='yes'){delete form.dataset.prepared;return;}event.preventDefault();error.hidden=true;error.textContent='';const button=form.querySelector('button');button.disabled=true;try{const files=Array.from(form.querySelector('[data-skill-folder]').files);if(!files.length||files.length>64||files.reduce((n,f)=>n+f.size,0)>1048576||files.some(f=>f.size>262144))throw Error('Choose one skill folder with up to 64 files and 1 MB total.');const packed=[];for(const file of files){const parts=file.webkitRelativePath.split('/');parts.shift();const data=new Uint8Array(await file.arrayBuffer());let binary='';for(const byte of data)binary+=String.fromCharCode(byte);packed.push({path:parts.join('/'),base64:btoa(binary)});}form.querySelector('[name=files]').value=JSON.stringify(packed);form.dataset.prepared='yes';button.disabled=false;form.requestSubmit();}catch(e){error.textContent=e.message||'The folder could not be read. Select it again.';error.hidden=false;button.disabled=false;}});})();`;
103
+ return `(()=>{const gsearch=document.querySelector('[data-global-skill-search]');if(gsearch)gsearch.addEventListener('input',()=>{let found=0;document.querySelectorAll('[data-global-skill-group]').forEach(el=>{el.hidden=!el.dataset.globalSkillQuery.toLowerCase().includes(gsearch.value.trim().toLowerCase());if(!el.hidden)found++;});const nm=document.querySelector('[data-global-skill-no-matches]');if(nm)nm.hidden=found>0;});const search=document.querySelector('[data-skill-search]');if(search)search.addEventListener('input',()=>{let found=0;document.querySelectorAll('[data-skill-group]').forEach(el=>{el.hidden=!el.dataset.skillQuery.toLowerCase().includes(search.value.trim().toLowerCase());if(!el.hidden)found++;});document.querySelector('[data-skill-no-matches]').hidden=found>0;});const form=document.querySelector('[data-skill-import]');if(!form)return;const method=form.querySelector('[data-skill-method]'),error=form.querySelector('[data-skill-error]');function sync(){form.querySelectorAll('[data-skill-input]').forEach(el=>{el.hidden=el.dataset.skillInput!==method.value;el.querySelectorAll('input,textarea').forEach(i=>i.disabled=el.hidden);});}method.addEventListener('change',sync);sync();form.addEventListener('submit',async event=>{if(method.value!=='folder')return;if(form.dataset.prepared==='yes'){delete form.dataset.prepared;return;}event.preventDefault();error.hidden=true;error.textContent='';const button=form.querySelector('button');button.disabled=true;try{const files=Array.from(form.querySelector('[data-skill-folder]').files);if(!files.length||files.length>64||files.reduce((n,f)=>n+f.size,0)>1048576||files.some(f=>f.size>262144))throw Error('Choose one skill folder with up to 64 files and 1 MB total.');const packed=[];for(const file of files){const parts=file.webkitRelativePath.split('/');parts.shift();const data=new Uint8Array(await file.arrayBuffer());let binary='';for(const byte of data)binary+=String.fromCharCode(byte);packed.push({path:parts.join('/'),base64:btoa(binary)});}form.querySelector('[name=files]').value=JSON.stringify(packed);form.dataset.prepared='yes';button.disabled=false;form.requestSubmit();}catch(e){error.textContent=e.message||'The folder could not be read. Select it again.';error.hidden=false;button.disabled=false;}});})();`;
104
104
  }
105
105
  export function skillTestFeedbackHtml(test, csrf, canManage, error = "", draft = "") {
106
106
  return html `<section class="skills" id="skill-test-feedback"><h2>Improve this test</h2>${test.sourceRun ? html `<p>Revises test run #${test.sourceRun}.</p>` : ""}${test.feedback ? html `<details><summary>Feedback for this test</summary><p>${test.feedback}</p></details>` : ""}${test.revisions.length ? html `<p>${joinHtml(test.revisions.map((id, i) => html `<a href="/t/${encodeURIComponent(id)}">Test revision ${i + 1}</a>`), " · ")}</p>` : ""}${error ? html `<p role="alert">${error}</p>` : ""}${canManage && csrf ? postForm("/settings/skills/revise", html `<label>What should change?<textarea name="feedback" required maxlength="500" rows="3" placeholder="Try a clearer action label and explain why it fits the user’s goal.">${draft}</textarea></label><p class="meta">Creates another report task with this skill version and your feedback. Review its scope before it runs.</p><button>Create revision</button>`, { hidden: fields({ repo: test.repo, run: test.run, nonce: randomUUID() }) }) : ""}</section>`;
107
107
  }
108
+ export function skillLibrarySectionHtml(library, localTools, csrf, canManage, options = {}) {
109
+ const manage = canManage && !!csrf;
110
+ const repo = options.repo ?? "";
111
+ const libForm = (action, contents, extra = {}) => postForm("/settings/skills/library", contents, { hidden: fields({ action, repo, revision: library.revision, ...extra }) });
112
+ const enabledCount = Object.values(library.selection).filter((c) => c.enabled).length;
113
+ const projectOptedOutAll = library.projectOptOut?.all === true;
114
+ const projectOptOutNames = new Set(library.projectOptOut?.names ?? []);
115
+ const importBundleForm = manage
116
+ ? disclose("Import a GitHub skill bundle", libForm("import-bundle", joinHtml([
117
+ formRow("GitHub repository URL", "Imports every SKILL.md found in the repository, pinned to its exact commit SHA.", input({ id: "bundle-url", name: "url", type: "url", attrs: { required: true, placeholder: "https://github.com/owner/repo", "aria-label": "GitHub repository URL" } }), "wide"),
118
+ html `<label class="k-note"><input type="checkbox" name="autoUpdate" value="1" checked> Check daily and apply clean updates automatically (suspicious changes are held for review)</label>`,
119
+ acts(btn("Import bundle", { variant: "primary", type: "submit" })),
120
+ ])), library.bundles.length === 0 && library.skills.length === 0)
121
+ : "";
122
+ const addGlobalSkillForm = manage
123
+ ? disclose("Add a single skill to all projects", libForm("import-skill", joinHtml([
124
+ formRow("SKILL.md", "Added to the global library and enabled across all projects unless opted out.", textarea({ id: "global-skill-content", name: "content", rows: 6, attrs: { required: true, maxlength: 24576, placeholder: "---\nname: code-review\ndescription: Review changes for clarity and bugs.\n---\nWrite your instructions here.", "aria-label": "Global SKILL.md" } }), "top"),
125
+ acts(btn("Add to global library", { sm: true, type: "submit" })),
126
+ ]), { method: "paste" }))
127
+ : "";
128
+ const bundleCards = library.bundles.map((bundle) => {
129
+ const heldBlock = bundle.heldCommit
130
+ ? joinHtml([
131
+ notice(`Update held for review (${bundle.heldCommit.slice(0, 12)}): ${bundle.heldReason ?? "Suspicious change detected."}`),
132
+ manage ? html `<div class="skill-controls">${libForm("apply-held", btn("Apply held update anyway", { sm: true, type: "submit" }), { bundle: bundle.id })}${libForm("dismiss-held", btn("Dismiss held update", { sm: true, type: "submit" }), { bundle: bundle.id })}</div>` : "",
133
+ ])
134
+ : "";
135
+ const controls = manage
136
+ ? html `<div class="skill-controls">
137
+ ${libForm("sweep-bundle", btn("Check for updates", { sm: true, type: "submit" }), { bundle: bundle.id })}
138
+ ${libForm("bundle-auto-update", btn(bundle.autoUpdate ? "Pause daily updates" : "Enable daily updates", { sm: true, type: "submit" }), { bundle: bundle.id, autoUpdate: bundle.autoUpdate ? "0" : "1" })}
139
+ ${bundle.previousCommit ? libForm("rollback-bundle", btn(`Roll back to ${bundle.previousCommit.slice(0, 10)}`, { sm: true, type: "submit" }), { bundle: bundle.id }) : ""}
140
+ </div>`
141
+ : "";
142
+ return settingsRecord({
143
+ title: html `<span>${bundle.owner}/${bundle.repoName}</span>${chip(`${plural(bundle.skillNames.length, "skill", "skills")}`, "done")}${bundle.heldCommit ? chip("Update held", "") : ""}`,
144
+ sub: html `Pinned at <span class="k-mono">${bundle.pinnedCommit.slice(0, 12)}</span> · ${bundle.autoUpdate ? "Daily auto-update on" : "Manual updates"}`,
145
+ when: bundle.lastCheckedAt ? html `Checked ${whenUtc(bundle.lastCheckedAt)}` : undefined,
146
+ more: joinHtml([heldBlock, controls]),
147
+ });
148
+ });
149
+ const projectOptOutToggle = manage && repo
150
+ ? libForm("project-opt-out", acts(btn(projectOptedOutAll ? "Re-enable global library for this project" : "Opt this project out of the global library", { sm: true, type: "submit" })), {
151
+ skill: "*",
152
+ optedOut: projectOptedOutAll ? "0" : "1",
153
+ })
154
+ : "";
155
+ const globalSkillCards = library.skills.map((skill) => {
156
+ const enabled = library.selection[skill.name]?.sha === skill.sha && library.selection[skill.name]?.enabled === true;
157
+ const optedOutThis = projectOptOutNames.has(skill.name);
158
+ const optOut = optedOutThis || projectOptedOutAll;
159
+ const statusChip = !enabled
160
+ ? chip("Disabled", "")
161
+ : optOut
162
+ ? chip("Opted out here", "")
163
+ : chip("Active", "done");
164
+ const controls = manage
165
+ ? html `<div class="skill-controls">
166
+ ${libForm(enabled ? "disable-skill" : "enable-skill", btn(enabled ? "Disable globally" : "Enable globally", { sm: true, type: "submit" }), { sha: skill.sha })}
167
+ ${repo && !projectOptedOutAll ? libForm("project-opt-out", btn(optedOutThis ? "Include in this project" : "Opt out here", { sm: true, type: "submit" }), { skill: skill.name, optedOut: optedOutThis ? "0" : "1" }) : ""}
168
+ </div>`
169
+ : "";
170
+ return html `<div data-global-skill-group data-global-skill-query="${skill.name + " " + skill.description}">${settingsRecord({
171
+ title: html `<span>${skill.name}</span>${statusChip}`,
172
+ sub: skill.description,
173
+ more: joinHtml([
174
+ disclose("Review skill", joinHtml([sourceKit(skill), controls])),
175
+ ]),
176
+ })}</div>`;
177
+ });
178
+ const globalSearch = library.skills.length > 5
179
+ ? html `${formRow("Search global library", null, input({ id: "global-skill-search", name: "global-skill-search", type: "search", attrs: { "data-global-skill-search": true, placeholder: "Filter global skills by name or description", "aria-label": "Search global library" } }), "wide")}<p class="k-note" data-global-skill-no-matches hidden>No matching global skills.</p>`
180
+ : "";
181
+ const globalSection = settingsSection({
182
+ id: "global-library",
183
+ title: "Global Skill Library",
184
+ lead: `${enabledCount ? `${plural(enabledCount, "skill", "skills")} active across all projects by default.` : "No global skills installed yet."} Every agent (tasks, Direct Chat, threads, terminals, and the lead) receives this pinned set unless a project opts out.`,
185
+ body: joinHtml([
186
+ importBundleForm,
187
+ addGlobalSkillForm,
188
+ bundleCards.length ? html `<h3>Tracked GitHub bundles</h3>${joinHtml(bundleCards)}` : "",
189
+ projectOptOutToggle,
190
+ globalSearch,
191
+ globalSkillCards.length ? joinHtml(globalSkillCards) : note("Import a GitHub skill repository or add a skill above to share it across every project."),
192
+ ]),
193
+ });
194
+ const localToolCards = localTools.map((tool) => {
195
+ const statusChip = !tool.detected
196
+ ? chip("Not detected", "")
197
+ : tool.enabled
198
+ ? chip(`Synced (${tool.installedCount})`, "done")
199
+ : chip("Detected · off", "");
200
+ const sub = tool.detected
201
+ ? html `Writes only Toolroll-managed skills to <span class="k-mono">${tool.skillsDir ?? tool.toolHome}</span>. Your own hand-written skills are never overwritten.`
202
+ : "Folder not found on this computer — Toolroll only writes where a tool is already installed.";
203
+ const actions = manage && tool.detected
204
+ ? html `<div class="skill-controls">
205
+ ${libForm("local-sync", btn(tool.enabled ? "Turn off sync" : "Also install here", { sm: true, type: "submit" }), { tool: tool.tool, enabled: tool.enabled ? "0" : "1" })}
206
+ ${tool.enabled ? libForm("local-sync-now", btn("Sync now", { sm: true, type: "submit" }), { tool: tool.tool }) : ""}
207
+ </div>`
208
+ : "";
209
+ return settingsRecord({
210
+ title: html `<span>${tool.label}</span>${statusChip}`,
211
+ sub,
212
+ when: tool.syncedAt ? html `Last synced ${whenUtc(tool.syncedAt)}` : undefined,
213
+ more: actions,
214
+ });
215
+ });
216
+ const localSection = settingsSection({
217
+ id: "local-sync",
218
+ title: "Also install on this computer",
219
+ lead: "Mirror your enabled global skills into your local Claude Code, Codex, and Gemini CLI folders. Toolroll only writes into tools detected on this computer and never touches your own skills.",
220
+ body: joinHtml(localToolCards),
221
+ });
222
+ return joinHtml([
223
+ options.said ? notice(options.said) : "",
224
+ options.error ? notice(options.error) : "",
225
+ globalSection,
226
+ localSection,
227
+ ]);
228
+ }
package/dist/store.js CHANGED
@@ -40,6 +40,7 @@ import { V181_REQUIRED_COLUMNS, V181_SCHEMA, V181_STEPS, V181_TABLES, V182_REQUI
40
40
  import { V177_STEPS, V177_SCHEMA, V177_OBJECTS, WORKSPACE_ID_PATTERN, RECOVERY_GENERATION_PATTERN } from "./workspace-identity-schema.js";
41
41
  import { V174_OBJECTS, V174_SCHEMA, V174_STEPS } from "./flexible-everyday-schema.js";
42
42
  import { V185_OBJECTS, V185_SCHEMA, V185_STEPS } from "./flexible-conversation-schema.js";
43
+ import { V186_OBJECTS, V186_SCHEMA, V186_STEPS } from "./skill-library-schema.js";
43
44
  import { endThreadAuthorityFor } from "./flexible-authority-end.js";
44
45
  import { relayCancel } from "./flexible-relay-cancel.js";
45
46
  import { endLapsedFlexible } from "./flexible.js";
@@ -846,7 +847,7 @@ export function checkSuitesOf(value) {
846
847
  }
847
848
  }
848
849
  const REGISTERED_AT_FILING = "again, as it was filed";
849
- export const SCHEMA_VERSION = 185;
850
+ export const SCHEMA_VERSION = 186;
850
851
  export const V179_STEPS = Object.freeze(["antigravity-provider"]);
851
852
  export const V118_MERGED_TABLES = Object.freeze({ api_token: "person", coordinator_credential: "coordinator", lead_credential: "lead" });
852
853
  const V118_REFERENCES = /REFERENCES (?:coordinator_credential\(cid\)|api_token\(id\))/g;
@@ -912,7 +913,7 @@ export const V115_DROPPED_TABLES = Object.freeze([
912
913
  "fallback_config", "fallback_cycle", "fallback_transition",
913
914
  ]);
914
915
  const V115_DROPPED_REFERENCES = /\s+REFERENCES (?:contestant|contest|tournament_terms|session_turn|attended_authorization|held_session|fallback_cycle|fallback_config|fallback_transition|routine|routine_fire)\(id\)(?: ON DELETE CASCADE)?/g;
915
- export const UPDATE_SAFE_MIGRATIONS = Object.freeze([108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185]);
916
+ export const UPDATE_SAFE_MIGRATIONS = Object.freeze([108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186]);
916
917
  export const V119_ADDED_COLUMNS = Object.freeze({
917
918
  task_ref: { planning_generation: { definition: "INTEGER NOT NULL DEFAULT 0", saved: "0" } },
918
919
  run: { planning_generation: { definition: "INTEGER NOT NULL DEFAULT 0", saved: "0" } },
@@ -1455,7 +1456,7 @@ export { V156_STEPS };
1455
1456
  export { V157_STEPS };
1456
1457
  export { V158_STEPS };
1457
1458
  export { V159_STEPS };
1458
- export { V160_STEPS, V161_STEPS, V162_STEPS, V163_STEPS, V164_STEPS, V165_STEPS, V166_STEPS, V167_STEPS, V168_STEPS, V169_STEPS, V170_STEPS, V171_STEPS, V172_STEPS, V173_STEPS, V174_STEPS, V175_STEPS, V176_STEPS, V177_STEPS, V178_STEPS, V180_STEPS, V181_STEPS, V182_STEPS, V183_STEPS, V184_STEPS, V185_STEPS };
1459
+ export { V160_STEPS, V161_STEPS, V162_STEPS, V163_STEPS, V164_STEPS, V165_STEPS, V166_STEPS, V167_STEPS, V168_STEPS, V169_STEPS, V170_STEPS, V171_STEPS, V172_STEPS, V173_STEPS, V174_STEPS, V175_STEPS, V176_STEPS, V177_STEPS, V178_STEPS, V180_STEPS, V181_STEPS, V182_STEPS, V183_STEPS, V184_STEPS, V185_STEPS, V186_STEPS };
1459
1460
  export const RELEASE_ONCE_SCHEMA = `
1460
1461
  CREATE TABLE IF NOT EXISTS release_authority (
1461
1462
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -4244,7 +4245,7 @@ function initializeStore(db, file, options = {}) {
4244
4245
  throw new Error(`${file}: ${problem}; refusing to move chat history it cannot name`);
4245
4246
  }
4246
4247
  if (preflight === SCHEMA_VERSION && !findingSourcesStale(db)) {
4247
- const missing = codeMapShapeProblem(db) ?? viewPreferenceShapeProblem(db) ?? flexibleTermsShapeProblem(db) ?? flexibleThreadShapeProblem(db) ?? typedByPersonShapeProblem(db) ?? flexibleTurnsShapeProblem(db) ?? flexibleLaunchShapeProblem(db) ?? flexibleRelayShapeProblem(db) ?? flexibleAnswersShapeProblem(db) ?? flexibleShipShapeProblem(db) ?? taskSizingShapeProblem(db) ?? agentSaidShapeProblem(db) ?? flexibleSettingShapeProblem(db) ?? flexibleSignInShapeProblem(db) ?? planProblemsShapeProblem(db) ?? flexibleEverydayShapeProblem(db) ?? flexibleInteractiveShapeProblem(db) ?? subagentBackupShapeProblem(db) ?? workspaceIdentityShapeProblem(db) ?? pendingAgentChangeShapeProblem(db) ?? directChatShapeProblem(db) ?? directChatPhase1bShapeProblem(db) ?? directChatHardeningShapeProblem(db) ?? flexibleConversationShapeProblem(db);
4248
+ const missing = codeMapShapeProblem(db) ?? viewPreferenceShapeProblem(db) ?? flexibleTermsShapeProblem(db) ?? flexibleThreadShapeProblem(db) ?? typedByPersonShapeProblem(db) ?? flexibleTurnsShapeProblem(db) ?? flexibleLaunchShapeProblem(db) ?? flexibleRelayShapeProblem(db) ?? flexibleAnswersShapeProblem(db) ?? flexibleShipShapeProblem(db) ?? taskSizingShapeProblem(db) ?? agentSaidShapeProblem(db) ?? flexibleSettingShapeProblem(db) ?? flexibleSignInShapeProblem(db) ?? planProblemsShapeProblem(db) ?? flexibleEverydayShapeProblem(db) ?? flexibleInteractiveShapeProblem(db) ?? subagentBackupShapeProblem(db) ?? workspaceIdentityShapeProblem(db) ?? pendingAgentChangeShapeProblem(db) ?? directChatShapeProblem(db) ?? directChatPhase1bShapeProblem(db) ?? directChatHardeningShapeProblem(db) ?? flexibleConversationShapeProblem(db) ?? skillLibraryShapeProblem(db);
4248
4249
  if (missing !== null)
4249
4250
  throw new Error(`${file}: refusing to open — ${missing}, though the schema says v${SCHEMA_VERSION}`);
4250
4251
  db.exec("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;");
@@ -4734,6 +4735,11 @@ CREATE INDEX IF NOT EXISTS run_checkpoint_by_task ON run_checkpoint (task_ref, i
4734
4735
  if (conversationDamaged !== null)
4735
4736
  throw new Error(`${file}: refusing to open — ${conversationDamaged}`);
4736
4737
  step("flexible-conversation");
4738
+ db.exec(V186_SCHEMA);
4739
+ const skillLibraryDamaged = skillLibraryShapeProblem(db);
4740
+ if (skillLibraryDamaged !== null)
4741
+ throw new Error(`${file}: refusing to open — ${skillLibraryDamaged}`);
4742
+ step("skill-library");
4737
4743
  if (!fresh)
4738
4744
  reclaimDatabase(db, "migration");
4739
4745
  const expectedMarker = preflight < 0 ? preflight : -preflight;
@@ -19690,3 +19696,15 @@ export function verifyCommandAt(store, repo, at) {
19690
19696
  .get(repo, when, when);
19691
19697
  return row === undefined ? null : { ...readVerifyCommand(row), revokedAt: null, revokedBy: null };
19692
19698
  }
19699
+ function skillLibraryShapeProblem(db) {
19700
+ const statements = V186_SCHEMA.split(/;\s*\n(?=CREATE )/).map(one => one.trim().replace(/;$/, "")).filter(one => one !== "");
19701
+ for (const [type, name] of V186_OBJECTS) {
19702
+ const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = ? AND name = ?").get(type, name);
19703
+ if (row === undefined)
19704
+ return `the skill library ${type} ${name} is missing`;
19705
+ const want = statements.find(one => new RegExp(`^CREATE (?:UNIQUE )?${type.toUpperCase()} IF NOT EXISTS ${name}\\b`).test(one));
19706
+ if (want === undefined || canonicalDdl(String(row["sql"]).replace(/;$/, "")).trim() !== canonicalDdl(want.replace(/;$/, "")).trim())
19707
+ return `the skill library ${type} ${name} has an unknown shape`;
19708
+ }
19709
+ return null;
19710
+ }
package/dist/surface.js CHANGED
@@ -309,7 +309,7 @@ const GUIDE_ROWS = [
309
309
  { name: "digest", takesValue: true, meaning: "the exact receipt from assignment show; accepts and finishes exactly that result" },
310
310
  { name: "despite", takesValue: true, meaning: "accept with this reason, without finishing; never combines with --finish or --digest (--note is its alias)" }],
311
311
  notableReasons: ["usage", "unknown-task", "no-run", "not-ready"] },
312
- { ...operator("task land", "put accepted work on the project's own branch when it has no pull requests: bare shows exactly what lands where; --yes --key <key> lands it as one new commit on top; --undo reverts that commit with a new one"),
312
+ { ...operator("task land", "put accepted work on the project's own branch when it has no pull requests: bare shows exactly what lands where; --yes --key <preview-key> lands it as one new commit on top; --undo reverts that commit with a new one"),
313
313
  positionals: [{ name: "id", required: true, meaning: "the task" }],
314
314
  flags: [jsonFlag, dbFlag, { name: "into", takesValue: true, meaning: "land on this branch instead of the recorded one (the yes records it)" },
315
315
  { name: "undo", takesValue: false, meaning: "revert the landing with a new commit on the branch" },
@@ -154,7 +154,8 @@ function sentenceOf(headline, facts) {
154
154
  return `Accepted automatically: ${facts.landed}.`;
155
155
  const by = facts.completedBy ? `Accepted by ${facts.completedBy}.` : "Accepted.";
156
156
  const pr = facts.pullRequest;
157
- return pr?.state === "merged" ? `${by} ${pr.number === null ? "Its pull request" : `Pull request #${pr.number}`} merged.` : by;
157
+ const again = facts.checks?.status === "failed" ? " Its checks failed when they ran again." : "";
158
+ return pr?.state === "merged" ? `${by} ${pr.number === null ? "Its pull request" : `Pull request #${pr.number}`} merged.${again}` : `${by}${again}`;
158
159
  }
159
160
  case "Failed":
160
161
  if (facts.checks?.status === "failed")
Binary file
Binary file
Binary file
Binary file
@@ -14,7 +14,7 @@ import { buildReviewOf } from './review-switch.js';
14
14
  import { shownVerdictOf } from './proof.js';
15
15
  import { isCheckLevel, repoClause, requiredCheckCommandFor, RUN_LEVEL_ACTION, TASK_LEVEL_ACTION } from './check-levels.js';
16
16
  import { MARKER } from './worktree.js';
17
- import { CHECKS_FINISHED, CHECKS_REQUESTED, CHECKS_STARTED, withFollowUps } from './result-follow-ups.js';
17
+ import { CHECKS_FINISHED, CHECKS_REQUESTED, CHECKS_STARTED, FOLLOW_UP_LOG, FOLLOW_UP_RECEIPT, withFollowUps } from './result-follow-ups.js';
18
18
  import { LANDED_ACTOR, landedReasonOf } from './result-completion.js';
19
19
  import { ASKS, CODE_READING, STORAGE_HOLD_PREFIX, NEED_ASK, NEEDS, askChipOf, failedAttemptSentence, isWaitCode, processNeedOf, resultHoldUpSentence } from './needs-you.js';
20
20
  import { agentlessCommand, NO_AGENT_TITLE, noAgentWords, retryWhenWords, signInAgainWords } from './dispatch.js';
@@ -212,7 +212,10 @@ const PROJECTION = `WITH RECURSIVE admitted AS MATERIALIZED (
212
212
  AND a.action IN ('task state changed','scope approved','task placed','run started','run finished')) END completion_changed,
213
213
  CASE WHEN f.ready AND EXISTS(SELECT 1 FROM action_ledger a
214
214
  WHERE a.task_id=f.root_id AND a.run_id=f.result_id AND a.action='assignment handoff checked' AND a.source='work')
215
- THEN (SELECT MAX(ar.created_at) FROM json_each(f.fam_refs) m JOIN run r ON r.task_ref=m.value JOIN artifact ar ON ar.run=r.id) END completion_artifact_at
215
+ THEN (SELECT MAX(ar.created_at) FROM json_each(f.fam_refs) m JOIN run r ON r.task_ref=m.value JOIN artifact ar ON ar.run=r.id
216
+ -- A follow-up check's own log and receipt (Run checks after accepting) are a separate check fact, never changed
217
+ -- work: assignment.ts reads the completion with the checks as they read then, so the list does too.
218
+ WHERE NOT (ar.kind='structured-output' AND ar.capture IN ('${FOLLOW_UP_LOG}','${FOLLOW_UP_RECEIPT}'))) END completion_artifact_at
216
219
  FROM ready f) f
217
220
  ), classified AS MATERIALIZED (
218
221
  SELECT f.*,CASE