fwdloop 0.15.0 → 0.17.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 (72) hide show
  1. package/README.md +2 -0
  2. package/bin/fwdloop +113 -36
  3. package/package.json +2 -2
  4. package/src/authoring.js +27 -15
  5. package/src/catalogue.json +9 -3
  6. package/src/closers.js +5 -0
  7. package/src/config.js +66 -4
  8. package/src/ctx-tools.js +245 -0
  9. package/src/declaration.js +25 -1
  10. package/src/draft-steps.js +138 -0
  11. package/src/drafter.js +81 -18
  12. package/src/draftspend.js +109 -3
  13. package/src/flowmodel.js +30 -0
  14. package/src/input-facts.js +12 -3
  15. package/src/keysfile.js +51 -16
  16. package/src/liveness.js +34 -10
  17. package/src/model-step.js +13 -11
  18. package/src/monthly.js +9 -1
  19. package/src/panel/author.js +170 -43
  20. package/src/panel/authorcard.js +32 -20
  21. package/src/panel/authorflows.js +34 -19
  22. package/src/panel/authorresume.js +11 -9
  23. package/src/panel/authorstart.js +11 -9
  24. package/src/panel/authorvalues.js +5 -3
  25. package/src/panel/data.js +20 -8
  26. package/src/panel/index.html +584 -182
  27. package/src/panel/resume.js +3 -3
  28. package/src/panel/server.js +12 -6
  29. package/src/panel/settings.js +138 -80
  30. package/src/panel/spawn.js +15 -9
  31. package/src/plain-checks.js +51 -0
  32. package/src/primitives.js +34 -3
  33. package/src/provider.js +148 -181
  34. package/src/providershapes.js +7 -7
  35. package/src/run-store.js +47 -0
  36. package/src/runner.js +40 -22
  37. package/src/setup.js +3 -0
  38. package/src/thinking.js +55 -0
  39. package/src/version.js +13 -0
  40. package/types/authoring.d.ts +11 -6
  41. package/types/closers.d.ts +2 -0
  42. package/types/config.d.ts +9 -1
  43. package/types/ctx-tools.d.ts +18 -0
  44. package/types/draft-steps.d.ts +47 -0
  45. package/types/drafter.d.ts +15 -12
  46. package/types/draftspend.d.ts +56 -0
  47. package/types/flowmodel.d.ts +16 -0
  48. package/types/input-facts.d.ts +6 -1
  49. package/types/keysfile.d.ts +23 -6
  50. package/types/liveness.d.ts +7 -1
  51. package/types/model-step.d.ts +1 -1
  52. package/types/monthly.d.ts +1 -0
  53. package/types/panel/author.d.ts +47 -9
  54. package/types/panel/authorcard.d.ts +33 -10
  55. package/types/panel/authorflows.d.ts +32 -9
  56. package/types/panel/authorresume.d.ts +2 -1
  57. package/types/panel/authorstart.d.ts +16 -6
  58. package/types/panel/authorvalues.d.ts +3 -1
  59. package/types/panel/data.d.ts +2 -2
  60. package/types/panel/resume.d.ts +2 -1
  61. package/types/panel/server.d.ts +6 -2
  62. package/types/panel/settings.d.ts +3 -1
  63. package/types/panel/spawn.d.ts +13 -4
  64. package/types/plain-checks.d.ts +22 -0
  65. package/types/primitives.d.ts +0 -6
  66. package/types/provider.d.ts +100 -284
  67. package/types/providershapes.d.ts +3 -4
  68. package/types/run-store.d.ts +11 -0
  69. package/types/runner.d.ts +2 -4
  70. package/types/setup.d.ts +8 -0
  71. package/types/thinking.d.ts +25 -0
  72. package/types/version.d.ts +2 -0
package/src/drafter.js CHANGED
@@ -16,14 +16,19 @@
16
16
  // prices an unpriced round at the ceiling.
17
17
 
18
18
  import { Loop, HaltError } from 'bare-agent';
19
+ import { capTooSmallText, usdText } from './draftspend.js';
19
20
  import { parseSignedText, unsignedAskTtls } from './signed-text.js';
20
21
  import { validateDeclaration, SHAPE_KEYS, checkGuardrailSums, guardrailWordsPerSection } from './declaration.js';
21
22
  import { loadCatalogue } from './catalogue.js';
22
23
  import { WIRED_VERBS, wiredMenu } from './primitives.js';
23
24
  import { readInputFacts } from './input-facts.js';
24
- import { makeProvider, sumMeterings, ceilingCostUsd, priceRecord } from './provider.js';
25
+ import { isCellsPath } from './closers.js';
26
+ import {
27
+ makeProvider, ModelRefusal, sumMeterings, ceilingCostUsd, priceRecord,
28
+ } from './provider.js';
25
29
  import { LIVE_PROVIDER_OPTIONS } from './model-step.js';
26
30
  import { ConfigError } from './config.js';
31
+ import { thinkingSay, worstThinkingStatus } from './thinking.js';
27
32
 
28
33
  export const MAX_STRUCTURE_RETRIES = 2;
29
34
  export const MAX_REVISIONS = 2;
@@ -63,7 +68,7 @@ export function buildDeclarationSchema(menu) {
63
68
  items: { type: 'string', enum: menu.map((e) => e.verb) },
64
69
  description: 'verbs this step is granted, from the menu only; [] for a pure stop',
65
70
  },
66
- reads: { type: 'array', items: { type: 'string' }, description: 'artifact ids emitted by EARLIER steps only' },
71
+ reads: { type: 'array', items: { type: 'string' }, description: 'artifact ids emitted by EARLIER steps only (an ask step lists the earlier output to be checked FIRST), or the role of a CSV input (a step whose line has a green guardrail must list a CSV input role here)' },
67
72
  emits: { type: 'string', minLength: 1, description: 'the ONE new artifact id this step declares (unique)' },
68
73
  fromLine: { type: ['integer', 'null'], description: 'the ONE numbered job line this step serves' },
