fwdloop 0.33.0 → 0.35.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 (87) hide show
  1. package/README.md +14 -0
  2. package/bin/fwdloop +18 -2
  3. package/package.json +1 -1
  4. package/src/action-line.js +100 -0
  5. package/src/action-stop.js +44 -0
  6. package/src/ask.js +9 -2
  7. package/src/auditchecks.js +6 -4
  8. package/src/authoring.js +28 -14
  9. package/src/blockasks.js +3 -2
  10. package/src/blockassemble.js +40 -21
  11. package/src/blockdraft.js +8 -13
  12. package/src/blockpick.js +11 -1
  13. package/src/checkblock.js +102 -58
  14. package/src/checked.js +7 -2
  15. package/src/checklist.js +1 -3
  16. package/src/checklistsign.js +1 -1
  17. package/src/checkpick.js +7 -73
  18. package/src/declaration.js +20 -35
  19. package/src/drafter.js +281 -208
  20. package/src/jobkey.js +2 -3
  21. package/src/noteask.js +62 -0
  22. package/src/pageask.js +24 -69
  23. package/src/pagedry.js +27 -4
  24. package/src/pagemap.js +8 -2
  25. package/src/pagerules.js +19 -3
  26. package/src/panel/author.js +63 -36
  27. package/src/panel/authorcard.js +36 -20
  28. package/src/panel/data.js +5 -1
  29. package/src/panel/index.html +66 -37
  30. package/src/pickrecord.js +42 -54
  31. package/src/planrebuild.js +16 -6
  32. package/src/rowedit.js +35 -5
  33. package/src/rubricstep.js +9 -1
  34. package/src/runner.js +87 -41
  35. package/src/runvalues.js +9 -1
  36. package/src/setup.js +3 -1
  37. package/src/sheetblock.js +17 -7
  38. package/src/sheetbuild.js +148 -0
  39. package/src/sheetchecks.js +3 -2
  40. package/src/sheetfind.js +4 -4
  41. package/src/sheetlook.js +15 -4
  42. package/src/sheetoffer.js +50 -5
  43. package/src/sheetrows.js +18 -2
  44. package/src/signed-text.js +1 -5
  45. package/src/ticket-draft.js +4 -21
  46. package/src/ticketrows.js +100 -0
  47. package/src/whole-job.js +27 -11
  48. package/types/action-line.d.ts +71 -0
  49. package/types/action-stop.d.ts +36 -0
  50. package/types/ask.d.ts +3 -2
  51. package/types/auditchecks.d.ts +2 -1
  52. package/types/authoring.d.ts +8 -3
  53. package/types/blockasks.d.ts +1 -2
  54. package/types/blockassemble.d.ts +20 -3
  55. package/types/blockdraft.d.ts +4 -12
  56. package/types/blockpick.d.ts +5 -0
  57. package/types/checkblock.d.ts +33 -17
  58. package/types/checked.d.ts +2 -0
  59. package/types/checklist.d.ts +3 -5
  60. package/types/checkpick.d.ts +4 -34
  61. package/types/declaration.d.ts +7 -0
  62. package/types/drafter.d.ts +23 -356
  63. package/types/noteask.d.ts +52 -0
  64. package/types/pageask.d.ts +12 -36
  65. package/types/pagedry.d.ts +13 -0
  66. package/types/pagerules.d.ts +7 -0
  67. package/types/panel/author.d.ts +1 -1
  68. package/types/panel/authorcard.d.ts +13 -8
  69. package/types/panel/authorflows.d.ts +4 -4
  70. package/types/panel/data.d.ts +2 -2
  71. package/types/panel/jobgrid.d.ts +1 -1
  72. package/types/pickrecord.d.ts +47 -13
  73. package/types/rowedit.d.ts +16 -1
  74. package/types/rubricstep.d.ts +3 -0
  75. package/types/sheetblock.d.ts +11 -4
  76. package/types/sheetbuild.d.ts +82 -0
  77. package/types/sheetchecks.d.ts +2 -1
  78. package/types/sheetfind.d.ts +2 -2
  79. package/types/sheetoffer.d.ts +26 -1
  80. package/types/sheetrows.d.ts +8 -0
  81. package/types/ticket-draft.d.ts +3 -49
  82. package/types/ticketrows.d.ts +61 -0
  83. package/types/whole-job.d.ts +3 -3
  84. package/src/added-end.js +0 -60
  85. package/src/repairs.js +0 -38
  86. package/types/added-end.d.ts +0 -62
  87. package/types/repairs.d.ts +0 -13
package/README.md CHANGED
@@ -28,6 +28,20 @@ change.
28
28
  It is built mainly for that shape of work: gather, decide, pause, hand off, continue. Not a
29
29
  general agent. Not a chat bot. A workflow that a person can read, approve, rerun, and edit.
30
30
 
31
+ ## The machine that makes machines
32
+
33
+ Like a CNC machine, fwdloop builds the thing that does the work, then lets a gauge it can't touch decide if the work is good, and stops for you where you said. Trust needs four things. Miss one and trust is zero. fwdloop has all four.
34
+
35
+ **Intent.** You write the job as plain numbered lines, and `~` rules under each say what success means. Every rule gets a check or a written reason why not. You sign before a dollar is spent.
36
+
37
+ **Guide rails, not just guardrails.** Guardrails stop the agent going off the road: a money cap per run, a monthly limit, a time limit on every Ask, and a send destination you signed that it can't move. Nothing leaves the machine without that signed destination and your accept in the same run. Guide rails keep it on the road: each new try hears what earlier tries in the run did; lessons from past runs go to the drafter and to retries; a rule it can't settle comes back as a question with buttons (Agree, Drop it, or your own words), not a guess.
38
+
39
+ **Verification.** The check sits outside the agent's loop: code decides, built on bareguard. Anything code can't check is listed as Not checked, and you judge it at the Ask. A red step goes back with the real gap to be fixed, up to four tries a step; the same miss twice stops it.
40
+
41
+ **Evidence.** Every try, its cost and its check result is recorded, and the books balance to the cent. You can read it all in the Audit tab, including exactly what each try was told. Page facts are quoted from a saved copy of the page.
42
+
43
+ The one difference from a lights-out machine: a person stands at the gate. The run parks at your Ask, spending nothing, and only after your accept does it act on the world.
44
+
31
45
  ## See it
32
46
 
33
47
  A real past run: a job that reads a public flights page, lists 3 Madrid→Rome flights, asks a
package/bin/fwdloop CHANGED
@@ -52,7 +52,7 @@ import { panelMain } from '../src/panel/server.js';
52
52
  import { launcherMain } from '../src/launcher.js';
53
53
  import { isInteractive, confirmTypedName, NEEDS_TTY } from '../src/sign-confirm.js';
54
54
  import { draftToDir, draftKeyRefusal, signDraft, SIGN_LINE, costText, questionsRefusal } from '../src/authoring.js';
55
- import { readRecordFile, readRowChoices, readSheetDropped } from '../src/pickrecord.js';
55
+ import { readRecordFile, readRowChoices, readSheetDropped, readColumns } from '../src/pickrecord.js';
56
56
  import { userInfo } from 'node:os';
57
57
  import { pageAddressesOf, pageAddressRefusal } from '../src/pagefetch.js';
