@integrity-labs/agt-cli 0.28.1233 → 0.28.1235
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/dist/bin/agt.js +6 -6
- package/dist/{chunk-VGEMWYW3.js → chunk-ASJCTFLB.js} +5 -5
- package/dist/{chunk-3HLECXMI.js → chunk-FIGZJ6AU.js} +46 -1
- package/dist/{chunk-3HLECXMI.js.map → chunk-FIGZJ6AU.js.map} +1 -1
- package/dist/{chunk-DQEUE2X2.js → chunk-GAQFCMBK.js} +2 -2
- package/dist/{chunk-XXIALNTU.js → chunk-I57M57XZ.js} +89 -3
- package/dist/{chunk-XXIALNTU.js.map → chunk-I57M57XZ.js.map} +1 -1
- package/dist/{chunk-HI4JD2K2.js → chunk-VGZ2SKEW.js} +3 -3
- package/dist/{chunk-4FLMCHQB.js → chunk-WAWLHUCT.js} +2 -2
- package/dist/{claude-code-updater-UTFTOX3B.js → claude-code-updater-GXYP3Y6O.js} +3 -3
- package/dist/{claude-pair-runtime-DI43DJ4P.js → claude-pair-runtime-GEFCVMJA.js} +3 -3
- package/dist/lib/manager-worker.js +42 -24
- package/dist/lib/manager-worker.js.map +1 -1
- package/dist/mcp/direct-chat-channel.js +42 -2
- package/dist/mcp/index.js +47 -5
- package/dist/mcp/origami.js +42 -2
- package/dist/mcp/slack-channel.js +42 -2
- package/dist/mcp/telegram-channel.js +42 -2
- package/dist/{persistent-session-S57KHU34.js → persistent-session-VEE36NTM.js} +4 -4
- package/dist/{responsiveness-probe-TFPKYDPB.js → responsiveness-probe-ZPBEQOK5.js} +4 -4
- package/dist/{scheduler-engine-M6AFZWNU.js → scheduler-engine-5PCBGRNY.js} +8 -2
- package/dist/{session-auth-dead-EYJAWW46.js → session-auth-dead-HOVWVHBB.js} +3 -3
- package/package.json +1 -1
- /package/dist/{chunk-VGEMWYW3.js.map → chunk-ASJCTFLB.js.map} +0 -0
- /package/dist/{chunk-DQEUE2X2.js.map → chunk-GAQFCMBK.js.map} +0 -0
- /package/dist/{chunk-HI4JD2K2.js.map → chunk-VGZ2SKEW.js.map} +0 -0
- /package/dist/{chunk-4FLMCHQB.js.map → chunk-WAWLHUCT.js.map} +0 -0
- /package/dist/{claude-code-updater-UTFTOX3B.js.map → claude-code-updater-GXYP3Y6O.js.map} +0 -0
- /package/dist/{claude-pair-runtime-DI43DJ4P.js.map → claude-pair-runtime-GEFCVMJA.js.map} +0 -0
- /package/dist/{persistent-session-S57KHU34.js.map → persistent-session-VEE36NTM.js.map} +0 -0
- /package/dist/{responsiveness-probe-TFPKYDPB.js.map → responsiveness-probe-ZPBEQOK5.js.map} +0 -0
- /package/dist/{scheduler-engine-M6AFZWNU.js.map → scheduler-engine-5PCBGRNY.js.map} +0 -0
- /package/dist/{session-auth-dead-EYJAWW46.js.map → session-auth-dead-HOVWVHBB.js.map} +0 -0
package/dist/bin/agt.js
CHANGED
|
@@ -40,17 +40,17 @@ import {
|
|
|
40
40
|
success,
|
|
41
41
|
table,
|
|
42
42
|
warn
|
|
43
|
-
} from "../chunk-
|
|
43
|
+
} from "../chunk-ASJCTFLB.js";
|
|
44
44
|
import {
|
|
45
45
|
getProjectDir,
|
|
46
46
|
isSessionResumeDisabled,
|
|
47
47
|
readDirectChatSessionState
|
|
48
|
-
} from "../chunk-
|
|
48
|
+
} from "../chunk-VGZ2SKEW.js";
|
|
49
49
|
import {
|
|
50
50
|
markDailySessionSpawn,
|
|
51
51
|
sessionFileExists,
|
|
52
52
|
sessionTranscriptDir
|
|
53
|
-
} from "../chunk-
|
|
53
|
+
} from "../chunk-WAWLHUCT.js";
|
|
54
54
|
import "../chunk-HYQ7VOC3.js";
|
|
55
55
|
import "../chunk-6HBXEJHO.js";
|
|
56
56
|
import "../chunk-XWVM4KPK.js";
|
|
@@ -83,7 +83,7 @@ import {
|
|
|
83
83
|
requiredMcpWildcard,
|
|
84
84
|
resolveChannels,
|
|
85
85
|
serializeManifestForSlackCli
|
|
86
|
-
} from "../chunk-
|
|
86
|
+
} from "../chunk-I57M57XZ.js";
|
|
87
87
|
import "../chunk-AIUIMEUS.js";
|
|
88
88
|
import "../chunk-DGUM43GV.js";
|
|
89
89
|
|
|
@@ -5205,7 +5205,7 @@ import { execFileSync, execSync } from "child_process";
|
|
|
5205
5205
|
import { existsSync as existsSync10, realpathSync as realpathSync2 } from "fs";
|
|
5206
5206
|
import chalk17 from "chalk";
|
|
5207
5207
|
import ora15 from "ora";
|
|
5208
|
-
var cliVersion = true ? "0.28.
|
|
5208
|
+
var cliVersion = true ? "0.28.1235" : "dev";
|
|
5209
5209
|
async function fetchLatestVersion() {
|
|
5210
5210
|
const host2 = getHost();
|
|
5211
5211
|
if (!host2) return null;
|
|
@@ -6465,7 +6465,7 @@ function handleError(err) {
|
|
|
6465
6465
|
}
|
|
6466
6466
|
|
|
6467
6467
|
// src/bin/agt.ts
|
|
6468
|
-
var cliVersion2 = true ? "0.28.
|
|
6468
|
+
var cliVersion2 = true ? "0.28.1235" : "dev";
|
|
6469
6469
|
var program = new Command();
|
|
6470
6470
|
program.name("agt").description("Augmented CLI \u2014 agent provisioning and management").version(cliVersion2).option("--json", "Emit machine-readable JSON output (suppress spinners and colors)").option("--skip-update-check", "Skip the automatic update check on startup");
|
|
6471
6471
|
program.hook("preAction", async (thisCommand, actionCommand) => {
|
|
@@ -18,11 +18,11 @@ import {
|
|
|
18
18
|
requiresRemoteMcpToolGate,
|
|
19
19
|
shellQuote,
|
|
20
20
|
withheldRemoteMcpMessage
|
|
21
|
-
} from "./chunk-
|
|
21
|
+
} from "./chunk-VGZ2SKEW.js";
|
|
22
22
|
import {
|
|
23
23
|
readDailySessionPin,
|
|
24
24
|
sessionTranscriptDir
|
|
25
|
-
} from "./chunk-
|
|
25
|
+
} from "./chunk-WAWLHUCT.js";
|
|
26
26
|
import {
|
|
27
27
|
classifyUnanswerablePane,
|
|
28
28
|
isConsumerTermsDialogVisible,
|
|
@@ -95,7 +95,7 @@ import {
|
|
|
95
95
|
scanConfigForLiteralSecrets,
|
|
96
96
|
worseConnectivityOutcome,
|
|
97
97
|
wrapScheduledTaskPrompt
|
|
98
|
-
} from "./chunk-
|
|
98
|
+
} from "./chunk-I57M57XZ.js";
|
|
99
99
|
import {
|
|
100
100
|
claudeJsonPathFor,
|
|
101
101
|
effectiveClaudeJsonPath,
|
|
@@ -8095,7 +8095,7 @@ function exchangeFailureKind(err) {
|
|
|
8095
8095
|
}
|
|
8096
8096
|
|
|
8097
8097
|
// src/lib/api-client.ts
|
|
8098
|
-
var agtCliVersion = true ? "0.28.
|
|
8098
|
+
var agtCliVersion = true ? "0.28.1235" : "dev";
|
|
8099
8099
|
var lastConfigHash = null;
|
|
8100
8100
|
function setConfigHash(hash) {
|
|
8101
8101
|
lastConfigHash = hash && hash.length > 0 ? hash : null;
|
|
@@ -13750,4 +13750,4 @@ export {
|
|
|
13750
13750
|
managerInstallSystemUnitCommand,
|
|
13751
13751
|
managerUninstallSystemUnitCommand
|
|
13752
13752
|
};
|
|
13753
|
-
//# sourceMappingURL=chunk-
|
|
13753
|
+
//# sourceMappingURL=chunk-ASJCTFLB.js.map
|
|
@@ -173,6 +173,48 @@ function getReadyTasks(state, inFlightTaskIds) {
|
|
|
173
173
|
return true;
|
|
174
174
|
});
|
|
175
175
|
}
|
|
176
|
+
var CATCH_UP_MIN_LATENESS_MS = 10 * 6e4;
|
|
177
|
+
var CATCH_UP_COUNT_CAP = 1e3;
|
|
178
|
+
function describeCatchUp(task, nowMs) {
|
|
179
|
+
if (task.triggeredAt && task.triggeredAt > (task.consumedTriggeredAt ?? 0)) return null;
|
|
180
|
+
if (task.scheduleKind === "at" || task.nextFireAt === null) return null;
|
|
181
|
+
const dueAt = task.nextFireAt;
|
|
182
|
+
if (nowMs - dueAt < CATCH_UP_MIN_LATENESS_MS) return null;
|
|
183
|
+
let occurrences = 1;
|
|
184
|
+
let capped = false;
|
|
185
|
+
if (task.scheduleKind === "every") {
|
|
186
|
+
const interval = parseIntervalMs(task.scheduleEvery);
|
|
187
|
+
occurrences = 1 + Math.floor((nowMs - dueAt) / interval);
|
|
188
|
+
if (occurrences > CATCH_UP_COUNT_CAP) {
|
|
189
|
+
occurrences = CATCH_UP_COUNT_CAP;
|
|
190
|
+
capped = true;
|
|
191
|
+
}
|
|
192
|
+
} else if (task.scheduleExpr) {
|
|
193
|
+
try {
|
|
194
|
+
const cron = new Cron(task.scheduleExpr, { timezone: task.timezone || void 0 });
|
|
195
|
+
let cursor = new Date(dueAt);
|
|
196
|
+
for (; ; ) {
|
|
197
|
+
const next = cron.nextRun(cursor);
|
|
198
|
+
if (!next || next.getTime() > nowMs) break;
|
|
199
|
+
if (occurrences >= CATCH_UP_COUNT_CAP) {
|
|
200
|
+
capped = true;
|
|
201
|
+
break;
|
|
202
|
+
}
|
|
203
|
+
occurrences++;
|
|
204
|
+
cursor = next;
|
|
205
|
+
}
|
|
206
|
+
} catch {
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return { dueAt, occurrences, capped };
|
|
210
|
+
}
|
|
211
|
+
function catchUpNote(facts, nowMs) {
|
|
212
|
+
const due = new Date(facts.dueAt).toISOString().slice(0, 16).replace("T", " ");
|
|
213
|
+
const now = new Date(nowMs).toISOString().slice(0, 16).replace("T", " ");
|
|
214
|
+
const missed = facts.occurrences - 1;
|
|
215
|
+
const count = facts.capped ? `more than ${missed}` : String(missed);
|
|
216
|
+
return `[Catch-up run: this task was due at ${due} UTC but the agent was not running until ${now} UTC. ` + (missed > 0 ? `${count} further scheduled run${missed === 1 ? "" : "s"} fell due in that window and were skipped; this one run covers them. ` : "") + "If the task is time-sensitive, cover the whole missed window, not only the latest slot.]";
|
|
217
|
+
}
|
|
176
218
|
function markTaskFired(codeName, taskId, status) {
|
|
177
219
|
const state = loadSchedulerState(codeName);
|
|
178
220
|
const task = state.tasks[taskId];
|
|
@@ -217,8 +259,11 @@ export {
|
|
|
217
259
|
saveSchedulerState,
|
|
218
260
|
syncTasksToScheduler,
|
|
219
261
|
getReadyTasks,
|
|
262
|
+
CATCH_UP_MIN_LATENESS_MS,
|
|
263
|
+
describeCatchUp,
|
|
264
|
+
catchUpNote,
|
|
220
265
|
markTaskFired,
|
|
221
266
|
findTaskByTemplate,
|
|
222
267
|
getProjectDir
|
|
223
268
|
};
|
|
224
|
-
//# sourceMappingURL=chunk-
|
|
269
|
+
//# sourceMappingURL=chunk-FIGZJ6AU.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/scheduler-engine.ts"],"sourcesContent":["/**\n * Framework-agnostic scheduled-task state machine.\n *\n * The pure scheduling engine: schedule definitions -> next-fire computation ->\n * ready-task detection -> post-fire state advance, with on-disk persistence so\n * nextFireAt/lastFireAt survive manager restarts. It owns the WHEN, not the HOW:\n * each framework supplies its own firing leaf and calls back into\n * `markTaskFired`.\n * - Claude Code fires via the in-session kanban todo-card route\n * (manager/scheduler/execution.ts + kanban-route.ts).\n * - opencode fires via an HTTP inject into `opencode serve`\n * (manager/opencode-scheduler.ts).\n * Both share this engine verbatim, so cadence, one-shot completion,\n * manual-trigger, and cross-restart recovery are identical across frameworks.\n * (Named claude-scheduler.ts historically, when the claude `-p` oneshot was the\n * only consumer.)\n */\n\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\nimport { Cron } from 'croner';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface SchedulerTaskState {\n taskId: string;\n templateId: string;\n name: string;\n agentCodeName: string;\n agentId: string;\n scheduleKind: 'cron' | 'every' | 'at';\n scheduleExpr: string | null;\n scheduleEvery: string | null;\n scheduleAt: string | null;\n timezone: string;\n prompt: string;\n sessionTarget: string;\n deliveryMode: string;\n /** ENG-6107: always | conditional | never — whether results deliver.\n * Optional: states persisted by older CLIs lack it; absent = 'always'. */\n deliveryPolicy?: string | null;\n deliveryChannel: string | null;\n /** ENG-4422 §4: JSONB DeliveryTarget (or null). Legacy string form is gone\n * after the migration; in-memory shape is the structured object. */\n deliveryTo: unknown | null;\n enabled: boolean;\n triggeredAt: number | null; // epoch ms — manual trigger from webapp\n /** ENG-8154: the `triggeredAt` value this task has already been fired for.\n * A manual trigger is a ONE-SHOT COMMAND, but `scheduled_tasks.triggered_at`\n * is only ever set server-side and never cleared, so the manager re-reads the\n * same historical trigger on every sync, forever. Consumption used to be\n * inferred from `lastFireAt`, which is null on any cold entry into state —\n * so a task that had ever been triggered re-fired immediately, ignoring its\n * own nextFireAt. Tracking the consumed trigger explicitly makes the trigger\n * idempotent per occurrence and independent of fire history.\n * Optional: states persisted by older CLIs lack it; normalised on load. */\n consumedTriggeredAt?: number | null;\n nextFireAt: number | null; // epoch ms, null = completed one-shot\n lastFireAt: number | null;\n lastStatus: 'ok' | 'error' | null;\n firedCount: number;\n}\n\nexport interface SchedulerState {\n version: 1;\n tasks: Record<string, SchedulerTaskState>;\n updatedAt: string;\n}\n\nexport interface SchedulerTaskInput {\n id: string;\n template_id: string;\n name: string;\n schedule_kind: 'cron' | 'every' | 'at';\n schedule_expr: string | null;\n schedule_every: string | null;\n schedule_at: string | null;\n timezone: string;\n prompt: string;\n session_target: string;\n delivery_mode: string;\n /** ENG-6107: absent from older APIs — treated as 'always'. */\n delivery_policy?: string | null;\n delivery_channel: string | null;\n /** ENG-4422 §4: JSONB DeliveryTarget or null (post-migration). */\n delivery_to: unknown | null;\n enabled: boolean;\n triggered_at?: string | null;\n}\n\n// ---------------------------------------------------------------------------\n// Interval parsing (reused from Claude Code adapter)\n// ---------------------------------------------------------------------------\n\nfunction parseIntervalMs(scheduleEvery: string | null): number {\n if (!scheduleEvery) return 60 * 60_000; // 1hr default\n const match = scheduleEvery.match(/^(\\d+)\\s*(m|min|h|hr|d)$/i);\n if (!match) return 60 * 60_000;\n const value = parseInt(match[1]!, 10);\n const unit = match[2]!.toLowerCase();\n if (unit === 'h' || unit === 'hr') return value * 60 * 60_000;\n if (unit === 'd') return value * 24 * 60 * 60_000;\n return value * 60_000; // minutes\n}\n\n// ---------------------------------------------------------------------------\n// Next-fire computation\n// ---------------------------------------------------------------------------\n\nexport function computeNextFire(\n kind: 'cron' | 'every' | 'at',\n expr: string | null,\n every: string | null,\n at: string | null,\n timezone: string,\n afterMs?: number,\n): number | null {\n const now = afterMs ?? Date.now();\n\n if (kind === 'cron' && expr) {\n try {\n const cron = new Cron(expr, { timezone: timezone || undefined });\n const next = cron.nextRun(new Date(now));\n return next ? next.getTime() : null;\n } catch {\n return null;\n }\n }\n\n if (kind === 'every') {\n const intervalMs = parseIntervalMs(every);\n return now + intervalMs;\n }\n\n if (kind === 'at' && at) {\n const ts = new Date(at).getTime();\n if (isNaN(ts)) return null;\n // If the 'at' timestamp is in the past and afterMs is set (meaning we already\n // fired), return null to prevent re-firing on state rebuild.\n if (afterMs && ts <= afterMs) return null;\n return ts;\n }\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// State persistence\n// ---------------------------------------------------------------------------\n\n/**\n * ENG-8154: how recent a `triggered_at` must be to count as a LIVE manual\n * trigger when a task enters scheduler state cold.\n *\n * `scheduled_tasks.triggered_at` is never cleared server-side, so on a cold\n * entry we cannot tell \"the user just hit Run now\" from \"the user hit Run now\n * three days ago\" by presence alone — and treating every cold-seen trigger as\n * live is precisely the defect (a task re-added by a sync fired on the spot,\n * ignoring its own nextFireAt). Age is the only signal available host-side.\n *\n * Sized against the manager's task-sync cadence, ~3 min in the field (the\n * ENG-8154 report shows polls at 06:08 / 06:11 / 06:14 / 06:17), so this allows\n * three missed polls before a genuine trigger is written off. Well under the\n * respawn cadence that produced the stale-trigger storm, and far under the\n * multi-day age of the trigger in the incident.\n *\n * Known trade-off, deliberate: a \"Run now\" issued while the agent is down for\n * longer than this window will not fire on recovery. Firing a much older\n * trigger on an unrelated restart is the worse failure, and it is the one that\n * actually happened. The durable fix is to acknowledge and clear the trigger\n * server-side, which removes the need to guess from age at all.\n */\nconst TRIGGER_FRESHNESS_MS = 10 * 60_000;\n\n/**\n * ENG-8154: is a trigger recent enough to still be owed a run on cold entry?\n * Returns false for null so callers can seed the consumed watermark safely.\n */\nfunction isTriggerFresh(triggeredAtMs: number | null, nowMs = Date.now()): boolean {\n if (triggeredAtMs === null) return false;\n return nowMs - triggeredAtMs <= TRIGGER_FRESHNESS_MS;\n}\n\nfunction getStateDir(codeName: string): string {\n // ENG-4418: unified agent dir — scheduler state lives at the agent root\n // alongside other runtime state files (plugins.json, schedules.json,\n // registration.json). Legacy ~/.augmented/<codeName>/claudecode/scheduler-state.json\n // is migrated up by claudeCodeAdapter.getAgentDir on first poll.\n return join(homedir(), '.augmented', codeName);\n}\n\nfunction getStatePath(codeName: string): string {\n return join(getStateDir(codeName), 'scheduler-state.json');\n}\n\nexport function loadSchedulerState(codeName: string): SchedulerState {\n const path = getStatePath(codeName);\n if (existsSync(path)) {\n try {\n const parsed: SchedulerState = JSON.parse(readFileSync(path, 'utf-8'));\n // ENG-8154 upgrade normalisation. A state file written by an older CLI has\n // no `consumedTriggeredAt`. Seeding it from the CURRENT `triggeredAt`\n // treats any trigger already on the task as consumed, so upgrading does not\n // itself fire a historical trigger — which is the exact bug being fixed.\n // A genuinely new manual trigger arrives with a LATER timestamp and still\n // fires normally.\n for (const task of Object.values(parsed.tasks ?? {})) {\n if (task.consumedTriggeredAt === undefined) {\n // Same freshness rule as the cold-add path: a trigger still inside the\n // window was plausibly issued moments ago and is left owed, anything\n // older is written off so upgrading cannot fire history.\n task.consumedTriggeredAt = isTriggerFresh(task.triggeredAt) ? null : (task.triggeredAt ?? null);\n }\n }\n return parsed;\n } catch { /* corrupted — start fresh */ }\n }\n return { version: 1, tasks: {}, updatedAt: new Date().toISOString() };\n}\n\nexport function saveSchedulerState(codeName: string, state: SchedulerState): void {\n const dir = getStateDir(codeName);\n mkdirSync(dir, { recursive: true });\n state.updatedAt = new Date().toISOString();\n const path = getStatePath(codeName);\n const tmpPath = path + '.tmp';\n writeFileSync(tmpPath, JSON.stringify(state, null, 2));\n renameSync(tmpPath, path);\n}\n\n// ---------------------------------------------------------------------------\n// Sync API tasks → scheduler state\n// ---------------------------------------------------------------------------\n\nexport function syncTasksToScheduler(\n codeName: string,\n agentId: string,\n tasks: SchedulerTaskInput[],\n): SchedulerState {\n const state = loadSchedulerState(codeName);\n const desiredIds = new Set(tasks.map((t) => t.id));\n\n // Remove tasks no longer in API\n for (const id of Object.keys(state.tasks)) {\n if (!desiredIds.has(id)) {\n delete state.tasks[id];\n }\n }\n\n // Add or update tasks\n for (const t of tasks) {\n const existing = state.tasks[t.id];\n if (existing) {\n // Only recompute nextFireAt if the schedule definition actually changed.\n // Without this guard, every sync cycle resets nextFireAt from \"now\",\n // preventing past-due tasks from ever being detected as ready.\n const scheduleChanged =\n existing.scheduleKind !== t.schedule_kind ||\n existing.scheduleExpr !== t.schedule_expr ||\n existing.scheduleEvery !== t.schedule_every ||\n existing.scheduleAt !== t.schedule_at ||\n existing.timezone !== t.timezone;\n\n // Update mutable fields, preserve fire history\n existing.name = t.name;\n existing.templateId = t.template_id;\n existing.scheduleKind = t.schedule_kind;\n existing.scheduleExpr = t.schedule_expr;\n existing.scheduleEvery = t.schedule_every;\n existing.scheduleAt = t.schedule_at;\n existing.timezone = t.timezone;\n existing.prompt = t.prompt;\n existing.sessionTarget = t.session_target;\n existing.deliveryMode = t.delivery_mode;\n existing.deliveryPolicy = t.delivery_policy ?? 'always';\n existing.deliveryChannel = t.delivery_channel;\n existing.deliveryTo = t.delivery_to;\n existing.enabled = t.enabled;\n if (t.triggered_at) existing.triggeredAt = new Date(t.triggered_at).getTime();\n if (scheduleChanged) {\n existing.nextFireAt = computeNextFire(\n t.schedule_kind, t.schedule_expr, t.schedule_every, t.schedule_at,\n t.timezone, existing.lastFireAt ?? undefined,\n );\n }\n } else {\n // New task\n state.tasks[t.id] = {\n taskId: t.id,\n templateId: t.template_id,\n name: t.name,\n agentCodeName: codeName,\n agentId,\n scheduleKind: t.schedule_kind,\n scheduleExpr: t.schedule_expr,\n scheduleEvery: t.schedule_every,\n scheduleAt: t.schedule_at,\n timezone: t.timezone,\n prompt: t.prompt,\n sessionTarget: t.session_target,\n deliveryMode: t.delivery_mode,\n deliveryPolicy: t.delivery_policy ?? 'always',\n deliveryChannel: t.delivery_channel,\n deliveryTo: t.delivery_to,\n enabled: t.enabled,\n triggeredAt: t.triggered_at ? new Date(t.triggered_at).getTime() : null,\n // ENG-8154: a task entering state COLD must not fire a trigger that was\n // already sitting on the row, so a STALE trigger is seeded as consumed.\n // This is the load-bearing line: syncTasksToScheduler deletes any task\n // absent from a sync's task list, so a transient partial list re-adds it\n // here — and before this, the fresh `lastFireAt: null` made `!lastFireAt`\n // true and it fired on the spot, whatever nextFireAt said. That is the\n // ~11-fires-in-75-min engine.\n //\n // A FRESH trigger is left unconsumed so it still fires. That case is\n // real: a task created and immediately \"Run now\"-ed enters state through\n // this branch carrying a live trigger, and seeding it unconditionally\n // would silently swallow the user's explicit request.\n consumedTriggeredAt: isTriggerFresh(t.triggered_at ? new Date(t.triggered_at).getTime() : null)\n ? null\n : (t.triggered_at ? new Date(t.triggered_at).getTime() : null),\n nextFireAt: computeNextFire(\n t.schedule_kind, t.schedule_expr, t.schedule_every, t.schedule_at, t.timezone,\n ),\n lastFireAt: null,\n lastStatus: null,\n firedCount: 0,\n };\n }\n }\n\n saveSchedulerState(codeName, state);\n return state;\n}\n\n// ---------------------------------------------------------------------------\n// Ready-task detection\n// ---------------------------------------------------------------------------\n\n// ENG-4675: pass `inFlightTaskIds` so the manager's poll loop doesn't\n// re-detect tasks that already have a `claude -p` subprocess running.\n// Without this, every supervisor tick (~17s) saw the manual trigger as\n// still ready (because lastFireAt is only set on completion, not on\n// fire start), spamming \"N ready task(s)\" + \"Firing task\" log lines that\n// looked like duplicate fires. The in-flight guard at the spawn site\n// prevented actual duplicate subprocesses, but the log was misleading.\nexport function getReadyTasks(\n state: SchedulerState,\n inFlightTaskIds?: ReadonlySet<string>,\n): SchedulerTaskState[] {\n const now = Date.now();\n const ready = Object.values(state.tasks).filter((t) => {\n if (!t.enabled) return false;\n if (inFlightTaskIds?.has(t.taskId)) return false;\n // Manual trigger: triggered_at is set and this exact trigger hasn't been\n // consumed yet. ENG-8154: consumption is tracked explicitly rather than\n // inferred from `lastFireAt`. The old test (`!t.lastFireAt || ...`) treated\n // \"we have no fire history\" as \"this trigger is pending\", so any cold entry\n // into scheduler state re-fired a long-dead trigger and — because this\n // branch returns before the nextFireAt check below — did so regardless of\n // when the task was actually next due.\n if (t.triggeredAt && t.triggeredAt > (t.consumedTriggeredAt ?? 0)) return true;\n // Normal schedule\n return t.nextFireAt !== null && t.nextFireAt <= now;\n });\n // Deduplicate by templateId — only fire one task per template per cycle\n const seen = new Set<string>();\n return ready.filter((t) => {\n if (seen.has(t.templateId)) return false;\n seen.add(t.templateId);\n return true;\n });\n}\n\n// ---------------------------------------------------------------------------\n// Post-execution state update\n// ---------------------------------------------------------------------------\n\nexport function markTaskFired(\n codeName: string,\n taskId: string,\n status: 'ok' | 'error',\n): SchedulerState {\n const state = loadSchedulerState(codeName);\n const task = state.tasks[taskId];\n if (!task) return state;\n\n task.lastFireAt = Date.now();\n task.lastStatus = status;\n task.firedCount++;\n // ENG-8154: whatever caused this fire, the trigger currently on the task is\n // now spent. Recording it here (rather than relying on lastFireAt ordering)\n // keeps the trigger one-shot even if the fire-history watermark is later lost.\n if (task.triggeredAt) task.consumedTriggeredAt = task.triggeredAt;\n\n // Compute next fire\n if (task.scheduleKind === 'at') {\n // One-shot — mark as completed\n task.nextFireAt = null;\n } else {\n task.nextFireAt = computeNextFire(\n task.scheduleKind, task.scheduleExpr, task.scheduleEvery, task.scheduleAt,\n task.timezone, task.lastFireAt,\n );\n }\n\n // Persisting is best-effort: the SchedulerState the caller stores in memory\n // (claudeSchedulerStates) is the running source of truth — getReadyTasks\n // reads it, not the disk file. A disk-write failure (ENOSPC/EACCES) must NOT\n // throw, or the caller's in-memory state would never advance and the task\n // would be treated as ready again next poll (ENG-5599: a duplicate\n // scheduled-task card materialised every tick). The mutated `state` is\n // returned regardless; cross-restart recovery is a separate concern.\n try {\n saveSchedulerState(codeName, state);\n } catch (err) {\n console.error(\n `[scheduler-engine] markTaskFired: failed to persist state for '${codeName}': ${(err as Error).message}`,\n );\n }\n return state;\n}\n\n// ---------------------------------------------------------------------------\n// Find a task by template ID (for work triggers)\n// ---------------------------------------------------------------------------\n\nexport function findTaskByTemplate(state: SchedulerState, templateId: string): SchedulerTaskState | undefined {\n return Object.values(state.tasks).find(\n (t) => t.templateId === templateId && t.enabled,\n );\n}\n\nexport function getProjectDir(codeName: string): string {\n return join(homedir(), '.augmented', codeName, 'project');\n}\n"],"mappings":";AAkBA,SAAS,YAAY,WAAW,cAAc,YAAY,qBAAqB;AAC/E,SAAS,YAAY;AACrB,SAAS,eAAe;AACxB,SAAS,YAAY;AA4ErB,SAAS,gBAAgB,eAAsC;AAC7D,MAAI,CAAC,cAAe,QAAO,KAAK;AAChC,QAAM,QAAQ,cAAc,MAAM,2BAA2B;AAC7D,MAAI,CAAC,MAAO,QAAO,KAAK;AACxB,QAAM,QAAQ,SAAS,MAAM,CAAC,GAAI,EAAE;AACpC,QAAM,OAAO,MAAM,CAAC,EAAG,YAAY;AACnC,MAAI,SAAS,OAAO,SAAS,KAAM,QAAO,QAAQ,KAAK;AACvD,MAAI,SAAS,IAAK,QAAO,QAAQ,KAAK,KAAK;AAC3C,SAAO,QAAQ;AACjB;AAMO,SAAS,gBACd,MACA,MACA,OACA,IACA,UACA,SACe;AACf,QAAM,MAAM,WAAW,KAAK,IAAI;AAEhC,MAAI,SAAS,UAAU,MAAM;AAC3B,QAAI;AACF,YAAM,OAAO,IAAI,KAAK,MAAM,EAAE,UAAU,YAAY,OAAU,CAAC;AAC/D,YAAM,OAAO,KAAK,QAAQ,IAAI,KAAK,GAAG,CAAC;AACvC,aAAO,OAAO,KAAK,QAAQ,IAAI;AAAA,IACjC,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAEA,MAAI,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nostic scheduled-task state machine.\n *\n * The pure scheduling engine: schedule definitions -> next-fire computation ->\n * ready-task detection -> post-fire state advance, with on-disk persistence so\n * nextFireAt/lastFireAt survive manager restarts. It owns the WHEN, not the HOW:\n * each framework supplies its own firing leaf and calls back into\n * `markTaskFired`.\n * - Claude Code fires via the in-session kanban todo-card route\n * (manager/scheduler/execution.ts + kanban-route.ts).\n * - opencode fires via an HTTP inject into `opencode serve`\n * (manager/opencode-scheduler.ts).\n * Both share this engine verbatim, so cadence, one-shot completion,\n * manual-trigger, and cross-restart recovery are identical across frameworks.\n * (Named claude-scheduler.ts historically, when the claude `-p` oneshot was the\n * only consumer.)\n */\n\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\nimport { Cron } from 'croner';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface SchedulerTaskState {\n taskId: string;\n templateId: string;\n name: string;\n agentCodeName: string;\n agentId: string;\n scheduleKind: 'cron' | 'every' | 'at';\n scheduleExpr: string | null;\n scheduleEvery: string | null;\n scheduleAt: string | null;\n timezone: string;\n prompt: string;\n sessionTarget: string;\n deliveryMode: string;\n /** ENG-6107: always | conditional | never — whether results deliver.\n * Optional: states persisted by older CLIs lack it; absent = 'always'. */\n deliveryPolicy?: string | null;\n deliveryChannel: string | null;\n /** ENG-4422 §4: JSONB DeliveryTarget (or null). Legacy string form is gone\n * after the migration; in-memory shape is the structured object. */\n deliveryTo: unknown | null;\n enabled: boolean;\n triggeredAt: number | null; // epoch ms — manual trigger from webapp\n /** ENG-8154: the `triggeredAt` value this task has already been fired for.\n * A manual trigger is a ONE-SHOT COMMAND, but `scheduled_tasks.triggered_at`\n * is only ever set server-side and never cleared, so the manager re-reads the\n * same historical trigger on every sync, forever. Consumption used to be\n * inferred from `lastFireAt`, which is null on any cold entry into state —\n * so a task that had ever been triggered re-fired immediately, ignoring its\n * own nextFireAt. Tracking the consumed trigger explicitly makes the trigger\n * idempotent per occurrence and independent of fire history.\n * Optional: states persisted by older CLIs lack it; normalised on load. */\n consumedTriggeredAt?: number | null;\n nextFireAt: number | null; // epoch ms, null = completed one-shot\n lastFireAt: number | null;\n lastStatus: 'ok' | 'error' | null;\n firedCount: number;\n}\n\nexport interface SchedulerState {\n version: 1;\n tasks: Record<string, SchedulerTaskState>;\n updatedAt: string;\n}\n\nexport interface SchedulerTaskInput {\n id: string;\n template_id: string;\n name: string;\n schedule_kind: 'cron' | 'every' | 'at';\n schedule_expr: string | null;\n schedule_every: string | null;\n schedule_at: string | null;\n timezone: string;\n prompt: string;\n session_target: string;\n delivery_mode: string;\n /** ENG-6107: absent from older APIs — treated as 'always'. */\n delivery_policy?: string | null;\n delivery_channel: string | null;\n /** ENG-4422 §4: JSONB DeliveryTarget or null (post-migration). */\n delivery_to: unknown | null;\n enabled: boolean;\n triggered_at?: string | null;\n}\n\n// ---------------------------------------------------------------------------\n// Interval parsing (reused from Claude Code adapter)\n// ---------------------------------------------------------------------------\n\nfunction parseIntervalMs(scheduleEvery: string | null): number {\n if (!scheduleEvery) return 60 * 60_000; // 1hr default\n const match = scheduleEvery.match(/^(\\d+)\\s*(m|min|h|hr|d)$/i);\n if (!match) return 60 * 60_000;\n const value = parseInt(match[1]!, 10);\n const unit = match[2]!.toLowerCase();\n if (unit === 'h' || unit === 'hr') return value * 60 * 60_000;\n if (unit === 'd') return value * 24 * 60 * 60_000;\n return value * 60_000; // minutes\n}\n\n// ---------------------------------------------------------------------------\n// Next-fire computation\n// ---------------------------------------------------------------------------\n\nexport function computeNextFire(\n kind: 'cron' | 'every' | 'at',\n expr: string | null,\n every: string | null,\n at: string | null,\n timezone: string,\n afterMs?: number,\n): number | null {\n const now = afterMs ?? Date.now();\n\n if (kind === 'cron' && expr) {\n try {\n const cron = new Cron(expr, { timezone: timezone || undefined });\n const next = cron.nextRun(new Date(now));\n return next ? next.getTime() : null;\n } catch {\n return null;\n }\n }\n\n if (kind === 'every') {\n const intervalMs = parseIntervalMs(every);\n return now + intervalMs;\n }\n\n if (kind === 'at' && at) {\n const ts = new Date(at).getTime();\n if (isNaN(ts)) return null;\n // If the 'at' timestamp is in the past and afterMs is set (meaning we already\n // fired), return null to prevent re-firing on state rebuild.\n if (afterMs && ts <= afterMs) return null;\n return ts;\n }\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// State persistence\n// ---------------------------------------------------------------------------\n\n/**\n * ENG-8154: how recent a `triggered_at` must be to count as a LIVE manual\n * trigger when a task enters scheduler state cold.\n *\n * `scheduled_tasks.triggered_at` is never cleared server-side, so on a cold\n * entry we cannot tell \"the user just hit Run now\" from \"the user hit Run now\n * three days ago\" by presence alone — and treating every cold-seen trigger as\n * live is precisely the defect (a task re-added by a sync fired on the spot,\n * ignoring its own nextFireAt). Age is the only signal available host-side.\n *\n * Sized against the manager's task-sync cadence, ~3 min in the field (the\n * ENG-8154 report shows polls at 06:08 / 06:11 / 06:14 / 06:17), so this allows\n * three missed polls before a genuine trigger is written off. Well under the\n * respawn cadence that produced the stale-trigger storm, and far under the\n * multi-day age of the trigger in the incident.\n *\n * Known trade-off, deliberate: a \"Run now\" issued while the agent is down for\n * longer than this window will not fire on recovery. Firing a much older\n * trigger on an unrelated restart is the worse failure, and it is the one that\n * actually happened. The durable fix is to acknowledge and clear the trigger\n * server-side, which removes the need to guess from age at all.\n */\nconst TRIGGER_FRESHNESS_MS = 10 * 60_000;\n\n/**\n * ENG-8154: is a trigger recent enough to still be owed a run on cold entry?\n * Returns false for null so callers can seed the consumed watermark safely.\n */\nfunction isTriggerFresh(triggeredAtMs: number | null, nowMs = Date.now()): boolean {\n if (triggeredAtMs === null) return false;\n return nowMs - triggeredAtMs <= TRIGGER_FRESHNESS_MS;\n}\n\nfunction getStateDir(codeName: string): string {\n // ENG-4418: unified agent dir — scheduler state lives at the agent root\n // alongside other runtime state files (plugins.json, schedules.json,\n // registration.json). Legacy ~/.augmented/<codeName>/claudecode/scheduler-state.json\n // is migrated up by claudeCodeAdapter.getAgentDir on first poll.\n return join(homedir(), '.augmented', codeName);\n}\n\nfunction getStatePath(codeName: string): string {\n return join(getStateDir(codeName), 'scheduler-state.json');\n}\n\nexport function loadSchedulerState(codeName: string): SchedulerState {\n const path = getStatePath(codeName);\n if (existsSync(path)) {\n try {\n const parsed: SchedulerState = JSON.parse(readFileSync(path, 'utf-8'));\n // ENG-8154 upgrade normalisation. A state file written by an older CLI has\n // no `consumedTriggeredAt`. Seeding it from the CURRENT `triggeredAt`\n // treats any trigger already on the task as consumed, so upgrading does not\n // itself fire a historical trigger — which is the exact bug being fixed.\n // A genuinely new manual trigger arrives with a LATER timestamp and still\n // fires normally.\n for (const task of Object.values(parsed.tasks ?? {})) {\n if (task.consumedTriggeredAt === undefined) {\n // Same freshness rule as the cold-add path: a trigger still inside the\n // window was plausibly issued moments ago and is left owed, anything\n // older is written off so upgrading cannot fire history.\n task.consumedTriggeredAt = isTriggerFresh(task.triggeredAt) ? null : (task.triggeredAt ?? null);\n }\n }\n return parsed;\n } catch { /* corrupted — start fresh */ }\n }\n return { version: 1, tasks: {}, updatedAt: new Date().toISOString() };\n}\n\nexport function saveSchedulerState(codeName: string, state: SchedulerState): void {\n const dir = getStateDir(codeName);\n mkdirSync(dir, { recursive: true });\n state.updatedAt = new Date().toISOString();\n const path = getStatePath(codeName);\n const tmpPath = path + '.tmp';\n writeFileSync(tmpPath, JSON.stringify(state, null, 2));\n renameSync(tmpPath, path);\n}\n\n// ---------------------------------------------------------------------------\n// Sync API tasks → scheduler state\n// ---------------------------------------------------------------------------\n\nexport function syncTasksToScheduler(\n codeName: string,\n agentId: string,\n tasks: SchedulerTaskInput[],\n): SchedulerState {\n const state = loadSchedulerState(codeName);\n const desiredIds = new Set(tasks.map((t) => t.id));\n\n // Remove tasks no longer in API\n for (const id of Object.keys(state.tasks)) {\n if (!desiredIds.has(id)) {\n delete state.tasks[id];\n }\n }\n\n // Add or update tasks\n for (const t of tasks) {\n const existing = state.tasks[t.id];\n if (existing) {\n // Only recompute nextFireAt if the schedule definition actually changed.\n // Without this guard, every sync cycle resets nextFireAt from \"now\",\n // preventing past-due tasks from ever being detected as ready.\n const scheduleChanged =\n existing.scheduleKind !== t.schedule_kind ||\n existing.scheduleExpr !== t.schedule_expr ||\n existing.scheduleEvery !== t.schedule_every ||\n existing.scheduleAt !== t.schedule_at ||\n existing.timezone !== t.timezone;\n\n // Update mutable fields, preserve fire history\n existing.name = t.name;\n existing.templateId = t.template_id;\n existing.scheduleKind = t.schedule_kind;\n existing.scheduleExpr = t.schedule_expr;\n existing.scheduleEvery = t.schedule_every;\n existing.scheduleAt = t.schedule_at;\n existing.timezone = t.timezone;\n existing.prompt = t.prompt;\n existing.sessionTarget = t.session_target;\n existing.deliveryMode = t.delivery_mode;\n existing.deliveryPolicy = t.delivery_policy ?? 'always';\n existing.deliveryChannel = t.delivery_channel;\n existing.deliveryTo = t.delivery_to;\n existing.enabled = t.enabled;\n if (t.triggered_at) existing.triggeredAt = new Date(t.triggered_at).getTime();\n if (scheduleChanged) {\n existing.nextFireAt = computeNextFire(\n t.schedule_kind, t.schedule_expr, t.schedule_every, t.schedule_at,\n t.timezone, existing.lastFireAt ?? undefined,\n );\n }\n } else {\n // New task\n state.tasks[t.id] = {\n taskId: t.id,\n templateId: t.template_id,\n name: t.name,\n agentCodeName: codeName,\n agentId,\n scheduleKind: t.schedule_kind,\n scheduleExpr: t.schedule_expr,\n scheduleEvery: t.schedule_every,\n scheduleAt: t.schedule_at,\n timezone: t.timezone,\n prompt: t.prompt,\n sessionTarget: t.session_target,\n deliveryMode: t.delivery_mode,\n deliveryPolicy: t.delivery_policy ?? 'always',\n deliveryChannel: t.delivery_channel,\n deliveryTo: t.delivery_to,\n enabled: t.enabled,\n triggeredAt: t.triggered_at ? new Date(t.triggered_at).getTime() : null,\n // ENG-8154: a task entering state COLD must not fire a trigger that was\n // already sitting on the row, so a STALE trigger is seeded as consumed.\n // This is the load-bearing line: syncTasksToScheduler deletes any task\n // absent from a sync's task list, so a transient partial list re-adds it\n // here — and before this, the fresh `lastFireAt: null` made `!lastFireAt`\n // true and it fired on the spot, whatever nextFireAt said. That is the\n // ~11-fires-in-75-min engine.\n //\n // A FRESH trigger is left unconsumed so it still fires. That case is\n // real: a task created and immediately \"Run now\"-ed enters state through\n // this branch carrying a live trigger, and seeding it unconditionally\n // would silently swallow the user's explicit request.\n consumedTriggeredAt: isTriggerFresh(t.triggered_at ? new Date(t.triggered_at).getTime() : null)\n ? null\n : (t.triggered_at ? new Date(t.triggered_at).getTime() : null),\n nextFireAt: computeNextFire(\n t.schedule_kind, t.schedule_expr, t.schedule_every, t.schedule_at, t.timezone,\n ),\n lastFireAt: null,\n lastStatus: null,\n firedCount: 0,\n };\n }\n }\n\n saveSchedulerState(codeName, state);\n return state;\n}\n\n// ---------------------------------------------------------------------------\n// Ready-task detection\n// ---------------------------------------------------------------------------\n\n// ENG-4675: pass `inFlightTaskIds` so the manager's poll loop doesn't\n// re-detect tasks that already have a `claude -p` subprocess running.\n// Without this, every supervisor tick (~17s) saw the manual trigger as\n// still ready (because lastFireAt is only set on completion, not on\n// fire start), spamming \"N ready task(s)\" + \"Firing task\" log lines that\n// looked like duplicate fires. The in-flight guard at the spawn site\n// prevented actual duplicate subprocesses, but the log was misleading.\nexport function getReadyTasks(\n state: SchedulerState,\n inFlightTaskIds?: ReadonlySet<string>,\n): SchedulerTaskState[] {\n const now = Date.now();\n const ready = Object.values(state.tasks).filter((t) => {\n if (!t.enabled) return false;\n if (inFlightTaskIds?.has(t.taskId)) return false;\n // Manual trigger: triggered_at is set and this exact trigger hasn't been\n // consumed yet. ENG-8154: consumption is tracked explicitly rather than\n // inferred from `lastFireAt`. The old test (`!t.lastFireAt || ...`) treated\n // \"we have no fire history\" as \"this trigger is pending\", so any cold entry\n // into scheduler state re-fired a long-dead trigger and — because this\n // branch returns before the nextFireAt check below — did so regardless of\n // when the task was actually next due.\n if (t.triggeredAt && t.triggeredAt > (t.consumedTriggeredAt ?? 0)) return true;\n // Normal schedule\n return t.nextFireAt !== null && t.nextFireAt <= now;\n });\n // Deduplicate by templateId — only fire one task per template per cycle\n const seen = new Set<string>();\n return ready.filter((t) => {\n if (seen.has(t.templateId)) return false;\n seen.add(t.templateId);\n return true;\n });\n}\n\n// ---------------------------------------------------------------------------\n// CS-2326: say when a firing is a catch-up for runs that were missed\n// ---------------------------------------------------------------------------\n\n/** A firing this late is a catch-up, not tick latency (a tick is ~17s). */\nexport const CATCH_UP_MIN_LATENESS_MS = 10 * 60_000;\n/** Stop counting occurrences past this; the note then says \"more than\". */\nconst CATCH_UP_COUNT_CAP = 1000;\n\nexport interface CatchUpFacts {\n /** When the oldest missed occurrence fell due (the task's stale nextFireAt). */\n dueAt: number;\n /** Occurrences that fell due in [dueAt, now], this one included. */\n occurrences: number;\n /** True when counting stopped at the cap. */\n capped: boolean;\n}\n\n/**\n * CS-2326: is this firing standing in for runs that fell due while the agent\n * was not running (a usage cap, a dead host, a stopped manager)?\n *\n * Missed runs are deliberately coalesced (ENG-8197: one firing per task on\n * resume, not a burst), but until now that left NO trace: the occurrences\n * simply vanished. Pure. Returns null for an on-time firing, a manual trigger,\n * or a one-shot.\n */\nexport function describeCatchUp(task: SchedulerTaskState, nowMs: number): CatchUpFacts | null {\n if (task.triggeredAt && task.triggeredAt > (task.consumedTriggeredAt ?? 0)) return null;\n if (task.scheduleKind === 'at' || task.nextFireAt === null) return null;\n const dueAt = task.nextFireAt;\n if (nowMs - dueAt < CATCH_UP_MIN_LATENESS_MS) return null;\n let occurrences = 1;\n let capped = false;\n if (task.scheduleKind === 'every') {\n const interval = parseIntervalMs(task.scheduleEvery);\n occurrences = 1 + Math.floor((nowMs - dueAt) / interval);\n if (occurrences > CATCH_UP_COUNT_CAP) {\n occurrences = CATCH_UP_COUNT_CAP;\n capped = true;\n }\n } else if (task.scheduleExpr) {\n try {\n const cron = new Cron(task.scheduleExpr, { timezone: task.timezone || undefined });\n let cursor = new Date(dueAt);\n for (;;) {\n const next = cron.nextRun(cursor);\n if (!next || next.getTime() > nowMs) break;\n if (occurrences >= CATCH_UP_COUNT_CAP) {\n capped = true;\n break;\n }\n occurrences++;\n cursor = next;\n }\n } catch {\n // An expression croner cannot parse still had a due time that passed:\n // report the lateness with the one occurrence we know of.\n }\n }\n return { dueAt, occurrences, capped };\n}\n\n/** The line prepended to a catch-up firing's prompt, so it lands on the card. */\nexport function catchUpNote(facts: CatchUpFacts, nowMs: number): string {\n const due = new Date(facts.dueAt).toISOString().slice(0, 16).replace('T', ' ');\n const now = new Date(nowMs).toISOString().slice(0, 16).replace('T', ' ');\n const missed = facts.occurrences - 1;\n const count = facts.capped ? `more than ${missed}` : String(missed);\n return (\n `[Catch-up run: this task was due at ${due} UTC but the agent was not running until ${now} UTC. ` +\n (missed > 0\n ? `${count} further scheduled run${missed === 1 ? '' : 's'} fell due in that window and were skipped; this one run covers them. `\n : '') +\n 'If the task is time-sensitive, cover the whole missed window, not only the latest slot.]'\n );\n}\n\n// ---------------------------------------------------------------------------\n// Post-execution state update\n// ---------------------------------------------------------------------------\n\nexport function markTaskFired(\n codeName: string,\n taskId: string,\n status: 'ok' | 'error',\n): SchedulerState {\n const state = loadSchedulerState(codeName);\n const task = state.tasks[taskId];\n if (!task) return state;\n\n task.lastFireAt = Date.now();\n task.lastStatus = status;\n task.firedCount++;\n // ENG-8154: whatever caused this fire, the trigger currently on the task is\n // now spent. Recording it here (rather than relying on lastFireAt ordering)\n // keeps the trigger one-shot even if the fire-history watermark is later lost.\n if (task.triggeredAt) task.consumedTriggeredAt = task.triggeredAt;\n\n // Compute next fire\n if (task.scheduleKind === 'at') {\n // One-shot — mark as completed\n task.nextFireAt = null;\n } else {\n task.nextFireAt = computeNextFire(\n task.scheduleKind, task.scheduleExpr, task.scheduleEvery, task.scheduleAt,\n task.timezone, task.lastFireAt,\n );\n }\n\n // Persisting is best-effort: the SchedulerState the caller stores in memory\n // (claudeSchedulerStates) is the running source of truth — getReadyTasks\n // reads it, not the disk file. A disk-write failure (ENOSPC/EACCES) must NOT\n // throw, or the caller's in-memory state would never advance and the task\n // would be treated as ready again next poll (ENG-5599: a duplicate\n // scheduled-task card materialised every tick). The mutated `state` is\n // returned regardless; cross-restart recovery is a separate concern.\n try {\n saveSchedulerState(codeName, state);\n } catch (err) {\n console.error(\n `[scheduler-engine] markTaskFired: failed to persist state for '${codeName}': ${(err as Error).message}`,\n );\n }\n return state;\n}\n\n// ---------------------------------------------------------------------------\n// Find a task by template ID (for work triggers)\n// ---------------------------------------------------------------------------\n\nexport function findTaskByTemplate(state: SchedulerState, templateId: string): SchedulerTaskState | undefined {\n return Object.values(state.tasks).find(\n (t) => t.templateId === templateId && t.enabled,\n );\n}\n\nexport function getProjectDir(codeName: string): string {\n return join(homedir(), '.augmented', codeName, 'project');\n}\n"],"mappings":";AAkBA,SAAS,YAAY,WAAW,cAAc,YAAY,qBAAqB;AAC/E,SAAS,YAAY;AACrB,SAAS,eAAe;AACxB,SAAS,YAAY;AA4ErB,SAAS,gBAAgB,eAAsC;AAC7D,MAAI,CAAC,cAAe,QAAO,KAAK;AAChC,QAAM,QAAQ,cAAc,MAAM,2BAA2B;AAC7D,MAAI,CAAC,MAAO,QAAO,KAAK;AACxB,QAAM,QAAQ,SAAS,MAAM,CAAC,GAAI,EAAE;AACpC,QAAM,OAAO,MAAM,CAAC,EAAG,YAAY;AACnC,MAAI,SAAS,OAAO,SAAS,KAAM,QAAO,QAAQ,KAAK;AACvD,MAAI,SAAS,IAAK,QAAO,QAAQ,KAAK,KAAK;AAC3C,SAAO,QAAQ;AACjB;AAMO,SAAS,gBACd,MACA,MACA,OACA,IACA,UACA,SACe;AACf,QAAM,MAAM,WAAW,KAAK,IAAI;AAEhC,MAAI,SAAS,UAAU,MAAM;AAC3B,QAAI;AACF,YAAM,OAAO,IAAI,KAAK,MAAM,EAAE,UAAU,YAAY,OAAU,CAAC;AAC/D,YAAM,OAAO,KAAK,QAAQ,IAAI,KAAK,GAAG,CAAC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AAE;AAAA,IAChC,CAAC,MAAM,EAAE,eAAe,cAAc,EAAE;AAAA,EAC1C;AACF;AAEO,SAAS,cAAc,UAA0B;AACtD,SAAO,KAAK,QAAQ,GAAG,cAAc,UAAU,SAAS;AAC1D;","names":[]}
|
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
} from "./chunk-XWVM4KPK.js";
|
|
5
5
|
import {
|
|
6
6
|
FORCED_UPDATE_HARD_DEADLINE_MS
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-I57M57XZ.js";
|
|
8
8
|
import {
|
|
9
9
|
effectiveClaudeJsonPath
|
|
10
10
|
} from "./chunk-AIUIMEUS.js";
|
|
@@ -722,4 +722,4 @@ export {
|
|
|
722
722
|
probeClaudeInstalls,
|
|
723
723
|
maybeUpdateClaudeCode
|
|
724
724
|
};
|
|
725
|
-
//# sourceMappingURL=chunk-
|
|
725
|
+
//# sourceMappingURL=chunk-GAQFCMBK.js.map
|
|
@@ -6569,6 +6569,12 @@ var FLAG_REGISTRY = [
|
|
|
6569
6569
|
flagType: "boolean",
|
|
6570
6570
|
defaultValue: true
|
|
6571
6571
|
},
|
|
6572
|
+
{
|
|
6573
|
+
key: "pending-inbound-tiered-page",
|
|
6574
|
+
description: "Unanswered-inbound tiered PAGE (ENG-9755): when ON, the responsiveness-probe route opens an `agent_pending_inbound` alert for an agent whose oldest reply-expecting inbound has gone unanswered 15 minutes (warning) or 2 hours (critical), re-raised on every probe and closed when the marker clears. Tiers decided by Sherlock 2026-11-08. Before this the only producer was the CloudWatch bridge at `info`, which alert-pager drops, so a 20-hour silent drop paged nobody. Defaults ON for the same reason as frozen-customer-waiting-page: the input (pending_inbound_oldest_age_seconds) has been measured since ENG-6017, and shipping it dark would leave the bug in place. Flip OFF from the admin Feature Flags page to disarm stage-wide: new pages stop at once, and pages ALREADY open are closed (as superseded) by the agent-paused reconciler sweep on its next tick, so disarming never strands an open page. No envVar (ENG-8303 / check-new-env-gates.sh).",
|
|
6575
|
+
flagType: "boolean",
|
|
6576
|
+
defaultValue: true
|
|
6577
|
+
},
|
|
6572
6578
|
{
|
|
6573
6579
|
key: "promise-outstanding-alarm",
|
|
6574
6580
|
description: 'Outstanding-interim-promise alarm (ENG-8265): when ON, the responsiveness-probe route creates a per-agent CloudWatch alarm on `PromiseOutstandingOldestAgeSeconds` \u2014 an inbound the agent acknowledged with an interim reply ("on it") and never answered substantively. Closes the blind spot where an ack satisfied channel-silent-loss, refreshed pending-inbound, and left agent_stall with no in_progress card to see, so a broken promise looked like a served request. Defaults ON (armed on deploy) because the alert it opens is `info` severity \u2014 dashboard-only, never paged \u2014 so a day-one false positive costs a visible row, not a woken human. Flip OFF from the admin Feature Flags page to disarm stage-wide; the window itself is tuned with the AUGMENTED_PROMISE_OUTSTANDING_THRESHOLD_SECONDS API tunable (default 1800).',
|
|
@@ -7006,6 +7012,25 @@ var FLAG_REGISTRY = [
|
|
|
7006
7012
|
flagType: "boolean",
|
|
7007
7013
|
defaultValue: false
|
|
7008
7014
|
},
|
|
7015
|
+
{
|
|
7016
|
+
key: "kanban-waiting-person-notify",
|
|
7017
|
+
description: `Notify a human teammate, via their preferred channel (Slack DM, else email fallback), when an agent PARKS a kanban card on them - "I still own this and cannot finish until you act" (ENG-8291 / ENG-11974). This is a DIFFERENT ask from human-task-assignment-notify, which covers "this is yours now", where ownership MOVES to the person. Until ENG-11974 one flag gated both, because the park path composes the assignment path's delivery; an org that silenced assignment pings therefore also lost every blocked-on-you message, which is the failure my-waiting.ts measured at a PR sitting 25.5h on a single merge tap. Off = the card is parked silently (it still appears in the recipient's "Awaiting you" queue on My Tasks). Note kanban-waiting-status is a separate gate and governs whether a park may be EMITTED at all; this one governs whether the human is TOLD.`,
|
|
7018
|
+
flagType: "boolean",
|
|
7019
|
+
// Declared safe value is `false`, matching its assignment sibling: fail-closed
|
|
7020
|
+
// is the right direction for a rail that messages a human.
|
|
7021
|
+
//
|
|
7022
|
+
// This default is NOT the deploy-time behaviour, and reading it as such is the
|
|
7023
|
+
// trap. The accompanying migration MIRRORS human-task-assignment-notify onto
|
|
7024
|
+
// this key - whatever that flag's central value is, plus every one of its
|
|
7025
|
+
// overrides at every grain - so no org's effective behaviour changes when
|
|
7026
|
+
// ENG-11974 ships. It deliberately does NOT seed a literal `true`: on a stage
|
|
7027
|
+
// where the old flag has no row, the old gate resolves to `false` and nobody
|
|
7028
|
+
// is being messaged, so a literal `true` would ARM a rail that DMs and emails
|
|
7029
|
+
// real humans on a fleet that never had one. A registry default
|
|
7030
|
+
// renders identically to a measurement - to learn whether this is on for an
|
|
7031
|
+
// org, read feature_flags.value and feature_flag_overrides, never this line.
|
|
7032
|
+
defaultValue: false
|
|
7033
|
+
},
|
|
7009
7034
|
{
|
|
7010
7035
|
key: "resume-reconciler",
|
|
7011
7036
|
description: "Health-gated safe auto-resume for circuit-breaker pauses (ENG-6383, epic ENG-6333). When on, the manager clears a trip only when the dependency has genuinely recovered (status active + MCP present + connectivity ok \u2265 hysteresis), replacing the blind ENG-6088 quiet-timer; when off, the blind timer still governs. Boolean gate; ships dark.",
|
|
@@ -9616,6 +9641,16 @@ var integration_metadata_v1_default = {
|
|
|
9616
9641
|
enum: ["basic_username", "basic_pair", "raw"],
|
|
9617
9642
|
description: "How the credential is encoded into Authorization (ENG-10524). `basic_username` sends it as the HTTP Basic username with an empty password (`Authorization: Basic base64(<credential>:)`), Sportsyear's API-key form. `basic_pair` splits the credential on its first `:` and sends `Authorization: Basic base64(<username>:<password>)`, Projectworks' API-account form (CS-1980). `raw` sends the credential itself as the header value with no scheme word (`Authorization: <credential>`), AppsFlyer OneLink's form (CS-1918). Omit for `<auth_scheme> <credential>`. Must not be combined with `auth_scheme`."
|
|
9618
9643
|
},
|
|
9644
|
+
token_exchange: {
|
|
9645
|
+
type: "object",
|
|
9646
|
+
description: "OAuth 2.0 client-credentials exchange (CS-1958). The stored credential is `<client id>:<client secret>`, exchanged at token_url for a short-lived bearer that the broker holds and sends as Bearer.",
|
|
9647
|
+
additionalProperties: false,
|
|
9648
|
+
required: ["token_url", "scope"],
|
|
9649
|
+
properties: {
|
|
9650
|
+
token_url: { type: "string", pattern: "^https://[^\\s]+$" },
|
|
9651
|
+
scope: { type: "string", minLength: 1 }
|
|
9652
|
+
}
|
|
9653
|
+
},
|
|
9619
9654
|
runtime_scopes: {
|
|
9620
9655
|
type: "object",
|
|
9621
9656
|
description: "Per-runtime-scope support map. Each slot is either null (the integration does not support installs at this scope) or an object describing how token resolution and auth work for that scope.",
|
|
@@ -9676,8 +9711,13 @@ var integration_metadata_v1_default = {
|
|
|
9676
9711
|
anyOf: [{ required: ["base_url"] }, { required: ["base_url_template"] }]
|
|
9677
9712
|
},
|
|
9678
9713
|
not: {
|
|
9679
|
-
description: "auth_scheme and auth_encoding are mutually exclusive (ENG-10524). The templater refuses the combination on every call, so catalog validation refuses it first.",
|
|
9680
|
-
|
|
9714
|
+
description: "auth_scheme and auth_encoding are mutually exclusive (ENG-10524). The templater refuses the combination on every call, so catalog validation refuses it first. token_exchange excludes both (CS-1958): the exchanged token must go out as Bearer, and either field would send it in a form the vendor rejects. It also excludes config_arg_defaults: those resolve the token before the approval gate, and an exchange there would post the secret for a call that may then be denied.",
|
|
9715
|
+
anyOf: [
|
|
9716
|
+
{ required: ["auth_scheme", "auth_encoding"] },
|
|
9717
|
+
{ required: ["token_exchange", "auth_scheme"] },
|
|
9718
|
+
{ required: ["token_exchange", "auth_encoding"] },
|
|
9719
|
+
{ required: ["token_exchange", "config_arg_defaults"] }
|
|
9720
|
+
]
|
|
9681
9721
|
},
|
|
9682
9722
|
$defs: {
|
|
9683
9723
|
scopeConfig: {
|
|
@@ -13783,6 +13823,50 @@ async function probeProjectworks(creds, fetchImpl) {
|
|
|
13783
13823
|
};
|
|
13784
13824
|
}
|
|
13785
13825
|
}
|
|
13826
|
+
var CULTUREAMP_TOKEN_URL = "https://api.cultureamp.com/v1/oauth2/token";
|
|
13827
|
+
var CULTUREAMP_TOKEN_SCOPE = "target-entity:8ed17dce-9eca-4383-a9e1-54f82c362b6d:employees-read,employee-demographics-read,performance-evaluations-read";
|
|
13828
|
+
async function probeCultureAmp(creds, fetchImpl) {
|
|
13829
|
+
const pair = creds.api_key ?? creds.access_token;
|
|
13830
|
+
if (!pair)
|
|
13831
|
+
return { status: "down", message: "No Culture Amp credential present" };
|
|
13832
|
+
const raw = String(pair);
|
|
13833
|
+
const colon = raw.indexOf(":");
|
|
13834
|
+
if (colon <= 0 || colon === raw.length - 1) {
|
|
13835
|
+
return { status: "down", message: "Culture Amp credential needs both the client ID and the client secret" };
|
|
13836
|
+
}
|
|
13837
|
+
try {
|
|
13838
|
+
const res = await timedFetch(fetchImpl, CULTUREAMP_TOKEN_URL, {
|
|
13839
|
+
method: "POST",
|
|
13840
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
|
|
13841
|
+
body: new URLSearchParams({
|
|
13842
|
+
grant_type: "client_credentials",
|
|
13843
|
+
scope: CULTUREAMP_TOKEN_SCOPE,
|
|
13844
|
+
client_id: raw.slice(0, colon),
|
|
13845
|
+
client_secret: raw.slice(colon + 1)
|
|
13846
|
+
}).toString(),
|
|
13847
|
+
// As in the broker's exchange: a redirect would carry the secret to wherever it points.
|
|
13848
|
+
redirect: "error"
|
|
13849
|
+
});
|
|
13850
|
+
if (!res.ok) {
|
|
13851
|
+
const message = res.status === 400 || res.status === 401 ? `Culture Amp refused the credential (${res.status}) - check the client ID and secret, and that it has the three read permissions` : res.status === 429 ? rateLimitMessage("Culture Amp", res.status) : `Culture Amp token endpoint returned ${res.status}`;
|
|
13852
|
+
return res.status === 400 ? { status: "down", cause: "auth_rejected", message } : { status: statusForHttp(res.status), cause: causeForHttp(res.status), message };
|
|
13853
|
+
}
|
|
13854
|
+
let body = null;
|
|
13855
|
+
try {
|
|
13856
|
+
body = await res.json();
|
|
13857
|
+
} catch {
|
|
13858
|
+
body = null;
|
|
13859
|
+
}
|
|
13860
|
+
const token = body?.access_token;
|
|
13861
|
+
if (typeof token !== "string" || token === "") {
|
|
13862
|
+
return { status: "down", message: "Culture Amp returned 200 without a token - not a Culture Amp API response" };
|
|
13863
|
+
}
|
|
13864
|
+
return { status: "ok", message: "Connected to Culture Amp" };
|
|
13865
|
+
} catch (err) {
|
|
13866
|
+
const outcome = networkOutcome(err, raw);
|
|
13867
|
+
return outcome.message === void 0 ? outcome : { ...outcome, message: redactSecret(outcome.message, raw.slice(colon + 1)) };
|
|
13868
|
+
}
|
|
13869
|
+
}
|
|
13786
13870
|
async function probeStorrito(creds, fetchImpl, config) {
|
|
13787
13871
|
const token = creds.api_key ?? creds.access_token;
|
|
13788
13872
|
if (!token)
|
|
@@ -14006,6 +14090,8 @@ async function probeHttpProvider(definitionId, credentials, fetchImpl = fetch, c
|
|
|
14006
14090
|
return probeMitti(credentials, fetchImpl);
|
|
14007
14091
|
case "projectworks":
|
|
14008
14092
|
return probeProjectworks(credentials, fetchImpl);
|
|
14093
|
+
case "cultureamp":
|
|
14094
|
+
return probeCultureAmp(credentials, fetchImpl);
|
|
14009
14095
|
case "omnisend":
|
|
14010
14096
|
return probeOmnisend(credentials, fetchImpl);
|
|
14011
14097
|
case "flutterflow":
|
|
@@ -18246,4 +18332,4 @@ export {
|
|
|
18246
18332
|
HOST_ROTATE_KEY_CONFLICT,
|
|
18247
18333
|
shouldMintReplacementKey
|
|
18248
18334
|
};
|
|
18249
|
-
//# sourceMappingURL=chunk-
|
|
18335
|
+
//# sourceMappingURL=chunk-I57M57XZ.js.map
|