2 Commits

Author SHA1 Message Date
Danny Kim 6c4e4bf67d Move the phase entry points into aliased module folders
Check / check (pull_request) Successful in 46s
2026-10-18 23:58:13 +09:00
Danny Kim 0a9f86a102 Group the sources into aliased modules and lint with the published plugins
Agents / agent (pull_request) Has been skipped
Check / check (pull_request) Successful in 38s
2026-10-18 23:50:27 +09:00
31 changed files with 438 additions and 614 deletions
@@ -0,0 +1,21 @@
---
description: bot-agents lint has prefer-readonly-parameter-types and the size/complexity rules off (Deno had no limits) and no overrides; nothing else
---
The repo follows [[lint-config-shape]] with one recorded exception, present
when the migration PR was approved:
- `typescript/prefer-readonly-parameter-types` is `"off"` in
`scripts/project-lint.ts`, as in the explicit-types template, because
Node/web types (`Response`, `Stats`, `RequestInit`) can never satisfy it.
- `vite.config.ts` has no `overrides`. The `scripts/**` override for
`typescript/no-unsafe-enum-comparison` was removed (2026-10-16):
`scripts/project-lint.ts` compares node types with `AST_NODE_TYPES` members
from `@typescript-eslint/types` instead of string literals
([[lint-overrides-policy]]).
Size and complexity limits match Deno, which had none here, so every Oxlint
limit rule is `"off"` ([[lint-config-shape]]). `src/run/index.ts` and `src/post/index.ts` keep
main's single-file layout (2026-10-17 revert of the size splits). Sequential
awaits in loops became recursion or a `reduce` chain (`no-await-in-loop`) to
stay sequential. Add no other opt-out without the user.
+1 -1
View File
@@ -72,7 +72,7 @@ import { x } from "../x.ts"; // no: no ../ anywhere
- An area used from outside exposes its API through its alias target, and - An area used from outside exposes its API through its alias target, and
callers import the alias (`#ui`), not files inside it. callers import the alias (`#ui`), not files inside it.
- Barrels are also the standard fix for `import/max-dependencies`: one barrel - Barrels are also the standard fix for `import/max-dependencies`: one barrel
import replaces many direct ones ([[lint-config]]). import replaces many direct ones ([[lint-overrides-policy]]).
- `import/no-cycle` is on; a barrel must not create a cycle. - `import/no-cycle` is on; a barrel must not create a cycle.
Relative imports are written with the `.ts` extension. Relative imports are written with the `.ts` extension.
+48
View File
@@ -0,0 +1,48 @@
---
description: vite.config.ts lint uses Oxlint categories at error with Deno size limits, names no rule itself, and spreads configs from the plugins and scripts/project-lint.ts
---
The lint config is short and category-driven (user decisions 2026-10-14/15):
turn on whole categories, then list only what parity or a real need adds.
```ts
lint: {
plugins: ["typescript", "unicorn", "oxc", "import"],
jsPlugins: ["eslint-plugin-explicit-types", "./scripts/project-lint.ts"],
categories: { correctness: "error", suspicious: "error", pedantic: "error", perf: "error" },
rules: { ...explicitTypes.configs.concrete.rules, ...projectLint.configs.project.rules },
ignorePatterns: ["src/generated/**"], // generated files only, see below
options: { typeAware: true, typeCheck: true, maxWarnings: 0, reportUnusedDisableDirectives: "error" },
},
```
- **Categories:** `correctness`, `suspicious`, `pedantic`, `perf` at `error`.
`style` and `restriction` are never turned on wholesale; pick single rules
from them in `configs.project`. Extra rules that categories bring are fine.
- **Size limits match Deno** (2026-10-17, replaces the 2026-10-16 "default
limits stay"): repos behave as they did on Deno. bot-agents ran `deno lint`
with no config, so it had no size or complexity limit, and every Oxlint
limit rule (`complexity`, `max-lines`, `max-params`, `id-length`,
`no-nested-ternary`, `max-lines-per-function`, `max-classes-per-file`,
`max-depth`, `max-nested-callbacks`, `max-statements`,
`import/max-dependencies`, `unicorn/max-nested-calls`) is `"off"` in
`configs.project`. No file is split for size. Do not add new opt-outs
anywhere without asking the user.
- **`vite.config.ts` names no rule.** Every rule id, built-in ones included,
lives in `configs.project` of `scripts/project-lint.ts`
([[project-lint-plugin]]). `vite.config.ts` only spreads configs.
- **Published plugins are consumed through their configs**: ESLint flat config
uses `plugin.configs.<name>`; Oxlint lists the package in `jsPlugins` and
spreads `plugin.configs.<name>.rules`, since Oxlint plugins carry no configs.
Use the configs equivalent to what the repo enabled under Deno.
- **`maxWarnings: 0`** keeps Deno's "every diagnostic fails" behaviour.
- **`ignorePatterns`** is only for generated files (compiled output, codegen).
Hand-written code is never ignored.
- **No lint disable comments**: [[lint-no-disable-comments]].
- **Parity:** [[lint-parity-never-shrinks]]. **Naming:** [[naming-id-match]].
- Don't add a second import sorter; the import-structure plugin's
`enforce-import-order` is the only one, and Oxfmt's `sortImports` stays off.
`perf` came last: in the template it flagged nine `.includes` on constant
arrays, fixed as `ReadonlySet` + `.has()` rather than by turning a rule off.
That is the expected response to any new rule: change the code.
-51
View File
@@ -1,51 +0,0 @@
---
description: Lint config shape: every non-nursery Oxlint category on, plugins via `all`, a blacklist of offs in configs.project, per-file exceptions only in projectOverrides, ignorePatterns only for generated output
---
Policy (2026-10-19): a blacklist, not a whitelist. Replaces the older
category-subset and "no overrides" notes.
- **Categories:** `correctness`, `suspicious`, `pedantic`, `perf`, `style`,
`restriction` at `error`. `nursery` stays off (no line for it).
- **Plugins** are enabled whole through their `all` config
(`explicitTypes.configs.all.rules`, `importStructure.configs.all.rules`).
- **Blacklist:** repo-wide offs and option tweaks live in
`projectLint.configs.project.rules` in `scripts/project-lint.ts`, spread
last in `rules`, each with a one-line reason. Never re-list a rule a
category already turns on. bot-agents runs on Node everywhere, so
`import/no-nodejs-modules`, `unicorn/no-process-exit`, and `no-console` are
off repo-wide.
- **Per-file exceptions** only via `projectOverrides`, the whole `overrides`
array exported from `scripts/project-lint.ts`: the Node code entry
(`vite.config.ts`, `scripts/**`, `nodeRules`) first, then one entry per
exception with a why-comment. `vite.config.ts` has exactly
`overrides: projectOverrides`.
- **No `allowFiles`** options in custom rules, and no disable comments
([[lint-no-disable-comments]]).
- **`ignorePatterns`** only for generated or build output, never hand-written
code. A hand-written file is linted, with override entries for only what it
legitimately breaks. bot-agents has no generated code, so none.
- **Precedence:** categories < `rules` (a later spread wins) < `overrides` (a
later entry wins).
- Size and complexity limits (`complexity`, `max-lines`, ...) are set to the
smallest value the current code passes.
```ts
// scripts/project-lint.ts
export const projectOverrides: OxlintOverride[] = [
{ files: ["vite.config.ts", "scripts/**"], rules: nodeRules },
// Why: src/example.ts must ... (a per-file exception, if one is ever needed)
// { files: ["src/example.ts"], rules: { "some-rule": "off" } },
];
// vite.config.ts
rules: {
...explicitTypes.configs.all.rules,
...importStructure.configs.all.rules,
...projectLint.configs.project.rules,
},
overrides: projectOverrides,
```
A new category hit is fixed in the code; an off or exception is added only
for a real collision or churn, with its reason. Rules: [[project-lint-plugin]].
+33
View File
@@ -0,0 +1,33 @@
---
description: No lint overrides for source files; narrow ones only for scripts/**; generated files go in ignorePatterns; size limits match Deno, so nothing is split for size
---
Final policy (2026-10-16). The user considers per-file `overrides` bad
practice.
- **Source files: never.** No `overrides` entry may target `src/**` or any
other hand-written production or test code.
- **The one exception** is in lint-plugin repos: `import/max-dependencies`
off for `src/rules/index.ts`, the rule registry, which must import every
rule. It is not a precedent for apps.
- **`scripts/**`:** a narrow override is allowed when a tooling script truly
needs it, e.g. `no-console` in a CLI script.
- **Generated files:** list them in `ignorePatterns`, never `overrides`.
- **Anything else needs the user's approval first.** When the user is away,
don't add it: refactor, or leave the violation failing and log the question.
## Fix the code instead
Category rule violations are fixed in the code without behavior change,
covered by the tests, inside the same migration PR; e.g. `prefer-set-has`
becomes `const K: ReadonlySet<string> = new Set([...])` with `.has`.
Size and complexity limits are not refactored for: they match what Deno
enforced (2026-10-17, replacing the earlier "refactor to Oxlint's defaults"),
which for bot-agents is none, so those rules are `"off"`
([[lint-config-shape]]).
Alias rule: an alias may point anywhere and owns its target (a folder's
`index.ts` owns the folder and below, any other file owns only itself); no
two aliases may own the same file, and `../` is banned everywhere
([[imports-aliases-barrels]]).
+2 -2
View File
@@ -52,5 +52,5 @@ export default plugin;
and every repo should look the same. and every repo should look the same.
`scripts/` is tooling, not production code: never packed or published, and `scripts/` is tooling, not production code: never packed or published, and
no tests. Its offs sit in the Node code entry of `projectOverrides`; see no tests. Narrow `overrides` for `scripts/**` are allowed when a script truly
[[lint-config]]. needs one (e.g. `no-console`); see [[lint-overrides-policy]].
+3 -5
View File
@@ -50,11 +50,9 @@ relative imports. `scripts/` is flat: one file per tool, no subfolders and no `i
([.agents/memory/imports-aliases-barrels.md](.agents/memory/imports-aliases-barrels.md)). ([.agents/memory/imports-aliases-barrels.md](.agents/memory/imports-aliases-barrels.md)).
The only config files are `package.json`, `tsconfig.json`, and The only config files are `package.json`, `tsconfig.json`, and
`vite.config.ts`, plus `package-lock.json`. Repo-local lint rules, the rule `vite.config.ts`, plus `package-lock.json`. Repo-local lint rules and the rule
list, and the `overrides` array (`projectOverrides`) live in list live in `scripts/project-lint.ts`. Lint disable comments are not allowed;
`scripts/project-lint.ts` fix the source instead.
([.agents/memory/lint-config.md](.agents/memory/lint-config.md)). Lint disable
comments are not allowed; fix the source instead.
The composite action uses npm only to install the externally distributed The composite action uses npm only to install the externally distributed
Claude Code, Codex, and OpenCode command-line tools; do not treat those Claude Code, Codex, and OpenCode command-line tools; do not treat those
+69 -134
View File
@@ -1,7 +1,7 @@
/** /**
* `project` — this repository's changes to the Oxlint categories in * `project` — lint rules this repository holds its own source to, on top of
* `vite.config.ts`. Its rules of its own are `no-disable-comments` and * the Oxlint categories in `vite.config.ts`. Its rules of its own are
* `no-asset-imports`. * `no-disable-comments` and `no-asset-imports`.
* *
* Loaded by `vite.config.ts` as an Oxlint `jsPlugins` entry. * Loaded by `vite.config.ts` as an Oxlint `jsPlugins` entry.
* *
@@ -10,11 +10,11 @@
import type { LanguageOptions, RuleDefinition, RuleVisitor, TextSourceCode } from "@eslint/core"; import type { LanguageOptions, RuleDefinition, RuleVisitor, TextSourceCode } from "@eslint/core";
import { AST_NODE_TYPES, type TSESTree } from "@typescript-eslint/types"; import { AST_NODE_TYPES, type TSESTree } from "@typescript-eslint/types";
import type { DummyRuleMap, OxlintOverride } from "vite-plus/lint"; import type { DummyRuleMap } from "vite-plus/lint";
/** The source code both hosts hand a rule, with the comment list. */ /** The source code both hosts hand a rule, with the comment list. */
interface ProjectSourceCode extends TextSourceCode { interface ProjectSourceCode extends TextSourceCode {
getAllComments: () => TSESTree.Comment[]; getAllComments(): TSESTree.Comment[];
} }
/** ESLint's default rule types, reporting TypeScript-ESTree nodes. */ /** ESLint's default rule types, reporting TypeScript-ESTree nodes. */
@@ -161,9 +161,9 @@ const noAssetImportsRule: ProjectRule = {
}; };
/** /**
* This repository's changes to the Oxlint categories in `vite.config.ts`, * This repository's own rule list, spread by `vite.config.ts`: rules that
* which turn every non-nursery category on: its own rules, the category * sit outside the Oxlint categories, plus the template's extras. Built-in
* rules it turns off, and options that differ from a rule's defaults. * Oxlint rule ids sit here too, so `vite.config.ts` lists no rule by name.
*/ */
const rules: DummyRuleMap = { const rules: DummyRuleMap = {
// The explicit-types template's `camelcase` stand-in: no `_` inside a name // The explicit-types template's `camelcase` stand-in: no `_` inside a name
@@ -174,6 +174,31 @@ const rules: DummyRuleMap = {
"^_*[^_]*_*$|^[^a-z]*$", "^_*[^_]*_*$|^[^a-z]*$",
{ properties: false, classFields: false, onlyDeclarations: false, ignoreDestructuring: true }, { properties: false, classFields: false, onlyDeclarations: false, ignoreDestructuring: true },
], ],
// Rules outside the categories.
"no-array-constructor": "error",
"no-case-declarations": "error",
"no-empty": "error",
"no-fallthrough": "error",
"no-inner-declarations": "error",
"no-prototype-builtins": "error",
"no-redeclare": "error",
"no-regex-spaces": "error",
"no-var": "error",
"prefer-const": "error",
"require-await": "error",
"require-yield": "error",
"typescript/adjacent-overload-signatures": "error",
"typescript/ban-ts-comment": "error",
"typescript/no-empty-interface": "error",
"typescript/no-empty-object-type": "error",
"typescript/no-explicit-any": "error",
"typescript/no-namespace": "error",
"typescript/no-non-null-asserted-optional-chain": "error",
"typescript/no-unsafe-function-type": "error",
"typescript/no-wrapper-object-types": "error",
"typescript/prefer-as-const": "error",
"typescript/prefer-namespace-keyword": "error",
"typescript/triple-slash-reference": "error",
// On Node, these come from an explicit `node:` import instead of the global scope. // On Node, these come from an explicit `node:` import instead of the global scope.
"no-restricted-globals": [ "no-restricted-globals": [
"error", "error",
@@ -184,137 +209,47 @@ const rules: DummyRuleMap = {
"setImmediate", "setImmediate",
"clearImmediate", "clearImmediate",
], ],
// Single capital type parameters, which explicit-types requires, may be one letter. // The explicit-types template's extras.
"id-length": ["error", { exceptionPatterns: ["^[A-Z]$"] }], "import/no-cycle": "error",
// Option tweaks. // `../` is banned in every file; anything above a file needs a `#` alias.
"one-var": ["error", "never"], "import/no-relative-parent-imports": "error",
"no-use-before-define": ["error", { functions: false }], "typescript/consistent-type-imports": "error",
"func-style": ["error", "declaration", { allowArrowFunctions: true }], "typescript/no-import-type-side-effects": "error",
"unicorn/import-style": ["error", { styles: { "node:path": { named: true } } }], "typescript/no-non-null-assertion": "error",
// Each limit is the smallest value the current code passes. // No disable comments at all.
complexity: ["error", 26],
"max-depth": ["error", 6],
"max-lines": ["error", { max: 2048, skipBlankLines: false, skipComments: false }],
"max-lines-per-function": ["error", 96],
"max-params": ["error", 4],
"max-statements": ["error", 32],
"import/max-dependencies": ["error", { max: 13 }],
"unicorn/max-nested-calls": ["error", { max: 4 }],
// No lint suppression and only `.ts` imports, as in the plugin template.
"project/no-disable-comments": "error", "project/no-disable-comments": "error",
"project/no-asset-imports": "error", "project/no-asset-imports": "error",
// Off, collides with a repo or plugin rule, Oxfmt, or another category rule: "unicorn/no-abusive-eslint-disable": "error",
// Collides with `#private`: members are public unless marked so. // Size and complexity limits match Deno's: this repo's `deno lint` ran the
"typescript/explicit-member-accessibility": "off", // `recommended` set with no config file, so no size or complexity rule
// Collides with `typescript/prefer-readonly-parameter-types` being off. // applied and none applies here. Each Oxlint limit rule, from a category or
"typescript/prefer-readonly": "off", // not, is off:
// Collides with Node's and the web's mutable types (`Response`, `Stats`). // - `complexity`: Deno had no `max-complexity`.
// - `max-lines`: Deno had no `max-file-lines`.
// - `max-params`: Deno had no `max-params`.
// - `id-length`: Deno had no `max-identifier-length`.
// - `no-nested-ternary`: Deno had no `max-nest-ternaries`.
// - `max-lines-per-function`, `max-classes-per-file`, `max-depth`,
// `max-nested-callbacks`, `max-statements`, `import/max-dependencies`,
// `unicorn/max-nested-calls`: Deno had none of these.
complexity: "off",
"max-lines": "off",
"max-params": "off",
"id-length": "off",
"no-nested-ternary": "off",
"max-lines-per-function": "off",
"max-classes-per-file": "off",
"max-depth": "off",
"max-nested-callbacks": "off",
"max-statements": "off",
"import/max-dependencies": "off",
"unicorn/max-nested-calls": "off",
// Pedantic, but Node's and the web's own types (`Response`, `Stats`,
// `RequestInit`) are mutable, so no parameter of theirs can pass; the
// explicit-types template and the app repos turn it off too.
"typescript/prefer-readonly-parameter-types": "off", "typescript/prefer-readonly-parameter-types": "off",
// Collides with explicit-types `no-utility-types`, which bans `Record`.
"typescript/consistent-indexed-object-style": "off",
// Collides with explicitly annotated declarations.
"typescript/no-inferrable-types": "off",
// Collides with import-structure `enforce-import-order`.
"sort-imports": "off",
// Collides with import-structure `enforce-mod-file` barrels.
"oxc/no-barrel-file": "off",
// Collides with exporting each declaration where it stands.
"import/group-exports": "off",
// Collides with exporting each declaration where it stands.
"import/exports-last": "off",
// Collides with `import/no-default-export`.
"import/prefer-default-export": "off",
// Collides with `unicorn/prefer-ternary`.
"no-ternary": "off",
// Collides with `require-await` and `promise-function-async`.
"oxc/no-async-await": "off",
// Collides with `typescript/prefer-optional-chain`.
"oxc/no-optional-chaining": "off",
// Collides with file mode checks such as `mode & 0o077`.
"no-bitwise": "off",
// Collides with explicit-types `no-optional-null`, which makes `undefined` the absent value.
"no-undefined": "off",
// Collides with `typescript/no-floating-promises`, which `void` satisfies.
"no-void": "off",
// Collides with JSON and Node APIs, which return `null`.
"unicorn/no-null": "off",
// Collides with `import/no-default-export`.
"import/no-named-export": "off",
// Collides with `typescript/consistent-type-imports`.
"import/consistent-type-specifier-style": "off",
// Collides with `require-await`, which fails an `async` wrapper with no `await`.
"typescript/promise-function-async": "off",
// Collides with explicit-types `no-undefined-type`: a `let` that `try`
// assigns would need `T | undefined`.
"init-declarations": "off",
// Collides with `no-await-in-loop`: sequential steps chain through `reduce`.
"unicorn/no-array-reduce": "off",
// Collides with literal Gitea Actions `${{ }}` expressions in workflow strings.
"no-template-curly-in-string": "off",
// Node code, everywhere: this action runs on Node.
// Node built-ins are the action's runtime.
"import/no-nodejs-modules": "off",
// Command-line entry points set their exit status.
"unicorn/no-process-exit": "off",
// The action reports to the job log through the console.
"no-console": "off",
// PENDING USER: union members are values in profiles.json, the Gitea API,
// and posted comments; renaming them changes behavior.
"explicit-types/upper-snake-string-unions": "off",
// PENDING USER: a fitting `name` needs a constructor and changes logged
// error names.
"unicorn/custom-error-definition": "off",
// Off, too much churn:
// Literal numbers read better than a constant per use.
"no-magic-numbers": "off",
// Keys follow meaning, not the alphabet.
"sort-keys": "off",
// Comments may start with code or lowercase identifiers.
"capitalized-comments": "off",
// explicit-types `require-return-type` covers return types.
"typescript/explicit-function-return-type": "off",
// explicit-types `require-return-type` covers return types.
"typescript/explicit-module-boundary-types": "off",
// Empty callbacks are legitimate no-ops.
"no-empty-function": "off",
// Methods may not need `this`.
"class-methods-use-this": "off",
// Braces only where a case declares.
"unicorn/switch-case-braces": "off",
// Plain property reads are fine.
"prefer-destructuring": "off",
// Object rest and spread are idiomatic.
"oxc/no-rest-spread-properties": "off",
// Short numbers need no separators.
"unicorn/numeric-separators-style": "off",
// `continue` keeps loop bodies flat.
"no-continue": "off",
}; };
/** Node code (`vite.config.ts` and `scripts/`): the first `projectOverrides` entry. */
const nodeRules: DummyRuleMap = {
// Vite and the Oxlint plugin host read a default export.
"import/no-default-export": "off",
// Node code: tooling imports Node's built-ins.
"import/no-nodejs-modules": "off",
// Node code: a CLI exits with a status.
"unicorn/no-process-exit": "off",
// Node code: a CLI reports through the console.
"no-console": "off",
};
/**
* The whole `overrides` array of `vite.config.ts`: the Node code entry first,
* then each per-file exception, each with a comment saying why. Later entries
* win over earlier ones, and all of them over `rules`.
*/
export const projectOverrides: OxlintOverride[] = [
{
files: ["vite.config.ts", "scripts/**"],
rules: nodeRules,
},
];
/** /**
* The repo-local plugin, namespace `project`: its own rules, enabled as * The repo-local plugin, namespace `project`: its own rules, enabled as
* `project/<rule>`, and `configs.project`, the rule list above. * `project/<rule>`, and `configs.project`, the rule list above.
+8 -10
View File
@@ -19,10 +19,10 @@ test("retries once after an invalid refresh token", async () => {
() => () =>
Promise.resolve({ Promise.resolve({
code: 1, code: 1,
error: (attempts += 1) === 1 ? "ERROR: invalid_refresh_token" : "still failed", error: attempts++ === 0 ? "ERROR: invalid_refresh_token" : "still failed",
}), }),
() => { () => {
relogins += 1; relogins++;
return Promise.resolve(); return Promise.resolve();
}, },
); );
@@ -39,14 +39,14 @@ test("does not retry an unrelated failure", async () => {
let relogins = 0; let relogins = 0;
await retryInvalidToken( await retryInvalidToken(
() => { () => {
attempts += 1; attempts++;
return Promise.resolve({ return Promise.resolve({
code: 1, code: 1,
error: "rate limited", error: "rate limited",
}); });
}, },
() => { () => {
relogins += 1; relogins++;
return Promise.resolve(); return Promise.resolve();
}, },
); );
@@ -87,11 +87,11 @@ test("re-logs in after the job 9837 revoked-session stderr", async () => {
const result = await retryInvalidToken( const result = await retryInvalidToken(
() => () =>
Promise.resolve({ Promise.resolve({
code: (attempts += 1) > 1 ? 0 : 1, code: attempts++ > 0 ? 0 : 1,
error: attempts === 1 ? REVOKED_CODEX.join("\n") : "", error: attempts === 1 ? REVOKED_CODEX.join("\n") : "",
}), }),
() => { () => {
relogins += 1; relogins++;
return Promise.resolve(); return Promise.resolve();
}, },
); );
@@ -144,8 +144,7 @@ test.skipIf(IS_WINDOWS)("stages and persists only a regular private Codex login"
const staged = await stageCodexAuth(canonical, home, currentUid(), currentGid()); const staged = await stageCodexAuth(canonical, home, currentUid(), currentGid());
expect(await readFile(staged, "utf8")).toStrictEqual(AUTH); expect(await readFile(staged, "utf8")).toStrictEqual(AUTH);
const stagedStat = await stat(staged); expect((await stat(staged)).mode & 0o777).toBe(0o600);
expect(stagedStat.mode & 0o777).toBe(0o600);
const refreshed = JSON.stringify({ const refreshed = JSON.stringify({
auth_mode: "chatgpt", auth_mode: "chatgpt",
@@ -154,8 +153,7 @@ test.skipIf(IS_WINDOWS)("stages and persists only a regular private Codex login"
await writeFile(staged, refreshed); await writeFile(staged, refreshed);
await persistCodexAuth(staged, canonical); await persistCodexAuth(staged, canonical);
expect(await readFile(canonical, "utf8")).toStrictEqual(refreshed); expect(await readFile(canonical, "utf8")).toStrictEqual(refreshed);
const canonicalStat = await stat(canonical); expect((await stat(canonical)).mode & 0o777).toBe(0o600);
expect(canonicalStat.mode & 0o777).toBe(0o600);
} finally { } finally {
await rm(root, { recursive: true }); await rm(root, { recursive: true });
} }
+9 -12
View File
@@ -12,7 +12,7 @@ import {
} from "node:fs/promises"; } from "node:fs/promises";
import { dirname, join } from "node:path"; import { dirname, join } from "node:path";
import { field, isNotFound, isObject } from "#common"; import { isNotFound, isObject } from "#common";
interface CodexApiKey { interface CodexApiKey {
kind: "api-key"; kind: "api-key";
@@ -89,16 +89,15 @@ async function readCodexAuth(path: string): Promise<string> {
} catch { } catch {
throw new Error("invalid Codex login"); throw new Error("invalid Codex login");
} }
const authMode = field(value, "auth_mode"); const tokens = isObject(value) ? value["tokens"] : undefined;
const tokens = field(value, "tokens");
if ( if (
typeof authMode !== "string" || !isObject(value) ||
authMode === "" || typeof value["auth_mode"] !== "string" ||
value["auth_mode"] === "" ||
!isObject(tokens) || !isObject(tokens) ||
!["access_token", "refresh_token", "id_token", "account_id"].every((name) => { !["access_token", "refresh_token", "id_token", "account_id"].every(
const token = field(tokens, name); (name) => typeof tokens[name] === "string" && tokens[name] !== "",
return typeof token === "string" && token !== ""; )
})
) { ) {
throw new Error("invalid Codex login"); throw new Error("invalid Codex login");
} }
@@ -121,9 +120,7 @@ export async function stageCodexAuth(
await chmod(stagedPath, 0o600); await chmod(stagedPath, 0o600);
await chown(stagedPath, uid, gid); await chown(stagedPath, uid, gid);
} catch (error) { } catch (error) {
if (!isNotFound(error)) { if (!isNotFound(error)) throw error;
throw error;
}
} }
return stagedPath; return stagedPath;
} }
+13 -21
View File
@@ -1,4 +1,4 @@
import { field, isObject } from "#common"; import { isObject } from "#common";
import { AgentAuthError } from "#profiles"; import { AgentAuthError } from "#profiles";
export function openCodeArgs(model: string, prompt: string): string[] { export function openCodeArgs(model: string, prompt: string): string[] {
@@ -49,23 +49,20 @@ export async function collectOpenCodeOutput(
export function openCodeError(output: string): Error | null { export function openCodeError(output: string): Error | null {
let failure: Error | null = null; let failure: Error | null = null;
for (const line of output.split("\n")) { for (const line of output.split("\n")) {
if (line.trim() === "") { if (line.trim() === "") continue;
continue;
}
let event: unknown; let event: unknown;
try { try {
event = JSON.parse(line); event = JSON.parse(line);
} catch { } catch {
continue; continue;
} }
const error = field(event, "error"); if (!isObject(event)) continue;
if (field(event, "type") !== "error" || !isObject(error)) { const { type, error } = event;
if (type !== "error" || !isObject(error)) {
continue; continue;
} }
const name = field(error, "name"); const { name, data } = error;
const data = field(error, "data"); const { message, statusCode } = isObject(data) ? data : {};
const message = field(data, "message");
const statusCode = field(data, "statusCode");
const detail = `opencode ${typeof name === "string" ? name : "error"}${ const detail = `opencode ${typeof name === "string" ? name : "error"}${
typeof statusCode === "number" ? ` (API error ${statusCode})` : "" typeof statusCode === "number" ? ` (API error ${statusCode})` : ""
}: ${typeof message === "string" ? message : "unknown error"}`; }: ${typeof message === "string" ? message : "unknown error"}`;
@@ -82,18 +79,13 @@ export function openCodeError(output: string): Error | null {
export function parseOpenCodeEvents(output: string): string { export function parseOpenCodeEvents(output: string): string {
let result: string | null = null; let result: string | null = null;
for (const line of output.split("\n")) { for (const line of output.split("\n")) {
if (line.trim() === "") { if (line.trim() === "") continue;
continue;
}
const event: unknown = JSON.parse(line); const event: unknown = JSON.parse(line);
const part = field(event, "part"); if (!isObject(event)) continue;
if (field(event, "type") !== "text" || !isObject(part)) { const { type, part } = event;
continue; if (type !== "text" || !isObject(part)) continue;
} const { text } = part;
const text = field(part, "text"); if (typeof text === "string" && text.trim() !== "") result = text;
if (typeof text === "string" && text.trim() !== "") {
result = text;
}
} }
if (result === null) { if (result === null) {
throw openCodeError(output) ?? new Error("OpenCode produced no text output"); throw openCodeError(output) ?? new Error("OpenCode produced no text output");
+2 -1
View File
@@ -1,3 +1,4 @@
// Helpers every phase shares: error and JSON value checks. // Helpers every phase shares: error and JSON value checks.
export { isNotFound } from "./errors.ts"; export { isNotFound } from "./errors.ts";
export { field, isMapping, isObject } from "./json.ts"; export { isMapping, isObject } from "./json.ts";
export type { JsonObject } from "./json.ts";
-23
View File
@@ -1,23 +0,0 @@
import { expect, test } from "vite-plus/test";
import { field, isMapping, isObject } from "./json.ts";
test("reads a named field of a parsed object", () => {
const value: unknown = JSON.parse('{"login":"bot","user":{"login":"nested"}}');
expect(field(value, "login")).toBe("bot");
expect(field(field(value, "user"), "login")).toBe("nested");
expect(field(value, "missing")).toBeUndefined();
});
test("reads no field of a value that is not an object", () => {
for (const value of [null, undefined, "text", 1, true]) {
expect(field(value, "login")).toBeUndefined();
}
});
test("counts arrays as objects but not as mappings", () => {
expect(isObject([])).toBe(true);
expect(isMapping([])).toBe(false);
expect(isMapping({})).toBe(true);
expect(field(["first"], "0")).toBe("first");
});
+5 -12
View File
@@ -1,19 +1,12 @@
// Checks and field reads for values parsed from JSON, which arrive as // Type guards for values read from JSON, which arrive as `unknown`.
// `unknown`. Callers read the fields they know by name into their own export type JsonObject = NodeJS.Dict<unknown>;
// declared interfaces.
// Any non-null object, arrays included. // Any non-null object, arrays included: reading a missing key yields undefined.
export function isObject(value: unknown): value is object { export function isObject(value: unknown): value is JsonObject {
return typeof value === "object" && value !== null; return typeof value === "object" && value !== null;
} }
// A plain mapping, which an array is not. // A plain mapping, which an array is not.
export function isMapping(value: unknown): value is object { export function isMapping(value: unknown): value is JsonObject {
return isObject(value) && !Array.isArray(value); return isObject(value) && !Array.isArray(value);
} }
// The named field of an object, or undefined for a missing field or a value
// that is not an object.
export function field(value: unknown, name: string): unknown {
return isObject(value) ? Reflect.get(value, name) : undefined;
}
+1 -3
View File
@@ -8,9 +8,7 @@ export { type Fetcher, type PostContext, postRuntime } from "./post.ts";
function required(name: string): string { function required(name: string): string {
const value = process.env[name]; const value = process.env[name];
if (value === undefined || value === "") { if (value === undefined || value === "") throw new Error(`${name} is not set`);
throw new Error(`${name} is not set`);
}
return value; return value;
} }
+4 -12
View File
@@ -45,15 +45,9 @@ async function writeArtifacts(
review?: string, review?: string,
anchors?: unknown, anchors?: unknown,
): Promise<void> { ): Promise<void> {
if (!outcome.ok) { if (!outcome.ok) return;
return; if (review !== undefined) await writePrivate(outcome.reviewPath, review);
} if (anchors !== undefined) await writePrivate(outcome.anchorsPath, JSON.stringify(anchors));
if (review !== undefined) {
await writePrivate(outcome.reviewPath, review);
}
if (anchors !== undefined) {
await writePrivate(outcome.anchorsPath, JSON.stringify(anchors));
}
} }
function manifestFor(runtimeDir: string, profileHome: string): RuntimeManifest { function manifestFor(runtimeDir: string, profileHome: string): RuntimeManifest {
@@ -112,9 +106,7 @@ const missing = async (path: string): Promise<boolean> => {
await stat(path); await stat(path);
return false; return false;
} catch (error) { } catch (error) {
if (isNotFound(error)) { if (isNotFound(error)) return true;
return true;
}
throw error; throw error;
} }
}; };
+37 -53
View File
@@ -2,7 +2,7 @@ import type { Stats } from "node:fs";
import { lstat, readFile, rm } from "node:fs/promises"; import { lstat, readFile, rm } from "node:fs/promises";
import { join } from "node:path"; import { join } from "node:path";
import { field, isNotFound, isObject } from "#common"; import { isNotFound, isObject } from "#common";
import { failureFooter, type FailureReason, type ProfileFailure, withProfile } from "#profiles"; import { failureFooter, type FailureReason, type ProfileFailure, withProfile } from "#profiles";
import { readRuntimeManifest, type RuntimeManifest, type RuntimeOutcome } from "#runtime"; import { readRuntimeManifest, type RuntimeManifest, type RuntimeOutcome } from "#runtime";
@@ -22,12 +22,12 @@ interface Anchor {
const ANSI = new RegExp(`${String.fromCodePoint(27)}\\[[0-9;]*[A-Za-z]`, "gu"); const ANSI = new RegExp(`${String.fromCodePoint(27)}\\[[0-9;]*[A-Za-z]`, "gu");
const stripAnsi = (text: string): string => text.replace(ANSI, ""); const stripAnsi = (text: string): string => text.replace(ANSI, "");
const VERDICTS = new Map<string, [event: string, mark: string]>([ const VERDICTS: NodeJS.Dict<[event: string, mark: string]> = {
["Approved", ["APPROVED", "✅"]], Approved: ["APPROVED", "✅"],
["Changes requested", ["REQUEST_CHANGES", "🛑"]], "Changes requested": ["REQUEST_CHANGES", "🛑"],
]); };
const PROFILE_TYPES = new Set<unknown>(["claude", "codex", "opencode"]); const PROFILE_TYPES: Set<unknown> = new Set(["claude", "codex", "opencode"]);
const FAILURE_REASONS = new Set<unknown>(["sign-in failed", "usage exhausted", "failed"]); const FAILURE_REASONS: Set<unknown> = new Set(["sign-in failed", "usage exhausted", "failed"]);
const isProfileType = (value: unknown): value is ProfileFailure["type"] => PROFILE_TYPES.has(value); const isProfileType = (value: unknown): value is ProfileFailure["type"] => PROFILE_TYPES.has(value);
const isFailureReason = (value: unknown): value is FailureReason => FAILURE_REASONS.has(value); const isFailureReason = (value: unknown): value is FailureReason => FAILURE_REASONS.has(value);
const failureComment = (failures: ProfileFailure[]): string => const failureComment = (failures: ProfileFailure[]): string =>
@@ -40,19 +40,13 @@ class GiteaRequestError extends Error {}
function parseAnchors(text: string, sourcePath: string): Anchor[] { function parseAnchors(text: string, sourcePath: string): Anchor[] {
const entries: unknown = JSON.parse(text); const entries: unknown = JSON.parse(text);
if (!Array.isArray(entries)) { if (!Array.isArray(entries)) throw new TypeError(`${sourcePath}: not an array`);
throw new TypeError(`${sourcePath}: not an array`);
}
return entries.map((entry: unknown, index) => { return entries.map((entry: unknown, index) => {
const at = `${sourcePath}[${index}]`; const at = `${sourcePath}[${index}]`;
if (!isObject(entry)) { if (!isObject(entry)) {
throw new TypeError(`${at}: not an object`); throw new TypeError(`${at}: not an object`);
} }
const path = field(entry, "path"); const { path, line, side = "new", body } = entry;
const line = field(entry, "line");
const givenSide = field(entry, "side");
const side = givenSide === undefined ? "new" : givenSide;
const body = field(entry, "body");
if (typeof path !== "string" || path === "") { if (typeof path !== "string" || path === "") {
throw new TypeError(`${at}.path: expected a repository path`); throw new TypeError(`${at}.path: expected a repository path`);
} }
@@ -74,42 +68,43 @@ async function readOutcome(path: string): Promise<RuntimeOutcome> {
if (!isObject(value) || !("ok" in value)) { if (!isObject(value) || !("ok" in value)) {
throw new Error("invalid agent outcome"); throw new Error("invalid agent outcome");
} }
const ok = field(value, "ok"); const outcome = value;
if (ok === false) { if (outcome["ok"] === false) {
// Only known labels reach the comment, never raw agent output. // Only known labels reach the comment, never raw agent output.
const listed = field(value, "failures"); const failures: unknown[] = Array.isArray(outcome["failures"]) ? outcome["failures"] : [];
const failures: unknown[] = Array.isArray(listed) ? listed : [];
return { return {
ok: false, ok: false,
failures: failures.flatMap((entry: unknown) => { failures: failures.flatMap((entry: unknown) => {
const type = field(entry, "type"); const { type, model, reason } = isObject(entry) ? entry : {};
const model = field(entry, "model");
const reason = field(entry, "reason");
return isProfileType(type) && typeof model === "string" && isFailureReason(reason) return isProfileType(type) && typeof model === "string" && isFailureReason(reason)
? [{ type, model, reason }] ? [{ type, model, reason }]
: []; : [];
}), }),
}; };
} }
const body = field(value, "body");
const reviewPath = field(value, "reviewPath");
const anchorsPath = field(value, "anchorsPath");
const profile = field(value, "profile");
if ( if (
ok !== true || outcome["ok"] !== true ||
typeof body !== "string" || typeof outcome["body"] !== "string" ||
typeof reviewPath !== "string" || typeof outcome["reviewPath"] !== "string" ||
typeof anchorsPath !== "string" || typeof outcome["anchorsPath"] !== "string" ||
!isObject(profile) !isObject(outcome["profile"])
) { ) {
throw new Error("invalid agent outcome"); throw new Error("invalid agent outcome");
} }
const type = field(profile, "type"); const profile = outcome["profile"];
const model = field(profile, "model"); if (!isProfileType(profile["type"]) || typeof profile["model"] !== "string") {
if (!isProfileType(type) || typeof model !== "string") {
throw new Error("invalid agent outcome"); throw new Error("invalid agent outcome");
} }
return { ok: true, body, reviewPath, anchorsPath, profile: { type, model } }; return {
ok: true,
body: outcome["body"],
reviewPath: outcome["reviewPath"],
anchorsPath: outcome["anchorsPath"],
profile: {
type: profile["type"],
model: profile["model"],
},
};
} }
async function readAgentArtifact( async function readAgentArtifact(
@@ -118,16 +113,12 @@ async function readAgentArtifact(
name: string, name: string,
): Promise<string | null> { ): Promise<string | null> {
const profile = manifest.profiles.find((entry) => join(entry.home, name) === path); const profile = manifest.profiles.find((entry) => join(entry.home, name) === path);
if (profile === undefined) { if (profile === undefined) throw new Error(`${name}: outside profile home`);
throw new Error(`${name}: outside profile home`);
}
let stat: Stats; let stat: Stats;
try { try {
stat = await lstat(path); stat = await lstat(path);
} catch (error) { } catch (error) {
if (isNotFound(error)) { if (isNotFound(error)) return null;
return null;
}
throw error; throw error;
} }
if ( if (
@@ -149,8 +140,7 @@ export async function postRuntime(
): Promise<void> { ): Promise<void> {
const manifest = await readRuntimeManifest(manifestPath); const manifest = await readRuntimeManifest(manifestPath);
try { try {
const reviewerText = await readFile(manifest.reviewerFile, "utf8"); const reviewerToken = (await readFile(manifest.reviewerFile, "utf8")).trim();
const reviewerToken = reviewerText.trim();
const request = async (path: string, body: unknown): Promise<void> => { const request = async (path: string, body: unknown): Promise<void> => {
let response: Response; let response: Response;
try { try {
@@ -198,7 +188,7 @@ export async function postRuntime(
} }
const [verdict = "", ...rest] = review.split("\n"); const [verdict = "", ...rest] = review.split("\n");
const [event, mark] = VERDICTS.get(verdict.trim()) ?? ["COMMENT", "💬"]; const [event, mark] = VERDICTS[verdict.trim()] ?? ["COMMENT", "💬"];
const anchorText = await readAgentArtifact(manifest, outcome.anchorsPath, "anchors.json"); const anchorText = await readAgentArtifact(manifest, outcome.anchorsPath, "anchors.json");
const anchors = anchorText === null ? [] : parseAnchors(anchorText, outcome.anchorsPath); const anchors = anchorText === null ? [] : parseAnchors(anchorText, outcome.anchorsPath);
const postReview = (entries: Anchor[]): Promise<void> => const postReview = (entries: Anchor[]): Promise<void> =>
@@ -215,26 +205,20 @@ export async function postRuntime(
})), })),
}); });
await postReview(anchors).catch(async (error: unknown) => { await postReview(anchors).catch(async (error: unknown) => {
if (anchors.length === 0) { if (anchors.length === 0) throw error;
throw error;
}
console.error( console.error(
`inline comments rejected: ${error instanceof Error ? error.message : String(error)}`, `inline comments rejected: ${error instanceof Error ? error.message : String(error)}`,
); );
await postReview([]); await postReview([]);
}); });
} catch (error) { } catch (error) {
if (error instanceof GiteaRequestError) { if (error instanceof GiteaRequestError) throw error;
throw error;
}
await postComment(failureComment([{ ...outcome.profile, reason: "failed" }])); await postComment(failureComment([{ ...outcome.profile, reason: "failed" }]));
throw error; throw error;
} }
} finally { } finally {
await rm(manifest.runtimeDir, { recursive: true }).catch((error: unknown) => { await rm(manifest.runtimeDir, { recursive: true }).catch((error: unknown) => {
if (!isNotFound(error)) { if (!isNotFound(error)) throw error;
throw error;
}
}); });
} }
} }
+1 -3
View File
@@ -5,9 +5,7 @@ import { prepareRuntime } from "#runtime";
const env = (name: string): string => { const env = (name: string): string => {
const value = process.env[name]; const value = process.env[name];
if (value === undefined || value === "") { if (value === undefined || value === "") throw new Error(`${name} is not set`);
throw new Error(`${name} is not set`);
}
return value; return value;
}; };
+6 -11
View File
@@ -25,14 +25,14 @@ function runAs(
selected: RuntimeProfile, selected: RuntimeProfile,
command: string, command: string,
args: string[], args: string[],
env?: ReadonlyMap<string, string>, env?: NodeJS.ProcessEnv,
): SpawnSyncReturns<string> { ): SpawnSyncReturns<string> {
return spawnSync(command, args, { return spawnSync(command, args, {
cwd: "/", cwd: "/",
uid: selected.uid, uid: selected.uid,
gid: selected.gid, gid: selected.gid,
encoding: "utf8", encoding: "utf8",
...(env !== undefined && { env: Object.fromEntries(env) }), ...(env !== undefined && { env }),
}); });
} }
@@ -96,9 +96,7 @@ test.skipIf(!IS_ROOT)("cleanup leaves no runnable daemonized process", async ()
await killProfileProcesses(selected.uid); await killProfileProcesses(selected.uid);
const status = await readFile(`/proc/${pid}/status`, "utf8").catch((error: unknown) => { const status = await readFile(`/proc/${pid}/status`, "utf8").catch((error: unknown) => {
if (isNotFound(error)) { if (isNotFound(error)) return null;
return null;
}
throw error; throw error;
}); });
expect(status === null || !isRunnableProfileProcess(status, selected.uid)).toBe(true); expect(status === null || !isRunnableProfileProcess(status, selected.uid)).toBe(true);
@@ -106,12 +104,9 @@ test.skipIf(!IS_ROOT)("cleanup leaves no runnable daemonized process", async ()
test.skipIf(!IS_ROOT)("the agent process cannot read its coordinator environment", () => { test.skipIf(!IS_ROOT)("the agent process cannot read its coordinator environment", () => {
const selected = profile(20_020, "/tmp"); const selected = profile(20_020, "/tmp");
const result = runAs( const result = runAs(selected, "/usr/bin/cat", [`/proc/${process.pid}/environ`], {
selected, PARENT_SECRET: "must-not-cross-boundary",
"/usr/bin/cat", });
[`/proc/${process.pid}/environ`],
new Map([["PARENT_SECRET", "must-not-cross-boundary"]]),
);
expect(result.status).not.toBe(0); expect(result.status).not.toBe(0);
}); });
+4 -8
View File
@@ -6,8 +6,8 @@ import { isNotFound } from "#common";
import type { RuntimeProfile } from "#runtime"; import type { RuntimeProfile } from "#runtime";
export function isRunnableProfileProcess(status: string, uid: number): boolean { export function isRunnableProfileProcess(status: string, uid: number): boolean {
const owner = /^Uid:\s+(?<uid>\d+)/mu.exec(status)?.[1]; const owner = /^Uid:\s+(\d+)/mu.exec(status)?.[1];
const state = /^State:\s+(?<state>\w)/mu.exec(status)?.[1]; const state = /^State:\s+(\w)/mu.exec(status)?.[1];
return owner !== undefined && Number(owner) === uid && state !== "Z"; return owner !== undefined && Number(owner) === uid && state !== "Z";
} }
@@ -33,16 +33,12 @@ export async function killProfileProcesses(uid: number, attempt = 0): Promise<vo
throw new Error(`profile UID ${uid} still owns processes after cleanup`); throw new Error(`profile UID ${uid} still owns processes after cleanup`);
} }
const ids = await profileProcessIds(uid); const ids = await profileProcessIds(uid);
if (ids.length === 0) { if (ids.length === 0) return;
return;
}
for (const pid of ids) { for (const pid of ids) {
try { try {
process.kill(pid, "SIGKILL"); process.kill(pid, "SIGKILL");
} catch (error) { } catch (error) {
if (!isNotFound(error)) { if (!isNotFound(error)) throw error;
throw error;
}
} }
} }
await sleep(10); await sleep(10);
+36 -49
View File
@@ -62,9 +62,7 @@ test("recognizes provider API exhaustion status", async () => {
{ type: "codex", model: "gpt-5.6-terra" }, { type: "codex", model: "gpt-5.6-terra" },
], ],
(profile) => { (profile) => {
if (profile.type === "claude") { if (profile.type === "claude") throw new Error(message);
throw new Error(message);
}
return Promise.resolve("fallback"); return Promise.resolve("fallback");
}, },
), ),
@@ -86,9 +84,7 @@ test("falls through after a sign-in failure and records each try", async () => {
if (profile.type === "codex") { if (profile.type === "codex") {
throw new AgentAuthError("codex sign-in failed"); throw new AgentAuthError("codex sign-in failed");
} }
if (profile.type === "claude") { if (profile.type === "claude") throw new Error("API Error: 429");
throw new Error("API Error: 429");
}
return Promise.resolve("fallback"); return Promise.resolve("fallback");
}, },
failures, failures,
@@ -120,8 +116,7 @@ test("throws the last sign-in failure when every profile fails", async () => {
), ),
).rejects.toThrow( ).rejects.toThrow(
expect.toSatisfy( expect.toSatisfy(
(error: unknown) => (e: unknown) => e instanceof AgentAuthError && e.message.includes("claude sign-in failed"),
error instanceof AgentAuthError && error.message.includes("claude sign-in failed"),
), ),
); );
expect(failures.map(({ reason }) => reason)).toStrictEqual(["sign-in failed", "sign-in failed"]); expect(failures.map(({ reason }) => reason)).toStrictEqual(["sign-in failed", "sign-in failed"]);
@@ -162,20 +157,20 @@ test("does not mistake incidental quota text for exhaustion", async () => {
}); });
test("exposes only the selected profile credential to the agent", () => { test("exposes only the selected profile credential to the agent", () => {
const base = new Map([ const base = {
["PATH", "/usr/bin"], PATH: "/usr/bin",
["HOME", "/home/bot"], HOME: "/home/bot",
["UNRELATED_SECRET", "must-not-reach-agent"], UNRELATED_SECRET: "must-not-reach-agent",
["BOT_AGENTS_MASTER_KEY", "master"], BOT_AGENTS_MASTER_KEY: "master",
["PROFILES", "contains every secret"], PROFILES: "contains every secret",
["REVIEWER_TOKEN", "reviewer"], REVIEWER_TOKEN: "reviewer",
["CLAUDE_CODE_OAUTH_TOKEN", "old-claude"], CLAUDE_CODE_OAUTH_TOKEN: "old-claude",
["ANTHROPIC_API_KEY", "old-anthropic-key"], ANTHROPIC_API_KEY: "old-anthropic-key",
["ANTHROPIC_AUTH_TOKEN", "old-anthropic-token"], ANTHROPIC_AUTH_TOKEN: "old-anthropic-token",
["OPENAI_API_KEY", "old-openai"], OPENAI_API_KEY: "old-openai",
["CODEX_API_KEY", "old-codex-key"], CODEX_API_KEY: "old-codex-key",
["CODEX_ACCESS_TOKEN", "old-codex-token"], CODEX_ACCESS_TOKEN: "old-codex-token",
]); };
const profile = { const profile = {
index: 0, index: 0,
type: "claude" as const, type: "claude" as const,
@@ -186,19 +181,15 @@ test("exposes only the selected profile credential to the agent", () => {
tokenFile: "/runtime/profile-0/token", tokenFile: "/runtime/profile-0/token",
}; };
expect(agentEnvironment(base, profile, "selected")).toStrictEqual( expect(agentEnvironment(base, profile, "selected")).toStrictEqual({
new Map([ PATH: "/usr/bin",
["PATH", "/usr/bin"], HOME: "/runtime/profile-0",
["HOME", "/runtime/profile-0"], CLAUDE_CODE_OAUTH_TOKEN: "selected",
["CLAUDE_CODE_OAUTH_TOKEN", "selected"], });
]), expect(sanitizedEnvironment(base)).toStrictEqual({
); PATH: "/usr/bin",
expect(sanitizedEnvironment(base)).toStrictEqual( HOME: "/home/bot",
new Map([ });
["PATH", "/usr/bin"],
["HOME", "/home/bot"],
]),
);
}); });
test("uses a private Codex home without inventing an API credential", () => { test("uses a private Codex home without inventing an API credential", () => {
@@ -212,13 +203,11 @@ test("uses a private Codex home without inventing an API credential", () => {
tokenFile: null, tokenFile: null,
}; };
expect(agentEnvironment(new Map([["PATH", "/bin"]]), profile)).toStrictEqual( expect(agentEnvironment({ PATH: "/bin" }, profile)).toStrictEqual({
new Map([ PATH: "/bin",
["PATH", "/bin"], HOME: "/runtime/profile-1",
["HOME", "/runtime/profile-1"], CODEX_HOME: "/runtime/profile-1/.codex",
["CODEX_HOME", "/runtime/profile-1/.codex"], });
]),
);
}); });
test("exposes an OpenRouter key only to the OpenCode profile", () => { test("exposes an OpenRouter key only to the OpenCode profile", () => {
@@ -232,11 +221,9 @@ test("exposes an OpenRouter key only to the OpenCode profile", () => {
tokenFile: "/runtime/profile-2/token", tokenFile: "/runtime/profile-2/token",
}; };
expect(agentEnvironment(new Map([["PATH", "/bin"]]), profile, "selected")).toStrictEqual( expect(agentEnvironment({ PATH: "/bin" }, profile, "selected")).toStrictEqual({
new Map([ PATH: "/bin",
["PATH", "/bin"], HOME: "/runtime/profile-2",
["HOME", "/runtime/profile-2"], OPENROUTER_API_KEY: "selected",
["OPENROUTER_API_KEY", "selected"], });
]),
);
}); });
+12 -26
View File
@@ -38,16 +38,12 @@ function isUsageExhausted(error: unknown): boolean {
} }
function failureReason(error: unknown): FailureReason { function failureReason(error: unknown): FailureReason {
if (error instanceof AgentAuthError) { if (error instanceof AgentAuthError) return "sign-in failed";
return "sign-in failed";
}
return isUsageExhausted(error) ? "usage exhausted" : "failed"; return isUsageExhausted(error) ? "usage exhausted" : "failed";
} }
export function failureFooter(failures: ProfileFailure[]): string { export function failureFooter(failures: ProfileFailure[]): string {
if (failures.length === 0) { if (failures.length === 0) return "> Profile: none";
return "> Profile: none";
}
return `> Tried: ${failures return `> Tried: ${failures
.map(({ type, model, reason }) => `\`${type}\` · \`${model}\` (${reason})`) .map(({ type, model, reason }) => `\`${type}\` · \`${model}\` (${reason})`)
.join(", ")}`; .join(", ")}`;
@@ -70,9 +66,7 @@ async function attemptFrom<T, P extends ProfileIdentity>(
} catch (error) { } catch (error) {
const reason = failureReason(error); const reason = failureReason(error);
failures.push({ type: profile.type, model: profile.model, reason }); failures.push({ type: profile.type, model: profile.model, reason });
if (reason === "failed" || index === profiles.length - 1) { if (reason === "failed" || index === profiles.length - 1) throw error;
throw error;
}
console.error(`${profile.type} ${reason}; trying next profile`); console.error(`${profile.type} ${reason}; trying next profile`);
return attemptFrom(profiles, attempt, failures, index + 1); return attemptFrom(profiles, attempt, failures, index + 1);
} }
@@ -86,12 +80,8 @@ export function runProfiles<T, P extends ProfileIdentity>(
return attemptFrom(profiles, attempt, failures, 0); return attemptFrom(profiles, attempt, failures, 0);
} }
// Environments are maps from variable name to value, converted to the object export function sanitizedEnvironment(environment: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
// form only where a child process is spawned. const result: NodeJS.ProcessEnv = {};
export function sanitizedEnvironment(
environment: ReadonlyMap<string, string>,
): Map<string, string> {
const result = new Map<string, string>();
for (const name of [ for (const name of [
"PATH", "PATH",
"HOME", "HOME",
@@ -118,31 +108,27 @@ export function sanitizedEnvironment(
"SSL_CERT_DIR", "SSL_CERT_DIR",
"NODE_EXTRA_CA_CERTS", "NODE_EXTRA_CA_CERTS",
]) { ]) {
const value = environment.get(name); const value = environment[name];
if (value !== undefined) { if (value !== undefined) result[name] = value;
result.set(name, value);
}
} }
return result; return result;
} }
export function agentEnvironment( export function agentEnvironment(
environment: ReadonlyMap<string, string>, environment: NodeJS.ProcessEnv,
profile: ProfileHome, profile: ProfileHome,
token?: string, token?: string,
): Map<string, string> { ): NodeJS.ProcessEnv {
const result = sanitizedEnvironment(environment); const result = sanitizedEnvironment(environment);
result.set("HOME", profile.home); result["HOME"] = profile.home;
if (profile.type === "codex") { if (profile.type === "codex") result["CODEX_HOME"] = `${profile.home}/.codex`;
result.set("CODEX_HOME", `${profile.home}/.codex`);
}
if (token !== undefined && token !== "") { if (token !== undefined && token !== "") {
const tokenName = { const tokenName = {
claude: "CLAUDE_CODE_OAUTH_TOKEN", claude: "CLAUDE_CODE_OAUTH_TOKEN",
codex: "OPENAI_API_KEY", codex: "OPENAI_API_KEY",
opencode: "OPENROUTER_API_KEY", opencode: "OPENROUTER_API_KEY",
}[profile.type]; }[profile.type];
result.set(tokenName, token); result[tokenName] = token;
} }
return result; return result;
} }
+49 -64
View File
@@ -24,7 +24,7 @@ import {
retryInvalidToken, retryInvalidToken,
stageCodexAuth, stageCodexAuth,
} from "#agents"; } from "#agents";
import { field, isObject } from "#common"; import { isObject } from "#common";
import { echo, exitCode, killProfileProcesses, readProfileFile } from "#processes"; import { echo, exitCode, killProfileProcesses, readProfileFile } from "#processes";
import { import {
AgentAuthError, AgentAuthError,
@@ -58,17 +58,15 @@ interface RenderedPrompt {
const env = (name: string): string => { const env = (name: string): string => {
const value = process.env[name]; const value = process.env[name];
if (value === undefined) { if (value === undefined) throw new Error(`${name} is not set`);
throw new Error(`${name} is not set`);
}
return value; return value;
}; };
function definedEnvironment(): Map<string, string> { function definedEnvironment(): NodeJS.ProcessEnv {
const result = new Map<string, string>(); const result: NodeJS.ProcessEnv = {};
for (const [name, value] of Object.entries(process.env)) { for (const [name, value] of Object.entries(process.env)) {
if (value !== undefined) { if (value !== undefined) {
result.set(name, value); result[name] = value;
} }
} }
return result; return result;
@@ -106,24 +104,17 @@ async function postAuthorComment(body: string): Promise<void> {
} }
async function runRoot(command: string, args: string[]): Promise<void> { async function runRoot(command: string, args: string[]): Promise<void> {
const code = await exitCode( const code = await exitCode(spawn(command, args, { env: PROCESS_ENV, stdio: "ignore" }));
spawn(command, args, { env: Object.fromEntries(PROCESS_ENV), stdio: "ignore" }), if (code !== 0) throw new Error(`${command} ${args[0]} exited with ${code}`);
);
if (code !== 0) {
throw new Error(`${command} ${args[0]} exited with ${code}`);
}
} }
async function configureGitAuthor(): Promise<void> { async function configureGitAuthor(): Promise<void> {
const userResponse = await gitea("user"); const user: unknown = await (await gitea("user")).json();
const user: unknown = await userResponse.json(); if (!isObject(user) || typeof user["login"] !== "string" || typeof user["email"] !== "string") {
const login = field(user, "login"); throw new Error("user: unexpected Gitea response");
const email = field(user, "email");
if (typeof login !== "string" || typeof email !== "string") {
throw new TypeError("user: unexpected Gitea response");
} }
await runRoot("git", ["config", "user.name", login]); await runRoot("git", ["config", "user.name", user["login"]]);
await runRoot("git", ["config", "user.email", email]); await runRoot("git", ["config", "user.email", user["email"]]);
} }
async function readProfileToken(profile: RuntimeProfile): Promise<string | null> { async function readProfileToken(profile: RuntimeProfile): Promise<string | null> {
@@ -139,15 +130,13 @@ async function runAgentCommand(
): Promise<void> { ): Promise<void> {
const child = spawn(command, args, { const child = spawn(command, args, {
cwd: WORKSPACE, cwd: WORKSPACE,
env: Object.fromEntries(agentEnvironment(PROCESS_ENV, profile, token)), env: agentEnvironment(PROCESS_ENV, profile, token),
uid: profile.uid, uid: profile.uid,
gid: profile.gid, gid: profile.gid,
stdio: "ignore", stdio: "ignore",
}); });
const code = await exitCode(child); const code = await exitCode(child);
if (code !== 0) { if (code !== 0) throw new Error(`${command} ${args[0]} exited with ${code}`);
throw new Error(`${command} ${args[0]} exited with ${code}`);
}
} }
async function prepareProfile(profile: RuntimeProfile): Promise<void> { async function prepareProfile(profile: RuntimeProfile): Promise<void> {
@@ -170,36 +159,36 @@ async function prepareProfile(profile: RuntimeProfile): Promise<void> {
// One issue comment as the prompt quotes it. // One issue comment as the prompt quotes it.
function formatComment(comment: unknown): string { function formatComment(comment: unknown): string {
const login = field(field(comment, "user"), "login"); const { user, created_at: createdAt, body } = isObject(comment) ? comment : {};
const createdAt = field(comment, "created_at"); const login = isObject(user) ? user["login"] : undefined;
const body = field(comment, "body");
return `## ${String(login)} at ${String(createdAt)}\n\n${String(body)}\n`; return `## ${String(login)} at ${String(createdAt)}\n\n${String(body)}\n`;
} }
async function renderPrompt(profile: RuntimeProfile): Promise<RenderedPrompt> { async function renderPrompt(profile: RuntimeProfile): Promise<RenderedPrompt> {
const reviewPath = await makeProfileFile(profile, "review.md"); const reviewPath = await makeProfileFile(profile, "review.md");
const anchorsPath = await makeProfileFile(profile, "anchors.json"); const anchorsPath = await makeProfileFile(profile, "anchors.json");
const commentsResponse = await gitea(`repos/${REPO}/issues/${INDEX}/comments?limit=100`); const comments: unknown = await (
const comments: unknown = await commentsResponse.json(); await gitea(`repos/${REPO}/issues/${INDEX}/comments?limit=100`)
).json();
if (!Array.isArray(comments)) { if (!Array.isArray(comments)) {
throw new TypeError("comments: unexpected Gitea response"); throw new TypeError("comments: unexpected Gitea response");
} }
const values = new Map<string, string>([ const values: NodeJS.ProcessEnv = {
["COMMENT", env("COMMENT")], COMMENT: env("COMMENT"),
["ISSUE_COMMENTS", comments.map((comment: unknown) => formatComment(comment)).join("\n")], ISSUE_COMMENTS: comments.map((comment: unknown) => formatComment(comment)).join("\n"),
["CODE_RULES", await gitea(RULES_PATH).then((response) => response.text())], CODE_RULES: await (await gitea(RULES_PATH)).text(),
["EVENT_NAME", EVENT], EVENT_NAME: EVENT,
["GITEA_API_URL", API], GITEA_API_URL: API,
["GITEA_REPOSITORY", REPO], GITEA_REPOSITORY: REPO,
["ISSUE_INDEX", INDEX], ISSUE_INDEX: INDEX,
["REVIEW_PATH", reviewPath], REVIEW_PATH: reviewPath,
["ANCHORS_PATH", anchorsPath], ANCHORS_PATH: anchorsPath,
]); };
const template = await readFile(new URL("../../prompt.md", import.meta.url), "utf8"); const template = await readFile(new URL("../../prompt.md", import.meta.url), "utf8");
return { return {
prompt: template.replaceAll( prompt: template.replaceAll(
/\$\{(?<name>\w+)\}/gu, /\$\{(\w+)\}/gu,
(match: string, name: string) => values.get(name) ?? match, (match: string, name: string) => values[name] ?? match,
), ),
reviewPath, reviewPath,
anchorsPath, anchorsPath,
@@ -221,7 +210,10 @@ async function runClaude(profile: RuntimeProfile, token: string, prompt: string)
], ],
{ {
cwd: WORKSPACE, cwd: WORKSPACE,
env: Object.fromEntries(agentEnvironment(PROCESS_ENV, profile, token).set("IS_SANDBOX", "1")), env: {
...agentEnvironment(PROCESS_ENV, profile, token),
IS_SANDBOX: "1",
},
uid: profile.uid, uid: profile.uid,
gid: profile.gid, gid: profile.gid,
stdio: ["ignore", "pipe", "pipe"], stdio: ["ignore", "pipe", "pipe"],
@@ -242,20 +234,17 @@ async function runClaude(profile: RuntimeProfile, token: string, prompt: string)
if (line !== "") { if (line !== "") {
const event: unknown = JSON.parse(line); const event: unknown = JSON.parse(line);
if (isObject(event)) { if (isObject(event)) {
const content = field(field(event, "message"), "content"); const content = isObject(event["message"]) ? event["message"]["content"] : undefined;
for (const part of Array.isArray(content) ? content : []) { for (const part of Array.isArray(content) ? content : []) {
if (isObject(part)) { if (isObject(part)) {
const text = field(part, "thinking") ?? field(part, "text") ?? field(part, "name"); const text = part["thinking"] ?? part["text"] ?? part["name"];
if (typeof text === "string" && text !== "") { if (typeof text === "string" && text !== "") {
console.log(text); console.log(text);
} }
} }
} }
if (field(event, "type") === "result") { if (event["type"] === "result") {
const isError = field(event, "is_error"); const { is_error: isError, result: answer, subtype, api_error_status: apiStatus } = event;
const answer = field(event, "result");
const subtype = field(event, "subtype");
const apiStatus = field(event, "api_error_status");
result = { result = {
isError: typeof isError === "boolean" ? isError : undefined, isError: typeof isError === "boolean" ? isError : undefined,
result: typeof answer === "string" ? answer : undefined, result: typeof answer === "string" ? answer : undefined,
@@ -300,11 +289,11 @@ async function pollForInstructions(
async function codexDeviceLogin( async function codexDeviceLogin(
profile: RuntimeProfile, profile: RuntimeProfile,
environment: ReadonlyMap<string, string>, environment: NodeJS.ProcessEnv,
): Promise<void> { ): Promise<void> {
const login = spawn("codex", ["login", "--device-auth"], { const login = spawn("codex", ["login", "--device-auth"], {
cwd: WORKSPACE, cwd: WORKSPACE,
env: Object.fromEntries(environment), env: environment,
uid: profile.uid, uid: profile.uid,
gid: profile.gid, gid: profile.gid,
stdio: ["ignore", "pipe", "pipe"], stdio: ["ignore", "pipe", "pipe"],
@@ -329,12 +318,12 @@ async function codexDeviceLogin(
async function codexApiLogin( async function codexApiLogin(
profile: RuntimeProfile, profile: RuntimeProfile,
environment: ReadonlyMap<string, string>, environment: NodeJS.ProcessEnv,
token: string, token: string,
): Promise<void> { ): Promise<void> {
const login = spawn("codex", ["login", "--with-api-key"], { const login = spawn("codex", ["login", "--with-api-key"], {
cwd: WORKSPACE, cwd: WORKSPACE,
env: Object.fromEntries(environment), env: environment,
uid: profile.uid, uid: profile.uid,
gid: profile.gid, gid: profile.gid,
stdio: ["pipe", "inherit", "pipe"], stdio: ["pipe", "inherit", "pipe"],
@@ -368,14 +357,12 @@ async function runCodex(
} else { } else {
const check = spawn("codex", ["login", "status"], { const check = spawn("codex", ["login", "status"], {
cwd: WORKSPACE, cwd: WORKSPACE,
env: Object.fromEntries(environment), env: environment,
uid: profile.uid, uid: profile.uid,
gid: profile.gid, gid: profile.gid,
stdio: "ignore", stdio: "ignore",
}); });
if ((await exitCode(check)) !== 0) { if ((await exitCode(check)) !== 0) await codexDeviceLogin(profile, environment);
await codexDeviceLogin(profile, environment);
}
} }
const outputPath = await makeProfileFile(profile, "result.md"); const outputPath = await makeProfileFile(profile, "result.md");
const attempt = async (): Promise<CommandResult> => { const attempt = async (): Promise<CommandResult> => {
@@ -392,7 +379,7 @@ async function runCodex(
], ],
{ {
cwd: WORKSPACE, cwd: WORKSPACE,
env: Object.fromEntries(environment), env: environment,
uid: profile.uid, uid: profile.uid,
gid: profile.gid, gid: profile.gid,
stdio: ["ignore", "inherit", "pipe"], stdio: ["ignore", "inherit", "pipe"],
@@ -433,7 +420,7 @@ async function runOpenCode(
): Promise<string> { ): Promise<string> {
const child = spawn("opencode", openCodeArgs(profile.model, prompt), { const child = spawn("opencode", openCodeArgs(profile.model, prompt), {
cwd: WORKSPACE, cwd: WORKSPACE,
env: Object.fromEntries(agentEnvironment(PROCESS_ENV, profile, token)), env: agentEnvironment(PROCESS_ENV, profile, token),
uid: profile.uid, uid: profile.uid,
gid: profile.gid, gid: profile.gid,
stdio: ["ignore", "pipe", "pipe"], stdio: ["ignore", "pipe", "pipe"],
@@ -486,9 +473,7 @@ async function runProfile(profile: RuntimeProfile): Promise<AttemptResult> {
await persistCodexAuth(stagedCodexAuth, CODEX_AUTH); await persistCodexAuth(stagedCodexAuth, CODEX_AUTH);
} }
} }
if (resultPath !== null) { if (resultPath !== null) body = await readProfileFile(profile, resultPath);
body = await readProfileFile(profile, resultPath);
}
if (body === null || reviewPath === null || anchorsPath === null) { if (body === null || reviewPath === null || anchorsPath === null) {
throw new Error("agent attempt produced no result"); throw new Error("agent attempt produced no result");
} }
+1 -1
View File
@@ -4,7 +4,7 @@ import { decryptCredential, encryptCredential, parseCredentials } from "./creden
const MASTER_KEY = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"; const MASTER_KEY = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8";
const OTHER_KEY = "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE"; const OTHER_KEY = "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE";
const NONCE = Uint8Array.from({ length: 12 }, (_value, index) => index + 32); const NONCE = Uint8Array.from({ length: 12 }, (_, index) => index + 32);
const ENCRYPTED = "v1:ICEiIyQlJicoKSor:oV_FAgnsN3p1FyegJxwGVdyjfyPio6qDeSUwbA"; const ENCRYPTED = "v1:ICEiIyQlJicoKSor:oV_FAgnsN3p1FyegJxwGVdyjfyPio6qDeSUwbA";
test("decrypts a known AES-256-GCM credential", async () => { test("decrypts a known AES-256-GCM credential", async () => {
+5 -12
View File
@@ -1,6 +1,6 @@
import { webcrypto } from "node:crypto"; import { webcrypto } from "node:crypto";
import { field, isMapping } from "#common"; import { isMapping } from "#common";
import type { BotProfile } from "#profiles"; import type { BotProfile } from "#profiles";
interface DefaultModels { interface DefaultModels {
@@ -47,9 +47,7 @@ export async function decryptCredential(encrypted: string, masterKey: string): P
throw new Error("credential must use v1:<nonce>:<ciphertext>"); throw new Error("credential must use v1:<nonce>:<ciphertext>");
} }
const nonce = decodeBase64Url(encodedNonce); const nonce = decodeBase64Url(encodedNonce);
if (nonce.length !== 12) { if (nonce.length !== 12) throw new Error("credential nonce must be 12 bytes");
throw new Error("credential nonce must be 12 bytes");
}
const plaintext = await webcrypto.subtle.decrypt( const plaintext = await webcrypto.subtle.decrypt(
{ name: "AES-GCM", iv: buffer(nonce) }, { name: "AES-GCM", iv: buffer(nonce) },
await importMasterKey(masterKey, "decrypt"), await importMasterKey(masterKey, "decrypt"),
@@ -63,9 +61,7 @@ export async function encryptCredential(
masterKey: string, masterKey: string,
nonce: Uint8Array = webcrypto.getRandomValues(new Uint8Array(12)), nonce: Uint8Array = webcrypto.getRandomValues(new Uint8Array(12)),
): Promise<string> { ): Promise<string> {
if (nonce.length !== 12) { if (nonce.length !== 12) throw new Error("AES-GCM nonce must be 12 bytes");
throw new Error("AES-GCM nonce must be 12 bytes");
}
const ciphertext = await webcrypto.subtle.encrypt( const ciphertext = await webcrypto.subtle.encrypt(
{ name: "AES-GCM", iv: buffer(nonce) }, { name: "AES-GCM", iv: buffer(nonce) },
await importMasterKey(masterKey, "encrypt"), await importMasterKey(masterKey, "encrypt"),
@@ -84,9 +80,7 @@ async function parseProfile(entry: unknown, index: number, masterKey: string): P
throw new Error(`${at}.${key}: unknown field`); throw new Error(`${at}.${key}: unknown field`);
} }
} }
const type = field(entry, "type"); const { type, model, token } = entry;
const model = field(entry, "model");
const token = field(entry, "token");
if (type !== "claude" && type !== "codex" && type !== "opencode") { if (type !== "claude" && type !== "codex" && type !== "opencode") {
throw new Error(`${at}.type: expected "claude", "codex", or "opencode"`); throw new Error(`${at}.type: expected "claude", "codex", or "opencode"`);
} }
@@ -118,8 +112,7 @@ export async function parseCredentials(text: string, masterKey: string): Promise
throw new Error(`${key}: unknown field`); throw new Error(`${key}: unknown field`);
} }
} }
const reviewerToken = field(value, "reviewer-token"); const { "reviewer-token": reviewerToken, profiles } = value;
const profiles = field(value, "profiles");
if (typeof reviewerToken !== "string") { if (typeof reviewerToken !== "string") {
throw new TypeError("reviewer-token: expected an encrypted credential"); throw new TypeError("reviewer-token: expected an encrypted credential");
} }
+7 -8
View File
@@ -49,8 +49,7 @@ test.skipIf(!IS_ROOT)("prepares root-only reviewer and isolated profile credenti
assert(claude.tokenFile !== null); assert(claude.tokenFile !== null);
expect(await readFile(claude.tokenFile, "utf8")).toBe("secret-token"); expect(await readFile(claude.tokenFile, "utf8")).toBe("secret-token");
await expectPrivate(claude.tokenFile, claude.uid, 0o600); await expectPrivate(claude.tokenFile, claude.uid, 0o600);
const codexHome = await stat(codex.home); expect((await stat(codex.home)).uid).toStrictEqual(codex.uid);
expect(codexHome.uid).toStrictEqual(codex.uid);
expect(codex.tokenFile).toBe(null); expect(codex.tokenFile).toBe(null);
const ownToken = spawnSync("/bin/cat", [claude.tokenFile], { const ownToken = spawnSync("/bin/cat", [claude.tokenFile], {
@@ -84,12 +83,12 @@ test.skipIf(!IS_ROOT)("removes prepared credentials when output publication fail
process.execPath, process.execPath,
[fileURLToPath(new URL("../prepare/index.ts", import.meta.url))], [fileURLToPath(new URL("../prepare/index.ts", import.meta.url))],
{ {
env: Object.fromEntries([ env: {
["ACTION_PATH", action], ACTION_PATH: action,
["RUNNER_TEMP", root], RUNNER_TEMP: root,
["BOT_AGENTS_MASTER_KEY", MASTER_KEY], BOT_AGENTS_MASTER_KEY: MASTER_KEY,
["GITHUB_OUTPUT", action], GITHUB_OUTPUT: action,
]), },
}, },
); );
+6 -6
View File
@@ -1,7 +1,7 @@
import { chmod, chown, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { chmod, chown, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path"; import { join } from "node:path";
import { field, isMapping } from "#common"; import { isMapping } from "#common";
import type { ProfileFailure, ProfileIdentity } from "#profiles"; import type { ProfileFailure, ProfileIdentity } from "#profiles";
import { parseCredentials } from "./credentials.ts"; import { parseCredentials } from "./credentials.ts";
@@ -107,11 +107,11 @@ export async function prepareRuntime(
function isRuntimeManifest(value: unknown): value is RuntimeManifest { function isRuntimeManifest(value: unknown): value is RuntimeManifest {
return ( return (
isMapping(value) && isMapping(value) &&
typeof field(value, "runtimeDir") === "string" && typeof value["runtimeDir"] === "string" &&
typeof field(value, "manifestPath") === "string" && typeof value["manifestPath"] === "string" &&
typeof field(value, "reviewerFile") === "string" && typeof value["reviewerFile"] === "string" &&
typeof field(value, "outcomeFile") === "string" && typeof value["outcomeFile"] === "string" &&
Array.isArray(field(value, "profiles")) Array.isArray(value["profiles"])
); );
} }
+4 -18
View File
@@ -1,5 +1,5 @@
// Test support: the current user's IDs, a fresh temporary directory, the // Test support: the current user's IDs, a fresh temporary directory, and a
// inherited environment, and a plain command runner. It imports no source module, so the repository-level // plain command runner. It imports no source module, so the repository-level
// tests in tests/, which reach src/ only through `#testing`, never touch // tests in tests/, which reach src/ only through `#testing`, never touch
// internals. // internals.
import { spawn } from "node:child_process"; import { spawn } from "node:child_process";
@@ -33,28 +33,14 @@ export interface CommandResult {
stderr: string; stderr: string;
} }
// This process's environment as a map from variable name to value.
export function inheritedEnvironment(): Map<string, string> {
const result = new Map<string, string>();
for (const [name, value] of Object.entries(process.env)) {
if (value !== undefined) {
result.set(name, value);
}
}
return result;
}
// Runs a command with stdin closed and only the given environment, and // Runs a command with stdin closed and only the given environment, and
// collects its stderr. // collects its stderr.
export async function runCommand( export async function runCommand(
command: string, command: string,
args: string[], args: string[],
env: ReadonlyMap<string, string>, env: NodeJS.ProcessEnv,
): Promise<CommandResult> { ): Promise<CommandResult> {
const child = spawn(command, args, { const child = spawn(command, args, { env, stdio: ["ignore", "ignore", "pipe"] });
env: Object.fromEntries(env),
stdio: ["ignore", "ignore", "pipe"],
});
const [stderr, closed] = await Promise.all([text(child.stderr), once(child, "close")]); const [stderr, closed] = await Promise.all([text(child.stderr), once(child, "close")]);
const exitCode: unknown = closed[0]; const exitCode: unknown = closed[0];
return { success: exitCode === 0, stderr }; return { success: exitCode === 0, stderr };
+1 -5
View File
@@ -15,11 +15,7 @@ const PHASES: [phase: string, firstVariable: string][] = [
test.each(PHASES)("Node loads the %s phase", async (phase, firstVariable) => { test.each(PHASES)("Node loads the %s phase", async (phase, firstVariable) => {
const path = fileURLToPath(new URL(`../src/${phase}/index.ts`, import.meta.url)); const path = fileURLToPath(new URL(`../src/${phase}/index.ts`, import.meta.url));
const result = await runCommand( const result = await runCommand(process.execPath, [path], { PATH: process.env["PATH"] ?? "" });
process.execPath,
[path],
new Map([["PATH", process.env["PATH"] ?? ""]]),
);
expect(result.success).toBe(false); expect(result.success).toBe(false);
expect(result.stderr).toContain(`${firstVariable} is not set`); expect(result.stderr).toContain(`${firstVariable} is not set`);
}); });
+45 -51
View File
@@ -3,22 +3,24 @@ import process from "node:process";
import { assert, expect, test } from "vite-plus/test"; import { assert, expect, test } from "vite-plus/test";
import { parse } from "yaml"; import { parse } from "yaml";
import { inheritedEnvironment, makeTempDir, runCommand } from "#testing"; import { makeTempDir, runCommand } from "#testing";
// A parsed YAML or JSON mapping, keyed by its dynamic field names. type JsonObject = NodeJS.Dict<unknown>;
type Mapping = Map<string, unknown>;
const mapping = (value: unknown, at: string): Mapping => { const isMapping = (value: unknown): value is JsonObject =>
assert(typeof value === "object" && value !== null && !Array.isArray(value), at); typeof value === "object" && value !== null && !Array.isArray(value);
return new Map(Object.entries(value));
const mapping = (value: unknown, at: string): JsonObject => {
assert(isMapping(value), at);
return value;
}; };
const sequence = (value: unknown, at: string): Mapping[] => { const sequence = (value: unknown, at: string): JsonObject[] => {
assert(Array.isArray(value), at); assert(Array.isArray(value), at);
return value.map((entry: unknown, index) => mapping(entry, `${at}[${index}]`)); return value.map((entry: unknown, index) => mapping(entry, `${at}[${index}]`));
}; };
async function yaml(path: string): Promise<Mapping> { async function yaml(path: string): Promise<JsonObject> {
const value: unknown = parse(await readFile(path, "utf8")); const value: unknown = parse(await readFile(path, "utf8"));
return mapping(value, path); return mapping(value, path);
} }
@@ -31,8 +33,8 @@ async function yamlFiles(): Promise<string[]> {
.filter((path) => !/^(?:\.git|\.superpowers|node_modules)\//u.test(path)); .filter((path) => !/^(?:\.git|\.superpowers|node_modules)\//u.test(path));
} }
const findStep = (steps: Mapping[], key: string, value: string): Mapping => { const findStep = (steps: JsonObject[], key: string, value: string): JsonObject => {
const step = steps.find((entry) => entry.get(key) === value); const step = steps.find((entry) => entry[key] === value);
assert(step !== undefined, `${key}: ${value}`); assert(step !== undefined, `${key}: ${value}`);
return step; return step;
}; };
@@ -45,12 +47,11 @@ test("all committed YAML parses", async () => {
test("the action exposes only the master key and scopes it to preparation", async () => { test("the action exposes only the master key and scopes it to preparation", async () => {
const action = await yaml("action.yml"); const action = await yaml("action.yml");
expect([...mapping(action.get("inputs"), "inputs").keys()]).toStrictEqual(["master-key"]); expect(Object.keys(mapping(action["inputs"], "inputs"))).toStrictEqual(["master-key"]);
const steps = sequence(mapping(action.get("runs"), "runs").get("steps"), "runs.steps"); const steps = sequence(mapping(action["runs"], "runs")["steps"], "runs.steps");
for (const step of steps) { for (const step of steps) {
const run = step.get("run"); if (typeof step["run"] === "string") {
if (typeof run === "string") { expect(step["run"].includes("\n"), String(step["name"])).toBe(false);
expect(run.includes("\n"), String(step.get("name"))).toBe(false);
} }
} }
const checkout = findStep(steps, "uses", "actions/checkout@v4"); const checkout = findStep(steps, "uses", "actions/checkout@v4");
@@ -58,16 +59,16 @@ test("the action exposes only the master key and scopes it to preparation", asyn
const agent = findStep(steps, "id", "agent"); const agent = findStep(steps, "id", "agent");
const post = findStep(steps, "id", "post"); const post = findStep(steps, "id", "post");
findStep(steps, "id", "source"); findStep(steps, "id", "source");
expect(mapping(checkout.get("with"), "checkout.with").get("token")).toBe("${{ gitea.token }}"); expect(mapping(checkout["with"], "checkout.with")["token"]).toBe("${{ gitea.token }}");
expect(mapping(prepare.get("env"), "prepare.env").get("BOT_AGENTS_MASTER_KEY")).toBe( expect(mapping(prepare["env"], "prepare.env")["BOT_AGENTS_MASTER_KEY"]).toBe(
"${{ inputs.master-key }}", "${{ inputs.master-key }}",
); );
expect(JSON.stringify(Object.fromEntries(agent)).includes("BOT_AGENTS_MASTER_KEY")).toBe(false); expect(JSON.stringify(agent).includes("BOT_AGENTS_MASTER_KEY")).toBe(false);
expect(JSON.stringify(Object.fromEntries(post)).includes("BOT_AGENTS_MASTER_KEY")).toBe(false); expect(JSON.stringify(post).includes("BOT_AGENTS_MASTER_KEY")).toBe(false);
expect(mapping(agent.get("env"), "agent.env").get("GITEA_TOKEN")).toBe("${{ gitea.token }}"); expect(mapping(agent["env"], "agent.env")["GITEA_TOKEN"]).toBe("${{ gitea.token }}");
assert(String(post.get("if")).includes("always()")); assert(String(post["if"]).includes("always()"));
for (const step of [prepare, agent, post]) { for (const step of [prepare, agent, post]) {
assert(String(step.get("run")).includes("steps.source.outputs.path")); assert(String(step["run"]).includes("steps.source.outputs.path"));
} }
}); });
@@ -75,15 +76,15 @@ test("the source protection script stages immutable action files", async () => {
const temp = await makeTempDir(); const temp = await makeTempDir();
const outputFile = `${temp}/output`; const outputFile = `${temp}/output`;
try { try {
const environment = inheritedEnvironment(); const result = await runCommand("/bin/bash", ["scripts/protect-source.sh"], {
environment.set("ACTION_PATH", process.cwd()); ...process.env,
environment.set("GITHUB_OUTPUT", outputFile); ACTION_PATH: process.cwd(),
environment.set("RUNNER_TEMP", temp); GITHUB_OUTPUT: outputFile,
const result = await runCommand("/bin/bash", ["scripts/protect-source.sh"], environment); RUNNER_TEMP: temp,
});
assert(result.success, result.stderr); assert(result.success, result.stderr);
const output = await readFile(outputFile, "utf8"); const path = (await readFile(outputFile, "utf8")).trim().slice(5);
const path = output.trim().slice(5);
const files = [ const files = [
"src/prepare/index.ts", "src/prepare/index.ts",
"src/run/index.ts", "src/run/index.ts",
@@ -107,7 +108,7 @@ test("the source protection script stages immutable action files", async () => {
test("module-relative runtime assets exist", async () => { test("module-relative runtime assets exist", async () => {
const module = new URL("../src/run/index.ts", import.meta.url); const module = new URL("../src/run/index.ts", import.meta.url);
const source = await readFile(module, "utf8"); const source = await readFile(module, "utf8");
const assets = [...source.matchAll(/new URL\("(?<asset>[^"]+)", import\.meta\.url\)/gu)].map( const assets = [...source.matchAll(/new URL\("([^"]+)", import\.meta\.url\)/gu)].map(
([, asset = ""]) => new URL(asset, module), ([, asset = ""]) => new URL(asset, module),
); );
const stats = await Promise.all(assets.map((asset) => stat(asset))); const stats = await Promise.all(assets.map((asset) => stat(asset)));
@@ -118,30 +119,27 @@ test("module-relative runtime assets exist", async () => {
test("the repository uses its trusted main action", async () => { test("the repository uses its trusted main action", async () => {
const workflow = await yaml(".gitea/workflows/agents.yml"); const workflow = await yaml(".gitea/workflows/agents.yml");
const job = mapping(mapping(workflow.get("jobs"), "jobs").get("agent"), "jobs.agent"); const job = mapping(mapping(workflow["jobs"], "jobs")["agent"], "jobs.agent");
const permissions = mapping(job.get("permissions"), "jobs.agent.permissions"); const permissions = mapping(job["permissions"], "jobs.agent.permissions");
expect(Object.fromEntries(permissions)).toStrictEqual({ expect(permissions).toStrictEqual({
code: "write", code: "write",
issues: "write", issues: "write",
"pull-requests": "write", "pull-requests": "write",
}); });
const steps = sequence(job.get("steps"), "jobs.agent.steps"); const steps = sequence(job["steps"], "jobs.agent.steps");
expect(steps.findIndex((step) => step.get("uses") === "./")).toStrictEqual(-1); expect(steps.findIndex((step) => step["uses"] === "./")).toStrictEqual(-1);
const trusted = findStep(steps, "uses", "https://git.capsulizers.com/commons/bot-agents@main"); const trusted = findStep(steps, "uses", "https://git.capsulizers.com/commons/bot-agents@main");
expect(mapping(trusted.get("with"), "trusted.with").get("master-key")).toBe( expect(mapping(trusted["with"], "trusted.with")["master-key"]).toBe(
"${{ secrets.BOT_AGENTS_MASTER_KEY }}", "${{ secrets.BOT_AGENTS_MASTER_KEY }}",
); );
expect(JSON.stringify(Object.fromEntries(workflow)).includes("gitea.actor != 'bot'")).toBe(true); expect(JSON.stringify(workflow).includes("gitea.actor != 'bot'")).toBe(true);
}); });
test("CI checks every phase and the root isolation suite", async () => { test("CI checks every phase and the root isolation suite", async () => {
const workflow = await yaml(".gitea/workflows/check.yml"); const workflow = await yaml(".gitea/workflows/check.yml");
const job = mapping(mapping(workflow.get("jobs"), "jobs").get("check"), "jobs.check"); const job = mapping(mapping(workflow["jobs"], "jobs")["check"], "jobs.check");
const commands = sequence(job.get("steps"), "jobs.check.steps") const commands = sequence(job["steps"], "jobs.check.steps")
.map((step) => { .map((step) => (typeof step["run"] === "string" ? step["run"] : ""))
const run = step.get("run");
return typeof run === "string" ? run : "";
})
.join("\n"); .join("\n");
// `vp check` type-checks every phase, and `vp test` runs each of them under // `vp check` type-checks every phase, and `vp test` runs each of them under
// Node as well as the root-only isolation tests. // Node as well as the root-only isolation tests.
@@ -178,12 +176,8 @@ test("profile preparation does not receive provider credentials", async () => {
test("central profiles fall back from Codex to Claude to OpenCode", async () => { test("central profiles fall back from Codex to Claude to OpenCode", async () => {
const credentials: unknown = JSON.parse(await readFile("profiles.json", "utf8")); const credentials: unknown = JSON.parse(await readFile("profiles.json", "utf8"));
const profiles = sequence(mapping(credentials, "profiles.json").get("profiles"), "profiles"); const profiles = sequence(mapping(credentials, "profiles.json")["profiles"], "profiles");
expect(profiles.map((profile) => profile.get("type"))).toStrictEqual([ expect(profiles.map((profile) => profile["type"])).toStrictEqual(["codex", "claude", "opencode"]);
"codex", expect(profiles[2]?.["model"]).toBe("openrouter/qwen/qwen3.8-27b");
"claude", assert(String(profiles[2]?.["token"]).startsWith("v1:"));
"opencode",
]);
expect(profiles[2]?.get("model")).toBe("openrouter/qwen/qwen3.8-27b");
assert(String(profiles[2]?.get("token")).startsWith("v1:"));
}); });
+5 -12
View File
@@ -2,7 +2,7 @@ import explicitTypes from "eslint-plugin-explicit-types";
import importStructure from "eslint-plugin-import-structure"; import importStructure from "eslint-plugin-import-structure";
import { defineConfig } from "vite-plus"; import { defineConfig } from "vite-plus";
import projectLint, { projectOverrides } from "./scripts/project-lint.ts"; import projectLint from "./scripts/project-lint.ts";
export default defineConfig({ export default defineConfig({
lint: { lint: {
@@ -12,20 +12,13 @@ export default defineConfig({
"eslint-plugin-import-structure", "eslint-plugin-import-structure",
"./scripts/project-lint.ts", "./scripts/project-lint.ts",
], ],
categories: { categories: { correctness: "error", suspicious: "error", pedantic: "error", perf: "error" },
correctness: "error",
suspicious: "error",
pedantic: "error",
perf: "error",
style: "error",
restriction: "error",
},
rules: { rules: {
...explicitTypes.configs.all.rules, ...explicitTypes.configs.concrete.rules,
...importStructure.configs.all.rules, ...explicitTypes.configs.absence.rules,
...importStructure.configs.modules.rules,
...projectLint.configs.project.rules, ...projectLint.configs.project.rules,
}, },
overrides: projectOverrides,
options: { options: {
typeAware: true, typeAware: true,
typeCheck: true, typeCheck: true,