bareloop 0.54.0 → 0.55.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 (139) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/bareloop.context.md +73 -12
  3. package/package.json +3 -3
  4. package/src/authorflow.js +148 -46
  5. package/src/authoring.js +21 -4
  6. package/src/authorjob.js +82 -3
  7. package/src/authorreadout.js +20 -3
  8. package/src/authorrun.js +1 -1
  9. package/src/authorscout.js +9 -6
  10. package/src/bridges.js +4 -3
  11. package/src/cardschedule.js +42 -0
  12. package/src/carrystore.js +1 -1
  13. package/src/checkpick.js +576 -0
  14. package/src/checksuggest.js +28 -0
  15. package/src/checkwords.js +25 -0
  16. package/src/cli.js +1 -1
  17. package/src/config.js +24 -1
  18. package/src/declaredclose.js +1 -1
  19. package/src/destpoint.js +149 -0
  20. package/src/draftspend.js +39 -0
  21. package/src/factwords.js +14 -1
  22. package/src/job.js +81 -1
  23. package/src/jobblock.js +9 -0
  24. package/src/labelscan.js +11 -0
  25. package/src/launcher.js +10 -6
  26. package/src/learn.js +6 -4
  27. package/src/mcpchecks.js +52 -0
  28. package/src/mcppick.js +36 -0
  29. package/src/mcpsources.js +77 -0
  30. package/src/mcpuse.js +97 -0
  31. package/src/natural.js +23 -0
  32. package/src/pagemap.js +5 -2
  33. package/src/panel/authorroutes.js +90 -15
  34. package/src/panel/authorsession.js +183 -21
  35. package/src/panel/index.html +686 -26
  36. package/src/panel/jobgrid.js +117 -0
  37. package/src/panel/jobplan.js +31 -15
  38. package/src/panel/scheduler.js +80 -13
  39. package/src/panel/schedules.js +189 -28
  40. package/src/panel/schedulestart.js +44 -13
  41. package/src/panel/server.js +438 -33
  42. package/src/panel/settingsroutes.js +133 -3
  43. package/src/panel/status.js +22 -2
  44. package/src/panel/tickets.js +44 -0
  45. package/src/pickrecord.js +145 -0
  46. package/src/plan.js +31 -2
  47. package/src/planrun.js +71 -15
  48. package/src/prcheckout.js +259 -0
  49. package/src/readshim.js +3 -2
  50. package/src/replay.js +6 -0
  51. package/src/reuse.js +3 -3
  52. package/src/revises.js +56 -0
  53. package/src/rubricstep.js +62 -16
  54. package/src/run.js +10 -1
  55. package/src/runexport.js +2 -0
  56. package/src/runlist.js +3 -2
  57. package/src/schedulewords.js +46 -4
  58. package/src/source.js +81 -7
  59. package/src/stepmcp.js +86 -0
  60. package/src/ticket.js +113 -0
  61. package/src/ticketfilter.js +76 -0
  62. package/src/ticketlabels.js +79 -0
  63. package/src/ticketmcp.js +111 -0
  64. package/src/ticketnext.js +35 -0
  65. package/src/ticketrepo.js +98 -0
  66. package/src/ticketschedule.js +32 -0
  67. package/src/ticketshape.js +45 -0
  68. package/src/tools.js +9 -0
  69. package/src/trigger.js +14 -2
  70. package/src/triggerclock.js +7 -3
  71. package/src/triggerfiles.js +19 -11
  72. package/src/triggertickets.js +244 -0
  73. package/src/u-readout.js +2 -2
  74. package/src/userrun.js +146 -10
  75. package/src/validate.js +3 -1
  76. package/src/worktree.js +43 -1
  77. package/types/authorflow.d.ts +128 -28
  78. package/types/authorjob.d.ts +16 -3
  79. package/types/authorreadout.d.ts +9 -2
  80. package/types/authorscout.d.ts +4 -2
  81. package/types/bridges.d.ts +4 -3
  82. package/types/cardschedule.d.ts +24 -0
  83. package/types/checkpick.d.ts +297 -0
  84. package/types/checksuggest.d.ts +30 -0
  85. package/types/checkwords.d.ts +14 -0
  86. package/types/config.d.ts +7 -0
  87. package/types/destpoint.d.ts +87 -0
  88. package/types/draftspend.d.ts +16 -0
  89. package/types/factwords.d.ts +7 -0
  90. package/types/job.d.ts +13 -0
  91. package/types/jobblock.d.ts +9 -0
  92. package/types/labelscan.d.ts +7 -0
  93. package/types/launcher.d.ts +7 -2
  94. package/types/mcpchecks.d.ts +8 -0
  95. package/types/mcppick.d.ts +33 -0
  96. package/types/mcpsources.d.ts +51 -0
  97. package/types/mcpuse.d.ts +15 -0
  98. package/types/natural.d.ts +2 -0
  99. package/types/pagemap.d.ts +2 -1
  100. package/types/panel/authorroutes.d.ts +11 -2
  101. package/types/panel/authorsession.d.ts +58 -3
  102. package/types/panel/jobgrid.d.ts +405 -0
  103. package/types/panel/jobplan.d.ts +10 -4
  104. package/types/panel/scheduler.d.ts +7 -2
  105. package/types/panel/schedules.d.ts +124 -4
  106. package/types/panel/schedulestart.d.ts +21 -3
  107. package/types/panel/server.d.ts +427 -6
  108. package/types/panel/settingsroutes.d.ts +4 -2
  109. package/types/panel/status.d.ts +16 -2
  110. package/types/panel/tickets.d.ts +61 -0
  111. package/types/pickrecord.d.ts +88 -0
  112. package/types/plan.d.ts +1 -0
  113. package/types/prcheckout.d.ts +151 -0
  114. package/types/readshim.d.ts +4 -3
  115. package/types/replay.d.ts +3 -0
  116. package/types/reuse.d.ts +2 -2
  117. package/types/revises.d.ts +23 -0
  118. package/types/rubricstep.d.ts +14 -5
  119. package/types/run.d.ts +18 -1
  120. package/types/runlist.d.ts +6 -3
  121. package/types/schedulewords.d.ts +29 -2
  122. package/types/source.d.ts +40 -4
  123. package/types/stepmcp.d.ts +40 -0
  124. package/types/ticket.d.ts +114 -0
  125. package/types/ticketfilter.d.ts +34 -0
  126. package/types/ticketlabels.d.ts +44 -0
  127. package/types/ticketmcp.d.ts +84 -0
  128. package/types/ticketnext.d.ts +33 -0
  129. package/types/ticketrepo.d.ts +118 -0
  130. package/types/ticketschedule.d.ts +21 -0
  131. package/types/ticketshape.d.ts +37 -0
  132. package/types/tools.d.ts +1 -0
  133. package/types/trigger.d.ts +9 -1
  134. package/types/triggerclock.d.ts +6 -2
  135. package/types/triggerfiles.d.ts +13 -5
  136. package/types/triggertickets.d.ts +110 -0
  137. package/types/userrun.d.ts +50 -0
  138. package/types/validate.d.ts +1 -0
  139. package/types/worktree.d.ts +19 -0
