diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml new file mode 100644 index 0000000..8601766 --- /dev/null +++ b/.github/actionlint.yaml @@ -0,0 +1,7 @@ +# actionlint #648: built-in metadata for create-github-app-token@v3 is stale +# (app-id required, client-id missing). Upstream uses client-id. +paths: + .github/workflows/**/*.{yaml,yml}: + ignore: + - 'missing input "app-id" which is required by action "actions/create-github-app-token@v3"' + - 'input "client-id" is not defined in action "actions/create-github-app-token@v3"' diff --git a/.mise.toml b/.mise.toml index 279ef0f..3aa7c31 100644 --- a/.mise.toml +++ b/.mise.toml @@ -1,6 +1,7 @@ [tools] -hadolint = "latest" -prek = "latest" -actionlint = "latest" -typos = "latest" -shellcheck = "latest" +bun = { version = "latest", lazy = true } +hadolint = { version = "latest", lazy = true } +prek = { version = "latest", lazy = true } +actionlint = { version = "latest", lazy = true } +typos = { version = "latest", lazy = true } +shellcheck = { version = "latest", lazy = true } diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 00a3056..39b1549 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -12,27 +12,38 @@ repos: - id: mixed-line-ending - id: check-merge-conflict + - repo: https://github.com/python-jsonschema/check-jsonschema + rev: 0.39.0 + hooks: + - id: check-jsonschema + name: validate skills.yaml against schema + files: ^skills\.yaml$ + args: [--schemafile, skills.schema.json] + - id: check-metaschema + name: validate skills schema + files: ^skills\.schema\.json$ + - repo: https://github.com/adrienverge/yamllint rev: v1.38.0 hooks: - id: yamllint - repo: https://github.com/hadolint/hadolint - rev: v2.14.0 + rev: v2.15.1 hooks: - id: hadolint - repo: https://github.com/DavidAnson/markdownlint-cli2 - rev: v0.21.0 + rev: v0.24.2 hooks: - id: markdownlint-cli2 - repo: https://github.com/rhysd/actionlint - rev: v1.7.11 + rev: v1.7.12 hooks: - id: actionlint - repo: https://github.com/crate-ci/typos - rev: v1.44.0 + rev: v1.52.2 hooks: - id: typos diff --git a/Dockerfile b/Dockerfile index b381600..3b16405 100644 --- a/Dockerfile +++ b/Dockerfile @@ -106,7 +106,7 @@ ARG MOLI_VERSION=latest ARG ANYDOC_VERSION=latest ARG OPENCODE_VERSION=latest ARG CAVEMAN_VERSION=latest -ARG AZURE_FOUNDRY_PROVIDER_REF=latest +ARG AZURE_FOUNDRY_PROVIDER_VERSION=latest ARG PONYTAIL_VERSION=latest ARG ENGRAM_VERSION=latest ARG GRAPHIFY_VERSION=latest @@ -151,11 +151,11 @@ bun install -g --trust "@opencode/cli@${OPENCODE_VERSION}" || exit 1 ### # providers # -# AZURE_FOUNDRY_PROVIDER_REF: if starts with 'v' → version tag, else → branch name +# AZURE_FOUNDRY_PROVIDER_VERSION: if starts with 'v' → version tag, else → branch name # ( - azure_foundry_provider_resolved_version=$(resolve_github_latest_version "ophiosdev/azure-foundry-provider" "${AZURE_FOUNDRY_PROVIDER_REF}") || exit 1 - echo "AZURE_FOUNDRY_PROVIDER_REF=${azure_foundry_provider_resolved_version}" + azure_foundry_provider_resolved_version=$(resolve_github_latest_version "ophiosdev/azure-foundry-provider" "${AZURE_FOUNDRY_PROVIDER_VERSION}") || exit 1 + echo "AZURE_FOUNDRY_PROVIDER_VERSION=${azure_foundry_provider_resolved_version}" pushd /tmp \ && bun install "github:ophiosdev/azure-foundry-provider#${azure_foundry_provider_resolved_version}" \ && cd node_modules/azure-foundry-provider \ @@ -213,24 +213,27 @@ bun install -g --trust skills@latest # caveman_resolved_version=$(resolve_github_latest_version "JuliusBrussee/caveman" "${CAVEMAN_VERSION}") || exit 1 echo "CAVEMAN_RESOLVED_REF=${caveman_resolved_version}" -echo "${caveman_resolved_version}" > /tmp/caveman_version mkdir -p "${OPENCODE_CONFIG_DIR}/plugins/caveman" "${OPENCODE_CONFIG_DIR}/commands" "${OPENCODE_CONFIG_DIR}/agents" CAVEMAN_RAW_BASE="https://raw.githubusercontent.com/JuliusBrussee/caveman/refs/tags/${caveman_resolved_version}" # AGENTS.md — always-on caveman ruleset (auto-discovered by opencode) -curl -fsSL "${CAVEMAN_RAW_BASE}/src/rules/caveman-activate.md" -o "${OPENCODE_CONFIG_DIR}/AGENTS.md" || exit 1 +curl -fsSL "${CAVEMAN_RAW_BASE}/src/rules/caveman-activate.md" >> "${OPENCODE_CONFIG_DIR}/AGENTS.md" || exit 1 { curl -fsSL "${CAVEMAN_RAW_BASE}/src/plugins/opencode/package.json" -o "${OPENCODE_CONFIG_DIR}/plugins/caveman/package.json" curl -fsSL "${CAVEMAN_RAW_BASE}/src/plugins/opencode/plugin.js" -o "${OPENCODE_CONFIG_DIR}/plugins/caveman/plugin.js" + curl -fsSL "${CAVEMAN_RAW_BASE}/src/plugins/opencode/server.js" -o "${OPENCODE_CONFIG_DIR}/plugins/caveman/server.js" curl -fsSL "${CAVEMAN_RAW_BASE}/src/hooks/caveman-config.js" -o "${OPENCODE_CONFIG_DIR}/plugins/caveman/caveman-config.cjs" + curl -fsSL "${CAVEMAN_RAW_BASE}/src/hooks/caveman-parse.js" -o "${OPENCODE_CONFIG_DIR}/plugins/caveman/caveman-parse.cjs" curl -fsSL "${CAVEMAN_RAW_BASE}/src/plugins/opencode/commands/caveman.md" -o "${OPENCODE_CONFIG_DIR}/commands/caveman.md" curl -fsSL "${CAVEMAN_RAW_BASE}/src/plugins/opencode/commands/caveman-commit.md" -o "${OPENCODE_CONFIG_DIR}/commands/caveman-commit.md" curl -fsSL "${CAVEMAN_RAW_BASE}/src/plugins/opencode/commands/caveman-review.md" -o "${OPENCODE_CONFIG_DIR}/commands/caveman-review.md" curl -fsSL "${CAVEMAN_RAW_BASE}/src/plugins/opencode/commands/caveman-stats.md" -o "${OPENCODE_CONFIG_DIR}/commands/caveman-stats.md" curl -fsSL "${CAVEMAN_RAW_BASE}/src/plugins/opencode/commands/caveman-help.md" -o "${OPENCODE_CONFIG_DIR}/commands/caveman-help.md" + curl -fsSL "${CAVEMAN_RAW_BASE}/src/plugins/opencode/commands/ultracave.md" -o "${OPENCODE_CONFIG_DIR}/commands/ultracave.md" + curl -fsSL "${CAVEMAN_RAW_BASE}/src/plugins/opencode/commands/megacave.md" -o "${OPENCODE_CONFIG_DIR}/commands/megacave.md" # cavecrew subagents — strip `tools:` frontmatter (opencode rejects YAML array form) curl -fsSL "${CAVEMAN_RAW_BASE}/agents/cavecrew-investigator.md" | sed '/^tools:/,/^[^ ]/ { /^tools:/d; /^ /d; }' > "${OPENCODE_CONFIG_DIR}/agents/cavecrew-investigator.md" curl -fsSL "${CAVEMAN_RAW_BASE}/agents/cavecrew-builder.md" | sed '/^tools:/,/^[^ ]/ { /^tools:/d; /^ /d; }' > "${OPENCODE_CONFIG_DIR}/agents/cavecrew-builder.md" @@ -312,14 +315,6 @@ curl -fsSL "${moli_url}" | tar -xz -C /usr/local/bin --strip-components=1 --wild chmod +x /usr/local/bin/moli || exit 1 moli --version || exit 1 -# Append moli always-on section to AGENTS.md -cat >> "${OPENCODE_CONFIG_DIR}/AGENTS.md" <<-'AGENTS_MOLI' - -## moli - -For live websites or web research, use the installed moli skills: `moli-webfetch` for fetching/capturing JS-rendered pages, `moli-websearch` for keyword/image search. Prefer `moli fetch` over raw curl for JS-rendered content. -AGENTS_MOLI - ### # anydoc # @@ -328,14 +323,6 @@ anydoc_version="${anydoc_resolved_version#v}" bun install -g --trust "@firecrawl/anydoc@${anydoc_version}" || exit 1 anydoc --help > /dev/null || exit 1 -# Append anydoc always-on section to AGENTS.md -cat >> "${OPENCODE_CONFIG_DIR}/AGENTS.md" <<-'AGENTS_ANYDOC' - -## anydoc - -For office documents, spreadsheets, presentations, ebooks, or PDFs you cannot read directly, use the installed `convert-documents-to-markdown` skill and the `anydoc` CLI to convert to Markdown. For large documents write to a file with `-o` and read the parts you need. -AGENTS_ANYDOC - ### # graphify # @@ -344,36 +331,6 @@ echo "GRAPHIFY_RESOLVED_REF=${graphify_resolved_version}" uv pip install --system graphifyy[pdf,office,svg,openai,azure,sql,postgres,terraform] || exit 1 -# Install graphify for opencode into a temp project dir — uses install.py's -# own _copy_skill_file + _install_opencode_plugin logic so the SKILL.md, -# references/ sidecar, .graphify_version stamp, and graphify.js plugin are -# all laid down correctly by graphify itself, not reconstructed here. -TMP_GRAPHIFY=/tmp/graphify-install -mkdir -p "$TMP_GRAPHIFY" -( cd "$TMP_GRAPHIFY" && graphify install --project --platform opencode ) || exit 1 - -# Move installed artifacts to system opencode dir -cp -r "$TMP_GRAPHIFY/.opencode/skills/graphify" "${OPENCODE_CONFIG_DIR}/skills/graphify" -cp "$TMP_GRAPHIFY/.opencode/plugins/graphify.js" "${OPENCODE_CONFIG_DIR}/plugins/graphify.js" - -rm -rf "$TMP_GRAPHIFY" - -# Append graphify always-on section to AGENTS.md -cat >> "${OPENCODE_CONFIG_DIR}/AGENTS.md" <<-'AGENTS_GRAPHIFY' - -## graphify - -This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships. - -When the user types `/graphify`, use the installed graphify skill or instructions before doing anything else. - -Rules: -- For codebase questions, first run `graphify query ""` when graphify-out/graph.json exists. Use `graphify path "" ""` for relationships and `graphify explain ""` for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output. -- Dirty graphify-out/ files are expected after hooks or incremental updates; dirty graph files are not a reason to skip graphify. Only skip graphify if the task is about stale or incorrect graph output, or the user explicitly says not to use it. -- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing. -- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context. -- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost). -AGENTS_GRAPHIFY ### # cleanup @@ -396,14 +353,15 @@ bun "${OPENCODE_BUILD_DIR}/scripts/install-skills.ts" || exit 1 rm -rf "${OPENCODE_BUILD_DIR}" - cat >"${OPENCODE_CONFIG_DIR}/opencode.json" <<-EOF { "\$schema": "https://opencode.ai/config.json", "update": "disable", + "instructions": [ + "/etc/opencode/AGENTS.md" + ], "plugins": [ "file:///usr/local/bun/install/global/node_modules/opencode-gemini-auth", - "file:///etc/opencode/plugins/caveman", "-opencode.plan" ], "mcp": { diff --git a/Makefile b/Makefile index 73c9a2a..46b170b 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ DOCKERFILE ?= Dockerfile CONTEXT ?= . DOCKER_BUILD_ARGS ?= OPENCODE_VERSION ?= latest -AZURE_FOUNDRY_PROVIDER_REF ?= latest +AZURE_FOUNDRY_PROVIDER_VERSION ?= latest .PHONY: build clean @@ -15,7 +15,7 @@ build: -t $(IMAGE_REF) \ -f $(DOCKERFILE) \ --build-arg OPENCODE_VERSION=$(OPENCODE_VERSION) \ - --build-arg AZURE_FOUNDRY_PROVIDER_REF=$(AZURE_FOUNDRY_PROVIDER_REF) \ + --build-arg AZURE_FOUNDRY_PROVIDER_VERSION=$(AZURE_FOUNDRY_PROVIDER_VERSION) \ $(DOCKER_BUILD_ARGS) \ $(CONTEXT) diff --git a/README.md b/README.md index 59a7ee6..9a119cd 100644 --- a/README.md +++ b/README.md @@ -353,6 +353,45 @@ The build bundles these tools and skills: The repository also includes `git-export.ts`, a Bun helper script that exports a single directory from a GitHub repository using a treeless, sparse clone workflow. +### Skills manifest (`skills.yaml`) + +Skills are installed by `scripts/install-skills.ts` from the `skills.yaml` manifest. Beyond +`download`, `git-export`, and `uv-pip` steps, a skill may declare ordered file-edit steps that run +against its staged files before publishing: + +- `replace`: literal (non-regex) replacement of `from` with `to` in `file`, applied to every + non-overlapping occurrence. `expected` is optional: when present it requires exactly that many + occurrences, otherwise at least one is required. Counts fail loudly instead of shipping a + half-patched skill. +- `assert-absent`: fails the install when the JavaScript regular expression `pattern` matches `file`. +- `shell`: runs `commands` with `bash -c` (staging dir as cwd). Exposes `OPENCODE_CONFIG_DIR`, + `SKILL_NAME`, and `SKILL_STAGING_DIR`. Use only when the tool must install itself (graphify); + prefer declarative steps otherwise. A skill with a shell step merges staged files over the + skill dir instead of replacing it, so direct installs survive. Non-zero exit fails the build. + +Match counts are exact on purpose: if upstream skill text changes, the install fails instead of +silently shipping a half-patched skill. Update the manifest after inspecting the upstream change. + +Each skill carries its own guidance: a skill may declare `agents_md` for the tool it installs +(`moli-webfetch`, `convert-documents-to-markdown`, and `graphify` do). Skills may be grouped with +`- group: ` holding `skills: [...]` plus one shared `agents_md` for the group; install order +and guidance order follow manifest order, with a group's `agents_md` landing where the group sits +(before its skills' own `agents_md`). After all skills install, +the per-skill additions are concatenated in manifest skill order and written once to +`${OPENCODE_CONFIG_DIR}/AGENTS.md`. A top-level `agents_md` remains available for genuinely shared +guidance and, when present, comes first. The managed +content lives in one block between `` and +``; base Caveman rules and anything outside the block are +preserved byte-for-byte, and reruns are idempotent. Omitting both forms leaves `AGENTS.md` untouched. + +The `graphify` skill self-installs via `graphify install --project --platform opencode` in a +temp dir (upstream's layout isn't a plain exportable skill tree), then moves its skill dir and +opencode plugin into place — including the `.graphify_version` stamp. The Dockerfile installs +only the graphify binary; the skill directory itself is manifest-owned. + +During image builds, `scripts/install-skills.test.ts` runs before installation, so a broken patch or +manifest fails the build. + ## Release Model This repo publishes container images to GitHub Container Registry from version tags. @@ -378,6 +417,8 @@ Configured checks include: - General file hygiene checks from `pre-commit-hooks` - YAML linting with `yamllint` +- `skills.yaml` schema validation with `check-jsonschema` +- TypeScript linting of `scripts/` with `eslint` (`bun run lint` needs `bun install --cwd scripts` once) - Dockerfile linting with `hadolint` - Markdown linting with `markdownlint-cli2` - GitHub Actions validation with `actionlint` diff --git a/plugins/project-plan/bunfig.toml b/plugins/project-plan/bunfig.toml new file mode 100644 index 0000000..6bebe57 --- /dev/null +++ b/plugins/project-plan/bunfig.toml @@ -0,0 +1,6 @@ +telemetry = false + +[test] +coverage = true +coverageThreshold = { lines = 0.9, functions = 0.9 } +coverageSkipTestFiles = true diff --git a/plugins/project-plan/test/project-plan.test.ts b/plugins/project-plan/test/project-plan.test.ts index 471c299..b9cf689 100644 --- a/plugins/project-plan/test/project-plan.test.ts +++ b/plugins/project-plan/test/project-plan.test.ts @@ -1,10 +1,16 @@ import { describe, expect, test } from "bun:test"; -import { +import { Effect, Exit, Logger, Queue, Scope, Stream } from "effect"; +import plugin, { editResource, resolvePlanDirectory, shouldSwitchReminder, } from "../src/index.ts"; +// The failure-path tests below deliberately kill synthetic() with Effect.die, +// which makes the plugin log a warning. Silence logs there so the output only +// shows relevant failures. +const silentLogs = Logger.layer([Logger.make(() => undefined)]); + describe("project-local Plan plugin", () => { test("defaults to .opencode/plans at the project root", () => { expect(resolvePlanDirectory(undefined, "/workspace/repo")).toBe( @@ -50,4 +56,581 @@ describe("project-local Plan plugin", () => { }), ).toBeUndefined(); }); + + test("rejects non-string or blank directory options", () => { + expect(() => resolvePlanDirectory(42, "/workspace/repo")).toThrow( + "must be a non-empty path", + ); + expect(() => resolvePlanDirectory(" ", "/workspace/repo")).toThrow( + "must be a non-empty path", + ); + }); + + test("rejects absolute paths outside the project checkout", () => { + expect(() => resolvePlanDirectory("/outside", "/workspace/repo")).toThrow( + "must be inside the project checkout", + ); + }); + + test("resolves nested directories inside the project", () => { + expect(resolvePlanDirectory("plans/custom", "/workspace/repo")).toBe( + "/workspace/repo/plans/custom", + ); + }); + + test("builds a plan glob relative to the current directory", () => { + expect( + editResource("/workspace/repo", "/workspace/repo/.opencode/plans"), + ).toBe(".opencode/plans/*"); + }); + + test("stays silent for sessions that never touch Plan", () => { + expect( + shouldSwitchReminder({ type: "session.created", data: {} }), + ).toBeUndefined(); + expect( + shouldSwitchReminder({ + type: "session.created", + data: { agent: "build" }, + }), + ).toBeUndefined(); + expect( + shouldSwitchReminder({ + type: "session.agent.selected", + data: { agent: "plan", previous: "plan" }, + }), + ).toBeUndefined(); + expect( + shouldSwitchReminder({ + type: "session.agent.selected", + data: { agent: "build", previous: "other" }, + }), + ).toBeUndefined(); + }); +}); + +const projectDirectory = "/repo"; +const projectID = "project-1"; +const workspaceID = "workspace-1"; + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +async function waitFor(condition: () => boolean): Promise { + const deadline = Date.now() + 3000; + while (!condition()) { + if (Date.now() > deadline) throw new Error("timed out waiting"); + await sleep(10); + } +} + +function userText(text: string): any { + return { role: "user", content: [{ type: "text", text }] }; +} + +function toolEvent(overrides: any): any { + return { + tool: "edit", + sessionID: "session-1", + agent: "plan", + messageID: "message-1", + id: "call-1", + input: {}, + status: "error", + error: { message: "Permission denied: edit /repo/other.ts" }, + ...overrides, + }; +} + +interface Harness { + agents: any[]; + toolHooks: Record Effect.Effect>; + sessionHooks: Record Effect.Effect>; + syntheticCalls: any[]; + offer: (event: any) => Promise; + setSynthetic: (impl: (args: any) => Effect.Effect) => void; + setSession: (resolve: (args: any) => any) => void; + clearSyntheticCalls: () => void; + close: () => Promise; +} + +async function setup(input?: { + options?: Record; + synthetic?: (args: any) => Effect.Effect; + silent?: boolean; +}): Promise { + const agents: any[] = []; + const toolHooks: Record = {}; + const sessionHooks: Record = {}; + const syntheticCalls: any[] = []; + const queue = await Effect.runPromise(Queue.unbounded()); + let syntheticImpl = + input?.synthetic ?? ((_args: any) => Effect.void as Effect.Effect); + let sessionFor: (args: any) => any = () => ({ + projectID, + location: { directory: projectDirectory, workspaceID }, + }); + const ctx = { + options: input?.options ?? {}, + location: { + project: { directory: projectDirectory, id: projectID }, + directory: projectDirectory, + workspaceID, + }, + agent: { + transform: (callback: any) => { + const editor = { + update: (id: string, update: any) => { + const agent: any = { + name: "", + description: "", + mode: "", + permissions: [], + }; + update(agent); + agents.push({ id, agent }); + }, + }; + callback(editor); + return Effect.succeed({ dispose: Effect.void }); + }, + }, + tool: { + hook: (name: string, callback: any) => { + toolHooks[name] = callback; + return Effect.succeed({ dispose: Effect.void }); + }, + }, + session: { + hook: (name: string, callback: any) => { + sessionHooks[name] = callback; + return Effect.succeed({ dispose: Effect.void }); + }, + get: (args: any) => Effect.succeed(sessionFor(args)), + synthetic: (args: any) => { + syntheticCalls.push(args); + return syntheticImpl(args); + }, + }, + event: { + subscribe: () => Stream.fromQueue(queue), + }, + } as unknown as Parameters[0]; + const scope = await Effect.runPromise(Scope.make()); + const effect = plugin.effect(ctx).pipe(Scope.provide(scope)); + await Effect.runPromise( + input?.silent ? Effect.provide(effect, silentLogs) : effect, + ); + return { + agents, + toolHooks, + sessionHooks, + syntheticCalls, + offer: async (event: any) => { + await Effect.runPromise(Queue.offer(queue, event)); + }, + setSynthetic: (impl) => { + syntheticImpl = impl; + }, + setSession: (resolve) => { + sessionFor = resolve; + }, + clearSyntheticCalls: () => { + syntheticCalls.length = 0; + }, + close: () => Effect.runPromise(Scope.close(scope, Exit.succeed(undefined))), + }; +} + +async function learnTexts( + h: Harness, +): Promise<{ enter: string; leave: string }> { + const hook = h.sessionHooks["context"]!; + await Effect.runPromise( + hook({ agent: "plan", messages: [], sessionID: "s" }), + ); + const enter = h.syntheticCalls[0].text as string; + await Effect.runPromise( + hook({ agent: "build", messages: [userText(enter)], sessionID: "s" }), + ); + const leave = h.syntheticCalls[1].text as string; + h.clearSyntheticCalls(); + return { enter, leave }; +} + +describe("plan agent transform", () => { + test("configures the Plan agent as read-only within the plan directory", async () => { + const h = await setup(); + try { + expect(h.agents).toHaveLength(1); + const entry = h.agents[0]; + expect(entry.id).toBe("plan"); + expect(entry.agent.name).toBe("Plan"); + expect(entry.agent.description).toBe( + "Read-only agent for exploring codebases and planning work before implementation.", + ); + expect(entry.agent.mode).toBe("primary"); + expect(entry.agent.permissions).toEqual([ + { action: "question", resource: "*", effect: "allow" }, + { action: "edit", resource: "*", effect: "deny" }, + { action: "edit", resource: ".opencode/plans/*", effect: "allow" }, + ]); + } finally { + await h.close(); + } + }); + + test("scopes the allow rule to a custom directory option", async () => { + const h = await setup({ options: { directory: "custom" } }); + try { + expect(h.agents).toHaveLength(1); + expect(h.agents[0].agent.permissions[2]).toEqual({ + action: "edit", + resource: "custom/*", + effect: "allow", + }); + } finally { + await h.close(); + } + }); +}); + +describe("execute.after hook", () => { + test("points permission errors at the plan directory, nothing else", async () => { + const h = await setup(); + try { + const hook = h.toolHooks["execute.after"]!; + const denied = toolEvent({}); + await Effect.runPromise(hook(denied)); + expect(denied.error.message).toBe( + "Cannot use edit to modify files outside the Plan directory: /repo/.opencode/plans", + ); + for (const tool of ["write", "patch"]) { + const event = toolEvent({ tool }); + await Effect.runPromise(hook(event)); + expect(event.error.message).toBe( + `Cannot use ${tool} to modify files outside the Plan directory: /repo/.opencode/plans`, + ); + } + const untouched = [ + toolEvent({ agent: "build" }), + toolEvent({ status: "completed", result: {} }), + toolEvent({ tool: "read" }), + toolEvent({ error: { message: "Something else broke" } }), + ]; + for (const event of untouched) { + const before = event.error?.message; + await Effect.runPromise(hook(event)); + expect(event.error?.message).toBe(before); + } + } finally { + await h.close(); + } + }); +}); + +describe("context hook", () => { + test("appends the enter reminder for the plan agent", async () => { + const h = await setup(); + try { + const hook = h.sessionHooks["context"]!; + const messages: any[] = [ + { role: "assistant", content: [{ type: "text", text: "hello" }] }, + ]; + await Effect.runPromise( + hook({ agent: "plan", messages, sessionID: "session-1" }), + ); + expect(messages).toHaveLength(2); + const text = messages[1].content[0].text as string; + expect(text).toContain("You are in Plan mode"); + expect(text).toContain("/repo/.opencode/plans"); + expect(h.syntheticCalls).toEqual([ + { sessionID: "session-1", text, resume: false }, + ]); + } finally { + await h.close(); + } + }); + + test("inserts before a trailing user message", async () => { + const h = await setup(); + try { + const hook = h.sessionHooks["context"]!; + const messages: any[] = [ + { role: "assistant", content: [{ type: "text", text: "hello" }] }, + userText("go on"), + ]; + await Effect.runPromise( + hook({ agent: "plan", messages, sessionID: "session-1" }), + ); + expect(messages).toHaveLength(3); + expect(messages[1].content[0].text).toContain("You are in Plan mode"); + expect(messages[2]).toEqual(userText("go on")); + } finally { + await h.close(); + } + }); + + test("inserts the leave reminder when the reminder goes stale", async () => { + const h = await setup(); + try { + const { enter } = await learnTexts(h); + const hook = h.sessionHooks["context"]!; + const messages: any[] = [userText(enter)]; + await Effect.runPromise( + hook({ agent: "build", messages, sessionID: "session-1" }), + ); + expect(messages).toHaveLength(2); + const text = messages[0].content[0].text as string; + expect(text).toContain("NO LONGER in Plan mode"); + expect(h.syntheticCalls).toEqual([ + { sessionID: "session-1", text, resume: false }, + ]); + } finally { + await h.close(); + } + }); + + test("leaves messages alone when the reminder already matches", async () => { + const h = await setup(); + try { + const { enter, leave } = await learnTexts(h); + const hook = h.sessionHooks["context"]!; + const cases: any[] = [ + { agent: "plan", messages: [userText(enter)], sessionID: "s" }, + { agent: "build", messages: [userText("hello")], sessionID: "s" }, + { agent: "build", messages: [userText(leave)], sessionID: "s" }, + ]; + for (const event of cases) { + const before: number = event.messages.length; + await Effect.runPromise(hook(event)); + expect(event.messages).toHaveLength(before); + } + expect(h.syntheticCalls).toHaveLength(0); + } finally { + await h.close(); + } + }); + + test("ignores non-user, multi-part, and non-text content", async () => { + const h = await setup(); + try { + const { enter } = await learnTexts(h); + const hook = h.sessionHooks["context"]!; + const messages: any[] = [ + { role: "assistant", content: [{ type: "text", text: enter }] }, + { + role: "user", + content: [ + { type: "text", text: "a" }, + { type: "text", text: "b" }, + ], + }, + { role: "user", content: [{ type: "image", url: "x" }] }, + ]; + await Effect.runPromise( + hook({ agent: "build", messages, sessionID: "session-1" }), + ); + expect(messages).toHaveLength(3); + expect(h.syntheticCalls).toHaveLength(0); + } finally { + await h.close(); + } + }); + + test("replays non-text parts while still reminding the plan agent", async () => { + const h = await setup(); + try { + const hook = h.sessionHooks["context"]!; + const messages: any[] = [ + { role: "user", content: [{ type: "tool", text: "x" }] }, + ]; + await Effect.runPromise( + hook({ agent: "plan", messages, sessionID: "session-1" }), + ); + expect(messages).toHaveLength(2); + expect(h.syntheticCalls).toHaveLength(1); + } finally { + await h.close(); + } + }); + + test("interrupts when persisting the reminder is interrupted", async () => { + const h = await setup({ synthetic: () => Effect.interrupt }); + try { + const hook = h.sessionHooks["context"]!; + const exit = await Effect.runPromiseExit( + hook({ agent: "plan", messages: [], sessionID: "session-1" }), + ); + expect(Exit.isFailure(exit)).toBe(true); + expect(h.syntheticCalls).toHaveLength(1); + } finally { + await h.close(); + } + }); + + test("logs instead of failing when persisting the reminder fails", async () => { + const h = await setup({ + synthetic: () => Effect.die(new Error("boom")), + }); + try { + const hook = h.sessionHooks["context"]!; + await Effect.runPromise( + Effect.provide( + hook({ agent: "plan", messages: [], sessionID: "session-1" }), + silentLogs, + ), + ); + expect(h.syntheticCalls).toHaveLength(1); + } finally { + await h.close(); + } + }); +}); + +describe("event subscription", () => { + test("injects the enter reminder when entering Plan mode", async () => { + const h = await setup(); + try { + const { enter } = await learnTexts(h); + await h.offer({ + type: "session.created", + data: { sessionID: "s-enter", agent: "plan" }, + }); + await h.offer({ + type: "session.agent.selected", + data: { sessionID: "s-select", agent: "plan", previous: "build" }, + }); + await waitFor(() => h.syntheticCalls.length === 2); + expect(h.syntheticCalls).toEqual([ + { sessionID: "s-enter", text: enter, resume: false }, + { sessionID: "s-select", text: enter, resume: false }, + ]); + } finally { + await h.close(); + } + }); + + test("injects the leave reminder when leaving Plan mode", async () => { + const h = await setup(); + try { + const { leave } = await learnTexts(h); + await h.offer({ + type: "session.agent.selected", + data: { sessionID: "s-leave", agent: "build", previous: "plan" }, + }); + await waitFor(() => h.syntheticCalls.length === 1); + expect(h.syntheticCalls).toEqual([ + { sessionID: "s-leave", text: leave, resume: false }, + ]); + } finally { + await h.close(); + } + }); + + test("ignores sessions that do not switch plan mode", async () => { + const h = await setup(); + try { + await h.offer({ + type: "session.created", + data: { sessionID: "s-1", agent: "build" }, + }); + await h.offer({ + type: "session.agent.selected", + data: { sessionID: "s-2", agent: "build", previous: "build" }, + }); + await h.offer({ + type: "session.agent.selected", + data: { sessionID: "s-3", agent: "build", previous: "other" }, + }); + await sleep(150); + expect(h.syntheticCalls).toHaveLength(0); + } finally { + await h.close(); + } + }); + + test("skips sessions from other projects or locations", async () => { + const h = await setup(); + try { + h.setSession((args: any) => { + if (args.sessionID === "s-project") + return { + projectID: "other", + location: { directory: projectDirectory, workspaceID }, + }; + if (args.sessionID === "s-directory") + return { + projectID, + location: { directory: "/elsewhere", workspaceID }, + }; + return { + projectID, + location: { directory: projectDirectory, workspaceID: "other" }, + }; + }); + await h.offer({ + type: "session.created", + data: { sessionID: "s-project", agent: "plan" }, + }); + await h.offer({ + type: "session.created", + data: { sessionID: "s-directory", agent: "plan" }, + }); + await h.offer({ + type: "session.created", + data: { sessionID: "s-workspace", agent: "plan" }, + }); + await sleep(200); + expect(h.syntheticCalls).toHaveLength(0); + } finally { + await h.close(); + } + }); + + test("keeps injecting after synthetic failures", async () => { + const h = await setup({ + synthetic: () => Effect.die(new Error("boom")), + silent: true, + }); + try { + await h.offer({ + type: "session.created", + data: { sessionID: "s-bad", agent: "plan" }, + }); + await waitFor(() => h.syntheticCalls.length === 1); + await sleep(150); + h.setSynthetic(() => Effect.void); + await h.offer({ + type: "session.created", + data: { sessionID: "s-good", agent: "plan" }, + }); + await waitFor(() => h.syntheticCalls.length === 2); + expect(h.syntheticCalls[1].sessionID).toBe("s-good"); + } finally { + await h.close(); + } + }); + + test("stops the subscription when injection is interrupted", async () => { + const h = await setup({ synthetic: () => Effect.interrupt }); + try { + await h.offer({ + type: "session.created", + data: { sessionID: "s-bad", agent: "plan" }, + }); + await waitFor(() => h.syntheticCalls.length === 1); + await sleep(150); + h.setSynthetic(() => Effect.void); + await h.offer({ + type: "session.created", + data: { sessionID: "s-good", agent: "plan" }, + }); + await sleep(200); + expect(h.syntheticCalls).toHaveLength(1); + } finally { + await h.close(); + } + }); }); diff --git a/scripts/.prettierignore b/scripts/.prettierignore new file mode 100644 index 0000000..97d2c31 --- /dev/null +++ b/scripts/.prettierignore @@ -0,0 +1,6 @@ +node_modules +dist +coverage +*.tsbuildinfo +bun.lock +.eslintcache diff --git a/scripts/bun.lock b/scripts/bun.lock new file mode 100644 index 0000000..a1509cc --- /dev/null +++ b/scripts/bun.lock @@ -0,0 +1,279 @@ +{ + "lockfileVersion": 2, + "configVersion": 1, + "workspaces": { + "": { + "name": "@ophios/scripts", + "dependencies": { + "yaml": "^2.9.1", + }, + "devDependencies": { + "@eslint/js": "^10.0.1", + "@types/bun": "1.4.4", + "@types/node": "^24.12.2", + "eslint": "^10.13.0", + "eslint-config-prettier": "^10.1.8", + "globals": "^17.13.0", + "prettier": "^3.9.10", + "prettier-plugin-multiline-arrays": "^4.1.11", + "typescript": "6.0.3", + "typescript-eslint": "^8.72.1", + }, + }, + }, + "packages": { + "@augment-vir/assert": ["@augment-vir/assert@32.7.1", "", { "dependencies": { "@augment-vir/core": "^32.7.1", "@date-vir/duration": "^9.4.1", "deep-eql": "^5.0.2", "expect-type": "^1.4.0" } }, "sha512-epUzDi0LZ1Z5NNCVtlGMK7auKENZTq8AXmvvvPNU/pkIjVBs2JSuEGvPpi+HiBo3sr0ZDGRuyMA6ZtgEJyPDiA=="], + + "@augment-vir/common": ["@augment-vir/common@32.7.1", "", { "dependencies": { "@augment-vir/assert": "^32.7.1", "@augment-vir/core": "^32.7.1", "@date-vir/duration": "^9.4.1", "@paralleldrive/cuid2": "^3.3.0", "ansi-styles": "^7.0.0", "deepcopy-esm": "^2.1.2", "json5": "^2.2.3", "typed-event-target": "^4.3.4" } }, "sha512-bC1DtYkXrKJpt/scy/fEyEoC086Z0ZZw6BFu63EEZZK+z2dZgyPOwAc8Z0u6bP/8YbEw4hfYPsIb5y2s95epSA=="], + + "@augment-vir/core": ["@augment-vir/core@32.7.1", "", { "dependencies": { "@date-vir/duration": "^9.4.1", "browser-or-node": "^3.0.0", "diff": "^9.0.0", "json5": "^2.2.3" } }, "sha512-erxNYd1XC+1tHTg/Pn9xFt2ZFjls3eYVdyfx0CEfH7K62/lKZaEHLg7TPbh74hIXlpPxs+bCJpumrOwSrcOlpg=="], + + "@cacheable/memory": ["@cacheable/memory@2.2.0", "", { "dependencies": { "@cacheable/utils": "^2.5.0", "@keyv/bigmap": "^1.3.1", "hookified": "^1.15.1", "keyv": "^5.6.0" } }, "sha512-CTLKqLItRCEixEAewD3/j9DB3/o96gpTPD4eJ1v+DGOlxZRZncRQkGYqqnAGCscYd6RNeXfGeiuCphsPtqyIfQ=="], + + "@cacheable/utils": ["@cacheable/utils@2.5.0", "", { "dependencies": { "hashery": "^1.5.1", "keyv": "^5.6.0" } }, "sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA=="], + + "@date-vir/duration": ["@date-vir/duration@9.4.1", "", { "dependencies": { "@augment-vir/assert": "^32.6.0", "@types/luxon": "^3.7.6", "luxon": "^3.7.2", "type-fest": "^5.10.0" } }, "sha512-5wm+UQN+CKY2jgB5F8oWYxT2WgpffHEPgXh8wzs2xnbOx8ms3dsrCz6jW6oiX4kENNlS295VzwrXnq4SDg1GQA=="], + + "@eslint-community/eslint-utils": ["@eslint-community/eslint-utils@4.10.1", "", { "dependencies": { "eslint-visitor-keys": "^3.4.3" }, "peerDependencies": { "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" } }, "sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg=="], + + "@eslint-community/regexpp": ["@eslint-community/regexpp@4.12.3", "", {}, "sha512-R76UKbvsqI68DJJVTVyqFKqU98CN4+B+acxNfEA2IFarSzP0SjtKf/3+fFiXzTyv5Fj3PxLkGHe2wnVWWMxobQ=="], + + "@eslint/config-array": ["@eslint/config-array@0.23.6", "", { "dependencies": { "@eslint/object-schema": "^3.0.5", "debug": "^4.3.1", "minimatch": "^11.0.5" } }, "sha512-WrTH7nioI9QPY4NZGnsywmecswJdgeq4BCM76qok9VgjTO29ZgUzUvcuJLVPYVQM4uDbaPBU0M33R9DIxI8X3w=="], + + "@eslint/config-helpers": ["@eslint/config-helpers@0.7.0", "", { "dependencies": { "@eslint/core": "^1.2.1" } }, "sha512-DObd/KKUsU+FaFv4PLxSRenpXfQWmPXXP3pPZ6/K1PCrMu2vQpMDMuQe/BqYeoLcz8ro0bVDF1RxOJgfVEdhUw=="], + + "@eslint/core": ["@eslint/core@1.2.1", "", { "dependencies": { "@types/json-schema": "^7.0.15" } }, "sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ=="], + + "@eslint/js": ["@eslint/js@10.0.1", "", { "peerDependencies": { "eslint": "^10.0.0" }, "optionalPeers": ["eslint"] }, "sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA=="], + + "@eslint/object-schema": ["@eslint/object-schema@3.0.5", "", {}, "sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw=="], + + "@eslint/plugin-kit": ["@eslint/plugin-kit@0.7.3", "", { "dependencies": { "@eslint/core": "^1.2.1", "levn": "^0.4.1" } }, "sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q=="], + + "@humanfs/core": ["@humanfs/core@0.19.2", "", { "dependencies": { "@humanfs/types": "^0.15.0" } }, "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA=="], + + "@humanfs/node": ["@humanfs/node@0.16.8", "", { "dependencies": { "@humanfs/core": "^0.19.2", "@humanfs/types": "^0.15.0", "@humanwhocodes/retry": "^0.4.0" } }, "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ=="], + + "@humanfs/types": ["@humanfs/types@0.15.0", "", {}, "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q=="], + + "@humanwhocodes/module-importer": ["@humanwhocodes/module-importer@1.0.1", "", {}, "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA=="], + + "@humanwhocodes/retry": ["@humanwhocodes/retry@0.4.3", "", {}, "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ=="], + + "@isaacs/nonrecursive-glob-match": ["@isaacs/nonrecursive-glob-match@1.1.0", "", {}, "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw=="], + + "@keyv/bigmap": ["@keyv/bigmap@1.3.1", "", { "dependencies": { "hashery": "^1.4.0", "hookified": "^1.15.0" }, "peerDependencies": { "keyv": "^5.6.0" } }, "sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ=="], + + "@keyv/serialize": ["@keyv/serialize@1.1.1", "", {}, "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA=="], + + "@noble/hashes": ["@noble/hashes@2.4.0", "", {}, "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA=="], + + "@paralleldrive/cuid2": ["@paralleldrive/cuid2@3.3.0", "", { "dependencies": { "@noble/hashes": "^2.0.1", "bignumber.js": "^9.3.1", "error-causes": "^3.0.2" }, "bin": { "cuid2": "bin/cuid2.js" } }, "sha512-OqiFvSOF0dBSesELYY2CAMa4YINvlLpvKOz/rv6NeZEqiyttlHgv98Juwv4Ch+GrEV7IZ8jfI2VcEoYUjXXCjw=="], + + "@types/bun": ["@types/bun@1.4.4", "", { "dependencies": { "bun-types": "1.4.4" } }, "sha512-9wkRDXUXK124pEnAutE6n/l18j+i9GC5IAHK8TmX/2nlySETmky0OU6yL5U8pW1AoKh++AN9auDCr647BfurjQ=="], + + "@types/esrecurse": ["@types/esrecurse@4.3.1", "", {}, "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw=="], + + "@types/estree": ["@types/estree@1.0.11", "", {}, "sha512-YBdNe5JcjYR0sPhJW1QIeRCmI11YhYvaRuGCs9+WCeTTb+Yhb2BE2XMe5/wAqF10FK5g3+q1PDhQABfT7aX0gg=="], + + "@types/json-schema": ["@types/json-schema@7.0.15", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="], + + "@types/luxon": ["@types/luxon@3.7.6", "", {}, "sha512-6KSjliQAXK8ZLgFQO4B7iE4Rpf/B3rItzCFuXezBY/XIAGxOdLd7vRNK9/StRPwiS/yJsVbB7HKpW46B8tcEuQ=="], + + "@types/node": ["@types/node@24.19.4", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-s04odlR3ksJrLu7QLi+pddkWLD0RmSbcP9KuWn2/ozQKAp/YgwBC/6x9kJj8yAzZnGPfxePm7zm7nysVPCRagw=="], + + "@typescript-eslint/eslint-plugin": ["@typescript-eslint/eslint-plugin@8.74.0", "", { "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.74.0", "@typescript-eslint/type-utils": "8.74.0", "@typescript-eslint/utils": "8.74.0", "@typescript-eslint/visitor-keys": "8.74.0", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.74.0", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-z3KXk1+Vm+d82ZRplOoC89ho4Rf1da5ju6sx8//92GnN532U62DGPjECXkkVqtYzIv0zoJlpO39SX2Z9tk6LVw=="], + + "@typescript-eslint/parser": ["@typescript-eslint/parser@8.74.0", "", { "dependencies": { "@typescript-eslint/scope-manager": "8.74.0", "@typescript-eslint/types": "8.74.0", "@typescript-eslint/typescript-estree": "8.74.0", "@typescript-eslint/visitor-keys": "8.74.0", "debug": "^4.4.3" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-ecr8AYdig7avVkxaHdQvxHnIJ/mOyliO4Gv/uWF8q69vBew/z3sexqBwHUZX5Vql+Ns0w4sH6gBLkICGbOvJkA=="], + + "@typescript-eslint/project-service": ["@typescript-eslint/project-service@8.74.0", "", { "dependencies": { "@typescript-eslint/tsconfig-utils": "^8.74.0", "@typescript-eslint/types": "^8.74.0", "debug": "^4.4.3" }, "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-z/mymuE+JlEeSFIv3Mo70EvgG1Zz74Hl0IDfExfXutARAP834bt+MppTD7mVAwmZO0GdxdOAi0jbTam749eH6g=="], + + "@typescript-eslint/scope-manager": ["@typescript-eslint/scope-manager@8.74.0", "", { "dependencies": { "@typescript-eslint/types": "8.74.0", "@typescript-eslint/visitor-keys": "8.74.0" } }, "sha512-kpOdpu4CpWN5U38ox3f727DwWRBtUAVhyUJtqTBYe5gf2wYoxac7PgKP14txrxN7ICVtcjlLdzjqfRgpSnDKvQ=="], + + "@typescript-eslint/tsconfig-utils": ["@typescript-eslint/tsconfig-utils@8.74.0", "", { "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-p07wAuaS6BjCYgOSXKJi4YhvTnAf7fiG37e9THcpnYaQEt2QiTTYZWKwUFNgeRiywiMudazhzgddAirZ0GgHtQ=="], + + "@typescript-eslint/type-utils": ["@typescript-eslint/type-utils@8.74.0", "", { "dependencies": { "@typescript-eslint/types": "8.74.0", "@typescript-eslint/typescript-estree": "8.74.0", "@typescript-eslint/utils": "8.74.0", "debug": "^4.4.3", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-CV3Y3la8l3F9ANfxcfpgSSiQgJTe4IeLEoZV4O/gcW86Ugp8X6SKiQ0vm+QegXaRIbbDMokZZSF3A1CgiU/kPw=="], + + "@typescript-eslint/types": ["@typescript-eslint/types@8.74.0", "", {}, "sha512-MpnMrJCVNpP1iVL8NiHkQZgQqIMBH5ewDGUPBh1pqQXwFtMFjsl1M03QcYPXmv6stCKEiF0PN7CGbU1ZbXFzEA=="], + + "@typescript-eslint/typescript-estree": ["@typescript-eslint/typescript-estree@8.74.0", "", { "dependencies": { "@typescript-eslint/project-service": "8.74.0", "@typescript-eslint/tsconfig-utils": "8.74.0", "@typescript-eslint/types": "8.74.0", "@typescript-eslint/visitor-keys": "8.74.0", "debug": "^4.4.3", "minimatch": "^11.0.1", "semver": "^7.7.3", "tinyglobby": "^0.2.15", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "@typescript/native": "npm:typescript@>=7.1.0-dev.20261009.1 || >=7.1.0-beta <7.1.0-dev", "typescript": ">=4.8.4 <6.1.0" }, "optionalPeers": ["@typescript/native"] }, "sha512-wL348k6l92DNG+kPP5rVpKwNBoz7a3xRZy3TPKc1uymQttd7u7gcMv3eENmcuh4CjC4mO3FTM0DYstFXMyDLuw=="], + + "@typescript-eslint/utils": ["@typescript-eslint/utils@8.74.0", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", "@typescript-eslint/scope-manager": "8.74.0", "@typescript-eslint/types": "8.74.0", "@typescript-eslint/typescript-estree": "8.74.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-IpWXPxXXomzxyTcvjhZJexgdvtTR1TooLAPpuxzaGqQ8BHll1lf4Ysp/BTE/l0U5TJ+x1j7B4bEM8pLRrvY+XA=="], + + "@typescript-eslint/visitor-keys": ["@typescript-eslint/visitor-keys@8.74.0", "", { "dependencies": { "@typescript-eslint/types": "8.74.0", "eslint-visitor-keys": "^5.0.0" } }, "sha512-XSZmOtMUbWCBIM+2BK134FyMFxmll1mW2mPLk/PSwYQYzGIPMgJAqL929U4qXVizLv7Xq5b7r41/o7Ombuwk0g=="], + + "acorn": ["acorn@8.19.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw=="], + + "acorn-jsx": ["acorn-jsx@5.3.2", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="], + + "ajv": ["ajv@6.15.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw=="], + + "ansi-styles": ["ansi-styles@7.0.0", "", {}, "sha512-kKvt3m4uwzqL0wlkPd09CmljPJGOZZ4D0fP65sqFSvPkMRKhNi+74MgIJ5QxE6SxqB4t4KyUFGg8+n5zjo6hew=="], + + "balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], + + "bignumber.js": ["bignumber.js@9.3.1", "", {}, "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ=="], + + "brace-expansion": ["brace-expansion@5.1.0", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-aa11Dv491GKnYqxaul3aRJ0szew7yMJMfZPnqD44NjGrZXoj62l41OEDDpdpC4eE2P88vBFfLuSyRhpG91NUvg=="], + + "browser-or-node": ["browser-or-node@3.0.0", "", {}, "sha512-iczIdVJzGEYhP5DqQxYM9Hh7Ztpqqi+CXZpSmX8ALFs9ecXkQIeqRyM6TfxEfMVpwhl3dSuDvxdzzo9sUOIVBQ=="], + + "bun-types": ["bun-types@1.4.4", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-yjrJh5oGX7mMPKGd19YXyIjmEuj4G4zNC30bs7PM9Az7NQ3ndF3j6hbeRdvJTRQEhJ/FYQwW0a2moweEi2hMxQ=="], + + "cacheable": ["cacheable@2.5.0", "", { "dependencies": { "@cacheable/memory": "^2.2.0", "@cacheable/utils": "^2.5.0", "hookified": "^1.15.0", "keyv": "^5.6.0", "qified": "^0.10.1" } }, "sha512-60cyAOytib/OzBw1JNSoSV/boK1AtHryDIjvVBk7XbN4ugfkM3+Sry7fEjNgPMGgOjuaZPAp8ruZ0Cxafwyq9g=="], + + "cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="], + + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + + "deep-eql": ["deep-eql@5.0.2", "", {}, "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q=="], + + "deep-is": ["deep-is@0.1.4", "", {}, "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ=="], + + "deepcopy-esm": ["deepcopy-esm@2.1.2", "", {}, "sha512-iOrQr2AZDcKi5jenwiidK96Ivvn2uHqU1g25qmfs3MbgOUlXPNRbMtHDwTx+U83tD6z+PeYhZzvsPiOqVh20IA=="], + + "diff": ["diff@9.0.0", "", {}, "sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw=="], + + "error-causes": ["error-causes@3.0.2", "", {}, "sha512-i0B8zq1dHL6mM85FGoxaJnVtx6LD5nL2v0hlpGdntg5FOSyzQ46c9lmz5qx0xRS2+PWHGOHcYxGIBC5Le2dRMw=="], + + "escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="], + + "eslint": ["eslint@10.15.0", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.2", "@eslint/config-array": "^0.23.6", "@eslint/config-helpers": "^0.7.0", "@eslint/core": "^1.2.1", "@eslint/plugin-kit": "^0.7.3", "@humanfs/node": "^0.16.8", "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.4.2", "@types/estree": "^1.0.6", "ajv": "^6.14.0", "cross-spawn": "^7.0.6", "debug": "^4.3.2", "escape-string-regexp": "^4.0.0", "eslint-scope": "^9.1.2", "eslint-visitor-keys": "^5.0.1", "espree": "^11.2.0", "esquery": "^1.7.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", "file-entry-cache": "11.1.5 || >11.1.6 <12", "find-up": "^5.0.0", "glob-parent": "^6.0.2", "ignore": "^5.2.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "json-stable-stringify-without-jsonify": "^1.0.1", "minimatch": "^11.0.5", "natural-compare": "^1.4.0", "optionator": "^0.9.3" }, "peerDependencies": { "jiti": "*" }, "optionalPeers": ["jiti"], "bin": { "eslint": "bin/eslint.js" } }, "sha512-+5Wg4p+ze3sG1WErYgUO/3H1IQIfFBymVUA0Fo/XTeBOLS6UQIUekpSJ8sdRkn7O7wjh84b55w/roqavH2aScg=="], + + "eslint-config-prettier": ["eslint-config-prettier@10.1.8", "", { "peerDependencies": { "eslint": ">=7.0.0" }, "bin": { "eslint-config-prettier": "bin/cli.js" } }, "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w=="], + + "eslint-scope": ["eslint-scope@9.1.2", "", { "dependencies": { "@types/esrecurse": "^4.3.1", "@types/estree": "^1.0.8", "esrecurse": "^4.3.0", "estraverse": "^5.2.0" } }, "sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ=="], + + "eslint-visitor-keys": ["eslint-visitor-keys@5.0.1", "", {}, "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA=="], + + "espree": ["espree@11.2.0", "", { "dependencies": { "acorn": "^8.16.0", "acorn-jsx": "^5.3.2", "eslint-visitor-keys": "^5.0.1" } }, "sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw=="], + + "esquery": ["esquery@1.7.0", "", { "dependencies": { "estraverse": "^5.1.0" } }, "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g=="], + + "esrecurse": ["esrecurse@4.3.0", "", { "dependencies": { "estraverse": "^5.2.0" } }, "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag=="], + + "estraverse": ["estraverse@5.3.0", "", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="], + + "esutils": ["esutils@2.0.3", "", {}, "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g=="], + + "expect-type": ["expect-type@1.4.0", "", {}, "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA=="], + + "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], + + "fast-json-stable-stringify": ["fast-json-stable-stringify@2.1.0", "", {}, "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw=="], + + "fast-levenshtein": ["fast-levenshtein@2.0.6", "", {}, "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw=="], + + "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], + + "file-entry-cache": ["file-entry-cache@11.1.5", "", { "dependencies": { "flat-cache": "^6.1.23" } }, "sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q=="], + + "find-up": ["find-up@5.0.0", "", { "dependencies": { "locate-path": "^6.0.0", "path-exists": "^4.0.0" } }, "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng=="], + + "flat-cache": ["flat-cache@6.1.23", "", { "dependencies": { "cacheable": "^2.5.0", "flatted": "^3.4.2", "hookified": "^1.15.0" } }, "sha512-f++BY9pTk+983xK1FLzlLpmM0i0z+jHmx3QESGkURMXujQZz1k5wzwX6hjnQ8goaD0B+sYnDK1yZ6MTyZfUaqA=="], + + "flatted": ["flatted@3.4.4", "", {}, "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q=="], + + "glob-parent": ["glob-parent@6.0.2", "", { "dependencies": { "is-glob": "^4.0.3" } }, "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A=="], + + "globals": ["globals@17.14.0", "", {}, "sha512-UtdkTVyAJePQv0J2M9Xe4L0ruNSDV314XiIJsADI2Zf40bcdAonE/D/OhAU8AT99oij9mhLByb+NvA3QWZYgCg=="], + + "hashery": ["hashery@1.5.1", "", { "dependencies": { "hookified": "^1.15.0" } }, "sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ=="], + + "hookified": ["hookified@1.15.1", "", {}, "sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg=="], + + "ignore": ["ignore@5.3.2", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="], + + "imurmurhash": ["imurmurhash@0.1.4", "", {}, "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA=="], + + "is-extglob": ["is-extglob@2.1.1", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="], + + "is-glob": ["is-glob@4.0.3", "", { "dependencies": { "is-extglob": "^2.1.1" } }, "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg=="], + + "isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], + + "json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="], + + "json-stable-stringify-without-jsonify": ["json-stable-stringify-without-jsonify@1.0.1", "", {}, "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw=="], + + "json5": ["json5@2.2.3", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="], + + "keyv": ["keyv@5.6.0", "", { "dependencies": { "@keyv/serialize": "^1.1.1" } }, "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw=="], + + "levn": ["levn@0.4.1", "", { "dependencies": { "prelude-ls": "^1.2.1", "type-check": "~0.4.0" } }, "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ=="], + + "locate-path": ["locate-path@6.0.0", "", { "dependencies": { "p-locate": "^5.0.0" } }, "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw=="], + + "luxon": ["luxon@3.7.2", "", {}, "sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew=="], + + "minimatch": ["minimatch@11.0.9", "", { "dependencies": { "@isaacs/nonrecursive-glob-match": "^1.1.0", "brace-expansion": "^5.0.12" } }, "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q=="], + + "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + + "natural-compare": ["natural-compare@1.4.0", "", {}, "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw=="], + + "optionator": ["optionator@0.9.4", "", { "dependencies": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", "type-check": "^0.4.0", "word-wrap": "^1.2.5" } }, "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g=="], + + "p-limit": ["p-limit@3.1.0", "", { "dependencies": { "yocto-queue": "^0.1.0" } }, "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ=="], + + "p-locate": ["p-locate@5.0.0", "", { "dependencies": { "p-limit": "^3.0.2" } }, "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw=="], + + "path-exists": ["path-exists@4.0.0", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="], + + "path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="], + + "picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], + + "prelude-ls": ["prelude-ls@1.2.1", "", {}, "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g=="], + + "prettier": ["prettier@3.10.1", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-70vp3ZUYoPlFbF9uiTdXHUUCGEIp7d4+6p+8DYbkm2jP7x/3i/paXVF6dopSI3zd/CEitrZN1rc4i85xWmmXlg=="], + + "prettier-plugin-multiline-arrays": ["prettier-plugin-multiline-arrays@4.1.11", "", { "dependencies": { "@augment-vir/assert": "^32.2.1", "@augment-vir/common": "^32.2.1", "proxy-vir": "^2.0.3" }, "peerDependencies": { "prettier": ">=3.0.0 <4.0.0" } }, "sha512-HZU/1PfNrS1BruYbNGIiIyEcZ9TKAl+88vAmpqWj8d8ywW1jkxttSy4e2+5oTG4/0J+MQajydA0/MUJnivHeIw=="], + + "proxy-vir": ["proxy-vir@2.0.4", "", { "dependencies": { "@augment-vir/assert": "^32.2.1", "@augment-vir/common": "^32.2.1" } }, "sha512-ss7IuTHbS6SeuEKcFfkVtp8kInS8HfMOb1dc/1x1aIyXp97sdQRDH781j1j3PeU5ieLR3FLUrIqF1+UjQ2oIZQ=="], + + "punycode": ["punycode@2.3.1", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="], + + "qified": ["qified@0.10.1", "", { "dependencies": { "hookified": "^2.1.1" } }, "sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA=="], + + "semver": ["semver@7.8.6", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw=="], + + "shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="], + + "shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="], + + "tagged-tag": ["tagged-tag@1.0.0", "", {}, "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng=="], + + "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], + + "ts-api-utils": ["ts-api-utils@2.5.0", "", { "peerDependencies": { "typescript": ">=4.8.4" } }, "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA=="], + + "type-check": ["type-check@0.4.0", "", { "dependencies": { "prelude-ls": "^1.2.1" } }, "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew=="], + + "type-fest": ["type-fest@5.10.0", "", { "dependencies": { "tagged-tag": "^1.0.0" } }, "sha512-NoSdpq/WEiAg5sjmBkmV/hfxv6HJH4NqPNrqjtSO5CwRmpsDfaf4begxW34KdJykH/l1yHtwBWQkCRdoXO8mPA=="], + + "typed-event-target": ["typed-event-target@4.3.4", "", { "dependencies": { "@augment-vir/assert": "^32.3.0", "@augment-vir/common": "^32.3.0" } }, "sha512-ZaBVgXjCvCxlK2Ct89CF3/rgkTy6Hk5PxWMbSbmrviinx1J/YhyvuSc6Ko4SKnY3XeePffq83nCFPR9Y9Os17g=="], + + "typescript": ["typescript@6.0.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw=="], + + "typescript-eslint": ["typescript-eslint@8.74.0", "", { "dependencies": { "@typescript-eslint/eslint-plugin": "8.74.0", "@typescript-eslint/parser": "8.74.0", "@typescript-eslint/typescript-estree": "8.74.0", "@typescript-eslint/utils": "8.74.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-OsWQlsedt1ZpZXfZZMNK3m4SoQONFFcy4h/uRznsCeRfVuEic3gh4KGUs2pJJ5o0Jj0Jr7keUHQGN1Ns9aDw7Q=="], + + "undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="], + + "uri-js": ["uri-js@4.4.1", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="], + + "which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], + + "word-wrap": ["word-wrap@1.2.5", "", {}, "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA=="], + + "yaml": ["yaml@2.9.1", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw=="], + + "yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="], + + "@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="], + + "@typescript-eslint/eslint-plugin/ignore": ["ignore@7.0.17", "", {}, "sha512-0c3zcBRlWmcKhcIQWckzkYncJRv5HHB8O32wO/FcWL8DDXWDJgiEF6SX9ThbTv5h/eZ+xJK+VvDjjQ+cQJhp3Q=="], + + "qified/hookified": ["hookified@2.2.0", "", {}, "sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA=="], + } +} diff --git a/scripts/bunfig.toml b/scripts/bunfig.toml new file mode 100644 index 0000000..6bebe57 --- /dev/null +++ b/scripts/bunfig.toml @@ -0,0 +1,6 @@ +telemetry = false + +[test] +coverage = true +coverageThreshold = { lines = 0.9, functions = 0.9 } +coverageSkipTestFiles = true diff --git a/scripts/convert-gemini.auth.test.ts b/scripts/convert-gemini.auth.test.ts new file mode 100644 index 0000000..75113ff --- /dev/null +++ b/scripts/convert-gemini.auth.test.ts @@ -0,0 +1,270 @@ +import { describe, test, expect, afterEach, beforeEach, spyOn } from "bun:test"; +import { mkdtemp, mkdir, readFile, rm, stat } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { + data, + dst, + existing, + fail, + home, + json, + main, + ms, + onError, + src, +} from "./convert-gemini.auth.ts"; + +const ENV_KEYS = [ + "HOME", + "XDG_DATA_HOME", + "GEMINI_OAUTH_CREDS_PATH", + "OPENCODE_AUTH_PATH", +] as const; +type EnvKey = (typeof ENV_KEYS)[number]; + +let savedEnv: Record; +const tmpRoots: string[] = []; + +async function makeTmp(prefix = "convert-gemini-auth-test-") { + await mkdir("/tmp/opencode", { recursive: true }); + const dir = await mkdtemp(path.join("/tmp/opencode/", prefix)); + tmpRoots.push(dir); + return dir; +} + +beforeEach(() => { + savedEnv = { + HOME: process.env.HOME, + XDG_DATA_HOME: process.env.XDG_DATA_HOME, + GEMINI_OAUTH_CREDS_PATH: process.env.GEMINI_OAUTH_CREDS_PATH, + OPENCODE_AUTH_PATH: process.env.OPENCODE_AUTH_PATH, + }; +}); + +afterEach(async () => { + for (const key of ENV_KEYS) { + const value = savedEnv[key]; + if (value === undefined) Reflect.deleteProperty(process.env, key); + else process.env[key] = value; + } + let dir: string | undefined; + while ((dir = tmpRoots.pop()) !== undefined) { + await rm(dir, { recursive: true, force: true }).catch(() => {}); + } +}); + +describe("ms", () => { + const OFFSET = 55 * 60 * 1000; + + function expectFallback(value: unknown) { + const before = Date.now(); + const got = ms(value); + const after = Date.now(); + expect(got).toBeGreaterThanOrEqual(before + OFFSET); + expect(got).toBeLessThanOrEqual(after + OFFSET); + } + + test("millisecond numbers pass through, second numbers scale up", () => { + expect(ms(1700000000000)).toBe(1700000000000); + expect(ms(1700000000)).toBe(1700000000000); + }); + + test("non-finite numbers fall back", () => { + expectFallback(Number.NaN); + expectFallback(Number.POSITIVE_INFINITY); + }); + + test("numeric strings scale like numbers", () => { + expect(ms("1700000000000")).toBe(1700000000000); + expect(ms("1700000000")).toBe(1700000000000); + }); + + test("date strings parse to epoch ms", () => { + expect(ms("2024-01-01T00:00:00.000Z")).toBe( + Date.parse("2024-01-01T00:00:00.000Z"), + ); + }); + + test("numeric-but-infinite, garbage, empty, and missing fall back", () => { + expectFallback("Infinity"); + expectFallback("not-a-date"); + expectFallback(""); + expectFallback(" "); + expectFallback(undefined); + expectFallback(null); + }); +}); + +describe("paths", () => { + test("env overrides win", () => { + process.env.HOME = "/tmp/opencode/fake-home"; + process.env.XDG_DATA_HOME = "/tmp/opencode/fake-data"; + process.env.GEMINI_OAUTH_CREDS_PATH = "/tmp/opencode/fake-creds.json"; + process.env.OPENCODE_AUTH_PATH = "/tmp/opencode/fake-auth.json"; + expect(home()).toBe("/tmp/opencode/fake-home"); + expect(data()).toBe("/tmp/opencode/fake-data"); + expect(src()).toBe("/tmp/opencode/fake-creds.json"); + expect(dst()).toBe("/tmp/opencode/fake-auth.json"); + }); + + test("defaults derive from home", () => { + process.env.HOME = "/tmp/opencode/fake-home"; + delete process.env.XDG_DATA_HOME; + delete process.env.GEMINI_OAUTH_CREDS_PATH; + delete process.env.OPENCODE_AUTH_PATH; + expect(home()).toBe("/tmp/opencode/fake-home"); + expect(data()).toBe( + path.join("/tmp/opencode/fake-home", ".local", "share"), + ); + expect(src()).toBe( + path.join("/tmp/opencode/fake-home", ".gemini", "oauth_creds.json"), + ); + expect(dst()).toBe( + path.join( + "/tmp/opencode/fake-home", + ".local", + "share", + "opencode", + "auth.json", + ), + ); + }); + + test("home falls back to os.homedir without HOME", () => { + delete process.env.HOME; + expect(home()).toBe(os.homedir()); + }); +}); + +describe("json/existing", () => { + test("json reads a valid file", async () => { + const dir = await makeTmp(); + const file = path.join(dir, "a.json"); + await Bun.write(file, JSON.stringify({ a: 1 })); + expect(await json(file)).toEqual({ a: 1 }); + }); + + test("existing returns content, {} for missing or corrupt", async () => { + const dir = await makeTmp(); + const good = path.join(dir, "good.json"); + await Bun.write(good, JSON.stringify({ google: { type: "oauth" } })); + expect(await existing(good)).toEqual({ google: { type: "oauth" } }); + expect(await existing(path.join(dir, "missing.json"))).toEqual({}); + const bad = path.join(dir, "bad.json"); + await Bun.write(bad, "{not json"); + expect(await existing(bad)).toEqual({}); + }); +}); + +describe("fail", () => { + function mockExit() { + const logged: string[] = []; + let code: number | undefined; + const exitSpy = spyOn(process, "exit").mockImplementation( + (c?: number): never => { + code = c; + throw new Error(`exited:${String(c)}`); + }, + ); + const errorSpy = spyOn(console, "error").mockImplementation( + (...args: unknown[]): void => { + logged.push(args.map((a) => String(a)).join(" ")); + }, + ); + return { + logged, + code: () => code, + restore: () => { + exitSpy.mockRestore(); + errorSpy.mockRestore(); + }, + }; + } + + test("logs and exits 1", () => { + const mocked = mockExit(); + try { + expect(() => fail("boom")).toThrow("exited:1"); + expect(mocked.code()).toBe(1); + expect(mocked.logged.join("\n")).toContain("[convert-gemini.auth] boom"); + } finally { + mocked.restore(); + } + }); + + test("onError reports Error messages and plain values", () => { + const mocked = mockExit(); + try { + expect(() => onError(new Error("bad creds"))).toThrow("exited:1"); + expect(() => onError("plain")).toThrow("exited:1"); + expect(mocked.logged.join("\n")).toContain( + "[convert-gemini.auth] bad creds", + ); + expect(mocked.logged.join("\n")).toContain("[convert-gemini.auth] plain"); + } finally { + mocked.restore(); + } + }); +}); + +describe("main", () => { + test("writes merged auth.json from tmp creds", async () => { + const dir = await makeTmp(); + const credsFile = path.join(dir, "oauth_creds.json"); + const authFile = path.join(dir, "sub", "auth.json"); + await Bun.write( + credsFile, + JSON.stringify({ + access_token: "access-123", + refresh_token: "refresh-456", + expiry_date: 1700000000, + }), + ); + await mkdir(path.dirname(authFile), { recursive: true }); + await Bun.write(authFile, JSON.stringify({ other: { keep: true } })); + process.env.GEMINI_OAUTH_CREDS_PATH = credsFile; + process.env.OPENCODE_AUTH_PATH = authFile; + await main(); + const raw = await readFile(authFile, "utf8"); + const auth = JSON.parse(raw) as Record; + expect(auth.other).toEqual({ keep: true }); + expect(auth.google).toEqual({ + type: "oauth", + refresh: "refresh-456", + access: "access-123", + expires: 1700000000000, + }); + expect(raw.endsWith("\n")).toBe(true); + expect((await stat(authFile)).mode & 0o777).toBe(0o600); + }); + + test("missing tokens fail via CLI with exit 1", async () => { + const dir = await makeTmp("cli-"); + const script = new URL("./convert-gemini.auth.ts", import.meta.url) + .pathname; + for (const [name, creds, needle] of [ + ["no-refresh", { access_token: "a" }, "missing refresh_token"], + ["no-access", { refresh_token: "r" }, "missing access_token"], + ] as const) { + const credsFile = path.join(dir, `${name}.json`); + const authFile = path.join(dir, `${name}.auth.json`); + await Bun.write(credsFile, JSON.stringify(creds)); + const proc = Bun.spawn(["bun", script], { + env: { + ...process.env, + GEMINI_OAUTH_CREDS_PATH: credsFile, + OPENCODE_AUTH_PATH: authFile, + }, + stdout: "pipe", + stderr: "pipe", + }); + const [err, code] = await Promise.all([ + new Response(proc.stderr).text(), + proc.exited, + ]); + expect(code).toBe(1); + expect(err).toContain(needle); + } + }, 30000); +}); diff --git a/scripts/convert-gemini.auth.ts b/scripts/convert-gemini.auth.ts index a744810..7260405 100644 --- a/scripts/convert-gemini.auth.ts +++ b/scripts/convert-gemini.auth.ts @@ -1,92 +1,103 @@ #!/usr/bin/env bun -import { chmod, mkdir, readFile, writeFile } from "node:fs/promises" -import os from "node:os" -import path from "node:path" +import { chmod, mkdir, readFile, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; type Gemini = { - access_token?: string - refresh_token?: string - expiry_date?: number | string -} + access_token?: string; + refresh_token?: string; + expiry_date?: number | string; +}; type OAuth = { - type: "oauth" - refresh: string - access: string - expires: number -} + type: "oauth"; + refresh: string; + access: string; + expires: number; +}; -type Auth = Record> +type Auth = Record>; -function fail(msg: string): never { - console.error(`[convert-gemini.auth] ${msg}`) - process.exit(1) +export function fail(msg: string): never { + console.error(`[convert-gemini.auth] ${msg}`); + process.exit(1); } -function home() { - return process.env.HOME || os.homedir() +export function home() { + return process.env.HOME || os.homedir(); } -function data() { - return process.env.XDG_DATA_HOME || path.join(home(), ".local", "share") +export function data() { + return process.env.XDG_DATA_HOME || path.join(home(), ".local", "share"); } -function src() { - return process.env.GEMINI_OAUTH_CREDS_PATH || path.join(home(), ".gemini", "oauth_creds.json") +export function src() { + return ( + process.env.GEMINI_OAUTH_CREDS_PATH || + path.join(home(), ".gemini", "oauth_creds.json") + ); } -function dst() { - return process.env.OPENCODE_AUTH_PATH || path.join(data(), "opencode", "auth.json") +export function dst() { + return ( + process.env.OPENCODE_AUTH_PATH || path.join(data(), "opencode", "auth.json") + ); } -function ms(value: unknown) { +export function ms(value: unknown) { if (typeof value === "number" && Number.isFinite(value)) { - return value < 1e12 ? value * 1000 : value + return value < 1e12 ? value * 1000 : value; } if (typeof value === "string" && value.trim()) { - const num = Number(value) - if (Number.isFinite(num)) return num < 1e12 ? num * 1000 : num - const date = Date.parse(value) - if (!Number.isNaN(date)) return date + const num = Number(value); + if (Number.isFinite(num)) return num < 1e12 ? num * 1000 : num; + const date = Date.parse(value); + if (!Number.isNaN(date)) return date; } - return Date.now() + 55 * 60 * 1000 + return Date.now() + 55 * 60 * 1000; } -async function json(file: string) { - return JSON.parse(await readFile(file, "utf8")) as Record +export async function json(file: string) { + return JSON.parse(await readFile(file, "utf8")) as Record; } -async function existing(file: string): Promise { +export async function existing(file: string): Promise { try { - return (await json(file)) as Auth + return (await json(file)) as Auth; } catch { - return {} + return {}; } } -async function main() { - const source = src() - const target = dst() - const creds = (await json(source)) as Gemini +export async function main() { + const source = src(); + const target = dst(); + const creds = (await json(source)) as Gemini; - if (!creds.refresh_token) fail(`missing refresh_token in ${source}`) - if (!creds.access_token) fail(`missing access_token in ${source}`) + if (!creds.refresh_token) fail(`missing refresh_token in ${source}`); + if (!creds.access_token) fail(`missing access_token in ${source}`); - const auth = await existing(target) + const auth = await existing(target); auth.google = { type: "oauth", refresh: creds.refresh_token, access: creds.access_token, expires: ms(creds.expiry_date), - } + }; - await mkdir(path.dirname(target), { recursive: true }) - await writeFile(target, `${JSON.stringify(auth, null, 2)}\n`, { mode: 0o600 }) - await chmod(target, 0o600) + await mkdir(path.dirname(target), { recursive: true }); + await writeFile(target, `${JSON.stringify(auth, null, 2)}\n`, { + mode: 0o600, + }); + await chmod(target, 0o600); } -await main().catch((err) => { - fail(err instanceof Error ? err.message : String(err)) -}) +export function onError(err: unknown): void { + fail(err instanceof Error ? err.message : String(err)); +} + +if (import.meta.main) { + await main().catch(onError); +} diff --git a/scripts/eslint.config.mjs b/scripts/eslint.config.mjs new file mode 100644 index 0000000..5923b0c --- /dev/null +++ b/scripts/eslint.config.mjs @@ -0,0 +1,95 @@ +import js from "@eslint/js"; +import eslintConfigPrettier from "eslint-config-prettier/flat"; +import globals from "globals"; +import tseslint from "typescript-eslint"; + +export default tseslint.config( + { + ignores: ["**/node_modules/**", "**/dist/**", "**/eslint.config.mjs"], + }, + { + ...js.configs.recommended, + files: ["**/*.js", "**/*.mjs", "**/*.cjs"], + }, + ...tseslint.configs.strictTypeChecked.map((config) => ({ + ...config, + files: ["**/*.ts"], + })), + { + files: ["**/*.ts"], + ignores: ["**/*.test.ts"], + languageOptions: { + ecmaVersion: "latest", + sourceType: "module", + globals: { + ...globals.bun, + ...globals.node, + }, + parserOptions: { + project: "./tsconfig.json", + tsconfigRootDir: import.meta.dirname, + }, + }, + rules: { + "@typescript-eslint/consistent-type-imports": [ + "error", + { prefer: "type-imports", fixStyle: "inline-type-imports" }, + ], + "@typescript-eslint/consistent-type-definitions": "off", + "@typescript-eslint/no-explicit-any": "error", + "@typescript-eslint/no-floating-promises": "error", + "@typescript-eslint/no-misused-promises": "error", + "@typescript-eslint/no-unsafe-member-access": "off", + "@typescript-eslint/no-unsafe-assignment": "off", + "@typescript-eslint/no-unsafe-return": "off", + "@typescript-eslint/no-unnecessary-condition": "off", + "@typescript-eslint/no-unnecessary-type-assertion": "error", + "@typescript-eslint/no-unused-vars": [ + "error", + { argsIgnorePattern: "^_", varsIgnorePattern: "^_" }, + ], + "@typescript-eslint/no-dynamic-delete": "off", + "@typescript-eslint/no-redundant-type-constituents": "off", + "@typescript-eslint/require-await": "off", + }, + }, + { + files: ["**/*.test.ts"], + languageOptions: { + ecmaVersion: "latest", + sourceType: "module", + globals: { + ...globals.bun, + ...globals.node, + }, + parserOptions: { + project: "./tsconfig.json", + tsconfigRootDir: import.meta.dirname, + }, + }, + rules: { + "@typescript-eslint/consistent-type-imports": [ + "error", + { prefer: "type-imports", fixStyle: "inline-type-imports" }, + ], + "@typescript-eslint/consistent-type-definitions": "off", + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-floating-promises": "off", + "@typescript-eslint/no-misused-promises": "off", + "@typescript-eslint/no-confusing-void-expression": "off", + "@typescript-eslint/await-thenable": "off", + "@typescript-eslint/no-base-to-string": "off", + "@typescript-eslint/no-unsafe-assignment": "off", + "@typescript-eslint/no-unsafe-call": "off", + "@typescript-eslint/no-unsafe-member-access": "off", + "@typescript-eslint/no-unnecessary-condition": "off", + "@typescript-eslint/no-unnecessary-type-assertion": "off", + "@typescript-eslint/no-unused-vars": [ + "error", + { argsIgnorePattern: "^_", varsIgnorePattern: "^_" }, + ], + "@typescript-eslint/require-await": "off", + }, + }, + eslintConfigPrettier, +); diff --git a/scripts/git-export.test.ts b/scripts/git-export.test.ts new file mode 100644 index 0000000..64dc9ab --- /dev/null +++ b/scripts/git-export.test.ts @@ -0,0 +1,759 @@ +import { describe, test, expect, afterEach } from "bun:test"; +import { + mkdtemp, + mkdir, + rm, + symlink, + lstat, + readlink, + readdir, +} from "node:fs/promises"; +import path from "node:path"; +import { + GitExportError, + parseGithubDirectoryUrl, + normalizeSourcePath, + formatCommand, + pathExists, + isDirectory, + prepareOutputDir, + removeExisting, + copyEntry, + parseArgs, + printHelp, + runGit, + exportDirectory, + runMain, + main, +} from "./git-export.ts"; + +const tmpRoots: string[] = []; + +async function makeTmp(prefix = "git-export-test-") { + await mkdir("/tmp/opencode", { recursive: true }).catch(() => {}); + const dir = await mkdtemp(path.join("/tmp/opencode/", prefix)); + tmpRoots.push(dir); + return dir; +} + +afterEach(async () => { + let dir: string | undefined; + while ((dir = tmpRoots.pop()) !== undefined) { + await rm(dir, { recursive: true, force: true }).catch(() => {}); + } +}); + +async function initFixtureRepo() { + const dir = await makeTmp("git-export-fixture-"); + await runGit("git", ["init"], dir); + await runGit("git", ["config", "user.email", "test@test.com"], dir); + await runGit("git", ["config", "user.name", "test"], dir); + await mkdir(path.join(dir, "pkg", "sub"), { recursive: true }); + await Bun.write(path.join(dir, "pkg", "sub", "file.txt"), "hello sub"); + await Bun.write(path.join(dir, "root.txt"), "root content"); + await mkdir(path.join(dir, "emptydir"), { recursive: true }); + await Bun.write(path.join(dir, "emptydir", ".gitkeep"), ""); + await mkdir(path.join(dir, "pkg", "emptysub"), { recursive: true }); + await Bun.write(path.join(dir, "pkg", "emptysub", ".gitkeep"), ""); + await runGit("git", ["add", "-A"], dir); + await runGit("git", ["commit", "-m", "init"], dir); + await runGit("git", ["tag", "v1"], dir); + await Bun.write(path.join(dir, "pkg", "sub", "file.txt"), "hello sub v2"); + await Bun.write(path.join(dir, "pkg", "sub", "extra.txt"), "extra"); + await runGit("git", ["add", "-A"], dir); + await runGit("git", ["commit", "-m", "v2"], dir); + return dir; +} + +function captureLog() { + const logs: string[] = []; + const orig = console.log; + console.log = (...args: unknown[]) => { + logs.push(args.map((a) => String(a)).join(" ")); + }; + return { + logs, + restore() { + console.log = orig; + }, + }; +} + +describe("parseGithubDirectoryUrl", () => { + test("root url", () => { + const p = parseGithubDirectoryUrl("https://github.com/owner/repo"); + expect(p.repoUrl).toBe("https://github.com/owner/repo.git"); + expect(p.sourcePath).toBeNull(); + expect(p.ref).toBeNull(); + }); + + test("git suffix and www host", () => { + const p = parseGithubDirectoryUrl("https://www.github.com/owner/repo.git"); + expect(p.repoUrl).toBe("https://github.com/owner/repo.git"); + }); + + test("tree with ref and path", () => { + const p = parseGithubDirectoryUrl( + "https://github.com/owner/repo/tree/main/src/lib", + ); + expect(p.repoUrl).toBe("https://github.com/owner/repo.git"); + expect(p.ref).toBe("main"); + expect(p.sourcePath).toBe("src/lib"); + }); + + test("blob with ref and path", () => { + const p = parseGithubDirectoryUrl( + "https://github.com/owner/repo/blob/v1.0/docs/readme.md", + ); + expect(p.ref).toBe("v1.0"); + expect(p.sourcePath).toBe("docs/readme.md"); + }); + + test("bare path without tree/blob", () => { + const p = parseGithubDirectoryUrl( + "https://github.com/owner/repo/mydir/sub", + ); + expect(p.ref).toBeNull(); + expect(p.sourcePath).toBe("mydir/sub"); + }); + + test("http protocol allowed", () => { + const p = parseGithubDirectoryUrl("http://github.com/o/r"); + expect(p.repoUrl).toBe("https://github.com/o/r.git"); + }); + + test("invalid url throws", () => { + expect(() => parseGithubDirectoryUrl("not a url")).toThrow(GitExportError); + }); + + test("wrong host and protocol throw", () => { + expect(() => parseGithubDirectoryUrl("https://gitlab.com/o/r")).toThrow( + "Not a supported GitHub URL", + ); + expect(() => parseGithubDirectoryUrl("ftp://github.com/o/r")).toThrow( + "Not a supported GitHub URL", + ); + }); + + test("missing owner/repo throws", () => { + expect(() => parseGithubDirectoryUrl("https://github.com/owner")).toThrow( + "must include owner/repo", + ); + expect(() => parseGithubDirectoryUrl("https://github.com/")).toThrow( + "must include owner/repo", + ); + }); + + test("tree/blob without path throws", () => { + expect(() => + parseGithubDirectoryUrl("https://github.com/o/r/tree/main"), + ).toThrow("tree/blob URLs must include ref"); + expect(() => + parseGithubDirectoryUrl("https://github.com/o/r/blob/v1"), + ).toThrow("tree/blob URLs must include ref"); + expect(() => + parseGithubDirectoryUrl("https://github.com/o/r/tree"), + ).toThrow("tree/blob URLs must include ref"); + }); +}); + +describe("normalizeSourcePath", () => { + test("slashes and dot segments", () => { + expect(normalizeSourcePath("/a/b/")).toBe("a/b"); + expect(normalizeSourcePath("///a///b///")).toBe("a/b"); + expect(normalizeSourcePath("a/./b/./c")).toBe("a/b/c"); + expect(normalizeSourcePath("./a")).toBe("a"); + expect(normalizeSourcePath(" pkg/sub ")).toBe("pkg/sub"); + }); + + test("empty and dotdot reject", () => { + expect(() => normalizeSourcePath("")).toThrow("must not be empty"); + expect(() => normalizeSourcePath(" ")).toThrow("must not be empty"); + expect(() => normalizeSourcePath("/")).toThrow("must not be empty"); + expect(() => normalizeSourcePath("..")).toThrow("must not contain '..'"); + expect(() => normalizeSourcePath("a/../b")).toThrow( + "must not contain '..'", + ); + expect(() => normalizeSourcePath("../a")).toThrow("must not contain '..'"); + }); +}); + +describe("formatCommand", () => { + test("plain and quoting", () => { + expect(formatCommand(["git", "clone", "url"])).toBe("git clone url"); + expect(formatCommand(["git", "a b"])).toBe(`git "a b"`); + expect(formatCommand(["git", `a"b`])).toBe(`git "a\\"b"`); + expect(formatCommand(["git", "a'b"])).toBe(`git "a'b"`); + }); +}); + +describe("pathExists/isDirectory", () => { + test("exists, missing, file vs dir, symlink", async () => { + const dir = await makeTmp(); + const file = path.join(dir, "f.txt"); + await Bun.write(file, "x"); + expect(await pathExists(file)).toBe(true); + expect(await pathExists(path.join(dir, "missing"))).toBe(false); + expect(await isDirectory(dir)).toBe(true); + expect(await isDirectory(file)).toBe(false); + expect(await isDirectory(path.join(dir, "missing"))).toBe(false); + const linkToDir = path.join(dir, "linkdir"); + await symlink(dir, linkToDir); + expect(await isDirectory(linkToDir)).toBe(false); + const linkToFile = path.join(dir, "linkfile"); + await symlink(file, linkToFile); + expect(await isDirectory(linkToFile)).toBe(false); + }); +}); + +describe("prepareOutputDir", () => { + test("missing creates", async () => { + const dir = await makeTmp(); + const out = path.join(dir, "new", "nested"); + await prepareOutputDir(out, false); + expect(await isDirectory(out)).toBe(true); + }); + + test("exists naked fails", async () => { + const dir = await makeTmp(); + const out = path.join(dir, "out"); + await mkdir(out, { recursive: true }); + await expect(prepareOutputDir(out, false)).rejects.toThrow( + "already exists", + ); + }); + + test("exists dir with force replaces", async () => { + const dir = await makeTmp(); + const out = path.join(dir, "out"); + await mkdir(out, { recursive: true }); + await Bun.write(path.join(out, "old.txt"), "old"); + await prepareOutputDir(out, true); + expect(await isDirectory(out)).toBe(true); + expect(await pathExists(path.join(out, "old.txt"))).toBe(false); + }); + + test("exists file with force replaces", async () => { + const dir = await makeTmp(); + const out = path.join(dir, "out"); + await Bun.write(out, "i am a file"); + await prepareOutputDir(out, true); + expect(await isDirectory(out)).toBe(true); + }); + + test("exists symlink with force replaces", async () => { + const dir = await makeTmp(); + const target = path.join(dir, "target.txt"); + await Bun.write(target, "t"); + const out = path.join(dir, "out"); + await symlink(target, out); + expect((await lstat(out)).isSymbolicLink()).toBe(true); + await prepareOutputDir(out, true); + expect(await isDirectory(out)).toBe(true); + }); +}); + +describe("removeExisting", () => { + test("missing no-op", async () => { + const dir = await makeTmp(); + await removeExisting(path.join(dir, "nope")); + }); + + test("dir removed", async () => { + const dir = await makeTmp(); + const sub = path.join(dir, "sub"); + await mkdir(sub, { recursive: true }); + await Bun.write(path.join(sub, "a.txt"), "a"); + await removeExisting(sub); + expect(await pathExists(sub)).toBe(false); + }); + + test("file removed", async () => { + const dir = await makeTmp(); + const f = path.join(dir, "f.txt"); + await Bun.write(f, "x"); + await removeExisting(f); + expect(await pathExists(f)).toBe(false); + }); + + test("symlink removed but target kept", async () => { + const dir = await makeTmp(); + const target = path.join(dir, "t.txt"); + await Bun.write(target, "t"); + const link = path.join(dir, "link"); + await symlink(target, link); + await removeExisting(link); + expect(await pathExists(link)).toBe(false); + expect(await pathExists(target)).toBe(true); + }); +}); + +describe("copyEntry", () => { + test("file", async () => { + const dir = await makeTmp(); + const src = path.join(dir, "src.txt"); + await Bun.write(src, "data"); + const dst = path.join(dir, "dst.txt"); + await copyEntry(src, dst); + expect(await Bun.file(dst).text()).toBe("data"); + }); + + test("dir recursive", async () => { + const dir = await makeTmp(); + const src = path.join(dir, "srcdir"); + await mkdir(path.join(src, "nested"), { recursive: true }); + await Bun.write(path.join(src, "a.txt"), "a"); + await Bun.write(path.join(src, "nested", "b.txt"), "b"); + const dst = path.join(dir, "dstdir"); + await copyEntry(src, dst); + expect(await Bun.file(path.join(dst, "a.txt")).text()).toBe("a"); + expect(await Bun.file(path.join(dst, "nested", "b.txt")).text()).toBe("b"); + }); + + test("symlink overwrites existing", async () => { + const dir = await makeTmp(); + const target = path.join(dir, "target.txt"); + await Bun.write(target, "t"); + const src = path.join(dir, "srclink"); + await symlink(target, src); + const dst = path.join(dir, "dstlink"); + await Bun.write(dst, "old"); + await copyEntry(src, dst); + expect((await lstat(dst)).isSymbolicLink()).toBe(true); + expect(await readlink(dst)).toBe(target); + }); +}); + +describe("runGit", () => { + test("success", async () => { + await runGit("git", ["--version"]); + }); + + test("verbose true logs with and without cwd", async () => { + const cap = captureLog(); + try { + const dir = await makeTmp(); + await runGit("git", ["--version"], dir, true); + await runGit("git", ["--version"], undefined, true); + } finally { + cap.restore(); + } + expect(cap.logs.join("\n")).toContain("cwd="); + }); + + test("failure mentions exit code", async () => { + await expect(runGit("false", ["anything"])).rejects.toThrow(/exit code/); + await expect(runGit("false", ["anything"])).rejects.toThrow( + "git command failed", + ); + }); + + test("failure with stderr detail", async () => { + const dir = await makeTmp(); + await runGit("git", ["init"], dir); + await expect( + runGit("git", ["rev-parse", "nonexistent-ref-xyz"], dir), + ).rejects.toThrow("git command failed"); + }); +}); + +describe("parseArgs", () => { + test("all flags", () => { + const o = parseArgs([ + "src", + "out", + "--ref", + "main", + "--path", + "a/b", + "--depth", + "5", + "--git", + "/usr/bin/git", + "--force", + "--verbose", + ]); + expect(o.source).toBe("src"); + expect(o.output).toBe("out"); + expect(o.ref).toBe("main"); + expect(o.sourcePath).toBe("a/b"); + expect(o.depth).toBe(5); + expect(o.gitBin).toBe("/usr/bin/git"); + expect(o.force).toBe(true); + expect(o.verbose).toBe(true); + }); + + test("defaults", () => { + const o = parseArgs(["s", "o"]); + expect(o.ref).toBeNull(); + expect(o.sourcePath).toBeNull(); + expect(o.depth).toBe(1); + expect(o.gitBin).toBe("git"); + expect(o.force).toBe(false); + expect(o.verbose).toBe(false); + }); + + test("missing values fail", () => { + expect(() => parseArgs(["s", "o", "--ref"])).toThrow( + "--ref requires a value", + ); + expect(() => parseArgs(["s", "o", "--path"])).toThrow( + "--path requires a value", + ); + expect(() => parseArgs(["s", "o", "--depth"])).toThrow( + "--depth requires a value", + ); + expect(() => parseArgs(["s", "o", "--git"])).toThrow( + "--git requires a value", + ); + }); + + test("bad depth fails", () => { + expect(() => parseArgs(["s", "o", "--depth", "0"])).toThrow( + "Invalid --depth", + ); + expect(() => parseArgs(["s", "o", "--depth", "-3"])).toThrow( + "Invalid --depth", + ); + expect(() => parseArgs(["s", "o", "--depth", "xyz"])).toThrow( + "Invalid --depth", + ); + }); + + test("unknown option fails", () => { + expect(() => parseArgs(["s", "o", "--nope"])).toThrow("Unknown option"); + expect(() => parseArgs(["s", "o", "-x"])).toThrow("Unknown option"); + }); + + test("wrong positional count fails", () => { + const cap = captureLog(); + try { + expect(() => parseArgs([])).toThrow( + "Expected SOURCE and OUTPUT arguments", + ); + expect(() => parseArgs(["only-one"])).toThrow( + "Expected SOURCE and OUTPUT arguments", + ); + expect(() => parseArgs(["a", "b", "c"])).toThrow( + "Expected SOURCE and OUTPUT arguments", + ); + } finally { + cap.restore(); + } + expect(cap.logs.join("\n")).toContain("Usage:"); + }); +}); + +describe("printHelp", () => { + test("logs usage", () => { + const cap = captureLog(); + try { + printHelp(); + } finally { + cap.restore(); + } + expect(cap.logs.join("\n")).toContain("Usage:"); + expect(cap.logs.join("\n")).toContain("--force"); + }); +}); + +describe("exportDirectory", () => { + test("subpath export", async () => { + const fixture = await initFixtureRepo(); + const parent = await makeTmp("git-export-e2e-"); + const out = path.join(parent, "out-sub"); + await exportDirectory({ + repoUrl: fixture, + sourcePath: "pkg/sub", + outputDir: out, + ref: null, + depth: 1, + force: false, + gitBin: "git", + verbose: false, + }); + expect(await Bun.file(path.join(out, "file.txt")).text()).toBe( + "hello sub v2", + ); + expect(await Bun.file(path.join(out, "extra.txt")).text()).toBe("extra"); + expect(await pathExists(path.join(out, ".git"))).toBe(false); + expect(await pathExists(path.join(out, "root.txt"))).toBe(false); + }); + + test("repo-root export skips .git and disables sparse", async () => { + const fixture = await initFixtureRepo(); + const parent = await makeTmp("git-export-e2e-"); + const out = path.join(parent, "out-root"); + await exportDirectory({ + repoUrl: fixture, + sourcePath: "", + outputDir: out, + ref: null, + depth: 1, + force: false, + gitBin: "git", + verbose: false, + }); + expect(await pathExists(path.join(out, "root.txt"))).toBe(true); + expect(await pathExists(path.join(out, "pkg", "sub", "file.txt"))).toBe( + true, + ); + expect(await pathExists(path.join(out, ".git"))).toBe(false); + expect(await pathExists(path.join(out, "emptydir", ".gitkeep"))).toBe(true); + expect( + await pathExists(path.join(out, "pkg", "emptysub", ".gitkeep")), + ).toBe(true); + }); + + test("tag ref exports old content with verbose", async () => { + const fixture = await initFixtureRepo(); + const parent = await makeTmp("git-export-e2e-"); + const out = path.join(parent, "out-tag"); + const cap = captureLog(); + try { + await exportDirectory({ + repoUrl: fixture, + sourcePath: "pkg/sub", + outputDir: out, + ref: "v1", + depth: 1, + force: false, + gitBin: "git", + verbose: true, + }); + } finally { + cap.restore(); + } + expect(await Bun.file(path.join(out, "file.txt")).text()).toBe("hello sub"); + expect(await pathExists(path.join(out, "extra.txt"))).toBe(false); + expect(cap.logs.join("\n")).toContain("cwd="); + }); + + test("force-overwrite existing output", async () => { + const fixture = await initFixtureRepo(); + const parent = await makeTmp("git-export-e2e-"); + const out = path.join(parent, "out-force"); + await mkdir(out, { recursive: true }); + await Bun.write(path.join(out, "stale.txt"), "stale"); + await exportDirectory({ + repoUrl: fixture, + sourcePath: "pkg/sub", + outputDir: out, + ref: null, + depth: 1, + force: true, + gitBin: "git", + verbose: false, + }); + expect(await pathExists(path.join(out, "stale.txt"))).toBe(false); + expect(await pathExists(path.join(out, "file.txt"))).toBe(true); + }); + + test("existing output without force fails", async () => { + const fixture = await initFixtureRepo(); + const parent = await makeTmp("git-export-e2e-"); + const out = path.join(parent, "out-noforce"); + await mkdir(out, { recursive: true }); + await expect( + exportDirectory({ + repoUrl: fixture, + sourcePath: "pkg/sub", + outputDir: out, + ref: null, + depth: 1, + force: false, + gitBin: "git", + verbose: false, + }), + ).rejects.toThrow("already exists"); + }); + + test("missing source dir failure", async () => { + const fixture = await initFixtureRepo(); + const parent = await makeTmp("git-export-e2e-"); + const out = path.join(parent, "out-missing"); + await expect( + exportDirectory({ + repoUrl: fixture, + sourcePath: "does/not/exist", + outputDir: out, + ref: null, + depth: 1, + force: false, + gitBin: "git", + verbose: false, + }), + ).rejects.toThrow("Source directory not found"); + }); + + test("file-at-output replace", async () => { + const fixture = await initFixtureRepo(); + const parent = await makeTmp("git-export-e2e-"); + const out = path.join(parent, "out-file"); + await Bun.write(out, "i am a file"); + await exportDirectory({ + repoUrl: fixture, + sourcePath: "pkg/sub", + outputDir: out, + ref: null, + depth: 1, + force: true, + gitBin: "git", + verbose: false, + }); + expect(await isDirectory(out)).toBe(true); + expect(await pathExists(path.join(out, "file.txt"))).toBe(true); + }); + + test("emptydir with gitkeep exports (empty-dir case)", async () => { + const fixture = await initFixtureRepo(); + const parent = await makeTmp("git-export-e2e-"); + const out = path.join(parent, "out-empty"); + await exportDirectory({ + repoUrl: fixture, + sourcePath: "emptydir", + outputDir: out, + ref: null, + depth: 1, + force: false, + gitBin: "git", + verbose: false, + }); + expect(await isDirectory(out)).toBe(true); + expect(await readdir(out)).toHaveLength(1); + expect(await pathExists(path.join(out, ".gitkeep"))).toBe(true); + }); + + test("output parent missing resolves via fallback", async () => { + const fixture = await initFixtureRepo(); + const parent = await makeTmp("git-export-e2e-"); + const out = path.join(parent, "no-such-parent", "out"); + await exportDirectory({ + repoUrl: fixture, + sourcePath: "pkg/sub", + outputDir: out, + ref: null, + depth: 1, + force: false, + gitBin: "git", + verbose: false, + }); + expect(await pathExists(path.join(out, "file.txt"))).toBe(true); + }); +}); + +describe("runMain", () => { + test("local fixture with --path succeeds", async () => { + const fixture = await initFixtureRepo(); + const parent = await makeTmp("git-export-runmain-"); + const out = path.join(parent, "out"); + await runMain([fixture, out, "--path", "pkg/sub"]); + expect(await Bun.file(path.join(out, "file.txt")).text()).toBe( + "hello sub v2", + ); + }); + + test("local without --path fails", async () => { + const fixture = await initFixtureRepo(); + const parent = await makeTmp("git-export-runmain-"); + const out = path.join(parent, "out"); + await expect(runMain([fixture, out])).rejects.toThrow("--path is required"); + }); + + test("github root with --path uses false git (no network)", async () => { + const parent = await makeTmp("git-export-runmain-"); + const out = path.join(parent, "out"); + await expect( + runMain([ + "https://github.com/o/r", + out, + "--path", + "a/b", + "--git", + "false", + ]), + ).rejects.toThrow("git command failed"); + }); + + test("github tree url uses parsed path and ref (no network)", async () => { + const parent = await makeTmp("git-export-runmain-"); + const out = path.join(parent, "out"); + await expect( + runMain([ + "https://github.com/o/r/tree/main/src/app", + out, + "--git", + "false", + ]), + ).rejects.toThrow("git command failed"); + }); + + test("github root without --path defaults to empty (no network)", async () => { + const parent = await makeTmp("git-export-runmain-"); + const out = path.join(parent, "out"); + await expect( + runMain(["https://github.com/o/r", out, "--git", "false"]), + ).rejects.toThrow("git command failed"); + }); + + test("github tree with --ref override (no network)", async () => { + const parent = await makeTmp("git-export-runmain-"); + const out = path.join(parent, "out"); + await expect( + runMain([ + "https://github.com/o/r/tree/main/src/app", + out, + "--ref", + "v2", + "--git", + "false", + ]), + ).rejects.toThrow("git command failed"); + }); + + test("main uses process.argv", async () => { + const fixture = await initFixtureRepo(); + const parent = await makeTmp("git-export-main-"); + const out = path.join(parent, "out"); + const origArgv = process.argv; + process.argv = ["bun", "git-export.ts", fixture, out, "--path", "pkg/sub"]; + try { + await main(); + } finally { + process.argv = origArgv; + } + expect(await pathExists(path.join(out, "file.txt"))).toBe(true); + }); +}); + +describe("cli subprocess", () => { + test("bad source exit code", async () => { + const parent = await makeTmp("git-export-cli-"); + const out = path.join(parent, "out"); + const script = new URL("./git-export.ts", import.meta.url).pathname; + const proc = Bun.spawn( + ["bun", script, "/nonexistent-source-xyz", out, "--path", "a"], + { + stdout: "pipe", + stderr: "pipe", + }, + ); + const [code] = await Promise.all([proc.exited]); + expect(code).not.toBe(0); + }, 30000); + + test("--help exit 0", async () => { + const script = new URL("./git-export.ts", import.meta.url).pathname; + const proc = Bun.spawn(["bun", script, "--help"], { + stdout: "pipe", + stderr: "pipe", + }); + const [outText, errText, code] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + proc.exited, + ]); + expect(code).toBe(0); + expect(outText + errText).toContain("Usage:"); + }, 30000); +}); diff --git a/scripts/git-export.ts b/scripts/git-export.ts index 827c892..b3e8ca3 100644 --- a/scripts/git-export.ts +++ b/scripts/git-export.ts @@ -1,5 +1,5 @@ #!/usr/bin/env bun -import { constants as fsConstants } from "node:fs" +import { constants as fsConstants } from "node:fs"; import { copyFile, cp, @@ -12,182 +12,197 @@ import { rm, symlink, unlink, -} from "node:fs/promises" -import os from "node:os" -import path from "node:path" +} from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; -class GitExportError extends Error { +export class GitExportError extends Error { constructor(message: string) { - super(message) - this.name = "GitExportError" + super(message); + this.name = "GitExportError"; } } -type Options = { - source: string - output: string - ref: string | null - sourcePath: string | null - depth: number - gitBin: string - force: boolean - verbose: boolean -} - -type ParsedGithubUrl = { - repoUrl: string - sourcePath: string | null - ref: string | null -} +export type Options = { + source: string; + output: string; + ref: string | null; + sourcePath: string | null; + depth: number; + gitBin: string; + force: boolean; + verbose: boolean; +}; + +export type ParsedGithubUrl = { + repoUrl: string; + sourcePath: string | null; + ref: string | null; +}; function info(message: string) { - console.log(`[git-export] ${message}`) + console.log(`[git-export] ${message}`); } function fail(message: string): never { - throw new GitExportError(message) + throw new GitExportError(message); } -async function pathExists(target: string) { +export async function pathExists(target: string) { try { - await lstat(target) - return true + await lstat(target); + return true; } catch { - return false + return false; } } -async function isDirectory(target: string) { +export async function isDirectory(target: string) { try { - const stat = await lstat(target) - return stat.isDirectory() && !stat.isSymbolicLink() + const stat = await lstat(target); + return stat.isDirectory() && !stat.isSymbolicLink(); } catch { - return false + return false; } } -function formatCommand(args: string[]) { - return args.map((arg) => (/[\s"']/u.test(arg) ? JSON.stringify(arg) : arg)).join(" ") +export function formatCommand(args: string[]) { + return args + .map((arg) => (/[\s"']/u.test(arg) ? JSON.stringify(arg) : arg)) + .join(" "); } -async function runGit(gitBin: string, args: string[], cwd?: string, verbose = false) { - const cmd = [gitBin, ...args] +export async function runGit( + gitBin: string, + args: string[], + cwd?: string, + verbose = false, +) { + const cmd = [gitBin, ...args]; if (verbose) { - info(`+ (cwd=${cwd || process.cwd()}) ${formatCommand(cmd)}`) + info(`+ (cwd=${cwd || process.cwd()}) ${formatCommand(cmd)}`); } const proc = Bun.spawn(cmd, { cwd, stdout: "pipe", stderr: "pipe", - }) + }); const [stdoutText, stderrText, code] = await Promise.all([ new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited, - ]) + ]); if (code !== 0) { - const stderr = stderrText.trim() - const stdout = stdoutText.trim() - const detail = stderr || stdout || `exit code ${code}` - fail(`git command failed: ${formatCommand(cmd)}\n${detail}`) + const stderr = stderrText.trim(); + const stdout = stdoutText.trim(); + const detail = stderr || stdout || `exit code ${String(code)}`; + fail(`git command failed: ${formatCommand(cmd)}\n${detail}`); } } -function normalizeSourcePath(value: string) { - const source = value.trim().replace(/^\/+|\/+$/g, "") - if (!source) fail("Source path must not be empty") +export function normalizeSourcePath(value: string) { + const source = value.trim().replace(/^\/+|\/+$/g, ""); + if (!source) fail("Source path must not be empty"); - const parts = source.split("/").filter((part) => part && part !== ".") + const parts = source.split("/").filter((part) => part && part !== "."); if (parts.some((part) => part === "..")) { - fail("Source path must not contain '..'") + fail("Source path must not contain '..'"); } - return parts.join("/") + return parts.join("/"); } -function parseGithubDirectoryUrl(rawUrl: string): ParsedGithubUrl { - let parsed: URL +export function parseGithubDirectoryUrl(rawUrl: string): ParsedGithubUrl { + let parsed: URL; try { - parsed = new URL(rawUrl) + parsed = new URL(rawUrl); } catch { - fail(`Not a supported GitHub URL: ${rawUrl}`) + fail(`Not a supported GitHub URL: ${rawUrl}`); } - if (!["http:", "https:"].includes(parsed.protocol) || !["github.com", "www.github.com"].includes(parsed.hostname)) { - fail(`Not a supported GitHub URL: ${rawUrl}`) + if ( + !["http:", "https:"].includes(parsed.protocol) || + !["github.com", "www.github.com"].includes(parsed.hostname) + ) { + fail(`Not a supported GitHub URL: ${rawUrl}`); } - const parts = parsed.pathname.split("/").filter(Boolean) - if (parts.length < 2) { - fail(`GitHub URL must include owner/repo (got: ${rawUrl})`) + const parts = parsed.pathname.split("/").filter(Boolean); + const owner = parts[0]; + const repoRaw = parts[1]; + if (!owner || !repoRaw) { + fail(`GitHub URL must include owner/repo (got: ${rawUrl})`); } - const owner = parts[0] - const repo = parts[1].endsWith(".git") ? parts[1].slice(0, -4) : parts[1] - const rest = parts.slice(2) + const repo = repoRaw.endsWith(".git") ? repoRaw.slice(0, -4) : repoRaw; + const rest = parts.slice(2); - let ref: string | null = null - let sourcePath: string | null = null + let ref: string | null = null; + let sourcePath: string | null = null; - if (rest.length === 0) { - sourcePath = null - } else if (rest[0] === "tree" || rest[0] === "blob") { - if (rest.length < 3) { - fail(`tree/blob URLs must include ref and directory path, got: ${rawUrl}`) + if (rest.length !== 0) { + if (rest[0] === "tree" || rest[0] === "blob") { + if (rest.length < 3) { + fail( + `tree/blob URLs must include ref and directory path, got: ${rawUrl}`, + ); + } + ref = rest[1]; + sourcePath = rest.slice(2).join("/"); + } else { + sourcePath = rest.join("/"); } - ref = rest[1] - sourcePath = rest.slice(2).join("/") - } else { - sourcePath = rest.join("/") } return { repoUrl: `https://github.com/${owner}/${repo}.git`, sourcePath: sourcePath === null ? null : normalizeSourcePath(sourcePath), ref, - } + }; } -async function prepareOutputDir(outputDir: string, force: boolean) { +export async function prepareOutputDir(outputDir: string, force: boolean) { if (await pathExists(outputDir)) { if (!force) { - fail(`Output path already exists: ${outputDir} (use --force to overwrite)`) + fail( + `Output path already exists: ${outputDir} (use --force to overwrite)`, + ); } - const stat = await lstat(outputDir) + const stat = await lstat(outputDir); if (stat.isFile() || stat.isSymbolicLink()) { - await unlink(outputDir) + await unlink(outputDir); } else { - await rm(outputDir, { recursive: true, force: true }) + await rm(outputDir, { recursive: true, force: true }); } } - await mkdir(outputDir, { recursive: true }) + await mkdir(outputDir, { recursive: true }); } -async function removeExisting(dst: string) { - if (!(await pathExists(dst))) return +export async function removeExisting(dst: string) { + if (!(await pathExists(dst))) return; - const stat = await lstat(dst) + const stat = await lstat(dst); if (stat.isDirectory() && !stat.isSymbolicLink()) { - await rm(dst, { recursive: true, force: true }) - return + await rm(dst, { recursive: true, force: true }); + return; } - await unlink(dst) + await unlink(dst); } -async function copyEntry(src: string, dst: string) { - const stat = await lstat(src) +export async function copyEntry(src: string, dst: string) { + const stat = await lstat(src); if (stat.isSymbolicLink()) { - const target = await readlink(src) - await removeExisting(dst) - await symlink(target, dst) - return + const target = await readlink(src); + await removeExisting(dst); + await symlink(target, dst); + return; } if (stat.isDirectory()) { @@ -196,175 +211,218 @@ async function copyEntry(src: string, dst: string) { dereference: false, force: true, verbatimSymlinks: true, - }) - return + }); + return; } - await copyFile(src, dst, fsConstants.COPYFILE_FICLONE) + await copyFile(src, dst, fsConstants.COPYFILE_FICLONE); } -async function exportDirectory(options: { - repoUrl: string - sourcePath: string - outputDir: string - ref: string | null - depth: number - force: boolean - gitBin: string - verbose: boolean +export async function exportDirectory(options: { + repoUrl: string; + sourcePath: string; + outputDir: string; + ref: string | null; + depth: number; + force: boolean; + gitBin: string; + verbose: boolean; }) { - const start = performance.now() - const sourcePath = options.sourcePath.replace(/^\/+|\/+$/g, "") + const start = performance.now(); + const sourcePath = options.sourcePath.replace(/^\/+|\/+$/g, ""); const outputDir = await realpath(path.dirname(options.outputDir)).then( (parent) => path.join(parent, path.basename(options.outputDir)), () => path.resolve(options.outputDir), - ) + ); - info(`Repository: ${options.repoUrl}`) - info(`Source path: ${sourcePath || "(repo root)"}`) - info(`Ref: ${options.ref || "default branch"}`) - info(`Output: ${outputDir}`) + info(`Repository: ${options.repoUrl}`); + info(`Source path: ${sourcePath || "(repo root)"}`); + info(`Ref: ${options.ref || "default branch"}`); + info(`Output: ${outputDir}`); - const workDir = await mkdtemp(path.join(os.tmpdir(), "git-export-")) - const cloneDir = path.join(workDir, "repo") + const workDir = await mkdtemp(path.join(os.tmpdir(), "git-export-")); + const cloneDir = path.join(workDir, "repo"); try { - info("Step 1/6: cloning repository (treeless + sparse, no checkout)") - let stepStart = performance.now() - await runGit(options.gitBin, [ - "clone", - "--depth", - String(options.depth), - "--filter=tree:0", - "--sparse", - "--no-checkout", - options.repoUrl, + info("Step 1/6: cloning repository (treeless + sparse, no checkout)"); + let stepStart = performance.now(); + await runGit( + options.gitBin, + [ + "clone", + "--depth", + String(options.depth), + "--filter=tree:0", + "--sparse", + "--no-checkout", + options.repoUrl, + cloneDir, + ], + undefined, + options.verbose, + ); + info( + `Step 1/6 complete in ${((performance.now() - stepStart) / 1000).toFixed(1)}s`, + ); + + info("Step 2/6: configuring sparse checkout"); + stepStart = performance.now(); + await runGit( + options.gitBin, + ["sparse-checkout", "init", "--cone"], cloneDir, - ], undefined, options.verbose) - info(`Step 1/6 complete in ${((performance.now() - stepStart) / 1000).toFixed(1)}s`) - - info("Step 2/6: configuring sparse checkout") - stepStart = performance.now() - await runGit(options.gitBin, ["sparse-checkout", "init", "--cone"], cloneDir, options.verbose) + options.verbose, + ); if (sourcePath) { - await runGit(options.gitBin, ["sparse-checkout", "set", "--", sourcePath], cloneDir, options.verbose) + await runGit( + options.gitBin, + ["sparse-checkout", "set", "--", sourcePath], + cloneDir, + options.verbose, + ); } else { - await runGit(options.gitBin, ["sparse-checkout", "disable"], cloneDir, options.verbose) + await runGit( + options.gitBin, + ["sparse-checkout", "disable"], + cloneDir, + options.verbose, + ); } - info(`Step 2/6 complete in ${((performance.now() - stepStart) / 1000).toFixed(1)}s`) + info( + `Step 2/6 complete in ${((performance.now() - stepStart) / 1000).toFixed(1)}s`, + ); - info("Step 3/6: checking out requested ref/path") - stepStart = performance.now() + info("Step 3/6: checking out requested ref/path"); + stepStart = performance.now(); if (options.ref) { - await runGit(options.gitBin, ["fetch", "--depth", String(options.depth), "origin", options.ref], cloneDir, options.verbose) - await runGit(options.gitBin, ["checkout", "--detach", "FETCH_HEAD"], cloneDir, options.verbose) + await runGit( + options.gitBin, + ["fetch", "--depth", String(options.depth), "origin", options.ref], + cloneDir, + options.verbose, + ); + await runGit( + options.gitBin, + ["checkout", "--detach", "FETCH_HEAD"], + cloneDir, + options.verbose, + ); } else { - await runGit(options.gitBin, ["checkout"], cloneDir, options.verbose) + await runGit(options.gitBin, ["checkout"], cloneDir, options.verbose); } - info(`Step 3/6 complete in ${((performance.now() - stepStart) / 1000).toFixed(1)}s`) + info( + `Step 3/6 complete in ${((performance.now() - stepStart) / 1000).toFixed(1)}s`, + ); - info("Step 4/6: validating source directory") - const sourceDir = sourcePath ? path.join(cloneDir, sourcePath) : cloneDir + info("Step 4/6: validating source directory"); + const sourceDir = sourcePath ? path.join(cloneDir, sourcePath) : cloneDir; if (!(await isDirectory(sourceDir))) { fail( `Source directory not found after checkout: ${sourcePath || "."}\nRepository: ${options.repoUrl}\nRef: ${options.ref || "default branch"}`, - ) + ); } - info("Step 4/6 complete") - - info("Step 5/6: preparing output directory") - stepStart = performance.now() - await prepareOutputDir(outputDir, options.force) - info(`Step 5/6 complete in ${((performance.now() - stepStart) / 1000).toFixed(1)}s`) - - info("Step 6/6: copying exported files") - stepStart = performance.now() - const children = await readdir(sourceDir) - const totalChildren = children.length + info("Step 4/6 complete"); + + info("Step 5/6: preparing output directory"); + stepStart = performance.now(); + await prepareOutputDir(outputDir, options.force); + info( + `Step 5/6 complete in ${((performance.now() - stepStart) / 1000).toFixed(1)}s`, + ); + + info("Step 6/6: copying exported files"); + stepStart = performance.now(); + const children = await readdir(sourceDir); + const totalChildren = children.length; if (totalChildren === 0) { - info("Source directory is empty") + info("Source directory is empty"); } for (const [index, name] of children.entries()) { + const progress = `${String(index + 1)}/${String(totalChildren)}`; if (name === ".git") { - info(` - [${index + 1}/${totalChildren}] ${name} (skipped)`) - continue + info(` - [${progress}] ${name} (skipped)`); + continue; } - info(` - [${index + 1}/${totalChildren}] ${name}`) - await copyEntry(path.join(sourceDir, name), path.join(outputDir, name)) + info(` - [${progress}] ${name}`); + await copyEntry(path.join(sourceDir, name), path.join(outputDir, name)); } - info(`Step 6/6 complete in ${((performance.now() - stepStart) / 1000).toFixed(1)}s`) + info( + `Step 6/6 complete in ${((performance.now() - stepStart) / 1000).toFixed(1)}s`, + ); } finally { - await rm(workDir, { recursive: true, force: true }) + await rm(workDir, { recursive: true, force: true }); } - info("Finalizing export (removing .git if present)") - await rm(path.join(outputDir, ".git"), { recursive: true, force: true }) - info(`Export complete in ${((performance.now() - start) / 1000).toFixed(1)}s`) + info("Finalizing export (removing .git if present)"); + await rm(path.join(outputDir, ".git"), { recursive: true, force: true }); + info( + `Export complete in ${((performance.now() - start) / 1000).toFixed(1)}s`, + ); } -function parseArgs(argv: string[]): Options { - const positionals: string[] = [] - let ref: string | null = null - let sourcePath: string | null = null - let depth = 1 - let gitBin = "git" - let force = false - let verbose = false +export function parseArgs(argv: string[]): Options { + const positionals: string[] = []; + let ref: string | null = null; + let sourcePath: string | null = null; + let depth = 1; + let gitBin = "git"; + let force = false; + let verbose = false; for (let i = 0; i < argv.length; i += 1) { - const arg = argv[i] + const arg = argv[i] ?? fail("unreachable: missing argv entry"); if (arg === "--ref") { - ref = argv[++i] ?? fail("--ref requires a value") - continue + ref = argv[++i] ?? fail("--ref requires a value"); + continue; } if (arg === "--path") { - sourcePath = argv[++i] ?? fail("--path requires a value") - continue + sourcePath = argv[++i] ?? fail("--path requires a value"); + continue; } if (arg === "--depth") { - const value = argv[++i] ?? fail("--depth requires a value") - depth = Number.parseInt(value, 10) + const value = argv[++i] ?? fail("--depth requires a value"); + depth = Number.parseInt(value, 10); if (!Number.isInteger(depth) || depth <= 0) { - fail(`Invalid --depth value: ${value}`) + fail(`Invalid --depth value: ${value}`); } - continue + continue; } if (arg === "--git") { - gitBin = argv[++i] ?? fail("--git requires a value") - continue + gitBin = argv[++i] ?? fail("--git requires a value"); + continue; } if (arg === "--force") { - force = true - continue + force = true; + continue; } if (arg === "--verbose") { - verbose = true - continue + verbose = true; + continue; } if (arg === "-h" || arg === "--help") { - printHelp() - process.exit(0) + printHelp(); + process.exit(0); } if (arg.startsWith("-")) { - fail(`Unknown option: ${arg}`) + fail(`Unknown option: ${arg}`); } - positionals.push(arg) + positionals.push(arg); } if (positionals.length !== 2) { - printHelp() - fail("Expected SOURCE and OUTPUT arguments") + printHelp(); + fail("Expected SOURCE and OUTPUT arguments"); } return { @@ -376,10 +434,10 @@ function parseArgs(argv: string[]): Options { gitBin, force, verbose, - } + }; } -function printHelp() { +export function printHelp() { console.log(`Usage: git-export.ts SOURCE OUTPUT [options] Export a directory from a GitHub repository. @@ -391,16 +449,21 @@ Options: --git Git binary to use (default: git) --force Overwrite output if it exists --verbose Print git commands - -h, --help Show this help message`) + -h, --help Show this help message`); } -async function main() { - const args = parseArgs(process.argv.slice(2)) +export async function runMain(argv: string[]) { + const args = parseArgs(argv); if (args.source.startsWith("https://github.com/")) { - const parsed = parseGithubDirectoryUrl(args.source) - const sourcePath = parsed.sourcePath === null ? (args.sourcePath ? normalizeSourcePath(args.sourcePath) : "") : parsed.sourcePath - const ref = args.ref ?? parsed.ref + const parsed = parseGithubDirectoryUrl(args.source); + const sourcePath = + parsed.sourcePath === null + ? args.sourcePath + ? normalizeSourcePath(args.sourcePath) + : "" + : parsed.sourcePath; + const ref = args.ref ?? parsed.ref; await exportDirectory({ repoUrl: parsed.repoUrl, @@ -411,12 +474,12 @@ async function main() { force: args.force, gitBin: args.gitBin, verbose: args.verbose, - }) - return + }); + return; } if (!args.sourcePath) { - fail("--path is required when source is not a GitHub directory URL") + fail("--path is required when source is not a GitHub directory URL"); } await exportDirectory({ @@ -428,16 +491,22 @@ async function main() { force: args.force, gitBin: args.gitBin, verbose: args.verbose, - }) + }); } -await main().catch((err) => { - const message = err instanceof Error ? err.message : String(err) - if (err instanceof GitExportError) { - console.error(`Error: ${message}`) - process.exit(2) - } +export async function main() { + await runMain(process.argv.slice(2)); +} + +if (import.meta.main) { + await main().catch((err: unknown) => { + const message = err instanceof Error ? err.message : String(err); + if (err instanceof GitExportError) { + console.error(`Error: ${message}`); + process.exit(2); + } - console.error(`Error: ${message}`) - process.exit(1) -}) + console.error(`Error: ${message}`); + process.exit(1); + }); +} diff --git a/scripts/install-skills.test.ts b/scripts/install-skills.test.ts new file mode 100644 index 0000000..d19ed89 --- /dev/null +++ b/scripts/install-skills.test.ts @@ -0,0 +1,1325 @@ +import { describe, test, expect, afterEach } from "bun:test"; +import { + mkdtemp, + rm, + mkdir, + symlink, + readFile, + readdir, +} from "node:fs/promises"; +import path from "node:path"; +import { + parse, + applyFileStep, + updateAgentsMd, + runShellStep, + flattenSkills, + collectAgentsMd, + isGroup, + runSkill, + run, + safe, + resolveLatestReleaseTag, + resolveRef, + workspaceKey, + copySubtreeFromWorkspace, + cleanupWorkspaces, + shell, + workspaces, + gitExportScript, + type Step, +} from "./install-skills.ts"; + +const START = ""; +const END = ""; +const tmpRoots: string[] = []; +const originalFetch = globalThis.fetch; +const originalGitExportScript = process.env.GIT_EXPORT_SCRIPT; + +async function makeTmp(prefix = "install-skills-test-") { + await mkdir("/tmp/opencode", { recursive: true }).catch(() => {}); + const dir = await mkdtemp(path.join("/tmp/opencode/", prefix)); + tmpRoots.push(dir); + return dir; +} + +afterEach(async () => { + globalThis.fetch = originalFetch; + if (originalGitExportScript === undefined) { + delete process.env.GIT_EXPORT_SCRIPT; + } else { + process.env.GIT_EXPORT_SCRIPT = originalGitExportScript; + } + await cleanupWorkspaces().catch(() => {}); + workspaces.clear(); + let dir: string | undefined; + while ((dir = tmpRoots.pop()) !== undefined) { + await rm(dir, { recursive: true, force: true }).catch(() => {}); + } +}); + +async function stageWith(files: Record) { + const dir = await makeTmp(); + for (const [rel, content] of Object.entries(files)) { + await Bun.write(path.join(dir, rel), content); + } + return dir; +} + +describe("parse", () => { + test("old manifest without agents_md works", () => { + const m = parse( + "skills:\n - name: a\n steps:\n - type: download\n url: https://example.com/x\n dest: SKILL.md\n", + ); + expect(m.skills).toHaveLength(1); + expect(m.agents_md).toBeUndefined(); + }); + + test("agents_md is retained", () => { + const m = parse("skills: []\nagents_md: |\n ## hi\n body\n"); + expect(m.agents_md).toContain("## hi"); + }); + + test("per-skill agents_md is retained", () => { + const m = parse( + "skills:\n - name: a\n steps: []\n agents_md: |\n ## hi\n body\n", + ); + expect(m.skills).toHaveLength(1); + expect(m.skills[0].agents_md).toContain("## hi"); + expect(m.agents_md).toBeUndefined(); + }); + + test("per-skill agents_md malformed fails", () => { + expect(() => + parse('skills:\n - name: a\n steps: []\n agents_md: " "\n'), + ).toThrow("[install-skills]"); + expect(() => + parse( + `skills:\n - name: a\n steps: []\n agents_md: "x ${START} y"\n`, + ), + ).toThrow("[install-skills]"); + expect(() => + parse( + `skills:\n - name: a\n steps: []\n agents_md: "x ${END} y"\n`, + ), + ).toThrow("[install-skills]"); + expect(() => + parse("skills:\n - name: a\n steps: []\n agents_md: 42\n"), + ).toThrow("[install-skills]"); + }); + + test("replace expected is optional but must be a positive integer when present", () => { + const m = parse( + "skills:\n - name: a\n steps:\n - type: replace\n file: SKILL.md\n from: x\n to: y\n", + ); + expect(m.skills).toHaveLength(1); + for (const bad of [ + "expected: 0", + "expected: -2", + "expected: 1.5", + "expected: '3'", + ]) { + expect(() => + parse( + `skills:\n - name: a\n steps:\n - type: replace\n file: SKILL.md\n from: x\n to: y\n ${bad}\n`, + ), + ).toThrow("[install-skills]"); + } + }); + + test("malformed new fields fail", () => { + expect(() => + parse( + "skills:\n - name: a\n steps:\n - type: replace\n file: SKILL.md\n from: ''\n to: x\n expected: 1\n", + ), + ).toThrow("[install-skills]"); + expect(() => + parse( + "skills:\n - name: a\n steps:\n - type: replace\n file: SKILL.md\n from: x\n to: y\n expected: 0\n", + ), + ).toThrow("[install-skills]"); + expect(() => + parse( + "skills:\n - name: a\n steps:\n - type: assert-absent\n file: SKILL.md\n pattern: ''\n", + ), + ).toThrow("[install-skills]"); + expect(() => + parse( + "skills:\n - name: a\n steps:\n - type: replace\n file: ''\n from: x\n to: y\n expected: 1\n", + ), + ).toThrow("[install-skills]"); + expect(() => + parse("skills:\n - name: a\n steps:\n - type: nope\n"), + ).toThrow("[install-skills]"); + }); + + test("invalid regex fails", () => { + expect(() => + parse( + "skills:\n - name: a\n steps:\n - type: assert-absent\n file: SKILL.md\n pattern: '(['\n", + ), + ).toThrow("[install-skills]"); + }); + + test("duplicate and unsafe names fail", () => { + expect(() => + parse( + "skills:\n - name: a\n steps: []\n - name: a\n steps: []\n", + ), + ).toThrow("[install-skills]"); + for (const bad of ["../x", "/abs", "a/b", "a\\b", ".", ".."]) { + expect(() => + parse(`skills:\n - name: ${JSON.stringify(bad)}\n steps: []\n`), + ).toThrow("[install-skills]"); + } + }); + + test("shell commands required", () => { + const m = parse( + "skills:\n - name: a\n steps:\n - type: shell\n commands: |\n echo hi\n", + ); + expect(m.skills).toHaveLength(1); + expect(() => + parse("skills:\n - name: a\n steps:\n - type: shell\n"), + ).toThrow("[install-skills]"); + expect(() => + parse( + "skills:\n - name: a\n steps:\n - type: shell\n commands: ''\n", + ), + ).toThrow("[install-skills]"); + expect(() => + parse( + "skills:\n - name: a\n steps:\n - type: shell\n commands: ' '\n", + ), + ).toThrow("[install-skills]"); + expect(() => + parse( + "skills:\n - name: a\n steps:\n - type: shell\n commands: 42\n", + ), + ).toThrow("[install-skills]"); + }); + + test("agents_md with marker or blank fails", () => { + expect(() => parse(`skills: []\nagents_md: " "\n`)).toThrow( + "[install-skills]", + ); + expect(() => + parse(`skills: []\nagents_md: "has ${START} inside"\n`), + ).toThrow("[install-skills]"); + expect(() => parse(`skills: []\nagents_md: "has ${END} inside"\n`)).toThrow( + "[install-skills]", + ); + }); + + test("group parses, flattens and collects guidance in order", () => { + const m = parse( + [ + "skills:", + " - name: solo", + " steps: []", + " agents_md: |", + " ## solo", + " - group: tools", + " agents_md: |", + " ## group-md", + " skills:", + " - name: a", + " steps: []", + " - name: b", + " steps: []", + " agents_md: |", + " ## b-md", + "", + ].join("\n"), + ); + expect(m.skills).toHaveLength(2); + expect(isGroup(m.skills[0])).toBe(false); + expect(isGroup(m.skills[1])).toBe(true); + const flat = flattenSkills(m.skills); + expect(flat.map((s) => s.name)).toEqual(["solo", "a", "b"]); + expect(collectAgentsMd(m)).toEqual(["## solo", "## group-md", "## b-md"]); + }); + + test("group validation fails", () => { + expect(() => + parse( + "skills:\n - group: ''\n skills:\n - name: a\n steps: []\n", + ), + ).toThrow("[install-skills]"); + expect(() => parse("skills:\n - group: g\n skills: []\n")).toThrow( + "[install-skills]", + ); + expect(() => + parse( + "skills:\n - group: g\n name: x\n skills:\n - name: a\n steps: []\n", + ), + ).toThrow("[install-skills]"); + expect(() => + parse( + "skills:\n - group: g\n steps: []\n skills:\n - name: a\n steps: []\n", + ), + ).toThrow("[install-skills]"); + expect(() => + parse( + "skills:\n - group: g\n skills:\n - group: nested\n skills:\n - name: a\n steps: []\n", + ), + ).toThrow("[install-skills]"); + expect(() => + parse( + "skills:\n - name: a\n steps: []\n - group: g\n skills:\n - name: a\n steps: []\n", + ), + ).toThrow("duplicate skill name"); + expect(() => + parse( + "skills:\n - group: g\n skills:\n - name: a\n steps: []\n - group: g\n skills:\n - name: b\n steps: []\n", + ), + ).toThrow("duplicate group name"); + expect(() => + parse( + "skills:\n - group: g\n agents_md: ' '\n skills:\n - name: a\n steps: []\n", + ), + ).toThrow("[install-skills]"); + expect(() => + parse("skills:\n - name: a\n group: g\n steps: []\n"), + ).toThrow("[install-skills]"); + }); +}); + +describe("replace", () => { + test("exact count, multiline, empty replacement, literal $&", async () => { + const dir = await stageWith({ + "SKILL.md": + "a `npx -y @firecrawl/anydoc` b `npx -y @firecrawl/anydoc` c `npx -y @firecrawl/anydoc` keep", + }); + await applyFileStep( + "s", + { + type: "replace", + file: "SKILL.md", + from: "npx -y @firecrawl/anydoc", + to: "anydoc", + expected: 3, + }, + dir, + ); + const after = await Bun.file(path.join(dir, "SKILL.md")).text(); + expect(after).toBe("a `anydoc` b `anydoc` c `anydoc` keep"); + + const dir2 = await stageWith({ "f.md": "line1\nOLD\nline3\nOLD tail" }); + await applyFileStep( + "s", + { type: "replace", file: "f.md", from: "OLD\n", to: "", expected: 1 }, + dir2, + ); + expect(await Bun.file(path.join(dir2, "f.md")).text()).toBe( + "line1\nline3\nOLD tail", + ); + + const dir3 = await stageWith({ "g.md": "price: X here" }); + await applyFileStep( + "s", + { type: "replace", file: "g.md", from: "X", to: "$& $' $`", expected: 1 }, + dir3, + ); + expect(await Bun.file(path.join(dir3, "g.md")).text()).toBe( + "price: $& $' $` here", + ); + }); + + test("count mismatch throws and leaves input unchanged", async () => { + for (const expected of [2, 5]) { + const dir = await stageWith({ + "SKILL.md": "one npx -y @firecrawl/anydoc two", + }); + const before = await Bun.file(path.join(dir, "SKILL.md")).text(); + await expect( + applyFileStep( + "s", + { + type: "replace", + file: "SKILL.md", + from: "npx -y @firecrawl/anydoc", + to: "anydoc", + expected, + }, + dir, + ), + ).rejects.toThrow("[install-skills]"); + expect(await Bun.file(path.join(dir, "SKILL.md")).text()).toBe(before); + } + const dir = await stageWith({ "SKILL.md": "no match here" }); + await expect( + applyFileStep( + "s", + { + type: "replace", + file: "SKILL.md", + from: "missing", + to: "x", + expected: 1, + }, + dir, + ), + ).rejects.toThrow("[install-skills]"); + }); + + test("omitted expected replaces all, zero matches fail", async () => { + const dir = await stageWith({ "SKILL.md": "a `npx` b `npx` c keep" }); + await applyFileStep( + "s", + { type: "replace", file: "SKILL.md", from: "`npx`", to: "`anydoc`" }, + dir, + ); + expect(await Bun.file(path.join(dir, "SKILL.md")).text()).toBe( + "a `anydoc` b `anydoc` c keep", + ); + + const dir2 = await stageWith({ "SKILL.md": "no match here" }); + await expect( + applyFileStep( + "s", + { type: "replace", file: "SKILL.md", from: "missing", to: "x" }, + dir2, + ), + ).rejects.toThrow("at least 1 occurrence"); + expect(await Bun.file(path.join(dir2, "SKILL.md")).text()).toBe( + "no match here", + ); + }); +}); + +describe("assert-absent", () => { + test("matching content fails, nonmatching succeeds without changing bytes", async () => { + const dir = await stageWith({ + "SKILL.md": "run npx -y blah @firecrawl/anydoc now", + }); + await expect( + applyFileStep( + "s", + { + type: "assert-absent", + file: "SKILL.md", + pattern: "npx[^\\r\\n]*@firecrawl/anydoc", + }, + dir, + ), + ).rejects.toThrow("[install-skills]"); + + const dir2 = await stageWith({ "SKILL.md": "run anydoc now" }); + const before = await Bun.file(path.join(dir2, "SKILL.md")).text(); + await applyFileStep( + "s", + { + type: "assert-absent", + file: "SKILL.md", + pattern: "npx[^\\r\\n]*@firecrawl/anydoc", + }, + dir2, + ); + const raw = await readFile(path.join(dir2, "SKILL.md")); + expect(raw.toString("utf8")).toBe(before); + }); +}); + +describe("shell", () => { + test("runs with staging cwd and env, fails on nonzero exit", async () => { + const dir = await makeTmp(); + await runShellStep( + "s", + 'echo "$SKILL_NAME" > name.txt\necho "$SKILL_STAGING_DIR" > stage.txt\ntest -n "$OPENCODE_CONFIG_DIR"', + dir, + ); + expect(await Bun.file(path.join(dir, "name.txt")).text()).toBe("s\n"); + expect(await Bun.file(path.join(dir, "stage.txt")).text()).toBe(`${dir}\n`); + await expect(runShellStep("s", "exit 3", dir)).rejects.toThrow( + "[install-skills]", + ); + }); +}); + +describe("file safety", () => { + test("missing file, directory, absolute path, traversal, escaping symlink fail", async () => { + const dir = await makeTmp(); + await Bun.write(path.join(dir, "SKILL.md"), "hello"); + await expect( + applyFileStep( + "s", + { + type: "replace", + file: "MISSING.md", + from: "h", + to: "x", + expected: 1, + }, + dir, + ), + ).rejects.toThrow("[install-skills]"); + + await mkdir(path.join(dir, "sub")); + await expect( + applyFileStep( + "s", + { type: "replace", file: "sub", from: "h", to: "x", expected: 1 }, + dir, + ), + ).rejects.toThrow("[install-skills]"); + + await expect( + applyFileStep( + "s", + { + type: "replace", + file: "/etc/passwd", + from: "r", + to: "x", + expected: 1, + }, + dir, + ), + ).rejects.toThrow("[install-skills]"); + + await expect( + applyFileStep( + "s", + { + type: "replace", + file: "../evil.md", + from: "h", + to: "x", + expected: 1, + }, + dir, + ), + ).rejects.toThrow("[install-skills]"); + + const outside = await makeTmp("sentinel-"); + const sentinel = path.join(outside, "secret.txt"); + await Bun.write(sentinel, "sentinel-bytes"); + await symlink(sentinel, path.join(dir, "link.md")); + await expect( + applyFileStep( + "s", + { + type: "replace", + file: "link.md", + from: "sentinel", + to: "changed", + expected: 1, + }, + dir, + ), + ).rejects.toThrow("[install-skills]"); + expect(await Bun.file(sentinel).text()).toBe("sentinel-bytes"); + }); + + test("interior symlink is allowed", async () => { + const dir = await makeTmp(); + await Bun.write(path.join(dir, "real.md"), "hello hello"); + await symlink(path.join(dir, "real.md"), path.join(dir, "link.md")); + await applyFileStep( + "s", + { + type: "replace", + file: "link.md", + from: "hello", + to: "hi", + expected: 2, + }, + dir, + ); + expect(await Bun.file(path.join(dir, "real.md")).text()).toBe("hi hi"); + }); +}); + +describe("guidance append/update", () => { + test("prefix preserved, repeat identical, changed guidance replaces", async () => { + const dir = await makeTmp(); + const target = path.join(dir, "AGENTS.md"); + await Bun.write(target, "# base rules\n"); + await updateAgentsMd(target, "## extra\n\nbody\n"); + const first = await Bun.file(target).text(); + expect(first.startsWith("# base rules\n")).toBe(true); + expect(first).toContain(START); + expect(first.endsWith("\n")).toBe(true); + + await updateAgentsMd(target, "## extra\n\nbody\n"); + expect(await Bun.file(target).text()).toBe(first); + + await updateAgentsMd(target, "## extra\n\nchanged\n"); + const third = await Bun.file(target).text(); + expect(third).toContain("changed"); + expect(third.startsWith("# base rules\n")).toBe(true); + expect(third).not.toContain("body"); + }); + + test("unmanaged suffix after block stays identical", async () => { + const dir = await makeTmp(); + const target = path.join(dir, "AGENTS.md"); + await Bun.write(target, "prefix\n"); + await updateAgentsMd(target, "guidance v1"); + const withSuffix = `${await Bun.file(target).text()}\nSuffix instructions stay.\n`; + await Bun.write(target, withSuffix); + const before = await Bun.file(target).text(); + await updateAgentsMd(target, "guidance v2"); + const after = await Bun.file(target).text(); + expect(after).toContain("guidance v2"); + expect(after.endsWith("\nSuffix instructions stay.\n")).toBe(true); + expect(after.slice(after.indexOf(END))).toBe( + before.slice(before.indexOf(END)), + ); + }); + + test("bad state fails without changing target", async () => { + const dir = await makeTmp(); + await expect( + updateAgentsMd(path.join(dir, "nope.md"), "guidance"), + ).rejects.toThrow("[install-skills]"); + + const target = path.join(dir, "AGENTS.md"); + await Bun.write(target, "base\n"); + await expect(updateAgentsMd(target, `x ${START} y`)).rejects.toThrow( + "[install-skills]", + ); + expect(await Bun.file(target).text()).toBe("base\n"); + + const cases = [ + `before ${START} only`, + `before ${END} only`, + `${START} a ${END} b ${START} c ${END}`, + `reversed ${END} then ${START}`, + ]; + for (const bad of cases) { + await Bun.write(target, bad); + await expect(updateAgentsMd(target, "guidance")).rejects.toThrow( + "[install-skills]", + ); + expect(await Bun.file(target).text()).toBe(bad); + } + }); + + test("symlink target is rejected", async () => { + const dir = await makeTmp(); + const real = path.join(dir, "real.md"); + await Bun.write(real, "base\n"); + const link = path.join(dir, "AGENTS.md"); + await symlink(real, link); + await expect(updateAgentsMd(link, "guidance")).rejects.toThrow( + "[install-skills]", + ); + }); +}); + +describe("cli integration", () => { + test("download + patches + guidance, repeat idempotent, mismatch fails safe", async () => { + const fixture = [ + "# fixture", + "It needs Node 20+ and no install:", + "- `npx -y @firecrawl/anydoc --help`", + "- `npx -y @firecrawl/anydoc convert a.pdf`", + "- `npx -y @firecrawl/anydoc convert b.docx`", + "", + ].join("\n"); + const server = Bun.serve({ + port: 0, + hostname: "127.0.0.1", + fetch: () => new Response(fixture), + }); + try { + const work = await makeTmp("cli-"); + const cfgDir = path.join(work, "cfg"); + await mkdir(cfgDir, { recursive: true }); + const baseAgents = "# caveman base\n"; + await Bun.write(path.join(cfgDir, "AGENTS.md"), baseAgents); + const manifestFile = path.join(work, "skills.yaml"); + const url = `http://127.0.0.1:${String(server.port)}/skill.md`; + const manifest = [ + "skills:", + " - name: convert-documents-to-markdown", + " steps:", + " - type: download", + ` url: ${url}`, + " dest: SKILL.md", + " - type: replace", + " file: SKILL.md", + " from: 'npx -y @firecrawl/anydoc'", + " to: 'anydoc'", + " expected: 3", + " - type: replace", + " file: SKILL.md", + " from: 'It needs Node 20+ and no install:'", + " to: 'It is preinstalled on PATH; invoke it directly, never via npx/bunx:'", + " expected: 1", + " - type: assert-absent", + " file: SKILL.md", + " pattern: 'npx[^\\r\\n]*@firecrawl/anydoc'", + " agents_md: |", + " ## per-skill-guidance", + " skill body", + "", + "agents_md: |", + " ## cli-guidance", + " test body", + "", + ].join("\n"); + await Bun.write(manifestFile, manifest); + const installer = new URL("./install-skills.ts", import.meta.url) + .pathname; + + async function runInstaller() { + const proc = Bun.spawn(["bun", installer], { + env: { + ...process.env, + OPENCODE_CONFIG_DIR: cfgDir, + SKILLS_MANIFEST: manifestFile, + }, + stdout: "pipe", + stderr: "pipe", + }); + const [out, err, code] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + proc.exited, + ]); + return { out, err, code }; + } + + const first = await runInstaller(); + expect(first.code).toBe(0); + const skillFile = path.join( + cfgDir, + "skills", + "convert-documents-to-markdown", + "SKILL.md", + ); + expect(await Bun.file(skillFile).text()).toContain( + "It is preinstalled on PATH; invoke it directly, never via npx/bunx:", + ); + expect(await Bun.file(skillFile).text()).not.toContain( + "npx -y @firecrawl/anydoc", + ); + expect(await Bun.file(skillFile).text()).not.toMatch( + /npx[^\r\n]*@firecrawl\/anydoc/, + ); + const agentsFirst = await Bun.file(path.join(cfgDir, "AGENTS.md")).text(); + expect(agentsFirst.startsWith(baseAgents)).toBe(true); + expect(agentsFirst).toContain("## cli-guidance"); + expect(agentsFirst).toContain("## per-skill-guidance"); + expect(agentsFirst.indexOf("## cli-guidance")).toBeLessThan( + agentsFirst.indexOf("## per-skill-guidance"), + ); + + const second = await runInstaller(); + expect(second.code).toBe(0); + expect(await Bun.file(path.join(cfgDir, "AGENTS.md")).text()).toBe( + agentsFirst, + ); + + const badManifest = manifest.replace("expected: 3", "expected: 99"); + await Bun.write(manifestFile, badManifest); + const skillBefore = await Bun.file(skillFile).text(); + const agentsBefore = await Bun.file( + path.join(cfgDir, "AGENTS.md"), + ).text(); + const bad = await runInstaller(); + expect(bad.code).not.toBe(0); + expect(bad.err + bad.out).toContain("expected 99"); + expect(await Bun.file(skillFile).text()).toBe(skillBefore); + expect(await Bun.file(path.join(cfgDir, "AGENTS.md")).text()).toBe( + agentsBefore, + ); + } finally { + server.stop(); + } + }, 30000); + + test("shell direct writes survive publish, repeat idempotent, failure exits nonzero", async () => { + const work = await makeTmp("cli-shell-"); + const cfgDir = path.join(work, "cfg"); + await mkdir(cfgDir, { recursive: true }); + await Bun.write(path.join(cfgDir, "AGENTS.md"), "# base\n"); + const manifestFile = path.join(work, "skills.yaml"); + const manifest = [ + "skills:", + " - name: shellskill", + " steps:", + " - type: shell", + " commands: |", + ' printf staged > "$SKILL_STAGING_DIR/staged.txt"', + ' mkdir -p "${OPENCODE_CONFIG_DIR}/skills/shellskill"', + ' printf direct > "${OPENCODE_CONFIG_DIR}/skills/shellskill/direct.txt"', + " agents_md: |", + " ## shell-guidance", + " body", + "", + ].join("\n"); + await Bun.write(manifestFile, manifest); + const installer = new URL("./install-skills.ts", import.meta.url).pathname; + + async function runInstaller() { + const proc = Bun.spawn(["bun", installer], { + env: { + ...process.env, + OPENCODE_CONFIG_DIR: cfgDir, + SKILLS_MANIFEST: manifestFile, + }, + stdout: "pipe", + stderr: "pipe", + }); + const [out, err, code] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + proc.exited, + ]); + return { out, err, code }; + } + + const first = await runInstaller(); + expect(first.code).toBe(0); + const skillDir = path.join(cfgDir, "skills", "shellskill"); + expect(await Bun.file(path.join(skillDir, "staged.txt")).text()).toBe( + "staged", + ); + expect(await Bun.file(path.join(skillDir, "direct.txt")).text()).toBe( + "direct", + ); + + const second = await runInstaller(); + expect(second.code).toBe(0); + expect(await Bun.file(path.join(skillDir, "staged.txt")).text()).toBe( + "staged", + ); + expect(await Bun.file(path.join(skillDir, "direct.txt")).text()).toBe( + "direct", + ); + + await Bun.write( + manifestFile, + manifest.replace( + 'printf direct > "${OPENCODE_CONFIG_DIR}/skills/shellskill/direct.txt"', + "exit 1", + ), + ); + const bad = await runInstaller(); + expect(bad.code).not.toBe(0); + expect(bad.err + bad.out).toContain("shell step failed"); + expect(await Bun.file(path.join(skillDir, "direct.txt")).text()).toBe( + "direct", + ); + }, 30000); + + test("group installs skills and lands group agents_md", async () => { + const work = await makeTmp("cli-group-"); + const cfgDir = path.join(work, "cfg"); + await mkdir(cfgDir, { recursive: true }); + await Bun.write(path.join(cfgDir, "AGENTS.md"), "# base\n"); + const manifestFile = path.join(work, "skills.yaml"); + const manifest = [ + "skills:", + " - group: tools", + " agents_md: |", + " ## group-md", + " group body", + " skills:", + " - name: gskill", + " steps:", + " - type: shell", + " commands: |", + ' printf hi > "$SKILL_STAGING_DIR/SKILL.md"', + "", + ].join("\n"); + await Bun.write(manifestFile, manifest); + const installer = new URL("./install-skills.ts", import.meta.url).pathname; + const proc = Bun.spawn(["bun", installer], { + env: { + ...process.env, + OPENCODE_CONFIG_DIR: cfgDir, + SKILLS_MANIFEST: manifestFile, + }, + stdout: "pipe", + stderr: "pipe", + }); + const [, , code] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + proc.exited, + ]); + expect(code).toBe(0); + expect( + await Bun.file(path.join(cfgDir, "skills", "gskill", "SKILL.md")).text(), + ).toBe("hi"); + expect(await Bun.file(path.join(cfgDir, "AGENTS.md")).text()).toContain( + "## group-md", + ); + }, 30000); +}); + +describe("resolveLatestReleaseTag", () => { + test("200 with tag returns tag", async () => { + globalThis.fetch = async () => + new Response(JSON.stringify({ tag_name: "v1.2.3" }), { status: 200 }); + expect(await resolveLatestReleaseTag("o/r")).toBe("v1.2.3"); + }); + + test("200 without tag returns null", async () => { + globalThis.fetch = async () => + new Response(JSON.stringify({}), { status: 200 }); + expect(await resolveLatestReleaseTag("o/r")).toBeNull(); + }); + + test("404 returns null", async () => { + globalThis.fetch = async () => new Response("nope", { status: 404 }); + expect(await resolveLatestReleaseTag("o/r")).toBeNull(); + }); + + test("non-ok fails", async () => { + globalThis.fetch = async () => new Response("oops", { status: 500 }); + await expect(resolveLatestReleaseTag("o/r")).rejects.toThrow( + "[install-skills]", + ); + }); +}); + +describe("resolveRef", () => { + test("missing repo or path fails", async () => { + await expect( + resolveRef({ type: "git-export", repo: "", path: "p" }), + ).rejects.toThrow("[install-skills]"); + await expect( + resolveRef({ type: "git-export", repo: "o/r", path: "" }), + ).rejects.toThrow("[install-skills]"); + }); + + test("bad repo format fails", async () => { + await expect( + resolveRef({ type: "git-export", repo: "not-valid", path: "p" }), + ).rejects.toThrow("[install-skills]"); + }); + + test("pinned version needs no fetch", async () => { + globalThis.fetch = async () => { + throw new Error("must not fetch"); + }; + const out = await resolveRef({ + type: "git-export", + repo: "o/r", + path: "sub", + version: "v1.0.0", + }); + expect(out).toEqual({ repo: "o/r", ref: "v1.0.0", path: "sub" }); + }); + + test("latest resolves via fetch, 404 gives null ref", async () => { + globalThis.fetch = async () => + new Response(JSON.stringify({ tag_name: "v9" }), { status: 200 }); + const out = await resolveRef({ + type: "git-export", + repo: "o/r", + path: "p", + }); + expect(out).toEqual({ repo: "o/r", ref: "v9", path: "p" }); + + globalThis.fetch = async () => new Response("x", { status: 404 }); + const out2 = await resolveRef({ + type: "git-export", + repo: "o/r", + path: "p", + }); + expect(out2).toEqual({ repo: "o/r", ref: null, path: "p" }); + }); +}); + +describe("workspaceKey", () => { + test("formats ref and HEAD", () => { + expect(workspaceKey("o/r", "v1")).toBe("o/r@v1"); + expect(workspaceKey("o/r", null)).toBe("o/r@HEAD"); + }); +}); + +describe("shell seam", () => { + test("true succeeds, false fails", async () => { + await shell(["true"]); + await expect(shell(["false"])).rejects.toThrow("[install-skills]"); + }); +}); + +describe("safe", () => { + test("escapes fail, inside passes", async () => { + const dir = await makeTmp(); + expect(() => safe(dir, "../evil.md")).toThrow("[install-skills]"); + expect(() => safe(dir, "/abs")).toThrow("[install-skills]"); + expect(safe(dir, "a.md")).toBe(path.join(dir, "a.md")); + }); +}); + +describe("run download", () => { + test("success writes file, failure throws, traversal throws", async () => { + const dir = await makeTmp(); + globalThis.fetch = async () => new Response("hello", { status: 200 }); + await run( + "s", + { type: "download", url: "https://example.com/x", dest: "SKILL.md" }, + dir, + ); + expect(await Bun.file(path.join(dir, "SKILL.md")).text()).toBe("hello"); + + globalThis.fetch = async () => new Response("bad", { status: 500 }); + await expect( + run( + "s2", + { type: "download", url: "https://example.com/x", dest: "SKILL.md" }, + dir, + ), + ).rejects.toThrow("[install-skills]"); + + globalThis.fetch = async () => new Response("hi", { status: 200 }); + await expect( + run( + "s3", + { type: "download", url: "https://example.com/x", dest: "../evil.md" }, + dir, + ), + ).rejects.toThrow("[install-skills]"); + }); +}); + +describe("run git-export url", () => { + test("stub success writes file, stub failure throws", async () => { + const dir = await makeTmp(); + const stubDir = await makeTmp("stub-"); + const okStub = path.join(stubDir, "ok.ts"); + await Bun.write( + okStub, + 'await Bun.write(process.argv[3] + "/SKILL.md", "stub");\n', + ); + process.env.GIT_EXPORT_SCRIPT = okStub; + await run("s", { type: "git-export", url: "https://example.com/x" }, dir); + expect(await Bun.file(path.join(dir, "SKILL.md")).text()).toBe("stub"); + + const failStub = path.join(stubDir, "fail.ts"); + await Bun.write(failStub, "process.exit(1);\n"); + process.env.GIT_EXPORT_SCRIPT = failStub; + const dir2 = await makeTmp(); + await expect( + run("s", { type: "git-export", url: "https://example.com/x" }, dir2), + ).rejects.toThrow("[install-skills]"); + }); +}); + +describe("run other steps", () => { + test("replace, assert-absent, shell and unsupported", async () => { + const dir = await makeTmp(); + await Bun.write(path.join(dir, "f.md"), "hello"); + await run( + "s", + { type: "replace", file: "f.md", from: "hello", to: "hi", expected: 1 }, + dir, + ); + expect(await Bun.file(path.join(dir, "f.md")).text()).toBe("hi"); + + await run( + "s", + { type: "assert-absent", file: "f.md", pattern: "missing" }, + dir, + ); + + const dir2 = await makeTmp(); + await run( + "s", + { type: "shell", commands: 'printf hi > "$SKILL_STAGING_DIR/out.txt"' }, + dir2, + ); + expect(await Bun.file(path.join(dir2, "out.txt")).text()).toBe("hi"); + + await expect( + run("s", { type: "nope" } as unknown as Step, dir2), + ).rejects.toThrow("[install-skills]"); + }); +}); + +describe("runSkill", () => { + test("rename path replaces dest", async () => { + const destRoot = await makeTmp("runskill-rename-"); + await mkdir(path.join(destRoot, "myskill"), { recursive: true }); + await Bun.write(path.join(destRoot, "myskill", "old.txt"), "old"); + globalThis.fetch = async () => new Response("body", { status: 200 }); + await runSkill( + "myskill", + [{ type: "download", url: "https://example.com/x", dest: "SKILL.md" }], + destRoot, + ); + expect( + await Bun.file(path.join(destRoot, "myskill", "SKILL.md")).text(), + ).toBe("body"); + expect( + await Bun.file(path.join(destRoot, "myskill", "old.txt")).exists(), + ).toBe(false); + }); + + test("shell path merges and keeps existing", async () => { + const destRoot = await makeTmp("runskill-merge-"); + await mkdir(path.join(destRoot, "myskill"), { recursive: true }); + await Bun.write(path.join(destRoot, "myskill", "keep.txt"), "keep"); + await runSkill( + "myskill", + [ + { + type: "shell", + commands: 'printf staged > "$SKILL_STAGING_DIR/staged.txt"', + }, + ], + destRoot, + ); + expect( + await Bun.file(path.join(destRoot, "myskill", "keep.txt")).text(), + ).toBe("keep"); + expect( + await Bun.file(path.join(destRoot, "myskill", "staged.txt")).text(), + ).toBe("staged"); + }); +}); + +describe("copySubtreeFromWorkspace", () => { + test("copies root and subpath, skips .git", async () => { + const work = await makeTmp("ws-"); + const cloneDir = path.join(work, "repo"); + await mkdir(path.join(cloneDir, "sub"), { recursive: true }); + await Bun.write(path.join(cloneDir, "root.txt"), "root"); + await Bun.write(path.join(cloneDir, "sub", "inner.txt"), "inner"); + await mkdir(path.join(cloneDir, ".git"), { recursive: true }); + await Bun.write(path.join(cloneDir, ".git", "config"), "git"); + const workspace = { dir: work, cloneDir, ref: null }; + + const dest = await makeTmp("ws-dest-"); + await copySubtreeFromWorkspace(workspace, "", dest); + expect(await Bun.file(path.join(dest, "root.txt")).text()).toBe("root"); + expect(await Bun.file(path.join(dest, "sub", "inner.txt")).text()).toBe( + "inner", + ); + expect(await readdir(dest)).not.toContain(".git"); + + const dest2 = await makeTmp("ws-dest2-"); + await copySubtreeFromWorkspace(workspace, "sub", dest2); + expect(await Bun.file(path.join(dest2, "inner.txt")).text()).toBe("inner"); + }); +}); + +describe("cleanupWorkspaces", () => { + test("empty is fine", async () => { + await cleanupWorkspaces(); + }); +}); + +describe("parse extra", () => { + test("invalid manifest fails", () => { + expect(() => parse("")).toThrow("[install-skills]"); + expect(() => parse("skills: 42\n")).toThrow("[install-skills]"); + }); + + test("skill with group/skills field fails", () => { + expect(() => + parse("skills:\n - name: a\n steps: []\n skills: []\n"), + ).toThrow("[install-skills]"); + }); + + test("group inner non-object fails", () => { + expect(() => + parse("skills:\n - group: g\n skills:\n - 42\n"), + ).toThrow("[install-skills]"); + }); + + test("absolute file path and missing to fail", () => { + expect(() => + parse( + "skills:\n - name: a\n steps:\n - type: replace\n file: /abs\n from: x\n to: y\n", + ), + ).toThrow("[install-skills]"); + expect(() => + parse( + "skills:\n - name: a\n steps:\n - type: replace\n file: SKILL.md\n from: x\n", + ), + ).toThrow("[install-skills]"); + }); + + test("missing steps and bad step shapes fail", () => { + expect(() => parse("skills:\n - name: a\n")).toThrow("[install-skills]"); + expect(() => + parse("skills:\n - name: a\n steps:\n - 42\n"), + ).toThrow("[install-skills]"); + expect(() => + parse( + "skills:\n - name: a\n steps:\n - type: replace\n file: ''\n from: x\n to: y\n", + ), + ).toThrow("[install-skills]"); + }); +}); + +describe("applyFileStep extra", () => { + test("staging missing fails", async () => { + const parent = await makeTmp(); + const missing = path.join(parent, "nope"); + await expect( + applyFileStep( + "s", + { type: "replace", file: "x.md", from: "a", to: "b", expected: 1 }, + missing, + ), + ).rejects.toThrow("[install-skills]"); + }); + + test("invalid regex fails", async () => { + const dir = await makeTmp(); + await Bun.write(path.join(dir, "f.md"), "hi"); + await expect( + applyFileStep( + "s", + { type: "assert-absent", file: "f.md", pattern: "([" }, + dir, + ), + ).rejects.toThrow("[install-skills]"); + }); +}); + +describe("updateAgentsMd extra", () => { + test("empty additions fail", async () => { + const dir = await makeTmp(); + const target = path.join(dir, "AGENTS.md"); + await Bun.write(target, "base\n"); + await expect(updateAgentsMd(target, " ")).rejects.toThrow( + "[install-skills]", + ); + }); + + test("empty file and newline variants", async () => { + const dir = await makeTmp(); + const emptyTarget = path.join(dir, "AGENTS.md"); + await Bun.write(emptyTarget, ""); + await updateAgentsMd(emptyTarget, "guidance"); + expect(await Bun.file(emptyTarget).text()).toContain(START); + + const dbl = path.join(dir, "dbl.md"); + await Bun.write(dbl, "base\n\n"); + await updateAgentsMd(dbl, "guidance"); + expect(await Bun.file(dbl).text()).toContain(START); + + const noNl = path.join(dir, "nonl.md"); + await Bun.write(noNl, "base"); + await updateAgentsMd(noNl, "guidance"); + expect(await Bun.file(noNl).text()).toContain(START); + }); +}); + +describe("runShellStep extra", () => { + test("empty commands fail", async () => { + const dir = await makeTmp(); + await expect(runShellStep("s", "", dir)).rejects.toThrow( + "[install-skills]", + ); + await expect(runShellStep("s", " ", dir)).rejects.toThrow( + "[install-skills]", + ); + }); +}); + +describe("run git-export repo cached", () => { + test("pinned version uses cached workspace offline", async () => { + const work = await makeTmp("ws-cache-"); + const cloneDir = path.join(work, "repo"); + await mkdir(path.join(cloneDir, "sub"), { recursive: true }); + await Bun.write(path.join(cloneDir, "sub", "SKILL.md"), "cached"); + await mkdir(path.join(cloneDir, ".git"), { recursive: true }); + workspaces.set("o/r@v1", { dir: work, cloneDir, ref: "v1" }); + + const dir = await makeTmp("run-repo-"); + await run( + "s", + { type: "git-export", repo: "o/r", path: "sub", version: "v1" }, + dir, + ); + expect(await Bun.file(path.join(dir, "SKILL.md")).text()).toBe("cached"); + // cleanupWorkspaces should remove the fake workspace dir + await cleanupWorkspaces(); + expect(workspaces.size).toBe(0); + expect(await Bun.file(path.join(work, "repo")).exists()).toBe(false); + }); +}); + +describe("run git-export default script", () => { + test("resolves default when env unset, env override when set", () => { + process.env.GIT_EXPORT_SCRIPT = "/tmp/opencode/stub-export.ts"; + expect(gitExportScript()).toBe("/tmp/opencode/stub-export.ts"); + delete process.env.GIT_EXPORT_SCRIPT; + expect(gitExportScript()).toBe( + path.join( + process.env.OPENCODE_BUILD_DIR || "/tmp", + "scripts", + "git-export.ts", + ), + ); + }); +}); + +describe("run offline mocks", () => { + test("repo clone path via mocked spawn still throws on missing sub", async () => { + const originalSpawn = Bun.spawn; + (Bun as unknown as { spawn: unknown }).spawn = ( + _args: string[], + ): unknown => { + return { exited: Promise.resolve(0) }; + }; + try { + const dir = await makeTmp("run-clone-"); + await expect( + run( + "s", + { type: "git-export", repo: "o/r", path: "sub", version: "v1" }, + dir, + ), + ).rejects.toThrow(); + } finally { + (Bun as unknown as { spawn: unknown }).spawn = originalSpawn; + await cleanupWorkspaces().catch(() => {}); + workspaces.clear(); + } + }); + + test("repo clone null ref covers else branch", async () => { + const originalSpawn = Bun.spawn; + (Bun as unknown as { spawn: unknown }).spawn = ( + _args: string[], + ): unknown => { + return { exited: Promise.resolve(0) }; + }; + globalThis.fetch = async () => new Response("x", { status: 404 }); + try { + const dir = await makeTmp("run-clone-null-"); + await expect( + run("s", { type: "git-export", repo: "o/r", path: "sub" }, dir), + ).rejects.toThrow(); + } finally { + (Bun as unknown as { spawn: unknown }).spawn = originalSpawn; + await cleanupWorkspaces().catch(() => {}); + workspaces.clear(); + } + }); + + test("uv-pip via mocked spawn records calls", async () => { + const originalSpawn = Bun.spawn; + const calls: string[][] = []; + (Bun as unknown as { spawn: unknown }).spawn = ( + args: string[], + ): unknown => { + calls.push(args); + return { exited: Promise.resolve(0) }; + }; + try { + const dir = await makeTmp("run-uv-"); + await run("s", { type: "uv-pip", packages: ["a", "b"] }, dir); + expect(calls).toEqual([ + ["uv", "pip", "install", "--system", "a"], + ["uv", "pip", "install", "--system", "b"], + ]); + } finally { + (Bun as unknown as { spawn: unknown }).spawn = originalSpawn; + } + }); +}); diff --git a/scripts/install-skills.ts b/scripts/install-skills.ts index e8584a4..aa2c89e 100644 --- a/scripts/install-skills.ts +++ b/scripts/install-skills.ts @@ -1,224 +1,670 @@ #!/usr/bin/env bun -import { mkdir, mkdtemp, readdir, cp, rm, rename } from "node:fs/promises" -import path from "node:path" -import os from "node:os" -import YAML from "yaml" - -type Step = +import { + mkdir, + mkdtemp, + readdir, + cp, + rm, + rename, + realpath, + stat, + lstat, + chmod, + readFile, +} from "node:fs/promises"; +import path from "node:path"; +import os from "node:os"; +import YAML from "yaml"; + +export type Step = | { type: "download"; url: string; dest: string } | { type: "git-export"; url: string } | { type: "git-export"; repo: string; path: string; version?: string } | { type: "uv-pip"; packages: string[] } + | { type: "shell"; commands: string } + | { + type: "replace"; + file: string; + from: string; + to: string; + expected?: number; + } + | { type: "assert-absent"; file: string; pattern: string }; -type GitExportSpec = Extract +type GitExportRepoSpec = Extract; type ResolvedGitExport = { - repo: string - ref: string | null - path: string -} + repo: string; + ref: string | null; + path: string; +}; type Workspace = { - dir: string - cloneDir: string - ref: string | null -} + dir: string; + cloneDir: string; + ref: string | null; +}; type Skill = { - name: string - steps: Step[] -} + name: string; + steps: Step[]; + agents_md?: string; +}; + +type SkillGroup = { + group: string; + skills: Skill[]; + agents_md?: string; +}; + +type ManifestEntry = Skill | SkillGroup; type Manifest = { - skills: Skill[] -} + skills: ManifestEntry[]; + agents_md?: string; +}; + +const AGENTS_MD_START = ""; +const AGENTS_MD_END = ""; -const cfg = process.env.OPENCODE_CONFIG_DIR || "/etc/opencode" -const root = path.join(cfg, "skills") -const base = process.env.OPENCODE_BUILD_DIR || "/tmp" -const manifestPath = process.env.SKILLS_MANIFEST || path.join(base, "skills.yaml") -const gitExport = process.env.GIT_EXPORT_SCRIPT || path.join(base, "scripts", "git-export.ts") -const workspaces = new Map() +const cfg = process.env.OPENCODE_CONFIG_DIR || "/etc/opencode"; +const root = path.join(cfg, "skills"); +const base = process.env.OPENCODE_BUILD_DIR || "/tmp"; +const manifestPath = + process.env.SKILLS_MANIFEST || path.join(base, "skills.yaml"); +export const workspaces = new Map(); function fail(msg: string): never { - throw new Error(`[install-skills] ${msg}`) + throw new Error(`[install-skills] ${msg}`); } function info(msg: string) { - console.log(`[install-skills] ${msg}`) + console.log(`[install-skills] ${msg}`); } -function safe(base: string, dest: string) { - const file = path.resolve(base, dest) - const rel = path.relative(base, file) - if (rel.startsWith("..") || path.isAbsolute(rel)) fail(`invalid destination path: ${dest}`) - return file +export function safe(base: string, dest: string) { + const file = path.resolve(base, dest); + const rel = path.relative(base, file); + if (rel.startsWith("..") || path.isAbsolute(rel)) + fail(`invalid destination path: ${dest}`); + return file; } async function ensure(dir: string) { - await mkdir(dir, { recursive: true }) + await mkdir(dir, { recursive: true }); } async function resetDir(dir: string) { - await rm(dir, { recursive: true, force: true }) - await mkdir(dir, { recursive: true }) + await rm(dir, { recursive: true, force: true }); + await mkdir(dir, { recursive: true }); } -async function shell(args: string[]) { +export async function shell(args: string[]) { const proc = Bun.spawn(args, { stdout: "inherit", stderr: "inherit", stdin: "inherit", - }) - const code = await proc.exited - if (code !== 0) fail(`command failed (${code}): ${args.join(" ")}`) + }); + const code = await proc.exited; + if (code !== 0) fail(`command failed (${String(code)}): ${args.join(" ")}`); } function isGitHubRepo(repo: string) { - return /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo) + return /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo); } -async function resolveLatestReleaseTag(repo: string) { - const res = await fetch(`https://api.github.com/repos/${repo}/releases/latest`, { - headers: { - Accept: "application/vnd.github+json", - "User-Agent": "install-skills", +export async function resolveLatestReleaseTag(repo: string) { + const res = await fetch( + `https://api.github.com/repos/${repo}/releases/latest`, + { + headers: { + Accept: "application/vnd.github+json", + "User-Agent": "install-skills", + }, }, - }) - - if (res.status === 404) return null - if (!res.ok) fail(`git-export: failed latest release lookup for ${repo} (${res.status})`) - - const data = (await res.json()) as { tag_name?: unknown } - const tag = typeof data.tag_name === "string" && data.tag_name ? data.tag_name : null - if (tag) info(`git-export: resolved latest release for ${repo} -> ${tag}`) - return tag + ); + + if (res.status === 404) return null; + if (!res.ok) + fail( + `git-export: failed latest release lookup for ${repo} (${String(res.status)})`, + ); + + const data = (await res.json()) as { tag_name?: unknown }; + const tag = + typeof data.tag_name === "string" && data.tag_name ? data.tag_name : null; + if (tag) info(`git-export: resolved latest release for ${repo} -> ${tag}`); + return tag; } -async function resolveRef(step: GitExportSpec): Promise { - if (!step.repo) fail(`git-export: missing repo`) - if (!step.path) fail(`git-export: missing path for ${step.repo}`) - if (!isGitHubRepo(step.repo)) fail(`git-export: unsupported repo format: ${step.repo}`) - - const version = step.version ?? "latest" - const ref = version === "latest" ? await resolveLatestReleaseTag(step.repo) : version - return { repo: step.repo, path: step.path, ref } +export async function resolveRef( + step: GitExportRepoSpec, +): Promise { + if (!step.repo) fail(`git-export: missing repo`); + if (!step.path) fail(`git-export: missing path for ${step.repo}`); + if (!isGitHubRepo(step.repo)) + fail(`git-export: unsupported repo format: ${step.repo}`); + + const version = step.version ?? "latest"; + const ref = + version === "latest" ? await resolveLatestReleaseTag(step.repo) : version; + return { repo: step.repo, path: step.path, ref }; } -function workspaceKey(repo: string, ref: string | null) { - return `${repo}@${ref ?? "HEAD"}` +export function workspaceKey(repo: string, ref: string | null) { + return `${repo}@${ref ?? "HEAD"}`; } async function ensureWorkspace(repo: string, ref: string | null) { - const key = workspaceKey(repo, ref) - const existing = workspaces.get(key) - if (existing) return existing - - const dir = await mkdtemp(path.join(os.tmpdir(), "skills-export-")) - const cloneDir = path.join(dir, "repo") - const repoUrl = `https://github.com/${repo}.git` - await shell(["git", "clone", "--depth", "1", "--filter=tree:0", "--no-checkout", repoUrl, cloneDir]) + const key = workspaceKey(repo, ref); + const existing = workspaces.get(key); + if (existing) return existing; + + const dir = await mkdtemp(path.join(os.tmpdir(), "skills-export-")); + const cloneDir = path.join(dir, "repo"); + const repoUrl = `https://github.com/${repo}.git`; + await shell([ + "git", + "clone", + "--depth", + "1", + "--filter=tree:0", + "--no-checkout", + repoUrl, + cloneDir, + ]); if (ref) { - await shell(["git", "-C", cloneDir, "fetch", "--depth", "1", "origin", ref]) - await shell(["git", "-C", cloneDir, "checkout", "--detach", "FETCH_HEAD"]) + await shell([ + "git", + "-C", + cloneDir, + "fetch", + "--depth", + "1", + "origin", + ref, + ]); + await shell(["git", "-C", cloneDir, "checkout", "--detach", "FETCH_HEAD"]); } else { - await shell(["git", "-C", cloneDir, "checkout"]) + await shell(["git", "-C", cloneDir, "checkout"]); } - const workspace: Workspace = { dir, cloneDir, ref } - workspaces.set(key, workspace) - return workspace + const workspace: Workspace = { dir, cloneDir, ref }; + workspaces.set(key, workspace); + return workspace; } -async function copySubtreeFromWorkspace(workspace: Workspace, sourcePath: string, destDir: string) { - const sourceDir = sourcePath ? path.join(workspace.cloneDir, sourcePath) : workspace.cloneDir - const entries = await readdir(sourceDir) - await ensure(destDir) +export async function copySubtreeFromWorkspace( + workspace: Workspace, + sourcePath: string, + destDir: string, +) { + const sourceDir = sourcePath + ? path.join(workspace.cloneDir, sourcePath) + : workspace.cloneDir; + const entries = await readdir(sourceDir); + await ensure(destDir); for (const entry of entries) { - if (entry === ".git") continue - await cp(path.join(sourceDir, entry), path.join(destDir, entry), { recursive: true, force: true, verbatimSymlinks: true }) + if (entry === ".git") continue; + await cp(path.join(sourceDir, entry), path.join(destDir, entry), { + recursive: true, + force: true, + verbatimSymlinks: true, + }); } } -async function cleanupWorkspaces() { +export async function cleanupWorkspaces() { for (const workspace of workspaces.values()) { - await rm(workspace.dir, { recursive: true, force: true }) + await rm(workspace.dir, { recursive: true, force: true }); + } + workspaces.clear(); +} + +export function isGroup(entry: unknown): entry is SkillGroup { + return ( + !!entry && + typeof entry === "object" && + "group" in (entry as Record) + ); +} + +function checkAgentsMd(value: unknown, label: string) { + if (value === undefined) return; + if (typeof value !== "string" || !value.trim()) + fail(`${label}: agents_md is empty`); + if (value.includes(AGENTS_MD_START) || value.includes(AGENTS_MD_END)) { + fail(`${label}: agents_md contains reserved marker`); + } +} + +function checkSteps(skillName: string, steps: unknown) { + if (!Array.isArray(steps)) fail(`${skillName}: missing steps`); + for (const step of steps) { + if (!step || typeof step !== "object") fail(`${skillName}: invalid step`); + const t = step as Record; + if (typeof t.type !== "string" || !knownStepTypes.has(t.type)) + fail(`${skillName}: unsupported step type`); + if (t.type === "replace" || t.type === "assert-absent") { + if (typeof t.file !== "string" || !t.file) + fail(`${skillName}: file step missing file`); + if (path.isAbsolute(t.file)) + fail(`${skillName}: invalid file path: ${t.file}`); + } + if (t.type === "replace") { + if (typeof t.from !== "string" || !t.from) + fail(`${skillName}: replace step missing from`); + if (typeof t.to !== "string") + fail(`${skillName}: replace step missing to`); + if ( + t.expected !== undefined && + (typeof t.expected !== "number" || + !Number.isSafeInteger(t.expected) || + t.expected <= 0) + ) { + fail(`${skillName}: replace step has invalid expected count`); + } + } + if (t.type === "assert-absent") { + if (typeof t.pattern !== "string" || !t.pattern) + fail(`${skillName}: assert-absent step missing pattern`); + try { + new RegExp(t.pattern); + } catch { + fail(`${skillName}: invalid regex pattern`); + } + } + if (t.type === "shell") { + if (typeof t.commands !== "string" || !t.commands.trim()) + fail(`${skillName}: shell step missing commands`); + } + } +} + +function checkSkillName(name: unknown): asserts name is string { + if (typeof name !== "string" || !name) fail(`skill missing name`); + if ( + name === "." || + name === ".." || + name.includes("/") || + name.includes("\\") || + path.isAbsolute(name) + ) { + fail(`invalid skill name: ${name}`); + } +} + +const knownStepTypes = new Set([ + "download", + "git-export", + "uv-pip", + "replace", + "assert-absent", + "shell", +]); + +export async function runShellStep( + name: string, + commands: string, + dir: string, +) { + if (typeof commands !== "string" || !commands.trim()) + fail(`${name}: shell step missing commands`); + // Shell steps manage their own outputs (e.g. graphify installs its skill dir + // and plugin directly into OPENCODE_CONFIG_DIR). Run with the staging dir as + // cwd and expose both the staging dir and the config dir, so commands can + // stage files normally or place final artifacts directly. + const proc = Bun.spawn(["bash", "-c", commands], { + cwd: dir, + env: { + ...process.env, + OPENCODE_CONFIG_DIR: cfg, + SKILL_NAME: name, + SKILL_STAGING_DIR: dir, + }, + stdout: "inherit", + stderr: "inherit", + stdin: "inherit", + }); + const code = await proc.exited; + if (code !== 0) fail(`${name}: shell step failed (${String(code)})`); +} + +export async function applyFileStep( + name: string, + step: Extract, + dir: string, +) { + const rel = step.file; + if (typeof rel !== "string" || !rel) fail(`${name}: file step missing file`); + if (path.isAbsolute(rel)) fail(`${name}: invalid file path: ${rel}`); + const file = safe(dir, rel); + + let realDir: string; + try { + realDir = await realpath(dir); + } catch { + fail(`${name}: staging directory missing for ${rel}`); + } + let realFile: string; + try { + realFile = await realpath(file); + } catch { + fail(`${name}: file not found: ${rel}`); + } + if (realFile !== realDir && !realFile.startsWith(realDir + path.sep)) { + fail(`${name}: file escapes staging directory: ${rel}`); + } + let st: Awaited>; + try { + st = await stat(file); + } catch { + fail(`${name}: file not found: ${rel}`); + } + if (!st.isFile()) fail(`${name}: not a regular file: ${rel}`); + + const text = await readFile(file, "utf8"); + if (step.type === "replace") { + const parts = text.split(step.from); + const actual = parts.length - 1; + if (step.expected === undefined) { + // No pinned count: replace all, but a zero-match step is a stale patch — fail loudly. + if (actual === 0) + fail(`${name}: ${rel}: expected at least 1 occurrence(s), found 0`); + } else if (actual !== step.expected) { + fail( + `${name}: ${rel}: expected ${String(step.expected)} occurrence(s), found ${String(actual)}`, + ); + } + await Bun.write(file, parts.join(step.to)); + return; + } + + let re: RegExp; + try { + re = new RegExp(step.pattern); + } catch { + fail(`${name}: ${rel}: invalid regex pattern`); } - workspaces.clear() + if (re.test(text)) fail(`${name}: ${rel}: forbidden pattern present`); } -async function runSkill(name: string, steps: Step[]) { - const destDir = path.join(root, name) - const stageParent = await mkdtemp(path.join(os.tmpdir(), "skills-install-")) - const stageDir = path.join(stageParent, name) +export async function updateAgentsMd(file: string, additions: string) { + if (typeof additions !== "string" || !additions.trim()) + fail(`agents_md is empty`); + if ( + additions.includes(AGENTS_MD_START) || + additions.includes(AGENTS_MD_END) + ) { + fail(`agents_md contains reserved marker`); + } + let lst: Awaited>; + try { + lst = await lstat(file); + } catch { + fail(`AGENTS.md not found or unreadable: ${file}`); + } + if (lst.isSymbolicLink()) fail(`AGENTS.md is a symlink: ${file}`); + let st: Awaited>; + try { + st = await stat(file); + } catch { + fail(`AGENTS.md not found or unreadable: ${file}`); + } + if (!st.isFile()) fail(`AGENTS.md is not a regular file: ${file}`); + let original: string; try { - await resetDir(stageDir) + original = await readFile(file, "utf8"); + } catch { + fail(`AGENTS.md not found or unreadable: ${file}`); + } + + const block = `${AGENTS_MD_START}\n${additions.trimEnd()}\n${AGENTS_MD_END}`; + const firstStart = original.indexOf(AGENTS_MD_START); + const lastStart = original.lastIndexOf(AGENTS_MD_START); + const firstEnd = original.indexOf(AGENTS_MD_END); + const lastEnd = original.lastIndexOf(AGENTS_MD_END); + + let next: string; + if (firstStart === -1 && firstEnd === -1) { + if (original === "") { + next = `${block}\n`; + } else if (original.endsWith("\n\n")) { + next = `${original}${block}\n`; + } else if (original.endsWith("\n")) { + next = `${original}\n${block}\n`; + } else { + next = `${original}\n\n${block}\n`; + } + } else if ( + firstStart !== -1 && + firstEnd !== -1 && + firstStart < firstEnd && + firstStart === lastStart && + firstEnd === lastEnd + ) { + next = + original.slice(0, firstStart) + + block + + original.slice(firstEnd + AGENTS_MD_END.length); + } else { + fail(`AGENTS.md has malformed managed block`); + } + + if (next === original) return; + + const dir = path.dirname(file); + const tmpDir = await mkdtemp(path.join(dir, ".agents-md-")); + const tmpFile = path.join(tmpDir, "AGENTS.md"); + try { + await Bun.write(tmpFile, next); + await chmod(tmpFile, st.mode & 0o777); + await rename(tmpFile, file); + } finally { + await rm(tmpDir, { recursive: true, force: true }); + } +} + +export function gitExportScript(): string { + return ( + process.env.GIT_EXPORT_SCRIPT || path.join(base, "scripts", "git-export.ts") + ); +} + +export async function runSkill(name: string, steps: Step[], destRoot = root) { + const destDir = path.join(destRoot, name); + const stageParent = await mkdtemp(path.join(os.tmpdir(), "skills-install-")); + const stageDir = path.join(stageParent, name); + + try { + await resetDir(stageDir); for (const step of steps) { - await run(name, step, stageDir) + await run(name, step, stageDir); } - await rm(destDir, { recursive: true, force: true }) - await ensure(path.dirname(destDir)) - await rename(stageDir, destDir) + if (steps.some((s) => s.type === "shell")) { + // A shell step may place final artifacts directly (e.g. graphify's skill + // dir and plugin). Merging preserves those instead of wiping them with + // an atomic replace of the empty staging dir. + await ensure(destDir); + for (const entry of await readdir(stageDir)) { + if (entry === ".git") continue; + await cp(path.join(stageDir, entry), path.join(destDir, entry), { + recursive: true, + force: true, + verbatimSymlinks: true, + }); + } + } else { + await rm(destDir, { recursive: true, force: true }); + await ensure(path.dirname(destDir)); + await rename(stageDir, destDir); + } } finally { - await rm(stageParent, { recursive: true, force: true }) + await rm(stageParent, { recursive: true, force: true }); } } -async function run(name: string, step: Step, dir: string) { +export async function run(name: string, step: Step, dir: string) { if (step.type === "download") { - await ensure(dir) - const res = await fetch(step.url) - if (!res.ok) fail(`${name}: failed download ${step.url} (${res.status})`) - await Bun.write(safe(dir, step.dest), await res.text()) - return + await ensure(dir); + const res = await fetch(step.url); + if (!res.ok) + fail(`${name}: failed download ${step.url} (${String(res.status)})`); + await Bun.write(safe(dir, step.dest), await res.text()); + return; } if (step.type === "git-export") { - await ensure(dir) + await ensure(dir); if ("url" in step) { - await shell(["bun", gitExport, step.url, dir, "--force"]) - return + await shell(["bun", gitExportScript(), step.url, dir, "--force"]); + return; } - const resolved = await resolveRef(step) - const workspace = await ensureWorkspace(resolved.repo, resolved.ref) - await copySubtreeFromWorkspace(workspace, resolved.path, dir) - return + const resolved = await resolveRef(step); + const workspace = await ensureWorkspace(resolved.repo, resolved.ref); + await copySubtreeFromWorkspace(workspace, resolved.path, dir); + return; } if (step.type === "uv-pip") { for (const pkg of step.packages) { - await shell(["uv", "pip", "install", "--system", pkg]) + await shell(["uv", "pip", "install", "--system", pkg]); } - return + return; } - fail(`${name}: unsupported step type`) + if (step.type === "replace" || step.type === "assert-absent") { + await applyFileStep(name, step, dir); + return; + } + + if (step.type === "shell") { + await runShellStep(name, step.commands, dir); + return; + } + + fail(`${name}: unsupported step type`); +} + +export function flattenSkills(entries: ManifestEntry[]): Skill[] { + const flat: Skill[] = []; + for (const entry of entries) { + if (isGroup(entry)) flat.push(...entry.skills); + else flat.push(entry); + } + return flat; } -function parse(input: string): Manifest { - const parsed = YAML.parse(input) as Partial | null - if (!parsed || !Array.isArray(parsed.skills)) fail(`invalid manifest at ${manifestPath}`) - return { skills: parsed.skills as Skill[] } +export function collectAgentsMd(manifest: Manifest): string[] { + const out: string[] = []; + if (manifest.agents_md !== undefined) out.push(manifest.agents_md.trim()); + for (const entry of manifest.skills) { + if (isGroup(entry)) { + if (entry.agents_md !== undefined) out.push(entry.agents_md.trim()); + for (const skill of entry.skills) { + if (skill.agents_md !== undefined) out.push(skill.agents_md.trim()); + } + } else if (entry.agents_md !== undefined) { + out.push(entry.agents_md.trim()); + } + } + return out; +} + +export function parse(input: string): Manifest { + const parsed = YAML.parse(input) as Partial | null; + if (!parsed || !Array.isArray(parsed.skills)) + fail(`invalid manifest at ${manifestPath}`); + + const entries = parsed.skills as unknown[]; + const seenSkills = new Set(); + const seenGroups = new Set(); + + function validateSkill(s: unknown): asserts s is Skill { + if (!s || typeof s !== "object") fail(`skill missing name`); + const obj = s as { + name?: unknown; + steps?: unknown; + agents_md?: unknown; + group?: unknown; + skills?: unknown; + }; + if ("group" in obj || "skills" in obj) + fail(`skill entry must not contain group/skills`); + checkSkillName(obj.name); + const name = obj.name; + if (seenSkills.has(name)) fail(`duplicate skill name: ${name}`); + seenSkills.add(name); + checkAgentsMd(obj.agents_md, name); + checkSteps(name, obj.steps); + } + + for (const entry of entries) { + if (!entry || typeof entry !== "object") fail(`skill missing name`); + const obj = entry as Record; + if ("group" in obj) { + if (typeof obj.group !== "string" || !obj.group.trim()) + fail(`group missing name`); + if ("name" in obj || "steps" in obj) + fail(`group ${obj.group}: must not contain name/steps`); + const groupName = obj.group.trim(); + if (seenGroups.has(groupName)) fail(`duplicate group name: ${groupName}`); + seenGroups.add(groupName); + checkAgentsMd(obj.agents_md, `group ${groupName}`); + if (!Array.isArray(obj.skills) || obj.skills.length === 0) + fail(`group ${groupName}: missing skills`); + for (const inner of obj.skills as unknown[]) { + if (!inner || typeof inner !== "object") + fail(`group ${groupName}: skill missing name`); + if ("group" in (inner as Record)) + fail(`group ${groupName}: nested groups are not supported`); + validateSkill(inner); + } + continue; + } + validateSkill(entry); + } + + const agents_md = (parsed as { agents_md?: unknown }).agents_md; + if (agents_md !== undefined) { + if (typeof agents_md !== "string" || !agents_md.trim()) + fail(`agents_md is empty`); + if ( + agents_md.includes(AGENTS_MD_START) || + agents_md.includes(AGENTS_MD_END) + ) { + fail(`agents_md contains reserved marker`); + } + return { skills: entries as ManifestEntry[], agents_md }; + } + return { skills: entries as ManifestEntry[] }; } async function main() { - const manifest = parse(await Bun.file(manifestPath).text()) - await ensure(root) + const manifest = parse(await Bun.file(manifestPath).text()); + await ensure(root); try { - for (const skill of manifest.skills) { - if (!skill.name) fail(`skill missing name`) - if (!Array.isArray(skill.steps)) fail(`${skill.name}: missing steps`) - await runSkill(skill.name, skill.steps) + for (const skill of flattenSkills(manifest.skills)) { + if (!skill.name) fail(`skill missing name`); + if (!Array.isArray(skill.steps)) fail(`${skill.name}: missing steps`); + await runSkill(skill.name, skill.steps); + } + + const additions = collectAgentsMd(manifest).join("\n\n"); + if (additions.trim()) { + await updateAgentsMd(path.join(cfg, "AGENTS.md"), additions); } } finally { - await cleanupWorkspaces() + await cleanupWorkspaces(); } } -await main().catch((err) => { - const msg = err instanceof Error ? err.message : String(err) - console.error(msg) - process.exit(1) -}) +if (import.meta.main) { + await main().catch((err: unknown) => { + const msg = err instanceof Error ? err.message : String(err); + console.error(msg); + process.exit(1); + }); +} diff --git a/scripts/package.json b/scripts/package.json new file mode 100644 index 0000000..5212897 --- /dev/null +++ b/scripts/package.json @@ -0,0 +1,27 @@ +{ + "name": "@ophios/scripts", + "private": true, + "devDependencies": { + "@eslint/js": "^10.0.1", + "@types/bun": "1.4.4", + "@types/node": "^24.12.2", + "eslint": "^10.13.0", + "eslint-config-prettier": "^10.1.8", + "globals": "^17.13.0", + "prettier": "^3.9.10", + "prettier-plugin-multiline-arrays": "^4.1.11", + "typescript": "6.0.3", + "typescript-eslint": "^8.72.1" + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "bun test", + "lint": "eslint .", + "lint:fix": "eslint . --fix", + "format": "prettier --write . --ignore-path .prettierignore", + "format:check": "prettier --check . --ignore-path .prettierignore" + }, + "dependencies": { + "yaml": "^2.9.1" + } +} diff --git a/scripts/tsconfig.json b/scripts/tsconfig.json new file mode 100644 index 0000000..7d49514 --- /dev/null +++ b/scripts/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "noUncheckedIndexedAccess": true, + "exactOptionalPropertyTypes": true, + "noImplicitOverride": true, + "noPropertyAccessFromIndexSignature": true, + "noImplicitReturns": true, + "skipLibCheck": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "types": ["bun", "node"] + }, + "include": ["*.ts"], + "exclude": ["**/node_modules/**", "**/dist/**", "**/coverage/**"] +} diff --git a/skills.schema.json b/skills.schema.json new file mode 100644 index 0000000..985a697 --- /dev/null +++ b/skills.schema.json @@ -0,0 +1,176 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://ophiosdev/opencode-cli/skills.schema.json", + "title": "skills.yaml manifest", + "description": "Skill installer manifest consumed by scripts/install-skills.ts. skills[] holds plain skills (- name) and named groups (- group) in install order; guidance order follows manifest order with a group's agents_md landing where the group sits, before its skills' own agents_md. Parse-time mirror of the installer; runtime-only checks (unique skill/group names, `..` traversal escapes, RegExp validity, repo existence, downloads) live in scripts/install-skills.ts.", + "type": "object", + "required": ["skills"], + "additionalProperties": false, + "properties": { + "skills": { + "type": "array", + "items": { "$ref": "#/$defs/entry" } + }, + "agents_md": { "$ref": "#/$defs/agentsMd" } + }, + "$defs": { + "agentsMd": { + "type": "string", + "pattern": ".*\\S.*", + "not": { + "anyOf": [ + { "pattern": "install-skills:agents-md:start" }, + { "pattern": "install-skills:agents-md:end" } + ] + }, + "description": "Markdown appended to the managed AGENTS.md block. Non-blank; must not contain the installer's reserved markers." + }, + "skillName": { + "type": "string", + "minLength": 1, + "pattern": "^(?!\\.{1,2}$)[^/\\\\]+$", + "description": "Skill directory name: no / or \\, never . or .. ." + }, + "relativeFile": { + "type": "string", + "minLength": 1, + "pattern": "^(?!/).+$", + "description": "Relative staged-file path. Must not be absolute; `..` escapes fail at install time." + }, + "downloadStep": { + "type": "object", + "required": ["type", "url", "dest"], + "additionalProperties": false, + "properties": { + "type": { "const": "download" }, + "url": { "type": "string", "minLength": 1, "description": "http(s) URL fetched into the staging dir." }, + "dest": { "$ref": "#/$defs/relativeFile" } + } + }, + "gitExportUrlStep": { + "type": "object", + "required": ["type", "url"], + "additionalProperties": false, + "properties": { + "type": { "const": "git-export" }, + "url": { "type": "string", "minLength": 1, "description": "Full GitHub URL of the skill tree to export." } + } + }, + "gitExportRepoStep": { + "type": "object", + "required": ["type", "repo", "path"], + "additionalProperties": false, + "properties": { + "type": { "const": "git-export" }, + "repo": { + "type": "string", + "pattern": "^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$", + "description": "GitHub owner/repo. Unpinned means the latest release (falls back to HEAD)." + }, + "path": { "type": "string", "minLength": 1, "description": "Subtree inside the repo to export." }, + "version": { "type": "string", "minLength": 1, "description": "Git ref to pin. Defaults to the latest release." } + } + }, + "uvPipStep": { + "type": "object", + "required": ["type", "packages"], + "additionalProperties": false, + "properties": { + "type": { "const": "uv-pip" }, + "packages": { + "type": "array", + "minItems": 1, + "items": { "type": "string", "minLength": 1 } + } + } + }, + "replaceStep": { + "type": "object", + "required": ["type", "file", "from", "to"], + "additionalProperties": false, + "properties": { + "type": { "const": "replace" }, + "file": { "$ref": "#/$defs/relativeFile" }, + "from": { "type": "string", "minLength": 1, "description": "Literal (non-regex) text to replace." }, + "to": { "type": "string", "description": "Replacement text; may be empty." }, + "expected": { + "type": "integer", + "minimum": 1, + "description": "Optional exact occurrence count; any other count fails the install. When omitted, all occurrences are replaced but at least one is required." + } + } + }, + "assertAbsentStep": { + "type": "object", + "required": ["type", "file", "pattern"], + "additionalProperties": false, + "properties": { + "type": { "const": "assert-absent" }, + "file": { "$ref": "#/$defs/relativeFile" }, + "pattern": { "type": "string", "minLength": 1, "description": "JavaScript RegExp; the install fails when it matches." } + } + }, + "shellStep": { + "type": "object", + "required": ["type", "commands"], + "additionalProperties": false, + "properties": { + "type": { "const": "shell" }, + "commands": { + "type": "string", + "pattern": ".*\\S.*", + "description": "bash -c body. Staging dir is the cwd; OPENCODE_CONFIG_DIR, SKILL_NAME and SKILL_STAGING_DIR are set. Non-zero exit fails the build. Only for tools that must install themselves." + } + } + }, + "step": { + "oneOf": [ + { "$ref": "#/$defs/downloadStep" }, + { "$ref": "#/$defs/gitExportUrlStep" }, + { "$ref": "#/$defs/gitExportRepoStep" }, + { "$ref": "#/$defs/uvPipStep" }, + { "$ref": "#/$defs/replaceStep" }, + { "$ref": "#/$defs/assertAbsentStep" }, + { "$ref": "#/$defs/shellStep" } + ], + "description": "Install steps run in order. Shell steps merge staged files over the skill dir instead of replacing it." + }, + "skill": { + "type": "object", + "required": ["name", "steps"], + "additionalProperties": false, + "properties": { + "name": { "$ref": "#/$defs/skillName" }, + "steps": { + "type": "array", + "items": { "$ref": "#/$defs/step" }, + "description": "Steps may be empty (export-only skill)." + }, + "agents_md": { "$ref": "#/$defs/agentsMd" } + } + }, + "group": { + "type": "object", + "required": ["group", "skills"], + "additionalProperties": false, + "description": "A group installs its skills in order but installs nothing itself. Its agents_md is shared guidance landing once where the group sits.", + "properties": { + "group": { + "type": "string", + "pattern": ".*\\S.*", + "description": "Group label. Must be unique in the manifest; must not collide with step/name keys." + }, + "skills": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#/$defs/skill" }, + "description": "Grouped skills, installed in order. Groups cannot nest." + }, + "agents_md": { "$ref": "#/$defs/agentsMd" } + } + }, + "entry": { + "oneOf": [{ "$ref": "#/$defs/skill" }, { "$ref": "#/$defs/group" }] + } + } +} diff --git a/skills.yaml b/skills.yaml index 68aeebc..fc42b6b 100644 --- a/skills.yaml +++ b/skills.yaml @@ -1,70 +1,147 @@ +# yaml-language-server: $schema=./skills.schema.json skills: - name: stop-slop steps: - type: git-export url: https://github.com/hardikpandya/stop-slop - - name: changelog - steps: - - type: git-export - url: https://github.com/sickn33/antigravity-awesome-skills/skills/changelog-automation + - group: caveman + skills: + - name: caveman + steps: + - type: git-export + repo: JuliusBrussee/caveman + path: skills/caveman - - name: caveman - steps: - - type: git-export - repo: JuliusBrussee/caveman - path: skills/caveman + - name: caveman-commit + steps: + - type: git-export + repo: JuliusBrussee/caveman + path: skills/caveman-commit - - name: caveman-commit - steps: - - type: git-export - repo: JuliusBrussee/caveman - path: skills/caveman-commit + - name: caveman-review + steps: + - type: git-export + repo: JuliusBrussee/caveman + path: skills/caveman-review - - name: caveman-review - steps: - - type: git-export - repo: JuliusBrussee/caveman - path: skills/caveman-review + - name: caveman-help + steps: + - type: git-export + repo: JuliusBrussee/caveman + path: skills/caveman-help - - name: caveman-help - steps: - - type: git-export - repo: JuliusBrussee/caveman - path: skills/caveman-help + - name: caveman-stats + steps: + - type: git-export + repo: JuliusBrussee/caveman + path: skills/caveman-stats - - name: caveman-stats - steps: - - type: git-export - repo: JuliusBrussee/caveman - path: skills/caveman-stats + - name: caveman-compress + steps: + - type: git-export + repo: JuliusBrussee/caveman + path: skills/caveman-compress - - name: caveman-compress - steps: - - type: git-export - repo: JuliusBrussee/caveman - path: skills/caveman-compress + - name: cavecrew + steps: + - type: git-export + repo: JuliusBrussee/caveman + path: skills/cavecrew - - name: cavecrew - steps: - - type: git-export - repo: JuliusBrussee/caveman - path: skills/cavecrew + - name: ultracave + steps: + - type: git-export + repo: JuliusBrussee/caveman + path: skills/ultracave - - name: moli-webfetch - steps: - - type: git-export - repo: lexmount/moli - path: skills/moli-webfetch + - name: megacave + steps: + - type: git-export + repo: JuliusBrussee/caveman + path: skills/megacave - - name: moli-websearch - steps: - - type: git-export - repo: lexmount/moli - path: skills/moli-websearch + - group: moli + skills: + - name: moli-webfetch + steps: + - type: git-export + repo: lexmount/moli + path: skills/moli-webfetch + + - name: moli-websearch + steps: + - type: git-export + repo: lexmount/moli + path: skills/moli-websearch + agents_md: | + ## moli + + `moli` is preinstalled on PATH (`moli --version`). Invoke it directly as `moli ...`. + If unavailable, stop and report it as blocked. Do not reinstall, upgrade, or fetch an + installer without explicit user approval. + + For live websites or web research, use the installed moli skills: `moli-webfetch` + for fetching/capturing JS-rendered pages, `moli-websearch` for keyword/image search. + Use built-in websearch only if user asks or moli unavailable. + Use the following search engines: DuckDuckGo HTML, Brave Search. + + Always Prefer `moli fetch` over raw curl for JS-rendered content. - name: convert-documents-to-markdown steps: - type: git-export repo: firecrawl/anydoc path: skills/convert-documents-to-markdown + - type: replace + file: SKILL.md + from: 'npx -y @firecrawl/anydoc' + to: 'anydoc' + - type: replace + file: SKILL.md + from: 'It needs Node 20+ and no install:' + to: 'It is preinstalled on PATH; invoke it directly, never via npx/bunx:' + - type: assert-absent + file: SKILL.md + pattern: 'npx[^\r\n]*@firecrawl/anydoc' + agents_md: | + ## anydoc + + `anydoc` is preinstalled on PATH (`anydoc --help`). Invoke it directly as `anydoc ...`. + Do not use `npx`/`bunx`, reinstall, or upgrade without explicit user approval. + + For office documents, spreadsheets, presentations, ebooks, or PDFs you cannot read directly, + use the installed `convert-documents-to-markdown` skill and the `anydoc` CLI to convert to Markdown. + For large documents write to a file with `-o` and read the parts you need. + + - name: graphify + steps: + - type: shell + commands: | + # Install graphify for opencode into a temp project dir — uses install.py's + # own _copy_skill_file + _install_opencode_plugin logic so the SKILL.md, + # references/ sidecar, .graphify_version stamp, and graphify.js plugin are + # all laid down correctly by graphify itself, not reconstructed here. + TMP_GRAPHIFY=/tmp/graphify-install + mkdir -p "$TMP_GRAPHIFY" + ( cd "$TMP_GRAPHIFY" && graphify install --project --platform opencode ) || exit 1 + + # Move installed artifacts to system opencode dir + cp -r "$TMP_GRAPHIFY/.opencode/skills/graphify" "${OPENCODE_CONFIG_DIR}/skills/graphify" + cp "$TMP_GRAPHIFY/.opencode/plugins/graphify.js" "${OPENCODE_CONFIG_DIR}/plugins/graphify.js" + + rm -rf "$TMP_GRAPHIFY" + # agents_md: | + # ## graphify + + # This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships. + + # When the user types `/graphify`, use the installed graphify skill or instructions before doing anything else. + + # Rules: + # - When graphify-out/graph.json exists, run `graphify query ""` before your first grep, search or source-file read for a codebase question, and put this rule in every subagent prompt that explores code. Read raw files only for lines the graph or an earlier read already located. Use `graphify path "" ""` for relationships and `graphify explain ""` for focused concepts. When the answer is under a Markdown heading, `graphify section ""` prints that section's text, so the .md need not be opened. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output. + # - Dirty graphify-out/ files are expected after hooks or incremental updates; dirty graph files are not a reason to skip graphify. Only skip graphify if the task is about stale or incorrect graph output, or the user explicitly says not to use it. + # - If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing. + # - Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context. + # - After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost). + # - A committed graphify-out/graph.json is rewritten whole on every build, so a large diff to it in a pull request is expected. Do not flag it as churn or suggest skipping the graph rebuild or its hooks.