11 Commits

Author SHA1 Message Date
Danny Kim 8b9aedf911 Record the 2026-10-19 lint decisions and the UPPER_SNAKE value rule in the agent notes
Check / check (pull_request) Successful in 40s
2026-10-19 19:49:24 +09:00
Danny Kim a0dce6a4c2 Port the hugoalh rules, prefer-ascii and no-nan into the project lint plugin 2026-10-19 19:48:42 +09:00
Danny Kim c783935936 Turn on upper-snake-string-unions and convert profile types, failure reasons and anchor sides at their boundaries 2026-10-19 19:46:31 +09:00
Danny Kim 71150900ff Turn on custom-error-definition and name the custom errors 2026-10-19 19:45:02 +09:00
Danny Kim d879b04e46 Turn on promise-function-async and init-declarations and satisfy them with async functions and null-initialized lets 2026-10-19 19:44:35 +09:00
Danny Kim a65bf353ab Turn off no-await-in-loop, consistent-return and switch-exhaustiveness-check, turn on no-array-reduce, and restore the plain loops 2026-10-19 19:41:06 +09:00
Danny Kim bd1ddb9406 Update eslint-plugin-explicit-types to 0.7.0 2026-10-19 19:41:06 +09:00
Danny Kim f2de92067f Export the whole overrides array from project-lint and document the lint config
Check / check (pull_request) Successful in 1m28s
2026-10-19 16:49:57 +09:00
Danny Kim df66bea5e4 Enable each lint plugin through its all config and share the Node code override
Check / check (pull_request) Successful in 42s
2026-10-19 14:20:24 +09:00
Danny Kim d09806daad Lint with every Oxlint category and list only the offs and options
Check / check (pull_request) Successful in 51s
2026-10-19 11:26:48 +09:00
Danny Kim c8ffb9cc6f Replace NodeJS dict aliases with maps and named field reads
Agents / agent (pull_request) Has been skipped
Check / check (pull_request) Successful in 49s
2026-10-19 02:30:54 +09:00
29 changed files with 465 additions and 1016 deletions
-19
View File
@@ -79,24 +79,5 @@ overrides: projectOverrides,
`project/prefer-ascii` in `projectOverrides`: posted Gitea text shows emoji
verdict marks and a middle dot.
## Rule decisions (2026-10-20, all repos)
- `unicorn/number-literal-case` is off: Oxfmt lowercases hex digits back.
- `typescript/consistent-return` is off too: it misfires on complete
switches, like `consistent-return`.
- On with defaults, no offs: `prefer-object-spread`, `unicorn/prefer-spread`,
`unicorn/no-useless-spread`, `typescript/no-misused-spread`, `no-plusplus`
(`x += 1`), `unicorn/no-array-method-this-argument`,
`typescript/method-signature-style` ("property"),
`typescript/unified-signatures`.
- `unicorn/import-style` uses its default: `import nodePath from "node:path"`
and `nodePath.join(...)` (`nodePath`, since `path` is a common variable).
- `no-template-curly-in-string` is on; only `tests/workflow.test.ts`, which
checks literal Gitea `${{ }}` expressions, is exempt in `projectOverrides`.
- Rule defaults are preferred over option tweaks unless a tweak is needed.
- `fmt` matches `deno fmt`: `printWidth: 80`, `quoteProps: "preserve"`,
`embeddedLanguageFormatting: "off"`. `max-lines-per-function` is 124 after
the narrower width.
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]].
+8 -16
View File
@@ -9,8 +9,8 @@
"@eslint/core": "^0.17.0",
"@types/node": "^24.19.2",
"@typescript-eslint/types": "^8.71.2",
"eslint-plugin-explicit-types": "^0.7.2",
"eslint-plugin-import-structure": "^0.12.0",
"eslint-plugin-explicit-types": "^0.7.0",
"eslint-plugin-import-structure": "^0.10.2",
"vite-plus": "^1.2.0",
"yaml": "^2.9.1"
}
@@ -1890,9 +1890,9 @@
"license": "MIT"
},
"node_modules/eslint-plugin-explicit-types": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/eslint-plugin-explicit-types/-/eslint-plugin-explicit-types-0.7.2.tgz",
"integrity": "sha512-ffHVVuyBH2esZwwRItcz2sDnL5xvSRDAoLjSqmQbevT6ETcjtfThtLoWoc+cv5pvtxa6YiXEK1P2D+x/yUBc1g==",
"version": "0.7.0",
"resolved": "https://registry.npmjs.org/eslint-plugin-explicit-types/-/eslint-plugin-explicit-types-0.7.0.tgz",
"integrity": "sha512-TCX40NrxEKH+zXhIPvuY6e9dWjhHfAlEbkNlcyvhY7fUFG+sSIt3VMT0C/U2QGFbtVhDnV1xE7JkOlGGXzPcZQ==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -1903,9 +1903,9 @@
}
},
"node_modules/eslint-plugin-import-structure": {
"version": "0.12.0",
"resolved": "https://registry.npmjs.org/eslint-plugin-import-structure/-/eslint-plugin-import-structure-0.12.0.tgz",
"integrity": "sha512-axo8TH0mik9NmsnW+J5rNwNXlOxxqOhULwN7zE4EJaNRdk/Ci/aRac3BAeeIi/SDUyPgN6Ig34l+mFlLQYWkfw==",
"version": "0.10.2",
"resolved": "https://registry.npmjs.org/eslint-plugin-import-structure/-/eslint-plugin-import-structure-0.10.2.tgz",
"integrity": "sha512-jvx4sccxEdURGXrDtBJZtCHiKqELkHRVlLrMU5bVZIjglN0U464Joopcfn6JvmNB2zyIh2FkolaJQJaKkvy6Xw==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -1913,14 +1913,6 @@
},
"engines": {
"node": ">=22.18"
},
"peerDependencies": {
"eslint": ">=9"
},
"peerDependenciesMeta": {
"eslint": {
"optional": true
}
}
},
"node_modules/estree-walker": {
+2 -2
View File
@@ -18,8 +18,8 @@
"@eslint/core": "^0.17.0",
"@types/node": "^24.19.2",
"@typescript-eslint/types": "^8.71.2",
"eslint-plugin-explicit-types": "^0.7.2",
"eslint-plugin-import-structure": "^0.12.0",
"eslint-plugin-explicit-types": "^0.7.0",
"eslint-plugin-import-structure": "^0.10.2",
"vite-plus": "^1.2.0",
"yaml": "^2.9.1"
}
+4 -4
View File
@@ -1,15 +1,15 @@
{
"reviewer-token": "v1:XFUvCI9PnXVaW-ig:_3S9BvXywUp29cVYGA_EzFScKwC5oHkV9x2Ld8k-V_uiG7iA8n3fmjXCArzh2Lz-JDgy3IMTHoY",
"profiles": [
{
"type": "CODEX",
"model": "gpt-5.6-terra"
},
{
"type": "CLAUDE",
"model": "claude-sonnet-5",
"token": "v1:-dyfF6ZicEhjPk4C:WCuMaGd09tYjtzUCl7abloRzPITvP5C35WpR372w3O_tcaD-ls-yV5sJBdU8iIVApZVCC98sY2gOyM3o9RMa8ciJq8Fuys7KxlYOp8QiluL9AYMSQi6rEsSH71EPWnxSACgo3uDQY8bWQpUlEZvXH9O-ZN9A58dh6b3vRg"
},
{
"type": "CODEX",
"model": "gpt-5.6-terra"
},
{
"type": "OPENCODE",
"model": "openrouter/qwen/qwen3.8-27b",
+47 -139
View File
@@ -62,18 +62,13 @@ const noDisableCommentsRule: ProjectRule = {
type: "problem",
docs: { description: "Disallow lint disable and enable comments" },
schema: [],
messages: {
directive: "Lint disable comments are not allowed; fix the source.",
},
messages: { directive: "Lint disable comments are not allowed; fix the source." },
},
create(context) {
return {
Program(_node: TSESTree.Program): void {
for (const comment of context.sourceCode.getAllComments()) {
if (
DIRECTIVE_PATTERN.test(comment.value) &&
!comment.value.includes(RULE_NAME)
) {
if (DIRECTIVE_PATTERN.test(comment.value) && !comment.value.includes(RULE_NAME)) {
context.report({ loc: comment.loc, messageId: "directive" });
}
}
@@ -95,8 +90,7 @@ const preferAsciiRule: ProjectRule = {
docs: { description: "Require the source to be ASCII" },
schema: [],
messages: {
nonAscii:
"Non-ASCII character '{{character}}' (U+{{codePoint}}) is not allowed.",
nonAscii: "Non-ASCII character '{{character}}' (U+{{codePoint}}) is not allowed.",
},
},
create(context) {
@@ -113,13 +107,7 @@ const preferAsciiRule: ProjectRule = {
end: sourceCode.getLocFromIndex(index + character.length),
},
messageId: "nonAscii",
data: {
character,
codePoint: codePoint
.toString(16)
.toUpperCase()
.padStart(4, "0"),
},
data: { character, codePoint: codePoint.toString(16).toUpperCase().padStart(4, "0") },
});
}
index += character.length;
@@ -135,10 +123,7 @@ const noDuplicateTypeofsRule: ProjectRule = {
type: "problem",
docs: { description: "Disallow `typeof` applied twice in a row" },
schema: [],
messages: {
doubled:
'Multiple `typeof`s always return `"string"`, possibly not intended.',
},
messages: { doubled: 'Multiple `typeof`s always return `"string"`, possibly not intended.' },
},
create(context) {
return {
@@ -161,9 +146,7 @@ const noEmptyYieldRule: ProjectRule = {
type: "problem",
docs: { description: "Disallow `yield` without an expression" },
schema: [],
messages: {
empty: "Empty `yield` is not allowed, possibly missing the expression.",
},
messages: { empty: "Empty `yield` is not allowed, possibly missing the expression." },
},
create(context) {
return {
@@ -177,21 +160,14 @@ const noEmptyYieldRule: ProjectRule = {
};
/** The globals `no-nan` sees through, as in `globalThis.Number.NaN`. */
const GLOBAL_NAMES: ReadonlySet<string> = new Set<string>([
"globalThis",
"self",
"window",
]);
const GLOBAL_NAMES: ReadonlySet<string> = new Set<string>(["globalThis", "self", "window"]);
/** The name a member expression's property spells, computed or not. */
function propertyName(node: TSESTree.MemberExpression): string | null {
if (node.property.type === AST_NODE_TYPES.Identifier && !node.computed) {
return node.property.name;
}
if (
node.property.type === AST_NODE_TYPES.Literal &&
typeof node.property.value === "string"
) {
if (node.property.type === AST_NODE_TYPES.Literal && typeof node.property.value === "string") {
return node.property.value;
}
return null;
@@ -235,17 +211,12 @@ const noNanRule: ProjectRule = {
type: "problem",
docs: { description: "Disallow `NaN` as a value" },
schema: [],
messages: {
nan: "Using `NaN` as a value is usually an error and not intended.",
},
messages: { nan: "Using `NaN` as a value is usually an error and not intended." },
},
create(context) {
return {
Identifier(node: TSESTree.Identifier): void {
if (
node.name === "NaN" &&
node.parent.type !== AST_NODE_TYPES.MemberExpression
) {
if (node.name === "NaN" && node.parent.type !== AST_NODE_TYPES.MemberExpression) {
context.report({ node, messageId: "nan" });
}
},
@@ -262,9 +233,7 @@ const noNanRule: ProjectRule = {
const noUnsafeNumberRule: ProjectRule = {
meta: {
type: "problem",
docs: {
description: "Disallow number literals outside the safe integer range",
},
docs: { description: "Disallow number literals outside the safe integer range" },
schema: [],
messages: {
unsafe:
@@ -276,8 +245,7 @@ const noUnsafeNumberRule: ProjectRule = {
Literal(node: TSESTree.Literal): void {
if (
typeof node.value === "number" &&
(node.value < Number.MIN_SAFE_INTEGER ||
node.value > Number.MAX_SAFE_INTEGER)
(node.value < Number.MIN_SAFE_INTEGER || node.value > Number.MAX_SAFE_INTEGER)
) {
context.report({ node, messageId: "unsafe" });
}
@@ -307,15 +275,11 @@ interface TrailingContinue {
function trailingContinue(node: LoopStatement): TrailingContinue | null {
if (node.body.type === AST_NODE_TYPES.BlockStatement) {
const last = node.body.body.at(-1);
return last?.type === AST_NODE_TYPES.ContinueStatement &&
last.label === null
return last?.type === AST_NODE_TYPES.ContinueStatement && last.label === null
? { statement: last, removable: true }
: null;
}
if (
node.body.type === AST_NODE_TYPES.ContinueStatement &&
node.body.label === null
) {
if (node.body.type === AST_NODE_TYPES.ContinueStatement && node.body.label === null) {
return { statement: node.body, removable: false };
}
return null;
@@ -329,14 +293,11 @@ function trailingContinue(node: LoopStatement): TrailingContinue | null {
const noUselessContinueRule: ProjectRule = {
meta: {
type: "suggestion",
docs: {
description: "Disallow an unlabeled `continue` at the end of a loop",
},
docs: { description: "Disallow an unlabeled `continue` at the end of a loop" },
fixable: "code",
schema: [],
messages: {
useless:
"The statement `continue` at the end of the loop and without a label is useless.",
useless: "The statement `continue` at the end of the loop and without a label is useless.",
},
},
create(context) {
@@ -411,8 +372,7 @@ function serialize(value: unknown): string {
if (typeof value !== "object" || value === null) {
return JSON.stringify(value) ?? "undefined";
}
const unordered: boolean =
"type" in value && UNORDERED_TYPES.has(String(value.type));
const unordered: boolean = "type" in value && UNORDERED_TYPES.has(String(value.type));
const parts: string[] = Object.entries(value)
.filter(([key]: [string, unknown]) => !POSITION_KEYS.has(key))
.map(([key, child]: [string, unknown]) => {
@@ -436,9 +396,7 @@ function declarationsOf<T extends TSESTree.Node>(
const found: T[] = [];
for (const statement of statements) {
const declaration: TSESTree.Node | null =
statement.type === AST_NODE_TYPES.ExportNamedDeclaration
? statement.declaration
: statement;
statement.type === AST_NODE_TYPES.ExportNamedDeclaration ? statement.declaration : statement;
if (declaration !== null && matches(declaration)) {
found.push(declaration);
}
@@ -447,16 +405,12 @@ function declarationsOf<T extends TSESTree.Node>(
}
/** Whether a node is an interface declaration. */
function isInterface(
node: TSESTree.Node,
): node is TSESTree.TSInterfaceDeclaration {
function isInterface(node: TSESTree.Node): node is TSESTree.TSInterfaceDeclaration {
return node.type === AST_NODE_TYPES.TSInterfaceDeclaration;
}
/** Whether a node is a type alias declaration. */
function isTypeAlias(
node: TSESTree.Node,
): node is TSESTree.TSTypeAliasDeclaration {
function isTypeAlias(node: TSESTree.Node): node is TSESTree.TSTypeAliasDeclaration {
return node.type === AST_NODE_TYPES.TSTypeAliasDeclaration;
}
@@ -488,33 +442,21 @@ function typeAliasShape(node: TSESTree.TSTypeAliasDeclaration): string {
const noDuplicateInterfacesRule: ProjectRule = {
meta: {
type: "suggestion",
docs: {
description:
"Disallow interfaces with the same name or shape in one block",
},
docs: { description: "Disallow interfaces with the same name or shape in one block" },
schema: [],
messages: {
sameShape:
"Found multiple interfaces with the same shape, possibly mergeable.",
sameName:
"Found multiple interfaces named '{{name}}', possibly not intended.",
sameShape: "Found multiple interfaces with the same shape, possibly mergeable.",
sameName: "Found multiple interfaces named '{{name}}', possibly not intended.",
},
},
create(context) {
function check(statements: TSESTree.Node[]): void {
const nodes: TSESTree.TSInterfaceDeclaration[] = declarationsOf(
statements,
isInterface,
);
const nodes: TSESTree.TSInterfaceDeclaration[] = declarationsOf(statements, isInterface);
for (const node of duplicateGroups(nodes, interfaceShape).flat()) {
context.report({ node, messageId: "sameShape" });
}
for (const node of duplicateGroups(nodes, interfaceName).flat()) {
context.report({
node,
messageId: "sameName",
data: { name: node.id.name },
});
context.report({ node, messageId: "sameName", data: { name: node.id.name } });
}
}
return {
@@ -532,21 +474,13 @@ const noDuplicateInterfacesRule: ProjectRule = {
const noDuplicateTypesRule: ProjectRule = {
meta: {
type: "suggestion",
docs: {
description: "Disallow type aliases with the same type in one block",
},
docs: { description: "Disallow type aliases with the same type in one block" },
schema: [],
messages: {
sameShape:
"Found multiple types with the same shape, possibly mergeable.",
},
messages: { sameShape: "Found multiple types with the same shape, possibly mergeable." },
},
create(context) {
function check(statements: TSESTree.Node[]): void {
const nodes: TSESTree.TSTypeAliasDeclaration[] = declarationsOf(
statements,
isTypeAlias,
);
const nodes: TSESTree.TSTypeAliasDeclaration[] = declarationsOf(statements, isTypeAlias);
for (const node of duplicateGroups(nodes, typeAliasShape).flat()) {
context.report({ node, messageId: "sameShape" });
}
@@ -582,15 +516,12 @@ const noModifierPrivateRule: ProjectRule = {
type: "suggestion",
docs: { description: "Disallow the private modifier" },
schema: [],
messages: {
private: "Use a # private name instead of the private modifier.",
},
messages: { private: "Use a # private name instead of the private modifier." },
},
create(context) {
function check(node: AccessibilityCarrier): void {
const isConstructor: boolean =
node.type === AST_NODE_TYPES.MethodDefinition &&
node.kind === "constructor";
node.type === AST_NODE_TYPES.MethodDefinition && node.kind === "constructor";
if (node.accessibility === "private" && !isConstructor) {
context.report({ node, messageId: "private" });
}
@@ -649,12 +580,7 @@ const PATH_SPECIFIER_PATTERN: RegExp = /^[./#]/u;
* `.mts`, or `.mjs` package subpaths. `.cts`, `.cjs`, `.tsx`, and `.jsx` are
* not among them.
*/
const SCRIPT_EXTENSIONS: ReadonlySet<string> = new Set([
".ts",
".js",
".mts",
".mjs",
]);
const SCRIPT_EXTENSIONS: ReadonlySet<string> = new Set([".ts", ".js", ".mts", ".mjs"]);
/**
* Whether `source` names an asset rather than a script module: a query string
@@ -674,11 +600,7 @@ function isAssetSource(source: string): boolean {
}
}
const lastSegment: string = segments.at(-1) ?? "";
if (
lastSegment === "." ||
lastSegment === ".." ||
!lastSegment.includes(".")
) {
if (lastSegment === "." || lastSegment === ".." || !lastSegment.includes(".")) {
return false;
}
const extension: string = lastSegment.slice(lastSegment.lastIndexOf("."));
@@ -699,10 +621,7 @@ function isAssetSource(source: string): boolean {
const noAssetImportsRule: ProjectRule = {
meta: {
type: "problem",
docs: {
description:
"Disallow importing assets instead of .ts, .js, .mts, or .mjs modules",
},
docs: { description: "Disallow importing assets instead of .ts, .js, .mts, or .mjs modules" },
schema: [],
messages: {
extension: "Only .ts, .js, .mts and .mjs modules may be imported.",
@@ -734,10 +653,7 @@ const noAssetImportsRule: ProjectRule = {
ExportNamedDeclaration: checkDeclaration,
ExportAllDeclaration: checkDeclaration,
ImportExpression(node: TSESTree.ImportExpression): void {
if (
node.source.type === AST_NODE_TYPES.Literal &&
typeof node.source.value === "string"
) {
if (node.source.type === AST_NODE_TYPES.Literal && typeof node.source.value === "string") {
checkSource(node.source);
}
if (node.options !== null) {
@@ -760,12 +676,7 @@ const rules: DummyRuleMap = {
"id-match": [
"error",
"^_*[^_]*_*$|^[^a-z]*$",
{
properties: false,
classFields: false,
onlyDeclarations: false,
ignoreDestructuring: true,
},
{ properties: false, classFields: false, onlyDeclarations: false, ignoreDestructuring: true },
],
// On Node, these come from an explicit `node:` import instead of the global scope.
"no-restricted-globals": [
@@ -783,14 +694,12 @@ const rules: DummyRuleMap = {
"one-var": ["error", "never"],
"no-use-before-define": ["error", { functions: false }],
"func-style": ["error", "declaration", { allowArrowFunctions: true }],
"unicorn/import-style": ["error", { styles: { "node:path": { named: true } } }],
// Each limit is the smallest value the current code passes.
complexity: ["error", 26],
"max-depth": ["error", 6],
"max-lines": [
"error",
{ max: 2048, skipBlankLines: false, skipComments: false },
],
"max-lines-per-function": ["error", 124],
"max-lines": ["error", { max: 2048, skipBlankLines: false, skipComments: false }],
"max-lines-per-function": ["error", 98],
"max-params": ["error", 4],
"max-statements": ["error", 32],
"import/max-dependencies": ["error", { max: 13 }],
@@ -848,8 +757,8 @@ const rules: DummyRuleMap = {
"import/no-named-export": "off",
// Collides with `typescript/consistent-type-imports`.
"import/consistent-type-specifier-style": "off",
// Collides with Oxfmt, which lowercases hex digits back.
"unicorn/number-literal-case": "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",
@@ -861,11 +770,9 @@ const rules: DummyRuleMap = {
"no-await-in-loop": "off",
// Not type-aware; TypeScript's `noImplicitReturns` covers it.
"consistent-return": "off",
// Misfires on complete switches, like `consistent-return`; TypeScript covers it.
"typescript/consistent-return": "off",
// TypeScript's type checking covers exhaustive switches.
"typescript/switch-exhaustiveness-check": "off",
// TypeScript checks completeness; a forced `default:` hides missing cases.
// A `default` on a switch over a union would hide a new member from TS.
"default-case": "off",
// Off, too much churn:
// Literal numbers read better than a constant per use.
@@ -898,6 +805,12 @@ const rules: DummyRuleMap = {
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",
};
/**
@@ -926,11 +839,6 @@ export const projectOverrides: OxlintOverride[] = [
],
rules: { "project/prefer-ascii": "off" },
},
// The workflow test checks literal Gitea Actions `${{ }}` expressions.
{
files: ["tests/workflow.test.ts"],
rules: { "no-template-curly-in-string": "off" },
},
];
/**
+45 -74
View File
@@ -1,11 +1,4 @@
import {
mkdir,
readFile,
rm,
stat,
symlink,
writeFile,
} from "node:fs/promises";
import { mkdir, readFile, rm, stat, symlink, writeFile } from "node:fs/promises";
import { expect, test } from "vite-plus/test";
import { currentGid, currentUid, IS_WINDOWS, makeTempDir } from "#testing";
@@ -26,10 +19,7 @@ test("retries once after an invalid refresh token", async () => {
async () => {
const resolved = await Promise.resolve({
code: 1,
error:
(attempts += 1) === 1
? "ERROR: invalid_refresh_token"
: "still failed",
error: (attempts += 1) === 1 ? "ERROR: invalid_refresh_token" : "still failed",
});
return resolved;
},
@@ -121,19 +111,15 @@ test("recognizes a rejected Claude OAuth token", () => {
expect(
isClaudeAuthFailure({
apiErrorStatus: 401,
result:
"Failed to authenticate. API Error: 401 OAuth access token is invalid.",
result: "Failed to authenticate. API Error: 401 OAuth access token is invalid.",
}),
).toBe(true);
expect(
isClaudeAuthFailure({
result:
"OAuth token has expired. Please obtain a new token or refresh your existing token.",
result: "OAuth token has expired. Please obtain a new token or refresh your existing token.",
}),
).toBe(true);
expect(
isClaudeAuthFailure({ apiErrorStatus: 429, result: "API Error: 429" }),
).toBe(false);
expect(isClaudeAuthFailure({ apiErrorStatus: 429, result: "API Error: 429" })).toBe(false);
});
test("selects API-key login only for a configured Codex token", () => {
@@ -152,62 +138,47 @@ const AUTH_TOKENS = {
};
const AUTH = JSON.stringify({ auth_mode: "chatgpt", tokens: AUTH_TOKENS });
test.skipIf(IS_WINDOWS)(
"stages and persists only a regular private Codex login",
async () => {
const root = await makeTempDir();
try {
const canonical = `${root}/persistent/auth.json`;
await mkdir(`${root}/persistent`);
await writeFile(canonical, AUTH, { mode: 0o600 });
const home = `${root}/profile`;
await mkdir(home);
test.skipIf(IS_WINDOWS)("stages and persists only a regular private Codex login", async () => {
const root = await makeTempDir();
try {
const canonical = `${root}/persistent/auth.json`;
await mkdir(`${root}/persistent`);
await writeFile(canonical, AUTH, { mode: 0o600 });
const home = `${root}/profile`;
await mkdir(home);
const staged = await stageCodexAuth(
canonical,
home,
currentUid(),
currentGid(),
);
expect(await readFile(staged, "utf8")).toStrictEqual(AUTH);
const stagedStat = await stat(staged);
expect(stagedStat.mode & 0o777).toBe(0o600);
const staged = await stageCodexAuth(canonical, home, currentUid(), currentGid());
expect(await readFile(staged, "utf8")).toStrictEqual(AUTH);
const stagedStat = await stat(staged);
expect(stagedStat.mode & 0o777).toBe(0o600);
const refreshed = JSON.stringify({
auth_mode: "chatgpt",
tokens: { ...AUTH_TOKENS, access_token: "refreshed" },
});
await writeFile(staged, refreshed);
await persistCodexAuth(staged, canonical);
expect(await readFile(canonical, "utf8")).toStrictEqual(refreshed);
const canonicalStat = await stat(canonical);
expect(canonicalStat.mode & 0o777).toBe(0o600);
} finally {
await rm(root, { recursive: true });
}
},
);
const refreshed = JSON.stringify({
auth_mode: "chatgpt",
tokens: { ...AUTH_TOKENS, access_token: "refreshed" },
});
await writeFile(staged, refreshed);
await persistCodexAuth(staged, canonical);
expect(await readFile(canonical, "utf8")).toStrictEqual(refreshed);
const canonicalStat = await stat(canonical);
expect(canonicalStat.mode & 0o777).toBe(0o600);
} finally {
await rm(root, { recursive: true });
}
});
test.skipIf(IS_WINDOWS)(
"rejects a symlink or malformed Codex login",
async () => {
const root = await makeTempDir();
try {
const canonical = `${root}/auth.json`;
const malformed = `${root}/malformed.json`;
const linked = `${root}/linked.json`;
await writeFile(canonical, AUTH, { mode: 0o600 });
await writeFile(malformed, '{"tokens":{}}', { mode: 0o600 });
await symlink(canonical, linked);
test.skipIf(IS_WINDOWS)("rejects a symlink or malformed Codex login", async () => {
const root = await makeTempDir();
try {
const canonical = `${root}/auth.json`;
const malformed = `${root}/malformed.json`;
const linked = `${root}/linked.json`;
await writeFile(canonical, AUTH, { mode: 0o600 });
await writeFile(malformed, '{"tokens":{}}', { mode: 0o600 });
await symlink(canonical, linked);
await expect(persistCodexAuth(linked, canonical)).rejects.toThrow(
"regular file",
);
await expect(persistCodexAuth(malformed, canonical)).rejects.toThrow(
"invalid Codex login",
);
} finally {
await rm(root, { recursive: true });
}
},
);
await expect(persistCodexAuth(linked, canonical)).rejects.toThrow("regular file");
await expect(persistCodexAuth(malformed, canonical)).rejects.toThrow("invalid Codex login");
} finally {
await rm(root, { recursive: true });
}
});
+12 -21
View File
@@ -10,7 +10,7 @@ import {
rm,
writeFile,
} from "node:fs/promises";
import nodePath from "node:path";
import { dirname, join } from "node:path";
import { field, isNotFound, isObject } from "#common";
@@ -26,9 +26,7 @@ interface CodexPersistent {
export type CodexAuthentication = CodexApiKey | CodexPersistent;
export function codexAuthentication(token?: string): CodexAuthentication {
return token === undefined
? { kind: "persistent" }
: { kind: "api-key", token };
return token === undefined ? { kind: "persistent" } : { kind: "api-key", token };
}
// Codex logs revoked, expired, or reused ChatGPT sign-ins and rejected API keys
@@ -97,12 +95,10 @@ async function readCodexAuth(path: string): Promise<string> {
typeof authMode !== "string" ||
authMode === "" ||
!isObject(tokens) ||
!["access_token", "refresh_token", "id_token", "account_id"].every(
(name) => {
const token = field(tokens, name);
return typeof token === "string" && token !== "";
},
)
!["access_token", "refresh_token", "id_token", "account_id"].every((name) => {
const token = field(tokens, name);
return typeof token === "string" && token !== "";
})
) {
throw new Error("invalid Codex login");
}
@@ -115,15 +111,13 @@ export async function stageCodexAuth(
uid: number,
gid: number,
): Promise<string> {
const codexHome = nodePath.join(profileHome, ".codex");
const codexHome = join(profileHome, ".codex");
await mkdir(codexHome, { recursive: true, mode: 0o700 });
await chmod(codexHome, 0o700);
await chown(codexHome, uid, gid);
const stagedPath = nodePath.join(codexHome, "auth.json");
const stagedPath = join(codexHome, "auth.json");
try {
await writeFile(stagedPath, await readCodexAuth(canonicalPath), {
mode: 0o600,
});
await writeFile(stagedPath, await readCodexAuth(canonicalPath), { mode: 0o600 });
await chmod(stagedPath, 0o600);
await chown(stagedPath, uid, gid);
} catch (error) {
@@ -136,18 +130,15 @@ export async function stageCodexAuth(
// Creates an empty private file under a fresh name.
async function makeTempFile(directory: string): Promise<string> {
const path = nodePath.join(directory, `.tmp-${randomUUID()}`);
const path = join(directory, `.tmp-${randomUUID()}`);
const handle = await open(path, "wx", 0o600);
await handle.close();
return path;
}
export async function persistCodexAuth(
stagedPath: string,
canonicalPath: string,
): Promise<void> {
export async function persistCodexAuth(stagedPath: string, canonicalPath: string): Promise<void> {
const text = await readCodexAuth(stagedPath);
const directory = nodePath.dirname(canonicalPath);
const directory = dirname(canonicalPath);
await mkdir(directory, { recursive: true, mode: 0o700 });
const temporary = await makeTempFile(directory);
try {
+1 -5
View File
@@ -8,11 +8,7 @@ export {
retryInvalidToken,
stageCodexAuth,
} from "./auth.ts";
export type {
ClaudeFailureFields,
CodexAuthentication,
CommandResult,
} from "./auth.ts";
export type { ClaudeFailureFields, CodexAuthentication, CommandResult } from "./auth.ts";
export {
collectOpenCodeOutput,
openCodeArgs,
+6 -13
View File
@@ -10,9 +10,7 @@ import {
} from "./opencode.ts";
test("builds a non-interactive auto-approved OpenCode command", () => {
expect(
openCodeArgs("openrouter/qwen/qwen3.8-27b", "Review this"),
).toStrictEqual([
expect(openCodeArgs("openrouter/qwen/qwen3.8-27b", "Review this")).toStrictEqual([
"run",
"--format",
"json",
@@ -72,10 +70,7 @@ test("streams OpenCode output while collecting it", async () => {
},
);
expect(result).toStrictEqual({
stdout: "first\nsecond\n",
stderr: "warning\n",
});
expect(result).toStrictEqual({ stdout: "first\nsecond\n", stderr: "warning\n" });
expect(shown).toStrictEqual(["out:first\n", "err:warning\n", "out:second\n"]);
});
@@ -99,14 +94,12 @@ test("reports a rejected OpenRouter key as a sign-in failure", () => {
assert.instanceOf(error, AgentAuthError);
expect(error.message).toBe("opencode sign-in failed");
assert.instanceOf(error.cause, Error);
expect(error.cause.message).toBe(
"opencode APIError (API error 401): User not found.",
);
expect(error.cause.message).toBe("opencode APIError (API error 401): User not found.");
});
test("surfaces an OpenCode error event instead of empty output", () => {
expect(() =>
parseOpenCodeEvents(openRouterError(429, "Rate limit exceeded")),
).toThrow("API error 429");
expect(() => parseOpenCodeEvents(openRouterError(429, "Rate limit exceeded"))).toThrow(
"API error 429",
);
expect(openCodeError('{"type":"text","part":{"text":"ok"}}')).toBeNull();
});
+1 -3
View File
@@ -96,9 +96,7 @@ export function parseOpenCodeEvents(output: string): string {
}
}
if (result === null) {
throw (
openCodeError(output) ?? new Error("OpenCode produced no text output")
);
throw openCodeError(output) ?? new Error("OpenCode produced no text output");
}
return result;
}
+1 -3
View File
@@ -3,9 +3,7 @@ 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"}}',
);
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();
+36 -47
View File
@@ -145,11 +145,9 @@ test("posts a successful issue result and removes runtime credentials", async ()
expect(requests.length).toBe(1);
const [request] = requests;
expect(request?.url).toStrictEqual(
`${context.apiUrl}/repos/owner/repo/issues/7/comments`,
);
expect(request?.url).toStrictEqual(`${context.apiUrl}/repos/owner/repo/issues/7/comments`);
expect(requestBody(request?.init)).toStrictEqual({
body: "done\n\n> Profile: `codex` · `gpt-test`",
body: "done\n\n> Profile: `CODEX` · `gpt-test`",
});
expect(request?.init?.headers).toStrictEqual({
Authorization: "token reviewer-secret",
@@ -159,11 +157,9 @@ test("posts a successful issue result and removes runtime credentials", async ()
});
test("retries a rejected inline review without anchors", async () => {
const result = await fixture(
{ ok: true, body: "ignored final response" },
"Approved\nReady",
[{ path: "run.ts", line: 1, side: "NEW", body: "Finding" }],
);
const result = await fixture({ ok: true, body: "ignored final response" }, "Approved\nReady", [
{ path: "run.ts", line: 1, side: "NEW", body: "Finding" },
]);
const bodies: unknown[] = [];
await postRuntime(
@@ -182,11 +178,11 @@ test("retries a rejected inline review without anchors", async () => {
);
expect(bodies[0]).toMatchObject({
comments: [{ body: "Finding\n\n> Profile: `codex` · `gpt-test`" }],
comments: [{ body: "Finding\n\n> Profile: `CODEX` · `gpt-test`" }],
});
expect(bodies[1]).toMatchObject({
comments: [],
body: "✅ Approved\nReady\n\n> Profile: `codex` · `gpt-test`",
body: "✅ Approved\nReady\n\n> Profile: `CODEX` · `gpt-test`",
});
assert(await missing(result.runtimeDir));
});
@@ -202,16 +198,16 @@ test("reports each tried profile and keeps the action failed", async () => {
});
const bodies: unknown[] = [];
await expect(
postRuntime(result.manifestPath, context, recordingFetch(bodies)),
).rejects.toThrow("agent phase failed");
await expect(postRuntime(result.manifestPath, context, recordingFetch(bodies))).rejects.toThrow(
"agent phase failed",
);
expect(bodies).toStrictEqual([
{
body:
"AI bot failed.\n\n> Tried: `codex` · `gpt-test` (sign-in failed), " +
"`claude` · `claude-test` (usage exhausted), " +
"`opencode` · `openrouter/test` (failed)",
"AI bot failed.\n\n> Tried: `CODEX` · `gpt-test` (sign-in failed), " +
"`CLAUDE` · `claude-test` (usage exhausted), " +
"`OPENCODE` · `openrouter/test` (failed)",
},
]);
assert(!JSON.stringify(bodies).includes("reviewer-secret"));
@@ -233,13 +229,13 @@ test("drops failure entries that are not known labels", async () => {
);
const bodies: unknown[] = [];
await expect(
postRuntime(result.manifestPath, context, recordingFetch(bodies)),
).rejects.toThrow("agent phase failed");
await expect(postRuntime(result.manifestPath, context, recordingFetch(bodies))).rejects.toThrow(
"agent phase failed",
);
expect(bodies).toStrictEqual([
{
body: "AI bot failed.\n\n> Tried: `claude` · `claude-test` (sign-in failed)",
body: "AI bot failed.\n\n> Tried: `CLAUDE` · `claude-test` (sign-in failed)",
},
]);
});
@@ -249,9 +245,9 @@ test("reports a generic failure when the runner wrote no outcome", async () => {
await rm(result.outcomeFile);
const bodies: unknown[] = [];
await expect(
postRuntime(result.manifestPath, context, recordingFetch(bodies)),
).rejects.toThrow("agent phase failed");
await expect(postRuntime(result.manifestPath, context, recordingFetch(bodies))).rejects.toThrow(
"agent phase failed",
);
expect(bodies).toStrictEqual([{ body: "AI bot failed.\n\n> Profile: none" }]);
assert(await missing(result.runtimeDir));
@@ -262,9 +258,7 @@ test("removes runtime credentials when posting fails", async () => {
await expect(
postRuntime(result.manifestPath, context, async () => {
const resolved = await Promise.resolve(
new Response("failed", { status: 500 }),
);
const resolved = await Promise.resolve(new Response("failed", { status: 500 }));
return resolved;
}),
).rejects.toThrow("500");
@@ -287,27 +281,22 @@ test("preserves a Gitea transport failure without retrying a comment", async ()
assert(await missing(result.runtimeDir));
});
test.skipIf(IS_WINDOWS)(
"refuses to follow an agent artifact symlink",
async () => {
const result = await fixture({ ok: true, body: "done" });
await symlink(result.reviewerFile, result.reviewPath);
let requests = 0;
test.skipIf(IS_WINDOWS)("refuses to follow an agent artifact symlink", async () => {
const result = await fixture({ ok: true, body: "done" });
await symlink(result.reviewerFile, result.reviewPath);
let requests = 0;
await expect(
postRuntime(result.manifestPath, context, async () => {
requests += 1;
const resolved = await Promise.resolve(
new Response(null, { status: 200 }),
);
return resolved;
}),
).rejects.toThrow("regular private file");
await expect(
postRuntime(result.manifestPath, context, async () => {
requests += 1;
const resolved = await Promise.resolve(new Response(null, { status: 200 }));
return resolved;
}),
).rejects.toThrow("regular private file");
expect(requests).toBe(1);
assert(await missing(result.runtimeDir));
},
);
expect(requests).toBe(1);
assert(await missing(result.runtimeDir));
});
test("reports an attributed failure when a pull request review is missing", async () => {
const result = await fixture({ ok: true, body: "done" });
@@ -326,7 +315,7 @@ test("reports an attributed failure when a pull request review is missing", asyn
expect(bodies).toStrictEqual([
{
body: "AI bot failed.\n\n> Tried: `codex` · `gpt-test` (failed)",
body: "AI bot failed.\n\n> Tried: `CODEX` · `gpt-test` (failed)",
},
]);
assert(await missing(result.runtimeDir));
+34 -85
View File
@@ -1,19 +1,10 @@
import type { Stats } from "node:fs";
import { lstat, readFile, rm } from "node:fs/promises";
import nodePath from "node:path";
import { join } from "node:path";
import { field, isNotFound, isObject } from "#common";
import {
failureFooter,
type FailureReason,
type ProfileFailure,
withProfile,
} from "#profiles";
import {
readRuntimeManifest,
type RuntimeManifest,
type RuntimeOutcome,
} from "#runtime";
import { failureFooter, type FailureReason, type ProfileFailure, withProfile } from "#profiles";
import { readRuntimeManifest, type RuntimeManifest, type RuntimeOutcome } from "#runtime";
export interface PostContext {
apiUrl: string;
@@ -36,20 +27,9 @@ const VERDICTS = new Map<string, [event: string, mark: string]>([
["Changes requested", ["REQUEST_CHANGES", "🛑"]],
]);
const PROFILE_TYPES = new Set<unknown>(["CLAUDE", "CODEX", "OPENCODE"]);
const FAILURE_REASONS = new Set<unknown>([
"SIGN_IN_FAILED",
"USAGE_EXHAUSTED",
"FAILED",
]);
// Anchors written before the UPPER_SNAKE switch spell sides in lowercase.
const OLD_SIDES = new Map<unknown, Anchor["side"]>([
["new", "NEW"],
["old", "OLD"],
]);
const isProfileType = (value: unknown): value is ProfileFailure["type"] =>
PROFILE_TYPES.has(value);
const isFailureReason = (value: unknown): value is FailureReason =>
FAILURE_REASONS.has(value);
const FAILURE_REASONS = new Set<unknown>(["SIGN_IN_FAILED", "USAGE_EXHAUSTED", "FAILED"]);
const isProfileType = (value: unknown): value is ProfileFailure["type"] => PROFILE_TYPES.has(value);
const isFailureReason = (value: unknown): value is FailureReason => FAILURE_REASONS.has(value);
const failureComment = (failures: ProfileFailure[]): string =>
`AI bot failed.\n\n${failureFooter(failures)}`;
@@ -76,8 +56,7 @@ function parseAnchors(text: string, sourcePath: string): Anchor[] {
const path = field(entry, "path");
const line = field(entry, "line");
const givenSide = field(entry, "side");
const side =
givenSide === undefined ? "NEW" : (OLD_SIDES.get(givenSide) ?? givenSide);
const side = givenSide === undefined ? "NEW" : givenSide;
const body = field(entry, "body");
if (typeof path !== "string" || path === "") {
throw new TypeError(`${at}.path: expected a repository path`);
@@ -111,9 +90,7 @@ async function readOutcome(path: string): Promise<RuntimeOutcome> {
const type = field(entry, "type");
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 }]
: [];
}),
@@ -145,9 +122,7 @@ async function readAgentArtifact(
path: string,
name: string,
): Promise<string | null> {
const profile = manifest.profiles.find(
(entry) => nodePath.join(entry.home, name) === path,
);
const profile = manifest.profiles.find((entry) => join(entry.home, name) === path);
if (profile === undefined) {
throw new Error(`${name}: outside profile home`);
}
@@ -197,18 +172,13 @@ export async function postRuntime(
throw new GiteaRequestError(`${path}: ${detail}`, { cause: error });
}
if (!response.ok) {
throw new GiteaRequestError(
`${path}: ${response.status} ${await response.text()}`,
);
throw new GiteaRequestError(`${path}: ${response.status} ${await response.text()}`);
}
};
const postComment = async (body: string): Promise<void> => {
await request(
`repos/${context.repository}/issues/${context.issueIndex}/comments`,
{
body: stripAnsi(body),
},
);
await request(`repos/${context.repository}/issues/${context.issueIndex}/comments`, {
body: stripAnsi(body),
});
};
let outcome: RuntimeOutcome | null = null;
@@ -224,11 +194,7 @@ export async function postRuntime(
}
try {
const review = await readAgentArtifact(
manifest,
outcome.reviewPath,
"review.md",
);
const review = await readAgentArtifact(manifest, outcome.reviewPath, "review.md");
if (review === null) {
if (context.eventName === "pull_request") {
throw new Error("agent did not write a pull request review");
@@ -239,34 +205,21 @@ export async function postRuntime(
const [verdict = "", ...rest] = review.split("\n");
const [event, mark] = VERDICTS.get(verdict.trim()) ?? ["COMMENT", "💬"];
const anchorText = await readAgentArtifact(
manifest,
outcome.anchorsPath,
"anchors.json",
);
const anchors =
anchorText === null
? []
: parseAnchors(anchorText, outcome.anchorsPath);
const anchorText = await readAgentArtifact(manifest, outcome.anchorsPath, "anchors.json");
const anchors = anchorText === null ? [] : parseAnchors(anchorText, outcome.anchorsPath);
const postReview = async (entries: Anchor[]): Promise<void> => {
await request(
`repos/${context.repository}/pulls/${context.issueIndex}/reviews`,
{
body: stripAnsi(
withProfile(
[`${mark} ${verdict.trim()}`, ...rest].join("\n"),
outcome.profile,
),
),
event,
comments: entries.map(({ path, line, side, body }) => ({
path,
body: stripAnsi(withProfile(body, outcome.profile)),
new_position: side === "NEW" ? line : 0,
old_position: side === "OLD" ? line : 0,
})),
},
);
await request(`repos/${context.repository}/pulls/${context.issueIndex}/reviews`, {
body: stripAnsi(
withProfile([`${mark} ${verdict.trim()}`, ...rest].join("\n"), outcome.profile),
),
event,
comments: entries.map(({ path, line, side, body }) => ({
path,
body: stripAnsi(withProfile(body, outcome.profile)),
new_position: side === "NEW" ? line : 0,
old_position: side === "OLD" ? line : 0,
})),
});
};
await postReview(anchors).catch(async (error: unknown) => {
if (anchors.length === 0) {
@@ -281,18 +234,14 @@ export async function postRuntime(
if (error instanceof GiteaRequestError) {
throw error;
}
await postComment(
failureComment([{ ...outcome.profile, reason: "FAILED" }]),
);
await postComment(failureComment([{ ...outcome.profile, reason: "FAILED" }]));
throw error;
}
} finally {
await rm(manifest.runtimeDir, { recursive: true }).catch(
(error: unknown) => {
if (!isNotFound(error)) {
throw error;
}
},
);
await rm(manifest.runtimeDir, { recursive: true }).catch((error: unknown) => {
if (!isNotFound(error)) {
throw error;
}
});
}
}
+3 -9
View File
@@ -6,12 +6,8 @@ import { isNotFound } from "#common";
import { exitCode } from "./child.ts";
test("reports the exit code", async () => {
expect(
await exitCode(spawn("/bin/sh", ["-c", "exit 0"], { stdio: "ignore" })),
).toBe(0);
expect(
await exitCode(spawn("/bin/sh", ["-c", "exit 3"], { stdio: "ignore" })),
).toBe(3);
expect(await exitCode(spawn("/bin/sh", ["-c", "exit 0"], { stdio: "ignore" }))).toBe(0);
expect(await exitCode(spawn("/bin/sh", ["-c", "exit 3"], { stdio: "ignore" }))).toBe(3);
});
test("reports a signal as 128 plus its number", async () => {
@@ -20,9 +16,7 @@ test("reports a signal as 128 plus its number", async () => {
});
test("resolves on exit while a grandchild still holds the output open", async () => {
const child = spawn("/bin/sh", ["-c", "sleep 2 & exit 5"], {
stdio: ["ignore", "pipe", "pipe"],
});
const child = spawn("/bin/sh", ["-c", "sleep 2 & exit 5"], { stdio: ["ignore", "pipe", "pipe"] });
const started = Date.now();
expect(await exitCode(child)).toBe(5);
expect(Date.now() - started).toBeLessThan(1500);
+1 -4
View File
@@ -23,10 +23,7 @@ export function exitCode(child: ChildProcess): Promise<number> {
}
// Writes a chunk, waiting for the stream to drain when its buffer is full.
export async function echo(
stream: Writable,
chunk: string | Uint8Array,
): Promise<void> {
export async function echo(stream: Writable, chunk: string | Uint8Array): Promise<void> {
if (!stream.write(chunk)) {
await once(stream, "drain");
}
+72 -103
View File
@@ -1,13 +1,5 @@
import { spawnSync, type SpawnSyncReturns } from "node:child_process";
import {
chmod,
chown,
mkdir,
readFile,
rm,
symlink,
writeFile,
} from "node:fs/promises";
import { chmod, chown, mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises";
import process from "node:process";
import { expect, test } from "vite-plus/test";
@@ -15,11 +7,7 @@ import { isNotFound } from "#common";
import type { RuntimeProfile } from "#runtime";
import { currentUid, IS_ROOT, IS_WINDOWS, makeTempDir } from "#testing";
import {
isRunnableProfileProcess,
killProfileProcesses,
readProfileFile,
} from "./isolation.ts";
import { isRunnableProfileProcess, killProfileProcesses, readProfileFile } from "./isolation.ts";
const profile = (uid: number, home: string): RuntimeProfile => ({
index: uid - 20_000,
@@ -53,96 +41,77 @@ test("zombie process entries are already quiescent", () => {
expect(isRunnableProfileProcess(status, 20_010)).toBe(false);
});
test.skipIf(IS_WINDOWS)(
"refuses to read a profile result symlink as root",
async () => {
const root = await makeTempDir();
try {
const secret = `${root}/reviewer-token`;
const result = `${root}/result.md`;
await writeFile(secret, "reviewer-secret", { mode: 0o600 });
await symlink(secret, result);
test.skipIf(IS_WINDOWS)("refuses to read a profile result symlink as root", async () => {
const root = await makeTempDir();
try {
const secret = `${root}/reviewer-token`;
const result = `${root}/result.md`;
await writeFile(secret, "reviewer-secret", { mode: 0o600 });
await symlink(secret, result);
await expect(
readProfileFile(profile(currentUid(), root), result),
).rejects.toThrow("regular private file");
} finally {
await rm(root, { recursive: true });
}
},
);
test.skipIf(!IS_ROOT)(
"a profile process can read only its own private files",
async () => {
const root = await makeTempDir();
await chmod(root, 0o711);
try {
const homeA = `${root}/a`;
const homeB = `${root}/b`;
await mkdir(homeA, { mode: 0o700 });
await mkdir(homeB, { mode: 0o700 });
await chown(homeA, 20_000, 20_000);
await chown(homeB, 20_001, 20_001);
await writeFile(`${homeA}/token`, "own", { mode: 0o600 });
await chown(`${homeA}/token`, 20_000, 20_000);
await writeFile(`${homeB}/token`, "sibling", { mode: 0o600 });
await chown(`${homeB}/token`, 20_001, 20_001);
await writeFile(`${root}/reviewer`, "root", { mode: 0o600 });
const selected = profile(20_000, homeA);
const own = runAs(selected, "/bin/cat", [`${homeA}/token`]);
const sibling = runAs(selected, "/bin/cat", [`${homeB}/token`]);
const reviewer = runAs(selected, "/bin/cat", [`${root}/reviewer`]);
expect(own.stdout).toBe("own");
expect(own.status).toBe(0);
expect(sibling.status).not.toBe(0);
expect(reviewer.status).not.toBe(0);
} finally {
await rm(root, { recursive: true });
}
},
);
test.skipIf(!IS_ROOT)(
"cleanup leaves no runnable daemonized process",
async () => {
const selected = profile(20_010, "/tmp");
const launched = runAs(selected, "/bin/sh", [
"-c",
"sleep 60 >/dev/null 2>&1 & echo $!",
]);
const pid = Number(launched.stdout.trim());
expect(Number.isInteger(pid)).toBe(true);
await killProfileProcesses(selected.uid);
const status = await readFile(`/proc/${pid}/status`, "utf8").catch(
(error: unknown) => {
if (isNotFound(error)) {
return null;
}
throw error;
},
await expect(readProfileFile(profile(currentUid(), root), result)).rejects.toThrow(
"regular private file",
);
expect(
status === null || !isRunnableProfileProcess(status, selected.uid),
).toBe(true);
},
);
} finally {
await rm(root, { recursive: true });
}
});
test.skipIf(!IS_ROOT)(
"the agent process cannot read its coordinator environment",
() => {
const selected = profile(20_020, "/tmp");
const result = runAs(
selected,
"/usr/bin/cat",
[`/proc/${process.pid}/environ`],
new Map([["PARENT_SECRET", "must-not-cross-boundary"]]),
);
test.skipIf(!IS_ROOT)("a profile process can read only its own private files", async () => {
const root = await makeTempDir();
await chmod(root, 0o711);
try {
const homeA = `${root}/a`;
const homeB = `${root}/b`;
await mkdir(homeA, { mode: 0o700 });
await mkdir(homeB, { mode: 0o700 });
await chown(homeA, 20_000, 20_000);
await chown(homeB, 20_001, 20_001);
await writeFile(`${homeA}/token`, "own", { mode: 0o600 });
await chown(`${homeA}/token`, 20_000, 20_000);
await writeFile(`${homeB}/token`, "sibling", { mode: 0o600 });
await chown(`${homeB}/token`, 20_001, 20_001);
await writeFile(`${root}/reviewer`, "root", { mode: 0o600 });
expect(result.status).not.toBe(0);
},
);
const selected = profile(20_000, homeA);
const own = runAs(selected, "/bin/cat", [`${homeA}/token`]);
const sibling = runAs(selected, "/bin/cat", [`${homeB}/token`]);
const reviewer = runAs(selected, "/bin/cat", [`${root}/reviewer`]);
expect(own.stdout).toBe("own");
expect(own.status).toBe(0);
expect(sibling.status).not.toBe(0);
expect(reviewer.status).not.toBe(0);
} finally {
await rm(root, { recursive: true });
}
});
test.skipIf(!IS_ROOT)("cleanup leaves no runnable daemonized process", async () => {
const selected = profile(20_010, "/tmp");
const launched = runAs(selected, "/bin/sh", ["-c", "sleep 60 >/dev/null 2>&1 & echo $!"]);
const pid = Number(launched.stdout.trim());
expect(Number.isInteger(pid)).toBe(true);
await killProfileProcesses(selected.uid);
const status = await readFile(`/proc/${pid}/status`, "utf8").catch((error: unknown) => {
if (isNotFound(error)) {
return null;
}
throw error;
});
expect(status === null || !isRunnableProfileProcess(status, selected.uid)).toBe(true);
});
test.skipIf(!IS_ROOT)("the agent process cannot read its coordinator environment", () => {
const selected = profile(20_020, "/tmp");
const result = runAs(
selected,
"/usr/bin/cat",
[`/proc/${process.pid}/environ`],
new Map([["PARENT_SECRET", "must-not-cross-boundary"]]),
);
expect(result.status).not.toBe(0);
});
+6 -18
View File
@@ -6,8 +6,8 @@ import { isNotFound } from "#common";
import type { RuntimeProfile } from "#runtime";
export function isRunnableProfileProcess(status: string, uid: number): boolean {
const owner = /^Uid:\s+(?<uid>\d+)/mu.exec(status)?.groups?.["uid"];
const state = /^State:\s+(?<state>\w)/mu.exec(status)?.groups?.["state"];
const owner = /^Uid:\s+(?<uid>\d+)/mu.exec(status)?.[1];
const state = /^State:\s+(?<state>\w)/mu.exec(status)?.[1];
return owner !== undefined && Number(owner) === uid && state !== "Z";
}
@@ -18,29 +18,20 @@ async function profileProcessIds(uid: number): Promise<number[]> {
.map((entry) => entry.name);
const statuses = await Promise.all(
pids.map(async (pid) => {
const status = await readFile(`/proc/${pid}/status`, "utf8").catch(
() => null,
);
const status = await readFile(`/proc/${pid}/status`, "utf8").catch(() => null);
return status;
}),
);
return pids
.filter((_pid, index) => {
const status = statuses[index];
return (
status !== null &&
status !== undefined &&
isRunnableProfileProcess(status, uid)
);
return status !== null && status !== undefined && isRunnableProfileProcess(status, uid);
})
.map(Number);
}
// Kills the UID's processes every 10 ms until none is left, for up to 100 rounds.
export async function killProfileProcesses(
uid: number,
attempt = 0,
): Promise<void> {
export async function killProfileProcesses(uid: number, attempt = 0): Promise<void> {
if (attempt === 100) {
throw new Error(`profile UID ${uid} still owns processes after cleanup`);
}
@@ -61,10 +52,7 @@ export async function killProfileProcesses(
await killProfileProcesses(uid, attempt + 1);
}
export async function readProfileFile(
profile: RuntimeProfile,
path: string,
): Promise<string> {
export async function readProfileFile(profile: RuntimeProfile, path: string): Promise<string> {
const stat = await lstat(path);
if (
!stat.isFile() ||
+1 -6
View File
@@ -9,9 +9,4 @@ export {
sanitizedEnvironment,
withProfile,
} from "./profiles.ts";
export type {
BotProfile,
FailureReason,
ProfileFailure,
ProfileIdentity,
} from "./profiles.ts";
export type { BotProfile, FailureReason, ProfileFailure, ProfileIdentity } from "./profiles.ts";
+24 -32
View File
@@ -11,9 +11,9 @@ import {
} from "./profiles.ts";
test("formats profile attribution as a Markdown quote", () => {
expect(
profileFooter({ type: "OPENCODE", model: "openrouter/qwen/qwen3.8-27b" }),
).toBe("> Profile: `opencode` · `openrouter/qwen/qwen3.8-27b`");
expect(profileFooter({ type: "OPENCODE", model: "openrouter/qwen/qwen3.8-27b" })).toBe(
"> Profile: `OPENCODE` · `openrouter/qwen/qwen3.8-27b`",
);
});
test("falls through only after usage exhaustion", async () => {
@@ -57,24 +57,22 @@ test("recognizes Claude's weekly limit message", async () => {
test("recognizes provider API exhaustion status", async () => {
const results = await Promise.all(
["API Error: 402 Insufficient funds", "HTTP error: 429"].map(
async (message) => {
const result = await runProfiles(
[
{ type: "CLAUDE", model: "claude-sonnet-5", token: "first" },
{ type: "CODEX", model: "gpt-5.6-terra" },
],
async (profile) => {
if (profile.type === "CLAUDE") {
throw new Error(message);
}
const resolved = await Promise.resolve("fallback");
return resolved;
},
);
return result;
},
),
["API Error: 402 Insufficient funds", "HTTP error: 429"].map(async (message) => {
const result = await runProfiles(
[
{ type: "CLAUDE", model: "claude-sonnet-5", token: "first" },
{ type: "CODEX", model: "gpt-5.6-terra" },
],
async (profile) => {
if (profile.type === "CLAUDE") {
throw new Error(message);
}
const resolved = await Promise.resolve("fallback");
return resolved;
},
);
return result;
}),
);
expect(results).toStrictEqual(["fallback", "fallback"]);
@@ -107,8 +105,8 @@ test("falls through after a sign-in failure and records each try", async () => {
{ type: "CLAUDE", model: "claude-sonnet-5", reason: "USAGE_EXHAUSTED" },
]);
expect(failureFooter(failures)).toStrictEqual(
"> Tried: `codex` · `gpt-5.6-terra` (sign-in failed), " +
"`claude` · `claude-sonnet-5` (usage exhausted)",
"> Tried: `CODEX` · `gpt-5.6-terra` (sign-in failed), " +
"`CLAUDE` · `claude-sonnet-5` (usage exhausted)",
);
});
@@ -128,14 +126,10 @@ test("throws the last sign-in failure when every profile fails", async () => {
).rejects.toThrow(
expect.toSatisfy(
(error: unknown) =>
error instanceof AgentAuthError &&
error.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"]);
});
test("preserves an ordinary agent failure", async () => {
@@ -243,9 +237,7 @@ test("exposes an OpenRouter key only to the OpenCode profile", () => {
tokenFile: "/runtime/profile-2/token",
};
expect(
agentEnvironment(new Map([["PATH", "/bin"]]), profile, "selected"),
).toStrictEqual(
expect(agentEnvironment(new Map([["PATH", "/bin"]]), profile, "selected")).toStrictEqual(
new Map([
["PATH", "/bin"],
["HOME", "/runtime/profile-2"],
+3 -20
View File
@@ -8,20 +8,8 @@ export interface BotProfile extends ProfileIdentity {
token?: string;
}
// The lowercase name a profile type reads as in posted comments.
function profileName(type: ProfileIdentity["type"]): string {
switch (type) {
case "CLAUDE":
return "claude";
case "CODEX":
return "codex";
case "OPENCODE":
return "opencode";
}
}
export function profileFooter(profile: ProfileIdentity): string {
return `> Profile: \`${profileName(profile.type)}\` · \`${profile.model}\``;
return `> Profile: \`${profile.type}\` · \`${profile.model}\``;
}
export function withProfile(body: string, profile: ProfileIdentity): string {
@@ -78,10 +66,7 @@ export function failureFooter(failures: ProfileFailure[]): string {
return "> Profile: none";
}
return `> Tried: ${failures
.map(
({ type, model, reason }) =>
`\`${profileName(type)}\` · \`${model}\` (${toMessage(reason)})`,
)
.map(({ type, model, reason }) => `\`${type}\` · \`${model}\` (${toMessage(reason)})`)
.join(", ")}`;
}
@@ -101,9 +86,7 @@ export async function runProfiles<T, P extends ProfileIdentity>(
if (reason === "FAILED" || index === profiles.length - 1) {
throw error;
}
console.error(
`${profile.type} ${toMessage(reason)}; trying next profile`,
);
console.error(`${profile.type} ${toMessage(reason)}; trying next profile`);
}
}
throw new Error("profiles must contain at least one profile");
+23 -87
View File
@@ -25,12 +25,7 @@ import {
stageCodexAuth,
} from "#agents";
import { field, isObject } from "#common";
import {
echo,
exitCode,
killProfileProcesses,
readProfileFile,
} from "#processes";
import { echo, exitCode, killProfileProcesses, readProfileFile } from "#processes";
import {
AgentAuthError,
agentEnvironment,
@@ -40,11 +35,7 @@ import {
sanitizedEnvironment,
withProfile,
} from "#profiles";
import {
readRuntimeManifest,
type RuntimeOutcome,
type RuntimeProfile,
} from "#runtime";
import { readRuntimeManifest, type RuntimeOutcome, type RuntimeProfile } from "#runtime";
interface AttemptResult {
body: string;
@@ -116,10 +107,7 @@ async function postAuthorComment(body: string): Promise<void> {
async function runRoot(command: string, args: string[]): Promise<void> {
const code = await exitCode(
spawn(command, args, {
env: Object.fromEntries(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}`);
@@ -138,13 +126,8 @@ async function configureGitAuthor(): Promise<void> {
await runRoot("git", ["config", "user.email", email]);
}
async function readProfileToken(
profile: RuntimeProfile,
): Promise<string | null> {
const token =
profile.tokenFile === null
? null
: await readFile(profile.tokenFile, "utf8");
async function readProfileToken(profile: RuntimeProfile): Promise<string | null> {
const token = profile.tokenFile === null ? null : await readFile(profile.tokenFile, "utf8");
return token;
}
@@ -208,9 +191,7 @@ function formatComment(comment: unknown): string {
async function renderPrompt(profile: RuntimeProfile): Promise<RenderedPrompt> {
const reviewPath = await makeProfileFile(profile, "review.md");
const anchorsPath = await makeProfileFile(profile, "anchors.json");
const commentsResponse = await gitea(
`repos/${REPO}/issues/${INDEX}/comments?limit=100`,
);
const commentsResponse = await gitea(`repos/${REPO}/issues/${INDEX}/comments?limit=100`);
const comments: unknown = await commentsResponse.json();
if (!Array.isArray(comments)) {
throw new TypeError("comments: unexpected Gitea response");
@@ -219,10 +200,7 @@ async function renderPrompt(profile: RuntimeProfile): Promise<RenderedPrompt> {
const codeRules = await rulesResponse.text();
const values = new Map<string, string>([
["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", codeRules],
["EVENT_NAME", EVENT],
["GITEA_API_URL", API],
@@ -231,29 +209,18 @@ async function renderPrompt(profile: RuntimeProfile): Promise<RenderedPrompt> {
["REVIEW_PATH", reviewPath],
["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 {
prompt: template.replaceAll(
/\$\{(?<name>\w+)\}/gu,
(match: string, ...args: unknown[]) => {
const groups = args.at(-1);
const name = isObject(groups) ? field(groups, "name") : undefined;
return typeof name === "string" ? (values.get(name) ?? match) : match;
},
(match: string, name: string) => values.get(name) ?? match,
),
reviewPath,
anchorsPath,
};
}
async function runClaude(
profile: RuntimeProfile,
token: string,
prompt: string,
): Promise<string> {
async function runClaude(profile: RuntimeProfile, token: string, prompt: string): Promise<string> {
const claude = spawn(
"claude",
[
@@ -268,9 +235,7 @@ async function runClaude(
],
{
cwd: WORKSPACE,
env: Object.fromEntries(
agentEnvironment(PROCESS_ENV, profile, token).set("IS_SANDBOX", "1"),
),
env: Object.fromEntries(agentEnvironment(PROCESS_ENV, profile, token).set("IS_SANDBOX", "1")),
uid: profile.uid,
gid: profile.gid,
stdio: ["ignore", "pipe", "pipe"],
@@ -287,20 +252,14 @@ async function runClaude(
console.error(part);
}
})();
for await (const line of createInterface({
input: claude.stdout,
crlfDelay: Infinity,
})) {
for await (const line of createInterface({ input: claude.stdout, crlfDelay: Infinity })) {
if (line !== "") {
const event: unknown = JSON.parse(line);
if (isObject(event)) {
const content = field(field(event, "message"), "content");
for (const part of Array.isArray(content) ? content : []) {
if (isObject(part)) {
const text =
field(part, "thinking") ??
field(part, "text") ??
field(part, "name");
const text = field(part, "thinking") ?? field(part, "text") ?? field(part, "name");
if (typeof text === "string" && text !== "") {
console.log(text);
}
@@ -315,8 +274,7 @@ async function runClaude(
isError: typeof isError === "boolean" ? isError : undefined,
result: typeof answer === "string" ? answer : undefined,
subtype: String(subtype),
apiErrorStatus:
typeof apiStatus === "number" ? apiStatus : undefined,
apiErrorStatus: typeof apiStatus === "number" ? apiStatus : undefined,
};
}
}
@@ -324,18 +282,14 @@ async function runClaude(
}
const [code] = await Promise.all([status, copyError]);
if (result?.isError === true) {
const failure = new Error(
result.result ?? `claude ended with ${result.subtype}`,
);
const failure = new Error(result.result ?? `claude ended with ${result.subtype}`);
if (isClaudeAuthFailure(result)) {
throw new AgentAuthError("claude sign-in failed", { cause: failure });
}
throw failure;
}
if (result?.result === undefined) {
throw new Error(
error.trim() || `claude ended with ${result?.subtype ?? "no result"}`,
);
throw new Error(error.trim() || `claude ended with ${result?.subtype ?? "no result"}`);
}
if (code !== 0) {
throw new Error(error.trim() || `claude exited with ${code}`);
@@ -365,10 +319,7 @@ async function codexDeviceLogin(
const drained = Promise.all([collect(login.stdout), collect(login.stderr)]);
await sleep(3000);
while (shown.trim() === "") {
const exited = await Promise.race([
status.then(() => true),
sleep(100, false),
]);
const exited = await Promise.race([status.then(() => true), sleep(100, false)]);
if (exited) {
throw new AgentAuthError("AI bot login produced no instructions");
}
@@ -401,10 +352,7 @@ async function codexApiLogin(
}
}
async function makeProfileFile(
profile: RuntimeProfile,
name: string,
): Promise<string> {
async function makeProfileFile(profile: RuntimeProfile, name: string): Promise<string> {
const path = `${profile.home}/${name}`;
await writeFile(path, "", { mode: 0o600 });
await chmod(path, 0o600);
@@ -417,8 +365,7 @@ async function runCodex(
prompt: string,
authentication: CodexAuthentication,
): Promise<string> {
const token =
authentication.kind === "api-key" ? authentication.token : undefined;
const token = authentication.kind === "api-key" ? authentication.token : undefined;
const environment = agentEnvironment(PROCESS_ENV, profile, token);
if (authentication.kind === "api-key") {
await codexApiLogin(profile, environment, authentication.token);
@@ -474,9 +421,7 @@ async function runCodex(
await codexDeviceLogin(profile, environment);
});
if (result.code !== 0) {
const failure = new Error(
result.error.trim() || `codex exited with ${result.code}`,
);
const failure = new Error(result.error.trim() || `codex exited with ${result.code}`);
if (isCodexAuthFailure(result.error)) {
throw new AgentAuthError("codex sign-in failed", { cause: failure });
}
@@ -511,18 +456,14 @@ async function runOpenCode(
const [code, streams] = await Promise.all([status, collected]);
const error = streams.stderr.trim();
if (code !== 0) {
throw (
openCodeError(streams.stdout) ??
new Error(error || `opencode exited with ${code}`)
);
throw openCodeError(streams.stdout) ?? new Error(error || `opencode exited with ${code}`);
}
return parseOpenCodeEvents(streams.stdout);
}
async function runProfile(profile: RuntimeProfile): Promise<AttemptResult> {
const token = await readProfileToken(profile);
const authentication =
profile.type === "CODEX" ? codexAuthentication(token ?? undefined) : null;
const authentication = profile.type === "CODEX" ? codexAuthentication(token ?? undefined) : null;
let stagedCodexAuth: string | null = null;
let body: string | null = null;
let resultPath: string | null = null;
@@ -530,12 +471,7 @@ async function runProfile(profile: RuntimeProfile): Promise<AttemptResult> {
let anchorsPath: string | null = null;
try {
if (authentication?.kind === "persistent") {
stagedCodexAuth = await stageCodexAuth(
CODEX_AUTH,
profile.home,
profile.uid,
profile.gid,
);
stagedCodexAuth = await stageCodexAuth(CODEX_AUTH, profile.home, profile.uid, profile.gid);
}
await prepareProfile(profile);
const rendered = await renderPrompt(profile);
+5 -33
View File
@@ -1,10 +1,6 @@
import { expect, test } from "vite-plus/test";
import {
decryptCredential,
encryptCredential,
parseCredentials,
} from "./credentials.ts";
import { decryptCredential, encryptCredential, parseCredentials } from "./credentials.ts";
const MASTER_KEY = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8";
const OTHER_KEY = "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE";
@@ -16,9 +12,7 @@ test("decrypts a known AES-256-GCM credential", async () => {
});
test("encrypts a credential with a fresh supplied nonce", async () => {
expect(
await encryptCredential("secret-token", MASTER_KEY, NONCE),
).toStrictEqual(ENCRYPTED);
expect(await encryptCredential("secret-token", MASTER_KEY, NONCE)).toStrictEqual(ENCRYPTED);
});
test("rejects a credential encrypted by another master key", async () => {
@@ -27,10 +21,7 @@ test("rejects a credential encrypted by another master key", async () => {
test("rejects a credential with a nonstandard nonce", async () => {
await expect(
decryptCredential(
"v1:AA:oV_FAgnsN3p1FyegJxwGVdyjfyPio6qDeSUwbA",
MASTER_KEY,
),
decryptCredential("v1:AA:oV_FAgnsN3p1FyegJxwGVdyjfyPio6qDeSUwbA", MASTER_KEY),
).rejects.toThrow("nonce must be 12 bytes");
});
@@ -66,30 +57,11 @@ test("decrypts the central reviewer token and ordered profiles", async () => {
});
test("rejects malformed central credentials", async () => {
await expect(
parseCredentials('{"profiles": []}', MASTER_KEY),
).rejects.toThrow("reviewer-token");
await expect(parseCredentials('{"profiles": []}', MASTER_KEY)).rejects.toThrow("reviewer-token");
await expect(
parseCredentials(
JSON.stringify({
"reviewer-token": ENCRYPTED,
profiles: [{ type: "CLAUDE" }],
}),
JSON.stringify({ "reviewer-token": ENCRYPTED, profiles: [{ type: "CLAUDE" }] }),
MASTER_KEY,
),
).rejects.toThrow("profiles[0].token");
});
test("reads lowercase profile types from older credentials", async () => {
const credentials = await parseCredentials(
JSON.stringify({
"reviewer-token": ENCRYPTED,
profiles: [{ type: "codex" }, { type: "claude", token: ENCRYPTED }],
}),
MASTER_KEY,
);
expect(credentials.profiles.map(({ type }) => type)).toStrictEqual([
"CODEX",
"CLAUDE",
]);
});
+12 -57
View File
@@ -23,24 +23,15 @@ export interface BotCredentials {
function decodeBase64Url(value: string): Uint8Array {
const base64 = value.replaceAll("-", "+").replaceAll("_", "/");
const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
return Uint8Array.from(
atob(padded),
(character) => character.codePointAt(0) ?? 0,
);
return Uint8Array.from(atob(padded), (character) => character.codePointAt(0) ?? 0);
}
function encodeBase64Url(value: Uint8Array): string {
const binary = Array.from(value, (byte) => String.fromCodePoint(byte)).join(
"",
);
return btoa(binary)
.replaceAll("+", "-")
.replaceAll("/", "_")
.replaceAll("=", "");
const binary = Array.from(value, (byte) => String.fromCodePoint(byte)).join("");
return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
}
const buffer = (value: Uint8Array): ArrayBuffer =>
Uint8Array.from(value).buffer;
const buffer = (value: Uint8Array): ArrayBuffer => Uint8Array.from(value).buffer;
async function importMasterKey(
encoded: string,
@@ -50,28 +41,13 @@ async function importMasterKey(
if (bytes.length !== 32) {
throw new Error("master-key must be 32 bytes encoded as base64url");
}
const key = await webcrypto.subtle.importKey(
"raw",
buffer(bytes),
"AES-GCM",
false,
[usage],
);
const key = await webcrypto.subtle.importKey("raw", buffer(bytes), "AES-GCM", false, [usage]);
return key;
}
export async function decryptCredential(
encrypted: string,
masterKey: string,
): Promise<string> {
const [version, encodedNonce = "", encodedCiphertext = "", extra = ""] =
encrypted.split(":");
if (
version !== "v1" ||
encodedNonce === "" ||
encodedCiphertext === "" ||
extra !== ""
) {
export async function decryptCredential(encrypted: string, masterKey: string): Promise<string> {
const [version, encodedNonce = "", encodedCiphertext = "", extra = ""] = encrypted.split(":");
if (version !== "v1" || encodedNonce === "" || encodedCiphertext === "" || extra !== "") {
throw new Error("credential must use v1:<nonce>:<ciphertext>");
}
const nonce = decodeBase64Url(encodedNonce);
@@ -102,22 +78,7 @@ export async function encryptCredential(
return `v1:${encodeBase64Url(nonce)}:${encodeBase64Url(new Uint8Array(ciphertext))}`;
}
// profiles.json files written before the UPPER_SNAKE switch spell types in lowercase.
const OLD_PROFILE_TYPES = new Map<unknown, BotProfile["type"]>([
["claude", "CLAUDE"],
["codex", "CODEX"],
["opencode", "OPENCODE"],
]);
function currentSpelling(type: unknown): unknown {
return OLD_PROFILE_TYPES.get(type) ?? type;
}
async function parseProfile(
entry: unknown,
index: number,
masterKey: string,
): Promise<BotProfile> {
async function parseProfile(entry: unknown, index: number, masterKey: string): Promise<BotProfile> {
const at = `profiles[${index}]`;
if (!isMapping(entry)) {
throw new TypeError(`${at}: expected a mapping`);
@@ -127,7 +88,7 @@ async function parseProfile(
throw new Error(`${at}.${key}: unknown field`);
}
}
const type = currentSpelling(field(entry, "type"));
const type = field(entry, "type");
const model = field(entry, "model");
const token = field(entry, "token");
if (type !== "CLAUDE" && type !== "CODEX" && type !== "OPENCODE") {
@@ -151,10 +112,7 @@ async function parseProfile(
};
}
export async function parseCredentials(
text: string,
masterKey: string,
): Promise<BotCredentials> {
export async function parseCredentials(text: string, masterKey: string): Promise<BotCredentials> {
const value: unknown = JSON.parse(text);
if (!isMapping(value)) {
throw new TypeError("credentials must be a mapping");
@@ -178,8 +136,5 @@ export async function parseCredentials(
return profile;
}),
);
return {
reviewerToken: await decryptCredential(reviewerToken, masterKey),
profiles: parsed,
};
return { reviewerToken: await decryptCredential(reviewerToken, masterKey), profiles: parsed };
}
+76 -103
View File
@@ -1,12 +1,5 @@
import { spawnSync } from "node:child_process";
import {
chmod,
readdir,
readFile,
rm,
stat,
writeFile,
} from "node:fs/promises";
import { chmod, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
import process from "node:process";
import { fileURLToPath } from "node:url";
import { assert, expect, test } from "vite-plus/test";
@@ -19,111 +12,91 @@ const MASTER_KEY = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8";
const ENCRYPTED = "v1:ICEiIyQlJicoKSor:oV_FAgnsN3p1FyegJxwGVdyjfyPio6qDeSUwbA";
// Runs `command` as the profile's user, from the root directory.
function runAs(
profile: RuntimeProfile,
command: string,
path: string,
): boolean {
const result = spawnSync(command, [path], {
cwd: "/",
uid: profile.uid,
gid: profile.gid,
});
function runAs(profile: RuntimeProfile, command: string, path: string): boolean {
const result = spawnSync(command, [path], { cwd: "/", uid: profile.uid, gid: profile.gid });
return result.status === 0;
}
async function expectPrivate(
path: string,
uid: number,
mode: number,
): Promise<void> {
async function expectPrivate(path: string, uid: number, mode: number): Promise<void> {
const info = await stat(path);
expect(info.uid).toStrictEqual(uid);
expect(info.mode & 0o777).toBe(mode);
}
test.skipIf(!IS_ROOT)(
"prepares root-only reviewer and isolated profile credentials",
async () => {
const root = await makeTempDir();
await chmod(root, 0o711);
const action = await makeTempDir();
try {
await writeFile(
`${action}/profiles.json`,
JSON.stringify({
"reviewer-token": ENCRYPTED,
profiles: [{ type: "CLAUDE", token: ENCRYPTED }, { type: "CODEX" }],
}),
);
test.skipIf(!IS_ROOT)("prepares root-only reviewer and isolated profile credentials", async () => {
const root = await makeTempDir();
await chmod(root, 0o711);
const action = await makeTempDir();
try {
await writeFile(
`${action}/profiles.json`,
JSON.stringify({
"reviewer-token": ENCRYPTED,
profiles: [{ type: "CLAUDE", token: ENCRYPTED }, { type: "CODEX" }],
}),
);
const manifest = await prepareRuntime(action, root, MASTER_KEY);
const serialized = await readFile(manifest.manifestPath, "utf8");
assert(!serialized.includes("secret-token"));
expect(await readFile(manifest.reviewerFile, "utf8")).toBe(
"secret-token",
);
await expectPrivate(manifest.reviewerFile, 0, 0o600);
const manifest = await prepareRuntime(action, root, MASTER_KEY);
const serialized = await readFile(manifest.manifestPath, "utf8");
assert(!serialized.includes("secret-token"));
expect(await readFile(manifest.reviewerFile, "utf8")).toBe("secret-token");
await expectPrivate(manifest.reviewerFile, 0, 0o600);
const [claude, codex] = manifest.profiles;
assert(claude !== undefined && codex !== undefined);
expect(claude.uid).not.toStrictEqual(codex.uid);
await expectPrivate(claude.home, claude.uid, 0o700);
assert(claude.tokenFile !== null);
expect(await readFile(claude.tokenFile, "utf8")).toBe("secret-token");
await expectPrivate(claude.tokenFile, claude.uid, 0o600);
const codexHome = await stat(codex.home);
expect(codexHome.uid).toStrictEqual(codex.uid);
expect(codex.tokenFile).toBe(null);
const [claude, codex] = manifest.profiles;
assert(claude !== undefined && codex !== undefined);
expect(claude.uid).not.toStrictEqual(codex.uid);
await expectPrivate(claude.home, claude.uid, 0o700);
assert(claude.tokenFile !== null);
expect(await readFile(claude.tokenFile, "utf8")).toBe("secret-token");
await expectPrivate(claude.tokenFile, claude.uid, 0o600);
const codexHome = await stat(codex.home);
expect(codexHome.uid).toStrictEqual(codex.uid);
expect(codex.tokenFile).toBe(null);
const ownToken = spawnSync("/bin/cat", [claude.tokenFile], {
cwd: "/",
uid: claude.uid,
gid: claude.gid,
encoding: "utf8",
});
expect(ownToken.status).toBe(0);
expect(ownToken.stdout).toBe("secret-token");
expect(runAs(claude, "/bin/cat", manifest.reviewerFile)).toBe(false);
expect(runAs(claude, "/bin/ls", codex.home)).toBe(false);
} finally {
await rm(root, { recursive: true });
await rm(action, { recursive: true });
}
},
);
const ownToken = spawnSync("/bin/cat", [claude.tokenFile], {
cwd: "/",
uid: claude.uid,
gid: claude.gid,
encoding: "utf8",
});
expect(ownToken.status).toBe(0);
expect(ownToken.stdout).toBe("secret-token");
expect(runAs(claude, "/bin/cat", manifest.reviewerFile)).toBe(false);
expect(runAs(claude, "/bin/ls", codex.home)).toBe(false);
} finally {
await rm(root, { recursive: true });
await rm(action, { recursive: true });
}
});
test.skipIf(!IS_ROOT)(
"removes prepared credentials when output publication fails",
async () => {
const root = await makeTempDir();
const action = await makeTempDir();
try {
await writeFile(
`${action}/profiles.json`,
JSON.stringify({
"reviewer-token": ENCRYPTED,
profiles: [{ type: "CLAUDE", token: ENCRYPTED }],
}),
);
const result = spawnSync(
process.execPath,
[fileURLToPath(new URL("../prepare/index.ts", import.meta.url))],
{
env: Object.fromEntries([
["ACTION_PATH", action],
["RUNNER_TEMP", root],
["BOT_AGENTS_MASTER_KEY", MASTER_KEY],
["GITHUB_OUTPUT", action],
]),
},
);
test.skipIf(!IS_ROOT)("removes prepared credentials when output publication fails", async () => {
const root = await makeTempDir();
const action = await makeTempDir();
try {
await writeFile(
`${action}/profiles.json`,
JSON.stringify({
"reviewer-token": ENCRYPTED,
profiles: [{ type: "CLAUDE", token: ENCRYPTED }],
}),
);
const result = spawnSync(
process.execPath,
[fileURLToPath(new URL("../prepare/index.ts", import.meta.url))],
{
env: Object.fromEntries([
["ACTION_PATH", action],
["RUNNER_TEMP", root],
["BOT_AGENTS_MASTER_KEY", MASTER_KEY],
["GITHUB_OUTPUT", action],
]),
},
);
expect(result.status).not.toBe(0);
expect(await readdir(root)).toStrictEqual([]);
} finally {
await rm(root, { recursive: true });
await rm(action, { recursive: true });
}
},
);
expect(result.status).not.toBe(0);
expect(await readdir(root)).toStrictEqual([]);
} finally {
await rm(root, { recursive: true });
await rm(action, { recursive: true });
}
});
+11 -28
View File
@@ -1,13 +1,5 @@
import {
chmod,
chown,
mkdir,
mkdtemp,
readFile,
rm,
writeFile,
} from "node:fs/promises";
import nodePath from "node:path";
import { chmod, chown, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { field, isMapping } from "#common";
import type { ProfileFailure, ProfileIdentity } from "#profiles";
@@ -47,12 +39,7 @@ export interface RuntimeFailure {
export type RuntimeOutcome = RuntimeSuccess | RuntimeFailure;
async function writePrivate(
path: string,
value: string,
uid: number,
gid: number,
): Promise<void> {
async function writePrivate(path: string, value: string, uid: number, gid: number): Promise<void> {
await writeFile(path, value, { mode: 0o600 });
await chmod(path, 0o600);
await chown(path, uid, gid);
@@ -64,27 +51,25 @@ export async function prepareRuntime(
masterKey: string,
): Promise<RuntimeManifest> {
const credentials = await parseCredentials(
await readFile(nodePath.join(actionPath, "profiles.json"), "utf8"),
await readFile(join(actionPath, "profiles.json"), "utf8"),
masterKey,
);
const runtimeDir = await mkdtemp(nodePath.join(runtimeRoot, "bot-agents-"));
const runtimeDir = await mkdtemp(join(runtimeRoot, "bot-agents-"));
try {
await chmod(runtimeDir, 0o711);
const reviewerFile = nodePath.join(runtimeDir, "reviewer-token");
const reviewerFile = join(runtimeDir, "reviewer-token");
await writePrivate(reviewerFile, credentials.reviewerToken, 0, 0);
// One profile at a time, in order, as each claims the next UID.
const profiles: RuntimeProfile[] = [];
for (const [index, profile] of credentials.profiles.entries()) {
const uid = FIRST_PROFILE_UID + index;
const home = nodePath.join(runtimeDir, `profile-${index}`);
const home = join(runtimeDir, `profile-${index}`);
await mkdir(home, { mode: 0o700 });
await chmod(home, 0o700);
await chown(home, uid, uid);
const tokenFile =
profile.token === undefined || profile.token === ""
? null
: nodePath.join(home, "token");
profile.token === undefined || profile.token === "" ? null : join(home, "token");
if (tokenFile !== null && profile.token !== undefined) {
await writePrivate(tokenFile, profile.token, uid, uid);
}
@@ -99,12 +84,12 @@ export async function prepareRuntime(
});
}
const manifestPath = nodePath.join(runtimeDir, "manifest.json");
const manifestPath = join(runtimeDir, "manifest.json");
const manifest: RuntimeManifest = {
runtimeDir,
manifestPath,
reviewerFile,
outcomeFile: nodePath.join(runtimeDir, "outcome.json"),
outcomeFile: join(runtimeDir, "outcome.json"),
profiles,
};
await writePrivate(manifestPath, JSON.stringify(manifest), 0, 0);
@@ -126,9 +111,7 @@ function isRuntimeManifest(value: unknown): value is RuntimeManifest {
);
}
export async function readRuntimeManifest(
path: string,
): Promise<RuntimeManifest> {
export async function readRuntimeManifest(path: string): Promise<RuntimeManifest> {
const value: unknown = JSON.parse(await readFile(path, "utf8"));
if (!isRuntimeManifest(value)) {
throw new Error(`${path}: invalid runtime manifest`);
+6 -9
View File
@@ -1,12 +1,12 @@
// Test support: the current user's IDs, a fresh temporary directory, the
// inherited environment, and a plain command runner. It imports no source
// module, so the repository-level tests in tests/, which reach src/ only
// through `#testing`, never touch internals.
// inherited environment, and a plain command runner. It imports no source module, so the repository-level
// tests in tests/, which reach src/ only through `#testing`, never touch
// internals.
import { spawn } from "node:child_process";
import { once } from "node:events";
import { mkdtemp } from "node:fs/promises";
import { tmpdir } from "node:os";
import nodePath from "node:path";
import { join } from "node:path";
import process from "node:process";
import { text } from "node:stream/consumers";
@@ -25,7 +25,7 @@ export const IS_ROOT: boolean = currentUid() === 0;
export const IS_WINDOWS: boolean = process.platform === "win32";
export async function makeTempDir(): Promise<string> {
const path = await mkdtemp(nodePath.join(tmpdir(), "bot-agents-test-"));
const path = await mkdtemp(join(tmpdir(), "bot-agents-test-"));
return path;
}
@@ -56,10 +56,7 @@ export async function runCommand(
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];
return { success: exitCode === 0, stderr };
}
+1 -3
View File
@@ -14,9 +14,7 @@ const PHASES: [phase: string, firstVariable: string][] = [
];
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(
process.execPath,
[path],
+24 -68
View File
@@ -9,18 +9,13 @@ import { inheritedEnvironment, makeTempDir, runCommand } from "#testing";
type Mapping = Map<string, unknown>;
const mapping = (value: unknown, at: string): Mapping => {
assert(
typeof value === "object" && value !== null && !Array.isArray(value),
at,
);
assert(typeof value === "object" && value !== null && !Array.isArray(value), at);
return new Map(Object.entries(value));
};
const sequence = (value: unknown, at: string): Mapping[] => {
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> {
@@ -54,13 +49,8 @@ test("all committed YAML parses", async () => {
test("the action exposes only the master key and scopes it to preparation", async () => {
const action = await yaml("action.yml");
expect([...mapping(action.get("inputs"), "inputs").keys()]).toStrictEqual([
"master-key",
]);
const steps = sequence(
mapping(action.get("runs"), "runs").get("steps"),
"runs.steps",
);
expect([...mapping(action.get("inputs"), "inputs").keys()]).toStrictEqual(["master-key"]);
const steps = sequence(mapping(action.get("runs"), "runs").get("steps"), "runs.steps");
for (const step of steps) {
const run = step.get("run");
if (typeof run === "string") {
@@ -72,21 +62,13 @@ test("the action exposes only the master key and scopes it to preparation", asyn
const agent = findStep(steps, "id", "agent");
const post = findStep(steps, "id", "post");
findStep(steps, "id", "source");
expect(mapping(checkout.get("with"), "checkout.with").get("token")).toBe(
"${{ gitea.token }}",
);
expect(
mapping(prepare.get("env"), "prepare.env").get("BOT_AGENTS_MASTER_KEY"),
).toBe("${{ inputs.master-key }}");
expect(
JSON.stringify(Object.fromEntries(agent)).includes("BOT_AGENTS_MASTER_KEY"),
).toBe(false);
expect(
JSON.stringify(Object.fromEntries(post)).includes("BOT_AGENTS_MASTER_KEY"),
).toBe(false);
expect(mapping(agent.get("env"), "agent.env").get("GITEA_TOKEN")).toBe(
"${{ gitea.token }}",
expect(mapping(checkout.get("with"), "checkout.with").get("token")).toBe("${{ gitea.token }}");
expect(mapping(prepare.get("env"), "prepare.env").get("BOT_AGENTS_MASTER_KEY")).toBe(
"${{ inputs.master-key }}",
);
expect(JSON.stringify(Object.fromEntries(agent)).includes("BOT_AGENTS_MASTER_KEY")).toBe(false);
expect(JSON.stringify(Object.fromEntries(post)).includes("BOT_AGENTS_MASTER_KEY")).toBe(false);
expect(mapping(agent.get("env"), "agent.env").get("GITEA_TOKEN")).toBe("${{ gitea.token }}");
assert(String(post.get("if")).includes("always()"));
for (const step of [prepare, agent, post]) {
assert(String(step.get("run")).includes("steps.source.outputs.path"));
@@ -101,11 +83,7 @@ test("the source protection script stages immutable action files", async () => {
environment.set("ACTION_PATH", process.cwd());
environment.set("GITHUB_OUTPUT", outputFile);
environment.set("RUNNER_TEMP", temp);
const result = await runCommand(
"/bin/bash",
["scripts/protect-source.sh"],
environment,
);
const result = await runCommand("/bin/bash", ["scripts/protect-source.sh"], environment);
assert(result.success, result.stderr);
const output = await readFile(outputFile, "utf8");
@@ -138,9 +116,9 @@ test("the source protection script stages immutable action files", async () => {
test("module-relative runtime assets exist", async () => {
const module = new URL("../src/run/index.ts", import.meta.url);
const source = await readFile(module, "utf8");
const assets = [
...source.matchAll(/new URL\("(?<asset>[^"]+)", import\.meta\.url\)/gu),
].map(([, asset = ""]) => new URL(asset, module));
const assets = [...source.matchAll(/new URL\("(?<asset>[^"]+)", import\.meta\.url\)/gu)].map(
([, asset = ""]) => new URL(asset, module),
);
const stats = await Promise.all(
assets.map(async (asset) => {
const info = await stat(asset);
@@ -154,10 +132,7 @@ test("module-relative runtime assets exist", async () => {
test("the repository uses its trusted main action", async () => {
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.get("jobs"), "jobs").get("agent"), "jobs.agent");
const permissions = mapping(job.get("permissions"), "jobs.agent.permissions");
expect(Object.fromEntries(permissions)).toStrictEqual({
code: "write",
@@ -165,30 +140,17 @@ test("the repository uses its trusted main action", async () => {
"pull-requests": "write",
});
const steps = sequence(job.get("steps"), "jobs.agent.steps");
expect(steps.findIndex((step) => step.get("uses") === "./")).toStrictEqual(
-1,
);
const trusted = findStep(
steps,
"uses",
"https://git.capsulizers.com/commons/bot-agents@main",
);
expect(steps.findIndex((step) => step.get("uses") === "./")).toStrictEqual(-1);
const trusted = findStep(steps, "uses", "https://git.capsulizers.com/commons/bot-agents@main");
expect(mapping(trusted.get("with"), "trusted.with").get("master-key")).toBe(
"${{ secrets.BOT_AGENTS_MASTER_KEY }}",
);
expect(
JSON.stringify(Object.fromEntries(workflow)).includes(
"gitea.actor != 'bot'",
),
).toBe(true);
expect(JSON.stringify(Object.fromEntries(workflow)).includes("gitea.actor != 'bot'")).toBe(true);
});
test("CI checks every phase and the root isolation suite", async () => {
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.get("jobs"), "jobs").get("check"), "jobs.check");
const commands = sequence(job.get("steps"), "jobs.check.steps")
.map((step) => {
const run = step.get("run");
@@ -207,8 +169,7 @@ test("uses the standard Skills installer without custom discovery", async () =>
assert(runner.includes("skills add obra/superpowers"));
const removed = await stat("superpowers.ts").then(
() => false,
(error: unknown) =>
error instanceof Error && "code" in error && error.code === "ENOENT",
(error: unknown) => error instanceof Error && "code" in error && error.code === "ENOENT",
);
assert(removed, "superpowers.ts should be removed");
});
@@ -229,17 +190,12 @@ test("profile preparation does not receive provider credentials", async () => {
expect(runner.includes("prepareProfile(profile, token)")).toBe(false);
});
test("central profiles fall back from Claude to Codex to OpenCode", async () => {
const credentials: unknown = JSON.parse(
await readFile("profiles.json", "utf8"),
);
const profiles = sequence(
mapping(credentials, "profiles.json").get("profiles"),
"profiles",
);
test("central profiles fall back from Codex to Claude to OpenCode", async () => {
const credentials: unknown = JSON.parse(await readFile("profiles.json", "utf8"));
const profiles = sequence(mapping(credentials, "profiles.json").get("profiles"), "profiles");
expect(profiles.map((profile) => profile.get("type"))).toStrictEqual([
"CLAUDE",
"CODEX",
"CLAUDE",
"OPENCODE",
]);
expect(profiles[2]?.get("model")).toBe("openrouter/qwen/qwen3.8-27b");
-5
View File
@@ -5,11 +5,6 @@ import { defineConfig } from "vite-plus";
import projectLint, { projectOverrides } from "./scripts/project-lint.ts";
export default defineConfig({
fmt: {
printWidth: 80,
quoteProps: "preserve",
embeddedLanguageFormatting: "off",
},
lint: {
plugins: ["typescript", "unicorn", "oxc", "import"],
jsPlugins: [