@@ -27,7 +27,7 @@ import {
27
27
  } from 'node:fs';
28
28
  import { join, resolve, dirname } from 'node:path';
29
29
  import {
30
- prepareSource, proveDestination, proveRubricInputs, looksLikeRubricInput, missingDependencies, looksLikeRepoSource, nearestGitAncestor, nonRepoSourceMessage,
30
+ prepareSource, proveDestination, proveRubricInputs, looksLikeRubricInput, missingDependencies, looksLikeRepoSource, nearestGitAncestor, nonRepoSourceMessage, destinationMissingInRepo, repoTrackedFiles,
31
31
  } from '../source.js';
32
32
  import {
33
33
  worktreePath, uncommittedCount, shortHead, removeWorktree,
@@ -48,21 +48,30 @@ import {
48
48
  resolveProvider, buildRunnerProviders, apiKeyProblem,
49
49
  } from '../providers.js';
50
50
  import { resolveJobJudge, defaultJudgeLoop } from '../judged.js';
51
- import { assertThinkingMode, thinkingPlanFor, thinkingRowText } from '../thinking.js';
51
+ import { assertThinkingMode, thinkingPlanFor, thinkingRowText, thinkingCallOptions } from '../thinking.js';
52
52
  import { closeJudges } from '../kinds.js';
53
53
  import { RUBRIC_LANG } from '../authoring.js';
54
54
  import { rubricGoal, reconcileRubricPlan, signedFactNames } from '../rubricstep.js';
55
55
  import { redactSecrets } from '../validate.js';
56
+ import { FLOW_TYPES } from '../job.js';
57
+ import { mcpPickFor, signFlow } from '../mcppick.js';
58
+ import { parseTicketList, ticketNumberOf, TICKET_NUMBER_WORDS } from '../ticketshape.js';
56
59
  import { isDropIt, isAgree, stripAgreeLead } from '../pagemap.js';
60
+ import { plainWords, SUGGEST_SYSTEM, settleRules } from '../checkpick.js';
61
+ import { readRecordFile, RECORD_FILE, KEPT_WORDS } from '../pickrecord.js';
62
+ import { MAX_REVISES, draftLabelOf, nextRevisesUsed, sessionsRootOf, writeRevisesUsed } from '../revises.js';
57
63
  import { FIT_ABSENT_NOTE } from '../fitcheck.js';
64
+ import { runDestPoint, destQuestionText, yesNoOf } from '../destpoint.js';
58
65
  import { tallyCalls } from '../text.js';
59
66
  import { appendDraftLog } from '../draftspend.js';
60
67
  import { PLAIN_PROPOSAL_STOPS, proposalStopText, signingStopText, draftStopText, redsRecord, declarationRecord, calibrationSummary, tryRefusedText } from '../authorreadout.js';
61
68
  import { runNpmCi, NPM_CI_LOCKS } from '../npminstall.js';
62
69
  import {
63
- parseJobBlock, parseInputs, jobBlockFitsCheck, renderJobLines, renderExamples, signedJobLines,
70
+ parseJobBlock, parseInputs, jobBlockFitsCheck, renderJobLines, renderExamples, signedJobLines, jobBoxText,
64
71
  } from '../jobblock.js';
65
72
  import { planFromConfirm } from './jobplan.js';
73
+ import { isTicketTrigger } from '../trigger.js';
74
+ import { ticketLookOf } from '../ticketschedule.js';
66
75
 
67
76
  /**
68
77
  * THE PROGRESS LIST's one table (hamr 2026-10-04, "one place showing all"): every pipeline step the left Chat panel
@@ -170,7 +179,7 @@ export const PLAN_FOOTER = 'Sign & run to confirm this plan, or Revise to edit t
170
179
  * The confirm turn's plan as a chat message (P7): a STRUCTURED `{role:'bot', kind:'plan', plan}` the page draws with the
171
180
  * same renderer the Job tab uses — each numbered job line, its `~` rule, its drafted checks folded; the AI's own "not
172
181
  * checked"; the always-on guards. `questions` (what the plan still asks) ride inside the plan. One owner of the shape.
173
- * @param {{goal?: string, checks?: string[], checkItems?: {text: string, fromLine: number[]|null}[], notChecked?: string[], questions?: string[], protections?: string[], signedFacts?: string[]}} p the confirm turn's plan
182
+ * @param {{goal?: string, checks?: string[], checkItems?: {text: string, fromLine: number[]|null}[], notChecked?: string[], questions?: string[], protections?: string[], signedFacts?: string[], ticketFilter?: any, picked?: {line: number, text: string}[]}} p the confirm turn's plan
174
183
  * @param {{n: number, text: string, rule: string}[]|null} jobLines
175
184
  * @returns {{role: 'bot', kind: 'plan', text: string, plan: ReturnType<typeof planFromConfirm> & {goal: string, questions: string[]}}}
176
185
  */
@@ -224,7 +233,7 @@ export function nextFreeJobName(origin, runJobs, opts = {}) {
224
233
  }
225
234
 
226
235
  /** the form's fields, in card order — what `card.json` stores, verbatim (P5 item 3) */
227
- export const CARD_FIELDS = Object.freeze(['jobName', 'checkType', 'provider', 'model', 'thinking', 'jobText', 'inputs', 'destination', 'capUsd', 'maxWallMs']);
236
+ export const CARD_FIELDS = Object.freeze(['jobName', 'checkType', 'provider', 'model', 'thinking', 'jobText', 'inputs', 'destination', 'capUsd', 'maxWallMs', 'flowType', 'mcp', 'ticket', 'schedule']);
228
237
 
229
238
  /**
230
239
  * The repo a card names: Inputs line 1 (P7 — the Source box is gone; the first input IS the repo). `''` when the Inputs
@@ -255,7 +264,53 @@ export function cardFields(card) {
255
264
  * `~` rules, `~ PASS`/`~ FAIL`), the check type and the thinking tick. The RUN boxes (Inputs, Destination, Model, $ cap, Time cap)
256
265
  * never decide it. A green origin with no job box changed reuses the signed plan verbatim (no drafting); anything else drafts.
257
266
  */
258
- export const JOB_BOXES = Object.freeze(['jobText', 'checkType', 'thinking']);
267
+ export const JOB_BOXES = Object.freeze(['jobText', 'checkType', 'thinking', 'flowType', 'mcp']);
268
+
269
+ /**
270
+ * The card's flow type and MCP, normalised: a card with no `flowType` (or `plain`) is plain with no MCP; any other pick keeps its server name.
271
+ * @param {any} card @returns {{flowType: 'plain'|'mcp'|'tickets', mcp: string}}
272
+ */
273
+ export function flowOfCard(card) {
274
+ const t = card?.flowType;
275
+ if (t !== 'mcp' && t !== 'tickets') return { flowType: 'plain', mcp: '' };
276
+ return { flowType: t, mcp: typeof card?.mcp === 'string' ? card.mcp.trim() : '' };
277
+ }
278
+
279
+ /**
280
+ * ITEM33-BUILD piece 8: what the card's Flow type and MCP become, decided at $0 before any session (nothing is started, no server runs). A plain card is `{flowType:'plain', pick:null}`.
281
+ * An MCP or Tickets card needs a server named in Settings > MCP and that server's newest successful `check tools` (`mcpPickFor`: ALL its tools, set by code); an unknown flow type, no pick, a
282
+ * never-checked MCP and a Tickets card with no ticket-list Inputs line are refused in plain words.
283
+ * @param {any} card @param {{ home?: string, mcpHome?: string }} [o]
284
+ * @returns {{ok: true, flowType: 'plain'|'mcp'|'tickets', pick: {server: string, tools: string[]}|null} | {ok: false, error: string}}
285
+ */
286
+ export function resolveFlowCard(card, o = {}) {
287
+ if (card?.flowType !== undefined && !FLOW_TYPES.includes(card.flowType)) return { ok: false, error: `Flow type must be one of ${FLOW_TYPES.join(', ')}.` };
288
+ const { flowType, mcp } = flowOfCard(card);
289
+ if (flowType === 'plain') return { ok: true, flowType, pick: null };
290
+ if (mcp === '') return { ok: false, error: 'Pick an MCP.' };
291
+ const pick = mcpPickFor(mcp, o);
292
+ if (!pick.ok) return { ok: false, error: pick.say };
293
+ if (flowType === 'tickets') {
294
+ const ip = parseInputs(card.inputs);
295
+ if (ip.ok && !ip.inputs.some((i) => parseTicketList(i.value).ok)) {
296
+ return { ok: false, error: 'Tickets MCP needs the ticket list address (the issues or pulls page of one repository) as an Inputs line.' };
297
+ }
298
+ }
299
+ return { ok: true, flowType, pick: { server: pick.server, tools: pick.tools } };
300
+ }
301
+
302
+ /**
303
+ * The by-hand ticket of a Tickets MCP run (ITEM33-BUILD piece 8): the number typed on the card, the same number `--ticket` takes, or BLANK = the newest ticket this job has not run
304
+ * (R6: `run-u` finds it with the schedule's own look, src/ticketnext.js, and a list that cannot be looked at says so and asks for a number). Any other job takes none.
305
+ * @param {any} card @param {'plain'|'mcp'|'tickets'} flowType the FINAL flow type of the job (the card's, or the reused spec's)
306
+ * @returns {string|null} the refusal in plain words, or null when the card is fine
307
+ */
308
+ export function ticketBoxProblem(card, flowType) {
309
+ const typed = typeof card?.ticket === 'string' ? card.ticket.trim() : (typeof card?.ticket === 'number' ? String(card.ticket) : '');
310
+ if (flowType !== 'tickets') return typed === '' ? null : 'A ticket number is only for a Tickets MCP job. Clear the Ticket box.';
311
+ if (typed === '') return null;
312
+ return ticketNumberOf(typed) === undefined ? `The ticket must be ${TICKET_NUMBER_WORDS}, not "${typed}".` : null;
313
+ }
259
314
 
260
315
  /**
261
316
  * Did any JOB box on `card` change from what the origin run prefilled (`origin`)? Whitespace is not compared (a one-line input drops
@@ -267,6 +322,8 @@ export const JOB_BOXES = Object.freeze(['jobText', 'checkType', 'thinking']);
267
322
  export function jobBoxesChanged(card, origin) {
268
323
  const text = (/** @type {any} */ v) => (typeof v === 'string' ? v.replace(/\s+/g, '') : '');
