@yandy-r/ycc-opencode 6.0.0 → 6.1.1

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 (63) hide show
  1. package/AGENTS.md +3 -2
  2. package/README.md +10 -1
  3. package/agents/backport-conflict-resolver.md +346 -4
  4. package/agents/db-modifier.md +346 -4
  5. package/agents/git-cleanup.md +3 -2
  6. package/agents/pr-comment-fixer.md +365 -23
  7. package/agents/release-fix-applier.md +383 -19
  8. package/agents/review-fixer.md +371 -26
  9. package/index.js +268 -5
  10. package/package.json +3 -2
  11. package/registration.json +4113 -1238
  12. package/shared/references/ci-monitoring.md +11 -1
  13. package/shared/references/goal-pairing.md +4 -2
  14. package/shared/references/question-policy.md +99 -0
  15. package/shared/references/review-dispatch.md +4 -2
  16. package/shared/references/standalone-dispatch.md +4 -2
  17. package/shared/references/target-capability-matrix.md +227 -36
  18. package/shared/references/worktree-strategy.md +20 -4
  19. package/shared/scripts/worktree-paths.sh +7 -2
  20. package/skills/backport/SKILL.md +2 -0
  21. package/skills/blueprint/SKILL.md +2 -0
  22. package/skills/bundle-author/SKILL.md +2 -0
  23. package/skills/bundle-release/SKILL.md +11 -7
  24. package/skills/bundle-release/references/release-checklist.md +4 -4
  25. package/skills/bundle-release/references/version-policy.md +21 -15
  26. package/skills/bundle-release/scripts/bump-version.sh +5 -3
  27. package/skills/bundle-release/scripts/draft-notes.sh +1 -1
  28. package/skills/bundle-release/scripts/preflight.sh +2 -1
  29. package/skills/bundle-release/scripts/release_versions.py +21 -7
  30. package/skills/clean/SKILL.md +2 -0
  31. package/skills/code-report/SKILL.md +2 -0
  32. package/skills/code-review/SKILL.md +2 -0
  33. package/skills/compatibility-audit/SKILL.md +9 -6
  34. package/skills/compatibility-audit/references/reading-the-report.md +4 -1
  35. package/skills/compatibility-audit/scripts/audit-install-assumptions.sh +71 -12
  36. package/skills/compatibility-audit/scripts/audit-target-features.sh +58 -20
  37. package/skills/feature-research/SKILL.md +2 -0
  38. package/skills/formatters/SKILL.md +2 -0
  39. package/skills/git-cleanup/SKILL.md +19 -5
  40. package/skills/git-cleanup/references/active-code-rules.md +8 -3
  41. package/skills/git-workflow/SKILL.md +2 -0
  42. package/skills/implement-plan/SKILL.md +2 -0
  43. package/skills/init/SKILL.md +2 -0
  44. package/skills/init/templates/git/gitignore.tmpl +1 -0
  45. package/skills/plan/SKILL.md +2 -0
  46. package/skills/plan-workflow/SKILL.md +4 -1
  47. package/skills/pr-autofix/SKILL.md +2 -0
  48. package/skills/prp-implement/SKILL.md +2 -0
  49. package/skills/prp-plan/SKILL.md +2 -2
  50. package/skills/prp-pr/SKILL.md +2 -0
  51. package/skills/prp-prd/SKILL.md +2 -0
  52. package/skills/prp-spec/SKILL.md +2 -0
  53. package/skills/quick-review/SKILL.md +5 -3
  54. package/skills/release-model/SKILL.md +2 -0
  55. package/skills/releaser/SKILL.md +2 -0
  56. package/skills/research-to-issues/SKILL.md +2 -0
  57. package/skills/resume-session/SKILL.md +2 -0
  58. package/skills/review-fix/SKILL.md +11 -9
  59. package/skills/save-session/SKILL.md +2 -0
  60. package/ycc-sensitive-guard/index.js +621 -0
  61. package/ycc-sensitive-guard/package.json +7 -0
  62. package/ycc-sensitive-guard/policy.json +40 -0
  63. package/skills/prp-plan/scripts/preflight-enhanced-agents.sh +0 -111
