@cloudhal/schedules 0.0.0-stage → 0.1.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.
Files changed (51) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +103 -2
  3. package/dist/src/automation.d.ts +82 -0
  4. package/dist/src/automation.js +199 -0
  5. package/dist/src/budget-meter.d.ts +58 -0
  6. package/dist/src/budget-meter.js +130 -0
  7. package/dist/src/budget.d.ts +41 -0
  8. package/dist/src/budget.js +76 -0
  9. package/dist/src/builtins.d.ts +132 -0
  10. package/dist/src/builtins.js +473 -0
  11. package/dist/src/engine.d.ts +16 -0
  12. package/dist/src/engine.js +30 -0
  13. package/dist/src/errors.d.ts +22 -0
  14. package/dist/src/errors.js +56 -0
  15. package/dist/src/feed-check.d.ts +56 -0
  16. package/dist/src/feed-check.js +365 -0
  17. package/dist/src/findings.d.ts +185 -0
  18. package/dist/src/findings.js +287 -0
  19. package/dist/src/ids.d.ts +24 -0
  20. package/dist/src/ids.js +96 -0
  21. package/dist/src/index.d.ts +24 -0
  22. package/dist/src/index.js +24 -0
  23. package/dist/src/instant.d.ts +19 -0
  24. package/dist/src/instant.js +50 -0
  25. package/dist/src/notify.d.ts +50 -0
  26. package/dist/src/notify.js +60 -0
  27. package/dist/src/recurrence.d.ts +155 -0
  28. package/dist/src/recurrence.js +939 -0
  29. package/dist/src/release-when.d.ts +23 -0
  30. package/dist/src/release-when.js +55 -0
  31. package/dist/src/release.d.ts +198 -0
  32. package/dist/src/release.js +552 -0
  33. package/dist/src/scheduler.d.ts +490 -0
  34. package/dist/src/scheduler.js +1343 -0
  35. package/dist/src/sql/finish.d.ts +32 -0
  36. package/dist/src/sql/finish.js +103 -0
  37. package/dist/src/sql/index.d.ts +6 -0
  38. package/dist/src/sql/index.js +15 -0
  39. package/dist/src/sql/rows.d.ts +125 -0
  40. package/dist/src/sql/rows.js +297 -0
  41. package/dist/src/sql/store.d.ts +467 -0
  42. package/dist/src/sql/store.js +2166 -0
  43. package/dist/src/taint.d.ts +65 -0
  44. package/dist/src/taint.js +138 -0
  45. package/dist/src/text.d.ts +6 -0
  46. package/dist/src/text.js +25 -0
  47. package/dist/src/time-entry.d.ts +6 -0
  48. package/dist/src/time-entry.js +6 -0
  49. package/dist/src/time.d.ts +61 -0
  50. package/dist/src/time.js +140 -0
  51. package/package.json +69 -3