58
58
  import { ticketListsOf, isTicketNumber, TICKET_NUMBER_WORDS } from '../src/ticket-shape.js';
@@ -885,6 +885,7 @@ async function cmdDraft(rest) {
885
885
  'no-questions': { type: 'boolean' },
886
886
  // M10 piece 3: the rules the person left Not checked ("drop it"), as `<line>.<rule>` pairs, e.g. `1.2,3.1` (the panel passes this to the redraft after the answers)
887
887
  left: { type: 'string' },
888
+ columns: { type: 'string' },
888
889
  // M10 am16: the checks the person picked and the answers that were not a pick, as JSON (the panel passes this to the redraft after the answers)
889
890
  picks: { type: 'string' },
890
891
  // M10 am17: the record file of the plan this draft follows (a Revise, or the redraft after the answers); its kept picks skip the suggestion and the asks
@@ -894,9 +895,12 @@ async function cmdDraft(rest) {
894
895
  model: { type: 'string' }, provider: { type: 'string' }, thinking: { type: 'boolean' },
895
896
  // M13 piece 4: the job's flow type (plain | mcp | tickets) and its MCP server, from the card; the tools come from that server's newest OK `check tools` (never a started server)
896
897
  'flow-type': { type: 'string' }, mcp: { type: 'string' },
898
+ // M13 am11: what the prose's send line is: check (the card's tentative send: the AI says if the last line is the action), known (the person agreed or typed the last line) . Absent: the prose file is the truth.
899
+ action: { type: 'string' },
897
900
  },
898
901
  allowPositionals: true,
899
902
  });
903
+ if (values.action !== undefined && !['check', 'known'].includes(values.action)) fail(`draft: --action takes check or known, got "${values.action}"`);
900
904
  const flowType = values['flow-type'] ?? 'plain';
901
905
  if (!['plain', 'mcp', 'tickets'].includes(flowType)) fail(`draft: --flow-type takes plain, mcp or tickets, got "${flowType}"`);
902
906
  if (flowType === 'plain' && values.mcp !== undefined) fail('draft: --mcp goes with --flow-type mcp or tickets');
@@ -914,6 +918,14 @@ async function cmdDraft(rest) {
914
918
  leftRules.push({ line: Number(m[1]), rule: Number(m[2]) });
915
919
  }
916
920
 
921
+ // M17 ruling 2: the columns the person agreed for words that are no `~` rule, `[{line, word, column}]`; told to the AI on the list turn, never a `~` line
922
+ /** @type {any[]} */
923
+ let columnAnswers = [];
924
+ if (values.columns !== undefined) {
925
+ try { columnAnswers = JSON.parse(values.columns); } catch { columnAnswers = []; }
926
+ if (!Array.isArray(columnAnswers) || columnAnswers.some((x) => !x || !Number.isInteger(x.line) || typeof x.word !== 'string' || typeof x.column !== 'string')) fail('draft: --columns takes a JSON list of {line, word, column}');
927
+ }
928
+
917
929
  /** @type {any[]|undefined} */
918
930
  let checkPicks;