69
74
  picks: {
@@ -214,6 +219,30 @@ function jobLinesText(lines, asks) {
214
219
  .join('\n');
215
220
  }
216
221
 
222
+ /** M4d amendment 8: the green step must read an input with cells, so the drafter is told the rule and which inputs have cells. */
223
+ function greenReadRule(sources) {
224
+ const csvRoles = (sources ?? []).filter((s) => s.kind === 'file' && isCellsPath(s.path)).map((s) => s.role);
225
+ const rule = '- A step whose line has a "green" guardrail must list the CSV input\'s role in its reads (for example reads: ["aging"]), because only an input with cells can be cited; a text output of an earlier step has no cells. A green step that reads only other steps is refused.';
226
+ return [csvRoles.length
227
+ ? `${rule} CSV inputs in this job: ${csvRoles.join(', ')}.`
228
+ : `${rule} This job signs no CSV input, so a guardrail that needs cited cells cannot be classed green here: class it "hitl".`];
229
+ }
230
+
231
+ /** M7 piece 6 (signed scope item 1): a granted verb ships WITH the line that says when to reach for it, or the
232
+ * model keeps using the familiar one. Only these three get a line; each only when it is on the menu. No number
233
+ * (the tool itself tells a step its size limit). Borrowed in spirit from bareloop src/tools.js@dc06660 strategyFor. */
234
+ const WHEN_TO_USE = Object.freeze({
235
+ compress: '- Use compress when a step only needs what a function IS (its signature and doc) rather than how it works: it returns the head without the body, far cheaper than reading the file. Code only.',
236
+ stash: '- Use stash to park a bulky intermediate result under an id instead of carrying it from step to step; it lasts this run only and each parked item has a size limit.',
237
+ peek: '- Use peek to look at the start and end of something parked with stash without loading all of it.',
238
+ });
239
+
240
+ /** @param {Array<{verb: string}>} menu */
241
+ function whenToUse(menu) {
242
+ const on = new Set(menu.map((e) => e.verb));
243
+ return Object.entries(WHEN_TO_USE).filter(([verb]) => on.has(verb)).map(([, line]) => line);
244
+ }
245
+
217
246
  export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
218
247
  const askLines = arbiter.asks.map((a) => a.line);
219
248
  const sendLines = arbiter.sends.map((s) => s.line);
@@ -223,15 +252,18 @@ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
223
252
  'Primitive menu (a grant list; a verb not listed does not exist):',
224
253
  ...menu.map((e) => `- ${e.verb}: ${e.desc} (class: ${e.class})`),
225
254
  '',
255
+ ...(whenToUse(menu).length ? ['When to use them:', ...whenToUse(menu), ''] : []),
226
256
  'Rules:',
227
- '- Steps share one artifact space. Each step: primitives (verbs it needs, [] if none), reads (artifact ids emitted by an EARLIER step only), emits (ONE new unique artifact id), fromLine (the ONE job line it serves), close. The machine fills each step\'s goal with that signed line, verbatim — you never write a goal.',
257
+ '- Steps share one artifact space. Each step: primitives (verbs it needs, [] if none), reads (artifact ids emitted by an EARLIER step, or the role of a CSV input listed under Inputs), emits (ONE new unique artifact id), fromLine (the ONE job line it serves), close. The machine fills each step\'s goal with that signed line, verbatim — you never write a goal.',
228
258
  '- Every numbered job line must be served by a step (fromLine = that line) or listed in "refused" with a reason.',
229
259
  '- guardrailClasses: for each job line that HAS a guardrail, classify its wording once: "green" (every figure must cite its source cell), "softgreen" (the human declared a SHAPE the output must take), "hitl" (an ask/accept/review gate, or anything you are not sure of). When unsure, "hitl".',
230
260
  '- close.class MUST equal the class of the guardrail on that step\'s fromLine (guardrailClasses[fromLine]); a line with no guardrail is "hitl". A step cannot claim a class its own line does not earn.',
261
+ ...greenReadRule(arbiter.sources),
231
262
  '- close.shape only on a softgreen step; it is the human\'s declared shape in structured form.',
232
263
  '- A step whose check reads its reply (softgreen) answers in its reply text and is never granted `write`, `edit` or any other write-class verb; only the send step at the end writes files out.',
233
264
  `- Signed ask line(s): ${askLines.length ? askLines.join(', ') : 'none'}. For each, emit EXACTLY ONE step: fromLine = that line, close.class "hitl", primitives []. It is a stop only — never grant a primitive on it, and never emit a pause at any other line.`,
234
265
  `- Signed send line(s): ${sendLines.length ? sendLines.join(', ') : 'none'}. That step is drafted like any other: grant the write primitive and read the artifact of the ask step that comes before it. Its target and position are signed, not yours.`,
266
+ '- An ask step must read the output of an earlier step, the thing you are asked to check: its FIRST read is what the human sees at the ask (for example reads: ["bucket_assignment"], the nearest earlier step\'s emits). An ask that reads nothing, or reads something no earlier step makes, is refused. Reading is not a grant: the ask still grants no primitive.',
235
267
  '- Nothing hitl may come after the last signed ask except the send step.',
236
268
  '- You never author a trigger, cap, ask position or TTL, allow-list, send target, or what "done" means.',
237
269
  '',
@@ -260,13 +292,10 @@ function reviseMessage(reds) {
260
292
 
261
293
  function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArray(v); }
262
294
 
263
- // F49: deepseek-flash 400s on a forced tool_choice in thinking mode; the drafter forces its tool, so disable thinking.
264
- export const DRAFT_PROVIDER_OPTIONS = Object.freeze({ ...LIVE_PROVIDER_OPTIONS, thinking: Object.freeze({ type: 'disabled' }) });
265
-
266
295
  /**
267
296
  * Draft one declaration. `provider`/`rates`/`modelId` may be injected (tests,
268
297
  * the batch); otherwise a live provider is built from `slot` (throws on a bad
269
- * key — the batch preflights first). `budgetUsd` is this draft's hard cap.
298
+ * key — the batch preflights first). The draft's hard cap is the cap signed in the prose (M4d am13); `priorSpend(ceilingUsd)` (am16) is what this job's earlier drafting already spent, so every round must fit what is LEFT of the cap.
270
299
  * `makeProviderFn` is a test seam: the live-provider factory (default `makeProvider`).
271
300
  * `onBook` (M4e piece 2a, scope 13): called right BEFORE each provider call (`inFlight: true`, the call counted in
272
301
  * `calls`) and right AFTER it (`inFlight: false`), with what is known so far, so the caller can book spend per call
@@ -275,17 +304,24 @@ export const DRAFT_PROVIDER_OPTIONS = Object.freeze({ ...LIVE_PROVIDER_OPTIONS,
275
304
  *
276
305
  * @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
277
306
  * costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[],
278
- * questions?:{line:number, question:string}[], droppedQuestions?:object[], notChecked?:string[]}>}
307
+ * questions?:{line:number, question:string}[], droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[]}>}
279
308
  */
280
309
  export async function draft({
281
- proseText, slot = 'deepseek', model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
282
- budgetUsd = 0.10, skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true,
310
+ proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
311
+ priorSpend = /** @type {((ceilingUsd: number) => number)|null} */ (null), skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true, draftThinking = /** @type {'on'|'off'} */ ('off'),
283
312
  }) {
313
+ // What was asked of thinking and the WORST status bareagent reported across the rounds (the page says it loudly unless 'applied'). Read from the round log, the one record.
314
+ const thinkingOf = () => {
315
+ const status = worstThinkingStatus(log.map((e) => e.thinkingStatus));
316
+ return { asked: draftThinking, status, say: thinkingSay(status) };
317
+ };
284
318
  const fail = (reds, extra = {}) => ({
285
319
  ok: false, declaration: null, reds, rounds: 0, calls: 0, spendComplete: true, costUsd: 0, modelReturned: null, structureRetries: 0, revisions: 0, stop: 'pre-flight', log: [], ...extra,
286
320
  });
287
321
 
288
322
  // ---- $0 gates, before any provider is built -------------------------------
323
+ // `draftThinking` ('on'|'off', M4d am6 item 7 / am7: the Chat tick-box, per job) is an intent only: turning thinking on or off on the wire is bareagent's (am7 item 3).
324
+ if (draftThinking !== 'on' && draftThinking !== 'off') return fail([`config: draftThinking must be on | off, got ${JSON.stringify(draftThinking)}`]);
289
325
  const parsed = parseSignedText(proseText);
290
326
  if (!parsed.ok) return fail(parsed.reds.map((r) => `signed-text: ${r}`));
291
327
  const { lines, arbiter } = parsed;
@@ -304,9 +340,9 @@ export async function draft({
304
340
  try {
305
341
  ({
306
342
  provider, rates, modelId, prices = null,
307
- } = makeProviderFn(slot, { model, env, ...DRAFT_PROVIDER_OPTIONS }));
343
+ } = makeProviderFn(slot, { model, env, ...LIVE_PROVIDER_OPTIONS }));
308
344
  } catch (err) {
309
- return fail([`${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`]);
345
+ return fail([err instanceof ModelRefusal ? err.message : `${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`]);
310
346
  }
311
347
  }
312
348
 
@@ -318,10 +354,19 @@ export async function draft({
318
354
  const cat = loadCatalogue();
319
355
  if (!cat.ok) return fail([`catalogue: ${cat.reds.join('; ')}`]);
320
356
  const validationCatalogue = cat.primitives;
321
- const roundCeiling = ceilingCostUsd(modelId, undefined, prices ? { prices } : {});
322
- // One round at its ceiling must fit the budget, or refuse at $0 before any provider call.
357
+ // The hold: the picked model's own Settings prices (or the rates a test injected) times the token bounds - never a table.
358
+ if (!rates) return fail(['price: this round has no price to hold - tick a model in Settings > Providers with both prices first']);
359
+ const roundCeiling = ceilingCostUsd(rates);
360
+ // M4d am13: the draft is capped by the card's Cap $ (the cap signed in the prose), the same number the run is capped at.
361
+ // One round at its ceiling must fit that cap, or refuse at $0 before any provider call.
362
+ // M4d am16 item 2: against the remaining money, not the whole cap. Spend by earlier drafts of this job (a revise, the redraft after answers) is taken off first.
363
+ const priorUsd = typeof priorSpend === 'function' ? priorSpend(roundCeiling) : 0;
364
+ const budgetUsd = arbiter.capUsd - priorUsd;
323
365
  if (roundCeiling > budgetUsd) {
324
- return fail([`budget: $${budgetUsd} is below one round's worst-case cost — the minimum budget is $${roundCeiling.toFixed(4)}`]);
366
+ const capText = usdText(arbiter.capUsd);
367
+ return fail([priorUsd > 0
368
+ ? `Cap ${capText} less ${usdText(priorUsd)} already spent on drafting leaves ${usdText(Math.max(0, budgetUsd))}, below one drafting round's worst case for ${modelId}, $${roundCeiling.toFixed(4)}. Raise Cap $ or pick another model.`
369
+ : capTooSmallText('drafting', arbiter.capUsd, roundCeiling, modelId)]);
325
370
  }
326
371
 
327
372
  const meterings = [];
@@ -374,7 +419,9 @@ export async function draft({
374
419
  result = await loop.run(
375
420
  [{ role: 'system', content: system }, { role: 'user', content: userText }],
376
421
  [tool],
377
- { maxTokens: DRAFT_MAX_TOKENS, toolChoice: { name: TOOL } },
422
+ // M4d am4: thinking 'on' forces no tool (provider default 'auto'; a text reply goes to the structure retry); 'off' forces it.
423
+ // M4d am7 item 3: `thinkingMode` is bareagent's switch ('on' | 'off'); we send no raw `thinking` field anywhere.
424
+ { maxTokens: DRAFT_MAX_TOKENS, thinkingMode: draftThinking, ...(draftThinking === 'on' ? {} : { toolChoice: { name: TOOL } }) },
378
425
  );
379
426
  } catch (err) {
380
427
  threw = err;
@@ -383,6 +430,9 @@ export async function draft({
383
430
  book(false);
384
431
  const entry = { round: log.length + 1, kind: nextKind };
385
432
 
433
+ if (result?.thinkingApplied !== undefined) entry.thinkingApplied = result.thinkingApplied; // bareagent's verdict on this round: true | false | null
434
+ if (result?.thinkingStatus !== undefined) entry.thinkingStatus = result.thinkingStatus; // 'applied' | 'unsupported' | 'ignored' | 'unknown' (bare-agent >= 0.52)
435
+
386
436
  if (threw) {
387
437
  entry.outcome = `provider-red: ${threw.message}`;
388
438
  log.push(entry);
@@ -399,6 +449,19 @@ export async function draft({
399
449
  entry.outcome = `structure: ${why}`;
400
450
  log.push(entry);
401
451
  lastReds = [why];
452
+ // M4d am3 A3: a round cut off at the output cap before tries 1 and 2 are spent is a FAILED TRY, advancing the same counter a
453
+ // validator red does, so the try-3 question can open. A cut-off names no line, so then every job line may be asked about.
454
+ if (result?.stopReason === 'max_tokens' && revisions < MAX_REVISIONS) {
455
+ revisions += 1;
456
+ nextKind = 'revision';
457
+ userText = `Your last reply was cut off at the output limit before a complete tool call. Call ${TOOL} now with a complete, valid JSON declaration.`;
458
+ if (validatorReds.length) userText += `\n\nThe last declaration you emitted was still refused by the validator; keep fixing these too:\n${validatorReds.map((r) => `- ${r}`).join('\n')}`;
459
+ if (offerQuestions && revisions === MAX_REVISIONS) {
460
+ failedLines = lineNums;
461
+ userText += `\n\n${QUESTIONS_PROMPT}`;
462
+ }
463
+ continue;
464
+ }
402
465
  if (structureRetries >= MAX_STRUCTURE_RETRIES) { stop = 'structure'; break; }
403
466
  structureRetries += 1;
404
467
  nextKind = 'structure-retry';
@@ -439,7 +502,7 @@ export async function draft({
439
502
  log.push(entry);
440
503
  const m = sumMeterings(meterings);
441
504
  return {
442
- ok: true, declaration, reds: [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop: null, log, ...extras,
505
+ ok: true, declaration, reds: [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop: null, log, thinking: thinkingOf(), inputs: facts.list, ...extras,
443
506
  };
444
507
  }
445
508
  lastReds = [...verdict.reds];
@@ -461,6 +524,6 @@ export async function draft({
461
524
  // Runner convention: `costUsd` is the priced sum (null when ANY round is unpriced, so the CLI prints UNKNOWN,
462
525
  // never a bare number), and `spendComplete:false` marks a call that failed unmetered or a round left unpriced.
463
526
  return {
464
- ok: false, declaration: lastDecl, reds: lastReds, rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop, log, ...extras,
527
+ ok: false, declaration: lastDecl, reds: lastReds, rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop, log, thinking: thinkingOf(), inputs: facts.list, ...extras,
465
528
  };
466
529
  }
package/src/draftspend.js CHANGED
@@ -17,10 +17,11 @@
17
17
  // { kind:'draft-live', provider, model, price, tokens, costUsd (metered floor, null when unpriced), rounds, calls,
18
18
  // spendComplete (false while a call is in flight or any call is unmetered/unpriced), inFlight, at, startedAt, updatedAt }
19
19
  import { renameSync, writeFileSync } from 'node:fs';
20
- import { join } from 'node:path';
20
+ import { basename, dirname, join, resolve } from 'node:path';
21
21
 
22
- import { readFileInside } from './flow.js';
23
- import { readSpendRows } from './provider.js';
22
+ import { readdirInside, readFileInside } from './flow.js';
23
+ import { readSpendRows, rowCeilingUsd, spendRowCost, unmeteredCalls } from './provider.js';
24
+ import { parseSignedText } from './signed-text.js';
24
25
 
25
26
  export const DRAFT_SPEND_FILE = 'draft-spend.json';
26
27
 
@@ -68,3 +69,108 @@ export function readDirSpendRows(dir) {
68
69
  const live = readDraftSpend(dir);
69
70
  return live ? [live] : [];
70
71
  }
72
+
73
+ const PLAN_DIR_RE = /^draft(?:-\d+)?$/;
74
+ /** M4d am21 item 2: the one sentence for a Start over (or revise, or sign) whose chain names an earlier draft that is gone. */
75
+ export const EARLIER_MISSING_SAY = "An earlier draft of this job is missing, so its spend can't be counted.";
76
+
77
+ /** The file a Start over's session folder carries to name the session it started over from (written once by src/panel/author.js). */
78
+ export const STARTED_OVER_FILE = 'started-over-from.json';
79
+ const SESSION_ID_RE = /^d-[0-9a-z]{10}-[0-9a-f]{4}$/;
80
+
81
+ /**
82
+ * M4d amendment 16 item 1: what ALL of a job's drafting spent — the one writer of that total. A panel draft's session folder holds one plan
83
+ * folder per draft (`draft/`, `draft-<n>/` for each revise and the redraft after answers); each is read by `readDirSpendRows` and priced by
84
+ * `spendRowCost`, the one cost rule. A round whose cost is not known counts at its WORST CASE (item 5): its own booked price's ceiling, else
85
+ * `ceilingUsd` (Settings prices x the fixed token limits), never $0; `notPriced` counts those rounds and `complete` is false.
86
+ * @param {string} sessionDir the panel's draft folder
87
+ * @param {{ ceilingUsd?: number, exclude?: string }} [o] `exclude` = a plan folder name to leave out (the one being written now)
88
+ * @returns {{ usd: number, notPriced: number, complete: boolean, missingEarlier: boolean }}
89
+ */
90
+ export function draftingSpent(sessionDir, { ceilingUsd = 0, exclude } = {}, seen = new Set()) {
91
+ seen.add(resolve(sessionDir));
92
+ let usd = 0;
93
+ let notPriced = 0;
94
+ let missingEarlier = false;
95
+ for (const name of readdirInside(sessionDir, '.')) {
96
+ if (!PLAN_DIR_RE.test(name) || name === exclude) continue;
97
+ for (const row of readDirSpendRows(join(sessionDir, name))) {
98
+ if (row.spendComplete === false) {
99
+ const n = unmeteredCalls(row);
100
+ const per = rowCeilingUsd(row) > 0 ? rowCeilingUsd(row) : ceilingUsd;
101
+ usd += (row.costUsd ?? 0) + n * per;
102
+ notPriced += n;
103
+ } else if (row.costUsd === null || row.costUsd === undefined) {
104
+ usd += rowCeilingUsd(row) > 0 ? rowCeilingUsd(row) : ceilingUsd;
105
+ notPriced += 1;
106
+ } else usd += spendRowCost(row).usd;
107
+ }
108
+ }
109
+ // M4d am19 item 3: a Start over opens a new session folder that names the one it started over from (`started-over-from.json`, written once by the panel):
110
+ // what the earlier session spent is still this job's drafting, so the chain is followed (a name that points back at a folder already counted is not).
111
+ const so = readFileInside(sessionDir, STARTED_OVER_FILE);
112
+ if (so.ok) {
113
+ let from = null;
114
+ try { from = JSON.parse(so.text)?.startedOverFrom; } catch { /* unreadable: no chain */ }
115
+ if (typeof from === 'string' && SESSION_ID_RE.test(from) && !seen.has(resolve(dirname(sessionDir), from))) {
116
+ const prev = join(dirname(sessionDir), from);
117
+ // M4d am21 item 2: a link naming a folder that is gone is NOT $0: what it spent cannot be counted (`missingEarlier`, never a clean figure)
118
+ if (!readFileInside(prev, 'card.json').ok) missingEarlier = true;
119
+ else {
120
+ const before = draftingSpent(prev, { ceilingUsd }, seen);
121
+ usd += before.usd;
122
+ notPriced += before.notPriced;
123
+ missingEarlier = before.missingEarlier;
124
+ }
125
+ } else if (typeof from === 'string' && !SESSION_ID_RE.test(from)) missingEarlier = true;
126
+ }
127
+ return { usd, notPriced, complete: notPriced === 0 && !missingEarlier, missingEarlier };
128
+ }
129
+
130
+ /** Money to 4 places, trailing zeros kept to 2 (`0.05`, `0.0016`). @param {number} n */
131
+ export const usdText = (n) => `$${String(Math.round(n * 1e4) / 1e4).replace(/^(\d+)$/, '$1.00').replace(/^(\d+\.\d)$/, '$10')}`;
132
+
133
+ /**
134
+ * M4d amendment 16 items 1, 3, 5: the split of the card's Cap $ at Sign & run. `leftUsd` is what the first run may spend, rounded DOWN to 4 places (never
135
+ * more than is left). `line` is the sentence the page shows.
136
+ * @param {number} capUsd @param {{ usd: number, notPriced: number }} spent
137
+ */
138
+ export function potSplit(capUsd, spent) {
139
+ const leftUsd = Math.max(0, Math.floor((capUsd - spent.usd) * 1e4 + 1e-6) / 1e4);
140
+ const drafting = spent.notPriced > 0
141
+ ? `drafting spent at most ${usdText(spent.usd)} (${spent.notPriced} round${spent.notPriced === 1 ? '' : 's'} not priced)`
142
+ : `drafting spent ${usdText(spent.usd)}`;
143
+ return { capUsd, spentUsd: spent.usd, notPriced: spent.notPriced, leftUsd, line: `Cap ${usdText(capUsd)} · ${drafting} · this run up to ${usdText(leftUsd)}` };
144
+ }
145
+
146
+ /**
147
+ * The drafter's `priorSpend` for the plan folder `dir`: when it sits in a panel session folder (a `card.json` beside it), what the session's earlier plans spent;
148
+ * null for a plain CLI draft (no session, nothing earlier). The folder being written is left out.
149
+ * @param {string} dir @returns {((ceilingUsd: number) => number)|null}
150
+ */
151
+ export function sessionPriorSpend(dir) {
152
+ const sessionDir = dirname(resolve(dir));
153
+ if (!readFileInside(sessionDir, 'card.json').ok) return null;
154
+ return (ceilingUsd) => draftingSpent(sessionDir, { ceilingUsd, exclude: basename(dir) }).usd;
155
+ }
156
+
157
+ /**
158
+ * M4d amendment 19 item 1: what a draft reserves against the monthly limit: what is LEFT of the cap in its prose (cap minus what this job's drafting already
159
+ * spent, `sessionPriorSpend`), not one round. A prose that does not parse falls back to one round: the draft itself refuses it at $0.
160
+ * @param {string} proseText @param {string} outDir the plan folder the draft will write @param {number} ceilingUsd one round at its worst case
161
+ */
162
+ export function draftHoldUsd(proseText, outDir, ceilingUsd) {
163
+ const parsed = parseSignedText(proseText);
164
+ if (!parsed.ok) return ceilingUsd;
165
+ const prior = sessionPriorSpend(outDir);
166
+ return Math.max(0, parsed.arbiter.capUsd - (prior === null ? 0 : prior(ceilingUsd)));
167
+ }
168
+
169
+ /**
170
+ * M4d amendment 19 item 5 / amendment 20: the ONE sentence for a cap that cannot pay for one round. `kind` is "drafting" (the Chat card, the drafter) or "run"
171
+ * (Run a signed flow, Resume); nothing else differs. `modelId` is the model the minimum was computed for, `minUsd` its worst-case round.
172
+ * @param {'drafting'|'run'} kind @param {number} capUsd @param {number} minUsd @param {string} modelId
173
+ */
174
+ export function capTooSmallText(kind, capUsd, minUsd, modelId) {
175
+ return `Cap ${usdText(capUsd)} is below one ${kind} round's worst case for ${modelId}, $${minUsd.toFixed(4)}. Raise Cap $ or pick another model.`;
176
+ }
@@ -0,0 +1,30 @@
1
+ // M4d amendment 6 item 6: the model a job was drafted with is the model it runs with. The pick - a provider (the name of a key)
2
+ // and a model id - is recorded in `model.json`, beside the draft and then beside the signed flow. It is NOT one of the signed files: which model
3
+ // runs, and at what price, is Settings' to say (a line that is no longer ticked is refused by name at run time), so the record only remembers the choice.
4
+ // One writer (`writeModelRecord`), one reader (`readModelRecord`); both go through the safe gateway.
5
+ import { writeFileSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import { readFileInside } from './flow.js';
8
+ import { isKeyName } from './provider.js';
9
+
10
+ export const MODEL_FILE = 'model.json';
11
+
12
+ /**
13
+ * @param {string} dir a draft folder or a flow folder
14
+ * @returns {{ slot: string, model: string }|null} null when there is no usable record (missing, unreadable, or not a name and a model id)
15
+ */
16
+ export function readModelRecord(dir) {
17
+ const r = readFileInside(dir, MODEL_FILE);
18
+ if (!r.ok) return null;
19
+ try {
20
+ const j = JSON.parse(r.text);
21
+ return isKeyName(j?.slot) && typeof j?.model === 'string' && j.model !== '' ? { slot: j.slot, model: j.model } : null;
22
+ } catch { return null; }
23
+ }
24
+
25
+ /**
26
+ * Write the record once (never over an existing one). @param {string} dir @param {{ slot: string, model: string }} pick
27
+ */
28
+ export function writeModelRecord(dir, { slot, model }) {
29
+ writeFileSync(join(dir, MODEL_FILE), `${JSON.stringify({ slot, model }, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
30
+ }
@@ -12,15 +12,20 @@
12
12
 
13
13
  import { readFileSync } from 'node:fs';
14
14
  import { readDocxText, readDocxHeadings } from './docx.js';
15
+ import { isCellsPath } from './closers.js';
16
+ import { parseCsv } from './csv.js';
15
17
 
16
18
  /**
17
19
  * @param {Array<{kind?:string, role:string, path:string}>} sources arbiter.sources
18
- * @returns {{ok:boolean, inputFacts:Record<string,string[]>, info:string[], reds:string[]}}
20
+ * `list` (M4d am10) is one `{role, detail}` per readable input for the Chat card's list (a CSV: its columns; text: its headings); never hashed.
21
+ * @returns {{ok:boolean, inputFacts:Record<string,string[]>, info:string[], list:Array<{role:string, detail:string}>, reds:string[]}}
19
22
  */
20
23
  export function readInputFacts(sources) {
21
24
  /** @type {Record<string,string[]>} */
22
25
  const inputFacts = {};
23
26
  const info = [];
27
+ const list = [];
28
+ const headingsDetail = (n) => `${n} heading${n === 1 ? '' : 's'}`;
24
29
  const reds = [];
25
30
  for (const s of sources ?? []) {
26
31
  if (s.kind !== 'file') continue;
@@ -31,6 +36,7 @@ export function readInputFacts(sources) {
31
36
  if (!h.ok) { reds.push(`input "${s.role}": ${h.red}`); continue; }
32
37
  const words = r.text.trim() === '' ? 0 : r.text.trim().split(/\s+/).length;
33
38
  inputFacts[s.role] = h.headings;
39
+ list.push({ role: s.role, detail: headingsDetail(h.headings.length) });
34
40
  info.push(`- ${s.role}: a .docx file, ${r.paragraphs} paragraphs, ~${words} words, headings: ${h.headings.join(', ') || '(none)'} (read it with "readDocx")`);
35
41
  } else {
36
42
  let raw;
@@ -38,8 +44,11 @@ export function readInputFacts(sources) {
38
44
  if (raw.trim() === '') { reds.push(`input "${s.role}": "${s.path}" is empty`); continue; }
39
45
  const headings = raw.split(/\r?\n/).filter((l) => /^#{1,6}\s+\S/.test(l)).map((l) => l.replace(/^#{1,6}\s*/, '').trim());
40
46
  inputFacts[s.role] = headings;
41
- info.push(`- ${s.role}: a text/markdown file, ~${raw.trim().split(/\s+/).length} words, headings: ${headings.join(', ') || '(none)'} (read it with "read")`);
47
+ list.push({ role: s.role, detail: isCellsPath(s.path) ? `${parseCsv(raw).header.length} columns` : headingsDetail(headings.length) });
48
+ info.push(isCellsPath(s.path)
49
+ ? `- ${s.role}: a CSV file with cells (a step reads it by listing "${s.role}" in its reads; or with "read")`
50
+ : `- ${s.role}: a text/markdown file, ~${raw.trim().split(/\s+/).length} words, headings: ${headings.join(', ') || '(none)'} (read it with "read")`);
42
51
  }
43
52
  }
44
- return { ok: reds.length === 0, inputFacts, info, reds };
53
+ return { ok: reds.length === 0, inputFacts, info, list, reds };
45
54
  }
package/src/keysfile.js CHANGED
@@ -7,6 +7,10 @@
7
7
  // `export ` prefix, `#` full-line comments, one pair of matching quotes around the
8
8
  // value); no dependency.
9
9
  //
10
+ // Every key-looking name (`isKeyName`: …_KEY) with a value is a Settings row (M4d amendment 6): fwdloop knows no key name of its own.
11
+ // A name reaches the env (and so a child) only once its row is set up in Settings (`configured`): a `NODE_OPTIONS` line is not a key
12
+ // name, so it is neither listed nor passed on, even if config.json names it.
13
+ //
10
14
  // Precedence: the SHELL wins. An exported `FOO=…` beats the file; the file only fills
11
15
  // names the shell leaves unset (or empty). The merged env is a NEW object —
12
16
  // `process.env` is never mutated.
@@ -21,13 +25,19 @@ import {
21
25
  openSync, fstatSync, readFileSync, closeSync, writeFileSync, mkdirSync,
22
26
  } from 'node:fs';
23
27
  import { join } from 'node:path';
24
- import { PROVIDER_SLOTS } from './provider.js';
25
- import { configHome, configDoorHome } from './config.js';
28
+ import { configHome, configDoorHome, readConfig } from './config.js';
26
29
 
27
30
  const NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
31
+ const KEY_NAME_RE = /^[A-Z][A-Z0-9_]*_KEY$/;
28
32
 
29
- /** The key names fwdloop knows (one per provider slot). */
30
- export const KEY_NAMES = Object.freeze(Object.values(PROVIDER_SLOTS).map((p) => p.envVar));
33
+ /**
34
+ * THE rule for what may be a key name (hamr's ruling, branch-review): it looks like an API key, `…_KEY` in capitals. Used at every gate:
35
+ * the `names` Settings lists, the env pass-through, and the routes that take a slot name. A `NODE_OPTIONS` line is not a key.
36
+ * @param {unknown} name @returns {name is string}
37
+ */
38
+ export function isKeyName(name) {
39
+ return typeof name === 'string' && KEY_NAME_RE.test(name);
40
+ }
31
41
 
32
42
  const DEFAULT_SHOWN = '~/.config/fwdloop/.env';
33
43
 
@@ -92,7 +102,7 @@ export function parseKeysText(text) {
92
102
  function createKeysFile(home) {
93
103
  mkdirSync(keysHome(home), { recursive: true, mode: 0o700 });
94
104
  const body = '# fwdloop keys — type NAME=value by hand; this file is never shown or written by fwdloop.\n'
95
- + `${KEY_NAMES.map((n) => `# ${n}=`).join('\n')}\n`;
105
+ + '# One line per provider key, e.g. MY_PROVIDER_API_KEY=... ; each key becomes a row in Settings > Providers.\n';
96
106
  try {
97
107
  writeFileSync(keysFilePath(home), body, { mode: 0o600, flag: 'wx' });
98
108
  } catch (/** @type {any} */ e) {
@@ -108,7 +118,8 @@ function createKeysFile(home) {
108
118
  * @property {string} path the keys file's path as shown to people
109
119
  * @property {boolean} exists the file is there (true after a create)
110
120
  * @property {string[]} names the NAMES the file defines with a value (sorted; never values)
111
- * @property {string[]} shellOnly the known key names that only the shell sets (file empty/absent)
121
+ * @property {string[]} shellOnly the configured key names that only the shell sets (file empty/absent)
122
+ * @property {string[]} keyNames the NAMES of the keys that are set up in Settings and hold a value in `env` (the scrub list's names; never values)
112
123
  * @property {string|null} refusal a plain sentence when `ok` is false, else null
113
124
  * @property {Record<string,string|undefined>} env shell env with the file filling the names the
114
125
  * shell does not set; on a refusal just a copy of the shell env (no file value). THE ONLY
@@ -116,18 +127,32 @@ function createKeysFile(home) {
116
127
  */
117
128
 
118
129
  /**
119
- * Load the keys file over an env. A missing file is created (0600) and is not a refusal.
120
- * @param {{ env?: Record<string,string|undefined>, home?: string }} [opts]
130
+ * The key VALUES of the named keys in an env: the scrub list. The names come from a load's `keyNames`.
131
+ * @param {Record<string,string|undefined>} env @param {readonly string[]|undefined} names
132
+ * @returns {string[]}
133
+ */
134
+ export function keyValues(env, names) {
135
+ /** @type {string[]} */
136
+ const out = [];
137
+ for (const n of names ?? []) { const v = env[n]; if (typeof v === 'string' && v !== '') out.push(v); }
138
+ return out;
139
+ }
140
+
141
+ /**
142
+ * Load the keys file over an env. A missing file is created (0600) and is not a refusal. `configured` = the key names that have a row
143
+ * set up in Settings (`config.providers`): only those file values reach `env`.
144
+ * @param {{ env?: Record<string,string|undefined>, home?: string, configured?: string[] }} [opts]
121
145
  * @returns {KeysLoad}
122
146
  */
123
147
  export function loadKeysEnv(opts = {}) {
124
148
  const base = opts.env ?? process.env;
125
149
  const file = keysFilePath(opts.home);
126
150
  const path = shownPath(opts.home);
127
- const knownShell = (parsed) => KEY_NAMES.filter((n) => base[n] && !parsed[n]);
151
+ const configured = (opts.configured ?? []).filter(isKeyName); // defence in depth: a non-key name in config.json never reaches env
152
+ const knownShell = (parsed) => configured.filter((n) => base[n] && !parsed[n]);
128
153
  /** @param {string} refusal @param {boolean} exists @returns {KeysLoad} */
129
154
  const refused = (refusal, exists) => ({
130
- ok: false, path, exists, names: [], shellOnly: [], refusal, env: { ...base },
155
+ ok: false, path, exists, names: [], shellOnly: [], keyNames: [], refusal, env: { ...base },
131
156
  });
132
157
  let fd;
133
158
  let created = false;
@@ -145,13 +170,13 @@ export function loadKeysEnv(opts = {}) {
145
170
  const parsed = parseKeysText(readFileSync(fd, 'utf8'));
146
171
  /** @type {Record<string,string|undefined>} */
147
172
  const env = { ...base };
148
- // C4 (amendment 16): only the known key names reach the env (and so a child). Any other name in the file is listed in `names`
149
- // for Settings but its value stays here — a `NODE_OPTIONS` line must never reach a run, resume or draft child.
150
- for (const name of KEY_NAMES) {
173
+ // C4 (amendment 16), M4d amendment 6: only a name whose row is set up in Settings reaches the env (and so a child). Any other name in the
174
+ // file stays here (a non-key name is not even listed) — a `NODE_OPTIONS` line must never reach a run, resume or draft child.
175
+ for (const name of configured) {
151
176
  if (!env[name] && Object.hasOwn(parsed, name)) env[name] = parsed[name];
152
177
  }
153
178
  return {
154
- ok: true, path, exists: true, names: Object.entries(parsed).filter(([, v]) => v !== '').map(([n]) => n).sort(), shellOnly: knownShell(parsed), refusal: null, env,
179
+ ok: true, path, exists: true, names: Object.entries(parsed).filter(([n, v]) => v !== '' && isKeyName(n)).map(([n]) => n).sort(), shellOnly: knownShell(parsed), keyNames: [...new Set(configured)].filter((n) => env[n]).sort(), refusal: null, env,
155
180
  };
156
181
  } catch (/** @type {any} */ e) {
157
182
  return refused(`Your keys file ${path} could not be read (${e?.code ?? 'error'}).`, created || e?.code !== 'ENOENT');
@@ -160,6 +185,16 @@ export function loadKeysEnv(opts = {}) {
160
185
  }
161
186
  }
162
187
 
188
+ /**
189
+ * The key names that have a row set up in Settings (a `config.providers` entry). A broken config reads as none here: the file is
190
+ * still listed, and whoever reads the config refuses it by name.
191
+ * @param {string|undefined} home
192
+ * @returns {string[]}
193
+ */
194
+ function configuredNames(home) {
195
+ try { return Object.keys(readConfig({ home }).providers ?? {}); } catch { return []; }
196
+ }
197
+
163
198
  /**
164
199
  * The door helper the CLI and the panel call. Loads the file only when the caller is on the
165
200
  * REAL environment, or names a home explicitly (a test), or a test process (`configDoorHome`) with
@@ -175,8 +210,8 @@ export function keysForDoor(deps = {}) {
175
210
  const testNoHome = door.skip && home === undefined;
176
211
  if ((deps.env !== undefined && home === undefined) || testNoHome) {
177
212
  return {
178
- ok: true, skipped: true, path: shownPath(undefined), exists: false, names: [], shellOnly: [], refusal: null, env: { ...(deps.env ?? shell) },
213
+ ok: true, skipped: true, path: shownPath(undefined), exists: false, names: [], shellOnly: [], keyNames: [], refusal: null, env: { ...(deps.env ?? shell) },
179
214
  };
180
215
  }
181
- return { ...loadKeysEnv({ env: deps.env, home }), skipped: false };
216
+ return { ...loadKeysEnv({ env: deps.env, home, configured: configuredNames(home) }), skipped: false };
182
217
  }
package/src/liveness.js CHANGED
@@ -23,14 +23,28 @@ const NAME = 'fwdloop';
23
23
  * @returns {string|null}
24
24
  */
25
25
  export function procStartOf(pid) {
26
- try {
27
- const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
28
- const after = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
29
- const v = after[19]; // field 3 is after[0], so field 22 is after[19]
30
- return v !== undefined && /^\d+$/.test(v) ? v : null;
31
- } catch { return null; }
26
+ try { return startFromStat(readFileSync(`/proc/${pid}/stat`, 'utf8')); } catch { return null; }
32
27
  }
33
28
 
29
+ /** Field 22 of a /proc/<pid>/stat text, or null. @param {string} stat */
30
+ function startFromStat(stat) {
31
+ const after = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
32
+ const v = after[19]; // field 3 is after[0], so field 22 is after[19]
33
+ return v !== undefined && /^\d+$/.test(v) ? v : null;
34
+ }
35
+
36
+ /** Field 3 (state) of a /proc/<pid>/stat text. @param {string} stat */
37
+ const stateFromStat = (stat) => stat.slice(stat.lastIndexOf(')') + 2, stat.lastIndexOf(')') + 3);
38
+
39
+ /** Field 23 (vsize, bytes) of a /proc/<pid>/stat text: 0 for a task that has already released its memory (dying), > 0 for one that is alive (even in its exec window). @param {string} stat */
40
+ const vsizeFromStat = (stat) => Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[20]);
41
+
42
+ /** The two /proc files this module reads, as one seam so a test can hand it a snapshot. */
43
+ const REAL_PROC = {
44
+ cmdline: (/** @type {number} */ pid) => readFileSync(`/proc/${pid}/cmdline`, 'utf8'),
45
+ stat: (/** @type {number} */ pid) => readFileSync(`/proc/${pid}/stat`, 'utf8'),
46
+ };
47
+
34
48
  /**
35
49
  * Is `pid` a live fwdloop process — and, when `procStart` is given, the SAME
36
50
  * process that recorded it?
@@ -39,16 +53,25 @@ export function procStartOf(pid) {
39
53
  * null - cannot tell (no /proc, or not ours to read): caller falls back to the 10-minute rule
40
54
  * @param {number} pid
41
55
  * @param {string|null} [procStart] the starttime recorded by the process itself; absent/null = not compared
56
+ * @param {typeof REAL_PROC} [proc] where /proc is read from (tests pass a snapshot)
42
57
  * @returns {boolean|null}
43
58
  */
44
- export function isFwdloopAlive(pid, procStart) {
59
+ export function isFwdloopAlive(pid, procStart, proc = REAL_PROC) {
45
60
  if (!Number.isInteger(pid) || pid <= 0) return false;
46
61
  try { process.kill(pid, 0); } catch (e) { if (e?.code !== 'EPERM') return false; /* EPERM: exists, not ours */ }
47
62
  let cmdline;
48
- try { cmdline = readFileSync(`/proc/${pid}/cmdline`, 'utf8'); } catch (e) {
63
+ try { cmdline = proc.cmdline(pid); } catch (e) {
49
64
  return e?.code === 'ENOENT' && process.platform === 'linux' && hasProc() ? false : null; // died between the two calls vs no /proc
50
65
  }
51
- if (cmdline === '') return false; // zombie (or kernel thread): not a runner
66
+ if (cmdline === '') {
67
+ // A zombie reads empty, but so does a LIVE child for a few ms after its exec (seen under load: state R, starttime equal, cmdline
68
+ // empty), which used to read as dead and showed a fresh draft as "stopped". Only a state of Z/X is dead; otherwise we cannot tell yet.
69
+ // A task that is exiting also reads empty (and R/D) for an instant, but it has already let go of its memory: vsize 0. That is dead, not "cannot tell".
70
+ let state = null;
71
+ let vsize = 0;
72
+ try { const st = proc.stat(pid); state = stateFromStat(st); vsize = vsizeFromStat(st); } catch { /* gone between the reads */ }
73
+ return state === 'Z' || state === 'X' || state === null || !(vsize > 0) ? false : null;
74
+ }
52
75
  const [argv0, ...rest] = cmdline.split('\0');
53
76
  let isFwdloop;
54
77
  if (basename(argv0) === NAME) isFwdloop = true; // direct exec of a renamed/compiled bin
@@ -60,7 +83,8 @@ export function isFwdloopAlive(pid, procStart) {
60
83
  }
61
84
  if (!isFwdloop) return false;
62
85
  if (typeof procStart === 'string') {
63
- const live = procStartOf(pid);
86
+ let live = null;
87
+ try { live = startFromStat(proc.stat(pid)); } catch { /* unreadable */ }
64
88
  if (live === null) return null; // cannot compare: never a silent true
65
89
  if (live !== procStart) return false; // a different fwdloop process reusing the pid
66
90
  }