import { types } from "node:util"; import { statSync } from "node:fs"; import { dirname, isAbsolute, resolve, sep } from "node:path"; import { canonicalPath, realPath } from "./project.ts"; import { defaultPeerRoles, definitionOf, type AdapterDefinition, type StartForm, type ProjectAdapterCatalog } from "../adapters/registry.ts"; import { isPermissionMode, type PermissionMode } from "./permission-mode.ts"; import { isReviewScope } from "./review-scope.ts"; import { isNativeModelToken } from "../adapters/model-token.ts"; export interface InstanceConfig { kind: string; roles?: string[]; start_mode?: StartForm; permission_mode?: PermissionMode; review_mode?: "fresh"; /** A fresh reviewer's review scope (#852): `code` reads the code only, `full` also runs tests and reads CI. Machine-local, tier 3. */ review_scope?: "full" | "code"; worktree?: string; readOnly?: boolean; /** Jcode instances (#685): their own native data home, and optional model selection. A headless Claude implementer also takes `model` (#844). Machine-local, never editable from settings. */ jcode_home?: string; /** Names of jcode MCP servers `ahub doctor` accepts for this instance; absent inherits the top-level list (#1621). */ jcode_mcp_allow?: string[]; provider?: string; model?: string; provider_profile?: string; } const JCODE_FIELDS = ["jcode_home", "jcode_mcp_allow", "provider", "model", "provider_profile"] as const; /** At most this many extra Jcode instances per project (#685). */ export const MAX_JCODE_INSTANCES = 8; /** A flag value jcode takes as one argv word: bounded, printable, no spaces. */ export { isNativeModelToken } from "../adapters/model-token.ts"; export type InstancesConfig = Readonly>; export interface InstanceCatalogEntry { id: string; kind: string; definition: AdapterDefinition; config?: InstanceConfig } const MAX_INSTANCES = 64; const FLOW_ROLES = new Set(["planner", "implementer", "verifier", "reviewer", "conductor"]); const PEER_ID = /^[a-z][a-z0-9-]{0,31}$/; const RESERVED = new Set(["user", "hub", "digest"]); const fail = (field: string, reason: string): never => { throw new Error(`${field}: ${reason}`); }; /** Inspect only ordinary own data descriptors; accessors, proxies, symbols and custom prototypes are not config. */ function fields(value: unknown, field: string): Record { if (!value || typeof value !== "object" || types.isProxy(value) || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value)) || Object.getOwnPropertySymbols(value).length) return fail(field, "must be a plain own-data object"); const descriptors: Record = Object.assign(Object.create(null), Object.getOwnPropertyDescriptors(value)); if (Object.values(descriptors).some(entry => !Object.hasOwn(entry, "value") || !entry.enumerable)) return fail(field, "must contain enumerable data fields only"); return descriptors; } function roles(value: unknown, field: string): string[] { if (!Array.isArray(value) || types.isProxy(value) || Object.getPrototypeOf(value) !== Array.prototype || Object.getOwnPropertySymbols(value).length) return fail(field, "must be a role array"); const descriptors: Record = Object.assign(Object.create(null), Object.getOwnPropertyDescriptors(value)); const length = descriptors.length?.value; if (!Number.isSafeInteger(length) || length > FLOW_ROLES.size || Object.keys(descriptors).length !== length + 1) return fail(field, "invalid role array"); const out: string[] = []; for (let index = 0; index < length; index++) { const descriptor = descriptors[String(index)]; if (!descriptor || !Object.hasOwn(descriptor, "value") || !descriptor.enumerable || typeof descriptor.value !== "string" || !FLOW_ROLES.has(descriptor.value) || out.includes(descriptor.value)) return fail(field, "roles must be known and unique"); out.push(descriptor.value); } return out; } /** A jcode MCP allowlist (#1621): an array of nonempty, control-free names of at most 256 bytes, at most 64 of them. */ export function mcpAllowNames(value: unknown, field: string): string[] { if (!Array.isArray(value) || value.length > 64 || value.some(name => typeof name !== "string" || !name.trim() || Buffer.byteLength(name) > 256 || /\p{Cc}/u.test(name))) return fail(field, "must be an array of at most 64 nonempty control-free server names"); return [...value] as string[]; } /** The Jcode-only fields of one declaration (#685). Only the validated values are copied; nothing is read twice. */ function jcodeInstanceFields(entry: Record, path: string): Partial { const home: unknown = entry.jcode_home?.value; if (typeof home !== "string" || !isAbsolute(home) || !home.trim() || Buffer.byteLength(home) > 4096 || /\p{Cc}/u.test(home)) return fail(`${path}.jcode_home`, "is required: a nonempty control-free absolute path of at most 4096 UTF-8 bytes, other than the base Jcode's home"); const out: Partial = { jcode_home: home }; for (const key of ["provider", "model", "provider_profile"] as const) { const present = entry[key]; if (!present) continue; const word: unknown = present.value; if (!isNativeModelToken(word)) return fail(`${path}.${key}`, "must be one bounded printable word without spaces"); out[key] = word; } if (entry.jcode_mcp_allow) out.jcode_mcp_allow = mcpAllowNames(entry.jcode_mcp_allow.value, `${path}.jcode_mcp_allow`); if (entry.start_mode && entry.start_mode.value !== "headless") return fail(`${path}.start_mode`, "a Jcode instance starts headless"); return out; } /** * The directory a home names, as the disk sees it (#685 review): symlinks and system aliases (`/tmp` and `/private/tmp`) resolved with * `realPath` (never `realpathSync`, which Bun fails on a backslash path), and for a home that does not exist yet the nearest existing * ancestor resolved the same way. Compared case-folded when the volume folds case, so a case-only alias is the same home. */ function canonicalHome(home: string): { path: string; key: string; identity?: string } { let path: string; try { path = realPath(home); } catch { path = canonicalPath(home); } const stat = (target: string) => { try { return statSync(target); } catch { return undefined; } }; let existing = path; while (!stat(existing) && dirname(existing) !== existing) existing = dirname(existing); const info = stat(path), anchor = stat(existing); const swapped = existing.replace(/[A-Za-z]/g, letter => letter === letter.toLowerCase() ? letter.toUpperCase() : letter.toLowerCase()); const alias = swapped !== existing ? stat(swapped) : undefined; const folds = !!anchor && !!alias && alias.ino === anchor.ino && alias.dev === anchor.dev; return { path, key: folds ? path.toLowerCase() : path, ...(info ? { identity: `${info.dev}:${info.ino}` } : {}) }; } /** * One native data home per Jcode (#685): an instance may not use the base Jcode's home, another instance's, or one nested * inside either (their stores would overlap), however the path is spelled: a symlink, a system alias or a case-only alias of one * is the same home. Run once with the loaded base `jcode_home`. */ export function checkJcodeInstanceHomes(declarations: InstancesConfig | undefined, baseHome: string): void { const homes: { id: string; key: string; identity?: string }[] = [{ id: "the base Jcode", ...canonicalHome(baseHome) }]; for (const [id, config] of Object.entries(declarations ?? {})) { if (config.jcode_home === undefined) continue; // only a native-home kind carries one const home = canonicalHome(config.jcode_home); for (const other of homes) { const label = other.id === "the base Jcode" ? "base" : other.id; if (home.key === other.key || (home.identity !== undefined && home.identity === other.identity)) return fail(`instances.${id}.jcode_home`, other.id === "the base Jcode" ? "must differ from the base Jcode's home" : `is the same home as ${label}`); if (home.key.startsWith(`${other.key}${sep}`) || other.key.startsWith(`${home.key}${sep}`)) return fail(`instances.${id}.jcode_home`, `is nested inside or around ${other.id === "the base Jcode" ? "the base Jcode's home" : `${label}'s home`}`); } homes.push({ id, ...home }); } } /** Planner/reviewer combinations plan without a writing role; mixed implementer/verifier holders keep their native behavior. */ export function isPlannerOnly(roles: readonly string[]): boolean { return roles.includes("planner") && !roles.includes("implementer") && !roles.includes("verifier"); } /** Declaration support is explicit policy, independent of the native MCP binding mechanism. */ export function supportsHeadlessInstances(definition: AdapterDefinition): boolean { return definition.instances?.mode === "headless" && !!definition.start.create && definition.start.forms.includes("headless"); } /** Resolve project declarations only through their captured, explicit catalog. */ export function instanceDefinitionOf(id: string, declarations: InstancesConfig | undefined, catalog: ProjectAdapterCatalog): AdapterDefinition | undefined { return catalog.definitionOf(id, declarations); } /** Pure I2 validation; physical worktree and startup authority stay host-bound. */ export function validateInstances(raw: unknown, catalog: ProjectAdapterCatalog): InstancesConfig { const resolve = catalog.definitionOf; const result: Record = Object.create(null); if (raw === undefined) return Object.freeze(result); const declarations = fields(raw, "instances"); let jcodeCount = 0; if (Object.keys(declarations).length > MAX_INSTANCES) return fail("instances", "at most 64 extra instances are supported"); for (const [id, descriptor] of Object.entries(declarations)) { if (!PEER_ID.test(id) || RESERVED.has(id) || resolve(id)) return fail("instances", "ids must be nonreserved extra instance ids, not builtin ids"); const path = `instances.${id}`, entry = fields(descriptor.value, path); const declaredKind: unknown = entry.kind?.value; const jcodeFields = typeof declaredKind === "string" && resolve(declaredKind)?.instances?.nativeHome === true; // #844: a kind whose headless variant declares `instances.modelSelect` may name its model; no other kind but Jcode has the field. const modelSelect = typeof declaredKind === "string" && resolve(declaredKind)?.headlessVariant?.instances?.modelSelect === true; if (Object.keys(entry).some(key => !["kind", "roles", "start_mode", "permission_mode", "worktree", "review_mode", "readOnly", "review_scope", ...(jcodeFields ? JCODE_FIELDS : []), ...(modelSelect ? ["model"] : [])].includes(key))) return fail(path, "unsupported field"); const kind: unknown = entry.kind?.value; if (typeof kind !== "string") return fail(`${path}.kind`, "must name a native kind"); const definition = resolve(kind), prefix = `${kind}-`; if (!definition) return fail(`${path}.kind`, "unknown native kind (a live startup catalog is required for external instances)"); const moduleInstance = catalog.externalDefinitions.some(item => item.kind === kind); let moduleRoles: string[] | undefined; if (moduleInstance) { const optIn = definition.headlessInstances; if (!optIn || optIn.form !== "headless" || !supportsHeadlessInstances(definition)) return fail(`${path}.kind`, "external module has not opted into headless instances"); if (entry.review_mode || entry.review_scope) return fail(path, "external instances do not have fresh or isolated reviewer capabilities"); if (entry.start_mode && entry.start_mode.value !== "headless") return fail(`${path}.start_mode`, "external instances start headless only"); if (!entry.worktree) return fail(`${path}.worktree`, "every external instance requires its own managed worktree"); const allowedRoles: readonly string[] = optIn.roles; const requestedRoles = entry.roles ? roles(entry.roles.value, `${path}.roles`) : definition.roles.filter(role => allowedRoles.includes(role)); if (!requestedRoles.length || requestedRoles.some(role => !allowedRoles.includes(role) || !definition.roles.includes(role))) return fail(`${path}.roles`, "roles must fit the external module's explicit instance subset and kind ceiling"); moduleRoles = requestedRoles; if (entry.permission_mode) { const mode = entry.permission_mode.value; if (!isPermissionMode(mode) || !definition.permission.genericAcp?.modes?.[mode]) return fail(`${path}.permission_mode`, "external native adapter has no mapping for this permission mode"); } } if (!id.startsWith(prefix) || !/^[a-z0-9][a-z0-9-]*$/.test(id.slice(prefix.length))) return fail(path, "id must be -"); const declaredRoles = entry.roles ? roles(entry.roles.value, `${path}.roles`) : moduleRoles ?? []; const reviewer = (definition.reviewerVariant ?? definition).reviewer; const reviewerOnly = entry.start_mode?.value === "headless" && declaredRoles.length === 1 && declaredRoles[0] === "reviewer"; if (entry.review_mode && (entry.review_mode.value !== "fresh" || !reviewerOnly || !reviewer)) return fail(`${path}.review_mode`, "fresh requires reviewer-only roles, headless mode and a declared fresh-review capability"); const freshReviewer = reviewerOnly && !!reviewer && (reviewer.declaration === "automatic" || entry.review_mode?.value === "fresh"); if (definition.routing?.reviewOnly && !freshReviewer) return fail(path, "a review-only kind requires headless roles exactly [\"reviewer\"]"); if (freshReviewer && entry.worktree) return fail(`${path}.worktree`, "a fresh reviewer reads the project checkout: worktree is not supported"); if (freshReviewer && entry.permission_mode) return fail(`${path}.permission_mode`, "a fresh reviewer has a fixed read-only policy"); // An external instance runs only in the person's terminal; its definition bounds the declared roles. const external = definition.instances?.mode === "external"; const headlessWriter = entry.start_mode?.value === "headless" && !!definition.headlessVariant && declaredRoles.includes("implementer") && declaredRoles.every(role => role === "implementer" || role === "verifier"); if (headlessWriter && !entry.worktree) return fail(`${path}.worktree`, "a headless implementer needs its own worktree"); if (headlessWriter && entry.permission_mode && entry.permission_mode.value !== "ask" && entry.permission_mode.value !== "ask-when-needed") return fail(`${path}.permission_mode`, "a headless implementer permits only ask or ask-when-needed"); const runtime = freshReviewer ? definition.reviewerVariant ?? definition : headlessWriter ? definition.headlessVariant! : definition; const unavailableReviewer = freshReviewer && !!(definition.reviewerVariant ?? definition).reviewer?.unavailable; if (!unavailableReviewer && runtime.instances?.mode !== "external" && !supportsHeadlessInstances(runtime)) return fail(`${path}.kind`, definition.reviewerVariant ? 'unsupported; this kind only declares headless reviewer instances with roles exactly ["reviewer"]' : "unsupported; explicit external instance policy or a headless instance policy with a headless factory is required"); if (declaredRoles.includes("planner") && definition.projection?.plannerEligible !== true) return fail(`${path}.roles`, "this kind cannot plan"); if (external) { const declared = entry.roles ? roles(entry.roles.value, `${path}.roles`) : []; // #223: a headless one is the kind's reviewer variant, one fresh hub-run session per review request. if (headlessWriter) { // Runtime policy and worktree/permission checks above govern this builtin-only writer variant. } else if (entry.start_mode && definition.reviewerVariant) { const reviewerRoles = declared.length === 1 && declared[0] === "reviewer"; if (!reviewerRoles) return fail(`${path}.roles`, "a headless channel-kind instance is a reviewer: roles must be exactly [\"reviewer\"]"); if (entry.worktree) return fail(path, "a headless reviewer reads the project checkout: worktree is not supported"); } else { if (entry.start_mode) return fail(`${path}.start_mode`, "a channel instance starts only from the person's terminal (ahub --as ); a headless reviewer declares roles [\"reviewer\"] and start_mode \"headless\""); const allowed = definition.instances?.roles ?? definition.roles; if (!declared.length || declared.some(role => !allowed.includes(role))) return fail(`${path}.roles`, `a channel instance must declare its roles within: ${allowed.join(", ")}`); // #525 R1: an implementer or verifier writes, so it needs its own worktree; a planner or reviewer reads the project checkout. const writes = declared.includes("implementer") || declared.includes("verifier"); if (writes && !entry.worktree) return fail(`${path}.worktree`, "an implementer or verifier channel instance needs its own worktree"); if (!writes && entry.worktree) return fail(`${path}.worktree`, "a planner or reviewer channel instance reads the project checkout: worktree is not supported"); } } else { const allowed = runtime.instances?.roles; if (allowed && (declaredRoles.length ? declaredRoles : runtime.roles).some(role => !allowed.includes(role))) return fail(`${path}.roles`, "roles must fit the definition's instance policy"); } if (runtime.start.daemonPort === "codex-appserver" && isPlannerOnly(declaredRoles) && entry.worktree) return fail(`${path}.worktree`, "a planner-only app-server instance plans on the project checkout; worktree is not supported"); if (entry.readOnly) { if (typeof entry.readOnly.value !== "boolean") return fail(`${path}.readOnly`, "must be a boolean"); if (!runtime.permission.genericAcp?.readOnly) return fail(`${path}.readOnly`, "native adapter has no verified read-only mode"); if (entry.readOnly.value && entry.permission_mode) return fail(`${path}.permission_mode`, "read-only instances cannot select a permission mode"); } const value: InstanceConfig = { kind, ...(entry.review_mode ? { review_mode: "fresh" as const } : {}) }; if (jcodeFields) { if (++jcodeCount > MAX_JCODE_INSTANCES) return fail("instances", `at most ${MAX_JCODE_INSTANCES} extra Jcode instances are supported per project`); Object.assign(value, jcodeInstanceFields(entry, path)); } if (entry.model && modelSelect) { if (!headlessWriter) return fail(`${path}.model`, "only a headless implementer takes a model"); const word: unknown = entry.model.value; if (!isNativeModelToken(word)) return fail(`${path}.model`, "must be one bounded printable word without spaces"); value.model = word; } if (entry.review_scope) { if (!freshReviewer) return fail(`${path}.review_scope`, "only a fresh reviewer instance has a review scope"); if (!isReviewScope(entry.review_scope.value)) return fail(`${path}.review_scope`, 'must be "code" or "full"'); value.review_scope = entry.review_scope.value; } if (entry.readOnly) value.readOnly = entry.readOnly.value as boolean; if (entry.roles || moduleRoles) { value.roles = entry.roles ? roles(entry.roles.value, `${path}.roles`) : [...moduleRoles!]; Object.freeze(value.roles); } if (entry.start_mode) { if (entry.start_mode.value !== "headless") return fail(`${path}.start_mode`, "I2 extra instances require headless mode"); value.start_mode = "headless"; } if (entry.permission_mode) { if (!isPermissionMode(entry.permission_mode.value)) return fail(`${path}.permission_mode`, "must be ask, ask-when-needed or never-ask"); value.permission_mode = entry.permission_mode.value; } if (entry.worktree) { const worktree: unknown = entry.worktree.value; if (typeof worktree !== "string" || !worktree.trim() || Buffer.byteLength(worktree) > 4096 || /\p{Cc}/u.test(worktree)) return fail(`${path}.worktree`, "must be a nonempty control-free path of at most 4096 UTF-8 bytes"); value.worktree = worktree; } result[id] = Object.freeze(value); } return Object.freeze(result); } /** Each call derives a fresh project-local projection, without registration or suffix discovery. */ export function instanceCatalog(declarations: InstancesConfig | undefined, catalog: ProjectAdapterCatalog): readonly InstanceCatalogEntry[] { const instances = validateInstances(declarations, catalog); return Object.freeze([ ...catalog.definitions.map(definition => Object.freeze({ id: definition.kind, kind: definition.kind, definition })), ...Object.entries(instances).map(([id, config]) => Object.freeze({ id, kind: config.kind, definition: catalog.definitionOf(id, instances)!, config })), ]); } export function instancePeerIds(declarations: InstancesConfig | undefined, catalog: ProjectAdapterCatalog): string[] { return instanceCatalog(declarations, catalog).map(entry => entry.id); } export function instanceDefaultRoles(declarations: InstancesConfig | undefined, includeOptional: boolean, catalog: ProjectAdapterCatalog): Record { const result = defaultPeerRoles(includeOptional); for (const definition of catalog.definitions) if (!definitionOf(definition.kind) && (includeOptional || !definition.optional)) result[definition.kind] = [...definition.roles]; const instances = validateInstances(declarations, catalog); for (const [id, config] of Object.entries(instances)) result[id] = [...(config.roles ?? catalog.definitionOf(id, instances)!.roles)]; return result; } /** One precedence rule for startup, native launch and recovery; ordinary roles may use the instance id or its kind. */ export function effectiveInstanceRoles(id: string, declarations: InstancesConfig | undefined, policyRoles: Readonly>, catalog: ProjectAdapterCatalog): string[] { const definition = catalog.definitionOf(id, declarations); if (!definition) throw new Error(`${id}: no declared native instance`); const declaration = declarations && Object.hasOwn(declarations, id) ? declarations[id] : undefined; const ownRoles = (key: string): readonly string[] | undefined => Object.hasOwn(policyRoles, key) ? policyRoles[key] : undefined; const roles = declaration?.roles ?? ownRoles(id) ?? ownRoles(definition.kind) ?? definition.roles; // A module's current runtime policy cannot widen its captured opt-in, including id-keyed role overrides. if (declaration && catalog.externalDefinitions.some(item => item.kind === definition.kind)) { const allowed: readonly string[] = definition.headlessInstances?.roles ?? []; return roles.filter(role => allowed.includes(role) && definition.roles.includes(role) && role !== "planner" && role !== "conductor"); } // #525 R1: a roles entry keyed by an instance id skips loadConductorPolicy's kind check, so planner is gated here too. return roles.filter(role => role !== "planner" || definition.projection?.plannerEligible === true); }