@christang/keel 5.83.0 → 5.85.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.
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+
3
+ // How chat records read to a person or an agent (issue #187, design D8, D20).
4
+ // Stored times carry the writer's UTC offset; every display converts to the
5
+ // viewer's local time and never prints the raw stamp. Edits and retractions
6
+ // are records of their own: a view applies them to the message they target
7
+ // and leaves the original file untouched.
8
+
9
+ function pad(value) {
10
+ return String(value).padStart(2, "0");
11
+ }
12
+
13
+ function parseTime(created) {
14
+ const time = Date.parse(created);
15
+ return Number.isNaN(time) ? null : new Date(time);
16
+ }
17
+
18
+ // `YYYY-MM-DD HH:MM` in the viewer's local time zone.
19
+ function localStamp(created) {
20
+ const date = parseTime(created);
21
+ if (!date) return "????-??-?? ??:??";
22
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} `
23
+ + `${pad(date.getHours())}:${pad(date.getMinutes())}`;
24
+ }
25
+
26
+ function localDay(created) {
27
+ return localStamp(created).slice(0, 10);
28
+ }
29
+
30
+ function localClock(created) {
31
+ return localStamp(created).slice(11);
32
+ }
33
+
34
+ // `3h ago`, for agent notices, where the absolute time costs a reader a
35
+ // conversion it does not need.
36
+ function relativeAge(created, now = Date.now()) {
37
+ const date = parseTime(created);
38
+ if (!date) return "at an unknown time";
39
+ const seconds = Math.max(0, Math.round((now - date.getTime()) / 1000));
40
+ if (seconds < 60) return "just now";
41
+ const minutes = Math.round(seconds / 60);
42
+ if (minutes < 60) return `${minutes}m ago`;
43
+ const hours = Math.round(minutes / 60);
44
+ if (hours < 48) return `${hours}h ago`;
45
+ return `${Math.round(hours / 24)}d ago`;
46
+ }
47
+
48
+ // The records a reader sees: edits and retractions applied to their targets
49
+ // and dropped as lines of their own; a todo knows whether it was closed.
50
+ function displayRecords(records) {
51
+ const byId = new Map();
52
+ const shown = [];
53
+ for (const record of records) {
54
+ if (record.kind === "edit" || record.kind === "retract") {
55
+ const target = byId.get(record.target);
56
+ if (!target || target.from !== record.from) continue;
57
+ if (record.kind === "edit") {
58
+ target.text = record.text;
59
+ target.edited = true;
60
+ } else {
61
+ target.retracted = true;
62
+ }
63
+ continue;
64
+ }
65
+ const copy = { ...record };
66
+ if (copy.kind === "done") {
67
+ const todo = byId.get(copy.target);
68
+ if (todo) todo.done = true;
69
+ }
70
+ byId.set(copy.id, copy);
71
+ shown.push(copy);
72
+ }
73
+ return shown;
74
+ }
75
+
76
+ function markers(record) {
77
+ const parts = [];
78
+ if (record.kind === "todo") {
79
+ parts.push(`[todo → ${record.assignee || "?"}${record.issue ? ` ${record.issue}` : ""}${record.done ? ", done" : ""}]`);
80
+ }
81
+ if (record.reply_to) parts.push(`↳ ${record.reply_to}`);
82
+ if (record.mentions && record.mentions.length) parts.push(record.mentions.map((m) => `@${m}`).join(" "));
83
+ if (record.edited) parts.push("(edited)");
84
+ return parts.length ? ` ${parts.join(" ")}` : "";
85
+ }
86
+
87
+ function describe(record) {
88
+ switch (record.kind) {
89
+ case "join":
90
+ return `${record.from} added ${record.target}`;
91
+ case "leave":
92
+ return `${record.from} removed ${record.target}`;
93
+ case "archive":
94
+ return `${record.from} archived the group`;
95
+ case "done":
96
+ return `${record.from} closed todo ${record.target}`;
97
+ default:
98
+ if (record.retracted) return `${record.from}: (retracted)`;
99
+ return `${record.from}:${markers(record)} ${record.text}`;
100
+ }
101
+ }
102
+
103
+ function formatLine(record, { clock = false } = {}) {
104
+ const when = clock ? localClock(record.created) : localStamp(record.created);
105
+ return `${when} ${describe(record)} [${record.id}]`;
106
+ }
107
+
108
+ // `--since`: a duration back from now (`90s`, `15m`, `2h`, `3d`) or a date or
109
+ // time (`2026-10-01` is local midnight). Returns epoch milliseconds or null.
110
+ function parseSince(value, now = Date.now()) {
111
+ const text = String(value || "").trim();
112
+ const duration = text.match(/^(\d+)([smhd])$/);
113
+ if (duration) {
114
+ const unit = { s: 1e3, m: 60e3, h: 3600e3, d: 86400e3 }[duration[2]];
115
+ return now - Number(duration[1]) * unit;
116
+ }
117
+ const day = text.match(/^(\d{4})-(\d\d)-(\d\d)$/);
118
+ if (day) return new Date(Number(day[1]), Number(day[2]) - 1, Number(day[3])).getTime();
119
+ const time = Date.parse(text);
120
+ return Number.isNaN(time) ? null : time;
121
+ }
122
+
123
+ function since(records, threshold) {
124
+ if (threshold === null || threshold === undefined) return records;
125
+ return records.filter((record) => {
126
+ const time = Date.parse(record.created);
127
+ return Number.isNaN(time) || time >= threshold;
128
+ });
129
+ }
130
+
131
+ // The per-group Markdown transcript a person opens in any editor (D20): one
132
+ // heading per local day, then `HH:MM sender: text` per record.
133
+ function renderTranscript(group, records) {
134
+ const shown = displayRecords(records).slice().sort((a, b) => {
135
+ const left = Date.parse(a.created);
136
+ const right = Date.parse(b.created);
137
+ return (Number.isNaN(left) ? 0 : left) - (Number.isNaN(right) ? 0 : right) || (a.id < b.id ? -1 : 1);
138
+ });
139
+ const lines = [`# ${group}`, "", "Generated by keel chat after every write; edit the group, not this file.", ""];
140
+ let day = null;
141
+ for (const record of shown) {
142
+ const recordDay = localDay(record.created);
143
+ if (recordDay !== day) {
144
+ if (day !== null) lines.push("");
145
+ lines.push(`## ${recordDay}`, "");
146
+ day = recordDay;
147
+ }
148
+ const text = describe(record).replace(/\n/g, " / ");
149
+ lines.push(`${localClock(record.created)} ${text.startsWith(`${record.from}:`) ? text : `${record.from}: ${text}`}`);
150
+ }
151
+ return `${lines.join("\n")}\n`;
152
+ }
153
+
154
+ module.exports = {
155
+ describe,
156
+ parseSince,
157
+ renderTranscript,
158
+ since,
159
+ displayRecords,
160
+ formatLine,
161
+ localClock,
162
+ localDay,
163
+ localStamp,
164
+ relativeAge,
165
+ };
package/src/core/gates.js CHANGED
@@ -401,7 +401,154 @@ function equivalenceEscapeProblems(repo, selection, task, compiled) {
401
401
  return problems;
402
402
  }