269
324
  return text(card?.jobText) !== text(origin?.jobText)
325
+ || flowOfCard(card).flowType !== flowOfCard(origin).flowType
326
+ || flowOfCard(card).mcp !== flowOfCard(origin).mcp
270
327
  || (card?.checkType === 'rubric') !== (origin?.checkType === 'rubric')
271
328
  || (card?.thinking === true) !== (origin?.thinking === true);
272
329
  }
@@ -335,6 +392,9 @@ export { nonRepoSourceMessage };
335
392
  /** the refusal for a plain-files rubric job whose Destination is not an absolute folder (ends with the words the session start shows) */
336
393
  export const FILES_DESTINATION_WORDS = 'Destination must be the full path of a folder, like /home/me/out — the finished files are delivered there. Nothing spent.';
337
394
 
395
+ /** the fixed example of a Destination refusal (code-owned; it never guesses a folder from the job's words) */
396
+ export const DESTINATION_HINT = 'Type the folder that holds the files the job should change, like src/.';
397
+
338
398
  /**
339
399
  * THE ONE Destination check of a session start, at $0, before any session, copy or model call. The session's own pipeline, the HTTP
340
400
  * start (`startSession`), the schedule's two clicks and a scheduled fire's `wouldAccept` all call THIS (never a copy of it), so a start
@@ -349,6 +409,12 @@ export function startDestinationProblem(card) {
349
409
  const isRepoLike = looksLikeRepoSource(source);
350
410
  const repo = repoDestinationProblem(destination, isRepoLike);
351
411
  if (repo !== null) return repo;
412
+ // R7b (F287): a repo's Destination is the write fence, so every piece of it must name something the repo really has (its committed tree: what the job's copy holds)
413
+ if (isRepoLike) {
414
+ const root = nearestGitAncestor(resolve(source))?.dir;
415
+ const missing = root === undefined ? null : destinationMissingInRepo(root, destination);
416
+ if (missing !== null) return `Destination \`${missing}\` is not a folder or file in this repo. ${DESTINATION_HINT}`;
417
+ }
352
418
  if (card?.checkType === 'rubric' && !isRepoLike && !isAbsoluteDestination(destination)) return FILES_DESTINATION_WORDS;
353
419
  return null;
354
420
  }
@@ -407,8 +473,8 @@ export function validateJobCard(card, opts = {}) {
407
473
  * `signPrepare()` are the only ways in.
408
474
  * @param {any} card the validated job card (see {@link validateJobCard})
409
475
  * @param {{env?: Record<string,string|undefined>, sessionsRoot?: string, home?: string, timeoutMs?: number,
410
- * scout?: any, generate?: Function, confirmGenerate?: Function, authorFn?: Function,
411
- * prepareSigningFn?: Function, npmCiFn?: Function, lookFn?: Function|null, fitFn?: Function|null, fetchUrl?: (url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>, draftThinking?: "on"|"off", reuse?: {spec: any, workflowKey: string}}} [deps] `scout`..`prepareSigningFn` are
476
+ * scout?: any, generate?: Function, pickGenerate?: Function|null, carryFrom?: string, carryKind?: string, confirmGenerate?: Function, authorFn?: Function,
477
+ * prepareSigningFn?: Function, npmCiFn?: Function, lookFn?: Function|null, fitFn?: Function|null, destFn?: Function|null, fetchUrl?: (url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>, draftThinking?: "on"|"off", reuse?: {spec: any, workflowKey: string}, schedule?: import('../trigger.js').Trigger|null, flow?: {flowType: 'plain'|'mcp'|'tickets', pick: {server: string, tools: string[]}|null}}} [deps] `scout`..`prepareSigningFn` are
412
478
  * TEST SEAMS ONLY — see the note just above where each is read, below. `reuse` (Reuse workflow) is NOT a seam: the
413
479
  * caller (`/api/author/start`) sets it only when the server's own same-job rule held.
414
480
  * @returns {any} the session object
@@ -426,7 +492,7 @@ export function createSession(card, deps = {}) {
426
492
  const INPUTS = inputsParsed.ok ? inputsParsed.inputs : [];
427
493
  /** the repo — Inputs line 1 */
