fwdloop 0.19.1 → 0.21.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/README.md +2 -0
- package/bin/fwdloop +22 -13
- package/package.json +1 -1
- package/src/audit-fold.js +177 -0
- package/src/authoring.js +24 -4
- package/src/books.js +4 -3
- package/src/closers.js +49 -2
- package/src/ctx-tools.js +1 -1
- package/src/diary.js +49 -0
- package/src/flow.js +218 -2
- package/src/flowmodel.js +42 -5
- package/src/jobkey.js +25 -0
- package/src/jsonl-append.js +29 -0
- package/src/model-step.js +103 -5
- package/src/monthly.js +3 -2
- package/src/panel/author.js +44 -18
- package/src/panel/authorcard.js +7 -13
- package/src/panel/authorflows.js +118 -24
- package/src/panel/authorresume.js +8 -4
- package/src/panel/authorstart.js +63 -18
- package/src/panel/authortrigger.js +250 -125
- package/src/panel/authorvalues.js +13 -2
- package/src/panel/data.js +279 -43
- package/src/panel/index.html +547 -150
- package/src/panel/needsyou.js +29 -0
- package/src/panel/scheduler.js +21 -22
- package/src/panel/server.js +30 -6
- package/src/primitives.js +44 -2
- package/src/provider.js +3 -2
- package/src/runner.js +58 -22
- package/src/runvalues.js +10 -2
- package/src/schedule.js +135 -0
- package/src/setup.js +0 -21
- package/src/summary-words.js +180 -7
- package/src/thinking.js +39 -0
- package/src/trigger-clock.js +18 -16
- package/src/trigger-files.js +37 -24
- package/src/trigger-line.js +6 -15
- package/src/try-checks.js +62 -0
- package/src/types.js +2 -1
- package/types/audit-fold.d.ts +54 -0
- package/types/authoring.d.ts +33 -2
- package/types/books.d.ts +17 -0
- package/types/ctx-tools.d.ts +1 -0
- package/types/diary.d.ts +57 -0
- package/types/flow.d.ts +106 -0
- package/types/flowmodel.d.ts +25 -3
- package/types/jobkey.d.ts +11 -0
- package/types/jsonl-append.d.ts +6 -0
- package/types/model-step.d.ts +4 -1
- package/types/panel/author.d.ts +47 -17
- package/types/panel/authorcard.d.ts +3 -6
- package/types/panel/authorflows.d.ts +38 -10
- package/types/panel/authorstart.d.ts +15 -2
- package/types/panel/authortrigger.d.ts +73 -41
- package/types/panel/authorvalues.d.ts +6 -0
- package/types/panel/data.d.ts +101 -19
- package/types/panel/needsyou.d.ts +20 -0
- package/types/runvalues.d.ts +5 -0
- package/types/schedule.d.ts +69 -0
- package/types/setup.d.ts +0 -19
- package/types/summary-words.d.ts +105 -2
- package/types/thinking.d.ts +31 -0
- package/types/trigger-clock.d.ts +8 -7
- package/types/trigger-files.d.ts +17 -10
- package/types/trigger-line.d.ts +16 -8
- package/types/try-checks.d.ts +55 -0
- package/types/types.d.ts +10 -1
|
@@ -1,57 +1,50 @@
|
|
|
1
|
-
// M9 pieces 3 and 4 (docs/wiki/the-module-ladder.md, "M9" items 1-6, am1, am2): the
|
|
1
|
+
// M9 pieces 3 and 4 (docs/wiki/the-module-ladder.md, "M9" items 1-6, am1, am2) and M9 am20: the SCHEDULE door of the panel's backend.
|
|
2
2
|
//
|
|
3
3
|
// prepare(body) POST /api/author/trigger-prepare { flow, trigger } the first click: every $0 check, signs nothing, returns the hash
|
|
4
|
-
// set(body) POST /api/author/trigger { flow, trigger, hash } the second click:
|
|
5
|
-
//
|
|
4
|
+
// set(body) POST /api/author/trigger { flow, trigger, hash } the second click: writes `<flow>/schedule.json` (signed by the human) and arms it;
|
|
5
|
+
// trigger null = Cancel. The JOB is never opened for writing: its signature never changes.
|
|
6
6
|
// read(flow) the one read function the cards use: the trigger, whether it is armed, the next slot, the last outcome. No words.
|
|
7
7
|
// fire(...) one fire's outcome, in order: busy -> monthly -> sources -> the ONE start. Every outcome is a `triggers.jsonl` row.
|
|
8
8
|
//
|
|
9
|
-
// ONE WRITER PER FIELD: `set` writes the
|
|
10
|
-
//
|
|
11
|
-
// `
|
|
9
|
+
// ONE WRITER PER FIELD: `set` writes the schedule (through `writeSchedule` in src/schedule.js); `armFor` writes the armed row and the baseline;
|
|
10
|
+
// `recordFire` / the file trigger's `poll` write the fire / ran rows BEFORE a start (a crash loses a run, never doubles one); `appendOutcome` writes
|
|
11
|
+
// `triggers.jsonl`. Nothing here is read from a model: the schedule is typed data signed by a human.
|
|
12
12
|
//
|
|
13
13
|
// Files, per job, under `<flowDir>/`:
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
|
|
19
|
-
import {
|
|
20
|
-
appendFileSync, mkdirSync, realpathSync,
|
|
21
|
-
} from 'node:fs';
|
|
14
|
+
// schedule.json the current signed schedule (M9 am20): the trigger and what a fire uses (plan, inputs, model, destination)
|
|
15
|
+
// schedule-ledger.jsonl ONE queue file for the life of the job: clock and file rows, each with `sig` = the signing that wrote it
|
|
16
|
+
// triggers.jsonl append-only history of every fire outcome (rows of this signing carry its `sig`)
|
|
17
|
+
// An old trigger LINE inside a job's prose (signed before am20) is never read by this door: nothing fires, nothing arms.
|
|
18
|
+
import { realpathSync } from 'node:fs';
|
|
19
|
+
import { createHash } from 'node:crypto';
|
|
22
20
|
import { userInfo } from 'node:os';
|
|
23
|
-
import { dirname, isAbsolute, join } from 'node:path';
|
|
21
|
+
import { basename, dirname, isAbsolute, join } from 'node:path';
|
|
24
22
|
|
|
25
|
-
import {
|
|
23
|
+
import { flowValues, valuesHash } from '../runvalues.js';
|
|
24
|
+
import { destinationRefusal, checkInputRows, runInputRows } from './authorcard.js';
|
|
26
25
|
import { endRow, readHistory } from '../books.js';
|
|
26
|
+
import { appendRow } from '../jsonl-append.js';
|
|
27
27
|
import { loadCatalogue } from '../catalogue.js';
|
|
28
28
|
import {
|
|
29
|
-
FLOW_FILES, checkFlowName, listFlowNames, listRunIds, readFileInside, readFlow,
|
|
29
|
+
FLOW_FILES, checkFlowName, listFlowNames, listRunIds, planForReuse, readFileInside, readFlow, readRunJobCopy, resolveRunDir,
|
|
30
30
|
} from '../flow.js';
|
|
31
|
-
import {
|
|
32
|
-
import { editClearsWords, scheduledWords } from '../summary-words.js';
|
|
31
|
+
import { scheduleHead, scheduledWords } from '../summary-words.js';
|
|
33
32
|
import { armTrigger, nextSlot, readRows, validateSchedule } from '../trigger-clock.js';
|
|
34
33
|
import { checkTarget, createFileTrigger } from '../trigger-files.js';
|
|
35
34
|
import { readModelRecord } from '../flowmodel.js';
|
|
36
|
-
import { carrySetup, readSetup } from '../setup.js';
|
|
37
35
|
import {
|
|
38
|
-
|
|
39
|
-
} from '../
|
|
36
|
+
carryQueue, dropQueue, finishCarry, isArmed, ledgerOf, readSchedule, recordCancelled, removeSchedule, sameTarget, sigOf, writeSchedule,
|
|
37
|
+
} from '../schedule.js';
|
|
38
|
+
import { triggerHash, triggerLine } from '../trigger-line.js';
|
|
40
39
|
|
|
41
40
|
/** @typedef {import('../trigger-line.js').Trigger} Trigger */
|
|
41
|
+
/** @typedef {import('../schedule.js').Schedule} Schedule */
|
|
42
42
|
|
|
43
43
|
/** A trigger in the words a row and a run reason use: `daily 09:00`, `new-file jd = file:/home/you/inbox`. @param {Trigger} t */
|
|
44
44
|
const describe = (t) => triggerLine(t).replace('guardrail: trigger ', '');
|
|
45
45
|
|
|
46
46
|
export const NO_GREEN_SAY = 'This job has not had a good run yet. Run it once by hand and get it right first; then you can set when it runs. Nothing was changed.';
|
|
47
47
|
const HISTORY_FILE = 'triggers.jsonl';
|
|
48
|
-
const HASH_RE = /^[0-9a-f]{64}$/;
|
|
49
|
-
|
|
50
|
-
/** The folder holding the ledgers of ONE signed trigger. @param {string} flowDir @param {string} flowHash */
|
|
51
|
-
export function triggerLedgerDir(flowDir, flowHash) {
|
|
52
|
-
if (!HASH_RE.test(flowHash)) throw new Error('trigger ledger: the flow signature hash is not a sha256');
|
|
53
|
-
return join(flowDir, 'triggers', flowHash);
|
|
54
|
-
}
|
|
55
48
|
|
|
56
49
|
/** Every fire outcome of a job, oldest first, through the safe gateway. @param {string} flowDir @returns {any[]} */
|
|
57
50
|
export function readOutcomes(flowDir) {
|
|
@@ -62,30 +55,13 @@ export function readOutcomes(flowDir) {
|
|
|
62
55
|
|
|
63
56
|
/** The ONE writer of `triggers.jsonl`: append-only, one line per fire outcome. @param {string} flowDir @param {Record<string, any>} row */
|
|
64
57
|
export function appendOutcome(flowDir, row) {
|
|
65
|
-
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* The signature hashes that are this job: the current one plus every one it is a trigger-only re-sign of (the `trigger-resign` rows `set` appends to
|
|
70
|
-
* setup.jsonl, followed back by `resignOf`). A real Edit writes a new setup.jsonl with no such rows, so it starts a new chain (am1).
|
|
71
|
-
* @param {string} flowDir @param {string} sig
|
|
72
|
-
*/
|
|
73
|
-
function signingsOf(flowDir, sig) {
|
|
74
|
-
const out = new Set([sig]);
|
|
75
|
-
const s = readSetup(flowDir);
|
|
76
|
-
if (!s.present) return out;
|
|
77
|
-
for (let h = sig; ;) {
|
|
78
|
-
const prev = s.rows.findLast((r) => r.kind === 'trigger-resign' && r.flowHash === h)?.resignOf;
|
|
79
|
-
if (typeof prev !== 'string' || out.has(prev)) return out;
|
|
80
|
-
out.add(prev); h = prev;
|
|
81
|
-
}
|
|
58
|
+
appendRow(join(flowDir, HISTORY_FILE), row, { mode: 0o600 });
|
|
82
59
|
}
|
|
83
60
|
|
|
84
61
|
/**
|
|
85
62
|
* M9 item 1 and 2: does this job have "one green run"? The ONE function that decides it. A passed run counts when the job it ran (its own
|
|
86
|
-
* `job/` copy) is the
|
|
87
|
-
*
|
|
88
|
-
* history row's signature is the job's current one (a job signed since then is not the job it ran, unless that signing only added or changed its trigger line: see signingsOf).
|
|
63
|
+
* `job/` copy) is the job as it is now (prose and declaration, byte for byte: a schedule is its own file, so setting one never changes the job).
|
|
64
|
+
* A run from before runs kept a job copy has none to compare, so it counts only when its history row's signature is the job's current one.
|
|
89
65
|
* @param {string} flowDir
|
|
90
66
|
*/
|
|
91
67
|
export function hasGreenRunForJob(flowDir) {
|
|
@@ -97,9 +73,8 @@ export function hasGreenRunForJob(flowDir) {
|
|
|
97
73
|
}
|
|
98
74
|
let sig;
|
|
99
75
|
try { sig = JSON.parse(cur['signature.json']).flow; } catch { return false; }
|
|
100
|
-
const key = (/** @type {string} */ prose, /** @type {string} */ decl) => `${
|
|
76
|
+
const key = (/** @type {string} */ prose, /** @type {string} */ decl) => `${prose.trimEnd()}\n\u0000${decl}`;
|
|
101
77
|
const want = key(cur['prose.txt'], cur['declaration.json']);
|
|
102
|
-
const signings = signingsOf(flowDir, sig);
|
|
103
78
|
const history = readHistory(flowDir);
|
|
104
79
|
for (const id of listRunIds(flowDir)) {
|
|
105
80
|
const r = resolveRunDir(flowDir, id);
|
|
@@ -108,26 +83,27 @@ export function hasGreenRunForJob(flowDir) {
|
|
|
108
83
|
if (end === null || end.outcome !== 'complete') continue;
|
|
109
84
|
const prose = readFileInside(r.runDir, 'job/prose.txt');
|
|
110
85
|
const decl = readFileInside(r.runDir, 'job/declaration.json');
|
|
111
|
-
if (prose.ok && decl.ok) { if (key(prose.text, decl.text) === want) return true; } else if (!prose.ok && prose.missing &&
|
|
86
|
+
if (prose.ok && decl.ok) { if (key(prose.text, decl.text) === want) return true; } else if (!prose.ok && prose.missing && end.signatureHash === sig) return true;
|
|
112
87
|
}
|
|
113
88
|
return false;
|
|
114
89
|
}
|
|
115
90
|
|
|
116
91
|
/**
|
|
117
|
-
* The ONE writer of "this
|
|
118
|
-
* (never runs
|
|
119
|
-
* the target is not usable now.
|
|
120
|
-
* @param {string} flowDir @param {
|
|
92
|
+
* The ONE writer of "this schedule was set": the starting point (am2 item 2). Idempotent per signing. A file kind records what is already there first
|
|
93
|
+
* (never runs; `baseline: false` = the folder is the same as the earlier signing's, whose rows were carried), then the armed row. Throws, naming why,
|
|
94
|
+
* when the target is not usable now.
|
|
95
|
+
* @param {string} flowDir @param {Schedule} schedule @param {number} now epoch ms @param {{baseline?: boolean}} [o]
|
|
121
96
|
* @returns {{armed: boolean, already: boolean}}
|
|
122
97
|
*/
|
|
123
|
-
export function armFor(flowDir,
|
|
124
|
-
const
|
|
125
|
-
const
|
|
126
|
-
if (
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
98
|
+
export function armFor(flowDir, schedule, now, o = {}) {
|
|
99
|
+
const ledger = ledgerOf(flowDir);
|
|
100
|
+
const { sig, trigger } = schedule;
|
|
101
|
+
if (isArmed(flowDir, sig)) return { armed: true, already: true };
|
|
102
|
+
if (o.baseline !== false) {
|
|
103
|
+
if (trigger.kind === 'file-updated') createFileTrigger({ mode: 'updated', target: trigger.path, ledger, sig }).arm();
|
|
104
|
+
else if (trigger.kind === 'new-file') createFileTrigger({ mode: 'new', target: trigger.folder, ledger, sig }).arm();
|
|
105
|
+
}
|
|
106
|
+
armTrigger(ledger, now, sig);
|
|
131
107
|
return { armed: true, already: false };
|
|
132
108
|
}
|
|
133
109
|
|
|
@@ -190,8 +166,8 @@ export function createTriggerDoor(opts) {
|
|
|
190
166
|
const { trigger } = shaped;
|
|
191
167
|
const flowDir = join(realRoot, flow);
|
|
192
168
|
if (trigger !== null && !hasGreenRunForJob(flowDir)) return reply(409, { refused: 'no-green-run', say: NO_GREEN_SAY });
|
|
193
|
-
|
|
194
|
-
|
|
169
|
+
// M9 am20 item 3: neither Cancel nor a new schedule is refused because a run is starting, working or waiting: a run carries on from its own copy and
|
|
170
|
+
// keeps its own signed values; the next fire uses the new schedule. (A schedule never touches the job, so there is nothing for a run to collide with.)
|
|
195
171
|
if (trigger !== null && 'role' in trigger) {
|
|
196
172
|
try {
|
|
197
173
|
checkTarget(trigger.kind === 'new-file' ? 'new' : 'updated', trigger.kind === 'new-file' ? trigger.folder : trigger.path);
|
|
@@ -203,18 +179,85 @@ export function createTriggerDoor(opts) {
|
|
|
203
179
|
try { realpathSync(dirname(trigger.path)); } catch { return reply(400, { refused: 'bad-trigger', say: `The folder of ${trigger.path} does not exist. Nothing was changed.` }); }
|
|
204
180
|
}
|
|
205
181
|
}
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
182
|
+
// M6 am5 item 3: a schedule may carry the model of the run it was made from (a run field). Checked now by the Run door's own model check; the same as
|
|
183
|
+
// the job's recorded model is no change (null). It is bound into the hash, written beside the trigger's ledger, and read by the fire.
|
|
184
|
+
let scheduledModel = null;
|
|
185
|
+
if (trigger !== null && (typeof body?.provider === 'string' || typeof body?.model === 'string') && (body.provider !== '' || body.model !== '')) {
|
|
186
|
+
const loaded = loadEnv();
|
|
187
|
+
if (!loaded.ok) return reply(409, { refused: 'keys-file', say: String(loaded.refusal) });
|
|
188
|
+
const says = modelRefusal({ provider: body.provider, model: body.model }, loaded);
|
|
189
|
+
if (says.length > 0) return reply(400, { refused: 'bad-model', say: says[0].say, refusals: says });
|
|
190
|
+
const rec0 = readModelRecord(flowDir);
|
|
191
|
+
if (rec0 === null || rec0.slot !== body.provider || rec0.model !== body.model) scheduledModel = { slot: body.provider, model: body.model };
|
|
192
|
+
}
|
|
193
|
+
// M6 am5 item 3, the rest: the scheduled run's DESTINATION and INPUTS, bound the same way (hash, then a file beside the ledgers, then each fired run's values).
|
|
194
|
+
// A destination equal to the flow's is no change. The same checks as Sign & run (M4e am5 item 4); the input roles are exactly the job's.
|
|
195
|
+
let scheduledDestination = null;
|
|
196
|
+
let scheduledInputs = null;
|
|
197
|
+
if (trigger !== null) {
|
|
198
|
+
const own = flowValues(read.arbiter).destination;
|
|
199
|
+
if (typeof body?.destination === 'string' && body.destination.trim() !== '' && body.destination.trim() !== own) {
|
|
200
|
+
if (own === null) return reply(400, { refused: 'bad-destination', say: 'This flow has no send step, so there is no destination to schedule. Nothing was changed.' });
|
|
201
|
+
const why = destinationRefusal(body.destination.trim(), realRoot);
|
|
202
|
+
if (why !== null) return reply(400, { refused: 'bad-destination', say: `${why} Nothing was changed.` });
|
|
203
|
+
scheduledDestination = body.destination.trim();
|
|
204
|
+
}
|
|
205
|
+
if (Array.isArray(body?.inputs)) {
|
|
206
|
+
const rows = runInputRows(body.inputs);
|
|
207
|
+
const declared = roles;
|
|
208
|
+
const bad = [...checkInputRows(rows)];
|
|
209
|
+
for (const role of declared) if (!rows.some((r) => r.role === role)) bad.push({ field: 'inputs', say: `This flow needs an input named "${role}". Add it.` });
|
|
210
|
+
for (const r of rows) if (!declared.includes(r.role)) bad.push({ field: 'inputs', say: `This flow has no input named "${r.role}" (it takes: ${declared.join(', ') || 'none'}).` });
|
|
211
|
+
if (bad.length > 0) return reply(400, { refused: 'bad-inputs', say: `${bad[0].say} Nothing was changed.`, refusals: bad });
|
|
212
|
+
scheduledInputs = declared.map((role) => ({ role, path: /** @type {{path: string}} */ (rows.find((r) => r.role === role)).path }));
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
// M6 am9: the schedule uses the plan of the run it was set from. The workflow's own plan = nothing to bind; a different kept plan is verified now and
|
|
216
|
+
// bound into the hash (the run, that plan's signature and the sha of its declaration), so the second click signs exactly this plan.
|
|
217
|
+
let scheduledPlan = null;
|
|
218
|
+
let scheduledFrom = null;
|
|
219
|
+
const planOf = typeof body?.planOf === 'string' ? body.planOf.trim() : '';
|
|
220
|
+
if (trigger !== null && planOf !== '') {
|
|
221
|
+
const rr = resolveRunDir(flowDir, planOf);
|
|
222
|
+
if (!rr.ok) return reply(400, { refused: 'plan', say: `"${planOf}" is not a run name. Nothing was changed.` });
|
|
223
|
+
const cat = loadCatalogue();
|
|
224
|
+
if (!cat.ok) return reply(500, { refused: 'catalogue', say: 'The catalogue could not be read. Nothing was changed.' });
|
|
225
|
+
const pf = planForReuse({ root: realRoot, name: flow, runDir: rr.runDir, catalogue: cat.primitives });
|
|
226
|
+
if (!pf.ok) return reply(409, { refused: 'plan', say: pf.red.replace('Nothing was started.', 'Nothing was changed.') });
|
|
227
|
+
scheduledFrom = planOf;
|
|
228
|
+
if (!pf.same) {
|
|
229
|
+
const decl = readFileInside(rr.runDir, 'job/declaration.json');
|
|
230
|
+
if (!decl.ok) return reply(409, { refused: 'plan', say: `The plan ${planOf} kept cannot be read. Nothing was changed.` });
|
|
231
|
+
scheduledPlan = { run: planOf, flowHash: String(pf.read.signature.flow), declSha: createHash('sha256').update(decl.text).digest('hex') };
|
|
232
|
+
}
|
|
233
|
+
}
|
|
212
234
|
return {
|
|
213
|
-
ok: /** @type {true} */ (true), flow, read, trigger, flowDir, realRoot,
|
|
214
|
-
|
|
235
|
+
ok: /** @type {true} */ (true), flow, read, trigger, flowDir, realRoot,
|
|
236
|
+
model: scheduledModel, destination: scheduledDestination, inputs: scheduledInputs, plan: scheduledPlan, from: scheduledFrom,
|
|
237
|
+
hash: triggerHash({ flow, flowSignatureHash: read.signature.flow, trigger, model: scheduledModel, destination: scheduledDestination, inputs: scheduledInputs, plan: scheduledPlan }),
|
|
215
238
|
};
|
|
216
239
|
}
|
|
217
240
|
|
|
241
|
+
/**
|
|
242
|
+
* The schedule of this job as it counts NOW: its `schedule.json`, read and checked, and only while it was set for THIS job as it is (an Edit signs a new job,
|
|
243
|
+
* M9 am1: the job is By hand again; the scheduler cancels the stale file with Cancel's own words). `null` = By hand. @param {string} flowDir @param {string} jobHash
|
|
244
|
+
*/
|
|
245
|
+
function liveSchedule(flowDir, jobHash) {
|
|
246
|
+
const sc = readSchedule(flowDir);
|
|
247
|
+
return sc !== null && sc.flowSignatureHash === jobHash ? sc : null;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* THE one cancel: every waiting file leaves its queue with am16's row, a `cancelled` row is written, then `schedule.json` is removed. Used by the Cancel
|
|
252
|
+
* click and by the scheduler for a schedule whose job was Edited. @param {string} flow @param {string} flowDir @param {Schedule} cur
|
|
253
|
+
*/
|
|
254
|
+
function cancelSchedule(flow, flowDir, cur) {
|
|
255
|
+
const at = now();
|
|
256
|
+
dropQueue(flowDir, cur.sig, at, (row) => appendOutcome(flowDir, { at: new Date(at).toISOString(), flow, trigger: 'By hand', sig: cur.sig, ...row }));
|
|
257
|
+
recordCancelled(flowDir, cur.sig, at);
|
|
258
|
+
removeSchedule(flowDir);
|
|
259
|
+
}
|
|
260
|
+
|
|
218
261
|
return {
|
|
219
262
|
/** `POST /api/author/trigger-prepare`: the first click. Checks, signs and writes nothing. @param {any} body */
|
|
220
263
|
prepare(body) {
|
|
@@ -224,8 +267,8 @@ export function createTriggerDoor(opts) {
|
|
|
224
267
|
},
|
|
225
268
|
|
|
226
269
|
/**
|
|
227
|
-
* `POST /api/author/trigger`: the second click, carrying the hash it was shown.
|
|
228
|
-
*
|
|
270
|
+
* `POST /api/author/trigger`: the second click, carrying the hash it was shown. Writes `schedule.json` (signed by the human who clicked) and arms it, or
|
|
271
|
+
* (trigger null) cancels. The job's files are never opened for writing. $0: no drafter, no run. A run that is starting, working or waiting is never touched.
|
|
229
272
|
* @param {any} body
|
|
230
273
|
*/
|
|
231
274
|
set(body) {
|
|
@@ -234,56 +277,80 @@ export function createTriggerDoor(opts) {
|
|
|
234
277
|
if (typeof body.hash !== 'string' || body.hash !== s.hash) {
|
|
235
278
|
return { status: 409, body: { ok: false, refused: 'stale-hash', say: 'What you were shown is not what is on the card now (its hash differs). Nothing was signed. Look again, then sign.' } };
|
|
236
279
|
}
|
|
237
|
-
const
|
|
238
|
-
if (
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
const
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
280
|
+
const cur = readSchedule(s.flowDir);
|
|
281
|
+
if (s.trigger === null) {
|
|
282
|
+
if (cur !== null) cancelSchedule(s.flow, s.flowDir, cur);
|
|
283
|
+
return { status: 200, body: { ok: true, flow: s.flow, trigger: null, words: scheduledWords(null), armed: true } };
|
|
284
|
+
}
|
|
285
|
+
const at = now();
|
|
286
|
+
const signedAt = new Date(at).toISOString();
|
|
287
|
+
const bound = s.hash;
|
|
288
|
+
/** @type {Schedule} */
|
|
289
|
+
const schedule = {
|
|
290
|
+
v: 1, flow: s.flow, trigger: s.trigger, flowSignatureHash: s.read.signature.flow, bound, sig: sigOf(bound, signedAt), signedBy: userInfo().username, signedAt,
|
|
291
|
+
model: s.model, destination: s.destination, inputs: s.inputs, plan: s.plan, from: s.from,
|
|
292
|
+
};
|
|
293
|
+
const keep = cur !== null && sameTarget(cur.trigger, s.trigger);
|
|
294
|
+
try {
|
|
295
|
+
if (cur !== null && keep) carryQueue(s.flowDir, cur.sig, schedule.sig);
|
|
296
|
+
armFor(s.flowDir, schedule, at, { baseline: !keep });
|
|
297
|
+
} catch (e) {
|
|
298
|
+
return { status: 409, body: { ok: false, refused: 'not-armed', say: `The schedule was not signed: ${/** @type {Error} */ (e).message}. Nothing was changed.` } };
|
|
250
299
|
}
|
|
251
|
-
|
|
300
|
+
writeSchedule(s.flowDir, schedule);
|
|
301
|
+
if (cur !== null && keep) finishCarry(s.flowDir, cur.sig, at);
|
|
302
|
+
// a changed folder drops the queue of the earlier signing, with am16's row, in this same click, but only now that the new schedule is armed and
|
|
303
|
+
// written: everything that can refuse (arm) came first, so "Nothing was changed" is true. A crash between the write and the drop leaves the old
|
|
304
|
+
// signing's files unrun (the old sig is not live) without their row; it never runs one twice and never fires unsigned.
|
|
305
|
+
if (cur !== null && !keep) dropQueue(s.flowDir, cur.sig, at, (row) => appendOutcome(s.flowDir, { at: signedAt, flow: s.flow, trigger: describe(cur.trigger), sig: cur.sig, ...row }));
|
|
306
|
+
return { status: 200, body: { ok: true, flow: s.flow, trigger: s.trigger, words: scheduledWords(s.trigger), flowHash: s.read.signature.flow, sig: schedule.sig, armed: true } };
|
|
252
307
|
},
|
|
253
308
|
|
|
254
|
-
/** Every
|
|
309
|
+
/** Every job with a live schedule, as the scheduler needs it: `{flow, flowDir, read, schedule, trigger, sig}`. Reads each job the way the CLI will (signature verified). */
|
|
255
310
|
scan() {
|
|
256
311
|
const realRoot = realRootOrNull();
|
|
257
312
|
if (realRoot === null) return [];
|
|
258
313
|
const jobs = [];
|
|
259
314
|
for (const flow of listFlowNames(realRoot)) {
|
|
315
|
+
const flowDir = join(realRoot, flow);
|
|
316
|
+
if (readSchedule(flowDir) === null) continue; // the cheap test first: most jobs have none
|
|
260
317
|
const read = readSigned(realRoot, flow);
|
|
261
|
-
if (read.ok
|
|
318
|
+
if (!read.ok) continue;
|
|
319
|
+
const schedule = liveSchedule(flowDir, read.signature.flow);
|
|
320
|
+
if (schedule !== null && isArmed(flowDir, schedule.sig)) jobs.push({ flow, flowDir, read, schedule, trigger: schedule.trigger, sig: schedule.sig });
|
|
262
321
|
}
|
|
263
322
|
return jobs;
|
|
264
323
|
},
|
|
265
324
|
|
|
266
|
-
/**
|
|
267
|
-
|
|
268
|
-
|
|
325
|
+
/** A schedule whose job was Edited since (M9 am1: By hand again) is cancelled the way Cancel does it, once. Called at the top of every scheduler tick. */
|
|
326
|
+
retireStale() {
|
|
327
|
+
const realRoot = realRootOrNull();
|
|
328
|
+
if (realRoot === null) return;
|
|
329
|
+
for (const flow of listFlowNames(realRoot)) {
|
|
330
|
+
const flowDir = join(realRoot, flow);
|
|
331
|
+
const sc = readSchedule(flowDir);
|
|
332
|
+
if (sc === null) continue;
|
|
333
|
+
const read = readSigned(realRoot, flow);
|
|
334
|
+
if (read.ok && sc.flowSignatureHash !== read.signature.flow) cancelSchedule(flow, flowDir, sc);
|
|
335
|
+
}
|
|
269
336
|
},
|
|
270
337
|
|
|
271
|
-
/** M9 am3: is a run of this job starting
|
|
338
|
+
/** M9 am3/am8: is a run of this job starting or still working? A run waiting at its ask is not busy. (the same check `fire` makes first) @param {{flow: string}} job */
|
|
272
339
|
busy(job) {
|
|
273
|
-
return flowsDoor.
|
|
340
|
+
return flowsDoor.scheduleBusy(job.flow) !== null;
|
|
274
341
|
},
|
|
275
342
|
|
|
276
|
-
/** M9 am3: one row for a queued file that is not a fire (deleted / changed before its turn). @param {{flow: string, flowDir: string, trigger: Trigger}} job @param {Record<string, any>} row */
|
|
343
|
+
/** M9 am3: one row for a queued file that is not a fire (deleted / changed before its turn). @param {{flow: string, flowDir: string, trigger: Trigger, sig: string}} job @param {Record<string, any>} row */
|
|
277
344
|
note(job, row) {
|
|
278
|
-
appendOutcome(job.flowDir, { at: new Date(now()).toISOString(), flow: job.flow, trigger: describe(job.trigger), ...row });
|
|
345
|
+
appendOutcome(job.flowDir, { at: new Date(now()).toISOString(), flow: job.flow, trigger: describe(job.trigger), sig: job.sig, ...row });
|
|
279
346
|
},
|
|
280
347
|
|
|
281
348
|
/**
|
|
282
|
-
* One row in `triggers.jsonl` that is not a fire (the trigger could not be watched). @param {{flow: string, flowDir: string, trigger: Trigger}} job @param {string} why
|
|
349
|
+
* One row in `triggers.jsonl` that is not a fire (the trigger could not be watched). @param {{flow: string, flowDir: string, trigger: Trigger, sig: string}} job @param {string} why
|
|
283
350
|
*/
|
|
284
351
|
refuse(job, why) {
|
|
285
352
|
appendOutcome(job.flowDir, {
|
|
286
|
-
at: new Date(now()).toISOString(), flow: job.flow, trigger: describe(job.trigger), outcome: 'refused', why,
|
|
353
|
+
at: new Date(now()).toISOString(), flow: job.flow, trigger: describe(job.trigger), sig: job.sig, outcome: 'refused', why,
|
|
287
354
|
});
|
|
288
355
|
},
|
|
289
356
|
|
|
@@ -291,27 +358,46 @@ export function createTriggerDoor(opts) {
|
|
|
291
358
|
* M9 item 3-5: one fire, in this order, each outcome ONE row in `triggers.jsonl`: busy -> monthly-exhausted -> refused (an input or the keys
|
|
292
359
|
* are missing) -> started through the ONE start path (kind `trigger`; the reason and the catch-up mark go into the run's own folder first).
|
|
293
360
|
* The fire / ran ledger row was written by the caller BEFORE this, so a crash loses a run and never doubles one.
|
|
294
|
-
* @param {{flow: string, flowDir: string, read: any, trigger: Trigger}} job
|
|
361
|
+
* @param {{flow: string, flowDir: string, read: any, trigger: Trigger, schedule: Schedule}} job
|
|
295
362
|
* @param {{kind: 'clock', slot: number, catchUp: boolean, missed: number} | {kind: 'file', path: string, sha: string}} cause
|
|
296
|
-
* @param {{ told?: (row: Record<string, any>) => boolean, beforeStart?: () => void }} [hooks] M9 am3 (a queued file): `told(row)` true = this file
|
|
363
|
+
* @param {{ told?: (row: Record<string, any>) => boolean, beforeStart?: () => void, holdIfCannotStart?: boolean }} [hooks] M9 am3 (a queued file): `told(row)` true = this file
|
|
297
364
|
* already has a row for that outcome and reason (`why`), so none is written again (the outcome is still returned); `beforeStart` runs right before the ONE
|
|
298
|
-
* start, once every check has passed: the scheduler writes the file's `ran` row there.
|
|
365
|
+
* start, once every check has passed: the scheduler writes the file's `ran` row there. `holdIfCannotStart` (a queued file, M9 am17): the starter's `canStart` is asked first, and a no writes nothing
|
|
366
|
+
* (no row, no `beforeStart`) and returns outcome `cannot-start`.
|
|
299
367
|
*/
|
|
300
368
|
fire(job, cause, hooks = {}) {
|
|
301
|
-
const {
|
|
369
|
+
const {
|
|
370
|
+
flow, flowDir, read: flowRead, trigger, schedule,
|
|
371
|
+
} = job;
|
|
372
|
+
let read = flowRead; // the plan this fire runs: the workflow's own, or (M6 am9) the kept plan of the run the schedule was set from
|
|
302
373
|
const desc = describe(trigger);
|
|
303
374
|
const base = {
|
|
304
|
-
at: new Date(now()).toISOString(), flow, trigger: desc,
|
|
375
|
+
at: new Date(now()).toISOString(), flow, trigger: desc, sig: schedule.sig,
|
|
305
376
|
...(cause.kind === 'clock' ? { slot: new Date(cause.slot).toISOString(), catchUp: cause.catchUp, missed: cause.missed } : { file: cause.path, sha: cause.sha, catchUp: false }),
|
|
306
377
|
};
|
|
307
378
|
const done = (/** @type {Record<string, any>} */ r) => { const row = /** @type {Record<string, any>} */ ({ ...base, ...r }); if (!(row.outcome !== 'started' && hooks.told?.(row))) appendOutcome(flowDir, row); return row; };
|
|
308
|
-
const busy = flowsDoor.
|
|
379
|
+
const busy = flowsDoor.scheduleBusy(flow); // M9 am8: one WORKING run at a time per job; a run waiting at its ask does not block
|
|
309
380
|
if (busy !== null) return done({ outcome: 'busy', say: busy });
|
|
381
|
+
// M6 am9: a schedule set from a run that kept another plan runs THAT plan; it is re-verified now, against what the second click signed
|
|
382
|
+
let planRun = null;
|
|
383
|
+
const planRec = schedule.plan;
|
|
384
|
+
if (planRec !== null) {
|
|
385
|
+
const cat = loadCatalogue();
|
|
386
|
+
const rr = resolveRunDir(flowDir, planRec.run);
|
|
387
|
+
const kept = rr.ok && cat.ok ? readRunJobCopy(rr.runDir, cat.primitives) : null;
|
|
388
|
+
const decl = rr.ok ? readFileInside(rr.runDir, 'job/declaration.json') : null;
|
|
389
|
+
const good = kept && kept.present && kept.ok && kept.signature.flow === planRec.flowHash && decl && decl.ok && createHash('sha256').update(decl.text).digest('hex') === planRec.declSha;
|
|
390
|
+
if (!good) return done({ outcome: 'refused', why: `The plan of ${planRec.run} is no longer the one that was signed, so nothing started. Set the schedule again.` });
|
|
391
|
+
read = /** @type {any} */ (kept);
|
|
392
|
+
planRun = planRec.run;
|
|
393
|
+
}
|
|
310
394
|
const claim = monthlyClaim(read.arbiter.capUsd); // the same check the Run door decides on
|
|
311
395
|
if (claim && 'problem' in claim) return done({ outcome: 'refused', why: `${claim.problem}. Nothing spent.` });
|
|
312
396
|
if (claim && !claim.ok) return done({ outcome: 'monthly-exhausted', leftUsd: claim.room.leftUsd, needUsd: claim.room.needUsd, atLeast: claim.room.atLeast === true });
|
|
313
397
|
const roles = (read.arbiter.sources ?? []).map((x) => x.role);
|
|
314
|
-
|
|
398
|
+
// M6 am5 item 3: the scheduled run's inputs, when the schedule carries them; else the newest run's (as before). A file trigger's own role is always the arriving file.
|
|
399
|
+
let last = flowsDoor.lastSourcesOf(flow, roles).sources;
|
|
400
|
+
if (schedule.inputs !== null) last = { ...last, ...Object.fromEntries(schedule.inputs.map((r) => [r.role, r.path])) };
|
|
315
401
|
const sources = [];
|
|
316
402
|
for (const role of roles) {
|
|
317
403
|
const p = 'role' in trigger && trigger.role === role && cause.kind === 'file' ? cause.path : last[role];
|
|
@@ -322,25 +408,41 @@ export function createTriggerDoor(opts) {
|
|
|
322
408
|
if (!loaded.ok) return done({ outcome: 'refused', why: String(loaded.refusal) });
|
|
323
409
|
// the Run door's model check (its one `modelRefusal`), on the job's recorded model: a trigger picks no model, so a job without a record, or whose
|
|
324
410
|
// line is no longer ticked / priced / keyed in Settings, is refused here at $0, never started
|
|
325
|
-
const
|
|
326
|
-
if (
|
|
411
|
+
const jobRec = readModelRecord(flowDir);
|
|
412
|
+
if (jobRec === null) return done({ outcome: 'refused', why: 'This job has no model recorded, so it cannot start by itself. Run it by hand once from the Chat card and pick a model. Nothing started.' });
|
|
413
|
+
// M6 am5 item 3: the model this schedule was signed with (a run field) wins over the job's recorded one; it is signed into the run's own values
|
|
414
|
+
let rec = jobRec; let values = null;
|
|
415
|
+
if (schedule.model !== null) rec = schedule.model;
|
|
416
|
+
const destination = schedule.destination;
|
|
417
|
+
if (destination !== null) {
|
|
418
|
+
const why = destinationRefusal(destination, realpathSync(root)); // the Sign & run checks, again at the moment of use
|
|
419
|
+
if (why !== null) return done({ outcome: 'refused', why: `${why} Nothing started.` });
|
|
420
|
+
}
|
|
421
|
+
if (rec !== jobRec || destination !== null) {
|
|
422
|
+
const vals = { ...flowValues(read.arbiter), ...(destination !== null ? { destination } : {}), ...(rec !== jobRec ? { model: rec } : {}) };
|
|
423
|
+
values = { flow, flowSignatureHash: read.signature.flow, version: 0, values: vals, hash: valuesHash({ flow, flowSignatureHash: read.signature.flow, runId: null, version: 0, values: vals }), signedBy: userInfo().username, at: new Date(now()).toISOString() };
|
|
424
|
+
}
|
|
327
425
|
const modelSays = modelRefusal({ provider: rec.slot, model: rec.model }, loaded);
|
|
328
426
|
if (modelSays.length > 0) return done({ outcome: 'refused', why: modelSays[0].say.replace(/ Nothing was spent\.$/, '. Nothing started.') });
|
|
329
427
|
const catchUp = base.catchUp === true;
|
|
330
428
|
const record = {
|
|
331
429
|
kind: cause.kind, trigger: desc, reason: `Started by the trigger: ${desc}${catchUp ? ' (catch-up)' : ''}`, catchUp, ...(cause.kind === 'clock' ? { slot: new Date(cause.slot).toISOString(), missed: cause.missed } : { file: cause.path, sha: cause.sha }),
|
|
430
|
+
// M9 am6: typed facts for the run's Job tab and Audit (their words are built from these, in src/summary-words.js, never here)
|
|
431
|
+
triggerKind: trigger.kind, words: scheduleHead(trigger), at: base.at, ...(cause.kind === 'clock' ? { lateMin: Math.max(0, Math.round((now() - cause.slot) / 60_000)) } : {}),
|
|
432
|
+
sig: schedule.sig, ...(schedule.from ? { fromRun: schedule.from } : {}),
|
|
332
433
|
};
|
|
434
|
+
if (hooks.holdIfCannotStart === true && starter.canStart({ flow, runId: '', planRun: false }, loaded) !== null) return { ...base, outcome: 'cannot-start' }; // M9 am17: nothing written, the file stays queued for the next turn
|
|
333
435
|
hooks.beforeStart?.();
|
|
334
436
|
const started = starter.start({
|
|
335
|
-
kind: 'trigger', flow, runId: '', sources, trigger: record,
|
|
437
|
+
kind: 'trigger', flow, runId: '', sources, trigger: record, values, planOf: planRun,
|
|
336
438
|
}, loaded);
|
|
337
439
|
if (started.status !== 202) return done({ outcome: 'refused', why: String(started.body.say ?? 'The run did not start.') });
|
|
338
440
|
return done({ outcome: 'started', runId: started.body.runId, startId: started.body.startId });
|
|
339
441
|
},
|
|
340
442
|
|
|
341
443
|
/**
|
|
342
|
-
* What a card shows of a job's
|
|
343
|
-
* fire outcome. `null` when the job is not a readable signed job.
|
|
444
|
+
* What a card shows of a job's schedule, as data (no words): the trigger (null = By hand), whether it is armed, the next slot (clock kinds), the last
|
|
445
|
+
* fire outcome of THIS signing (rows with its `sig`, never a wall-clock compare). `null` when the job is not a readable signed job.
|
|
344
446
|
* @param {string} flow
|
|
345
447
|
*/
|
|
346
448
|
read(flow) {
|
|
@@ -349,25 +451,49 @@ export function createTriggerDoor(opts) {
|
|
|
349
451
|
const r = readSigned(realRoot, flow);
|
|
350
452
|
if (!r.ok) return null;
|
|
351
453
|
const flowDir = join(realRoot, flow);
|
|
352
|
-
const
|
|
353
|
-
const
|
|
354
|
-
const
|
|
355
|
-
|
|
356
|
-
const since = Date.parse(r.signature.signedAt);
|
|
357
|
-
const outcomes = readOutcomes(flowDir).filter((o) => Date.parse(o.at) >= since);
|
|
454
|
+
const sc = liveSchedule(flowDir, r.signature.flow);
|
|
455
|
+
const trigger = sc === null ? null : sc.trigger;
|
|
456
|
+
const armedRow = sc === null ? undefined : readRows(ledgerOf(flowDir), sc.sig).find((x) => x.kind === 'armed');
|
|
457
|
+
const outcomes = sc === null ? [] : readOutcomes(flowDir).filter((o) => o.sig === sc.sig);
|
|
358
458
|
const clockKind = trigger !== null && (trigger.kind === 'daily' || trigger.kind === 'weekdays' || trigger.kind === 'weekly');
|
|
359
459
|
return {
|
|
360
|
-
flow, trigger, flowHash: r.signature.flow,
|
|
361
|
-
nextSlotMs: clockKind &&
|
|
460
|
+
flow, trigger, flowHash: r.signature.flow, sig: sc === null ? null : sc.sig, armed: armedRow !== undefined, armedAt: armedRow ? armedRow.at : null,
|
|
461
|
+
nextSlotMs: clockKind && armedRow ? nextSlot(/** @type {any} */ (trigger), now()) : null,
|
|
362
462
|
lastOutcome: outcomes.length > 0 ? outcomes[outcomes.length - 1] : null,
|
|
363
463
|
hasGreenRun: hasGreenRunForJob(flowDir),
|
|
364
464
|
};
|
|
365
465
|
},
|
|
366
466
|
|
|
467
|
+
/**
|
|
468
|
+
* M9 am6/am7: every fact the Job tab's Schedule field, a run's Audit schedule rows and the Run tab's SCHEDULE block are built from, for one job: the
|
|
469
|
+
* schedule, what it is bound to (the run it was set from, model, destination, inputs: what the fire reads from `schedule.json`), the fires of this signing
|
|
470
|
+
* (each one `triggers.jsonl` row with its `sig`) and the newest one. Data only; the words are `src/summary-words.js`'s. `null` when the job is not a readable signed job.
|
|
471
|
+
* @param {string} flow
|
|
472
|
+
*/
|
|
473
|
+
facts(flow) {
|
|
474
|
+
const base = this.read(flow);
|
|
475
|
+
if (base === null) return null;
|
|
476
|
+
const realRoot = /** @type {string} */ (realRootOrNull());
|
|
477
|
+
const flowDir = join(realRoot, flow);
|
|
478
|
+
const read = readSigned(realRoot, flow);
|
|
479
|
+
const sc = base.sig === null ? null : readSchedule(flowDir);
|
|
480
|
+
const rec = readModelRecord(flowDir);
|
|
481
|
+
const roles = read.ok ? (read.arbiter.sources ?? []).map((x) => x.role) : [];
|
|
482
|
+
const sources = sc !== null && sc.inputs !== null ? sc.inputs.map((x) => x.path) : Object.values(flowsDoor.lastSourcesOf(flow, roles).sources).filter(Boolean);
|
|
483
|
+
return {
|
|
484
|
+
...base,
|
|
485
|
+
from: sc ? sc.from : null,
|
|
486
|
+
model: sc && sc.model ? sc.model.model : (rec ? rec.model : null),
|
|
487
|
+
destination: sc && sc.destination ? sc.destination : (read.ok ? flowValues(read.arbiter).destination : null),
|
|
488
|
+
inputs: sources.map((p) => basename(String(p))),
|
|
489
|
+
fires: base.sig === null ? [] : readOutcomes(flowDir).filter((o) => o.sig === base.sig),
|
|
490
|
+
allFires: readOutcomes(flowDir), // M9 am9 item 4: the Audit's `tries` span every signing
|
|
491
|
+
};
|
|
492
|
+
},
|
|
493
|
+
|
|
367
494
|
/**
|
|
368
495
|
* What the Run card's dropdown needs of one job (M9 piece 5): the typed trigger, its words, whether it is armed, and, when the job has had
|
|
369
|
-
* no good run, the server's refusal sentence (the page shows it and disables the dropdown; it invents no words). `
|
|
370
|
-
* warning, set only when the job has a trigger. `null` when the job is not a readable signed job.
|
|
496
|
+
* no good run, the server's refusal sentence (the page shows it and disables the dropdown; it invents no words). `null` when the job is not a readable signed job.
|
|
371
497
|
* @param {string} flow
|
|
372
498
|
*/
|
|
373
499
|
card(flow) {
|
|
@@ -375,9 +501,8 @@ export function createTriggerDoor(opts) {
|
|
|
375
501
|
if (r === null) return null;
|
|
376
502
|
return {
|
|
377
503
|
trigger: r.trigger, words: scheduledWords(r.trigger), armed: r.armed, hasGreenRun: r.hasGreenRun,
|
|
378
|
-
refusal: r.hasGreenRun ? null : NO_GREEN_SAY,
|
|
504
|
+
refusal: r.hasGreenRun ? null : NO_GREEN_SAY,
|
|
379
505
|
};
|
|
380
506
|
},
|
|
381
507
|
};
|
|
382
508
|
}
|
|
383
|
-
|
|
@@ -24,6 +24,17 @@ export function leastResumeCapUsd(spentUsd, floorUsd) {
|
|
|
24
24
|
return Math.max(aboveSpent, Math.ceil(floorUsd * 100 - 1e-6) / 100);
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
/** The one decider (M4d am23/am24): is a cap at or below what is already spent? Used by the Cap note, Draft and a Resume. @param {number} capUsd @param {number} alreadyUsd */
|
|
28
|
+
export const capNotAboveSpent = (capUsd, alreadyUsd) => alreadyUsd > 0 && capUsd <= alreadyUsd + 1e-9;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The one sentence for a cap that is not above what is already spent (a Resume's door and note, and the Cap note of a card that belongs to a draft, M4d am23).
|
|
32
|
+
* @param {number} spentUsd @param {number} floorUsd
|
|
33
|
+
*/
|
|
34
|
+
export function capAboveSpentText(spentUsd, floorUsd) {
|
|
35
|
+
return `The cap must be above what is already spent (at least $${leastResumeCapUsd(spentUsd, floorUsd).toFixed(2)}).`;
|
|
36
|
+
}
|
|
37
|
+
|
|
27
38
|
/** @param {unknown} v */
|
|
28
39
|
const typed = (v) => (typeof v === 'string' ? v.trim() : v);
|
|
29
40
|
|
|
@@ -64,8 +75,8 @@ export function checkValues({
|
|
|
64
75
|
else capUsd = n;
|
|
65
76
|
}
|
|
66
77
|
if (refusals.length === 0) {
|
|
67
|
-
if (
|
|
68
|
-
no('capUsd',
|
|
78
|
+
if (capNotAboveSpent(capUsd, spentUsd)) {
|
|
79
|
+
no('capUsd', capAboveSpentText(spentUsd, floorUsd));
|
|
69
80
|
} else if (capUsd < floorUsd && (always || capUsd !== base.capUsd)) no('capUsd', capTooSmallText('run', capUsd, floorUsd, String(floorModel)));
|
|
70
81
|
}
|
|
71
82
|
|