@tidegap/core 0.27.0 → 0.28.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/dist/handoff.d.ts CHANGED
@@ -149,6 +149,11 @@ export declare function wakeError(wake: unknown, origin: {
149
149
  * fallback; it creates that file at start, so the two agree from then on.
150
150
  */
151
151
  export declare function defaultDbPath(): string;
152
+ /**
153
+ * The default ledger as a refusal names it, under `~`: the file the hooks
154
+ * read, so `~/.ebb/queue.sqlite` on a home that has only that one.
155
+ */
156
+ export declare function defaultLedgerShown(): string;
152
157
  /**
153
158
  * The `wake:` line of a task's work shape, or undefined when it does not
154
159
  * wake: a one-off wake task wakes when it finishes; a run of a bound job
@@ -161,7 +166,8 @@ export declare function wakeShapeText(shape: Pick<TaskWorkShape, "wake" | "wakeR
161
166
  * read that ledger only, so a pass over another ledger must neither
162
167
  * create nor remove them, and a wake for a task in another ledger could
163
168
  * never fire. Compares real paths; a missing file compares by
164
- * its folder's real path and its name.
169
+ * its folder's real path and its name, the name in any case on macOS and
170
+ * Windows, whose file systems ignore case by default.
165
171
  */
166
172
  export declare function isDefaultLedger(dbPath: string): boolean;
167
173
  /** `~/.tidegap/sessions/wake`: one marker per session with a task to wake it for. */
package/dist/handoff.js CHANGED
@@ -392,6 +392,13 @@ export function defaultDbPath() {
392
392
  return legacyPath;
393
393
  return newPath;
394
394
  }
395
+ /**
396
+ * The default ledger as a refusal names it, under `~`: the file the hooks
397
+ * read, so `~/.ebb/queue.sqlite` on a home that has only that one.
398
+ */
399
+ export function defaultLedgerShown() {
400
+ return join("~", relative(homedir(), defaultDbPath()));
401
+ }
395
402
  /**
396
403
  * The `wake:` line of a task's work shape, or undefined when it does not
397
404
  * wake: a one-off wake task wakes when it finishes; a run of a bound job
@@ -412,7 +419,8 @@ export function wakeShapeText(shape) {
412
419
  * read that ledger only, so a pass over another ledger must neither
413
420
  * create nor remove them, and a wake for a task in another ledger could
414
421
  * never fire. Compares real paths; a missing file compares by
415
- * its folder's real path and its name.
422
+ * its folder's real path and its name, the name in any case on macOS and
423
+ * Windows, whose file systems ignore case by default.
416
424
  */
417
425
  export function isDefaultLedger(dbPath) {
418
426
  if (dbPath === ":memory:")
@@ -420,18 +428,29 @@ export function isDefaultLedger(dbPath) {
420
428
  // A missing file resolves through its folder, so a linked home still matches.
421
429
  const real = (path) => {
422
430
  try {
423
- return realpathSync.native(path);
431
+ return { path: realpathSync.native(path), exists: true };
424
432
  }
425
433
  catch {
426
434
  try {
427
- return join(realpathSync.native(dirname(path)), basename(path));
435
+ return { path: join(realpathSync.native(dirname(path)), basename(path)), exists: false };
428
436
  }
429
437
  catch {
430
- return resolve(path);
438
+ return { path: resolve(path), exists: false };
431
439
  }
432
440
  }
433
441
  };
434
- return real(dbPath) === real(defaultDbPath());
442
+ const given = real(dbPath);
443
+ const ledger = real(defaultDbPath());
444
+ if (given.path === ledger.path)
445
+ return true;
446
+ // An existing file's real path has the case on disk, and on a file system
447
+ // that ignores case the other name then resolves to it too: only two
448
+ // missing files keep the case they were given.
449
+ if (given.exists || ledger.exists)
450
+ return false;
451
+ if (process.platform !== "darwin" && process.platform !== "win32")
452
+ return false;
453
+ return dirname(given.path) === dirname(ledger.path) && basename(given.path).toLowerCase() === basename(ledger.path).toLowerCase();
435
454
  }
436
455
  /** `~/.tidegap/sessions/wake`: one marker per session with a task to wake it for. */
437
456
  export function wakeMarkersDir(home = resolveTidegapHome()) {
package/dist/history.d.ts CHANGED
@@ -76,8 +76,8 @@ export interface TaskActions {
76
76
  markRead: boolean;
77
77
  /**
78
78
  * Failed provider-call one-off task, a `command` task included: retry it
79
- * by hand (due on the next tick). A run of a job, and a run that stopped
80
- * during its Batch submit, are refused.
79
+ * by hand (due on the next tick). A run of a job, a run that stopped
80
+ * during its Batch submit and a lost Batch row are refused.
81
81
  */
82
82
  retry: boolean;
83
83
  }
@@ -90,6 +90,23 @@ export interface TaskActions {
90
90
  * module imports nothing from `jobs.ts` (which imports `deriveTitle` from here).
91
91
  */
92
92
  export declare const BATCH_SUBMIT_INTERRUPTED_ERROR = "interrupted: the tick stopped during the Batch submit; the provider may have accepted the batch, so check the provider's batch list before you enqueue the task again";
93
+ /**
94
+ * How long after its deadline a Batch row whose poll still fails counts as
95
+ * lost (batch 44 KTD2). A row goes to a Batch API only with a deadline over
96
+ * a day ahead, and the providers end every batch within 24 hours, so by
97
+ * then no live batch answers the poll.
98
+ */
99
+ export declare const BATCH_LOST_AFTER_MS: number;
100
+ /**
101
+ * The error of a Batch row whose poll still failed {@link BATCH_LOST_AFTER_MS}
102
+ * after its deadline. The batch may have completed and been billed, so, as
103
+ * with {@link BATCH_SUBMIT_INTERRUPTED_ERROR}, no path runs the row again:
104
+ * `retryTask`, the Python `retry_task` and the job sweep refuse it.
105
+ * `test/fixtures/lost-batch-polls.json` shares the text with the Python core.
106
+ */
107
+ export declare function batchLostError(batchId: string): string;
108
+ /** True for the error {@link batchLostError} writes (an `(after N attempts)` suffix included). */
109
+ export declare function isBatchLostError(error: string | undefined): boolean;
93
110
  /** True when the task repeats (a stored rule other than `none`). */
94
111
  export declare function isRepeating(record: Pick<TaskRecord<unknown>, "repeat">): boolean;
95
112
  /** Allowed actions for `record`; see {@link TaskActions}. */
@@ -197,7 +214,11 @@ export interface TaskAttachment extends StoredAttachment {
197
214
  index: number;
198
215
  expired?: boolean;
199
216
  }
200
- /** A file name for people: one line, no control, bidirectional or zero-width characters, whitespace runs joined, at most 80 characters; "" when nothing is left. */
217
+ /**
218
+ * A file name for people: one line, no control, bidirectional or zero-width
219
+ * characters (one ZWNJ or ZWJ between two characters stays), whitespace runs
220
+ * joined, at most 80 characters; "" when nothing is left.
221
+ */
201
222
  export declare function attachmentDisplayName(name: string): string;
202
223
  /**
203
224
  * The stored attachments of a completed run, in order. An entry whose shape
package/dist/history.js CHANGED
@@ -152,6 +152,29 @@ export function deadlineKindLabel(record, quota = {}) {
152
152
  * module imports nothing from `jobs.ts` (which imports `deriveTitle` from here).
153
153
  */
154
154
  export const BATCH_SUBMIT_INTERRUPTED_ERROR = "interrupted: the tick stopped during the Batch submit; the provider may have accepted the batch, so check the provider's batch list before you enqueue the task again";
155
+ /**
156
+ * How long after its deadline a Batch row whose poll still fails counts as
157
+ * lost (batch 44 KTD2). A row goes to a Batch API only with a deadline over
158
+ * a day ahead, and the providers end every batch within 24 hours, so by
159
+ * then no live batch answers the poll.
160
+ */
161
+ export const BATCH_LOST_AFTER_MS = 24 * 60 * 60_000;
162
+ /** The start of a lost Batch row's error; {@link isBatchLostError} reads it. */
163
+ const BATCH_LOST_PREFIX = "batch lost: ";
164
+ /**
165
+ * The error of a Batch row whose poll still failed {@link BATCH_LOST_AFTER_MS}
166
+ * after its deadline. The batch may have completed and been billed, so, as
167
+ * with {@link BATCH_SUBMIT_INTERRUPTED_ERROR}, no path runs the row again:
168
+ * `retryTask`, the Python `retry_task` and the job sweep refuse it.
169
+ * `test/fixtures/lost-batch-polls.json` shares the text with the Python core.
170
+ */
171
+ export function batchLostError(batchId) {
172
+ return `${BATCH_LOST_PREFIX}the provider did not answer for ${batchId}; check the provider's batch list`;
173
+ }
174
+ /** True for the error {@link batchLostError} writes (an `(after N attempts)` suffix included). */
175
+ export function isBatchLostError(error) {
176
+ return error?.startsWith(BATCH_LOST_PREFIX) ?? false;
177
+ }
155
178
  const PENDING = new Set(["queued", "scheduled", "submitted", "running"]);
156
179
  /** True when the task repeats (a stored rule other than `none`). */
157
180
  export function isRepeating(record) {
@@ -173,7 +196,11 @@ export function taskActions(record) {
173
196
  reply: record.status === "completed" && providerCall && spec?.provider !== "command",
174
197
  markRead: record.status === "completed" || record.status === "failed",
175
198
  // The same rule as `Scheduler.retryLater` refuses by.
176
- retry: record.status === "failed" && providerCall && !record.jobId && record.error !== BATCH_SUBMIT_INTERRUPTED_ERROR,
199
+ retry: record.status === "failed" &&
200
+ providerCall &&
201
+ !record.jobId &&
202
+ record.error !== BATCH_SUBMIT_INTERRUPTED_ERROR &&
203
+ !isBatchLostError(record.error),
177
204
  };
178
205
  }
179
206
  /**
@@ -237,11 +264,20 @@ export const ATTACHMENT_TYPES = {
237
264
  "application/json": { ext: "json", label: "JSON", photo: false, inline: false },
238
265
  "image/svg+xml": { ext: "svg", label: "SVG image", photo: false, inline: false },
239
266
  };
240
- /** Zero-width characters: a name that holds them can pass for another. */
241
- const ZERO_WIDTH = /[\u200B-\u200D\u2060\uFEFF]/g;
242
- /** A file name for people: one line, no control, bidirectional or zero-width characters, whitespace runs joined, at most 80 characters; "" when nothing is left. */
267
+ /** Zero-width characters: a name that holds them can pass for another. ZWNJ and ZWJ go by {@link JOINERS}. */
268
+ const ZERO_WIDTH = /[\u200B\u2060\uFEFF]/g;
269
+ /** ZWNJ and ZWJ: Persian and Indic words and emoji sequences need one between two characters, nowhere else. */
270
+ const JOINERS = /[\u200C\u200D]+/g;
271
+ /**
272
+ * A file name for people: one line, no control, bidirectional or zero-width
273
+ * characters (one ZWNJ or ZWJ between two characters stays), whitespace runs
274
+ * joined, at most 80 characters; "" when nothing is left.
275
+ */
243
276
  export function attachmentDisplayName(name) {
244
- return cutPreview(stripBidiControls(stripControlChars(name)).replace(ZERO_WIDTH, "").replace(/\s+/g, " ").trim(), TITLE_MAX_CHARS);
277
+ const text = stripBidiControls(stripControlChars(name))
278
+ .replace(ZERO_WIDTH, "")
279
+ .replace(JOINERS, (run, at, whole) => (/\S/.test(whole[at - 1] ?? " ") && /\S/.test(whole[at + run.length] ?? " ") ? run[0] : ""));
280
+ return cutPreview(text.replace(/\s+/g, " ").trim(), TITLE_MAX_CHARS);
245
281
  }
246
282
  function attachmentName(value) {
247
283
  return typeof value === "string" ? attachmentDisplayName(value) || undefined : undefined;
package/dist/index.d.ts CHANGED
@@ -58,7 +58,7 @@ export type { CarbonStats, RegionStats, BandHistogram, Achievement, } from "./ag
58
58
  export { NOTIFY_PREVIEW_CHARS, WIN_NOTIFY_BODY_VAR, WIN_NOTIFY_TITLE_VAR, firstErrorLine, osNotifyCommand, taskNotificationContent, } from "./notify.js";
59
59
  export type { OsNotifyCommand, OsNotifyOptions } from "./notify.js";
60
60
  export { CLAUDE_CODE_TOOL_ALLOWLIST, DEFAULT_CLAUDE_CODE_TOOLS, DEFAULT_ORIGIN_TOOLS, claudeCodeToolsError, includesFileTool, includesWebTool, } from "./claude-tools.js";
61
- export { HANDOFF_PATH_MAX_CHARS, HANDOFF_PROFILES, PROFILE_TOOLS, defaultDbPath, handoffCwdError, isDefaultLedger, latestResultFile, nodeHandoffFs, outputPathError, profileTools, PROTECTED_HOME_DIRS, resultFileText, resultPathError, removeWakeMarker, sameTools, taskWorkShape, wakeShapeText, isWakeTask, noticeWakes, releaseWakeMarker, removeWakeMarkerUnlessPending, sessionHasWaitWork, wakeTasksToCome, wakeError, wakeMarkerPath, wakeMarkersDir, writeWakeMarker, } from "./handoff.js";
61
+ export { HANDOFF_PATH_MAX_CHARS, HANDOFF_PROFILES, PROFILE_TOOLS, defaultDbPath, defaultLedgerShown, handoffCwdError, isDefaultLedger, latestResultFile, nodeHandoffFs, outputPathError, profileTools, PROTECTED_HOME_DIRS, resultFileText, resultPathError, removeWakeMarker, sameTools, taskWorkShape, wakeShapeText, isWakeTask, noticeWakes, releaseWakeMarker, removeWakeMarkerUnlessPending, sessionHasWaitWork, wakeTasksToCome, wakeError, wakeMarkerPath, wakeMarkersDir, writeWakeMarker, } from "./handoff.js";
62
62
  export type { HandoffFs, HandoffFsEntry, HandoffPathContext, HandoffProfile, HandoffSpec, ProfileChoice, TaskWorkShape, } from "./handoff.js";
63
63
  export { forkCommand, freshReasonText, runSessionSummary, shortSessionId, taskOrigin, tokensLabel } from "./run-session.js";
64
64
  export type { FreshReason, RunSession, RunSessionMode } from "./run-session.js";
@@ -75,7 +75,7 @@ export type { JobSchedule, NextOccurrenceInput } from "./job-cadence.js";
75
75
  export { localToUtcMs, systemTimeZone, zoneTimeLabel } from "./zone-time.js";
76
76
  export { loadNoticeLanguage, NOTICE_LANGUAGE_KEY, NoticeLanguageError, parseNoticeLanguage } from "./notice-language.js";
77
77
  export type { NoticeLanguage, NoticeLanguageSetting } from "./notice-language.js";
78
- export { createJob, getJob, JOB_AUTO_PAUSE_FAILURES, JOB_AUTO_PAUSE_PREFIX, jobAutoPauseReason, jobEndsText, jobEndText, JOB_INTERRUPTED_ERROR, JOB_MAX_COUNT, DEFAULT_SUMMARIZE_PROMPT, effectiveSummarizePrompt, isDefaultSummarizePrompt, SUMMARIZE_GUARD_LINE, JOB_SECRET_NAME, JobActionError, isExtraRunId, jobHistory, jobLastRun, jobNextRun, jobRunLimits, jobWakeSession, listJobs, pauseJob, removeJob, resumeJob, runJobNow, runNowRefusal, runOutcome, sweepJobs, updateJob, } from "./jobs.js";
78
+ export { createJob, getJob, JOB_AUTO_PAUSE_FAILURES, JOB_AUTO_PAUSE_PREFIX, jobAutoPauseReason, jobEndsText, jobEndText, JOB_INTERRUPTED_ERROR, JOB_MAX_COUNT, DEFAULT_SUMMARIZE_PROMPT, effectiveSummarizePrompt, isDefaultSummarizePrompt, SUMMARIZE_GUARD_LINE, JOB_SECRET_NAME, JobActionError, JOB_FINAL_FAILURES_META_KEY, isExtraRunId, jobFinalFailureIds, queueJobFinalFailure, jobHistory, jobLastRun, jobNextRun, jobRunLimits, jobWakeSession, listJobs, pauseJob, removeJob, resumeJob, runJobNow, runNowRefusal, runOutcome, sweepJobs, updateJob, } from "./jobs.js";
79
79
  export type { JobActionOptions, JobCapsPatch, JobHistoryEntry, JobInput, JobPatch, JobSweepResult, JobUpdateOptions, JobWakeInput } from "./jobs.js";
80
80
  export { JOB_WAKE_FORMS, JOB_WAKE_MATCH_TIMEOUT_MS, JOB_WAKE_PATTERN_MAX_CHARS, JOB_WAKE_TEXT_MAX_CHARS, JobWakeError, matchWake, parseWakeRule, wakePatternError, } from "./job-wake.js";
81
81
  export type { JobWakeRule, WakeMatch } from "./job-wake.js";
package/dist/index.js CHANGED
@@ -56,7 +56,7 @@ export { ASSUMED_KWH_PER_CALL, classifyBand, aggregateStats, aggregateByRegion,
56
56
  // Desktop notifications (v0.17): pure command builder, hosts spawn it.
57
57
  export { NOTIFY_PREVIEW_CHARS, WIN_NOTIFY_BODY_VAR, WIN_NOTIFY_TITLE_VAR, firstErrorLine, osNotifyCommand, taskNotificationContent, } from "./notify.js";
58
58
  export { CLAUDE_CODE_TOOL_ALLOWLIST, DEFAULT_CLAUDE_CODE_TOOLS, DEFAULT_ORIGIN_TOOLS, claudeCodeToolsError, includesFileTool, includesWebTool, } from "./claude-tools.js";
59
- export { HANDOFF_PATH_MAX_CHARS, HANDOFF_PROFILES, PROFILE_TOOLS, defaultDbPath, handoffCwdError, isDefaultLedger, latestResultFile, nodeHandoffFs, outputPathError, profileTools, PROTECTED_HOME_DIRS, resultFileText, resultPathError, removeWakeMarker, sameTools, taskWorkShape, wakeShapeText, isWakeTask, noticeWakes, releaseWakeMarker, removeWakeMarkerUnlessPending, sessionHasWaitWork, wakeTasksToCome, wakeError, wakeMarkerPath, wakeMarkersDir, writeWakeMarker, } from "./handoff.js";
59
+ export { HANDOFF_PATH_MAX_CHARS, HANDOFF_PROFILES, PROFILE_TOOLS, defaultDbPath, defaultLedgerShown, handoffCwdError, isDefaultLedger, latestResultFile, nodeHandoffFs, outputPathError, profileTools, PROTECTED_HOME_DIRS, resultFileText, resultPathError, removeWakeMarker, sameTools, taskWorkShape, wakeShapeText, isWakeTask, noticeWakes, releaseWakeMarker, removeWakeMarkerUnlessPending, sessionHasWaitWork, wakeTasksToCome, wakeError, wakeMarkerPath, wakeMarkersDir, writeWakeMarker, } from "./handoff.js";
60
60
  export { forkCommand, freshReasonText, runSessionSummary, shortSessionId, taskOrigin, tokensLabel } from "./run-session.js";
61
61
  export { carbonBudgetConfigPath, carbonBudgetStatus, carbonBudgetUsage, loadCarbonBudgetConfig, parseKeyValues, KEY_PREFIX, receiptCarbonG, windowBounds, } from "./budget.js";
62
62
  // Quota-reset deadlines and the shared pre-tick step (v0.17).
@@ -70,7 +70,7 @@ export { localToUtcMs, systemTimeZone, zoneTimeLabel } from "./zone-time.js";
70
70
  // The notice language a job's summarize step writes in (`tidegap language`).
71
71
  export { loadNoticeLanguage, NOTICE_LANGUAGE_KEY, NoticeLanguageError, parseNoticeLanguage } from "./notice-language.js";
72
72
  // Floating recurring jobs: actions and the job sweep (KTD2, KTD9).
73
- export { createJob, getJob, JOB_AUTO_PAUSE_FAILURES, JOB_AUTO_PAUSE_PREFIX, jobAutoPauseReason, jobEndsText, jobEndText, JOB_INTERRUPTED_ERROR, JOB_MAX_COUNT, DEFAULT_SUMMARIZE_PROMPT, effectiveSummarizePrompt, isDefaultSummarizePrompt, SUMMARIZE_GUARD_LINE, JOB_SECRET_NAME, JobActionError, isExtraRunId, jobHistory, jobLastRun, jobNextRun, jobRunLimits, jobWakeSession, listJobs, pauseJob, removeJob, resumeJob, runJobNow, runNowRefusal, runOutcome, sweepJobs, updateJob, } from "./jobs.js";
73
+ export { createJob, getJob, JOB_AUTO_PAUSE_FAILURES, JOB_AUTO_PAUSE_PREFIX, jobAutoPauseReason, jobEndsText, jobEndText, JOB_INTERRUPTED_ERROR, JOB_MAX_COUNT, DEFAULT_SUMMARIZE_PROMPT, effectiveSummarizePrompt, isDefaultSummarizePrompt, SUMMARIZE_GUARD_LINE, JOB_SECRET_NAME, JobActionError, JOB_FINAL_FAILURES_META_KEY, isExtraRunId, jobFinalFailureIds, queueJobFinalFailure, jobHistory, jobLastRun, jobNextRun, jobRunLimits, jobWakeSession, listJobs, pauseJob, removeJob, resumeJob, runJobNow, runNowRefusal, runOutcome, sweepJobs, updateJob, } from "./jobs.js";
74
74
  // Wake rules of a job bound to a session (KTD7, KTD9).
75
75
  export { JOB_WAKE_FORMS, JOB_WAKE_MATCH_TIMEOUT_MS, JOB_WAKE_PATTERN_MAX_CHARS, JOB_WAKE_TEXT_MAX_CHARS, JobWakeError, matchWake, parseWakeRule, wakePatternError, } from "./job-wake.js";
76
76
  export { AnthropicAdapter, OpenAIAdapter, GeminiAdapter, OllamaAdapter, DEFAULT_MODEL_BY_PROVIDER, NonRetryableError, permanentError, ProviderRefusalError, } from "./providers/index.js";
package/dist/jobs.d.ts CHANGED
@@ -31,7 +31,6 @@
31
31
  * adopts it on an active job and cancels it otherwise (the stop-flag-first
32
32
  * rule). The sweep never throws.
33
33
  */
34
- import { BATCH_SUBMIT_INTERRUPTED_ERROR } from "./history.js";
35
34
  import { type JobWakeRule } from "./job-wake.js";
36
35
  import { type SleepReading } from "./readiness.js";
37
36
  import type { Scheduler } from "./scheduler.js";
@@ -199,7 +198,7 @@ export declare const JOB_AUTO_PAUSE_PREFIX = "auto: ";
199
198
  /** The error line of an auto-pause reason, or undefined when the job was not paused by its failures. */
200
199
  export declare function jobAutoPauseReason(pauseReason: string | undefined): string | undefined;
201
200
  export declare const JOB_INTERRUPTED_ERROR = "interrupted: the tick stopped during the run";
202
- export { BATCH_SUBMIT_INTERRUPTED_ERROR };
201
+ export { BATCH_LOST_AFTER_MS, BATCH_SUBMIT_INTERRUPTED_ERROR, batchLostError, isBatchLostError } from "./history.js";
203
202
  /** What an end reason says: `its end date (<until>) passed` or `its runs are done`. */
204
203
  export declare function jobEndText(reason: JobEndReason | undefined, until?: string): string;
205
204
  /**
@@ -216,6 +215,16 @@ export declare function jobWakeSession(job: Pick<JobRecord, "wake" | "originSess
216
215
  export declare function jobRunLimits(job: JobRecord, scheduler?: Scheduler): ResolvedRunLimits;
217
216
  /** True for an extra run's id (`<job>~<seq>x`, which run now adds) or one of its retries (`...xr`, `...xr2`). */
218
217
  export declare function isExtraRunId(taskId: string): boolean;
218
+ /** Meta key of the job runs whose failure became final when their retry was cancelled: a JSON list of task ids, which the channel emit claims. */
219
+ export declare const JOB_FINAL_FAILURES_META_KEY = "job_final_failures";
220
+ /** The task ids in a {@link JOB_FINAL_FAILURES_META_KEY} value; anything unreadable is an empty list. */
221
+ export declare function jobFinalFailureIds(raw: string | undefined): string[];
222
+ /**
223
+ * Add `taskId` to the {@link JOB_FINAL_FAILURES_META_KEY} list by
224
+ * compare-and-set (the newest {@link JOB_FINAL_FAILURES_MAX} are kept). True
225
+ * when it is on the list now; false when other writers won every try.
226
+ */
227
+ export declare function queueJobFinalFailure(store: Pick<TaskStore, "getMeta" | "setMetaIf">, taskId: string): boolean;
219
228
  /**
220
229
  * The job sweep (KTD2): for every job, record the outcome of its finished
221
230
  * occurrence and keep one live occurrence per active job. Never throws.
package/dist/jobs.js CHANGED
@@ -34,7 +34,7 @@
34
34
  import { randomBytes } from "node:crypto";
35
35
  import { DEFAULT_MODEL_BY_PROVIDER } from "./providers/defaults.js";
36
36
  import { wakeError } from "./handoff.js";
37
- import { BATCH_SUBMIT_INTERRUPTED_ERROR, deriveTitle, taskResultText } from "./history.js";
37
+ import { BATCH_SUBMIT_INTERRUPTED_ERROR, deriveTitle, isBatchLostError, taskResultText } from "./history.js";
38
38
  import { JOB_WAKE_FORMS, matchWake, wakePatternError } from "./job-wake.js";
39
39
  import { isCalendarAnchored, JobScheduleError, nextOccurrence, untilBoundMs, untilText, validateJobSchedule } from "./job-cadence.js";
40
40
  import { sleptBetween } from "./readiness.js";
@@ -159,7 +159,7 @@ const EXTRA_RUN_WINDOW_MS = 24 * 60 * MINUTE_MS;
159
159
  const RUN_NOW_SOON_MS = 5 * MINUTE_MS;
160
160
  export const JOB_INTERRUPTED_ERROR = "interrupted: the tick stopped during the run";
161
161
  // The Batch submit marker lives in history.ts (`taskActions` reads it), so history.ts imports nothing from this module.
162
- export { BATCH_SUBMIT_INTERRUPTED_ERROR };
162
+ export { BATCH_LOST_AFTER_MS, BATCH_SUBMIT_INTERRUPTED_ERROR, batchLostError, isBatchLostError } from "./history.js";
163
163
  const CORRUPT = "corrupt template";
164
164
  function ledgerOf(scheduler) {
165
165
  const store = scheduler.ledger();
@@ -392,10 +392,10 @@ function retryOrdinal(taskId) {
392
392
  export function isExtraRunId(taskId) {
393
393
  return /~\d+x(?:r\d*)?$/.test(taskId);
394
394
  }
395
- /** The id of retry `k` of the slot of `taskId`: `<job>~<seq>r`, then `r2`, `r3`, ... */
395
+ /** The id of retry `k` of the slot of `taskId`: the slot's own run for 0, `<job>~<seq>r`, then `r2`, `r3`, ... */
396
396
  function retryIdOf(taskId, k) {
397
397
  const base = taskId.replace(/r\d*$/, "");
398
- return k === 1 ? `${base}r` : `${base}r${k}`;
398
+ return k === 0 ? base : k === 1 ? `${base}r` : `${base}r${k}`;
399
399
  }
400
400
  function firstLine(text, max = 200) {
401
401
  return (text ?? "").split("\n")[0].slice(0, max);
@@ -414,8 +414,12 @@ function dispatchedEvent(scheduler, taskId) {
414
414
  * event's steps and its error give (a failure after the command step is
415
415
  * `after_command`, the Batch submit marker `batch_submit_interrupted`,
416
416
  * anything else `transient`, as those rows always got their one retry).
417
+ * A lost Batch row is `permanent` whatever its event says: its batch may
418
+ * have been billed, so the slot gets no retry run.
417
419
  */
418
420
  function failureClassOf(scheduler, row) {
421
+ if (isBatchLostError(row.error))
422
+ return "permanent";
419
423
  const events = scheduler.listTaskEvents(row.taskId);
420
424
  let details = {};
421
425
  for (let i = events.length - 1; i >= 0; i--) {
@@ -506,8 +510,6 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
506
510
  await sweepExtraRun(scheduler, jobId, now, result, opts);
507
511
  /** Rows this call inserted: cleaned up when every job write misses. */
508
512
  const inserted = [];
509
- /** Runs whose notice this call decided: a second attempt does not match the pattern again. */
510
- const notices = new Set();
511
513
  for (let attempt = 0; attempt < 3; attempt++) {
512
514
  const job = store.getJob(jobId);
513
515
  // An ended job keeps no occurrence; its extra run was the step above.
@@ -663,13 +665,25 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
663
665
  }
664
666
  }
665
667
  next.pendingTaskId = taskId;
666
- // The run's session notice goes in before the job write, so a reader
667
- // never sees the job ended (or moved on) without it (KTD9).
668
- if (tracked && successor !== "retry")
669
- recordJobNotice(store, job, tracked, slotEnded, endReason !== undefined, result, notices);
670
668
  // A miss: another writer moved the job meanwhile. The next pass adopts
671
669
  // the insert on an active job, or cancels it on an inactive one.
672
670
  if (store.updateJobIf(next, job.revision)) {
671
+ // The session notice follows the job write: a write that lost decides nothing.
672
+ const cancelledRetry = retryId && edited.includes(retryId) ? store.get(retryId) : tracked;
673
+ const failure = cancelledRetry && failedBeforeCancelledRetry(scheduler, store, cancelledRetry);
674
+ // A run has one notice per finish: the run whose failure became final here carries `failed` beside `ended`.
675
+ const failedHere = (row) => row.taskId === failure?.taskId;
676
+ if (tracked && successor !== "retry") {
677
+ recordJobNotice(store, job, tracked, slotEnded || failedHere(tracked), endReason !== undefined, result);
678
+ }
679
+ else if (!tracked && endReason) {
680
+ // A paused job that ends by its date or count has no tracked row: the notice names its newest finished row.
681
+ const newest = newestFinishedRow(store, job);
682
+ if (newest)
683
+ recordJobNotice(store, job, newest, failedHere(newest), true, result);
684
+ }
685
+ if (failure)
686
+ recordFinalFailure(store, job, failure, result);
673
687
  if (endReason) {
674
688
  result.ended.push(jobId);
675
689
  // The sweep skips an ended job, so no later pass cancels a stray pending row.
@@ -727,7 +741,6 @@ function stoppedReason(status) {
727
741
  async function sweepExtraRun(scheduler, jobId, now, result, opts) {
728
742
  const store = ledgerOf(scheduler);
729
743
  const nowMs = now.getTime();
730
- const notices = new Set();
731
744
  for (let attempt = 0; attempt < 3; attempt++) {
732
745
  const job = store.getJob(jobId);
733
746
  if (!job || job.pauseReason === CORRUPT)
@@ -757,6 +770,8 @@ async function sweepExtraRun(scheduler, jobId, now, result, opts) {
757
770
  if (!job.extraTaskId && strays.length === 0)
758
771
  return;
759
772
  const next = { ...job, extraTaskId: undefined, updatedAt: now.toISOString() };
773
+ /** The extra run finished for good: completed, or failed with no retry. */
774
+ let finished;
760
775
  if (extra) {
761
776
  recordLastRun(store, next, extra);
762
777
  const used = retryOrdinal(extra.taskId);
@@ -770,7 +785,7 @@ async function sweepExtraRun(scheduler, jobId, now, result, opts) {
770
785
  next.extraTaskId = retryId;
771
786
  }
772
787
  else if (extra.status === "completed" || extra.status === "failed") {
773
- recordJobNotice(store, job, extra, true, false, result, notices);
788
+ finished = extra;
774
789
  }
775
790
  }
776
791
  if (next.extraTaskId === undefined && strays.length > 0) {
@@ -779,8 +794,15 @@ async function sweepExtraRun(scheduler, jobId, now, result, opts) {
779
794
  if (PENDING.has(t.status))
780
795
  cancelOccurrence(scheduler, t.taskId, jobId, "duplicate");
781
796
  }
782
- if (store.updateJobIf(next, job.revision))
797
+ if (store.updateJobIf(next, job.revision)) {
798
+ // Notices follow the job write: a run that got no retry, or the failure a cancelled retry leaves final.
799
+ if (finished)
800
+ recordJobNotice(store, job, finished, true, false, result);
801
+ const failure = extra && failedBeforeCancelledRetry(scheduler, store, extra);
802
+ if (failure)
803
+ recordFinalFailure(store, job, failure, result);
783
804
  return;
805
+ }
784
806
  }
785
807
  result.messages.push(`job ${jobId}: the job row kept changing; its extra run is left for the next sweep`);
786
808
  }
@@ -793,11 +815,10 @@ async function sweepExtraRun(scheduler, jobId, now, result, opts) {
793
815
  * `matched`, while the job is active. A run of another session (made before a rebind), or of a job
794
816
  * no longer bound, gets nothing.
795
817
  */
796
- function recordJobNotice(store, job, run, slotEnded, ended, result, decided) {
818
+ function recordJobNotice(store, job, run, slotEnded, ended, result) {
797
819
  const session = jobWakeSession(job);
798
- if (!session || run.originSessionId !== session || decided.has(run.taskId) || !run.completedAt)
820
+ if (!session || run.originSessionId !== session || !run.completedAt)
799
821
  return;
800
- decided.add(run.taskId);
801
822
  const reasons = [];
802
823
  const failed = run.status === "failed" && slotEnded;
803
824
  if (failed)
@@ -820,6 +841,76 @@ function recordJobNotice(store, job, run, slotEnded, ended, result, decided) {
820
841
  if (store.recordSessionNotice(run.taskId, { reasons, wake }))
821
842
  result.sessionNotices.push(run.taskId);
822
843
  }
844
+ /**
845
+ * The failed run whose planned retry `row` is, when `row` was cancelled
846
+ * before it ran (the job was paused, edited or removed, or the retry was
847
+ * skipped); otherwise undefined. A failed run with a planned retry sends
848
+ * nothing, so with the retry gone its failure is the final outcome.
849
+ */
850
+ function failedBeforeCancelledRetry(scheduler, store, row) {
851
+ const k = retryOrdinal(row.taskId);
852
+ if (row.status !== "cancelled" || k === 0 || cancelReason(scheduler, row.taskId) === "duplicate")
853
+ return undefined;
854
+ const failed = store.get(retryIdOf(row.taskId, k - 1));
855
+ return failed?.status === "failed" ? failed : undefined;
856
+ }
857
+ /** Meta key of the job runs whose failure became final when their retry was cancelled: a JSON list of task ids, which the channel emit claims. */
858
+ export const JOB_FINAL_FAILURES_META_KEY = "job_final_failures";
859
+ /** Queued final failures kept at most; the oldest go first. */
860
+ const JOB_FINAL_FAILURES_MAX = 200;
861
+ /** The task ids in a {@link JOB_FINAL_FAILURES_META_KEY} value; anything unreadable is an empty list. */
862
+ export function jobFinalFailureIds(raw) {
863
+ try {
864
+ const v = JSON.parse(raw ?? "[]");
865
+ return Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
866
+ }
867
+ catch {
868
+ return [];
869
+ }
870
+ }
871
+ /**
872
+ * A failed run whose retry was cancelled: its session notice (`failed`)
873
+ * and its channel notice, queued under {@link JOB_FINAL_FAILURES_META_KEY}
874
+ * by compare-and-set for the next emit.
875
+ */
876
+ function recordFinalFailure(store, job, run, result) {
877
+ recordJobNotice(store, job, run, true, false, result);
878
+ result.messages.push(queueJobFinalFailure(store, run.taskId)
879
+ ? `job ${job.jobId}: ${run.taskId} failed for good: its retry was cancelled`
880
+ : `job ${job.jobId}: ${run.taskId}: the final failure notice could not be queued`);
881
+ }
882
+ /**
883
+ * Add `taskId` to the {@link JOB_FINAL_FAILURES_META_KEY} list by
884
+ * compare-and-set (the newest {@link JOB_FINAL_FAILURES_MAX} are kept). True
885
+ * when it is on the list now; false when other writers won every try.
886
+ */
887
+ export function queueJobFinalFailure(store, taskId) {
888
+ for (let attempt = 0; attempt < 3; attempt++) {
889
+ const raw = store.getMeta(JOB_FINAL_FAILURES_META_KEY);
890
+ const ids = jobFinalFailureIds(raw);
891
+ if (ids.includes(taskId))
892
+ return true;
893
+ if (store.setMetaIf(JOB_FINAL_FAILURES_META_KEY, raw, JSON.stringify([...ids, taskId].slice(-JOB_FINAL_FAILURES_MAX))))
894
+ return true;
895
+ }
896
+ return false;
897
+ }
898
+ /**
899
+ * The bound session's row of the job that finished last (a run, or an
900
+ * occurrence a pause or skip cancelled) and has no notice for that finish
901
+ * yet, so an `ended` notice written on it is not dropped; undefined when
902
+ * none.
903
+ */
904
+ function newestFinishedRow(store, job) {
905
+ const session = jobWakeSession(job);
906
+ if (!session)
907
+ return undefined;
908
+ const finished = store
909
+ .list({ jobId: job.jobId })
910
+ .filter((row) => row.completedAt !== undefined && row.originSessionId === session)
911
+ .sort((a, b) => (a.completedAt < b.completedAt ? 1 : a.completedAt > b.completedAt ? -1 : 0));
912
+ return finished.find((row) => store.sessionNoticeOf(row) === undefined);
913
+ }
823
914
  /** The `until` bound of a job in ms, or undefined when it has none or the stored text does not parse. */
824
915
  function untilBound(job) {
825
916
  if (job.until === undefined)
package/dist/notify.d.ts CHANGED
@@ -52,8 +52,9 @@ export declare function clip(text: string, max: number): string;
52
52
  export declare function firstErrorLine(error: string | undefined, max?: number): string | undefined;
53
53
  /**
54
54
  * Notification title and body for a finished task: the task title (or id),
55
- * a redacted one-line preview of the result (completed) or the first line
56
- * of the error (failed), the grams, and the `tidegap queue show <id>` command.
55
+ * a redacted one-line preview of the result (completed: its summary when a
56
+ * summarize step wrote one, else its text) or the first line of the error
57
+ * (failed), the grams, and the `tidegap queue show <id>` command.
57
58
  */
58
59
  export declare function taskNotificationContent(record: Pick<TaskRecord<unknown>, "taskId" | "status" | "title" | "error" | "result" | "receipt">): {
59
60
  title: string;
package/dist/notify.js CHANGED
@@ -109,8 +109,9 @@ function grams(receipt) {
109
109
  }
110
110
  /**
111
111
  * Notification title and body for a finished task: the task title (or id),
112
- * a redacted one-line preview of the result (completed) or the first line
113
- * of the error (failed), the grams, and the `tidegap queue show <id>` command.
112
+ * a redacted one-line preview of the result (completed: its summary when a
113
+ * summarize step wrote one, else its text) or the first line of the error
114
+ * (failed), the grams, and the `tidegap queue show <id>` command.
114
115
  */
115
116
  export function taskNotificationContent(record) {
116
117
  const name = clip(oneLine(record.title ?? "") || record.taskId, 80);
@@ -122,8 +123,8 @@ export function taskNotificationContent(record) {
122
123
  };
123
124
  }
124
125
  const r = record.result;
125
- const text = r && typeof r === "object" && typeof r.text === "string" ? r.text : "";
126
- const preview = clip(oneLine(text), NOTIFY_PREVIEW_CHARS);
126
+ const field = (v) => (typeof v === "string" ? oneLine(v) : "");
127
+ const preview = clip((r && typeof r === "object" && (field(r.summary) || field(r.text))) || "", NOTIFY_PREVIEW_CHARS);
127
128
  return {
128
129
  title: `Tidegap: done: ${name}`,
129
130
  body: `${preview ? `${preview}\n` : ""}${grams(record.receipt)} · ${show}`,
package/dist/redact.d.ts CHANGED
@@ -47,12 +47,15 @@ export declare function redactPrompt(prompt: string, patterns: string[] | undefi
47
47
  export declare function redactBodyJson(bodyJson: string | undefined): string | undefined;
48
48
  /** Shortest secret value {@link scrubValues} replaces; shorter ones would mangle ordinary text. */
49
49
  export declare const SCRUB_MIN_LENGTH = 4;
50
+ /** Shortest secret value whose encoded forms {@link scrubValues} also replaces (KTD10). */
51
+ export declare const SCRUB_ENCODED_MIN_LENGTH = 8;
50
52
  /**
51
- * Replace every exact occurrence of each value with `[redacted]` (job
52
- * secrets, KTD12). Longest value first, so a value that contains another is
53
- * replaced whole. Values shorter than {@link SCRUB_MIN_LENGTH} are left
54
- * alone. Literal matching only: no regex is built from a value. Transformed
55
- * forms (base64, URL-encoding) are not caught.
53
+ * Replace every occurrence of each value with `[redacted]` (job secrets,
54
+ * KTD12), and of its encoded forms (base64, URL-safe base64,
55
+ * percent-encoding, see {@link secretForms}) for a value of {@link SCRUB_ENCODED_MIN_LENGTH} or more.
56
+ * Longest form first, so a form that contains another is replaced whole.
57
+ * Values shorter than {@link SCRUB_MIN_LENGTH} are left alone. Literal
58
+ * matching only: no regex is built from a value.
56
59
  */
57
60
  export declare function scrubValues(text: string, values: readonly string[]): string;
58
61
  /**
package/dist/redact.js CHANGED
@@ -125,17 +125,49 @@ export function redactBodyJson(bodyJson) {
125
125
  }
126
126
  /** Shortest secret value {@link scrubValues} replaces; shorter ones would mangle ordinary text. */
127
127
  export const SCRUB_MIN_LENGTH = 4;
128
+ /** Shortest secret value whose encoded forms {@link scrubValues} also replaces (KTD10). */
129
+ export const SCRUB_ENCODED_MIN_LENGTH = 8;
128
130
  /**
129
- * Replace every exact occurrence of each value with `[redacted]` (job
130
- * secrets, KTD12). Longest value first, so a value that contains another is
131
- * replaced whole. Values shorter than {@link SCRUB_MIN_LENGTH} are left
132
- * alone. Literal matching only: no regex is built from a value. Transformed
133
- * forms (base64, URL-encoding) are not caught.
131
+ * The forms of a secret value {@link scrubValues} replaces: the value, and
132
+ * for a value of {@link SCRUB_ENCODED_MIN_LENGTH} or more its standard and
133
+ * URL-safe base64 (with and without padding) and its percent-encoding as
134
+ * `encodeURIComponent`, RFC 3986 (`!'()*` encoded too) and a form body (`+`
135
+ * for a space) write it, each in upper and lower case hex. The forms come
136
+ * from the known value; no pattern guesses at an encoding.
137
+ */
138
+ function secretForms(value) {
139
+ if (value.length < SCRUB_ENCODED_MIN_LENGTH)
140
+ return [value];
141
+ const bytes = Buffer.from(value, "utf8");
142
+ const b64 = bytes.toString("base64");
143
+ // Unpadded base64 is the first ceil(4n/3) characters; no regex on the padding.
144
+ const forms = [value, b64, b64.slice(0, Math.ceil((bytes.length * 4) / 3)), bytes.toString("base64url")];
145
+ let percent;
146
+ try {
147
+ percent = encodeURIComponent(value);
148
+ }
149
+ catch {
150
+ // A lone surrogate has no UTF-8 form: there is no percent form to find, and the scrub must not throw.
151
+ return forms;
152
+ }
153
+ const strict = percent.replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
154
+ const formBody = new URLSearchParams({ v: value }).toString().slice(2);
155
+ for (const p of [percent, strict, formBody])
156
+ forms.push(p, p.replace(/%[0-9A-F]{2}/g, (h) => h.toLowerCase()));
157
+ return forms;
158
+ }
159
+ /**
160
+ * Replace every occurrence of each value with `[redacted]` (job secrets,
161
+ * KTD12), and of its encoded forms (base64, URL-safe base64,
162
+ * percent-encoding, see {@link secretForms}) for a value of {@link SCRUB_ENCODED_MIN_LENGTH} or more.
163
+ * Longest form first, so a form that contains another is replaced whole.
164
+ * Values shorter than {@link SCRUB_MIN_LENGTH} are left alone. Literal
165
+ * matching only: no regex is built from a value.
134
166
  */
135
167
  export function scrubValues(text, values) {
136
- const sorted = [...new Set(values)].filter((v) => v.length >= SCRUB_MIN_LENGTH).sort((a, b) => b.length - a.length);
168
+ const forms = new Set(values.filter((v) => v.length >= SCRUB_MIN_LENGTH).flatMap(secretForms));
137
169
  let out = text;
138
- for (const v of sorted)
170
+ for (const v of [...forms].sort((a, b) => b.length - a.length))
139
171
  out = out.split(v).join("[redacted]");
140
172
  return out;
141
173
  }
@@ -836,6 +836,8 @@ export declare class Scheduler {
836
836
  * file) and mark completed.
837
837
  * - failed/expired: mark failed with the provider error (retryTask
838
838
  * re-dispatches sync via the expedite path).
839
+ * - a poll error: back to "submitted"; a day past the deadline, failed
840
+ * for good as lost (`batchLostError`).
839
841
  */
840
842
  private pollBatch;
841
843
  /**
package/dist/scheduler.js CHANGED
@@ -26,7 +26,7 @@ import { deferRetryAt } from "./providers/defer.js";
26
26
  import { postponeOptions, resolveLimitReset, resolvePostpone, taskProvider, writeLimitResetHint, } from "./postpone.js";
27
27
  import { candidateId, parseCandidates, previewRouting, scoreCandidates, } from "./routing.js";
28
28
  import { capHistory, deriveTitle, displayTitle, isRepeating, taskActions, taskHistory } from "./history.js";
29
- import { BATCH_SUBMIT_INTERRUPTED_ERROR, JOB_CAPS_KEYS, JOB_INTERRUPTED_ERROR } from "./jobs.js";
29
+ import { BATCH_LOST_AFTER_MS, BATCH_SUBMIT_INTERRUPTED_ERROR, batchLostError, isBatchLostError, JOB_CAPS_KEYS, JOB_INTERRUPTED_ERROR } from "./jobs.js";
30
30
  import { attemptNumber, CAPS_VERSION, capValueError, classifyFailure, failureFactsOf, finalFailureError, isRetryableFailure, loadRunLimitSettings, planRetry, resolveTaskRunLimits, retryPolicyOf, runLimitsDetails, taskRunLimitsView, } from "./run-limits.js";
31
31
  import { resolveQuotaDeadline } from "./quota.js";
32
32
  import { tickDispatch } from "./readiness.js";
@@ -1054,7 +1054,7 @@ export class Scheduler {
1054
1054
  // eslint-disable-next-line no-console
1055
1055
  console.warn(`[tidegap/scheduler] task ${taskId}: could not record a progress event (this and later failed lines are dropped): ${describeErr(err)}`);
1056
1056
  }
1057
- }, { existing: () => store.countTaskEvents(taskId, "progress") });
1057
+ }, { existing: () => store.lastProgressSeq(taskId) });
1058
1058
  }
1059
1059
  /** `{ tick }` for a `dispatched` event under the tick lock; else nothing. */
1060
1060
  tickDetails() {
@@ -2862,6 +2862,8 @@ export class Scheduler {
2862
2862
  * file) and mark completed.
2863
2863
  * - failed/expired: mark failed with the provider error (retryTask
2864
2864
  * re-dispatches sync via the expedite path).
2865
+ * - a poll error: back to "submitted"; a day past the deadline, failed
2866
+ * for good as lost (`batchLostError`).
2865
2867
  */
2866
2868
  async pollBatch(record, adapters) {
2867
2869
  let spec;
@@ -2892,6 +2894,14 @@ export class Scheduler {
2892
2894
  poll = await retryWithBackoff(() => adapter.retrieveBatch(batchId));
2893
2895
  }
2894
2896
  catch (err) {
2897
+ // A day past the deadline no live batch answers (KTD2): the row fails
2898
+ // for good with the lost marker, and no path runs it again.
2899
+ const deadline = Date.parse(record.deadline ?? "");
2900
+ if (Number.isFinite(deadline) && Date.now() - deadline > BATCH_LOST_AFTER_MS) {
2901
+ // eslint-disable-next-line no-console
2902
+ console.warn(`[tidegap/scheduler] tick: retrieveBatch failed for ${record.taskId} a day past its deadline (${describeErr(err)}); failing it as lost`);
2903
+ return this.failRun(record, { error: batchLostError(batchId), facts: { permanent: true } });
2904
+ }
2895
2905
  // A transient poll error must not fail a genuinely in-flight batch:
2896
2906
  // return it to "submitted" and let a later tick retry.
2897
2907
  this.writeIf(record, { ...record, status: "submitted" }, ["running"]);
@@ -3097,8 +3107,10 @@ function jobDispatchOptions(record, spec, limits) {
3097
3107
  }
3098
3108
  /**
3099
3109
  * The usage limit a dispatch can hit: its provider and model. A command
3100
- * job's limit is its summarize step's, so a limit hit there defers the
3101
- * other calls to that provider this tick, not every command job.
3110
+ * job's limit is its summarize step's: when an earlier call this tick hit
3111
+ * that limit, the command job waits with it, not every command job. A
3112
+ * limit its own summarize step hits completes the run with no summary and
3113
+ * defers nothing.
3102
3114
  */
3103
3115
  function deferKeyOf(spec) {
3104
3116
  if (spec.provider === "command" && spec.summarize) {
@@ -3398,6 +3410,10 @@ function retryRefusal(action, record) {
3398
3410
  if (!record.bodyJson) {
3399
3411
  throw new TaskActionError(`${action}: task ${taskId} is closure-based; only provider-call tasks can be retried`);
3400
3412
  }
3413
+ if (isBatchLostError(record.error)) {
3414
+ throw new TaskActionError(`${action}: task ${taskId} lost its batch: its poll still failed a day after the deadline, and the batch may have run and been billed; ` +
3415
+ "a retry could run and bill it twice, so check the provider's batch list and enqueue the task again only if the batch has no result");
3416
+ }
3401
3417
  if (record.jobId) {
3402
3418
  // The job sweep already recorded this failure and queued a retry or
3403
3419
  // the next run; a second run of the same slot would go unrecorded.
@@ -169,6 +169,13 @@ export declare class TaskStore {
169
169
  recordEvent(taskId: string, event: TaskEventInput, opts?: {
170
170
  busyMs?: number;
171
171
  }): void;
172
+ /**
173
+ * The `seq` a progress recorder continues after (P37): the highest `seq`
174
+ * of the task's progress events, or their count when that is higher (an
175
+ * event without a number). A dropped line leaves a gap, so the count alone
176
+ * would repeat a stored `seq` after a tick restart. 0 for none.
177
+ */
178
+ lastProgressSeq(taskId: string): number;
172
179
  /** How many events of `kind` a task has: one `COUNT(*)`, no rows read. */
173
180
  countTaskEvents(taskId: string, kind: TaskEventKind): number;
174
181
  /**
@@ -359,9 +366,10 @@ export declare class TaskStore {
359
366
  /** Insert a new job row. Throws when the id exists. */
360
367
  insertJob(job: JobRecord): void;
361
368
  getJob(jobId: string): JobRecord | undefined;
362
- /** Jobs, oldest first; `status` limits the list to one or several statuses. */
369
+ /** Jobs, oldest first; `status` limits the list to one or several statuses, `updatedSince` to jobs written at or after that instant. */
363
370
  listJobs(filter?: {
364
371
  status?: JobStatus | readonly JobStatus[];
372
+ updatedSince?: string;
365
373
  }): JobRecord[];
366
374
  /**
367
375
  * Compare-and-set job write: store the mutable columns of `next` only while
@@ -241,6 +241,9 @@ function ensureColumns(db) {
241
241
  addColumn("origin_session_id", "TEXT");
242
242
  addColumn("not_before", "TEXT");
243
243
  db.exec(`CREATE INDEX IF NOT EXISTS tasks_series_idx ON tasks(series_id)`);
244
+ // The session-notice query (`listSessionNotices`, KTD9). Additive: older
245
+ // readers ignore it; the Python core creates the same index.
246
+ db.exec(`CREATE INDEX IF NOT EXISTS tasks_session_notice_idx ON tasks(origin_session_id, completed_at)`);
244
247
  // Floating recurring jobs: the job a row is an occurrence of. No backfill:
245
248
  // NULL means "not a job occurrence".
246
249
  addColumn("job_id", "TEXT");
@@ -657,13 +660,39 @@ export class TaskStore {
657
660
  return;
658
661
  }
659
662
  this.db.exec(`PRAGMA busy_timeout = ${bound}`);
663
+ let failed = false;
660
664
  try {
661
665
  this.tx(() => this.insertEvent(taskId, event));
662
666
  }
667
+ catch (err) {
668
+ failed = true;
669
+ throw err;
670
+ }
663
671
  finally {
664
- this.db.exec(`PRAGMA busy_timeout = ${own}`);
672
+ // Its own try: a failing restore must not replace the write's error (SQLITE_BUSY).
673
+ try {
674
+ this.db.exec(`PRAGMA busy_timeout = ${own}`);
675
+ }
676
+ catch (restoreErr) {
677
+ if (!failed)
678
+ throw restoreErr;
679
+ }
665
680
  }
666
681
  }
682
+ /**
683
+ * The `seq` a progress recorder continues after (P37): the highest `seq`
684
+ * of the task's progress events, or their count when that is higher (an
685
+ * event without a number). A dropped line leaves a gap, so the count alone
686
+ * would repeat a stored `seq` after a tick restart. 0 for none.
687
+ */
688
+ lastProgressSeq(taskId) {
689
+ const row = this.db
690
+ .prepare(`SELECT COUNT(*) AS n,
691
+ MAX(CASE WHEN json_valid(details) THEN CAST(json_extract(details, '$.seq') AS INTEGER) END) AS seq
692
+ FROM task_events WHERE task_id = ? AND kind = 'progress'`)
693
+ .get(taskId);
694
+ return Math.max(Number(row?.["n"] ?? 0), Number(row?.["seq"] ?? 0));
695
+ }
667
696
  /** How many events of `kind` a task has: one `COUNT(*)`, no rows read. */
668
697
  countTaskEvents(taskId, kind) {
669
698
  const row = this.db.prepare("SELECT COUNT(*) AS n FROM task_events WHERE task_id = ? AND kind = ?").get(taskId, kind);
@@ -1220,13 +1249,18 @@ export class TaskStore {
1220
1249
  const row = this.db.prepare(`SELECT * FROM jobs WHERE job_id = ?`).get(jobId);
1221
1250
  return row ? rowToJob(row) : undefined;
1222
1251
  }
1223
- /** Jobs, oldest first; `status` limits the list to one or several statuses. */
1252
+ /** Jobs, oldest first; `status` limits the list to one or several statuses, `updatedSince` to jobs written at or after that instant. */
1224
1253
  listJobs(filter = {}) {
1225
1254
  const statuses = filter.status === undefined ? [] : typeof filter.status === "string" ? [filter.status] : [...filter.status];
1226
- const clause = statuses.length > 0 ? ` WHERE status IN (${statuses.map(() => "?").join(", ")})` : "";
1255
+ const where = [];
1256
+ if (statuses.length > 0)
1257
+ where.push(`status IN (${statuses.map(() => "?").join(", ")})`);
1258
+ if (filter.updatedSince !== undefined)
1259
+ where.push("updated_at >= ?");
1260
+ const clause = where.length > 0 ? ` WHERE ${where.join(" AND ")}` : "";
1227
1261
  return this.db
1228
1262
  .prepare(`SELECT * FROM jobs${clause} ORDER BY created_at ASC, job_id ASC`)
1229
- .all(...statuses)
1263
+ .all(...statuses, ...(filter.updatedSince !== undefined ? [filter.updatedSince] : []))
1230
1264
  .map(rowToJob);
1231
1265
  }
1232
1266
  /**
@@ -104,8 +104,9 @@ export interface ProgressRecorder {
104
104
  * cleaned by {@link progressLine}. A line that comes before its slot waits
105
105
  * for it, and a newer line takes its place, so the event shows the newest
106
106
  * line. `write` gets the details of each event (`line`, `seq`); `seq`
107
- * counts the task's progress events from 1, after the `existing` ones (read
108
- * once, when the first event is due). The caller scrubs secrets from each
107
+ * counts the task's progress events from 1, after `existing`, the highest
108
+ * `seq` the task already holds (read once, when the first event is due), so
109
+ * a restarted run never repeats one. The cap counts from it too. The caller scrubs secrets from each
109
110
  * line first. Never throws.
110
111
  */
111
112
  export declare function createProgressRecorder(write: (details: {
@@ -287,8 +287,9 @@ export function progressLine(raw) {
287
287
  * cleaned by {@link progressLine}. A line that comes before its slot waits
288
288
  * for it, and a newer line takes its place, so the event shows the newest
289
289
  * line. `write` gets the details of each event (`line`, `seq`); `seq`
290
- * counts the task's progress events from 1, after the `existing` ones (read
291
- * once, when the first event is due). The caller scrubs secrets from each
290
+ * counts the task's progress events from 1, after `existing`, the highest
291
+ * `seq` the task already holds (read once, when the first event is due), so
292
+ * a restarted run never repeats one. The cap counts from it too. The caller scrubs secrets from each
292
293
  * line first. Never throws.
293
294
  */
294
295
  export function createProgressRecorder(write, opts = {}) {
@@ -432,7 +432,6 @@ export const TOOL_SURFACE = [
432
432
  name: "until",
433
433
  kind: "string",
434
434
  optional: true,
435
- hosts: ["mcp"],
436
435
  description: "When a job ends: a day 'YYYY-MM-DD' (the last local day in time_zone a run may start, e.g. '2026-11-17' for \"for 5 days\") or an ISO instant with Z or an offset (a run must start before it). The job then ends by itself and sends one final notice. Only with a job repeat; omit for a job that runs until it is removed.",
437
436
  },
438
437
  {
@@ -442,7 +441,6 @@ export const TOOL_SURFACE = [
442
441
  min: 1,
443
442
  max: 1000,
444
443
  optional: true,
445
- hosts: ["mcp"],
446
444
  description: "How many runs a job makes before it ends by itself, 1 to 1000, e.g. 5 for \"five times\". A retry is part of its run; a skipped run does not count. Only with a job repeat; with until too, the job ends at whichever comes first. Omit for a job that runs until it is removed.",
447
445
  },
448
446
  {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tidegap/core",
3
- "version": "0.27.0",
3
+ "version": "0.28.0",
4
4
  "description": "Carbon-aware scheduling for agentic AI workflows — core TypeScript library.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Vitalii Borovyk",
@@ -54,8 +54,8 @@
54
54
  "devDependencies": {
55
55
  "@anthropic-ai/sdk": "^0.137.0",
56
56
  "@types/better-sqlite3": "^7.6.13",
57
- "@types/node": "^22.20.5",
58
- "openai": "^7.57.0",
57
+ "@types/node": "^22.20.7",
58
+ "openai": "^7.65.0",
59
59
  "typescript": "^5.6.3",
60
60
  "vitest": "^4.1.12"
61
61
  },