@@ -0,0 +1,621 @@
1
+ // ycc sensitive-file guard: OpenCode V2 plugin for restricted ycc specialists.
2
+ //
3
+ // Copied verbatim as index.js by scripts/opencode_sensitive_policy.py, beside
4
+ // policy.json (a copy of ycc/settings/sensitive-files.json), into the bundle's
5
+ // own ycc-sensitive-guard unit. The file-copy install loads it through the
6
+ // managed `plugins` entry "./ycc-sensitive-guard"; the experimental npm
7
+ // package ships the same directory and calls its setup from its own setup.
8
+ //
9
+ // Only agents in policy.restricted_agents are affected. For them:
10
+ // - execute.before rejects read/edit/write/patch targets, grep/glob search
11
+ // roots, a grep `include` naming a sensitive file, and shell commands or
12
+ // workdirs whose arguments name a sensitive path. Paths are resolved
13
+ // against the calling session's location (ctx.session.get, falling back
14
+ // to the plugin's setup location; with neither, the call is rejected),
15
+ // `~` expands to the home directory, and
16
+ // existing paths are also checked through realpath so a symlink to a
17
+ // sensitive file is treated as that file.
18
+ // - execute.after removes sensitive files from grep and glob results and
19
+ // rebuilds the model-facing text, so a directory-wide search returns
20
+ // neither their names nor their content.
21
+ // - Search runs only through this plugin. Built-in grep/glob permissions
22
+ // are keyed by the search pattern, so native path rules cannot cover
23
+ // them; the generated restricted agents allow `ycc_grep`/`ycc_glob`
24
+ // instead of `grep`/`glob`. This plugin registers those tools by reusing
25
+ // the built-in definitions, applies the checks above inside them, and
26
+ // runs the built-in implementation as a hidden internal agent that may
27
+ // only search. A context hook shows them to restricted agents under the
28
+ // built-in names. When this plugin is not loaded, restricted agents have
29
+ // no search tool at all (fail closed).
30
+ // Shell checks inspect the command text only. Build, test, and interpreter
31
+ // commands execute project code, which this guard does not and cannot bound.
32
+ //
33
+ // Contract (opencode v2.0.32 tag sources):
34
+ // - Default export { id, setup } (packages/core/src/plugin/module.ts).
35
+ // - ctx.tool.hook("execute.before" | "execute.after", callback): events carry
36
+ // { tool, sessionID, agent, messageID, id, input } and, after a completed
37
+ // call, a mutable `result` { output?, content, metadata? }
38
+ // (packages/plugin/src/effect/tool.ts). Only execute.before may fail; a
39
+ // thrown error rejects that call before it runs
40
+ // (packages/plugin/src/promise/adapter.ts toolHook). execute.before sees
41
+ // the name the model called, execute.after the registered tool name
42
+ // (packages/core/src/tool.ts snapshot execute).
43
+ // - grep/glob output paths are relative to the session location; their
44
+ // model content lists absolute paths (packages/core/src/tool/plugin/grep.ts,
45
+ // glob.ts toModelContent). Both assert their own action name against
46
+ // context.agent (grep.ts, glob.ts permission.assert).
47
+ // - ctx.tool.transform editor.get(id) returns a registered tool with a
48
+ // promise-returning execute; editor.add registers a tool whose visibility
49
+ // is gated by the permission action equal to its name
50
+ // (packages/plugin/src/promise/adapter.ts, packages/core/src/tool.ts
51
+ // snapshot/whollyDisabled).
52
+ // - ctx.session.hook("context") may move a tool definition to another key;
53
+ // the core maps it back to the registered tool by object identity
54
+ // (packages/plugin/src/promise/session.ts SessionContext,
55
+ // packages/core/src/session/model-request.ts).
56
+ // - `hidden` keeps an agent out of default selection and the subagent
57
+ // catalog, and the subagent tool refuses a `primary` agent
58
+ // (packages/core/src/agent.ts selectable, tool/plugin/subagent.ts). Such
59
+ // an agent is still listed by /api/agent and a client can select it.
60
+ // - ctx.permission.assert(input) evaluates the given agent's rules, prompts
61
+ // on `ask`, and rejects on deny or a declined prompt
62
+ // (packages/plugin/src/promise/permission.ts). Built-in search asks
63
+ // `external_directory` for a root outside both the session directory and
64
+ // the project worktree (the nearest `.git`/`.hg` ancestor), with resource
65
+ // `<directory>/*`; grep judges a file root by its parent, glob always
66
+ // treats the root as a directory (packages/core/src/file-access.ts
67
+ // resolve/authorizeExternal, project.ts resolve, tool/plugin/grep.ts,
68
+ // glob.ts). ctx.permission.hook("evaluate") may change an allow/ask
69
+ // effect; its event carries the request's `source` { messageID, id }.
70
+ // - ctx.session.get({ sessionID }) resolves { data: Session.Info } whose
71
+ // `location.directory` is the session's absolute directory
72
+ // (packages/protocol/src/groups/session.ts "session.get",
73
+ // packages/plugin/src/promise/adapter.ts); hooks may return promises.
74
+
75
+ import { fileURLToPath } from "node:url";
76
+ import { homedir } from "node:os";
77
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
78
+ import { lstatSync, readdirSync, readFileSync, readlinkSync, statSync } from "node:fs";
79
+
80
+ const POLICY = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "policy.json"), "utf8"));
81
+ const BLOCKED = "blocked by ycc sensitive-file guard: this specialist may not access secret-bearing files";
82
+ // Built-in search tool -> guarded tool restricted agents are granted
83
+ // (mirrors GUARDED_SEARCH_TOOLS in scripts/opencode_sensitive_policy.py).
84
+ const GUARDED_SEARCH = { grep: "ycc_grep", glob: "ycc_glob" };
85
+ const SEARCH_BASE = Object.fromEntries(Object.entries(GUARDED_SEARCH).map(([base, name]) => [name, base]));
86
+ // Internal agent the guarded tools run the built-in implementation as. It may
87
+ // only search. Every check that depends on the caller (its own search and
88
+ // external-directory rules) is made as the calling agent before delegating,
89
+ // so the helper allows external directories; host-wide rules appended after
90
+ // its own can still deny them. execute.before rejects any tool call made by
91
+ // it directly; the delegated call does not pass through tool hooks.
92
+ const SEARCH_AGENT = "ycc-sensitive-search";
93
+ const SEARCH_AGENT_RULES = [
94
+ { action: "*", resource: "*", effect: "deny" },
95
+ { action: "grep", resource: "*", effect: "allow" },
96
+ { action: "glob", resource: "*", effect: "allow" },
97
+ { action: "external_directory", resource: "*", effect: "allow" },
98
+ ];
99
+
100
+ function globRegExp(glob) {
101
+ let source = "";
102
+ for (const character of glob) {
103
+ if (character === "*") source += "[^/]*";
104
+ else if (character === "?") source += "[^/]";
105
+ else source += character.replace(/[.+^${}()|[\]\\]/g, "\\$&");
106
+ }
107
+ return new RegExp(`^${source}$`, "i");
108
+ }
109
+
110
+ const RESTRICTED = new Set(POLICY.restricted_agents);
111
+ // Allow exceptions (`*.env.example`) only lift the .env-family patterns (every
112
+ // basename pattern containing `.env`); a name that also matches another
113
+ // basename pattern (`id_rsa.env.example`) stays denied.
114
+ const NAME_PATTERNS = POLICY.patterns.filter((pattern) => !pattern.includes("/"));
115
+ const ENV_NAMES = NAME_PATTERNS.filter((pattern) => pattern.includes(".env")).map(globRegExp);
116
+ const OTHER_NAMES = NAME_PATTERNS.filter((pattern) => !pattern.includes(".env")).map(globRegExp);
117
+ const DIRECTORIES = POLICY.patterns
118
+ .filter((pattern) => pattern.endsWith("/"))
119
+ .map((pattern) => pattern.slice(0, -1).toLowerCase());
120
+ const SUFFIXES = POLICY.patterns
121
+ .filter((pattern) => pattern.includes("/") && !pattern.endsWith("/"))
122
+ .map((pattern) => pattern.toLowerCase().split("/"));
123
+ const ALLOW = POLICY.allow.map(globRegExp);
124
+
125
+ function segments(path) {
126
+ return path.split(/[\\/]+/).filter(Boolean);
127
+ }
128
+
129
+ // Lexical policy match on one absolute or relative path.
130
+ function matches(path) {
131
+ const parts = segments(path);
132
+ if (parts.length === 0) return false;
133
+ const lower = parts.map((part) => part.toLowerCase());
134
+ if (lower.some((part) => DIRECTORIES.includes(part))) return true;
135
+ if (SUFFIXES.some((suffix) => suffix.every((part, index) => lower.at(index - suffix.length) === part))) return true;
136
+ const name = parts.at(-1);
137
+ if (OTHER_NAMES.some((pattern) => pattern.test(name))) return true;
138
+ return ENV_NAMES.some((pattern) => pattern.test(name)) && !ALLOW.some((pattern) => pattern.test(name));
139
+ }
140
+
141
+ function expandHome(value) {
142
+ if (value === "~") return homedir();
143
+ if (value.startsWith("~/")) return join(homedir(), value.slice(2));
144
+ return value;
145
+ }
146
+
147
+ // Physical path: every existing symlink component is replaced by its target,
148
+ // including a dangling link whose target does not exist yet, so a write
149
+ // through a link to a sensitive path is judged by that path.
150
+ function canonical(absolute) {
151
+ let pending = segments(absolute);
152
+ let current = sep;
153
+ let hops = 0;
154
+ while (pending.length > 0) {
155
+ const part = pending.shift();
156
+ const next = join(current, part);
157
+ let link = null;
158
+ try {
159
+ if (lstatSync(next).isSymbolicLink() && hops < 40) link = readlinkSync(next);
160
+ } catch {
161
+ link = null;
162
+ }
163
+ if (link === null) {
164
+ current = next;
165
+ continue;
166
+ }
167
+ hops += 1;
168
+ if (isAbsolute(link)) current = sep;
169
+ pending = [...segments(link), ...pending];
170
+ }
171
+ return current;
172
+ }
173
+
174
+ function sensitive(value, base) {
175
+ if (typeof value !== "string" || value === "") return false;
176
+ const absolute = resolve(base, expandHome(value));
177
+ return matches(absolute) || matches(canonical(absolute));
178
+ }
179
+
180
+ const GLOB = /[*?[]/;
181
+
182
+ // Expand one shell glob argument against the filesystem (bash semantics:
183
+ // a leading `*`/`?` does not match dotfiles).
184
+ function globHits(word, base) {
185
+ const absolute = resolve(base, expandHome(word));
186
+ const parts = segments(absolute);
187
+ let candidates = [isAbsolute(absolute) ? sep : base];
188
+ for (const part of parts) {
189
+ const next = [];
190
+ for (const directory of candidates) {
191
+ if (!GLOB.test(part)) {
192
+ next.push(join(directory, part));
193
+ continue;
194
+ }
195
+ const pattern = globRegExp(part.replace(/\[[^\]]*\]/g, "?"));
196
+ let entries = [];
197
+ try {
198
+ entries = readdirSync(directory);
199
+ } catch {
200
+ continue;
201
+ }
202
+ for (const entry of entries) {
203
+ if (entry.startsWith(".") && !part.startsWith(".")) continue;
204
+ if (pattern.test(entry)) next.push(join(directory, entry));
205
+ }
206
+ }
207
+ candidates = next.slice(0, 2000);
208
+ }
209
+ return candidates;
210
+ }
211
+
212
+ // Every path-like fragment of a command: whole words with quotes removed,
213
+ // fragments between shell or language punctuation, option values, and the
214
+ // text after each `:` (git object names such as `HEAD:.env` or `:0:.env`).
215
+ function shellWords(command) {
216
+ const words = new Set();
217
+ for (const raw of command.split(/[\s;&|()<>`{}]+/)) {
218
+ const word = raw.replace(/["'\\$]/g, "");
219
+ if (word) words.add(word);
220
+ for (const fragment of raw.split(/[^A-Za-z0-9._~/*?[\]@%+:-]+/)) if (fragment) words.add(fragment);
221
+ }
222
+ for (const word of [...words]) {
223
+ const option = word.match(/^-{1,2}[A-Za-z0-9-]+=(.+)$/) ?? word.match(/^[A-Za-z_][A-Za-z0-9_]*=(.+)$/);
224
+ if (option) words.add(option[1]);
225
+ }
226
+ for (const word of [...words]) {
227
+ for (let index = word.indexOf(":"); index !== -1; index = word.indexOf(":", index + 1)) {
228
+ const rest = word.slice(index + 1);
229
+ if (rest) words.add(rest);
230
+ }
231
+ }
232
+ return [...words];
233
+ }
234
+
235
+ // Shell text the word scan cannot resolve to file names: brace lists and
236
+ // sequences (`.{e,x}nv`, `{a..z}`, quoted elements included), every `$` form
237
+ // (parameter expansion such as `$HOME`/`${PWD}`, `$(…)`, ANSI-C `$'\x2e'`),
238
+ // backtick substitution, and tilde prefixes other than `~` and `~/`
239
+ // (`~user`, `~+`, `~-`, also after `=` or `:`). `git diff --no-index`
240
+ // compares arbitrary directories (gitignored dotfiles included), so it is
241
+ // refused outright.
242
+ const AMBIGUOUS_SHELL = [
243
+ /\{[^{}]*(?:,|\.\.)[^{}]*\}/,
244
+ /[$`]/,
245
+ /(?:^|[\s=:;&|()<>"'])~(?![/\s;&|()<>"']|$)/,
246
+ /--no-index\b/,
247
+ ];
248
+
249
+ function outside(path, root) {
250
+ const fromRoot = relative(root, path);
251
+ return fromRoot === ".." || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot);
252
+ }
253
+
254
+ // git switches to no-index mode on its own when a path argument lies outside
255
+ // the worktree or it runs outside a repository, and -C/-c/--git-dir/
256
+ // --work-tree (or GIT_DIR/GIT_WORK_TREE) retarget it. A restricted agent's git
257
+ // commands therefore stay inside the session root: no retargeting, no
258
+ // directory (workdir or an earlier `cd`) outside it, and no argument that
259
+ // resolves outside it. Shell expansions are already refused (AMBIGUOUS_SHELL).
260
+ function gitEscapes(command, workdir, root) {
261
+ let cwd = workdir;
262
+ for (const simple of command.split(/[;&|()\n`]+/)) {
263
+ const words = simple
264
+ .trim()
265
+ .split(/\s+/)
266
+ .map((word) => word.replace(/["'\\]/g, ""))
267
+ .filter(Boolean);
268
+ let retargeted = false;
269
+ while (words.length > 0 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[0])) {
270
+ if (/^GIT_/.test(words.shift())) retargeted = true;
271
+ }
272
+ if (words.length === 0) continue;
273
+ const program = basename(words[0]);
274
+ if (program === "cd" || program === "pushd") {
275
+ const target = words.slice(1).find((word) => !word.startsWith("-"));
276
+ cwd = resolve(cwd, expandHome(target ?? "~"));
277
+ continue;
278
+ }
279
+ if (program !== "git") continue;
280
+ if (retargeted || outside(cwd, root) || outside(canonical(cwd), canonical(root))) return true;
281
+ let subcommand = false;
282
+ for (const word of words.slice(1)) {
283
+ if (word.startsWith("-")) {
284
+ // Options before the subcommand are git's own; after it, `-C`/`-c`
285
+ // mean copy detection / combined diffs.
286
+ if (!subcommand && /^(?:-C|-c|--git-dir|--work-tree)/.test(word)) return true;
287
+ continue;
288
+ }
289
+ subcommand = true;
290
+ const path = resolve(cwd, expandHome(word));
291
+ if (outside(path, root) || outside(canonical(path), canonical(root))) return true;
292
+ }
293
+ }
294
+ return false;
295
+ }
296
+
297
+ function shellBlocked(input, root) {
298
+ const workdir = typeof input.workdir === "string" && input.workdir ? resolve(root, expandHome(input.workdir)) : root;
299
+ if (workdir !== root && sensitive(workdir, root)) return true;
300
+ const command = typeof input.command === "string" ? input.command : "";
301
+ if (AMBIGUOUS_SHELL.some((pattern) => pattern.test(command))) return true;
302
+ if (gitEscapes(command, workdir, root)) return true;
303
+ for (const word of shellWords(command)) {
304
+ if (sensitive(word, workdir)) return true;
305
+ if (GLOB.test(word) && globHits(word, workdir).some((hit) => sensitive(hit, workdir))) return true;
306
+ }
307
+ return false;
308
+ }
309
+
310
+ // The core trims each patch line before matching its file headers.
311
+ function patchPaths(text) {
312
+ if (typeof text !== "string") return [];
313
+ return [...text.matchAll(/^\s*\*\*\* (?:Add File|Update File|Delete File|Move to):[ \t]*(.+?)\s*$/gm)].map(
314
+ (match) => match[1],
315
+ );
316
+ }
317
+
318
+ // The read tool falls back to one sibling whose name matches after this
319
+ // normalization when the requested path does not exist.
320
+ function lookAlike(name) {
321
+ return name.normalize("NFC").replace(/[\u00a0\u202f]/g, " ").replace(/[\u2018\u2019]/g, "'");
322
+ }
323
+
324
+ function readBlocked(path, root) {
325
+ if (sensitive(path, root)) return true;
326
+ if (typeof path !== "string" || path === "") return false;
327
+ const absolute = resolve(root, expandHome(path));
328
+ try {
329
+ lstatSync(absolute);
330
+ return false;
331
+ } catch {
332
+ // Missing: check every sibling the fallback could pick instead.
333
+ }
334
+ const wanted = lookAlike(basename(absolute));
335
+ let entries = [];
336
+ try {
337
+ entries = readdirSync(dirname(absolute));
338
+ } catch {
339
+ return false;
340
+ }
341
+ return entries.some((entry) => lookAlike(entry) === wanted && sensitive(join(dirname(absolute), entry), root));
342
+ }
343
+
344
+ function includeBlocked(include, root) {
345
+ if (typeof include !== "string" || include === "") return false;
346
+ const last = include.split("/").at(-1);
347
+ if (GLOB.test(last) || /[{}!]/.test(last)) return false;
348
+ return sensitive(last, root);
349
+ }
350
+
351
+ function blocked(tool, input, root) {
352
+ const args = input && typeof input === "object" ? input : {};
353
+ switch (SEARCH_BASE[tool] ?? tool) {
354
+ case "read":
355
+ return readBlocked(args.path, root);
356
+ case "edit":
357
+ case "write":
358
+ return sensitive(args.path, root);
359
+ case "patch":
360
+ return patchPaths(args.patchText).some((path) => sensitive(path, root));
361
+ case "grep":
362
+ return sensitive(args.path ?? ".", root) || includeBlocked(args.include, root);
363
+ case "glob":
364
+ return sensitive(args.path ?? ".", root);
365
+ case "shell":
366
+ return shellBlocked(args, root);
367
+ default:
368
+ return false;
369
+ }
370
+ }
371
+
372
+ const TRUNCATED = (count) =>
373
+ `(Results are truncated: showing first ${count} results. Consider using a more specific path or pattern.)`;
374
+
375
+ function grepContent(matches, root, truncated) {
376
+ const lines = matches.length === 0 ? ["No matches found"] : [`Found ${matches.length} matches`];
377
+ let current = "";
378
+ for (const match of matches) {
379
+ const path = resolve(root, match.entry.path);
380
+ if (current !== path) {
381
+ if (current) lines.push("");
382
+ current = path;
383
+ lines.push(`${path}:`);
384
+ }
385
+ lines.push(` Line ${match.line}: ${match.text}`);
386
+ }
387
+ if (truncated) lines.push("", TRUNCATED(matches.length));
388
+ return lines.join("\n");
389
+ }
390
+
391
+ function globContent(entries, root, truncated) {
392
+ const lines = entries.length === 0 ? ["No files found"] : entries.map((entry) => resolve(root, entry.path));
393
+ if (truncated) lines.push("", TRUNCATED(entries.length));
394
+ return lines.join("\n");
395
+ }
396
+
397
+ function filterResult(tool, result, root) {
398
+ const metadata = result.metadata ?? {};
399
+ const truncated = metadata.truncated === true;
400
+ if (!Array.isArray(result.output)) {
401
+ // Unknown result shape: withhold it rather than pass raw text through.
402
+ result.content = "Search results withheld by ycc sensitive-file guard.";
403
+ return;
404
+ }
405
+ if (tool === "grep") {
406
+ const kept = result.output.filter((match) => !sensitive(match?.entry?.path, root));
407
+ result.output = kept;
408
+ result.content = grepContent(kept, root, truncated);
409
+ result.metadata = { ...metadata, matches: kept.length };
410
+ } else {
411
+ const kept = result.output.filter((entry) => !sensitive(entry?.path, root));
412
+ result.output = kept;
413
+ result.content = globContent(kept, root, truncated);
414
+ result.metadata = { ...metadata, count: kept.length };
415
+ }
416
+ }
417
+
418
+ function absoluteDirectory(value) {
419
+ return typeof value === "string" && isAbsolute(value) ? value : undefined;
420
+ }
421
+
422
+ // The session's own location, not the server's: a session created or moved
423
+ // to another directory resolves tool paths there. Order: a location carried on
424
+ // the event, then session.get(sessionID), then the plugin's setup location.
425
+ // Undefined when none is usable.
426
+ async function sessionRoot(ctx, event) {
427
+ const carried = absoluteDirectory(event.location?.directory);
428
+ if (carried) return carried;
429
+ try {
430
+ const session = await ctx.session?.get?.({ sessionID: event.sessionID });
431
+ const directory = absoluteDirectory((session?.data ?? session)?.location?.directory);
432
+ if (directory) return directory;
433
+ } catch {
434
+ // Fall through to the setup location.
435
+ }
436
+ return absoluteDirectory(ctx.location?.directory);
437
+ }
438
+
439
+ // Nearest ancestor holding `.git` or `.hg`: the project worktree the host
440
+ // treats as internal (core/src/project.ts resolve). The filesystem root never
441
+ // counts, as in core/src/file-access.ts resolve.
442
+ function projectDirectory(start) {
443
+ let current = start;
444
+ while (true) {
445
+ for (const marker of [".git", ".hg"]) {
446
+ try {
447
+ lstatSync(join(current, marker));
448
+ return dirname(current) === current ? undefined : current;
449
+ } catch {
450
+ // Not here; keep walking up.
451
+ }
452
+ }
453
+ const parent = dirname(current);
454
+ if (parent === current) return undefined;
455
+ current = parent;
456
+ }
457
+ }
458
+
459
+ // The `external_directory` request the built-in makes for this search root
460
+ // (`<directory>/*`), or undefined when the root is inside the session
461
+ // directory or its project. Made for the calling agent instead of the helper;
462
+ // an "always" reply saves only that directory.
463
+ function externalDirectory(base, path, root) {
464
+ const target = resolve(root, expandHome(typeof path === "string" ? path : "."));
465
+ if (!outside(target, root)) return undefined;
466
+ const project = projectDirectory(root);
467
+ if (project && !outside(target, project)) return undefined;
468
+ let directory = target;
469
+ if (base === "grep") {
470
+ directory = dirname(target);
471
+ try {
472
+ if (statSync(target).isDirectory()) directory = target;
473
+ } catch {
474
+ // A missing root is judged by its parent, as the built-in does.
475
+ }
476
+ }
477
+ return join(directory, "*").replaceAll("\\", "/");
478
+ }
479
+
480
+ // The metadata the built-in attaches to its own search permission request.
481
+ function searchMetadata(base, input) {
482
+ const args = input && typeof input === "object" ? input : {};
483
+ if (base === "grep") {
484
+ return {
485
+ root: ".",
486
+ path: args.path,
487
+ include: args.include,
488
+ literal: args.literal,
489
+ caseSensitive: args.caseSensitive,
490
+ limit: args.limit,
491
+ };
492
+ }
493
+ return { root: args.path ?? ".", path: args.path, hidden: args.hidden, limit: args.limit };
494
+ }
495
+
496
+ // Guarded calls in flight whose caller approved an external directory:
497
+ // `${sessionID}\0${callID}` -> approved resource. The built-in then asks the
498
+ // helper for the same directory, which would prompt the user a second time.
499
+ const APPROVED = new Map();
500
+
501
+ function approvalKey(sessionID, id) {
502
+ return `${sessionID}\u0000${id}`;
503
+ }
504
+
505
+ // Guarded search for restricted agents: the built-in grep/glob definition and
506
+ // implementation, run as SEARCH_AGENT after the caller's own permission
507
+ // checks, the same root checks the hooks apply, and with the same result
508
+ // filtering. A host without the built-in gets no guarded tool, so the
509
+ // restricted agent simply has no search (fail closed).
510
+ async function registerSearchTools(ctx) {
511
+ await ctx.agent.transform((editor) => {
512
+ editor.update(SEARCH_AGENT, (agent) => {
513
+ agent.name = SEARCH_AGENT;
514
+ agent.description = "Internal: runs guarded searches for restricted ycc specialists.";
515
+ // Checked on an isolated v2.0.32 host: as a hidden `subagent` it could
516
+ // still be started by name through the subagent tool; as `primary` the
517
+ // tool rejects it ("cannot run as a subagent"). Explicit client
518
+ // selection remains possible, so execute.before also rejects its calls.
519
+ agent.mode = "primary";
520
+ agent.hidden = true;
521
+ agent.permissions = structuredClone(SEARCH_AGENT_RULES);
522
+ });
523
+ });
524
+ await ctx.tool.transform((editor) => {
525
+ for (const [base, name] of Object.entries(GUARDED_SEARCH)) {
526
+ const builtin = editor.get(base);
527
+ if (!builtin || typeof builtin.execute !== "function") continue;
528
+ editor.add({
529
+ name,
530
+ description: builtin.description,
531
+ input: builtin.input,
532
+ output: builtin.output,
533
+ options: { codemode: false },
534
+ execute: async (input, context) => {
535
+ if (!RESTRICTED.has(context.agent)) throw new Error(`${name} is reserved for restricted ycc specialists`);
536
+ const root = await sessionRoot(ctx, { sessionID: context.sessionID });
537
+ if (!root || blocked(base, input, root)) throw new Error(BLOCKED);
538
+ const caller = {
539
+ sessionID: context.sessionID,
540
+ agent: context.agent,
541
+ source: { type: "tool", messageID: context.messageID, id: context.id },
542
+ };
543
+ const external = externalDirectory(base, input?.path, root);
544
+ if (external) {
545
+ await ctx.permission.assert({ action: "external_directory", resources: [external], save: [external], ...caller });
546
+ }
547
+ await ctx.permission.assert({
548
+ action: name,
549
+ resources: [String(input?.pattern)],
550
+ save: ["*"],
551
+ metadata: searchMetadata(base, input),
552
+ ...caller,
553
+ });
554
+ const key = approvalKey(context.sessionID, context.id);
555
+ if (external) APPROVED.set(key, external);
556
+ try {
557
+ const result = await builtin.execute(input, { ...context, agent: SEARCH_AGENT });
558
+ filterResult(base, result, root);
559
+ return result;
560
+ } finally {
561
+ APPROVED.delete(key);
562
+ }
563
+ },
564
+ });
565
+ }
566
+ });
567
+ // The caller already approved this directory for this call: the helper's
568
+ // identical request is not asked again. Only an `ask` for exactly that
569
+ // resource, from the in-flight call, is changed; a deny never is.
570
+ await ctx.permission.hook("evaluate", (event) => {
571
+ if (event.agent !== SEARCH_AGENT || event.action !== "external_directory" || event.effect !== "ask") return;
572
+ const approved = APPROVED.get(approvalKey(event.sessionID, event.source?.id));
573
+ if (approved && event.resources.length > 0 && event.resources.every((resource) => resource === approved)) {
574
+ event.effect = "allow";
575
+ }
576
+ });
577
+ // Model-facing names stay grep/glob for restricted agents; a built-in the
578
+ // host still offers under that name is never shadowed. Other agents are
579
+ // never offered the guarded tools, which reject them anyway.
580
+ await ctx.session.hook("context", (event) => {
581
+ if (!RESTRICTED.has(event.agent)) {
582
+ for (const name of Object.values(GUARDED_SEARCH)) delete event.tools[name];
583
+ return;
584
+ }
585
+ for (const [base, name] of Object.entries(GUARDED_SEARCH)) {
586
+ const definition = event.tools[name];
587
+ if (!definition || event.tools[base]) continue;
588
+ event.tools[base] = definition;
589
+ delete event.tools[name];
590
+ }
591
+ });
592
+ }
593
+
594
+ export async function registerSensitiveGuard(ctx) {
595
+ await ctx.tool.hook("execute.before", async (event) => {
596
+ // The internal search agent only runs inside the guarded tools, which
597
+ // call the built-in directly; a session running as it gets no tools.
598
+ if (event.agent === SEARCH_AGENT) throw new Error(BLOCKED);
599
+ if (!RESTRICTED.has(event.agent)) return;
600
+ const root = await sessionRoot(ctx, event);
601
+ if (!root || blocked(event.tool, event.input, root)) throw new Error(BLOCKED);
602
+ });
603
+ await ctx.tool.hook("execute.after", async (event) => {
604
+ if (!RESTRICTED.has(event.agent) || event.status !== "completed") return;
605
+ const base = SEARCH_BASE[event.tool] ?? event.tool;
606
+ if (base !== "grep" && base !== "glob") return;
607
+ const root = await sessionRoot(ctx, event);
608
+ if (!root) {
609
+ event.result.output = [];
610
+ event.result.content = "Search results withheld by ycc sensitive-file guard.";
611
+ return;
612
+ }
613
+ filterResult(base, event.result, root);
614
+ });
615
+ await registerSearchTools(ctx);
616
+ }
617
+
618
+ export default {
619
+ id: "yandy-r.ycc-sensitive-guard",
620
+ setup: registerSensitiveGuard,
621
+ };
@@ -0,0 +1,7 @@
1
+ {
2
+ "name": "ycc-sensitive-guard",
3
+ "private": true,
4
+ "type": "module",
5
+ "main": "index.js",
6
+ "description": "ycc sensitive-file guard for restricted OpenCode V2 specialists."
7
+ }
@@ -0,0 +1,40 @@
1
+ {
2
+ "restricted_agents": [
3
+ "backport-conflict-resolver",
4
+ "db-modifier",
5
+ "pr-comment-fixer",
6
+ "release-fix-applier",
7
+ "review-fixer"
8
+ ],
9
+ "patterns": [
10
+ ".env",
11
+ ".env.*",
12
+ ".env-*",
13
+ ".env_*",
14
+ ".envrc",
15
+ "*.env",
16
+ "*.env.*",
17
+ "*.pem",
18
+ "*.key",
19
+ "*.p12",
20
+ "*.pfx",
21
+ "id_rsa*",
22
+ "id_dsa*",
23
+ "id_ecdsa*",
24
+ "id_ed25519*",
25
+ "credentials.json",
26
+ "secrets.json",
27
+ "service-account*.json",
28
+ ".netrc",
29
+ ".git-credentials",
30
+ ".npmrc",
31
+ ".pypirc",
32
+ ".pgpass",
33
+ ".kube/config",
34
+ ".docker/config.json",
35
+ ".ssh/",
36
+ ".aws/",
37
+ ".gnupg/"
38
+ ],
39
+ "allow": ["*.env.example", "*.env.*.example"]
40
+ }