@@ -0,0 +1,130 @@
1
+ /**
2
+ * The per-invocation query budget (RFC-0008 §8.1, §8.2, S17). A `TickMeter` wraps the `SqlDriver`
3
+ * a tick uses and counts statements — every `get`, `all` and `run` is one, a `batch()` counts each
4
+ * of its statements (the conservative reading of L7) — and refuses a statement that would exceed
5
+ * `maxQueries` before it reaches the database, so a tick stops cleanly under the platform's limit
6
+ * (Workers Free: 50 D1 queries per invocation; the tick takes 40). `runDue` also asks
7
+ * `canAfford(n)` before starting a unit of work, so a refusal mid-path is a safety net only.
8
+ */
9
+
10
+ import { TickBudgetExhaustedError } from "./errors.js";
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+ /** Workers Free and Paid budgets (§8.2); Node uses `paid` (no platform limit, same bounded steps). */
24
+ export const TICK_BUDGETS = {
25
+ free: { maxQueries: 40, maxReleases: 1, deadlineMs: 8_000 },
26
+ paid: { maxQueries: 900, maxReleases: 50, deadlineMs: 12 * 60_000 },
27
+ } ;
28
+
29
+ export class TickMeter {
30
+ budget ;
31
+ #used = 0;
32
+ #started ;
33
+ #clock ;
34
+
35
+ /** `clock` is a monotonic-enough millisecond source for the deadline (injected in tests). */
36
+ constructor(budget , clock = () => Date.now()) {
37
+ this.budget = budget;
38
+ this.#clock = clock;
39
+ this.#started = clock();
40
+ }
41
+
42
+ /** Statements executed so far. */
43
+ get used() {
44
+ return this.#used;
45
+ }
46
+
47
+ get remaining() {
48
+ return Math.max(0, this.budget.maxQueries - this.#used);
49
+ }
50
+
51
+ /** True when `n` more statements fit, keeping `reserve` for the heartbeat. */
52
+ canAfford(n , reserve = 0) {
53
+ return this.#used + n + reserve <= this.budget.maxQueries;
54
+ }
55
+
56
+ deadlinePassed() {
57
+ return this.#clock() - this.#started >= this.budget.deadlineMs;
58
+ }
59
+
60
+ /** Counts `n` statements, refusing before the budget would be exceeded. */
61
+ take(n ) {
62
+ if (this.#used + n > this.budget.maxQueries)
63
+ throw new TickBudgetExhaustedError(this.#used + n, this.budget.maxQueries);
64
+ this.#used += n;
65
+ }
66
+
67
+ /**
68
+ * Counts `n` statements that already ran outside the limit (a system job's own driver): later
69
+ * units see less room, and nothing is refused.
70
+ */
71
+ note(n ) {
72
+ this.#used += n;
73
+ }
74
+
75
+ /**
76
+ * A driver that counts every statement into this meter without refusing any — for work whose
77
+ * own bounds hold (the analytics rollup, the comments job) but whose statements share the
78
+ * invocation's platform limit with the tick.
79
+ */
80
+ wrapCounting(inner ) {
81
+ const note = (n ) => this.note(n);
82
+ return {
83
+ name: `counted(${inner.name})`,
84
+ get: async (sql, params) => {
85
+ note(1);
86
+ return inner.get(sql, params);
87
+ },
88
+ all: async (sql, params) => {
89
+ note(1);
90
+ return inner.all(sql, params);
91
+ },
92
+ run: async (sql, params) => {
93
+ note(1);
94
+ return inner.run(sql, params);
95
+ },
96
+ batch: async (statements) => {
97
+ note(statements.length);
98
+ return inner.batch(statements);
99
+ },
100
+ exec: (sql) => inner.exec(sql),
101
+ close: () => inner.close(),
102
+ };
103
+ }
104
+
105
+ /** A driver that counts (and limits) every statement it executes through `inner`. */
106
+ wrap(inner ) {
107
+ const take = (n ) => this.take(n);
108
+ return {
109
+ name: `metered(${inner.name})`,
110
+ get: async (sql, params) => {
111
+ take(1);
112
+ return inner.get(sql, params);
113
+ },
114
+ all: async (sql, params) => {
115
+ take(1);
116
+ return inner.all(sql, params);
117
+ },
118
+ run: async (sql, params) => {
119
+ take(1);
120
+ return inner.run(sql, params);
121
+ },
122
+ batch: async (statements) => {
123
+ take(statements.length);
124
+ return inner.batch(statements);
125
+ },
126
+ exec: (sql) => inner.exec(sql),
127
+ close: () => inner.close(),
128
+ };
129
+ }
130
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Budget accounting for runs and sites (RFC-0008 §11.5, D11). Pure: usage is counted from audit
3
+ * and approval rows (`SqlScheduleStore.runUsage`, `automationWritesToday`); these functions decide.
4
+ */
5
+ import type { AutomationBudget, ScheduleRunUsage } from "@cloudhal/core-contracts";
6
+ /** Defaults for a new agent task (§11.5). */
7
+ export declare const DEFAULT_AGENT_BUDGET: Readonly<AutomationBudget>;
8
+ /** Automation mutations per site per UTC day (`schedule_settings.daily_write_cap`, §11.5). */
9
+ export declare const DEFAULT_DAILY_WRITE_CAP = 200;
10
+ export declare const EMPTY_USAGE: Readonly<ScheduleRunUsage>;
11
+ export type BudgetLimit = "toolCalls" | "writes" | "approvalRequests" | "minutes";
12
+ /** What the next call would add. */
13
+ export interface NextCall {
14
+ write?: boolean;
15
+ approvalRequest?: boolean;
16
+ }
17
+ export type BudgetCheck = {
18
+ ok: true;
19
+ } | {
20
+ ok: false;
21
+ exceeded: BudgetLimit;
22
+ };
23
+ /**
24
+ * Whether a run may make its next call: the call itself, a write, an approval request and the
25
+ * clock must all stay within the budget (`startedAt + maxMinutes`). A refusal ends the run as
26
+ * `budget-exceeded` and pauses the automation.
27
+ */
28
+ export declare function checkRunBudget(budget: AutomationBudget, usage: ScheduleRunUsage, clock: {
29
+ startedAt: string | Date | number;
30
+ now: string | Date | number;
31
+ }, next?: NextCall): BudgetCheck;
32
+ /** What the run has left (for `get_mode`'s `budgetLeft`). */
33
+ export declare function budgetLeft(budget: AutomationBudget, usage: ScheduleRunUsage): {
34
+ toolCalls: number;
35
+ writes: number;
36
+ approvalRequests: number;
37
+ };
38
+ /** Whether one more automation write fits the site's daily cap. */
39
+ export declare function withinDailyWriteCap(writesToday: number, cap: number): boolean;
40
+ /** Midnight UTC of the instant's day (the daily cap's window). */
41
+ export declare function utcDayStart(now: string | Date | number): string;
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Budget accounting for runs and sites (RFC-0008 §11.5, D11). Pure: usage is counted from audit
3
+ * and approval rows (`SqlScheduleStore.runUsage`, `automationWritesToday`); these functions decide.
4
+ */
5
+
6
+ import { canonicalInstant, DAY_MS, instantMs, MINUTE_MS } from "./time.js";
7
+
8
+ /** Defaults for a new agent task (§11.5). */
9
+ export const DEFAULT_AGENT_BUDGET = Object.freeze({
10
+ maxToolCalls: 100,
11
+ maxWrites: 20,
12
+ maxApprovalRequests: 5,
13
+ maxMinutes: 15,
14
+ });
15
+
16
+ /** Automation mutations per site per UTC day (`schedule_settings.daily_write_cap`, §11.5). */
17
+ export const DEFAULT_DAILY_WRITE_CAP = 200;
18
+
19
+ export const EMPTY_USAGE = Object.freeze({
20
+ toolCalls: 0,
21
+ writes: 0,
22
+ approvalRequests: 0,
23
+ });
24
+
25
+
26
+
27
+ /** What the next call would add. */
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+ /**
36
+ * Whether a run may make its next call: the call itself, a write, an approval request and the
37
+ * clock must all stay within the budget (`startedAt + maxMinutes`). A refusal ends the run as
38
+ * `budget-exceeded` and pauses the automation.
39
+ */
40
+ export function checkRunBudget(
41
+ budget ,
42
+ usage ,
43
+ clock ,
44
+ next = {},
45
+ ) {
46
+ if (instantMs(clock.now) > instantMs(clock.startedAt) + budget.maxMinutes * MINUTE_MS)
47
+ return { ok: false, exceeded: "minutes" };
48
+ if (usage.toolCalls + 1 > budget.maxToolCalls) return { ok: false, exceeded: "toolCalls" };
49
+ if (next.write && usage.writes + 1 > budget.maxWrites) return { ok: false, exceeded: "writes" };
50
+ if (next.approvalRequest && usage.approvalRequests + 1 > budget.maxApprovalRequests)
51
+ return { ok: false, exceeded: "approvalRequests" };
52
+ return { ok: true };
53
+ }
54
+
55
+ /** What the run has left (for `get_mode`'s `budgetLeft`). */
56
+ export function budgetLeft(
57
+ budget ,
58
+ usage ,
59
+ ) {
60
+ return {
61
+ toolCalls: Math.max(0, budget.maxToolCalls - usage.toolCalls),
62
+ writes: Math.max(0, budget.maxWrites - usage.writes),
63
+ approvalRequests: Math.max(0, budget.maxApprovalRequests - usage.approvalRequests),
64
+ };
65
+ }
66
+
67
+ /** Whether one more automation write fits the site's daily cap. */
68
+ export function withinDailyWriteCap(writesToday , cap ) {
69
+ return writesToday + 1 <= cap;
70
+ }
71
+
72
+ /** Midnight UTC of the instant's day (the daily cap's window). */
73
+ export function utcDayStart(now ) {
74
+ const ms = instantMs(now);
75
+ return canonicalInstant(ms - (((ms % DAY_MS) + DAY_MS) % DAY_MS));
76
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * The built-in deterministic automations (RFC-0008 §11.1, rollout step 9): `broken-links`,
3
+ * `stale-content`, `feed-check`, `weekly-digest` and `cleanup`, as the `BuiltinRunner` that
4
+ * `runDue` steps.
5
+ *
6
+ * Every job runs in **bounded, resumable steps**: one step per tick, a fixed number of statements
7
+ * (`BUILTIN_STEP_COST`, checked by `runDue` against the tick's budget before it starts, S17), a page
8
+ * of nodes at most, and a JSON `position` the scheduler keeps in `automations.cursor`, so a large
9
+ * site's sweep spans several ticks and survives a crash between them (the next tick continues the
10
+ * same run from the position). Findings accumulate in the position up to 200 per run; counts stay
11
+ * exact.
12
+ *
13
+ * What a job reads comes through `BuiltinSources` (the live snapshot, analytics' 404 rows, the
14
+ * fetched feed): `@cloudhal/core-ts/automations` implements it over the graph's tables; tests pass
15
+ * fakes. Built-ins run as the system actor and change no content (§11.1): their only writes are
16
+ * the run row, the cursor and, for `cleanup`, the deletion of old schedule rows.
17
+ *
18
+ * Taint (§11.4, D10): a step that reads visitor-supplied text (analytics' 404 paths) or a fetched
19
+ * document (the feed check) returns `taint`, and the run records `{ at, tool }`.
20
+ */
21
+ import type { BuiltinAutomationJob } from "@cloudhal/core-contracts";
22
+ import { type FeedExpectations, type FetchedDocument } from "./feed-check.js";
23
+ import { type LinkFinding, type NotFoundFinding, type StaleDraftFinding, type StaleEntryFinding, type WeeklyDigest } from "./findings.js";
24
+ import type { BuiltinRunner } from "./scheduler.js";
25
+ export type BuiltinJobName = BuiltinAutomationJob["builtin"];
26
+ /**
27
+ * Statements one step of each job may take (the sources' reads and writes), declared up front for
28
+ * the tick's budget check. The core-ts conformance suite measures every step against them on
29
+ * SQLite and D1; the Workers Free tick (40) keeps the claim, the finish, the overview and the
30
+ * heartbeat beside the largest step with room to spare.
31
+ */
32
+ export declare const BUILTIN_STEP_COST: Readonly<Record<BuiltinJobName, number>>;
33
+ /** Live nodes one `broken-links` step scans (§11.1: at most 200 nodes per tick on Free). */
34
+ export declare const LINK_PAGE_SIZE = 50;
35
+ /** Entries one `stale-content` step looks at (only route fields are read, not bodies). */
36
+ export declare const STALE_PAGE_SIZE = 200;
37
+ /** 404 rows the sweep asks analytics for. */
38
+ export declare const NOT_FOUND_LIMIT = 20;
39
+ /** Rows `cleanup` deletes per table and step. */
40
+ export declare const CLEANUP_LIMIT = 200;
41
+ export interface LinkScanPage {
42
+ /** Live nodes scanned in this page. */
43
+ readonly scanned: number;
44
+ /** References checked. */
45
+ readonly links: number;
46
+ readonly findings: readonly LinkFinding[];
47
+ /** Resume after this node id; undefined when the snapshot is done. */
48
+ readonly next?: string;
49
+ }
50
+ export type NotFoundRow = Omit<NotFoundFinding, "code" | "severity" | "untrusted">;
51
+ export interface StalePage {
52
+ readonly scanned: number;
53
+ readonly stale: readonly StaleEntryFinding[];
54
+ readonly next?: string;
55
+ }
56
+ export interface CleanupStep {
57
+ /** `runs-deleted`, `releases-deleted`, `findings-trimmed`, `leases-cleared`, `stale-runs-closed`. */
58
+ readonly counts: Readonly<Record<string, number>>;
59
+ /** Something hit its per-step limit: another step follows. */
60
+ readonly more: boolean;
61
+ }
62
+ /**
63
+ * Where the built-in jobs read from. Each method's statements count against the step's
64
+ * `BUILTIN_STEP_COST`; `undefined` from a snapshot read means the site has never been published.
65
+ */
66
+ export interface BuiltinSources {
67
+ /** A page of live pages, entries, terms and menus after `after`, with their references checked. */
68
+ scanLinks(input: {
69
+ siteId: string;
70
+ after?: string;
71
+ limit: number;
72
+ now: Date;
73
+ }): Promise<LinkScanPage | undefined>;
74
+ /** The top 404 paths of the last week from analytics; undefined when analytics is off. */
75
+ notFoundPaths?(input: {
76
+ siteId: string;
77
+ now: Date;
78
+ limit: number;
79
+ }): Promise<readonly NotFoundRow[] | undefined>;
80
+ /** Live, published entries updated before `cutoff`, a page after `after`. */
81
+ staleEntries(input: {
82
+ siteId: string;
83
+ cutoff: string;
84
+ after?: string;
85
+ limit: number;
86
+ now: Date;
87
+ }): Promise<StalePage | undefined>;
88
+ /** What the feed and sitemap must and must not contain at `now`. */
89
+ feedExpectations(input: {
90
+ siteId: string;
91
+ now: Date;
92
+ newest: number;
93
+ }): Promise<FeedExpectations | undefined>;
94
+ /** Fetches the site's own document (`SITE` binding, local renderer); undefined: none reachable. */
95
+ fetchDocument?(input: {
96
+ siteId: string;
97
+ path: string;
98
+ }): Promise<FetchedDocument | undefined>;
99
+ /** The weekly digest's data (§11.1). */
100
+ digest(input: {
101
+ siteId: string;
102
+ automationId: string;
103
+ now: Date;
104
+ }): Promise<WeeklyDigest>;
105
+ /** One bounded retention step (`schedules` tables of the site). */
106
+ cleanup(input: {
107
+ siteId: string;
108
+ now: Date;
109
+ limit: number;
110
+ }): Promise<CleanupStep>;
111
+ /** Drafts untouched for `days` (reminders, at most `limit`). */
112
+ staleDrafts(input: {
113
+ siteId: string;
114
+ now: Date;
115
+ days: number;
116
+ limit: number;
117
+ }): Promise<{
118
+ readonly count: number;
119
+ readonly drafts: readonly StaleDraftFinding[];
120
+ }>;
121
+ }
122
+ export interface BuiltinRunnerOptions {
123
+ readonly linkPageSize?: number;
124
+ readonly stalePageSize?: number;
125
+ }
126
+ /**
127
+ * The five built-in jobs as one `BuiltinRunner` (`cost` is the largest step; `costOf` the job's).
128
+ * Steps throw only for source errors, which `runDue` records as a failed run.
129
+ */
130
+ export declare function createBuiltinRunner(sources: BuiltinSources, options?: BuiltinRunnerOptions): BuiltinRunner & {
131
+ costOf(job: BuiltinAutomationJob): number;
132
+ };