919
931
  if (values.picks !== undefined) {
@@ -927,10 +939,11 @@ async function cmdDraft(rest) {
927
939
  let carriedChoices;
928
940
  /** @type {any[]|undefined} */
929
941
  let carriedSheetDropped;
942
+ let carriedColumns;
930
943
  if (values.carry !== undefined) {
931
944
  const abs = resolve(values.carry);
932
945
  const g = readFileInside(dirname(abs), basename(abs));
933
- if (g.ok) { carriedPicks = readRecordFile(abs) ?? undefined; carriedChoices = readRowChoices(abs) ?? undefined; carriedSheetDropped = readSheetDropped(abs) ?? undefined; } // a missing or unreadable record is no record: every guardrail is asked, as before
946
+ if (g.ok) { carriedPicks = readRecordFile(abs) ?? undefined; carriedChoices = readRowChoices(abs) ?? undefined; carriedSheetDropped = readSheetDropped(abs) ?? undefined; carriedColumns = readColumns(abs) ?? undefined; } // a missing or unreadable record is no record: every guardrail is asked, as before
934
947
  }
935
948
 
936
949
  let injected = {};
@@ -990,11 +1003,14 @@ async function cmdDraft(rest) {
990
1003
  root: values.root === undefined ? defaultFlowsRoot() : resolve(values.root),
991
1004
  name: values.name,
992
1005
  noQuestions: values['no-questions'] === true,
1006
+ ...(values.action === undefined ? {} : { actionMode: values.action }),
993
1007
  ...(leftRules.length ? { leftRules } : {}),
1008
+ ...(columnAnswers.length ? { columnAnswers } : {}),
994
1009
  ...(checkPicks === undefined ? {} : { checkPicks }),
995
1010
  ...(carriedPicks === undefined ? {} : { carriedPicks }),
996
1011
  ...(carriedChoices === undefined ? {} : { carriedChoices }),
997
1012
  ...(carriedSheetDropped === undefined ? {} : { carriedSheetDropped }),
1013
+ ...(carriedColumns === undefined ? {} : { carriedColumns }),
998
1014
  draftThinking: values.thinking === true ? 'on' : 'off',
999
1015
  flowType,
1000
1016
  ...(values.mcp ? { mcpServer: values.mcp } : {}),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.33.0",
3
+ "version": "0.35.0",
4
4
  "description": "Describe a job as steps and guardrails; an agent builds the workflow, pauses for humans where you said, checks every step happened, and reruns it under budgets it cannot touch.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -0,0 +1,100 @@
1
+ // M13 am11 rules 1 and 2: the job's last line is the action. ONE module for the two AI questions (prompts verbatim from poc/f204-action-ai/prompts.mjs, F204),
2
+ // the checks code makes on each answer, and the one function that takes the tentative send out of a prose file.
3
+ // The AI answers one question ("is there a last step that writes or sends everything that came before it?"); code checks the answer is the LAST line and not an Ask.
4
+ // The AI suggests one line when there is none; code keeps one plain line or nothing. The AI never writes a destination: the send target is typed data in the signed arbiter.
5
+ // Throws away: whatever else the answer carried (only `action.line` / `text` are read). Third outcomes: a line that is not the last, an Ask, a non-integer, text with a
6
+ // newline or empty -> "no action" / "no suggestion" (never a guess).
7
+
8
+ export const RECOGNISE_TOOL = 'record_action';
9
+ export const SUGGEST_TOOL = 'suggest_action';
10
+ export const MAX_SUGGESTION_CHARS = 300;
11
+
12
+ export const RECOGNISE_SYSTEM = `A person wrote a numbered list of steps for a job. The finished result goes to the Destination named below the list.
13
+
14
+ Is there a last step that writes or sends everything that came before it? Answer with that step's number, or null if there is none.
15
+
16
+ A step that only reads, makes, lists, checks or asks something is not one. The step does not have to name the Destination: the Destination is only where the result goes.
17
+
18
+ Answer by calling the tool ${RECOGNISE_TOOL} exactly once, with the field "action" holding one required field: line (the step's number, or null).`;
19
+
20
+ export const SUGGEST_SYSTEM = `A person wrote a numbered list of steps for a job. The finished result goes to the Destination named below the list. The list has no last step that writes or sends everything that came before it.
21
+
22
+ Your one task: suggest ONE last step that writes or sends everything that came before it to the Destination.
23
+
24
+ Rules:
25
+ - Write the step as one short plain sentence, in the person's voice, like their other steps. It must say that the result is written or sent to the Destination.
26
+ - Do not repeat or change any existing step. Do not write a step that asks the person a question.
27
+
28
+ Answer by calling the tool ${SUGGEST_TOOL} exactly once. The one required field is text (the new step).`;
29
+
30
+ export const RECOGNISE_SCHEMA = {
31
+ type: 'object',
32
+ properties: {
33
+ action: {
34
+ type: 'object',
35
+ properties: {
36
+ line: { type: ['integer', 'null'], description: 'Number of the last step that writes or sends everything that came before it, or null if there is none.' },
37
+ },
38
+ required: ['line'],
39
+ additionalProperties: false,
40
+ },
41
+ },
42
+ required: ['action'],
43
+ additionalProperties: false,
44
+ };
45
+
46
+ export const SUGGEST_SCHEMA = {
47
+ type: 'object',
48
+ properties: {
49
+ text: { type: 'string', description: 'The one new last step, one short plain sentence.' },
50
+ },
51
+ required: ['text'],
52
+ additionalProperties: false,
53
+ };
54
+
55
+ /**
56
+ * The job as the model sees it (F204's listing): `n. text`, ` gN: rule` per `; ` part, then the Destination.
57
+ * @param {{n: number, text: string, guardrail?: string}[]} lines `parseSignedText`'s lines @param {Set<number>} askLines @param {string} destination
58
+ */
59
+ export function jobListing(lines, askLines, destination) {
60
+ const out = ['The job:'];
61
+ for (const l of lines) {
62
+ out.push(`${l.n}. ${askLines.has(l.n) ? `Ask: ${l.text}` : l.text}`);
63
+ const rules = typeof l.guardrail === 'string' && l.guardrail !== '' ? l.guardrail.split('; ') : [];
64
+ rules.forEach((g, i) => out.push(` g${i + 1}: ${g}`));
65
+ }
66
+ out.push('', `Destination: folder ${destination}`);
67
+ return out.join('\n');
68
+ }
69
+
70
+ /**
71
+ * Code's check of the recognise answer: the action is the LAST line (and not an Ask) or there is none.
72
+ * @param {any} args the tool call's arguments @param {number} lastLine @param {boolean} lastIsAsk
73
+ * @returns {boolean} true = the last line is the action
74
+ */
75
+ export function recognisedIsLast(args, lastLine, lastIsAsk) {
76
+ const line = args && typeof args === 'object' ? args.action?.line : undefined;
77
+ return Number.isInteger(line) && line === lastLine && !lastIsAsk;
78
+ }
79
+
80
+ /**
81
+ * Code's check of the suggestion: one plain line, not empty, not long, no control characters. Anything else is no suggestion.
82
+ * @param {any} args @returns {string|null}
83
+ */
84
+ export function cleanSuggestion(args) {
85
+ const t = args && typeof args === 'object' && typeof args.text === 'string' ? args.text.trim() : '';
86
+ // eslint-disable-next-line no-control-regex
87
+ if (t === '' || t.length > MAX_SUGGESTION_CHARS || /[\x00-\x1F\x7F]/.test(t)) return null;
88
+ return t;
89
+ }
90
+
91
+ /** The asked question's words (signed, M13 am11 rule 2). @param {string} line */
92
+ export const suggestionQuestion = (line) => `Your job has no last step that writes it out. I suggest: "${line}". `;
93
+
94
+ /**
95
+ * The prose file without its (tentative) send line: the one writer of "this job has no write". Only the arbiter's `send at line <n> to ...` line is removed.
96
+ * @param {string} proseText
97
+ */
98
+ export function withoutSend(proseText) {
99
+ return proseText.split('\n').filter((l) => !/^guardrail: send at line \d+ to /.test(l)).join('\n');
100
+ }
@@ -0,0 +1,44 @@
1
+ // M13 am11 rule 3 / am11a: before the action (the job's last line, a signed send) writes or sends, what goes out is compared by sha256 with what the person
2
+ // accepted at their last Ask IN THIS RUN. ONE function decides (`decideAction`), the words and the wait live here once.
3
+ // Throws away: nothing. Third outcomes: an accept with no recorded sha (null / '') reads as "nothing accepted"; an unreadable outgoing sha reads as unseen.
4
+ import { sha256Hex, serializeArtifact } from './ask.js';
5
+
6
+ export const ACTION_STOP_KIND = 'action-stop';
7
+ export const STOP_CHANGED = 'This changed since you accepted it.';
8
+ export const STOP_UNSEEN = 'You have not seen this yet.';
9
+ /** am11a 1: the card's Ask wait is 1h unless the person changes it; this is the default when nothing else is signed. */
10
+ export const DEFAULT_ACTION_WAIT_MS = 3_600_000;
11
+
12
+ /**
13
+ * @param {{ acceptedSha: string|null|undefined, outgoing: Record<string, any> }} a `acceptedSha` = the sha256 recorded at the last Ask accepted this run; `outgoing` = the artifact about to go out
14
+ * @returns {{ go: true, outgoingSha: string } | { go: false, question: string, outgoingSha: string }}
15
+ */
16
+ export function decideAction({ acceptedSha, outgoing }) {
17
+ const outgoingSha = sha256Hex(serializeArtifact(outgoing));
18
+ if (typeof acceptedSha !== 'string' || acceptedSha === '') return { go: false, question: STOP_UNSEEN, outgoingSha };
19
+ return acceptedSha === outgoingSha ? { go: true, outgoingSha } : { go: false, question: STOP_CHANGED, outgoingSha };
20
+ }
21
+
22
+ /**
23
+ * The accept to compare against: the sha of the LAST Ask (by step order) before step `i` that was accepted in this run, or null when there is none.
24
+ * @param {{ emits?: string }[]} steps @param {number} i @param {Map<string, string|null>} acceptedAskEmitsThisRun
25
+ */
26
+ export function lastAcceptedSha(steps, i, acceptedAskEmitsThisRun) {
27
+ for (let k = i - 1; k >= 0; k -= 1) {
28
+ const e = steps[k].emits;
29
+ if (typeof e === 'string' && acceptedAskEmitsThisRun.has(e)) return acceptedAskEmitsThisRun.get(e) ?? null;
30
+ }
31
+ return null;
32
+ }
33
+
34
+ /**
35
+ * am11a 1/2: the wait of the stop. The LAST Ask's own wait when the job has an Ask before the action; else the card's Ask wait kept in the run's signed values (`arbiter.actionWaitMs`), else 1h.
36
+ * @param {{ fromLine: number }[]} steps @param {number} i @param {Map<number, {ttlMs: number}>} askLines @param {number|undefined} actionWaitMs
37
+ */
38
+ export function stopWaitMs(steps, i, askLines, actionWaitMs) {
39
+ for (let k = i - 1; k >= 0; k -= 1) {
40
+ const ask = askLines.get(steps[k].fromLine);
41
+ if (ask) return ask.ttlMs;
42
+ }
43
+ return Number.isFinite(actionWaitMs) && /** @type {number} */ (actionWaitMs) > 0 ? /** @type {number} */ (actionWaitMs) : DEFAULT_ACTION_WAIT_MS;
44
+ }
package/src/ask.js CHANGED
@@ -509,6 +509,11 @@ export function answerAsk({
509
509
  return { ok: false, red: `answerAsk: askId "${askId}" is unknown for run ${runDir}` };
510
510
  }
511
511
 
512
+ // M13 am11: the stop before the action takes Accept only; "Not now" is the Stop (the run ends stopped, nothing written)
513
+ if (ask.kind === 'action-stop' && decision !== 'accept') {
514
+ return { ok: false, red: `answerAsk: askId "${askId}" is the stop before the action and takes Accept only (Not now is Stop)` };
515
+ }
516
+
512
517
  const nowIso = now();
513
518
  // A present-but-unparseable expiresAt (Date.parse -> NaN) must never read
514
519
  // as "not expired" — `NaN > x`/`x > NaN` are both false, so the comparison
@@ -619,11 +624,11 @@ export function answerAsk({
619
624
  * Written once with the rest of the record; an existing archive is never
620
625
  * rewritten to add it (the `wx` create refuses).
621
626
  *
622
- * @param {{ runDir: string, askId: string, question: string, askedAt: string, expiresAt: string, evidence: unknown, emits?: string }} opts
627
+ * @param {{ runDir: string, askId: string, question: string, askedAt: string, expiresAt: string, evidence: unknown, emits?: string, kind?: string }} opts
623
628
  * @returns {{ ok: true } | { ok: false, red: string }}
624
629
  */
625
630
  export function writeAskArchive({
626
- runDir, askId, question, askedAt, expiresAt, evidence, emits,
631
+ runDir, askId, question, askedAt, expiresAt, evidence, emits, kind,
627
632
  }) {
628
633
  if (typeof runDir !== 'string' || runDir.length === 0) {
629
634
  return { ok: false, red: 'writeAskArchive: "runDir" must be a non-empty string' };
@@ -638,6 +643,7 @@ export function writeAskArchive({
638
643
  askId, question, askedAt, expiresAt, evidence,
639
644
  };
640
645
  if (typeof emits === 'string' && emits.length > 0) payload.emits = emits;
646
+ if (typeof kind === 'string' && kind.length > 0) payload.kind = kind; // M13 am11: the stop before the action is an ask record with this one added field
641
647
  try {
642
648
  writeFileSync(archivePath, JSON.stringify(payload, null, 2), { flag: 'wx' });
643
649
  } catch (err) {
@@ -785,6 +791,7 @@ export function listArchivedAsks(runDir) {
785
791
  evidence: readAskEvidence(ask),
786
792
  answer,
787
793
  ...(typeof ask.emits === 'string' ? { emits: ask.emits } : {}),
794
+ ...(typeof ask.kind === 'string' ? { kind: ask.kind } : {}), // M13 am11: the stop before the action
788
795
  });
789
796
  }
790
797
 
@@ -3,7 +3,7 @@
3
3
  // What a run recorded for a check is read off its diary (`checks` rows: each check numbered with its `ok`, and for a list line its `part`); nothing is re-derived. What this throws away: the checks of a line off the list
4
4
  // (the sheet and the older plans keep their own Audit rows), and the per-try history (the LAST try of a step is the one that closed it).
5
5
  import { listLinesOf } from './checklistsign.js';
6
- import { listPartRows } from './checked.js';
6
+ import { listPartRows, notCheckedView } from './checked.js';
7
7
  import { EVERY_STEP, EVERY_STEP_TEXTS } from './try-checks.js';
8
8
  import { sheetRowsOf } from './sheetrows.js';
9
9
 
@@ -13,7 +13,7 @@ export const AUDIT_NO_RESULT = 'no result recorded';
13
13
  /**
14
14
  * @param {any} declaration the signed plan @param {any[]} diary the run's `checks` rows (src/diary.js readChecks) @param {{items?: string[], by?: Record<string, string>}|null} notChecked the sign row's Not-checked block
15
15
  * @param {{lines?: any[], csvRoles?: string[]}} [sheet] the signed job lines and CSV roles: a plan whose list has sheet rows (M16 am4) shows them here, tagged by where each comes from (hamr 2026-11-14)
16
- * @returns {{checks: AuditCheckRow[], notChecked: AuditCheckRow[], always: AuditCheckRow[]}|null} null for a plan with no list (it keeps its own Audit rows)
16
+ * @returns {{checks: AuditCheckRow[], notChecked: AuditCheckRow[], readNotes: string[], always: AuditCheckRow[]}|null} null for a plan with no list (it keeps its own Audit rows)
17
17
  * @typedef {{text: string, by: 'you'|'agent'|'default'|null, result: 'passed'|'failed'|'none'|'not-checked'}} AuditCheckRow
18
18
  */
19
19
  export function auditChecksOf(declaration, diary, notChecked, { lines: jobLines = [], csvRoles = [] } = {}) {
@@ -40,8 +40,10 @@ export function auditChecksOf(declaration, diary, notChecked, { lines: jobLines
40
40
  checks.push({ text: `line ${r.line} \u00b7 ${r.text}`, by: r.by, result: got === undefined ? 'none' : got.ok ? 'passed' : 'failed' });
41
41
  }
42
42
  const by = notChecked?.by ?? {};
43
+ // M17 am4 (C3): the Audit splits a reading note from Not checked as the card and the Job tab do (src/checked.js notCheckedView)
44
+ const view = notCheckedView(notChecked?.items ?? [], declaration);
43
45
  /** @type {AuditCheckRow[]} */
44
- const notRows = (notChecked?.items ?? []).map((t) => ({ text: t, by: by[t] === 'you' || by[t] === 'agent' || by[t] === 'default' ? /** @type {'you'|'agent'|'default'} */ (by[t]) : null, result: 'not-checked' }));
46
+ const notRows = view.items.map((t) => ({ text: t, by: by[t] === 'you' || by[t] === 'agent' || by[t] === 'default' ? /** @type {'you'|'agent'|'default'} */ (by[t]) : null, result: 'not-checked' }));
45
47
  // the two checks every step has (src/try-checks.js #1 and #2): passed when every step that ran them passed, failed when one did not
46
48
  const every = (/** @type {string} */ text) => {
47
49
  const seen = (Array.isArray(diary) ? diary : []).flatMap((d) => (d.checks ?? []).filter((/** @type {any} */ c) => c.source === EVERY_STEP && c.text === text));
@@ -49,5 +51,5 @@ export function auditChecksOf(declaration, diary, notChecked, { lines: jobLines
49
51
  };
50
52
  /** @type {AuditCheckRow[]} */
51
53
  const always = EVERY_STEP_TEXTS.map((text) => ({ text, by: /** @type {'default'} */ ('default'), result: every(text) }));
52
- return { checks, notChecked: notRows, always };
54
+ return { checks, notChecked: notRows, readNotes: view.readNotes, always };
53
55
  }
package/src/authoring.js CHANGED
@@ -22,7 +22,6 @@ import path from 'node:path';
22
22
  import { draft } from './drafter.js';
23
23
  import { parseSignedText, unsignedAskTtls } from './signed-text.js';
24
24
  import { validateDeclaration, flowTypeOf } from './declaration.js';
25
- import { addedLinesOf } from './added-end.js';
26
25
  import { factRows, factSentence, countSentence } from './citedcheck.js';
27
26
  import { plainWords, labelled, tagged } from './checkwords.js';
28
27
  import { listLinesOf, partByOf, factByOf, countByOf } from './checklistsign.js';
@@ -44,6 +43,7 @@ import { sessionPriorSpend, writeDraftSpend } from './draftspend.js';
44
43
  import { writeSetup } from './setup.js';
45
44
  import { RECORD_FILE } from './pickrecord.js';
46
45
  import { mcpPickHere } from './mcp-pick.js';
46
+ import { hitlWords } from './checked.js';
47
47
 
48
48
  export const SPEC_HASH_FILE = 'spec.hash';
49
49
  /** The one folder under the flows root where the panel keeps its draft folders (M4e). Starts with a dot, so it is never a flow name. */
@@ -181,11 +181,15 @@ const READOUT_HEADS = {
181
181
  refused: 'REFUSED LINES',
182
182
  jobLines: 'JOB LINES',
183
183
  };
184
- /** Zero-based indexes of the heading lines in a readout's text (split on "\n"): the panel renders those bold. */
184
+ // borrowed-from: bareloop src/authorreadout.js@v0.58.0
185
+ /** The readout's top line prefix: ONE owner for the text `buildReadout` writes and the bold `readoutHeadIndexes` finds. */
186
+ export const READOUT_HEADER_PREFIX = 'DRAFT READOUT — NOT SIGNED — flow ';
187
+
188
+ /** Zero-based indexes of the header and heading lines in a readout's text (split on "\n"): the panel renders those bold. */
185
189
  export function readoutHeadIndexes(text) {
186
190
  const heads = new Set(Object.values(READOUT_HEADS));
187
191
  const idx = [];
188
- String(text).split('\n').forEach((l, i) => { if (heads.has(l)) idx.push(i); });
192
+ String(text).split('\n').forEach((l, i) => { if (heads.has(l) || l.startsWith(READOUT_HEADER_PREFIX)) idx.push(i); });
189
193
  return idx;
190
194
  }
191
195
 
@@ -194,7 +198,7 @@ export function buildReadout({
194
198
  declaration, arbiter, lines, name, modelId, costUsd, rounds, spendComplete, root,
195
199
  }) {
196
200
  const out = [];
197
- out.push(`DRAFT READOUT — NOT SIGNED — flow "${name}"`, '');
201
+ out.push(`${READOUT_HEADER_PREFIX}"${name}"`, '');
198
202
  out.push(`Drafted by: ${modelId ?? '?'} in ${rounds} round(s), cost ${usd(costUsd, spendComplete)}`);
199
203
  if (typeof root === 'string') out.push(`Flows root: ${root} (the flow is written to <flows root>/${name} when you sign)`);
200
204
  out.push(`Cap per run (signed by you in the prose): $${arbiter.capUsd}`, '');
@@ -220,11 +224,14 @@ export function buildReadout({
220
224
  out.push('', READOUT_HEADS.steps);
221
225
  const sheetBlocks = sheetLineBlocks({ declaration, lines });
222
226
  const onList = listLinesOf(declaration);
223
- const addedLines = addedLinesOf(lines, arbiter); // M13 am8: the lines code added at the end are marked `added`
227
+ // display only: a hitl step that is not an Ask line prints the card's words (src/checked.js hitlWords); an Ask line (pure stop) keeps `hitl`
228
+ const askLineNos = (arbiter.asks ?? []).map((a) => a.line);
229
+ const lastAskIdx = declaration.steps.reduce((m, st, i) => (askLineNos.includes(st.fromLine) ? i : m), -1);
230
+ const checkText = (st, i) => (st.close?.class === 'hitl' && !askLineNos.includes(st.fromLine) ? hitlWords(askLineNos.length > 0, lastAskIdx !== -1 && i > lastAskIdx) : st.close?.class);
224
231
  declaration.steps.forEach((st, i) => {
225
- out.push(` ${i + 1}. (line ${st.fromLine}) ${st.goal}${addedLines.has(st.fromLine) ? ' [added]' : ''}`);
232
+ out.push(` ${i + 1}. (line ${st.fromLine}) ${st.goal}`);
226
233
  out.push(` grants: ${st.primitives?.length ? st.primitives.join(', ') : 'none (pure stop)'}`
227
- + ` | reads: ${st.reads?.length ? st.reads.join(', ') : '-'} | emits: ${st.emits} | check: ${st.close?.class}`);
234
+ + ` | reads: ${st.reads?.length ? st.reads.join(', ') : '-'} | emits: ${st.emits} | check: ${checkText(st, i)}`);
228
235
  if (Array.isArray(st.mcpTools) && st.mcpTools.length) out.push(` tools: ${st.mcpTools.join(', ')}`);
229
236
  // M10 am7 item 1: the facts a cited step checks its quotes against, signed with the readout (typed fields, never model prose)
230
237
  // M16: a list line's checks carry the tag of the row that built each (`[you]`, `[agent]`, `[default]`); any other line keeps today's words
@@ -337,8 +344,10 @@ export function writePlanFiles(dir, files, opts = {}) {
337
344
  * `onResult({ ok })` (M4d am32): called once, after the spend is booked and just before the result files are written (the CLI gives its monthly hold back there).
338
345
  */
339
346
  export async function draftToDir({
340
- proseFile, dir, root, name, slot, model, draftThinking = /** @type {'on'|'off'} */ ('off'), keyNames, env = process.env, provider, rates, modelId, noQuestions = false, onResult, fetchPage, leftRules, checkPicks, carriedPicks, carriedChoices, carriedSheetDropped, proseRead,
347
+ proseFile, dir, root, name, slot, model, draftThinking = /** @type {'on'|'off'} */ ('off'), keyNames, env = process.env, provider, rates, modelId, noQuestions = false, onResult, fetchPage, leftRules, columnAnswers, carriedColumns, checkPicks, carriedPicks, carriedChoices, carriedSheetDropped, proseRead,
341
348
  flowType = /** @type {'plain'|'mcp'|'tickets'} */ ('plain'), mcpServer = /** @type {string|undefined} */ (undefined), mcpPick = /** @type {any} */ (undefined), mcpServers = /** @type {string[]|undefined} */ (undefined),
349
+ // M13 am11: what the card's tentative send line is (see draft()); null = the prose file is the truth
350
+ actionMode = /** @type {null|'check'|'known'} */ (null),
342
351
  }) {
343
352
  const refuse = (reds) => ({ ok: false, wrote: false, reds, costUsd: 0 });
344
353
  const nameCheck = checkFlowName(name);
@@ -417,12 +426,13 @@ export async function draftToDir({
417
426
  /** @type {any[]|null} */
418
427
  let rowChoices = null; // a Revise's carried Drop/Add choices, handed back by draft() and kept in the same record
419
428
  /** @type {any[]} */
429
+ let columnRecord = []; // the agreed columns of this plan (fresh and carried), kept in the same record (M17 ruling 2)
420
430
  let sheetDropped = []; // the sheet checks this plan has dropped (a Revise's carried ones, applied by draft()), kept in the same record
421
431
  /** @type {any} */
422
432
  let pickRecord = null; // M10 am17: handed by draft() as it learns it; the last one handed is this draft's (written below, the one writer)
423
433
  const result = await draft({
424
- proseText: prose.text, slot, model, provider, rates, modelId, env, onBook, priorSpend, offerQuestions: !noQuestions, draftThinking, draftDir: path.join(dir, PAGES_DIR), fetchPage, learnHints, ...(leftRules === undefined ? {} : { leftRules }), ...(checkPicks === undefined ? {} : { checkPicks }), ...(carriedPicks === undefined ? {} : { carriedPicks }), ...(carriedChoices === undefined ? {} : { carriedChoices, onChoices: (rec) => { rowChoices = rec; } }), ...(carriedSheetDropped === undefined ? {} : { carriedSheetDropped }), onSheetDropped: (rec) => { sheetDropped = rec; }, onPickRecord: (r) => { pickRecord = r; },
425
- flowType, mcp, ...(mcpServers === undefined ? {} : { mcpServers }),
434
+ proseText: prose.text, slot, model, provider, rates, modelId, env, onBook, priorSpend, offerQuestions: !noQuestions, draftThinking, draftDir: path.join(dir, PAGES_DIR), fetchPage, learnHints, ...(leftRules === undefined ? {} : { leftRules }), ...(columnAnswers === undefined ? {} : { columnAnswers }), ...(carriedColumns === undefined ? {} : { carriedColumns }), onColumns: (rec) => { columnRecord = rec; }, ...(checkPicks === undefined ? {} : { checkPicks }), ...(carriedPicks === undefined ? {} : { carriedPicks }), ...(carriedChoices === undefined ? {} : { carriedChoices, onChoices: (rec) => { rowChoices = rec; } }), ...(carriedSheetDropped === undefined ? {} : { carriedSheetDropped }), onSheetDropped: (rec) => { sheetDropped = rec; }, onPickRecord: (r) => { pickRecord = r; },
435
+ flowType, mcp, ...(mcpServers === undefined ? {} : { mcpServers }), actionMode,
426
436
  });
427
437
  if (result.stop === 'pre-flight') {
428
438
  try { rmdirSync(dir); } catch { /* the claimed dir is still empty; leave it rather than mask the refusal */ }
@@ -440,12 +450,14 @@ export async function draftToDir({
440
450
  const paidFail = (red) => ({
441
451
  ok: false, wrote: true, dir, reds: [red], costUsd: result.costUsd, spendComplete: result.spendComplete, stop: 'write', rounds: result.rounds, calls: result.calls, leaks: 0,
442
452
  });
443
- const parsed = parseSignedText(prose.text); // the drafter already proved it parses
453
+ // M13 am11: the prose as the drafter kept it (its tentative send line stays or is taken out); every file below is made from this one text
454
+ const proseOut = typeof result.proseText === 'string' ? result.proseText : prose.text;
455
+ const parsed = parseSignedText(proseOut); // the drafter already proved it parses
444
456
  if (!parsed.ok) return paidFail(`parse: ${parsed.reds.join('; ')}`);
445
457
  const dj = (o) => `${JSON.stringify(o, null, 2)}\n`;
446
458
  /** @type {Record<string, string>} */
447
459
  const files = {};
448
- files['prose.txt'] = prose.text; // verbatim
460
+ files['prose.txt'] = proseOut; // verbatim (M13 am11: as the drafter kept it)
449
461
  const targetText = dj({ root, name });
450
462
  files['target.json'] = targetText;
451
463
  // M4d am6 item 6: the pick is remembered beside the draft (written below as model.json, outside the signed files) so the signed job runs with it.
@@ -454,7 +466,7 @@ export async function draftToDir({
454
466
  // Amendments 24/25: the questions and the drafter's own "not checked" reading are written BEFORE log.json/spec.hash (the panel reads those
455
467
  // two as "the draft finished"), as their own files: never in the readout, so never in the hash.
456
468
  if (result.questions?.length) files[QUESTIONS_FILE] = scrub(dj({ questions: result.questions }), secrets);
457
- if (pickRecord !== null) files[RECORD_FILE] = scrub(dj({ ...pickRecord, ...(rowChoices === null ? {} : { rowChoices }), ...(sheetDropped.length ? { sheetDropped } : {}) }), secrets); // M10 am17: the picks carried to the next plan (this drafting folder only, never a run folder)
469
+ if (pickRecord !== null) files[RECORD_FILE] = scrub(dj({ ...pickRecord, ...(rowChoices === null ? {} : { rowChoices }), ...(sheetDropped.length ? { sheetDropped } : {}), ...(columnRecord.length ? { columns: columnRecord } : {}) }), secrets); // M10 am17: the picks carried to the next plan (this drafting folder only, never a run folder)
458
470
  files[NOT_CHECKED_FILE] = scrub(dj({ notChecked: result.notChecked ?? [], ...(result.notCheckedBy && Object.keys(result.notCheckedBy).length ? { by: result.notCheckedBy } : {}) }), secrets); // M16 item 5: the tag of each line that tells a row
459
471
  if (result.pageLooks || result.sheetLooks) files[PAGE_LOOK_FILE] = scrub(dj({ pages: result.pageLooks ?? [], ...(result.sheetLooks ? { sheets: result.sheetLooks } : {}), look: result.look ?? { facts: [], dropped: [] } }), secrets);
460
472
  files['log.json'] = scrub(dj({
@@ -463,6 +475,8 @@ export async function draftToDir({
463
475
  revisions: result.revisions, thinking: result.thinking, inputs: result.inputs, log: result.log,
464
476
  // M16 P4: what the plan card shows of the list (rows with tags and reasons, the suggestions), drawn by the page; Drop and Add rebuild it
465
477
  ...(result.checkCard ? { checkCard: result.checkCard } : {}),
478
+ // M13 am11: the job's action (the last line the AI named, or the person agreed or typed), or null: the plan card's row `› line <n> writes everything before it`
479
+ action: result.action ?? null,
466
480
  }), secrets);
467
481
  let hash = null;
468
482
  if (result.ok) {
@@ -475,7 +489,7 @@ export async function draftToDir({
475
489
  files['input-facts.json'] = inputFactsText;
476
490
  files['readout.txt'] = readoutText;
477
491
  const h = specHash({
478
- proseText: prose.text, declarationText, inputFactsText, readoutText, targetText,
492
+ proseText: proseOut, declarationText, inputFactsText, readoutText, targetText,
479
493
  });
480
494
  if (!h.ok) return paidFail(`hash: ${h.red}`);
481
495
  hash = h.hash; // spec.hash is written only after a clean sweep, below
package/src/blockasks.js CHANGED
@@ -1,10 +1,11 @@
1
+ // borrowed-from: bareloop src/blockasks.js@v0.57.0 (c18df406)
1
2
  // borrowed-from: bareloop src/blockasks.js@v0.56.0 (3383cce)
2
3
  // The questions of the check block, as the answer gate reads them (`answerQuestions`, src/questionbox.js): ONE spelling of the question words, written by code from a row that
3
4
  // code could not settle (reading | cant-check | check). The block's `open` list is the source; the person's CHOICE (agree | drop | rule) goes back through `block.applyAnswer`.
4
5
  import { readingQuestion, cantCheckQuestion } from './pageask.js';
5
6
  import { plainWords, HOW_TO_ANSWER, CANT_CHECK_WORDS } from './checkpick.js';
6
7
 
7
- /** @typedef {{key: string, rowKey: string, line: number, rule: number, source: 'look', ask: 'reading'|'cant-check'|'no-check'|'check', ruleText: string, question: string, counted: boolean, reading?: string, check?: Record<string, any>, pairRule?: number}} BlockAsk */
8
+ /** @typedef {{key: string, rowKey: string, line: number, rule: number, source: 'look', ask: 'reading'|'cant-check'|'no-check'|'check', ruleText: string, question: string, counted: boolean, reading?: string, check?: Record<string, any>}} BlockAsk */
8
9
 
9
10
  /**
10
11
  * The questions the block has open, in the order the person meets them: the look's readings, then the look's can't-checks, then the pick path's asks (a proposal or a can't-check about a rule the pick path owns) in rule order (a proposal is not counted toward the 3-ask cap).
@@ -17,7 +18,7 @@ export function questionsOfBlock(block, scoped = []) {
17
18
  return block.open.map((/** @type {any} */ q) => {
18
19
  const row = block.rows.find((r) => r.key === q.rowKey);
19
20
  const rule = Number(row?.rule);
20
- const base = { key: q.key, rowKey: q.rowKey, line: q.line, rule, source: /** @type {'look'} */ ('look'), ruleText: String(q.ruleText), ...(row?.pairWith !== undefined ? { pairRule: row.pairWith } : {}) };
21
+ const base = { key: q.key, rowKey: q.rowKey, line: q.line, rule, source: /** @type {'look'} */ ('look'), ruleText: String(q.ruleText) };
21
22
  if (q.ask === 'reading') return { ...base, ask: /** @type {'reading'} */ ('reading'), counted: true, reading: String(q.proposal), question: readingQuestion(q.line, String(q.ruleText), String(q.proposal)) };
22
23
  if (q.ask === 'check') {
23
24
  const words = plainWords(q.proposal);
@@ -3,18 +3,21 @@
3
3
  // a fact part -> close.cited = {source, facts, count}, class green; the source is added to the step's reads by code
4
4
  // a countable part -> a picked check (M10 am22 (1)-(3)): close.shape.picked on a softgreen step, close.picked on a fact (or sheet) step with the line in pickedLines
5
5
  // the numbers tie -> close.numbersFrom (M16 am3 (2), R7)
6
- // no part -> hitl, and `unjudgeable` carries the rows' Not-checked reasons
6
+ // no part -> hitl; the rows' Not-checked reasons are the list's own (no `unjudgeable` record, M17 am4)
7
7
  // Whatever the AI wrote for these checks (close.cited, close.shape, close.picked, close.class) is dropped. The block's signed rows become the declaration's `checkList`, which the sign and the
8
8
  // run-start gate prove (src/checklistsign.js). A fwd line keeps ONE close per line, whose class must equal the class its guardrail earns (signed, M4d): so a line with no guardrail of the
9
9
  // person's own can carry only the numbers tie; any other check the list built there cannot be signed on it and its rows are signed Not checked, with that reason.
10
10
 
11
+ /** M17 am5 item 2 (D3): the reason a `~` rule on a signed Ask line is Not checked, the signed words */
12
+ export const ASK_LINE_REASON = 'you judge it at the Ask';
13
+
11
14
  /** what a row says when its check cannot ride a line that has no guardrail of its own (the class of a line comes from its guardrail) */
12
15
  export const NO_GUARDRAIL_WORDS = 'This line has no guardrail of yours, so a check on it cannot be signed; you judge it at the Ask.';
13
16
 
14
- import { factsOfLook } from './citedcheck.js';
15
17
  import { REASON, renderCard } from './checkblock.js';
16
18
  import { dropSentence } from './pagedropwords.js';
17
19
  import { KEPT_WORDS } from './pickrecord.js';
20
+ import { lineRules } from './pagebits.js';
18
21
 
19
22
  const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
20
23
 
@@ -42,19 +45,13 @@ export function pickedOf(part) {
42
45
  }
43
46
 
44
47
  /**
45
- * @param {{declaration: Record<string, any>, block: import('./checkblock.js').CheckBlock, lines: {n: number, guardrail?: string|null}[], lineSet: Set<number>}} o
46
- * `lineSet` = the lines the block was given; `lines` = the signed lines (a guardrail decides the class)
48
+ * @param {{declaration: Record<string, any>, block: import('./checkblock.js').CheckBlock, lines: {n: number, guardrail?: string|null}[], lineSet: Set<number>, askLines?: Set<number>}} o
49
+ * `lineSet` = the lines the block was given; `lines` = the signed lines (a guardrail decides the class); `askLines` = the signed Ask lines: each `~` rule on one is a Not-checked line here, never skipped (M17 am5 item 2)
47
50
  * @returns {{declaration: Record<string, any>, notChecked: string[], notCheckedBy: Record<string, 'you'|'agent'|'default'>, built: Set<number>}} `built` = the lines that got a check from the block (a red naming one of them is a fault of the build)
48
51
  */
49
- export function assembleFromBlock({ declaration, block, lines, lineSet }) {
52
+ export function assembleFromBlock({ declaration, block, lines, lineSet, askLines = new Set() }) {
50
53
  if (!isRec(declaration) || !Array.isArray(declaration.steps)) return { declaration, notChecked: [], notCheckedBy: {}, built: new Set() };
51
54
  const c = block.reconcile();
52
- // fwd's signed R2c (M10 am7 item 2; bareloop v0.56.0 has no such rule, M16 am3 (1): fwd's rule stays): a place the page-read grew to phrases is checked with EVERY phrase, one phrase fact each,
53
- // not with the one word the block built it from
54
- const placeFactsOf = (/** @type {any} */ part, /** @type {number} */ n) => {
55
- const places = /** @type {any[]} */ (block.lookFacts).filter((k) => k.line === n && Array.isArray(k.phrases) && (k.source === undefined || k.source === part.source));
56
- return part.facts.flatMap((/** @type {any} */ f) => { const k = f.shape === 'phrase' ? places.find((x) => String(x.name) === f.name) : undefined; return k ? factsOfLook(k) : [f]; });
57
- };
58
55
  const partsOf = (/** @type {number} */ n) => c.map.filter((m) => m.line === n).map((m) => ({ ...c.parts[m.part], oldIndex: c.map.filter((x) => x.line === n).findIndex((x) => x.part === m.part) }));
59
56
  const guarded = (/** @type {number} */ n) => typeof lines.find((l) => l.n === n)?.guardrail === 'string' && String(lines.find((l) => l.n === n)?.guardrail).trim() !== '';
60
57
  /** @type {Set<number>} */ const built = new Set();
@@ -63,8 +60,6 @@ export function assembleFromBlock({ declaration, block, lines, lineSet }) {
63
60
  /** @type {Set<number>} */ const notSignable = new Set();
64
61
  /** @type {Set<number>} */ const pickedLines = new Set(Array.isArray(declaration.pickedLines) ? declaration.pickedLines : []);
65
62
  const guardrailClasses = isRec(declaration.guardrailClasses) ? { ...declaration.guardrailClasses } : {};
66
- const unjudgeable = isRec(declaration.unjudgeable) ? { ...declaration.unjudgeable } : {};
67
- const rowsOn = (/** @type {number} */ n) => block.rows.filter((r) => r.line === n && r.kind !== 'floor' && !r.hidden && r.state === 'not-checked');
68
63
  const steps = declaration.steps.map((/** @type {any} */ st) => {
69
64
  const n = st?.fromLine;
70
65
  if (!isRec(st) || !Number.isInteger(n) || !lineSet.has(n)) return st;
@@ -85,7 +80,7 @@ export function assembleFromBlock({ declaration, block, lines, lineSet }) {
85
80
  const close = { ...(sheet ? { sheet } : {}), ...(Array.isArray(old.columns) ? { columns: old.columns } : {}) };
86
81
  if (fact) {
87
82
  close.class = 'green';
88
- close.cited = { source: fact.source, facts: placeFactsOf(fact, n), ...(isRec(fact.count) ? { count: fact.count } : {}) };
83
+ close.cited = { source: fact.source, facts: fact.facts, ...(isRec(fact.count) ? { count: fact.count } : {}) };
89
84
  } else close.class = sheet ? 'green' : picks.length ? 'softgreen' : 'hitl';
90
85
  if (picks.length) {
91
86
  const checks = picks.map(pickedOf);
@@ -99,12 +94,10 @@ export function assembleFromBlock({ declaration, block, lines, lineSet }) {
99
94
  // the class of a line with a guardrail is the class its close ended in; a hitl one says why in the rows' own Not-checked reasons
100
95
  for (const n of lineSet) {
101
96
  const mine = steps.find((/** @type {any} */ st) => isRec(st) && st.fromLine === n);
102
- // the classes of a list line are code's: a line with no guardrail of the person's has no class entry and no unjudgeable note, whatever the AI sent
103
- if (!guarded(n)) { delete guardrailClasses[String(n)]; delete unjudgeable[String(n)]; continue; }
97
+ // the classes of a list line are code's: a line with no guardrail of the person's has no class entry, whatever the AI sent
98
+ if (!guarded(n)) { delete guardrailClasses[String(n)]; continue; }
104
99
  if (!mine) continue;
105
100
  guardrailClasses[String(n)] = mine.close.class;
106
- if (mine.close.class === 'hitl') unjudgeable[String(n)] = [...new Set(rowsOn(n).map((r) => notCheckedWords(r.reason, r)).filter(Boolean))].join(' ') || 'No check was picked for it, so you judge it at the Ask.';
107
- else delete unjudgeable[String(n)];
108
101
  }
109
102
  const served = new Set(steps.filter((/** @type {any} */ st) => isRec(st)).map((/** @type {any} */ st) => st.fromLine));
110
103
  /** the signed list: the block's signed fields per row, the parts renumbered to the close's order, a row whose check cannot ride its line signed Not checked @type {any[]} */
@@ -122,8 +115,7 @@ export function assembleFromBlock({ declaration, block, lines, lineSet }) {
122
115
  const notChecked = checkList.filter((r) => r.state === 'not-checked' && r.kind !== 'floor').map((r) => {
123
116
  const own = block.rows.find((x) => x.key === r.key);
124
117
  if (own?.hidden) return null;
125
- // an agreed or carried `~` line shares its source's answer (a follower is told as the rule it follows)
126
- const row = own?.parent ? { ...own, cantAsked: block.rows.find((x) => x.key === own.parent)?.cantAsked === true, keptFromLast: own.keptFromLast ?? block.rows.find((x) => x.key === own.parent)?.keptFromLast } : own;
118
+ const row = own;
127
119
  // any other row is told in the words the card draws it with (renderCard; never the row's key)
128
120
  // a `~` rule is told in the signed table's form, `not checked · "<rule>" — <reason>` (M10 am16 (5)); any other row names its line
129
121
  const kept = row?.keptFromLast === true ? ` (${KEPT_WORDS})` : ''; // M10 am17 (6)
@@ -131,10 +123,37 @@ export function assembleFromBlock({ declaration, block, lines, lineSet }) {
131
123
  if (r.by === 'you' || r.by === 'agent' || r.by === 'default') notCheckedBy[line] = r.by;
132
124
  return line;
133
125
  }).filter((x) => x !== null);
126
+ for (const l of lines) {
127
+ if (!askLines.has(l.n) || typeof l.guardrail !== 'string') continue;
128
+ for (const rule of lineRules({ rule: l.guardrail })) {
129
+ const line = `not checked · "${rule}" — ${ASK_LINE_REASON}`;
130
+ if (!notChecked.includes(line)) notChecked.push(line);
131
+ notCheckedBy[line] = 'you';
132
+ }
133
+ }
134
134
  /** @type {Record<string, any>} */
135
135
  const listed = checkList.filter((r) => served.has(r.line)); // a line no step serves is refused as a line; its rows are not signed
136
136
  /** @type {Record<string, any>} */
137
- const out = { ...declaration, steps, guardrailClasses, ...(Object.keys(unjudgeable).length || isRec(declaration.unjudgeable) ? { unjudgeable } : {}), checkList: listed };
137
+ const out = { ...declaration, steps, guardrailClasses, checkList: listed };
138
138
  if (pickedLines.size) out.pickedLines = [...pickedLines].sort((a, b) => a - b); else delete out.pickedLines;
139
139
  return { declaration: out, notChecked: /** @type {string[]} */ (notChecked), notCheckedBy, built };
140
140
  }
141
+
142
+ /**
143
+ * M17 am5 / P5: a green sheet step the builder (src/sheetbuild.js) reported as holding no built check has nothing to check it: its close becomes `hitl` (the class is decided here, never in the sheet files),
144
+ * the class on its line follows, and its rules are the Not-checked lines the builder gave. A plan signed before M17 is never passed through here.
145
+ * @param {Record<string, any>} declaration @param {{line: number, lost: string[]}[]} unbuilt
146
+ * @returns {{declaration: Record<string, any>, lines: number[], lost: string[]}}
147
+ */
148
+ export function closeUnbuiltSheetSteps(declaration, unbuilt) {
149
+ if (!isRec(declaration) || !Array.isArray(declaration.steps) || unbuilt.length === 0) return { declaration, lines: [], lost: [] };
150
+ const lines = unbuilt.map((u) => u.line);
151
+ const steps = declaration.steps.map((/** @type {any} */ st) => (isRec(st) && lines.includes(st.fromLine) && isRec(st.close) && st.close.class === 'green' ? { ...st, close: { class: 'hitl' } } : st));
152
+ /** @type {Record<string, any>} */
153
+ const out = { ...declaration, steps };
154
+ if (isRec(declaration.guardrailClasses)) {
155
+ out.guardrailClasses = { ...declaration.guardrailClasses };
156
+ for (const n of lines) out.guardrailClasses[String(n)] = 'hitl';
157
+ }
158
+ return { declaration: out, lines, lost: unbuilt.flatMap((u) => u.lost) };
159
+ }