fwdloop 0.13.0 → 0.15.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/bin/fwdloop +25 -12
- package/package.json +2 -2
- package/src/authoring.js +73 -39
- package/src/canrun.js +71 -1
- package/src/catalogue.json +2 -2
- package/src/checked.js +54 -0
- package/src/closers.js +112 -91
- package/src/declaration.js +115 -11
- package/src/drafter.js +139 -39
- package/src/flow.js +220 -5
- package/src/keysfile.js +4 -2
- package/src/model-step.js +1 -1
- package/src/monthly.js +139 -17
- package/src/panel/author.js +226 -64
- package/src/panel/authorcard.js +99 -4
- package/src/panel/authorflows.js +51 -10
- package/src/panel/authorresume.js +2 -2
- package/src/panel/authorstart.js +18 -10
- package/src/panel/data.js +147 -81
- package/src/panel/index.html +497 -338
- package/src/panel/server.js +5 -2
- package/src/panel/settings.js +1 -1
- package/src/runner.js +105 -48
- package/src/setup.js +21 -14
- package/src/signed-diff.js +71 -0
- package/types/authoring.d.ts +52 -14
- package/types/canrun.d.ts +33 -1
- package/types/checked.d.ts +25 -0
- package/types/closers.d.ts +47 -28
- package/types/declaration.d.ts +16 -2
- package/types/drafter.d.ts +146 -11
- package/types/flow.d.ts +42 -2
- package/types/model-step.d.ts +1 -6
- package/types/monthly.d.ts +25 -1
- package/types/panel/author.d.ts +55 -40
- package/types/panel/authorcard.d.ts +54 -0
- package/types/panel/authorflows.d.ts +39 -0
- package/types/panel/authorstart.d.ts +1 -0
- package/types/panel/data.d.ts +11 -56
- package/types/runner.d.ts +11 -3
- package/types/setup.d.ts +6 -12
- package/types/signed-diff.d.ts +10 -0
package/src/drafter.js
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
|
|
18
18
|
import { Loop, HaltError } from 'bare-agent';
|
|
19
19
|
import { parseSignedText, unsignedAskTtls } from './signed-text.js';
|
|
20
|
-
import { validateDeclaration, SHAPE_KEYS } from './declaration.js';
|
|
20
|
+
import { validateDeclaration, SHAPE_KEYS, checkGuardrailSums, guardrailWordsPerSection } from './declaration.js';
|
|
21
21
|
import { loadCatalogue } from './catalogue.js';
|
|
22
22
|
import { WIRED_VERBS, wiredMenu } from './primitives.js';
|
|
23
23
|
import { readInputFacts } from './input-facts.js';
|
|
@@ -32,8 +32,11 @@ export const DRAFT_SKILLS = Object.freeze(['core']);
|
|
|
32
32
|
|
|
33
33
|
export const CLASSES = Object.freeze(['green', 'softgreen', 'hitl']);
|
|
34
34
|
|
|
35
|
+
/** The whole-output-ceiling rule, told once to the drafter (schema and prompt use this string). Amendment 29; no number words (am25). */
|
|
36
|
+
export const WHOLE_OUTPUT_CEILING_RULE = "use the guardrail's ceiling for the whole output";
|
|
37
|
+
|
|
35
38
|
const SHAPE_PROPS = Object.freeze({
|
|
36
|
-
maxWords: { type: 'integer', minimum: 1, description:
|
|
39
|
+
maxWords: { type: 'integer', minimum: 1, description: `the whole output's word ceiling; ${WHOLE_OUTPUT_CEILING_RULE}` },
|
|
37
40
|
sections: { type: 'array', minItems: 1, items: { type: 'string', minLength: 1 }, description: 'required section headings, in order' },
|
|
38
41
|
linesPerInvoice: { type: 'integer', minimum: 1, description: 'lines the output must carry per invoice' },
|
|
39
42
|
mustCarry: { type: 'array', minItems: 1, items: { type: 'string', minLength: 1 }, description: 'named fields every line must carry' },
|
|
@@ -115,6 +118,94 @@ export function buildDeclarationSchema(menu) {
|
|
|
115
118
|
|
|
116
119
|
const TOOL = 'emit_declaration';
|
|
117
120
|
|
|
121
|
+
// ---- M4e amendments 24 + 25: questions (try 3 only) and "not checked" (every try) ---------------------------------
|
|
122
|
+
// borrowed-from: fwdloop poc/am24-questions/draft.mjs@dda0e0f (prompts, linesNamedByReds, normalizeQuestions), adjusted to the product drafter.
|
|
123
|
+
export const MAX_QUESTIONS = 2;
|
|
124
|
+
|
|
125
|
+
/** What fwdloop's typed checks can really check (bareloop F174: give the model the real list, or "Not checked" is invented). */
|
|
126
|
+
export const CHECKABLE = Object.freeze([
|
|
127
|
+
'green: a figure cites its source cell or formula',
|
|
128
|
+
'softgreen: the output carries named section headings (sections), in order',
|
|
129
|
+
`softgreen: a word ceiling for the whole output (maxWords; ${WHOLE_OUTPUT_CEILING_RULE}) and per section (wordsPerSection)`,
|
|
130
|
+
'softgreen: a line count per invoice (linesPerInvoice) and fields every line must carry (mustCarry)',
|
|
131
|
+
'hitl: a human accepts or reviews at a signed ask — the machine checks only that the step happened',
|
|
132
|
+
]);
|
|
133
|
+
|
|
134
|
+
/** Offered on EVERY try (it is information, not asking). */
|
|
135
|
+
export const NOTCHECKED_PROMPT = [
|
|
136
|
+
'notChecked (optional): a short list of things about the job that no check below will verify. These are the ONLY things fwdloop can check:',
|
|
137
|
+
...CHECKABLE.map((c) => `- ${c}`),
|
|
138
|
+
'Anything the job asks for beyond those (tone, correctness of prose, completeness, matching a taste) is NOT checked: list it in "notChecked", a plain short phrase each. [] or leave out if nothing.',
|
|
139
|
+
].join('\n');
|
|
140
|
+
|
|
141
|
+
/** Try 3 only, and only after tries 1 and 2 both failed validation. No digit and no number word anywhere (a test greps this): the machine, not the prompt, bounds the count. */
|
|
142
|
+
export const QUESTIONS_PROMPT = [
|
|
143
|
+
'You may add "questions" to this reply. Ask only about a job line named in the refusals above, and only if that line cannot be drafted without the answer',
|
|
144
|
+
'(an undefined size, format, destination, or what "done" means). Each question is {line, question}: "line" is the number of the job line it is about.',
|
|
145
|
+
'If the refusals can be fixed without asking, fix them and leave "questions" out. Never ask about a trigger, cap, ask position or TTL, allow-list or send target (signed, not yours).',
|
|
146
|
+
'Still emit the complete corrected declaration.',
|
|
147
|
+
].join('\n');
|
|
148
|
+
|
|
149
|
+
/** The declaration schema plus the optional `notChecked` (every try) and, on try 3 only, `questions`. Neither is in `required`. */
|
|
150
|
+
export function buildRoundSchema(menu, { questions = false } = {}) {
|
|
151
|
+
const s = buildDeclarationSchema(menu);
|
|
152
|
+
const extra = { notChecked: { type: 'array', items: { type: 'string' }, description: 'what the job asks for that no typed check verifies' } };
|
|
153
|
+
if (questions) {
|
|
154
|
+
extra.questions = {
|
|
155
|
+
type: 'array',
|
|
156
|
+
items: {
|
|
157
|
+
type: 'object',
|
|
158
|
+
properties: { line: { type: 'integer' }, question: { type: 'string' } },
|
|
159
|
+
required: ['line', 'question'],
|
|
160
|
+
},
|
|
161
|
+
description: 'questions the job cannot be drafted without; each names the job line it is about',
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
return { ...s, properties: { ...s.properties, ...extra } };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Which job lines did these reds name? Reds name a line three ways: "line N" (also "ask at line N", "(line N)",
|
|
169
|
+
* "guardrailClasses key \"N\""), "steps[i]" (mapped through that declaration's steps[i].fromLine), and "step N's check"
|
|
170
|
+
* (1-based). A red naming none (a missing top-level key, an unknown key) names no line. Returns sorted real line numbers.
|
|
171
|
+
*/
|
|
172
|
+
export function linesNamedByReds(reds, declaration, lineNums) {
|
|
173
|
+
const found = new Set();
|
|
174
|
+
const steps = Array.isArray(declaration?.steps) ? declaration.steps : [];
|
|
175
|
+
const stepLine = (i) => (isPlainObject(steps[i]) && Number.isInteger(steps[i].fromLine) ? steps[i].fromLine : null);
|
|
176
|
+
for (const red of reds) {
|
|
177
|
+
for (const m of red.matchAll(/\bline (\d+)\b/g)) found.add(Number(m[1]));
|
|
178
|
+
for (const m of red.matchAll(/guardrailClasses key "(\d+)"|unjudgeable key "(\d+)"/g)) found.add(Number(m[1] ?? m[2]));
|
|
179
|
+
for (const m of red.matchAll(/steps\[(\d+)\]/g)) { const n = stepLine(Number(m[1])); if (n !== null) found.add(n); }
|
|
180
|
+
for (const m of red.matchAll(/\bstep (\d+)'s check/g)) { const n = stepLine(Number(m[1]) - 1); if (n !== null) found.add(n); }
|
|
181
|
+
}
|
|
182
|
+
return [...found].filter((n) => lineNums.includes(n)).sort((x, y) => x - y);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Amendment 25: a question is kept only if its line is one try 2's reds named; no line, a blank question or a third question is
|
|
187
|
+
* dropped. Every drop comes back with its reason, for the draft's log. Returns {kept, dropped}.
|
|
188
|
+
*/
|
|
189
|
+
export function normalizeQuestions(raw, failedLines) {
|
|
190
|
+
const kept = [];
|
|
191
|
+
const dropped = [];
|
|
192
|
+
if (raw === undefined || raw === null) return { kept, dropped };
|
|
193
|
+
if (!Array.isArray(raw)) return { kept, dropped: [{ reason: 'questions is not a list', raw }] };
|
|
194
|
+
for (const q of raw) {
|
|
195
|
+
if (!isPlainObject(q) || !Number.isInteger(q.line)) { dropped.push({ reason: 'no line', raw: q }); continue; }
|
|
196
|
+
if (!failedLines.includes(q.line)) { dropped.push({ reason: `line ${q.line} is not a line try 2's checks failed on`, raw: q }); continue; }
|
|
197
|
+
if (typeof q.question !== 'string' || q.question.trim() === '') { dropped.push({ reason: 'blank question', raw: q }); continue; }
|
|
198
|
+
if (kept.length >= MAX_QUESTIONS) { dropped.push({ reason: 'third question', raw: q }); continue; }
|
|
199
|
+
kept.push({ line: q.line, question: q.question.trim() });
|
|
200
|
+
}
|
|
201
|
+
return { kept, dropped };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** `notChecked` as the model sent it: non-blank strings only, trimmed. Anything else is an empty list. */
|
|
205
|
+
function cleanNotChecked(raw) {
|
|
206
|
+
return Array.isArray(raw) ? raw.filter((x) => typeof x === 'string' && x.trim() !== '').map((x) => x.trim()) : [];
|
|
207
|
+
}
|
|
208
|
+
|
|
118
209
|
function jobLinesText(lines, asks) {
|
|
119
210
|
const askLines = new Set(asks.map((a) => a.line));
|
|
120
211
|
return lines
|
|
@@ -138,6 +229,7 @@ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
|
|
|
138
229
|
'- guardrailClasses: for each job line that HAS a guardrail, classify its wording once: "green" (every figure must cite its source cell), "softgreen" (the human declared a SHAPE the output must take), "hitl" (an ask/accept/review gate, or anything you are not sure of). When unsure, "hitl".',
|
|
139
230
|
'- close.class MUST equal the class of the guardrail on that step\'s fromLine (guardrailClasses[fromLine]); a line with no guardrail is "hitl". A step cannot claim a class its own line does not earn.',
|
|
140
231
|
'- close.shape only on a softgreen step; it is the human\'s declared shape in structured form.',
|
|
232
|
+
'- A step whose check reads its reply (softgreen) answers in its reply text and is never granted `write`, `edit` or any other write-class verb; only the send step at the end writes files out.',
|
|
141
233
|
`- Signed ask line(s): ${askLines.length ? askLines.join(', ') : 'none'}. For each, emit EXACTLY ONE step: fromLine = that line, close.class "hitl", primitives []. It is a stop only — never grant a primitive on it, and never emit a pause at any other line.`,
|
|
142
234
|
`- Signed send line(s): ${sendLines.length ? sendLines.join(', ') : 'none'}. That step is drafted like any other: grant the write primitive and read the artifact of the ask step that comes before it. Its target and position are signed, not yours.`,
|
|
143
235
|
'- Nothing hitl may come after the last signed ask except the send step.',
|
|
@@ -166,33 +258,6 @@ function reviseMessage(reds) {
|
|
|
166
258
|
+ `${TOOL} again with the complete corrected declaration:\n${reds.map((r) => `- ${r}`).join('\n')}`;
|
|
167
259
|
}
|
|
168
260
|
|
|
169
|
-
/**
|
|
170
|
-
* M4e amendment 3 item 3 (revise the plan): the first round's user text when the human asked for a change. The model sees the
|
|
171
|
-
* current plan (its own fields only: no machine-set `goal`, no `inputFacts`) and the note; the rules above still hold, and the
|
|
172
|
-
* validator below is the ONE check that refuses a plan that touches what only the card may set.
|
|
173
|
-
*/
|
|
174
|
-
export function reviseOpening(plan, note) {
|
|
175
|
-
const own = {
|
|
176
|
-
steps: (plan.steps ?? []).map(({ goal, ...rest }) => rest), // eslint-disable-line no-unused-vars
|
|
177
|
-
guardrailClasses: plan.guardrailClasses ?? {},
|
|
178
|
-
unjudgeable: plan.unjudgeable ?? {},
|
|
179
|
-
refused: plan.refused ?? [],
|
|
180
|
-
};
|
|
181
|
-
return [
|
|
182
|
-
`The human reviewed the plan below and asks for a change to the plan. Call ${TOOL} with the complete revised plan.`,
|
|
183
|
-
'',
|
|
184
|
-
'Current plan:',
|
|
185
|
-
JSON.stringify(own),
|
|
186
|
-
'',
|
|
187
|
-
'The human\'s note:',
|
|
188
|
-
note,
|
|
189
|
-
'',
|
|
190
|
-
'The note may change HOW steps are done (their primitives, reads, close checks). It can never change the numbered job lines, '
|
|
191
|
-
+ 'the cap, the destination, the signed asks and their waits, or the inputs: those come only from the card, so keep every '
|
|
192
|
-
+ 'line served by its step and every signed ask a pure stop exactly as the rules above say.',
|
|
193
|
-
].join('\n');
|
|
194
|
-
}
|
|
195
|
-
|
|
196
261
|
function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArray(v); }
|
|
197
262
|
|
|
198
263
|
// F49: deepseek-flash 400s on a forced tool_choice in thinking mode; the drafter forces its tool, so disable thinking.
|
|
@@ -207,15 +272,14 @@ export const DRAFT_PROVIDER_OPTIONS = Object.freeze({ ...LIVE_PROVIDER_OPTIONS,
|
|
|
207
272
|
* `calls`) and right AFTER it (`inFlight: false`), with what is known so far, so the caller can book spend per call
|
|
208
273
|
* and a draft killed between rounds still has its paid rounds on disk. It may throw before a call (nothing is
|
|
209
274
|
* spent then and the draft stops); after a call it is the caller's to keep from throwing.
|
|
210
|
-
* `revise` (M4e amendment 3 item 3): `{ plan, note }` — the current green plan and the human's note; the first round then asks for the
|
|
211
|
-
* revised plan. Everything else (the $0 gates, the validator, the budget, the metering) is the same code path as a first draft.
|
|
212
275
|
*
|
|
213
276
|
* @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
|
|
214
|
-
* costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[]
|
|
277
|
+
* costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[],
|
|
278
|
+
* questions?:{line:number, question:string}[], droppedQuestions?:object[], notChecked?:string[]}>}
|
|
215
279
|
*/
|
|
216
280
|
export async function draft({
|
|
217
281
|
proseText, slot = 'deepseek', model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
|
|
218
|
-
budgetUsd = 0.10, skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook,
|
|
282
|
+
budgetUsd = 0.10, skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true,
|
|
219
283
|
}) {
|
|
220
284
|
const fail = (reds, extra = {}) => ({
|
|
221
285
|
ok: false, declaration: null, reds, rounds: 0, calls: 0, spendComplete: true, costUsd: 0, modelReturned: null, structureRetries: 0, revisions: 0, stop: 'pre-flight', log: [], ...extra,
|
|
@@ -227,6 +291,9 @@ export async function draft({
|
|
|
227
291
|
const { lines, arbiter } = parsed;
|
|
228
292
|
const ttlReds = unsignedAskTtls(arbiter);
|
|
229
293
|
if (ttlReds.length) return fail(ttlReds);
|
|
294
|
+
// M4e amendment 15 item 2: a guardrail that fights itself on words is red at $0, before any provider is built or called.
|
|
295
|
+
const sumReds = checkGuardrailSums(lines);
|
|
296
|
+
if (sumReds.length) return fail(sumReds);
|
|
230
297
|
const menu = wiredMenu(skills);
|
|
231
298
|
const facts = readInputFacts(arbiter.sources);
|
|
232
299
|
if (!facts.ok) return fail(facts.reds);
|
|
@@ -243,8 +310,10 @@ export async function draft({
|
|
|
243
310
|
}
|
|
244
311
|
}
|
|
245
312
|
|
|
246
|
-
|
|
247
|
-
const
|
|
313
|
+
// `notChecked` is offered on every try (information, not asking); `questions` only on try 3 (below).
|
|
314
|
+
const baseSystem = buildSystemPrompt({ menu, lines, arbiter, factsInfo: facts.info });
|
|
315
|
+
const system = `${baseSystem}\n\n${NOTCHECKED_PROMPT}`;
|
|
316
|
+
const lineNums = lines.map((l) => l.n);
|
|
248
317
|
// Full catalogue + the wired set: an unwired verb reds "not wired" by name; an unsigned skill reds by skill.
|
|
249
318
|
const cat = loadCatalogue();
|
|
250
319
|
if (!cat.ok) return fail([`catalogue: ${cat.reds.join('; ')}`]);
|
|
@@ -261,10 +330,13 @@ export async function draft({
|
|
|
261
330
|
let revisions = 0;
|
|
262
331
|
let lastReds = [];
|
|
263
332
|
let lastDecl = null;
|
|
264
|
-
let userText =
|
|
333
|
+
let userText = `Call ${TOOL} now.`;
|
|
265
334
|
let nextKind = 'first'; // what the round about to run actually is
|
|
266
335
|
let validatorReds = []; // the last validator refusal; a structure retry after a revision must not drop it
|
|
267
336
|
let stop = null;
|
|
337
|
+
let failedLines = []; // the job lines try 2's reds named: a question is kept only about one of these (amendment 25)
|
|
338
|
+
/** @type {{questions:{line:number, question:string}[], droppedQuestions:object[], notChecked:string[]}} */
|
|
339
|
+
let extras = { questions: [], droppedQuestions: [], notChecked: [] }; // from the round that produced `lastDecl`, never an earlier one
|
|
268
340
|
let calls = 0; // provider calls made (a call that threw before metering is in `calls`, not in `rounds`)
|
|
269
341
|
let unmetered = 0; // calls that failed with no metering: their cost is unknown
|
|
270
342
|
|
|
@@ -274,7 +346,13 @@ export async function draft({
|
|
|
274
346
|
const spent = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
|
|
275
347
|
if (spent + roundCeiling > budgetUsd) { stop = 'budget'; break; }
|
|
276
348
|
|
|
349
|
+
// assigned inside the tool's execute callback, which TS cannot see
|
|
350
|
+
/** @type {any} */
|
|
277
351
|
let captured;
|
|
352
|
+
// Amendment 25: a lock is a mechanism. Only try 3 of 3, and only when tries 1 and 2 BOTH failed validation (`revisions` counts the
|
|
353
|
+
// validator's refusals fed back), gets the `questions` property; the redraft after an answer passes offerQuestions:false and never does.
|
|
354
|
+
const askOpen = offerQuestions && revisions === MAX_REVISIONS;
|
|
355
|
+
const schema = buildRoundSchema(menu, { questions: askOpen });
|
|
278
356
|
const tool = {
|
|
279
357
|
name: TOOL,
|
|
280
358
|
description: 'Emit the flow declaration over the granted primitives, or refuse lines you cannot serve.',
|
|
@@ -326,24 +404,42 @@ export async function draft({
|
|
|
326
404
|
nextKind = 'structure-retry';
|
|
327
405
|
userText = `Your last reply was not a usable tool call (${why}). Call ${TOOL} now with a complete, valid JSON declaration.`;
|
|
328
406
|
if (validatorReds.length) userText += `\n\nThe last declaration you emitted was still refused by the validator; keep fixing these too:\n${validatorReds.map((r) => `- ${r}`).join('\n')}`;
|
|
407
|
+
if (askOpen) userText += `\n\n${QUESTIONS_PROMPT}`;
|
|
329
408
|
continue;
|
|
330
409
|
}
|
|
331
410
|
|
|
332
|
-
|
|
411
|
+
// `notChecked` was offered on every try, so it is information and never reaches the validator. `questions` is stripped only where it was
|
|
412
|
+
// offered; sent when not offered it stays, and the validator reds it as an unknown key (a stray key, never a silent pass).
|
|
413
|
+
const { questions: rawQuestions, notChecked: rawNotChecked, ...captureRest } = /** @type {Record<string, any>} */ (captured);
|
|
414
|
+
/** @type {Record<string, any>} */
|
|
415
|
+
const declaration = { ...(askOpen ? captureRest : { ...captureRest, ...(rawQuestions === undefined ? {} : { questions: rawQuestions }) }), inputFacts: facts.inputFacts };
|
|
333
416
|
// M6a amendment 1 (F50): the goal is the signed line, set by the machine; whatever the model sent is overwritten.
|
|
334
417
|
if (Array.isArray(declaration.steps)) {
|
|
335
418
|
declaration.steps = declaration.steps.map((st) => (isPlainObject(st) ? { ...st, goal: goalForLine(st.fromLine, lines) } : st));
|
|
336
419
|
}
|
|
420
|
+
// M4e amendment 15 item 1: `wordsPerSection` is the guardrail's number, set by the machine. If the model sent one it is overwritten
|
|
421
|
+
// (or dropped when the guardrail gives none), so it can never differ from the guardrail.
|
|
422
|
+
if (Array.isArray(declaration.steps)) {
|
|
423
|
+
declaration.steps = declaration.steps.map((st) => {
|
|
424
|
+
if (!isPlainObject(st) || !isPlainObject(st.close) || !isPlainObject(st.close.shape)) return st;
|
|
425
|
+
const { wordsPerSection: _drop, ...shape } = st.close.shape;
|
|
426
|
+
const per = guardrailWordsPerSection(lines.find((l) => l.n === st.fromLine)?.guardrail);
|
|
427
|
+
return { ...st, close: { ...st.close, shape: per === null ? shape : { ...shape, wordsPerSection: per } } };
|
|
428
|
+
});
|
|
429
|
+
}
|
|
337
430
|
const verdict = validateDeclaration(declaration, {
|
|
338
431
|
arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
|
|
339
432
|
});
|
|
340
433
|
lastDecl = declaration;
|
|
434
|
+
const asked = askOpen ? normalizeQuestions(rawQuestions, failedLines) : { kept: [], dropped: [] };
|
|
435
|
+
extras = { questions: asked.kept, droppedQuestions: asked.dropped, notChecked: cleanNotChecked(rawNotChecked) };
|
|
436
|
+
if (asked.dropped.length) entry.droppedQuestions = asked.dropped;
|
|
341
437
|
if (verdict.ok) {
|
|
342
438
|
entry.outcome = 'valid';
|
|
343
439
|
log.push(entry);
|
|
344
440
|
const m = sumMeterings(meterings);
|
|
345
441
|
return {
|
|
346
|
-
ok: true, declaration, reds: [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop: null, log,
|
|
442
|
+
ok: true, declaration, reds: [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop: null, log, ...extras,
|
|
347
443
|
};
|
|
348
444
|
}
|
|
349
445
|
lastReds = [...verdict.reds];
|
|
@@ -355,12 +451,16 @@ export async function draft({
|
|
|
355
451
|
validatorReds = lastReds;
|
|
356
452
|
nextKind = 'revision';
|
|
357
453
|
userText = reviseMessage(lastReds);
|
|
454
|
+
if (offerQuestions && revisions === MAX_REVISIONS) {
|
|
455
|
+
failedLines = linesNamedByReds(lastReds, declaration, lineNums);
|
|
456
|
+
userText += `\n\n${QUESTIONS_PROMPT}`;
|
|
457
|
+
}
|
|
358
458
|
}
|
|
359
459
|
|
|
360
460
|
const m = sumMeterings(meterings);
|
|
361
461
|
// Runner convention: `costUsd` is the priced sum (null when ANY round is unpriced, so the CLI prints UNKNOWN,
|
|
362
462
|
// never a bare number), and `spendComplete:false` marks a call that failed unmetered or a round left unpriced.
|
|
363
463
|
return {
|
|
364
|
-
ok: false, declaration: lastDecl, reds: lastReds, rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop, log,
|
|
464
|
+
ok: false, declaration: lastDecl, reds: lastReds, rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop, log, ...extras,
|
|
365
465
|
};
|
|
366
466
|
}
|
package/src/flow.js
CHANGED
|
@@ -28,6 +28,7 @@ import path from 'node:path';
|
|
|
28
28
|
import { parseSignedText } from './signed-text.js';
|
|
29
29
|
import { signFlow, verifyFlow } from './signature.js';
|
|
30
30
|
import { validateDeclaration } from './declaration.js';
|
|
31
|
+
import { describeChange } from './signed-diff.js';
|
|
31
32
|
|
|
32
33
|
/** @typedef {import('./types.js').WriteFlowResult} WriteFlowResult */
|
|
33
34
|
/** @typedef {import('./types.js').ReadFlowResult} ReadFlowResult */
|
|
@@ -40,6 +41,15 @@ export const FLOW_FILES = Object.freeze(['prose.txt', 'declaration.json', 'signa
|
|
|
40
41
|
export const PANEL_STARTS_DIR = '.starts';
|
|
41
42
|
|
|
42
43
|
const RUNS_DIR = 'runs';
|
|
44
|
+
/** Amendment 43: the write-once copy of the two signed files, made at sign by `writeFlow` (the ONE writer). Outside FLOW_FILES: it never enters the signature or `readFlow`'s success path. */
|
|
45
|
+
const SIGNED_COPY_DIR = 'signed';
|
|
46
|
+
const CHANGED_PREFIX = 'changed since signing: ';
|
|
47
|
+
|
|
48
|
+
/** The plain "what changed" sentences inside a readFlow refusal (am43), joined for a sentence a human reads; '' when there are none. @param {string[]} reds */
|
|
49
|
+
export function changeSentence(reds) {
|
|
50
|
+
const xs = reds.filter((r) => typeof r === 'string' && r.startsWith(CHANGED_PREFIX)).map((r) => r.slice(CHANGED_PREFIX.length));
|
|
51
|
+
return xs.length > 0 ? ` What changed: ${xs.join('; ')}.` : '';
|
|
52
|
+
}
|
|
43
53
|
|
|
44
54
|
/**
|
|
45
55
|
* Check a flow name against the allowed shape: 1..64 characters, lowercase
|
|
@@ -404,11 +414,14 @@ function readTextFile(filePath, label, reds) {
|
|
|
404
414
|
* last (each via a temp file + rename in the same directory), creates an
|
|
405
415
|
* empty `runs/`, and proves the result by reading it back with `readFlow`.
|
|
406
416
|
*
|
|
407
|
-
*
|
|
417
|
+
* M6: with `replaces: {flowHash}` it instead REPLACES the signed job already under that name (see `replaceSigned`), and only if that job is
|
|
418
|
+
* still the one with that signature hash. `onReplaceStep` is a test seam: called after each move of the swap; a throw there is a failure.
|
|
419
|
+
*
|
|
420
|
+
* @param {{root: unknown, name: unknown, proseText: unknown, declaration: unknown, signedBy: unknown, signedAt: unknown, catalogue: unknown, replaces?: {flowHash: string}, onReplaceStep?: (step: string) => void}} input
|
|
408
421
|
* @returns {WriteFlowResult}
|
|
409
422
|
*/
|
|
410
423
|
export function writeFlow({
|
|
411
|
-
root, name, proseText, declaration, signedBy, signedAt, catalogue,
|
|
424
|
+
root, name, proseText, declaration, signedBy, signedAt, catalogue, replaces, onReplaceStep,
|
|
412
425
|
}) {
|
|
413
426
|
const nameCheck = checkFlowName(name);
|
|
414
427
|
if (!nameCheck.ok) return { ok: false, reds: [nameCheck.red] };
|
|
@@ -440,6 +453,12 @@ export function writeFlow({
|
|
|
440
453
|
|
|
441
454
|
const dir = path.join(root, safeName);
|
|
442
455
|
|
|
456
|
+
if (replaces !== undefined) {
|
|
457
|
+
return replaceSigned({
|
|
458
|
+
root, name: safeName, dir, proseText: /** @type {string} */ (proseText), declarationText, signature: signResult.signature, replaces, catalogue, onReplaceStep,
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
|
|
443
462
|
// Refuse if any of the three files already exists — M1 never overwrites a
|
|
444
463
|
// signed flow (versions are M4).
|
|
445
464
|
for (const fileName of FLOW_FILES) {
|
|
@@ -455,6 +474,10 @@ export function writeFlow({
|
|
|
455
474
|
}
|
|
456
475
|
}
|
|
457
476
|
|
|
477
|
+
if (existsSync(path.join(dir, SIGNED_COPY_DIR))) {
|
|
478
|
+
return { ok: false, reds: [`flow: "${SIGNED_COPY_DIR}" already exists at ${path.join(dir, SIGNED_COPY_DIR)}`] };
|
|
479
|
+
}
|
|
480
|
+
|
|
458
481
|
// Track what THIS call creates so a failure partway through can be rolled
|
|
459
482
|
// back — a directory must never be left with a signature but a missing
|
|
460
483
|
// file.
|
|
@@ -466,7 +489,7 @@ export function writeFlow({
|
|
|
466
489
|
if (createdDir) {
|
|
467
490
|
rmSync(dir, { recursive: true, force: true });
|
|
468
491
|
} else {
|
|
469
|
-
for (const p of written) rmSync(p, { force: true });
|
|
492
|
+
for (const p of written) rmSync(p, { recursive: true, force: true });
|
|
470
493
|
}
|
|
471
494
|
} catch {
|
|
472
495
|
// best-effort cleanup; the red already reports the real failure
|
|
@@ -495,6 +518,12 @@ export function writeFlow({
|
|
|
495
518
|
try {
|
|
496
519
|
writeOne('prose.txt', proseText);
|
|
497
520
|
writeOne('declaration.json', declarationText);
|
|
521
|
+
// am43: the copy of what is being signed, write-once (`wx` refuses an existing file), before the signature that makes it a signed flow.
|
|
522
|
+
const copyDir = path.join(dir, SIGNED_COPY_DIR);
|
|
523
|
+
mkdirSync(copyDir);
|
|
524
|
+
written.push(copyDir);
|
|
525
|
+
writeFileSync(path.join(copyDir, 'prose.txt'), /** @type {string} */ (proseText), { encoding: 'utf8', flag: 'wx' });
|
|
526
|
+
writeFileSync(path.join(copyDir, 'declaration.json'), declarationText, { encoding: 'utf8', flag: 'wx' });
|
|
498
527
|
writeOne('signature.json', `${JSON.stringify(signResult.signature, null, 2)}\n`);
|
|
499
528
|
|
|
500
529
|
const runsDir = path.join(dir, RUNS_DIR);
|
|
@@ -517,6 +546,95 @@ export function writeFlow({
|
|
|
517
546
|
};
|
|
518
547
|
}
|
|
519
548
|
|
|
549
|
+
/**
|
|
550
|
+
* The signature hash (`signature.json` `flow`) of the signed job in `flowDir`, or null when there is no readable one. It does NOT verify the
|
|
551
|
+
* files (that is `readFlow`): it only says which signing this folder is at, for M6's "was this job signed again since you opened it".
|
|
552
|
+
* @param {string} flowDir @returns {string|null}
|
|
553
|
+
*/
|
|
554
|
+
export function signedHashOf(flowDir) {
|
|
555
|
+
const f = readFileInside(flowDir, 'signature.json');
|
|
556
|
+
if (!f.ok) return null;
|
|
557
|
+
try { const h = JSON.parse(f.text)?.flow; return typeof h === 'string' && h !== '' ? h : null; } catch { return null; }
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
/** M6: the names `replaceSigned` swaps, signature last (the file that makes the folder a signed flow). `setup.jsonl` is only moved away: the caller writes the new one. */
|
|
561
|
+
const SWAP_NAMES = ['prose.txt', 'declaration.json', SIGNED_COPY_DIR, 'setup.jsonl', 'signature.json'];
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* M6 ("Signing replaces the job"): replace the signed job in `<root>/<name>/`, ALL OR NOTHING, keeping the name, `runs/` and the flow's books.
|
|
565
|
+
* Refuses (touching nothing) unless the folder holds a signed job whose `signature.json` `flow` hash is `replaces.flowHash` (a draft opened from an
|
|
566
|
+
* older version of the job, or a job signed again meanwhile, is refused by name). The new files are staged inside the folder first; the swap then moves
|
|
567
|
+
* each old file into a backup folder and its new one into place (signature last); ANY failure, or a proof read that does not verify, moves everything
|
|
568
|
+
* back. On success the backup is deleted — no old version is kept anywhere (hamr's ruling). Only a hard kill inside the swap leaves the backup
|
|
569
|
+
* (`.replace-old-*`) holding the old files; nothing recovers it automatically.
|
|
570
|
+
* @param {{root: string, name: string, dir: string, proseText: string, declarationText: string, signature: any, replaces: {flowHash: string}, catalogue: unknown, onReplaceStep?: (step: string) => void}} a
|
|
571
|
+
* @returns {WriteFlowResult}
|
|
572
|
+
*/
|
|
573
|
+
function replaceSigned({
|
|
574
|
+
root, name, dir, proseText, declarationText, signature, replaces, catalogue, onReplaceStep,
|
|
575
|
+
}) {
|
|
576
|
+
const red = (/** @type {string} */ r) => ({ ok: /** @type {false} */ (false), reds: [r] });
|
|
577
|
+
let dirStat;
|
|
578
|
+
try { dirStat = lstatSync(dir); } catch { return red(`flow: nothing signed to replace — "${name}" has no folder here`); }
|
|
579
|
+
if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) return red(`flow: "${dir}" is not a plain folder, refused`);
|
|
580
|
+
const current = signedHashOf(dir);
|
|
581
|
+
if (current === null) return red(`flow: nothing signed to replace — "${name}" has no readable signature.json`);
|
|
582
|
+
if (typeof replaces?.flowHash !== 'string' || current !== replaces.flowHash) {
|
|
583
|
+
return red(`flow: "${name}" was signed again since you opened it for editing, so this edit is out of date. Nothing was changed. Open the job again and redo the edit.`);
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
const stamp = `${process.pid}-${Date.now()}`;
|
|
587
|
+
const stage = path.join(dir, `.replace-new-${stamp}`);
|
|
588
|
+
const backup = path.join(dir, `.replace-old-${stamp}`);
|
|
589
|
+
const moved = []; // names whose OLD file is now in backup
|
|
590
|
+
const placed = []; // names whose NEW file is now in dir
|
|
591
|
+
const cleanup = () => {
|
|
592
|
+
for (const p of [stage, backup]) { try { rmSync(p, { recursive: true, force: true }); } catch { /* best-effort */ } }
|
|
593
|
+
};
|
|
594
|
+
const putBack = () => {
|
|
595
|
+
for (const n of [...placed].reverse()) rmSync(path.join(dir, n), { recursive: true, force: true });
|
|
596
|
+
for (const n of [...moved].reverse()) renameSync(path.join(backup, n), path.join(dir, n));
|
|
597
|
+
};
|
|
598
|
+
const fail = (/** @type {string} */ why) => {
|
|
599
|
+
try { putBack(); } catch (err) {
|
|
600
|
+
// the old files could not all be put back: say where they are rather than pretend (the backup is NOT cleaned up)
|
|
601
|
+
return red(`flow: ${why}; the old job could not be fully put back (${err.message}) — its files are in ${backup}`);
|
|
602
|
+
}
|
|
603
|
+
cleanup();
|
|
604
|
+
return red(`flow: ${why}`);
|
|
605
|
+
};
|
|
606
|
+
|
|
607
|
+
try {
|
|
608
|
+
mkdirSync(stage);
|
|
609
|
+
mkdirSync(backup);
|
|
610
|
+
mkdirSync(path.join(stage, SIGNED_COPY_DIR));
|
|
611
|
+
writeFileSync(path.join(stage, 'prose.txt'), proseText, 'utf8');
|
|
612
|
+
writeFileSync(path.join(stage, 'declaration.json'), declarationText, 'utf8');
|
|
613
|
+
writeFileSync(path.join(stage, SIGNED_COPY_DIR, 'prose.txt'), proseText, { encoding: 'utf8', flag: 'wx' });
|
|
614
|
+
writeFileSync(path.join(stage, SIGNED_COPY_DIR, 'declaration.json'), declarationText, { encoding: 'utf8', flag: 'wx' });
|
|
615
|
+
writeFileSync(path.join(stage, 'signature.json'), `${JSON.stringify(signature, null, 2)}\n`, 'utf8');
|
|
616
|
+
} catch (err) {
|
|
617
|
+
cleanup();
|
|
618
|
+
return red(`flow: could not stage the new files — ${err.message}. Nothing was changed.`);
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
try {
|
|
622
|
+
for (const n of SWAP_NAMES) {
|
|
623
|
+
if (existsSync(path.join(dir, n))) { renameSync(path.join(dir, n), path.join(backup, n)); moved.push(n); }
|
|
624
|
+
if (existsSync(path.join(stage, n))) { renameSync(path.join(stage, n), path.join(dir, n)); placed.push(n); }
|
|
625
|
+
onReplaceStep?.(n);
|
|
626
|
+
}
|
|
627
|
+
} catch (err) {
|
|
628
|
+
return fail(`could not replace the job — ${err.message}`);
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
// the mechanical "it happened" check, as at sign: read the replaced job back through the one reader
|
|
632
|
+
const proof = readFlow({ root, name, catalogue });
|
|
633
|
+
if (!proof.ok) return fail(`the replaced job does not verify (${proof.reds.join('; ')})`);
|
|
634
|
+
cleanup();
|
|
635
|
+
return { ok: true, dir, signature };
|
|
636
|
+
}
|
|
637
|
+
|
|
520
638
|
/**
|
|
521
639
|
* Read and verify a signed flow from `<root>/<name>/`. Verifies the bytes on
|
|
522
640
|
* disk against the signature FIRST — before anything in the flow is
|
|
@@ -602,8 +720,21 @@ export function readFlow({ root, name, catalogue }) {
|
|
|
602
720
|
const verified = verifyFlow({
|
|
603
721
|
proseText, declarationText, signature: signatureJson,
|
|
604
722
|
});
|
|
605
|
-
if (!verified.ok) return { ok: false, reds: verified.reds };
|
|
723
|
+
if (!verified.ok) return { ok: false, reds: [...verified.reds, ...explainEdit(dir, signatureJson, /** @type {string} */ (proseText), /** @type {string} */ (declarationText))] };
|
|
606
724
|
|
|
725
|
+
return interpretSigned({
|
|
726
|
+
proseText: /** @type {string} */ (proseText), declarationJson, signatureJson, catalogue, dir,
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/**
|
|
731
|
+
* The part of a read that follows a passed signature check, shared by `readFlow` and `readRunJobCopy`: parse the signed text, validate the declaration.
|
|
732
|
+
* @param {{proseText: string, declarationJson: any, signatureJson: any, catalogue: unknown, dir: string}} a
|
|
733
|
+
* @returns {ReadFlowResult}
|
|
734
|
+
*/
|
|
735
|
+
function interpretSigned({
|
|
736
|
+
proseText, declarationJson, signatureJson, catalogue, dir,
|
|
737
|
+
}) {
|
|
607
738
|
const signed = parseSignedText(proseText);
|
|
608
739
|
if (!signed.ok) return { ok: false, reds: signed.reds };
|
|
609
740
|
|
|
@@ -613,7 +744,7 @@ export function readFlow({ root, name, catalogue }) {
|
|
|
613
744
|
if (!validated.ok) return { ok: false, reds: validated.reds };
|
|
614
745
|
|
|
615
746
|
return {
|
|
616
|
-
ok: true,
|
|
747
|
+
ok: /** @type {true} */ (true),
|
|
617
748
|
dir,
|
|
618
749
|
lines: signed.lines,
|
|
619
750
|
arbiter: signed.arbiter,
|
|
@@ -622,3 +753,87 @@ export function readFlow({ root, name, catalogue }) {
|
|
|
622
753
|
classes: validated.classes,
|
|
623
754
|
};
|
|
624
755
|
}
|
|
756
|
+
|
|
757
|
+
/** M6: the folder inside a run that holds the copy of the job it ran. */
|
|
758
|
+
const RUN_JOB_DIR = 'job';
|
|
759
|
+
|
|
760
|
+
/**
|
|
761
|
+
* M6 ("Each run saves a copy of the job it ran when it starts"): the ONE writer of `<runDir>/job/`. Reads the flow's three files, proves them against
|
|
762
|
+
* the flow's own signature first (a flow that does not verify is never copied), then writes them write-once (`wx`). `{ok:false, red}` writes nothing
|
|
763
|
+
* it did not finish (a half-written copy is removed). Never throws.
|
|
764
|
+
* @param {string} flowDir @param {string} runDir @param {string} [expectedFlowHash] the `signature.flow` the caller read; a different job on disk is refused
|
|
765
|
+
* @returns {{ok: true} | {ok: false, red: string}}
|
|
766
|
+
*/
|
|
767
|
+
export function writeRunJobCopy(flowDir, runDir, expectedFlowHash) {
|
|
768
|
+
const texts = {};
|
|
769
|
+
for (const f of FLOW_FILES) {
|
|
770
|
+
const r = readFileInside(flowDir, f);
|
|
771
|
+
if (!r.ok) return { ok: false, red: `job copy: could not read ${f} (${r.missing ? 'missing' : r.red})` };
|
|
772
|
+
texts[f] = r.text;
|
|
773
|
+
}
|
|
774
|
+
let signature;
|
|
775
|
+
try { signature = JSON.parse(texts['signature.json']); } catch { return { ok: false, red: 'job copy: signature.json is not valid JSON' }; }
|
|
776
|
+
const verified = verifyFlow({ proseText: texts['prose.txt'], declarationText: texts['declaration.json'], signature });
|
|
777
|
+
if (!verified.ok) return { ok: false, red: `job copy: the flow does not match its signature (${verified.reds[0]})` };
|
|
778
|
+
// M6 F3: the copy must be the job the run verified at its start; a job replaced since is never copied (nothing is written)
|
|
779
|
+
if (typeof expectedFlowHash === 'string' && signature.flow !== expectedFlowHash) return { ok: false, red: 'the job was replaced while this run was starting' };
|
|
780
|
+
const dir = path.join(runDir, RUN_JOB_DIR);
|
|
781
|
+
try {
|
|
782
|
+
mkdirSync(dir);
|
|
783
|
+
for (const f of FLOW_FILES) writeFileSync(path.join(dir, f), texts[f], { encoding: 'utf8', flag: 'wx' });
|
|
784
|
+
} catch (err) {
|
|
785
|
+
try { if (err.code !== 'EEXIST') rmSync(dir, { recursive: true, force: true }); } catch { /* best-effort */ }
|
|
786
|
+
return { ok: false, red: err.code === 'EEXIST' ? 'job copy: this run already has its copy — never overwritten' : `job copy: could not write (${err.code ?? err.message})` };
|
|
787
|
+
}
|
|
788
|
+
return { ok: true };
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
/**
|
|
792
|
+
* M6: the job a run ran, from its own copy. `{present:false}` = the run has none (it started before M6). `{present:true, ok:true, ...}` = the same
|
|
793
|
+
* shape as a good `readFlow` (lines, arbiter, declaration, signature, classes), after the copy was verified against the copied signature.
|
|
794
|
+
* `{present:true, ok:false, reds}` = a copy that was edited or is incomplete: refused, never shown as the job.
|
|
795
|
+
* @param {string} runDir @param {unknown} catalogue
|
|
796
|
+
* @returns {{present: false} | ({present: true} & ReadFlowResult)}
|
|
797
|
+
*/
|
|
798
|
+
export function readRunJobCopy(runDir, catalogue) {
|
|
799
|
+
const dir = path.join(runDir, RUN_JOB_DIR);
|
|
800
|
+
if (!existsSync(dir)) return { present: false };
|
|
801
|
+
const reds = [];
|
|
802
|
+
const proseText = readTextFile(path.join(dir, 'prose.txt'), 'prose.txt', reds);
|
|
803
|
+
const declarationText = readTextFile(path.join(dir, 'declaration.json'), 'declaration.json', reds);
|
|
804
|
+
const signatureText = readTextFile(path.join(dir, 'signature.json'), 'signature.json', reds);
|
|
805
|
+
let declarationJson;
|
|
806
|
+
let signatureJson;
|
|
807
|
+
try { if (declarationText !== null) declarationJson = JSON.parse(declarationText); } catch { reds.push('flow: declaration.json is not valid JSON'); }
|
|
808
|
+
try { if (signatureText !== null) signatureJson = JSON.parse(signatureText); } catch { reds.push('flow: signature.json is not valid JSON'); }
|
|
809
|
+
if (reds.length > 0) return { present: true, ok: false, reds };
|
|
810
|
+
const verified = verifyFlow({ proseText, declarationText, signature: signatureJson });
|
|
811
|
+
if (!verified.ok) return { present: true, ok: false, reds: [...verified.reds] };
|
|
812
|
+
return {
|
|
813
|
+
present: /** @type {true} */ (true),
|
|
814
|
+
...interpretSigned({
|
|
815
|
+
proseText: /** @type {string} */ (proseText), declarationJson, signatureJson, catalogue, dir,
|
|
816
|
+
}),
|
|
817
|
+
};
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
/**
|
|
821
|
+
* Amendment 43: after a failed verify, name what changed by comparing with the copy `writeFlow` kept at sign. The copy is trusted ONLY if it
|
|
822
|
+
* verifies against signature.json itself; otherwise it is never compared. Returns extra reds (plain sentences); never throws.
|
|
823
|
+
* @param {string} dir @param {any} signature @param {string} proseText @param {string} declarationText
|
|
824
|
+
* @returns {string[]}
|
|
825
|
+
*/
|
|
826
|
+
function explainEdit(dir, signature, proseText, declarationText) {
|
|
827
|
+
const oldProse = readFileInside(dir, `${SIGNED_COPY_DIR}/prose.txt`);
|
|
828
|
+
const oldDecl = readFileInside(dir, `${SIGNED_COPY_DIR}/declaration.json`);
|
|
829
|
+
if (!oldProse.ok && oldProse.missing && !oldDecl.ok && oldDecl.missing) {
|
|
830
|
+
return [CHANGED_PREFIX + '(signed before amendment 43: no copy to compare)'];
|
|
831
|
+
}
|
|
832
|
+
if (!oldProse.ok || !oldDecl.ok) return [CHANGED_PREFIX + "the saved copy of the signed files is incomplete, so it can't be trusted to compare"];
|
|
833
|
+
if (!verifyFlow({ proseText: oldProse.text, declarationText: oldDecl.text, signature }).ok) {
|
|
834
|
+
return [CHANGED_PREFIX + "the saved copy of the signed files does not match the signature, so it can't be trusted to compare"];
|
|
835
|
+
}
|
|
836
|
+
const changes = describeChange({ oldProse: oldProse.text, newProse: proseText, oldDecl: oldDecl.text, newDecl: declarationText });
|
|
837
|
+
if (changes.length === 0) return [CHANGED_PREFIX + 'the files match the saved copy; signature.json itself was changed'];
|
|
838
|
+
return changes.map((c) => `${CHANGED_PREFIX}${c}`);
|
|
839
|
+
}
|
package/src/keysfile.js
CHANGED
|
@@ -145,8 +145,10 @@ export function loadKeysEnv(opts = {}) {
|
|
|
145
145
|
const parsed = parseKeysText(readFileSync(fd, 'utf8'));
|
|
146
146
|
/** @type {Record<string,string|undefined>} */
|
|
147
147
|
const env = { ...base };
|
|
148
|
-
|
|
149
|
-
|
|
148
|
+
// C4 (amendment 16): only the known key names reach the env (and so a child). Any other name in the file is listed in `names`
|
|
149
|
+
// for Settings but its value stays here — a `NODE_OPTIONS` line must never reach a run, resume or draft child.
|
|
150
|
+
for (const name of KEY_NAMES) {
|
|
151
|
+
if (!env[name] && Object.hasOwn(parsed, name)) env[name] = parsed[name];
|
|
150
152
|
}
|
|
151
153
|
return {
|
|
152
154
|
ok: true, path, exists: true, names: Object.entries(parsed).filter(([, v]) => v !== '').map(([n]) => n).sort(), shellOnly: knownShell(parsed), refusal: null, env,
|
package/src/model-step.js
CHANGED
|
@@ -103,10 +103,10 @@ const SOFTGREEN_SCHEMA = Object.freeze({
|
|
|
103
103
|
type: 'object',
|
|
104
104
|
properties: {
|
|
105
105
|
text: { type: 'string' },
|
|
106
|
-
lines: { type: 'array', items: { type: 'string' } },
|
|
107
106
|
...DONE_PROPS,
|
|
108
107
|
},
|
|
109
108
|
required: ['text', 'done'],
|
|
109
|
+
additionalProperties: false,
|
|
110
110
|
});
|
|
111
111
|
|
|
112
112
|
// hitl/read-style steps: the documented common shapes are {text} or
|