@hilbras/omninode 2.0.0-alpha.14 → 2.0.0-alpha.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/index.ts","../../src/version.ts","../../src/config/schema.ts","../../src/config/secrets.ts","../../src/config/loader.ts","../../src/config/default.ts","../../src/cli/commands/init.ts","../../src/cli/commands/project.ts","../../src/registry/index.ts","../../src/cli/commands/shared.ts","../../src/agents/process/index.ts","../../src/agent-protocol/version.ts","../../src/agent-protocol/types.ts","../../src/agent-protocol/codec.ts","../../src/agent-protocol/handshake.ts","../../src/agent-protocol/session.ts","../../src/agents/cwd.ts","../../src/agents/env.ts","../../src/agents/adapters.ts","../../src/agents/registry.ts","../../src/agents/factory.ts","../../src/roles/index.ts","../../src/persistence/json-file-store.ts","../../src/memory/base.ts","../../src/memory/local.ts","../../src/memory/remembera.ts","../../src/memory/factory.ts","../../src/memory/service.ts","../../src/pipelines/store.ts","../../src/tasks/store.ts","../../src/cli/commands/inspect.ts","../../src/cli/commands/providers.ts","../../src/cli/commands/models.ts","../../src/cli/commands/agents.ts","../../src/cli/commands/roles.ts","../../src/tasks/engine.ts","../../src/audit/index.ts","../../src/tasks/engine-factory.ts","../../src/cli/commands/tasks.ts","../../src/reports/aggregate.ts","../../src/reports/schema.ts","../../src/reports/extract.ts","../../src/reports/service.ts","../../src/reports/store.ts","../../src/cli/commands/reports.ts","../../src/pipelines/engine.ts","../../src/planner/heuristic.ts","../../src/planner/model.ts","../../src/planner/schema.ts","../../src/planner/context.ts","../../src/planner/store.ts","../../src/planner/factory.ts","../../src/pipelines/engine-factory.ts","../../src/cli/commands/pipelines.ts","../../src/cli/commands/memory.ts","../../src/cli/commands/plan.ts","../../src/cli/commands/status.ts","../../src/cli/commands/audit.ts","../../src/persistence/index.ts","../../src/cli/commands/migrate.ts","../../src/cli/commands/security.ts"],"sourcesContent":["import { pathToFileURL } from \"node:url\";\nimport { realpathSync } from \"node:fs\";\nimport { Command } from \"commander\";\nimport { OMNINODE_VERSION } from \"../version.js\";\nimport { isOmniNodeError } from \"../errors/index.js\";\nimport { configureLogger } from \"../logger/index.js\";\nimport { findConfigFile, loadConfig } from \"../config/index.js\";\nimport { registerInitCommand } from \"./commands/init.js\";\nimport { registerProjectCommands } from \"./commands/project.js\";\nimport { registerProviderCommands } from \"./commands/providers.js\";\nimport { registerModelsCommand } from \"./commands/models.js\";\nimport { registerAgentCommands } from \"./commands/agents.js\";\nimport { registerRoleCommands } from \"./commands/roles.js\";\nimport { registerTaskCommands } from \"./commands/tasks.js\";\nimport { registerReportCommands } from \"./commands/reports.js\";\nimport { registerPipelineCommands, registerRunAlias } from \"./commands/pipelines.js\";\nimport { registerMemoryCommands } from \"./commands/memory.js\";\nimport { registerPlanCommands } from \"./commands/plan.js\";\nimport { registerStatusCommand } from \"./commands/status.js\";\nimport { registerAuditCommand } from \"./commands/audit.js\";\nimport { registerMigrateCommand } from \"./commands/migrate.js\";\nimport { registerSecurityCommand } from \"./commands/security.js\";\n\nexport function createProgram(): Command {\n const program = new Command();\n\n program\n .name(\"omninode\")\n .description(\n \"Provider-agnostic multi-AI orchestration platform: coordinate CLI agents, \" +\n \"AI providers, memory, roles, reports and planning in one execution system.\",\n )\n .version(OMNINODE_VERSION, \"-v, --version\", \"Print the OmniNode version.\");\n\n registerInitCommand(program);\n registerProjectCommands(program);\n registerProviderCommands(program);\n registerAgentCommands(program);\n registerRoleCommands(program);\n registerTaskCommands(program);\n registerReportCommands(program);\n registerModelsCommand(program);\n registerPipelineCommands(program);\n registerMemoryCommands(program);\n registerPlanCommands(program);\n registerStatusCommand(program);\n registerAuditCommand(program);\n registerMigrateCommand(program);\n registerSecurityCommand(program);\n registerRunAlias(program);\n\n return program;\n}\n\nfunction applyLoggingConfig(): void {\n // Best effort: `init` and `--help` must work without a valid configuration.\n try {\n if (findConfigFile()) {\n const logging = loadConfig().logging;\n if (logging) configureLogger(logging);\n }\n } catch {\n // Configuration problems surface when the command actually needs it.\n }\n}\n\nexport async function run(argv: string[]): Promise<void> {\n applyLoggingConfig();\n const program = createProgram();\n try {\n await program.parseAsync(argv);\n } catch (error) {\n handleError(error);\n }\n}\n\nexport function handleError(error: unknown): never {\n if (isOmniNodeError(error)) {\n console.error(`error: [${error.code}] ${error.message}`);\n if (error.details !== undefined) {\n console.error(JSON.stringify(error.details, null, 2));\n }\n process.exit(1);\n }\n console.error(error instanceof Error ? error.message : String(error));\n process.exit(1);\n}\n\nconst entry = process.argv[1]\n ? pathToFileURL(realpathSync(process.argv[1])).href\n : \"\";\nif (import.meta.url === entry) {\n run(process.argv).catch((error) => handleError(error));\n}\n","export const OMNINODE_VERSION = \"2.0.0-alpha.14\";\n","/**\n * Configuration schema. The project file (omninode.yaml) uses snake_case keys\n * as shown in DEVELOPMENT_PLAN.md §7 and §23; the loader maps them onto the\n * camelCase TypeScript contracts in src/types.\n */\nimport { z } from \"zod\";\n\nexport const providerConfigSchema = z\n .object({\n name: z.string().min(1),\n type: z.enum([\"openai-compatible\", \"omnihilbras\", \"openrouter\", \"local\", \"custom\"]),\n base_url: z.string().url(),\n api_key_env_var: z.string().min(1).optional(),\n timeout_ms: z.number().int().positive().optional(),\n headers: z.record(z.string()).optional(),\n enabled: z.boolean().optional(),\n metadata: z.record(z.unknown()).optional(),\n })\n .strict();\n\nexport const agentConfigSchema = z\n .object({\n name: z.string().min(1),\n /** \"cli\" agents communicate over stdin/stdout (process adapter). */\n type: z.enum([\"cli\", \"native\", \"process\"]).default(\"cli\"),\n command: z.string().min(1).optional(),\n args: z.array(z.string()).optional(),\n cwd: z.string().optional(),\n env: z.record(z.string()).optional(),\n input_mode: z.enum([\"stdin\", \"arg\", \"protocol\"]).default(\"stdin\"),\n timeout_ms: z.number().int().positive().optional(),\n inherit_env: z.boolean().optional(),\n env_policy: z.enum([\"inherit\", \"allowlist\", \"denylist\", \"explicit\"]).optional(),\n env_allowlist: z.array(z.string()).optional(),\n env_denylist: z.array(z.string()).optional(),\n max_output_bytes: z.number().int().positive().optional(),\n allow_external_cwd: z.boolean().optional(),\n metadata: z.record(z.unknown()).optional(),\n })\n .strict();\n\nexport const roleConfigSchema = z\n .object({\n id: z\n .string()\n .min(1)\n .regex(/^[a-z0-9][a-z0-9-]*$/, \"role id must be kebab-case\"),\n name: z.string().min(1),\n description: z.string().optional(),\n responsibilities: z.array(z.string()).default([]),\n expected_outputs: z.array(z.string()).default([]),\n preferred_agents: z.array(z.string()).optional(),\n system_prompt: z.string().optional(),\n metadata: z.record(z.unknown()).optional(),\n })\n .strict();\n\nexport const pipelineStepConfigSchema = z\n .object({\n id: z.string().min(1),\n kind: z.enum([\"research\", \"collect\", \"analyze\", \"plan\", \"execute\", \"custom\"]),\n agents: z.array(z.string()).optional(),\n agent: z.string().optional(),\n model: z.string().optional(),\n depends_on: z.array(z.string()).optional(),\n retries: z.number().int().min(0).max(10).optional(),\n condition: z.enum([\"always\", \"on-success\", \"on-failure\"]).optional(),\n /** Constraints passed to the planner for plan steps (§15). */\n constraints: z.array(z.string()).optional(),\n })\n .strict();\n\nexport const pipelineConfigSchema = z\n .object({\n id: z\n .string()\n .min(1)\n .regex(/^[a-z0-9][a-z0-9-]*$/, \"pipeline id must be kebab-case\"),\n name: z.string().optional(),\n objective: z.string().optional(),\n role: z.string().optional(),\n steps: z.array(pipelineStepConfigSchema).min(1),\n })\n .strict();\n\nexport const plannerConfigSchema = z\n .object({\n kind: z.enum([\"model\", \"heuristic\"]).default(\"model\"),\n model: z.string().optional(),\n instruction: z.string().optional(),\n })\n .strict();\n\nexport const projectConfigSchema = z\n .object({\n name: z.string().min(1),\n providers: z.array(providerConfigSchema).default([]),\n agents: z.array(agentConfigSchema).default([]),\n roles: z.array(roleConfigSchema).default([]),\n pipelines: z.array(pipelineConfigSchema).default([]),\n planner: plannerConfigSchema.optional(),\n memory: z\n .object({\n provider: z.string().min(1).default(\"local\"),\n base_url: z.string().url().optional(),\n api_key_env_var: z.string().min(1).optional(),\n /** When true, memory failures fail tasks instead of being tolerated (§12). */\n required: z.boolean().optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\n\nexport const appConfigSchema = z\n .object({\n project: projectConfigSchema,\n logging: z\n .object({\n level: z.enum([\"debug\", \"info\", \"warn\", \"error\"]),\n format: z.enum([\"text\", \"json\"]).optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\n\nexport type ProviderConfigYaml = z.infer<typeof providerConfigSchema>;\nexport type AgentConfigYaml = z.infer<typeof agentConfigSchema>;\nexport type RoleConfigYaml = z.infer<typeof roleConfigSchema>;\nexport type PipelineConfigYaml = z.infer<typeof pipelineConfigSchema>;\nexport type PipelineStepConfigYaml = z.infer<typeof pipelineStepConfigSchema>;\nexport type PlannerConfigYaml = z.infer<typeof plannerConfigSchema>;\nexport type ProjectConfigYaml = z.infer<typeof projectConfigSchema>;\nexport type AppConfigYaml = z.infer<typeof appConfigSchema>;\n","/**\n * Inline secret detection (roadmap §17, Secrets).\n *\n * OmniNode configuration must never contain literal credentials — only\n * environment-variable *references*. This scanner runs before the config is\n * parsed and reports anything that looks like an inline secret, so the file\n * is rejected before it can be committed or persisted.\n */\n\nexport interface SecretFinding {\n /** 1-based line number in the source. */\n line: number;\n /** The offending key, e.g. `api_key`. */\n key: string;\n /** Redacted excerpt — never echoes the value. */\n excerpt: string;\n}\n\n/** Keys that are references or placeholders, not secrets. */\nconst SAFE_KEY_SUFFIXES = [\"_env\", \"_env_var\", \"_file\", \"_path\", \"_ref\", \"_id\", \"_url\", \"_command\"];\n\nconst SECRET_KEY = /^\\s*([A-Za-z0-9_-]*(?:api[_-]?key|token|password|passwd|secret|credential)[A-Za-z0-9_-]*)\\s*:\\s*(.*)$/i;\n\n/** Values that are clearly references, not credentials. */\nconst SAFE_VALUE = /^\\s*(?:\\$\\{[^}]*\\}|\\$[A-Z_][A-Z0-9_]*|<[^>]*>|\"\"|''|null|~)\\s*$/i;\n\nexport function scanForInlineSecrets(source: string): SecretFinding[] {\n const findings: SecretFinding[] = [];\n source.split(\"\\n\").forEach((line, index) => {\n const trimmed = line.trim();\n if (trimmed.startsWith(\"#\")) return; // comments are not credentials\n const match = SECRET_KEY.exec(line);\n if (!match) return;\n const key = match[1] ?? \"\";\n const rawValue = (match[2] ?? \"\").trim().replace(/,\\s*$/, \"\");\n const keyIsReference = SAFE_KEY_SUFFIXES.some((suffix) => key.toLowerCase().endsWith(suffix));\n if (keyIsReference) return;\n const value = rawValue.replace(/^[\"']|[\"']$/g, \"\");\n if (value.length === 0 || SAFE_VALUE.test(rawValue)) return;\n // Very short values are almost always placeholders, not credentials.\n if (value.length < 8) return;\n findings.push({\n line: index + 1,\n key,\n excerpt: `${key}: ${value.slice(0, 3)}… (${value.length} chars, redacted)`,\n });\n });\n return findings;\n}\n\n/** Formats findings as an actionable configuration error message. */\nexport function describeSecretFindings(file: string, findings: SecretFinding[]): string {\n const lines = findings.map((f) => ` line ${f.line}: ${f.excerpt}`).join(\"\\n\");\n return (\n `${file} appears to contain ${findings.length} inline secret(s):\\n${lines}\\n` +\n `OmniNode never stores credentials in configuration. Replace each value with an ` +\n `environment-variable reference, e.g. api_key_env_var: MY_API_KEY.`\n );\n}\n","/**\n * Configuration loader: discovers omninode.yaml, expands ${ENV_VAR}\n * references (so credentials never live in project files, §24), validates it\n * and maps it onto the core TypeScript contracts.\n */\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { parse as parseYaml } from \"yaml\";\nimport { ConfigError } from \"../errors/index.js\";\nimport { describeSecretFindings, scanForInlineSecrets } from \"./secrets.js\";\nimport type { AgentConfig, AgentIntegrationType } from \"../types/agent.js\";\nimport type { ProviderConfig } from \"../types/provider.js\";\nimport type { RoleDefinition } from \"../types/role.js\";\nimport type { LogLevel } from \"../logger/index.js\";\nimport { appConfigSchema } from \"./schema.js\";\nimport type { AgentConfigYaml, PipelineConfigYaml, ProviderConfigYaml, RoleConfigYaml } from \"./schema.js\";\nimport type { PipelineDefinition } from \"../types/pipeline.js\";\n\nconst CONFIG_FILENAMES = [\"omninode.yaml\", \"omninode.yml\", \"omninode.json\"];\n\nexport interface AppConfig {\n project: {\n name: string;\n providers: ProviderConfig[];\n agents: AgentConfig[];\n roles: RoleDefinition[];\n pipelines: PipelineDefinition[];\n planner?: {\n kind: \"model\" | \"heuristic\";\n model?: string;\n instruction?: string;\n };\n memory?: {\n provider: string;\n baseUrl?: string;\n apiKeyEnvVar?: string;\n required?: boolean;\n };\n };\n logging?: {\n level: LogLevel;\n };\n}\n\nexport interface LoadConfigOptions {\n /** Explicit path; otherwise omninode.yaml/yml/json is looked up in the given directory. */\n path?: string;\n directory?: string;\n /** Environment used for ${VAR} expansion; defaults to process.env. */\n env?: Record<string, string | undefined>;\n}\n\nexport function findConfigFile(directory = process.cwd()): string | undefined {\n for (const filename of CONFIG_FILENAMES) {\n const candidate = `${directory}/${filename}`;\n if (existsSync(candidate)) return candidate;\n }\n return undefined;\n}\n\n/**\n * Replaces ${VAR} and ${VAR:-fallback} references. Unset variables without a\n * fallback abort loading: a half-resolved config could silently misroute\n * authentication.\n */\nexport function expandEnvRefs(\n text: string,\n env: Record<string, string | undefined>,\n source = \"config\",\n): string {\n return text.replace(\n /\\$\\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\\}/g,\n (_match, name: string, fallback?: string) => {\n const value = env[name] ?? fallback;\n if (value === undefined) {\n throw new ConfigError(\n \"CONFIG_INVALID\",\n `Environment variable \"${name}\" is referenced in ${source} but is not set and has no default.`,\n );\n }\n return value;\n },\n );\n}\n\nexport function loadConfig(options: LoadConfigOptions = {}): AppConfig {\n const env = options.env ?? process.env;\n const path = options.path ?? (options.directory ? findConfigFile(options.directory) : findConfigFile());\n if (!path) {\n throw new ConfigError(\n \"CONFIG_NOT_FOUND\",\n \"No omninode.yaml found. Run `omninode init` to create one, or pass an explicit path.\",\n );\n }\n\n const raw = readFileSync(path, \"utf8\");\n // §13 Security: refuse inline credentials before anything is persisted.\n const secretFindings = scanForInlineSecrets(raw);\n if (secretFindings.length > 0) {\n throw new ConfigError(\"CONFIG_INVALID\", describeSecretFindings(path, secretFindings));\n }\n const expanded = expandEnvRefs(raw, env, path);\n\n let data: unknown;\n try {\n data = parseYaml(expanded);\n } catch (error) {\n throw new ConfigError(\"CONFIG_INVALID\", `Failed to parse ${path}.`, { cause: error });\n }\n\n const parsed = appConfigSchema.safeParse(data);\n if (!parsed.success) {\n const issues = parsed.error.issues.map((issue) => {\n const location = issue.path.length > 0 ? issue.path.join(\".\") : \"(root)\";\n return `${location}: ${issue.message}`;\n });\n throw new ConfigError(\"CONFIG_INVALID\", `Invalid configuration in ${path}.`, {\n details: { issues },\n });\n }\n\n return toAppConfig(parsed.data);\n}\n\nfunction toAppConfig(yaml: ReturnType<typeof appConfigSchema.parse>): AppConfig {\n return {\n project: {\n name: yaml.project.name,\n providers: yaml.project.providers.map(toProviderConfig),\n agents: yaml.project.agents.map(toAgentConfig),\n roles: yaml.project.roles.map(toRoleDefinition),\n pipelines: yaml.project.pipelines.map(toPipelineDefinition),\n ...(yaml.project.planner !== undefined\n ? {\n planner: {\n kind: yaml.project.planner.kind,\n model: yaml.project.planner.model,\n instruction: yaml.project.planner.instruction,\n },\n }\n : {}),\n ...(yaml.project.memory !== undefined\n ? {\n memory: {\n provider: yaml.project.memory.provider,\n baseUrl: yaml.project.memory.base_url,\n apiKeyEnvVar: yaml.project.memory.api_key_env_var,\n required: yaml.project.memory.required,\n },\n }\n : {}),\n },\n ...(yaml.logging !== undefined ? { logging: yaml.logging } : {}),\n };\n}\n\nfunction toPipelineDefinition(raw: PipelineConfigYaml): PipelineDefinition {\n return {\n id: raw.id,\n name: raw.name,\n objective: raw.objective,\n role: raw.role,\n steps: raw.steps.map((step) => ({\n id: step.id,\n kind: step.kind,\n agents: step.agents,\n agent: step.agent,\n model: step.model,\n dependsOn: step.depends_on,\n retries: step.retries,\n condition: step.condition,\n constraints: step.constraints,\n })),\n };\n}\n\nfunction toProviderConfig(raw: ProviderConfigYaml): ProviderConfig {\n return {\n name: raw.name,\n type: raw.type,\n baseUrl: raw.base_url,\n apiKeyEnvVar: raw.api_key_env_var,\n timeoutMs: raw.timeout_ms,\n headers: raw.headers,\n enabled: raw.enabled,\n metadata: raw.metadata,\n };\n}\n\nfunction toAgentConfig(raw: AgentConfigYaml): AgentConfig {\n const integration: AgentIntegrationType =\n raw.type === \"native\" ? \"native\" : \"process\";\n return {\n name: raw.name,\n integration,\n command: raw.command,\n args: raw.args,\n cwd: raw.cwd,\n env: raw.env,\n inputMode: raw.input_mode,\n timeoutMs: raw.timeout_ms,\n inheritEnv: raw.inherit_env,\n envPolicy: raw.env_policy,\n envAllowlist: raw.env_allowlist,\n envDenylist: raw.env_denylist,\n maxOutputBytes: raw.max_output_bytes,\n allowExternalCwd: raw.allow_external_cwd,\n metadata: raw.metadata,\n };\n}\n\nfunction toRoleDefinition(raw: RoleConfigYaml): RoleDefinition {\n return {\n id: raw.id,\n name: raw.name,\n description: raw.description,\n responsibilities: raw.responsibilities,\n expectedOutputs: raw.expected_outputs,\n preferredAgents: raw.preferred_agents,\n systemPrompt: raw.system_prompt,\n metadata: raw.metadata,\n };\n}\n\n","/** Template written by `omninode init` (§22, §23). */\n\nexport function defaultProjectConfigYaml(projectName = \"My Project\"): string {\n return `project:\n name: ${projectName}\n\n # Providers connect OmniNode to AI model gateways (Phase 1+).\n # Credentials are referenced by environment variable, never stored in this file.\n providers: []\n # - name: my-gateway\n # type: openai-compatible\n # base_url: https://example.com/v1\n # api_key_env_var: MY_API_KEY\n\n # CLI agents registered with OmniNode (Phase 3 wires them up).\n agents: []\n # - name: opencode\n # type: cli\n # command: opencode\n\n # Roles describe what an AI is supposed to do (Phase 4).\n roles: []\n # - id: architecture-reviewer\n # name: Architecture Reviewer\n # responsibilities:\n # - architecture analysis\n # expected_outputs:\n # - findings\n # - recommendations\n\n # Memory is optional; Remembera is the preferred integration (Phase 7).\n # memory:\n # provider: remembera\n`;\n}\n","import { existsSync, writeFileSync } from \"node:fs\";\nimport type { Command } from \"commander\";\nimport { OmniNodeError } from \"../../errors/index.js\";\nimport { defaultProjectConfigYaml } from \"../../config/index.js\";\n\nexport async function runInit(options: { force?: boolean; name?: string }): Promise<void> {\n const target = `${process.cwd()}/omninode.yaml`;\n if (!options.force && existsSync(target)) {\n throw new OmniNodeError(\n \"CLI_USAGE\",\n `${target} already exists. Use --force to overwrite it.`,\n );\n }\n writeFileSync(target, defaultProjectConfigYaml(options.name), \"utf8\");\n console.log(`Created ${target}`);\n console.log(\"\\nNext steps:\");\n console.log(\" 1. Add a provider under `project.providers` (see omninode.yaml.example).\");\n console.log(\" 2. Register CLI agents under `project.agents`.\");\n console.log(\" 3. Run `omninode provider list` to validate the configuration.\");\n}\n\nexport function registerInitCommand(program: Command): void {\n program\n .command(\"init\")\n .description(\"Create an omninode.yaml project configuration in the current directory.\")\n .option(\"-f, --force\", \"Overwrite an existing omninode.yaml.\")\n .option(\"-n, --name <name>\", \"Project name to write into the configuration.\", \"My Project\")\n .action(async (options: { force?: boolean; name: string }) => runInit(options));\n}\n","import type { Command } from \"commander\";\nimport { runInit } from \"./init.js\";\n\nexport function registerProjectCommands(program: Command): void {\n const project = program\n .command(\"project\")\n .description(\"Project-level operations.\");\n\n project\n .command(\"init\")\n .description(\"Alias of `omninode init`.\")\n .option(\"-f, --force\", \"Overwrite an existing omninode.yaml.\")\n .option(\"-n, --name <name>\", \"Project name to write into the configuration.\", \"My Project\")\n .action(async (options: { force?: boolean; name: string }) => runInit(options));\n}\n","/**\n * Normalized model registry (§8): aggregates models discovered from all\n * configured providers under \"provider:model\" keys.\n */\nimport type { ModelCapabilities, ModelInfo } from \"../types/model.js\";\nimport type { IProvider } from \"../types/provider.js\";\n\nexport interface ModelFilter {\n provider?: string;\n capability?: keyof ModelCapabilities;\n}\n\nexport interface DiscoveryResult {\n provider: string;\n models: ModelInfo[];\n error?: Error;\n}\n\nexport function registryKey(provider: string, id: string): string {\n return `${provider}:${id}`;\n}\n\nexport class ModelRegistry {\n private readonly models = new Map<string, ModelInfo>();\n\n register(model: ModelInfo): void {\n this.models.set(registryKey(model.provider, model.id), model);\n }\n\n get(provider: string, id: string): ModelInfo | undefined {\n return this.models.get(registryKey(provider, id));\n }\n\n list(filter: ModelFilter = {}): ModelInfo[] {\n return [...this.models.values()]\n .filter((model) => (filter.provider ? model.provider === filter.provider : true))\n .filter((model) =>\n filter.capability ? model.capabilities?.[filter.capability] === true : true,\n )\n .sort((a, b) => a.provider.localeCompare(b.provider) || a.id.localeCompare(b.id));\n }\n\n /** Availability validation (§27 Phase 1): present in the registry and not retired. */\n isAvailable(provider: string, id: string): boolean {\n const model = this.get(provider, id);\n return model !== undefined && (model.status ?? \"available\") === \"available\";\n }\n\n /** Discover models from one provider and register them. */\n async discoverFrom(provider: IProvider): Promise<ModelInfo[]> {\n const discovered = await provider.listModels();\n for (const model of discovered) this.register(model);\n return discovered;\n }\n\n /** Discover from many providers; a failing provider does not abort the rest. */\n async discoverAll(providers: IProvider[]): Promise<DiscoveryResult[]> {\n return Promise.all(\n providers.map(async (provider) => {\n try {\n return {\n provider: provider.config.name,\n models: await this.discoverFrom(provider),\n };\n } catch (error) {\n return {\n provider: provider.config.name,\n models: [],\n error: error instanceof Error ? error : new Error(String(error)),\n };\n }\n }),\n );\n }\n}\n","import { readFileSync, writeFileSync } from \"node:fs\";\nimport { parseDocument } from \"yaml\";\nimport { appConfigSchema, findConfigFile } from \"../../config/index.js\";\nimport { ConfigError, OmniNodeError } from \"../../errors/index.js\";\n\n/** Shared helper for commands whose phase has not landed yet. */\nexport function notImplemented(command: string, when: string): OmniNodeError {\n return new OmniNodeError(\n \"NOT_IMPLEMENTED\",\n `${command} is planned for ${when}. Edit omninode.yaml directly for now.`,\n );\n}\n\nexport function truncate(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n\n/**\n * Appends an item to a list in omninode.yaml, preserving comments and\n * formatting, and validates the resulting document before writing.\n * Returns the config path that was edited.\n */\nexport function appendToConfigList(listKey: \"providers\" | \"agents\", item: unknown): string {\n const configPath = findConfigFile();\n if (!configPath) {\n throw new OmniNodeError(\"CONFIG_NOT_FOUND\", \"No omninode.yaml found. Run `omninode init` first.\");\n }\n\n // Edit as a YAML document so existing comments and formatting survive.\n const doc = parseDocument(readFileSync(configPath, \"utf8\"));\n if (doc.getIn([\"project\", listKey]) === undefined) {\n doc.setIn([\"project\", listKey], [item]);\n } else {\n doc.addIn([\"project\", listKey], item);\n }\n\n const validated = appConfigSchema.safeParse(doc.toJS());\n if (!validated.success) {\n const issues = validated.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"(root)\"}: ${issue.message}`)\n .join(\"; \");\n throw new ConfigError(\n \"CONFIG_INVALID\",\n `Editing ${configPath} would produce an invalid configuration: ${issues}`,\n );\n }\n\n writeFileSync(configPath, doc.toString(), \"utf8\");\n return configPath;\n}\n","/**\n * Process adapter (§9): runs CLI agents as child processes and communicates\n * over stdin/stdout, managing the process lifecycle, working directory,\n * environment, exit codes, logs and timeouts.\n *\n * Three input modes (§9, §21):\n * - \"stdin\": the composed task text is written to the agent's stdin.\n * - \"arg\": the composed task text is appended as the last command argument.\n * - \"protocol\": NodeToAgentMessage envelopes as JSON lines on stdin; the\n * agent answers with AgentToNodeMessage JSON lines (REPORT,\n * COMPLETION, ERROR, ...) whose structured payloads are parsed\n * into reports.\n */\nimport { spawn, type ChildProcess } from \"node:child_process\";\nimport { AgentError } from \"../../errors/index.js\";\nimport { PROTOCOL_V2, ProtocolSession, type QuestionResponder } from \"../../agent-protocol/index.js\";\nimport { logger, type Logger } from \"../../logger/index.js\";\nimport type {\n AgentConfig,\n AgentInfo,\n AgentTaskInput,\n AgentTaskOutput,\n IAgent,\n} from \"../../types/agent.js\";\nimport type { Report } from \"../../types/report.js\";\nimport { validateWorkingDirectory } from \"../cwd.js\";\nimport { buildChildEnv } from \"../env.js\";\n\nconst DEFAULT_TIMEOUT_MS = 600_000;\nconst KILL_GRACE_MS = 5_000;\n/** Per-stream byte budget before output is truncated and the agent killed. */\nexport const DEFAULT_MAX_OUTPUT_BYTES = 5 * 1024 * 1024;\n\nexport function composeTaskText(input: AgentTaskInput): string {\n const sections: string[] = [`# Objective\\n${input.objective}`];\n if (input.role) {\n const lines = [\"# Role\", `${input.role.name} (${input.role.id})`];\n if (input.role.responsibilities.length > 0) {\n lines.push(\"\", \"Responsibilities:\", ...input.role.responsibilities.map((r) => `- ${r}`));\n }\n if (input.role.expectedOutputs.length > 0) {\n lines.push(\"\", \"Expected outputs:\", ...input.role.expectedOutputs.map((o) => `- ${o}`));\n }\n sections.push(lines.join(\"\\n\"));\n }\n if (input.context) sections.push(`# Context\\n${input.context}`);\n if (input.instruction) sections.push(`# Instruction\\n${input.instruction}`);\n return sections.join(\"\\n\\n\");\n}\n\nfunction buildProtocolMessages(input: AgentTaskInput, agentName: string): string[] {\n // Protocol v2 envelopes with full correlation (roadmap §7.2, §7.4).\n const session = new ProtocolSession({\n requestId: `req-${input.taskId}`,\n taskId: input.taskId,\n agentId: agentName,\n ...(input.pipelineId !== undefined ? { pipelineId: input.pipelineId } : {}),\n ...(input.executionId !== undefined ? { executionId: input.executionId } : {}),\n });\n return session.taskMessages(\n input.objective,\n input.role,\n input.context,\n input.instruction,\n );\n}\n\nexport class ProcessAgent implements IAgent {\n readonly config: AgentConfig;\n readonly info: AgentInfo;\n private readonly log: Logger;\n private readonly running = new Map<string, ChildProcess>();\n\n constructor(config: AgentConfig, log: Logger = logger) {\n if (!config.command) {\n throw new AgentError(\"AGENT_NOT_FOUND\", `Agent \"${config.name}\" has no command configured.`);\n }\n this.config = config;\n this.log = log.child({ agent: config.name });\n this.info = {\n name: config.name,\n integration: \"process\",\n command: config.command,\n cwd: config.cwd,\n status: \"ready\",\n capabilities: [config.inputMode ?? \"stdin\"],\n };\n }\n\n async run(input: AgentTaskInput): Promise<AgentTaskOutput> {\n const command = this.config.command;\n if (!command) {\n throw new AgentError(\"AGENT_NOT_FOUND\", `Agent \"${this.config.name}\" has no command configured.`);\n }\n const mode = this.config.inputMode ?? \"stdin\";\n const timeoutMs = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\n return new Promise<AgentTaskOutput>((resolve, reject) => {\n // Validate the working directory BEFORE spawning (roadmap §8): never\n // silently fall back to the OmniNode cwd.\n let cwd: string | undefined;\n try {\n cwd = validateWorkingDirectory(this.config.cwd, {\n allowExternal: this.config.allowExternalCwd,\n })?.cwd;\n } catch (error) {\n // Invalid working directory — fail before spawning anything.\n reject(error);\n return;\n }\n\n const child = spawn(\n command,\n [...(this.config.args ?? []), ...(mode === \"arg\" ? [composeTaskText(input)] : [])],\n {\n ...(cwd !== undefined ? { cwd } : {}),\n env: buildChildEnv(this.config),\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n // Own process group so the whole tree can be terminated together\n // (roadmap §8: no orphaned children).\n ...(process.platform === \"win32\" ? {} : { detached: true }),\n },\n );\n this.running.set(input.taskId, child);\n GLOBAL_RUNNING.add(child);\n installSignalForwarding();\n\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n let outputLimitExceeded = false;\n let settled = false;\n const maxOutputBytes = this.config.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;\n\n const timer = setTimeout(() => {\n timedOut = true;\n this.log.warn(`Task ${input.taskId} exceeded ${timeoutMs}ms — killing process tree.`);\n killTree(child, \"SIGTERM\");\n setTimeout(() => killTree(child, \"SIGKILL\"), KILL_GRACE_MS).unref();\n }, timeoutMs);\n\n const settle = (finish: () => void): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n this.running.delete(input.taskId);\n GLOBAL_RUNNING.delete(child);\n finish();\n };\n\n // Output protection (roadmap §8): runaway/binary output is truncated at\n // a byte budget, and a flooding agent is killed rather than allowed to\n // exhaust memory.\n const collect = (into: \"stdout\" | \"stderr\", chunk: Buffer): void => {\n if (outputLimitExceeded) return;\n const text = sanitizeChunk(chunk);\n if (into === \"stdout\") {\n if (stdout.length + text.length > maxOutputBytes) {\n stdout = (stdout + text).slice(0, maxOutputBytes);\n outputLimitExceeded = true;\n this.log.warn(`Agent \"${this.config.name}\" exceeded the ${maxOutputBytes} byte output limit — killing it.`);\n killTree(child, \"SIGKILL\");\n return;\n }\n stdout += text;\n } else {\n if (stderr.length + text.length > maxOutputBytes) {\n stderr = (stderr + text).slice(0, maxOutputBytes);\n return;\n }\n stderr += text;\n }\n };\n child.stdout?.on(\"data\", (chunk: Buffer) => collect(\"stdout\", chunk));\n child.stderr?.on(\"data\", (chunk: Buffer) => collect(\"stderr\", chunk));\n\n // Agents that exit without reading stdin raise EPIPE on write — that is\n // not an agent failure, so the stream error is ignored.\n child.stdin?.on(\"error\", () => {});\n if (mode !== \"arg\") {\n const payload =\n mode === \"protocol\"\n ? buildProtocolMessages(input, this.config.name).join(\"\\n\") + \"\\n\"\n : composeTaskText(input) + \"\\n\";\n child.stdin?.write(payload);\n child.stdin?.end();\n }\n\n child.on(\"error\", (error) => {\n settle(() => {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n reject(\n new AgentError(\n \"AGENT_NOT_FOUND\",\n `Agent \"${this.config.name}\": command \"${command}\" was not found. Is it installed and on PATH?`,\n { cause: error },\n ),\n );\n return;\n }\n reject(\n new AgentError(\"AGENT_FAILED\", `Agent \"${this.config.name}\" failed to start: ${error.message}.`, {\n cause: error,\n }),\n );\n });\n });\n\n child.on(\"close\", (code, signal) => {\n settle(() => {\n if (timedOut) {\n reject(\n new AgentError(\n \"AGENT_TIMEOUT\",\n `Agent \"${this.config.name}\" timed out after ${timeoutMs}ms and was killed.`,\n {\n details: {\n operation: \"agent.run\",\n agent: this.config.name,\n durationMs: timeoutMs,\n // The process was started and may have performed side\n // effects before being killed — the outcome is unknown,\n // not failed (roadmap §6.3).\n dispatched: true,\n stdout: stdout.slice(0, 4000),\n stderr: stderr.slice(0, 2000),\n },\n },\n ),\n );\n return;\n }\n\n const logs = stderr.trim().length > 0 ? stderr.split(\"\\n\") : undefined;\n if (mode === \"protocol\") {\n // interpretProtocolRun can reject (e.g. protocol violations); throwing\n // inside this event callback would escape the promise entirely.\n try {\n resolve(\n interpretProtocolRun({\n input,\n agentName: this.config.name,\n stdout,\n exitCode: code,\n logs,\n }),\n );\n } catch (error) {\n reject(error);\n }\n return;\n }\n\n const trimmed = stdout.trim();\n resolve({\n taskId: input.taskId,\n status: code === 0 && !outputLimitExceeded ? \"completed\" : \"failed\",\n summary: trimmed.length > 0 ? firstLine(trimmed) : undefined,\n rawOutput: trimmed.length > 0 ? trimmed : undefined,\n exitCode: code ?? undefined,\n logs,\n ...(outputLimitExceeded\n ? { error: `Agent exceeded the ${maxOutputBytes} byte output limit and was terminated.` }\n : code === 0\n ? {}\n : { error: describeExit(code, signal) }),\n });\n });\n });\n });\n }\n\n /** Ask the agent to stop current work (SIGTERM). */\n async cancel(taskId: string): Promise<void> {\n const child = this.running.get(taskId);\n if (child) killTree(child, \"SIGTERM\");\n }\n\n runningTaskIds(): string[] {\n return [...this.running.keys()];\n }\n}\n\ninterface ProtocolRunInput {\n input: AgentTaskInput;\n agentName: string;\n stdout: string;\n exitCode: number | null;\n logs?: string[];\n responder?: QuestionResponder;\n}\n\nfunction interpretProtocolRun({\n input,\n agentName,\n stdout,\n exitCode,\n logs,\n responder,\n}: ProtocolRunInput): AgentTaskOutput {\n const session = new ProtocolSession(\n {\n requestId: `req-${input.taskId}`,\n taskId: input.taskId,\n agentId: agentName,\n ...(input.pipelineId !== undefined ? { pipelineId: input.pipelineId } : {}),\n ...(input.executionId !== undefined ? { executionId: input.executionId } : {}),\n },\n { ...(responder !== undefined ? { responder } : {}) },\n );\n\n // The stream was drained line-by-line already; re-decode deterministically.\n for (const result of session.decoder.push(stdout)) {\n // handled synchronously below via handle(); questions are resolved eagerly\n session.handle(result);\n }\n for (const result of session.decoder.flush()) {\n session.handle(result);\n }\n\n const reports = session.reports\n .flatMap((payload) => (Array.isArray(payload) ? payload : [payload]))\n .map((payload, index) => normalizeReport(payload, input.taskId, agentName, index))\n .filter((report): report is NonNullable<typeof report> => report !== undefined);\n\n const trimmed = stdout.trim();\n const protocolBlock = {\n protocol: session.descriptor?.protocol ?? PROTOCOL_V2,\n legacy: !session.sawV2 && session.descriptor === undefined,\n ...(session.descriptor !== undefined ? { descriptor: session.descriptor } : {}),\n questions: session.questions,\n violations: session.violations.map((v) => `${v.code}: ${v.message}`),\n };\n\n if (session.errorMessage !== undefined) {\n return {\n taskId: input.taskId,\n status: \"failed\",\n error: session.errorMessage,\n rawOutput: trimmed.length > 0 ? trimmed : undefined,\n exitCode: exitCode ?? undefined,\n logs,\n protocol: protocolBlock,\n ...(reports.length > 0 ? { reports } : {}),\n };\n }\n\n if (session.descriptor === undefined && session.violations.length > 0 && session.reports.length === 0 && session.completionSummary === undefined) {\n // Nothing usable parsed: protocol violation rather than silent success.\n return {\n taskId: input.taskId,\n status: \"failed\",\n error: `agent produced no valid protocol messages: ${protocolBlock.violations.join(\"; \")}`,\n rawOutput: trimmed.length > 0 ? trimmed : undefined,\n exitCode: exitCode ?? undefined,\n logs,\n protocol: protocolBlock,\n };\n }\n\n const completed = exitCode === 0 && session.completionSummary !== undefined;\n return {\n taskId: input.taskId,\n status: completed || exitCode === 0 ? (completed ? \"completed\" : \"completed\") : \"failed\",\n summary: session.completionSummary ?? reports[0]?.summary,\n rawOutput: trimmed.length > 0 ? trimmed : undefined,\n exitCode: exitCode ?? undefined,\n logs,\n protocol: protocolBlock,\n ...(reports.length > 0 ? { reports } : {}),\n ...(exitCode !== 0 ? { error: `Process exited with code ${exitCode ?? \"unknown\"}` } : {}),\n };\n}\n\n/**\n * Every live agent process, so Ctrl-C / SIGTERM on OmniNode reaches the whole\n * tree instead of orphaning children (roadmap §8, signal handling).\n */\nconst GLOBAL_RUNNING = new Set<ChildProcess>();\nlet signalForwardingInstalled = false;\n\nfunction installSignalForwarding(): void {\n if (signalForwardingInstalled) return;\n signalForwardingInstalled = true;\n for (const signal of [\"SIGINT\", \"SIGTERM\"] as const) {\n process.on(signal, () => {\n for (const child of GLOBAL_RUNNING) {\n killTree(child, \"SIGTERM\");\n }\n });\n }\n}\n\n/** Kills a child and, on POSIX, its whole process group (roadmap §8 tree cleanup). */\nexport function killTree(child: ChildProcess, signal: NodeJS.Signals): void {\n if (child.pid === undefined) return;\n if (process.platform !== \"win32\") {\n try {\n process.kill(-child.pid, signal);\n return;\n } catch {\n // Group already gone — fall through to direct kill.\n }\n }\n try {\n child.kill(signal);\n } catch {\n // Process already exited.\n }\n}\n\n/** Human-readable exit reason, including signal terminations. */\nexport function describeExit(code: number | null, signal: NodeJS.Signals | null): string {\n if (signal !== null) {\n return signal === \"SIGKILL\"\n ? \"Process was killed (SIGKILL) — usually an external kill or OOM.\"\n : `Process terminated by signal ${signal}.`;\n }\n if (code === null) return \"Process terminated without an exit code.\";\n return `Process exited with code ${code}.`;\n}\n\n/**\n * Decodes a stdout/stderr chunk safely: invalid UTF-8 becomes replacement\n * characters and NUL bytes are stripped, so binary noise cannot poison the\n * protocol decoder or the terminal (roadmap §8, encoding hardening).\n */\nexport function sanitizeChunk(chunk: Buffer): string {\n return [...chunk.toString(\"utf8\")].filter((char) => char.charCodeAt(0) !== 0).join(\"\");\n}\n\n/** Normalizes a loose REPORT payload into a strict Report; drops malformed entries. */\nfunction normalizeReport(\n payload: unknown,\n taskId: string,\n agentName: string,\n index: number,\n): Report | undefined {\n if (payload === null || typeof payload !== \"object\") return undefined;\n const raw = payload as Record<string, unknown>;\n if (typeof raw.summary !== \"string\") return undefined;\n return {\n id: typeof raw.id === \"string\" ? raw.id : `${taskId}-report-${index}`,\n taskId: typeof raw.taskId === \"string\" ? raw.taskId : taskId,\n agent: typeof raw.agent === \"string\" ? raw.agent : agentName,\n summary: raw.summary,\n findings: Array.isArray(raw.findings) ? (raw.findings as Report[\"findings\"]) : [],\n recommendations: Array.isArray(raw.recommendations) ? (raw.recommendations as string[]) : [],\n createdAt: typeof raw.createdAt === \"string\" ? raw.createdAt : new Date().toISOString(),\n };\n}\n\nfunction firstLine(text: string, maxLength = 200): string {\n const line = text.split(\"\\n\", 1)[0] ?? text;\n return line.length > maxLength ? `${line.slice(0, maxLength)}…` : line;\n}\n","/**\n * OmniNode Agent Protocol v2 — versioning (roadmap §7.1).\n *\n * Protocol identifiers are namespaced strings so an agent can negotiate the\n * dialect it speaks: `omninode-agent-protocol/2`.\n */\nexport const PROTOCOL_V2 = \"omninode-agent-protocol/2\";\n\n/** Versions this build accepts. v1 is the unversioned dialect shipped with OmniNode 1.x. */\nexport const SUPPORTED_PROTOCOL_VERSIONS: readonly string[] = [\n \"omninode-agent-protocol/1\",\n PROTOCOL_V2,\n];\n\nexport const MAX_MESSAGE_BYTES = 1_048_576; // 1 MiB per message line\n\nexport function isSupportedProtocol(protocol: string): boolean {\n return SUPPORTED_PROTOCOL_VERSIONS.includes(protocol);\n}","/**\n * OmniNode Agent Protocol v2 — message model (roadmap §7.2–§7.4, §7.7).\n *\n * Every message is a JSON line carrying a `ProtocolEnvelope`. All ids are\n * optional for inbound tolerance but OmniNode always emits them, so every\n * message is traceable to agent / task / pipeline / execution / request.\n */\nimport type { Report } from \"../types/report.js\";\nimport { PROTOCOL_V2 } from \"./version.js\";\n\n/** Messages OmniNode sends to an agent. */\nexport type ProtocolNodeToAgentType =\n | \"TASK\"\n | \"HELLO_ACK\"\n | \"CONTEXT\"\n | \"INSTRUCTION\"\n | \"RESPONSE\"\n | \"CANCEL\";\n\n/** Messages an agent sends to OmniNode. */\nexport type ProtocolAgentToNodeType =\n | \"HELLO\"\n | \"TASK_REQUEST\"\n | \"TASK_ACCEPTED\"\n | \"TASK_STARTED\"\n | \"STATUS\"\n | \"QUESTION\"\n | \"REPORT\"\n | \"ARTIFACT\"\n | \"COMPLETION\"\n | \"ERROR\"\n | \"CANCELLED\";\n\nexport type ProtocolMessageType = ProtocolNodeToAgentType | ProtocolAgentToNodeType;\n\nexport interface ProtocolEnvelope<T extends ProtocolMessageType = ProtocolMessageType> {\n /** `omninode-agent-protocol/2`. Inbound messages without it are treated as v1. */\n protocol: string;\n /** Unique id of this message. */\n messageId: string;\n /** Id of the request/thread this message belongs to. */\n requestId?: string;\n taskId?: string;\n agentId?: string;\n pipelineId?: string;\n /** Execution identity (roadmap §6.5) — ties the message to one attempt. */\n executionId?: string;\n timestamp: string;\n type: T;\n payload: unknown;\n metadata?: Record<string, unknown>;\n}\n\n/** Standard artifact kinds (roadmap §7.7). */\nexport type ArtifactKind =\n | \"file\"\n | \"patch\"\n | \"report\"\n | \"log\"\n | \"screenshot\"\n | \"document\"\n | \"data\";\n\nexport interface ArtifactPayload {\n kind: ArtifactKind;\n /** Path, URL or logical name. */\n ref: string;\n description?: string;\n mediaType?: string;\n bytes?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface QuestionPayload {\n /** Question id to answer. */\n questionId: string;\n question: string;\n /** What kind of answer is expected (free text, file path, options…). */\n expected?: \"text\" | \"path\" | \"choice\";\n options?: string[];\n}\n\nexport interface TaskPayload {\n taskId: string;\n objective: string;\n}\n\nexport interface ReportPayload {\n report: Report | Report[];\n}\n\n/** A question an agent asked during a run, with the answer OmniNode gave (if any). */\nexport interface AskedQuestion {\n questionId: string;\n question: string;\n answer?: string;\n}\n\nexport function newMessageId(prefix = \"msg\"): string {\n const random = Math.random().toString(36).slice(2, 10);\n return `${prefix}-${Date.now().toString(36)}-${random}`;\n}\n\n/** Builds a v2 envelope with ids and timestamp filled in. */\nexport function envelope<T extends ProtocolMessageType>(\n type: T,\n payload: unknown,\n ids: {\n requestId?: string;\n taskId?: string;\n agentId?: string;\n pipelineId?: string;\n executionId?: string;\n metadata?: Record<string, unknown>;\n } = {},\n): ProtocolEnvelope<T> {\n return {\n protocol: PROTOCOL_V2,\n messageId: newMessageId(),\n ...(ids.requestId !== undefined ? { requestId: ids.requestId } : {}),\n ...(ids.taskId !== undefined ? { taskId: ids.taskId } : {}),\n ...(ids.agentId !== undefined ? { agentId: ids.agentId } : {}),\n ...(ids.pipelineId !== undefined ? { pipelineId: ids.pipelineId } : {}),\n ...(ids.executionId !== undefined ? { executionId: ids.executionId } : {}),\n timestamp: new Date().toISOString(),\n type,\n payload,\n ...(ids.metadata !== undefined ? { metadata: ids.metadata } : {}),\n };\n}","/**\n * OmniNode Agent Protocol v2 — codec and validation (roadmap §7.5).\n *\n * Decoding NEVER throws: every failure is returned as a typed\n * `ProtocolViolation` with a machine-readable code, so a misbehaving agent\n * can never crash OmniNode.\n */\nimport {\n MAX_MESSAGE_BYTES,\n PROTOCOL_V2,\n isSupportedProtocol,\n} from \"./version.js\";\nimport type { ProtocolEnvelope, ProtocolMessageType } from \"./types.js\";\n\nexport type ProtocolViolationCode =\n | \"INVALID_JSON\"\n | \"NOT_AN_OBJECT\"\n | \"UNKNOWN_TYPE\"\n | \"MISSING_FIELD\"\n | \"UNSUPPORTED_VERSION\"\n | \"OVERSIZED\"\n | \"INVALID_PAYLOAD\";\n\nexport interface ProtocolViolation {\n code: ProtocolViolationCode;\n message: string;\n /** Raw line (truncated) for diagnostics. */\n sample?: string;\n}\n\nexport type DecodeResult =\n | { ok: true; envelope: ProtocolEnvelope; legacy: boolean }\n | { ok: false; error: ProtocolViolation };\n\nconst KNOWN_TYPES = new Set<string>([\n // node → agent\n \"TASK\", \"HELLO_ACK\", \"CONTEXT\", \"INSTRUCTION\", \"RESPONSE\", \"CANCEL\",\n // agent → node\n \"HELLO\", \"TASK_REQUEST\", \"TASK_ACCEPTED\", \"TASK_STARTED\", \"STATUS\",\n \"QUESTION\", \"REPORT\", \"ARTIFACT\", \"COMPLETION\", \"ERROR\", \"CANCELLED\",\n]);\n\nconst PAYLOAD_REQUIRED_TYPES = new Set<string>([\"TASK\", \"REPORT\", \"COMPLETION\", \"ERROR\", \"QUESTION\", \"ARTIFACT\", \"HELLO\"]);\n\n/** Validates one decoded JSON value as a protocol envelope. */\nexport function validateEnvelope(value: unknown, line?: string): DecodeResult {\n const sample = line?.slice(0, 200);\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return { ok: false, error: { code: \"NOT_AN_OBJECT\", message: \"message must be a JSON object\", ...(sample ? { sample } : {}) } };\n }\n const raw = value as Record<string, unknown>;\n\n // Version negotiation: absent protocol = v1 (OmniNode 1.x agents), else must be supported.\n const protocol = raw.protocol;\n if (protocol === undefined) {\n // legacy v1: requires a bare {type, payload} shape\n const type = raw.type;\n if (typeof type !== \"string\" || !KNOWN_TYPES.has(type)) {\n return { ok: false, error: { code: \"UNKNOWN_TYPE\", message: `unknown message type ${String(type)}`, ...(sample ? { sample } : {}) } };\n }\n return {\n ok: true,\n legacy: true,\n envelope: {\n protocol: \"omninode-agent-protocol/1\",\n messageId: typeof raw.messageId === \"string\" ? raw.messageId : \"legacy\",\n timestamp: new Date().toISOString(),\n type: type as ProtocolMessageType,\n payload: raw.payload,\n },\n };\n }\n if (typeof protocol !== \"string\" || !isSupportedProtocol(protocol)) {\n return {\n ok: false,\n error: { code: \"UNSUPPORTED_VERSION\", message: `unsupported protocol \"${String(protocol)}\"`, ...(sample ? { sample } : {}) },\n };\n }\n\n if (raw.type === undefined) {\n return { ok: false, error: { code: \"MISSING_FIELD\", message: \"message is missing 'type'\", ...(sample ? { sample } : {}) } };\n }\n if (typeof raw.type !== \"string\" || !KNOWN_TYPES.has(raw.type)) {\n return { ok: false, error: { code: \"UNKNOWN_TYPE\", message: `unknown message type ${String(raw.type)}`, ...(sample ? { sample } : {}) } };\n }\n if (raw.timestamp !== undefined && typeof raw.timestamp !== \"string\") {\n return { ok: false, error: { code: \"MISSING_FIELD\", message: \"'timestamp' must be a string\", ...(sample ? { sample } : {}) } };\n }\n if (PAYLOAD_REQUIRED_TYPES.has(raw.type) && (raw.payload === undefined || raw.payload === null)) {\n return { ok: false, error: { code: \"INVALID_PAYLOAD\", message: `${raw.type} requires a payload`, ...(sample ? { sample } : {}) } };\n }\n\n return {\n ok: true,\n legacy: protocol !== PROTOCOL_V2,\n envelope: {\n protocol,\n messageId: typeof raw.messageId === \"string\" ? raw.messageId : \"unknown\",\n ...(typeof raw.requestId === \"string\" ? { requestId: raw.requestId } : {}),\n ...(typeof raw.taskId === \"string\" ? { taskId: raw.taskId } : {}),\n ...(typeof raw.agentId === \"string\" ? { agentId: raw.agentId } : {}),\n ...(typeof raw.pipelineId === \"string\" ? { pipelineId: raw.pipelineId } : {}),\n ...(typeof raw.executionId === \"string\" ? { executionId: raw.executionId } : {}),\n timestamp: typeof raw.timestamp === \"string\" ? raw.timestamp : new Date().toISOString(),\n type: raw.type as ProtocolMessageType,\n payload: raw.payload,\n ...(raw.metadata !== null && typeof raw.metadata === \"object\" ? { metadata: raw.metadata as Record<string, unknown> } : {}),\n },\n };\n}\n\n/** Decodes one protocol line (no trailing newline). */\nexport function decodeMessage(line: string, maxBytes = MAX_MESSAGE_BYTES): DecodeResult {\n const trimmed = line.trim();\n if (trimmed.length === 0) {\n return { ok: false, error: { code: \"INVALID_JSON\", message: \"empty line\" } };\n }\n if (trimmed.length > maxBytes) {\n return {\n ok: false,\n error: { code: \"OVERSIZED\", message: `message of ${trimmed.length} bytes exceeds the ${maxBytes} byte limit`, sample: trimmed.slice(0, 200) },\n };\n }\n let value: unknown;\n try {\n value = JSON.parse(trimmed);\n } catch (error) {\n return {\n ok: false,\n error: { code: \"INVALID_JSON\", message: error instanceof Error ? error.message : \"invalid JSON\", sample: trimmed.slice(0, 200) },\n };\n }\n return validateEnvelope(value, trimmed);\n}\n\n/** Serializes an envelope to a single JSON line. */\nexport function encodeMessage(envelope: ProtocolEnvelope, maxBytes = MAX_MESSAGE_BYTES): string {\n const line = JSON.stringify(envelope);\n if (line.length > maxBytes) {\n throw new Error(`outbound protocol message of ${line.length} bytes exceeds the ${maxBytes} byte limit`);\n }\n return line;\n}\n\n/**\n * Streaming line decoder for agent stdout. Feed chunks; receive decoded\n * envelopes and violations in order. Survives garbage: a bad line yields a\n * violation and the stream continues.\n */\nexport class ProtocolDecoder {\n private buffer = \"\";\n private readonly maxBytes: number;\n\n constructor(maxBytes = MAX_MESSAGE_BYTES) {\n this.maxBytes = maxBytes;\n }\n\n push(chunk: string): DecodeResult[] {\n this.buffer += chunk;\n const results: DecodeResult[] = [];\n let index = this.buffer.indexOf(\"\\n\");\n while (index >= 0) {\n const line = this.buffer.slice(0, index);\n this.buffer = this.buffer.slice(index + 1);\n if (line.trim().length > 0) results.push(decodeMessage(line, this.maxBytes));\n index = this.buffer.indexOf(\"\\n\");\n }\n // Guard against an agent emitting an endless line with no newline.\n if (this.buffer.length > this.maxBytes) {\n results.push({\n ok: false,\n error: { code: \"OVERSIZED\", message: `line exceeded ${this.maxBytes} bytes without a newline`, sample: this.buffer.slice(0, 200) },\n });\n this.buffer = \"\";\n }\n return results;\n }\n\n /** Flush any trailing line when the process exits. */\n flush(): DecodeResult[] {\n if (this.buffer.trim().length === 0) {\n this.buffer = \"\";\n return [];\n }\n const result = decodeMessage(this.buffer, this.maxBytes);\n this.buffer = \"\";\n return [result];\n }\n}","/**\n * OmniNode Agent Protocol v2 — handshake (roadmap §7.1).\n *\n * An agent announces itself with HELLO; OmniNode replies with HELLO_ACK.\n * Handshakes are optional for v1-style agents (no HELLO = legacy dialect).\n */\nimport { PROTOCOL_V2 } from \"./version.js\";\nimport { envelope, type ProtocolEnvelope } from \"./types.js\";\n\nexport interface AgentDescriptor {\n /** Protocol the agent speaks. */\n protocol: string;\n name: string;\n version?: string;\n capabilities: string[];\n /** Message types the agent can emit. */\n supports: string[];\n}\n\nexport type HelloResult =\n | { ok: true; descriptor: AgentDescriptor }\n | { ok: false; reason: string };\n\nexport function parseHello(envelopeValue: ProtocolEnvelope): HelloResult {\n if (envelopeValue.type !== \"HELLO\") {\n return { ok: false, reason: `expected HELLO, received ${envelopeValue.type}` };\n }\n const payload = envelopeValue.payload;\n if (payload === null || typeof payload !== \"object\") {\n return { ok: false, reason: \"HELLO payload must be an object\" };\n }\n const p = payload as Record<string, unknown>;\n if (typeof p.name !== \"string\" || p.name.length === 0) {\n return { ok: false, reason: \"HELLO payload is missing 'name'\" };\n }\n return {\n ok: true,\n descriptor: {\n protocol: envelopeValue.protocol,\n name: p.name,\n ...(typeof p.version === \"string\" ? { version: p.version } : {}),\n capabilities: Array.isArray(p.capabilities) ? p.capabilities.filter((c): c is string => typeof c === \"string\") : [],\n supports: Array.isArray(p.supports) ? p.supports.filter((s): s is string => typeof s === \"string\") : [],\n },\n };\n}\n\nexport function buildHello(descriptor: Omit<AgentDescriptor, \"protocol\">): ProtocolEnvelope<\"HELLO\"> {\n return envelope(\"HELLO\", descriptor, { agentId: descriptor.name });\n}\n\nexport function buildHelloAck(descriptor: AgentDescriptor): ProtocolEnvelope<\"HELLO_ACK\"> {\n return envelope(\"HELLO_ACK\", {\n ok: true,\n protocol: PROTOCOL_V2,\n agent: descriptor.name,\n ...(descriptor.version !== undefined ? { agentVersion: descriptor.version } : {}),\n supportedProtocols: [PROTOCOL_V2],\n }, { agentId: descriptor.name });\n}\n","/**\n * OmniNode Agent Protocol v2 — session (roadmap §7.6).\n *\n * A session drives a protocol-mode agent: it emits v2 envelopes with\n * correlation ids, tolerates legacy (unversioned) replies, answers agent\n * questions through a responder callback, and collects reports, artifacts\n * and the completion — never throwing on malformed input.\n */\nimport { decodeMessage, encodeMessage, ProtocolDecoder, type DecodeResult, type ProtocolViolation } from \"./codec.js\";\nimport { PROTOCOL_V2 } from \"./version.js\";\nimport { envelope, type AskedQuestion, type ProtocolEnvelope } from \"./types.js\";\nimport { parseHello, buildHelloAck, type AgentDescriptor } from \"./handshake.js\";\nimport { ProtocolError } from \"../errors/index.js\";\n\nexport interface SessionIds {\n requestId: string;\n taskId: string;\n agentId: string;\n pipelineId?: string;\n executionId?: string;\n}\n\nexport interface QuestionResponder {\n (question: { questionId: string; question: string; expected?: string }): Promise<string> | string;\n}\n\nexport class ProtocolSession {\n readonly decoder: ProtocolDecoder;\n private readonly ids: SessionIds;\n private readonly responder: QuestionResponder | undefined;\n readonly violations: ProtocolViolation[] = [];\n readonly questions: AskedQuestion[] = [];\n readonly artifacts: ProtocolEnvelope[\"payload\"][] = [];\n reports: ProtocolEnvelope[\"payload\"][] = [];\n descriptor?: AgentDescriptor;\n completionSummary?: string;\n errorMessage?: string;\n\n constructor(ids: SessionIds, options: { responder?: QuestionResponder; maxBytes?: number } = {}) {\n this.ids = ids;\n this.responder = options.responder;\n this.decoder = new ProtocolDecoder(options.maxBytes);\n }\n\n /** The v2 messages OmniNode sends to open a task (written to the agent's stdin). */\n taskMessages(objective: string, role?: unknown, context?: string, instruction?: string): string[] {\n const ids = this.ids;\n const messages: ProtocolEnvelope[] = [envelope(\"TASK\", { taskId: ids.taskId, objective }, ids)];\n if (role !== undefined) messages.push(envelope(\"CONTEXT\", { role }, ids));\n if (context !== undefined && context.length > 0) messages.push(envelope(\"CONTEXT\", { body: context }, ids));\n if (instruction !== undefined && instruction.length > 0) messages.push(envelope(\"INSTRUCTION\", { text: instruction }, ids));\n return messages.map((m) => encodeMessage(m));\n }\n\n helloAck(descriptor: AgentDescriptor): string {\n return encodeMessage(buildHelloAck(descriptor));\n }\n\n /** Consumes decoded stdout, answering questions as they arrive. */\n async handle(decoded: DecodeResult): Promise<void> {\n if (!decoded.ok) {\n // Agent misbehavior is recorded, never fatal (§7.5).\n this.violations.push(decoded.error);\n return;\n }\n const message = decoded.envelope;\n if (message.protocol === PROTOCOL_V2) this.sawV2 = true;\n if (message.type === \"HELLO\") {\n const hello = parseHello(message);\n if (hello.ok) this.descriptor = hello.descriptor;\n else this.violations.push({ code: \"INVALID_PAYLOAD\", message: `bad HELLO: ${hello.reason}` });\n return;\n }\n if (message.type === \"QUESTION\") {\n await this.answerQuestion(message);\n return;\n }\n if (message.type === \"REPORT\") {\n this.reports.push(message.payload);\n return;\n }\n if (message.type === \"ARTIFACT\") {\n this.artifacts.push(message.payload);\n return;\n }\n if (message.type === \"COMPLETION\") {\n const payload = message.payload as { summary?: unknown } | undefined;\n this.completionSummary = typeof payload?.summary === \"string\" ? payload.summary : \"\";\n return;\n }\n if (message.type === \"ERROR\") {\n const payload = message.payload as { message?: unknown; code?: unknown } | undefined;\n const detail = typeof payload?.message === \"string\" ? payload.message : \"agent reported an error\";\n const code = typeof payload?.code === \"string\" ? ` [${payload.code}]` : \"\";\n this.errorMessage = `Agent error${code}: ${detail}`;\n return;\n }\n if (message.type === \"TASK_ACCEPTED\" || message.type === \"TASK_STARTED\" || message.type === \"STATUS\") {\n // Lifecycle acknowledgements: observed, no action needed by the core.\n return;\n }\n this.violations.push({\n code: \"UNKNOWN_TYPE\",\n message: `unexpected message type ${message.type} from agent`,\n });\n }\n\n private async answerQuestion(message: ProtocolEnvelope): Promise<void> {\n const payload = (message.payload ?? {}) as { questionId?: unknown; question?: unknown; expected?: unknown };\n const questionId = typeof payload.questionId === \"string\" ? payload.questionId : message.messageId;\n const question = typeof payload.question === \"string\" ? payload.question : \"\";\n const expected = typeof payload.expected === \"string\" ? payload.expected : \"text\";\n\n let answer: string | undefined;\n if (this.responder) {\n try {\n answer = await this.responder({ questionId, question, expected });\n } catch (error) {\n this.violations.push({\n code: \"INVALID_PAYLOAD\",\n message: `question responder failed: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n }\n this.questions.push({ questionId, question, ...(answer !== undefined ? { answer } : {}) });\n // Answer on stdout via the write callback supplied by the caller.\n this.pendingAnswers.push(\n encodeMessage(\n envelope(\"RESPONSE\", { questionId, ...(answer !== undefined ? { body: answer } : {}) }, {\n ...this.ids,\n requestId: message.requestId ?? this.ids.requestId,\n }),\n ),\n );\n }\n\n readonly pendingAnswers: string[] = [];\n /** True once any inbound message carried the v2 protocol field. */\n sawV2 = false;\n}\n\nexport async function decodeStream(session: ProtocolSession, chunk: string): Promise<string[]> {\n const decoded = session.decoder.push(chunk);\n for (const result of decoded) {\n await session.handle(result);\n }\n return session.pendingAnswers.splice(0);\n}\n\nexport function requireCompletion(session: ProtocolSession): void {\n if (session.errorMessage !== undefined) {\n throw new ProtocolError(session.errorMessage);\n }\n}\n\nexport { decodeMessage };","/**\n * Working-directory validation for agent processes (roadmap §8): existence,\n * directory-ness, access, path normalization and project boundaries.\n */\nimport { statSync } from \"node:fs\";\nimport { isAbsolute, relative, resolve } from \"node:path\";\nimport { AgentError } from \"../errors/index.js\";\n\nexport interface CwdValidation {\n /** Normalized absolute path. */\n cwd: string;\n /** True when the directory sits outside the project root (project boundary). */\n outsideProject: boolean;\n}\n\nexport function validateWorkingDirectory(\n cwd: string | undefined,\n options: { projectRoot?: string; allowExternal?: boolean } = {},\n): CwdValidation | undefined {\n if (!cwd) return undefined;\n\n const normalized = isAbsolute(cwd) ? resolve(cwd) : resolve(process.cwd(), cwd);\n let stats;\n try {\n stats = statSync(normalized);\n } catch (error) {\n throw new AgentError(\n \"AGENT_NOT_FOUND\",\n `Working directory \"${normalized}\" does not exist or is not accessible.`,\n { cause: error, details: { cwd: normalized } },\n );\n }\n if (!stats.isDirectory()) {\n throw new AgentError(\"AGENT_NOT_FOUND\", `Working directory \"${normalized}\" is not a directory.`, {\n details: { cwd: normalized },\n });\n }\n // Access check: attempt to list it.\n try {\n statSync(resolve(normalized, \".\"));\n } catch (error) {\n throw new AgentError(\n \"AGENT_NOT_FOUND\",\n `Working directory \"${normalized}\" is not accessible.`,\n { cause: error },\n );\n }\n\n const projectRoot = resolve(options.projectRoot ?? process.cwd());\n const rel = relative(projectRoot, normalized);\n const outsideProject = rel.startsWith(\"..\") || isAbsolute(rel);\n if (outsideProject && options.allowExternal !== true) {\n throw new AgentError(\n \"AGENT_NOT_FOUND\",\n `Working directory \"${normalized}\" is outside the project root \"${projectRoot}\". ` +\n `Set allow_external_cwd: true on the agent to permit this.`,\n { details: { cwd: normalized, projectRoot } },\n );\n }\n return { cwd: normalized, outsideProject };\n}","/**\n * Agent environment policies (roadmap §8, Environment Isolation).\n *\n * Four explicit policies, so operators decide exactly what an agent can see:\n * - `inherit` (default, backwards compatible): the full parent environment\n * - `allowlist`: only the allow-listed variables (+ PATH/HOME)\n * - `denylist`: the parent environment minus the deny-listed variables\n * - `explicit`: nothing from the parent; only PATH/HOME and `env`\n *\n * The v1 boolean `inherit_env: false` is still honored and maps to `explicit`.\n */\nimport type { AgentConfig } from \"../types/agent.js\";\n\nexport type EnvPolicy = \"inherit\" | \"allowlist\" | \"denylist\" | \"explicit\";\n\n/** Variables always provided so shells and runtimes keep working. */\nconst BASELINE_KEYS = [\"PATH\", \"HOME\"] as const;\n\nexport function resolveEnvPolicy(config: Partial<AgentConfig>): EnvPolicy {\n if (config.envPolicy !== undefined) return config.envPolicy;\n if (config.inheritEnv === false) return \"explicit\"; // v1 compatibility\n return \"inherit\";\n}\n\nexport function buildChildEnv(config: AgentConfig): NodeJS.ProcessEnv {\n const configured = config.env ?? {};\n const policy = resolveEnvPolicy(config);\n\n if (policy === \"inherit\") {\n return { ...process.env, ...configured };\n }\n\n const base: NodeJS.ProcessEnv = {};\n for (const key of BASELINE_KEYS) {\n const value = process.env[key];\n if (value !== undefined) base[key] = value;\n }\n\n switch (policy) {\n case \"explicit\":\n return { ...base, ...configured };\n case \"allowlist\": {\n const allowed: NodeJS.ProcessEnv = { ...base };\n for (const key of config.envAllowlist ?? []) {\n const value = process.env[key];\n if (value !== undefined) allowed[key] = value;\n }\n return { ...allowed, ...configured };\n }\n case \"denylist\": {\n const denied = new Set((config.envDenylist ?? []).map((k) => k.toUpperCase()));\n const filtered: NodeJS.ProcessEnv = {};\n for (const [key, value] of Object.entries(process.env)) {\n if (denied.has(key.toUpperCase())) continue;\n filtered[key] = value;\n }\n return { ...filtered, ...configured };\n }\n }\n}","/**\n * Agent adapter registry (roadmap §8, Native Adapters).\n *\n * New integration styles (native/API-level agents) plug in here without\n * changing OmniNode core: register an `IAgentAdapter` and `createAgent`\n * consults the registry before falling back to the process adapter.\n */\nimport { AgentError } from \"../errors/index.js\";\nimport type { AgentConfig, IAgent } from \"../types/agent.js\";\n\nexport interface IAgentAdapter {\n /** Integration type this adapter serves, e.g. \"native\" or \"process\". */\n readonly integration: string;\n create(config: AgentConfig): IAgent;\n}\n\nexport class AgentAdapterRegistry {\n private readonly adapters = new Map<string, IAgentAdapter>();\n\n register(adapter: IAgentAdapter): void {\n this.adapters.set(adapter.integration, adapter);\n }\n\n get(integration: string): IAgentAdapter | undefined {\n return this.adapters.get(integration);\n }\n\n list(): IAgentAdapter[] {\n return [...this.adapters.values()];\n }\n\n create(config: AgentConfig): IAgent {\n const adapter = this.get(config.integration);\n if (!adapter) {\n throw new AgentError(\n \"AGENT_NOT_FOUND\",\n `No agent adapter registered for integration \"${config.integration}\". ` +\n `Registered: ${[...this.adapters.keys()].join(\", \") || \"(none)\"}.`,\n );\n }\n return adapter.create(config);\n }\n}\n\n/** Process-level adapter — the built-in CLI integration. */\nexport class ProcessAgentAdapter implements IAgentAdapter {\n readonly integration = \"process\";\n\n constructor(private readonly factory: (config: AgentConfig) => IAgent) {}\n\n create(config: AgentConfig): IAgent {\n return this.factory(config);\n }\n}","/** Agent registry (§10): the set of agents connected to OmniNode. */\nimport type { IAgent } from \"../types/agent.js\";\n\nexport class AgentRegistry {\n private readonly agents = new Map<string, IAgent>();\n\n register(agent: IAgent): void {\n this.agents.set(agent.info.name, agent);\n }\n\n get(name: string): IAgent | undefined {\n return this.agents.get(name);\n }\n\n list(): IAgent[] {\n return [...this.agents.values()].sort((a, b) => a.info.name.localeCompare(b.info.name));\n }\n}\n","/**\n * Agent factory (§9–§10): builds adapter instances from configuration.\n * \"cli\" agent configs are mapped to the process integration by the loader.\n */\nimport type { AppConfig } from \"../config/index.js\";\nimport { OmniNodeError } from \"../errors/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { AgentConfig, IAgent } from \"../types/agent.js\";\nimport { ProcessAgent } from \"./process/index.js\";\nimport { AgentRegistry } from \"./registry.js\";\nimport { AgentAdapterRegistry, ProcessAgentAdapter } from \"./adapters.js\";\n\n/**\n * Registry consulted first so native/API-level integrations plug in without\n * touching core (roadmap §8, Native Adapters).\n */\nexport const defaultAgentAdapters = new AgentAdapterRegistry();\ndefaultAgentAdapters.register(new ProcessAgentAdapter((config) => new ProcessAgent(config)));\n\nexport function createAgent(config: AgentConfig, adapters: AgentAdapterRegistry = defaultAgentAdapters): IAgent {\n const registered = adapters.get(config.integration);\n if (registered) return registered.create(config);\n if (config.integration === \"native\") {\n throw new OmniNodeError(\n \"NOT_IMPLEMENTED\",\n `No native adapter is registered for \"${config.name}\". Register an IAgentAdapter ` +\n `(createAgent(config, adapters)) or use input over stdin/stdout (type \"cli\").`,\n );\n }\n throw new OmniNodeError(\"NOT_IMPLEMENTED\", `Agent integration \"${config.integration}\" has no adapter yet.`);\n}\n\nexport { AgentAdapterRegistry } from \"./adapters.js\";\nexport type { IAgentAdapter } from \"./adapters.js\";\n\n/** Builds an agent registry from the project configuration, skipping agents that fail to construct. */\nexport function buildAgentRegistry(config: AppConfig, log: Logger = logger): AgentRegistry {\n const registry = new AgentRegistry();\n for (const agentConfig of config.project.agents) {\n try {\n registry.register(createAgent(agentConfig));\n } catch (error) {\n log.warn(\n `Skipping agent \"${agentConfig.name}\": ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n return registry;\n}\n","/** Role registry (§11): the set of roles available for task assignment. */\nimport type { AppConfig } from \"../config/index.js\";\nimport type { RoleDefinition } from \"../types/role.js\";\n\nexport class RoleRegistry {\n private readonly roles = new Map<string, RoleDefinition>();\n\n register(role: RoleDefinition): void {\n this.roles.set(role.id, role);\n }\n\n registerAll(roles: RoleDefinition[]): void {\n for (const role of roles) this.register(role);\n }\n\n get(id: string): RoleDefinition | undefined {\n return this.roles.get(id);\n }\n\n list(): RoleDefinition[] {\n return [...this.roles.values()].sort((a, b) => a.id.localeCompare(b.id));\n }\n}\n\n/** Builds a role registry from the project configuration. */\nexport function buildRoleRegistry(config: AppConfig): RoleRegistry {\n const registry = new RoleRegistry();\n registry.registerAll(config.project.roles);\n return registry;\n}\n","/**\n * Shared JSON file persistence (v2 Phase 12 — Persistence Layer).\n *\n * Guarantees:\n * - **Atomic writes**: temp file → fsync → rename → directory fsync, so a\n * crash never leaves a half-written store.\n * - **Corruption detection**: unparseable files are *quarantined* (renamed,\n * never deleted) and the store continues empty.\n * - **Schema versioning**: documents carry `schemaVersion`; v1 documents are\n * migrated on read, future versions are refused rather than misread.\n */\nimport { open, mkdir, readFile, rename, stat, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { logger, type Logger } from \"../logger/index.js\";\n\n/** Current on-disk schema version. */\nexport const SCHEMA_VERSION = 2;\n\nexport interface JsonDocument<T> {\n schemaVersion?: number;\n items: T[];\n}\n\nexport type DocumentState =\n | { status: \"missing\" }\n | { status: \"empty\" }\n | { status: \"v1-legacy\" }\n | { status: \"current\"; schemaVersion: number; count: number }\n | { status: \"future\"; schemaVersion: number }\n | { status: \"corrupt\"; detail: string };\n\nexport interface JsonFileStoreOptions {\n directory?: string;\n fileName: string;\n /** Schema version to write (defaults to the current version). */\n schemaVersion?: number;\n /** Power-loss durability: \"rename\" (default) or \"fsync\" (slower). */\n durability?: Durability;\n /** Called when a persisted file is corrupt (after quarantine). */\n onCorrupt?: (path: string, error: unknown) => void;\n /** Disable file moves (used by dry runs / tests that inspect in place). */\n quarantine?: boolean;\n}\n\nexport type Durability = \"rename\" | \"fsync\";\n\n/**\n * Writes a file atomically: temp → rename. The rename guarantees readers\n * never observe a torn file. With `durability: \"fsync\"` the data and the\n * directory entry are also flushed, which additionally survives power loss —\n * at a significant per-write cost, so it is opt-in.\n */\nexport async function writeFileAtomic(\n target: string,\n contents: string,\n durability: Durability = \"rename\",\n): Promise<void> {\n const tmp = `${target}.tmp`;\n await mkdir(dirname(target), { recursive: true });\n\n if (durability === \"fsync\") {\n const handle = await open(tmp, \"w\");\n try {\n await handle.writeFile(contents, \"utf8\");\n await handle.sync();\n } finally {\n await handle.close();\n }\n } else {\n await writeFile(tmp, contents, \"utf8\");\n }\n\n await rename(tmp, target);\n\n if (durability === \"fsync\") {\n try {\n const dir = await open(dirname(target), \"r\");\n try {\n await dir.sync();\n } finally {\n await dir.close();\n }\n } catch {\n // Directory fsync is unsupported on some platforms — the rename is still atomic.\n }\n }\n}\n\n/** Reads and classifies a persisted document without modifying it. */\nexport async function inspectDocument(path: string): Promise<DocumentState> {\n let raw: string;\n try {\n await stat(path);\n } catch {\n return { status: \"missing\" };\n }\n try {\n raw = await readFile(path, \"utf8\");\n } catch (error) {\n return { status: \"corrupt\", detail: `unreadable: ${error instanceof Error ? error.message : String(error)}` };\n }\n if (raw.trim().length === 0) return { status: \"empty\" };\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n return { status: \"corrupt\", detail: error instanceof Error ? error.message : \"invalid JSON\" };\n }\n if (Array.isArray(parsed)) return { status: \"v1-legacy\" }; // v1 stored bare arrays\n if (parsed === null || typeof parsed !== \"object\") return { status: \"corrupt\", detail: \"not an object\" };\n const doc = parsed as JsonDocument<unknown>;\n if (!Array.isArray(doc.items)) return { status: \"corrupt\", detail: \"missing items array\" };\n const version = typeof doc.schemaVersion === \"number\" ? doc.schemaVersion : 1;\n if (version > SCHEMA_VERSION) return { status: \"future\", schemaVersion: version };\n if (version < SCHEMA_VERSION) return { status: \"v1-legacy\" };\n return { status: \"current\", schemaVersion: version, count: doc.items.length };\n}\n\n/** Reads a document, migrating v1 shapes and quarantining corruption. */\nexport async function readDocument<T>(\n path: string,\n onCorrupt?: (path: string, error: unknown) => void,\n quarantine = true,\n): Promise<T[]> {\n const state = await inspectDocument(path);\n if (state.status === \"missing\" || state.status === \"empty\") return [];\n if (state.status === \"future\") {\n const error = new Error(\n `${path} was written by a newer OmniNode (schema v${state.schemaVersion} > v${SCHEMA_VERSION})`,\n );\n onCorrupt?.(path, error);\n return [];\n }\n\n let raw: string;\n try {\n raw = await readFile(path, \"utf8\");\n } catch (error) {\n onCorrupt?.(path, error);\n return [];\n }\n try {\n const parsed: unknown = JSON.parse(raw);\n if (Array.isArray(parsed)) return parsed as T[]; // v1 legacy: bare array\n return (parsed as JsonDocument<T>).items ?? [];\n } catch (error) {\n // Preserve the damaged file for inspection instead of overwriting it.\n if (quarantine) {\n const quarantinePath = `${path}.corrupt-${Date.now()}`;\n try {\n await rename(path, quarantinePath);\n logger.child({ component: \"persistence\" }).warn(\n `Quarantined unreadable store file ${path} → ${quarantinePath}`,\n );\n } catch {\n // Quarantine is best effort.\n }\n }\n onCorrupt?.(path, error);\n return [];\n }\n}\n\nexport class JsonFileStore<T> {\n private readonly filePath: string;\n private readonly schemaVersion: number;\n private readonly durability: Durability;\n private readonly onCorrupt?: (path: string, error: unknown) => void;\n private readonly quarantine: boolean;\n private readonly log: Logger;\n private queue: Promise<unknown> = Promise.resolve();\n\n constructor(options: JsonFileStoreOptions) {\n this.filePath = `${options.directory ?? `${process.cwd()}/.omninode`}/${options.fileName}`;\n this.schemaVersion = options.schemaVersion ?? SCHEMA_VERSION;\n this.durability = options.durability ?? \"rename\";\n this.onCorrupt = options.onCorrupt;\n this.quarantine = options.quarantine ?? true;\n this.log = logger.child({ component: \"persistence\", file: options.fileName });\n }\n\n get path(): string {\n return this.filePath;\n }\n\n /** All items, or [] when missing/migrated-from-v1/corrupt. */\n protected async readAll(): Promise<T[]> {\n return readDocument<T>(this.filePath, this.onCorrupt, this.quarantine);\n }\n\n protected async writeAll(items: T[]): Promise<void> {\n const document: JsonDocument<T> = { schemaVersion: this.schemaVersion, items };\n await writeFileAtomic(this.filePath, `${JSON.stringify(document, null, 2)}\\n`, this.durability);\n }\n\n /** Serializes an async operation against this file. */\n protected synchronized<R>(operation: () => Promise<R>): Promise<R> {\n const result = this.queue.then(operation, operation);\n this.queue = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n /** Read-modify-write helper: applies `mutate` to the current items. */\n protected async mutate<R>(mutate: (items: T[]) => Promise<[T[], R]> | [T[], R]): Promise<R> {\n return this.synchronized(async () => {\n const items = await this.readAll();\n const [next, result] = await mutate(items);\n await this.writeAll(next);\n return result;\n });\n }\n}\n","/**\n * Shared memory-contract helpers (roadmap §12). Adapters implement\n * `retrieve` / `store`; these helpers supply the defaults for `search`,\n * `metadata` and the v1 `query` / `write` aliases, so the contract is\n * defined once.\n */\nimport type {\n IMemoryProvider,\n MemoryEntry,\n MemoryProviderMetadata,\n MemoryQuery,\n} from \"../types/memory.js\";\n\n/** Free-text search defaults to a relevance retrieve. */\nexport function defaultSearch(\n provider: Pick<IMemoryProvider, \"retrieve\">,\n text: string,\n options: { limit?: number; scope?: MemoryQuery[\"scope\"] } = {},\n): Promise<MemoryEntry[]> {\n return provider.retrieve({\n text,\n ...(options.scope !== undefined ? { scope: options.scope } : {}),\n ...(options.limit !== undefined ? { limit: options.limit } : {}),\n });\n}\n\nexport function defaultMetadata(\n name: string,\n options: {\n capabilities?: MemoryProviderMetadata[\"capabilities\"];\n relevanceRanking?: boolean;\n backend?: Record<string, unknown>;\n } = {},\n): MemoryProviderMetadata {\n return {\n name,\n capabilities: options.capabilities ?? [\"retrieve\", \"store\", \"search\"],\n relevanceRanking: options.relevanceRanking ?? false,\n ...(options.backend !== undefined ? { backend: options.backend } : {}),\n };\n}","/**\n * Local file-based memory provider: the default implementation so persistent\n * memory works out of the box, locally (§25), with no external service.\n * Relevance is scored by keyword overlap and tag matches — deterministic and\n * dependency-free.\n */\nimport { JsonFileStore } from \"../persistence/json-file-store.js\";\nimport { defaultMetadata, defaultSearch } from \"./base.js\";\nimport type {\n IMemoryProvider,\n MemoryEntry,\n MemoryProviderMetadata,\n MemoryQuery,\n} from \"../types/memory.js\";\n\nconst STOPWORDS = new Set([\n \"the\", \"and\", \"for\", \"with\", \"this\", \"that\", \"from\", \"into\", \"was\", \"were\",\n \"have\", \"has\", \"had\", \"are\", \"but\", \"not\", \"you\", \"his\", \"her\", \"its\",\n \"their\", \"them\", \"then\", \"than\", \"when\", \"what\", \"which\", \"will\", \"would\",\n \"been\", \"were\", \"also\", \"because\", \"about\", \"after\", \"before\",\n]);\n\nexport function keywords(text: string): Set<string> {\n return new Set(\n (text ?? \"\")\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, \" \")\n .split(/\\s+/)\n .filter((t) => t.length >= 4 && !STOPWORDS.has(t)),\n );\n}\n\nfunction relevanceScore(queryKeywords: Set<string>, entry: MemoryEntry): number {\n if (queryKeywords.size === 0) return 0;\n const entryKeywords = keywords(`${entry.content} ${entry.key}`);\n let overlap = 0;\n for (const keyword of queryKeywords) {\n if (entryKeywords.has(keyword)) overlap += 1;\n }\n let tagMatches = 0;\n for (const tag of entry.tags ?? []) {\n if (queryKeywords.has(tag.toLowerCase())) tagMatches += 1;\n }\n return overlap * 2 + tagMatches * 1.5;\n}\n\nexport class LocalMemoryProvider extends JsonFileStore<MemoryEntry> implements IMemoryProvider {\n readonly name = \"local\";\n\n constructor(directory?: string) {\n super({ ...(directory !== undefined ? { directory } : {}), fileName: \"memory.json\" });\n }\n\n metadata(): MemoryProviderMetadata {\n return defaultMetadata(this.name, {\n capabilities: [\"retrieve\", \"store\", \"search\", \"categories\", \"tags\"],\n relevanceRanking: true,\n backend: { kind: \"json-file\", deterministicScoring: true },\n });\n }\n\n search(text: string, options: { limit?: number; scope?: MemoryQuery[\"scope\"] } = {}): Promise<MemoryEntry[]> {\n return defaultSearch(this, text, options);\n }\n\n /** @deprecated v1 alias of {@link retrieve}. */\n query(query: MemoryQuery): Promise<MemoryEntry[]> {\n return this.retrieve(query);\n }\n\n /** @deprecated v1 alias of {@link store}. */\n write(entry: MemoryEntry): Promise<void> {\n return this.store(entry);\n }\n\n async retrieve(query: MemoryQuery): Promise<MemoryEntry[]> {\n const entries = await this.readAll();\n const filtered = entries\n .filter((entry) => (query.scope ? entry.scope === query.scope : true))\n .filter((entry) => (query.category ? entry.category === query.category : true))\n .filter((entry) =>\n query.tags && query.tags.length > 0\n ? query.tags.every((tag) => (entry.tags ?? []).includes(tag))\n : true,\n );\n\n if (!query.text || query.text.trim().length === 0) {\n return filtered\n .sort((a, b) => (b.updatedAt ?? b.createdAt ?? \"\").localeCompare(a.updatedAt ?? a.createdAt ?? \"\"))\n .slice(0, query.limit ?? 10);\n }\n\n const queryKeywords = keywords(query.text);\n return filtered\n .map((entry) => ({ entry, score: relevanceScore(queryKeywords, entry) }))\n .filter(({ score }) => score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, query.limit ?? 10)\n .map(({ entry }) => entry);\n }\n\n store(entry: MemoryEntry): Promise<void> {\n return this.mutate((entries) => {\n const index = entries.findIndex((e) => e.key === entry.key);\n const stamped: MemoryEntry = {\n ...entry,\n createdAt: entry.createdAt ?? new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n };\n if (index >= 0) entries[index] = stamped;\n else entries.push(stamped);\n return [entries, undefined];\n });\n }\n\n async count(): Promise<number> {\n return (await this.readAll()).length;\n }\n}\n","/**\n * Remembera memory provider (§19): the preferred Hilbras memory integration,\n * reached over HTTP. Remembera is strictly optional — the core also runs with\n * the local memory provider or none at all (§2).\n *\n * API convention assumed by this adapter (adjust here if the real API differs):\n * write: POST {baseUrl}/api/memory body: MemoryEntry JSON → 2xx\n * query: POST {baseUrl}/api/memory/query body: MemoryQuery JSON → { entries: MemoryEntry[] }\n */\nimport { MemoryError } from \"../errors/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport { resolveApiKey } from \"../providers/auth.js\";\nimport { requestJson } from \"../providers/http.js\";\nimport type {\n IMemoryProvider,\n MemoryEntry,\n MemoryProviderMetadata,\n MemoryQuery,\n} from \"../types/memory.js\";\nimport { defaultMetadata, defaultSearch } from \"./base.js\";\n\nexport interface RememberaConfig {\n baseUrl: string;\n apiKeyEnvVar?: string;\n env?: Record<string, string | undefined>;\n}\n\nexport class RememberaMemoryProvider implements IMemoryProvider {\n readonly name = \"remembera\";\n private readonly baseUrl: string;\n private readonly apiKeyEnvVar?: string;\n private readonly env: Record<string, string | undefined>;\n private readonly log: Logger;\n\n constructor(config: RememberaConfig, log: Logger = logger) {\n this.baseUrl = config.baseUrl.replace(/\\/+$/, \"\");\n this.apiKeyEnvVar = config.apiKeyEnvVar;\n this.env = config.env ?? process.env;\n this.log = log.child({ component: \"remembera\" });\n }\n\n private get authenticationConfigured(): boolean {\n return this.apiKeyEnvVar === undefined || Boolean(this.env[this.apiKeyEnvVar]);\n }\n\n private headers(): Record<string, string> {\n const key = this.apiKeyEnvVar\n ? resolveApiKey({ name: \"remembera\", apiKeyEnvVar: this.apiKeyEnvVar }, this.env)\n : undefined;\n return key ? { authorization: `Bearer ${key}` } : {};\n }\n\n /** Search delegates to the gateway's relevance query. */\n search(text: string, options: { limit?: number; scope?: MemoryQuery[\"scope\"] } = {}): Promise<MemoryEntry[]> {\n return defaultSearch(\n this,\n text,\n {\n ...(options.scope !== undefined ? { scope: options.scope } : {}),\n ...(options.limit !== undefined ? { limit: options.limit } : {}),\n },\n );\n }\n\n metadata(): MemoryProviderMetadata {\n return defaultMetadata(this.name, {\n capabilities: [\"retrieve\", \"store\", \"search\", \"categories\", \"tags\"],\n relevanceRanking: true,\n backend: { kind: \"http\", baseUrl: this.baseUrl, authenticated: this.authenticationConfigured },\n });\n }\n\n /** @deprecated v1 alias of {@link retrieve}. */\n query(query: MemoryQuery): Promise<MemoryEntry[]> {\n return this.retrieve(query);\n }\n\n /** @deprecated v1 alias of {@link store}. */\n write(entry: MemoryEntry): Promise<void> {\n return this.store(entry);\n }\n\n async retrieve(query: MemoryQuery): Promise<MemoryEntry[]> {\n const { status, body } = await this.request(`${this.baseUrl}/api/memory/query`, query);\n if (status !== 200) {\n throw new MemoryError(`Remembera query returned HTTP ${status}.`);\n }\n const entries = (body as { entries?: unknown }).entries;\n if (!Array.isArray(entries)) {\n throw new MemoryError(\"Remembera query response had no entries array.\");\n }\n return entries.map((entry) => this.toEntry(entry)).filter((entry): entry is MemoryEntry => entry !== undefined);\n }\n\n async store(entry: MemoryEntry): Promise<void> {\n const { status } = await this.request(`${this.baseUrl}/api/memory`, entry);\n if (status !== 200 && status !== 201) {\n throw new MemoryError(`Remembera write returned HTTP ${status}.`);\n }\n }\n\n private async request(url: string, body: unknown): Promise<{ status: number; body: unknown }> {\n // Resolved outside the try so auth failures propagate as-is.\n const headers = this.headers();\n try {\n return await requestJson(url, {\n method: \"POST\",\n headers,\n body,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new MemoryError(`Remembera request to ${url} failed: ${message}`, { cause: error });\n }\n }\n\n private toEntry(raw: unknown): MemoryEntry | undefined {\n if (raw === null || typeof raw !== \"object\") {\n this.log.warn(\"Skipping malformed Remembera memory entry.\");\n return undefined;\n }\n const entry = raw as Record<string, unknown>;\n if (typeof entry.key !== \"string\" || typeof entry.content !== \"string\") {\n this.log.warn(\"Skipping Remembera memory entry without key/content.\");\n return undefined;\n }\n const scope = entry.scope;\n return {\n key: entry.key,\n content: entry.content,\n scope:\n scope === \"project\" || scope === \"role\" || scope === \"task\" || scope === \"knowledge\"\n ? scope\n : \"knowledge\",\n ...(Array.isArray(entry.tags) ? { tags: entry.tags.filter((t): t is string => typeof t === \"string\") } : {}),\n ...(typeof entry.category === \"string\"\n ? { category: entry.category as MemoryEntry[\"category\"] }\n : {}),\n ...(typeof entry.createdAt === \"string\" ? { createdAt: entry.createdAt } : {}),\n ...(typeof entry.updatedAt === \"string\" ? { updatedAt: entry.updatedAt } : {}),\n };\n }\n}\n","/** Memory provider factory: memory is optional; local is the default. */\nimport { ConfigError } from \"../errors/index.js\";\nimport type { AppConfig } from \"../config/index.js\";\nimport type { IMemoryProvider } from \"../types/memory.js\";\nimport { LocalMemoryProvider } from \"./local.js\";\nimport { RememberaMemoryProvider } from \"./remembera.js\";\n\nexport type MemoryProviderConfig = NonNullable<AppConfig[\"project\"][\"memory\"]>;\n\nexport function createMemoryProvider(config?: MemoryProviderConfig): IMemoryProvider {\n if (!config || config.provider === \"local\") {\n return new LocalMemoryProvider();\n }\n if (config.provider === \"remembera\") {\n if (!config.baseUrl) {\n throw new ConfigError(\n \"CONFIG_INVALID\",\n `Memory provider \"remembera\" needs a base_url in omninode.yaml.`,\n );\n }\n return new RememberaMemoryProvider({\n baseUrl: config.baseUrl,\n apiKeyEnvVar: config.apiKeyEnvVar,\n });\n }\n throw new ConfigError(\n \"CONFIG_INVALID\",\n `Unknown memory provider \"${config.provider}\". Available: local, remembera.`,\n );\n}\n","/**\n * Memory service + context manager (§12, Context Retrieval):\n *\n * Task → context query → relevant memory → context → agent/planner\n *\n * Retrieval is task-oriented and budgeted — OmniNode never loads all memory\n * into a prompt. Failures are best-effort by default; when memory is marked\n * `required`, they become fatal instead (§12, Failure Handling).\n */\nimport { MemoryError } from \"../errors/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { IMemoryProvider, MemoryEntry } from \"../types/memory.js\";\nimport type { Task } from \"../types/task.js\";\n\nexport interface MemoryContextQuery {\n objective: string;\n role?: string;\n project?: string;\n /** Maximum entries to consider (relevance-ranked by the provider). */\n limit?: number;\n}\n\nexport interface MemoryTaskContext {\n /** Prompt-ready context text (\"\" when nothing relevant was found). */\n text: string;\n entries: MemoryEntry[];\n /** True when the character budget cut the context short. */\n truncated: boolean;\n}\n\nconst DEFAULT_ENTRY_LIMIT = 8;\nexport const MAX_CONTEXT_CHARS = 4_000;\n\nexport interface MemoryServiceOptions {\n /** When true, backend failures propagate instead of being logged. */\n required?: boolean;\n maxContextChars?: number;\n}\n\nexport class MemoryService {\n private readonly log: Logger;\n private readonly required: boolean;\n private readonly maxContextChars: number;\n\n constructor(\n private readonly provider: IMemoryProvider,\n log: Logger = logger,\n options: MemoryServiceOptions = {},\n ) {\n this.log = log.child({ component: \"memory\", provider: provider.name });\n this.required = options.required ?? false;\n this.maxContextChars = options.maxContextChars ?? MAX_CONTEXT_CHARS;\n }\n\n get providerRef(): IMemoryProvider {\n return this.provider;\n }\n\n get providerName(): string {\n return this.provider.name;\n }\n\n get isRequired(): boolean {\n return this.required;\n }\n\n /** Structured, budgeted context for a task (§12 — avoid loading all memory). */\n async contextFor(query: MemoryContextQuery): Promise<MemoryTaskContext> {\n let entries: MemoryEntry[];\n try {\n entries = await this.provider.retrieve({\n text: query.objective,\n ...(query.role ? { tags: [query.role] } : {}),\n limit: query.limit ?? DEFAULT_ENTRY_LIMIT,\n });\n } catch (error) {\n return this.handleFailure(\"retrieve\", error, { text: \"\", entries: [], truncated: false });\n }\n return this.format(entries);\n }\n\n /** Prompt-ready context text (v1 convenience wrapper). */\n async gatherContext(query: MemoryContextQuery): Promise<string> {\n return (await this.contextFor(query)).text;\n }\n\n /** Records a finished task's outcome — task history plus \"known problems\" (§12). */\n async recordTaskOutcome(task: Task): Promise<void> {\n const outcome = task.result?.summary ?? task.result?.error ?? \"(no output)\";\n try {\n await this.provider.store({\n key: `task:${task.id}`,\n scope: \"task\",\n category: \"tasks\",\n content: `Objective: ${task.objective}\\nStatus: ${task.status}\\nOutcome: ${outcome}`,\n tags: [\"task\", ...(task.agent ? [task.agent] : []), ...(task.role ? [task.role] : [])],\n createdAt: task.createdAt,\n });\n const significant = (task.result?.reports ?? []).flatMap((report) =>\n report.findings\n .filter((finding) => finding.severity === \"high\" || finding.severity === \"critical\")\n .map((finding) => ({ report, finding })),\n );\n for (const { report, finding } of significant) {\n await this.provider.store({\n key: `finding:${report.id}:${finding.id}`,\n scope: \"project\",\n category: \"problems\",\n content: `[${finding.severity}] ${finding.title} — ${finding.detail}`,\n tags: [\"known-problem\", report.agent],\n });\n }\n } catch (error) {\n this.handleFailure(\"store\", error, undefined);\n }\n }\n\n private format(entries: MemoryEntry[]): MemoryTaskContext {\n if (entries.length === 0) return { text: \"\", entries, truncated: false };\n const byScope = new Map<string, MemoryEntry[]>();\n for (const entry of entries) {\n byScope.set(entry.scope, [...(byScope.get(entry.scope) ?? []), entry]);\n }\n const parts: string[] = [];\n for (const scope of [\"project\", \"task\", \"role\", \"knowledge\"]) {\n const scopeEntries = byScope.get(scope) ?? [];\n if (scopeEntries.length === 0) continue;\n const lines = scopeEntries\n .map((entry) => {\n const category = entry.category ? `[${entry.category}] ` : \"\";\n return `- ${category}${entry.content}`;\n })\n .join(\"\\n\");\n parts.push(`### Relevant memory (${scope})\\n${lines}`);\n }\n let text = parts.join(\"\\n\\n\");\n const truncated = text.length > this.maxContextChars;\n if (truncated) text = `${text.slice(0, this.maxContextChars - 1)}…`;\n return { text, entries, truncated };\n }\n\n /**\n * Failure policy (§12): continue unless memory is explicitly required.\n */\n private handleFailure(operation: string, error: unknown, fallback?: MemoryTaskContext): MemoryTaskContext {\n const message = error instanceof Error ? error.message : String(error);\n if (this.required) {\n throw new MemoryError(\n `Memory is marked required, but ${operation} failed: ${message}`,\n { cause: error },\n );\n }\n this.log.warn(`Memory ${operation} failed (continuing without memory): ${message}`);\n return fallback ?? { text: \"\", entries: [], truncated: false };\n }\n}","/**\n * Pipeline run persistence (§27 Phase 5 — pipeline state). Same\n * replaceable-store pattern as the task store, local-first JSON file.\n */\nimport { JsonFileStore } from \"../persistence/json-file-store.js\";\nimport type { PipelineRun, PipelineRunStatus } from \"../types/pipeline.js\";\n\nexport interface PipelineRunFilter {\n pipelineId?: string;\n status?: PipelineRunStatus;\n}\n\nexport interface PipelineRunStore {\n save(run: PipelineRun): Promise<void>;\n get(id: string): Promise<PipelineRun | undefined>;\n list(filter?: PipelineRunFilter): Promise<PipelineRun[]>;\n}\n\nexport class FilePipelineRunStore extends JsonFileStore<PipelineRun> implements PipelineRunStore {\n constructor(directory?: string) {\n super({ ...(directory !== undefined ? { directory } : {}), fileName: \"pipelines.json\" });\n }\n\n save(run: PipelineRun): Promise<void> {\n return this.mutate((runs) => {\n const index = runs.findIndex((r) => r.id === run.id);\n if (index >= 0) runs[index] = run;\n else runs.push(run);\n return [runs, undefined];\n });\n }\n\n async get(id: string): Promise<PipelineRun | undefined> {\n return (await this.readAll()).find((r) => r.id === id);\n }\n\n async list(filter: PipelineRunFilter = {}): Promise<PipelineRun[]> {\n return (await this.readAll())\n .filter((run) => (filter.pipelineId ? run.pipelineId === filter.pipelineId : true))\n .filter((run) => (filter.status ? run.status === filter.status : true))\n .sort((a, b) => (a.startedAt ?? \"\").localeCompare(b.startedAt ?? \"\"));\n }\n}\n","/**\n * Task persistence (§4.1 — execution state). The store is replaceable\n * (§2 — Modular); the default implementation is a local JSON file so\n * OmniNode stays local-first (§25).\n */\nimport { JsonFileStore } from \"../persistence/json-file-store.js\";\nimport type { Task, TaskStatus } from \"../types/task.js\";\n\nexport interface TaskStoreFilter {\n status?: TaskStatus;\n project?: string;\n}\n\nexport interface TaskStore {\n save(task: Task): Promise<void>;\n get(id: string): Promise<Task | undefined>;\n list(filter?: TaskStoreFilter): Promise<Task[]>;\n}\n\nexport class FileTaskStore extends JsonFileStore<Task> implements TaskStore {\n constructor(directory?: string) {\n super({ ...(directory !== undefined ? { directory } : {}), fileName: \"tasks.json\" });\n }\n\n save(task: Task): Promise<void> {\n return this.mutate((tasks) => {\n const index = tasks.findIndex((t) => t.id === task.id);\n if (index >= 0) tasks[index] = task;\n else tasks.push(task);\n return [tasks, undefined];\n });\n }\n\n async get(id: string): Promise<Task | undefined> {\n const tasks = await this.readAll();\n return tasks.find((t) => t.id === id);\n }\n\n async list(filter: TaskStoreFilter = {}): Promise<Task[]> {\n const tasks = await this.readAll();\n return tasks\n .filter((task) => (filter.status ? task.status === filter.status : true))\n .filter((task) => (filter.project ? task.project === filter.project : true))\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n }\n}\n","/**\n * `omninode <subject> inspect` — post-hoc diagnostics (roadmap §18): everything\n * known about a task, pipeline run, agent or provider, so a failed execution\n * can be understood after the fact. `--json` emits the raw records.\n */\nimport type { Command } from \"commander\";\nimport { loadConfig } from \"../../config/index.js\";\nimport { buildAgentRegistry } from \"../../agents/index.js\";\nimport { buildRoleRegistry } from \"../../roles/index.js\";\nimport { createMemoryProvider, MemoryService } from \"../../memory/index.js\";\nimport { OmniNodeError } from \"../../errors/index.js\";\nimport { FilePipelineRunStore } from \"../../pipelines/store.js\";\nimport { FileTaskStore } from \"../../tasks/store.js\";\nimport { resolveEnvPolicy } from \"../../agents/env.js\";\n\nfunction emit(json: boolean, payload: unknown, render: () => void): void {\n if (json) {\n console.log(JSON.stringify(payload, null, 2));\n return;\n }\n render();\n}\n\nfunction jsonOption(command: Command): Command {\n return command.option(\"--json\", \"Emit the raw record as JSON.\");\n}\n\n/** Registers `task inspect` on the existing task group. */\nexport function registerTaskInspect(taskGroup: Command): void {\n jsonOption(\n taskGroup\n .command(\"inspect <id>\")\n .description(\"Show a task with its execution history, result and report references.\")\n .action(async (id: string, options: { json?: boolean }) => {\n const tasks = await new FileTaskStore().list();\n const task = tasks.find((t) => t.id === id);\n if (!task) throw new OmniNodeError(\"TASK_NOT_FOUND\", `No task \"${id}\" in this project's store.`);\n emit(options.json ?? false, task, () => {\n console.log(`Task ${task.id}`);\n console.log(` status: ${task.status}${task.attempt > 0 ? ` (attempt ${task.attempt})` : \"\"}`);\n if (task.project) console.log(` project: ${task.project}`);\n if (task.pipelineId) console.log(` pipeline: ${task.pipelineId}`);\n console.log(` objective: ${task.objective}`);\n if (task.role) console.log(` role: ${task.role}`);\n if (task.agent) console.log(` agent: ${task.agent}`);\n console.log(` created: ${task.createdAt}`);\n console.log(` updated: ${task.updatedAt}`);\n if (task.lastError) console.log(` lastError: ${task.lastError}`);\n if (task.executions && task.executions.length > 0) {\n console.log(\" executions:\");\n for (const execution of task.executions) {\n console.log(\n ` #${execution.attempt} ${execution.outcome} (${execution.executionId})` +\n `${execution.error ? ` — ${execution.error}` : \"\"}`,\n );\n }\n }\n if (task.result?.summary) console.log(` summary: ${task.result.summary}`);\n if (task.result?.reports && task.result.reports.length > 0) {\n console.log(` reports: ${task.result.reports.length}`);\n for (const report of task.result.reports) {\n console.log(` - [${report.agent}] ${report.summary}`);\n for (const finding of report.findings) {\n console.log(` · [${finding.severity ?? \"info\"}] ${finding.title}`);\n }\n }\n }\n });\n }),\n );\n}\n\n/** Registers `pipeline inspect` on the pipeline group. */\nexport function registerPipelineInspect(pipelineGroup: Command): void {\n jsonOption(\n pipelineGroup\n .command(\"inspect <run-id>\")\n .description(\"Show a pipeline run with per-step status and artifact references.\")\n .action(async (runId: string, options: { json?: boolean }) => {\n const run = await new FilePipelineRunStore().get(runId);\n if (!run) throw new OmniNodeError(\"PIPELINE_NOT_FOUND\", `No pipeline run \"${runId}\" in this project's store.`);\n emit(options.json ?? false, run, () => {\n console.log(`Pipeline run ${run.id} (${run.pipelineId})`);\n console.log(` status: ${run.status}${run.attempt > 1 ? ` (attempt ${run.attempt})` : \"\"}`);\n if (run.objective) console.log(` objective: ${run.objective}`);\n console.log(` started: ${run.startedAt ?? \"?\"}`);\n if (run.finishedAt) console.log(` finished: ${run.finishedAt}`);\n if (run.planId) console.log(` plan: ${run.planId}`);\n if (run.combinedReportId) console.log(` combined: ${run.combinedReportId}`);\n if (run.resultSummary) console.log(` result: ${run.resultSummary}`);\n console.log(\" steps:\");\n for (const step of run.stepRuns) {\n const stepTaskIds = step.taskIds ?? [];\n const tasks = stepTaskIds.length > 0 ? ` tasks=${stepTaskIds.join(\",\")}` : \"\";\n console.log(` ${step.stepId.padEnd(14)} ${step.status}${tasks}${step.error ? ` — ${step.error}` : \"\"}`);\n }\n });\n }),\n );\n}\n\n/** Registers `agent inspect` on the agent group. */\nexport function registerAgentInspect(agentGroup: Command): void {\n jsonOption(\n agentGroup\n .command(\"inspect <name>\")\n .description(\"Show an agent's effective configuration and recent tasks.\")\n .action(async (name: string, options: { json?: boolean }) => {\n const config = loadConfig();\n const agentConfig = config.project.agents.find((a) => a.name === name);\n if (!agentConfig) throw new OmniNodeError(\"AGENT_NOT_FOUND\", `No agent \"${name}\" is configured.`);\n const registry = buildAgentRegistry(config);\n const agent = registry.get(name);\n const recent = (await new FileTaskStore().list())\n .filter((task) => task.agent === name)\n .slice(-5)\n .map((task) => ({ id: task.id, status: task.status, updatedAt: task.updatedAt }));\n const payload = {\n config: agentConfig,\n effective: agent?.info,\n envPolicy: resolveEnvPolicy(agentConfig),\n recentTasks: recent,\n };\n emit(options.json ?? false, payload, () => {\n console.log(`Agent ${name}`);\n console.log(` integration: ${agentConfig.integration}`);\n console.log(` command: ${agentConfig.command ?? \"(none)\"}`);\n console.log(` input mode: ${agentConfig.inputMode ?? \"stdin\"}`);\n console.log(` env policy: ${resolveEnvPolicy(agentConfig)}`);\n if (agentConfig.cwd) console.log(` working dir: ${agentConfig.cwd}`);\n if (agentConfig.timeoutMs) console.log(` timeout: ${agentConfig.timeoutMs}ms`);\n if (agentConfig.maxOutputBytes) console.log(` max output: ${agentConfig.maxOutputBytes} bytes/stream`);\n if (agentConfig.allowExternalCwd) console.log(` external cwd allowed`);\n console.log(` recent tasks: ${recent.map((t) => `${t.id}:${t.status}`).join(\", \") || \"(none)\"}`);\n });\n }),\n );\n}\n\n/** Registers `provider inspect` on the provider group. */\nexport function registerProviderInspect(providerGroup: Command): void {\n jsonOption(\n providerGroup\n .command(\"inspect <name>\")\n .description(\"Show a provider's authentication status and capabilities.\")\n .action(async (name: string, options: { json?: boolean }) => {\n const config = loadConfig();\n const providerConfig = config.project.providers.find((p) => p.name === name);\n if (!providerConfig) throw new OmniNodeError(\"PROVIDER_NOT_FOUND\", `No provider \"${name}\" is configured.`);\n const { createProvider } = await import(\"../../providers/index.js\");\n const provider = createProvider(providerConfig);\n const payload = {\n config: providerConfig,\n providerId: provider.providerId,\n authentication: provider.authentication,\n capabilities: providerConfig.capabilities ?? [],\n memoryConfigured: config.project.memory\n ? { provider: config.project.memory.provider, required: config.project.memory.required ?? false }\n : undefined,\n memoryEntries: config.project.memory\n ? await new MemoryService(createMemoryProvider(config.project.memory)).providerRef.query({ limit: 10_000 }).then((e) => e.length)\n : undefined,\n roles: buildRoleRegistry(config).list().length,\n };\n emit(options.json ?? false, payload, () => {\n console.log(`Provider ${name}`);\n console.log(` providerId: ${provider.providerId}`);\n console.log(` type: ${providerConfig.type}`);\n console.log(` base URL: ${providerConfig.baseUrl}`);\n console.log(` auth: ${provider.authentication.method}${provider.authentication.envVar ? ` ($${provider.authentication.envVar})` : \"\"}`);\n console.log(` credentials: ${provider.authentication.configured ? \"configured\" : \"MISSING\"}`);\n if (providerConfig.capabilities?.length) {\n console.log(` capabilities: ${providerConfig.capabilities.join(\", \")}`);\n }\n });\n }),\n );\n}\n","import type { Command } from \"commander\";\nimport { findConfigFile, loadConfig, providerConfigSchema } from \"../../config/index.js\";\nimport { OmniNodeError, ProviderError } from \"../../errors/index.js\";\nimport { createProvider, OmniHilbrasProvider } from \"../../providers/index.js\";\nimport { ModelRegistry } from \"../../registry/index.js\";\nimport type { ProviderStatus } from \"../../types/provider.js\";\nimport { appendToConfigList, notImplemented } from \"./shared.js\";\nimport { registerProviderInspect } from \"./inspect.js\";\n\ninterface AddProviderOptions {\n name: string;\n baseUrl: string;\n type: string;\n apiKeyEnvVar?: string;\n}\n\nexport function registerProviderCommands(program: Command): void {\n const provider = program\n .command(\"provider\")\n .description(\"Manage AI providers configured in omninode.yaml.\");\n\n provider\n .command(\"list\")\n .description(\"List configured providers.\")\n .action(async () => {\n const config = loadConfig();\n const providers = config.project.providers;\n if (providers.length === 0) {\n console.log(\n \"No providers configured. Add one with `omninode provider add` or edit omninode.yaml.\",\n );\n return;\n }\n for (const provider of providers) {\n const key = provider.apiKeyEnvVar ? `$${provider.apiKeyEnvVar}` : \"none\";\n const enabled = provider.enabled === false ? \" (disabled)\" : \"\";\n console.log(\n `${provider.name} type=${provider.type} base_url=${provider.baseUrl} key=${key}${enabled}`,\n );\n }\n });\n\n provider\n .command(\"add\")\n .description(\n \"Add a provider to omninode.yaml. OpenAI-compatible gateways (including OpenRouter \" +\n \"and local runtimes) are supported today; OmniHilbras gets its own adapter in Phase 2.\",\n )\n .requiredOption(\"--name <name>\", \"Unique provider name used in configuration and the model registry.\")\n .requiredOption(\"--base-url <url>\", \"Provider base URL, e.g. https://example.com/v1\")\n .option(\n \"--type <type>\",\n \"Provider type: openai-compatible, omnihilbras, openrouter, local or custom.\",\n \"openai-compatible\",\n )\n .option(\n \"--api-key-env-var <envVar>\",\n \"Environment variable holding the API key. Keys are never written to the config file.\",\n )\n .action(async (options: AddProviderOptions) => addProvider(options));\n\n provider\n .command(\"test <name>\")\n .description(\"Test connectivity, authentication and model discovery for a configured provider.\")\n .option(\n \"--connect\",\n \"Run the full provider connect flow (authenticate, fetch, validate, register) where the adapter supports it.\",\n )\n .action(async (name: string, options: { connect?: boolean }) => testProvider(name, options));\n\n provider\n .command(\"remove <name>\")\n .description(\"Remove a provider (planned for Phase 1 follow-up).\")\n .action(() => {\n throw notImplemented(\"omninode provider remove\", \"a Phase 1 follow-up\");\n });\n registerProviderInspect(provider);\n}\n\nexport async function addProvider(options: AddProviderOptions): Promise<void> {\n const configPath = findConfigFile();\n if (!configPath) {\n throw new OmniNodeError(\"CONFIG_NOT_FOUND\", \"No omninode.yaml found. Run `omninode init` first.\");\n }\n\n const candidate = providerConfigSchema.safeParse({\n name: options.name,\n type: options.type,\n base_url: options.baseUrl,\n ...(options.apiKeyEnvVar !== undefined ? { api_key_env_var: options.apiKeyEnvVar } : {}),\n });\n if (!candidate.success) {\n const issues = candidate.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"(root)\"}: ${issue.message}`)\n .join(\"; \");\n throw new OmniNodeError(\"CLI_USAGE\", `Invalid provider options: ${issues}`);\n }\n const newProvider = candidate.data;\n\n // Existing name check happens before the document is edited.\n const existing = loadConfig();\n if (existing.project.providers.some((p) => p.name === newProvider.name)) {\n throw new OmniNodeError(\n \"CLI_USAGE\",\n `Provider \"${newProvider.name}\" already exists in ${findConfigFile() ?? \"omninode.yaml\"}.`,\n );\n }\n\n const writtenPath = appendToConfigList(\"providers\", newProvider);\n console.log(`Added provider \"${newProvider.name}\" (${newProvider.type}) to ${writtenPath}.`);\n if (newProvider.api_key_env_var) {\n console.log(\n `Set $${newProvider.api_key_env_var} in your environment, then run: omninode provider test ${newProvider.name}`,\n );\n } else {\n console.log(`Run \\`omninode provider test ${newProvider.name}\\` to verify connectivity.`);\n }\n}\n\nexport async function testProvider(\n name: string,\n options: { connect?: boolean } = {},\n): Promise<void> {\n const config = loadConfig();\n const providerConfig = config.project.providers.find((p) => p.name === name);\n if (!providerConfig) {\n const available = config.project.providers.map((p) => p.name).join(\", \") || \"(none)\";\n throw new ProviderError(\n \"PROVIDER_NOT_FOUND\",\n `Provider \"${name}\" is not configured. Configured providers: ${available}.`,\n );\n }\n\n const provider = createProvider(providerConfig);\n console.log(`Testing provider \"${name}\" (${providerConfig.type}) at ${provider.config.baseUrl}`);\n\n if (options.connect && provider instanceof OmniHilbrasProvider) {\n const registry = new ModelRegistry();\n try {\n const result = await provider.connectAndRegister(registry);\n printProviderStatus(result.status);\n console.log(` registered: ${result.registered}`);\n } catch (error) {\n console.log(` connect failed: ${error instanceof Error ? error.message : String(error)}`);\n process.exitCode = 1;\n }\n return;\n }\n\n const health = await provider.healthCheck();\n printProviderStatus(health);\n if (!health.connected) process.exitCode = 1;\n}\n\nfunction printProviderStatus(status: ProviderStatus): void {\n console.log(` health: ${status.health}`);\n console.log(` connected: ${status.connected}`);\n console.log(` models: ${status.modelCount}`);\n if (status.message) console.log(` detail: ${status.message}`);\n}\n","import type { Command } from \"commander\";\nimport { loadConfig } from \"../../config/index.js\";\nimport { OmniNodeError } from \"../../errors/index.js\";\nimport { createProvider } from \"../../providers/index.js\";\nimport { ModelRegistry } from \"../../registry/index.js\";\nimport type { ModelCapabilities } from \"../../types/model.js\";\n\nconst CAPABILITIES: readonly (keyof ModelCapabilities)[] = [\n \"chat\",\n \"coding\",\n \"tools\",\n \"vision\",\n \"embeddings\",\n];\n\nexport function registerModelsCommand(program: Command): void {\n program\n .command(\"models\")\n .description(\"Discover and list models from configured providers (model registry, §8).\")\n .argument(\"[provider]\", \"Only discover from this provider.\")\n .option(\"-c, --capability <capability>\", `Filter by capability: ${CAPABILITIES.join(\", \")}.`)\n .action(async (providerName: string | undefined, options: { capability?: string }) => {\n const capability = options.capability as keyof ModelCapabilities | undefined;\n if (capability !== undefined && !CAPABILITIES.includes(capability)) {\n throw new OmniNodeError(\n \"CLI_USAGE\",\n `Unknown capability \"${options.capability}\". Valid capabilities: ${CAPABILITIES.join(\", \")}.`,\n );\n }\n\n const config = loadConfig();\n const selected = config.project.providers.filter((p) =>\n providerName ? p.name === providerName : true,\n );\n if (selected.length === 0) {\n throw new OmniNodeError(\n \"PROVIDER_NOT_FOUND\",\n providerName\n ? `Provider \"${providerName}\" is not configured.`\n : \"No providers configured. Add one with `omninode provider add`.\",\n );\n }\n\n const registry = new ModelRegistry();\n for (const providerConfig of selected) {\n try {\n const provider = createProvider(providerConfig);\n const discovered = await registry.discoverFrom(provider);\n console.log(`${providerConfig.name}: ${discovered.length} model(s)`);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.log(`${providerConfig.name}: discovery failed — ${message}`);\n }\n }\n\n const models = registry.list({\n ...(providerName !== undefined ? { provider: providerName } : {}),\n ...(capability !== undefined ? { capability } : {}),\n });\n if (models.length === 0) {\n console.log(\"No models found.\");\n return;\n }\n console.log(\"\");\n for (const model of models) {\n console.log(`${model.provider}:${model.id}`);\n }\n });\n}\n","import type { Command } from \"commander\";\nimport { agentConfigSchema, loadConfig } from \"../../config/index.js\";\nimport { AgentError, OmniNodeError } from \"../../errors/index.js\";\nimport { createAgent } from \"../../agents/index.js\";\nimport { appendToConfigList } from \"./shared.js\";\nimport { registerAgentInspect } from \"./inspect.js\";\n\nconst collectArgs = (value: string, previous: string[]): string[] => [...previous, value];\n\ninterface AddAgentOptions {\n name: string;\n command: string;\n arg?: string[];\n cwd?: string;\n inputMode: string;\n timeoutMs?: number;\n envPolicy?: string;\n allowEnv?: string[];\n denyEnv?: string[];\n maxOutputBytes?: number;\n allowExternalCwd?: boolean;\n}\n\nexport function registerAgentCommands(program: Command): void {\n const agent = program\n .command(\"agent\")\n .description(\"Manage CLI agents registered with OmniNode.\");\n\n agent\n .command(\"list\")\n .description(\"List configured agents.\")\n .action(async () => {\n const config = loadConfig();\n const agents = config.project.agents;\n if (agents.length === 0) {\n console.log(\"No agents configured. Add one with `omninode agent add` or edit omninode.yaml.\");\n return;\n }\n for (const agent of agents) {\n const command = agent.command ?? \"(no command)\";\n console.log(\n `${agent.name} integration=${agent.integration} command=${command} input=${agent.inputMode ?? \"stdin\"}`,\n );\n }\n });\n\n agent\n .command(\"add\")\n .description(\n \"Register a CLI agent in omninode.yaml. Agents run as child processes \" +\n \"(stdin/stdout); native adapters come in a later phase.\",\n )\n .requiredOption(\"--name <name>\", \"Unique agent name.\")\n .requiredOption(\"--command <command>\", \"Executable command, e.g. opencode\")\n .option(\"--arg <value>\", \"Additional command argument (repeatable).\", collectArgs, [])\n .option(\"--cwd <dir>\", \"Working directory for the agent process.\")\n .option(\n \"--input-mode <mode>\",\n \"How the task is delivered: stdin (prompt on stdin), arg (prompt as last argument) or protocol (§21 JSON-lines task protocol).\",\n \"stdin\",\n )\n .option(\"--env-policy <policy>\", \"Environment policy: inherit, allowlist, denylist or explicit.\")\n .option(\"--allow-env <name>\", \"Variable to forward under the allowlist policy (repeatable).\", collectArgs)\n .option(\"--deny-env <name>\", \"Variable to remove under the denylist policy (repeatable).\", collectArgs)\n .option(\"--max-output-bytes <n>\", \"Per-stream output budget in bytes (default 5 MiB).\", (value: string) => Number(value))\n .option(\"--allow-external-cwd\", \"Allow a working directory outside the project root.\")\n .option(\"--timeout-ms <ms>\", \"Per-task timeout in milliseconds.\", (value: string) =>\n Number(value),\n )\n .action(async (options: AddAgentOptions) => addAgent(options));\n\n agent\n .command(\"test <name>\")\n .description(\"Verify the OmniNode ↔ agent connection by sending a trivial task.\")\n .action(async (name: string) => testAgent(name));\n registerAgentInspect(agent);\n}\n\nexport async function addAgent(options: AddAgentOptions): Promise<void> {\n const candidate = agentConfigSchema.safeParse({\n name: options.name,\n type: \"cli\",\n command: options.command,\n ...(options.arg !== undefined && options.arg.length > 0 ? { args: options.arg } : {}),\n ...(options.cwd !== undefined ? { cwd: options.cwd } : {}),\n input_mode: options.inputMode,\n ...(options.timeoutMs !== undefined ? { timeout_ms: options.timeoutMs } : {}),\n ...(options.envPolicy !== undefined ? { env_policy: options.envPolicy } : {}),\n ...(options.allowEnv !== undefined && options.allowEnv.length > 0\n ? { env_allowlist: options.allowEnv }\n : {}),\n ...(options.denyEnv !== undefined && options.denyEnv.length > 0\n ? { env_denylist: options.denyEnv }\n : {}),\n ...(options.maxOutputBytes !== undefined ? { max_output_bytes: options.maxOutputBytes } : {}),\n ...(options.allowExternalCwd !== undefined ? { allow_external_cwd: options.allowExternalCwd } : {}),\n });\n if (!candidate.success) {\n const issues = candidate.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"(root)\"}: ${issue.message}`)\n .join(\"; \");\n throw new OmniNodeError(\"CLI_USAGE\", `Invalid agent options: ${issues}`);\n }\n const newAgent = candidate.data;\n\n const existing = loadConfig();\n if (existing.project.agents.some((a) => a.name === newAgent.name)) {\n throw new OmniNodeError(\n \"CLI_USAGE\",\n `Agent \"${newAgent.name}\" already exists in omninode.yaml. Remove it first or pick another name.`,\n );\n }\n\n const configPath = appendToConfigList(\"agents\", newAgent);\n console.log(`Added agent \"${newAgent.name}\" (${newAgent.type}, input=${newAgent.input_mode}) to ${configPath}.`);\n console.log(`Run \\`omninode agent test ${newAgent.name}\\` to verify the connection.`);\n}\n\nexport async function testAgent(name: string): Promise<void> {\n const config = loadConfig();\n const agentConfig = config.project.agents.find((a) => a.name === name);\n if (!agentConfig) {\n const available = config.project.agents.map((a) => a.name).join(\", \") || \"(none)\";\n throw new AgentError(\n \"AGENT_NOT_FOUND\",\n `Agent \"${name}\" is not configured. Configured agents: ${available}.`,\n );\n }\n\n const agent = createAgent(agentConfig);\n console.log(\n `Testing agent \"${name}\" (${agent.info.integration}, input=${agentConfig.inputMode ?? \"stdin\"}) — sending a trivial task.`,\n );\n const result = await agent.run({\n taskId: `test-${Date.now()}`,\n objective: \"Reply with the single word: OK\",\n });\n console.log(` status: ${result.status}`);\n if (result.exitCode !== undefined) console.log(` exit: ${result.exitCode}`);\n if (result.summary) console.log(` output: ${result.summary}`);\n if (result.rawOutput && result.rawOutput !== result.summary) {\n console.log(` raw: ${result.rawOutput.slice(0, 200).replace(/\\n/g, \" \")}`);\n }\n if (result.error) console.log(` error: ${result.error}`);\n if (result.status !== \"completed\") process.exitCode = 1;\n}\n","import type { Command } from \"commander\";\nimport { loadConfig } from \"../../config/index.js\";\n\nexport function registerRoleCommands(program: Command): void {\n const role = program\n .command(\"role\")\n .description(\"Inspect roles defined in omninode.yaml.\");\n\n role\n .command(\"list\")\n .description(\"List configured roles.\")\n .action(async () => {\n const config = loadConfig();\n const roles = config.project.roles;\n if (roles.length === 0) {\n console.log(\"No roles configured. Add one under `project.roles` in omninode.yaml.\");\n return;\n }\n for (const role of roles) {\n console.log(`${role.id} ${role.name}`);\n for (const responsibility of role.responsibilities) {\n console.log(` - ${responsibility}`);\n }\n }\n });\n}\n","/**\n * Task engine (§13, §27 Phase 4): owns the task lifecycle — create, queue,\n * run, cancel — validates role/agent assignment against the registries and\n * persists every transition through the task store.\n */\nimport { randomBytes } from \"node:crypto\";\nimport type { AgentRegistry } from \"../agents/index.js\";\nimport type { RoleRegistry } from \"../roles/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport { AgentError, TaskError } from \"../errors/index.js\";\nimport type { AuditAction, AuditSink } from \"../audit/index.js\";\nimport type { MemoryService } from \"../memory/index.js\";\nimport type {\n ExecutionRecord,\n Task,\n TaskContext,\n TaskResult,\n TaskStatus,\n} from \"../types/task.js\";\nimport type { TaskStore, TaskStoreFilter } from \"./store.js\";\n\n/**\n * Strict state machine (roadmap §6.2). Invalid transitions are rejected —\n * engines never mutate state directly.\n *\n * created ──▶ queued ──▶ running ──┬─▶ completed\n * │ │ │ ├─▶ failed\n * │ │ │ ├─▶ timed_out (no side effects possible)\n * └───────────┴─────────┴────────┼─▶ unknown (outcome unprovable — e.g. killed after dispatch)\n * ├─▶ cancelled\n * └─▶ partially_completed (fan-out where some units succeeded)\n */\nconst ALLOWED_TRANSITIONS: Record<TaskStatus, TaskStatus[]> = {\n created: [\"queued\", \"running\", \"cancelled\"],\n queued: [\"running\", \"cancelled\"],\n running: [\"completed\", \"failed\", \"timed_out\", \"unknown\", \"cancelled\", \"partially_completed\"],\n waiting: [\"running\", \"cancelled\"],\n completed: [],\n // failed → running is the only re-entry: bounded automatic retry (§6.4).\n failed: [\"running\"],\n timed_out: [],\n cancelled: [],\n unknown: [],\n partially_completed: [],\n};\n\n/**\n * Error codes safe to retry automatically: a transient agent crash before any\n * report was produced. Timeouts/unknown outcomes are NEVER auto-retried\n * because the agent may already have performed side effects (roadmap §6.4).\n */\nconst RETRYABLE_ERROR_CODES: readonly string[] = [\"AGENT_FAILED\"];\nconst EXECUTION_HISTORY_LIMIT = 10;\n\nexport interface CreateTaskInput {\n objective: string;\n project?: string;\n pipelineId?: string;\n role?: string;\n agent?: string;\n context?: TaskContext;\n}\n\nexport interface RunTaskOptions {\n /** Total attempts (1 = no automatic retry). Retries apply to retryable errors only. */\n maxAttempts?: number;\n /** Linear backoff base in ms: waits backoffMs × attempt between attempts. */\n retryBackoffMs?: number;\n}\n\nexport interface TaskEngineOptions {\n agents: AgentRegistry;\n roles: RoleRegistry;\n store: TaskStore;\n /** When present, tasks gather relevant memory before running and record outcomes after (§20). */\n memory?: MemoryService;\n /** When present, task lifecycle transitions are appended to the audit log (§24). */\n audit?: AuditSink;\n log?: Logger;\n}\n\nexport class TaskEngine {\n private readonly log: Logger;\n\n constructor(private readonly options: TaskEngineOptions) {\n this.log = (options.log ?? logger).child({ component: \"tasks\" });\n }\n\n get store(): TaskStore {\n return this.options.store;\n }\n\n async create(input: CreateTaskInput): Promise<Task> {\n if (!input.objective || input.objective.trim().length === 0) {\n throw new TaskError(\"TASK_INVALID\", \"Task objective must not be empty.\");\n }\n if (input.role && !this.options.roles.get(input.role)) {\n throw new TaskError(\"TASK_INVALID\", \n `Role \"${input.role}\" is not defined. Add it under project.roles in omninode.yaml.`,\n );\n }\n if (input.agent && !this.options.agents.get(input.agent)) {\n throw new TaskError(\"TASK_INVALID\", \n `Agent \"${input.agent}\" is not registered. Add it with \\`omninode agent add\\`.`,\n );\n }\n\n const now = new Date().toISOString();\n const task: Task = {\n id: generateTaskId(),\n objective: input.objective.trim(),\n status: \"created\",\n attempt: 0,\n createdAt: now,\n updatedAt: now,\n ...(input.project !== undefined ? { project: input.project } : {}),\n ...(input.pipelineId !== undefined ? { pipelineId: input.pipelineId } : {}),\n ...(input.role !== undefined ? { role: input.role } : {}),\n ...(input.agent !== undefined ? { agent: input.agent } : {}),\n ...(input.context !== undefined ? { context: input.context } : {}),\n };\n await this.options.store.save(task);\n this.log.info(`Created task ${task.id}.`);\n await this.audit(\"task.created\", task, { objective: task.objective });\n return task;\n }\n\n async queue(id: string): Promise<Task> {\n const task = await this.mustGet(id);\n return this.transition(task, \"queued\");\n }\n\n /** Runs the task through its assigned agent and records the result.\n * `maxAttempts` enables bounded automatic retries of *retryable* errors\n * with linear backoff; unknown/timed_out outcomes are never auto-retried. */\n async run(id: string, options: RunTaskOptions = {}): Promise<Task> {\n const task = await this.mustGet(id);\n if (task.status !== \"created\" && task.status !== \"queued\") {\n throw new TaskError(\"TASK_INVALID\", `Task ${id} is \"${task.status}\" and cannot be run.`);\n }\n if (!task.agent) {\n throw new TaskError(\"TASK_INVALID\", `Task ${id} has no agent assigned. Re-create it with --agent.`);\n }\n const agent = this.options.agents.get(task.agent);\n if (!agent) {\n throw new TaskError(\"TASK_INVALID\", `Agent \"${task.agent}\" is not registered anymore.`);\n }\n const role = task.role ? this.options.roles.get(task.role) : undefined;\n\n this.log.info(`Running task ${task.id} on agent \"${task.agent}\".`);\n\n // §20: relevant memory is gathered before the agent receives context.\n let background = task.context?.background;\n if (this.options.memory) {\n const memoryContext = await this.options.memory.gatherContext({\n objective: task.objective,\n ...(task.role ? { role: task.role } : {}),\n ...(task.project ? { project: task.project } : {}),\n });\n if (memoryContext.length > 0) {\n background = [memoryContext, background].filter((part) => part && part.length > 0).join(\"\\n\\n\");\n }\n }\n\n const maxAttempts = Math.max(1, options.maxAttempts ?? 1);\n const backoffMs = options.retryBackoffMs ?? 0;\n\n let current = task;\n for (let i = 0; i < maxAttempts; i += 1) {\n // Attempt numbers are cumulative for the task (roadmap §6.5).\n const attempt = current.attempt + 1;\n const executionId = `exec-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`;\n const startedAt = new Date().toISOString();\n current = await this.transition(current, \"running\", { attempt });\n\n await this.options.audit?.record({\n at: startedAt,\n action: \"agent.started\",\n id: current.id,\n taskId: current.id,\n ...(current.pipelineId !== undefined ? { pipelineId: current.pipelineId } : {}),\n agentId: task.agent,\n executionId,\n detail: { attempt },\n });\n\n let output;\n let thrown: unknown;\n try {\n output = await agent.run({\n taskId: current.id,\n objective: current.objective,\n executionId,\n ...(current.pipelineId !== undefined ? { pipelineId: current.pipelineId } : {}),\n ...(role ? { role } : {}),\n ...(background !== undefined ? { context: background } : {}),\n });\n } catch (error) {\n thrown = error;\n }\n\n const finishedAt = new Date().toISOString();\n await this.options.audit?.record({\n at: finishedAt,\n action: \"agent.completed\",\n id: current.id,\n taskId: current.id,\n ...(current.pipelineId !== undefined ? { pipelineId: current.pipelineId } : {}),\n agentId: task.agent,\n executionId,\n detail: { attempt, outcome: thrown !== undefined || output === undefined ? \"threw\" : \"returned\" },\n });\n if (thrown !== undefined || output === undefined) {\n const outcome = classifyThrown(thrown);\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n const retryable =\n outcome === \"failed\" &&\n RETRYABLE_ERROR_CODES.includes(errorCode(thrown)) &&\n i < maxAttempts - 1;\n current = await this.transition(current, outcome, {\n attempt,\n lastError: message,\n execution: {\n executionId,\n attempt,\n startedAt,\n finishedAt,\n outcome,\n error: message,\n },\n });\n this.log.warn(`Task ${current.id} attempt ${attempt} → ${outcome}: ${message}`);\n if (retryable) {\n if (backoffMs > 0) await sleep(backoffMs * attempt);\n continue;\n }\n if (this.options.memory) await this.options.memory.recordTaskOutcome(current);\n return current;\n }\n\n // The task may have been cancelled while the agent was finishing —\n // respect the terminal state instead of forcing a completed transition.\n const currentState = await this.options.store.get(current.id);\n if (currentState?.status === \"cancelled\") {\n current = currentState;\n break;\n }\n\n const result: TaskResult = {\n ...(output.summary !== undefined ? { summary: output.summary } : {}),\n ...(output.reports !== undefined && output.reports.length > 0 ? { reports: output.reports } : {}),\n // Keep the verbatim output (bounded) for report extraction and audit.\n ...(output.rawOutput !== undefined && output.rawOutput.length > 0\n ? { rawOutput: output.rawOutput.slice(0, 10_000) }\n : {}),\n ...(output.error !== undefined ? { error: output.error } : {}),\n finishedAt,\n };\n const finalStatus: TaskStatus = output.status === \"completed\" ? \"completed\" : \"failed\";\n current = await this.transition(current, finalStatus, {\n attempt,\n result,\n execution: { executionId, attempt, startedAt, finishedAt, outcome: finalStatus },\n });\n this.log.info(`Task ${current.id} finished: ${finalStatus}.`);\n break;\n }\n\n // §20: the outcome is written back to memory — best-effort, never fatal.\n if (this.options.memory) {\n await this.options.memory.recordTaskOutcome(current);\n }\n return current;\n }\n\n async cancel(id: string): Promise<Task> {\n const task = await this.mustGet(id);\n if (!ALLOWED_TRANSITIONS[task.status].includes(\"cancelled\")) {\n throw new TaskError(\"TASK_INVALID\", `Task ${id} is \"${task.status}\" and cannot be cancelled.`);\n }\n if (task.agent) {\n const agent = this.options.agents.get(task.agent);\n await agent?.cancel?.(task.id);\n }\n return this.transition(task, \"cancelled\");\n }\n\n /** Error recovery: reset a failed/cancelled/unknown/timed_out task so it can run again. */\n async retry(id: string): Promise<Task> {\n const task = await this.mustGet(id);\n const retryableStates: TaskStatus[] = [\"failed\", \"cancelled\", \"unknown\", \"timed_out\"];\n if (!retryableStates.includes(task.status)) {\n throw new TaskError(\n \"TASK_INVALID\",\n `Only failed, timed out, unknown or cancelled tasks can be retried — task ${id} is \"${task.status}\".`,\n );\n }\n const { result: _discarded, ...rest } = task;\n const reset: Task = {\n ...rest,\n status: \"created\",\n updatedAt: new Date().toISOString(),\n };\n await this.options.store.save(reset);\n await this.audit(\"task.retry\", reset, { from: task.status });\n this.log.info(`Task ${id} reset for retry.`);\n return reset;\n }\n\n async get(id: string): Promise<Task | undefined> {\n return this.options.store.get(id);\n }\n\n async list(filter?: TaskStoreFilter): Promise<Task[]> {\n return this.options.store.list(filter);\n }\n\n private async mustGet(id: string): Promise<Task> {\n const task = await this.options.store.get(id);\n if (!task) {\n throw new TaskError(\"TASK_NOT_FOUND\", `Task \"${id}\" does not exist in this project's task store.`);\n }\n return task;\n }\n\n private async transition(\n task: Task,\n to: TaskStatus,\n extra: { result?: TaskResult; attempt?: number; lastError?: string; execution?: ExecutionRecord } = {},\n ): Promise<Task> {\n const allowed = ALLOWED_TRANSITIONS[task.status] ?? [];\n if (!allowed.includes(to)) {\n throw new TaskError(\"TASK_INVALID\", `Task ${task.id} cannot move from \"${task.status}\" to \"${to}\".`);\n }\n const executions = extra.execution\n ? [...(task.executions ?? []), extra.execution].slice(-EXECUTION_HISTORY_LIMIT)\n : task.executions;\n const updated: Task = {\n ...task,\n status: to,\n updatedAt: new Date().toISOString(),\n ...(extra.attempt !== undefined ? { attempt: extra.attempt } : {}),\n ...(extra.lastError !== undefined ? { lastError: extra.lastError } : {}),\n ...(executions !== undefined ? { executions } : {}),\n ...(extra.result !== undefined\n ? { result: { ...task.result, ...extra.result } }\n : {}),\n };\n await this.options.store.save(updated);\n await this.audit(`task.${to === \"queued\" ? \"queued\" : to}` as AuditAction, updated, {\n from: task.status,\n });\n return updated;\n }\n\n private async audit(\n action: AuditAction,\n task: Task,\n detail?: Record<string, unknown>,\n executionId?: string,\n ): Promise<void> {\n // Correlation (§18): every event carries task/pipeline/agent/execution ids.\n await this.options.audit?.record({\n at: new Date().toISOString(),\n action,\n id: task.id,\n taskId: task.id,\n ...(task.project !== undefined ? { project: task.project } : {}),\n ...(task.pipelineId !== undefined ? { pipelineId: task.pipelineId } : {}),\n ...(task.agent !== undefined ? { agentId: task.agent } : {}),\n ...(executionId !== undefined ? { executionId } : {}),\n ...(detail !== undefined ? { detail } : {}),\n });\n }\n}\n\nfunction generateTaskId(): string {\n return `task-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`;\n}\n\nfunction errorCode(error: unknown): string {\n return (error as { code?: string } | undefined)?.code ?? \"\";\n}\n\n/**\n * Classifies a thrown adapter error into a terminal state.\n *\n * §6.3: a timeout is NOT assumed to be a failure. If the operation was\n * dispatched, the remote side may have completed it, so the outcome is\n * `unknown`. Only a timeout provably raised *before* dispatch becomes\n * `timed_out`.\n */\nfunction classifyThrown(error: unknown): \"failed\" | \"timed_out\" | \"unknown\" {\n if (error instanceof AgentError && error.code === \"AGENT_TIMEOUT\") {\n const dispatched = (error.details as { dispatched?: unknown } | undefined)?.dispatched;\n return dispatched === false ? \"timed_out\" : \"unknown\";\n }\n return \"failed\";\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * Audit logging (§24): append-only JSONL record of lifecycle events\n * (task/pipeline transitions) in the project's .omninode directory. Useful\n * for compliance reviews and debugging multi-agent runs.\n */\nimport { appendFile, mkdir, readFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { logger, type Logger } from \"../logger/index.js\";\n\nexport type AuditAction =\n | \"task.created\"\n | \"task.queued\"\n | \"task.running\"\n | \"task.completed\"\n | \"task.failed\"\n | \"task.cancelled\"\n | \"task.retry\"\n | \"pipeline.run.started\"\n | \"pipeline.run.finished\"\n | \"pipeline.run.failed\"\n | \"pipeline.run.cancelled\"\n | \"plan.generated\"\n | \"agent.started\"\n | \"agent.completed\"\n | \"provider.error\"\n | \"memory.context.gathered\"\n | \"memory.outcome.recorded\";\n\n/**\n * Every event carries correlation ids so a failed execution can be traced\n * across task → execution → pipeline run → agent → provider (roadmap §18).\n */\nexport interface AuditEvent {\n at: string;\n action: AuditAction;\n project?: string;\n /** Primary subject: task id, pipeline run id, plan id… */\n id?: string;\n taskId?: string;\n pipelineId?: string;\n executionId?: string;\n agentId?: string;\n providerId?: string;\n actor?: string;\n detail?: Record<string, unknown>;\n}\n\nexport interface AuditSink {\n record(event: AuditEvent): Promise<void>;\n}\n\n/** Append-only JSONL sink. Failures are logged, never propagated. */\nexport class FileAuditLog implements AuditSink {\n private readonly filePath: string;\n private readonly log: Logger;\n\n constructor(directory = `${process.cwd()}/.omninode`, log: Logger = logger) {\n this.filePath = `${directory}/audit.jsonl`;\n this.log = log.child({ component: \"audit\" });\n }\n\n async record(event: AuditEvent): Promise<void> {\n try {\n await mkdir(dirname(this.filePath), { recursive: true });\n // Append-only: a crash can tear the last line, which `recent()` skips.\n // fsync-per-event would make every execution wait on the disk.\n await appendFile(this.filePath, `${JSON.stringify(event)}\\n`, \"utf8\");\n } catch (error) {\n this.log.warn(\n `Audit write failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n /** Recent events, oldest first; used by the CLI. */\n async recent(limit = 20): Promise<AuditEvent[]> {\n let raw: string;\n try {\n raw = await readFile(this.filePath, \"utf8\");\n } catch {\n return [];\n }\n const events = raw\n .split(\"\\n\")\n .filter((line) => line.length > 0)\n .map((line) => {\n try {\n return JSON.parse(line) as AuditEvent;\n } catch {\n return undefined;\n }\n })\n .filter((event): event is AuditEvent => event !== undefined);\n return events.slice(-limit);\n }\n}","/** Assembles a TaskEngine from the project configuration (local-first defaults). */\nimport type { AppConfig } from \"../config/index.js\";\nimport { FileAuditLog } from \"../audit/index.js\";\nimport { buildAgentRegistry } from \"../agents/index.js\";\nimport { createMemoryProvider, MemoryService } from \"../memory/index.js\";\nimport { buildRoleRegistry } from \"../roles/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport { TaskEngine } from \"./engine.js\";\nimport { FileTaskStore } from \"./store.js\";\n\nexport function createTaskEngine(config: AppConfig, log: Logger = logger, directory?: string): TaskEngine {\n const agents = buildAgentRegistry(config, log);\n const roles = buildRoleRegistry(config);\n return new TaskEngine({\n agents,\n roles,\n store: new FileTaskStore(directory),\n ...(config.project.memory !== undefined\n ? {\n memory: new MemoryService(createMemoryProvider(config.project.memory), log, {\n required: config.project.memory.required,\n }),\n }\n : {}),\n audit: new FileAuditLog(),\n log,\n });\n}\n","import type { Command } from \"commander\";\nimport { loadConfig } from \"../../config/index.js\";\nimport { TaskError } from \"../../errors/index.js\";\nimport { createTaskEngine } from \"../../tasks/index.js\";\nimport type { Task } from \"../../types/task.js\";\nimport { registerTaskInspect } from \"./inspect.js\";\n\nconst collectFiles = (value: string, previous: string[]): string[] => [...previous, value];\n\nexport function registerTaskCommands(program: Command): void {\n const task = program\n .command(\"task\")\n .description(\"Create, run and inspect tasks (§13).\");\n\n task\n .command(\"create <objective>\")\n .description(\"Create a task. Assign a role and/or agent; run it with `omninode task run`.\")\n .option(\"-r, --role <roleId>\", \"Role id from project.roles (validated at creation).\")\n .option(\"-a, --agent <name>\", \"Agent name from project.agents (validated at creation).\")\n .option(\"-f, --file <path>\", \"File or glob relevant to the task (repeatable).\", collectFiles)\n .action(async (objective: string, options: { role?: string; agent?: string; file?: string[] }) => {\n const config = loadConfig();\n const engine = createTaskEngine(config);\n const created = await engine.create({\n objective,\n project: config.project.name,\n ...(options.role !== undefined ? { role: options.role } : {}),\n ...(options.agent !== undefined ? { agent: options.agent } : {}),\n ...(options.file !== undefined && options.file.length > 0\n ? { context: { files: options.file } }\n : {}),\n });\n console.log(`Created task ${created.id} (${created.status})`);\n console.log(` objective: ${created.objective}`);\n if (created.role) console.log(` role: ${created.role}`);\n if (created.agent) console.log(` agent: ${created.agent}`);\n if (created.context?.files) console.log(` files: ${created.context.files.join(\", \")}`);\n console.log(`Run \\`omninode task run ${created.id}\\` to execute it.`);\n });\n\n task\n .command(\"run <task-id>\")\n .description(\"Run a task through its assigned agent.\")\n .action(async (taskId: string) => {\n const config = loadConfig();\n const engine = createTaskEngine(config);\n console.log(`Running task ${taskId}...`);\n const finished = await engine.run(taskId);\n printOutcome(finished);\n if (finished.status !== \"completed\") process.exitCode = 1;\n });\n\n task\n .command(\"status <task-id>\")\n .description(\"Show task details and current status.\")\n .action(async (taskId: string) => {\n const config = loadConfig();\n const engine = createTaskEngine(config);\n const found = await engine.get(taskId);\n if (!found) {\n throw new TaskError(\n \"TASK_NOT_FOUND\",\n `Task \"${taskId}\" does not exist in this project's task store.`,\n );\n }\n printOutcome(found, { verbose: true });\n });\n\n task\n .command(\"list\")\n .description(\"List tasks in the project's task store.\")\n .option(\"-s, --status <status>\", \"Filter by status (created, queued, running, completed, failed, cancelled).\")\n .action(async (options: { status?: string }) => {\n const config = loadConfig();\n const engine = createTaskEngine(config);\n const tasks = await engine.list(\n options.status !== undefined ? { status: options.status as Task[\"status\"] } : {},\n );\n if (tasks.length === 0) {\n console.log(\"No tasks found. Create one with `omninode task create`.\");\n return;\n }\n for (const t of tasks) {\n console.log(`${t.id} ${t.status.padEnd(10)} ${truncate(t.objective, 60)}`);\n }\n });\n\n task\n .command(\"cancel <task-id>\")\n .description(\"Cancel a task that has not finished yet.\")\n .action(async (taskId: string) => {\n const config = loadConfig();\n const engine = createTaskEngine(config);\n const cancelled = await engine.cancel(taskId);\n console.log(`Task ${cancelled.id} is now \"${cancelled.status}\".`);\n });\n\n task\n .command(\"retry <task-id>\")\n .description(\"Reset a failed, timed out, unknown or cancelled task to created; combine with --run to execute it again.\")\n .option(\"--run\", \"Run the task again immediately after resetting it.\")\n .action(async (taskId: string, options: { run?: boolean }) => {\n const config = loadConfig();\n const engine = createTaskEngine(config);\n const reset = await engine.retry(taskId);\n console.log(`Task ${reset.id} reset to \"${reset.status}\".`);\n if (!options.run) return;\n console.log(`Running task ${reset.id}...`);\n const finished = await engine.run(reset.id);\n printOutcome(finished);\n if (finished.status !== \"completed\") process.exitCode = 1;\n });\n registerTaskInspect(task);\n}\n\nfunction printOutcome(task: Task, options: { verbose?: boolean } = {}): void {\n console.log(` id: ${task.id}`);\n console.log(` status: ${task.status}`);\n console.log(` created: ${task.createdAt}`);\n if (options.verbose) {\n console.log(` project: ${task.project ?? \"(none)\"}`);\n if (task.role) console.log(` role: ${task.role}`);\n if (task.agent) console.log(` agent: ${task.agent}`);\n if (task.context?.files) console.log(` files: ${task.context.files.join(\", \")}`);\n console.log(` objective: ${task.objective}`);\n }\n if (options.verbose && task.attempt > 0) {\n console.log(` attempt: ${task.attempt}`);\n }\n if (task.lastError) console.log(` error: ${task.lastError}`);\n if (options.verbose && task.executions && task.executions.length > 0) {\n console.log(\n ` executions: ${task.executions\n .map((e) => `#${e.attempt}:${e.outcome}`)\n .join(\", \")}`,\n );\n }\n const result = task.result;\n if (!result) return;\n if (result.summary) console.log(` summary: ${result.summary}`);\n if (result.reports && result.reports.length > 0) {\n console.log(` reports: ${result.reports.length} structured report(s)`);\n }\n if (result.error) console.log(` error: ${result.error}`);\n if (result.finishedAt) console.log(` ended: ${result.finishedAt}`);\n}\n\nfunction truncate(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n","/**\n * Report aggregation (§17): normalizes formats, groups duplicate and similar\n * findings, preserves source attribution, and produces one CombinedReport.\n * Grouping uses deterministic token-set similarity so results are testable.\n */\nimport { randomBytes } from \"node:crypto\";\nimport type {\n AggregatedFinding,\n AggregatedRecommendation,\n CombinedReport,\n Confidence,\n ConflictPosition,\n Finding,\n FindingSeverity,\n FindingSource,\n Report,\n ReportConflict,\n} from \"../types/report.js\";\nimport { normalizeEvidence } from \"./schema.js\";\n\nconst SEVERITY_RANK: Record<FindingSeverity, number> = {\n info: 0,\n low: 1,\n medium: 2,\n high: 3,\n critical: 4,\n};\n\nexport interface AggregateOptions {\n objective?: string;\n pipelineRunId?: string;\n taskIds?: string[];\n /** Token-set Jaccard similarity above which findings are merged. */\n similarityThreshold?: number;\n}\n\nexport function aggregateReports(reports: Report[], options: AggregateOptions = {}): CombinedReport {\n const threshold = options.similarityThreshold ?? 0.7;\n\n const findingGroups: AggregatedFinding[] = [];\n const recommendationGroups: AggregatedRecommendation[] = [];\n\n for (const report of reports) {\n for (const finding of report.findings) {\n mergeFinding(findingGroups, finding, report, threshold);\n }\n for (const text of report.recommendations) {\n mergeRecommendation(recommendationGroups, text, report, threshold);\n }\n }\n\n const sources = [...new Set(reports.map((r) => r.agent))].sort();\n const totalRawFindings = reports.reduce((sum, r) => sum + r.findings.length, 0);\n const conflicts = detectConflicts(findingGroups);\n // Agreement = independently reported by 2+ agents with the same severity.\n const agreements = findingGroups.filter(\n (group) =>\n group.sources.length > 1 &&\n group.severity !== undefined &&\n new Set(Object.values(group.severityBySource ?? {})).size === 1,\n );\n const disputed = conflicts.length;\n const summary =\n `${reports.length} report(s) from ${sources.length > 0 ? sources.join(\", \") : \"no agents\"}: ` +\n `${findingGroups.length} unique finding group(s) (${totalRawFindings} raw), ` +\n `${agreements.length} agreement(s), ${disputed} conflict(s), ` +\n `${recommendationGroups.length} recommendation group(s).`;\n\n return {\n id: `combined-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`,\n title: options.objective !== undefined ? truncate(options.objective, 120) : \"Combined report\",\n ...(options.objective !== undefined ? { objective: options.objective } : {}),\n ...(options.pipelineRunId !== undefined ? { pipelineRunId: options.pipelineRunId } : {}),\n taskIds: options.taskIds ?? [],\n summary,\n findings: findingGroups.sort((a, b) => rank(b) - rank(a)),\n agreements,\n conflicts,\n recommendations: recommendationGroups,\n sources,\n reportIds: reports.map((r) => r.id),\n createdAt: new Date().toISOString(),\n metadata: {\n agents: sources.length,\n reports: reports.length,\n rawFindings: totalRawFindings,\n findingGroups: findingGroups.length,\n agreements: agreements.length,\n conflicts: conflicts.length,\n },\n };\n}\n\nfunction rankConfidence(confidence: Confidence | undefined): number {\n return confidence ? { low: 1, medium: 2, high: 3 }[confidence] : 0;\n}\n\n/**\n * Conflict detection (§14): agents disagreeing about the same finding is a\n * first-class result. Both positions are preserved — OmniNode never silently\n * chooses one.\n */\nexport function detectConflicts(groups: AggregatedFinding[]): ReportConflict[] {\n const conflicts: ReportConflict[] = [];\n for (const group of groups) {\n if (group.sources.length < 2) continue;\n\n const severities = new Set(Object.values(group.severityBySource ?? {}));\n if (severities.size > 1) {\n conflicts.push({\n type: \"severity\",\n findingTitle: group.title,\n positions: group.sources.map((source) => position(source, group)),\n note:\n `Agents disagree on severity (${[...severities].sort((a, b) => SEVERITY_RANK[a] - SEVERITY_RANK[b]).join(\", \")}); ` +\n `the highest severity is shown, every position is preserved.`,\n });\n }\n\n const recommendations = (group.recommendations ?? []).filter((r) => r.length > 0);\n if (recommendations.length > 1) {\n conflicts.push({\n type: \"recommendation\",\n findingTitle: group.title,\n positions: group.sources.map((source) => position(source, group)),\n note: `Agents proposed ${recommendations.length} different fixes; none was discarded.`,\n });\n }\n }\n return conflicts;\n}\n\nfunction position(\n source: FindingSource,\n group: AggregatedFinding,\n): ConflictPosition {\n return {\n agent: source.agent,\n reportId: source.reportId,\n ...(group.severityBySource?.[source.agent] !== undefined\n ? { severity: group.severityBySource[source.agent] }\n : {}),\n ...(group.confidenceBySource?.[source.agent] !== undefined\n ? { confidence: group.confidenceBySource[source.agent] }\n : {}),\n ...(group.recommendations?.[0] !== undefined ? { recommendation: group.recommendations[0] } : {}),\n };\n}\n\nfunction rank(finding: AggregatedFinding): number {\n return finding.severity ? SEVERITY_RANK[finding.severity] : -1;\n}\n\nfunction mergeFinding(groups: AggregatedFinding[], finding: Finding, report: Report, threshold: number): void {\n const source: FindingSource = { agent: report.agent, reportId: report.id };\n const group = groups.find((g) => similar(g.title, finding.title, threshold));\n if (group) {\n group.occurrences += 1;\n group.details.push(finding.detail);\n group.sources.push(source);\n group.evidence.push(...(normalizeEvidence(finding.evidence) ?? []));\n if (finding.severity && (!group.severity || SEVERITY_RANK[finding.severity] > SEVERITY_RANK[group.severity])) {\n group.severity = finding.severity;\n }\n // Confidence preservation (§14): keep the strongest, and record per source.\n if (finding.confidence && rankConfidence(finding.confidence) > rankConfidence(group.confidence)) {\n group.confidence = finding.confidence;\n }\n if (finding.severity) {\n group.severityBySource = { ...group.severityBySource, [report.agent]: finding.severity };\n }\n if (finding.confidence) {\n group.confidenceBySource = { ...group.confidenceBySource, [report.agent]: finding.confidence };\n }\n if (finding.recommendation && !group.recommendations?.includes(finding.recommendation)) {\n group.recommendations = [...(group.recommendations ?? []), finding.recommendation];\n }\n return;\n }\n groups.push({\n title: finding.title,\n details: [finding.detail],\n sources: [source],\n occurrences: 1,\n ...(finding.severity ? { severity: finding.severity } : {}),\n ...(finding.confidence ? { confidence: finding.confidence } : {}),\n ...(finding.severity ? { severityBySource: { [report.agent]: finding.severity } } : {}),\n ...(finding.confidence ? { confidenceBySource: { [report.agent]: finding.confidence } } : {}),\n ...(finding.recommendation ? { recommendations: [finding.recommendation] } : {}),\n evidence: [...(normalizeEvidence(finding.evidence) ?? [])],\n });\n}\n\nfunction mergeRecommendation(\n groups: AggregatedRecommendation[],\n text: string,\n report: Report,\n threshold: number,\n): void {\n const source: FindingSource = { agent: report.agent, reportId: report.id };\n const group = groups.find((g) => similar(g.text, text, threshold));\n if (group) {\n group.occurrences += 1;\n group.sources.push(source);\n return;\n }\n groups.push({ text, sources: [source], occurrences: 1 });\n}\n\nexport function similar(a: string, b: string, threshold: number): boolean {\n const left = tokens(a);\n const right = tokens(b);\n if (left.size === 0 || right.size === 0) return false;\n let intersection = 0;\n for (const token of left) {\n if (right.has(token)) intersection += 1;\n }\n const union = left.size + right.size - intersection;\n return intersection / union >= threshold;\n}\n\nfunction tokens(text: string): Set<string> {\n return new Set(\n text\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, \" \")\n .split(/\\s+/)\n .filter((t) => t.length >= 3),\n );\n}\n\nfunction truncate(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n","/**\n * Report validation and normalization (roadmap §13, Report Validation).\n *\n * Reports are machine-readable objects: they are schema-validated before they\n * can enter aggregation, and legacy string evidence / `detail` fields are\n * normalized into the v2 shape on the way in.\n */\nimport { z } from \"zod\";\nimport type { Confidence, Evidence, EvidenceInput, Finding, Report } from \"../types/report.js\";\n\nconst evidenceSchema = z.union([\n z.string().transform((excerpt): Evidence => ({ kind: \"observation\", excerpt })),\n z.object({\n kind: z.enum([\"file\", \"line\", \"url\", \"command\", \"observation\", \"artifact\"]),\n ref: z.string().optional(),\n line: z.number().int().optional(),\n excerpt: z.string().optional(),\n agent: z.string().optional(),\n }),\n]);\n\nconst findingSchema = z.object({\n id: z.string().min(1),\n title: z.string().min(1),\n detail: z.string().default(\"\"),\n description: z.string().optional(),\n severity: z.enum([\"info\", \"low\", \"medium\", \"high\", \"critical\"]).optional(),\n confidence: z.enum([\"low\", \"medium\", \"high\"]).optional(),\n severityBySource: z.record(z.enum([\"info\", \"low\", \"medium\", \"high\", \"critical\"])).optional(),\n confidenceBySource: z.record(z.enum([\"low\", \"medium\", \"high\"])).optional(),\n recommendations: z.array(z.string()).optional(),\n evidence: z.array(evidenceSchema).optional(),\n location: z.string().optional(),\n tags: z.array(z.string()).optional(),\n source: z.object({ agent: z.string().optional(), reportId: z.string().optional(), pipelineRunId: z.string().optional() }).optional(),\n recommendation: z.string().optional(),\n});\n\nconst artifactSchema = z.object({\n kind: z.enum([\"file\", \"patch\", \"log\", \"screenshot\", \"document\", \"data\"]),\n ref: z.string().min(1),\n description: z.string().optional(),\n mediaType: z.string().optional(),\n bytes: z.number().int().optional(),\n});\n\nconst reportSchema = z.object({\n id: z.string().min(1),\n taskId: z.string().min(1),\n agent: z.string().min(1),\n agentId: z.string().optional(),\n pipelineRunId: z.string().optional(),\n model: z.string().optional(),\n summary: z.string(),\n findings: z.array(findingSchema),\n recommendations: z.array(z.string()),\n confidence: z.enum([\"low\", \"medium\", \"high\"]).optional(),\n evidence: z.array(evidenceSchema).optional(),\n artifacts: z.array(artifactSchema).optional(),\n createdAt: z.string().min(1),\n metadata: z.record(z.unknown()).optional(),\n});\n\nexport interface ReportValidationIssue {\n path: string;\n message: string;\n}\n\nexport type ReportValidationResult =\n | { valid: true; report: Report }\n | { valid: false; issues: ReportValidationIssue[]; reason: string };\n\n/** Validates (and normalizes) a report; malformed reports are rejected. */\nexport function validateReport(value: unknown): ReportValidationResult {\n const parsed = reportSchema.safeParse(value);\n if (!parsed.success) {\n const issues = parsed.error.issues.map((issue) => ({\n path: issue.path.join(\".\") || \"(root)\",\n message: issue.message,\n }));\n return {\n valid: false,\n issues,\n reason: `report failed schema validation (${issues.length} issue(s))`,\n };\n }\n const report = parsed.data as Report;\n // Cross-field normalization: description mirrors detail, source carries provenance.\n report.findings = report.findings.map((finding) => ({\n ...finding,\n description: finding.description ?? finding.detail,\n ...(finding.source === undefined\n ? { source: { agent: report.agent, reportId: report.id, ...(report.pipelineRunId !== undefined ? { pipelineRunId: report.pipelineRunId } : {}) } }\n : {}),\n }));\n return { valid: true, report };\n}\n\n/** Normalizes evidence entries (strings or objects) to typed evidence. */\nexport function normalizeEvidence(input: EvidenceInput[] | undefined): Evidence[] | undefined {\n if (input === undefined) return undefined;\n return input.map((item) =>\n typeof item === \"string\" ? { kind: \"observation\" as const, excerpt: item } : item,\n );\n}\n\nexport function normalizeFinding(finding: Finding): Finding {\n return {\n ...finding,\n description: finding.description ?? finding.detail,\n evidence: normalizeEvidence(finding.evidence),\n };\n}\n\nexport type { Confidence };","/**\n * Report normalization (§17): turns an agent's text output into a structured\n * Report by extracting findings, recommendations and evidence from\n * markdown-style sections. Deterministic heuristics; AI-assisted extraction\n * can layer on top later via the planner.\n */\nimport type { Finding, FindingSeverity, Report } from \"../types/report.js\";\n\nexport interface ExtractionMeta {\n taskId: string;\n agent: string;\n model?: string;\n}\n\nconst BULLET = /^(?:[-*•]|\\d+[.)])\\s+(.*)$/;\n\ninterface Section {\n heading: string;\n bullets: string[];\n}\n\nfunction parseSections(raw: string): Section[] {\n const sections: Section[] = [];\n let current: Section = { heading: \"\", bullets: [] };\n for (const line of raw.split(\"\\n\")) {\n const heading = /^(#{1,6})\\s+(.*)$/.exec(line.trim());\n if (heading) {\n if (current.heading.length > 0 || current.bullets.length > 0) {\n sections.push(current);\n }\n current = { heading: heading[2]?.toLowerCase() ?? \"\", bullets: [] };\n continue;\n }\n const bullet = BULLET.exec(line.trim());\n if (bullet && current.heading.length > 0) {\n current.bullets.push(bullet[1]?.trim() ?? \"\");\n }\n }\n if (current.heading.length > 0 || current.bullets.length > 0) {\n sections.push(current);\n }\n return sections;\n}\n\nfunction collectBullets(sections: Section[], patterns: RegExp[]): string[] {\n const matches = sections.filter((section) => patterns.some((p) => p.test(section.heading)));\n return matches.flatMap((section) => section.bullets).filter((b) => b.length > 0);\n}\n\nfunction guessSeverity(text: string): FindingSeverity | undefined {\n if (/critical|severe/i.test(text)) return \"critical\";\n if (/\\bhigh\\b|major/i.test(text)) return \"high\";\n if (/medium|moderate/i.test(text)) return \"medium\";\n if (/\\blow\\b|minor/i.test(text)) return \"low\";\n return undefined;\n}\n\nexport function extractReportFromText(raw: string, meta: ExtractionMeta): Report {\n const trimmed = raw.trim();\n const nonEmpty = trimmed\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n // Prefer a prose line over markdown headings/bullets for the summary.\n const proseLine =\n nonEmpty.find((line) => !line.startsWith(\"#\") && !BULLET.test(line)) ?? nonEmpty[0] ?? \"\";\n const cleaned = proseLine.replace(/^#{1,6}\\s+/, \"\").replace(BULLET, \"$1\");\n const summary = cleaned.length > 0 ? truncate(cleaned, 200) : \"(no output)\";\n\n const sections = parseSections(trimmed);\n const findingTexts = collectBullets(sections, [/finding/, /issue/, /problem/, /vulnerab/]);\n const recommendationTexts = collectBullets(sections, [/recommend/, /suggestion/, /next step/, /action/]);\n const evidenceTexts = collectBullets(sections, [/evidence/, /proof/, /log/]);\n\n const findings: Finding[] = findingTexts.map((text, index) => ({\n id: `${meta.taskId}-f-${index + 1}`,\n title: truncate(text, 120),\n detail: text,\n description: text,\n severity: guessSeverity(text),\n }));\n\n return {\n id: `${meta.taskId}-report`,\n taskId: meta.taskId,\n agent: meta.agent,\n ...(meta.model !== undefined ? { model: meta.model } : {}),\n summary,\n findings,\n recommendations: recommendationTexts.map((t) => truncate(t, 200)),\n ...(evidenceTexts.length > 0\n ? { evidence: evidenceTexts.map((excerpt) => ({ kind: \"observation\" as const, excerpt })) }\n : {}),\n metadata: evidenceTexts.length > 0 ? { evidenceCount: evidenceTexts.length } : undefined,\n createdAt: new Date().toISOString(),\n };\n}\n\nfunction truncate(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n","/**\n * Report service (§16–§17): collects reports from finished tasks (structured\n * protocol reports when present, extraction from text otherwise), persists\n * them with source attribution and generates combined reports.\n */\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { Task } from \"../types/task.js\";\nimport type { Report, CombinedReport } from \"../types/report.js\";\nimport { aggregateReports, type AggregateOptions } from \"./aggregate.js\";\nimport { extractReportFromText } from \"./extract.js\";\nimport { validateReport } from \"./schema.js\";\nimport type { ReportStore } from \"./store.js\";\n\nexport interface CombinedMeta {\n objective?: string;\n pipelineRunId?: string;\n taskIds?: string[];\n}\n\n/** Serialized size budget for a single report (roadmap §17 — output limits). */\nexport const MAX_REPORT_BYTES = 256 * 1024;\n\nexport interface CollectionDiagnostics {\n collected: number;\n accepted: number;\n rejected: Array<{ key: string; reason: string; issues: string[] }>;\n}\n\nexport class ReportService {\n private readonly log: Logger;\n /** Rejected reports from the last collection (§13 — malformed never enters aggregation). */\n lastDiagnostics: CollectionDiagnostics = { collected: 0, accepted: 0, rejected: [] };\n\n constructor(\n private readonly store: ReportStore,\n log: Logger = logger,\n ) {\n this.log = log.child({ component: \"reports\" });\n }\n\n get storeRef(): ReportStore {\n return this.store;\n }\n\n /** Normalizes finished tasks into reports (§17 — normalizer), validating each\n * one so malformed reports never reach aggregation (§13). */\n async collectFromTasks(tasks: Task[]): Promise<Report[]> {\n const candidates: Report[] = [];\n for (const task of tasks) {\n const structured = task.result?.reports ?? [];\n if (structured.length > 0) {\n candidates.push(...structured);\n continue;\n }\n const text = task.result?.rawOutput ?? task.result?.summary ?? \"\";\n if (text.trim().length === 0) continue;\n candidates.push(\n extractReportFromText(text, {\n taskId: task.id,\n agent: task.agent ?? \"unknown\",\n }),\n );\n }\n\n const reports: Report[] = [];\n const rejected: CollectionDiagnostics[\"rejected\"] = [];\n for (const candidate of candidates) {\n const size = Buffer.byteLength(JSON.stringify(candidate), \"utf8\");\n if (size > MAX_REPORT_BYTES) {\n rejected.push({\n key: (candidate as { id?: string })?.id ?? \"(unknown)\",\n reason: `report exceeds the ${MAX_REPORT_BYTES} byte limit (${size} bytes)`,\n issues: [],\n });\n this.log.warn(`Rejected oversized report (${size} bytes).`);\n continue;\n }\n const result = validateReport(candidate);\n if (result.valid) {\n reports.push(result.report);\n } else {\n rejected.push({\n key: (candidate as { id?: string })?.id ?? \"(unknown)\",\n reason: result.reason,\n issues: result.issues.map((issue) => `${issue.path}: ${issue.message}`),\n });\n this.log.warn(`Rejected malformed report: ${result.reason}`);\n }\n }\n this.lastDiagnostics = { collected: candidates.length, accepted: reports.length, rejected };\n return reports;\n }\n\n async saveReports(reports: Report[]): Promise<void> {\n if (reports.length === 0) return;\n await this.store.saveReports(reports);\n this.log.info(`Stored ${reports.length} report(s).`);\n }\n\n async generateCombined(reports: Report[], meta: CombinedMeta = {}): Promise<CombinedReport | undefined> {\n if (reports.length === 0) return undefined;\n const options: AggregateOptions = {\n ...(meta.objective !== undefined ? { objective: meta.objective } : {}),\n ...(meta.pipelineRunId !== undefined ? { pipelineRunId: meta.pipelineRunId } : {}),\n ...(meta.taskIds !== undefined ? { taskIds: meta.taskIds } : {}),\n };\n const combined = aggregateReports(reports, options);\n await this.store.saveCombined(combined);\n this.log.info(`Generated combined report ${combined.id}.`);\n return combined;\n }\n}\n","/**\n * Report persistence (§16 — report storage). Same replaceable-store and\n * serialized-write patterns as the other local stores.\n */\nimport { JsonFileStore } from \"../persistence/json-file-store.js\";\nimport type { CombinedReport, Report } from \"../types/report.js\";\n\nexport interface ReportFilter {\n taskId?: string;\n agent?: string;\n}\n\nexport interface CombinedReportFilter {\n pipelineRunId?: string;\n}\n\nexport interface ReportStore {\n saveReports(reports: Report[]): Promise<void>;\n listReports(filter?: ReportFilter): Promise<Report[]>;\n saveCombined(combined: CombinedReport): Promise<void>;\n getCombined(id: string): Promise<CombinedReport | undefined>;\n listCombined(filter?: CombinedReportFilter): Promise<CombinedReport[]>;\n}\n\ntype StoreEntry = { kind: \"report\"; report: Report } | { kind: \"combined\"; combined: CombinedReport };\n\nexport class FileReportStore extends JsonFileStore<StoreEntry> implements ReportStore {\n constructor(directory?: string) {\n super({ ...(directory !== undefined ? { directory } : {}), fileName: \"reports.json\" });\n }\n\n async saveReports(reports: Report[]): Promise<void> {\n await this.mutate((entries) => {\n for (const report of reports) {\n const index = entries.findIndex((e) => e.kind === \"report\" && e.report.id === report.id);\n const entry: StoreEntry = { kind: \"report\", report };\n if (index >= 0) entries[index] = entry;\n else entries.push(entry);\n }\n return [entries, undefined];\n });\n }\n\n async listReports(filter: ReportFilter = {}): Promise<Report[]> {\n return (await this.readAll())\n .filter((e): e is { kind: \"report\"; report: Report } => e.kind === \"report\")\n .map((e) => e.report)\n .filter((report) => (filter.taskId ? report.taskId === filter.taskId : true))\n .filter((report) => (filter.agent ? report.agent === filter.agent : true))\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n }\n\n async saveCombined(combined: CombinedReport): Promise<void> {\n await this.mutate((entries) => {\n const index = entries.findIndex((e) => e.kind === \"combined\" && e.combined.id === combined.id);\n const entry: StoreEntry = { kind: \"combined\", combined };\n if (index >= 0) entries[index] = entry;\n else entries.push(entry);\n return [entries, undefined];\n });\n }\n\n async getCombined(id: string): Promise<CombinedReport | undefined> {\n const found = (await this.readAll()).find((e) => e.kind === \"combined\" && e.combined.id === id);\n return found?.kind === \"combined\" ? found.combined : undefined;\n }\n\n async listCombined(filter: CombinedReportFilter = {}): Promise<CombinedReport[]> {\n return (await this.readAll())\n .filter((e): e is { kind: \"combined\"; combined: CombinedReport } => e.kind === \"combined\")\n .map((e) => e.combined)\n .filter((combined) => (filter.pipelineRunId ? combined.pipelineRunId === filter.pipelineRunId : true))\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n }\n}\n","import type { Command } from \"commander\";\nimport { OmniNodeError } from \"../../errors/index.js\";\nimport { ReportService } from \"../../reports/index.js\";\nimport { FileReportStore } from \"../../reports/store.js\";\nimport { truncate } from \"./shared.js\";\n\nfunction service(): ReportService {\n return new ReportService(new FileReportStore());\n}\n\nexport function registerReportCommands(program: Command): void {\n const report = program\n .command(\"report\")\n .description(\"Inspect AI reports collected from tasks and pipelines (§16–§17).\");\n\n report\n .command(\"list\")\n .description(\"List stored reports.\")\n .option(\"--task <taskId>\", \"Only reports for this task.\")\n .option(\"--agent <name>\", \"Only reports from this agent.\")\n .action(async (options: { task?: string; agent?: string }) => {\n const svc = service();\n const reports = await svc.storeRef.listReports({\n ...(options.task !== undefined ? { taskId: options.task } : {}),\n ...(options.agent !== undefined ? { agent: options.agent } : {}),\n });\n if (reports.length === 0) {\n console.log(\"No reports stored yet. Run a pipeline to collect some.\");\n return;\n }\n for (const r of reports) {\n console.log(`${r.id} ${r.agent.padEnd(10)} ${truncate(r.summary, 60)}`);\n }\n });\n\n report\n .command(\"combined\")\n .description(\"List combined reports (aggregated intelligence, §17).\")\n .option(\"--run <pipelineRunId>\", \"Only combined reports for this pipeline run.\")\n .action(async (options: { run?: string }) => {\n const svc = service();\n const combined = await svc.storeRef.listCombined({\n ...(options.run !== undefined ? { pipelineRunId: options.run } : {}),\n });\n if (combined.length === 0) {\n console.log(\"No combined reports stored yet. Run a pipeline to generate one.\");\n return;\n }\n for (const c of combined) {\n const conflicts = c.conflicts.length > 0 ? ` ${c.conflicts.length} CONFLICT(S)` : \"\";\n console.log(\n `${c.id} ${c.findings.length} finding(s) from ${c.sources.length} source(s)` +\n `${conflicts}${c.pipelineRunId ? ` run=${c.pipelineRunId}` : \"\"}`,\n );\n }\n });\n\n report\n .command(\"show <id>\")\n .description(\"Show a stored report or combined report in full.\")\n .action(async (id: string) => {\n const svc = service();\n const reports = await svc.storeRef.listReports();\n const raw = reports.find((r) => r.id === id);\n if (raw) {\n console.log(`Report ${raw.id}`);\n console.log(` agent: ${raw.agent}${raw.model ? ` (${raw.model})` : \"\"}`);\n console.log(` task: ${raw.taskId}`);\n console.log(` summary: ${raw.summary}`);\n if (raw.findings.length > 0) {\n console.log(\" findings:\");\n for (const finding of raw.findings) {\n console.log(` - [${finding.severity ?? \"info\"}] ${finding.title}`);\n for (const evidence of finding.evidence ?? []) {\n console.log(` evidence: ${evidence}`);\n }\n }\n }\n if (raw.recommendations.length > 0) {\n console.log(\" recommendations:\");\n for (const recommendation of raw.recommendations) {\n console.log(` - ${recommendation}`);\n }\n }\n return;\n }\n\n const combined = await svc.storeRef.getCombined(id);\n if (combined) {\n console.log(`Combined report ${combined.id}`);\n console.log(` sources: ${combined.sources.join(\", \")}`);\n console.log(` reports: ${combined.reportIds.length}`);\n if (combined.pipelineRunId) console.log(` run: ${combined.pipelineRunId}`);\n console.log(` summary: ${combined.summary}`);\n if (combined.conflicts.length > 0) {\n console.log(` CONFLICTS (${combined.conflicts.length}) — both positions preserved:`);\n for (const conflict of combined.conflicts) {\n console.log(` ! ${conflict.findingTitle} [${conflict.type}]`);\n for (const position of conflict.positions) {\n console.log(\n ` ${position.agent}: severity=${position.severity ?? \"unstated\"}` +\n `${position.recommendation ? ` fix=\"${position.recommendation}\"` : \"\"}`,\n );\n }\n console.log(` ${conflict.note}`);\n }\n }\n if (combined.agreements.length > 0) {\n console.log(` agreements: ${combined.agreements.length} (multi-agent consensus)`);\n }\n if (combined.findings.length > 0) {\n console.log(\" findings (grouped, duplicates merged):\");\n for (const finding of combined.findings) {\n console.log(\n ` - [${finding.severity ?? \"info\"}] ${finding.title} (x${finding.occurrences}, sources: ${finding.sources.map((s) => s.agent).join(\", \")})`,\n );\n }\n }\n if (combined.recommendations.length > 0) {\n console.log(\" recommendations:\");\n for (const recommendation of combined.recommendations) {\n console.log(` - ${recommendation.text} (x${recommendation.occurrences})`);\n }\n }\n return;\n }\n\n throw new OmniNodeError(\"REPORT_NOT_FOUND\", `Report \"${id}\" was not found in the report store.`);\n });\n}\n","/**\n * Pipeline engine (§14, §15, §27 Phase 5): validates pipeline definitions,\n * schedules steps over their dependency DAG (implicit sequential chain by\n * default, parallel where the DAG allows), fans research steps out to several\n * agents, hands combined context to plan steps (via a chat model) and to the\n * final execution agent. Every task runs through the TaskEngine, so tasks,\n * results and reports are persisted normally.\n */\nimport { randomBytes } from \"node:crypto\";\nimport type { AgentRegistry } from \"../agents/index.js\";\nimport type { AppConfig } from \"../config/index.js\";\nimport { PipelineError } from \"../errors/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { RoleRegistry } from \"../roles/index.js\";\nimport { createProvider } from \"../providers/index.js\";\nimport type { RoleDefinition } from \"../types/role.js\";\nimport type {\n IPipelineExecutor,\n PipelineDefinition,\n PipelineRun,\n PipelineRunOptions,\n PipelineRunStatus,\n PipelineStep,\n PipelineStepRun,\n} from \"../types/pipeline.js\";\nimport type { ChatFn } from \"../types/chat.js\";\n// Re-exported for v1 compatibility: ChatFn now lives in the neutral types layer.\nexport type { ChatFn };\nimport type { Plan } from \"../types/plan.js\";\nimport type { Report } from \"../types/report.js\";\nimport type { ReportService } from \"../reports/index.js\";\nimport { aggregateReports } from \"../reports/aggregate.js\";\nimport type { AuditSink } from \"../audit/index.js\";\nimport type { IPlanner } from \"../planner/index.js\";\nimport type { PlanStore } from \"../planner/store.js\";\nimport { HeuristicPlanner } from \"../planner/heuristic.js\";\nimport { ModelPlanner } from \"../planner/model.js\";\nimport type { TaskEngine } from \"../tasks/index.js\";\nimport type { PipelineRunStore } from \"./store.js\";\n\nexport interface PipelineEngineOptions {\n tasks: TaskEngine;\n agents: AgentRegistry;\n roles: RoleRegistry;\n providers: AppConfig[\"project\"][\"providers\"];\n store: PipelineRunStore;\n chat?: ChatFn;\n /** Default planner used by plan steps without their own model (§18). */\n planner?: IPlanner;\n /** When present, plans produced by plan steps are persisted. */\n plans?: PlanStore;\n /** When present, pipeline lifecycle events are appended to the audit log (§24). */\n audit?: AuditSink;\n /** When present, finished runs have their reports collected, stored and combined (§16–§17). */\n reports?: ReportService;\n log?: Logger;\n}\n\nexport interface RunPipelineOptions {\n objective?: string;\n onStep?: (stepRun: PipelineStepRun) => void;\n}\n\ninterface StepOutcome {\n status: \"completed\" | \"failed\" | \"partial\" | \"skipped\";\n summary: string;\n /** What this step adds to the combined context (defaults to summary). */\n contextContribution?: string;\n taskIds: string[];\n /** Execution ids of created tasks, for correlation (§6.5). */\n executionIds?: string[];\n /** Step attempt that produced this outcome (1 = first try). */\n attempt?: number;\n planId?: string;\n error?: string;\n reports: Report[];\n}\n\ninterface StepContext {\n objective: string;\n runId?: string;\n /** Definition id (correlates events with the pipeline, not just the run). */\n pipelineDefId?: string;\n taskId?: string;\n role?: RoleDefinition;\n combinedContext: string;\n reports: Report[];\n pipelineRunId?: string;\n}\n\nexport class PipelineEngine implements IPipelineExecutor {\n private readonly log: Logger;\n /** Runs executing in THIS process — cancellation can terminate them directly. */\n private readonly activeRuns = new Map<\n string,\n { taskIds: Set<string>; cancelTasks: () => Promise<void> }\n >();\n\n constructor(private readonly options: PipelineEngineOptions) {\n this.log = (options.log ?? logger).child({ component: \"pipelines\" });\n }\n\n get store(): PipelineRunStore {\n return this.options.store;\n }\n\n /**\n * Saves the run while preserving fields that may be set by another process\n * (e.g. a cancellation request) — an in-memory snapshot must never clobber\n * externally requested cancellation (§9.2).\n */\n private async persist(run: PipelineRun): Promise<void> {\n const current = await this.options.store.get(run.id);\n await this.options.store.save({\n ...run,\n ...(current?.cancellationRequested === true\n ? { cancellationRequested: true, cancellationRequestedAt: current.cancellationRequestedAt }\n : {}),\n });\n }\n\n /** Structural + semantic validation (§27 Phase 5 — pipeline parser). */\n validate(def: PipelineDefinition): void {\n const ids = new Set<string>();\n for (const step of def.steps) {\n if (ids.has(step.id)) {\n throw new PipelineError(\"PIPELINE_INVALID\", `Duplicate step id \"${step.id}\".`);\n }\n ids.add(step.id);\n }\n for (const step of def.steps) {\n for (const dep of step.dependsOn ?? []) {\n if (!ids.has(dep)) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Step \"${step.id}\" depends on unknown step \"${dep}\".`,\n );\n }\n }\n if ((step.kind === \"research\") && (step.agents ?? []).length === 0) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Research step \"${step.id}\" needs at least one agent.`,\n );\n }\n if ((step.kind === \"execute\" || step.kind === \"custom\") && !step.agent) {\n throw new PipelineError(\"PIPELINE_INVALID\", `Step \"${step.id}\" (${step.kind}) needs an agent.`);\n }\n }\n this.assertAcyclic(def);\n }\n\n private assertAcyclic(def: PipelineDefinition): void {\n const deps = this.effectiveDependencies(def);\n const remaining = new Map<string, number>();\n const dependents = new Map<string, string[]>();\n for (const [id, list] of deps) {\n remaining.set(id, list.length);\n for (const d of list) {\n dependents.set(d, [...(dependents.get(d) ?? []), id]);\n }\n }\n const queue = [...deps.keys()].filter((id) => (remaining.get(id) ?? 0) === 0);\n let processed = 0;\n while (queue.length > 0) {\n const id = queue.shift()!;\n processed += 1;\n for (const next of dependents.get(id) ?? []) {\n const left = (remaining.get(next) ?? 0) - 1;\n remaining.set(next, left);\n if (left === 0) queue.push(next);\n }\n }\n if (processed < deps.size) {\n const stuck = [...deps.keys()].filter((id) => (remaining.get(id) ?? 0) > 0);\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Pipeline \"${def.id}\" has a dependency cycle involving: ${stuck.join(\", \")}.`,\n );\n }\n }\n\n /**\n * Steps run sequentially in definition order unless they declare explicit\n * dependencies, which enable parallel branches.\n */\n private effectiveDependencies(def: PipelineDefinition): Map<string, string[]> {\n const deps = new Map<string, string[]>();\n def.steps.forEach((step, index) => {\n const explicit = step.dependsOn ?? [];\n deps.set(\n step.id,\n explicit.length > 0 ? explicit : index > 0 ? [def.steps[index - 1]!.id] : [],\n );\n });\n return deps;\n }\n\n async run(def: PipelineDefinition, options: PipelineRunOptions = {}): Promise<PipelineRun> {\n this.validate(def);\n\n const objective = (options.objective ?? def.objective ?? \"\").trim();\n if (objective.length === 0) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Pipeline \"${def.id}\" needs an objective — pass one or set it in the definition.`,\n );\n }\n const role = def.role ? this.options.roles.get(def.role) : undefined;\n if (def.role && !role) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Role \"${def.role}\" (pipeline \"${def.id}\") is not defined in project.roles.`,\n );\n }\n // Agents referenced by steps must be registered, and plan-step models\n // must resolve to a configured provider — both before anything runs (§9.5).\n for (const step of def.steps) {\n for (const name of [...(step.agents ?? []), ...(step.agent ? [step.agent] : [])]) {\n if (!this.options.agents.get(name)) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Step \"${step.id}\" references unregistered agent \"${name}\".`,\n );\n }\n }\n if (step.model) {\n const separator = step.model.indexOf(\":\");\n if (separator <= 0 || separator === step.model.length - 1) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Step \"${step.id}\" has an invalid model reference \"${step.model}\" — use \"provider:model-id\".`,\n );\n }\n const providerName = step.model.slice(0, separator);\n if (!this.options.providers.some((p) => p.name === providerName)) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Step \"${step.id}\" uses model \"${step.model}\" but provider \"${providerName}\" is not configured.`,\n );\n }\n }\n }\n\n const now = new Date().toISOString();\n const run: PipelineRun = {\n id: `run-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`,\n pipelineId: def.id,\n attempt: 1,\n objective,\n status: \"running\",\n startedAt: now,\n stepRuns: [],\n };\n await this.options.store.save(run);\n const liveTaskIds = new Set<string>();\n this.activeRuns.set(run.id, {\n taskIds: liveTaskIds,\n cancelTasks: async () => {\n for (const taskId of liveTaskIds) {\n await this.options.tasks.cancel(taskId).catch(() => undefined);\n }\n },\n });\n this.log.info(`Running pipeline ${def.id} as ${run.id} (attempt ${run.attempt}).`);\n await this.options.audit?.record({\n at: new Date().toISOString(),\n action: \"pipeline.run.started\",\n id: run.id,\n pipelineId: def.id,\n detail: { pipeline: def.id, objective },\n });\n\n const deps = this.effectiveDependencies(def);\n const outcomes = new Map<string, StepOutcome>();\n const pending = new Set(def.steps.map((s) => s.id));\n const contextParts: string[] = [];\n const allReports: Report[] = [];\n let cancelled = false;\n\n while (pending.size > 0) {\n // §9.2 cancellation check point: stop scheduling, terminate what runs.\n const persisted = await this.options.store.get(run.id);\n if (persisted?.cancellationRequested === true) {\n cancelled = true;\n run.cancellationRequested = true;\n run.cancellationRequestedAt = persisted.cancellationRequestedAt;\n await this.activeRuns.get(run.id)?.cancelTasks();\n for (const step of def.steps.filter((s) => pending.has(s.id))) {\n const stepRun: PipelineStepRun = { stepId: step.id, status: \"cancelled\" };\n run.stepRuns.push(stepRun);\n options.onStep?.(stepRun);\n }\n pending.clear();\n break;\n }\n\n const ready = def.steps.filter(\n (step) => pending.has(step.id) && (deps.get(step.id) ?? []).every((d) => outcomes.has(d)),\n );\n if (ready.length === 0) {\n // Cycle — already rejected by validate(), but never hang.\n throw new PipelineError(\"PIPELINE_FAILED\", `Pipeline \"${def.id}\" scheduling stalled.`);\n }\n\n const settled = await Promise.all(\n ready.map(async (step): Promise<StepOutcome> => {\n if (!this.shouldRun(step, deps.get(step.id) ?? [], outcomes)) {\n return { status: \"skipped\", summary: \"\", taskIds: [], reports: [] };\n }\n const ctx: StepContext = {\n objective,\n ...(role ? { role } : {}),\n combinedContext: contextParts.join(\"\\n\\n\"),\n reports: [...allReports],\n pipelineRunId: run.id,\n runId: run.id,\n pipelineDefId: def.id,\n taskId: run.id,\n };\n return this.executeStep(step, ctx);\n }),\n );\n\n ready.forEach((step, index) => {\n const outcome = settled[index]!;\n outcomes.set(step.id, outcome);\n pending.delete(step.id);\n allReports.push(...outcome.reports);\n if (outcome.status !== \"skipped\" && outcome.summary.length > 0) {\n const contribution = outcome.contextContribution ?? outcome.summary;\n contextParts.push(`## Step \"${step.id}\" (${step.kind})\\n${contribution}`);\n }\n const stepRun: PipelineStepRun = {\n stepId: step.id,\n attempt: outcome.attempt ?? 1,\n ...(outcome.executionIds && outcome.executionIds.length > 0\n ? { executionIds: outcome.executionIds }\n : {}),\n status:\n outcome.status === \"skipped\"\n ? \"cancelled\"\n : outcome.status === \"failed\"\n ? \"failed\"\n : outcome.status === \"partial\"\n ? \"partially_completed\"\n : \"completed\",\n ...(outcome.taskIds.length > 0 ? { taskIds: outcome.taskIds } : {}),\n ...(outcome.planId !== undefined ? { planId: outcome.planId } : {}),\n ...(outcome.error !== undefined ? { error: outcome.error } : {}),\n };\n run.stepRuns.push(stepRun);\n options.onStep?.(stepRun);\n });\n run.reports = [...allReports];\n await this.persist(run);\n }\n\n const allOutcomes = [...outcomes.values()];\n const failed = !cancelled && allOutcomes.some((o) => o.status === \"failed\");\n const partial = !cancelled && !failed && allOutcomes.some((o) => o.status === \"partial\");\n const finalStatus: PipelineRunStatus = cancelled\n ? \"cancelled\"\n : failed\n ? \"failed\"\n : partial\n ? \"partial\"\n : \"completed\";\n const planId = [...outcomes.values()].find((o) => o.planId !== undefined)?.planId;\n\n // §28 — Result: the outcome of the last completed step with tasks.\n let resultSummary: string | undefined;\n for (let i = def.steps.length - 1; i >= 0; i -= 1) {\n const step = def.steps[i]!;\n const outcome = outcomes.get(step.id);\n if (outcome?.status !== \"completed\" || outcome.taskIds.length === 0) continue;\n const stepTasks = (\n await Promise.all(outcome.taskIds.map((id) => this.options.tasks.get(id)))\n ).filter((task): task is NonNullable<typeof task> => task !== undefined);\n const summaries = stepTasks\n .map((task) => task.result?.summary)\n .filter((summary): summary is string => summary !== undefined);\n if (summaries.length > 0) resultSummary = summaries.join(\"\\n\");\n break;\n }\n\n // Report system (§16–§17): collect, store and combine reports from the\n // analysis tasks (research/analyze) — execution output is a result, not a report.\n let combinedReportId: string | undefined;\n if (this.options.reports) {\n const taskIds = def.steps\n .filter((step) => step.kind === \"research\" || step.kind === \"analyze\")\n .flatMap((step) => outcomes.get(step.id)?.taskIds ?? []);\n const tasks = (\n await Promise.all(taskIds.map((id) => this.options.tasks.get(id)))\n ).filter((task): task is NonNullable<typeof task> => task !== undefined);\n const collected = await this.options.reports.collectFromTasks(tasks);\n await this.options.reports.saveReports(collected);\n const combined = await this.options.reports.generateCombined(collected, {\n objective,\n pipelineRunId: run.id,\n taskIds,\n });\n combinedReportId = combined?.id;\n if (collected.length > 0) {\n run.reports = collected;\n }\n }\n\n const finishedAt = new Date().toISOString();\n this.activeRuns.delete(run.id);\n const finished: PipelineRun = {\n ...run,\n status: finalStatus,\n finishedAt,\n attempts: [...(run.attempts ?? []), { attempt: run.attempt, startedAt: run.startedAt ?? finishedAt, finishedAt, status: finalStatus }],\n ...(run.reports !== undefined && run.reports.length > 0 ? { reports: run.reports } : {}),\n ...(combinedReportId !== undefined ? { combinedReportId } : {}),\n ...(planId !== undefined ? { planId } : {}),\n ...(resultSummary !== undefined ? { resultSummary } : {}),\n };\n await this.persist(finished);\n this.log.info(`Pipeline ${def.id} finished: ${finalStatus}.`);\n await this.options.audit?.record({\n at: new Date().toISOString(),\n action: cancelled ? \"pipeline.run.cancelled\" : finalStatus === \"failed\" ? \"pipeline.run.failed\" : \"pipeline.run.finished\",\n id: run.id,\n pipelineId: def.id,\n detail: { pipeline: def.id, status: finalStatus },\n });\n return finished;\n }\n\n /** First-class cancellation (§9.2): requests cancellation and terminates\n * tasks that are running in this process immediately. */\n async cancel(runId: string): Promise<void> {\n const run = await this.options.store.get(runId);\n if (!run) {\n throw new PipelineError(\"PIPELINE_NOT_FOUND\", `Pipeline run \"${runId}\" does not exist.`);\n }\n await this.options.store.save({\n ...run,\n cancellationRequested: true,\n cancellationRequestedAt: new Date().toISOString(),\n });\n const active = this.activeRuns.get(runId);\n if (active) {\n await active.cancelTasks();\n }\n }\n\n async get(runId: string): Promise<PipelineRun | undefined> {\n return this.options.store.get(runId);\n }\n\n async listRuns(filter?: { pipelineId?: string }): Promise<PipelineRun[]> {\n return this.options.store.list(filter);\n }\n\n private shouldRun(\n step: PipelineStep,\n deps: string[],\n outcomes: Map<string, StepOutcome>,\n ): boolean {\n const condition = step.condition ?? \"on-success\";\n const depStatuses = deps.map((d) => outcomes.get(d)?.status);\n const anyFailed = depStatuses.includes(\"failed\");\n // A partial dependency carries real output, so it does not block.\n const anySkipped = depStatuses.includes(\"skipped\");\n if (condition === \"always\") return true;\n if (condition === \"on-failure\") return anyFailed;\n return !anyFailed && !anySkipped;\n }\n\n private async executeStep(step: PipelineStep, ctx: StepContext): Promise<StepOutcome> {\n const retries = step.retries ?? 0;\n let last: StepOutcome | undefined;\n for (let attempt = 0; attempt <= retries; attempt += 1) {\n if (attempt > 0) {\n this.log.warn(`Step \"${step.id}\" failed — retry ${attempt}/${retries}.`);\n }\n last = await this.executeStepOnce(step, ctx);\n if (last.status !== \"failed\") return { ...last, attempt: attempt + 1 };\n }\n return { ...last!, attempt: retries + 1 };\n }\n\n /** Registers tasks created for a step as live, so cancellation can terminate them (§9.2). */\n private trackLiveTasks(runId: string | undefined, taskIds: string[]): void {\n if (!runId) return;\n const active = this.activeRuns.get(runId);\n if (!active) return;\n for (const id of taskIds) active.taskIds.add(id);\n }\n\n private async executeStepOnce(step: PipelineStep, ctx: StepContext): Promise<StepOutcome> {\n switch (step.kind) {\n case \"research\":\n return this.runFanOut(step, ctx);\n case \"collect\":\n return { status: \"completed\", summary: \"(collect: outputs gathered from previous steps)\", taskIds: [], reports: [] };\n case \"analyze\":\n if (!step.agent) {\n return { status: \"completed\", summary: \"(analyze: pass-through, no agent assigned)\", taskIds: [], reports: [] };\n }\n return this.runSingle(step, ctx, step.agent);\n case \"plan\":\n return this.runPlan(step, ctx);\n case \"execute\":\n case \"custom\":\n return this.runSingle(step, ctx, step.agent!);\n }\n }\n\n /** Research fan-out: one task per agent, in parallel (§15). */\n private async runFanOut(step: PipelineStep, ctx: StepContext): Promise<StepOutcome> {\n const agentNames = step.agents ?? [];\n const created = await Promise.all(\n agentNames.map((name) =>\n this.options.tasks.create({\n objective: ctx.objective,\n ...(ctx.pipelineRunId !== undefined ? { pipelineId: ctx.pipelineRunId } : {}),\n agent: name,\n ...(ctx.role ? { role: ctx.role.id } : {}),\n ...(ctx.combinedContext.length > 0\n ? { context: { background: ctx.combinedContext } }\n : {}),\n }),\n ),\n );\n this.trackLiveTasks(ctx.runId, created.map((t) => t.id));\n const results = await Promise.all(created.map((task) => this.options.tasks.run(task.id)));\n const executionIds = results.map((r) => r.executions?.at(-1)?.executionId).filter((id): id is string => id !== undefined);\n\n const completedTasks = results.filter((r) => r.status === \"completed\");\n const failedTasks = results.filter((r) => r.status !== \"completed\");\n const lines = results.map((result, index) => {\n const agentName = agentNames[index] ?? \"unknown\";\n const outcome = result.result?.summary ?? result.result?.error ?? \"(no output)\";\n return `- ${agentName}: ${outcome}`;\n });\n const reports = results.flatMap((r) => r.result?.reports ?? []);\n const summary = lines.join(\"\\n\");\n\n if (failedTasks.length > 0) {\n const firstError = failedTasks[0]?.result?.error ?? failedTasks[0]?.lastError ?? \"unknown outcome\";\n const states = failedTasks.map((r) => r.status).join(\", \");\n return {\n // Some agents succeeded → the step produced usable but incomplete\n // intelligence: partial, not failed (roadmap §9.3).\n status: completedTasks.length > 0 ? \"partial\" : \"failed\",\n summary,\n taskIds: created.map((t) => t.id),\n error: `${failedTasks.length}/${results.length} task(s) incomplete (${states}) — ${firstError}`,\n reports,\n };\n }\n return {\n status: \"completed\",\n summary,\n taskIds: created.map((t) => t.id),\n ...(executionIds.length > 0 ? { executionIds } : {}),\n reports,\n };\n }\n\n private async runSingle(\n step: PipelineStep,\n ctx: StepContext,\n agentName: string,\n ): Promise<StepOutcome> {\n const task = await this.options.tasks.create({\n objective: ctx.objective,\n ...(ctx.pipelineRunId !== undefined ? { pipelineId: ctx.pipelineRunId } : {}),\n agent: agentName,\n ...(ctx.role ? { role: ctx.role.id } : {}),\n ...(ctx.combinedContext.length > 0 ? { context: { background: ctx.combinedContext } } : {}),\n });\n this.trackLiveTasks(ctx.runId, [task.id]);\n const result = await this.options.tasks.run(task.id);\n if (result.status !== \"completed\") {\n return {\n // Unknown/timed_out outcomes are not failures — the work may have\n // happened remotely; the step is incomplete, not broken.\n status: result.status === \"unknown\" || result.status === \"timed_out\" ? \"partial\" : \"failed\",\n summary: result.result?.summary ?? \"\",\n taskIds: [task.id],\n error: result.result?.error ?? `task ${task.id} did not complete`,\n reports: result.result?.reports ?? [],\n };\n }\n return {\n status: \"completed\",\n summary: result.result?.summary ?? \"(no output)\",\n taskIds: [task.id],\n reports: result.result?.reports ?? [],\n };\n }\n\n private async runPlan(step: PipelineStep, ctx: StepContext): Promise<StepOutcome> {\n // §15 Planner Input: task, reports, aggregated findings (consensus +\n // conflicts), context, role and step constraints.\n const aggregated = ctx.reports.length > 0 ? aggregateReports(ctx.reports) : undefined;\n const request = {\n objective: ctx.objective,\n reports: ctx.reports,\n ...(aggregated !== undefined ? { aggregated } : {}),\n ...(ctx.combinedContext.length > 0 ? { context: ctx.combinedContext } : {}),\n ...(ctx.role ? { role: ctx.role } : {}),\n ...(step.constraints !== undefined && step.constraints.length > 0\n ? { constraints: step.constraints }\n : {}),\n ...(ctx.pipelineRunId !== undefined ? { pipelineRunId: ctx.pipelineRunId } : {}),\n };\n\n // Selection order: an explicit step model wins, then the configured\n // default planner, then a pass-through (nothing to plan with).\n let planner: IPlanner;\n if (step.model) {\n planner = new ModelPlanner({\n model: step.model,\n chat: this.getChat(),\n fallback: new HeuristicPlanner(),\n log: this.log,\n });\n } else if (this.options.planner) {\n planner = this.options.planner;\n } else {\n return {\n status: \"completed\",\n summary: \"(plan: no model or planner configured — skipped)\",\n taskIds: [],\n reports: [],\n };\n }\n\n let plan: Plan;\n try {\n plan = await planner.plan(request);\n } catch (error) {\n return {\n status: \"failed\",\n summary: \"\",\n taskIds: [],\n error: error instanceof Error ? error.message : String(error),\n reports: [],\n };\n }\n\n await this.options.plans?.save(plan);\n await this.options.audit?.record({\n at: new Date().toISOString(),\n action: \"plan.generated\",\n id: plan.id,\n ...(ctx.pipelineDefId !== undefined ? { pipelineId: ctx.pipelineDefId } : {}),\n detail: {\n generatedBy: plan.generatedBy,\n steps: plan.steps.length,\n run: ctx.pipelineRunId,\n taskId: ctx.taskId,\n },\n });\n return {\n status: \"completed\",\n summary: plan.summary,\n contextContribution: formatPlan(plan),\n taskIds: [],\n planId: plan.id,\n reports: [],\n };\n }\n\n private getChat(): ChatFn {\n if (this.options.chat) return this.options.chat;\n throw new PipelineError(\n \"PIPELINE_FAILED\",\n \"No chat function available — configure a provider for plan steps.\",\n );\n }\n}\n\nfunction formatPlan(plan: Plan): string {\n const lines = [\n `# Implementation Plan (by ${plan.generatedBy})`,\n plan.summary,\n \"Steps:\",\n ...plan.steps.map((step) => {\n const targets = step.targets && step.targets.length > 0 ? ` [targets: ${step.targets.join(\", \")}]` : \"\";\n return `${step.order}. ${step.title}${targets}`;\n }),\n ];\n if (plan.risks && plan.risks.length > 0) {\n lines.push(\"Risks:\", ...plan.risks.map((risk) => `- ${risk}`));\n }\n return lines.join(\"\\n\");\n}\n\n/** Default chat function: resolves \"provider:model\" against the configured providers. */\nexport interface DefaultChatOptions {\n /** Correlates provider errors in the audit log (§18). */\n audit?: AuditSink;\n env?: Record<string, string | undefined>;\n}\n\nexport function createDefaultChatFn(\n providers: AppConfig[\"project\"][\"providers\"],\n options: DefaultChatOptions = {},\n): ChatFn {\n return async (modelRef, messages) => {\n const separator = modelRef.indexOf(\":\");\n if (separator <= 0 || separator === modelRef.length - 1) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Invalid model reference \"${modelRef}\". Use \"provider:model-id\".`,\n );\n }\n const providerName = modelRef.slice(0, separator);\n const modelId = modelRef.slice(separator + 1);\n const providerConfig = providers.find((p) => p.name === providerName);\n if (!providerConfig) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Provider \"${providerName}\" (model \"${modelRef}\") is not configured.`,\n );\n }\n const provider = createProvider(providerConfig, {\n ...(options.audit !== undefined ? { audit: options.audit } : {}),\n ...(options.env !== undefined ? { env: options.env } : {}),\n });\n const response = await provider.chat({ model: modelId, messages });\n return response.content;\n };\n}\n","/**\n * HeuristicPlanner: a deterministic, dependency-free planner that derives an\n * implementation plan from recommendations and significant findings.\n * Used as the no-model option and as the graceful fallback when a model's\n * output is rejected (§15).\n */\nimport { randomBytes } from \"node:crypto\";\nimport type { Plan, PlanStep } from \"../types/plan.js\";\nimport type { Finding, FindingSeverity } from \"../types/report.js\";\nimport type { IPlanner, PlanRequest } from \"./types.js\";\n\nconst SEVERITY_RANK: Record<FindingSeverity, number> = {\n info: 0,\n low: 1,\n medium: 2,\n high: 3,\n critical: 4,\n};\n\ninterface ContributedFinding {\n finding: Finding;\n agent: string;\n}\n\nexport class HeuristicPlanner implements IPlanner {\n readonly name = \"heuristic\";\n\n async plan(request: PlanRequest): Promise<Plan> {\n const steps: PlanStep[] = [];\n\n // One step per distinct recommendation (deduped by text).\n const recommendations = dedupe(request.reports.flatMap((r) => r.recommendations));\n for (const text of recommendations) {\n steps.push({\n id: `step-${steps.length + 1}`,\n title: truncate(text, 120),\n order: steps.length + 1,\n ...(steps.length > 0 ? { dependsOn: [`step-${steps.length}`] } : {}),\n });\n }\n\n // Remediation steps for significant findings, most severe first. Aggregated\n // findings (with consensus/conflicts) take precedence when available.\n const contributed: ContributedFinding[] = request.aggregated\n ? request.aggregated.findings.map((finding) => ({\n finding: {\n id: `agg-${slug(finding.title)}`,\n title: finding.title,\n detail: finding.details[0] ?? finding.title,\n ...(finding.severity ? { severity: finding.severity } : {}),\n ...(finding.recommendations && finding.recommendations.length > 0\n ? { recommendation: finding.recommendations[0] }\n : {}),\n },\n agent: finding.sources.map((s) => s.agent).join(\"+\"),\n }))\n : request.reports.flatMap((report) =>\n report.findings.map((finding) => ({ finding, agent: report.agent })),\n );\n\n const significant = contributed\n .filter(({ finding }) =>\n finding.severity ? SEVERITY_RANK[finding.severity] >= SEVERITY_RANK.high : false,\n )\n .sort(\n (a, b) =>\n SEVERITY_RANK[b.finding.severity ?? \"info\"] - SEVERITY_RANK[a.finding.severity ?? \"info\"],\n );\n for (const { finding } of significant) {\n steps.push(remediationStep(finding, steps.length + 1));\n }\n\n if (steps.length === 0) {\n steps.push({\n id: \"step-1\",\n title: \"Gather additional information\",\n description:\n \"The research reports contained no actionable recommendations or significant findings. \" +\n \"Investigate the objective further before planning implementation work.\",\n order: 1,\n });\n }\n\n const risks = significant\n .filter(({ finding }) => finding.severity === \"critical\")\n .map(({ finding }) => `Critical finding unaddressed until its step completes: ${finding.title}`);\n const conflicts = request.aggregated?.conflicts ?? [];\n if (conflicts.length > 0) {\n risks.push(\n `${conflicts.length} unresolved agent disagreement(s): ${conflicts.map((c) => c.findingTitle).join(\"; \")}`,\n );\n }\n\n return {\n id: `plan-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`,\n objective: request.objective,\n goal: request.aggregated?.title ?? truncate(request.objective, 120),\n summary:\n `Derived from ${request.reports.length} report(s): ` +\n `${recommendations.length} recommendation step(s), ${significant.length} remediation step(s).`,\n steps,\n ...(risks.length > 0 ? { risks } : {}),\n ...(request.constraints !== undefined && request.constraints.length > 0\n ? { constraints: request.constraints }\n : {}),\n generatedBy: \"heuristic\",\n ...(request.taskId !== undefined ? { taskId: request.taskId } : {}),\n ...(request.pipelineRunId !== undefined ? { pipelineRunId: request.pipelineRunId } : {}),\n createdAt: new Date().toISOString(),\n };\n }\n}\n\nfunction remediationStep(finding: Finding, order: number): PlanStep {\n return {\n id: `step-${order}`,\n title: `Fix: ${truncate(finding.title, 100)}`,\n description: finding.detail,\n order,\n dependsOn: order > 1 ? [`step-${order - 1}`] : [],\n sourceFindings: [finding.id],\n ...(finding.recommendation ? { recommendation: finding.recommendation } : {}),\n };\n}\n\nfunction dedupe(texts: string[]): string[] {\n return [...new Set(texts.map((t) => t.trim()).filter((t) => t.length > 0))];\n}\n\nfunction slug(text: string): string {\n return text.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-|-$/g, \"\").slice(0, 40);\n}\n\nfunction truncate(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n","/**\n * ModelPlanner (§18): uses a chat model (\"provider:model-id\" through the chat\n * layer) to produce an implementation plan. The model is asked for JSON\n * matching the plan contract; unparseable output degrades gracefully to the\n * heuristic fallback rather than failing the pipeline.\n */\nimport { randomBytes } from \"node:crypto\";\nimport { PlannerError } from \"../errors/index.js\";\nimport { planJsonSchema, validatePlan } from \"./schema.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { Plan, PlanStep } from \"../types/plan.js\";\nimport type { ChatFn, ChatMessage } from \"../types/chat.js\";\n\nimport { buildPlannerContext } from \"./context.js\";\nimport type { IPlanner, PlanRequest } from \"./types.js\";\n\nexport interface ModelPlannerOptions {\n model: string;\n chat: ChatFn;\n /** Extra instruction appended to the system prompt. */\n instruction?: string;\n /** Used when the model output is unparseable (or the call fails, if tolerateErrors). */\n fallback?: IPlanner;\n log?: Logger;\n}\n\nexport class ModelPlanner implements IPlanner {\n readonly name = \"model\";\n private readonly log: Logger;\n\n constructor(private readonly options: ModelPlannerOptions) {\n this.log = (options.log ?? logger).child({ component: \"planner\", model: options.model });\n }\n\n async plan(request: PlanRequest): Promise<Plan> {\n const context = buildPlannerContext(request);\n const messages: ChatMessage[] = [\n {\n role: \"system\",\n content:\n \"You are the OmniNode planner. Given the objective and the combined research context, \" +\n \"produce a final analysis and a prioritized, actionable implementation plan. \" +\n \"Respond with JSON ONLY (no prose, no code fences) matching exactly this shape: \" +\n '{\"goal\": string, \"summary\": string, \"steps\": [{\"id\": string, \"title\": string, \"description\": string, ' +\n '\"order\": number, \"targets\": string[], \"acceptance_criteria\": string[], \"source_findings\": string[]}], ' +\n '\"risks\": string[], \"notes\": string[]}. ' +\n (this.options.instruction ?? \"\"),\n },\n { role: \"user\", content: context },\n ];\n\n let responseText: string;\n try {\n responseText = await this.options.chat(this.options.model, messages);\n } catch (error) {\n return this.degrade(request, `planner model call failed: ${describe(error)}`);\n }\n\n const parsed = parsePlanJson(responseText);\n if (!parsed.ok) {\n return this.degrade(request, `planner model output rejected: ${parsed.reason}`, parsed.issues);\n }\n\n const plan: Plan = {\n id: `plan-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`,\n objective: request.objective,\n goal: parsed.goal,\n summary: parsed.summary,\n steps: parsed.steps,\n ...(parsed.risks !== undefined ? { risks: parsed.risks } : {}),\n ...(parsed.notes !== undefined ? { notes: parsed.notes } : {}),\n ...(request.constraints !== undefined && request.constraints.length > 0\n ? { constraints: request.constraints }\n : {}),\n generatedBy: `model:${this.options.model}`,\n model: this.options.model,\n ...(request.taskId !== undefined ? { taskId: request.taskId } : {}),\n ...(request.pipelineRunId !== undefined ? { pipelineRunId: request.pipelineRunId } : {}),\n createdAt: new Date().toISOString(),\n };\n\n // §15 Validation: every generated plan passes schema validation.\n const validation = validatePlan(plan);\n if (!validation.valid) {\n return this.degrade(request, `generated plan rejected: ${validation.reason}`, validation.issues);\n }\n return validation.plan;\n }\n\n private async degrade(\n request: PlanRequest,\n reason: string,\n issues: Array<{ path: string; message: string }> = [],\n ): Promise<Plan> {\n if (this.options.fallback) {\n this.log.warn(`${reason} — using the heuristic fallback planner.`);\n return this.options.fallback.plan(request);\n }\n // Structured error: the caller sees exactly what was rejected (§15).\n throw new PlannerError(\"PLAN_INVALID\", `Planner failed: ${reason}.`, {\n details: { reason, issues },\n });\n }\n}\n\nexport type PlanJsonResult =\n | { ok: true; goal: string; summary: string; steps: PlanStep[]; risks?: string[]; notes?: string[] }\n | { ok: false; reason: string; issues: Array<{ path: string; message: string }> };\n\n/** Extracts and validates plan JSON from arbitrary model output (§15). */\nexport function parsePlanJson(text: string): PlanJsonResult {\n const unfenced = text.replace(/```(?:json)?/gi, \"\");\n const start = unfenced.indexOf(\"{\");\n const end = unfenced.lastIndexOf(\"}\");\n if (start < 0 || end <= start) {\n return { ok: false, reason: \"planner output contained no JSON object\", issues: [] };\n }\n let json: unknown;\n try {\n json = JSON.parse(unfenced.slice(start, end + 1));\n } catch (error) {\n return {\n ok: false,\n reason: `planner output was not valid JSON: ${error instanceof Error ? error.message : String(error)}`,\n issues: [],\n };\n }\n const parsed = planJsonSchema.safeParse(json);\n if (!parsed.success) {\n return {\n ok: false,\n reason: \"planner output did not match the plan schema\",\n issues: parsed.error.issues.map((issue) => ({\n path: issue.path.join(\".\") || \"(root)\",\n message: issue.message,\n })),\n };\n }\n const steps: PlanStep[] = parsed.data.steps\n .map((step, index) => ({\n id: step.id ?? `step-${index + 1}`,\n title: step.title,\n description: step.description,\n order: step.order ?? index + 1,\n targets: step.targets,\n acceptanceCriteria: step.acceptance_criteria,\n dependsOn: step.depends_on,\n sourceFindings: step.source_findings,\n }))\n .sort((a, b) => a.order - b.order);\n return {\n ok: true,\n goal: parsed.data.goal,\n summary: parsed.data.summary,\n steps,\n risks: parsed.data.risks,\n notes: parsed.data.notes,\n };\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Plan validation (roadmap §15, Validation): every generated plan passes\n * schema validation. Invalid plans are rejected with structured issues and\n * — where a fallback is configured — fall back to heuristic planning.\n */\nimport { z } from \"zod\";\nimport type { Plan } from \"../types/plan.js\";\n\nconst planStepSchema = z.object({\n id: z.string().min(1).optional(),\n title: z.string().min(1),\n description: z.string().optional(),\n order: z.number().int().optional(),\n targets: z.array(z.string()).optional(),\n acceptance_criteria: z.array(z.string()).optional(),\n depends_on: z.array(z.string()).optional(),\n source_findings: z.array(z.string()).optional(),\n});\n\nexport const planJsonSchema = z.object({\n goal: z.string().min(1),\n summary: z.string().min(1),\n steps: z.array(planStepSchema).min(1),\n risks: z.array(z.string()).optional(),\n notes: z.array(z.string()).optional(),\n});\n\nexport interface PlanValidationIssue {\n path: string;\n message: string;\n}\n\nexport type PlanValidationResult =\n | { valid: true; plan: Plan }\n | { valid: false; issues: PlanValidationIssue[]; reason: string };\n\n/** Validates a plan object (ids/order filled by the caller). */\nexport function validatePlan(plan: Plan): PlanValidationResult {\n const issues: PlanValidationIssue[] = [];\n const stepIds = new Set<string>();\n\n for (const [index, step] of plan.steps.entries()) {\n if (stepIds.has(step.id)) {\n issues.push({ path: `steps.${index}.id`, message: `duplicate step id \"${step.id}\"` });\n }\n stepIds.add(step.id);\n if (!step.title || step.title.trim().length === 0) {\n issues.push({ path: `steps.${index}.title`, message: \"title must not be empty\" });\n }\n for (const dep of step.dependsOn ?? []) {\n if (!stepIds.has(dep) && !plan.steps.some((s) => s.id === dep)) {\n issues.push({ path: `steps.${index}.dependsOn`, message: `unknown step dependency \"${dep}\"` });\n }\n }\n }\n\n if (plan.steps.length === 0) {\n issues.push({ path: \"steps\", message: \"a plan needs at least one step\" });\n }\n if (!plan.summary || plan.summary.trim().length === 0) {\n issues.push({ path: \"summary\", message: \"summary must not be empty\" });\n }\n\n return issues.length > 0\n ? { valid: false, issues, reason: `plan failed validation (${issues.length} issue(s))` }\n : { valid: true, plan };\n}\n\n/** Builds the parser input type for model-produced plan JSON. */\nexport type PlanJsonInput = z.input<typeof planJsonSchema>;\n","/**\n * Planner context builder (§15, Planner Input): assembles the original task,\n * project context, agent reports, aggregated findings, relevant memory and\n * constraints into one structured input, in that order.\n */\nimport type { PlanRequest } from \"./types.js\";\nimport type { Report } from \"../types/report.js\";\n\nexport function buildPlannerContext(request: PlanRequest): string {\n const parts: string[] = [`# Task\\n${request.objective}`];\n\n if (request.projectContext) {\n parts.push(`# Project context\\n${request.projectContext}`);\n }\n\n if (request.role) {\n const roleLines = [`# Role\\n${request.role.name} (${request.role.id})`];\n if (request.role.responsibilities.length > 0) {\n roleLines.push(\"Responsibilities:\", ...request.role.responsibilities.map((r) => `- ${r}`));\n }\n if (request.role.expectedOutputs.length > 0) {\n roleLines.push(\"Expected outputs:\", ...request.role.expectedOutputs.map((o) => `- ${o}`));\n }\n parts.push(roleLines.join(\"\\n\"));\n }\n\n if (request.reports.length > 0) {\n const agents = [...new Set(request.reports.map((r) => r.agent))].join(\", \");\n const findingLines = request.reports.flatMap((report: Report) =>\n report.findings.map(\n (finding) =>\n `- [${finding.severity ?? \"info\"}] ${finding.title} (source: ${report.agent}, finding: ${finding.id})` +\n (finding.detail ? ` — ${finding.detail}` : \"\"),\n ),\n );\n parts.push(\n `# Agent reports (${request.reports.length} by ${agents})\\n` +\n (findingLines.length > 0 ? findingLines.join(\"\\n\") : \"(no findings reported)\"),\n );\n\n const recommendationLines = request.reports.flatMap((report) =>\n report.recommendations.map((text) => `- ${text} (source: ${report.agent})`),\n );\n if (recommendationLines.length > 0) {\n parts.push(`# Recommendations\\n${recommendationLines.join(\"\\n\")}`);\n }\n }\n\n if (request.aggregated) {\n const aggregatedLines = [\n `- findings: ${request.aggregated.findings.length} (agreements: ${request.aggregated.agreements.length}, conflicts: ${request.aggregated.conflicts.length})`,\n ...request.aggregated.findings.map(\n (finding) =>\n `- [${finding.severity ?? \"info\"}] ${finding.title} (x${finding.occurrences})`,\n ),\n // Conflicts stay visible to the planner — it must plan around disagreement.\n ...request.aggregated.conflicts.map(\n (conflict) => `- CONFLICT (${conflict.type}) on \"${conflict.findingTitle}\": ${conflict.note}`,\n ),\n ];\n parts.push(`# Aggregated findings\\n${aggregatedLines.join(\"\\n\")}`);\n }\n\n if (request.memory && request.memory.length > 0) {\n parts.push(\n `# Relevant memory\\n` +\n request.memory.map((entry) => `- [${entry.scope}] ${entry.content}`).join(\"\\n\"),\n );\n }\n\n if (request.constraints && request.constraints.length > 0) {\n parts.push(`# Constraints\\n${request.constraints.map((c) => `- ${c}`).join(\"\\n\")}`);\n }\n\n if (request.context) {\n parts.push(`# Research context\\n${request.context}`);\n }\n\n return parts.join(\"\\n\\n\");\n}\n","/**\n * Plan persistence (§27 Phase 8 — planner result storage). Same\n * replaceable-store pattern as the other local stores.\n */\nimport { JsonFileStore } from \"../persistence/json-file-store.js\";\nimport type { Plan } from \"../types/plan.js\";\n\nexport interface PlanFilter {\n pipelineRunId?: string;\n taskId?: string;\n}\n\nexport interface PlanStore {\n save(plan: Plan): Promise<void>;\n get(id: string): Promise<Plan | undefined>;\n list(filter?: PlanFilter): Promise<Plan[]>;\n}\n\nexport class FilePlanStore extends JsonFileStore<Plan> implements PlanStore {\n constructor(directory?: string) {\n super({ ...(directory !== undefined ? { directory } : {}), fileName: \"plans.json\" });\n }\n\n save(plan: Plan): Promise<void> {\n return this.mutate((plans) => {\n const index = plans.findIndex((p) => p.id === plan.id);\n if (index >= 0) plans[index] = plan;\n else plans.push(plan);\n return [plans, undefined];\n });\n }\n\n async get(id: string): Promise<Plan | undefined> {\n return (await this.readAll()).find((p) => p.id === id);\n }\n\n async list(filter: PlanFilter = {}): Promise<Plan[]> {\n return (await this.readAll())\n .filter((plan) => (filter.pipelineRunId ? plan.pipelineRunId === filter.pipelineRunId : true))\n .filter((plan) => (filter.taskId ? plan.taskId === filter.taskId : true))\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n }\n}\n","/** Planner factory from project configuration (§18 — planner provider support). */\nimport { ConfigError } from \"../errors/index.js\";\nimport type { AppConfig } from \"../config/index.js\";\nimport type { ChatFn } from \"../types/chat.js\";\nimport { HeuristicPlanner } from \"./heuristic.js\";\nimport { ModelPlanner } from \"./model.js\";\nimport type { IPlanner } from \"./types.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\n\nexport function buildPlanner(\n plannerConfig: AppConfig[\"project\"][\"planner\"],\n chat: ChatFn,\n log: Logger = logger,\n): IPlanner | undefined {\n if (!plannerConfig) return undefined;\n if (plannerConfig.kind === \"heuristic\") {\n return new HeuristicPlanner();\n }\n if (!plannerConfig.model) {\n throw new ConfigError(\n \"CONFIG_INVALID\",\n 'Planner kind \"model\" needs a model reference (\"provider:model-id\") in omninode.yaml.',\n );\n }\n return new ModelPlanner({\n model: plannerConfig.model,\n chat,\n ...(plannerConfig.instruction !== undefined ? { instruction: plannerConfig.instruction } : {}),\n fallback: new HeuristicPlanner(),\n log,\n });\n}\n","import type { AppConfig } from \"../config/index.js\";\nimport { FileAuditLog } from \"../audit/index.js\";\nimport { buildAgentRegistry } from \"../agents/index.js\";\nimport { createMemoryProvider, MemoryService } from \"../memory/index.js\";\nimport { buildPlanner } from \"../planner/index.js\";\nimport { FilePlanStore } from \"../planner/store.js\";\nimport { buildRoleRegistry } from \"../roles/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport { ReportService } from \"../reports/index.js\";\nimport { FileReportStore } from \"../reports/store.js\";\nimport { TaskEngine } from \"../tasks/index.js\";\nimport { FileTaskStore } from \"../tasks/store.js\";\nimport { PipelineEngine, createDefaultChatFn } from \"./engine.js\";\nimport { FilePipelineRunStore } from \"./store.js\";\n\nexport function buildPipelineEngine(config: AppConfig, log: Logger = logger): PipelineEngine {\n const auditLog = new FileAuditLog();\n const agents = buildAgentRegistry(config, log);\n const roles = buildRoleRegistry(config);\n const chat = createDefaultChatFn(config.project.providers, { audit: auditLog });\n const tasks = new TaskEngine({\n agents,\n roles,\n store: new FileTaskStore(),\n ...(config.project.memory !== undefined\n ? {\n memory: new MemoryService(createMemoryProvider(config.project.memory), log, {\n required: config.project.memory.required,\n }),\n }\n : {}),\n audit: new FileAuditLog(),\n log,\n });\n return new PipelineEngine({\n tasks,\n agents,\n roles,\n providers: config.project.providers,\n store: new FilePipelineRunStore(),\n chat,\n ...(config.project.planner !== undefined\n ? { planner: buildPlanner(config.project.planner, chat, log) }\n : {}),\n plans: new FilePlanStore(),\n reports: new ReportService(new FileReportStore(), log),\n audit: new FileAuditLog(),\n log,\n });\n}\n","import type { Command } from \"commander\";\nimport { loadConfig } from \"../../config/index.js\";\nimport { PipelineError } from \"../../errors/index.js\";\nimport { buildPipelineEngine } from \"../../pipelines/index.js\";\nimport type { PipelineDefinition } from \"../../types/pipeline.js\";\nimport { registerPipelineInspect } from \"./inspect.js\";\n\nexport function registerPipelineCommands(program: Command): void {\n const pipeline = program\n .command(\"pipeline\")\n .description(\"Run multi-step AI pipelines defined in omninode.yaml (§14).\");\n\n pipeline\n .command(\"list\")\n .description(\"List configured pipelines.\")\n .action(async () => {\n const config = loadConfig();\n const pipelines = config.project.pipelines;\n if (pipelines.length === 0) {\n console.log(\"No pipelines configured. Add one under `project.pipelines` in omninode.yaml.\");\n return;\n }\n for (const def of pipelines) {\n const name = def.name ? ` ${def.name}` : \"\";\n console.log(`${def.id}${name} ${def.steps.length} step(s)`);\n }\n });\n\n pipeline\n .command(\"run <id> [objective]\")\n .description(\n \"Run a pipeline. The objective argument overrides the definition's default objective.\",\n )\n .action(async (id: string, objective: string | undefined) => runPipelineAction(id, objective));\n\n pipeline\n .command(\"retry <run-id> [objective]\")\n .description(\n \"Error recovery: re-run a recorded pipeline run as a new run, reusing its objective.\",\n )\n .action(async (runId: string, objective: string | undefined) => {\n const config = loadConfig();\n const engine = buildPipelineEngine(config);\n const previous = await engine.get(runId);\n if (!previous) {\n throw new PipelineError(\n \"PIPELINE_NOT_FOUND\",\n `Pipeline run \"${runId}\" does not exist in this project's run store.`,\n );\n }\n const def = config.project.pipelines.find((p) => p.id === previous.pipelineId);\n if (!def) {\n throw new PipelineError(\n \"PIPELINE_NOT_FOUND\",\n `Pipeline \"${previous.pipelineId}\" (run ${runId}) is no longer configured in omninode.yaml.`,\n );\n }\n await runPipelineAction(def.id, objective ?? previous.objective);\n });\n\n pipeline\n .command(\"cancel <run-id>\")\n .description(\"Request cancellation of a pipeline run (stops scheduling and cancels running tasks).\")\n .action(async (runId: string) => {\n const config = loadConfig();\n const engine = buildPipelineEngine(config);\n await engine.cancel(runId);\n console.log(`Cancellation requested for run ${runId}.`);\n console.log(\"A run executing in another process stops at its next check point.\");\n });\n\n pipeline\n .command(\"validate <id>\")\n .description(\"Validate a pipeline definition before running it (§9.5).\")\n .action(async (id: string) => {\n const config = loadConfig();\n const def = findPipeline(config, id);\n const engine = buildPipelineEngine(config);\n engine.validate(def);\n console.log(`Pipeline \"${def.id}\" is valid (${def.steps.length} step(s)).`);\n for (const step of def.steps) {\n const deps = step.dependsOn?.join(\", \") ?? \"(previous step)\";\n console.log(` ${step.id} kind=${step.kind} depends_on=${deps}`);\n }\n });\n\n pipeline\n .command(\"runs <id>\")\n .description(\"List recorded runs of a pipeline.\")\n .action(async (id: string) => {\n const config = loadConfig();\n const engine = buildPipelineEngine(config);\n const runs = await engine.listRuns({ pipelineId: id });\n if (runs.length === 0) {\n console.log(`No recorded runs for pipeline \"${id}\".`);\n return;\n }\n for (const run of runs) {\n const note = isInterrupted(run) ? \" (interrupted — process gone before finish)\" : \"\";\n console.log(`${run.id} ${run.status.padEnd(10)} ${run.startedAt ?? \"?\"}${note}`);\n }\n });\n\n pipeline\n .command(\"status <run-id>\")\n .description(\"Show the recorded state of a pipeline run.\")\n .action(async (runId: string) => {\n const config = loadConfig();\n const engine = buildPipelineEngine(config);\n const run = await engine.get(runId);\n if (!run) {\n throw new PipelineError(\n \"PIPELINE_NOT_FOUND\",\n `Pipeline run \"${runId}\" does not exist in this project's run store.`,\n );\n }\n console.log(` id: ${run.id}`);\n console.log(` pipeline: ${run.pipelineId}`);\n console.log(` status: ${run.status}`);\n console.log(` started: ${run.startedAt ?? \"?\"}`);\n if (run.finishedAt) console.log(` finished: ${run.finishedAt}`);\n console.log(` attempt: ${run.attempt}`);\n if (run.cancellationRequested) {\n console.log(` cancellation requested at ${run.cancellationRequestedAt ?? \"?\"}`);\n }\n if (isInterrupted(run)) {\n console.log(\" note: this run looks interrupted (no finishedAt) — retry with `pipeline retry`\");\n }\n if (run.resultSummary) console.log(` result: ${run.resultSummary}`);\n for (const stepRun of run.stepRuns) {\n console.log(` [${stepRun.stepId}] ${stepRun.status}`);\n }\n if (run.reports && run.reports.length > 0) {\n console.log(` reports: ${run.reports.length}`);\n }\n });\n registerPipelineInspect(pipeline);\n}\n\nasync function runPipelineAction(id: string, objective: string | undefined): Promise<void> {\n const config = loadConfig();\n const def = findPipeline(config, id);\n const engine = buildPipelineEngine(config);\n console.log(\n `Running pipeline \"${def.id}\" (${def.steps.length} step(s))${objective ? ` — \"${objective}\"` : \"\"}...`,\n );\n const finished = await engine.run(def, {\n ...(objective !== undefined ? { objective } : {}),\n onStep: (stepRun) => {\n const suffix = stepRun.error ? ` — ${stepRun.error}` : \"\";\n console.log(` [${stepRun.stepId}] ${stepRun.status}${suffix}`);\n },\n });\n if (finished.reports && finished.reports.length > 0) {\n console.log(` reports: ${finished.reports.length} structured report(s)`);\n }\n if (finished.combinedReportId) {\n console.log(` combined report: ${finished.combinedReportId}`);\n }\n if (finished.planId) {\n console.log(` plan: ${finished.planId}`);\n }\n if (finished.resultSummary) {\n console.log(` result: ${finished.resultSummary}`);\n }\n console.log(`Pipeline ${finished.status}. Run id: ${finished.id}`);\n if (finished.status !== \"completed\") process.exitCode = 1;\n}\n\n/** Top-level `omninode run` — a workflow alias of `pipeline run` (§28). */\nexport function registerRunAlias(program: Command): void {\n program\n .command(\"run <id> [objective]\")\n .description(\"Alias of `omninode pipeline run` — execute a configured pipeline end to end.\")\n .action(async (id: string, objective: string | undefined) => runPipelineAction(id, objective));\n}\n\n/** A run left \"running\" with no finishedAt is assumed interrupted (§9.6). */\nfunction isInterrupted(run: { status: string; finishedAt?: string }): boolean {\n return run.status === \"running\" && run.finishedAt === undefined;\n}\n\nfunction findPipeline(config: ReturnType<typeof loadConfig>, id: string): PipelineDefinition {\n const def = config.project.pipelines.find((p) => p.id === id);\n if (!def) {\n const available = config.project.pipelines.map((p) => p.id).join(\", \") || \"(none)\";\n throw new PipelineError(\n \"PIPELINE_NOT_FOUND\",\n `Pipeline \"${id}\" is not configured. Configured pipelines: ${available}.`,\n );\n }\n return def;\n}\n","import type { Command } from \"commander\";\nimport { loadConfig } from \"../../config/index.js\";\nimport { createMemoryProvider, MemoryService } from \"../../memory/index.js\";\nimport { truncate } from \"./shared.js\";\n\nexport function registerMemoryCommands(program: Command): void {\n const memory = program\n .command(\"memory\")\n .description(\"Inspect and manage persistent project memory (§19–§20).\");\n\n memory\n .command(\"status\")\n .description(\"Show the active memory provider and how much is stored.\")\n .action(async () => {\n const config = loadConfig();\n const configured = config.project.memory?.provider ?? \"local (default — add a `memory:` section to opt in)\";\n const svc = new MemoryService(createMemoryProvider(config.project.memory));\n const entries = await svc.providerRef.query({ limit: 10_000 });\n console.log(`provider: ${configured}`);\n console.log(`entries: ${entries.length}`);\n const scopes = new Map<string, number>();\n for (const entry of entries) {\n scopes.set(entry.scope, (scopes.get(entry.scope) ?? 0) + 1);\n }\n for (const [scope, count] of [...scopes.entries()].sort()) {\n console.log(` ${scope}: ${count}`);\n }\n });\n\n memory\n .command(\"query <text>\")\n .description(\"Search memory for entries relevant to the text.\")\n .option(\"-s, --scope <scope>\", \"Restrict to a scope: project, task, role or knowledge.\")\n .option(\"-n, --limit <count>\", \"Maximum entries to return.\", (value: string) => Number(value), 10)\n .action(async (text: string, options: { scope?: string; limit: number }) => {\n const config = loadConfig();\n const svc = new MemoryService(createMemoryProvider(config.project.memory));\n const entries = await svc.providerRef.query({\n text,\n ...(options.scope !== undefined ? { scope: options.scope as \"project\" | \"task\" | \"role\" | \"knowledge\" } : {}),\n limit: options.limit,\n });\n if (entries.length === 0) {\n console.log(\"No relevant memory found.\");\n return;\n }\n for (const entry of entries) {\n console.log(`[${entry.scope}] ${entry.key}`);\n console.log(` ${truncate(entry.content.replace(/\\n/g, \" \"), 120)}`);\n }\n });\n\n memory\n .command(\"write <text>\")\n .description(\"Write an entry to memory.\")\n .option(\"-s, --scope <scope>\", \"Memory scope: project, task, role or knowledge.\", \"project\")\n .option(\"-t, --tags <tags>\", \"Comma-separated tags.\", (value: string) =>\n value.split(\",\").map((tag) => tag.trim()).filter((tag) => tag.length > 0),\n )\n .option(\"-k, --key <key>\", \"Entry key (defaults to a generated note key).\")\n .action(async (text: string, options: { scope: string; tags?: string[]; key?: string }) => {\n const config = loadConfig();\n const svc = new MemoryService(createMemoryProvider(config.project.memory));\n const key = options.key ?? `note:${Date.now().toString(36)}`;\n await svc.providerRef.write({\n key,\n scope: options.scope as \"project\" | \"task\" | \"role\" | \"knowledge\",\n content: text,\n ...(options.tags !== undefined && options.tags.length > 0 ? { tags: options.tags } : {}),\n });\n console.log(`Stored memory entry \"${key}\" (${options.scope}).`);\n });\n}\n","import type { Command } from \"commander\";\nimport { OmniNodeError } from \"../../errors/index.js\";\nimport { FilePlanStore } from \"../../planner/store.js\";\nimport { truncate } from \"./shared.js\";\n\nexport function registerPlanCommands(program: Command): void {\n const plan = program\n .command(\"plan\")\n .description(\"Inspect implementation plans produced by the planner layer (§18).\");\n\n plan\n .command(\"list\")\n .description(\"List stored plans.\")\n .option(\"--run <pipelineRunId>\", \"Only plans for this pipeline run.\")\n .action(async (options: { run?: string }) => {\n const store = new FilePlanStore();\n const plans = await store.list({\n ...(options.run !== undefined ? { pipelineRunId: options.run } : {}),\n });\n if (plans.length === 0) {\n console.log(\"No plans stored yet. Run a pipeline with a plan step to generate one.\");\n return;\n }\n for (const p of plans) {\n console.log(`${p.id} ${p.steps.length} step(s) by ${p.generatedBy} ${truncate(p.summary, 50)}`);\n }\n });\n\n plan\n .command(\"show <id>\")\n .description(\"Show a stored implementation plan in full.\")\n .action(async (id: string) => {\n const store = new FilePlanStore();\n const found = await store.get(id);\n if (!found) {\n throw new OmniNodeError(\"PLAN_INVALID\", `Plan \"${id}\" was not found in the plan store.`, {\n details: { id },\n });\n }\n console.log(`Plan ${found.id}`);\n console.log(` objective: ${found.objective}`);\n console.log(` by: ${found.generatedBy}`);\n console.log(` summary: ${found.summary}`);\n console.log(\" steps:\");\n for (const step of [...found.steps].sort((a, b) => a.order - b.order)) {\n const targets = step.targets && step.targets.length > 0 ? ` [${step.targets.join(\", \")}]` : \"\";\n console.log(` ${step.order}. ${step.title}${targets}`);\n if (step.description) console.log(` ${truncate(step.description, 100)}`);\n for (const criterion of step.acceptanceCriteria ?? []) {\n console.log(` accept: ${criterion}`);\n }\n }\n if (found.risks && found.risks.length > 0) {\n console.log(\" risks:\");\n for (const risk of found.risks) {\n console.log(` - ${risk}`);\n }\n }\n });\n}\n","import type { Command } from \"commander\";\nimport { loadConfig } from \"../../config/index.js\";\nimport { createMemoryProvider, MemoryService } from \"../../memory/index.js\";\nimport { FilePlanStore } from \"../../planner/store.js\";\nimport { FileReportStore } from \"../../reports/store.js\";\nimport { FileTaskStore } from \"../../tasks/store.js\";\nimport { FilePipelineRunStore } from \"../../pipelines/store.js\";\nimport { OMNINODE_VERSION } from \"../../version.js\";\n\nfunction groupBy<T>(items: T[], key: (item: T) => string): Record<string, number> {\n const counts: Record<string, number> = {};\n for (const item of items) {\n const k = key(item);\n counts[k] = (counts[k] ?? 0) + 1;\n }\n return counts;\n}\n\nfunction countBy<T>(items: T[], key: (item: T) => string): string {\n const counts = new Map<string, number>();\n for (const item of items) {\n const k = key(item);\n counts.set(k, (counts.get(k) ?? 0) + 1);\n }\n if (counts.size === 0) return \"0\";\n return `${items.length} (${[...counts.entries()].map(([k, v]) => `${k} ${v}`).join(\", \")})`;\n}\n\nexport function registerStatusCommand(program: Command): void {\n program\n .command(\"status\")\n .description(\"Show the project's OmniNode state overview (config, tasks, runs, reports, plans, memory).\")\n .option(\"--json\", \"Emit machine-readable JSON (for scripts and CI).\")\n .action(async (options: { json?: boolean }) => {\n const config = loadConfig();\n\n const tasks = await new FileTaskStore().list();\n const runs = await new FilePipelineRunStore().list();\n const reportStore = new FileReportStore();\n const reports = await reportStore.listReports();\n const combined = await reportStore.listCombined();\n const plans = await new FilePlanStore().list();\n\n let memory: { provider: string; entries: number } | undefined;\n if (config.project.memory !== undefined) {\n const service = new MemoryService(createMemoryProvider(config.project.memory));\n memory = {\n provider: service.providerName,\n entries: (await service.providerRef.query({ limit: 10_000 })).length,\n };\n }\n\n if (options.json) {\n console.log(\n JSON.stringify(\n {\n version: OMNINODE_VERSION,\n project: config.project.name,\n providers: config.project.providers.map((p) => p.name),\n agents: config.project.agents.map((a) => a.name),\n roles: config.project.roles.map((r) => r.id),\n pipelines: config.project.pipelines.map((p) => p.id),\n tasks: { total: tasks.length, byStatus: groupBy(tasks, (t) => t.status) },\n runs: { total: runs.length, byStatus: groupBy(runs, (r) => r.status) },\n reports: { raw: reports.length, combined: combined.length },\n plans: plans.length,\n ...(memory !== undefined ? { memory } : {}),\n },\n null,\n 2,\n ),\n );\n return;\n }\n\n console.log(`OmniNode v${OMNINODE_VERSION} — project \"${config.project.name}\"`);\n console.log(`providers: ${config.project.providers.map((p) => p.name).join(\", \") || \"none\"}`);\n console.log(`agents: ${config.project.agents.map((a) => a.name).join(\", \") || \"none\"}`);\n console.log(`roles: ${config.project.roles.map((r) => r.id).join(\", \") || \"none\"}`);\n console.log(`pipelines: ${config.project.pipelines.map((p) => p.id).join(\", \") || \"none\"}`);\n console.log(`tasks: ${countBy(tasks, (t) => t.status)}`);\n console.log(`runs: ${countBy(runs, (r) => r.status)}`);\n console.log(`reports: ${reports.length} raw, ${combined.length} combined`);\n console.log(`plans: ${plans.length}`);\n if (memory) {\n console.log(`memory: ${memory.provider}, ${memory.entries} entr(ies)`);\n } else {\n console.log(\"memory: not configured (local provider available — add a `memory:` section)\");\n }\n });\n}\n","import type { Command } from \"commander\";\nimport { FileAuditLog } from \"../../audit/index.js\";\n\nexport function registerAuditCommand(program: Command): void {\n program\n .command(\"audit\")\n .description(\"Show the recent audit log — task and pipeline lifecycle events (§24).\")\n .option(\"-n, --limit <count>\", \"Number of events to show (default 20).\", (value: string) => Number(value), 20)\n .action(async (options: { limit: number }) => {\n const events = await new FileAuditLog().recent(options.limit);\n if (events.length === 0) {\n console.log(\"No audit events recorded yet.\");\n return;\n }\n for (const event of events) {\n const id = event.id ? ` ${event.id}` : \"\";\n const detail = event.detail && Object.keys(event.detail).length > 0\n ? ` ${JSON.stringify(event.detail)}`\n : \"\";\n console.log(`${event.at} ${event.action}${id}${detail}`);\n }\n });\n}","/**\n * Persistence layer (v2 Phase 12): one entry point to every local store,\n * the canonical storage interface names, and the migration path that upgrades\n * v1 data in place.\n */\nimport { FileAuditLog } from \"../audit/index.js\";\nimport { LocalMemoryProvider } from \"../memory/local.js\";\nimport { FilePipelineRunStore } from \"../pipelines/store.js\";\nimport { FilePlanStore } from \"../planner/store.js\";\nimport { FileReportStore } from \"../reports/store.js\";\nimport { FileTaskStore } from \"../tasks/store.js\";\nimport {\n SCHEMA_VERSION,\n inspectDocument,\n readDocument,\n writeFileAtomic,\n type DocumentState,\n} from \"./json-file-store.js\";\nexport {\n JsonFileStore,\n SCHEMA_VERSION,\n inspectDocument,\n readDocument,\n writeFileAtomic,\n} from \"./json-file-store.js\";\nexport type { JsonDocument, DocumentState, JsonFileStoreOptions, Durability } from \"./json-file-store.js\";\n\n// Canonical storage interface names (roadmap §16). The v1 names above remain\n// the exported API; these aliases document the mapping.\nexport type { TaskStore, PipelineStore, ReportStore, PlanStore, MemoryStore, AuditStore } from \"./store-types.js\";\n\n/** Bundles every store for a single project directory. */\nexport class ProjectStores {\n readonly tasks: FileTaskStore;\n readonly pipelineRuns: FilePipelineRunStore;\n readonly reports: FileReportStore;\n readonly plans: FilePlanStore;\n readonly memory: LocalMemoryProvider;\n readonly audit: FileAuditLog;\n\n constructor(directory = `${process.cwd()}/.omninode`) {\n this.tasks = new FileTaskStore(directory);\n this.pipelineRuns = new FilePipelineRunStore(directory);\n this.reports = new FileReportStore(directory);\n this.plans = new FilePlanStore(directory);\n this.memory = new LocalMemoryProvider(directory);\n this.audit = new FileAuditLog(directory);\n }\n}\n\nexport interface MigrationReport {\n file: string;\n state: DocumentState[\"status\"];\n before?: number;\n after?: number;\n migrated: boolean;\n note?: string;\n}\n\n/** Every persisted store file OmniNode manages in a project. */\nexport const STORE_FILES = [\n \"tasks.json\",\n \"pipelines.json\",\n \"reports.json\",\n \"plans.json\",\n \"memory.json\",\n] as const;\n\n/**\n * Migration (roadmap §16): inspects every store file, reports its schema\n * state, and — unless `checkOnly` — rewrites v1 documents at the current\n * schema version. Idempotent and safe: unknown/future versions are reported,\n * never rewritten.\n */\nexport async function migrateProjectStores(\n directory = `${process.cwd()}/.omninode`,\n options: { checkOnly?: boolean } = {},\n): Promise<MigrationReport[]> {\n const reports: MigrationReport[] = [];\n for (const file of STORE_FILES) {\n const path = `${directory}/${file}`;\n const state = await inspectDocument(path);\n if (state.status === \"missing\") {\n reports.push({ file, state: state.status, migrated: false });\n continue;\n }\n if (state.status === \"current\") {\n reports.push({ file, state: state.status, before: state.count, after: state.count, migrated: false });\n continue;\n }\n if (state.status === \"future\") {\n reports.push({\n file,\n state: state.status,\n migrated: false,\n note: `written by a newer OmniNode (schema v${state.schemaVersion}); not touched`,\n });\n continue;\n }\n if (state.status === \"corrupt\") {\n reports.push({ file, state: state.status, migrated: false, note: state.detail });\n continue;\n }\n // v1-legacy or empty: rewrite at the current schema version.\n const items = await readDocument<unknown>(path, undefined, false);\n if (!options.checkOnly) {\n await writeFileAtomic(path, `${JSON.stringify({ schemaVersion: SCHEMA_VERSION, items }, null, 2)}\\n`);\n }\n const beforeCount = items.length;\n reports.push({\n file,\n state: state.status,\n before: beforeCount,\n after: items.length,\n migrated: !options.checkOnly,\n ...(options.checkOnly ? { note: \"would migrate\" } : {}),\n });\n }\n return reports;\n}\n","import type { Command } from \"commander\";\nimport { migrateProjectStores, SCHEMA_VERSION } from \"../../persistence/index.js\";\n\nexport function registerMigrateCommand(program: Command): void {\n program\n .command(\"migrate\")\n .description(\n `Inspect and upgrade persisted store files to schema v${SCHEMA_VERSION} (v1 data is migrated in place).`,\n )\n .option(\"--check\", \"Only report what would change; do not write.\")\n .action(async (options: { check?: boolean }) => {\n const reports = await migrateProjectStores(`${process.cwd()}/.omninode`, {\n checkOnly: options.check ?? false,\n });\n let changed = 0;\n for (const report of reports) {\n if (report.migrated || report.state === \"v1-legacy\") changed += 1;\n const detail =\n report.state === \"corrupt\"\n ? ` (corrupt: ${report.note})`\n : report.state === \"future\"\n ? ` (${report.note})`\n : report.state === \"v1-legacy\"\n ? ` ${report.migrated ? \"migrated\" : \"would migrate\"} ${report.before ?? 0} → ${report.after ?? 0} item(s)`\n : report.state === \"current\"\n ? ` ${report.after ?? 0} item(s)`\n : \"\";\n console.log(`${report.file.padEnd(16)} ${report.state}${detail}`);\n }\n console.log(\n changed === 0\n ? `All stores are at schema v${SCHEMA_VERSION}.`\n : `${options.check ? \"Would migrate\" : \"Migrated\"} ${changed} store file(s) to schema v${SCHEMA_VERSION}.`,\n );\n });\n}\n","/**\n * `omninode security audit` — reviews a project's configuration against the\n * security baseline (roadmap §17) and reports findings. Advisory: it reports,\n * it does not change anything.\n */\nimport type { Command } from \"commander\";\nimport { loadConfig } from \"../../config/index.js\";\nimport { resolveEnvPolicy } from \"../../agents/env.js\";\n\ntype Severity = \"info\" | \"warn\";\n\ninterface Finding {\n severity: Severity;\n subject: string;\n message: string;\n}\n\nexport function registerSecurityCommand(program: Command): void {\n program\n .command(\"security\")\n .description(\"Inspect a project's security posture (advisory).\")\n .argument(\"[action]\", \"Action to perform.\", \"audit\")\n .action(async (action: string) => {\n if (action !== \"audit\") {\n console.log(`Unknown security action \"${action}\". Available: audit.`);\n return;\n }\n const config = loadConfig();\n const findings: Finding[] = [];\n\n // Agents: environment exposure, working-directory reach, shell usage.\n for (const agent of config.project.agents) {\n const policy = resolveEnvPolicy(agent);\n if (policy === \"inherit\") {\n findings.push({\n severity: \"warn\",\n subject: `agent \"${agent.name}\"`,\n message:\n \"inherits the full environment — provider keys in OmniNode's environment are visible to it. \" +\n 'Consider env_policy: allowlist|denylist|explicit.',\n });\n }\n if (agent.allowExternalCwd) {\n findings.push({\n severity: \"info\",\n subject: `agent \"${agent.name}\"`,\n message: \"may run outside the project root (allow_external_cwd).\",\n });\n }\n if (agent.env && Object.keys(agent.env).length > 0) {\n findings.push({\n severity: \"info\",\n subject: `agent \"${agent.name}\"`,\n message: `receives ${Object.keys(agent.env).length} explicit environment variable(s).`,\n });\n }\n }\n\n // Providers and memory: credentials must be referenced, never inline.\n for (const provider of config.project.providers) {\n if (!provider.apiKeyEnvVar) {\n findings.push({\n severity: \"info\",\n subject: `provider \"${provider.name}\"`,\n message: \"no api_key_env_var — fine for keyless local endpoints, otherwise credentials cannot be resolved.\",\n });\n }\n }\n if (config.project.memory?.provider === \"remembera\" && !config.project.memory.apiKeyEnvVar) {\n findings.push({\n severity: \"warn\",\n subject: \"memory\",\n message: 'Remembera is configured without api_key_env_var; requests will be unauthenticated.',\n });\n }\n\n console.log(`OmniNode security audit — project \"${config.project.name}\"`);\n if (findings.length === 0) {\n console.log(\" no findings.\");\n }\n for (const finding of findings) {\n console.log(` [${finding.severity.toUpperCase()}] ${finding.subject}: ${finding.message}`);\n }\n console.log(\n `\\nTrust model: agents execute with the permissions of the OS user running OmniNode.`,\n );\n console.log(\n `OmniNode does not sandbox agents — run untrusted agents in a container or as a dedicated user.`,\n );\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,eAAe;;;ACFjB,IAAM,mBAAmB;;;ACKhC,SAAS,SAAS;AAEX,IAAM,uBAAuB,EACjC,OAAO;AAAA,EACN,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACtB,MAAM,EAAE,KAAK,CAAC,qBAAqB,eAAe,cAAc,SAAS,QAAQ,CAAC;AAAA,EAClF,UAAU,EAAE,OAAO,EAAE,IAAI;AAAA,EACzB,iBAAiB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EAC5C,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS;AAAA,EACjD,SAAS,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,SAAS;AAAA,EACvC,SAAS,EAAE,QAAQ,EAAE,SAAS;AAAA,EAC9B,UAAU,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE,SAAS;AAC3C,CAAC,EACA,OAAO;AAEH,IAAM,oBAAoB,EAC9B,OAAO;AAAA,EACN,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA;AAAA,EAEtB,MAAM,EAAE,KAAK,CAAC,OAAO,UAAU,SAAS,CAAC,EAAE,QAAQ,KAAK;AAAA,EACxD,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EACpC,MAAM,EAAE,MAAM,EAAE,O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AACA,UAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AACpE,UAAQ,KAAK,CAAC;AAChB;AAEA,IAAM,QAAQ,QAAQ,KAAK,CAAC,IACxB,cAAc,aAAa,QAAQ,KAAK,CAAC,CAAC,CAAC,EAAE,OAC7C;AACJ,IAAI,YAAY,QAAQ,OAAO;AAC7B,MAAI,QAAQ,IAAI,EAAE,MAAM,CAAC,UAAU,YAAY,KAAK,CAAC;AACvD;","names":["existsSync","existsSync","readFileSync","writeFileSync","readFileSync","writeFileSync","envelope","resolve","entry","entry","entry","run","run","createProvider","provider","agent","role","resolve","mkdir","readFile","dirname","mkdir","dirname","readFile","truncate","randomBytes","z","randomBytes","truncate","truncate","entry","position","randomBytes","randomBytes","SEVERITY_RANK","truncate","randomBytes","z","entry","randomBytes","run","randomBytes","run","entry","service"]}
1
+ {"version":3,"sources":["../../src/cli/index.ts","../../src/version.ts","../../src/cli/exit-codes.ts","../../src/config/schema.ts","../../src/config/secrets.ts","../../src/config/profiles.ts","../../src/config/loader.ts","../../src/config/default.ts","../../src/cli/options.ts","../../src/cli/commands/init.ts","../../src/cli/commands/project.ts","../../src/cli/commands/providers.ts","../../src/registry/index.ts","../../src/cli/commands/shared.ts","../../src/agents/process/index.ts","../../src/agent-protocol/version.ts","../../src/agent-protocol/types.ts","../../src/agent-protocol/codec.ts","../../src/agent-protocol/handshake.ts","../../src/agent-protocol/session.ts","../../src/agents/cwd.ts","../../src/agents/env.ts","../../src/agents/adapters.ts","../../src/agents/registry.ts","../../src/agents/factory.ts","../../src/roles/index.ts","../../src/persistence/json-file-store.ts","../../src/memory/base.ts","../../src/memory/local.ts","../../src/memory/remembera.ts","../../src/memory/factory.ts","../../src/memory/service.ts","../../src/pipelines/store.ts","../../src/tasks/store.ts","../../src/cli/commands/inspect.ts","../../src/tasks/engine.ts","../../src/audit/index.ts","../../src/tasks/engine-factory.ts","../../src/cli/commands/agents.ts","../../src/cli/commands/roles.ts","../../src/cli/commands/tasks.ts","../../src/reports/aggregate.ts","../../src/reports/schema.ts","../../src/reports/extract.ts","../../src/reports/service.ts","../../src/reports/store.ts","../../src/cli/commands/reports.ts","../../src/cli/commands/pipelines.ts","../../src/pipelines/engine.ts","../../src/planner/heuristic.ts","../../src/planner/model.ts","../../src/planner/schema.ts","../../src/planner/context.ts","../../src/planner/store.ts","../../src/planner/factory.ts","../../src/pipelines/engine-factory.ts","../../src/cli/commands/memory.ts","../../src/cli/commands/plan.ts","../../src/cli/commands/status.ts","../../src/cli/commands/audit.ts","../../src/persistence/index.ts","../../src/cli/commands/migrate.ts","../../src/cli/commands/security.ts","../../src/cli/commands/config.ts","../../src/cli/commands/models.ts"],"sourcesContent":["import { pathToFileURL } from \"node:url\";\nimport { realpathSync } from \"node:fs\";\nimport { Command } from \"commander\";\nimport { OMNINODE_VERSION } from \"../version.js\";\nimport { isOmniNodeError } from \"../errors/index.js\";\nimport { configureLogger } from \"../logger/index.js\";\nimport { exitCodeFor } from \"./exit-codes.js\";\nimport { cliConfigOptions, loadProjectConfig } from \"./options.js\";\nimport { registerInitCommand } from \"./commands/init.js\";\nimport { registerProjectCommands } from \"./commands/project.js\";\nimport { registerProviderCommands } from \"./commands/providers.js\";\nimport { registerAgentCommands } from \"./commands/agents.js\";\nimport { registerRoleCommands } from \"./commands/roles.js\";\nimport { registerTaskCommands } from \"./commands/tasks.js\";\nimport { registerReportCommands } from \"./commands/reports.js\";\nimport { registerPipelineCommands, registerRunAlias } from \"./commands/pipelines.js\";\nimport { registerMemoryCommands } from \"./commands/memory.js\";\nimport { registerPlanCommands } from \"./commands/plan.js\";\nimport { registerStatusCommand } from \"./commands/status.js\";\nimport { registerAuditCommand } from \"./commands/audit.js\";\nimport { registerMigrateCommand } from \"./commands/migrate.js\";\nimport { registerSecurityCommand } from \"./commands/security.js\";\nimport { registerConfigCommands } from \"./commands/config.js\";\nimport { registerModelsCommand } from \"./commands/models.js\";\n\nexport function createProgram(): Command {\n const program = new Command();\n\n program\n .name(\"omninode\")\n .description(\n \"Provider-agnostic multi-AI orchestration platform: coordinate CLI agents, \" +\n \"AI providers, memory, roles, reports and planning in one execution system.\",\n )\n .version(OMNINODE_VERSION, \"-v, --version\", \"Print the OmniNode version.\")\n .option(\"-c, --config <file>\", \"Use a specific configuration file instead of ./omninode.yaml.\")\n .option(\"-p, --profile <name>\", \"Apply a named configuration profile (development/production/testing).\")\n .hook(\"preAction\", (thisCommand) => {\n cliConfigOptions.path = thisCommand.opts().config;\n cliConfigOptions.profile = thisCommand.opts().profile;\n });\n\n registerInitCommand(program);\n registerProjectCommands(program);\n registerProviderCommands(program);\n registerAgentCommands(program);\n registerRoleCommands(program);\n registerTaskCommands(program);\n registerReportCommands(program);\n registerModelsCommand(program);\n registerPipelineCommands(program);\n registerMemoryCommands(program);\n registerPlanCommands(program);\n registerStatusCommand(program);\n registerAuditCommand(program);\n registerMigrateCommand(program);\n registerSecurityCommand(program);\n registerConfigCommands(program);\n registerRunAlias(program);\n\n return program;\n}\n\nfunction applyLoggingConfig(): void {\n // Best effort: `init` and `--help` must work without a valid configuration.\n try {\n const resolved = loadProjectConfig();\n if (resolved.logging) configureLogger(resolved.logging);\n } catch {\n // Configuration problems surface when the command actually needs it.\n }\n}\n\nexport async function run(argv: string[]): Promise<void> {\n applyLoggingConfig();\n const program = createProgram();\n try {\n await program.parseAsync(argv);\n } catch (error) {\n handleError(error);\n }\n}\n\nexport function handleError(error: unknown): never {\n const code = exitCodeFor(error);\n if (isOmniNodeError(error)) {\n console.error(`error: [${error.code}] ${error.message}`);\n if (error.details !== undefined) {\n console.error(JSON.stringify(error.details, null, 2));\n }\n process.exit(code);\n }\n console.error(error instanceof Error ? error.message : String(error));\n process.exit(code);\n}\n\nconst entry = process.argv[1]\n ? pathToFileURL(realpathSync(process.argv[1])).href\n : \"\";\nif (import.meta.url === entry) {\n run(process.argv).catch((error) => handleError(error));\n}\n","export const OMNINODE_VERSION = \"2.0.0-alpha.16\";\n","/**\n * CLI exit codes (roadmap §19). Stable, documented, and mapped from the\n * typed error hierarchy so scripts can branch on failure class.\n */\nimport { isOmniNodeError } from \"../errors/index.js\";\n\nexport const EXIT = {\n success: 0,\n general: 1,\n invalidInput: 2,\n config: 3,\n provider: 4,\n agent: 5,\n timeout: 6,\n cancelled: 7,\n notFound: 8,\n notImplemented: 9,\n} as const;\n\nexport type ExitCode = (typeof EXIT)[keyof typeof EXIT];\n\n/** Maps an OmniNode error to its documented exit code. */\nexport function exitCodeFor(error: unknown): number {\n if (!isOmniNodeError(error)) return EXIT.general;\n const code = error.code;\n if (code === \"NOT_IMPLEMENTED\") return EXIT.notImplemented;\n if (code === \"AGENT_TIMEOUT\") return EXIT.timeout;\n if (code.startsWith(\"CONFIG_\")) return EXIT.config;\n if (code.startsWith(\"PROVIDER_\") || code === \"MODEL_NOT_FOUND\") return EXIT.provider;\n if (code.startsWith(\"AGENT_\")) return EXIT.agent;\n if (code.endsWith(\"_NOT_FOUND\")) return EXIT.notFound;\n if (code.endsWith(\"_INVALID\") || code === \"CLI_USAGE\" || code === \"PROTOCOL_VIOLATION\") {\n return EXIT.invalidInput;\n }\n return EXIT.general;\n}\n\n/** Exit codes returned when a task/pipeline ends in a non-success terminal state. */\nexport function exitCodeForStatus(status: string): number {\n switch (status) {\n case \"completed\":\n return EXIT.success;\n case \"cancelled\":\n return EXIT.cancelled;\n case \"timed_out\":\n return EXIT.timeout;\n case \"failed\":\n return EXIT.general;\n default:\n // partial / unknown / queued / running are not failures of the CLI call\n return EXIT.success;\n }\n}\n","/**\n * Configuration schema. The project file (omninode.yaml) uses snake_case keys\n * as shown in DEVELOPMENT_PLAN.md §7 and §23; the loader maps them onto the\n * camelCase TypeScript contracts in src/types.\n */\nimport { z } from \"zod\";\n\nexport const providerConfigSchema = z\n .object({\n name: z.string().min(1),\n type: z.enum([\"openai-compatible\", \"omnihilbras\", \"openrouter\", \"local\", \"custom\"]),\n base_url: z.string().url(),\n api_key_env_var: z.string().min(1).optional(),\n timeout_ms: z.number().int().positive().optional(),\n headers: z.record(z.string()).optional(),\n enabled: z.boolean().optional(),\n metadata: z.record(z.unknown()).optional(),\n })\n .strict();\n\nexport const agentConfigSchema = z\n .object({\n name: z.string().min(1),\n /** \"cli\" agents communicate over stdin/stdout (process adapter). */\n type: z.enum([\"cli\", \"native\", \"process\"]).default(\"cli\"),\n command: z.string().min(1).optional(),\n args: z.array(z.string()).optional(),\n cwd: z.string().optional(),\n env: z.record(z.string()).optional(),\n input_mode: z.enum([\"stdin\", \"arg\", \"protocol\"]).default(\"stdin\"),\n timeout_ms: z.number().int().positive().optional(),\n inherit_env: z.boolean().optional(),\n env_policy: z.enum([\"inherit\", \"allowlist\", \"denylist\", \"explicit\"]).optional(),\n env_allowlist: z.array(z.string()).optional(),\n env_denylist: z.array(z.string()).optional(),\n max_output_bytes: z.number().int().positive().optional(),\n allow_external_cwd: z.boolean().optional(),\n metadata: z.record(z.unknown()).optional(),\n })\n .strict();\n\nexport const roleConfigSchema = z\n .object({\n id: z\n .string()\n .min(1)\n .regex(/^[a-z0-9][a-z0-9-]*$/, \"role id must be kebab-case\"),\n name: z.string().min(1),\n description: z.string().optional(),\n responsibilities: z.array(z.string()).default([]),\n expected_outputs: z.array(z.string()).default([]),\n preferred_agents: z.array(z.string()).optional(),\n system_prompt: z.string().optional(),\n metadata: z.record(z.unknown()).optional(),\n })\n .strict();\n\nexport const pipelineStepConfigSchema = z\n .object({\n id: z.string().min(1),\n kind: z.enum([\"research\", \"collect\", \"analyze\", \"plan\", \"execute\", \"custom\"]),\n agents: z.array(z.string()).optional(),\n agent: z.string().optional(),\n model: z.string().optional(),\n depends_on: z.array(z.string()).optional(),\n retries: z.number().int().min(0).max(10).optional(),\n condition: z.enum([\"always\", \"on-success\", \"on-failure\"]).optional(),\n /** Constraints passed to the planner for plan steps (§15). */\n constraints: z.array(z.string()).optional(),\n })\n .strict();\n\nexport const pipelineConfigSchema = z\n .object({\n id: z\n .string()\n .min(1)\n .regex(/^[a-z0-9][a-z0-9-]*$/, \"pipeline id must be kebab-case\"),\n name: z.string().optional(),\n objective: z.string().optional(),\n role: z.string().optional(),\n steps: z.array(pipelineStepConfigSchema).min(1),\n })\n .strict();\n\nexport const plannerConfigSchema = z\n .object({\n kind: z.enum([\"model\", \"heuristic\"]).default(\"model\"),\n model: z.string().optional(),\n instruction: z.string().optional(),\n })\n .strict();\n\nexport const projectConfigSchema = z\n .object({\n name: z.string().min(1),\n providers: z.array(providerConfigSchema).default([]),\n agents: z.array(agentConfigSchema).default([]),\n roles: z.array(roleConfigSchema).default([]),\n pipelines: z.array(pipelineConfigSchema).default([]),\n planner: plannerConfigSchema.optional(),\n memory: z\n .object({\n provider: z.string().min(1).default(\"local\"),\n base_url: z.string().url().optional(),\n api_key_env_var: z.string().min(1).optional(),\n /** When true, memory failures fail tasks instead of being tolerated (§12). */\n required: z.boolean().optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\n\nexport const appConfigSchema = z\n .object({\n /** Active profile; overlays live under `profiles` (§16). */\n profile: z.string().min(1).optional(),\n /** Named partial overlays, e.g. development/production/testing. */\n profiles: z.record(z.unknown()).optional(),\n project: projectConfigSchema,\n logging: z\n .object({\n level: z.enum([\"debug\", \"info\", \"warn\", \"error\"]),\n format: z.enum([\"text\", \"json\"]).optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\n\nexport type ProviderConfigYaml = z.infer<typeof providerConfigSchema>;\nexport type AgentConfigYaml = z.infer<typeof agentConfigSchema>;\nexport type RoleConfigYaml = z.infer<typeof roleConfigSchema>;\nexport type PipelineConfigYaml = z.infer<typeof pipelineConfigSchema>;\nexport type PipelineStepConfigYaml = z.infer<typeof pipelineStepConfigSchema>;\nexport type PlannerConfigYaml = z.infer<typeof plannerConfigSchema>;\nexport type ProjectConfigYaml = z.infer<typeof projectConfigSchema>;\nexport type AppConfigYaml = z.infer<typeof appConfigSchema>;\n","/**\n * Inline secret detection (roadmap §17, Secrets).\n *\n * OmniNode configuration must never contain literal credentials — only\n * environment-variable *references*. This scanner runs before the config is\n * parsed and reports anything that looks like an inline secret, so the file\n * is rejected before it can be committed or persisted.\n */\n\nexport interface SecretFinding {\n /** 1-based line number in the source. */\n line: number;\n /** The offending key, e.g. `api_key`. */\n key: string;\n /** Redacted excerpt — never echoes the value. */\n excerpt: string;\n}\n\n/** Keys that are references or placeholders, not secrets. */\nconst SAFE_KEY_SUFFIXES = [\"_env\", \"_env_var\", \"_file\", \"_path\", \"_ref\", \"_id\", \"_url\", \"_command\"];\n\nconst SECRET_KEY = /^\\s*([A-Za-z0-9_-]*(?:api[_-]?key|token|password|passwd|secret|credential)[A-Za-z0-9_-]*)\\s*:\\s*(.*)$/i;\n\n/** Values that are clearly references, not credentials. */\nconst SAFE_VALUE = /^\\s*(?:\\$\\{[^}]*\\}|\\$[A-Z_][A-Z0-9_]*|<[^>]*>|\"\"|''|null|~)\\s*$/i;\n\nexport function scanForInlineSecrets(source: string): SecretFinding[] {\n const findings: SecretFinding[] = [];\n source.split(\"\\n\").forEach((line, index) => {\n const trimmed = line.trim();\n if (trimmed.startsWith(\"#\")) return; // comments are not credentials\n const match = SECRET_KEY.exec(line);\n if (!match) return;\n const key = match[1] ?? \"\";\n const rawValue = (match[2] ?? \"\").trim().replace(/,\\s*$/, \"\");\n const keyIsReference = SAFE_KEY_SUFFIXES.some((suffix) => key.toLowerCase().endsWith(suffix));\n if (keyIsReference) return;\n const value = rawValue.replace(/^[\"']|[\"']$/g, \"\");\n if (value.length === 0 || SAFE_VALUE.test(rawValue)) return;\n // Very short values are almost always placeholders, not credentials.\n if (value.length < 8) return;\n findings.push({\n line: index + 1,\n key,\n excerpt: `${key}: ${value.slice(0, 3)}… (${value.length} chars, redacted)`,\n });\n });\n return findings;\n}\n\n/** Formats findings as an actionable configuration error message. */\nexport function describeSecretFindings(file: string, findings: SecretFinding[]): string {\n const lines = findings.map((f) => ` line ${f.line}: ${f.excerpt}`).join(\"\\n\");\n return (\n `${file} appears to contain ${findings.length} inline secret(s):\\n${lines}\\n` +\n `OmniNode never stores credentials in configuration. Replace each value with an ` +\n `environment-variable reference, e.g. api_key_env_var: MY_API_KEY.`\n );\n}\n","/**\n * Configuration composition (v2 Phase 16 — Configuration System v2).\n *\n * Precedence, highest first:\n * 1. CLI arguments (--config / --profile, explicit file)\n * 2. Environment (OMNINODE_*)\n * 3. Project config (./omninode.yaml)\n * 4. User config (~/.omninode/config.yaml)\n * 5. Profile overlay (selected profile, applied over 3+4)\n * 6. Defaults\n *\n * Profiles let one file describe several environments (development,\n * production, testing) without duplicating the whole configuration.\n */\nimport { homedir } from \"node:os\";\nimport path from \"node:path\";\nimport type { AppConfig } from \"./loader.js\";\n\n/** Loose input shape: composition happens before strict validation. */\nexport type AppConfigInput = Record<string, unknown>;\n\nexport const KNOWN_PROFILES = [\"default\", \"development\", \"production\", \"testing\"] as const;\nexport type ProfileName = (typeof KNOWN_PROFILES)[number];\n\nexport interface ConfigSources {\n /** Project-level configuration file, if any. */\n projectFile?: string;\n /** User-level configuration file, if any. */\n userFile?: string;\n /** Active profile. */\n profile: string;\n /** Environment variables that overrode configuration. */\n envOverrides: string[];\n /** Values that came from built-in defaults. */\n defaults: string[];\n}\n\n/** Default user-level configuration locations, most portable first. */\nexport function userConfigPath(env: Record<string, string | undefined> = process.env): string {\n if (env.OMNINODE_USER_CONFIG) return env.OMNINODE_USER_CONFIG;\n const home = env.HOME ?? homedir();\n return path.join(home, \".omninode\", \"config.yaml\");\n}\n\n/** Picks the profile: CLI (applied by the loader) > environment > file > default. */\nexport function resolveProfile(\n input: { profile?: unknown },\n env: Record<string, string | undefined>,\n): string {\n if (env.OMNINODE_PROFILE) return env.OMNINODE_PROFILE;\n if (typeof input.profile === \"string\" && input.profile.length > 0) return input.profile;\n return \"default\";\n}\n\n/** Deep-merges configuration overlays (objects merge, scalars/arrays replace). */\nexport function mergeConfig<T>(base: T, overlay: unknown): T {\n if (!isPlainObject(base) || !isPlainObject(overlay)) {\n return (overlay === undefined ? base : (overlay as T));\n }\n const result: Record<string, unknown> = { ...base };\n for (const [key, value] of Object.entries(overlay)) {\n const existing = result[key];\n if (Array.isArray(value)) {\n result[key] = value;\n } else if (isPlainObject(value) && isPlainObject(existing)) {\n result[key] = mergeConfig(existing, value);\n } else {\n result[key] = value;\n }\n }\n return result as T;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction asObject(value: unknown): Record<string, unknown> {\n return isPlainObject(value) ? value : {};\n}\n\n/** Environment overrides applied above every file source. */\nexport function applyEnvOverrides(\n input: AppConfigInput,\n env: Record<string, string | undefined>,\n): { config: AppConfigInput; applied: string[] } {\n const applied: string[] = [];\n const config: AppConfigInput = mergeConfig(input, {});\n\n if (env.OMNINODE_LOG_LEVEL) {\n config.logging = { ...(asObject(config.logging)), level: env.OMNINODE_LOG_LEVEL };\n applied.push(\"OMNINODE_LOG_LEVEL\");\n }\n if (env.OMNINODE_LOG_FORMAT) {\n config.logging = { ...(asObject(config.logging)), format: env.OMNINODE_LOG_FORMAT };\n applied.push(\"OMNINODE_LOG_FORMAT\");\n }\n const memoryProvider = env.OMNINODE_MEMORY_PROVIDER;\n const memoryRequired = env.OMNINODE_MEMORY_REQUIRED;\n if (memoryProvider || memoryRequired) {\n const project = asObject(config.project);\n config.project = {\n ...project,\n memory: {\n ...asObject(project.memory ?? { provider: \"local\" }),\n ...(memoryProvider ? { provider: memoryProvider } : {}),\n ...(memoryRequired ? { required: memoryRequired !== \"false\" } : {}),\n },\n };\n if (memoryProvider) applied.push(\"OMNINODE_MEMORY_PROVIDER\");\n if (memoryRequired) applied.push(\"OMNINODE_MEMORY_REQUIRED\");\n }\n return { config, applied };\n}\n\n/** Built-in defaults, applied last. */\nexport function applyDefaults(input: AppConfigInput): { config: AppConfigInput; applied: string[] } {\n const applied: string[] = [];\n const config: AppConfigInput = mergeConfig(input, {});\n const logging = asObject(config.logging);\n if (logging.level === undefined) {\n config.logging = { ...logging, level: \"info\" };\n applied.push(\"logging.level\");\n }\n if (logging.format === undefined) {\n config.logging = { ...asObject(config.logging), format: \"text\" };\n applied.push(\"logging.format\");\n }\n return { config, applied };\n}\n\nexport type { AppConfig };\n","/**\n * Configuration loader: discovers omninode.yaml, expands ${ENV_VAR}\n * references (so credentials never live in project files, §24), validates it\n * and maps it onto the core TypeScript contracts.\n */\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { parse as parseYaml } from \"yaml\";\nimport { ConfigError } from \"../errors/index.js\";\nimport { describeSecretFindings, scanForInlineSecrets } from \"./secrets.js\";\nimport {\n applyDefaults,\n applyEnvOverrides,\n mergeConfig,\n resolveProfile,\n userConfigPath,\n type AppConfigInput,\n type ConfigSources,\n} from \"./profiles.js\";\nimport type { AgentConfig, AgentIntegrationType } from \"../types/agent.js\";\nimport type { ProviderConfig } from \"../types/provider.js\";\nimport type { RoleDefinition } from \"../types/role.js\";\nimport type { LogLevel } from \"../logger/index.js\";\nimport { appConfigSchema } from \"./schema.js\";\nimport type { AgentConfigYaml, PipelineConfigYaml, ProviderConfigYaml, RoleConfigYaml } from \"./schema.js\";\nimport type { PipelineDefinition } from \"../types/pipeline.js\";\n\nconst CONFIG_FILENAMES = [\"omninode.yaml\", \"omninode.yml\", \"omninode.json\"];\n\nexport interface AppConfig {\n project: {\n name: string;\n providers: ProviderConfig[];\n agents: AgentConfig[];\n roles: RoleDefinition[];\n pipelines: PipelineDefinition[];\n planner?: {\n kind: \"model\" | \"heuristic\";\n model?: string;\n instruction?: string;\n };\n memory?: {\n provider: string;\n baseUrl?: string;\n apiKeyEnvVar?: string;\n required?: boolean;\n };\n };\n logging?: {\n level: LogLevel;\n };\n}\n\nexport interface LoadConfigOptions {\n /** Explicit path (CLI --config); otherwise the project file is discovered. */\n path?: string;\n directory?: string;\n /** Environment used for ${VAR} expansion and OMNINODE_* overrides; defaults to process.env. */\n env?: Record<string, string | undefined>;\n /** Profile override (CLI --profile), above environment and file selection. */\n profile?: string;\n}\n\nexport function findConfigFile(directory = process.cwd()): string | undefined {\n for (const filename of CONFIG_FILENAMES) {\n const candidate = `${directory}/${filename}`;\n if (existsSync(candidate)) return candidate;\n }\n return undefined;\n}\n\n/**\n * Replaces ${VAR} and ${VAR:-fallback} references. Unset variables without a\n * fallback abort loading: a half-resolved config could silently misroute\n * authentication.\n */\nexport function expandEnvRefs(\n text: string,\n env: Record<string, string | undefined>,\n source = \"config\",\n): string {\n return text.replace(\n /\\$\\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\\}/g,\n (_match, name: string, fallback?: string) => {\n const value = env[name] ?? fallback;\n if (value === undefined) {\n throw new ConfigError(\n \"CONFIG_INVALID\",\n `Environment variable \"${name}\" is referenced in ${source} but is not set and has no default.`,\n );\n }\n return value;\n },\n );\n}\n\nexport interface LoadConfigResult {\n config: AppConfig;\n sources: ConfigSources;\n}\n\n/**\n * Composes configuration from every source with the documented precedence\n * (roadmap §16): CLI → environment → project file → user file → profile\n * overlay → defaults.\n */\nexport function loadConfigDetailed(options: LoadConfigOptions = {}): LoadConfigResult {\n const env = options.env ?? process.env;\n const explicitPath = options.path;\n\n // 1. Files: user config first, project config overrides it.\n let input: AppConfigInput = {} as AppConfigInput;\n let projectFile: string | undefined;\n let userFile: string | undefined;\n\n if (!explicitPath) {\n const candidate = userConfigPath(env);\n if (existsSync(candidate)) {\n input = mergeConfig(input, readConfigDocument(candidate, env));\n userFile = candidate;\n }\n }\n\n const resolvedProject =\n explicitPath ??\n (options.directory ? findConfigFile(options.directory) : findConfigFile());\n if (resolvedProject) {\n input = mergeConfig(input, readConfigDocument(resolvedProject, env));\n projectFile = resolvedProject;\n }\n\n if (!projectFile && !userFile) {\n throw new ConfigError(\n \"CONFIG_NOT_FOUND\",\n \"No omninode.yaml found. Run `omninode init` to create one, or pass an explicit path.\",\n );\n }\n\n // 2. Profile overlay, selected by CLI > env > file.\n const profile = options.profile ?? resolveProfile(input, env);\n const overlay = (input as { profiles?: Record<string, unknown> }).profiles?.[profile];\n if (overlay !== undefined) {\n const { profiles: _drop, ...base } = input as { profiles?: unknown } & Record<string, unknown>;\n input = mergeConfig(base, overlay) as AppConfigInput;\n } else if (profile !== \"default\" && profile !== \"\") {\n throw new ConfigError(\n \"CONFIG_INVALID\",\n `Profile \"${profile}\" is not defined in this configuration (known: ${Object.keys((input as { profiles?: Record<string, unknown> }).profiles ?? {}).join(\", \") || \"none\"}).`,\n );\n }\n\n // 3. Environment overrides, then defaults.\n const withEnv = applyEnvOverrides(input, env);\n const withDefaults = applyDefaults(withEnv.config);\n\n // 4. Validate the composed document.\n const parsed = appConfigSchema.safeParse(withDefaults.config);\n if (!parsed.success) {\n const issues = parsed.error.issues.map((issue) => {\n const location = issue.path.join(\".\") || \"(root)\";\n return `${location}: ${issue.message}`;\n });\n throw new ConfigError(\n \"CONFIG_INVALID\",\n `Invalid configuration:\\n ${issues.join(\"\\n \")}`,\n { details: { issues } },\n );\n }\n\n return {\n config: toAppConfig(parsed.data),\n sources: {\n ...(projectFile !== undefined ? { projectFile } : {}),\n ...(userFile !== undefined ? { userFile } : {}),\n profile,\n envOverrides: withEnv.applied,\n defaults: withDefaults.applied,\n },\n };\n}\n\n/** Reads, secret-scans and parses a configuration file. */\nfunction readConfigDocument(path: string, optionsEnv: Record<string, string | undefined>): AppConfigInput {\n const raw = readFileSync(path, \"utf8\");\n // §13 Security: refuse inline credentials before anything is persisted.\n const secretFindings = scanForInlineSecrets(raw);\n if (secretFindings.length > 0) {\n throw new ConfigError(\"CONFIG_INVALID\", describeSecretFindings(path, secretFindings));\n }\n // ${VAR} / ${VAR:-fallback} references are expanded before parsing.\n const expanded = expandEnvRefs(raw, optionsEnv, path);\n try {\n return parseYaml(expanded) as AppConfigInput;\n } catch (error) {\n throw new ConfigError(\"CONFIG_INVALID\", `Failed to parse ${path}.`, { cause: error });\n }\n}\n\n/** Backwards-compatible wrapper: the composed configuration. */\nexport function loadConfig(options: LoadConfigOptions = {}): AppConfig {\n return loadConfigDetailed(options).config;\n}\n\n/**\n * Actionable configuration diagnostics (roadmap §16) — the kind of message a\n * user can act on, rather than a generic schema failure.\n */\nexport function configDiagnostics(config: AppConfig): string[] {\n const notes: string[] = [];\n for (const provider of config.project.providers) {\n if (!provider.apiKeyEnvVar && provider.baseUrl.startsWith(\"https://\")) {\n notes.push(\n `Provider \"${provider.name}\": API key reference is missing — add api_key_env_var: <ENV_VAR> unless this endpoint is intentionally keyless.`,\n );\n }\n }\n for (const agent of config.project.agents) {\n if (!agent.command && agent.integration !== \"custom\") {\n notes.push(`Agent \"${agent.name}\": no command configured — the process adapter needs one.`);\n }\n if (agent.allowExternalCwd) {\n notes.push(`Agent \"${agent.name}\": may run outside the project root (allow_external_cwd).`);\n }\n }\n for (const pipeline of config.project.pipelines) {\n const ids = new Set(pipeline.steps.map((s) => s.id));\n for (const step of pipeline.steps) {\n for (const dep of step.dependsOn ?? []) {\n if (!ids.has(dep)) {\n notes.push(`Pipeline \"${pipeline.id}\": step \"${step.id}\" depends on unknown step \"${dep}\".`);\n }\n }\n }\n }\n return notes;\n}\n\nfunction toAppConfig(yaml: ReturnType<typeof appConfigSchema.parse>): AppConfig {\n return {\n project: {\n name: yaml.project.name,\n providers: yaml.project.providers.map(toProviderConfig),\n agents: yaml.project.agents.map(toAgentConfig),\n roles: yaml.project.roles.map(toRoleDefinition),\n pipelines: yaml.project.pipelines.map(toPipelineDefinition),\n ...(yaml.project.planner !== undefined\n ? {\n planner: {\n kind: yaml.project.planner.kind,\n model: yaml.project.planner.model,\n instruction: yaml.project.planner.instruction,\n },\n }\n : {}),\n ...(yaml.project.memory !== undefined\n ? {\n memory: {\n provider: yaml.project.memory.provider,\n baseUrl: yaml.project.memory.base_url,\n apiKeyEnvVar: yaml.project.memory.api_key_env_var,\n required: yaml.project.memory.required,\n },\n }\n : {}),\n },\n ...(yaml.logging !== undefined ? { logging: yaml.logging } : {}),\n };\n}\n\nfunction toPipelineDefinition(raw: PipelineConfigYaml): PipelineDefinition {\n return {\n id: raw.id,\n name: raw.name,\n objective: raw.objective,\n role: raw.role,\n steps: raw.steps.map((step) => ({\n id: step.id,\n kind: step.kind,\n agents: step.agents,\n agent: step.agent,\n model: step.model,\n dependsOn: step.depends_on,\n retries: step.retries,\n condition: step.condition,\n constraints: step.constraints,\n })),\n };\n}\n\nfunction toProviderConfig(raw: ProviderConfigYaml): ProviderConfig {\n return {\n name: raw.name,\n type: raw.type,\n baseUrl: raw.base_url,\n apiKeyEnvVar: raw.api_key_env_var,\n timeoutMs: raw.timeout_ms,\n headers: raw.headers,\n enabled: raw.enabled,\n metadata: raw.metadata,\n };\n}\n\nfunction toAgentConfig(raw: AgentConfigYaml): AgentConfig {\n const integration: AgentIntegrationType =\n raw.type === \"native\" ? \"native\" : \"process\";\n return {\n name: raw.name,\n integration,\n command: raw.command,\n args: raw.args,\n cwd: raw.cwd,\n env: raw.env,\n inputMode: raw.input_mode,\n timeoutMs: raw.timeout_ms,\n inheritEnv: raw.inherit_env,\n envPolicy: raw.env_policy,\n envAllowlist: raw.env_allowlist,\n envDenylist: raw.env_denylist,\n maxOutputBytes: raw.max_output_bytes,\n allowExternalCwd: raw.allow_external_cwd,\n metadata: raw.metadata,\n };\n}\n\nfunction toRoleDefinition(raw: RoleConfigYaml): RoleDefinition {\n return {\n id: raw.id,\n name: raw.name,\n description: raw.description,\n responsibilities: raw.responsibilities,\n expectedOutputs: raw.expected_outputs,\n preferredAgents: raw.preferred_agents,\n systemPrompt: raw.system_prompt,\n metadata: raw.metadata,\n };\n}\n\n","/** Template written by `omninode init` (§22, §23). */\n\nexport function defaultProjectConfigYaml(projectName = \"My Project\"): string {\n return `project:\n name: ${projectName}\n\n # Providers connect OmniNode to AI model gateways (Phase 1+).\n # Credentials are referenced by environment variable, never stored in this file.\n providers: []\n # - name: my-gateway\n # type: openai-compatible\n # base_url: https://example.com/v1\n # api_key_env_var: MY_API_KEY\n\n # CLI agents registered with OmniNode (Phase 3 wires them up).\n agents: []\n # - name: opencode\n # type: cli\n # command: opencode\n\n # Roles describe what an AI is supposed to do (Phase 4).\n roles: []\n # - id: architecture-reviewer\n # name: Architecture Reviewer\n # responsibilities:\n # - architecture analysis\n # expected_outputs:\n # - findings\n # - recommendations\n\n # Memory is optional; Remembera is the preferred integration (Phase 7).\n # memory:\n # provider: remembera\n`;\n}\n","/**\n * CLI-level configuration options (roadmap §16 precedence: CLI arguments\n * sit above environment variables, project file, user file and defaults).\n */\nimport { findConfigFile, loadConfigDetailed, type AppConfig } from \"../config/index.js\";\n\nexport const cliConfigOptions: { path?: string; profile?: string } = {};\n\n/** Loads the project configuration honoring --config / --profile. */\nexport function loadProjectConfig(): AppConfig {\n return loadConfigDetailed({\n ...(cliConfigOptions.path !== undefined ? { path: cliConfigOptions.path } : {}),\n ...(cliConfigOptions.profile !== undefined ? { profile: cliConfigOptions.profile } : {}),\n }).config;\n}\n\n/** The configuration file in effect (explicit --config wins). */\nexport function activeConfigPath(): string | undefined {\n return cliConfigOptions.path ?? findConfigFile();\n}\n","import { existsSync, writeFileSync } from \"node:fs\";\nimport type { Command } from \"commander\";\nimport { OmniNodeError } from \"../../errors/index.js\";\nimport { defaultProjectConfigYaml } from \"../../config/index.js\";\n\nexport async function runInit(options: { force?: boolean; name?: string }): Promise<void> {\n const target = `${process.cwd()}/omninode.yaml`;\n if (!options.force && existsSync(target)) {\n throw new OmniNodeError(\n \"CLI_USAGE\",\n `${target} already exists. Use --force to overwrite it.`,\n );\n }\n writeFileSync(target, defaultProjectConfigYaml(options.name), \"utf8\");\n console.log(`Created ${target}`);\n console.log(\"\\nNext steps:\");\n console.log(\" 1. Add a provider under `project.providers` (see omninode.yaml.example).\");\n console.log(\" 2. Register CLI agents under `project.agents`.\");\n console.log(\" 3. Run `omninode provider list` to validate the configuration.\");\n}\n\nexport function registerInitCommand(program: Command): void {\n program\n .command(\"init\")\n .description(\"Create an omninode.yaml project configuration in the current directory.\")\n .option(\"-f, --force\", \"Overwrite an existing omninode.yaml.\")\n .option(\"-n, --name <name>\", \"Project name to write into the configuration.\", \"My Project\")\n .action(async (options: { force?: boolean; name: string }) => runInit(options));\n}\n","import type { Command } from \"commander\";\nimport { runInit } from \"./init.js\";\n\nexport function registerProjectCommands(program: Command): void {\n const project = program\n .command(\"project\")\n .description(\"Project-level operations.\");\n\n project\n .command(\"init\")\n .description(\"Alias of `omninode init`.\")\n .option(\"-f, --force\", \"Overwrite an existing omninode.yaml.\")\n .option(\"-n, --name <name>\", \"Project name to write into the configuration.\", \"My Project\")\n .action(async (options: { force?: boolean; name: string }) => runInit(options));\n}\n","import type { Command } from \"commander\";\nimport { readFileSync, writeFileSync } from \"node:fs\";\nimport { parseDocument } from \"yaml\";\nimport { appConfigSchema, providerConfigSchema } from \"../../config/index.js\";\nimport { OmniNodeError, ProviderError } from \"../../errors/index.js\";\nimport { createProvider, OmniHilbrasProvider } from \"../../providers/index.js\";\nimport { ModelRegistry } from \"../../registry/index.js\";\nimport type { ProviderStatus } from \"../../types/provider.js\";\nimport { appendToConfigList } from \"./shared.js\";\nimport { registerProviderInspect } from \"./inspect.js\";\nimport { loadProjectConfig, activeConfigPath } from \"../options.js\";\ninterface AddProviderOptions {\n name: string;\n baseUrl: string;\n type: string;\n apiKeyEnvVar?: string;\n}\n\nexport function registerProviderCommands(program: Command): void {\n const provider = program\n .command(\"provider\")\n .description(\"Manage AI providers configured in omninode.yaml.\");\n\n provider\n .command(\"list\")\n .description(\"List configured providers.\")\n .option(\"--json\", \"Emit providers as JSON.\")\n .action(async (options: { json?: boolean }) => {\n const config = loadProjectConfig();\n const providers = config.project.providers;\n if (options.json) {\n console.log(JSON.stringify(providers, null, 2));\n return;\n }\n if (providers.length === 0) {\n console.log(\n \"No providers configured. Add one with `omninode provider add` or edit omninode.yaml.\",\n );\n return;\n }\n for (const provider of providers) {\n const key = provider.apiKeyEnvVar ? `$${provider.apiKeyEnvVar}` : \"none\";\n const enabled = provider.enabled === false ? \" (disabled)\" : \"\";\n console.log(\n `${provider.name} type=${provider.type} base_url=${provider.baseUrl} key=${key}${enabled}`,\n );\n }\n });\n\n provider\n .command(\"add\")\n .description(\n \"Add a provider to omninode.yaml. OpenAI-compatible gateways (including OpenRouter \" +\n \"and local runtimes) are supported today; OmniHilbras gets its own adapter in Phase 2.\",\n )\n .requiredOption(\"--name <name>\", \"Unique provider name used in configuration and the model registry.\")\n .requiredOption(\"--base-url <url>\", \"Provider base URL, e.g. https://example.com/v1\")\n .option(\n \"--type <type>\",\n \"Provider type: openai-compatible, omnihilbras, openrouter, local or custom.\",\n \"openai-compatible\",\n )\n .option(\n \"--api-key-env-var <envVar>\",\n \"Environment variable holding the API key. Keys are never written to the config file.\",\n )\n .action(async (options: AddProviderOptions) => addProvider(options));\n\n provider\n .command(\"test <name>\")\n .description(\"Test connectivity, authentication and model discovery for a configured provider.\")\n .option(\n \"--connect\",\n \"Run the full provider connect flow (authenticate, fetch, validate, register) where the adapter supports it.\",\n )\n .action(async (name: string, options: { connect?: boolean }) => testProvider(name, options));\n\n provider\n .command(\"remove <name>\")\n .description(\"Remove a provider from omninode.yaml.\")\n .action((name: string) => {\n removeProvider(name);\n });\n registerProviderInspect(provider);\n}\n\nexport async function addProvider(options: AddProviderOptions): Promise<void> {\n const configPath = activeConfigPath();\n if (!configPath) {\n throw new OmniNodeError(\"CONFIG_NOT_FOUND\", \"No omninode.yaml found. Run `omninode init` first.\");\n }\n\n const candidate = providerConfigSchema.safeParse({\n name: options.name,\n type: options.type,\n base_url: options.baseUrl,\n ...(options.apiKeyEnvVar !== undefined ? { api_key_env_var: options.apiKeyEnvVar } : {}),\n });\n if (!candidate.success) {\n const issues = candidate.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"(root)\"}: ${issue.message}`)\n .join(\"; \");\n throw new OmniNodeError(\"CLI_USAGE\", `Invalid provider options: ${issues}`);\n }\n const newProvider = candidate.data;\n\n // Existing name check happens before the document is edited.\n const existing = loadProjectConfig();\n if (existing.project.providers.some((p) => p.name === newProvider.name)) {\n throw new OmniNodeError(\n \"CLI_USAGE\",\n `Provider \"${newProvider.name}\" already exists in ${activeConfigPath() ?? \"omninode.yaml\"}.`,\n );\n }\n\n const writtenPath = appendToConfigList(\"providers\", newProvider);\n console.log(`Added provider \"${newProvider.name}\" (${newProvider.type}) to ${writtenPath}.`);\n if (newProvider.api_key_env_var) {\n console.log(\n `Set $${newProvider.api_key_env_var} in your environment, then run: omninode provider test ${newProvider.name}`,\n );\n } else {\n console.log(`Run \\`omninode provider test ${newProvider.name}\\` to verify connectivity.`);\n }\n}\n\nfunction removeProvider(name: string): void {\n const configPath = activeConfigPath();\n if (!configPath) {\n throw new OmniNodeError(\"CONFIG_NOT_FOUND\", \"No omninode.yaml found.\");\n }\n const config = loadProjectConfig();\n if (!config.project.providers.some((p) => p.name === name)) {\n throw new ProviderError(\"PROVIDER_NOT_FOUND\", `No provider \"${name}\" is configured.`);\n }\n const doc = parseDocument(readFileSync(configPath, \"utf8\"));\n const current = doc.getIn([\"project\", \"providers\"]);\n const remaining = (current === undefined || current === null\n ? []\n : (doc.get(\"project\") as { providers?: unknown[] })?.providers ?? []\n ).filter((entry) => (entry as { name?: string })?.name !== name);\n doc.setIn([\"project\", \"providers\"], remaining);\n const validated = appConfigSchema.safeParse(doc.toJS());\n if (!validated.success) {\n throw new OmniNodeError(\"CONFIG_INVALID\", \"Removing this provider would produce an invalid configuration.\");\n }\n writeFileSync(configPath, doc.toString(), \"utf8\");\n console.log(`Removed provider \"${name}\" from ${configPath}.`);\n}\n\nexport async function testProvider(\n name: string,\n options: { connect?: boolean } = {},\n): Promise<void> {\n const config = loadProjectConfig();\n const providerConfig = config.project.providers.find((p) => p.name === name);\n if (!providerConfig) {\n const available = config.project.providers.map((p) => p.name).join(\", \") || \"(none)\";\n throw new ProviderError(\n \"PROVIDER_NOT_FOUND\",\n `Provider \"${name}\" is not configured. Configured providers: ${available}.`,\n );\n }\n\n const provider = createProvider(providerConfig);\n console.log(`Testing provider \"${name}\" (${providerConfig.type}) at ${provider.config.baseUrl}`);\n\n if (options.connect && provider instanceof OmniHilbrasProvider) {\n const registry = new ModelRegistry();\n try {\n const result = await provider.connectAndRegister(registry);\n printProviderStatus(result.status);\n console.log(` registered: ${result.registered}`);\n } catch (error) {\n console.log(` connect failed: ${error instanceof Error ? error.message : String(error)}`);\n process.exitCode = 1;\n }\n return;\n }\n\n const health = await provider.healthCheck();\n printProviderStatus(health);\n if (!health.connected) process.exitCode = 1;\n}\n\nfunction printProviderStatus(status: ProviderStatus): void {\n console.log(` health: ${status.health}`);\n console.log(` connected: ${status.connected}`);\n console.log(` models: ${status.modelCount}`);\n if (status.message) console.log(` detail: ${status.message}`);\n}\n","/**\n * Normalized model registry (§8): aggregates models discovered from all\n * configured providers under \"provider:model\" keys.\n */\nimport type { ModelCapabilities, ModelInfo } from \"../types/model.js\";\nimport type { IProvider } from \"../types/provider.js\";\n\nexport interface ModelFilter {\n provider?: string;\n capability?: keyof ModelCapabilities;\n}\n\nexport interface DiscoveryResult {\n provider: string;\n models: ModelInfo[];\n error?: Error;\n}\n\nexport function registryKey(provider: string, id: string): string {\n return `${provider}:${id}`;\n}\n\nexport class ModelRegistry {\n private readonly models = new Map<string, ModelInfo>();\n\n register(model: ModelInfo): void {\n this.models.set(registryKey(model.provider, model.id), model);\n }\n\n get(provider: string, id: string): ModelInfo | undefined {\n return this.models.get(registryKey(provider, id));\n }\n\n list(filter: ModelFilter = {}): ModelInfo[] {\n return [...this.models.values()]\n .filter((model) => (filter.provider ? model.provider === filter.provider : true))\n .filter((model) =>\n filter.capability ? model.capabilities?.[filter.capability] === true : true,\n )\n .sort((a, b) => a.provider.localeCompare(b.provider) || a.id.localeCompare(b.id));\n }\n\n /** Availability validation (§27 Phase 1): present in the registry and not retired. */\n isAvailable(provider: string, id: string): boolean {\n const model = this.get(provider, id);\n return model !== undefined && (model.status ?? \"available\") === \"available\";\n }\n\n /** Discover models from one provider and register them. */\n async discoverFrom(provider: IProvider): Promise<ModelInfo[]> {\n const discovered = await provider.listModels();\n for (const model of discovered) this.register(model);\n return discovered;\n }\n\n /** Discover from many providers; a failing provider does not abort the rest. */\n async discoverAll(providers: IProvider[]): Promise<DiscoveryResult[]> {\n return Promise.all(\n providers.map(async (provider) => {\n try {\n return {\n provider: provider.config.name,\n models: await this.discoverFrom(provider),\n };\n } catch (error) {\n return {\n provider: provider.config.name,\n models: [],\n error: error instanceof Error ? error : new Error(String(error)),\n };\n }\n }),\n );\n }\n}\n","import { readFileSync, writeFileSync } from \"node:fs\";\nimport { parseDocument } from \"yaml\";\nimport { appConfigSchema } from \"../../config/index.js\";\nimport { ConfigError, OmniNodeError } from \"../../errors/index.js\";\nimport { activeConfigPath } from \"../options.js\";\n/** Shared helper for commands whose phase has not landed yet. */\nexport function notImplemented(command: string, when: string): OmniNodeError {\n return new OmniNodeError(\n \"NOT_IMPLEMENTED\",\n `${command} is planned for ${when}. Edit omninode.yaml directly for now.`,\n );\n}\n\nexport function truncate(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n\n/**\n * Appends an item to a list in omninode.yaml, preserving comments and\n * formatting, and validates the resulting document before writing.\n * Returns the config path that was edited.\n */\nexport function appendToConfigList(listKey: \"providers\" | \"agents\", item: unknown): string {\n const configPath = activeConfigPath();\n if (!configPath) {\n throw new OmniNodeError(\"CONFIG_NOT_FOUND\", \"No omninode.yaml found. Run `omninode init` first.\");\n }\n\n // Edit as a YAML document so existing comments and formatting survive.\n const doc = parseDocument(readFileSync(configPath, \"utf8\"));\n if (doc.getIn([\"project\", listKey]) === undefined) {\n doc.setIn([\"project\", listKey], [item]);\n } else {\n doc.addIn([\"project\", listKey], item);\n }\n\n const validated = appConfigSchema.safeParse(doc.toJS());\n if (!validated.success) {\n const issues = validated.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"(root)\"}: ${issue.message}`)\n .join(\"; \");\n throw new ConfigError(\n \"CONFIG_INVALID\",\n `Editing ${configPath} would produce an invalid configuration: ${issues}`,\n );\n }\n\n writeFileSync(configPath, doc.toString(), \"utf8\");\n return configPath;\n}\n","/**\n * Process adapter (§9): runs CLI agents as child processes and communicates\n * over stdin/stdout, managing the process lifecycle, working directory,\n * environment, exit codes, logs and timeouts.\n *\n * Three input modes (§9, §21):\n * - \"stdin\": the composed task text is written to the agent's stdin.\n * - \"arg\": the composed task text is appended as the last command argument.\n * - \"protocol\": NodeToAgentMessage envelopes as JSON lines on stdin; the\n * agent answers with AgentToNodeMessage JSON lines (REPORT,\n * COMPLETION, ERROR, ...) whose structured payloads are parsed\n * into reports.\n */\nimport { spawn, type ChildProcess } from \"node:child_process\";\nimport { AgentError } from \"../../errors/index.js\";\nimport { PROTOCOL_V2, ProtocolSession, type QuestionResponder } from \"../../agent-protocol/index.js\";\nimport { logger, type Logger } from \"../../logger/index.js\";\nimport type {\n AgentConfig,\n AgentInfo,\n AgentTaskInput,\n AgentTaskOutput,\n IAgent,\n} from \"../../types/agent.js\";\nimport type { Report } from \"../../types/report.js\";\nimport { validateWorkingDirectory } from \"../cwd.js\";\nimport { buildChildEnv } from \"../env.js\";\n\nconst DEFAULT_TIMEOUT_MS = 600_000;\nconst KILL_GRACE_MS = 5_000;\n/** Per-stream byte budget before output is truncated and the agent killed. */\nexport const DEFAULT_MAX_OUTPUT_BYTES = 5 * 1024 * 1024;\n\nexport function composeTaskText(input: AgentTaskInput): string {\n const sections: string[] = [`# Objective\\n${input.objective}`];\n if (input.role) {\n const lines = [\"# Role\", `${input.role.name} (${input.role.id})`];\n if (input.role.responsibilities.length > 0) {\n lines.push(\"\", \"Responsibilities:\", ...input.role.responsibilities.map((r) => `- ${r}`));\n }\n if (input.role.expectedOutputs.length > 0) {\n lines.push(\"\", \"Expected outputs:\", ...input.role.expectedOutputs.map((o) => `- ${o}`));\n }\n sections.push(lines.join(\"\\n\"));\n }\n if (input.context) sections.push(`# Context\\n${input.context}`);\n if (input.instruction) sections.push(`# Instruction\\n${input.instruction}`);\n return sections.join(\"\\n\\n\");\n}\n\nfunction buildProtocolMessages(input: AgentTaskInput, agentName: string): string[] {\n // Protocol v2 envelopes with full correlation (roadmap §7.2, §7.4).\n const session = new ProtocolSession({\n requestId: `req-${input.taskId}`,\n taskId: input.taskId,\n agentId: agentName,\n ...(input.pipelineId !== undefined ? { pipelineId: input.pipelineId } : {}),\n ...(input.executionId !== undefined ? { executionId: input.executionId } : {}),\n });\n return session.taskMessages(\n input.objective,\n input.role,\n input.context,\n input.instruction,\n );\n}\n\nexport class ProcessAgent implements IAgent {\n readonly config: AgentConfig;\n readonly info: AgentInfo;\n private readonly log: Logger;\n private readonly running = new Map<string, ChildProcess>();\n\n constructor(config: AgentConfig, log: Logger = logger) {\n if (!config.command) {\n throw new AgentError(\"AGENT_NOT_FOUND\", `Agent \"${config.name}\" has no command configured.`);\n }\n this.config = config;\n this.log = log.child({ agent: config.name });\n this.info = {\n name: config.name,\n integration: \"process\",\n command: config.command,\n cwd: config.cwd,\n status: \"ready\",\n capabilities: [config.inputMode ?? \"stdin\"],\n };\n }\n\n async run(input: AgentTaskInput): Promise<AgentTaskOutput> {\n const command = this.config.command;\n if (!command) {\n throw new AgentError(\"AGENT_NOT_FOUND\", `Agent \"${this.config.name}\" has no command configured.`);\n }\n const mode = this.config.inputMode ?? \"stdin\";\n const timeoutMs = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\n return new Promise<AgentTaskOutput>((resolve, reject) => {\n // Validate the working directory BEFORE spawning (roadmap §8): never\n // silently fall back to the OmniNode cwd.\n let cwd: string | undefined;\n try {\n cwd = validateWorkingDirectory(this.config.cwd, {\n allowExternal: this.config.allowExternalCwd,\n })?.cwd;\n } catch (error) {\n // Invalid working directory — fail before spawning anything.\n reject(error);\n return;\n }\n\n const child = spawn(\n command,\n [...(this.config.args ?? []), ...(mode === \"arg\" ? [composeTaskText(input)] : [])],\n {\n ...(cwd !== undefined ? { cwd } : {}),\n env: buildChildEnv(this.config),\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n // Own process group so the whole tree can be terminated together\n // (roadmap §8: no orphaned children).\n ...(process.platform === \"win32\" ? {} : { detached: true }),\n },\n );\n this.running.set(input.taskId, child);\n GLOBAL_RUNNING.add(child);\n installSignalForwarding();\n\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n let outputLimitExceeded = false;\n let settled = false;\n const maxOutputBytes = this.config.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;\n\n const timer = setTimeout(() => {\n timedOut = true;\n this.log.warn(`Task ${input.taskId} exceeded ${timeoutMs}ms — killing process tree.`);\n killTree(child, \"SIGTERM\");\n setTimeout(() => killTree(child, \"SIGKILL\"), KILL_GRACE_MS).unref();\n }, timeoutMs);\n\n const settle = (finish: () => void): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n this.running.delete(input.taskId);\n GLOBAL_RUNNING.delete(child);\n finish();\n };\n\n // Output protection (roadmap §8): runaway/binary output is truncated at\n // a byte budget, and a flooding agent is killed rather than allowed to\n // exhaust memory.\n const collect = (into: \"stdout\" | \"stderr\", chunk: Buffer): void => {\n if (outputLimitExceeded) return;\n const text = sanitizeChunk(chunk);\n if (into === \"stdout\") {\n if (stdout.length + text.length > maxOutputBytes) {\n stdout = (stdout + text).slice(0, maxOutputBytes);\n outputLimitExceeded = true;\n this.log.warn(`Agent \"${this.config.name}\" exceeded the ${maxOutputBytes} byte output limit — killing it.`);\n killTree(child, \"SIGKILL\");\n return;\n }\n stdout += text;\n } else {\n if (stderr.length + text.length > maxOutputBytes) {\n stderr = (stderr + text).slice(0, maxOutputBytes);\n return;\n }\n stderr += text;\n }\n };\n child.stdout?.on(\"data\", (chunk: Buffer) => collect(\"stdout\", chunk));\n child.stderr?.on(\"data\", (chunk: Buffer) => collect(\"stderr\", chunk));\n\n // Agents that exit without reading stdin raise EPIPE on write — that is\n // not an agent failure, so the stream error is ignored.\n child.stdin?.on(\"error\", () => {});\n if (mode !== \"arg\") {\n const payload =\n mode === \"protocol\"\n ? buildProtocolMessages(input, this.config.name).join(\"\\n\") + \"\\n\"\n : composeTaskText(input) + \"\\n\";\n child.stdin?.write(payload);\n child.stdin?.end();\n }\n\n child.on(\"error\", (error) => {\n settle(() => {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n reject(\n new AgentError(\n \"AGENT_NOT_FOUND\",\n `Agent \"${this.config.name}\": command \"${command}\" was not found. Is it installed and on PATH?`,\n { cause: error },\n ),\n );\n return;\n }\n reject(\n new AgentError(\"AGENT_FAILED\", `Agent \"${this.config.name}\" failed to start: ${error.message}.`, {\n cause: error,\n }),\n );\n });\n });\n\n child.on(\"close\", (code, signal) => {\n settle(() => {\n if (timedOut) {\n reject(\n new AgentError(\n \"AGENT_TIMEOUT\",\n `Agent \"${this.config.name}\" timed out after ${timeoutMs}ms and was killed.`,\n {\n details: {\n operation: \"agent.run\",\n agent: this.config.name,\n durationMs: timeoutMs,\n // The process was started and may have performed side\n // effects before being killed — the outcome is unknown,\n // not failed (roadmap §6.3).\n dispatched: true,\n stdout: stdout.slice(0, 4000),\n stderr: stderr.slice(0, 2000),\n },\n },\n ),\n );\n return;\n }\n\n const logs = stderr.trim().length > 0 ? stderr.split(\"\\n\") : undefined;\n if (mode === \"protocol\") {\n // interpretProtocolRun can reject (e.g. protocol violations); throwing\n // inside this event callback would escape the promise entirely.\n try {\n resolve(\n interpretProtocolRun({\n input,\n agentName: this.config.name,\n stdout,\n exitCode: code,\n logs,\n }),\n );\n } catch (error) {\n reject(error);\n }\n return;\n }\n\n const trimmed = stdout.trim();\n resolve({\n taskId: input.taskId,\n status: code === 0 && !outputLimitExceeded ? \"completed\" : \"failed\",\n summary: trimmed.length > 0 ? firstLine(trimmed) : undefined,\n rawOutput: trimmed.length > 0 ? trimmed : undefined,\n exitCode: code ?? undefined,\n logs,\n ...(outputLimitExceeded\n ? { error: `Agent exceeded the ${maxOutputBytes} byte output limit and was terminated.` }\n : code === 0\n ? {}\n : { error: describeExit(code, signal) }),\n });\n });\n });\n });\n }\n\n /** Ask the agent to stop current work (SIGTERM). */\n async cancel(taskId: string): Promise<void> {\n const child = this.running.get(taskId);\n if (child) killTree(child, \"SIGTERM\");\n }\n\n runningTaskIds(): string[] {\n return [...this.running.keys()];\n }\n}\n\ninterface ProtocolRunInput {\n input: AgentTaskInput;\n agentName: string;\n stdout: string;\n exitCode: number | null;\n logs?: string[];\n responder?: QuestionResponder;\n}\n\nfunction interpretProtocolRun({\n input,\n agentName,\n stdout,\n exitCode,\n logs,\n responder,\n}: ProtocolRunInput): AgentTaskOutput {\n const session = new ProtocolSession(\n {\n requestId: `req-${input.taskId}`,\n taskId: input.taskId,\n agentId: agentName,\n ...(input.pipelineId !== undefined ? { pipelineId: input.pipelineId } : {}),\n ...(input.executionId !== undefined ? { executionId: input.executionId } : {}),\n },\n { ...(responder !== undefined ? { responder } : {}) },\n );\n\n // The stream was drained line-by-line already; re-decode deterministically.\n for (const result of session.decoder.push(stdout)) {\n // handled synchronously below via handle(); questions are resolved eagerly\n session.handle(result);\n }\n for (const result of session.decoder.flush()) {\n session.handle(result);\n }\n\n const reports = session.reports\n .flatMap((payload) => (Array.isArray(payload) ? payload : [payload]))\n .map((payload, index) => normalizeReport(payload, input.taskId, agentName, index))\n .filter((report): report is NonNullable<typeof report> => report !== undefined);\n\n const trimmed = stdout.trim();\n const protocolBlock = {\n protocol: session.descriptor?.protocol ?? PROTOCOL_V2,\n legacy: !session.sawV2 && session.descriptor === undefined,\n ...(session.descriptor !== undefined ? { descriptor: session.descriptor } : {}),\n questions: session.questions,\n violations: session.violations.map((v) => `${v.code}: ${v.message}`),\n };\n\n if (session.errorMessage !== undefined) {\n return {\n taskId: input.taskId,\n status: \"failed\",\n error: session.errorMessage,\n rawOutput: trimmed.length > 0 ? trimmed : undefined,\n exitCode: exitCode ?? undefined,\n logs,\n protocol: protocolBlock,\n ...(reports.length > 0 ? { reports } : {}),\n };\n }\n\n if (session.descriptor === undefined && session.violations.length > 0 && session.reports.length === 0 && session.completionSummary === undefined) {\n // Nothing usable parsed: protocol violation rather than silent success.\n return {\n taskId: input.taskId,\n status: \"failed\",\n error: `agent produced no valid protocol messages: ${protocolBlock.violations.join(\"; \")}`,\n rawOutput: trimmed.length > 0 ? trimmed : undefined,\n exitCode: exitCode ?? undefined,\n logs,\n protocol: protocolBlock,\n };\n }\n\n const completed = exitCode === 0 && session.completionSummary !== undefined;\n return {\n taskId: input.taskId,\n status: completed || exitCode === 0 ? (completed ? \"completed\" : \"completed\") : \"failed\",\n summary: session.completionSummary ?? reports[0]?.summary,\n rawOutput: trimmed.length > 0 ? trimmed : undefined,\n exitCode: exitCode ?? undefined,\n logs,\n protocol: protocolBlock,\n ...(reports.length > 0 ? { reports } : {}),\n ...(exitCode !== 0 ? { error: `Process exited with code ${exitCode ?? \"unknown\"}` } : {}),\n };\n}\n\n/**\n * Every live agent process, so Ctrl-C / SIGTERM on OmniNode reaches the whole\n * tree instead of orphaning children (roadmap §8, signal handling).\n */\nconst GLOBAL_RUNNING = new Set<ChildProcess>();\nlet signalForwardingInstalled = false;\n\nfunction installSignalForwarding(): void {\n if (signalForwardingInstalled) return;\n signalForwardingInstalled = true;\n for (const signal of [\"SIGINT\", \"SIGTERM\"] as const) {\n process.on(signal, () => {\n for (const child of GLOBAL_RUNNING) {\n killTree(child, \"SIGTERM\");\n }\n });\n }\n}\n\n/** Kills a child and, on POSIX, its whole process group (roadmap §8 tree cleanup). */\nexport function killTree(child: ChildProcess, signal: NodeJS.Signals): void {\n if (child.pid === undefined) return;\n if (process.platform !== \"win32\") {\n try {\n process.kill(-child.pid, signal);\n return;\n } catch {\n // Group already gone — fall through to direct kill.\n }\n }\n try {\n child.kill(signal);\n } catch {\n // Process already exited.\n }\n}\n\n/** Human-readable exit reason, including signal terminations. */\nexport function describeExit(code: number | null, signal: NodeJS.Signals | null): string {\n if (signal !== null) {\n return signal === \"SIGKILL\"\n ? \"Process was killed (SIGKILL) — usually an external kill or OOM.\"\n : `Process terminated by signal ${signal}.`;\n }\n if (code === null) return \"Process terminated without an exit code.\";\n return `Process exited with code ${code}.`;\n}\n\n/**\n * Decodes a stdout/stderr chunk safely: invalid UTF-8 becomes replacement\n * characters and NUL bytes are stripped, so binary noise cannot poison the\n * protocol decoder or the terminal (roadmap §8, encoding hardening).\n */\nexport function sanitizeChunk(chunk: Buffer): string {\n return [...chunk.toString(\"utf8\")].filter((char) => char.charCodeAt(0) !== 0).join(\"\");\n}\n\n/** Normalizes a loose REPORT payload into a strict Report; drops malformed entries. */\nfunction normalizeReport(\n payload: unknown,\n taskId: string,\n agentName: string,\n index: number,\n): Report | undefined {\n if (payload === null || typeof payload !== \"object\") return undefined;\n const raw = payload as Record<string, unknown>;\n if (typeof raw.summary !== \"string\") return undefined;\n return {\n id: typeof raw.id === \"string\" ? raw.id : `${taskId}-report-${index}`,\n taskId: typeof raw.taskId === \"string\" ? raw.taskId : taskId,\n agent: typeof raw.agent === \"string\" ? raw.agent : agentName,\n summary: raw.summary,\n findings: Array.isArray(raw.findings) ? (raw.findings as Report[\"findings\"]) : [],\n recommendations: Array.isArray(raw.recommendations) ? (raw.recommendations as string[]) : [],\n createdAt: typeof raw.createdAt === \"string\" ? raw.createdAt : new Date().toISOString(),\n };\n}\n\nfunction firstLine(text: string, maxLength = 200): string {\n const line = text.split(\"\\n\", 1)[0] ?? text;\n return line.length > maxLength ? `${line.slice(0, maxLength)}…` : line;\n}\n","/**\n * OmniNode Agent Protocol v2 — versioning (roadmap §7.1).\n *\n * Protocol identifiers are namespaced strings so an agent can negotiate the\n * dialect it speaks: `omninode-agent-protocol/2`.\n */\nexport const PROTOCOL_V2 = \"omninode-agent-protocol/2\";\n\n/** Versions this build accepts. v1 is the unversioned dialect shipped with OmniNode 1.x. */\nexport const SUPPORTED_PROTOCOL_VERSIONS: readonly string[] = [\n \"omninode-agent-protocol/1\",\n PROTOCOL_V2,\n];\n\nexport const MAX_MESSAGE_BYTES = 1_048_576; // 1 MiB per message line\n\nexport function isSupportedProtocol(protocol: string): boolean {\n return SUPPORTED_PROTOCOL_VERSIONS.includes(protocol);\n}","/**\n * OmniNode Agent Protocol v2 — message model (roadmap §7.2–§7.4, §7.7).\n *\n * Every message is a JSON line carrying a `ProtocolEnvelope`. All ids are\n * optional for inbound tolerance but OmniNode always emits them, so every\n * message is traceable to agent / task / pipeline / execution / request.\n */\nimport type { Report } from \"../types/report.js\";\nimport { PROTOCOL_V2 } from \"./version.js\";\n\n/** Messages OmniNode sends to an agent. */\nexport type ProtocolNodeToAgentType =\n | \"TASK\"\n | \"HELLO_ACK\"\n | \"CONTEXT\"\n | \"INSTRUCTION\"\n | \"RESPONSE\"\n | \"CANCEL\";\n\n/** Messages an agent sends to OmniNode. */\nexport type ProtocolAgentToNodeType =\n | \"HELLO\"\n | \"TASK_REQUEST\"\n | \"TASK_ACCEPTED\"\n | \"TASK_STARTED\"\n | \"STATUS\"\n | \"QUESTION\"\n | \"REPORT\"\n | \"ARTIFACT\"\n | \"COMPLETION\"\n | \"ERROR\"\n | \"CANCELLED\";\n\nexport type ProtocolMessageType = ProtocolNodeToAgentType | ProtocolAgentToNodeType;\n\nexport interface ProtocolEnvelope<T extends ProtocolMessageType = ProtocolMessageType> {\n /** `omninode-agent-protocol/2`. Inbound messages without it are treated as v1. */\n protocol: string;\n /** Unique id of this message. */\n messageId: string;\n /** Id of the request/thread this message belongs to. */\n requestId?: string;\n taskId?: string;\n agentId?: string;\n pipelineId?: string;\n /** Execution identity (roadmap §6.5) — ties the message to one attempt. */\n executionId?: string;\n timestamp: string;\n type: T;\n payload: unknown;\n metadata?: Record<string, unknown>;\n}\n\n/** Standard artifact kinds (roadmap §7.7). */\nexport type ArtifactKind =\n | \"file\"\n | \"patch\"\n | \"report\"\n | \"log\"\n | \"screenshot\"\n | \"document\"\n | \"data\";\n\nexport interface ArtifactPayload {\n kind: ArtifactKind;\n /** Path, URL or logical name. */\n ref: string;\n description?: string;\n mediaType?: string;\n bytes?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface QuestionPayload {\n /** Question id to answer. */\n questionId: string;\n question: string;\n /** What kind of answer is expected (free text, file path, options…). */\n expected?: \"text\" | \"path\" | \"choice\";\n options?: string[];\n}\n\nexport interface TaskPayload {\n taskId: string;\n objective: string;\n}\n\nexport interface ReportPayload {\n report: Report | Report[];\n}\n\n/** A question an agent asked during a run, with the answer OmniNode gave (if any). */\nexport interface AskedQuestion {\n questionId: string;\n question: string;\n answer?: string;\n}\n\nexport function newMessageId(prefix = \"msg\"): string {\n const random = Math.random().toString(36).slice(2, 10);\n return `${prefix}-${Date.now().toString(36)}-${random}`;\n}\n\n/** Builds a v2 envelope with ids and timestamp filled in. */\nexport function envelope<T extends ProtocolMessageType>(\n type: T,\n payload: unknown,\n ids: {\n requestId?: string;\n taskId?: string;\n agentId?: string;\n pipelineId?: string;\n executionId?: string;\n metadata?: Record<string, unknown>;\n } = {},\n): ProtocolEnvelope<T> {\n return {\n protocol: PROTOCOL_V2,\n messageId: newMessageId(),\n ...(ids.requestId !== undefined ? { requestId: ids.requestId } : {}),\n ...(ids.taskId !== undefined ? { taskId: ids.taskId } : {}),\n ...(ids.agentId !== undefined ? { agentId: ids.agentId } : {}),\n ...(ids.pipelineId !== undefined ? { pipelineId: ids.pipelineId } : {}),\n ...(ids.executionId !== undefined ? { executionId: ids.executionId } : {}),\n timestamp: new Date().toISOString(),\n type,\n payload,\n ...(ids.metadata !== undefined ? { metadata: ids.metadata } : {}),\n };\n}","/**\n * OmniNode Agent Protocol v2 — codec and validation (roadmap §7.5).\n *\n * Decoding NEVER throws: every failure is returned as a typed\n * `ProtocolViolation` with a machine-readable code, so a misbehaving agent\n * can never crash OmniNode.\n */\nimport {\n MAX_MESSAGE_BYTES,\n PROTOCOL_V2,\n isSupportedProtocol,\n} from \"./version.js\";\nimport type { ProtocolEnvelope, ProtocolMessageType } from \"./types.js\";\n\nexport type ProtocolViolationCode =\n | \"INVALID_JSON\"\n | \"NOT_AN_OBJECT\"\n | \"UNKNOWN_TYPE\"\n | \"MISSING_FIELD\"\n | \"UNSUPPORTED_VERSION\"\n | \"OVERSIZED\"\n | \"INVALID_PAYLOAD\";\n\nexport interface ProtocolViolation {\n code: ProtocolViolationCode;\n message: string;\n /** Raw line (truncated) for diagnostics. */\n sample?: string;\n}\n\nexport type DecodeResult =\n | { ok: true; envelope: ProtocolEnvelope; legacy: boolean }\n | { ok: false; error: ProtocolViolation };\n\nconst KNOWN_TYPES = new Set<string>([\n // node → agent\n \"TASK\", \"HELLO_ACK\", \"CONTEXT\", \"INSTRUCTION\", \"RESPONSE\", \"CANCEL\",\n // agent → node\n \"HELLO\", \"TASK_REQUEST\", \"TASK_ACCEPTED\", \"TASK_STARTED\", \"STATUS\",\n \"QUESTION\", \"REPORT\", \"ARTIFACT\", \"COMPLETION\", \"ERROR\", \"CANCELLED\",\n]);\n\nconst PAYLOAD_REQUIRED_TYPES = new Set<string>([\"TASK\", \"REPORT\", \"COMPLETION\", \"ERROR\", \"QUESTION\", \"ARTIFACT\", \"HELLO\"]);\n\n/** Validates one decoded JSON value as a protocol envelope. */\nexport function validateEnvelope(value: unknown, line?: string): DecodeResult {\n const sample = line?.slice(0, 200);\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return { ok: false, error: { code: \"NOT_AN_OBJECT\", message: \"message must be a JSON object\", ...(sample ? { sample } : {}) } };\n }\n const raw = value as Record<string, unknown>;\n\n // Version negotiation: absent protocol = v1 (OmniNode 1.x agents), else must be supported.\n const protocol = raw.protocol;\n if (protocol === undefined) {\n // legacy v1: requires a bare {type, payload} shape\n const type = raw.type;\n if (typeof type !== \"string\" || !KNOWN_TYPES.has(type)) {\n return { ok: false, error: { code: \"UNKNOWN_TYPE\", message: `unknown message type ${String(type)}`, ...(sample ? { sample } : {}) } };\n }\n return {\n ok: true,\n legacy: true,\n envelope: {\n protocol: \"omninode-agent-protocol/1\",\n messageId: typeof raw.messageId === \"string\" ? raw.messageId : \"legacy\",\n timestamp: new Date().toISOString(),\n type: type as ProtocolMessageType,\n payload: raw.payload,\n },\n };\n }\n if (typeof protocol !== \"string\" || !isSupportedProtocol(protocol)) {\n return {\n ok: false,\n error: { code: \"UNSUPPORTED_VERSION\", message: `unsupported protocol \"${String(protocol)}\"`, ...(sample ? { sample } : {}) },\n };\n }\n\n if (raw.type === undefined) {\n return { ok: false, error: { code: \"MISSING_FIELD\", message: \"message is missing 'type'\", ...(sample ? { sample } : {}) } };\n }\n if (typeof raw.type !== \"string\" || !KNOWN_TYPES.has(raw.type)) {\n return { ok: false, error: { code: \"UNKNOWN_TYPE\", message: `unknown message type ${String(raw.type)}`, ...(sample ? { sample } : {}) } };\n }\n if (raw.timestamp !== undefined && typeof raw.timestamp !== \"string\") {\n return { ok: false, error: { code: \"MISSING_FIELD\", message: \"'timestamp' must be a string\", ...(sample ? { sample } : {}) } };\n }\n if (PAYLOAD_REQUIRED_TYPES.has(raw.type) && (raw.payload === undefined || raw.payload === null)) {\n return { ok: false, error: { code: \"INVALID_PAYLOAD\", message: `${raw.type} requires a payload`, ...(sample ? { sample } : {}) } };\n }\n\n return {\n ok: true,\n legacy: protocol !== PROTOCOL_V2,\n envelope: {\n protocol,\n messageId: typeof raw.messageId === \"string\" ? raw.messageId : \"unknown\",\n ...(typeof raw.requestId === \"string\" ? { requestId: raw.requestId } : {}),\n ...(typeof raw.taskId === \"string\" ? { taskId: raw.taskId } : {}),\n ...(typeof raw.agentId === \"string\" ? { agentId: raw.agentId } : {}),\n ...(typeof raw.pipelineId === \"string\" ? { pipelineId: raw.pipelineId } : {}),\n ...(typeof raw.executionId === \"string\" ? { executionId: raw.executionId } : {}),\n timestamp: typeof raw.timestamp === \"string\" ? raw.timestamp : new Date().toISOString(),\n type: raw.type as ProtocolMessageType,\n payload: raw.payload,\n ...(raw.metadata !== null && typeof raw.metadata === \"object\" ? { metadata: raw.metadata as Record<string, unknown> } : {}),\n },\n };\n}\n\n/** Decodes one protocol line (no trailing newline). */\nexport function decodeMessage(line: string, maxBytes = MAX_MESSAGE_BYTES): DecodeResult {\n const trimmed = line.trim();\n if (trimmed.length === 0) {\n return { ok: false, error: { code: \"INVALID_JSON\", message: \"empty line\" } };\n }\n if (trimmed.length > maxBytes) {\n return {\n ok: false,\n error: { code: \"OVERSIZED\", message: `message of ${trimmed.length} bytes exceeds the ${maxBytes} byte limit`, sample: trimmed.slice(0, 200) },\n };\n }\n let value: unknown;\n try {\n value = JSON.parse(trimmed);\n } catch (error) {\n return {\n ok: false,\n error: { code: \"INVALID_JSON\", message: error instanceof Error ? error.message : \"invalid JSON\", sample: trimmed.slice(0, 200) },\n };\n }\n return validateEnvelope(value, trimmed);\n}\n\n/** Serializes an envelope to a single JSON line. */\nexport function encodeMessage(envelope: ProtocolEnvelope, maxBytes = MAX_MESSAGE_BYTES): string {\n const line = JSON.stringify(envelope);\n if (line.length > maxBytes) {\n throw new Error(`outbound protocol message of ${line.length} bytes exceeds the ${maxBytes} byte limit`);\n }\n return line;\n}\n\n/**\n * Streaming line decoder for agent stdout. Feed chunks; receive decoded\n * envelopes and violations in order. Survives garbage: a bad line yields a\n * violation and the stream continues.\n */\nexport class ProtocolDecoder {\n private buffer = \"\";\n private readonly maxBytes: number;\n\n constructor(maxBytes = MAX_MESSAGE_BYTES) {\n this.maxBytes = maxBytes;\n }\n\n push(chunk: string): DecodeResult[] {\n this.buffer += chunk;\n const results: DecodeResult[] = [];\n let index = this.buffer.indexOf(\"\\n\");\n while (index >= 0) {\n const line = this.buffer.slice(0, index);\n this.buffer = this.buffer.slice(index + 1);\n if (line.trim().length > 0) results.push(decodeMessage(line, this.maxBytes));\n index = this.buffer.indexOf(\"\\n\");\n }\n // Guard against an agent emitting an endless line with no newline.\n if (this.buffer.length > this.maxBytes) {\n results.push({\n ok: false,\n error: { code: \"OVERSIZED\", message: `line exceeded ${this.maxBytes} bytes without a newline`, sample: this.buffer.slice(0, 200) },\n });\n this.buffer = \"\";\n }\n return results;\n }\n\n /** Flush any trailing line when the process exits. */\n flush(): DecodeResult[] {\n if (this.buffer.trim().length === 0) {\n this.buffer = \"\";\n return [];\n }\n const result = decodeMessage(this.buffer, this.maxBytes);\n this.buffer = \"\";\n return [result];\n }\n}","/**\n * OmniNode Agent Protocol v2 — handshake (roadmap §7.1).\n *\n * An agent announces itself with HELLO; OmniNode replies with HELLO_ACK.\n * Handshakes are optional for v1-style agents (no HELLO = legacy dialect).\n */\nimport { PROTOCOL_V2 } from \"./version.js\";\nimport { envelope, type ProtocolEnvelope } from \"./types.js\";\n\nexport interface AgentDescriptor {\n /** Protocol the agent speaks. */\n protocol: string;\n name: string;\n version?: string;\n capabilities: string[];\n /** Message types the agent can emit. */\n supports: string[];\n}\n\nexport type HelloResult =\n | { ok: true; descriptor: AgentDescriptor }\n | { ok: false; reason: string };\n\nexport function parseHello(envelopeValue: ProtocolEnvelope): HelloResult {\n if (envelopeValue.type !== \"HELLO\") {\n return { ok: false, reason: `expected HELLO, received ${envelopeValue.type}` };\n }\n const payload = envelopeValue.payload;\n if (payload === null || typeof payload !== \"object\") {\n return { ok: false, reason: \"HELLO payload must be an object\" };\n }\n const p = payload as Record<string, unknown>;\n if (typeof p.name !== \"string\" || p.name.length === 0) {\n return { ok: false, reason: \"HELLO payload is missing 'name'\" };\n }\n return {\n ok: true,\n descriptor: {\n protocol: envelopeValue.protocol,\n name: p.name,\n ...(typeof p.version === \"string\" ? { version: p.version } : {}),\n capabilities: Array.isArray(p.capabilities) ? p.capabilities.filter((c): c is string => typeof c === \"string\") : [],\n supports: Array.isArray(p.supports) ? p.supports.filter((s): s is string => typeof s === \"string\") : [],\n },\n };\n}\n\nexport function buildHello(descriptor: Omit<AgentDescriptor, \"protocol\">): ProtocolEnvelope<\"HELLO\"> {\n return envelope(\"HELLO\", descriptor, { agentId: descriptor.name });\n}\n\nexport function buildHelloAck(descriptor: AgentDescriptor): ProtocolEnvelope<\"HELLO_ACK\"> {\n return envelope(\"HELLO_ACK\", {\n ok: true,\n protocol: PROTOCOL_V2,\n agent: descriptor.name,\n ...(descriptor.version !== undefined ? { agentVersion: descriptor.version } : {}),\n supportedProtocols: [PROTOCOL_V2],\n }, { agentId: descriptor.name });\n}\n","/**\n * OmniNode Agent Protocol v2 — session (roadmap §7.6).\n *\n * A session drives a protocol-mode agent: it emits v2 envelopes with\n * correlation ids, tolerates legacy (unversioned) replies, answers agent\n * questions through a responder callback, and collects reports, artifacts\n * and the completion — never throwing on malformed input.\n */\nimport { decodeMessage, encodeMessage, ProtocolDecoder, type DecodeResult, type ProtocolViolation } from \"./codec.js\";\nimport { PROTOCOL_V2 } from \"./version.js\";\nimport { envelope, type AskedQuestion, type ProtocolEnvelope } from \"./types.js\";\nimport { parseHello, buildHelloAck, type AgentDescriptor } from \"./handshake.js\";\nimport { ProtocolError } from \"../errors/index.js\";\n\nexport interface SessionIds {\n requestId: string;\n taskId: string;\n agentId: string;\n pipelineId?: string;\n executionId?: string;\n}\n\nexport interface QuestionResponder {\n (question: { questionId: string; question: string; expected?: string }): Promise<string> | string;\n}\n\nexport class ProtocolSession {\n readonly decoder: ProtocolDecoder;\n private readonly ids: SessionIds;\n private readonly responder: QuestionResponder | undefined;\n readonly violations: ProtocolViolation[] = [];\n readonly questions: AskedQuestion[] = [];\n readonly artifacts: ProtocolEnvelope[\"payload\"][] = [];\n reports: ProtocolEnvelope[\"payload\"][] = [];\n descriptor?: AgentDescriptor;\n completionSummary?: string;\n errorMessage?: string;\n\n constructor(ids: SessionIds, options: { responder?: QuestionResponder; maxBytes?: number } = {}) {\n this.ids = ids;\n this.responder = options.responder;\n this.decoder = new ProtocolDecoder(options.maxBytes);\n }\n\n /** The v2 messages OmniNode sends to open a task (written to the agent's stdin). */\n taskMessages(objective: string, role?: unknown, context?: string, instruction?: string): string[] {\n const ids = this.ids;\n const messages: ProtocolEnvelope[] = [envelope(\"TASK\", { taskId: ids.taskId, objective }, ids)];\n if (role !== undefined) messages.push(envelope(\"CONTEXT\", { role }, ids));\n if (context !== undefined && context.length > 0) messages.push(envelope(\"CONTEXT\", { body: context }, ids));\n if (instruction !== undefined && instruction.length > 0) messages.push(envelope(\"INSTRUCTION\", { text: instruction }, ids));\n return messages.map((m) => encodeMessage(m));\n }\n\n helloAck(descriptor: AgentDescriptor): string {\n return encodeMessage(buildHelloAck(descriptor));\n }\n\n /** Consumes decoded stdout, answering questions as they arrive. */\n async handle(decoded: DecodeResult): Promise<void> {\n if (!decoded.ok) {\n // Agent misbehavior is recorded, never fatal (§7.5).\n this.violations.push(decoded.error);\n return;\n }\n const message = decoded.envelope;\n if (message.protocol === PROTOCOL_V2) this.sawV2 = true;\n if (message.type === \"HELLO\") {\n const hello = parseHello(message);\n if (hello.ok) this.descriptor = hello.descriptor;\n else this.violations.push({ code: \"INVALID_PAYLOAD\", message: `bad HELLO: ${hello.reason}` });\n return;\n }\n if (message.type === \"QUESTION\") {\n await this.answerQuestion(message);\n return;\n }\n if (message.type === \"REPORT\") {\n this.reports.push(message.payload);\n return;\n }\n if (message.type === \"ARTIFACT\") {\n this.artifacts.push(message.payload);\n return;\n }\n if (message.type === \"COMPLETION\") {\n const payload = message.payload as { summary?: unknown } | undefined;\n this.completionSummary = typeof payload?.summary === \"string\" ? payload.summary : \"\";\n return;\n }\n if (message.type === \"ERROR\") {\n const payload = message.payload as { message?: unknown; code?: unknown } | undefined;\n const detail = typeof payload?.message === \"string\" ? payload.message : \"agent reported an error\";\n const code = typeof payload?.code === \"string\" ? ` [${payload.code}]` : \"\";\n this.errorMessage = `Agent error${code}: ${detail}`;\n return;\n }\n if (message.type === \"TASK_ACCEPTED\" || message.type === \"TASK_STARTED\" || message.type === \"STATUS\") {\n // Lifecycle acknowledgements: observed, no action needed by the core.\n return;\n }\n this.violations.push({\n code: \"UNKNOWN_TYPE\",\n message: `unexpected message type ${message.type} from agent`,\n });\n }\n\n private async answerQuestion(message: ProtocolEnvelope): Promise<void> {\n const payload = (message.payload ?? {}) as { questionId?: unknown; question?: unknown; expected?: unknown };\n const questionId = typeof payload.questionId === \"string\" ? payload.questionId : message.messageId;\n const question = typeof payload.question === \"string\" ? payload.question : \"\";\n const expected = typeof payload.expected === \"string\" ? payload.expected : \"text\";\n\n let answer: string | undefined;\n if (this.responder) {\n try {\n answer = await this.responder({ questionId, question, expected });\n } catch (error) {\n this.violations.push({\n code: \"INVALID_PAYLOAD\",\n message: `question responder failed: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n }\n this.questions.push({ questionId, question, ...(answer !== undefined ? { answer } : {}) });\n // Answer on stdout via the write callback supplied by the caller.\n this.pendingAnswers.push(\n encodeMessage(\n envelope(\"RESPONSE\", { questionId, ...(answer !== undefined ? { body: answer } : {}) }, {\n ...this.ids,\n requestId: message.requestId ?? this.ids.requestId,\n }),\n ),\n );\n }\n\n readonly pendingAnswers: string[] = [];\n /** True once any inbound message carried the v2 protocol field. */\n sawV2 = false;\n}\n\nexport async function decodeStream(session: ProtocolSession, chunk: string): Promise<string[]> {\n const decoded = session.decoder.push(chunk);\n for (const result of decoded) {\n await session.handle(result);\n }\n return session.pendingAnswers.splice(0);\n}\n\nexport function requireCompletion(session: ProtocolSession): void {\n if (session.errorMessage !== undefined) {\n throw new ProtocolError(session.errorMessage);\n }\n}\n\nexport { decodeMessage };","/**\n * Working-directory validation for agent processes (roadmap §8): existence,\n * directory-ness, access, path normalization and project boundaries.\n */\nimport { statSync } from \"node:fs\";\nimport { isAbsolute, relative, resolve } from \"node:path\";\nimport { AgentError } from \"../errors/index.js\";\n\nexport interface CwdValidation {\n /** Normalized absolute path. */\n cwd: string;\n /** True when the directory sits outside the project root (project boundary). */\n outsideProject: boolean;\n}\n\nexport function validateWorkingDirectory(\n cwd: string | undefined,\n options: { projectRoot?: string; allowExternal?: boolean } = {},\n): CwdValidation | undefined {\n if (!cwd) return undefined;\n\n const normalized = isAbsolute(cwd) ? resolve(cwd) : resolve(process.cwd(), cwd);\n let stats;\n try {\n stats = statSync(normalized);\n } catch (error) {\n throw new AgentError(\n \"AGENT_NOT_FOUND\",\n `Working directory \"${normalized}\" does not exist or is not accessible.`,\n { cause: error, details: { cwd: normalized } },\n );\n }\n if (!stats.isDirectory()) {\n throw new AgentError(\"AGENT_NOT_FOUND\", `Working directory \"${normalized}\" is not a directory.`, {\n details: { cwd: normalized },\n });\n }\n // Access check: attempt to list it.\n try {\n statSync(resolve(normalized, \".\"));\n } catch (error) {\n throw new AgentError(\n \"AGENT_NOT_FOUND\",\n `Working directory \"${normalized}\" is not accessible.`,\n { cause: error },\n );\n }\n\n const projectRoot = resolve(options.projectRoot ?? process.cwd());\n const rel = relative(projectRoot, normalized);\n const outsideProject = rel.startsWith(\"..\") || isAbsolute(rel);\n if (outsideProject && options.allowExternal !== true) {\n throw new AgentError(\n \"AGENT_NOT_FOUND\",\n `Working directory \"${normalized}\" is outside the project root \"${projectRoot}\". ` +\n `Set allow_external_cwd: true on the agent to permit this.`,\n { details: { cwd: normalized, projectRoot } },\n );\n }\n return { cwd: normalized, outsideProject };\n}","/**\n * Agent environment policies (roadmap §8, Environment Isolation).\n *\n * Four explicit policies, so operators decide exactly what an agent can see:\n * - `inherit` (default, backwards compatible): the full parent environment\n * - `allowlist`: only the allow-listed variables (+ PATH/HOME)\n * - `denylist`: the parent environment minus the deny-listed variables\n * - `explicit`: nothing from the parent; only PATH/HOME and `env`\n *\n * The v1 boolean `inherit_env: false` is still honored and maps to `explicit`.\n */\nimport type { AgentConfig } from \"../types/agent.js\";\n\nexport type EnvPolicy = \"inherit\" | \"allowlist\" | \"denylist\" | \"explicit\";\n\n/** Variables always provided so shells and runtimes keep working. */\nconst BASELINE_KEYS = [\"PATH\", \"HOME\"] as const;\n\nexport function resolveEnvPolicy(config: Partial<AgentConfig>): EnvPolicy {\n if (config.envPolicy !== undefined) return config.envPolicy;\n if (config.inheritEnv === false) return \"explicit\"; // v1 compatibility\n return \"inherit\";\n}\n\nexport function buildChildEnv(config: AgentConfig): NodeJS.ProcessEnv {\n const configured = config.env ?? {};\n const policy = resolveEnvPolicy(config);\n\n if (policy === \"inherit\") {\n return { ...process.env, ...configured };\n }\n\n const base: NodeJS.ProcessEnv = {};\n for (const key of BASELINE_KEYS) {\n const value = process.env[key];\n if (value !== undefined) base[key] = value;\n }\n\n switch (policy) {\n case \"explicit\":\n return { ...base, ...configured };\n case \"allowlist\": {\n const allowed: NodeJS.ProcessEnv = { ...base };\n for (const key of config.envAllowlist ?? []) {\n const value = process.env[key];\n if (value !== undefined) allowed[key] = value;\n }\n return { ...allowed, ...configured };\n }\n case \"denylist\": {\n const denied = new Set((config.envDenylist ?? []).map((k) => k.toUpperCase()));\n const filtered: NodeJS.ProcessEnv = {};\n for (const [key, value] of Object.entries(process.env)) {\n if (denied.has(key.toUpperCase())) continue;\n filtered[key] = value;\n }\n return { ...filtered, ...configured };\n }\n }\n}","/**\n * Agent adapter registry (roadmap §8, Native Adapters).\n *\n * New integration styles (native/API-level agents) plug in here without\n * changing OmniNode core: register an `IAgentAdapter` and `createAgent`\n * consults the registry before falling back to the process adapter.\n */\nimport { AgentError } from \"../errors/index.js\";\nimport type { AgentConfig, IAgent } from \"../types/agent.js\";\n\nexport interface IAgentAdapter {\n /** Integration type this adapter serves, e.g. \"native\" or \"process\". */\n readonly integration: string;\n create(config: AgentConfig): IAgent;\n}\n\nexport class AgentAdapterRegistry {\n private readonly adapters = new Map<string, IAgentAdapter>();\n\n register(adapter: IAgentAdapter): void {\n this.adapters.set(adapter.integration, adapter);\n }\n\n get(integration: string): IAgentAdapter | undefined {\n return this.adapters.get(integration);\n }\n\n list(): IAgentAdapter[] {\n return [...this.adapters.values()];\n }\n\n create(config: AgentConfig): IAgent {\n const adapter = this.get(config.integration);\n if (!adapter) {\n throw new AgentError(\n \"AGENT_NOT_FOUND\",\n `No agent adapter registered for integration \"${config.integration}\". ` +\n `Registered: ${[...this.adapters.keys()].join(\", \") || \"(none)\"}.`,\n );\n }\n return adapter.create(config);\n }\n}\n\n/** Process-level adapter — the built-in CLI integration. */\nexport class ProcessAgentAdapter implements IAgentAdapter {\n readonly integration = \"process\";\n\n constructor(private readonly factory: (config: AgentConfig) => IAgent) {}\n\n create(config: AgentConfig): IAgent {\n return this.factory(config);\n }\n}","/** Agent registry (§10): the set of agents connected to OmniNode. */\nimport type { IAgent } from \"../types/agent.js\";\n\nexport class AgentRegistry {\n private readonly agents = new Map<string, IAgent>();\n\n register(agent: IAgent): void {\n this.agents.set(agent.info.name, agent);\n }\n\n get(name: string): IAgent | undefined {\n return this.agents.get(name);\n }\n\n list(): IAgent[] {\n return [...this.agents.values()].sort((a, b) => a.info.name.localeCompare(b.info.name));\n }\n}\n","/**\n * Agent factory (§9–§10): builds adapter instances from configuration.\n * \"cli\" agent configs are mapped to the process integration by the loader.\n */\nimport type { AppConfig } from \"../config/index.js\";\nimport { OmniNodeError } from \"../errors/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { AgentConfig, IAgent } from \"../types/agent.js\";\nimport { ProcessAgent } from \"./process/index.js\";\nimport { AgentRegistry } from \"./registry.js\";\nimport { AgentAdapterRegistry, ProcessAgentAdapter } from \"./adapters.js\";\n\n/**\n * Registry consulted first so native/API-level integrations plug in without\n * touching core (roadmap §8, Native Adapters).\n */\nexport const defaultAgentAdapters = new AgentAdapterRegistry();\ndefaultAgentAdapters.register(new ProcessAgentAdapter((config) => new ProcessAgent(config)));\n\nexport function createAgent(config: AgentConfig, adapters: AgentAdapterRegistry = defaultAgentAdapters): IAgent {\n const registered = adapters.get(config.integration);\n if (registered) return registered.create(config);\n if (config.integration === \"native\") {\n throw new OmniNodeError(\n \"NOT_IMPLEMENTED\",\n `No native adapter is registered for \"${config.name}\". Register an IAgentAdapter ` +\n `(createAgent(config, adapters)) or use input over stdin/stdout (type \"cli\").`,\n );\n }\n throw new OmniNodeError(\"NOT_IMPLEMENTED\", `Agent integration \"${config.integration}\" has no adapter yet.`);\n}\n\nexport { AgentAdapterRegistry } from \"./adapters.js\";\nexport type { IAgentAdapter } from \"./adapters.js\";\n\n/** Builds an agent registry from the project configuration, skipping agents that fail to construct. */\nexport function buildAgentRegistry(config: AppConfig, log: Logger = logger): AgentRegistry {\n const registry = new AgentRegistry();\n for (const agentConfig of config.project.agents) {\n try {\n registry.register(createAgent(agentConfig));\n } catch (error) {\n log.warn(\n `Skipping agent \"${agentConfig.name}\": ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n return registry;\n}\n","/** Role registry (§11): the set of roles available for task assignment. */\nimport type { AppConfig } from \"../config/index.js\";\nimport type { RoleDefinition } from \"../types/role.js\";\n\nexport class RoleRegistry {\n private readonly roles = new Map<string, RoleDefinition>();\n\n register(role: RoleDefinition): void {\n this.roles.set(role.id, role);\n }\n\n registerAll(roles: RoleDefinition[]): void {\n for (const role of roles) this.register(role);\n }\n\n get(id: string): RoleDefinition | undefined {\n return this.roles.get(id);\n }\n\n list(): RoleDefinition[] {\n return [...this.roles.values()].sort((a, b) => a.id.localeCompare(b.id));\n }\n}\n\n/** Builds a role registry from the project configuration. */\nexport function buildRoleRegistry(config: AppConfig): RoleRegistry {\n const registry = new RoleRegistry();\n registry.registerAll(config.project.roles);\n return registry;\n}\n","/**\n * Shared JSON file persistence (v2 Phase 12 — Persistence Layer).\n *\n * Guarantees:\n * - **Atomic writes**: temp file → fsync → rename → directory fsync, so a\n * crash never leaves a half-written store.\n * - **Corruption detection**: unparseable files are *quarantined* (renamed,\n * never deleted) and the store continues empty.\n * - **Schema versioning**: documents carry `schemaVersion`; v1 documents are\n * migrated on read, future versions are refused rather than misread.\n */\nimport { open, mkdir, readFile, rename, stat, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { logger, type Logger } from \"../logger/index.js\";\n\n/** Current on-disk schema version. */\nexport const SCHEMA_VERSION = 2;\n\nexport interface JsonDocument<T> {\n schemaVersion?: number;\n items: T[];\n}\n\nexport type DocumentState =\n | { status: \"missing\" }\n | { status: \"empty\" }\n | { status: \"v1-legacy\" }\n | { status: \"current\"; schemaVersion: number; count: number }\n | { status: \"future\"; schemaVersion: number }\n | { status: \"corrupt\"; detail: string };\n\nexport interface JsonFileStoreOptions {\n directory?: string;\n fileName: string;\n /** Schema version to write (defaults to the current version). */\n schemaVersion?: number;\n /** Power-loss durability: \"rename\" (default) or \"fsync\" (slower). */\n durability?: Durability;\n /** Called when a persisted file is corrupt (after quarantine). */\n onCorrupt?: (path: string, error: unknown) => void;\n /** Disable file moves (used by dry runs / tests that inspect in place). */\n quarantine?: boolean;\n}\n\nexport type Durability = \"rename\" | \"fsync\";\n\n/**\n * Writes a file atomically: temp → rename. The rename guarantees readers\n * never observe a torn file. With `durability: \"fsync\"` the data and the\n * directory entry are also flushed, which additionally survives power loss —\n * at a significant per-write cost, so it is opt-in.\n */\nexport async function writeFileAtomic(\n target: string,\n contents: string,\n durability: Durability = \"rename\",\n): Promise<void> {\n const tmp = `${target}.tmp`;\n await mkdir(dirname(target), { recursive: true });\n\n if (durability === \"fsync\") {\n const handle = await open(tmp, \"w\");\n try {\n await handle.writeFile(contents, \"utf8\");\n await handle.sync();\n } finally {\n await handle.close();\n }\n } else {\n await writeFile(tmp, contents, \"utf8\");\n }\n\n await rename(tmp, target);\n\n if (durability === \"fsync\") {\n try {\n const dir = await open(dirname(target), \"r\");\n try {\n await dir.sync();\n } finally {\n await dir.close();\n }\n } catch {\n // Directory fsync is unsupported on some platforms — the rename is still atomic.\n }\n }\n}\n\n/** Reads and classifies a persisted document without modifying it. */\nexport async function inspectDocument(path: string): Promise<DocumentState> {\n let raw: string;\n try {\n await stat(path);\n } catch {\n return { status: \"missing\" };\n }\n try {\n raw = await readFile(path, \"utf8\");\n } catch (error) {\n return { status: \"corrupt\", detail: `unreadable: ${error instanceof Error ? error.message : String(error)}` };\n }\n if (raw.trim().length === 0) return { status: \"empty\" };\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n return { status: \"corrupt\", detail: error instanceof Error ? error.message : \"invalid JSON\" };\n }\n if (Array.isArray(parsed)) return { status: \"v1-legacy\" }; // v1 stored bare arrays\n if (parsed === null || typeof parsed !== \"object\") return { status: \"corrupt\", detail: \"not an object\" };\n const doc = parsed as JsonDocument<unknown>;\n if (!Array.isArray(doc.items)) return { status: \"corrupt\", detail: \"missing items array\" };\n const version = typeof doc.schemaVersion === \"number\" ? doc.schemaVersion : 1;\n if (version > SCHEMA_VERSION) return { status: \"future\", schemaVersion: version };\n if (version < SCHEMA_VERSION) return { status: \"v1-legacy\" };\n return { status: \"current\", schemaVersion: version, count: doc.items.length };\n}\n\n/** Reads a document, migrating v1 shapes and quarantining corruption. */\nexport async function readDocument<T>(\n path: string,\n onCorrupt?: (path: string, error: unknown) => void,\n quarantine = true,\n): Promise<T[]> {\n const state = await inspectDocument(path);\n if (state.status === \"missing\" || state.status === \"empty\") return [];\n if (state.status === \"future\") {\n const error = new Error(\n `${path} was written by a newer OmniNode (schema v${state.schemaVersion} > v${SCHEMA_VERSION})`,\n );\n onCorrupt?.(path, error);\n return [];\n }\n\n let raw: string;\n try {\n raw = await readFile(path, \"utf8\");\n } catch (error) {\n onCorrupt?.(path, error);\n return [];\n }\n try {\n const parsed: unknown = JSON.parse(raw);\n if (Array.isArray(parsed)) return parsed as T[]; // v1 legacy: bare array\n return (parsed as JsonDocument<T>).items ?? [];\n } catch (error) {\n // Preserve the damaged file for inspection instead of overwriting it.\n if (quarantine) {\n const quarantinePath = `${path}.corrupt-${Date.now()}`;\n try {\n await rename(path, quarantinePath);\n logger.child({ component: \"persistence\" }).warn(\n `Quarantined unreadable store file ${path} → ${quarantinePath}`,\n );\n } catch {\n // Quarantine is best effort.\n }\n }\n onCorrupt?.(path, error);\n return [];\n }\n}\n\nexport class JsonFileStore<T> {\n private readonly filePath: string;\n private readonly schemaVersion: number;\n private readonly durability: Durability;\n private readonly onCorrupt?: (path: string, error: unknown) => void;\n private readonly quarantine: boolean;\n private readonly log: Logger;\n private queue: Promise<unknown> = Promise.resolve();\n\n constructor(options: JsonFileStoreOptions) {\n this.filePath = `${options.directory ?? `${process.cwd()}/.omninode`}/${options.fileName}`;\n this.schemaVersion = options.schemaVersion ?? SCHEMA_VERSION;\n this.durability = options.durability ?? \"rename\";\n this.onCorrupt = options.onCorrupt;\n this.quarantine = options.quarantine ?? true;\n this.log = logger.child({ component: \"persistence\", file: options.fileName });\n }\n\n get path(): string {\n return this.filePath;\n }\n\n /** All items, or [] when missing/migrated-from-v1/corrupt. */\n protected async readAll(): Promise<T[]> {\n return readDocument<T>(this.filePath, this.onCorrupt, this.quarantine);\n }\n\n protected async writeAll(items: T[]): Promise<void> {\n const document: JsonDocument<T> = { schemaVersion: this.schemaVersion, items };\n await writeFileAtomic(this.filePath, `${JSON.stringify(document, null, 2)}\\n`, this.durability);\n }\n\n /** Serializes an async operation against this file. */\n protected synchronized<R>(operation: () => Promise<R>): Promise<R> {\n const result = this.queue.then(operation, operation);\n this.queue = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n /** Read-modify-write helper: applies `mutate` to the current items. */\n protected async mutate<R>(mutate: (items: T[]) => Promise<[T[], R]> | [T[], R]): Promise<R> {\n return this.synchronized(async () => {\n const items = await this.readAll();\n const [next, result] = await mutate(items);\n await this.writeAll(next);\n return result;\n });\n }\n}\n","/**\n * Shared memory-contract helpers (roadmap §12). Adapters implement\n * `retrieve` / `store`; these helpers supply the defaults for `search`,\n * `metadata` and the v1 `query` / `write` aliases, so the contract is\n * defined once.\n */\nimport type {\n IMemoryProvider,\n MemoryEntry,\n MemoryProviderMetadata,\n MemoryQuery,\n} from \"../types/memory.js\";\n\n/** Free-text search defaults to a relevance retrieve. */\nexport function defaultSearch(\n provider: Pick<IMemoryProvider, \"retrieve\">,\n text: string,\n options: { limit?: number; scope?: MemoryQuery[\"scope\"] } = {},\n): Promise<MemoryEntry[]> {\n return provider.retrieve({\n text,\n ...(options.scope !== undefined ? { scope: options.scope } : {}),\n ...(options.limit !== undefined ? { limit: options.limit } : {}),\n });\n}\n\nexport function defaultMetadata(\n name: string,\n options: {\n capabilities?: MemoryProviderMetadata[\"capabilities\"];\n relevanceRanking?: boolean;\n backend?: Record<string, unknown>;\n } = {},\n): MemoryProviderMetadata {\n return {\n name,\n capabilities: options.capabilities ?? [\"retrieve\", \"store\", \"search\"],\n relevanceRanking: options.relevanceRanking ?? false,\n ...(options.backend !== undefined ? { backend: options.backend } : {}),\n };\n}","/**\n * Local file-based memory provider: the default implementation so persistent\n * memory works out of the box, locally (§25), with no external service.\n * Relevance is scored by keyword overlap and tag matches — deterministic and\n * dependency-free.\n */\nimport { JsonFileStore } from \"../persistence/json-file-store.js\";\nimport { defaultMetadata, defaultSearch } from \"./base.js\";\nimport type {\n IMemoryProvider,\n MemoryEntry,\n MemoryProviderMetadata,\n MemoryQuery,\n} from \"../types/memory.js\";\n\nconst STOPWORDS = new Set([\n \"the\", \"and\", \"for\", \"with\", \"this\", \"that\", \"from\", \"into\", \"was\", \"were\",\n \"have\", \"has\", \"had\", \"are\", \"but\", \"not\", \"you\", \"his\", \"her\", \"its\",\n \"their\", \"them\", \"then\", \"than\", \"when\", \"what\", \"which\", \"will\", \"would\",\n \"been\", \"were\", \"also\", \"because\", \"about\", \"after\", \"before\",\n]);\n\nexport function keywords(text: string): Set<string> {\n return new Set(\n (text ?? \"\")\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, \" \")\n .split(/\\s+/)\n .filter((t) => t.length >= 4 && !STOPWORDS.has(t)),\n );\n}\n\nfunction relevanceScore(queryKeywords: Set<string>, entry: MemoryEntry): number {\n if (queryKeywords.size === 0) return 0;\n const entryKeywords = keywords(`${entry.content} ${entry.key}`);\n let overlap = 0;\n for (const keyword of queryKeywords) {\n if (entryKeywords.has(keyword)) overlap += 1;\n }\n let tagMatches = 0;\n for (const tag of entry.tags ?? []) {\n if (queryKeywords.has(tag.toLowerCase())) tagMatches += 1;\n }\n return overlap * 2 + tagMatches * 1.5;\n}\n\nexport class LocalMemoryProvider extends JsonFileStore<MemoryEntry> implements IMemoryProvider {\n readonly name = \"local\";\n\n constructor(directory?: string) {\n super({ ...(directory !== undefined ? { directory } : {}), fileName: \"memory.json\" });\n }\n\n metadata(): MemoryProviderMetadata {\n return defaultMetadata(this.name, {\n capabilities: [\"retrieve\", \"store\", \"search\", \"categories\", \"tags\"],\n relevanceRanking: true,\n backend: { kind: \"json-file\", deterministicScoring: true },\n });\n }\n\n search(text: string, options: { limit?: number; scope?: MemoryQuery[\"scope\"] } = {}): Promise<MemoryEntry[]> {\n return defaultSearch(this, text, options);\n }\n\n /** @deprecated v1 alias of {@link retrieve}. */\n query(query: MemoryQuery): Promise<MemoryEntry[]> {\n return this.retrieve(query);\n }\n\n /** @deprecated v1 alias of {@link store}. */\n write(entry: MemoryEntry): Promise<void> {\n return this.store(entry);\n }\n\n async retrieve(query: MemoryQuery): Promise<MemoryEntry[]> {\n const entries = await this.readAll();\n const filtered = entries\n .filter((entry) => (query.scope ? entry.scope === query.scope : true))\n .filter((entry) => (query.category ? entry.category === query.category : true))\n .filter((entry) =>\n query.tags && query.tags.length > 0\n ? query.tags.every((tag) => (entry.tags ?? []).includes(tag))\n : true,\n );\n\n if (!query.text || query.text.trim().length === 0) {\n return filtered\n .sort((a, b) => (b.updatedAt ?? b.createdAt ?? \"\").localeCompare(a.updatedAt ?? a.createdAt ?? \"\"))\n .slice(0, query.limit ?? 10);\n }\n\n const queryKeywords = keywords(query.text);\n return filtered\n .map((entry) => ({ entry, score: relevanceScore(queryKeywords, entry) }))\n .filter(({ score }) => score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, query.limit ?? 10)\n .map(({ entry }) => entry);\n }\n\n store(entry: MemoryEntry): Promise<void> {\n return this.mutate((entries) => {\n const index = entries.findIndex((e) => e.key === entry.key);\n const stamped: MemoryEntry = {\n ...entry,\n createdAt: entry.createdAt ?? new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n };\n if (index >= 0) entries[index] = stamped;\n else entries.push(stamped);\n return [entries, undefined];\n });\n }\n\n async count(): Promise<number> {\n return (await this.readAll()).length;\n }\n}\n","/**\n * Remembera memory provider (§19): the preferred Hilbras memory integration,\n * reached over HTTP. Remembera is strictly optional — the core also runs with\n * the local memory provider or none at all (§2).\n *\n * API convention assumed by this adapter (adjust here if the real API differs):\n * write: POST {baseUrl}/api/memory body: MemoryEntry JSON → 2xx\n * query: POST {baseUrl}/api/memory/query body: MemoryQuery JSON → { entries: MemoryEntry[] }\n */\nimport { MemoryError } from \"../errors/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport { resolveApiKey } from \"../providers/auth.js\";\nimport { requestJson } from \"../providers/http.js\";\nimport type {\n IMemoryProvider,\n MemoryEntry,\n MemoryProviderMetadata,\n MemoryQuery,\n} from \"../types/memory.js\";\nimport { defaultMetadata, defaultSearch } from \"./base.js\";\n\nexport interface RememberaConfig {\n baseUrl: string;\n apiKeyEnvVar?: string;\n env?: Record<string, string | undefined>;\n}\n\nexport class RememberaMemoryProvider implements IMemoryProvider {\n readonly name = \"remembera\";\n private readonly baseUrl: string;\n private readonly apiKeyEnvVar?: string;\n private readonly env: Record<string, string | undefined>;\n private readonly log: Logger;\n\n constructor(config: RememberaConfig, log: Logger = logger) {\n this.baseUrl = config.baseUrl.replace(/\\/+$/, \"\");\n this.apiKeyEnvVar = config.apiKeyEnvVar;\n this.env = config.env ?? process.env;\n this.log = log.child({ component: \"remembera\" });\n }\n\n private get authenticationConfigured(): boolean {\n return this.apiKeyEnvVar === undefined || Boolean(this.env[this.apiKeyEnvVar]);\n }\n\n private headers(): Record<string, string> {\n const key = this.apiKeyEnvVar\n ? resolveApiKey({ name: \"remembera\", apiKeyEnvVar: this.apiKeyEnvVar }, this.env)\n : undefined;\n return key ? { authorization: `Bearer ${key}` } : {};\n }\n\n /** Search delegates to the gateway's relevance query. */\n search(text: string, options: { limit?: number; scope?: MemoryQuery[\"scope\"] } = {}): Promise<MemoryEntry[]> {\n return defaultSearch(\n this,\n text,\n {\n ...(options.scope !== undefined ? { scope: options.scope } : {}),\n ...(options.limit !== undefined ? { limit: options.limit } : {}),\n },\n );\n }\n\n metadata(): MemoryProviderMetadata {\n return defaultMetadata(this.name, {\n capabilities: [\"retrieve\", \"store\", \"search\", \"categories\", \"tags\"],\n relevanceRanking: true,\n backend: { kind: \"http\", baseUrl: this.baseUrl, authenticated: this.authenticationConfigured },\n });\n }\n\n /** @deprecated v1 alias of {@link retrieve}. */\n query(query: MemoryQuery): Promise<MemoryEntry[]> {\n return this.retrieve(query);\n }\n\n /** @deprecated v1 alias of {@link store}. */\n write(entry: MemoryEntry): Promise<void> {\n return this.store(entry);\n }\n\n async retrieve(query: MemoryQuery): Promise<MemoryEntry[]> {\n const { status, body } = await this.request(`${this.baseUrl}/api/memory/query`, query);\n if (status !== 200) {\n throw new MemoryError(`Remembera query returned HTTP ${status}.`);\n }\n const entries = (body as { entries?: unknown }).entries;\n if (!Array.isArray(entries)) {\n throw new MemoryError(\"Remembera query response had no entries array.\");\n }\n return entries.map((entry) => this.toEntry(entry)).filter((entry): entry is MemoryEntry => entry !== undefined);\n }\n\n async store(entry: MemoryEntry): Promise<void> {\n const { status } = await this.request(`${this.baseUrl}/api/memory`, entry);\n if (status !== 200 && status !== 201) {\n throw new MemoryError(`Remembera write returned HTTP ${status}.`);\n }\n }\n\n private async request(url: string, body: unknown): Promise<{ status: number; body: unknown }> {\n // Resolved outside the try so auth failures propagate as-is.\n const headers = this.headers();\n try {\n return await requestJson(url, {\n method: \"POST\",\n headers,\n body,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new MemoryError(`Remembera request to ${url} failed: ${message}`, { cause: error });\n }\n }\n\n private toEntry(raw: unknown): MemoryEntry | undefined {\n if (raw === null || typeof raw !== \"object\") {\n this.log.warn(\"Skipping malformed Remembera memory entry.\");\n return undefined;\n }\n const entry = raw as Record<string, unknown>;\n if (typeof entry.key !== \"string\" || typeof entry.content !== \"string\") {\n this.log.warn(\"Skipping Remembera memory entry without key/content.\");\n return undefined;\n }\n const scope = entry.scope;\n return {\n key: entry.key,\n content: entry.content,\n scope:\n scope === \"project\" || scope === \"role\" || scope === \"task\" || scope === \"knowledge\"\n ? scope\n : \"knowledge\",\n ...(Array.isArray(entry.tags) ? { tags: entry.tags.filter((t): t is string => typeof t === \"string\") } : {}),\n ...(typeof entry.category === \"string\"\n ? { category: entry.category as MemoryEntry[\"category\"] }\n : {}),\n ...(typeof entry.createdAt === \"string\" ? { createdAt: entry.createdAt } : {}),\n ...(typeof entry.updatedAt === \"string\" ? { updatedAt: entry.updatedAt } : {}),\n };\n }\n}\n","/** Memory provider factory: memory is optional; local is the default. */\nimport { ConfigError } from \"../errors/index.js\";\nimport type { AppConfig } from \"../config/index.js\";\nimport type { IMemoryProvider } from \"../types/memory.js\";\nimport { LocalMemoryProvider } from \"./local.js\";\nimport { RememberaMemoryProvider } from \"./remembera.js\";\n\nexport type MemoryProviderConfig = NonNullable<AppConfig[\"project\"][\"memory\"]>;\n\nexport function createMemoryProvider(config?: MemoryProviderConfig): IMemoryProvider {\n if (!config || config.provider === \"local\") {\n return new LocalMemoryProvider();\n }\n if (config.provider === \"remembera\") {\n if (!config.baseUrl) {\n throw new ConfigError(\n \"CONFIG_INVALID\",\n `Memory provider \"remembera\" needs a base_url in omninode.yaml.`,\n );\n }\n return new RememberaMemoryProvider({\n baseUrl: config.baseUrl,\n apiKeyEnvVar: config.apiKeyEnvVar,\n });\n }\n throw new ConfigError(\n \"CONFIG_INVALID\",\n `Unknown memory provider \"${config.provider}\". Available: local, remembera.`,\n );\n}\n","/**\n * Memory service + context manager (§12, Context Retrieval):\n *\n * Task → context query → relevant memory → context → agent/planner\n *\n * Retrieval is task-oriented and budgeted — OmniNode never loads all memory\n * into a prompt. Failures are best-effort by default; when memory is marked\n * `required`, they become fatal instead (§12, Failure Handling).\n */\nimport { MemoryError } from \"../errors/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { IMemoryProvider, MemoryEntry } from \"../types/memory.js\";\nimport type { Task } from \"../types/task.js\";\n\nexport interface MemoryContextQuery {\n objective: string;\n role?: string;\n project?: string;\n /** Maximum entries to consider (relevance-ranked by the provider). */\n limit?: number;\n}\n\nexport interface MemoryTaskContext {\n /** Prompt-ready context text (\"\" when nothing relevant was found). */\n text: string;\n entries: MemoryEntry[];\n /** True when the character budget cut the context short. */\n truncated: boolean;\n}\n\nconst DEFAULT_ENTRY_LIMIT = 8;\nexport const MAX_CONTEXT_CHARS = 4_000;\n\nexport interface MemoryServiceOptions {\n /** When true, backend failures propagate instead of being logged. */\n required?: boolean;\n maxContextChars?: number;\n}\n\nexport class MemoryService {\n private readonly log: Logger;\n private readonly required: boolean;\n private readonly maxContextChars: number;\n\n constructor(\n private readonly provider: IMemoryProvider,\n log: Logger = logger,\n options: MemoryServiceOptions = {},\n ) {\n this.log = log.child({ component: \"memory\", provider: provider.name });\n this.required = options.required ?? false;\n this.maxContextChars = options.maxContextChars ?? MAX_CONTEXT_CHARS;\n }\n\n get providerRef(): IMemoryProvider {\n return this.provider;\n }\n\n get providerName(): string {\n return this.provider.name;\n }\n\n get isRequired(): boolean {\n return this.required;\n }\n\n /** Structured, budgeted context for a task (§12 — avoid loading all memory). */\n async contextFor(query: MemoryContextQuery): Promise<MemoryTaskContext> {\n let entries: MemoryEntry[];\n try {\n entries = await this.provider.retrieve({\n text: query.objective,\n ...(query.role ? { tags: [query.role] } : {}),\n limit: query.limit ?? DEFAULT_ENTRY_LIMIT,\n });\n } catch (error) {\n return this.handleFailure(\"retrieve\", error, { text: \"\", entries: [], truncated: false });\n }\n return this.format(entries);\n }\n\n /** Prompt-ready context text (v1 convenience wrapper). */\n async gatherContext(query: MemoryContextQuery): Promise<string> {\n return (await this.contextFor(query)).text;\n }\n\n /** Records a finished task's outcome — task history plus \"known problems\" (§12). */\n async recordTaskOutcome(task: Task): Promise<void> {\n const outcome = task.result?.summary ?? task.result?.error ?? \"(no output)\";\n try {\n await this.provider.store({\n key: `task:${task.id}`,\n scope: \"task\",\n category: \"tasks\",\n content: `Objective: ${task.objective}\\nStatus: ${task.status}\\nOutcome: ${outcome}`,\n tags: [\"task\", ...(task.agent ? [task.agent] : []), ...(task.role ? [task.role] : [])],\n createdAt: task.createdAt,\n });\n const significant = (task.result?.reports ?? []).flatMap((report) =>\n report.findings\n .filter((finding) => finding.severity === \"high\" || finding.severity === \"critical\")\n .map((finding) => ({ report, finding })),\n );\n for (const { report, finding } of significant) {\n await this.provider.store({\n key: `finding:${report.id}:${finding.id}`,\n scope: \"project\",\n category: \"problems\",\n content: `[${finding.severity}] ${finding.title} — ${finding.detail}`,\n tags: [\"known-problem\", report.agent],\n });\n }\n } catch (error) {\n this.handleFailure(\"store\", error, undefined);\n }\n }\n\n private format(entries: MemoryEntry[]): MemoryTaskContext {\n if (entries.length === 0) return { text: \"\", entries, truncated: false };\n const byScope = new Map<string, MemoryEntry[]>();\n for (const entry of entries) {\n byScope.set(entry.scope, [...(byScope.get(entry.scope) ?? []), entry]);\n }\n const parts: string[] = [];\n for (const scope of [\"project\", \"task\", \"role\", \"knowledge\"]) {\n const scopeEntries = byScope.get(scope) ?? [];\n if (scopeEntries.length === 0) continue;\n const lines = scopeEntries\n .map((entry) => {\n const category = entry.category ? `[${entry.category}] ` : \"\";\n return `- ${category}${entry.content}`;\n })\n .join(\"\\n\");\n parts.push(`### Relevant memory (${scope})\\n${lines}`);\n }\n let text = parts.join(\"\\n\\n\");\n const truncated = text.length > this.maxContextChars;\n if (truncated) text = `${text.slice(0, this.maxContextChars - 1)}…`;\n return { text, entries, truncated };\n }\n\n /**\n * Failure policy (§12): continue unless memory is explicitly required.\n */\n private handleFailure(operation: string, error: unknown, fallback?: MemoryTaskContext): MemoryTaskContext {\n const message = error instanceof Error ? error.message : String(error);\n if (this.required) {\n throw new MemoryError(\n `Memory is marked required, but ${operation} failed: ${message}`,\n { cause: error },\n );\n }\n this.log.warn(`Memory ${operation} failed (continuing without memory): ${message}`);\n return fallback ?? { text: \"\", entries: [], truncated: false };\n }\n}","/**\n * Pipeline run persistence (§27 Phase 5 — pipeline state). Same\n * replaceable-store pattern as the task store, local-first JSON file.\n */\nimport { JsonFileStore } from \"../persistence/json-file-store.js\";\nimport type { PipelineRun, PipelineRunStatus } from \"../types/pipeline.js\";\n\nexport interface PipelineRunFilter {\n pipelineId?: string;\n status?: PipelineRunStatus;\n}\n\nexport interface PipelineRunStore {\n save(run: PipelineRun): Promise<void>;\n get(id: string): Promise<PipelineRun | undefined>;\n list(filter?: PipelineRunFilter): Promise<PipelineRun[]>;\n}\n\nexport class FilePipelineRunStore extends JsonFileStore<PipelineRun> implements PipelineRunStore {\n constructor(directory?: string) {\n super({ ...(directory !== undefined ? { directory } : {}), fileName: \"pipelines.json\" });\n }\n\n save(run: PipelineRun): Promise<void> {\n return this.mutate((runs) => {\n const index = runs.findIndex((r) => r.id === run.id);\n if (index >= 0) runs[index] = run;\n else runs.push(run);\n return [runs, undefined];\n });\n }\n\n async get(id: string): Promise<PipelineRun | undefined> {\n return (await this.readAll()).find((r) => r.id === id);\n }\n\n async list(filter: PipelineRunFilter = {}): Promise<PipelineRun[]> {\n return (await this.readAll())\n .filter((run) => (filter.pipelineId ? run.pipelineId === filter.pipelineId : true))\n .filter((run) => (filter.status ? run.status === filter.status : true))\n .sort((a, b) => (a.startedAt ?? \"\").localeCompare(b.startedAt ?? \"\"));\n }\n}\n","/**\n * Task persistence (§4.1 — execution state). The store is replaceable\n * (§2 — Modular); the default implementation is a local JSON file so\n * OmniNode stays local-first (§25).\n */\nimport { JsonFileStore } from \"../persistence/json-file-store.js\";\nimport type { Task, TaskStatus } from \"../types/task.js\";\n\nexport interface TaskStoreFilter {\n status?: TaskStatus;\n project?: string;\n}\n\nexport interface TaskStore {\n save(task: Task): Promise<void>;\n get(id: string): Promise<Task | undefined>;\n list(filter?: TaskStoreFilter): Promise<Task[]>;\n}\n\nexport class FileTaskStore extends JsonFileStore<Task> implements TaskStore {\n constructor(directory?: string) {\n super({ ...(directory !== undefined ? { directory } : {}), fileName: \"tasks.json\" });\n }\n\n save(task: Task): Promise<void> {\n return this.mutate((tasks) => {\n const index = tasks.findIndex((t) => t.id === task.id);\n if (index >= 0) tasks[index] = task;\n else tasks.push(task);\n return [tasks, undefined];\n });\n }\n\n async get(id: string): Promise<Task | undefined> {\n const tasks = await this.readAll();\n return tasks.find((t) => t.id === id);\n }\n\n async list(filter: TaskStoreFilter = {}): Promise<Task[]> {\n const tasks = await this.readAll();\n return tasks\n .filter((task) => (filter.status ? task.status === filter.status : true))\n .filter((task) => (filter.project ? task.project === filter.project : true))\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n }\n}\n","/**\n * `omninode <subject> inspect` — post-hoc diagnostics (roadmap §18): everything\n * known about a task, pipeline run, agent or provider, so a failed execution\n * can be understood after the fact. `--json` emits the raw records.\n */\nimport type { Command } from \"commander\";\nimport { buildAgentRegistry } from \"../../agents/index.js\";\nimport { buildRoleRegistry } from \"../../roles/index.js\";\nimport { createMemoryProvider, MemoryService } from \"../../memory/index.js\";\nimport { OmniNodeError } from \"../../errors/index.js\";\nimport { FilePipelineRunStore } from \"../../pipelines/store.js\";\nimport { FileTaskStore } from \"../../tasks/store.js\";\nimport { resolveEnvPolicy } from \"../../agents/env.js\";\nimport { loadProjectConfig } from \"../options.js\";\nfunction emit(json: boolean, payload: unknown, render: () => void): void {\n if (json) {\n console.log(JSON.stringify(payload, null, 2));\n return;\n }\n render();\n}\n\nfunction jsonOption(command: Command): Command {\n return command.option(\"--json\", \"Emit the raw record as JSON.\");\n}\n\n/** Registers `task inspect` on the existing task group. */\nexport function registerTaskInspect(taskGroup: Command): void {\n jsonOption(\n taskGroup\n .command(\"inspect <id>\")\n .description(\"Show a task with its execution history, result and report references.\")\n .action(async (id: string, options: { json?: boolean }) => {\n const tasks = await new FileTaskStore().list();\n const task = tasks.find((t) => t.id === id);\n if (!task) throw new OmniNodeError(\"TASK_NOT_FOUND\", `No task \"${id}\" in this project's store.`);\n emit(options.json ?? false, task, () => {\n console.log(`Task ${task.id}`);\n console.log(` status: ${task.status}${task.attempt > 0 ? ` (attempt ${task.attempt})` : \"\"}`);\n if (task.project) console.log(` project: ${task.project}`);\n if (task.pipelineId) console.log(` pipeline: ${task.pipelineId}`);\n console.log(` objective: ${task.objective}`);\n if (task.role) console.log(` role: ${task.role}`);\n if (task.agent) console.log(` agent: ${task.agent}`);\n console.log(` created: ${task.createdAt}`);\n console.log(` updated: ${task.updatedAt}`);\n if (task.lastError) console.log(` lastError: ${task.lastError}`);\n if (task.executions && task.executions.length > 0) {\n console.log(\" executions:\");\n for (const execution of task.executions) {\n console.log(\n ` #${execution.attempt} ${execution.outcome} (${execution.executionId})` +\n `${execution.error ? ` — ${execution.error}` : \"\"}`,\n );\n }\n }\n if (task.result?.summary) console.log(` summary: ${task.result.summary}`);\n if (task.result?.reports && task.result.reports.length > 0) {\n console.log(` reports: ${task.result.reports.length}`);\n for (const report of task.result.reports) {\n console.log(` - [${report.agent}] ${report.summary}`);\n for (const finding of report.findings) {\n console.log(` · [${finding.severity ?? \"info\"}] ${finding.title}`);\n }\n }\n }\n });\n }),\n );\n}\n\n/** Registers `pipeline inspect` on the pipeline group. */\nexport function registerPipelineInspect(pipelineGroup: Command): void {\n jsonOption(\n pipelineGroup\n .command(\"inspect <run-id>\")\n .description(\"Show a pipeline run with per-step status and artifact references.\")\n .action(async (runId: string, options: { json?: boolean }) => {\n const run = await new FilePipelineRunStore().get(runId);\n if (!run) throw new OmniNodeError(\"PIPELINE_NOT_FOUND\", `No pipeline run \"${runId}\" in this project's store.`);\n emit(options.json ?? false, run, () => {\n console.log(`Pipeline run ${run.id} (${run.pipelineId})`);\n console.log(` status: ${run.status}${run.attempt > 1 ? ` (attempt ${run.attempt})` : \"\"}`);\n if (run.objective) console.log(` objective: ${run.objective}`);\n console.log(` started: ${run.startedAt ?? \"?\"}`);\n if (run.finishedAt) console.log(` finished: ${run.finishedAt}`);\n if (run.planId) console.log(` plan: ${run.planId}`);\n if (run.combinedReportId) console.log(` combined: ${run.combinedReportId}`);\n if (run.resultSummary) console.log(` result: ${run.resultSummary}`);\n console.log(\" steps:\");\n for (const step of run.stepRuns) {\n const stepTaskIds = step.taskIds ?? [];\n const tasks = stepTaskIds.length > 0 ? ` tasks=${stepTaskIds.join(\",\")}` : \"\";\n console.log(` ${step.stepId.padEnd(14)} ${step.status}${tasks}${step.error ? ` — ${step.error}` : \"\"}`);\n }\n });\n }),\n );\n}\n\n/** Registers `agent inspect` on the agent group. */\nexport function registerAgentInspect(agentGroup: Command): void {\n jsonOption(\n agentGroup\n .command(\"inspect <name>\")\n .description(\"Show an agent's effective configuration and recent tasks.\")\n .action(async (name: string, options: { json?: boolean }) => {\n const config = loadProjectConfig();\n const agentConfig = config.project.agents.find((a) => a.name === name);\n if (!agentConfig) throw new OmniNodeError(\"AGENT_NOT_FOUND\", `No agent \"${name}\" is configured.`);\n const registry = buildAgentRegistry(config);\n const agent = registry.get(name);\n const recent = (await new FileTaskStore().list())\n .filter((task) => task.agent === name)\n .slice(-5)\n .map((task) => ({ id: task.id, status: task.status, updatedAt: task.updatedAt }));\n const payload = {\n config: agentConfig,\n effective: agent?.info,\n envPolicy: resolveEnvPolicy(agentConfig),\n recentTasks: recent,\n };\n emit(options.json ?? false, payload, () => {\n console.log(`Agent ${name}`);\n console.log(` integration: ${agentConfig.integration}`);\n console.log(` command: ${agentConfig.command ?? \"(none)\"}`);\n console.log(` input mode: ${agentConfig.inputMode ?? \"stdin\"}`);\n console.log(` env policy: ${resolveEnvPolicy(agentConfig)}`);\n if (agentConfig.cwd) console.log(` working dir: ${agentConfig.cwd}`);\n if (agentConfig.timeoutMs) console.log(` timeout: ${agentConfig.timeoutMs}ms`);\n if (agentConfig.maxOutputBytes) console.log(` max output: ${agentConfig.maxOutputBytes} bytes/stream`);\n if (agentConfig.allowExternalCwd) console.log(` external cwd allowed`);\n console.log(` recent tasks: ${recent.map((t) => `${t.id}:${t.status}`).join(\", \") || \"(none)\"}`);\n });\n }),\n );\n}\n\n/** Registers `provider inspect` on the provider group. */\nexport function registerProviderInspect(providerGroup: Command): void {\n jsonOption(\n providerGroup\n .command(\"inspect <name>\")\n .description(\"Show a provider's authentication status and capabilities.\")\n .action(async (name: string, options: { json?: boolean }) => {\n const config = loadProjectConfig();\n const providerConfig = config.project.providers.find((p) => p.name === name);\n if (!providerConfig) throw new OmniNodeError(\"PROVIDER_NOT_FOUND\", `No provider \"${name}\" is configured.`);\n const { createProvider } = await import(\"../../providers/index.js\");\n const provider = createProvider(providerConfig);\n const payload = {\n config: providerConfig,\n providerId: provider.providerId,\n authentication: provider.authentication,\n capabilities: providerConfig.capabilities ?? [],\n memoryConfigured: config.project.memory\n ? { provider: config.project.memory.provider, required: config.project.memory.required ?? false }\n : undefined,\n memoryEntries: config.project.memory\n ? await new MemoryService(createMemoryProvider(config.project.memory)).providerRef.query({ limit: 10_000 }).then((e) => e.length)\n : undefined,\n roles: buildRoleRegistry(config).list().length,\n };\n emit(options.json ?? false, payload, () => {\n console.log(`Provider ${name}`);\n console.log(` providerId: ${provider.providerId}`);\n console.log(` type: ${providerConfig.type}`);\n console.log(` base URL: ${providerConfig.baseUrl}`);\n console.log(` auth: ${provider.authentication.method}${provider.authentication.envVar ? ` ($${provider.authentication.envVar})` : \"\"}`);\n console.log(` credentials: ${provider.authentication.configured ? \"configured\" : \"MISSING\"}`);\n if (providerConfig.capabilities?.length) {\n console.log(` capabilities: ${providerConfig.capabilities.join(\", \")}`);\n }\n });\n }),\n );\n}\n","/**\n * Task engine (§13, §27 Phase 4): owns the task lifecycle — create, queue,\n * run, cancel — validates role/agent assignment against the registries and\n * persists every transition through the task store.\n */\nimport { randomBytes } from \"node:crypto\";\nimport type { AgentRegistry } from \"../agents/index.js\";\nimport type { RoleRegistry } from \"../roles/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport { AgentError, TaskError } from \"../errors/index.js\";\nimport type { AuditAction, AuditSink } from \"../audit/index.js\";\nimport type { MemoryService } from \"../memory/index.js\";\nimport type {\n ExecutionRecord,\n Task,\n TaskContext,\n TaskResult,\n TaskStatus,\n} from \"../types/task.js\";\nimport type { TaskStore, TaskStoreFilter } from \"./store.js\";\n\n/**\n * Strict state machine (roadmap §6.2). Invalid transitions are rejected —\n * engines never mutate state directly.\n *\n * created ──▶ queued ──▶ running ──┬─▶ completed\n * │ │ │ ├─▶ failed\n * │ │ │ ├─▶ timed_out (no side effects possible)\n * └───────────┴─────────┴────────┼─▶ unknown (outcome unprovable — e.g. killed after dispatch)\n * ├─▶ cancelled\n * └─▶ partially_completed (fan-out where some units succeeded)\n */\nconst ALLOWED_TRANSITIONS: Record<TaskStatus, TaskStatus[]> = {\n created: [\"queued\", \"running\", \"cancelled\"],\n queued: [\"running\", \"cancelled\"],\n running: [\"completed\", \"failed\", \"timed_out\", \"unknown\", \"cancelled\", \"partially_completed\"],\n waiting: [\"running\", \"cancelled\"],\n completed: [],\n // failed → running is the only re-entry: bounded automatic retry (§6.4).\n failed: [\"running\"],\n timed_out: [],\n cancelled: [],\n unknown: [],\n partially_completed: [],\n};\n\n/**\n * Error codes safe to retry automatically: a transient agent crash before any\n * report was produced. Timeouts/unknown outcomes are NEVER auto-retried\n * because the agent may already have performed side effects (roadmap §6.4).\n */\nconst RETRYABLE_ERROR_CODES: readonly string[] = [\"AGENT_FAILED\"];\nconst EXECUTION_HISTORY_LIMIT = 10;\n\nexport interface CreateTaskInput {\n objective: string;\n project?: string;\n pipelineId?: string;\n role?: string;\n agent?: string;\n context?: TaskContext;\n}\n\nexport interface RunTaskOptions {\n /** Total attempts (1 = no automatic retry). Retries apply to retryable errors only. */\n maxAttempts?: number;\n /** Linear backoff base in ms: waits backoffMs × attempt between attempts. */\n retryBackoffMs?: number;\n}\n\nexport interface TaskEngineOptions {\n agents: AgentRegistry;\n roles: RoleRegistry;\n store: TaskStore;\n /** When present, tasks gather relevant memory before running and record outcomes after (§20). */\n memory?: MemoryService;\n /** When present, task lifecycle transitions are appended to the audit log (§24). */\n audit?: AuditSink;\n log?: Logger;\n}\n\nexport class TaskEngine {\n private readonly log: Logger;\n\n constructor(private readonly options: TaskEngineOptions) {\n this.log = (options.log ?? logger).child({ component: \"tasks\" });\n }\n\n get store(): TaskStore {\n return this.options.store;\n }\n\n async create(input: CreateTaskInput): Promise<Task> {\n if (!input.objective || input.objective.trim().length === 0) {\n throw new TaskError(\"TASK_INVALID\", \"Task objective must not be empty.\");\n }\n if (input.role && !this.options.roles.get(input.role)) {\n throw new TaskError(\"TASK_INVALID\", \n `Role \"${input.role}\" is not defined. Add it under project.roles in omninode.yaml.`,\n );\n }\n if (input.agent && !this.options.agents.get(input.agent)) {\n throw new TaskError(\"TASK_INVALID\", \n `Agent \"${input.agent}\" is not registered. Add it with \\`omninode agent add\\`.`,\n );\n }\n\n const now = new Date().toISOString();\n const task: Task = {\n id: generateTaskId(),\n objective: input.objective.trim(),\n status: \"created\",\n attempt: 0,\n createdAt: now,\n updatedAt: now,\n ...(input.project !== undefined ? { project: input.project } : {}),\n ...(input.pipelineId !== undefined ? { pipelineId: input.pipelineId } : {}),\n ...(input.role !== undefined ? { role: input.role } : {}),\n ...(input.agent !== undefined ? { agent: input.agent } : {}),\n ...(input.context !== undefined ? { context: input.context } : {}),\n };\n await this.options.store.save(task);\n this.log.info(`Created task ${task.id}.`);\n await this.audit(\"task.created\", task, { objective: task.objective });\n return task;\n }\n\n async queue(id: string): Promise<Task> {\n const task = await this.mustGet(id);\n return this.transition(task, \"queued\");\n }\n\n /** Runs the task through its assigned agent and records the result.\n * `maxAttempts` enables bounded automatic retries of *retryable* errors\n * with linear backoff; unknown/timed_out outcomes are never auto-retried. */\n async run(id: string, options: RunTaskOptions = {}): Promise<Task> {\n const task = await this.mustGet(id);\n if (task.status !== \"created\" && task.status !== \"queued\") {\n throw new TaskError(\"TASK_INVALID\", `Task ${id} is \"${task.status}\" and cannot be run.`);\n }\n if (!task.agent) {\n throw new TaskError(\"TASK_INVALID\", `Task ${id} has no agent assigned. Re-create it with --agent.`);\n }\n const agent = this.options.agents.get(task.agent);\n if (!agent) {\n throw new TaskError(\"TASK_INVALID\", `Agent \"${task.agent}\" is not registered anymore.`);\n }\n const role = task.role ? this.options.roles.get(task.role) : undefined;\n\n this.log.info(`Running task ${task.id} on agent \"${task.agent}\".`);\n\n // §20: relevant memory is gathered before the agent receives context.\n let background = task.context?.background;\n if (this.options.memory) {\n const memoryContext = await this.options.memory.gatherContext({\n objective: task.objective,\n ...(task.role ? { role: task.role } : {}),\n ...(task.project ? { project: task.project } : {}),\n });\n if (memoryContext.length > 0) {\n background = [memoryContext, background].filter((part) => part && part.length > 0).join(\"\\n\\n\");\n }\n }\n\n const maxAttempts = Math.max(1, options.maxAttempts ?? 1);\n const backoffMs = options.retryBackoffMs ?? 0;\n\n let current = task;\n for (let i = 0; i < maxAttempts; i += 1) {\n // Attempt numbers are cumulative for the task (roadmap §6.5).\n const attempt = current.attempt + 1;\n const executionId = `exec-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`;\n const startedAt = new Date().toISOString();\n current = await this.transition(current, \"running\", { attempt });\n\n await this.options.audit?.record({\n at: startedAt,\n action: \"agent.started\",\n id: current.id,\n taskId: current.id,\n ...(current.pipelineId !== undefined ? { pipelineId: current.pipelineId } : {}),\n agentId: task.agent,\n executionId,\n detail: { attempt },\n });\n\n let output;\n let thrown: unknown;\n try {\n output = await agent.run({\n taskId: current.id,\n objective: current.objective,\n executionId,\n ...(current.pipelineId !== undefined ? { pipelineId: current.pipelineId } : {}),\n ...(role ? { role } : {}),\n ...(background !== undefined ? { context: background } : {}),\n });\n } catch (error) {\n thrown = error;\n }\n\n const finishedAt = new Date().toISOString();\n await this.options.audit?.record({\n at: finishedAt,\n action: \"agent.completed\",\n id: current.id,\n taskId: current.id,\n ...(current.pipelineId !== undefined ? { pipelineId: current.pipelineId } : {}),\n agentId: task.agent,\n executionId,\n detail: { attempt, outcome: thrown !== undefined || output === undefined ? \"threw\" : \"returned\" },\n });\n if (thrown !== undefined || output === undefined) {\n const outcome = classifyThrown(thrown);\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n const retryable =\n outcome === \"failed\" &&\n RETRYABLE_ERROR_CODES.includes(errorCode(thrown)) &&\n i < maxAttempts - 1;\n current = await this.transition(current, outcome, {\n attempt,\n lastError: message,\n execution: {\n executionId,\n attempt,\n startedAt,\n finishedAt,\n outcome,\n error: message,\n },\n });\n this.log.warn(`Task ${current.id} attempt ${attempt} → ${outcome}: ${message}`);\n if (retryable) {\n if (backoffMs > 0) await sleep(backoffMs * attempt);\n continue;\n }\n if (this.options.memory) await this.options.memory.recordTaskOutcome(current);\n return current;\n }\n\n // The task may have been cancelled while the agent was finishing —\n // respect the terminal state instead of forcing a completed transition.\n const currentState = await this.options.store.get(current.id);\n if (currentState?.status === \"cancelled\") {\n current = currentState;\n break;\n }\n\n const result: TaskResult = {\n ...(output.summary !== undefined ? { summary: output.summary } : {}),\n ...(output.reports !== undefined && output.reports.length > 0 ? { reports: output.reports } : {}),\n // Keep the verbatim output (bounded) for report extraction and audit.\n ...(output.rawOutput !== undefined && output.rawOutput.length > 0\n ? { rawOutput: output.rawOutput.slice(0, 10_000) }\n : {}),\n ...(output.error !== undefined ? { error: output.error } : {}),\n finishedAt,\n };\n const finalStatus: TaskStatus = output.status === \"completed\" ? \"completed\" : \"failed\";\n current = await this.transition(current, finalStatus, {\n attempt,\n result,\n execution: { executionId, attempt, startedAt, finishedAt, outcome: finalStatus },\n });\n this.log.info(`Task ${current.id} finished: ${finalStatus}.`);\n break;\n }\n\n // §20: the outcome is written back to memory — best-effort, never fatal.\n if (this.options.memory) {\n await this.options.memory.recordTaskOutcome(current);\n }\n return current;\n }\n\n async cancel(id: string): Promise<Task> {\n const task = await this.mustGet(id);\n if (!ALLOWED_TRANSITIONS[task.status].includes(\"cancelled\")) {\n throw new TaskError(\"TASK_INVALID\", `Task ${id} is \"${task.status}\" and cannot be cancelled.`);\n }\n if (task.agent) {\n const agent = this.options.agents.get(task.agent);\n await agent?.cancel?.(task.id);\n }\n return this.transition(task, \"cancelled\");\n }\n\n /** Error recovery: reset a failed/cancelled/unknown/timed_out task so it can run again. */\n async retry(id: string): Promise<Task> {\n const task = await this.mustGet(id);\n const retryableStates: TaskStatus[] = [\"failed\", \"cancelled\", \"unknown\", \"timed_out\"];\n if (!retryableStates.includes(task.status)) {\n throw new TaskError(\n \"TASK_INVALID\",\n `Only failed, timed out, unknown or cancelled tasks can be retried — task ${id} is \"${task.status}\".`,\n );\n }\n const { result: _discarded, ...rest } = task;\n const reset: Task = {\n ...rest,\n status: \"created\",\n updatedAt: new Date().toISOString(),\n };\n await this.options.store.save(reset);\n await this.audit(\"task.retry\", reset, { from: task.status });\n this.log.info(`Task ${id} reset for retry.`);\n return reset;\n }\n\n async get(id: string): Promise<Task | undefined> {\n return this.options.store.get(id);\n }\n\n async list(filter?: TaskStoreFilter): Promise<Task[]> {\n return this.options.store.list(filter);\n }\n\n private async mustGet(id: string): Promise<Task> {\n const task = await this.options.store.get(id);\n if (!task) {\n throw new TaskError(\"TASK_NOT_FOUND\", `Task \"${id}\" does not exist in this project's task store.`);\n }\n return task;\n }\n\n private async transition(\n task: Task,\n to: TaskStatus,\n extra: { result?: TaskResult; attempt?: number; lastError?: string; execution?: ExecutionRecord } = {},\n ): Promise<Task> {\n const allowed = ALLOWED_TRANSITIONS[task.status] ?? [];\n if (!allowed.includes(to)) {\n throw new TaskError(\"TASK_INVALID\", `Task ${task.id} cannot move from \"${task.status}\" to \"${to}\".`);\n }\n const executions = extra.execution\n ? [...(task.executions ?? []), extra.execution].slice(-EXECUTION_HISTORY_LIMIT)\n : task.executions;\n const updated: Task = {\n ...task,\n status: to,\n updatedAt: new Date().toISOString(),\n ...(extra.attempt !== undefined ? { attempt: extra.attempt } : {}),\n ...(extra.lastError !== undefined ? { lastError: extra.lastError } : {}),\n ...(executions !== undefined ? { executions } : {}),\n ...(extra.result !== undefined\n ? { result: { ...task.result, ...extra.result } }\n : {}),\n };\n await this.options.store.save(updated);\n await this.audit(`task.${to === \"queued\" ? \"queued\" : to}` as AuditAction, updated, {\n from: task.status,\n });\n return updated;\n }\n\n private async audit(\n action: AuditAction,\n task: Task,\n detail?: Record<string, unknown>,\n executionId?: string,\n ): Promise<void> {\n // Correlation (§18): every event carries task/pipeline/agent/execution ids.\n await this.options.audit?.record({\n at: new Date().toISOString(),\n action,\n id: task.id,\n taskId: task.id,\n ...(task.project !== undefined ? { project: task.project } : {}),\n ...(task.pipelineId !== undefined ? { pipelineId: task.pipelineId } : {}),\n ...(task.agent !== undefined ? { agentId: task.agent } : {}),\n ...(executionId !== undefined ? { executionId } : {}),\n ...(detail !== undefined ? { detail } : {}),\n });\n }\n}\n\nfunction generateTaskId(): string {\n return `task-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`;\n}\n\nfunction errorCode(error: unknown): string {\n return (error as { code?: string } | undefined)?.code ?? \"\";\n}\n\n/**\n * Classifies a thrown adapter error into a terminal state.\n *\n * §6.3: a timeout is NOT assumed to be a failure. If the operation was\n * dispatched, the remote side may have completed it, so the outcome is\n * `unknown`. Only a timeout provably raised *before* dispatch becomes\n * `timed_out`.\n */\nfunction classifyThrown(error: unknown): \"failed\" | \"timed_out\" | \"unknown\" {\n if (error instanceof AgentError && error.code === \"AGENT_TIMEOUT\") {\n const dispatched = (error.details as { dispatched?: unknown } | undefined)?.dispatched;\n return dispatched === false ? \"timed_out\" : \"unknown\";\n }\n return \"failed\";\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * Audit logging (§24): append-only JSONL record of lifecycle events\n * (task/pipeline transitions) in the project's .omninode directory. Useful\n * for compliance reviews and debugging multi-agent runs.\n */\nimport { appendFile, mkdir, readFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { logger, type Logger } from \"../logger/index.js\";\n\nexport type AuditAction =\n | \"task.created\"\n | \"task.queued\"\n | \"task.running\"\n | \"task.completed\"\n | \"task.failed\"\n | \"task.cancelled\"\n | \"task.retry\"\n | \"pipeline.run.started\"\n | \"pipeline.run.finished\"\n | \"pipeline.run.failed\"\n | \"pipeline.run.cancelled\"\n | \"plan.generated\"\n | \"agent.started\"\n | \"agent.completed\"\n | \"provider.error\"\n | \"memory.context.gathered\"\n | \"memory.outcome.recorded\";\n\n/**\n * Every event carries correlation ids so a failed execution can be traced\n * across task → execution → pipeline run → agent → provider (roadmap §18).\n */\nexport interface AuditEvent {\n at: string;\n action: AuditAction;\n project?: string;\n /** Primary subject: task id, pipeline run id, plan id… */\n id?: string;\n taskId?: string;\n pipelineId?: string;\n executionId?: string;\n agentId?: string;\n providerId?: string;\n actor?: string;\n detail?: Record<string, unknown>;\n}\n\nexport interface AuditSink {\n record(event: AuditEvent): Promise<void>;\n}\n\n/** Append-only JSONL sink. Failures are logged, never propagated. */\nexport class FileAuditLog implements AuditSink {\n private readonly filePath: string;\n private readonly log: Logger;\n\n constructor(directory = `${process.cwd()}/.omninode`, log: Logger = logger) {\n this.filePath = `${directory}/audit.jsonl`;\n this.log = log.child({ component: \"audit\" });\n }\n\n async record(event: AuditEvent): Promise<void> {\n try {\n await mkdir(dirname(this.filePath), { recursive: true });\n // Append-only: a crash can tear the last line, which `recent()` skips.\n // fsync-per-event would make every execution wait on the disk.\n await appendFile(this.filePath, `${JSON.stringify(event)}\\n`, \"utf8\");\n } catch (error) {\n this.log.warn(\n `Audit write failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n /** Recent events, oldest first; used by the CLI. */\n async recent(limit = 20): Promise<AuditEvent[]> {\n let raw: string;\n try {\n raw = await readFile(this.filePath, \"utf8\");\n } catch {\n return [];\n }\n const events = raw\n .split(\"\\n\")\n .filter((line) => line.length > 0)\n .map((line) => {\n try {\n return JSON.parse(line) as AuditEvent;\n } catch {\n return undefined;\n }\n })\n .filter((event): event is AuditEvent => event !== undefined);\n return events.slice(-limit);\n }\n}","/** Assembles a TaskEngine from the project configuration (local-first defaults). */\nimport type { AppConfig } from \"../config/index.js\";\nimport { FileAuditLog } from \"../audit/index.js\";\nimport { buildAgentRegistry } from \"../agents/index.js\";\nimport { createMemoryProvider, MemoryService } from \"../memory/index.js\";\nimport { buildRoleRegistry } from \"../roles/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport { TaskEngine } from \"./engine.js\";\nimport { FileTaskStore } from \"./store.js\";\n\nexport function createTaskEngine(config: AppConfig, log: Logger = logger, directory?: string): TaskEngine {\n const agents = buildAgentRegistry(config, log);\n const roles = buildRoleRegistry(config);\n return new TaskEngine({\n agents,\n roles,\n store: new FileTaskStore(directory),\n ...(config.project.memory !== undefined\n ? {\n memory: new MemoryService(createMemoryProvider(config.project.memory), log, {\n required: config.project.memory.required,\n }),\n }\n : {}),\n audit: new FileAuditLog(),\n log,\n });\n}\n","import type { Command } from \"commander\";\nimport { agentConfigSchema } from \"../../config/index.js\";\nimport { AgentError, OmniNodeError } from \"../../errors/index.js\";\nimport { createAgent } from \"../../agents/index.js\";\nimport { createTaskEngine } from \"../../tasks/index.js\";\nimport { exitCodeForStatus } from \"../exit-codes.js\";\nimport { appendToConfigList } from \"./shared.js\";\nimport { registerAgentInspect } from \"./inspect.js\";\nimport { loadProjectConfig } from \"../options.js\";\nconst collectArgs = (value: string, previous: string[]): string[] => [...previous, value];\n\ninterface AddAgentOptions {\n name: string;\n command: string;\n arg?: string[];\n cwd?: string;\n inputMode: string;\n timeoutMs?: number;\n envPolicy?: string;\n allowEnv?: string[];\n denyEnv?: string[];\n maxOutputBytes?: number;\n allowExternalCwd?: boolean;\n}\n\nexport function registerAgentCommands(program: Command): void {\n const agent = program\n .command(\"agent\")\n .description(\"Manage CLI agents registered with OmniNode.\");\n\n agent\n .command(\"list\")\n .description(\"List configured agents.\")\n .option(\"--json\", \"Emit agents as JSON.\")\n .action(async (options: { json?: boolean }) => {\n const config = loadProjectConfig();\n const agents = config.project.agents;\n if (options.json) {\n console.log(JSON.stringify(config.project.agents, null, 2));\n return;\n }\n if (agents.length === 0) {\n console.log(\"No agents configured. Add one with `omninode agent add` or edit omninode.yaml.\");\n return;\n }\n for (const agent of agents) {\n const command = agent.command ?? \"(no command)\";\n console.log(\n `${agent.name} integration=${agent.integration} command=${command} input=${agent.inputMode ?? \"stdin\"}`,\n );\n }\n });\n\n agent\n .command(\"add\")\n .description(\n \"Register a CLI agent in omninode.yaml. Agents run as child processes \" +\n \"(stdin/stdout); native adapters come in a later phase.\",\n )\n .requiredOption(\"--name <name>\", \"Unique agent name.\")\n .requiredOption(\"--command <command>\", \"Executable command, e.g. opencode\")\n .option(\"--arg <value>\", \"Additional command argument (repeatable).\", collectArgs, [])\n .option(\"--cwd <dir>\", \"Working directory for the agent process.\")\n .option(\n \"--input-mode <mode>\",\n \"How the task is delivered: stdin (prompt on stdin), arg (prompt as last argument) or protocol (§21 JSON-lines task protocol).\",\n \"stdin\",\n )\n .option(\"--env-policy <policy>\", \"Environment policy: inherit, allowlist, denylist or explicit.\")\n .option(\"--allow-env <name>\", \"Variable to forward under the allowlist policy (repeatable).\", collectArgs)\n .option(\"--deny-env <name>\", \"Variable to remove under the denylist policy (repeatable).\", collectArgs)\n .option(\"--max-output-bytes <n>\", \"Per-stream output budget in bytes (default 5 MiB).\", (value: string) => Number(value))\n .option(\"--allow-external-cwd\", \"Allow a working directory outside the project root.\")\n .option(\"--timeout-ms <ms>\", \"Per-task timeout in milliseconds.\", (value: string) =>\n Number(value),\n )\n .action(async (options: AddAgentOptions) => addAgent(options));\n\n agent\n .command(\"run <name> <objective>\")\n .description(\"Run a single task through this agent immediately.\")\n .action(async (name: string, objective: string) => {\n const config = loadProjectConfig();\n const agentConfig = config.project.agents.find((a) => a.name === name);\n if (!agentConfig) {\n throw new AgentError(\"AGENT_NOT_FOUND\", `No agent \"${name}\" is configured.`);\n }\n const engine = createTaskEngine(config);\n const task = await engine.create({ objective, agent: name, project: config.project.name });\n const finished = await engine.run(task.id);\n console.log(` id: ${finished.id}`);\n console.log(` status: ${finished.status}`);\n if (finished.result?.summary) console.log(` summary: ${finished.result.summary}`);\n if (finished.result?.error) console.log(` error: ${finished.result.error}`);\n process.exitCode = exitCodeForStatus(finished.status);\n });\n\n agent\n .command(\"test <name>\")\n .description(\"Verify the OmniNode ↔ agent connection by sending a trivial task.\")\n .action(async (name: string) => testAgent(name));\n registerAgentInspect(agent);\n}\n\nexport async function addAgent(options: AddAgentOptions): Promise<void> {\n const candidate = agentConfigSchema.safeParse({\n name: options.name,\n type: \"cli\",\n command: options.command,\n ...(options.arg !== undefined && options.arg.length > 0 ? { args: options.arg } : {}),\n ...(options.cwd !== undefined ? { cwd: options.cwd } : {}),\n input_mode: options.inputMode,\n ...(options.timeoutMs !== undefined ? { timeout_ms: options.timeoutMs } : {}),\n ...(options.envPolicy !== undefined ? { env_policy: options.envPolicy } : {}),\n ...(options.allowEnv !== undefined && options.allowEnv.length > 0\n ? { env_allowlist: options.allowEnv }\n : {}),\n ...(options.denyEnv !== undefined && options.denyEnv.length > 0\n ? { env_denylist: options.denyEnv }\n : {}),\n ...(options.maxOutputBytes !== undefined ? { max_output_bytes: options.maxOutputBytes } : {}),\n ...(options.allowExternalCwd !== undefined ? { allow_external_cwd: options.allowExternalCwd } : {}),\n });\n if (!candidate.success) {\n const issues = candidate.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"(root)\"}: ${issue.message}`)\n .join(\"; \");\n throw new OmniNodeError(\"CLI_USAGE\", `Invalid agent options: ${issues}`);\n }\n const newAgent = candidate.data;\n\n const existing = loadProjectConfig();\n if (existing.project.agents.some((a) => a.name === newAgent.name)) {\n throw new OmniNodeError(\n \"CLI_USAGE\",\n `Agent \"${newAgent.name}\" already exists in omninode.yaml. Remove it first or pick another name.`,\n );\n }\n\n const configPath = appendToConfigList(\"agents\", newAgent);\n console.log(`Added agent \"${newAgent.name}\" (${newAgent.type}, input=${newAgent.input_mode}) to ${configPath}.`);\n console.log(`Run \\`omninode agent test ${newAgent.name}\\` to verify the connection.`);\n}\n\nexport async function testAgent(name: string): Promise<void> {\n const config = loadProjectConfig();\n const agentConfig = config.project.agents.find((a) => a.name === name);\n if (!agentConfig) {\n const available = config.project.agents.map((a) => a.name).join(\", \") || \"(none)\";\n throw new AgentError(\n \"AGENT_NOT_FOUND\",\n `Agent \"${name}\" is not configured. Configured agents: ${available}.`,\n );\n }\n\n const agent = createAgent(agentConfig);\n console.log(\n `Testing agent \"${name}\" (${agent.info.integration}, input=${agentConfig.inputMode ?? \"stdin\"}) — sending a trivial task.`,\n );\n const result = await agent.run({\n taskId: `test-${Date.now()}`,\n objective: \"Reply with the single word: OK\",\n });\n console.log(` status: ${result.status}`);\n if (result.exitCode !== undefined) console.log(` exit: ${result.exitCode}`);\n if (result.summary) console.log(` output: ${result.summary}`);\n if (result.rawOutput && result.rawOutput !== result.summary) {\n console.log(` raw: ${result.rawOutput.slice(0, 200).replace(/\\n/g, \" \")}`);\n }\n if (result.error) console.log(` error: ${result.error}`);\n if (result.status !== \"completed\") process.exitCode = 1;\n}\n","import type { Command } from \"commander\";\nimport { loadProjectConfig } from \"../options.js\";\nexport function registerRoleCommands(program: Command): void {\n const role = program\n .command(\"role\")\n .description(\"Inspect roles defined in omninode.yaml.\");\n\n role\n .command(\"list\")\n .description(\"List configured roles.\")\n .option(\"--json\", \"Emit roles as JSON.\")\n .action(async (options: { json?: boolean }) => {\n const config = loadProjectConfig();\n const roles = config.project.roles;\n if (options.json) {\n console.log(JSON.stringify(config.project.roles, null, 2));\n return;\n }\n if (roles.length === 0) {\n console.log(\"No roles configured. Add one under `project.roles` in omninode.yaml.\");\n return;\n }\n for (const role of roles) {\n console.log(`${role.id} ${role.name}`);\n for (const responsibility of role.responsibilities) {\n console.log(` - ${responsibility}`);\n }\n }\n });\n}\n","import type { Command } from \"commander\";\nimport { TaskError } from \"../../errors/index.js\";\nimport { createTaskEngine } from \"../../tasks/index.js\";\nimport type { Task } from \"../../types/task.js\";\nimport { registerTaskInspect } from \"./inspect.js\";\nimport { exitCodeForStatus } from \"../exit-codes.js\";\nimport { loadProjectConfig } from \"../options.js\";\nconst collectFiles = (value: string, previous: string[]): string[] => [...previous, value];\n\nexport function registerTaskCommands(program: Command): void {\n const task = program\n .command(\"task\")\n .description(\"Create, run and inspect tasks (§13).\");\n\n task\n .command(\"create <objective>\")\n .description(\"Create a task. Assign a role and/or agent; run it with `omninode task run`.\")\n .option(\"-r, --role <roleId>\", \"Role id from project.roles (validated at creation).\")\n .option(\"-a, --agent <name>\", \"Agent name from project.agents (validated at creation).\")\n .option(\"-f, --file <path>\", \"File or glob relevant to the task (repeatable).\", collectFiles)\n .action(async (objective: string, options: { role?: string; agent?: string; file?: string[] }) => {\n const config = loadProjectConfig();\n const engine = createTaskEngine(config);\n const created = await engine.create({\n objective,\n project: config.project.name,\n ...(options.role !== undefined ? { role: options.role } : {}),\n ...(options.agent !== undefined ? { agent: options.agent } : {}),\n ...(options.file !== undefined && options.file.length > 0\n ? { context: { files: options.file } }\n : {}),\n });\n console.log(`Created task ${created.id} (${created.status})`);\n console.log(` objective: ${created.objective}`);\n if (created.role) console.log(` role: ${created.role}`);\n if (created.agent) console.log(` agent: ${created.agent}`);\n if (created.context?.files) console.log(` files: ${created.context.files.join(\", \")}`);\n console.log(`Run \\`omninode task run ${created.id}\\` to execute it.`);\n });\n\n task\n .command(\"run <task-id>\")\n .description(\"Run a task through its assigned agent.\")\n .action(async (taskId: string) => {\n const config = loadProjectConfig();\n const engine = createTaskEngine(config);\n console.log(`Running task ${taskId}...`);\n const finished = await engine.run(taskId);\n printOutcome(finished);\n process.exitCode = exitCodeForStatus(finished.status);\n });\n\n task\n .command(\"status <task-id>\")\n .description(\"Show task details and current status.\")\n .action(async (taskId: string) => {\n const config = loadProjectConfig();\n const engine = createTaskEngine(config);\n const found = await engine.get(taskId);\n if (!found) {\n throw new TaskError(\n \"TASK_NOT_FOUND\",\n `Task \"${taskId}\" does not exist in this project's task store.`,\n );\n }\n printOutcome(found, { verbose: true });\n });\n\n task\n .command(\"list\")\n .description(\"List tasks in the project's task store.\")\n .option(\"-s, --status <status>\", \"Filter by status (created, queued, running, completed, failed, cancelled).\")\n .option(\"--json\", \"Emit tasks as JSON.\")\n .action(async (options: { status?: string; json?: boolean }) => {\n const config = loadProjectConfig();\n const engine = createTaskEngine(config);\n const tasks = await engine.list(\n options.status !== undefined ? { status: options.status as Task[\"status\"] } : {},\n );\n if (options.json) {\n console.log(JSON.stringify(tasks, null, 2));\n return;\n }\n if (tasks.length === 0) {\n console.log(\"No tasks found. Create one with `omninode task create`.\");\n return;\n }\n for (const t of tasks) {\n console.log(`${t.id} ${t.status.padEnd(10)} ${truncate(t.objective, 60)}`);\n }\n });\n\n task\n .command(\"cancel <task-id>\")\n .description(\"Cancel a task that has not finished yet.\")\n .action(async (taskId: string) => {\n const config = loadProjectConfig();\n const engine = createTaskEngine(config);\n const cancelled = await engine.cancel(taskId);\n console.log(`Task ${cancelled.id} is now \"${cancelled.status}\".`);\n });\n\n task\n .command(\"retry <task-id>\")\n .description(\"Reset a failed, timed out, unknown or cancelled task to created; combine with --run to execute it again.\")\n .option(\"--run\", \"Run the task again immediately after resetting it.\")\n .action(async (taskId: string, options: { run?: boolean }) => {\n const config = loadProjectConfig();\n const engine = createTaskEngine(config);\n const reset = await engine.retry(taskId);\n console.log(`Task ${reset.id} reset to \"${reset.status}\".`);\n if (!options.run) return;\n console.log(`Running task ${reset.id}...`);\n const finished = await engine.run(reset.id);\n printOutcome(finished);\n process.exitCode = exitCodeForStatus(finished.status);\n });\n registerTaskInspect(task);\n}\n\nfunction printOutcome(task: Task, options: { verbose?: boolean } = {}): void {\n console.log(` id: ${task.id}`);\n console.log(` status: ${task.status}`);\n console.log(` created: ${task.createdAt}`);\n if (options.verbose) {\n console.log(` project: ${task.project ?? \"(none)\"}`);\n if (task.role) console.log(` role: ${task.role}`);\n if (task.agent) console.log(` agent: ${task.agent}`);\n if (task.context?.files) console.log(` files: ${task.context.files.join(\", \")}`);\n console.log(` objective: ${task.objective}`);\n }\n if (options.verbose && task.attempt > 0) {\n console.log(` attempt: ${task.attempt}`);\n }\n if (task.lastError) console.log(` error: ${task.lastError}`);\n if (options.verbose && task.executions && task.executions.length > 0) {\n console.log(\n ` executions: ${task.executions\n .map((e) => `#${e.attempt}:${e.outcome}`)\n .join(\", \")}`,\n );\n }\n const result = task.result;\n if (!result) return;\n if (result.summary) console.log(` summary: ${result.summary}`);\n if (result.reports && result.reports.length > 0) {\n console.log(` reports: ${result.reports.length} structured report(s)`);\n }\n if (result.error) console.log(` error: ${result.error}`);\n if (result.finishedAt) console.log(` ended: ${result.finishedAt}`);\n}\n\nfunction truncate(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n","/**\n * Report aggregation (§17): normalizes formats, groups duplicate and similar\n * findings, preserves source attribution, and produces one CombinedReport.\n * Grouping uses deterministic token-set similarity so results are testable.\n */\nimport { randomBytes } from \"node:crypto\";\nimport type {\n AggregatedFinding,\n AggregatedRecommendation,\n CombinedReport,\n Confidence,\n ConflictPosition,\n Finding,\n FindingSeverity,\n FindingSource,\n Report,\n ReportConflict,\n} from \"../types/report.js\";\nimport { normalizeEvidence } from \"./schema.js\";\n\nconst SEVERITY_RANK: Record<FindingSeverity, number> = {\n info: 0,\n low: 1,\n medium: 2,\n high: 3,\n critical: 4,\n};\n\nexport interface AggregateOptions {\n objective?: string;\n pipelineRunId?: string;\n taskIds?: string[];\n /** Token-set Jaccard similarity above which findings are merged. */\n similarityThreshold?: number;\n}\n\nexport function aggregateReports(reports: Report[], options: AggregateOptions = {}): CombinedReport {\n const threshold = options.similarityThreshold ?? 0.7;\n\n const findingGroups: AggregatedFinding[] = [];\n const recommendationGroups: AggregatedRecommendation[] = [];\n\n for (const report of reports) {\n for (const finding of report.findings) {\n mergeFinding(findingGroups, finding, report, threshold);\n }\n for (const text of report.recommendations) {\n mergeRecommendation(recommendationGroups, text, report, threshold);\n }\n }\n\n const sources = [...new Set(reports.map((r) => r.agent))].sort();\n const totalRawFindings = reports.reduce((sum, r) => sum + r.findings.length, 0);\n const conflicts = detectConflicts(findingGroups);\n // Agreement = independently reported by 2+ agents with the same severity.\n const agreements = findingGroups.filter(\n (group) =>\n group.sources.length > 1 &&\n group.severity !== undefined &&\n new Set(Object.values(group.severityBySource ?? {})).size === 1,\n );\n const disputed = conflicts.length;\n const summary =\n `${reports.length} report(s) from ${sources.length > 0 ? sources.join(\", \") : \"no agents\"}: ` +\n `${findingGroups.length} unique finding group(s) (${totalRawFindings} raw), ` +\n `${agreements.length} agreement(s), ${disputed} conflict(s), ` +\n `${recommendationGroups.length} recommendation group(s).`;\n\n return {\n id: `combined-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`,\n title: options.objective !== undefined ? truncate(options.objective, 120) : \"Combined report\",\n ...(options.objective !== undefined ? { objective: options.objective } : {}),\n ...(options.pipelineRunId !== undefined ? { pipelineRunId: options.pipelineRunId } : {}),\n taskIds: options.taskIds ?? [],\n summary,\n findings: findingGroups.sort((a, b) => rank(b) - rank(a)),\n agreements,\n conflicts,\n recommendations: recommendationGroups,\n sources,\n reportIds: reports.map((r) => r.id),\n createdAt: new Date().toISOString(),\n metadata: {\n agents: sources.length,\n reports: reports.length,\n rawFindings: totalRawFindings,\n findingGroups: findingGroups.length,\n agreements: agreements.length,\n conflicts: conflicts.length,\n },\n };\n}\n\nfunction rankConfidence(confidence: Confidence | undefined): number {\n return confidence ? { low: 1, medium: 2, high: 3 }[confidence] : 0;\n}\n\n/**\n * Conflict detection (§14): agents disagreeing about the same finding is a\n * first-class result. Both positions are preserved — OmniNode never silently\n * chooses one.\n */\nexport function detectConflicts(groups: AggregatedFinding[]): ReportConflict[] {\n const conflicts: ReportConflict[] = [];\n for (const group of groups) {\n if (group.sources.length < 2) continue;\n\n const severities = new Set(Object.values(group.severityBySource ?? {}));\n if (severities.size > 1) {\n conflicts.push({\n type: \"severity\",\n findingTitle: group.title,\n positions: group.sources.map((source) => position(source, group)),\n note:\n `Agents disagree on severity (${[...severities].sort((a, b) => SEVERITY_RANK[a] - SEVERITY_RANK[b]).join(\", \")}); ` +\n `the highest severity is shown, every position is preserved.`,\n });\n }\n\n const recommendations = (group.recommendations ?? []).filter((r) => r.length > 0);\n if (recommendations.length > 1) {\n conflicts.push({\n type: \"recommendation\",\n findingTitle: group.title,\n positions: group.sources.map((source) => position(source, group)),\n note: `Agents proposed ${recommendations.length} different fixes; none was discarded.`,\n });\n }\n }\n return conflicts;\n}\n\nfunction position(\n source: FindingSource,\n group: AggregatedFinding,\n): ConflictPosition {\n return {\n agent: source.agent,\n reportId: source.reportId,\n ...(group.severityBySource?.[source.agent] !== undefined\n ? { severity: group.severityBySource[source.agent] }\n : {}),\n ...(group.confidenceBySource?.[source.agent] !== undefined\n ? { confidence: group.confidenceBySource[source.agent] }\n : {}),\n ...(group.recommendations?.[0] !== undefined ? { recommendation: group.recommendations[0] } : {}),\n };\n}\n\nfunction rank(finding: AggregatedFinding): number {\n return finding.severity ? SEVERITY_RANK[finding.severity] : -1;\n}\n\nfunction mergeFinding(groups: AggregatedFinding[], finding: Finding, report: Report, threshold: number): void {\n const source: FindingSource = { agent: report.agent, reportId: report.id };\n const group = groups.find((g) => similar(g.title, finding.title, threshold));\n if (group) {\n group.occurrences += 1;\n group.details.push(finding.detail);\n group.sources.push(source);\n group.evidence.push(...(normalizeEvidence(finding.evidence) ?? []));\n if (finding.severity && (!group.severity || SEVERITY_RANK[finding.severity] > SEVERITY_RANK[group.severity])) {\n group.severity = finding.severity;\n }\n // Confidence preservation (§14): keep the strongest, and record per source.\n if (finding.confidence && rankConfidence(finding.confidence) > rankConfidence(group.confidence)) {\n group.confidence = finding.confidence;\n }\n if (finding.severity) {\n group.severityBySource = { ...group.severityBySource, [report.agent]: finding.severity };\n }\n if (finding.confidence) {\n group.confidenceBySource = { ...group.confidenceBySource, [report.agent]: finding.confidence };\n }\n if (finding.recommendation && !group.recommendations?.includes(finding.recommendation)) {\n group.recommendations = [...(group.recommendations ?? []), finding.recommendation];\n }\n return;\n }\n groups.push({\n title: finding.title,\n details: [finding.detail],\n sources: [source],\n occurrences: 1,\n ...(finding.severity ? { severity: finding.severity } : {}),\n ...(finding.confidence ? { confidence: finding.confidence } : {}),\n ...(finding.severity ? { severityBySource: { [report.agent]: finding.severity } } : {}),\n ...(finding.confidence ? { confidenceBySource: { [report.agent]: finding.confidence } } : {}),\n ...(finding.recommendation ? { recommendations: [finding.recommendation] } : {}),\n evidence: [...(normalizeEvidence(finding.evidence) ?? [])],\n });\n}\n\nfunction mergeRecommendation(\n groups: AggregatedRecommendation[],\n text: string,\n report: Report,\n threshold: number,\n): void {\n const source: FindingSource = { agent: report.agent, reportId: report.id };\n const group = groups.find((g) => similar(g.text, text, threshold));\n if (group) {\n group.occurrences += 1;\n group.sources.push(source);\n return;\n }\n groups.push({ text, sources: [source], occurrences: 1 });\n}\n\nexport function similar(a: string, b: string, threshold: number): boolean {\n const left = tokens(a);\n const right = tokens(b);\n if (left.size === 0 || right.size === 0) return false;\n let intersection = 0;\n for (const token of left) {\n if (right.has(token)) intersection += 1;\n }\n const union = left.size + right.size - intersection;\n return intersection / union >= threshold;\n}\n\nfunction tokens(text: string): Set<string> {\n return new Set(\n text\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, \" \")\n .split(/\\s+/)\n .filter((t) => t.length >= 3),\n );\n}\n\nfunction truncate(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n","/**\n * Report validation and normalization (roadmap §13, Report Validation).\n *\n * Reports are machine-readable objects: they are schema-validated before they\n * can enter aggregation, and legacy string evidence / `detail` fields are\n * normalized into the v2 shape on the way in.\n */\nimport { z } from \"zod\";\nimport type { Confidence, Evidence, EvidenceInput, Finding, Report } from \"../types/report.js\";\n\nconst evidenceSchema = z.union([\n z.string().transform((excerpt): Evidence => ({ kind: \"observation\", excerpt })),\n z.object({\n kind: z.enum([\"file\", \"line\", \"url\", \"command\", \"observation\", \"artifact\"]),\n ref: z.string().optional(),\n line: z.number().int().optional(),\n excerpt: z.string().optional(),\n agent: z.string().optional(),\n }),\n]);\n\nconst findingSchema = z.object({\n id: z.string().min(1),\n title: z.string().min(1),\n detail: z.string().default(\"\"),\n description: z.string().optional(),\n severity: z.enum([\"info\", \"low\", \"medium\", \"high\", \"critical\"]).optional(),\n confidence: z.enum([\"low\", \"medium\", \"high\"]).optional(),\n severityBySource: z.record(z.enum([\"info\", \"low\", \"medium\", \"high\", \"critical\"])).optional(),\n confidenceBySource: z.record(z.enum([\"low\", \"medium\", \"high\"])).optional(),\n recommendations: z.array(z.string()).optional(),\n evidence: z.array(evidenceSchema).optional(),\n location: z.string().optional(),\n tags: z.array(z.string()).optional(),\n source: z.object({ agent: z.string().optional(), reportId: z.string().optional(), pipelineRunId: z.string().optional() }).optional(),\n recommendation: z.string().optional(),\n});\n\nconst artifactSchema = z.object({\n kind: z.enum([\"file\", \"patch\", \"log\", \"screenshot\", \"document\", \"data\"]),\n ref: z.string().min(1),\n description: z.string().optional(),\n mediaType: z.string().optional(),\n bytes: z.number().int().optional(),\n});\n\nconst reportSchema = z.object({\n id: z.string().min(1),\n taskId: z.string().min(1),\n agent: z.string().min(1),\n agentId: z.string().optional(),\n pipelineRunId: z.string().optional(),\n model: z.string().optional(),\n summary: z.string(),\n findings: z.array(findingSchema),\n recommendations: z.array(z.string()),\n confidence: z.enum([\"low\", \"medium\", \"high\"]).optional(),\n evidence: z.array(evidenceSchema).optional(),\n artifacts: z.array(artifactSchema).optional(),\n createdAt: z.string().min(1),\n metadata: z.record(z.unknown()).optional(),\n});\n\nexport interface ReportValidationIssue {\n path: string;\n message: string;\n}\n\nexport type ReportValidationResult =\n | { valid: true; report: Report }\n | { valid: false; issues: ReportValidationIssue[]; reason: string };\n\n/** Validates (and normalizes) a report; malformed reports are rejected. */\nexport function validateReport(value: unknown): ReportValidationResult {\n const parsed = reportSchema.safeParse(value);\n if (!parsed.success) {\n const issues = parsed.error.issues.map((issue) => ({\n path: issue.path.join(\".\") || \"(root)\",\n message: issue.message,\n }));\n return {\n valid: false,\n issues,\n reason: `report failed schema validation (${issues.length} issue(s))`,\n };\n }\n const report = parsed.data as Report;\n // Cross-field normalization: description mirrors detail, source carries provenance.\n report.findings = report.findings.map((finding) => ({\n ...finding,\n description: finding.description ?? finding.detail,\n ...(finding.source === undefined\n ? { source: { agent: report.agent, reportId: report.id, ...(report.pipelineRunId !== undefined ? { pipelineRunId: report.pipelineRunId } : {}) } }\n : {}),\n }));\n return { valid: true, report };\n}\n\n/** Normalizes evidence entries (strings or objects) to typed evidence. */\nexport function normalizeEvidence(input: EvidenceInput[] | undefined): Evidence[] | undefined {\n if (input === undefined) return undefined;\n return input.map((item) =>\n typeof item === \"string\" ? { kind: \"observation\" as const, excerpt: item } : item,\n );\n}\n\nexport function normalizeFinding(finding: Finding): Finding {\n return {\n ...finding,\n description: finding.description ?? finding.detail,\n evidence: normalizeEvidence(finding.evidence),\n };\n}\n\nexport type { Confidence };","/**\n * Report normalization (§17): turns an agent's text output into a structured\n * Report by extracting findings, recommendations and evidence from\n * markdown-style sections. Deterministic heuristics; AI-assisted extraction\n * can layer on top later via the planner.\n */\nimport type { Finding, FindingSeverity, Report } from \"../types/report.js\";\n\nexport interface ExtractionMeta {\n taskId: string;\n agent: string;\n model?: string;\n}\n\nconst BULLET = /^(?:[-*•]|\\d+[.)])\\s+(.*)$/;\n\ninterface Section {\n heading: string;\n bullets: string[];\n}\n\nfunction parseSections(raw: string): Section[] {\n const sections: Section[] = [];\n let current: Section = { heading: \"\", bullets: [] };\n for (const line of raw.split(\"\\n\")) {\n const heading = /^(#{1,6})\\s+(.*)$/.exec(line.trim());\n if (heading) {\n if (current.heading.length > 0 || current.bullets.length > 0) {\n sections.push(current);\n }\n current = { heading: heading[2]?.toLowerCase() ?? \"\", bullets: [] };\n continue;\n }\n const bullet = BULLET.exec(line.trim());\n if (bullet && current.heading.length > 0) {\n current.bullets.push(bullet[1]?.trim() ?? \"\");\n }\n }\n if (current.heading.length > 0 || current.bullets.length > 0) {\n sections.push(current);\n }\n return sections;\n}\n\nfunction collectBullets(sections: Section[], patterns: RegExp[]): string[] {\n const matches = sections.filter((section) => patterns.some((p) => p.test(section.heading)));\n return matches.flatMap((section) => section.bullets).filter((b) => b.length > 0);\n}\n\nfunction guessSeverity(text: string): FindingSeverity | undefined {\n if (/critical|severe/i.test(text)) return \"critical\";\n if (/\\bhigh\\b|major/i.test(text)) return \"high\";\n if (/medium|moderate/i.test(text)) return \"medium\";\n if (/\\blow\\b|minor/i.test(text)) return \"low\";\n return undefined;\n}\n\nexport function extractReportFromText(raw: string, meta: ExtractionMeta): Report {\n const trimmed = raw.trim();\n const nonEmpty = trimmed\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n // Prefer a prose line over markdown headings/bullets for the summary.\n const proseLine =\n nonEmpty.find((line) => !line.startsWith(\"#\") && !BULLET.test(line)) ?? nonEmpty[0] ?? \"\";\n const cleaned = proseLine.replace(/^#{1,6}\\s+/, \"\").replace(BULLET, \"$1\");\n const summary = cleaned.length > 0 ? truncate(cleaned, 200) : \"(no output)\";\n\n const sections = parseSections(trimmed);\n const findingTexts = collectBullets(sections, [/finding/, /issue/, /problem/, /vulnerab/]);\n const recommendationTexts = collectBullets(sections, [/recommend/, /suggestion/, /next step/, /action/]);\n const evidenceTexts = collectBullets(sections, [/evidence/, /proof/, /log/]);\n\n const findings: Finding[] = findingTexts.map((text, index) => ({\n id: `${meta.taskId}-f-${index + 1}`,\n title: truncate(text, 120),\n detail: text,\n description: text,\n severity: guessSeverity(text),\n }));\n\n return {\n id: `${meta.taskId}-report`,\n taskId: meta.taskId,\n agent: meta.agent,\n ...(meta.model !== undefined ? { model: meta.model } : {}),\n summary,\n findings,\n recommendations: recommendationTexts.map((t) => truncate(t, 200)),\n ...(evidenceTexts.length > 0\n ? { evidence: evidenceTexts.map((excerpt) => ({ kind: \"observation\" as const, excerpt })) }\n : {}),\n metadata: evidenceTexts.length > 0 ? { evidenceCount: evidenceTexts.length } : undefined,\n createdAt: new Date().toISOString(),\n };\n}\n\nfunction truncate(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n","/**\n * Report service (§16–§17): collects reports from finished tasks (structured\n * protocol reports when present, extraction from text otherwise), persists\n * them with source attribution and generates combined reports.\n */\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { Task } from \"../types/task.js\";\nimport type { Report, CombinedReport } from \"../types/report.js\";\nimport { aggregateReports, type AggregateOptions } from \"./aggregate.js\";\nimport { extractReportFromText } from \"./extract.js\";\nimport { validateReport } from \"./schema.js\";\nimport type { ReportStore } from \"./store.js\";\n\nexport interface CombinedMeta {\n objective?: string;\n pipelineRunId?: string;\n taskIds?: string[];\n}\n\n/** Serialized size budget for a single report (roadmap §17 — output limits). */\nexport const MAX_REPORT_BYTES = 256 * 1024;\n\nexport interface CollectionDiagnostics {\n collected: number;\n accepted: number;\n rejected: Array<{ key: string; reason: string; issues: string[] }>;\n}\n\nexport class ReportService {\n private readonly log: Logger;\n /** Rejected reports from the last collection (§13 — malformed never enters aggregation). */\n lastDiagnostics: CollectionDiagnostics = { collected: 0, accepted: 0, rejected: [] };\n\n constructor(\n private readonly store: ReportStore,\n log: Logger = logger,\n ) {\n this.log = log.child({ component: \"reports\" });\n }\n\n get storeRef(): ReportStore {\n return this.store;\n }\n\n /** Normalizes finished tasks into reports (§17 — normalizer), validating each\n * one so malformed reports never reach aggregation (§13). */\n async collectFromTasks(tasks: Task[]): Promise<Report[]> {\n const candidates: Report[] = [];\n for (const task of tasks) {\n const structured = task.result?.reports ?? [];\n if (structured.length > 0) {\n candidates.push(...structured);\n continue;\n }\n const text = task.result?.rawOutput ?? task.result?.summary ?? \"\";\n if (text.trim().length === 0) continue;\n candidates.push(\n extractReportFromText(text, {\n taskId: task.id,\n agent: task.agent ?? \"unknown\",\n }),\n );\n }\n\n const reports: Report[] = [];\n const rejected: CollectionDiagnostics[\"rejected\"] = [];\n for (const candidate of candidates) {\n const size = Buffer.byteLength(JSON.stringify(candidate), \"utf8\");\n if (size > MAX_REPORT_BYTES) {\n rejected.push({\n key: (candidate as { id?: string })?.id ?? \"(unknown)\",\n reason: `report exceeds the ${MAX_REPORT_BYTES} byte limit (${size} bytes)`,\n issues: [],\n });\n this.log.warn(`Rejected oversized report (${size} bytes).`);\n continue;\n }\n const result = validateReport(candidate);\n if (result.valid) {\n reports.push(result.report);\n } else {\n rejected.push({\n key: (candidate as { id?: string })?.id ?? \"(unknown)\",\n reason: result.reason,\n issues: result.issues.map((issue) => `${issue.path}: ${issue.message}`),\n });\n this.log.warn(`Rejected malformed report: ${result.reason}`);\n }\n }\n this.lastDiagnostics = { collected: candidates.length, accepted: reports.length, rejected };\n return reports;\n }\n\n async saveReports(reports: Report[]): Promise<void> {\n if (reports.length === 0) return;\n await this.store.saveReports(reports);\n this.log.info(`Stored ${reports.length} report(s).`);\n }\n\n async generateCombined(reports: Report[], meta: CombinedMeta = {}): Promise<CombinedReport | undefined> {\n if (reports.length === 0) return undefined;\n const options: AggregateOptions = {\n ...(meta.objective !== undefined ? { objective: meta.objective } : {}),\n ...(meta.pipelineRunId !== undefined ? { pipelineRunId: meta.pipelineRunId } : {}),\n ...(meta.taskIds !== undefined ? { taskIds: meta.taskIds } : {}),\n };\n const combined = aggregateReports(reports, options);\n await this.store.saveCombined(combined);\n this.log.info(`Generated combined report ${combined.id}.`);\n return combined;\n }\n}\n","/**\n * Report persistence (§16 — report storage). Same replaceable-store and\n * serialized-write patterns as the other local stores.\n */\nimport { JsonFileStore } from \"../persistence/json-file-store.js\";\nimport type { CombinedReport, Report } from \"../types/report.js\";\n\nexport interface ReportFilter {\n taskId?: string;\n agent?: string;\n}\n\nexport interface CombinedReportFilter {\n pipelineRunId?: string;\n}\n\nexport interface ReportStore {\n saveReports(reports: Report[]): Promise<void>;\n listReports(filter?: ReportFilter): Promise<Report[]>;\n saveCombined(combined: CombinedReport): Promise<void>;\n getCombined(id: string): Promise<CombinedReport | undefined>;\n listCombined(filter?: CombinedReportFilter): Promise<CombinedReport[]>;\n}\n\ntype StoreEntry = { kind: \"report\"; report: Report } | { kind: \"combined\"; combined: CombinedReport };\n\nexport class FileReportStore extends JsonFileStore<StoreEntry> implements ReportStore {\n constructor(directory?: string) {\n super({ ...(directory !== undefined ? { directory } : {}), fileName: \"reports.json\" });\n }\n\n async saveReports(reports: Report[]): Promise<void> {\n await this.mutate((entries) => {\n for (const report of reports) {\n const index = entries.findIndex((e) => e.kind === \"report\" && e.report.id === report.id);\n const entry: StoreEntry = { kind: \"report\", report };\n if (index >= 0) entries[index] = entry;\n else entries.push(entry);\n }\n return [entries, undefined];\n });\n }\n\n async listReports(filter: ReportFilter = {}): Promise<Report[]> {\n return (await this.readAll())\n .filter((e): e is { kind: \"report\"; report: Report } => e.kind === \"report\")\n .map((e) => e.report)\n .filter((report) => (filter.taskId ? report.taskId === filter.taskId : true))\n .filter((report) => (filter.agent ? report.agent === filter.agent : true))\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n }\n\n async saveCombined(combined: CombinedReport): Promise<void> {\n await this.mutate((entries) => {\n const index = entries.findIndex((e) => e.kind === \"combined\" && e.combined.id === combined.id);\n const entry: StoreEntry = { kind: \"combined\", combined };\n if (index >= 0) entries[index] = entry;\n else entries.push(entry);\n return [entries, undefined];\n });\n }\n\n async getCombined(id: string): Promise<CombinedReport | undefined> {\n const found = (await this.readAll()).find((e) => e.kind === \"combined\" && e.combined.id === id);\n return found?.kind === \"combined\" ? found.combined : undefined;\n }\n\n async listCombined(filter: CombinedReportFilter = {}): Promise<CombinedReport[]> {\n return (await this.readAll())\n .filter((e): e is { kind: \"combined\"; combined: CombinedReport } => e.kind === \"combined\")\n .map((e) => e.combined)\n .filter((combined) => (filter.pipelineRunId ? combined.pipelineRunId === filter.pipelineRunId : true))\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n }\n}\n","import type { Command } from \"commander\";\nimport { OmniNodeError } from \"../../errors/index.js\";\nimport { ReportService } from \"../../reports/index.js\";\nimport { FileReportStore } from \"../../reports/store.js\";\nimport { truncate } from \"./shared.js\";\n\nfunction service(): ReportService {\n return new ReportService(new FileReportStore());\n}\n\nexport function registerReportCommands(program: Command): void {\n const report = program\n .command(\"report\")\n .description(\"Inspect AI reports collected from tasks and pipelines (§16–§17).\");\n\n report\n .command(\"list\")\n .description(\"List stored reports.\")\n .option(\"--task <taskId>\", \"Only reports for this task.\")\n .option(\"--agent <name>\", \"Only reports from this agent.\")\n .option(\"--json\", \"Emit reports as JSON.\")\n .action(async (options: { task?: string; agent?: string; json?: boolean }) => {\n const svc = service();\n const reports = await svc.storeRef.listReports({\n ...(options.task !== undefined ? { taskId: options.task } : {}),\n ...(options.agent !== undefined ? { agent: options.agent } : {}),\n });\n if (options.json) {\n console.log(JSON.stringify(reports, null, 2));\n return;\n }\n if (reports.length === 0) {\n console.log(\"No reports stored yet. Run a pipeline to collect some.\");\n return;\n }\n for (const r of reports) {\n console.log(`${r.id} ${r.agent.padEnd(10)} ${truncate(r.summary, 60)}`);\n }\n });\n\n report\n .command(\"combined\")\n .description(\"List combined reports (aggregated intelligence, §17).\")\n .option(\"--run <pipelineRunId>\", \"Only combined reports for this pipeline run.\")\n .option(\"--json\", \"Emit combined reports as JSON.\")\n .action(async (options: { run?: string; json?: boolean }) => {\n const svc = service();\n const combined = await svc.storeRef.listCombined({\n ...(options.run !== undefined ? { pipelineRunId: options.run } : {}),\n });\n if (options.json) {\n console.log(JSON.stringify(combined, null, 2));\n return;\n }\n if (combined.length === 0) {\n console.log(\"No combined reports stored yet. Run a pipeline to generate one.\");\n return;\n }\n for (const c of combined) {\n const conflicts = c.conflicts.length > 0 ? ` ${c.conflicts.length} CONFLICT(S)` : \"\";\n console.log(\n `${c.id} ${c.findings.length} finding(s) from ${c.sources.length} source(s)` +\n `${conflicts}${c.pipelineRunId ? ` run=${c.pipelineRunId}` : \"\"}`,\n );\n }\n });\n\n report\n .command(\"show <id>\")\n .description(\"Show a stored report or combined report in full.\")\n .action(async (id: string) => {\n const svc = service();\n const reports = await svc.storeRef.listReports();\n const raw = reports.find((r) => r.id === id);\n if (raw) {\n console.log(`Report ${raw.id}`);\n console.log(` agent: ${raw.agent}${raw.model ? ` (${raw.model})` : \"\"}`);\n console.log(` task: ${raw.taskId}`);\n console.log(` summary: ${raw.summary}`);\n if (raw.findings.length > 0) {\n console.log(\" findings:\");\n for (const finding of raw.findings) {\n console.log(` - [${finding.severity ?? \"info\"}] ${finding.title}`);\n for (const evidence of finding.evidence ?? []) {\n console.log(` evidence: ${evidence}`);\n }\n }\n }\n if (raw.recommendations.length > 0) {\n console.log(\" recommendations:\");\n for (const recommendation of raw.recommendations) {\n console.log(` - ${recommendation}`);\n }\n }\n return;\n }\n\n const combined = await svc.storeRef.getCombined(id);\n if (combined) {\n console.log(`Combined report ${combined.id}`);\n console.log(` sources: ${combined.sources.join(\", \")}`);\n console.log(` reports: ${combined.reportIds.length}`);\n if (combined.pipelineRunId) console.log(` run: ${combined.pipelineRunId}`);\n console.log(` summary: ${combined.summary}`);\n if (combined.conflicts.length > 0) {\n console.log(` CONFLICTS (${combined.conflicts.length}) — both positions preserved:`);\n for (const conflict of combined.conflicts) {\n console.log(` ! ${conflict.findingTitle} [${conflict.type}]`);\n for (const position of conflict.positions) {\n console.log(\n ` ${position.agent}: severity=${position.severity ?? \"unstated\"}` +\n `${position.recommendation ? ` fix=\"${position.recommendation}\"` : \"\"}`,\n );\n }\n console.log(` ${conflict.note}`);\n }\n }\n if (combined.agreements.length > 0) {\n console.log(` agreements: ${combined.agreements.length} (multi-agent consensus)`);\n }\n if (combined.findings.length > 0) {\n console.log(\" findings (grouped, duplicates merged):\");\n for (const finding of combined.findings) {\n console.log(\n ` - [${finding.severity ?? \"info\"}] ${finding.title} (x${finding.occurrences}, sources: ${finding.sources.map((s) => s.agent).join(\", \")})`,\n );\n }\n }\n if (combined.recommendations.length > 0) {\n console.log(\" recommendations:\");\n for (const recommendation of combined.recommendations) {\n console.log(` - ${recommendation.text} (x${recommendation.occurrences})`);\n }\n }\n return;\n }\n\n throw new OmniNodeError(\"REPORT_NOT_FOUND\", `Report \"${id}\" was not found in the report store.`);\n });\n}\n","import type { Command } from \"commander\";\nimport { readFileSync, writeFileSync } from \"node:fs\";\nimport { parseDocument } from \"yaml\";\nimport { appConfigSchema, loadConfig, pipelineConfigSchema } from \"../../config/index.js\";\nimport { OmniNodeError } from \"../../errors/index.js\";\nimport { PipelineError } from \"../../errors/index.js\";\nimport { buildPipelineEngine } from \"../../pipelines/index.js\";\nimport type { PipelineDefinition } from \"../../types/pipeline.js\";\nimport { registerPipelineInspect } from \"./inspect.js\";\nimport { exitCodeForStatus } from \"../exit-codes.js\";\nimport { loadProjectConfig, activeConfigPath } from \"../options.js\";\nexport function registerPipelineCommands(program: Command): void {\n const pipeline = program\n .command(\"pipeline\")\n .description(\"Run multi-step AI pipelines defined in omninode.yaml (§14).\");\n\n pipeline\n .command(\"list\")\n .description(\"List configured pipelines.\")\n .option(\"--json\", \"Emit pipelines as JSON.\")\n .action(async (options: { json?: boolean }) => {\n const config = loadProjectConfig();\n const pipelines = config.project.pipelines;\n if (options.json) {\n console.log(JSON.stringify(config.project.pipelines, null, 2));\n return;\n }\n if (pipelines.length === 0) {\n console.log(\"No pipelines configured. Add one under `project.pipelines` in omninode.yaml.\");\n return;\n }\n for (const def of pipelines) {\n const name = def.name ? ` ${def.name}` : \"\";\n console.log(`${def.id}${name} ${def.steps.length} step(s)`);\n }\n });\n\n pipeline\n .command(\"run <id> [objective]\")\n .description(\n \"Run a pipeline. The objective argument overrides the definition's default objective.\",\n )\n .action(async (id: string, objective: string | undefined) => runPipelineAction(id, objective));\n\n pipeline\n .command(\"retry <run-id> [objective]\")\n .description(\n \"Error recovery: re-run a recorded pipeline run as a new run, reusing its objective.\",\n )\n .action(async (runId: string, objective: string | undefined) => {\n const config = loadProjectConfig();\n const engine = buildPipelineEngine(config);\n const previous = await engine.get(runId);\n if (!previous) {\n throw new PipelineError(\n \"PIPELINE_NOT_FOUND\",\n `Pipeline run \"${runId}\" does not exist in this project's run store.`,\n );\n }\n const def = config.project.pipelines.find((p) => p.id === previous.pipelineId);\n if (!def) {\n throw new PipelineError(\n \"PIPELINE_NOT_FOUND\",\n `Pipeline \"${previous.pipelineId}\" (run ${runId}) is no longer configured in omninode.yaml.`,\n );\n }\n await runPipelineAction(def.id, objective ?? previous.objective);\n });\n\n pipeline\n .command(\"cancel <run-id>\")\n .description(\"Request cancellation of a pipeline run (stops scheduling and cancels running tasks).\")\n .action(async (runId: string) => {\n const config = loadProjectConfig();\n const engine = buildPipelineEngine(config);\n await engine.cancel(runId);\n console.log(`Cancellation requested for run ${runId}.`);\n console.log(\"A run executing in another process stops at its next check point.\");\n });\n\n pipeline\n .command(\"create <id>\")\n .description(\"Create a pipeline from a YAML/JSON file and append it to omninode.yaml.\")\n .requiredOption(\"--from <file>\", \"File containing { objective?, steps: [...] } (YAML or JSON).\")\n .action(async (id: string, options: { from: string }) => {\n await createPipelineFromFile(id, options.from);\n });\n\n pipeline\n .command(\"validate <id>\")\n .description(\"Validate a pipeline definition before running it (§9.5).\")\n .action(async (id: string) => {\n const config = loadProjectConfig();\n const def = findPipeline(config, id);\n const engine = buildPipelineEngine(config);\n engine.validate(def);\n console.log(`Pipeline \"${def.id}\" is valid (${def.steps.length} step(s)).`);\n for (const step of def.steps) {\n const deps = step.dependsOn?.join(\", \") ?? \"(previous step)\";\n console.log(` ${step.id} kind=${step.kind} depends_on=${deps}`);\n }\n });\n\n pipeline\n .command(\"runs <id>\")\n .description(\"List recorded runs of a pipeline.\")\n .action(async (id: string) => {\n const config = loadProjectConfig();\n const engine = buildPipelineEngine(config);\n const runs = await engine.listRuns({ pipelineId: id });\n if (runs.length === 0) {\n console.log(`No recorded runs for pipeline \"${id}\".`);\n return;\n }\n for (const run of runs) {\n const note = isInterrupted(run) ? \" (interrupted — process gone before finish)\" : \"\";\n console.log(`${run.id} ${run.status.padEnd(10)} ${run.startedAt ?? \"?\"}${note}`);\n }\n });\n\n pipeline\n .command(\"status <run-id>\")\n .description(\"Show the recorded state of a pipeline run.\")\n .action(async (runId: string) => {\n const config = loadProjectConfig();\n const engine = buildPipelineEngine(config);\n const run = await engine.get(runId);\n if (!run) {\n throw new PipelineError(\n \"PIPELINE_NOT_FOUND\",\n `Pipeline run \"${runId}\" does not exist in this project's run store.`,\n );\n }\n console.log(` id: ${run.id}`);\n console.log(` pipeline: ${run.pipelineId}`);\n console.log(` status: ${run.status}`);\n console.log(` started: ${run.startedAt ?? \"?\"}`);\n if (run.finishedAt) console.log(` finished: ${run.finishedAt}`);\n console.log(` attempt: ${run.attempt}`);\n if (run.cancellationRequested) {\n console.log(` cancellation requested at ${run.cancellationRequestedAt ?? \"?\"}`);\n }\n if (isInterrupted(run)) {\n console.log(\" note: this run looks interrupted (no finishedAt) — retry with `pipeline retry`\");\n }\n if (run.resultSummary) console.log(` result: ${run.resultSummary}`);\n for (const stepRun of run.stepRuns) {\n console.log(` [${stepRun.stepId}] ${stepRun.status}`);\n }\n if (run.reports && run.reports.length > 0) {\n console.log(` reports: ${run.reports.length}`);\n }\n });\n registerPipelineInspect(pipeline);\n}\n\nasync function runPipelineAction(id: string, objective: string | undefined): Promise<void> {\n const config = loadProjectConfig();\n const def = findPipeline(config, id);\n const engine = buildPipelineEngine(config);\n console.log(\n `Running pipeline \"${def.id}\" (${def.steps.length} step(s))${objective ? ` — \"${objective}\"` : \"\"}...`,\n );\n const finished = await engine.run(def, {\n ...(objective !== undefined ? { objective } : {}),\n onStep: (stepRun) => {\n const suffix = stepRun.error ? ` — ${stepRun.error}` : \"\";\n console.log(` [${stepRun.stepId}] ${stepRun.status}${suffix}`);\n },\n });\n if (finished.reports && finished.reports.length > 0) {\n console.log(` reports: ${finished.reports.length} structured report(s)`);\n }\n if (finished.combinedReportId) {\n console.log(` combined report: ${finished.combinedReportId}`);\n }\n if (finished.planId) {\n console.log(` plan: ${finished.planId}`);\n }\n if (finished.resultSummary) {\n console.log(` result: ${finished.resultSummary}`);\n }\n console.log(`Pipeline ${finished.status}. Run id: ${finished.id}`);\n process.exitCode = exitCodeForStatus(finished.status);\n}\n\n/** Top-level `omninode run` — a workflow alias of `pipeline run` (§28). */\nexport function registerRunAlias(program: Command): void {\n program\n .command(\"run <id> [objective]\")\n .description(\"Alias of `omninode pipeline run` — execute a configured pipeline end to end.\")\n .action(async (id: string, objective: string | undefined) => runPipelineAction(id, objective));\n}\n\nasync function createPipelineFromFile(id: string, file: string): Promise<void> {\n const configPath = activeConfigPath();\n if (!configPath) {\n throw new OmniNodeError(\"CONFIG_NOT_FOUND\", \"No omninode.yaml found. Run `omninode init` first.\");\n }\n let definition: unknown;\n try {\n definition = parseDocument(readFileSync(file, \"utf8\")).toJS();\n } catch (error) {\n throw new PipelineError(\"PIPELINE_INVALID\", `Could not read pipeline definition from ${file}.`, {\n cause: error,\n });\n }\n const candidate = pipelineConfigSchema.safeParse({ id, ...(definition as object) });\n if (!candidate.success) {\n const issues = candidate.error.issues.map((i) => `${i.path.join(\".\") || \"(root)\"}: ${i.message}`).join(\"; \");\n throw new PipelineError(\"PIPELINE_INVALID\", `Invalid pipeline definition: ${issues}`);\n }\n // Reject duplicates and structural problems before touching the config.\n const engine = buildPipelineEngine(loadProjectConfig());\n engine.validate({ id, ...(candidate.data as object) } as never);\n\n const doc = parseDocument(readFileSync(configPath, \"utf8\"));\n if (doc.getIn([\"project\", \"pipelines\"]) === undefined) {\n doc.setIn([\"project\", \"pipelines\"], [candidate.data]);\n } else {\n doc.addIn([\"project\", \"pipelines\"], candidate.data);\n }\n const validated = appConfigSchema.safeParse(doc.toJS());\n if (!validated.success) {\n throw new PipelineError(\"PIPELINE_INVALID\", \"Adding this pipeline would produce an invalid configuration.\");\n }\n writeFileSync(configPath, doc.toString(), \"utf8\");\n console.log(`Created pipeline \"${id}\" (${candidate.data.steps.length} step(s)) in ${configPath}.`);\n console.log(`Run it with: omninode pipeline run ${id} \"<objective>\"`);\n}\n\n/** A run left \"running\" with no finishedAt is assumed interrupted (§9.6). */\nfunction isInterrupted(run: { status: string; finishedAt?: string }): boolean {\n return run.status === \"running\" && run.finishedAt === undefined;\n}\n\nfunction findPipeline(config: ReturnType<typeof loadConfig>, id: string): PipelineDefinition {\n const def = config.project.pipelines.find((p) => p.id === id);\n if (!def) {\n const available = config.project.pipelines.map((p) => p.id).join(\", \") || \"(none)\";\n throw new PipelineError(\n \"PIPELINE_NOT_FOUND\",\n `Pipeline \"${id}\" is not configured. Configured pipelines: ${available}.`,\n );\n }\n return def;\n}\n","/**\n * Pipeline engine (§14, §15, §27 Phase 5): validates pipeline definitions,\n * schedules steps over their dependency DAG (implicit sequential chain by\n * default, parallel where the DAG allows), fans research steps out to several\n * agents, hands combined context to plan steps (via a chat model) and to the\n * final execution agent. Every task runs through the TaskEngine, so tasks,\n * results and reports are persisted normally.\n */\nimport { randomBytes } from \"node:crypto\";\nimport type { AgentRegistry } from \"../agents/index.js\";\nimport type { AppConfig } from \"../config/index.js\";\nimport { PipelineError } from \"../errors/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { RoleRegistry } from \"../roles/index.js\";\nimport { createProvider } from \"../providers/index.js\";\nimport type { RoleDefinition } from \"../types/role.js\";\nimport type {\n IPipelineExecutor,\n PipelineDefinition,\n PipelineRun,\n PipelineRunOptions,\n PipelineRunStatus,\n PipelineStep,\n PipelineStepRun,\n} from \"../types/pipeline.js\";\nimport type { ChatFn } from \"../types/chat.js\";\n// Re-exported for v1 compatibility: ChatFn now lives in the neutral types layer.\nexport type { ChatFn };\nimport type { Plan } from \"../types/plan.js\";\nimport type { Report } from \"../types/report.js\";\nimport type { ReportService } from \"../reports/index.js\";\nimport { aggregateReports } from \"../reports/aggregate.js\";\nimport type { AuditSink } from \"../audit/index.js\";\nimport type { IPlanner } from \"../planner/index.js\";\nimport type { PlanStore } from \"../planner/store.js\";\nimport { HeuristicPlanner } from \"../planner/heuristic.js\";\nimport { ModelPlanner } from \"../planner/model.js\";\nimport type { TaskEngine } from \"../tasks/index.js\";\nimport type { PipelineRunStore } from \"./store.js\";\n\nexport interface PipelineEngineOptions {\n tasks: TaskEngine;\n agents: AgentRegistry;\n roles: RoleRegistry;\n providers: AppConfig[\"project\"][\"providers\"];\n store: PipelineRunStore;\n chat?: ChatFn;\n /** Default planner used by plan steps without their own model (§18). */\n planner?: IPlanner;\n /** When present, plans produced by plan steps are persisted. */\n plans?: PlanStore;\n /** When present, pipeline lifecycle events are appended to the audit log (§24). */\n audit?: AuditSink;\n /** When present, finished runs have their reports collected, stored and combined (§16–§17). */\n reports?: ReportService;\n log?: Logger;\n}\n\nexport interface RunPipelineOptions {\n objective?: string;\n onStep?: (stepRun: PipelineStepRun) => void;\n}\n\ninterface StepOutcome {\n status: \"completed\" | \"failed\" | \"partial\" | \"skipped\";\n summary: string;\n /** What this step adds to the combined context (defaults to summary). */\n contextContribution?: string;\n taskIds: string[];\n /** Execution ids of created tasks, for correlation (§6.5). */\n executionIds?: string[];\n /** Step attempt that produced this outcome (1 = first try). */\n attempt?: number;\n planId?: string;\n error?: string;\n reports: Report[];\n}\n\ninterface StepContext {\n objective: string;\n runId?: string;\n /** Definition id (correlates events with the pipeline, not just the run). */\n pipelineDefId?: string;\n taskId?: string;\n role?: RoleDefinition;\n combinedContext: string;\n reports: Report[];\n pipelineRunId?: string;\n}\n\nexport class PipelineEngine implements IPipelineExecutor {\n private readonly log: Logger;\n /** Runs executing in THIS process — cancellation can terminate them directly. */\n private readonly activeRuns = new Map<\n string,\n { taskIds: Set<string>; cancelTasks: () => Promise<void> }\n >();\n\n constructor(private readonly options: PipelineEngineOptions) {\n this.log = (options.log ?? logger).child({ component: \"pipelines\" });\n }\n\n get store(): PipelineRunStore {\n return this.options.store;\n }\n\n /**\n * Saves the run while preserving fields that may be set by another process\n * (e.g. a cancellation request) — an in-memory snapshot must never clobber\n * externally requested cancellation (§9.2).\n */\n private async persist(run: PipelineRun): Promise<void> {\n const current = await this.options.store.get(run.id);\n await this.options.store.save({\n ...run,\n ...(current?.cancellationRequested === true\n ? { cancellationRequested: true, cancellationRequestedAt: current.cancellationRequestedAt }\n : {}),\n });\n }\n\n /** Structural + semantic validation (§27 Phase 5 — pipeline parser). */\n validate(def: PipelineDefinition): void {\n const ids = new Set<string>();\n for (const step of def.steps) {\n if (ids.has(step.id)) {\n throw new PipelineError(\"PIPELINE_INVALID\", `Duplicate step id \"${step.id}\".`);\n }\n ids.add(step.id);\n }\n for (const step of def.steps) {\n for (const dep of step.dependsOn ?? []) {\n if (!ids.has(dep)) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Step \"${step.id}\" depends on unknown step \"${dep}\".`,\n );\n }\n }\n if ((step.kind === \"research\") && (step.agents ?? []).length === 0) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Research step \"${step.id}\" needs at least one agent.`,\n );\n }\n if ((step.kind === \"execute\" || step.kind === \"custom\") && !step.agent) {\n throw new PipelineError(\"PIPELINE_INVALID\", `Step \"${step.id}\" (${step.kind}) needs an agent.`);\n }\n }\n this.assertAcyclic(def);\n }\n\n private assertAcyclic(def: PipelineDefinition): void {\n const deps = this.effectiveDependencies(def);\n const remaining = new Map<string, number>();\n const dependents = new Map<string, string[]>();\n for (const [id, list] of deps) {\n remaining.set(id, list.length);\n for (const d of list) {\n dependents.set(d, [...(dependents.get(d) ?? []), id]);\n }\n }\n const queue = [...deps.keys()].filter((id) => (remaining.get(id) ?? 0) === 0);\n let processed = 0;\n while (queue.length > 0) {\n const id = queue.shift()!;\n processed += 1;\n for (const next of dependents.get(id) ?? []) {\n const left = (remaining.get(next) ?? 0) - 1;\n remaining.set(next, left);\n if (left === 0) queue.push(next);\n }\n }\n if (processed < deps.size) {\n const stuck = [...deps.keys()].filter((id) => (remaining.get(id) ?? 0) > 0);\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Pipeline \"${def.id}\" has a dependency cycle involving: ${stuck.join(\", \")}.`,\n );\n }\n }\n\n /**\n * Steps run sequentially in definition order unless they declare explicit\n * dependencies, which enable parallel branches.\n */\n private effectiveDependencies(def: PipelineDefinition): Map<string, string[]> {\n const deps = new Map<string, string[]>();\n def.steps.forEach((step, index) => {\n const explicit = step.dependsOn ?? [];\n deps.set(\n step.id,\n explicit.length > 0 ? explicit : index > 0 ? [def.steps[index - 1]!.id] : [],\n );\n });\n return deps;\n }\n\n async run(def: PipelineDefinition, options: PipelineRunOptions = {}): Promise<PipelineRun> {\n this.validate(def);\n\n const objective = (options.objective ?? def.objective ?? \"\").trim();\n if (objective.length === 0) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Pipeline \"${def.id}\" needs an objective — pass one or set it in the definition.`,\n );\n }\n const role = def.role ? this.options.roles.get(def.role) : undefined;\n if (def.role && !role) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Role \"${def.role}\" (pipeline \"${def.id}\") is not defined in project.roles.`,\n );\n }\n // Agents referenced by steps must be registered, and plan-step models\n // must resolve to a configured provider — both before anything runs (§9.5).\n for (const step of def.steps) {\n for (const name of [...(step.agents ?? []), ...(step.agent ? [step.agent] : [])]) {\n if (!this.options.agents.get(name)) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Step \"${step.id}\" references unregistered agent \"${name}\".`,\n );\n }\n }\n if (step.model) {\n const separator = step.model.indexOf(\":\");\n if (separator <= 0 || separator === step.model.length - 1) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Step \"${step.id}\" has an invalid model reference \"${step.model}\" — use \"provider:model-id\".`,\n );\n }\n const providerName = step.model.slice(0, separator);\n if (!this.options.providers.some((p) => p.name === providerName)) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Step \"${step.id}\" uses model \"${step.model}\" but provider \"${providerName}\" is not configured.`,\n );\n }\n }\n }\n\n const now = new Date().toISOString();\n const run: PipelineRun = {\n id: `run-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`,\n pipelineId: def.id,\n attempt: 1,\n objective,\n status: \"running\",\n startedAt: now,\n stepRuns: [],\n };\n await this.options.store.save(run);\n const liveTaskIds = new Set<string>();\n this.activeRuns.set(run.id, {\n taskIds: liveTaskIds,\n cancelTasks: async () => {\n for (const taskId of liveTaskIds) {\n await this.options.tasks.cancel(taskId).catch(() => undefined);\n }\n },\n });\n this.log.info(`Running pipeline ${def.id} as ${run.id} (attempt ${run.attempt}).`);\n await this.options.audit?.record({\n at: new Date().toISOString(),\n action: \"pipeline.run.started\",\n id: run.id,\n pipelineId: def.id,\n detail: { pipeline: def.id, objective },\n });\n\n const deps = this.effectiveDependencies(def);\n const outcomes = new Map<string, StepOutcome>();\n const pending = new Set(def.steps.map((s) => s.id));\n const contextParts: string[] = [];\n const allReports: Report[] = [];\n let cancelled = false;\n\n while (pending.size > 0) {\n // §9.2 cancellation check point: stop scheduling, terminate what runs.\n const persisted = await this.options.store.get(run.id);\n if (persisted?.cancellationRequested === true) {\n cancelled = true;\n run.cancellationRequested = true;\n run.cancellationRequestedAt = persisted.cancellationRequestedAt;\n await this.activeRuns.get(run.id)?.cancelTasks();\n for (const step of def.steps.filter((s) => pending.has(s.id))) {\n const stepRun: PipelineStepRun = { stepId: step.id, status: \"cancelled\" };\n run.stepRuns.push(stepRun);\n options.onStep?.(stepRun);\n }\n pending.clear();\n break;\n }\n\n const ready = def.steps.filter(\n (step) => pending.has(step.id) && (deps.get(step.id) ?? []).every((d) => outcomes.has(d)),\n );\n if (ready.length === 0) {\n // Cycle — already rejected by validate(), but never hang.\n throw new PipelineError(\"PIPELINE_FAILED\", `Pipeline \"${def.id}\" scheduling stalled.`);\n }\n\n const settled = await Promise.all(\n ready.map(async (step): Promise<StepOutcome> => {\n if (!this.shouldRun(step, deps.get(step.id) ?? [], outcomes)) {\n return { status: \"skipped\", summary: \"\", taskIds: [], reports: [] };\n }\n const ctx: StepContext = {\n objective,\n ...(role ? { role } : {}),\n combinedContext: contextParts.join(\"\\n\\n\"),\n reports: [...allReports],\n pipelineRunId: run.id,\n runId: run.id,\n pipelineDefId: def.id,\n taskId: run.id,\n };\n return this.executeStep(step, ctx);\n }),\n );\n\n ready.forEach((step, index) => {\n const outcome = settled[index]!;\n outcomes.set(step.id, outcome);\n pending.delete(step.id);\n allReports.push(...outcome.reports);\n if (outcome.status !== \"skipped\" && outcome.summary.length > 0) {\n const contribution = outcome.contextContribution ?? outcome.summary;\n contextParts.push(`## Step \"${step.id}\" (${step.kind})\\n${contribution}`);\n }\n const stepRun: PipelineStepRun = {\n stepId: step.id,\n attempt: outcome.attempt ?? 1,\n ...(outcome.executionIds && outcome.executionIds.length > 0\n ? { executionIds: outcome.executionIds }\n : {}),\n status:\n outcome.status === \"skipped\"\n ? \"cancelled\"\n : outcome.status === \"failed\"\n ? \"failed\"\n : outcome.status === \"partial\"\n ? \"partially_completed\"\n : \"completed\",\n ...(outcome.taskIds.length > 0 ? { taskIds: outcome.taskIds } : {}),\n ...(outcome.planId !== undefined ? { planId: outcome.planId } : {}),\n ...(outcome.error !== undefined ? { error: outcome.error } : {}),\n };\n run.stepRuns.push(stepRun);\n options.onStep?.(stepRun);\n });\n run.reports = [...allReports];\n await this.persist(run);\n }\n\n const allOutcomes = [...outcomes.values()];\n const failed = !cancelled && allOutcomes.some((o) => o.status === \"failed\");\n const partial = !cancelled && !failed && allOutcomes.some((o) => o.status === \"partial\");\n const finalStatus: PipelineRunStatus = cancelled\n ? \"cancelled\"\n : failed\n ? \"failed\"\n : partial\n ? \"partial\"\n : \"completed\";\n const planId = [...outcomes.values()].find((o) => o.planId !== undefined)?.planId;\n\n // §28 — Result: the outcome of the last completed step with tasks.\n let resultSummary: string | undefined;\n for (let i = def.steps.length - 1; i >= 0; i -= 1) {\n const step = def.steps[i]!;\n const outcome = outcomes.get(step.id);\n if (outcome?.status !== \"completed\" || outcome.taskIds.length === 0) continue;\n const stepTasks = (\n await Promise.all(outcome.taskIds.map((id) => this.options.tasks.get(id)))\n ).filter((task): task is NonNullable<typeof task> => task !== undefined);\n const summaries = stepTasks\n .map((task) => task.result?.summary)\n .filter((summary): summary is string => summary !== undefined);\n if (summaries.length > 0) resultSummary = summaries.join(\"\\n\");\n break;\n }\n\n // Report system (§16–§17): collect, store and combine reports from the\n // analysis tasks (research/analyze) — execution output is a result, not a report.\n let combinedReportId: string | undefined;\n if (this.options.reports) {\n const taskIds = def.steps\n .filter((step) => step.kind === \"research\" || step.kind === \"analyze\")\n .flatMap((step) => outcomes.get(step.id)?.taskIds ?? []);\n const tasks = (\n await Promise.all(taskIds.map((id) => this.options.tasks.get(id)))\n ).filter((task): task is NonNullable<typeof task> => task !== undefined);\n const collected = await this.options.reports.collectFromTasks(tasks);\n await this.options.reports.saveReports(collected);\n const combined = await this.options.reports.generateCombined(collected, {\n objective,\n pipelineRunId: run.id,\n taskIds,\n });\n combinedReportId = combined?.id;\n if (collected.length > 0) {\n run.reports = collected;\n }\n }\n\n const finishedAt = new Date().toISOString();\n this.activeRuns.delete(run.id);\n const finished: PipelineRun = {\n ...run,\n status: finalStatus,\n finishedAt,\n attempts: [...(run.attempts ?? []), { attempt: run.attempt, startedAt: run.startedAt ?? finishedAt, finishedAt, status: finalStatus }],\n ...(run.reports !== undefined && run.reports.length > 0 ? { reports: run.reports } : {}),\n ...(combinedReportId !== undefined ? { combinedReportId } : {}),\n ...(planId !== undefined ? { planId } : {}),\n ...(resultSummary !== undefined ? { resultSummary } : {}),\n };\n await this.persist(finished);\n this.log.info(`Pipeline ${def.id} finished: ${finalStatus}.`);\n await this.options.audit?.record({\n at: new Date().toISOString(),\n action: cancelled ? \"pipeline.run.cancelled\" : finalStatus === \"failed\" ? \"pipeline.run.failed\" : \"pipeline.run.finished\",\n id: run.id,\n pipelineId: def.id,\n detail: { pipeline: def.id, status: finalStatus },\n });\n return finished;\n }\n\n /** First-class cancellation (§9.2): requests cancellation and terminates\n * tasks that are running in this process immediately. */\n async cancel(runId: string): Promise<void> {\n const run = await this.options.store.get(runId);\n if (!run) {\n throw new PipelineError(\"PIPELINE_NOT_FOUND\", `Pipeline run \"${runId}\" does not exist.`);\n }\n await this.options.store.save({\n ...run,\n cancellationRequested: true,\n cancellationRequestedAt: new Date().toISOString(),\n });\n const active = this.activeRuns.get(runId);\n if (active) {\n await active.cancelTasks();\n }\n }\n\n async get(runId: string): Promise<PipelineRun | undefined> {\n return this.options.store.get(runId);\n }\n\n async listRuns(filter?: { pipelineId?: string }): Promise<PipelineRun[]> {\n return this.options.store.list(filter);\n }\n\n private shouldRun(\n step: PipelineStep,\n deps: string[],\n outcomes: Map<string, StepOutcome>,\n ): boolean {\n const condition = step.condition ?? \"on-success\";\n const depStatuses = deps.map((d) => outcomes.get(d)?.status);\n const anyFailed = depStatuses.includes(\"failed\");\n // A partial dependency carries real output, so it does not block.\n const anySkipped = depStatuses.includes(\"skipped\");\n if (condition === \"always\") return true;\n if (condition === \"on-failure\") return anyFailed;\n return !anyFailed && !anySkipped;\n }\n\n private async executeStep(step: PipelineStep, ctx: StepContext): Promise<StepOutcome> {\n const retries = step.retries ?? 0;\n let last: StepOutcome | undefined;\n for (let attempt = 0; attempt <= retries; attempt += 1) {\n if (attempt > 0) {\n this.log.warn(`Step \"${step.id}\" failed — retry ${attempt}/${retries}.`);\n }\n last = await this.executeStepOnce(step, ctx);\n if (last.status !== \"failed\") return { ...last, attempt: attempt + 1 };\n }\n return { ...last!, attempt: retries + 1 };\n }\n\n /** Registers tasks created for a step as live, so cancellation can terminate them (§9.2). */\n private trackLiveTasks(runId: string | undefined, taskIds: string[]): void {\n if (!runId) return;\n const active = this.activeRuns.get(runId);\n if (!active) return;\n for (const id of taskIds) active.taskIds.add(id);\n }\n\n private async executeStepOnce(step: PipelineStep, ctx: StepContext): Promise<StepOutcome> {\n switch (step.kind) {\n case \"research\":\n return this.runFanOut(step, ctx);\n case \"collect\":\n return { status: \"completed\", summary: \"(collect: outputs gathered from previous steps)\", taskIds: [], reports: [] };\n case \"analyze\":\n if (!step.agent) {\n return { status: \"completed\", summary: \"(analyze: pass-through, no agent assigned)\", taskIds: [], reports: [] };\n }\n return this.runSingle(step, ctx, step.agent);\n case \"plan\":\n return this.runPlan(step, ctx);\n case \"execute\":\n case \"custom\":\n return this.runSingle(step, ctx, step.agent!);\n }\n }\n\n /** Research fan-out: one task per agent, in parallel (§15). */\n private async runFanOut(step: PipelineStep, ctx: StepContext): Promise<StepOutcome> {\n const agentNames = step.agents ?? [];\n const created = await Promise.all(\n agentNames.map((name) =>\n this.options.tasks.create({\n objective: ctx.objective,\n ...(ctx.pipelineRunId !== undefined ? { pipelineId: ctx.pipelineRunId } : {}),\n agent: name,\n ...(ctx.role ? { role: ctx.role.id } : {}),\n ...(ctx.combinedContext.length > 0\n ? { context: { background: ctx.combinedContext } }\n : {}),\n }),\n ),\n );\n this.trackLiveTasks(ctx.runId, created.map((t) => t.id));\n const results = await Promise.all(created.map((task) => this.options.tasks.run(task.id)));\n const executionIds = results.map((r) => r.executions?.at(-1)?.executionId).filter((id): id is string => id !== undefined);\n\n const completedTasks = results.filter((r) => r.status === \"completed\");\n const failedTasks = results.filter((r) => r.status !== \"completed\");\n const lines = results.map((result, index) => {\n const agentName = agentNames[index] ?? \"unknown\";\n const outcome = result.result?.summary ?? result.result?.error ?? \"(no output)\";\n return `- ${agentName}: ${outcome}`;\n });\n const reports = results.flatMap((r) => r.result?.reports ?? []);\n const summary = lines.join(\"\\n\");\n\n if (failedTasks.length > 0) {\n const firstError = failedTasks[0]?.result?.error ?? failedTasks[0]?.lastError ?? \"unknown outcome\";\n const states = failedTasks.map((r) => r.status).join(\", \");\n return {\n // Some agents succeeded → the step produced usable but incomplete\n // intelligence: partial, not failed (roadmap §9.3).\n status: completedTasks.length > 0 ? \"partial\" : \"failed\",\n summary,\n taskIds: created.map((t) => t.id),\n error: `${failedTasks.length}/${results.length} task(s) incomplete (${states}) — ${firstError}`,\n reports,\n };\n }\n return {\n status: \"completed\",\n summary,\n taskIds: created.map((t) => t.id),\n ...(executionIds.length > 0 ? { executionIds } : {}),\n reports,\n };\n }\n\n private async runSingle(\n step: PipelineStep,\n ctx: StepContext,\n agentName: string,\n ): Promise<StepOutcome> {\n const task = await this.options.tasks.create({\n objective: ctx.objective,\n ...(ctx.pipelineRunId !== undefined ? { pipelineId: ctx.pipelineRunId } : {}),\n agent: agentName,\n ...(ctx.role ? { role: ctx.role.id } : {}),\n ...(ctx.combinedContext.length > 0 ? { context: { background: ctx.combinedContext } } : {}),\n });\n this.trackLiveTasks(ctx.runId, [task.id]);\n const result = await this.options.tasks.run(task.id);\n if (result.status !== \"completed\") {\n return {\n // Unknown/timed_out outcomes are not failures — the work may have\n // happened remotely; the step is incomplete, not broken.\n status: result.status === \"unknown\" || result.status === \"timed_out\" ? \"partial\" : \"failed\",\n summary: result.result?.summary ?? \"\",\n taskIds: [task.id],\n error: result.result?.error ?? `task ${task.id} did not complete`,\n reports: result.result?.reports ?? [],\n };\n }\n return {\n status: \"completed\",\n summary: result.result?.summary ?? \"(no output)\",\n taskIds: [task.id],\n reports: result.result?.reports ?? [],\n };\n }\n\n private async runPlan(step: PipelineStep, ctx: StepContext): Promise<StepOutcome> {\n // §15 Planner Input: task, reports, aggregated findings (consensus +\n // conflicts), context, role and step constraints.\n const aggregated = ctx.reports.length > 0 ? aggregateReports(ctx.reports) : undefined;\n const request = {\n objective: ctx.objective,\n reports: ctx.reports,\n ...(aggregated !== undefined ? { aggregated } : {}),\n ...(ctx.combinedContext.length > 0 ? { context: ctx.combinedContext } : {}),\n ...(ctx.role ? { role: ctx.role } : {}),\n ...(step.constraints !== undefined && step.constraints.length > 0\n ? { constraints: step.constraints }\n : {}),\n ...(ctx.pipelineRunId !== undefined ? { pipelineRunId: ctx.pipelineRunId } : {}),\n };\n\n // Selection order: an explicit step model wins, then the configured\n // default planner, then a pass-through (nothing to plan with).\n let planner: IPlanner;\n if (step.model) {\n planner = new ModelPlanner({\n model: step.model,\n chat: this.getChat(),\n fallback: new HeuristicPlanner(),\n log: this.log,\n });\n } else if (this.options.planner) {\n planner = this.options.planner;\n } else {\n return {\n status: \"completed\",\n summary: \"(plan: no model or planner configured — skipped)\",\n taskIds: [],\n reports: [],\n };\n }\n\n let plan: Plan;\n try {\n plan = await planner.plan(request);\n } catch (error) {\n return {\n status: \"failed\",\n summary: \"\",\n taskIds: [],\n error: error instanceof Error ? error.message : String(error),\n reports: [],\n };\n }\n\n await this.options.plans?.save(plan);\n await this.options.audit?.record({\n at: new Date().toISOString(),\n action: \"plan.generated\",\n id: plan.id,\n ...(ctx.pipelineDefId !== undefined ? { pipelineId: ctx.pipelineDefId } : {}),\n detail: {\n generatedBy: plan.generatedBy,\n steps: plan.steps.length,\n run: ctx.pipelineRunId,\n taskId: ctx.taskId,\n },\n });\n return {\n status: \"completed\",\n summary: plan.summary,\n contextContribution: formatPlan(plan),\n taskIds: [],\n planId: plan.id,\n reports: [],\n };\n }\n\n private getChat(): ChatFn {\n if (this.options.chat) return this.options.chat;\n throw new PipelineError(\n \"PIPELINE_FAILED\",\n \"No chat function available — configure a provider for plan steps.\",\n );\n }\n}\n\nfunction formatPlan(plan: Plan): string {\n const lines = [\n `# Implementation Plan (by ${plan.generatedBy})`,\n plan.summary,\n \"Steps:\",\n ...plan.steps.map((step) => {\n const targets = step.targets && step.targets.length > 0 ? ` [targets: ${step.targets.join(\", \")}]` : \"\";\n return `${step.order}. ${step.title}${targets}`;\n }),\n ];\n if (plan.risks && plan.risks.length > 0) {\n lines.push(\"Risks:\", ...plan.risks.map((risk) => `- ${risk}`));\n }\n return lines.join(\"\\n\");\n}\n\n/** Default chat function: resolves \"provider:model\" against the configured providers. */\nexport interface DefaultChatOptions {\n /** Correlates provider errors in the audit log (§18). */\n audit?: AuditSink;\n env?: Record<string, string | undefined>;\n}\n\nexport function createDefaultChatFn(\n providers: AppConfig[\"project\"][\"providers\"],\n options: DefaultChatOptions = {},\n): ChatFn {\n return async (modelRef, messages) => {\n const separator = modelRef.indexOf(\":\");\n if (separator <= 0 || separator === modelRef.length - 1) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Invalid model reference \"${modelRef}\". Use \"provider:model-id\".`,\n );\n }\n const providerName = modelRef.slice(0, separator);\n const modelId = modelRef.slice(separator + 1);\n const providerConfig = providers.find((p) => p.name === providerName);\n if (!providerConfig) {\n throw new PipelineError(\n \"PIPELINE_INVALID\",\n `Provider \"${providerName}\" (model \"${modelRef}\") is not configured.`,\n );\n }\n const provider = createProvider(providerConfig, {\n ...(options.audit !== undefined ? { audit: options.audit } : {}),\n ...(options.env !== undefined ? { env: options.env } : {}),\n });\n const response = await provider.chat({ model: modelId, messages });\n return response.content;\n };\n}\n","/**\n * HeuristicPlanner: a deterministic, dependency-free planner that derives an\n * implementation plan from recommendations and significant findings.\n * Used as the no-model option and as the graceful fallback when a model's\n * output is rejected (§15).\n */\nimport { randomBytes } from \"node:crypto\";\nimport type { Plan, PlanStep } from \"../types/plan.js\";\nimport type { Finding, FindingSeverity } from \"../types/report.js\";\nimport type { IPlanner, PlanRequest } from \"./types.js\";\n\nconst SEVERITY_RANK: Record<FindingSeverity, number> = {\n info: 0,\n low: 1,\n medium: 2,\n high: 3,\n critical: 4,\n};\n\ninterface ContributedFinding {\n finding: Finding;\n agent: string;\n}\n\nexport class HeuristicPlanner implements IPlanner {\n readonly name = \"heuristic\";\n\n async plan(request: PlanRequest): Promise<Plan> {\n const steps: PlanStep[] = [];\n\n // One step per distinct recommendation (deduped by text).\n const recommendations = dedupe(request.reports.flatMap((r) => r.recommendations));\n for (const text of recommendations) {\n steps.push({\n id: `step-${steps.length + 1}`,\n title: truncate(text, 120),\n order: steps.length + 1,\n ...(steps.length > 0 ? { dependsOn: [`step-${steps.length}`] } : {}),\n });\n }\n\n // Remediation steps for significant findings, most severe first. Aggregated\n // findings (with consensus/conflicts) take precedence when available.\n const contributed: ContributedFinding[] = request.aggregated\n ? request.aggregated.findings.map((finding) => ({\n finding: {\n id: `agg-${slug(finding.title)}`,\n title: finding.title,\n detail: finding.details[0] ?? finding.title,\n ...(finding.severity ? { severity: finding.severity } : {}),\n ...(finding.recommendations && finding.recommendations.length > 0\n ? { recommendation: finding.recommendations[0] }\n : {}),\n },\n agent: finding.sources.map((s) => s.agent).join(\"+\"),\n }))\n : request.reports.flatMap((report) =>\n report.findings.map((finding) => ({ finding, agent: report.agent })),\n );\n\n const significant = contributed\n .filter(({ finding }) =>\n finding.severity ? SEVERITY_RANK[finding.severity] >= SEVERITY_RANK.high : false,\n )\n .sort(\n (a, b) =>\n SEVERITY_RANK[b.finding.severity ?? \"info\"] - SEVERITY_RANK[a.finding.severity ?? \"info\"],\n );\n for (const { finding } of significant) {\n steps.push(remediationStep(finding, steps.length + 1));\n }\n\n if (steps.length === 0) {\n steps.push({\n id: \"step-1\",\n title: \"Gather additional information\",\n description:\n \"The research reports contained no actionable recommendations or significant findings. \" +\n \"Investigate the objective further before planning implementation work.\",\n order: 1,\n });\n }\n\n const risks = significant\n .filter(({ finding }) => finding.severity === \"critical\")\n .map(({ finding }) => `Critical finding unaddressed until its step completes: ${finding.title}`);\n const conflicts = request.aggregated?.conflicts ?? [];\n if (conflicts.length > 0) {\n risks.push(\n `${conflicts.length} unresolved agent disagreement(s): ${conflicts.map((c) => c.findingTitle).join(\"; \")}`,\n );\n }\n\n return {\n id: `plan-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`,\n objective: request.objective,\n goal: request.aggregated?.title ?? truncate(request.objective, 120),\n summary:\n `Derived from ${request.reports.length} report(s): ` +\n `${recommendations.length} recommendation step(s), ${significant.length} remediation step(s).`,\n steps,\n ...(risks.length > 0 ? { risks } : {}),\n ...(request.constraints !== undefined && request.constraints.length > 0\n ? { constraints: request.constraints }\n : {}),\n generatedBy: \"heuristic\",\n ...(request.taskId !== undefined ? { taskId: request.taskId } : {}),\n ...(request.pipelineRunId !== undefined ? { pipelineRunId: request.pipelineRunId } : {}),\n createdAt: new Date().toISOString(),\n };\n }\n}\n\nfunction remediationStep(finding: Finding, order: number): PlanStep {\n return {\n id: `step-${order}`,\n title: `Fix: ${truncate(finding.title, 100)}`,\n description: finding.detail,\n order,\n dependsOn: order > 1 ? [`step-${order - 1}`] : [],\n sourceFindings: [finding.id],\n ...(finding.recommendation ? { recommendation: finding.recommendation } : {}),\n };\n}\n\nfunction dedupe(texts: string[]): string[] {\n return [...new Set(texts.map((t) => t.trim()).filter((t) => t.length > 0))];\n}\n\nfunction slug(text: string): string {\n return text.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-|-$/g, \"\").slice(0, 40);\n}\n\nfunction truncate(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n","/**\n * ModelPlanner (§18): uses a chat model (\"provider:model-id\" through the chat\n * layer) to produce an implementation plan. The model is asked for JSON\n * matching the plan contract; unparseable output degrades gracefully to the\n * heuristic fallback rather than failing the pipeline.\n */\nimport { randomBytes } from \"node:crypto\";\nimport { PlannerError } from \"../errors/index.js\";\nimport { planJsonSchema, validatePlan } from \"./schema.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport type { Plan, PlanStep } from \"../types/plan.js\";\nimport type { ChatFn, ChatMessage } from \"../types/chat.js\";\n\nimport { buildPlannerContext } from \"./context.js\";\nimport type { IPlanner, PlanRequest } from \"./types.js\";\n\nexport interface ModelPlannerOptions {\n model: string;\n chat: ChatFn;\n /** Extra instruction appended to the system prompt. */\n instruction?: string;\n /** Used when the model output is unparseable (or the call fails, if tolerateErrors). */\n fallback?: IPlanner;\n log?: Logger;\n}\n\nexport class ModelPlanner implements IPlanner {\n readonly name = \"model\";\n private readonly log: Logger;\n\n constructor(private readonly options: ModelPlannerOptions) {\n this.log = (options.log ?? logger).child({ component: \"planner\", model: options.model });\n }\n\n async plan(request: PlanRequest): Promise<Plan> {\n const context = buildPlannerContext(request);\n const messages: ChatMessage[] = [\n {\n role: \"system\",\n content:\n \"You are the OmniNode planner. Given the objective and the combined research context, \" +\n \"produce a final analysis and a prioritized, actionable implementation plan. \" +\n \"Respond with JSON ONLY (no prose, no code fences) matching exactly this shape: \" +\n '{\"goal\": string, \"summary\": string, \"steps\": [{\"id\": string, \"title\": string, \"description\": string, ' +\n '\"order\": number, \"targets\": string[], \"acceptance_criteria\": string[], \"source_findings\": string[]}], ' +\n '\"risks\": string[], \"notes\": string[]}. ' +\n (this.options.instruction ?? \"\"),\n },\n { role: \"user\", content: context },\n ];\n\n let responseText: string;\n try {\n responseText = await this.options.chat(this.options.model, messages);\n } catch (error) {\n return this.degrade(request, `planner model call failed: ${describe(error)}`);\n }\n\n const parsed = parsePlanJson(responseText);\n if (!parsed.ok) {\n return this.degrade(request, `planner model output rejected: ${parsed.reason}`, parsed.issues);\n }\n\n const plan: Plan = {\n id: `plan-${Date.now().toString(36)}-${randomBytes(3).toString(\"hex\")}`,\n objective: request.objective,\n goal: parsed.goal,\n summary: parsed.summary,\n steps: parsed.steps,\n ...(parsed.risks !== undefined ? { risks: parsed.risks } : {}),\n ...(parsed.notes !== undefined ? { notes: parsed.notes } : {}),\n ...(request.constraints !== undefined && request.constraints.length > 0\n ? { constraints: request.constraints }\n : {}),\n generatedBy: `model:${this.options.model}`,\n model: this.options.model,\n ...(request.taskId !== undefined ? { taskId: request.taskId } : {}),\n ...(request.pipelineRunId !== undefined ? { pipelineRunId: request.pipelineRunId } : {}),\n createdAt: new Date().toISOString(),\n };\n\n // §15 Validation: every generated plan passes schema validation.\n const validation = validatePlan(plan);\n if (!validation.valid) {\n return this.degrade(request, `generated plan rejected: ${validation.reason}`, validation.issues);\n }\n return validation.plan;\n }\n\n private async degrade(\n request: PlanRequest,\n reason: string,\n issues: Array<{ path: string; message: string }> = [],\n ): Promise<Plan> {\n if (this.options.fallback) {\n this.log.warn(`${reason} — using the heuristic fallback planner.`);\n return this.options.fallback.plan(request);\n }\n // Structured error: the caller sees exactly what was rejected (§15).\n throw new PlannerError(\"PLAN_INVALID\", `Planner failed: ${reason}.`, {\n details: { reason, issues },\n });\n }\n}\n\nexport type PlanJsonResult =\n | { ok: true; goal: string; summary: string; steps: PlanStep[]; risks?: string[]; notes?: string[] }\n | { ok: false; reason: string; issues: Array<{ path: string; message: string }> };\n\n/** Extracts and validates plan JSON from arbitrary model output (§15). */\nexport function parsePlanJson(text: string): PlanJsonResult {\n const unfenced = text.replace(/```(?:json)?/gi, \"\");\n const start = unfenced.indexOf(\"{\");\n const end = unfenced.lastIndexOf(\"}\");\n if (start < 0 || end <= start) {\n return { ok: false, reason: \"planner output contained no JSON object\", issues: [] };\n }\n let json: unknown;\n try {\n json = JSON.parse(unfenced.slice(start, end + 1));\n } catch (error) {\n return {\n ok: false,\n reason: `planner output was not valid JSON: ${error instanceof Error ? error.message : String(error)}`,\n issues: [],\n };\n }\n const parsed = planJsonSchema.safeParse(json);\n if (!parsed.success) {\n return {\n ok: false,\n reason: \"planner output did not match the plan schema\",\n issues: parsed.error.issues.map((issue) => ({\n path: issue.path.join(\".\") || \"(root)\",\n message: issue.message,\n })),\n };\n }\n const steps: PlanStep[] = parsed.data.steps\n .map((step, index) => ({\n id: step.id ?? `step-${index + 1}`,\n title: step.title,\n description: step.description,\n order: step.order ?? index + 1,\n targets: step.targets,\n acceptanceCriteria: step.acceptance_criteria,\n dependsOn: step.depends_on,\n sourceFindings: step.source_findings,\n }))\n .sort((a, b) => a.order - b.order);\n return {\n ok: true,\n goal: parsed.data.goal,\n summary: parsed.data.summary,\n steps,\n risks: parsed.data.risks,\n notes: parsed.data.notes,\n };\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Plan validation (roadmap §15, Validation): every generated plan passes\n * schema validation. Invalid plans are rejected with structured issues and\n * — where a fallback is configured — fall back to heuristic planning.\n */\nimport { z } from \"zod\";\nimport type { Plan } from \"../types/plan.js\";\n\nconst planStepSchema = z.object({\n id: z.string().min(1).optional(),\n title: z.string().min(1),\n description: z.string().optional(),\n order: z.number().int().optional(),\n targets: z.array(z.string()).optional(),\n acceptance_criteria: z.array(z.string()).optional(),\n depends_on: z.array(z.string()).optional(),\n source_findings: z.array(z.string()).optional(),\n});\n\nexport const planJsonSchema = z.object({\n goal: z.string().min(1),\n summary: z.string().min(1),\n steps: z.array(planStepSchema).min(1),\n risks: z.array(z.string()).optional(),\n notes: z.array(z.string()).optional(),\n});\n\nexport interface PlanValidationIssue {\n path: string;\n message: string;\n}\n\nexport type PlanValidationResult =\n | { valid: true; plan: Plan }\n | { valid: false; issues: PlanValidationIssue[]; reason: string };\n\n/** Validates a plan object (ids/order filled by the caller). */\nexport function validatePlan(plan: Plan): PlanValidationResult {\n const issues: PlanValidationIssue[] = [];\n const stepIds = new Set<string>();\n\n for (const [index, step] of plan.steps.entries()) {\n if (stepIds.has(step.id)) {\n issues.push({ path: `steps.${index}.id`, message: `duplicate step id \"${step.id}\"` });\n }\n stepIds.add(step.id);\n if (!step.title || step.title.trim().length === 0) {\n issues.push({ path: `steps.${index}.title`, message: \"title must not be empty\" });\n }\n for (const dep of step.dependsOn ?? []) {\n if (!stepIds.has(dep) && !plan.steps.some((s) => s.id === dep)) {\n issues.push({ path: `steps.${index}.dependsOn`, message: `unknown step dependency \"${dep}\"` });\n }\n }\n }\n\n if (plan.steps.length === 0) {\n issues.push({ path: \"steps\", message: \"a plan needs at least one step\" });\n }\n if (!plan.summary || plan.summary.trim().length === 0) {\n issues.push({ path: \"summary\", message: \"summary must not be empty\" });\n }\n\n return issues.length > 0\n ? { valid: false, issues, reason: `plan failed validation (${issues.length} issue(s))` }\n : { valid: true, plan };\n}\n\n/** Builds the parser input type for model-produced plan JSON. */\nexport type PlanJsonInput = z.input<typeof planJsonSchema>;\n","/**\n * Planner context builder (§15, Planner Input): assembles the original task,\n * project context, agent reports, aggregated findings, relevant memory and\n * constraints into one structured input, in that order.\n */\nimport type { PlanRequest } from \"./types.js\";\nimport type { Report } from \"../types/report.js\";\n\nexport function buildPlannerContext(request: PlanRequest): string {\n const parts: string[] = [`# Task\\n${request.objective}`];\n\n if (request.projectContext) {\n parts.push(`# Project context\\n${request.projectContext}`);\n }\n\n if (request.role) {\n const roleLines = [`# Role\\n${request.role.name} (${request.role.id})`];\n if (request.role.responsibilities.length > 0) {\n roleLines.push(\"Responsibilities:\", ...request.role.responsibilities.map((r) => `- ${r}`));\n }\n if (request.role.expectedOutputs.length > 0) {\n roleLines.push(\"Expected outputs:\", ...request.role.expectedOutputs.map((o) => `- ${o}`));\n }\n parts.push(roleLines.join(\"\\n\"));\n }\n\n if (request.reports.length > 0) {\n const agents = [...new Set(request.reports.map((r) => r.agent))].join(\", \");\n const findingLines = request.reports.flatMap((report: Report) =>\n report.findings.map(\n (finding) =>\n `- [${finding.severity ?? \"info\"}] ${finding.title} (source: ${report.agent}, finding: ${finding.id})` +\n (finding.detail ? ` — ${finding.detail}` : \"\"),\n ),\n );\n parts.push(\n `# Agent reports (${request.reports.length} by ${agents})\\n` +\n (findingLines.length > 0 ? findingLines.join(\"\\n\") : \"(no findings reported)\"),\n );\n\n const recommendationLines = request.reports.flatMap((report) =>\n report.recommendations.map((text) => `- ${text} (source: ${report.agent})`),\n );\n if (recommendationLines.length > 0) {\n parts.push(`# Recommendations\\n${recommendationLines.join(\"\\n\")}`);\n }\n }\n\n if (request.aggregated) {\n const aggregatedLines = [\n `- findings: ${request.aggregated.findings.length} (agreements: ${request.aggregated.agreements.length}, conflicts: ${request.aggregated.conflicts.length})`,\n ...request.aggregated.findings.map(\n (finding) =>\n `- [${finding.severity ?? \"info\"}] ${finding.title} (x${finding.occurrences})`,\n ),\n // Conflicts stay visible to the planner — it must plan around disagreement.\n ...request.aggregated.conflicts.map(\n (conflict) => `- CONFLICT (${conflict.type}) on \"${conflict.findingTitle}\": ${conflict.note}`,\n ),\n ];\n parts.push(`# Aggregated findings\\n${aggregatedLines.join(\"\\n\")}`);\n }\n\n if (request.memory && request.memory.length > 0) {\n parts.push(\n `# Relevant memory\\n` +\n request.memory.map((entry) => `- [${entry.scope}] ${entry.content}`).join(\"\\n\"),\n );\n }\n\n if (request.constraints && request.constraints.length > 0) {\n parts.push(`# Constraints\\n${request.constraints.map((c) => `- ${c}`).join(\"\\n\")}`);\n }\n\n if (request.context) {\n parts.push(`# Research context\\n${request.context}`);\n }\n\n return parts.join(\"\\n\\n\");\n}\n","/**\n * Plan persistence (§27 Phase 8 — planner result storage). Same\n * replaceable-store pattern as the other local stores.\n */\nimport { JsonFileStore } from \"../persistence/json-file-store.js\";\nimport type { Plan } from \"../types/plan.js\";\n\nexport interface PlanFilter {\n pipelineRunId?: string;\n taskId?: string;\n}\n\nexport interface PlanStore {\n save(plan: Plan): Promise<void>;\n get(id: string): Promise<Plan | undefined>;\n list(filter?: PlanFilter): Promise<Plan[]>;\n}\n\nexport class FilePlanStore extends JsonFileStore<Plan> implements PlanStore {\n constructor(directory?: string) {\n super({ ...(directory !== undefined ? { directory } : {}), fileName: \"plans.json\" });\n }\n\n save(plan: Plan): Promise<void> {\n return this.mutate((plans) => {\n const index = plans.findIndex((p) => p.id === plan.id);\n if (index >= 0) plans[index] = plan;\n else plans.push(plan);\n return [plans, undefined];\n });\n }\n\n async get(id: string): Promise<Plan | undefined> {\n return (await this.readAll()).find((p) => p.id === id);\n }\n\n async list(filter: PlanFilter = {}): Promise<Plan[]> {\n return (await this.readAll())\n .filter((plan) => (filter.pipelineRunId ? plan.pipelineRunId === filter.pipelineRunId : true))\n .filter((plan) => (filter.taskId ? plan.taskId === filter.taskId : true))\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n }\n}\n","/** Planner factory from project configuration (§18 — planner provider support). */\nimport { ConfigError } from \"../errors/index.js\";\nimport type { AppConfig } from \"../config/index.js\";\nimport type { ChatFn } from \"../types/chat.js\";\nimport { HeuristicPlanner } from \"./heuristic.js\";\nimport { ModelPlanner } from \"./model.js\";\nimport type { IPlanner } from \"./types.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\n\nexport function buildPlanner(\n plannerConfig: AppConfig[\"project\"][\"planner\"],\n chat: ChatFn,\n log: Logger = logger,\n): IPlanner | undefined {\n if (!plannerConfig) return undefined;\n if (plannerConfig.kind === \"heuristic\") {\n return new HeuristicPlanner();\n }\n if (!plannerConfig.model) {\n throw new ConfigError(\n \"CONFIG_INVALID\",\n 'Planner kind \"model\" needs a model reference (\"provider:model-id\") in omninode.yaml.',\n );\n }\n return new ModelPlanner({\n model: plannerConfig.model,\n chat,\n ...(plannerConfig.instruction !== undefined ? { instruction: plannerConfig.instruction } : {}),\n fallback: new HeuristicPlanner(),\n log,\n });\n}\n","import type { AppConfig } from \"../config/index.js\";\nimport { FileAuditLog } from \"../audit/index.js\";\nimport { buildAgentRegistry } from \"../agents/index.js\";\nimport { createMemoryProvider, MemoryService } from \"../memory/index.js\";\nimport { buildPlanner } from \"../planner/index.js\";\nimport { FilePlanStore } from \"../planner/store.js\";\nimport { buildRoleRegistry } from \"../roles/index.js\";\nimport { logger, type Logger } from \"../logger/index.js\";\nimport { ReportService } from \"../reports/index.js\";\nimport { FileReportStore } from \"../reports/store.js\";\nimport { TaskEngine } from \"../tasks/index.js\";\nimport { FileTaskStore } from \"../tasks/store.js\";\nimport { PipelineEngine, createDefaultChatFn } from \"./engine.js\";\nimport { FilePipelineRunStore } from \"./store.js\";\n\nexport function buildPipelineEngine(config: AppConfig, log: Logger = logger): PipelineEngine {\n const auditLog = new FileAuditLog();\n const agents = buildAgentRegistry(config, log);\n const roles = buildRoleRegistry(config);\n const chat = createDefaultChatFn(config.project.providers, { audit: auditLog });\n const tasks = new TaskEngine({\n agents,\n roles,\n store: new FileTaskStore(),\n ...(config.project.memory !== undefined\n ? {\n memory: new MemoryService(createMemoryProvider(config.project.memory), log, {\n required: config.project.memory.required,\n }),\n }\n : {}),\n audit: new FileAuditLog(),\n log,\n });\n return new PipelineEngine({\n tasks,\n agents,\n roles,\n providers: config.project.providers,\n store: new FilePipelineRunStore(),\n chat,\n ...(config.project.planner !== undefined\n ? { planner: buildPlanner(config.project.planner, chat, log) }\n : {}),\n plans: new FilePlanStore(),\n reports: new ReportService(new FileReportStore(), log),\n audit: new FileAuditLog(),\n log,\n });\n}\n","import type { Command } from \"commander\";\nimport { createMemoryProvider, MemoryService } from \"../../memory/index.js\";\nimport { truncate } from \"./shared.js\";\nimport { loadProjectConfig } from \"../options.js\";\nexport function registerMemoryCommands(program: Command): void {\n const memory = program\n .command(\"memory\")\n .description(\"Inspect and manage persistent project memory (§19–§20).\");\n\n memory\n .command(\"status\")\n .description(\"Show the active memory provider and how much is stored.\")\n .action(async () => {\n const config = loadProjectConfig();\n const configured = config.project.memory?.provider ?? \"local (default — add a `memory:` section to opt in)\";\n const svc = new MemoryService(createMemoryProvider(config.project.memory));\n const entries = await svc.providerRef.query({ limit: 10_000 });\n console.log(`provider: ${configured}`);\n console.log(`entries: ${entries.length}`);\n const scopes = new Map<string, number>();\n for (const entry of entries) {\n scopes.set(entry.scope, (scopes.get(entry.scope) ?? 0) + 1);\n }\n for (const [scope, count] of [...scopes.entries()].sort()) {\n console.log(` ${scope}: ${count}`);\n }\n });\n\n memory\n .command(\"query <text>\")\n .description(\"Search memory for entries relevant to the text.\")\n .option(\"-s, --scope <scope>\", \"Restrict to a scope: project, task, role or knowledge.\")\n .option(\"-n, --limit <count>\", \"Maximum entries to return.\", (value: string) => Number(value), 10)\n .option(\"--json\", \"Emit entries as JSON.\")\n .action(async (text: string, options: { scope?: string; limit: number; json?: boolean }) => {\n const config = loadProjectConfig();\n const svc = new MemoryService(createMemoryProvider(config.project.memory));\n const entries = await svc.providerRef.query({\n text,\n ...(options.scope !== undefined ? { scope: options.scope as \"project\" | \"task\" | \"role\" | \"knowledge\" } : {}),\n limit: options.limit,\n });\n if (options.json) {\n console.log(JSON.stringify(entries, null, 2));\n return;\n }\n if (entries.length === 0) {\n console.log(\"No relevant memory found.\");\n return;\n }\n for (const entry of entries) {\n console.log(`[${entry.scope}] ${entry.key}`);\n console.log(` ${truncate(entry.content.replace(/\\n/g, \" \"), 120)}`);\n }\n });\n\n memory\n .command(\"write <text>\")\n .description(\"Write an entry to memory.\")\n .option(\"-s, --scope <scope>\", \"Memory scope: project, task, role or knowledge.\", \"project\")\n .option(\"-t, --tags <tags>\", \"Comma-separated tags.\", (value: string) =>\n value.split(\",\").map((tag) => tag.trim()).filter((tag) => tag.length > 0),\n )\n .option(\"-k, --key <key>\", \"Entry key (defaults to a generated note key).\")\n .action(async (text: string, options: { scope: string; tags?: string[]; key?: string }) => {\n const config = loadProjectConfig();\n const svc = new MemoryService(createMemoryProvider(config.project.memory));\n const key = options.key ?? `note:${Date.now().toString(36)}`;\n await svc.providerRef.write({\n key,\n scope: options.scope as \"project\" | \"task\" | \"role\" | \"knowledge\",\n content: text,\n ...(options.tags !== undefined && options.tags.length > 0 ? { tags: options.tags } : {}),\n });\n console.log(`Stored memory entry \"${key}\" (${options.scope}).`);\n });\n}\n","import type { Command } from \"commander\";\nimport { OmniNodeError } from \"../../errors/index.js\";\nimport { FilePlanStore } from \"../../planner/store.js\";\nimport { truncate } from \"./shared.js\";\n\nexport function registerPlanCommands(program: Command): void {\n const plan = program\n .command(\"plan\")\n .description(\"Inspect implementation plans produced by the planner layer (§18).\");\n\n plan\n .command(\"list\")\n .description(\"List stored plans.\")\n .option(\"--run <pipelineRunId>\", \"Only plans for this pipeline run.\")\n .option(\"--json\", \"Emit plans as JSON.\")\n .action(async (options: { run?: string; json?: boolean }) => {\n const store = new FilePlanStore();\n const plans = await store.list({\n ...(options.run !== undefined ? { pipelineRunId: options.run } : {}),\n });\n if (options.json) {\n console.log(JSON.stringify(plans, null, 2));\n return;\n }\n if (plans.length === 0) {\n console.log(\"No plans stored yet. Run a pipeline with a plan step to generate one.\");\n return;\n }\n for (const p of plans) {\n console.log(`${p.id} ${p.steps.length} step(s) by ${p.generatedBy} ${truncate(p.summary, 50)}`);\n }\n });\n\n plan\n .command(\"show <id>\")\n .description(\"Show a stored implementation plan in full.\")\n .action(async (id: string) => {\n const store = new FilePlanStore();\n const found = await store.get(id);\n if (!found) {\n throw new OmniNodeError(\"PLAN_INVALID\", `Plan \"${id}\" was not found in the plan store.`, {\n details: { id },\n });\n }\n console.log(`Plan ${found.id}`);\n console.log(` objective: ${found.objective}`);\n console.log(` by: ${found.generatedBy}`);\n console.log(` summary: ${found.summary}`);\n console.log(\" steps:\");\n for (const step of [...found.steps].sort((a, b) => a.order - b.order)) {\n const targets = step.targets && step.targets.length > 0 ? ` [${step.targets.join(\", \")}]` : \"\";\n console.log(` ${step.order}. ${step.title}${targets}`);\n if (step.description) console.log(` ${truncate(step.description, 100)}`);\n for (const criterion of step.acceptanceCriteria ?? []) {\n console.log(` accept: ${criterion}`);\n }\n }\n if (found.risks && found.risks.length > 0) {\n console.log(\" risks:\");\n for (const risk of found.risks) {\n console.log(` - ${risk}`);\n }\n }\n });\n}\n","import type { Command } from \"commander\";\nimport { createMemoryProvider, MemoryService } from \"../../memory/index.js\";\nimport { FilePlanStore } from \"../../planner/store.js\";\nimport { FileReportStore } from \"../../reports/store.js\";\nimport { FileTaskStore } from \"../../tasks/store.js\";\nimport { FilePipelineRunStore } from \"../../pipelines/store.js\";\nimport { OMNINODE_VERSION } from \"../../version.js\";\nimport { loadProjectConfig } from \"../options.js\";\nfunction groupBy<T>(items: T[], key: (item: T) => string): Record<string, number> {\n const counts: Record<string, number> = {};\n for (const item of items) {\n const k = key(item);\n counts[k] = (counts[k] ?? 0) + 1;\n }\n return counts;\n}\n\nfunction countBy<T>(items: T[], key: (item: T) => string): string {\n const counts = new Map<string, number>();\n for (const item of items) {\n const k = key(item);\n counts.set(k, (counts.get(k) ?? 0) + 1);\n }\n if (counts.size === 0) return \"0\";\n return `${items.length} (${[...counts.entries()].map(([k, v]) => `${k} ${v}`).join(\", \")})`;\n}\n\nexport function registerStatusCommand(program: Command): void {\n program\n .command(\"status\")\n .description(\"Show the project's OmniNode state overview (config, tasks, runs, reports, plans, memory).\")\n .option(\"--json\", \"Emit machine-readable JSON (for scripts and CI).\")\n .action(async (options: { json?: boolean }) => {\n const config = loadProjectConfig();\n\n const tasks = await new FileTaskStore().list();\n const runs = await new FilePipelineRunStore().list();\n const reportStore = new FileReportStore();\n const reports = await reportStore.listReports();\n const combined = await reportStore.listCombined();\n const plans = await new FilePlanStore().list();\n\n let memory: { provider: string; entries: number } | undefined;\n if (config.project.memory !== undefined) {\n const service = new MemoryService(createMemoryProvider(config.project.memory));\n memory = {\n provider: service.providerName,\n entries: (await service.providerRef.query({ limit: 10_000 })).length,\n };\n }\n\n if (options.json) {\n console.log(\n JSON.stringify(\n {\n version: OMNINODE_VERSION,\n project: config.project.name,\n providers: config.project.providers.map((p) => p.name),\n agents: config.project.agents.map((a) => a.name),\n roles: config.project.roles.map((r) => r.id),\n pipelines: config.project.pipelines.map((p) => p.id),\n tasks: { total: tasks.length, byStatus: groupBy(tasks, (t) => t.status) },\n runs: { total: runs.length, byStatus: groupBy(runs, (r) => r.status) },\n reports: { raw: reports.length, combined: combined.length },\n plans: plans.length,\n ...(memory !== undefined ? { memory } : {}),\n },\n null,\n 2,\n ),\n );\n return;\n }\n\n console.log(`OmniNode v${OMNINODE_VERSION} — project \"${config.project.name}\"`);\n console.log(`providers: ${config.project.providers.map((p) => p.name).join(\", \") || \"none\"}`);\n console.log(`agents: ${config.project.agents.map((a) => a.name).join(\", \") || \"none\"}`);\n console.log(`roles: ${config.project.roles.map((r) => r.id).join(\", \") || \"none\"}`);\n console.log(`pipelines: ${config.project.pipelines.map((p) => p.id).join(\", \") || \"none\"}`);\n console.log(`tasks: ${countBy(tasks, (t) => t.status)}`);\n console.log(`runs: ${countBy(runs, (r) => r.status)}`);\n console.log(`reports: ${reports.length} raw, ${combined.length} combined`);\n console.log(`plans: ${plans.length}`);\n if (memory) {\n console.log(`memory: ${memory.provider}, ${memory.entries} entr(ies)`);\n } else {\n console.log(\"memory: not configured (local provider available — add a `memory:` section)\");\n }\n });\n}\n","import type { Command } from \"commander\";\nimport { FileAuditLog } from \"../../audit/index.js\";\n\nexport function registerAuditCommand(program: Command): void {\n program\n .command(\"audit\")\n .description(\"Show the recent audit log — task and pipeline lifecycle events (§24).\")\n .option(\"-n, --limit <count>\", \"Number of events to show (default 20).\", (value: string) => Number(value), 20)\n .action(async (options: { limit: number }) => {\n const events = await new FileAuditLog().recent(options.limit);\n if (events.length === 0) {\n console.log(\"No audit events recorded yet.\");\n return;\n }\n for (const event of events) {\n const id = event.id ? ` ${event.id}` : \"\";\n const detail = event.detail && Object.keys(event.detail).length > 0\n ? ` ${JSON.stringify(event.detail)}`\n : \"\";\n console.log(`${event.at} ${event.action}${id}${detail}`);\n }\n });\n}","/**\n * Persistence layer (v2 Phase 12): one entry point to every local store,\n * the canonical storage interface names, and the migration path that upgrades\n * v1 data in place.\n */\nimport { FileAuditLog } from \"../audit/index.js\";\nimport { LocalMemoryProvider } from \"../memory/local.js\";\nimport { FilePipelineRunStore } from \"../pipelines/store.js\";\nimport { FilePlanStore } from \"../planner/store.js\";\nimport { FileReportStore } from \"../reports/store.js\";\nimport { FileTaskStore } from \"../tasks/store.js\";\nimport {\n SCHEMA_VERSION,\n inspectDocument,\n readDocument,\n writeFileAtomic,\n type DocumentState,\n} from \"./json-file-store.js\";\nexport {\n JsonFileStore,\n SCHEMA_VERSION,\n inspectDocument,\n readDocument,\n writeFileAtomic,\n} from \"./json-file-store.js\";\nexport type { JsonDocument, DocumentState, JsonFileStoreOptions, Durability } from \"./json-file-store.js\";\n\n// Canonical storage interface names (roadmap §16). The v1 names above remain\n// the exported API; these aliases document the mapping.\nexport type { TaskStore, PipelineStore, ReportStore, PlanStore, MemoryStore, AuditStore } from \"./store-types.js\";\n\n/** Bundles every store for a single project directory. */\nexport class ProjectStores {\n readonly tasks: FileTaskStore;\n readonly pipelineRuns: FilePipelineRunStore;\n readonly reports: FileReportStore;\n readonly plans: FilePlanStore;\n readonly memory: LocalMemoryProvider;\n readonly audit: FileAuditLog;\n\n constructor(directory = `${process.cwd()}/.omninode`) {\n this.tasks = new FileTaskStore(directory);\n this.pipelineRuns = new FilePipelineRunStore(directory);\n this.reports = new FileReportStore(directory);\n this.plans = new FilePlanStore(directory);\n this.memory = new LocalMemoryProvider(directory);\n this.audit = new FileAuditLog(directory);\n }\n}\n\nexport interface MigrationReport {\n file: string;\n state: DocumentState[\"status\"];\n before?: number;\n after?: number;\n migrated: boolean;\n note?: string;\n}\n\n/** Every persisted store file OmniNode manages in a project. */\nexport const STORE_FILES = [\n \"tasks.json\",\n \"pipelines.json\",\n \"reports.json\",\n \"plans.json\",\n \"memory.json\",\n] as const;\n\n/**\n * Migration (roadmap §16): inspects every store file, reports its schema\n * state, and — unless `checkOnly` — rewrites v1 documents at the current\n * schema version. Idempotent and safe: unknown/future versions are reported,\n * never rewritten.\n */\nexport async function migrateProjectStores(\n directory = `${process.cwd()}/.omninode`,\n options: { checkOnly?: boolean } = {},\n): Promise<MigrationReport[]> {\n const reports: MigrationReport[] = [];\n for (const file of STORE_FILES) {\n const path = `${directory}/${file}`;\n const state = await inspectDocument(path);\n if (state.status === \"missing\") {\n reports.push({ file, state: state.status, migrated: false });\n continue;\n }\n if (state.status === \"current\") {\n reports.push({ file, state: state.status, before: state.count, after: state.count, migrated: false });\n continue;\n }\n if (state.status === \"future\") {\n reports.push({\n file,\n state: state.status,\n migrated: false,\n note: `written by a newer OmniNode (schema v${state.schemaVersion}); not touched`,\n });\n continue;\n }\n if (state.status === \"corrupt\") {\n reports.push({ file, state: state.status, migrated: false, note: state.detail });\n continue;\n }\n // v1-legacy or empty: rewrite at the current schema version.\n const items = await readDocument<unknown>(path, undefined, false);\n if (!options.checkOnly) {\n await writeFileAtomic(path, `${JSON.stringify({ schemaVersion: SCHEMA_VERSION, items }, null, 2)}\\n`);\n }\n const beforeCount = items.length;\n reports.push({\n file,\n state: state.status,\n before: beforeCount,\n after: items.length,\n migrated: !options.checkOnly,\n ...(options.checkOnly ? { note: \"would migrate\" } : {}),\n });\n }\n return reports;\n}\n","import type { Command } from \"commander\";\nimport { migrateProjectStores, SCHEMA_VERSION } from \"../../persistence/index.js\";\n\nexport function registerMigrateCommand(program: Command): void {\n program\n .command(\"migrate\")\n .description(\n `Inspect and upgrade persisted store files to schema v${SCHEMA_VERSION} (v1 data is migrated in place).`,\n )\n .option(\"--check\", \"Only report what would change; do not write.\")\n .action(async (options: { check?: boolean }) => {\n const reports = await migrateProjectStores(`${process.cwd()}/.omninode`, {\n checkOnly: options.check ?? false,\n });\n let changed = 0;\n for (const report of reports) {\n if (report.migrated || report.state === \"v1-legacy\") changed += 1;\n const detail =\n report.state === \"corrupt\"\n ? ` (corrupt: ${report.note})`\n : report.state === \"future\"\n ? ` (${report.note})`\n : report.state === \"v1-legacy\"\n ? ` ${report.migrated ? \"migrated\" : \"would migrate\"} ${report.before ?? 0} → ${report.after ?? 0} item(s)`\n : report.state === \"current\"\n ? ` ${report.after ?? 0} item(s)`\n : \"\";\n console.log(`${report.file.padEnd(16)} ${report.state}${detail}`);\n }\n console.log(\n changed === 0\n ? `All stores are at schema v${SCHEMA_VERSION}.`\n : `${options.check ? \"Would migrate\" : \"Migrated\"} ${changed} store file(s) to schema v${SCHEMA_VERSION}.`,\n );\n });\n}\n","/**\n * `omninode security audit` — reviews a project's configuration against the\n * security baseline (roadmap §17) and reports findings. Advisory: it reports,\n * it does not change anything.\n */\nimport type { Command } from \"commander\";\nimport { resolveEnvPolicy } from \"../../agents/env.js\";\nimport { loadProjectConfig } from \"../options.js\";\ntype Severity = \"info\" | \"warn\";\n\ninterface Finding {\n severity: Severity;\n subject: string;\n message: string;\n}\n\nexport function registerSecurityCommand(program: Command): void {\n program\n .command(\"security\")\n .description(\"Inspect a project's security posture (advisory).\")\n .argument(\"[action]\", \"Action to perform.\", \"audit\")\n .action(async (action: string) => {\n if (action !== \"audit\") {\n console.log(`Unknown security action \"${action}\". Available: audit.`);\n return;\n }\n const config = loadProjectConfig();\n const findings: Finding[] = [];\n\n // Agents: environment exposure, working-directory reach, shell usage.\n for (const agent of config.project.agents) {\n const policy = resolveEnvPolicy(agent);\n if (policy === \"inherit\") {\n findings.push({\n severity: \"warn\",\n subject: `agent \"${agent.name}\"`,\n message:\n \"inherits the full environment — provider keys in OmniNode's environment are visible to it. \" +\n 'Consider env_policy: allowlist|denylist|explicit.',\n });\n }\n if (agent.allowExternalCwd) {\n findings.push({\n severity: \"info\",\n subject: `agent \"${agent.name}\"`,\n message: \"may run outside the project root (allow_external_cwd).\",\n });\n }\n if (agent.env && Object.keys(agent.env).length > 0) {\n findings.push({\n severity: \"info\",\n subject: `agent \"${agent.name}\"`,\n message: `receives ${Object.keys(agent.env).length} explicit environment variable(s).`,\n });\n }\n }\n\n // Providers and memory: credentials must be referenced, never inline.\n for (const provider of config.project.providers) {\n if (!provider.apiKeyEnvVar) {\n findings.push({\n severity: \"info\",\n subject: `provider \"${provider.name}\"`,\n message: \"no api_key_env_var — fine for keyless local endpoints, otherwise credentials cannot be resolved.\",\n });\n }\n }\n if (config.project.memory?.provider === \"remembera\" && !config.project.memory.apiKeyEnvVar) {\n findings.push({\n severity: \"warn\",\n subject: \"memory\",\n message: 'Remembera is configured without api_key_env_var; requests will be unauthenticated.',\n });\n }\n\n console.log(`OmniNode security audit — project \"${config.project.name}\"`);\n if (findings.length === 0) {\n console.log(\" no findings.\");\n }\n for (const finding of findings) {\n console.log(` [${finding.severity.toUpperCase()}] ${finding.subject}: ${finding.message}`);\n }\n console.log(\n `\\nTrust model: agents execute with the permissions of the OS user running OmniNode.`,\n );\n console.log(\n `OmniNode does not sandbox agents — run untrusted agents in a container or as a dedicated user.`,\n );\n });\n}\n","/**\n * `omninode config` — inspect the loaded configuration. Secrets are never\n * printed: only environment-variable *references* are shown (roadmap §17).\n */\nimport type { Command } from \"commander\";\nimport { readFileSync } from \"node:fs\";\nimport { parse as parseYaml } from \"yaml\";\nimport { configDiagnostics, loadConfigDetailed, scanForInlineSecrets } from \"../../config/index.js\";\nimport { OmniNodeError } from \"../../errors/index.js\";\nimport { activeConfigPath } from \"../options.js\";\nexport function registerConfigCommands(program: Command): void {\n const config = program\n .command(\"config\")\n .description(\"Inspect the project configuration (omninode.yaml).\");\n\n config\n .command(\"path\")\n .description(\"Print the path of the configuration file in use.\")\n .action(() => {\n const path = activeConfigPath();\n console.log(path ?? \"no omninode.yaml found\");\n });\n\n config\n .command(\"show\")\n .description(\"Print the effective configuration (credential references only, never values).\")\n .option(\"--json\", \"Emit the configuration as JSON.\")\n .action((options: { json?: boolean }) => {\n const resolved = loadConfigDetailed().config;\n const payload = {\n project: resolved.project.name,\n providers: resolved.project.providers.map((p) => ({\n name: p.name,\n type: p.type,\n baseUrl: p.baseUrl,\n apiKeyEnvVar: p.apiKeyEnvVar ?? null,\n })),\n agents: resolved.project.agents.map((a) => ({ name: a.name, command: a.command ?? null, inputMode: a.inputMode })),\n roles: resolved.project.roles.map((r) => r.id),\n pipelines: resolved.project.pipelines.map((p) => p.id),\n memory: resolved.project.memory ?? null,\n logging: resolved.logging ?? null,\n };\n if (options.json) {\n console.log(JSON.stringify(payload, null, 2));\n return;\n }\n console.log(`project: ${payload.project}`);\n console.log(`providers: ${payload.providers.map((p) => `${p.name} (${p.type}, key=${p.apiKeyEnvVar ? `$${p.apiKeyEnvVar}` : \"none\"})`).join(\", \") || \"none\"}`);\n console.log(`agents: ${payload.agents.map((a) => a.name).join(\", \") || \"none\"}`);\n console.log(`roles: ${payload.roles.join(\", \") || \"none\"}`);\n console.log(`pipelines: ${payload.pipelines.join(\", \") || \"none\"}`);\n console.log(`memory: ${payload.memory ? `${payload.memory.provider}${payload.memory.required ? \" (required)\" : \"\"}` : \"not configured\"}`);\n });\n\n config\n .command(\"profiles\")\n .description(\"List the configuration profiles defined in this project.\")\n .action(() => {\n const path = activeConfigPath();\n const raw = path ? (parseYaml(readFileSync(path, \"utf8\")) as { profile?: string; profiles?: Record<string, unknown> }) : {};\n const names = Object.keys(raw.profiles ?? {});\n const active = loadConfigDetailed().sources.profile;\n console.log(`active: ${active}`);\n console.log(`defined: ${names.length > 0 ? names.join(\", \") : \"none (add a `profiles:` section)\"}`);\n });\n\n config\n .command(\"validate\")\n .description(\"Validate the configuration file, including the inline-secret scan.\")\n .action(() => {\n const path = activeConfigPath();\n if (!path) throw new OmniNodeError(\"CONFIG_NOT_FOUND\", \"No omninode.yaml found.\");\n const findings = scanForInlineSecrets(readFileSync(path, \"utf8\"));\n if (findings.length > 0) {\n throw new OmniNodeError(\n \"CONFIG_INVALID\",\n `${path} contains ${findings.length} inline secret(s) (line ${findings.map((f) => f.line).join(\", \")}). Use environment-variable references.`,\n );\n }\n const { config: resolved, sources } = loadConfigDetailed();\n console.log(\n `${path} is valid — project \"${resolved.project.name}\" with ${resolved.project.providers.length} provider(s), ${resolved.project.agents.length} agent(s), ${resolved.project.pipelines.length} pipeline(s).`,\n );\n console.log(` profile: ${sources.profile}`);\n if (sources.userFile) console.log(` user cfg: ${sources.userFile}`);\n if (sources.envOverrides.length > 0) {\n console.log(` env overrides: ${sources.envOverrides.join(\", \")}`);\n }\n if (sources.defaults.length > 0) {\n console.log(` defaults applied: ${sources.defaults.join(\", \")}`);\n }\n const diagnostics = configDiagnostics(resolved);\n if (diagnostics.length > 0) {\n console.log(\" diagnostics:\");\n for (const note of diagnostics) console.log(` - ${note}`);\n }\n });\n}\n","import type { Command } from \"commander\";\nimport { OmniNodeError } from \"../../errors/index.js\";\nimport { createProvider } from \"../../providers/index.js\";\nimport { ModelRegistry } from \"../../registry/index.js\";\nimport type { ModelCapabilities } from \"../../types/model.js\";\nimport { loadProjectConfig } from \"../options.js\";\nconst CAPABILITIES: readonly (keyof ModelCapabilities)[] = [\n \"chat\",\n \"coding\",\n \"tools\",\n \"vision\",\n \"embeddings\",\n];\n\nexport function registerModelsCommand(program: Command): void {\n for (const name of [\"models\", \"model\"] as const) {\n registerModelGroup(program, name);\n }\n}\n\nfunction registerModelGroup(program: Command, name: \"models\" | \"model\"): void {\n program\n .command(name)\n .description(\"Discover and list models from configured providers (model registry, §8).\")\n .argument(\"[provider]\", \"Only discover from this provider.\")\n .option(\"-c, --capability <capability>\", `Filter by capability: ${CAPABILITIES.join(\", \")}.`)\n .option(\"--json\", \"Emit the discovered models as JSON.\")\n .action(async (providerName: string | undefined, options: { capability?: string; json?: boolean }) => {\n const capability = options.capability as keyof ModelCapabilities | undefined;\n if (capability !== undefined && !CAPABILITIES.includes(capability)) {\n throw new OmniNodeError(\n \"CLI_USAGE\",\n `Unknown capability \"${options.capability}\". Valid capabilities: ${CAPABILITIES.join(\", \")}.`,\n );\n }\n\n const config = loadProjectConfig();\n const selected = config.project.providers.filter((p) =>\n providerName ? p.name === providerName : true,\n );\n if (selected.length === 0) {\n if (options.json) {\n console.log(\"[]\");\n return;\n }\n throw new OmniNodeError(\n \"PROVIDER_NOT_FOUND\",\n providerName\n ? `Provider \"${providerName}\" is not configured.`\n : \"No providers configured. Add one with `omninode provider add`.\",\n );\n }\n\n const registry = new ModelRegistry();\n for (const providerConfig of selected) {\n try {\n const provider = createProvider(providerConfig);\n const discovered = await registry.discoverFrom(provider);\n console.log(`${providerConfig.name}: ${discovered.length} model(s)`);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.log(`${providerConfig.name}: discovery failed — ${message}`);\n }\n }\n\n const models = registry.list({\n ...(providerName !== undefined ? { provider: providerName } : {}),\n ...(capability !== undefined ? { capability } : {}),\n });\n if (options.json) {\n console.log(JSON.stringify(models, null, 2));\n return;\n }\n if (models.length === 0) {\n console.log(\"No models found.\");\n return;\n }\n console.log(\"\");\n for (const model of models) {\n console.log(`${model.provider}:${model.id}`);\n }\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,eAAe;;;ACFjB,IAAM,mBAAmB;;;ACMzB,IAAM,OAAO;AAAA,EAClB,SAAS;AAAA,EACT,SAAS;AAAA,EACT,cAAc;AAAA,EACd,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,OAAO;AAAA,EACP,SAAS;AAAA,EACT,WAAW;AAAA,EACX,UAAU;AAAA,EACV,gBAAgB;AAClB;AAKO,SAAS,YAAY,OAAwB;AAClD,MAAI,CAAC,gBAAgB,KAAK,EAAG,QAAO,KAAK;AACzC,QAAM,OAAO,MAAM;AACnB,MAAI,SAAS,kBAAmB,QAAO,KAAK;AAC5C,MAAI,SAAS,gBAAiB,QAAO,KAAK;AAC1C,MAAI,KAAK,WAAW,SAAS,EAAG,QAAO,KAAK;AAC5C,MAAI,KAAK,WAAW,WAAW,KAAK,SAAS,kBA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AA2B;AAElC,MAAI;AACF,UAAM,WAAW,kBAAkB;AACnC,QAAI,SAAS,QAAS,iBAAgB,SAAS,OAAO;AAAA,EACxD,QAAQ;AAAA,EAER;AACF;AAEA,eAAsB,IAAI,MAA+B;AACvD,qBAAmB;AACnB,QAAM,UAAU,cAAc;AAC9B,MAAI;AACF,UAAM,QAAQ,WAAW,IAAI;AAAA,EAC/B,SAAS,OAAO;AACd,gBAAY,KAAK;AAAA,EACnB;AACF;AAEO,SAAS,YAAY,OAAuB;AACjD,QAAM,OAAO,YAAY,KAAK;AAC9B,MAAI,gBAAgB,KAAK,GAAG;AAC1B,YAAQ,MAAM,WAAW,MAAM,IAAI,KAAK,MAAM,OAAO,EAAE;AACvD,QAAI,MAAM,YAAY,QAAW;AAC/B,cAAQ,MAAM,KAAK,UAAU,MAAM,SAAS,MAAM,CAAC,CAAC;AAAA,IACtD;AACA,YAAQ,KAAK,IAAI;AAAA,EACnB;AACA,UAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AACpE,UAAQ,KAAK,IAAI;AACnB;AAEA,IAAM,QAAQ,QAAQ,KAAK,CAAC,IACxB,cAAc,aAAa,QAAQ,KAAK,CAAC,CAAC,CAAC,EAAE,OAC7C;AACJ,IAAI,YAAY,QAAQ,OAAO;AAC7B,MAAI,QAAQ,IAAI,EAAE,MAAM,CAAC,UAAU,YAAY,KAAK,CAAC;AACvD;","names":["path","existsSync","existsSync","readFileSync","writeFileSync","parseDocument","readFileSync","writeFileSync","readFileSync","writeFileSync","envelope","resolve","path","entry","entry","entry","run","run","createProvider","provider","parseDocument","readFileSync","entry","writeFileSync","resolve","mkdir","readFile","dirname","mkdir","dirname","readFile","agent","role","truncate","randomBytes","z","randomBytes","truncate","truncate","entry","position","readFileSync","writeFileSync","parseDocument","randomBytes","randomBytes","SEVERITY_RANK","truncate","randomBytes","z","entry","randomBytes","run","randomBytes","run","parseDocument","readFileSync","writeFileSync","entry","service","path","readFileSync","parseYaml","path","parseYaml","readFileSync"]}