428
494
  const SOURCE = INPUTS[0]?.value ?? '';
429
- const sessionsRoot = deps.sessionsRoot ?? join(process.env.HOME ?? '/tmp', '.config', 'bareloop', 'panel-sessions');
495
+ const sessionsRoot = sessionsRootOf(deps.sessionsRoot);
430
496
  // config.json lives beside the sessions dir (~/.config/bareloop) unless a home is injected
431
497
  const configHome = deps.home ?? dirname(sessionsRoot);
432
498
  const timeoutMs = deps.timeoutMs ?? 300_000;
@@ -442,13 +508,27 @@ export function createSession(card, deps = {}) {
442
508
  const id = `s${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
443
509
  const outDir = join(sessionsRoot, id);
444
510
  mkdirSync(outDir, { recursive: true });
511
+ // R10 (fwd am17/am18/am20): the picks record of the earlier session this draft follows (a Revise, or a Start over), read from that session's own folder. The id is a session id
512
+ // (never a path); no record, or an unreadable one, is no record: every rule is asked.
513
+ const carriedPicks = typeof deps.carryFrom === 'string' && /^s[a-z0-9]+$/.test(deps.carryFrom) ? readRecordFile(join(sessionsRoot, deps.carryFrom, RECORD_FILE)) : null;
514
+
515
+ // fwd M4e am14 item 3: the revises this draft has used (src/revises.js); the page reads `revisesLeft` to word its button
516
+ const revisesUsed = nextRevisesUsed(sessionsRoot, deps.carryFrom, deps.carryKind);
517
+ writeRevisesUsed(outDir, revisesUsed);
518
+ // fwd am14 item 6: the draft record says which kind of draft this is (a first draft says nothing); the Audit's Draft group reads it back
519
+ const draftLabel = draftLabelOf(deps.carryFrom, deps.carryKind, revisesUsed);
520
+ if (draftLabel !== null) appendDraftLog(outDir, { kind: 'draft-label', no: 0, label: draftLabel, at: new Date().toISOString() });
445
521
 
446
522
  /** @type {any} */
447
523
  const state = {
448
524
  id,
525
+ revisesUsed,
526
+ revisesLeft: Math.max(0, MAX_REVISES - revisesUsed),
449
527
  // the form as submitted + whether it is a reuse session: a refreshed page re-attaches to a live session from these
450
528
  card: cardFields(card),
451
529
  reuse: deps.reuse !== undefined,
530
+ // R7: the schedule the card asked for (the typed trigger the job is signed with); `signRun` writes it OFF beside the run it starts
531
+ ...(deps.schedule ? { schedule: deps.schedule } : {}),
452
532
  messages: /** @type {{role: string, text: string}[]} */ ([]),
453
533
  pendingAsk: /** @type {any} */ (null),
454
534
  cost: /** @type {any} */ (null),
@@ -524,7 +604,9 @@ export function createSession(card, deps = {}) {
524
604
  /** @param {'bot'|'you'|'system'} role @param {string} text */
525
605
  const say = (role, text) => { state.messages.push({ role, text }); };
526
606
  /** a structured message (the plan bubble): the page draws it, the thread keeps it as data */
527
- const sayPlan = (/** @type {any} */ plan) => { state.messages.push(planMessage(plan, jobLines)); };
607
+ /** the checks the person has agreed so far (their plain words, `kept from last draft` on a carried one): the plan bubble draws each once, as a `[you picked]` row @type {{line: number, text: string}[]} */
608
+ const pickedSoFar = [];
609
+ const sayPlan = (/** @type {any} */ plan) => { state.messages.push(planMessage({ ...plan, ...(pickedSoFar.length ? { picked: [...pickedSoFar] } : {}) }, jobLines)); };
528
610
 
529
611
  /** @type {((value: string|null) => void)|null} */
530
612
  let resolvePending = null;
@@ -564,7 +646,7 @@ export function createSession(card, deps = {}) {
564
646
  if (step.kind === 'language') say('bot', `${step.field?.prompt ?? 'Which language is this job about?'} (${(step.candidates ?? []).join(', ')})`);
565
647
  else if (step.kind === 'menu') {
566
648
  sayPlan(step.plan ?? {});
567
- } else if (step.kind === 'answer' && step.source === 'fit-check') say('bot', step.question);
649
+ } else if (step.kind === 'answer' && (step.source === 'fit-check' || step.source === 'dest-point')) say('bot', step.question);
568
650
  else if (step.kind === 'answer') say('bot', `A question the plan raised (${step.index} of ${step.total})${Number.isInteger(step.line) ? `, about job line ${step.line}` : ''}: ${step.question}`);
569
651
  else if (step.kind === 'goal') say('bot', 'Type the goal sentence yourself.');
570
652
  });
@@ -605,6 +687,8 @@ export function createSession(card, deps = {}) {
605
687
  if (PHASE_STEP[name]) stepStart(PHASE_STEP[name], PHASE_STEP[name] === 'draft' ? `${card.model}, $${card.capUsd.toFixed(2)} cap` : undefined);
606
688
  // WHY a try was refused: the drafting log keeps it beside the call that made it (it used to say only "retry 3 of 3"), and the
607
689
  // progress line shows it briefly, in code's words
690
+ // PRD v1.131 tick 7: the retention counts of a rubric draft, one line when it ends (counts only, no words)
691
+ if (name === 'draft-retention' && Array.isArray(data.lines)) appendDraftLog(outDir, { kind: 'retention', no: Math.max(0, state.steps.length - 1), lines: data.lines, at: new Date().toISOString() });
608
692
  if (name === 'author-try-failed') {
609
693
  lastTryRefused = true;
610
694
  const no = state.steps.findLastIndex((/** @type {any} */ x) => x.id === 'draft');
@@ -867,6 +951,14 @@ export function createSession(card, deps = {}) {
867
951
  */
868
952
  const finish = async (spec, seedRef) => {
869
953
  if (abandoned) return;
954
+ // R7 (piece 9): a schedule picked on the card is part of the job the person signs, so the FIRST run's hash already covers it. By hand adds nothing (the key stays absent).
955
+ if (deps.schedule) {
956
+ spec.trigger = deps.schedule;
957
+ if (isTicketTrigger(deps.schedule)) {
958
+ const look = ticketLookOf(spec, deps.schedule);
959
+ if (!look.ok) { refuse(look.say); return; }
960
+ }
961
+ }
870
962
  const specFile = join(outDir, 'resolved-spec.json');
871
963
  writeFileSync(specFile, `${JSON.stringify(spec, null, 2)}\n`);
872
964
  state.resolvedSpecPath = specFile;
@@ -956,7 +1048,7 @@ export function createSession(card, deps = {}) {
956
1048
  reds: redsRecord(signing.reds ?? [], { signing: true }), at: new Date().toISOString(),
957
1049
  });
958
1050
  refuse(signingStopText({
959
- reds: signing.reds ?? [], refusal: signing.refusal,
1051
+ reds: signing.reds ?? [], refusal: signing.refusal, closeDecl: spec.closeDecl,
960
1052
  spend: { knownUsd: state.draftSpentUsd, spendComplete: state.draftSpendComplete },
961
1053
  }));
962
1054
  return;
@@ -989,7 +1081,7 @@ export function createSession(card, deps = {}) {
989
1081
 
990
1082
  // a rubric job on files writes only inside the hidden tree's own `output/`; its Destination is a drop-off folder
991
1083
  // (proven above, per run), never a fence
992
- const writeScope = RUBRIC_FILES ? ['output/'] : card.destination.split(/[,\n]/).map((s) => s.trim()).filter(Boolean);
1084
+ let writeScope = RUBRIC_FILES ? ['output/'] : card.destination.split(/[,\n]/).map((s) => s.trim()).filter(Boolean);
993
1085
  /** @type {any} the confirm turn (below) fills `goal` in once accepted —
994
1086
  * declared loosely rather than typed field-by-field, since this object's
995
1087
  * own shape is a `job-v1` draft `validateJob` itself is the real
@@ -1045,16 +1137,54 @@ export function createSession(card, deps = {}) {
1045
1137
  const noCallAfterAbandon = (fn) => (...a) => { if (abandoned) throw new Error('abandoned — no new model call'); return fn(...a); };
1046
1138
  const generate = noCallAfterAbandon(deps.generate ?? makeLoopGenerate(provider, { rates: draftPrice?.rates ?? null, draftThinking }));
1047
1139
  const confirmGenerate = noCallAfterAbandon(deps.confirmGenerate ?? makeLoopGenerate(provider, { system: CONFIRM_SYSTEM, rates: draftPrice?.rates ?? null, draftThinking }));
1140
+ // R10 (fwd am16): the check-suggestion call's own model boundary (SUGGEST_SYSTEM, the drafter's thinking); a test that replaces the model boundary never reaches it unless it brings `deps.pickGenerate`
1141
+ const pickGenerate = deps.pickGenerate !== undefined ? deps.pickGenerate : (deps.generate ? null : noCallAfterAbandon(makeLoopGenerate(provider, { system: SUGGEST_SYSTEM, rates: draftPrice?.rates ?? null, draftThinking })));
1142
+
1143
+ // R7b (3), hamr's option A: the drafting AI POINTS when a job line's file to change lies outside Destination; code checks the claim (src/destpoint.js) and asks ONE typed
1144
+ // yes/no question through the same `ask` as the fit check's "go on". "yes" sets the fence (below) AND this session's card Destination (the page re-fills its box from it);
1145
+ // "no" goes on unchanged. The fence and the draft are updated before the composer sees them, so the signed spec carries the answer. The caller's own card object is never mutated. A repo job only; failure is OPEN.
1146
+ if (!RUBRIC_FILES && isRepoLike) {
1147
+ const destFn = deps.destFn !== undefined ? deps.destFn : (deps.generate ? null : runDestPoint);
1148
+ const tracked = destFn ? repoTrackedFiles(prep.tree) : null;
1149
+ if (destFn && tracked !== null) {
1150
+ const pointed = await destFn({
1151
+ jobLines, files: tracked, destination: card.destination, provider, ceilingUsd: card.capUsd, onCall, ...(draftPrice?.rates ? { rates: draftPrice.rates } : {}),
1152
+ ...(Object.keys(thinkingCallOptions(provider, draftThinking)).length ? { callOptions: thinkingCallOptions(provider, draftThinking) } : {}),
1153
+ });
1154
+ if (abandoned) return;
1155
+ appendDraftLog(outDir, { kind: 'dest-point', no: Math.max(0, state.steps.length - 1), state: pointed.state, ...(pointed.point ? { line: pointed.point.line, file: redactSecrets(pointed.point.file), folder: redactSecrets(pointed.point.folder) } : {}), ...(pointed.reason ? { reason: redactSecrets(pointed.reason) } : {}), at: new Date().toISOString() });
1156
+ if (pointed.state === 'point' && pointed.point) {
1157
+ const question = destQuestionText(pointed.point, card.destination);
1158
+ let said = null;
1159
+ while (said === null) {
1160
+ const a = await ask({ kind: 'answer', source: 'dest-point', index: 1, total: 1, question, line: pointed.point.line });
1161
+ if (a === null) return;
1162
+ said = yesNoOf(a);
1163
+ if (said === null) say('bot', 'Type yes or no.');
1164
+ }
1165
+ appendDraftLog(outDir, { kind: 'dest-answer', no: Math.max(0, state.steps.length - 1), answer: said, from: redactSecrets(card.destination), to: redactSecrets(pointed.point.folder), at: new Date().toISOString() });
1166
+ if (said === 'yes') {
1167
+ card = { ...card, destination: pointed.point.folder };
1168
+ writeScope = [pointed.point.folder];
1169
+ draft.writeScope = writeScope;
1170
+ state.card = { ...state.card, destination: pointed.point.folder };
1171
+ say('bot', `Destination is now ${pointed.point.folder}. Drafting.`);
1172
+ } else say('bot', 'Destination stays as it is. Drafting.');
1173
+ }
1174
+ }
1175
+ }
1048
1176
 
1049
1177
  // P7 item 5 (fwdloop am24/25): the last drafting try, after two failed ones, may ask. Each question comes through the same
1050
1178
  // ask path as every other (the chat box + Send); the answer is REQUIRED (a blank one asks again, there is no skip) and is
1051
1179
  // added WORD FOR WORD as a `~` rule on the job line it names — never rewritten. The lines are mutated in place, so the
1052
1180
  // signed `jobLines`, the answers text and the plan card all read the same words.
1053
- const answerQuestions = async (/** @type {{questions: {line: number, question: string, rule?: number, source?: string, ask?: string, reading?: string}[], dropped: {reason: string, raw: any}[], confirmed: any}} */ o) => {
1181
+ const answerQuestions = async (/** @type {{questions: {line: number, question: string, rule?: number, source?: string, ask?: string, reading?: string, ruleText?: string, check?: Record<string, any>}[], dropped: {reason: string, raw: any}[], confirmed: any}} */ o) => {
1054
1182
  if (o.dropped.length) appendDraftLog(outDir, { kind: 'questions-dropped', no: Math.max(0, state.steps.length - 1), dropped: o.dropped, at: new Date().toISOString() });
1055
1183
  const total = o.questions.length;
1056
1184
  /** @type {{line: number, rule: number}[]} */
1057
1185
  const left = [];
1186
+ /** R10: the picks the person made (fwd am16): the check agreed to, or their own words with no check @type {{line: number, rule: number, check: Record<string, any>|null, added?: string, own?: boolean}[]} */
1187
+ const picks = [];
1058
1188
  for (let k = 0; k < total; k += 1) {
1059
1189
  const q = o.questions[k];
1060
1190
  let text = '';
@@ -1073,13 +1203,29 @@ export function createSession(card, deps = {}) {
1073
1203
  if (q.source === 'look') text = stripAgreeLead(text);
1074
1204
  if (q.source === 'look' && q.ask === 'reading' && typeof q.reading === 'string' && isAgree(text)) text = q.reading;
1075
1205
  if (q.source === 'look' && q.ask === 'cant-check' && Number.isInteger(q.rule) && isDropIt(text)) { left.push({ line: q.line, rule: /** @type {number} */ (q.rule) }); continue; }
1206
+ // R10 (fwd am16): a check-pick ask. `agree` writes the proposal's plain words as a new `~` rule and picks the check; "drop it" leaves the rule Not checked; anything else
1207
+ // is the person's own words, a `~` rule word for word with no check (Not checked: they judge it at Accept)
1208
+ const isPick = q.source === 'look' && (q.ask === 'check' || q.ask === 'no-check') && Number.isInteger(q.rule);
1209
+ // am21: the ask is about the person's EDITED added `~` line (`pairRule` = the rule it was agreed from): the answer REPLACES that line and the pick is kept under the source's number
1210
+ const pair = isPick && Number.isInteger(/** @type {any} */ (q).pairRule) ? /** @type {number} */ (/** @type {any} */ (q).pairRule) : null;
1211
+ if (isPick && isDropIt(text)) { left.push({ line: q.line, rule: /** @type {number} */ (q.rule) }); if (pair !== null) left.push({ line: q.line, rule: pair }); appendDraftLog(outDir, { kind: 'check-pick', no: Math.max(0, state.steps.length - 1), line: q.line, rule: q.rule, ruleText: redactSecrets(String(q.ruleText ?? '')), proposed: q.reading ?? null, how: 'drop it', at: new Date().toISOString() }); continue; }
1212
+ if (isPick) {
1213
+ const agreed = q.ask === 'check' && q.check && isAgree(text);
1214
+ if (agreed) text = plainWords(/** @type {any} */ (q.check));
1215
+ if (agreed) pickedSoFar.push({ line: q.line, text: plainWords(/** @type {any} */ (q.check)) });
1216
+ picks.push({ line: q.line, rule: pair ?? /** @type {number} */ (q.rule), check: agreed ? /** @type {any} */ (q.check) : null, added: text, ...(agreed ? {} : { own: true }) });
1217
+ appendDraftLog(outDir, { kind: 'check-pick', no: Math.max(0, state.steps.length - 1), line: q.line, rule: q.rule, ruleText: redactSecrets(String(q.ruleText ?? '')), proposed: q.reading ?? null, how: agreed ? 'agree' : 'own words', ...(agreed ? { picked: q.check } : {}), added: redactSecrets(text), at: new Date().toISOString() });
1218
+ }
1076
1219
  const line = jobLines.find((l) => l.n === q.line);
1077
- if (line) { line.rule = line.rule ? `${line.rule}; ${text}` : text; line.rules.push(text); }
1220
+ if (line && pair !== null) { line.rules[/** @type {number} */ (q.rule) - 1] = text; line.rule = line.rules.join('; '); }
1221
+ else if (line) { line.rule = line.rule ? `${line.rule}; ${text}` : text; line.rules.push(text); }
1078
1222
  }
1079
1223
  draft.jobLines = signedJobLines(jobLines);
1224
+ // R10 (fwd am21): the answers are `~` rules on the lines, so the card's job box says so too: a Revise reopens the boxes WITH them, and an edit of an agreed line is seen as an edit
1225
+ state.card = { ...state.card, jobText: jobBoxText(jobLines) };
1080
1226
  answers[1] = renderJobLines(jobLines);
1081
- state.messages.push({ ...planMessage(o.confirmed ?? {}, jobLines), text: left.length === total ? 'Noted: those stay Not checked. Drafting.' : 'Your answers are in as ~ rules on those job lines. Drafting again.' });
1082
- return { jobLines, answers, left };
1227
+ state.messages.push({ ...planMessage({ ...(o.confirmed ?? {}), ...(pickedSoFar.length ? { picked: [...pickedSoFar] } : {}) }, jobLines), text: left.length === total ? 'Noted: those stay Not checked. Drafting.' : 'Your answers are in as ~ rules on those job lines. Drafting again.' });
1228
+ return { jobLines, answers, left, picks };
1083
1229
  };
1084
1230
 
1085
1231
  // F243: the fit check's one question, through the same `ask` (the chat box + Send; a blank answer asks again, there is no skip)
@@ -1107,7 +1253,15 @@ export function createSession(card, deps = {}) {
1107
1253
  rates: draftPrice?.rates ?? null,
1108
1254
  draftThinking,
1109
1255
  onPhase, onCall,
1110
- ask, answerQuestions, confirmGenerate, isRepo: !RUBRIC_FILES, langResult,
1256
+ ask, answerQuestions, confirmGenerate, isRepo: !RUBRIC_FILES, langResult, pickGenerate, carriedPicks,
1257
+ // R10: this draft's record (the picks it kept and the ones just answered) goes to its own folder for the next draft to carry; each kept pick is logged as such
1258
+ onPicks: (/** @type {{entries: any[], kept: {line: number, rule: number, entry: any}[]}} */ o) => {
1259
+ try { writeFileSync(join(outDir, RECORD_FILE), `${JSON.stringify({ picks: o.entries })}\n`, { mode: 0o600 }); } catch { /* the record is a convenience: a disk fault only means the next draft asks again */ }
1260
+ for (const k of o.kept) {
1261
+ if (k.entry.check) pickedSoFar.push({ line: k.line, text: `${plainWords(/** @type {any} */ (k.entry.check))} \u00B7 ${KEPT_WORDS}` });
1262
+ appendDraftLog(outDir, { kind: 'check-pick', no: Math.max(0, state.steps.length - 1), line: k.line, rule: k.rule, ruleText: redactSecrets(String(k.entry.ruleText ?? '')), how: KEPT_WORDS, ...(k.entry.check ? { picked: k.entry.check } : {}), ...(k.entry.left ? { left: true } : {}), ...(k.entry.own ? { own: true } : {}), at: new Date().toISOString() });
1263
+ }
1264
+ },
1111
1265
  ...(deps.scout ? { scout: deps.scout } : {}),
1112
1266
  // PART 1c: a test that replaces the model boundary (`generate`) must not reach the real paid look; `deps.lookFn` brings its own
1113
1267
  ...(deps.lookFn !== undefined ? { lookFn: deps.lookFn } : (deps.generate ? { lookFn: null } : {})),
@@ -1115,6 +1269,8 @@ export function createSession(card, deps = {}) {
1115
1269
  fitAsk, onFit,
1116
1270
  ...(deps.fitFn !== undefined ? { fitFn: deps.fitFn } : (deps.generate ? { fitFn: null } : {})),
1117
1271
  ...(authorFnOverride ? { authorFn: authorFnOverride } : {}),
1272
+ // R5 (piece 2): a Tickets job's drafter is told about the ticket filter and may propose one (the person signs it)
1273
+ ...(deps.flow?.flowType === 'tickets' ? { authorOpts: { ticket: true } } : {}),
1118
1274
  });
1119
1275
 
1120
1276
  if (!authored.ok && PLAIN_PROPOSAL_STOPS.includes(String(authored.stop))) {
@@ -1152,7 +1308,8 @@ export function createSession(card, deps = {}) {
1152
1308
 
1153
1309
  if (RUBRIC_FILES) draft.goal = redactSecrets(rubricGoal({ jobLines, files: prep.manifest.inputs, confirmedGoal: authored.confirmed?.goal ?? null, closeDecl: authored.closeDecl }));
1154
1310
  else if (authored.confirmed?.goal) draft.goal = redactSecrets(String(authored.confirmed.goal));
1155
- const spec = assembleSpec(draft, { ...authored, verdictType: /** @type {string} */ (authored.verdictType) });
1311
+ // piece 8: the card's Flow type and MCP pick are signed by CODE, after the draft (the agent cannot carry them: `assembleSpec` refuses a draft that does). A plain card adds nothing.
1312
+ const spec = signFlow(assembleSpec(draft, { ...authored, verdictType: /** @type {string} */ (authored.verdictType) }), deps.flow?.flowType ?? 'plain', deps.flow?.pick ?? null, authored.authoring?.ticketFilter);
1156
1313
  // PART 1a (run mv5bk400): the plan the person confirmed named three checks for line 1; the composer wrote ONE stage and put
1157
1314
  // "lists 3 releases" in its notes, so the card promised a check the close never ran. The card AFTER drafting is now built
1158
1315
  // from the close itself, and every confirmed check no part carries out is moved to Not checked, in code, before signing.
@@ -1160,7 +1317,12 @@ export function createSession(card, deps = {}) {
1160
1317
  const rec = reconcileRubricPlan({
1161
1318
  confirmed: authored.confirmed?.checkItems ?? [], notChecked: authored.confirmed?.notChecked ?? [], closeDecl: spec.closeDecl, jobLines,
1162
1319
  });
1163
- state.finalPlan = { goal: String(draft.goal ?? ''), checkItems: rec.checkItems, notChecked: rec.notChecked, protections: authored.confirmed?.protections ?? [], moved: rec.moved, signedFacts: signedFactNames(spec.closeDecl) };
1320
+ // the checks this draft ended with, each marked who added it (`agent` or `you`): the Audit's Draft group shows them (a log line, not a second record of the plan)
1321
+ appendDraftLog(outDir, { kind: 'draft-checks', no: Math.max(0, state.steps.length - 1), checks: rec.checkItems.filter((/** @type {any} */ c) => c.by === 'agent' || c.by === 'you').map((/** @type {any} */ c) => ({ line: c.fromLine[0], text: redactSecrets(String(c.text)), by: c.by })), at: new Date().toISOString() });
1322
+ // R10: the checks the person picked, for the plan card's "You picked" rows (the check rows and the Not checked rows come from the signed close itself)
1323
+ const cp = authored.checkPicks;
1324
+ const picked = cp ? settleRules(cp.rules, cp.picks, cp.left, jobLines).checks.map((c) => ({ line: c.line, text: `${plainWords(/** @type {any} */ (c.check))}${c.kept ? ` \u00B7 ${KEPT_WORDS}` : ''}` })) : [];
1325
+ state.finalPlan = { goal: String(draft.goal ?? ''), checkItems: rec.checkItems, picked, notChecked: rec.notChecked, protections: authored.confirmed?.protections ?? [], moved: rec.moved, signedFacts: signedFactNames(spec.closeDecl), ...(spec.ticketFilter ? { ticketFilter: spec.ticketFilter } : {}) };
1164
1326
  }
1165
1327
  await finish(spec, authored.seedRef);
1166
1328
  if (state.finalPlan && state.phase === 'prepared') {
@@ -1169,7 +1331,7 @@ export function createSession(card, deps = {}) {
1169
1331
  // dropped, so drafter prose can never sit above (and be read instead of) the code's sentences (run mv5e1ktb).
1170
1332
  state.messages = state.messages.filter((/** @type {any} */ m) => m.kind !== 'plan');
1171
1333
  state.messages.push({
1172
- ...planMessage({ checkItems: state.finalPlan.checkItems, checks: state.finalPlan.checkItems.map((/** @type {any} */ c) => c.text), notChecked: state.finalPlan.notChecked, protections: state.finalPlan.protections, signedFacts: state.finalPlan.signedFacts, questions: [] }, jobLines),
1334
+ ...planMessage({ checkItems: state.finalPlan.checkItems, checks: state.finalPlan.checkItems.map((/** @type {any} */ c) => c.text), notChecked: state.finalPlan.notChecked, protections: state.finalPlan.protections, signedFacts: state.finalPlan.signedFacts, picked: state.finalPlan.picked, ticketFilter: state.finalPlan.ticketFilter, questions: [] }, jobLines),
1173
1335
  text: 'These are the checks the signed close will run, and what it will not check. Sign & run to accept them, or Revise to edit the boxes and draft again.',
1174
1336
  });
1175
1337
  }