403
403
 
404
+ // `--record` derives the record slots a valid capsule implies (issue #179):
405
+ // the Contract anchor, each bare `M<n>`, `.red`/`.green` for every red-green
406
+ // check not tagged `(regression)`, `.detects` where a check declares one, the
407
+ // Review block, and the Blocker and Reauthorizations defaults. All of it
408
+ // followed mechanically from the capsule and was typed by hand. Each slot
409
+ // reads `pending` (or the template's `none`), which every completion gate
410
+ // still refuses as unfilled, so this moves typing, never a verdict. Existing
411
+ // lines are never rewritten, nothing outside the selected task's Evidence is
412
+ // touched, and a task that does not compile apart from its missing slots is
413
+ // left exactly as it was.
414
+ const EVIDENCE_FIELD = /^ {2}- Evidence:\s*$/;
415
+ const TASK_FIELD = /^ {2}- [A-Za-z][A-Za-z /-]+:/;
416
+
417
+ function evidenceSlotKeys(lines) {
418
+ return new Set(
419
+ lines
420
+ .map((line) => line.match(/^ {4}- ([A-Za-z][\w.]*(?: [a-z]+)*):/))
421
+ .filter(Boolean)
422
+ .map((match) => match[1])
423
+ );
424
+ }
425
+
426
+ function withEvidenceSlots(content, task, slots) {
427
+ const eol = content.includes("\r\n") ? "\r\n" : "\n";
428
+ const lines = content.split(/\r?\n/);
429
+ const end = task.endLine !== undefined ? task.endLine : lines.length;
430
+ let header = -1;
431
+ for (let cursor = task.line + 1; cursor < end; cursor += 1) {
432
+ if (EVIDENCE_FIELD.test(lines[cursor])) {
433
+ header = cursor;
434
+ break;
435
+ }
436
+ }
437
+ let blockEnd = end;
438
+ if (header >= 0) {
439
+ for (let cursor = header + 1; cursor < end; cursor += 1) {
440
+ if (TASK_FIELD.test(lines[cursor])) {
441
+ blockEnd = cursor;
442
+ break;
443
+ }
444
+ }
445
+ }
446
+ const scanFrom = header >= 0 ? header + 1 : end;
447
+ const present = evidenceSlotKeys(lines.slice(scanFrom, blockEnd));
448
+ const added = [];
449
+ for (const slot of slots) {
450
+ if (present.has(slot.key)) continue;
451
+ added.push(...slot.lines);
452
+ }
453
+ if (added.length === 0) return { content, added };
454
+ let insertAt = header >= 0 ? blockEnd : end;
455
+ while (insertAt > task.line + 1 && !lines[insertAt - 1].trim()) insertAt -= 1;
456
+ const insertion = header >= 0 ? added : [" - Evidence:", ...added];
457
+ lines.splice(insertAt, 0, ...insertion);
458
+ return { content: lines.join(eol), added: insertion };
459
+ }
460
+
461
+ function basicSlots(task) {
462
+ const verify = field(task, "Verify") || field(task, "Commands");
463
+ const labels = [
464
+ ...verify.matchAll(/^\s*-\s*(M[1-9]\d*)\b/gm),
465
+ ].map((match) => match[1]);
466
+ return [
467
+ { key: "Contract", lines: [" - Contract: pending"] },
468
+ ...[...new Set(labels)].map((label) => ({
469
+ key: label,
470
+ lines: [` - ${label}: pending`],
471
+ })),
472
+ ];
473
+ }
474
+
475
+ // The full slot list in template order: Contract, then each check's bare,
476
+ // `.red`, `.green`, and `.detects` slots together, then Review and the logs.
477
+ function capsuleSlots(compiled) {
478
+ const verification = compiled.capsule.verification;
479
+ const redGreen = RED_GREEN_VERIFICATION_STRATEGIES.has(
480
+ verification.strategy.toLowerCase()
481
+ );
482
+ const slots = [{ key: "Contract", lines: [" - Contract: pending"] }];
483
+ for (const command of verification.commands) {
484
+ if (!command.label) continue;
485
+ const keys = [command.label];
486
+ if (redGreen && !command.regression) {
487
+ keys.push(`${command.label}.red`, `${command.label}.green`);
488
+ }
489
+ if (command.detects) keys.push(`${command.label}.detects`);
490
+ for (const key of keys) slots.push({ key, lines: [` - ${key}: pending`] });
491
+ }
492
+ slots.push(
493
+ {
494
+ key: "Review",
495
+ lines: [
496
+ " - Review:",
497
+ " - Status: pending",
498
+ " - Acceptance check: pending",
499
+ " - Scope check: pending",
500
+ " - Findings: pending",
501
+ ],
502
+ },
503
+ { key: "Blocker", lines: [" - Blocker: none"] },
504
+ { key: "Reauthorizations", lines: [" - Reauthorizations: none"] }
505
+ );
506
+ return slots;
507
+ }
508
+
509
+ function fillRecordSlots(repo, options) {
510
+ const first = loadSelection(repo, options);
511
+ const original = first.content;
512
+ const tasksPath = first.tasksPath;
513
+ // A trial write of the bare slots only, so the task can compile: the
514
+ // capsule is the authority for everything else, and it compiles from disk.
515
+ const trial = withEvidenceSlots(original, first.selected[0], basicSlots(first.selected[0]));
516
+ if (trial.added.length > 0) fs.writeFileSync(tasksPath, trial.content, "utf8");
517
+ const second = loadSelection(repo, options);
518
+ const compiled = compileTaskContract(repo, second.change, second.selected[0]);
519
+ if (trial.added.length > 0) fs.writeFileSync(tasksPath, original, "utf8");
520
+ if (compiled.diagnostics.length > 0) {
521
+ // The capsule has an authoring error of its own; slots would only hide it.
522
+ return { original, tasksPath, added: [] };
523
+ }
524
+ const full = withEvidenceSlots(original, first.selected[0], capsuleSlots(compiled));
525
+ if (full.added.length > 0) fs.writeFileSync(tasksPath, full.content, "utf8");
526
+ return {
527
+ original,
528
+ tasksPath,
529
+ added: full.added.filter((line) => line !== " - Evidence:"),
530
+ };
531
+ }
532
+
404
533
  function taskStart(repo, options) {
534
+ if (!options.record) return taskStartChecked(repo, options);
535
+ const filled = fillRecordSlots(repo, options);
536
+ const result = taskStartChecked(repo, options);
537
+ if (filled.added.length > 0) {
538
+ if (result.status !== "pass") {
539
+ // A refused start writes nothing, derived slots included.
540
+ fs.writeFileSync(filled.tasksPath, filled.original, "utf8");
541
+ } else if (result.record) {
542
+ result.record.filled = filled.added
543
+ .map((line) => line.match(/^\s*- ([^:]+):/))
544
+ .filter((match) => match && !/^(Status|Acceptance check|Scope check|Findings)$/.test(match[1]))
545
+ .map((match) => match[1]);
546
+ }
547
+ }
548
+ return result;
549
+ }
550
+
551
+ function taskStartChecked(repo, options) {
405
552
  const selection = loadSelection(repo, options);
406
553
  const task = selection.selected[0];
407
554
  const compiled = compileTaskContract(repo, selection.change, task);
@@ -455,8 +602,9 @@ function taskStart(repo, options) {
455
602
  problem(
456
603
  "record-refused",
457
604
  "--record needs a \"- Contract:\" Evidence line on the selected "
458
- + "task to anchor, and this task has none, so nothing was "
459
- + 'written. Add "- Contract: pending" to its Evidence.'
605
+ + "task to anchor, and none could be placed, so nothing was "
606
+ + "written. Check that the task's Evidence field is a "
607
+ + "two-space-indented \"- Evidence:\" line."
460
608
  )
461
609
  );
462
610
  }