spec-ctx 0.4.1 → 0.5.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.
@@ -1,4 +1,4 @@
1
- // REQ-LOOP-002 fail files under .ctx/evidence/<change>/<task>.fail-<n>.json and the attempt window (024/D4, 024/D5).
1
+ // REQ-LOOP-002 REQ-LOOP-017 REQ-LOOP-018 fail files under .ctx/evidence/<change>/<task>.fail-<n>.json and the attempt window (024/D4, 024/D5).
2
2
  import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
4
  import { readQuestions } from "../handoff/questions.js";
@@ -8,6 +8,7 @@ import { runCommand } from "../runcmd.js";
8
8
  import { dumps } from "../util/json.js";
9
9
  import { cmpStr } from "../util/pystr.js";
10
10
  import { isoNow } from "../util/time.js";
11
+ const CURRENT = ".ctx/current.json";
11
12
  /** Every fail file of a task, parsed, in `at` order. A damaged file is skipped. */
12
13
  export function readFails(root, task) {
13
14
  const rel = evidenceRel({ id: task });
@@ -31,19 +32,22 @@ export function readFails(root, task) {
31
32
  return out.sort((a, b) => cmpStr(a.file.at, b.file.at) || cmpStr(a.rel, b.rel));
32
33
  }
33
34
  /**
34
- * The start of the attempt window of a task: `current.json.started_at` when the file names the task, else the
35
- * start of time. A resolved question for the task moves the start to its `resolved_at`, so a resolve resets the count.
35
+ * REQ-LOOP-018 the start of the attempt window of a task: `current.json.started_at` when the file names the task, else
36
+ * null, and no fail file counts (056/D4). A resolved question for the task moves the start to its `resolved_at`, so a
37
+ * resolve resets the count. `fallback` gives the start of time instead of null, for a current.json that could not be written.
36
38
  */
37
- export function windowStart(root, task, questions) {
38
- let start = "";
39
+ export function windowStart(root, task, questions, fallback = false) {
40
+ let start = fallback ? "" : null;
39
41
  try {
40
- const cur = JSON.parse(readFileSync(join(root, ".ctx/current.json"), "utf8"));
42
+ const cur = JSON.parse(readFileSync(join(root, CURRENT), "utf8"));
41
43
  if (cur.task === task && typeof cur.started_at === "string")
42
44
  start = cur.started_at;
43
45
  }
44
46
  catch {
45
47
  // no current task
46
48
  }
49
+ if (start === null)
50
+ return null;
47
51
  for (const q of questions ?? safeQuestions(root)) {
48
52
  if (q.task === task && q.status === "resolved" && typeof q.resolved_at === "string" && cmpStr(q.resolved_at, start) > 0)
49
53
  start = q.resolved_at;
@@ -58,9 +62,11 @@ function safeQuestions(root) {
58
62
  return [];
59
63
  }
60
64
  }
61
- /** The fail files of a task inside its window, in `at` order. */
62
- export function failsInWindow(root, task, questions) {
63
- const start = windowStart(root, task, questions);
65
+ /** REQ-LOOP-018 the fail files of a task inside its window, in `at` order. None without a window. */
66
+ export function failsInWindow(root, task, questions, fallback = false) {
67
+ const start = windowStart(root, task, questions, fallback);
68
+ if (start === null)
69
+ return [];
64
70
  return readFails(root, task).filter((f) => cmpStr(f.file.at, start) >= 0);
65
71
  }
66
72
  /** The open question that names the task, if any. */
@@ -74,9 +80,53 @@ export function openQuestionFor(root, task, questions) {
74
80
  export function isCapQuestion(q, task) {
75
81
  return q.status === "open" && q.task === task && q.stage === "cap";
76
82
  }
83
+ /**
84
+ * REQ-LOOP-018 a failed run with no current.json for the task opens its window first (056/D4). The file has only
85
+ * `started_at` and `task`: no `verify`, so a later Verify edit is not refused, and no `bundle_chars`, so stats keeps
86
+ * cycle time for runs that began with task start. Returns false when the write fails.
87
+ */
88
+ export function openWindow(root, task) {
89
+ try {
90
+ const cur = JSON.parse(readFileSync(join(root, CURRENT), "utf8"));
91
+ if (cur.task === task && typeof cur.started_at === "string")
92
+ return true;
93
+ }
94
+ catch {
95
+ // absent or damaged: write a new one
96
+ }
97
+ try {
98
+ mkdirSync(join(root, ".ctx"), { recursive: true });
99
+ writeFileSync(join(root, CURRENT), dumps({ started_at: isoNow(), task }) + "\n");
100
+ return true;
101
+ }
102
+ catch {
103
+ return false;
104
+ }
105
+ }
106
+ /** REQ-LOOP-017 the line that keeps fail files out of git, in `.ctx/evidence/.gitignore` (056/D1). */
107
+ export const FAIL_IGNORE = "*.fail-*.json";
108
+ /**
109
+ * REQ-LOOP-017 make sure `.ctx/evidence/.gitignore` has the fail file line. Create the file or append the line. Other
110
+ * lines keep their bytes and order. A write error changes nothing (056/D1).
111
+ */
112
+ export function ensureFailIgnore(root) {
113
+ const p = join(root, ".ctx/evidence/.gitignore");
114
+ try {
115
+ const cur = existsSync(p) ? readFileSync(p, "utf8") : "";
116
+ if (cur.split(/\r?\n/).some((l) => l.trim() === FAIL_IGNORE))
117
+ return;
118
+ mkdirSync(dirname(p), { recursive: true });
119
+ writeFileSync(p, (cur === "" || cur.endsWith("\n") ? cur : cur + "\n") + FAIL_IGNORE + "\n");
120
+ }
121
+ catch {
122
+ // a read-only tree keeps its fail files tracked
123
+ }
124
+ }
77
125
  /** Write the next fail file of a task. The attempt counts the window, the file number counts every fail file. */
78
126
  export function writeFail(root, task, verify, tail) {
79
- const attempt = failsInWindow(root, task).length + 1;
127
+ // REQ-LOOP-018 when current.json cannot be written, count as before (056/D4)
128
+ const opened = openWindow(root, task);
129
+ const attempt = failsInWindow(root, task, undefined, !opened).length + 1;
80
130
  const rel = evidenceRel({ id: task });
81
131
  const base = rel.slice(0, -".json".length);
82
132
  let n = 1;
@@ -86,6 +136,7 @@ export function writeFail(root, task, verify, tail) {
86
136
  const file = { at: isoNow(), attempt, stderr_tail: tail, task, verify };
87
137
  mkdirSync(dirname(join(root, target)), { recursive: true });
88
138
  writeFileSync(join(root, target), dumps(file) + "\n");
139
+ ensureFailIgnore(root);
89
140
  return { rel: target, file };
90
141
  }
91
142
  /** REQ-LOOP-002 the question text at the cap. It quotes the failing line (033/D2). Strict mode. */
package/dist/main.js CHANGED
@@ -1,6 +1,9 @@
1
1
  // REQ-CLI-001 REQ-CLI-002 REQ-CLI-003 command dispatch. Each command loads its modules inside its action.
2
+ import { resolve } from "node:path";
2
3
  import { COMMANDS, GROUPS, parseArgs, UsageError } from "./cli/args.js";
3
4
  import { VERSION } from "./version.js";
5
+ import { errInfo, note } from "./journal/note.js";
6
+ import { runCommand } from "./runcmd.js";
4
7
  export async function main(argv, io) {
5
8
  // REQ-LINT-001 the linters keep the argument rules of the Python scripts, so they skip this parser
6
9
  // REQ-CLI-006 `specctx help <cmd>` prints the page of one command
@@ -29,6 +32,7 @@ export async function main(argv, io) {
29
32
  }
30
33
  catch (e) {
31
34
  if (e instanceof UsageError) {
35
+ note(io, { cmd: "?" });
32
36
  io.err(`specctx: ${e.message}\n`);
33
37
  return 2;
34
38
  }
@@ -49,18 +53,26 @@ export async function main(argv, io) {
49
53
  return 0;
50
54
  }
51
55
  if (GROUPS.includes(parsed.command)) {
56
+ note(io, { cmd: "?" });
52
57
  const subs = COMMANDS.filter((c) => c.startsWith(parsed.command + " ")).map((c) => c.split(" ")[1]);
53
58
  io.err(`specctx: ${parsed.command} needs a subcommand: ${subs.join(", ")}\n`);
54
59
  return 2;
55
60
  }
56
61
  if (!COMMANDS.includes(parsed.command)) {
62
+ note(io, { cmd: "?" });
57
63
  const { commandList } = await import("./cli/help.js");
58
64
  io.err(`specctx: unknown command: ${parsed.command}\n${commandList()}`);
59
65
  return 2;
60
66
  }
67
+ note(io, { cmd: parsed.command });
61
68
  try {
62
69
  const { run } = await import("./cli/commands.js");
63
- return await run(parsed, io);
70
+ const code = await run(parsed, io);
71
+ // REQ-JRN-002 init has no OpenSpec root check. Its root is the one it wrote to.
72
+ if (code === 0 && parsed.command === "init") {
73
+ note(io, { root: resolve(io.cwd, parsed.flags.root ?? "."), signal: "init-ok" });
74
+ }
75
+ return code;
64
76
  }
65
77
  catch (e) {
66
78
  const { UsageExit } = await import("./cli/errors.js");
@@ -69,6 +81,9 @@ export async function main(argv, io) {
69
81
  return 2;
70
82
  }
71
83
  io.err(`specctx: internal error: ${e.stack ?? String(e)}\n`);
84
+ // REQ-JRN-006 one Strict line that points to the report command and the issues page
85
+ io.err(`Run ${runCommand(io.journal?.run ?? "specctx", "report")} and file the output at https://github.com/sonqh/spec-ctx/issues.\n`);
86
+ note(io, { err: errInfo(e) });
72
87
  return 3;
73
88
  }
74
89
  }
@@ -39,9 +39,9 @@ export function writeEvidence(root, t, entries, verify, kind, note, cwd) {
39
39
  // REQ-STAT-002 copy the bundle size and the start time that task start wrote for this task
40
40
  try {
41
41
  const cur = JSON.parse(readFileSync(join(root, ".ctx/current.json"), "utf8"));
42
- if (cur.task === t.id) {
43
- if (typeof cur.bundle_chars === "number")
44
- ev.bundle_chars = cur.bundle_chars;
42
+ // REQ-LOOP-018 started_at only with bundle_chars, so a window that a failed run opened gives no cycle time (056/D4)
43
+ if (cur.task === t.id && typeof cur.bundle_chars === "number") {
44
+ ev.bundle_chars = cur.bundle_chars;
45
45
  if (typeof cur.started_at === "string")
46
46
  ev.started_at = cur.started_at;
47
47
  }
@@ -0,0 +1,57 @@
1
+ // REQ-TASK-008 machine paths out of evidence (056/D5). Windows paths are out of scope: Verify runs through sh.
2
+ import { realpathSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ const WORD = /[A-Za-z0-9._-]/;
5
+ function trimSlash(p) {
6
+ return p.length > 1 && p.endsWith("/") ? p.slice(0, -1) : p;
7
+ }
8
+ function realOf(root) {
9
+ try {
10
+ return realpathSync(root);
11
+ }
12
+ catch {
13
+ return null;
14
+ }
15
+ }
16
+ /** The home directory: HOME at call time when set, else the OS answer. Bun caches homedir(), so HOME goes first. */
17
+ function homeNow() {
18
+ return process.env.HOME || homedir();
19
+ }
20
+ /**
21
+ * REQ-TASK-008 replace the project root and its real path with `.`, and the home directory with `~`. The longest path
22
+ * goes first, and the root wins a tie. A match needs a start of text or a non word character before it and a non word
23
+ * character or the end after it. A root or home of `/` or the empty string is skipped. `real` defaults to the real path
24
+ * of `root`, so a test can pin the macOS `/tmp` case.
25
+ */
26
+ export function redactPaths(text, root, home = homeNow(), real = realOf(root)) {
27
+ const pairs = [];
28
+ const add = (from, to) => {
29
+ if (from === null)
30
+ return;
31
+ const p = trimSlash(from);
32
+ if (p === "" || p === "/" || pairs.some(([f]) => f === p))
33
+ return;
34
+ pairs.push([p, to]);
35
+ };
36
+ add(root, ".");
37
+ add(real, ".");
38
+ add(home, "~");
39
+ if (!pairs.length || text === "")
40
+ return text;
41
+ // the longest path first, the root before the home on a tie (a stable sort keeps the push order)
42
+ pairs.sort((a, b) => b[0].length - a[0].length);
43
+ let out = "";
44
+ let i = 0;
45
+ while (i < text.length) {
46
+ const hit = pairs.find(([from]) => text.startsWith(from, i) && (i === 0 || !WORD.test(text[i - 1])) && (i + from.length === text.length || !WORD.test(text[i + from.length])));
47
+ if (hit) {
48
+ out += hit[1];
49
+ i += hit[0].length;
50
+ }
51
+ else {
52
+ out += text[i];
53
+ i++;
54
+ }
55
+ }
56
+ return out;
57
+ }
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // REQ-CLI-001 version string. tests/cli/version.test.ts keeps it equal to package.json.
2
- export const VERSION = "0.4.1";
2
+ export const VERSION = "0.5.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spec-ctx",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "Deterministic context engine and task workflow for OpenSpec projects.",
5
5
  "type": "module",
6
6
  "license": "MIT",