agentix-cli 0.23.0 → 0.25.0
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.
- package/LICENSE +21 -0
- package/README.md +102 -103
- package/agentx.example.json +9 -3
- package/dist/App-6Y7B3YQH.js +8 -0
- package/dist/App-6Y7B3YQH.js.map +1 -0
- package/dist/ChatApp-KIEUJ2DS.js +7 -0
- package/dist/ChatApp-KIEUJ2DS.js.map +1 -0
- package/dist/{agent-FSE4KRLX.js → agent-QGZIAZMY.js} +2 -2
- package/dist/architect-SEPWMWS4.js +2 -0
- package/dist/{board-dashboard-PUACKWAN.js → board-dashboard-CQ5F4GPD.js} +3756 -1010
- package/dist/board-dashboard-CQ5F4GPD.js.map +1 -0
- package/dist/builtin-FRKAQMFS.js +2 -0
- package/dist/chunk-2WVX3LEC.js +2 -0
- package/dist/chunk-2WVX3LEC.js.map +1 -0
- package/dist/chunk-3WQFCIB6.js +24 -0
- package/dist/chunk-3WQFCIB6.js.map +1 -0
- package/dist/chunk-53GCFZPR.js +116 -0
- package/dist/chunk-53GCFZPR.js.map +1 -0
- package/dist/{chunk-IKBHHTIT.js → chunk-5U35WAZF.js} +2 -2
- package/dist/chunk-67Q4DCPS.js +54 -0
- package/dist/chunk-67Q4DCPS.js.map +1 -0
- package/dist/chunk-76Z4VHDX.js +8 -0
- package/dist/chunk-76Z4VHDX.js.map +1 -0
- package/dist/{chunk-7P5QRX5W.js → chunk-BFXONUUN.js} +2 -2
- package/dist/{chunk-DXTIG5YV.js → chunk-FDMWOPEL.js} +2 -2
- package/dist/chunk-FDWOECJY.js +54 -0
- package/dist/chunk-FDWOECJY.js.map +1 -0
- package/dist/chunk-G57RZCXM.js +5 -0
- package/dist/chunk-G57RZCXM.js.map +1 -0
- package/dist/{chunk-NOF4HSGK.js → chunk-H5D7ATXS.js} +2 -2
- package/dist/chunk-HA3XI7Z2.js +155 -0
- package/dist/chunk-HA3XI7Z2.js.map +1 -0
- package/dist/chunk-HR4JSRZS.js +3 -0
- package/dist/{chunk-A6BKSZQA.js.map → chunk-HR4JSRZS.js.map} +1 -1
- package/dist/chunk-I3SIXTJO.js +44 -0
- package/dist/chunk-I3SIXTJO.js.map +1 -0
- package/dist/chunk-ISEBLHWX.js +118 -0
- package/dist/chunk-ISEBLHWX.js.map +1 -0
- package/dist/{chunk-4ITQP3XL.js → chunk-JP5IEXR7.js} +2 -2
- package/dist/chunk-JXWAGMI2.js +13 -0
- package/dist/chunk-JXWAGMI2.js.map +1 -0
- package/dist/chunk-KUCCW2VG.js +431 -0
- package/dist/chunk-KUCCW2VG.js.map +1 -0
- package/dist/chunk-LDHPMJ7M.js +257 -0
- package/dist/chunk-LDHPMJ7M.js.map +1 -0
- package/dist/{chunk-KWUWZQGV.js → chunk-LNXCJWOU.js} +29 -30
- package/dist/chunk-LNXCJWOU.js.map +1 -0
- package/dist/chunk-M4AMWP3H.js +178 -0
- package/dist/chunk-M4AMWP3H.js.map +1 -0
- package/dist/chunk-NGSIRE4X.js +126 -0
- package/dist/chunk-NGSIRE4X.js.map +1 -0
- package/dist/{chunk-CNNLREHD.js → chunk-P4VWIVKN.js} +268 -410
- package/dist/chunk-P4VWIVKN.js.map +1 -0
- package/dist/chunk-Q6YO7LYE.js +47 -0
- package/dist/chunk-Q6YO7LYE.js.map +1 -0
- package/dist/chunk-TMKLHTCG.js +971 -0
- package/dist/chunk-TMKLHTCG.js.map +1 -0
- package/dist/chunk-TRJTTBE2.js +7 -0
- package/dist/chunk-TRJTTBE2.js.map +1 -0
- package/dist/chunk-U2CKL755.js +4 -0
- package/dist/chunk-U2CKL755.js.map +1 -0
- package/dist/chunk-UCQ2N3KO.js +9 -0
- package/dist/chunk-UCQ2N3KO.js.map +1 -0
- package/dist/chunk-W4YR2RO2.js +2 -0
- package/dist/chunk-W4YR2RO2.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/client-GGVVLOOF.js +2 -0
- package/dist/{compaction-BTUJJ3LJ.js → compaction-NWEMOSHA.js} +3 -3
- package/dist/config-7FSZFRTQ.js +2 -0
- package/dist/config-mutator-POCOYYJ4.js +2 -0
- package/dist/{context-planner-I7ID7XF3.js → context-planner-45GEWKGL.js} +2 -2
- package/dist/doctor-DHLBEKA4.js +2 -0
- package/dist/heal-HZ3EQD52.js +2 -0
- package/dist/index.d.ts +1193 -225
- package/dist/index.js +12 -12
- package/dist/index.js.map +1 -1
- package/dist/memory-extract-AENFVVO5.js +2 -0
- package/dist/processes-UIC4XXA6.js +2 -0
- package/dist/program-WVAVJFND.js +2 -0
- package/dist/projects-api-KRME2YKZ.js +2 -0
- package/dist/projects-api-KRME2YKZ.js.map +1 -0
- package/dist/projects-mutate-3NHVG437.js +7 -0
- package/dist/projects-mutate-3NHVG437.js.map +1 -0
- package/dist/providers-L27BJ5A6.js +2 -0
- package/dist/registry-T36ZIAWV.js +2 -0
- package/dist/rotation-memo-B3EXXSEH.js +13 -0
- package/dist/rotation-memo-B3EXXSEH.js.map +1 -0
- package/dist/scheduler-GH7TIKYS.js +2 -0
- package/dist/surface-usage-PRL6Z4U3.js +2 -0
- package/dist/wiki-M6YNRFC4.js +2 -0
- package/dist/workflows/templates/branching.yaml +75 -0
- package/dist/workflows/templates/extract.yaml +59 -0
- package/dist/workflows/templates/linear.yaml +37 -0
- package/dist/workflows/templates/retry.yaml +61 -0
- package/dist/workspace-setup-TBQAHYHJ.js +2 -0
- package/package.json +10 -3
- package/dist/board-dashboard-PUACKWAN.js.map +0 -1
- package/dist/builtin-TQKMR42Z.js +0 -2
- package/dist/chunk-3SHMHYPD.js +0 -450
- package/dist/chunk-3SHMHYPD.js.map +0 -1
- package/dist/chunk-4INOOHND.js +0 -6
- package/dist/chunk-4INOOHND.js.map +0 -1
- package/dist/chunk-5F3J55LG.js +0 -2
- package/dist/chunk-5F3J55LG.js.map +0 -1
- package/dist/chunk-72PAN7UI.js +0 -103
- package/dist/chunk-72PAN7UI.js.map +0 -1
- package/dist/chunk-A6BKSZQA.js +0 -3
- package/dist/chunk-BHSPAP4U.js +0 -44
- package/dist/chunk-BHSPAP4U.js.map +0 -1
- package/dist/chunk-BOUKM2PS.js +0 -163
- package/dist/chunk-BOUKM2PS.js.map +0 -1
- package/dist/chunk-CDNWCYF7.js +0 -2
- package/dist/chunk-CDNWCYF7.js.map +0 -1
- package/dist/chunk-CNNLREHD.js.map +0 -1
- package/dist/chunk-EK37JHJI.js +0 -13
- package/dist/chunk-EK37JHJI.js.map +0 -1
- package/dist/chunk-EQPUB7CZ.js +0 -685
- package/dist/chunk-EQPUB7CZ.js.map +0 -1
- package/dist/chunk-EW27SCCC.js +0 -2
- package/dist/chunk-EW27SCCC.js.map +0 -1
- package/dist/chunk-GOLZ6NEL.js +0 -111
- package/dist/chunk-GOLZ6NEL.js.map +0 -1
- package/dist/chunk-JGXE2YNV.js +0 -46
- package/dist/chunk-JGXE2YNV.js.map +0 -1
- package/dist/chunk-KWUWZQGV.js.map +0 -1
- package/dist/chunk-MTRWXRFF.js +0 -380
- package/dist/chunk-MTRWXRFF.js.map +0 -1
- package/dist/chunk-N67JZAXU.js +0 -2
- package/dist/chunk-N67JZAXU.js.map +0 -1
- package/dist/chunk-PD5Q7D6Z.js +0 -7
- package/dist/chunk-PD5Q7D6Z.js.map +0 -1
- package/dist/chunk-Q6CAFGXT.js +0 -118
- package/dist/chunk-Q6CAFGXT.js.map +0 -1
- package/dist/chunk-WJXU5F4Z.js +0 -53
- package/dist/chunk-WJXU5F4Z.js.map +0 -1
- package/dist/chunk-ZZFXI3CS.js +0 -8
- package/dist/chunk-ZZFXI3CS.js.map +0 -1
- package/dist/config-ADS54KLC.js +0 -2
- package/dist/config-mutator-WTRMBZTO.js +0 -2
- package/dist/doctor-T6RB4Q5X.js +0 -2
- package/dist/editor-chat-RVLCKKB7.js +0 -137
- package/dist/editor-chat-RVLCKKB7.js.map +0 -1
- package/dist/heal-YEQYWX2L.js +0 -2
- package/dist/inbox-BIN2S5XN.js +0 -2
- package/dist/memory-extract-KRCHD3OP.js +0 -2
- package/dist/processes-RJ6RDP32.js +0 -2
- package/dist/program-V7NGFB2R.js +0 -2
- package/dist/providers-WVCMIW67.js +0 -2
- package/dist/registry-42HEWCLA.js +0 -2
- package/dist/rotation-memo-GMTZPMNE.js +0 -13
- package/dist/rotation-memo-GMTZPMNE.js.map +0 -1
- package/dist/scheduler-C56ABAVP.js +0 -2
- package/dist/slack-6P7ZJ32Y.js +0 -3
- package/dist/slack-6P7ZJ32Y.js.map +0 -1
- package/dist/store-BAPDZHXE.js +0 -2
- package/dist/task-store-RHISEU6V.js +0 -2
- package/dist/telegram-PIYDRM46.js +0 -3
- package/dist/telegram-PIYDRM46.js.map +0 -1
- package/dist/types-ZRLHHCGB.js +0 -2
- package/dist/web/workflow-editor.global.js +0 -1452
- package/dist/web/workflow-editor.global.js.map +0 -1
- package/dist/whatsapp-PFRDMUMT.js +0 -3
- package/dist/whatsapp-PFRDMUMT.js.map +0 -1
- package/dist/wiki-53W5NLZV.js +0 -2
- package/dist/workspace-setup-DQCZX2NE.js +0 -2
- package/dist/workspace-setup-DQCZX2NE.js.map +0 -1
- /package/dist/{agent-FSE4KRLX.js.map → agent-QGZIAZMY.js.map} +0 -0
- /package/dist/{builtin-TQKMR42Z.js.map → architect-SEPWMWS4.js.map} +0 -0
- /package/dist/{config-ADS54KLC.js.map → builtin-FRKAQMFS.js.map} +0 -0
- /package/dist/{chunk-IKBHHTIT.js.map → chunk-5U35WAZF.js.map} +0 -0
- /package/dist/{chunk-7P5QRX5W.js.map → chunk-BFXONUUN.js.map} +0 -0
- /package/dist/{chunk-DXTIG5YV.js.map → chunk-FDMWOPEL.js.map} +0 -0
- /package/dist/{chunk-NOF4HSGK.js.map → chunk-H5D7ATXS.js.map} +0 -0
- /package/dist/{chunk-4ITQP3XL.js.map → chunk-JP5IEXR7.js.map} +0 -0
- /package/dist/{config-mutator-WTRMBZTO.js.map → client-GGVVLOOF.js.map} +0 -0
- /package/dist/{compaction-BTUJJ3LJ.js.map → compaction-NWEMOSHA.js.map} +0 -0
- /package/dist/{doctor-T6RB4Q5X.js.map → config-7FSZFRTQ.js.map} +0 -0
- /package/dist/{heal-YEQYWX2L.js.map → config-mutator-POCOYYJ4.js.map} +0 -0
- /package/dist/{context-planner-I7ID7XF3.js.map → context-planner-45GEWKGL.js.map} +0 -0
- /package/dist/{inbox-BIN2S5XN.js.map → doctor-DHLBEKA4.js.map} +0 -0
- /package/dist/{memory-extract-KRCHD3OP.js.map → heal-HZ3EQD52.js.map} +0 -0
- /package/dist/{processes-RJ6RDP32.js.map → memory-extract-AENFVVO5.js.map} +0 -0
- /package/dist/{program-V7NGFB2R.js.map → processes-UIC4XXA6.js.map} +0 -0
- /package/dist/{providers-WVCMIW67.js.map → program-WVAVJFND.js.map} +0 -0
- /package/dist/{registry-42HEWCLA.js.map → providers-L27BJ5A6.js.map} +0 -0
- /package/dist/{scheduler-C56ABAVP.js.map → registry-T36ZIAWV.js.map} +0 -0
- /package/dist/{store-BAPDZHXE.js.map → scheduler-GH7TIKYS.js.map} +0 -0
- /package/dist/{task-store-RHISEU6V.js.map → surface-usage-PRL6Z4U3.js.map} +0 -0
- /package/dist/{types-ZRLHHCGB.js.map → wiki-M6YNRFC4.js.map} +0 -0
- /package/dist/{wiki-53W5NLZV.js.map → workspace-setup-TBQAHYHJ.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/crons/scheduler.ts","../src/intent/mode.ts","../src/intent/ledger.ts","../src/intent/ulid.ts","../src/intent/instance.ts","../src/intent/governance.ts","../src/intent/decide.ts","../src/intent/divergence.ts","../src/intent/sources/cron.ts"],"sourcesContent":["import type { DaemonConfig, CronJobDef } from \"@/daemon/config\"\nimport type { AgentRegistry } from \"@/agents/registry\"\nimport type { HookRegistry } from \"@/hooks\"\nimport type { CronJobState, CronRunResult } from \"./types\"\nimport { writeFileSync, mkdirSync, existsSync, readFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { applyConfigMutation, setAtPath } from \"@/daemon/config-mutator\"\nimport { getLedgerMode } from \"@/intent/mode\"\nimport { getDefaultLedger } from \"@/intent/instance\"\nimport { recordCronDispatch } from \"@/intent/sources/cron\"\n\n// --- Cron Scheduler: lightweight cron engine with timezone support ---\n// No external dependencies — uses setTimeout-based scheduling.\n\n/**\n * Append a soft output-length cap to a cron prompt when the job configured\n * `maxOutputTokens`. Claude Code CLI has no hard flag for output length,\n * but a clear instruction at the end of the prompt is reliably honored by\n * the model. Keeps a cheap knob available for operators without us needing\n * to invent our own token counter or hack a post-response truncate.\n */\nfunction withOutputCap(prompt: string, maxOutputTokens?: number): string {\n if (!maxOutputTokens) return prompt\n const approxChars = maxOutputTokens * 4\n return `${prompt}\\n\\n[Response budget]\\nKeep your response under ~${maxOutputTokens} tokens (~${approxChars} chars). Be concise — this is automated batch work, not a conversation.`\n}\n\n/**\n * Parse a cron expression into next-fire timestamp.\n * Supports standard 5-field format: minute hour day-of-month month day-of-week\n */\nfunction parseCronField(field: string, min: number, max: number): number[] {\n const values: number[] = []\n\n for (const part of field.split(\",\")) {\n if (part === \"*\") {\n for (let i = min; i <= max; i++) values.push(i)\n } else if (part.includes(\"/\")) {\n const [range, stepStr] = part.split(\"/\")\n const step = parseInt(stepStr, 10)\n const start = range === \"*\" ? min : parseInt(range, 10)\n for (let i = start; i <= max; i += step) values.push(i)\n } else if (part.includes(\"-\")) {\n const [a, b] = part.split(\"-\").map(Number)\n for (let i = a; i <= b; i++) values.push(i)\n } else {\n values.push(parseInt(part, 10))\n }\n }\n\n return [...new Set(values)].sort((a, b) => a - b)\n}\n\nexport function getNextCronDate(expression: string, after: Date, timezone: string): Date {\n const fields = expression.trim().split(/\\s+/)\n if (fields.length !== 5) throw new Error(`Invalid cron: ${expression}`)\n\n const minutes = parseCronField(fields[0], 0, 59)\n const hours = parseCronField(fields[1], 0, 23)\n const daysOfMonth = parseCronField(fields[2], 1, 31)\n const months = parseCronField(fields[3], 1, 12)\n const daysOfWeek = parseCronField(fields[4], 0, 6)\n\n // Convert to timezone-aware date\n const fmt = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: timezone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n hour12: false,\n })\n\n // Start searching from next minute\n const candidate = new Date(after.getTime() + 60_000)\n candidate.setSeconds(0, 0)\n\n // Search up to 1 year ahead\n const limit = new Date(candidate.getTime() + 366 * 24 * 60 * 60 * 1000)\n\n while (candidate < limit) {\n const parts = fmt.formatToParts(candidate)\n const get = (type: string) => parseInt(parts.find((p) => p.type === type)?.value || \"0\", 10)\n\n const m = get(\"minute\")\n const h = get(\"hour\")\n const dom = get(\"day\")\n const mon = get(\"month\")\n const dow = candidate.getDay()\n\n if (\n minutes.includes(m) &&\n hours.includes(h) &&\n daysOfMonth.includes(dom) &&\n months.includes(mon) &&\n daysOfWeek.includes(dow)\n ) {\n return candidate\n }\n\n // Advance by 1 minute\n candidate.setTime(candidate.getTime() + 60_000)\n }\n\n throw new Error(`No next run found for cron \"${expression}\" within 1 year`)\n}\n\n// Retry config (inspired by OpenClaw's exponential backoff)\nconst MAX_RETRIES = 5\nconst RETRY_DELAYS = [30_000, 60_000, 300_000, 900_000, 3_600_000] // 30s, 1m, 5m, 15m, 60m\n\n/** Notification callback — injected by daemon to send alerts via channels */\nexport type CronNotifyCallback = (jobId: string, agent: string, error: string, consecutiveErrors: number) => Promise<void>\n\nexport class CronScheduler {\n private jobs: Map<string, CronJobState> = new Map()\n private timers: Map<string, ReturnType<typeof setTimeout>> = new Map()\n private registry: AgentRegistry\n private hooks?: HookRegistry\n private runsDir: string\n private lastRunFile: string\n private running = false\n private notifyCallback?: CronNotifyCallback\n private log: (...args: unknown[]) => void\n\n constructor(\n config: DaemonConfig,\n registry: AgentRegistry,\n hooks?: HookRegistry,\n log: (...args: unknown[]) => void = console.error.bind(console, \"[cron]\"),\n ) {\n this.registry = registry\n this.hooks = hooks\n this.log = log\n this.runsDir = resolve(process.cwd(), \".agentx/cron/runs\")\n this.lastRunFile = resolve(process.cwd(), \".agentx/cron/last-runs.json\")\n\n for (const [id, def] of Object.entries(config.crons)) {\n this.jobs.set(id, {\n id,\n enabled: def.enabled,\n schedule: def.schedule,\n timezone: def.timezone,\n agent: def.agent,\n prompt: def.prompt,\n timeout: def.timeout,\n model: def.model,\n maxOutputTokens: def.maxOutputTokens,\n onError: def.onError,\n consecutiveErrors: 0,\n totalRuns: 0,\n totalFailures: 0,\n })\n }\n }\n\n /**\n * Set a notification callback for failed crons.\n * Called when onError is \"notify\" or after multiple consecutive failures.\n */\n setNotifyCallback(cb: CronNotifyCallback): void {\n this.notifyCallback = cb\n }\n\n async start(): Promise<void> {\n this.running = true\n\n if (!existsSync(this.runsDir)) {\n mkdirSync(this.runsDir, { recursive: true })\n }\n\n // Detect missed runs before scheduling\n const missedRuns = this.detectMissedRuns()\n if (missedRuns.length > 0) {\n this.log(`Detected ${missedRuns.length} missed cron run(s) while daemon was down:`)\n for (const { jobId, missedAt } of missedRuns) {\n this.log(` \"${jobId}\" should have run at ${missedAt.toISOString()}`)\n }\n // Execute missed runs (fire-and-forget, don't block startup)\n this.executeMissedRuns(missedRuns).catch((e) => {\n this.log(`Error executing missed runs: ${e.message}`)\n })\n }\n\n for (const [id, job] of this.jobs) {\n if (!job.enabled) {\n this.log(`Job \"${id}\" is disabled, skipping`)\n continue\n }\n this.scheduleNext(id)\n }\n\n this.log(`${this.jobs.size} cron job(s) loaded, ${Array.from(this.jobs.values()).filter((j) => j.enabled).length} enabled`)\n }\n\n async stop(): Promise<void> {\n this.running = false\n for (const timer of this.timers.values()) {\n clearTimeout(timer)\n }\n this.timers.clear()\n\n // Persist last run times for missed run detection on next start\n this.saveLastRuns()\n }\n\n private scheduleNext(jobId: string): void {\n const job = this.jobs.get(jobId)\n if (!job || !job.enabled || !this.running) return\n\n // Clear any existing timer\n const existing = this.timers.get(jobId)\n if (existing) clearTimeout(existing)\n\n try {\n const nextRun = getNextCronDate(job.schedule, new Date(), job.timezone)\n job.nextRun = nextRun\n job.retryPending = false\n const delay = nextRun.getTime() - Date.now()\n\n this.log(`Job \"${jobId}\" next run: ${nextRun.toISOString()} (in ${Math.round(delay / 1000)}s)`)\n\n const timer = setTimeout(() => this.executeJob(jobId), delay)\n this.timers.set(jobId, timer)\n } catch (e: any) {\n this.log(`Failed to schedule \"${jobId}\": ${e.message}`)\n }\n }\n\n private scheduleRetry(jobId: string, attempt: number): void {\n const job = this.jobs.get(jobId)\n if (!job || !job.enabled || !this.running) return\n if (attempt >= MAX_RETRIES) {\n this.log(`Job \"${jobId}\" exhausted all ${MAX_RETRIES} retries, scheduling next regular run`)\n this.scheduleNext(jobId)\n return\n }\n\n const delay = RETRY_DELAYS[attempt] || RETRY_DELAYS[RETRY_DELAYS.length - 1]\n job.retryPending = true\n\n this.log(`Job \"${jobId}\" retry ${attempt + 1}/${MAX_RETRIES} in ${Math.round(delay / 1000)}s`)\n\n const timer = setTimeout(() => this.executeJob(jobId, attempt + 1), delay)\n this.timers.set(jobId, timer)\n }\n\n /**\n * Phase 1 commit 6.d — record one cron-fire decision in the ledger\n * when the source is enabled. Wrapped in try/catch so a ledger\n * failure can never break cron dispatch — legacy stays authoritative\n * until the 1c per-source promotion lands.\n */\n private recordCronDecisionInLedger(\n jobId: string,\n agentId: string,\n firedAt: Date,\n legacy: import(\"@/intent/divergence\").LegacyOutcome,\n ): { eventId: string; decidedBy: string } | undefined {\n if (getLedgerMode(\"cron\") === \"off\") return undefined\n try {\n const decision = recordCronDispatch(\n getDefaultLedger(),\n { jobId, agentId, firedAt },\n JSON.stringify({ jobId, agentId, firedAt: firedAt.toISOString() }),\n legacy,\n )\n if (decision.outcome === \"dispatched\") {\n return { eventId: decision.eventId, decidedBy: decision.decidedBy }\n }\n return undefined\n } catch (e: any) {\n this.log(`[ledger] cron \"${jobId}\" record failed: ${e?.message ?? e}`)\n return undefined\n }\n }\n\n private async executeJob(jobId: string, retryAttempt: number = 0): Promise<void> {\n const job = this.jobs.get(jobId)\n if (!job || !this.running) return\n\n const isRetry = retryAttempt > 0\n // firedAt is captured here (rather than below at the original\n // `startedAt` declaration) so the ledger event has a stable\n // sourceEventId regardless of whether we record at the hook-block\n // path or the dispatch path.\n const firedAt = new Date()\n\n // Pre-hook\n if (this.hooks?.has(\"pre:cron-run\" as any)) {\n const hookResult = await this.hooks.execute(\"pre:cron-run\" as any, {\n event: \"pre:cron-run\" as any,\n jobId,\n agent: job.agent,\n prompt: job.prompt,\n })\n if (hookResult.blocked) {\n this.log(`Job \"${jobId}\" blocked by hook: ${hookResult.message}`)\n this.recordCronDecisionInLedger(jobId, job.agent, firedAt, {\n agentId: null, outcome: \"halted\",\n reason: `pre-hook blocked: ${hookResult.message ?? \"\"}`.trim(),\n })\n this.scheduleNext(jobId)\n return\n }\n }\n\n this.log(`${isRetry ? `[retry ${retryAttempt}] ` : \"\"}Executing job \"${jobId}\" -> agent \"${job.agent}\"`)\n const startedAt = firedAt\n job.lastRun = startedAt\n job.totalRuns++\n\n // Phase 1 commit 6.d — record the dispatch decision before the\n // (potentially long-running) registry.execute call. The returned\n // intentRef threads through to registry.execute so it records a\n // resolution on completion.\n const intentRef = this.recordCronDecisionInLedger(jobId, job.agent, firedAt, {\n agentId: job.agent, outcome: \"dispatched\", reason: isRetry ? `retry ${retryAttempt}` : null,\n })\n\n try {\n const response = await this.registry.execute({\n message: withOutputCap(job.prompt, job.maxOutputTokens),\n agentId: job.agent,\n model: job.model,\n intentRef,\n // chatId per-job so different cron jobs for the same agent don't\n // collide in one \"default\" session. Without this, the marketing\n // daily-brief and the marketing weekly-report cron share history,\n // and one job's prompt context bleeds into the other.\n context: { channel: \"cron\", chatId: `cron:${jobId}` },\n })\n\n const result: CronRunResult = {\n jobId,\n startedAt,\n completedAt: new Date(),\n success: !response.error,\n response: response.content,\n error: response.error,\n duration: response.duration || Date.now() - startedAt.getTime(),\n isRetry,\n retryAttempt,\n }\n\n if (response.error) {\n job.consecutiveErrors++\n job.totalFailures++\n job.lastError = response.error\n this.log(`Job \"${jobId}\" failed (${job.consecutiveErrors} consecutive): ${response.error}`)\n\n // Notify on failure\n await this.notifyFailure(job, response.error)\n\n if (job.onError.includes(\"disable\") && job.consecutiveErrors >= 3) {\n job.enabled = false\n this.log(`Job \"${jobId}\" disabled after ${job.consecutiveErrors} consecutive errors`)\n // Persist to agentx.json so a daemon restart doesn't resurrect the\n // broken cron (previously this was in-memory only — a repeatedly\n // failing cron would keep burning money across restarts).\n try {\n const res = await applyConfigMutation(\n (cfg) => setAtPath(cfg, `crons.${jobId}.enabled`, false),\n { reload: false },\n )\n if (!res.success) {\n this.log(`Failed to persist disable for \"${jobId}\": ${res.error}`)\n }\n } catch (e: any) {\n this.log(`Failed to persist disable for \"${jobId}\": ${e.message}`)\n }\n await this.notifyDisabled(job)\n }\n\n // Retry\n this.logRun(result)\n this.scheduleRetry(jobId, retryAttempt)\n return\n } else {\n // Success — reset error state\n if (job.consecutiveErrors > 0) {\n this.log(`Job \"${jobId}\" recovered after ${job.consecutiveErrors} failure(s)`)\n }\n job.consecutiveErrors = 0\n job.lastSuccess = new Date()\n job.lastError = undefined\n job.retryPending = false\n this.log(`Job \"${jobId}\" completed in ${result.duration}ms`)\n }\n\n // Log run\n this.logRun(result)\n\n // Post-hook\n if (this.hooks?.has(\"post:cron-run\" as any)) {\n await this.hooks.execute(\"post:cron-run\" as any, {\n event: \"post:cron-run\" as any,\n jobId,\n success: result.success,\n duration: result.duration,\n error: result.error ? new Error(result.error) : undefined,\n })\n }\n } catch (e: any) {\n job.consecutiveErrors++\n job.totalFailures++\n job.lastError = e.message\n this.log(`Job \"${jobId}\" threw: ${e.message}`)\n\n await this.notifyFailure(job, e.message)\n this.scheduleRetry(jobId, retryAttempt)\n return\n }\n\n // Persist last run time\n this.saveLastRuns()\n\n // Schedule next regular run\n this.scheduleNext(jobId)\n }\n\n // --- Missed run detection ---\n\n /**\n * Detect cron jobs that should have fired while the daemon was down.\n * Compares saved last-run times against the cron schedule.\n */\n private detectMissedRuns(): Array<{ jobId: string; missedAt: Date }> {\n const missed: Array<{ jobId: string; missedAt: Date }> = []\n\n const lastRuns = this.loadLastRuns()\n if (!lastRuns) return missed // First boot — no history\n\n for (const [jobId, job] of this.jobs) {\n if (!job.enabled) continue\n\n const lastRunStr = lastRuns[jobId]\n if (!lastRunStr) continue // Never ran before\n\n const lastRun = new Date(lastRunStr)\n try {\n // What SHOULD the next run have been after the last recorded run?\n const shouldHaveRun = getNextCronDate(job.schedule, lastRun, job.timezone)\n if (shouldHaveRun.getTime() < Date.now()) {\n missed.push({ jobId, missedAt: shouldHaveRun })\n }\n } catch {\n // Invalid schedule — skip\n }\n }\n\n return missed\n }\n\n /**\n * Execute missed runs (catch-up). Runs sequentially to avoid overwhelming agents.\n */\n private async executeMissedRuns(missed: Array<{ jobId: string; missedAt: Date }>): Promise<void> {\n for (const { jobId, missedAt } of missed) {\n const job = this.jobs.get(jobId)\n if (!job || !job.enabled) continue\n\n this.log(`Running missed job \"${jobId}\" (was due at ${missedAt.toISOString()})`)\n\n try {\n const response = await this.registry.execute({\n message: withOutputCap(\n `[MISSED RUN — was scheduled for ${missedAt.toISOString()}]\\n\\n${job.prompt}`,\n job.maxOutputTokens,\n ),\n agentId: job.agent,\n context: { channel: \"cron\", chatId: `cron:${jobId}` },\n })\n\n const result: CronRunResult = {\n jobId,\n startedAt: new Date(),\n completedAt: new Date(),\n success: !response.error,\n response: response.content,\n error: response.error,\n duration: response.duration || 0,\n isRetry: false,\n }\n\n this.logRun(result)\n\n if (response.error) {\n this.log(`Missed job \"${jobId}\" failed: ${response.error}`)\n } else {\n this.log(`Missed job \"${jobId}\" completed`)\n job.lastSuccess = new Date()\n }\n job.lastRun = new Date()\n job.totalRuns++\n } catch (e: any) {\n this.log(`Missed job \"${jobId}\" threw: ${e.message}`)\n }\n }\n\n this.saveLastRuns()\n }\n\n // --- Notification ---\n\n private async notifyFailure(job: CronJobState, error: string): Promise<void> {\n if (!job.onError.includes(\"notify\") && job.consecutiveErrors < 2) return\n if (!this.notifyCallback) {\n this.log(`[ALERT] Cron \"${job.id}\" failed (${job.consecutiveErrors}x): ${error.slice(0, 200)}`)\n return\n }\n\n try {\n await this.notifyCallback(job.id, job.agent, error, job.consecutiveErrors)\n } catch {\n // Don't fail on notification errors\n }\n }\n\n private async notifyDisabled(job: CronJobState): Promise<void> {\n if (!this.notifyCallback) {\n this.log(`[ALERT] Cron \"${job.id}\" has been DISABLED after ${job.consecutiveErrors} consecutive failures`)\n return\n }\n\n try {\n await this.notifyCallback(\n job.id,\n job.agent,\n `AUTO-DISABLED after ${job.consecutiveErrors} consecutive failures. Last error: ${job.lastError || \"unknown\"}`,\n job.consecutiveErrors,\n )\n } catch {\n // Don't fail on notification errors\n }\n }\n\n // --- Persistence ---\n\n private saveLastRuns(): void {\n try {\n const data: Record<string, string> = {}\n for (const [id, job] of this.jobs) {\n if (job.lastRun) data[id] = job.lastRun.toISOString()\n }\n const dir = resolve(process.cwd(), \".agentx/cron\")\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true })\n writeFileSync(this.lastRunFile, JSON.stringify(data, null, 2))\n } catch {\n // Best-effort\n }\n }\n\n private loadLastRuns(): Record<string, string> | null {\n try {\n if (!existsSync(this.lastRunFile)) return null\n return JSON.parse(readFileSync(this.lastRunFile, \"utf-8\"))\n } catch {\n return null\n }\n }\n\n private logRun(result: CronRunResult): void {\n try {\n const runDir = resolve(this.runsDir, result.jobId)\n if (!existsSync(runDir)) {\n mkdirSync(runDir, { recursive: true })\n }\n\n const filename = `${result.startedAt.toISOString().replace(/[:.]/g, \"-\")}.json`\n writeFileSync(\n resolve(runDir, filename),\n JSON.stringify(result, null, 2),\n )\n } catch {\n // Don't fail on logging errors\n }\n }\n\n /**\n * List all jobs and their status (including failure info).\n */\n list(): CronJobState[] {\n return Array.from(this.jobs.values())\n }\n\n /**\n * Get a health summary of cron jobs.\n */\n health(): { healthy: number; failing: number; disabled: number; missed: number; jobs: Array<{ id: string; status: string; consecutiveErrors: number; lastError?: string }> } {\n const jobs = Array.from(this.jobs.values())\n const missed = this.detectMissedRuns()\n\n return {\n healthy: jobs.filter(j => j.enabled && j.consecutiveErrors === 0).length,\n failing: jobs.filter(j => j.enabled && j.consecutiveErrors > 0).length,\n disabled: jobs.filter(j => !j.enabled).length,\n missed: missed.length,\n jobs: jobs.map(j => ({\n id: j.id,\n status: !j.enabled ? \"disabled\" : j.retryPending ? \"retrying\" : j.consecutiveErrors > 0 ? \"failing\" : \"healthy\",\n consecutiveErrors: j.consecutiveErrors,\n lastError: j.lastError,\n })),\n }\n }\n}\n","import type { IntentSource } from \"./types\"\n\n// Mode-flag plumbing — Phase 1 commit 4 of the architectural rescue.\n//\n// The staged rollout in research-rescue-plan.md §7 needs three states:\n//\n// off ledger code is unreachable; legacy paths are authoritative.\n// This is the default and stays the default through 1a.\n// shadow decideAndCommit runs alongside the legacy paths on every\n// dispatch and records what *would* have happened. Legacy\n// remains authoritative; a divergence reporter (commit 5)\n// compares the two. The ≥7-day soak in 1b lives here.\n// authoritative ledger decision is the dispatch decision. Legacy paths\n// remain only as fallback gated by INTENT_LEDGER_FALLBACK\n// (commit 1c → 1d removes the legacy paths entirely).\n//\n// Mode is resolved per-source so 1c can flip sources one at a time\n// (gitlab → workflow → telegram → cron → mesh, ≥48h soak between each).\n//\n// This commit is plumbing only. No call site reads the mode yet —\n// commit 6 wires the readers behind the flag, defaulting to \"off\" so\n// production behaviour is unchanged at deploy time.\n\nexport type LedgerMode = \"off\" | \"shadow\" | \"authoritative\"\n\nconst VALID_MODES = [\"off\", \"shadow\", \"authoritative\"] as const satisfies readonly LedgerMode[]\n\n/** Per-source env-var names. Lifted to a constant so the call site (commit 6)\n * doesn't need to construct strings, and so the test matrix can drive them\n * by table rather than guessing the naming convention. */\nconst PER_SOURCE_ENV_VAR: Record<IntentSource, string> = {\n telegram: \"INTENT_LEDGER_MODE_TELEGRAM\",\n slack: \"INTENT_LEDGER_MODE_SLACK\",\n whatsapp: \"INTENT_LEDGER_MODE_WHATSAPP\",\n discord: \"INTENT_LEDGER_MODE_DISCORD\",\n gitlab: \"INTENT_LEDGER_MODE_GITLAB\",\n github: \"INTENT_LEDGER_MODE_GITHUB\",\n workflow: \"INTENT_LEDGER_MODE_WORKFLOW\",\n cron: \"INTENT_LEDGER_MODE_CRON\",\n mesh: \"INTENT_LEDGER_MODE_MESH\",\n}\n\nconst GLOBAL_ENV_VAR = \"INTENT_LEDGER_MODE\"\n\n/**\n * Resolve the ledger mode for one source. Resolution order:\n *\n * 1. Per-source env var (e.g. INTENT_LEDGER_MODE_GITLAB)\n * 2. Global env var (INTENT_LEDGER_MODE)\n * 3. Default — \"off\"\n *\n * Invalid values at any level (typos, foreign strings) are ignored — that\n * level falls through to the next. Defaulting to \"off\" on garbage means an\n * operator typo never accidentally promotes a source to authoritative; the\n * cost is silence on misconfig, but the cost of the alternative\n * (mis-promoted source) is much higher in production.\n *\n * The accepted values are case-insensitive (\"Shadow\", \"SHADOW\", \"shadow\"\n * all parse) so config copied from a doc or shell history doesn't surprise.\n *\n * Read every call rather than cached. Per-dispatch overhead is one or two\n * `process.env` lookups — negligible — and runtime flips (operator SIGHUPs\n * the daemon and changes `EnvironmentFile=` on systemd) take effect on the\n * next event without a restart.\n */\nexport function getLedgerMode(\n source: IntentSource,\n env: NodeJS.ProcessEnv = process.env,\n): LedgerMode {\n const perSource = parseLedgerMode(env[PER_SOURCE_ENV_VAR[source]])\n if (perSource) return perSource\n const global = parseLedgerMode(env[GLOBAL_ENV_VAR])\n if (global) return global\n return \"off\"\n}\n\n/** Parse a value into a LedgerMode, or return null for invalid / unset. */\nexport function parseLedgerMode(value: unknown): LedgerMode | null {\n if (typeof value !== \"string\") return null\n const normalized = value.trim().toLowerCase()\n return (VALID_MODES as readonly string[]).includes(normalized)\n ? (normalized as LedgerMode)\n : null\n}\n\n/** Convenience: is this source consulting the ledger at all? Equivalent to\n * `getLedgerMode(source) !== \"off\"`, named for callsite readability. */\nexport function isLedgerActive(\n source: IntentSource,\n env: NodeJS.ProcessEnv = process.env,\n): boolean {\n return getLedgerMode(source, env) !== \"off\"\n}\n","import Database from \"better-sqlite3\"\nimport { existsSync, mkdirSync } from \"fs\"\nimport { dirname, resolve } from \"path\"\nimport { newEventId } from \"./ulid\"\nimport type {\n IntentDecision,\n IntentDivergence,\n IntentEvent,\n IntentEventInput,\n IntentResolution,\n IntentSource,\n} from \"./types\"\n\n// Intent ledger — Phase 1 of the architectural rescue.\n//\n// Append-only SQLite store that becomes the single source of truth for\n// dispatch decisions across all sources (channel router, workflow\n// dispatcher, gitlab handler, cron, mesh). This commit only opens the db\n// and runs the schema migrations. The read/write API arrives in commit 2;\n// the `decideAndCommit` skeleton in commit 3.\n//\n// Lives in its own database file (`.agentx/intent/ledger.sqlite`) rather\n// than sharing the existing observability db at `.agentx/db.sqlite`:\n// - Different lifecycle: dispatch is hotter than observability, no point\n// making fsync compete.\n// - Different durability story: the ledger is canonical state; the\n// observability tables are derived. Different backup/retention policies.\n// - Cleaner schema separation — ledger migrations don't entangle with the\n// observability ones.\n//\n// WAL mode + synchronous=NORMAL — same balance the observability db uses.\n\nexport interface OpenLedgerOptions {\n /** Resolved relative to cwd. Default: .agentx/intent/ledger.sqlite */\n path?: string\n}\n\n/**\n * IntentLedger handle. One instance per database file. Tests open per-test\n * tmp instances; the daemon opens one process-global instance (added in a\n * later commit when daemon wiring lands).\n */\nexport class IntentLedger {\n readonly db: Database.Database\n readonly path: string\n\n constructor(opts: OpenLedgerOptions = {}) {\n this.path = resolve(process.cwd(), opts.path ?? \".agentx/intent/ledger.sqlite\")\n mkdirSync(dirname(this.path), { recursive: true })\n this.db = new Database(this.path)\n this.db.pragma(\"journal_mode = WAL\")\n this.db.pragma(\"synchronous = NORMAL\")\n this.db.pragma(\"foreign_keys = ON\")\n runMigrations(this.db)\n }\n\n /** Test-only — production never closes. */\n close(): void {\n this.db.close()\n }\n\n /** Current schema version. New migrations append to the runMigrations\n * list and bump the version. Useful for tests + diagnostics. */\n schemaVersion(): number {\n const row = this.db.prepare(\"SELECT MAX(v) AS v FROM schema_version\").get() as { v: number | null }\n return row.v ?? 0\n }\n\n // -------------------------------------------------------------------------\n // Events\n // -------------------------------------------------------------------------\n\n /**\n * Append an event. Idempotent on `(source, sourceEventId)` — a re-delivery\n * with the same external id returns the previously-stored row without\n * inserting a duplicate. Events with `sourceEventId === null` (cron tics,\n * ad-hoc internal events) are NOT deduplicated; each call writes a new row.\n *\n * Returns the canonical (existing or new) event row including its id.\n */\n recordEvent(input: IntentEventInput): IntentEvent {\n if (input.sourceEventId !== null) {\n const existing = this.findEventBySourceId(input.source, input.sourceEventId)\n if (existing) return existing\n }\n const event: IntentEvent = {\n id: input.id ?? newEventId(input.ts),\n ts: input.ts,\n source: input.source,\n sourceEventId: input.sourceEventId,\n project: input.project,\n subject: input.subject,\n intent: input.intent,\n rawJson: input.rawJson,\n }\n this.db\n .prepare(\n `INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n event.id,\n event.ts,\n event.source,\n event.sourceEventId,\n event.project,\n event.subject,\n event.intent,\n event.rawJson,\n )\n return event\n }\n\n /** Idempotency probe — used by `recordEvent` and by external callers that\n * want to check existence before constructing a full event payload. */\n findEventBySourceId(source: IntentSource, sourceEventId: string): IntentEvent | null {\n const row = this.db\n .prepare(\n `SELECT id, ts, source, source_event_id, project, subject, intent, raw_json\n FROM intent_events WHERE source = ? AND source_event_id = ?`,\n )\n .get(source, sourceEventId) as EventRow | undefined\n return row ? rowToEvent(row) : null\n }\n\n /** Lookup by primary key. Returns null when not found. */\n getEventById(id: string): IntentEvent | null {\n const row = this.db\n .prepare(\n `SELECT id, ts, source, source_event_id, project, subject, intent, raw_json\n FROM intent_events WHERE id = ?`,\n )\n .get(id) as EventRow | undefined\n return row ? rowToEvent(row) : null\n }\n\n // -------------------------------------------------------------------------\n // Decisions\n // -------------------------------------------------------------------------\n\n /**\n * Append a decision. Throws on `(eventId, decidedBy)` conflict — decisions\n * are once-and-only-once per decider. Idempotency for the *event* is the\n * caller's responsibility (use `recordEvent` for that); decisions\n * intentionally do not retry-coalesce so a buggy caller surfaces loudly\n * instead of silently overwriting prior judgement.\n */\n recordDecision(decision: IntentDecision): void {\n this.db\n .prepare(\n `INSERT INTO intent_decisions (event_id, decided_at, decided_by, agent_id, outcome, reason)\n VALUES (?, ?, ?, ?, ?, ?)`,\n )\n .run(\n decision.eventId,\n decision.decidedAt,\n decision.decidedBy,\n decision.agentId,\n decision.outcome,\n decision.reason,\n )\n }\n\n /** All decisions for one event, oldest first. The chain (channel-router →\n * pm-gate → workflow) reads naturally in insertion order. */\n getDecisionsForEvent(eventId: string): IntentDecision[] {\n const rows = this.db\n .prepare(\n `SELECT event_id, decided_at, decided_by, agent_id, outcome, reason\n FROM intent_decisions WHERE event_id = ? ORDER BY decided_at ASC`,\n )\n .all(eventId) as DecisionRow[]\n return rows.map(rowToDecision)\n }\n\n /**\n * The active-task-safety check. Returns the most recent `dispatched`\n * decision for `(project, subject)` that has not yet been resolved\n * (no row in `intent_resolutions`). `decideAndCommit` (commit 3) consults\n * this to enforce the at-most-one-in-flight invariant.\n *\n * Returns null when project or subject is null — the active-task concept\n * is meaningless without both axes pinned.\n */\n getActiveDecisionForSubject(project: string | null, subject: string | null): IntentDecision | null {\n if (project === null || subject === null) return null\n const row = this.db\n .prepare(\n `SELECT d.event_id, d.decided_at, d.decided_by, d.agent_id, d.outcome, d.reason\n FROM intent_decisions d\n JOIN intent_events e ON e.id = d.event_id\n LEFT JOIN intent_resolutions r\n ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by\n WHERE e.project = ? AND e.subject = ?\n AND d.outcome = 'dispatched'\n AND r.decision_event_id IS NULL\n ORDER BY d.decided_at DESC\n LIMIT 1`,\n )\n .get(project, subject) as DecisionRow | undefined\n return row ? rowToDecision(row) : null\n }\n\n // -------------------------------------------------------------------------\n // Resolutions\n // -------------------------------------------------------------------------\n\n /**\n * Append a resolution. Throws if a resolution already exists for the\n * decision — the ledger is append-only, so revising an outcome is a new\n * event, not an overwrite. The FK to `intent_decisions` ensures the\n * decision exists.\n */\n recordResolution(resolution: IntentResolution): void {\n this.db\n .prepare(\n `INSERT INTO intent_resolutions (decision_event_id, decision_decided_by, resolved_at, status, duration_ms, result_summary)\n VALUES (?, ?, ?, ?, ?, ?)`,\n )\n .run(\n resolution.decisionEventId,\n resolution.decisionDecidedBy,\n resolution.resolvedAt,\n resolution.status,\n resolution.durationMs,\n resolution.resultSummary,\n )\n }\n\n /**\n * Close every dispatched-and-unresolved decision by writing a\n * resolution with status \"canceled\" and the given reason. Used at\n * daemon startup to clean up dispatches whose agent execution died\n * with the previous process — without this, those decisions sit\n * in-flight forever and Inv-ActiveTaskSafety blocks legitimate\n * re-dispatches on the same slot.\n *\n * Returns the count of resolutions written. Idempotent — repeated\n * calls write 0 the second time because nothing remains in-flight.\n */\n cleanupOrphanedDispatches(reason: string = \"daemon-restart\", now: () => number = Date.now): number {\n const rows = this.db\n .prepare(`\n SELECT d.event_id, d.decided_by FROM intent_decisions d\n LEFT JOIN intent_resolutions r\n ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by\n WHERE d.outcome = 'dispatched' AND r.decision_event_id IS NULL\n `)\n .all() as Array<{ event_id: string; decided_by: string }>\n const ts = now()\n let count = 0\n for (const row of rows) {\n try {\n this.recordResolution({\n decisionEventId: row.event_id,\n decisionDecidedBy: row.decided_by,\n resolvedAt: ts,\n status: \"canceled\",\n durationMs: null,\n resultSummary: reason,\n })\n count++\n } catch {\n // Skip — resolution already exists (race with normal completion).\n }\n }\n return count\n }\n\n /** Returns the resolution for a decision, or null if still in-flight. */\n getResolution(eventId: string, decidedBy: string): IntentResolution | null {\n const row = this.db\n .prepare(\n `SELECT decision_event_id, decision_decided_by, resolved_at, status, duration_ms, result_summary\n FROM intent_resolutions WHERE decision_event_id = ? AND decision_decided_by = ?`,\n )\n .get(eventId, decidedBy) as ResolutionRow | undefined\n return row ? rowToResolution(row) : null\n }\n\n // -------------------------------------------------------------------------\n // Divergences (shadow-mode soak surface)\n // -------------------------------------------------------------------------\n\n /**\n * Append a divergence record. Throws on duplicate `id`. The composite FK\n * to `intent_decisions` (`event_id`, `decided_by`) enforces that a\n * divergence cannot exist without its ledger-side decision — so callers\n * must record the decision before reporting the divergence.\n */\n recordDivergence(divergence: IntentDivergence): void {\n this.db\n .prepare(\n `INSERT INTO intent_divergences (\n id, ts, source, event_id, decided_by,\n ledger_agent_id, ledger_outcome, ledger_reason,\n legacy_agent_id, legacy_outcome, legacy_reason\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n divergence.id,\n divergence.ts,\n divergence.source,\n divergence.eventId,\n divergence.decidedBy,\n divergence.ledgerAgentId,\n divergence.ledgerOutcome,\n divergence.ledgerReason,\n divergence.legacyAgentId,\n divergence.legacyOutcome,\n divergence.legacyReason,\n )\n }\n\n /**\n * Recent divergences, newest first. Filters compose: `source` narrows to\n * one dispatch source, `since` to a recency window, `limit` to top-N.\n * The intended consumer is the soak dashboard (commit 8) and `agentx\n * audit --divergence` queries; per-record introspection is rare so we\n * don't expose a single-id getter.\n */\n getDivergences(opts: {\n source?: IntentSource\n since?: number\n limit?: number\n } = {}): IntentDivergence[] {\n const wheres: string[] = []\n const params: Array<string | number> = []\n if (opts.source !== undefined) {\n wheres.push(\"source = ?\")\n params.push(opts.source)\n }\n if (opts.since !== undefined) {\n wheres.push(\"ts >= ?\")\n params.push(opts.since)\n }\n const whereSql = wheres.length ? `WHERE ${wheres.join(\" AND \")}` : \"\"\n const limitSql = opts.limit !== undefined ? \"LIMIT ?\" : \"\"\n if (opts.limit !== undefined) params.push(opts.limit)\n\n const rows = this.db\n .prepare(\n `SELECT id, ts, source, event_id, decided_by,\n ledger_agent_id, ledger_outcome, ledger_reason,\n legacy_agent_id, legacy_outcome, legacy_reason\n FROM intent_divergences\n ${whereSql}\n ORDER BY ts DESC\n ${limitSql}`,\n )\n .all(...params) as DivergenceRow[]\n return rows.map(rowToDivergence)\n }\n}\n\n// --- Row → typed-object adapters --------------------------------------------\n//\n// SQLite returns snake_case rows; the typed surface uses camelCase. Mapping\n// once here keeps every consumer in TS-ergonomic shape and makes column\n// renames a single-file refactor.\n\ninterface EventRow {\n id: string\n ts: number\n source: string\n source_event_id: string | null\n project: string | null\n subject: string | null\n intent: string | null\n raw_json: string\n}\n\ninterface DecisionRow {\n event_id: string\n decided_at: number\n decided_by: string\n agent_id: string | null\n outcome: string\n reason: string | null\n}\n\ninterface ResolutionRow {\n decision_event_id: string\n decision_decided_by: string\n resolved_at: number\n status: string\n duration_ms: number | null\n result_summary: string | null\n}\n\ninterface DivergenceRow {\n id: string\n ts: number\n source: string\n event_id: string\n decided_by: string\n ledger_agent_id: string | null\n ledger_outcome: string\n ledger_reason: string | null\n legacy_agent_id: string | null\n legacy_outcome: string\n legacy_reason: string | null\n}\n\nfunction rowToEvent(row: EventRow): IntentEvent {\n return {\n id: row.id,\n ts: row.ts,\n source: row.source as IntentSource,\n sourceEventId: row.source_event_id,\n project: row.project,\n subject: row.subject,\n intent: row.intent,\n rawJson: row.raw_json,\n }\n}\n\nfunction rowToDecision(row: DecisionRow): IntentDecision {\n return {\n eventId: row.event_id,\n decidedAt: row.decided_at,\n decidedBy: row.decided_by,\n agentId: row.agent_id,\n outcome: row.outcome as IntentDecision[\"outcome\"],\n reason: row.reason,\n }\n}\n\nfunction rowToResolution(row: ResolutionRow): IntentResolution {\n return {\n decisionEventId: row.decision_event_id,\n decisionDecidedBy: row.decision_decided_by,\n resolvedAt: row.resolved_at,\n status: row.status as IntentResolution[\"status\"],\n durationMs: row.duration_ms,\n resultSummary: row.result_summary,\n }\n}\n\nfunction rowToDivergence(row: DivergenceRow): IntentDivergence {\n return {\n id: row.id,\n ts: row.ts,\n source: row.source as IntentSource,\n eventId: row.event_id,\n decidedBy: row.decided_by,\n ledgerAgentId: row.ledger_agent_id,\n ledgerOutcome: row.ledger_outcome as IntentDivergence[\"ledgerOutcome\"],\n ledgerReason: row.ledger_reason,\n legacyAgentId: row.legacy_agent_id,\n legacyOutcome: row.legacy_outcome as IntentDivergence[\"legacyOutcome\"],\n legacyReason: row.legacy_reason,\n }\n}\n\n/**\n * Per-version schema steps. New tables / columns go in a new migration\n * function — never mutate an old one. Each step is idempotent so re-running\n * on an already-current db is safe.\n */\nfunction runMigrations(db: Database.Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS schema_version (\n v INTEGER PRIMARY KEY\n );\n `)\n const current = (db\n .prepare(\"SELECT MAX(v) AS v FROM schema_version\")\n .get() as { v: number | null }).v ?? 0\n\n if (current < 1) migrationV1(db)\n if (current < 2) migrationV2(db)\n}\n\nfunction migrationV1(db: Database.Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS intent_events (\n -- TEXT PRIMARY KEY isn't auto-NOT-NULL in SQLite; spell it out so the\n -- ULID invariant is enforced at the schema level rather than relying on\n -- the application layer.\n id TEXT NOT NULL PRIMARY KEY,\n ts INTEGER NOT NULL,\n source TEXT NOT NULL,\n source_event_id TEXT,\n project TEXT,\n subject TEXT,\n intent TEXT,\n raw_json TEXT NOT NULL\n );\n\n CREATE INDEX IF NOT EXISTS idx_intent_events_subject\n ON intent_events (project, subject);\n CREATE INDEX IF NOT EXISTS idx_intent_events_source_event_id\n ON intent_events (source, source_event_id);\n CREATE INDEX IF NOT EXISTS idx_intent_events_ts\n ON intent_events (ts);\n\n CREATE TABLE IF NOT EXISTS intent_decisions (\n event_id TEXT NOT NULL REFERENCES intent_events(id),\n decided_at INTEGER NOT NULL,\n decided_by TEXT NOT NULL,\n agent_id TEXT,\n outcome TEXT NOT NULL,\n reason TEXT,\n PRIMARY KEY (event_id, decided_by)\n );\n\n CREATE INDEX IF NOT EXISTS idx_intent_decisions_agent\n ON intent_decisions (agent_id, decided_at);\n CREATE INDEX IF NOT EXISTS idx_intent_decisions_outcome\n ON intent_decisions (outcome, decided_at);\n\n CREATE TABLE IF NOT EXISTS intent_resolutions (\n decision_event_id TEXT NOT NULL,\n decision_decided_by TEXT NOT NULL,\n resolved_at INTEGER NOT NULL,\n status TEXT NOT NULL,\n duration_ms INTEGER,\n result_summary TEXT,\n PRIMARY KEY (decision_event_id, decision_decided_by),\n FOREIGN KEY (decision_event_id, decision_decided_by)\n REFERENCES intent_decisions(event_id, decided_by)\n );\n\n CREATE INDEX IF NOT EXISTS idx_intent_resolutions_status\n ON intent_resolutions (status, resolved_at);\n `)\n db.prepare(\"INSERT INTO schema_version (v) VALUES (1)\").run()\n}\n\nfunction migrationV2(db: Database.Database): void {\n // Phase 1 commit 5 — divergence reporter surface. Each row records one\n // observed mismatch between the ledger's decision and the legacy path's\n // outcome during shadow-mode operation. The composite FK to\n // intent_decisions ensures a divergence cannot exist without its\n // ledger-side decision row.\n db.exec(`\n CREATE TABLE IF NOT EXISTS intent_divergences (\n id TEXT NOT NULL PRIMARY KEY,\n ts INTEGER NOT NULL,\n source TEXT NOT NULL,\n event_id TEXT NOT NULL,\n decided_by TEXT NOT NULL,\n ledger_agent_id TEXT,\n ledger_outcome TEXT NOT NULL,\n ledger_reason TEXT,\n legacy_agent_id TEXT,\n legacy_outcome TEXT NOT NULL,\n legacy_reason TEXT,\n FOREIGN KEY (event_id, decided_by)\n REFERENCES intent_decisions(event_id, decided_by)\n );\n\n -- \"show me recent divergences from gitlab\" — the soak's primary query\n CREATE INDEX IF NOT EXISTS idx_intent_divergences_source_ts\n ON intent_divergences (source, ts);\n -- \"are any deciders consistently wrong\" — per-decider analysis\n CREATE INDEX IF NOT EXISTS idx_intent_divergences_decided_by\n ON intent_divergences (decided_by, ts);\n `)\n db.prepare(\"INSERT INTO schema_version (v) VALUES (2)\").run()\n}\n\n// existsSync is imported for symmetry with src/storage/sqlite.ts; the\n// ledger constructor doesn't currently branch on file presence (the\n// migration is idempotent regardless), but keeping the import documents\n// the intent should later code need to distinguish first-open from re-open.\nvoid existsSync\n","import { randomBytes } from \"crypto\"\n\n// In-tree ULID generator — Phase 1 of the architectural rescue.\n//\n// The ledger demands monotonically-sortable ids so chronological queries\n// can use ID ranges and the audit trail reads coherently. ULIDs give us\n// that (10-char Crockford-base32 timestamp + 16-char randomness, total\n// 26 chars). The full `ulid` npm package is overkill for the few hundred\n// lines of generation logic we need, and adding a dep means another\n// `pnpm install --prod` step on clawd-server. So we inline.\n//\n// This is not a cryptographic primitive — its job is to be a unique,\n// time-sortable identifier. Random bytes come from `crypto.randomBytes`\n// purely because it's the right tool for \"give me bytes\" and there's no\n// reason to use weaker randomness.\n\nconst ENCODING = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\" // Crockford base32\n\nconst TIME_LEN = 10\nconst RAND_LEN = 16\n\nfunction encodeTime(ms: number): string {\n let out = \"\"\n for (let i = TIME_LEN - 1; i >= 0; i--) {\n out = ENCODING[ms & 31] + out\n ms = Math.floor(ms / 32)\n }\n return out\n}\n\nfunction encodeRandom(): string {\n const bytes = randomBytes(RAND_LEN)\n let out = \"\"\n for (let i = 0; i < RAND_LEN; i++) {\n out += ENCODING[bytes[i] & 31]\n }\n return out\n}\n\n/** Generate a new ULID. Pass `now` for deterministic tests. */\nexport function newEventId(now: number = Date.now()): string {\n return encodeTime(now) + encodeRandom()\n}\n\n/** Extract the timestamp portion from a ULID. Inverse of `newEventId`'s\n * time prefix. Useful for sanity checks; not load-bearing. */\nexport function decodeTime(id: string): number {\n let ms = 0\n for (let i = 0; i < TIME_LEN; i++) {\n const v = ENCODING.indexOf(id[i])\n if (v < 0) throw new Error(`invalid ULID character at position ${i}: ${id[i]}`)\n ms = ms * 32 + v\n }\n return ms\n}\n","import { IntentLedger } from \"./ledger\"\n\n// Daemon-process singleton accessor for the IntentLedger.\n//\n// Phase 1 commit 6.0 — scaffolding for the call-site wiring that lands in\n// 6.a (gitlab), 6.b (router), 6.c (workflow), 6.d (cron + mesh). Each\n// source's wrapper will read this singleton when the mode is non-\"off\".\n//\n// The singleton is lazy because the ledger isn't needed in production\n// until the operator flips INTENT_LEDGER_MODE off the default. Avoiding\n// eager construction means an unflipped agentx process never opens the\n// ledger db, never holds the file, never writes WAL pages — exactly what\n// \"deploy-time default is off\" means in practice.\n//\n// Tests use `setLedgerForTesting` to inject an in-memory or tmp-dir\n// ledger and `resetLedgerForTesting` to release it between cases. Outside\n// of tests, callers go through `getDefaultLedger()`.\n\nlet _ledger: IntentLedger | undefined\n\nexport interface DefaultLedgerOptions {\n /** Path override. Default: `.agentx/intent/ledger.sqlite` (resolved\n * against cwd by the IntentLedger constructor). */\n path?: string\n}\n\n/**\n * Lazy singleton getter. Idempotent — repeated calls return the same\n * handle. Constructs the ledger on first call.\n *\n * Throws on construction failure (file unwritable, native binding broken,\n * etc.). Call sites should gate the call behind `getLedgerMode(...) !== \"off\"`\n * so a bad ledger never reaches construction in normal \"off\" production.\n *\n * The decision to throw rather than fail-soft (return null like\n * src/storage/sqlite.ts does) is deliberate: the ledger is canonical\n * state once `mode !== \"off\"`, so a silent failure would leave the\n * dispatcher in an undefined \"I tried to record but didn't\" state. Loud\n * failure surfaces misconfig at startup rather than days into a soak.\n */\nexport function getDefaultLedger(opts: DefaultLedgerOptions = {}): IntentLedger {\n if (_ledger) return _ledger\n _ledger = new IntentLedger({ path: opts.path })\n return _ledger\n}\n\n/** Test-only: inject a pre-built ledger so per-test tmp dirs work without\n * fighting the singleton. Production code MUST NOT call this. */\nexport function setLedgerForTesting(ledger: IntentLedger): void {\n _ledger = ledger\n}\n\n/** Test-only: drop the singleton reference. Use in `afterEach` so the\n * next test's `setLedgerForTesting` or `getDefaultLedger` starts fresh.\n * Does NOT close the underlying db — the caller (test) owns close(). */\nexport function resetLedgerForTesting(): void {\n _ledger = undefined\n}\n","import type { DispatchGovernance } from \"./decide\"\n\n// Daemon-level governance singleton — Phase 3 of the architectural rescue.\n//\n// `decideAndCommit` reads this when its caller doesn't pass an explicit\n// `governance` argument. The daemon initializes it at startup from the\n// `BusinessLayer.organization` instance, gated by the\n// `INTENT_PM_GATE_ENABLED` env var. When the var is unset (the deploy\n// default), the singleton stays undefined and no PM gate / canHandle\n// check fires — production behaviour is unchanged.\n//\n// This indirection keeps governance an opt-in concern: call sites and\n// helpers (`recordGitLabTargetDispatch`, `recordRouterDispatch`, etc.)\n// don't need to know about Organization. The daemon plumbs Organization\n// → DispatchGovernance once at startup; everything else stays generic.\n//\n// Tests reset between cases via `setDefaultGovernance(undefined)` to\n// avoid leakage from one test's fixture into another's behaviour.\n\nlet _governance: DispatchGovernance | undefined\n\n/** Set the process-wide default governance. Called once at daemon\n * startup (or never, if INTENT_PM_GATE_ENABLED is off). */\nexport function setDefaultGovernance(g: DispatchGovernance | undefined): void {\n _governance = g\n}\n\n/** Read the current default. `decideAndCommit` falls back to this when\n * its caller didn't pass an explicit governance arg. Returns undefined\n * in test contexts that haven't set anything (no governance fires). */\nexport function getDefaultGovernance(): DispatchGovernance | undefined {\n return _governance\n}\n","import type { IntentLedger } from \"./ledger\"\nimport type { IntentDecision, IntentEventInput, IntentEvent } from \"./types\"\nimport { getDefaultGovernance } from \"./governance\"\n\n// decideAndCommit — Phase 1 of the architectural rescue.\n//\n// The single function every dispatch source will route through. Every event\n// entering the system flows: source-adapter → decideAndCommit → (optional\n// agent dispatch). The function's job is to:\n//\n// 1. Record the event idempotently (Inv-Idempotence)\n// 2. Consult the ledger for active-task state (Inv-ActiveTaskSafety)\n// 3. Ask the policy for a tentative decision\n// 4. Commit a single decision row to the ledger (Inv-NoSilentDrops)\n//\n// The four invariants are spelled out below and named so that Phase 2's\n// TLA+ spec can reference them by string. Tests in test/intent-decide.test.ts\n// cite these names in their assertion comments.\n//\n// **Phase 2 status**: three of the four invariants are formally verified\n// by TLC against `docs/architecture/DispatchSpec.tla` (410K distinct\n// states, depth 7, 0 violations as of 2026-04-29). The fourth\n// (Inv-Determinism) is a meta-property over traces, checked by code\n// review + the test in `intent-decide.test.ts`. See\n// `docs/architecture/dispatch-properties.md` for the full mapping\n// between code paths, invariants, and TLC results.\n//\n// Inv-Idempotence calling decideAndCommit twice with the same\n// (source, sourceEventId) and the same policy\n// produces one event row + one decision row;\n// the second call returns the row from the first.\n// Inv-Determinism given a fixed ledger snapshot, a fixed policy,\n// and a fixed clock, the resulting decision is a\n// pure function of the input event.\n// Inv-ActiveTaskSafety at most one decision with outcome=dispatched\n// that has not yet been resolved exists for any\n// (project, subject) at any point in the ledger.\n// Inv-NoSilentDrops every call to decideAndCommit appends exactly\n// one decision row to the ledger (or returns an\n// existing one under Inv-Idempotence). No code\n// path returns without a row visible in the ledger.\n//\n// What this commit does NOT do:\n// - Wire decideAndCommit into any real call site (commit 6).\n// - Add the mode flag (commit 4) — this function is reachable only from\n// tests until commit 6 wires it up behind a flag that defaults off.\n// - Read or expose the divergence reporter (commit 5).\n// - Run async or call out to network. Policies are sync; if a real call\n// site needs an LLM in the loop, that's a refactor for a later phase.\n\n/**\n * A pluggable dispatch policy. Each call site (channel router, workflow\n * dispatcher, gitlab handler, cron firing, mesh receiver) supplies its own\n * policy — the function below is purely the orchestration around the\n * policy's decision.\n *\n * The policy's `decidedBy` is the ledger's attribution string (\"who decided\n * this?\") and is what the ledger uses to scope idempotency: re-delivery of\n * the same event to the same `decidedBy` returns the existing row, while\n * the same event reaching a different `decidedBy` is a separate decision\n * (the chain-of-command case).\n */\nexport interface DispatchPolicy {\n /** Stable attribution string. Examples: `\"channel-router\"`,\n * `\"workflow:gitlab-sdlc-loop\"`, `\"gitlab-handler\"`. Must be stable\n * across calls — the ledger uses it as the per-policy idempotency key. */\n readonly decidedBy: string\n\n /**\n * Inspect the (already-recorded) event and return a tentative decision.\n * Return `null` to mean \"I have no opinion\" — the caller will record a\n * `halted` decision with reason `\"no policy match\"`.\n *\n * The policy MUST NOT write to the ledger directly. It MUST be a pure\n * function of `event` plus any read-only context the caller closed over\n * when constructing the policy. (Determinism — Inv-Determinism — depends\n * on this.)\n */\n decide(event: IntentEvent): PolicyDecision | null\n}\n\n/** What a policy returns. The `outcome` set excludes `\"deduped\"` because\n * dedup is the ledger's call, not the policy's. */\nexport interface PolicyDecision {\n agentId: string | null\n outcome: \"dispatched\" | \"halted\" | \"queued\"\n reason: string | null\n}\n\n/**\n * Phase 3 — Org-chart governance hooks. Optional. When supplied,\n * decideAndCommit consults them AFTER the policy decides:\n *\n * canHandle(agentId, project, intent) returns false → halt the\n * dispatch with reason \"org-chart: agent cannot handle\". Use to\n * enforce per-agent capability constraints (Phase 5 will add\n * typed capabilities; the v0 here is permissive).\n *\n * pmFor(project) returns the agentId of the\n * PM for `project`, or undefined when no PM is configured. When\n * defined AND the policy decided \"dispatched\", the decision's\n * `decidedBy` is rewritten to `pm:<pmId>` so the audit trail\n * attributes the dispatch to the PM gate. Per the kickoff:\n * \"a dispatch decision for (project, ...) where business.projects[].pm\n * is set never resolves to an agent without going through the PM\n * first (PM may rubber-stamp, but the decision row records\n * decided_by='pm:pm-mtgl')\".\n *\n * The full async-PM gate (synchronously dispatch to the PM agent,\n * wait up to 60s for approval, fall back to escalation on timeout)\n * is a future-phase refactor. The v0 here is the paper-trail gate:\n * the decision row is attributed to the PM, but no real call-out\n * happens. This satisfies the kickoff's property and unblocks the\n * 1c per-source promotions.\n */\nexport interface DispatchGovernance {\n canHandle?(agentId: string, project: string | null, intent: string | null): boolean\n pmFor?(project: string | null): string | undefined\n /** Phase 8 — capability-bounded security. Returns false when\n * dispatching `agentId` on `(project, subject)` would exceed the\n * agent's delegation-depth budget. Blocks cascade loops by\n * walking the ledger's prior decisions on the same slot. */\n withinDelegationBudget?(agentId: string, project: string | null, subject: string | null): boolean\n}\n\n/**\n * Append-only dispatch primitive. Returns the canonical decision row —\n * either freshly written or recovered from a prior call (Inv-Idempotence).\n *\n * The whole call runs inside a single SQLite transaction so the lookup\n * (`getDecisionsForEvent` + `getActiveDecisionForSubject`) and the write\n * (`recordDecision`) are atomic with respect to the same database. This\n * matters under concurrent-call scenarios; in the single-process daemon\n * use case, better-sqlite3 already serialises writes so the transaction\n * is belt-and-braces. Adding it now means the call-site wiring (commit 6)\n * can call decideAndCommit from anywhere without worrying about races.\n */\nexport function decideAndCommit(\n ledger: IntentLedger,\n input: IntentEventInput,\n policy: DispatchPolicy,\n now: () => number = Date.now,\n governance?: DispatchGovernance,\n): IntentDecision {\n const tx = ledger.db.transaction((decidedAt: number): IntentDecision => {\n // Step 1 — record the event. recordEvent is itself idempotent on\n // (source, sourceEventId), so this is safe under re-delivery.\n const event = ledger.recordEvent(input)\n\n // Phase 3 governance: compute the EFFECTIVE decidedBy upfront so\n // it threads through idempotency + recording. When a PM is\n // configured for the project, the decision is attributed to the\n // PM (pm:<id>) regardless of outcome — the PM is the gate, even\n // for halts and queues. canHandle is a veto applied later (forces\n // outcome=halted) but doesn't change decidedBy.\n //\n // Falls back to the daemon-level singleton (`getDefaultGovernance`)\n // when the caller doesn't pass an explicit governance — this is\n // the production path. Tests pass governance directly.\n const gov = governance ?? getDefaultGovernance()\n const pm = gov?.pmFor?.(event.project)\n const effectiveDecidedBy = pm ? `pm:${pm}` : policy.decidedBy\n\n // Step 2 — Inv-Idempotence. If this policy has already decided on this\n // event, return that decision unchanged. Two callers who race the same\n // event-policy pair are reduced to a single decision row.\n const prior = ledger\n .getDecisionsForEvent(event.id)\n .find((d) => d.decidedBy === effectiveDecidedBy)\n if (prior) return prior\n\n // Step 3 — Inv-ActiveTaskSafety. If a dispatched-and-unresolved\n // decision already exists for (project, subject), this event must\n // dedupe. The dedup outcome is ledger-managed; the policy never sees\n // a chance to override it.\n const active = ledger.getActiveDecisionForSubject(event.project, event.subject)\n if (active) {\n const decision: IntentDecision = {\n eventId: event.id,\n decidedAt,\n decidedBy: effectiveDecidedBy,\n agentId: null,\n outcome: \"deduped\",\n reason: `active dispatch in flight: ${active.decidedBy} → ${active.agentId ?? \"?\"}`,\n }\n ledger.recordDecision(decision)\n return decision\n }\n\n // Step 4 — consult the policy. A null result is a halt with explicit\n // reason rather than a silent drop (Inv-NoSilentDrops). A halted /\n // queued / dispatched policy decision flows through unchanged.\n const policyResult = policy.decide(event)\n let agentId: string | null = policyResult ? policyResult.agentId : null\n let outcome: \"dispatched\" | \"halted\" | \"queued\" = policyResult ? policyResult.outcome : \"halted\"\n let reason: string | null = policyResult ? policyResult.reason : \"no policy match\"\n\n // Step 5 — canHandle veto. Dispatches to agents the org chart says\n // can't handle the event get forced to halted.\n if (gov?.canHandle && outcome === \"dispatched\" && agentId) {\n const allowed = gov.canHandle(agentId, event.project, event.intent)\n if (!allowed) {\n const blocked = agentId\n agentId = null\n outcome = \"halted\"\n reason = `org-chart: agent \"${blocked}\" cannot handle (${event.project ?? \"no-project\"}/${event.intent ?? \"no-intent\"})`\n }\n }\n\n // Step 5b — Phase 8 delegation-depth check. Walks the ledger's\n // prior decisions on (project, subject) and refuses dispatches\n // that would push the chain past the agent's\n // `maxDelegationDepth`. Prevents cascade loops where A → B → A → ...\n // blows past sane chain depth.\n if (gov?.withinDelegationBudget && outcome === \"dispatched\" && agentId) {\n if (!gov.withinDelegationBudget(agentId, event.project, event.subject)) {\n const blocked = agentId\n agentId = null\n outcome = \"halted\"\n reason = `delegation-budget: agent \"${blocked}\" depth-limit exceeded on ${event.project ?? \"?\"}/${event.subject ?? \"?\"}`\n }\n }\n\n // Annotate the reason when PM-gate took effect, so the audit trail\n // distinguishes pm-gated dispatches from regular ones.\n if (pm && outcome === \"dispatched\" && agentId) {\n reason = reason\n ? `${reason} (pm-gate: rubber-stamped by ${pm})`\n : `pm-gate: rubber-stamped by ${pm}`\n }\n\n const decision: IntentDecision = {\n eventId: event.id,\n decidedAt,\n decidedBy: effectiveDecidedBy,\n agentId,\n outcome,\n reason,\n }\n ledger.recordDecision(decision)\n return decision\n })\n\n return tx(now())\n}\n","import { logger } from \"../utils/logger\"\nimport type { IntentLedger } from \"./ledger\"\nimport { newEventId } from \"./ulid\"\nimport type {\n IntentDecision,\n IntentDivergence,\n IntentOutcomeKind,\n IntentSource,\n} from \"./types\"\n\n// Divergence reporter — Phase 1 commit 5 of the architectural rescue.\n//\n// During shadow mode (1b in research-rescue-plan.md §7), every dispatch\n// runs through both the legacy path and decideAndCommit. The legacy path\n// remains authoritative; the ledger's decision is recorded but does not\n// drive behaviour. The reporter compares the two and:\n//\n// - on agreement: no-op (the soak's success criterion is \"zero\n// divergences for ≥7 days\" — quiet operation IS the signal).\n// - on mismatch: log a structured warning AND write a row to\n// intent_divergences so the soak dashboard has a queryable surface.\n//\n// The shape of \"the legacy outcome\" is deliberately structural rather\n// than tied to any one source's existing output type — that lets the\n// commit-6 wiring adapt each call site (channel-router's `Routed`, the\n// workflow dispatcher's `DispatchResult`, etc.) into a common\n// LegacyOutcome at the comparison boundary instead of carrying source-\n// specific shapes through the reporter.\n\n/** Minimal projection of a legacy dispatch path's outcome — only the\n * fields we compare against the ledger decision. */\nexport interface LegacyOutcome {\n agentId: string | null\n outcome: IntentOutcomeKind\n /** Optional human-readable reason; recorded for forensics, never\n * compared. (Legacy reasons and ledger reasons phrase the same\n * decision differently — comparing them would produce noise.) */\n reason?: string | null\n}\n\n/**\n * Compare a ledger decision against the legacy path's outcome. On mismatch,\n * append a divergence row and emit a `[ledger-divergence]` log line.\n * Returns `true` when a divergence was recorded, `false` on agreement.\n *\n * Comparison is structural on the load-bearing fields: `outcome` and\n * `agentId`. `reason` strings differ harmlessly between paths and are\n * forensic-only — comparing them would produce noise that drowns out\n * the actual semantic mismatches we care about.\n */\nexport function reportDivergence(\n ledger: IntentLedger,\n source: IntentSource,\n ledgerDecision: IntentDecision,\n legacy: LegacyOutcome,\n now: () => number = Date.now,\n): boolean {\n if (decisionsAgree(ledgerDecision, legacy)) return false\n\n const ts = now()\n const record: IntentDivergence = {\n id: newEventId(ts),\n ts,\n source,\n eventId: ledgerDecision.eventId,\n decidedBy: ledgerDecision.decidedBy,\n ledgerAgentId: ledgerDecision.agentId,\n ledgerOutcome: ledgerDecision.outcome,\n ledgerReason: ledgerDecision.reason,\n legacyAgentId: legacy.agentId,\n legacyOutcome: legacy.outcome,\n legacyReason: legacy.reason ?? null,\n }\n ledger.recordDivergence(record)\n\n // Single-line structured log so journalctl + grep are sufficient triage\n // tools during the soak (commit 8 adds a UI; until then, journal is it).\n logger.warn(\n `[ledger-divergence] source=${source} ` +\n `event=${ledgerDecision.eventId} ` +\n `decided_by=${ledgerDecision.decidedBy} ` +\n `ledger=${ledgerDecision.outcome}/${ledgerDecision.agentId ?? \"null\"} ` +\n `legacy=${legacy.outcome}/${legacy.agentId ?? \"null\"}`,\n )\n return true\n}\n\n/** Two outcomes agree iff they pick the same target with the same outcome\n * kind. Reasons (free-form) are not part of agreement.\n *\n * AgentIds that wrap a fresh-per-call instance id (workflow-run:<uuid>,\n * mesh-fwd:<id>) are normalized to the prefix before comparison — both\n * paths legitimately dispatch the same kind of work but with different\n * instance handles, and treating those as divergences buries the real\n * semantic mismatches in noise (Phase 1 soak finding: ~290 false\n * positives across both nodes pre-fix). */\nexport function decisionsAgree(\n ledgerDecision: IntentDecision,\n legacy: LegacyOutcome,\n): boolean {\n return (\n ledgerDecision.outcome === legacy.outcome &&\n normalizeSyntheticAgentId(ledgerDecision.agentId) === normalizeSyntheticAgentId(legacy.agentId)\n )\n}\n\nfunction normalizeSyntheticAgentId(id: string | null): string | null {\n if (!id) return null\n const m = id.match(/^(workflow-run|mesh-fwd):/)\n return m ? `${m[1]}:*` : id\n}\n","import type { IntentLedger } from \"../ledger\"\nimport { decideAndCommit, type DispatchPolicy } from \"../decide\"\nimport { reportDivergence, type LegacyOutcome } from \"../divergence\"\nimport type { IntentDecision, IntentEventInput } from \"../types\"\n\n// Source adapter — cron scheduler. Phase 1 commit 6.d.\n//\n// Cron is the cleanest 1:1 dispatch source: one fire → one agent. The\n// scheduler's `executeJob(jobId)` is the dispatch entry point. We\n// instrument the two decision branches (hook-blocked vs hook-approved)\n// and pass the legacy outcome to a pass-through policy.\n\nexport interface CronJobProjection {\n jobId: string\n agentId: string\n /** When the job fired (used as part of the ULID-friendly sourceEventId). */\n firedAt: Date\n}\n\n/** Build the IntentEventInput for one cron fire. sourceEventId is\n * per-(jobId, firedAt) so concurrent re-fires (shouldn't happen but)\n * collapse via idempotency. Subject scopes active-task safety to one\n * fire-in-flight per job — but project=null disables Inv-ActiveTaskSafety,\n * so successive fires of the same job both dispatch (matches legacy). */\nexport function buildCronEventInput(\n proj: CronJobProjection,\n rawJson: string,\n now: () => number = Date.now,\n): IntentEventInput {\n return {\n ts: now(),\n source: \"cron\",\n sourceEventId: `${proj.jobId}:${proj.firedAt.getTime()}`,\n project: null,\n subject: `cron:${proj.jobId}`,\n intent: \"cron.fired\",\n rawJson,\n }\n}\n\n/** Pass-through policy. Same shape as router/workflow: divergences come\n * from ledger MECHANICS, not policy disagreement. */\nexport function buildCronPolicyFromLegacy(legacy: LegacyOutcome): DispatchPolicy {\n return {\n decidedBy: \"cron-scheduler\",\n decide: () => ({\n agentId: legacy.agentId,\n outcome: legacy.outcome === \"deduped\" ? \"halted\" : legacy.outcome,\n reason:\n legacy.outcome === \"deduped\"\n ? `legacy-dedup: ${legacy.reason ?? \"\"}`.trim()\n : legacy.reason ?? null,\n }),\n }\n}\n\nexport function recordCronDispatch(\n ledger: IntentLedger,\n proj: CronJobProjection,\n rawJson: string,\n legacyOutcome: LegacyOutcome,\n now: () => number = Date.now,\n): IntentDecision {\n const eventInput = buildCronEventInput(proj, rawJson, now)\n const policy = buildCronPolicyFromLegacy(legacyOutcome)\n const ledgerDecision = decideAndCommit(ledger, eventInput, policy, now)\n reportDivergence(ledger, \"cron\", ledgerDecision, legacyOutcome, now)\n return ledgerDecision\n}\n"],"mappings":"uFAIA,OAAS,iBAAAA,EAAe,aAAAC,EAAW,cAAAC,EAAY,gBAAAC,OAAoB,KACnE,OAAS,WAAAC,MAAe,OCoBxB,IAAMC,EAAc,CAAC,MAAO,SAAU,eAAe,EAK/CC,EAAmD,CACvD,SAAU,8BACV,MAAO,2BACP,SAAU,8BACV,QAAS,6BACT,OAAQ,4B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B,KAAK,MAAMwC,GAAa,KAAK,YAAa,OAAO,CAAC,EADf,IAE5C,MAAE,CACA,OAAO,IACT,CACF,CAEQ,OAAOd,EAA6B,CAC1C,GAAI,CACF,IAAMe,EAAS7C,EAAQ,KAAK,QAAS8B,EAAO,KAAK,EAC5C1B,EAAWyC,CAAM,GACpBxC,EAAUwC,EAAQ,CAAE,UAAW,EAAK,CAAC,EAGvC,IAAMC,EAAW,GAAGhB,EAAO,UAAU,YAAY,EAAE,QAAQ,QAAS,GAAG,SACvEa,EACE3C,EAAQ6C,EAAQC,CAAQ,EACxB,KAAK,UAAUhB,EAAQ,KAAM,CAAC,CAChC,CACF,MAAE,CAEF,CACF,CAKA,MAAuB,CACrB,OAAO,MAAM,KAAK,KAAK,KAAK,OAAO,CAAC,CACtC,CAKA,QAA6K,CAC3K,IAAMiB,EAAO,MAAM,KAAK,KAAK,KAAK,OAAO,CAAC,EACpCZ,EAAS,KAAK,iBAAiB,EAErC,MAAO,CACL,QAASY,EAAK,OAAOpC,GAAKA,EAAE,SAAWA,EAAE,oBAAsB,CAAC,EAAE,OAClE,QAASoC,EAAK,OAAOpC,GAAKA,EAAE,SAAWA,EAAE,kBAAoB,CAAC,EAAE,OAChE,SAAUoC,EAAK,OAAOpC,GAAK,CAACA,EAAE,OAAO,EAAE,OACvC,OAAQwB,EAAO,OACf,KAAMY,EAAK,IAAIpC,IAAM,CACnB,GAAIA,EAAE,GACN,OAASA,EAAE,QAAuBA,EAAE,aAAe,WAAaA,EAAE,kBAAoB,EAAI,UAAY,UAAjF,WACrB,kBAAmBA,EAAE,kBACrB,UAAWA,EAAE,SACf,EAAE,CACJ,CACF,CACF","names":["writeFileSync","mkdirSync","existsSync","readFileSync","resolve","VALID_MODES","PER_SOURCE_ENV_VAR","GLOBAL_ENV_VAR","getLedgerMode","source","env","perSource","parseLedgerMode","global","value","normalized","Database","existsSync","mkdirSync","dirname","resolve","randomBytes","ENCODING","TIME_LEN","RAND_LEN","encodeTime","ms","out","i","encodeRandom","bytes","newEventId","now","IntentLedger","opts","resolve","mkdirSync","dirname","Database","runMigrations","input","existing","event","newEventId","source","sourceEventId","row","rowToEvent","id","decision","eventId","rowToDecision","project","subject","resolution","reason","now","rows","ts","count","decidedBy","rowToResolution","divergence","wheres","params","whereSql","limitSql","rowToDivergence","db","current","migrationV1","migrationV2","_ledger","getDefaultLedger","opts","IntentLedger","_governance","setDefaultGovernance","g","getDefaultGovernance","decideAndCommit","ledger","input","policy","now","governance","decidedAt","event","gov","getDefaultGovernance","pm","effectiveDecidedBy","prior","d","active","decision","policyResult","agentId","outcome","reason","blocked","reportDivergence","ledger","source","ledgerDecision","legacy","now","decisionsAgree","ts","record","newEventId","logger","normalizeSyntheticAgentId","id","m","buildCronEventInput","proj","rawJson","now","buildCronPolicyFromLegacy","legacy","recordCronDispatch","ledger","legacyOutcome","eventInput","policy","ledgerDecision","decideAndCommit","reportDivergence","withOutputCap","prompt","maxOutputTokens","approxChars","parseCronField","field","min","max","values","part","i","range","stepStr","step","start","a","b","getNextCronDate","expression","after","timezone","fields","minutes","hours","daysOfMonth","months","daysOfWeek","fmt","candidate","limit","parts","get","type","p","m","h","dom","mon","dow","MAX_RETRIES","RETRY_DELAYS","CronScheduler","config","registry","hooks","log","resolve","id","def","cb","existsSync","mkdirSync","missedRuns","jobId","missedAt","e","job","j","timer","existing","nextRun","delay","attempt","agentId","firedAt","legacy","getLedgerMode","decision","recordCronDispatch","getDefaultLedger","retryAttempt","isRetry","hookResult","startedAt","intentRef","response","result","res","applyConfigMutation","cfg","setAtPath","missed","lastRuns","lastRunStr","lastRun","shouldHaveRun","error","data","dir","writeFileSync","readFileSync","runDir","filename","jobs"]}
|
|
@@ -17,7 +17,7 @@ SKIP:
|
|
|
17
17
|
For each fact, output a JSON array:
|
|
18
18
|
[{"category":"fact|secret|preference|commitment|task-state","content":"concise fact, 1-2 sentences","keywords":["keyword1","keyword2"]}]
|
|
19
19
|
|
|
20
|
-
If nothing worth remembering, output: []`;async function h(t,s,a,n,r){if(s.length<20&&a.length<50)return;let{createProvider:i}=await import("./providers-
|
|
20
|
+
If nothing worth remembering, output: []`;async function h(t,s,a,n,r){if(s.length<20&&a.length<50)return;let{createProvider:i}=await import("./providers-L27BJ5A6.js"),c=(await i("claude").generate([{role:"system",content:f},{role:"user",content:`${n.sender} (via ${n.channel}): ${s}
|
|
21
21
|
|
|
22
22
|
Agent: ${a}`}],{model:m,maxTokens:512})).content.trim().match(/\[[\s\S]*\]/);if(!c)return;let o=JSON.parse(c[0]);if(!Array.isArray(o)||o.length===0)return;let d=new Date().toISOString().slice(0,10);for(let e of o)r.hasSimilar(t,e.content)||r.addMemory(t,{agentId:t,category:e.category,content:e.content,keywords:e.keywords||[],source:{...n,date:d},expiresAt:e.category==="task-state"?new Date(Date.now()+7*24*60*60*1e3).toISOString():void 0});Math.random()<.02&&r.prune(t)}export{h as a};
|
|
23
|
-
//# sourceMappingURL=chunk-
|
|
23
|
+
//# sourceMappingURL=chunk-5U35WAZF.js.map
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import{execFile as m}from"child_process";import{existsSync as d}from"fs";import{resolve as f}from"path";var R=["mcp__codegraph__codegraph_search","mcp__codegraph__codegraph_context","mcp__codegraph__codegraph_callers","mcp__codegraph__codegraph_callees","mcp__codegraph__codegraph_impact","mcp__codegraph__codegraph_node","mcp__codegraph__codegraph_status","mcp__codegraph__codegraph_files"],p={command:"codegraph",args:["serve","--mcp"]};function O(){return["## CodeGraph","","This workspace has CodeGraph initialized \u2014 a semantic code-knowledge-graph indexed via tree-sitter. Use it instead of grep/find/Read for exploration.","","**ALWAYS spawn an Explore subagent for `codegraph_explore` / `codegraph_context`** \u2014 those tools return large source sections that would otherwise bloat the main session. Include this in the Explore prompt:","","> Use `codegraph_explore` as your PRIMARY tool \u2014 one call returns full source from all relevant files. Do not re-Read files codegraph_explore already returned. Fall back to grep/glob/Read only if codegraph returned no results.","","**In the main session, use these lightweight codegraph tools directly:**","","| Tool | Use for |","|---|---|","| `codegraph_search` | Find symbols by name across the codebase |","| `codegraph_callers` / `codegraph_callees` | Trace call flow |","| `codegraph_impact` | Check what's affected before editing a symbol |","| `codegraph_node` | Get a single symbol's details |","| `codegraph_files` | Indexed file structure (faster than ls) |","| `codegraph_status` | Index health |",""].join(`
|
|
2
|
+
`)}function P(e){let t=e.mcp??{};return!e.codegraph||t.codegraph?t:{...t,codegraph:{command:p.command,args:[...p.args]}}}var _=".codegraph",x=10*60*1e3,g=2;function y(e){let t=Date.now();return new Promise((r,n)=>{m("codegraph",["init","--index","--quiet",e],{timeout:x,maxBuffer:4*1024*1024},o=>{o?n(o):r(Date.now()-t)})})}async function k(e,t=console.error){let r=[];for(let[i,s]of Object.entries(e))s.codegraph&&(s.tier!=="claude-code"&&s.tier!=="codex-cli"||d(s.workspace)&&(d(f(s.workspace,_))||r.push({agentId:i,workspace:s.workspace})));if(r.length===0)return;t(`codegraph: indexing ${r.length} workspace(s) in background (max ${g} parallel)`);let n=0,o=[];for(let i=0;i<Math.min(g,r.length);i++)o.push((async()=>{for(;;){let s=n++;if(s>=r.length)return;let{agentId:c,workspace:h}=r[s];try{let a=await y(h);t(` codegraph: indexed ${c} in ${(a/1e3).toFixed(1)}s`)}catch(a){let u=a?.code==="ENOENT"?" (codegraph CLI not on PATH; install with `npm i -g @colbymchenry/codegraph`)":"";t(` codegraph: ${c} index failed: ${a?.message??a}${u}`)}}})());await Promise.allSettled(o)}import{readFileSync as S,existsSync as b,unlinkSync as w,readdirSync as v}from"fs";import{resolve as l}from"path";function L(e,t){let r={},n=o=>{let i=l(e,o);if(b(i))try{return S(i,"utf-8").trim()||void 0}catch{return}};if(t){let o=n(`SOUL.${t}.md`);o?(r.soul=o,r.soulProfile=t):r.soul=n("SOUL.md")}else r.soul=n("SOUL.md");if(r.identity=n("IDENTITY.md"),r.user=n("USER.md"),r.agents=n("AGENTS.md"),r.bootstrap=n("BOOTSTRAP.md"),r.bootstrap)try{w(l(e,"BOOTSTRAP.md"))}catch{}return r}function D(e){let t=[];return e.identity&&t.push(`[Identity]
|
|
3
|
+
${e.identity}`),e.soul&&t.push(`[Personality & Boundaries]
|
|
4
|
+
${e.soul}`),e.user&&t.push(`[User Profile]
|
|
5
|
+
${e.user}`),e.bootstrap&&t.push(`[First-Run Instructions \u2014 one time only]
|
|
6
|
+
${e.bootstrap}`),t.length===0?"":t.join(`
|
|
7
|
+
|
|
8
|
+
`)}function F(e){return`# ${e.name}
|
|
9
|
+
|
|
10
|
+
> Agent ID: \`${e.id}\` | Tier: ${e.tier||"claude-code"}
|
|
11
|
+
|
|
12
|
+
## Role
|
|
13
|
+
|
|
14
|
+
${e.role||"AI agent managed by AgentX orchestrator."}
|
|
15
|
+
|
|
16
|
+
## Setup
|
|
17
|
+
|
|
18
|
+
This workspace is managed by AgentX. The agent runs via:
|
|
19
|
+
\`\`\`bash
|
|
20
|
+
# Direct execution
|
|
21
|
+
agentx daemon send ${e.id} "your task here"
|
|
22
|
+
|
|
23
|
+
# Or via any connected channel (Telegram, WhatsApp, GitLab)
|
|
24
|
+
\`\`\`
|
|
25
|
+
|
|
26
|
+
## Code Style
|
|
27
|
+
|
|
28
|
+
- Follow existing patterns in the codebase
|
|
29
|
+
- Use the language and framework conventions already present
|
|
30
|
+
- Keep changes minimal and focused
|
|
31
|
+
|
|
32
|
+
## Testing
|
|
33
|
+
|
|
34
|
+
Run tests before committing:
|
|
35
|
+
\`\`\`bash
|
|
36
|
+
npm test # or the project's test command
|
|
37
|
+
\`\`\`
|
|
38
|
+
|
|
39
|
+
## PR Guidelines
|
|
40
|
+
|
|
41
|
+
- One logical change per commit
|
|
42
|
+
- Reference issue numbers when applicable
|
|
43
|
+
- Keep PR descriptions concise
|
|
44
|
+
|
|
45
|
+
## AgentX Integration
|
|
46
|
+
|
|
47
|
+
This agent is part of an AgentX mesh. It can:
|
|
48
|
+
- Receive tasks from messaging channels (Telegram, WhatsApp, Discord)
|
|
49
|
+
- Respond to GitLab @mentions on issues and MRs
|
|
50
|
+
- Delegate to other agents by mentioning their handles
|
|
51
|
+
- Send cross-channel messages via the /send API
|
|
52
|
+
- Access its wiki knowledge base for context
|
|
53
|
+
`}function U(e){let t=e.match(/\/soul\s+(\w+)/i);return t?t[1].toLowerCase():/\/soul\s*$/i.test(e)?"default":null}export{R as a,O as b,P as c,k as d,L as e,D as f,F as g,U as h};
|
|
54
|
+
//# sourceMappingURL=chunk-67Q4DCPS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agents/codegraph-bootstrap.ts","../src/agents/bootstrap.ts"],"sourcesContent":["import { execFile } from \"child_process\"\nimport { existsSync } from \"fs\"\nimport { resolve } from \"path\"\nimport type { AgentDef } from \"@/daemon/config\"\nimport type { McpServerMap } from \"./agent-mcp\"\n\n// --- CodeGraph integration: per-agent semantic code-graph index ---\n//\n// CodeGraph (https://github.com/colbymchenry/codegraph) is a local\n// tree-sitter → SQLite knowledge graph exposed to Claude Code / Codex via\n// MCP. Opt-in per agent with `codegraph: true` on the agent's config.\n//\n// This module owns three responsibilities:\n// 1. `effectiveMcpConfig(def)` — synthesize the codegraph MCP server\n// entry into the agent's MCP map. Used by the daemon's\n// installAgentMcpConfig pass so the workspace's .mcp.json picks\n// up `codegraph serve --mcp` automatically.\n// 2. `bootstrapCodegraphIndexes(agents, log)` — at daemon boot, fire\n// off `codegraph init --index --quiet` in the background for any\n// opted-in workspace whose `.codegraph/` is missing. Throttled to\n// 2 parallel jobs so a large fleet doesn't thrash the host.\n// Returns immediately; the indexes finish on their own.\n// 3. Export the constant tool/CLI names that workspace-setup needs\n// to keep CLAUDE.md and settings.json in sync.\n\n/** MCP tool names exposed by `codegraph serve --mcp`. Used to extend the\n * per-workspace `.claude/settings.json` permissions.allow so claude\n * doesn't prompt for permission on every call. Keep in sync with the\n * upstream tool surface — additions are harmless, removals leave a\n * stale allow entry (also harmless). */\nexport const CODEGRAPH_TOOLS = [\n \"mcp__codegraph__codegraph_search\",\n \"mcp__codegraph__codegraph_context\",\n \"mcp__codegraph__codegraph_callers\",\n \"mcp__codegraph__codegraph_callees\",\n \"mcp__codegraph__codegraph_impact\",\n \"mcp__codegraph__codegraph_node\",\n \"mcp__codegraph__codegraph_status\",\n \"mcp__codegraph__codegraph_files\",\n] as const\n\n/** MCP server stanza we inject into `.mcp.json` for opted-in agents. */\nexport const CODEGRAPH_MCP_SERVER: { command: string; args: string[] } = {\n command: \"codegraph\",\n args: [\"serve\", \"--mcp\"],\n}\n\n/** Markdown block appended to managed CLAUDE.md when codegraph is on.\n * Tells the agent to prefer codegraph_* over grep, and to always spawn\n * an Explore subagent for codegraph_explore so the large source-dump\n * doesn't bloat the main session context. Mirrors the upstream-\n * recommended wording from the README's \"Global Instructions\" block. */\nexport function codegraphClaudeMdSection(): string {\n return [\n \"## CodeGraph\",\n \"\",\n \"This workspace has CodeGraph initialized — a semantic code-knowledge-graph indexed via tree-sitter. Use it instead of grep/find/Read for exploration.\",\n \"\",\n \"**ALWAYS spawn an Explore subagent for `codegraph_explore` / `codegraph_context`** — those tools return large source sections that would otherwise bloat the main session. Include this in the Explore prompt:\",\n \"\",\n \"> Use `codegraph_explore` as your PRIMARY tool — one call returns full source from all relevant files. Do not re-Read files codegraph_explore already returned. Fall back to grep/glob/Read only if codegraph returned no results.\",\n \"\",\n \"**In the main session, use these lightweight codegraph tools directly:**\",\n \"\",\n \"| Tool | Use for |\",\n \"|---|---|\",\n \"| `codegraph_search` | Find symbols by name across the codebase |\",\n \"| `codegraph_callers` / `codegraph_callees` | Trace call flow |\",\n \"| `codegraph_impact` | Check what's affected before editing a symbol |\",\n \"| `codegraph_node` | Get a single symbol's details |\",\n \"| `codegraph_files` | Indexed file structure (faster than ls) |\",\n \"| `codegraph_status` | Index health |\",\n \"\",\n ].join(\"\\n\")\n}\n\n/** Return the MCP server map an agent should expose to .mcp.json,\n * layering codegraph on top of the operator-declared `def.mcp` when\n * `def.codegraph === true`. Operator-declared entries win on key\n * collision (operator can override by declaring their own\n * `mcp.codegraph` block with different args). */\nexport function effectiveMcpConfig(def: AgentDef): McpServerMap {\n const base: McpServerMap = ((def as any).mcp ?? {}) as McpServerMap\n if (!def.codegraph) return base\n if (base.codegraph) return base\n return { ...base, codegraph: { command: CODEGRAPH_MCP_SERVER.command, args: [...CODEGRAPH_MCP_SERVER.args] } }\n}\n\nconst INDEX_DIR = \".codegraph\"\nconst INIT_TIMEOUT_MS = 10 * 60 * 1000 // 10 min — Swift Compiler benchmark indexed 25k files in ~4 min\nconst MAX_PARALLEL = 2\n\n/** Spawn `codegraph init --index --quiet` for one workspace. Returns the\n * duration in ms on success, throws on failure. Caller decides whether\n * to surface the error. */\nfunction indexWorkspace(workspace: string): Promise<number> {\n const started = Date.now()\n return new Promise<number>((res, rej) => {\n execFile(\n \"codegraph\",\n [\"init\", \"--index\", \"--quiet\", workspace],\n { timeout: INIT_TIMEOUT_MS, maxBuffer: 4 * 1024 * 1024 },\n (err) => {\n if (err) rej(err)\n else res(Date.now() - started)\n },\n )\n })\n}\n\n/** Boot-time helper: kick off `codegraph init --index` for every\n * opted-in workspace whose `.codegraph/` is missing. Fire-and-forget —\n * the returned promise resolves once all background jobs settle, but\n * callers (daemon start) don't need to await it. Indexing happens\n * while the daemon is already serving traffic; cold dispatches before\n * the index lands gracefully fall through to grep (the MCP server\n * returns an empty result, and CLAUDE.md tells the agent to fall back).\n *\n * Throttled to MAX_PARALLEL concurrent jobs so a fleet boot doesn't\n * saturate CPU/disk. */\nexport async function bootstrapCodegraphIndexes(\n agents: Record<string, AgentDef>,\n log: (...args: unknown[]) => void = console.error,\n): Promise<void> {\n const pending: Array<{ agentId: string; workspace: string }> = []\n for (const [agentId, def] of Object.entries(agents)) {\n if (!def.codegraph) continue\n if (def.tier !== \"claude-code\" && def.tier !== \"codex-cli\") continue\n if (!existsSync(def.workspace)) continue\n if (existsSync(resolve(def.workspace, INDEX_DIR))) continue\n pending.push({ agentId, workspace: def.workspace })\n }\n\n if (pending.length === 0) return\n\n log(`codegraph: indexing ${pending.length} workspace(s) in background (max ${MAX_PARALLEL} parallel)`)\n\n let i = 0\n const runners: Promise<void>[] = []\n for (let slot = 0; slot < Math.min(MAX_PARALLEL, pending.length); slot++) {\n runners.push((async () => {\n while (true) {\n const idx = i++\n if (idx >= pending.length) return\n const { agentId, workspace } = pending[idx]\n try {\n const ms = await indexWorkspace(workspace)\n log(` codegraph: indexed ${agentId} in ${(ms / 1000).toFixed(1)}s`)\n } catch (err: any) {\n // codegraph binary missing surfaces as ENOENT — recoverable hint\n const hint = err?.code === \"ENOENT\"\n ? \" (codegraph CLI not on PATH; install with `npm i -g @colbymchenry/codegraph`)\"\n : \"\"\n log(` codegraph: ${agentId} index failed: ${err?.message ?? err}${hint}`)\n }\n }\n })())\n }\n await Promise.allSettled(runners)\n}\n","import { readFileSync, existsSync, unlinkSync, readdirSync } from \"fs\"\nimport { resolve } from \"path\"\n\n// --- Bootstrap Identity Files ---\n//\n// Support for structured workspace identity files (inspired by OpenClaw).\n// These files live in the agent's workspace and are auto-loaded into context.\n//\n// Supported files:\n// SOUL.md — default personality, tone, boundaries\n// SOUL.{profile}.md — named soul profiles (e.g. SOUL.finance.md, SOUL.legal.md)\n// IDENTITY.md — name, role, emoji, tagline (persistent)\n// USER.md — user profile, preferences (persistent)\n// AGENTS.md — operating rules, standing orders (persistent)\n// BOOTSTRAP.md — one-time first-run ritual (auto-deleted after first load)\n//\n// Soul switching: send \"/soul finance\" to swap to SOUL.finance.md mid-session.\n\nexport interface BootstrapFiles {\n soul?: string\n /** Active soul profile name (undefined = default SOUL.md) */\n soulProfile?: string\n identity?: string\n user?: string\n agents?: string\n bootstrap?: string\n}\n\nconst BOOTSTRAP_FILE_NAMES = [\n \"SOUL.md\",\n \"IDENTITY.md\",\n \"USER.md\",\n \"AGENTS.md\",\n \"BOOTSTRAP.md\",\n] as const\n\n/**\n * Load bootstrap identity files from an agent's workspace.\n * @param soulProfile — optional soul profile name (e.g. \"finance\" loads SOUL.finance.md)\n */\nexport function loadBootstrapFiles(workspace: string, soulProfile?: string): BootstrapFiles {\n const result: BootstrapFiles = {}\n\n const tryLoad = (filename: string): string | undefined => {\n const filePath = resolve(workspace, filename)\n if (!existsSync(filePath)) return undefined\n try {\n const content = readFileSync(filePath, \"utf-8\").trim()\n return content || undefined\n } catch {\n return undefined\n }\n }\n\n // Load soul: profile-specific if requested, fallback to default\n if (soulProfile) {\n const profileSoul = tryLoad(`SOUL.${soulProfile}.md`)\n if (profileSoul) {\n result.soul = profileSoul\n result.soulProfile = soulProfile\n } else {\n // Profile not found — fall back to default and note it\n result.soul = tryLoad(\"SOUL.md\")\n }\n } else {\n result.soul = tryLoad(\"SOUL.md\")\n }\n\n result.identity = tryLoad(\"IDENTITY.md\")\n result.user = tryLoad(\"USER.md\")\n result.agents = tryLoad(\"AGENTS.md\")\n result.bootstrap = tryLoad(\"BOOTSTRAP.md\")\n\n // BOOTSTRAP.md is one-time: delete after loading\n if (result.bootstrap) {\n try {\n unlinkSync(resolve(workspace, \"BOOTSTRAP.md\"))\n } catch {\n // Best-effort deletion\n }\n }\n\n return result\n}\n\n/**\n * Build context string from bootstrap files.\n * Returns empty string if no files found.\n */\nexport function buildBootstrapContext(files: BootstrapFiles): string {\n const sections: string[] = []\n\n if (files.identity) {\n sections.push(`[Identity]\\n${files.identity}`)\n }\n\n if (files.soul) {\n sections.push(`[Personality & Boundaries]\\n${files.soul}`)\n }\n\n // AGENTS.md is intentionally NOT injected into AgentX's --append-system-prompt\n // anymore. It's loaded natively by Claude Code via `@AGENTS.md` in the\n // workspace's CLAUDE.md (generated by workspace-setup.ts for new workspaces;\n // added to existing workspaces by the 2026-04-24 distribution). Injecting it\n // here on top of the native CLAUDE.md path would double the bytes. Keeping\n // the load in BootstrapFiles for diagnostic/listing purposes only.\n\n if (files.user) {\n sections.push(`[User Profile]\\n${files.user}`)\n }\n\n if (files.bootstrap) {\n sections.push(`[First-Run Instructions — one time only]\\n${files.bootstrap}`)\n }\n\n if (sections.length === 0) return \"\"\n\n return sections.join(\"\\n\\n\")\n}\n\n/**\n * Check which bootstrap files exist in a workspace (for status/diagnostics).\n */\nexport function listBootstrapFiles(workspace: string): string[] {\n return BOOTSTRAP_FILE_NAMES.filter((name) =>\n existsSync(resolve(workspace, name))\n )\n}\n\n/**\n * List available soul profiles in a workspace.\n * Returns profile names (e.g. [\"finance\", \"legal\", \"creative\"]).\n */\nexport function listSoulProfiles(workspace: string): string[] {\n try {\n return readdirSync(workspace)\n .filter(f => f.startsWith(\"SOUL.\") && f.endsWith(\".md\") && f !== \"SOUL.md\")\n .map(f => f.slice(5, -3)) // \"SOUL.finance.md\" → \"finance\"\n } catch {\n return []\n }\n}\n\n/**\n * Generate a standard AGENTS.md for a new agent workspace.\n * Follows the agents.md community convention (https://agents.md/).\n * Readable by Claude Code, Codex, Cursor, Amp, Gemini CLI, etc.\n */\nexport function generateAgentsMd(agent: {\n name: string\n id: string\n role?: string\n workspace: string\n tier?: string\n}): string {\n return `# ${agent.name}\n\n> Agent ID: \\`${agent.id}\\` | Tier: ${agent.tier || \"claude-code\"}\n\n## Role\n\n${agent.role || \"AI agent managed by AgentX orchestrator.\"}\n\n## Setup\n\nThis workspace is managed by AgentX. The agent runs via:\n\\`\\`\\`bash\n# Direct execution\nagentx daemon send ${agent.id} \"your task here\"\n\n# Or via any connected channel (Telegram, WhatsApp, GitLab)\n\\`\\`\\`\n\n## Code Style\n\n- Follow existing patterns in the codebase\n- Use the language and framework conventions already present\n- Keep changes minimal and focused\n\n## Testing\n\nRun tests before committing:\n\\`\\`\\`bash\nnpm test # or the project's test command\n\\`\\`\\`\n\n## PR Guidelines\n\n- One logical change per commit\n- Reference issue numbers when applicable\n- Keep PR descriptions concise\n\n## AgentX Integration\n\nThis agent is part of an AgentX mesh. It can:\n- Receive tasks from messaging channels (Telegram, WhatsApp, Discord)\n- Respond to GitLab @mentions on issues and MRs\n- Delegate to other agents by mentioning their handles\n- Send cross-channel messages via the /send API\n- Access its wiki knowledge base for context\n`\n}\n\n/**\n * Detect a /soul command in a message.\n * Returns the requested profile name, or null if no /soul command found.\n * \"/soul finance\" → \"finance\"\n * \"/soul\" or \"/soul default\" → \"default\" (reset to SOUL.md)\n */\nexport function detectSoulSwitch(message: string): string | null {\n const match = message.match(/\\/soul\\s+(\\w+)/i)\n if (match) return match[1].toLowerCase()\n if (/\\/soul\\s*$/i.test(message)) return \"default\"\n return null\n}\n"],"mappings":"AAAA,OAAS,YAAAA,MAAgB,gBACzB,OAAS,cAAAC,MAAkB,KAC3B,OAAS,WAAAC,MAAe,OA4BjB,IAAMC,EAAkB,CAC7B,mCACA,oCACA,oCACA,oCACA,mCACA,iCACA,mCACA,iCACF,EAGaC,EAA4D,CACvE,QAAS,YACT,KAAM,CAAC,QAAS,OAAO,CACzB,EAOO,SAASC,GAAmC,CACjD,MAAO,CACL,eACA,GACA,6JACA,GACA,sNACA,GACA,0OACA,GACA,2EACA,GACA,qBACA,YACA,oEACA,kEACA,yEACA,uDACA,kEACA,wCACA,EACF,EAAE,KAAK;AAAA,CAAI,CACb,CAOO,SAASC,EAAmBC,EAA6B,CAC9D,IAAMC,EAAuBD,EAAY,KAAO,CAAC,EAEjD,MADI,CAACA,EAAI,WACLC,EAAK,UAAkBA,EACpB,CAAE,GAAGA,EAAM,UAAW,CAAE,QAASJ,EAAqB,QAAS,KAAM,CAAC,GAAGA,EAAqB,IAAI,CAAE,CAAE,CAC/G,CAEA,IAAMK,EAAY,aACZC,EAAkB,GAAK,GAAK,IAC5BC,EAAe,EAKrB,SAASC,EAAeC,EAAoC,CAC1D,IAAMC,EAAU,KAAK,IAAI,EACzB,OAAO,IAAI,QAAgB,CAACC,EAAKC,IAAQ,CACvChB,EACE,YACA,CAAC,OAAQ,UAAW,UAAWa,CAAS,EACxC,CAAE,QAASH,EAAiB,UAAW,EAAI,KAAO,IAAK,EACtDO,GAAQ,CACHA,EAAKD,EAAIC,CAAG,EACXF,EAAI,KAAK,IAAI,EAAID,CAAO,CAC/B,CACF,CACF,CAAC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A;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAiC3B,CAQO,SAASC,EAAiBC,EAAgC,CAC/D,IAAMC,EAAQD,EAAQ,MAAM,iBAAiB,EAC7C,OAAIC,EAAcA,EAAM,CAAC,EAAE,YAAY,EACnC,cAAc,KAAKD,CAAO,EAAU,UACjC,IACT","names":["execFile","existsSync","resolve","CODEGRAPH_TOOLS","CODEGRAPH_MCP_SERVER","codegraphClaudeMdSection","effectiveMcpConfig","def","base","INDEX_DIR","INIT_TIMEOUT_MS","MAX_PARALLEL","indexWorkspace","workspace","started","res","rej","err","bootstrapCodegraphIndexes","agents","log","pending","agentId","i","runners","slot","idx","ms","hint","readFileSync","existsSync","unlinkSync","readdirSync","resolve","loadBootstrapFiles","workspace","soulProfile","result","tryLoad","filename","filePath","resolve","existsSync","readFileSync","profileSoul","unlinkSync","buildBootstrapContext","files","sections","generateAgentsMd","agent","detectSoulSwitch","message","match"]}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{a as I}from"./chunk-W4YR2RO2.js";var w=new Map,ne=/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$/;function m(e){if(!ne.test(e.name))throw new Error(`built-in action name must be dotted lowercase identifier (got "${e.name}")`);w.set(e.name,e)}function re(e){return w.get(e)}function se(){let e=[];for(let[n,t]of w.entries())e.push({name:n,description:t.description,timeoutMs:t.timeoutMs});return e.sort((n,t)=>n.name.localeCompare(t.name)),e}function _(){w.clear()}var oe=6e4;async function ie(e,n){let t=w.get(e);if(!t)throw new Error(`unknown built-in action: ${e}`);let r=t.inputSchema.parse(n),o=t.timeoutMs??oe,i=t.handler(r),a=new Promise((y,b)=>{setTimeout(()=>b(new Error(`built-in action ${e} timed out after ${o}ms`)),o)}),c=await Promise.race([i,a]),g=t.outputSchema.safeParse(c);return g.success||process.stderr.write(`[builtin-action] ${e} output failed schema validation: ${g.error.message}
|
|
2
|
+
`),c}import{z as l}from"zod";var T=null;function M(){return T}function Ve(e){T=e}var ae=l.object({agentId:l.string().min(1),message:l.string().min(1),freshSession:l.boolean().default(!0),channel:l.string().default("api"),chatId:l.string().optional(),senderAgentId:l.string().optional(),timeoutMs:l.number().int().min(1).max(6e5).default(9e4)}),ce=l.object({agentId:l.string(),reply:l.string(),error:l.string().optional(),errorKind:l.string().optional(),usage:l.object({inputTokens:l.number().int().default(0),outputTokens:l.number().int().default(0),cacheReadTokens:l.number().int().default(0),cacheCreateTokens:l.number().int().default(0)}).default({inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0}),durationMs:l.number().int().default(0)}),k={name:"agent.call",description:"Dispatch a task to a local agent on the same daemon (fresh session by default \u2014 replaces ad-hoc 'Bash curl /task' delegation)",inputSchema:ae,outputSchema:ce,timeoutMs:6e5,handler:async e=>{let n=M();if(!n)throw new Error("agent registry not wired (daemon not started or running in a non-daemon process)");let t=e.chatId??`agent-call-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,r=Date.now(),o=await n.execute({agentId:e.agentId,message:e.message,freshSession:e.freshSession,context:{channel:e.channel,chatId:t}});return{agentId:e.agentId,reply:o.content??"",error:o.error,errorKind:o.errorKind,usage:{inputTokens:o.usage?.inputTokens??0,outputTokens:o.usage?.outputTokens??0,cacheReadTokens:o.usage?.cacheReadTokens??0,cacheCreateTokens:o.usage?.cacheCreateTokens??0},durationMs:o.duration??Date.now()-r}}};import{z as s}from"zod";var le=s.object({channel:s.string().min(1),chatId:s.string().min(1),text:s.string().min(1),agentId:s.string().optional(),accountId:s.string().optional(),replyTo:s.string().optional(),idempotencyKey:s.string().optional(),buttons:s.array(s.object({label:s.string(),url:s.string()})).optional(),poll:s.object({name:s.string(),values:s.array(s.string()),selectableCount:s.number().optional()}).optional(),media:s.object({type:s.enum(["image","document","audio","video"]),url:s.string(),caption:s.string().optional()}).optional()}),ue=s.object({messageId:s.string().nullable()}),R={name:"channel.reply",description:"Post a reply to a channel (gitlab/github comment, telegram/whatsapp message, \u2026) through the canonical adapter \u2014 auto-marker, auto-dedupe within 60s, identity resolved from agentMappings.",inputSchema:le,outputSchema:ue,timeoutMs:3e4,handler:async e=>{let n=I();if(!n)throw new Error("message router not wired (daemon not started or running in a non-daemon process)");let t=e.idempotencyKey??"",r=await n.sendOutbound({channel:e.channel,chatId:e.chatId,text:e.text,agentId:e.agentId,accountId:e.accountId,replyTo:e.replyTo,buttons:e.buttons,poll:e.poll,media:e.media},{idempotencyKey:t,dedupeWindowMs:6e4});return{messageId:typeof r=="string"?r:null}}},de=s.object({channel:s.literal("gitlab"),project:s.string().min(1),kind:s.enum(["issue","merge_request"]),iid:s.string().min(1),add:s.array(s.string()).default([]),remove:s.array(s.string()).default([]),agentId:s.string().optional()}),pe=s.object({labels:s.array(s.string())}),C={name:"channel.label",description:"Add and/or remove labels on a GitLab issue/MR through the adapter (per-agent token, ledger, no raw curl).",inputSchema:de,outputSchema:pe,timeoutMs:3e4,handler:async e=>{let n=I();if(!n)throw new Error("message router not wired");let t=n.getChannel?.(e.channel);if(!t?.setLabels)throw new Error(`channel "${e.channel}" does not expose setLabels`);let r=await t.setLabels({project:e.project,kind:e.kind,iid:e.iid,add:e.add,remove:e.remove,agentId:e.agentId});return{labels:Array.isArray(r)?r:[]}}},ge=s.object({channel:s.literal("gitlab"),project:s.string().min(1),kind:s.enum(["issue","merge_request"]),iid:s.string().min(1),assignees:s.array(s.string()).default([]),agentId:s.string().optional()}),me=s.object({assigneeIds:s.array(s.number())}),E={name:"channel.assign",description:"Set assignees on a GitLab issue or MR (replaces the assignee list). Pass empty array to unassign. Use during Triage\u2192To Do flip to assign the coding agent, or to designate reviewer/merger on an MR.",inputSchema:ge,outputSchema:me,timeoutMs:3e4,handler:async e=>{let n=I();if(!n)throw new Error("message router not wired");let t=n.getChannel?.(e.channel);if(!t?.setAssignees)throw new Error(`channel "${e.channel}" does not expose setAssignees`);let r=await t.setAssignees({project:e.project,kind:e.kind,iid:e.iid,assignees:e.assignees,agentId:e.agentId});return{assigneeIds:Array.isArray(r)?r:[]}}},he=s.object({channel:s.literal("gitlab"),project:s.string().min(1),title:s.string().min(1),description:s.string().default(""),labels:s.array(s.string()).default([]),assignees:s.array(s.string()).default([]),agentId:s.string().optional(),relateToIid:s.string().optional()}),fe=s.object({iid:s.number(),url:s.string(),related:s.boolean().default(!1)}),L={name:"channel.create_issue",description:"Create a GitLab issue from an agent (PM test cases, CX client requests). Honors per-agent identity; resolves assignee usernames to ids; optional /relate to a parent issue.",inputSchema:he,outputSchema:fe,timeoutMs:6e4,handler:async e=>{let n=I();if(!n)throw new Error("message router not wired");let t=n.getChannel?.(e.channel);if(!t?.createIssue)throw new Error(`channel "${e.channel}" does not expose createIssue`);let r=await t.createIssue({project:e.project,title:e.title,description:e.description,labels:e.labels,assignees:e.assignees,agentId:e.agentId});if(!r)throw new Error("createIssue returned null \u2014 see daemon log for details");let o=!1;return e.relateToIid&&t.relateIssue&&(o=await t.relateIssue({project:e.project,sourceIid:String(r.iid),targetIid:e.relateToIid,agentId:e.agentId})),{iid:r.iid,url:r.url,related:o}}};import{z as p}from"zod";var ye=p.object({model:p.string().default("claude-haiku-4-5"),prompt:p.string().min(1),schema:p.record(p.string(),p.unknown()),systemPrompt:p.string().optional(),maxTokens:p.number().int().min(1).max(8e3).default(1024),timeoutMs:p.number().int().min(1).max(12e4).default(6e4)}),be=p.object({data:p.unknown(),model:p.string(),usage:p.object({inputTokens:p.number().int(),outputTokens:p.number().int()})}),Ie="https://api.anthropic.com/v1/messages",we="2023-06-01",B={name:"extract.structured",description:"Single-call typed extraction: prompt + JSON-Schema \u2192 structured data via forced tool_use",inputSchema:ye,outputSchema:be,timeoutMs:12e4,handler:async e=>{let n=process.env.ANTHROPIC_API_KEY;if(!n)throw new Error("ANTHROPIC_API_KEY env var is not set \u2014 extract.structured needs direct API access");let t={model:e.model,max_tokens:e.maxTokens,messages:[{role:"user",content:e.prompt}],tools:[{name:"respond_with_structure",description:"Return a structured value matching the schema",input_schema:e.schema}],tool_choice:{type:"tool",name:"respond_with_structure"}};e.systemPrompt&&(t.system=e.systemPrompt);let r=new AbortController,o=setTimeout(()=>r.abort(),e.timeoutMs),i;try{i=await fetch(Ie,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":n,"anthropic-version":we},body:JSON.stringify(t),signal:r.signal})}finally{clearTimeout(o)}if(!i.ok){let b=await i.text().catch(()=>"");throw new Error(`anthropic API ${i.status}: ${b.slice(0,500)}`)}let a=await i.json(),c=Array.isArray(a.content)?a.content:[],g=c.find(b=>b?.type==="tool_use"&&b?.name==="respond_with_structure");if(!g||g.input===void 0)throw new Error(`anthropic API returned no respond_with_structure tool_use (got ${c.length} blocks)`);let y=a.usage??{};return{data:g.input,model:typeof a.model=="string"?a.model:e.model,usage:{inputTokens:typeof y.input_tokens=="number"?y.input_tokens:0,outputTokens:typeof y.output_tokens=="number"?y.output_tokens:0}}}};import{z as u}from"zod";import{existsSync as xe,readFileSync as Ae,appendFileSync as Se,mkdirSync as Oe,statSync as _e}from"fs";import{resolve as j,dirname as Te,isAbsolute as Me}from"path";var D=8*1024*1024;function z(e){let n=Me(e)?e:j(process.cwd(),e),r=(process.env.AGENTX_BUILTIN_FILE_ROOTS||process.cwd()).split(":").map(o=>j(o));for(let o of r)if(n===o||n.startsWith(o+"/"))return n;throw new Error(`path "${e}" is outside the allowed roots`)}var ke=u.object({path:u.string().min(1),maxLines:u.number().int().min(1).max(1e4).default(200),fromEnd:u.boolean().default(!1)}),Re=u.object({path:u.string(),lines:u.array(u.string()),totalLines:u.number().int(),truncated:u.boolean()}),v={name:"file.read_lines",description:"Read a text file as an array of lines (utf-8, 8MB cap, scoped to allowed roots)",inputSchema:ke,outputSchema:Re,timeoutMs:1e4,handler:async e=>{let n=z(e.path);if(!xe(n))throw new Error(`file not found: ${e.path}`);let t=_e(n);if(!t.isFile())throw new Error(`not a regular file: ${e.path}`);if(t.size>D)throw new Error(`file too large (${t.size} > ${D} bytes)`);let o=Ae(n,"utf8").split(`
|
|
3
|
+
`);o.length>0&&o[o.length-1]===""&&o.pop();let i=o.length,a,c;return i<=e.maxLines?(a=o,c=!1):(c=!0,a=e.fromEnd?o.slice(i-e.maxLines):o.slice(0,e.maxLines)),{path:n,lines:a,totalLines:i,truncated:c}}},Ce=u.object({path:u.string().min(1),records:u.array(u.unknown()).min(1),createDirs:u.boolean().default(!1)}),Ee=u.object({path:u.string(),written:u.number().int(),bytesAppended:u.number().int()}),P={name:"file.write_jsonl",description:"Append JSON records to a file as newline-delimited JSON (utf-8, scoped to allowed roots)",inputSchema:Ce,outputSchema:Ee,timeoutMs:1e4,handler:async e=>{let n=z(e.path),t=[];for(let o of e.records)try{t.push(JSON.stringify(o))}catch(i){throw new Error(`record ${t.length} not JSON-serializable: ${i?.message||String(i)}`)}let r=t.join(`
|
|
4
|
+
`)+`
|
|
5
|
+
`;return e.createDirs&&Oe(Te(n),{recursive:!0}),Se(n,r,"utf8"),{path:n,written:t.length,bytesAppended:Buffer.byteLength(r,"utf8")}}};import{z as d}from"zod";var $=1024*1024,x=d.record(d.string(),d.string()),Le=["http:","https:"];function F(e){let n;try{n=new URL(e)}catch{throw new Error(`invalid url: ${e}`)}if(!Le.includes(n.protocol))throw new Error(`scheme not allowed (only http/https): ${n.protocol}`);return n}var Be=d.object({url:d.string().min(1),headers:x.optional(),timeoutMs:d.number().int().min(1).max(6e4).default(3e4)}),N=d.object({status:d.number().int(),statusText:d.string(),headers:x,body:d.string(),truncated:d.boolean(),url:d.string()});async function J(e){if(!e.body)return{body:"",truncated:!1};let n=e.body.getReader(),t=new TextDecoder,r=0,o="",i=!1;for(;;){let{done:a,value:c}=await n.read();if(a)break;if(c){if(r+=c.length,r>$){o+=t.decode(c.slice(0,$-(r-c.length)),{stream:!1}),i=!0;try{await n.cancel()}catch{}break}o+=t.decode(c,{stream:!0})}}return o+=t.decode(),{body:o,truncated:i}}function U(e){let n={};return e.forEach((t,r)=>{n[r]=t}),n}var H={name:"http.fetch",description:"GET a URL, return body + status + headers (1MB cap, http/https only)",inputSchema:Be,outputSchema:N,timeoutMs:35e3,handler:async e=>{F(e.url);let n=new AbortController,t=setTimeout(()=>n.abort(),e.timeoutMs);try{let r=await fetch(e.url,{method:"GET",headers:e.headers??{},signal:n.signal}),{body:o,truncated:i}=await J(r);return{status:r.status,statusText:r.statusText,headers:U(r.headers),body:o,truncated:i,url:r.url}}finally{clearTimeout(t)}}},je=d.object({url:d.string().min(1),body:d.unknown(),headers:x.optional(),timeoutMs:d.number().int().min(1).max(6e4).default(3e4)}),K={name:"http.post",description:"POST a JSON body to a URL, return body + status + headers (1MB cap, http/https only)",inputSchema:je,outputSchema:N,timeoutMs:35e3,handler:async e=>{F(e.url);let n=new AbortController,t=setTimeout(()=>n.abort(),e.timeoutMs);try{let r={"Content-Type":"application/json",...e.headers??{}},o=await fetch(e.url,{method:"POST",headers:r,body:JSON.stringify(e.body??{}),signal:n.signal}),{body:i,truncated:a}=await J(o);return{status:o.status,statusText:o.statusText,headers:U(o.headers),body:i,truncated:a,url:o.url}}finally{clearTimeout(t)}}};import{z as f}from"zod";var q=null;function W(){return q}function gt(e){q=e}var De=f.object({peer:f.string().min(1),agent:f.string().optional(),message:f.string().min(1),timeoutMs:f.number().int().min(1).max(6e5).default(9e4),senderAgentId:f.string().optional(),freshSession:f.boolean().default(!0)}),ze=f.object({peer:f.string(),agent:f.string().nullable(),response:f.string()}),G={name:"mesh.delegate",description:"Send a task to a remote mesh peer's agent and return the response text",inputSchema:De,outputSchema:ze,timeoutMs:6e5,handler:async e=>{let n=W();if(!n)throw new Error("mesh not enabled on this daemon (config.mesh.enabled = false)");let t=await n.sendTask(e.peer,e.message,e.agent,{timeoutMs:e.timeoutMs,senderAgentId:e.senderAgentId,freshSession:e.freshSession});return{peer:e.peer,agent:e.agent??null,response:t}}};import{z as h}from"zod";import{existsSync as X,mkdirSync as ve,readFileSync as S,writeFileSync as Pe,statSync as $e}from"fs";import{resolve as Y,basename as Fe,relative as Ne}from"path";import Je from"fast-glob";import V from"minisearch";var Q=["title","body"],Z=["title","body","path","indexedAt"];function O(e,n=".agentx/rag"){return Y(process.cwd(),n,e,"index.json")}function Ue(){return new V({fields:Q,storeFields:Z,searchOptions:{boost:{title:2},fuzzy:.2,prefix:!0}})}function He(e,n){let t=S(e,"utf8"),r=t.match(/^\s*#\s+(.+)$/m),o=r?r[1].trim():Fe(e).replace(/\.[^.]+$/,"");return{id:n,title:o,body:t,path:e,indexedAt:new Date().toISOString()}}async function At(e,n,t={}){let r=t.cwd??process.cwd(),o=(await Je(n,{cwd:r,absolute:!0,dot:!1})).filter(c=>{try{return $e(c).isFile()}catch{return!1}}),i=Ue();for(let c of o){let g=Ne(r,c),y=He(c,g);i.add(y),t.verbose&&process.stderr.write(`[rag] indexed ${g} (${y.body.length} bytes)
|
|
6
|
+
`)}let a=O(e,t.baseDir);return ve(Y(a,".."),{recursive:!0}),Pe(a,JSON.stringify(i.toJSON()),"utf8"),{docs:o.length,path:a}}function Ke(e,n={}){let t=O(e,n.baseDir);if(!X(t))return null;try{let r=S(t,"utf8");return V.loadJSON(r,{fields:Q,storeFields:Z,searchOptions:{boost:{title:2},fuzzy:.2,prefix:!0}})}catch(r){return process.stderr.write(`[rag] failed to load ${t}: ${r?.message||String(r)}
|
|
7
|
+
`),null}}var A=80,qe=A*2+60;function We(e,n){let t=e.toLowerCase(),r=-1;for(let c of n){let g=t.indexOf(c.toLowerCase());g>=0&&(r===-1||g<r)&&(r=g)}if(r===-1)return e.slice(0,qe).replace(/\s+/g," ").trim();let o=Math.max(0,r-A),i=Math.min(e.length,r+A),a=e.slice(o,i).replace(/\s+/g," ").trim();return(o>0?"\u2026":"")+a+(i<e.length?"\u2026":"")}function ee(e,n,t={}){let r=Ke(e,{baseDir:t.baseDir});if(!r)return[];let o=Math.max(1,Math.min(50,t.k??5));return r.search(n).slice(0,o).map(a=>({id:a.id,title:a.title,path:a.path,score:a.score,snippet:We(a.body||"",a.terms||[])}))}function St(e,n={}){let t=O(e,n.baseDir);if(!X(t))return{exists:!1,path:t,docs:0};try{let r=JSON.parse(S(t,"utf8")),o=r?.storedFields??r?._storedFields;if(typeof r?.documentCount=="number")return{exists:!0,path:t,docs:r.documentCount};let i=o&&typeof o=="object"?Object.keys(o).length:0;return{exists:!0,path:t,docs:i}}catch{return{exists:!0,path:t,docs:0}}}var Ge=h.object({agentId:h.string().min(1),query:h.string().min(1),k:h.number().int().min(1).max(50).default(5)}),Xe=h.object({hits:h.array(h.object({id:h.string(),title:h.string(),path:h.string(),score:h.number(),snippet:h.string()}))}),te={name:"rag.lexical",description:"BM25-style lexical search over an agent's pre-built index (no embeddings, deterministic)",inputSchema:Ge,outputSchema:Xe,timeoutMs:5e3,handler:async e=>({hits:ee(e.agentId,e.query,{k:e.k})})};function zt(){m(k),m(E),m(L),m(C),m(R),m(B),m(v),m(P),m(H),m(K),m(G),m(te)}function vt(){_()}export{re as a,se as b,ie as c,Ve as d,gt as e,At as f,ee as g,St as h,zt as i,vt as j};
|
|
8
|
+
//# sourceMappingURL=chunk-76Z4VHDX.js.map
|