312 lines
15 KiB
JavaScript
312 lines
15 KiB
JavaScript
"use strict";
|
|
|
|
// adpanel:planner-done-reconcile — durable catch-up sweep for the planner
|
|
// done-flip.
|
|
//
|
|
// Problem this closes: processAiAgentJob marks the job row terminal
|
|
// 'completed' and THEN flips the planner item is_done = 0 -> 1 through
|
|
// markPlannerItemDoneAfterAgentJob. If the flip is lost (lock-wait
|
|
// timeout/deadlock under the contended active-range lock even after the
|
|
// caller's bounded retry, or the process dies between the completed write and
|
|
// the flip), the job stays terminal 'completed' while the item stays active —
|
|
// and the dedupe (plannerItemHasActiveAgentJob) matches only queued/running
|
|
// jobs, so the next scheduler fire or manual send RE-RUNS the identical
|
|
// prompt: a duplicate billable run with real tool effects. There is no
|
|
// reconciliation anywhere else (the boot resume sweep only re-enqueues
|
|
// status='queued').
|
|
//
|
|
// This module DISCOVERS the stranded pairs and calls the injected flipper. It
|
|
// deliberately contains NO flip SQL and NO lock discipline: the flip keeps
|
|
// EXACTLY ONE implementation (markPlannerItemDoneAfterAgentJob in index.js,
|
|
// handed in here as deps.flipDone) — the module only finds candidates and
|
|
// calls that one implementation, which re-verifies the canonical server name,
|
|
// the prompt snapshot and the lock order itself.
|
|
//
|
|
// Candidate safety: a pair qualifies only when the job's stored prompt is the
|
|
// EXACT recomposition of the item's CURRENT text
|
|
// (sanitizeAiAgentPrompt(buildPlannerAgentPrompt(item, serverName))). That is
|
|
// byte-for-byte the "prompt edited since enqueue" guard the flip itself
|
|
// applies, so a flip that was deliberately SKIPPED for an edited prompt is
|
|
// never force-flipped here — the skip means the new text must be re-run, not
|
|
// consumed. Items already flipped (is_done = 1) and jobs that are not
|
|
// terminal 'completed' planner jobs never qualify.
|
|
//
|
|
// Discovery shape (adpanel:planner-done-reconcile): ITEM-driven and
|
|
// WINDOW-FREE. The scan selects one row per ACTIVE item that owns at least
|
|
// one terminal 'completed' planner job — that item's LATEST completed job
|
|
// (a NOT EXISTS anti-join drops rows a newer completed job for the same item
|
|
// supersedes) — with NO completed_at window: a window would strand a lost
|
|
// flip older than the window forever, and the dedupe
|
|
// (plannerItemHasActiveAgentJob) matches only queued/running jobs, so an
|
|
// undiscovered pair is re-run billably on every scheduler fire or manual
|
|
// send. A RECENCY GUARD (adpanel:planner-reconcile-recency) also qualifies
|
|
// each pair in SQL: a row surfaces only when the item was NOT touched after
|
|
// its latest completed job finished (i.updated_at <= j.completed_at — both
|
|
// TIMESTAMP, compared in-SQL, with explicit IS NOT NULL guards that fail
|
|
// closed). updated_at carries ON UPDATE CURRENT_TIMESTAMP, so every user
|
|
// action on the item — above all a deliberate re-activation toggle — bumps
|
|
// it past the run's completion: a completion a user action postdates is
|
|
// consumed or superseded and must never re-archive the item (without this
|
|
// guard the window-free scan re-archived a deliberately re-activated item
|
|
// on every subsequent pass, forever). The candidate set is bounded by the
|
|
// active-item count
|
|
// (PLANNER_MAX_ITEMS_PER_SERVER = 200 per server) and scanLimit. The
|
|
// latest-job pick is a bound, not a gate — the exact-prompt recomposition
|
|
// above is the real filter and the flip re-verifies the snapshot itself.
|
|
// Accepted residual: when an item's latest completed job executes text that
|
|
// no longer matches the item's current text while an OLDER completed job
|
|
// does match (edit away, stranded flip, edit back to the original), the
|
|
// pair stays stranded — the edit-back-after-the-run variant is now skipped
|
|
// by the recency guard first (the edit-back touch postdates the latest
|
|
// completion, adpanel:planner-reconcile-recency), and the variant edited
|
|
// away and back WHILE the latest job was in flight (last touch predates
|
|
// completed_at, so the guard passes) is skipped by the recomposition gate
|
|
// on the latest-job row. Either way the item is still ACTIVE, so the
|
|
// scheduler's normal re-fire cycle remains the backstop: the re-run's own
|
|
// flip either fires or re-strands with a fresh snapshot whose completion
|
|
// postdates the last touch, which the sweep then catches.
|
|
//
|
|
// Failure posture: everything fails OPEN — discovery errors, per-pair flip
|
|
// errors and configuration gaps warn and are counted, never thrown to the
|
|
// caller (the interval callback has no error plumbing, and a broken sweep must
|
|
// never break boot).
|
|
//
|
|
// Known discovery bound (accepted): the join matches job.server_name to
|
|
// item.server_name exactly. Rows persisted before insertAiAgentChatJob began
|
|
// storing the canonical entry.name (adpanel:planner-job-retract) can carry an
|
|
// alias form the flip itself would canonicalize via findServer but this join
|
|
// cannot; those legacy rows are out of the sweep's reach and rely on the
|
|
// normal completion path.
|
|
|
|
// The planner job source family. The one home is index.js's
|
|
// PLANNER_AGENT_JOB_SOURCES — this default exists so the module is testable
|
|
// standalone, and the index.js wiring passes [...PLANNER_AGENT_JOB_SOURCES]
|
|
// so the family cannot drift between the two files.
|
|
const DEFAULT_PLANNER_JOB_SOURCES = Object.freeze([
|
|
"planner_send",
|
|
"scheduler_planner_next",
|
|
]);
|
|
|
|
const DEFAULT_SCAN_LIMIT = 200;
|
|
const DEFAULT_BOOT_DELAY_MS = 10 * 1000;
|
|
const DEFAULT_INTERVAL_MS = 15 * 60 * 1000;
|
|
|
|
function clampPositiveInt(value, fallback, max) {
|
|
const parsed = parseInt(value, 10);
|
|
if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
|
|
return Math.min(parsed, max);
|
|
}
|
|
|
|
// Module-level once-guard for start(): index.js's table-init path can in
|
|
// principle run twice against the same process (boot timer + a lazy
|
|
// ensure-ready request racing it), and two factory instances cannot see each
|
|
// other's instance flags — the schedule must exist at most once per process.
|
|
let scheduledOnce = false;
|
|
|
|
function createPlannerDoneReconcile(deps) {
|
|
const db = deps && deps.db && typeof deps.db.query === "function" ? deps.db : null;
|
|
const buildPlannerAgentPrompt =
|
|
deps && typeof deps.buildPlannerAgentPrompt === "function" ? deps.buildPlannerAgentPrompt : null;
|
|
const sanitizeAiAgentPrompt =
|
|
deps && typeof deps.sanitizeAiAgentPrompt === "function" ? deps.sanitizeAiAgentPrompt : null;
|
|
const flipDone = deps && typeof deps.flipDone === "function" ? deps.flipDone : null;
|
|
const logger = deps && deps.logger ? deps.logger : console;
|
|
const jobSources = Array.isArray(deps?.plannerJobSources) && deps.plannerJobSources.length
|
|
? deps.plannerJobSources.map((s) => String(s)).filter((s) => /^[a-z_]+$/.test(s))
|
|
: DEFAULT_PLANNER_JOB_SOURCES;
|
|
const scanLimit = clampPositiveInt(deps?.scanLimit, DEFAULT_SCAN_LIMIT, 1000);
|
|
|
|
let sweepInFlight = false;
|
|
|
|
function warn(message, err) {
|
|
if (logger && typeof logger.warn === "function") {
|
|
logger.warn(message, err?.message || err || "");
|
|
}
|
|
}
|
|
|
|
// Read-only candidate discovery — ITEM-driven and WINDOW-FREE (see the
|
|
// module header): one row per ACTIVE item that owns at least one terminal
|
|
// 'completed' planner job, carrying that item's LATEST completed job — the
|
|
// NOT EXISTS anti-join drops rows a newer completed job for the same item
|
|
// supersedes (latest by completed_at, id as the same-second tie-break), so
|
|
// the result is bounded by the active-item count, not by job history. A
|
|
// completed_at window is deliberately absent: a lost flip older than any
|
|
// window must stay discoverable (the dedupe matches only queued/running,
|
|
// so an undiscovered pair re-runs billably on every fire). The ORDER BY is
|
|
// a drain preference, not a filter: oldest strandings surface first across
|
|
// passes. The exact-prompt recomposition in reconcile() is the real
|
|
// filter, and the flip re-verifies the snapshot itself.
|
|
//
|
|
// adpanel:planner-reconcile-recency — qualification predicate, kept in SQL
|
|
// so a disqualified row never surfaces: a stranded flip means NO user
|
|
// action postdated the run; if the item was touched after the job
|
|
// completed, the completion is consumed or superseded — never re-archive.
|
|
// Both columns are TIMESTAMP (i.updated_at is NOT NULL ... ON UPDATE
|
|
// CURRENT_TIMESTAMP — every user toggle/edit/reorder bumps it;
|
|
// j.completed_at is stamped by the same UPDATE that writes the terminal
|
|
// status, so a qualifying 'completed' row cannot legitimately carry NULL),
|
|
// compared in-SQL with no cross-type coercion. The IS NOT NULL guards are
|
|
// the fail-closed path for the unexpected: an unforeseen NULL simply never
|
|
// surfaces the row (the flip is skipped) instead of comparing
|
|
// NULL-ambiguously.
|
|
//
|
|
// source_ref is a VARCHAR storing the CANONICAL DIGIT STRING of the item
|
|
// id (adpanel:source-ref-string-bind — every comparison must stay
|
|
// string-shaped, never numerically coerced), so the join casts the BIGINT
|
|
// id to CHAR: VARCHAR = VARCHAR keeps the comparison on the index the way
|
|
// the bound String(itemId) queries do. scanLimit is a server-side clamped
|
|
// integer (never user input), inlined for the same driver reason as
|
|
// pruneTerminalAiAgentJobs: db.query prepares statements and LIMIT bind
|
|
// quirk-free only when the driver sends literal integers across versions.
|
|
function candidateSql() {
|
|
const sourceList = jobSources.map((s) => `'${s}'`).join(",");
|
|
return `
|
|
SELECT i.id AS item_id,
|
|
i.server_name AS item_server_name,
|
|
i.title AS item_title,
|
|
i.prompt AS item_prompt,
|
|
j.id AS job_id,
|
|
j.source AS job_source,
|
|
j.server_name AS job_server_name,
|
|
j.source_ref AS job_source_ref,
|
|
j.prompt AS job_prompt,
|
|
j.user_email AS job_user_email
|
|
FROM server_planner_items i
|
|
JOIN ai_agent_jobs j
|
|
ON j.server_name = i.server_name
|
|
AND j.source_ref = CAST(i.id AS CHAR)
|
|
AND j.source IN (${sourceList})
|
|
AND j.status = 'completed'
|
|
WHERE i.is_done = 0
|
|
AND (i.agent_edit_hold_job_id IS NULL OR i.agent_edit_hold_job_id = j.id)
|
|
AND i.updated_at IS NOT NULL
|
|
AND j.completed_at IS NOT NULL
|
|
AND i.updated_at <= j.completed_at
|
|
AND NOT EXISTS (
|
|
SELECT 1 FROM ai_agent_jobs j2
|
|
WHERE j2.server_name = i.server_name
|
|
AND j2.source_ref = CAST(i.id AS CHAR)
|
|
AND j2.source IN (${sourceList})
|
|
AND j2.status = 'completed'
|
|
AND (j2.completed_at > j.completed_at
|
|
OR (j2.completed_at = j.completed_at AND j2.id > j.id))
|
|
)
|
|
ORDER BY j.completed_at ASC, j.id ASC
|
|
LIMIT ${scanLimit}`;
|
|
}
|
|
|
|
async function reconcile() {
|
|
// Re-entrancy guard: an interval fire while a previous sweep is still
|
|
// running is skipped silently — the sweep is bounded and sequential, and
|
|
// logging every overlapped tick would spam a slow-but-healthy pass.
|
|
if (sweepInFlight) {
|
|
return { ok: false, skipped: true, reason: "sweep_in_flight", flipped: 0, failed: 0 };
|
|
}
|
|
if (!db || !buildPlannerAgentPrompt || !sanitizeAiAgentPrompt || !flipDone) {
|
|
warn("[planner-done-reconcile] Not configured (missing db / prompt composer / sanitizer / flip callback); skipping reconcile pass");
|
|
return { ok: false, skipped: true, reason: "not_configured", flipped: 0, failed: 0 };
|
|
}
|
|
sweepInFlight = true;
|
|
let flipped = 0;
|
|
let failed = 0;
|
|
let scanned = 0;
|
|
try {
|
|
let rows;
|
|
try {
|
|
rows = await db.query(candidateSql(), []);
|
|
} catch (err) {
|
|
// Fail open: a missing table (planner init not landed yet on a slow
|
|
// boot) or a transient DB loss must never throw to the caller.
|
|
warn("[planner-done-reconcile] Candidate discovery failed; skipping reconcile pass", err);
|
|
return { ok: false, skipped: false, reason: "discovery_failed", flipped: 0, failed: 0 };
|
|
}
|
|
for (const row of rows || []) {
|
|
scanned += 1;
|
|
// Recompose the executed snapshot from the item's CURRENT text — the
|
|
// exact byte-compare the flip itself guards with. A mismatch is the
|
|
// "prompt edited since enqueue" family: the edit must be re-run, so
|
|
// the stranded old-text job is left alone (counted, not flipped).
|
|
let matches;
|
|
try {
|
|
const recomposed = sanitizeAiAgentPrompt(
|
|
buildPlannerAgentPrompt({ title: row.item_title, prompt: row.item_prompt }, row.item_server_name)
|
|
);
|
|
matches = recomposed === String(row.job_prompt || "");
|
|
} catch (composeErr) {
|
|
warn(`[planner-done-reconcile] Could not recompose snapshot for item ${row.item_id} on ${row.item_server_name}; skipping pair`, composeErr);
|
|
failed += 1;
|
|
continue;
|
|
}
|
|
if (!matches) continue;
|
|
// Per-item error isolation: one stranded pair's flip failure must not
|
|
// abort the sweep — the remaining pairs are independent.
|
|
try {
|
|
await flipDone({
|
|
id: row.job_id,
|
|
source: row.job_source,
|
|
server_name: row.job_server_name,
|
|
source_ref: String(row.job_source_ref),
|
|
prompt: row.job_prompt,
|
|
user_email: row.job_user_email,
|
|
});
|
|
flipped += 1;
|
|
} catch (flipErr) {
|
|
failed += 1;
|
|
warn(`[planner-done-reconcile] Done-flip failed for job ${row.job_id} (item ${row.item_id} on ${row.item_server_name}); will retry on the next pass`, flipErr);
|
|
}
|
|
}
|
|
if (flipped > 0 || failed > 0) {
|
|
warn(`[planner-done-reconcile] Reconcile pass: ${scanned} candidate pair(s) scanned, ${flipped} flipped done, ${failed} failed (retry on next pass)`);
|
|
}
|
|
return { ok: true, skipped: false, scanned, flipped, failed };
|
|
} finally {
|
|
sweepInFlight = false;
|
|
}
|
|
}
|
|
|
|
// Schedule: one delayed boot pass (delayed so a normal boot's table-init
|
|
// timers — ai chat tables at +3s, planner tables at +3.2s — have landed
|
|
// before the first discovery; a slower boot just warns and waits for the
|
|
// interval) plus a low-frequency interval. Both timers are unref'd: a worker
|
|
// with nothing else to do must stay stoppable. Errors never propagate —
|
|
// reconcile fails open internally.
|
|
let bootTimer = null;
|
|
let intervalTimer = null;
|
|
function start(options) {
|
|
if (scheduledOnce) return false;
|
|
scheduledOnce = true;
|
|
const bootDelayMs = clampPositiveInt(options?.bootDelayMs, DEFAULT_BOOT_DELAY_MS, 24 * 60 * 60 * 1000);
|
|
const intervalMs = clampPositiveInt(options?.intervalMs, DEFAULT_INTERVAL_MS, 24 * 60 * 60 * 1000);
|
|
bootTimer = setTimeout(() => {
|
|
bootTimer = null;
|
|
reconcile();
|
|
}, bootDelayMs);
|
|
if (typeof bootTimer.unref === "function") bootTimer.unref();
|
|
intervalTimer = setInterval(() => {
|
|
reconcile();
|
|
}, intervalMs);
|
|
if (typeof intervalTimer.unref === "function") intervalTimer.unref();
|
|
return true;
|
|
}
|
|
|
|
// Test/ops handle: tears both timers down so a stopped instance stops
|
|
// sweeping (the module-level once-guard still prevents a second start from
|
|
// the same process — that guard exists to protect the live wiring, not to
|
|
// be toggled by stop()).
|
|
function stop() {
|
|
if (bootTimer) {
|
|
clearTimeout(bootTimer);
|
|
bootTimer = null;
|
|
}
|
|
if (intervalTimer) {
|
|
clearInterval(intervalTimer);
|
|
intervalTimer = null;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
return { reconcile, start, stop };
|
|
}
|
|
|
|
module.exports = { createPlannerDoneReconcile };
|