pi-todo-ledger 0.14.2 → 0.14.3

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-todo-ledger",
3
- "version": "0.14.2",
3
+ "version": "0.14.3",
4
4
  "description": "A todo list for pi agents with a public bookkeeping contract: snapshot entries, change events, and namespace validators. Fork of @juicesharp/rpiv-todo",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -17,7 +17,7 @@ import { getState, listGeneration, sid } from "../state/store.ts";
17
17
  import { sanitizeTerminalText } from "../tool/sanitize.ts";
18
18
  import { cleanAt, commitOf, commonDirOf, GitReadError, headAt, statusAt } from "./git-branch.ts";
19
19
  import { type BoundBranch, boundBranchOf } from "./head-evidence.ts";
20
- import { anchorParts, checkRun, type CheckRun, matchedParts, MAX_WITNESSED_COMMAND, mentionedParts, parseRun, WITNESS_ENTRY_TYPE, type Witness, type WitnessHead } from "./witness.ts";
20
+ import { anchorParts, type CheckRun, inspectCheckRun, matchSteps, MAX_WITNESSED_COMMAND, mentionedParts, parseRun, WITNESS_ENTRY_TYPE, type Witness, type WitnessHead } from "./witness.ts";
21
21
 
22
22
  const record = (x: unknown): x is Record<string, unknown> => typeof x === "object" && x !== null && !Array.isArray(x);
23
23
 
@@ -61,17 +61,32 @@ function openAnchors(session: string): OpenAnchor[] {
61
61
  });
62
62
  }
63
63
 
64
- /** Every step must match the same anchor; read a matching repository and branch only once. */
65
- function openBindings(anchors: OpenAnchor[], run: CheckRun): BoundBranch[] {
64
+ const commandWord = (words: string[]) => words.find((w) => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(w));
65
+
66
+ /** Read each matching binding once; on a near miss, name the step where the last possible anchor stopped matching. */
67
+ function openBindings(anchors: OpenAnchor[], run: CheckRun): BoundBranch[] | Note | undefined {
66
68
  const bindings = new Map<string, BoundBranch>();
69
+ let missedStep = -1;
70
+ let expected: string[] = [];
67
71
  for (const { binding, parts } of anchors) {
68
- if (matchedParts(run, parts).length) bindings.set(`${binding.repo}\0${binding.ref}`, binding);
72
+ const match = matchSteps(run, parts);
73
+ if ("hits" in match) bindings.set(`${binding.repo}\0${binding.ref}`, binding);
74
+ else if (match.missedStep >= missedStep) {
75
+ if (match.missedStep > missedStep) expected = [];
76
+ missedStep = match.missedStep;
77
+ expected.push(...parts);
78
+ }
69
79
  }
70
- return [...bindings.values()];
80
+ if (bindings.size) return [...bindings.values()];
81
+ const runners = new Set(run.steps.map((step) => commandWord(step.words)));
82
+ const near = [...new Set(expected)].filter((part) => runners.has(commandWord(parseRun(part)!.words)));
83
+ if (!near.length) return undefined;
84
+ const where = missedStep ? " that also matches the preceding steps" : "";
85
+ const examples = near.slice(0, 3).map((p) => JSON.stringify(p)).join(" or ");
86
+ const advice = run.steps.length > 1 ? " Run setup in a separate call." : "";
87
+ return { note: `not witnessed: step ${JSON.stringify(run.steps[missedStep].core)} is not part of any open bound todo's anchor${where}. Declared checks include ${examples}.${advice}` };
71
88
  }
72
89
 
73
- const commandWord = (words: string[]) => words.find((w) => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(w));
74
-
75
90
  /** Common git directories of bound repositories read so far, by `repo` path: a path's repository does not change under it. */
76
91
  const commonDirs = new Map<string, string>();
77
92
 
@@ -97,21 +112,18 @@ async function capture(session: string, cwd: string, toolCallId: string, command
97
112
  if (command.length > MAX_WITNESSED_COMMAND) return undefined;
98
113
  const anchors = openAnchors(session);
99
114
  if (!anchors.length) return undefined;
100
- const run = checkRun(command);
101
- if (!run) {
115
+ const run = inspectCheckRun(command);
116
+ if ("why" in run) {
102
117
  const mentions = mentionedParts(command, anchors.flatMap(({ parts }) => parts));
103
- return mentions.length ? { mentions, note: "not witnessed: run checkout or setup in a separate call, then run the check without a pipe or wrapper." } : undefined;
118
+ return mentions.length ? { mentions, note: `not witnessed: ${run.why}.` } : undefined;
104
119
  }
105
120
  const bindings = openBindings(anchors, run);
106
- if (!bindings.length) {
107
- const runners = new Set(run.steps.map((step) => commandWord(step.words)).filter((word) => word !== undefined));
108
- const near = anchors.flatMap(({ parts }) => parts).find((part) => runners.has(commandWord(parseRun(part)!.words) ?? ""));
109
- return near ? { note: `not witnessed: each && step must match a command of the same anchor. Keep the declared arguments in order (e.g. ${near}); extra steps or different selectors do not match. Run setup in a separate call.` } : undefined;
110
- }
121
+ if (!Array.isArray(bindings)) return bindings;
111
122
  const dir = run.cd === undefined ? cwd : resolve(cwd, run.cd.replace(/^~(?=$|\/)/, homedir()));
112
123
  try {
113
124
  const here = await headAt(dir);
114
- if (!here || (run.pin && run.pin !== here.head)) return undefined;
125
+ if (!here) return undefined;
126
+ if (run.pin && run.pin !== here.head) return { note: `not witnessed: pin ${run.pin} does not equal HEAD ${here.head} of ${dir}` };
115
127
  // The bindings first, read in parallel; `git status`, the costly read, only for a checkout of a bound branch's head.
116
128
  const matched = await Promise.all(
117
129
  bindings.map(async (binding) =>
@@ -104,13 +104,16 @@ const OPS = ["&>>", "&&", "||", ";;", "|&", "&>", ">>", ">&", ">|", "<<", "<&",
104
104
  const opAt = (command: string, i: number) => OPS.find((op) => command.startsWith(op, i));
105
105
  const blank = (c: string) => c === " " || c === "\t" || c === "\r";
106
106
 
107
- /**
108
- * `command` as shell tokens, or `undefined` when it holds what a plain run never needs: an expansion (`$`, a backtick, also inside
109
- * double quotes) or an unclosed quote. Hints alone may use the known prefix up to that point.
110
- */
111
- function lex(command: string, mode: "complete" | "hintPrefix" = "complete"): Token[] | undefined {
107
+ interface Rejection { why: string }
108
+
109
+ /** Hints may skip a simple variable or substitution as an opaque word fragment, never as evidence or a command position. */
110
+ function lex(command: string, hints = false): { tokens: Token[]; why?: string } {
112
111
  const tokens: Token[] = [];
113
- const stop = () => mode === "hintPrefix" ? tokens : undefined;
112
+ const expansion = /\$(?:[A-Za-z_]\w*|\{[A-Za-z_]\w*\}|\([\w@./:+ \t-]+\))/y;
113
+ const expansionEnd = (i: number) => {
114
+ expansion.lastIndex = i;
115
+ return hints && expansion.test(command) ? expansion.lastIndex : 0;
116
+ };
114
117
  let i = 0;
115
118
  while (i < command.length) {
116
119
  if (blank(command[i])) {
@@ -126,31 +129,40 @@ function lex(command: string, mode: "complete" | "hintPrefix" = "complete"): Tok
126
129
  const start = i;
127
130
  while (i < command.length && !blank(command[i]) && !opAt(command, i)) {
128
131
  const c = command[i];
129
- if (c === "$" || c === "`") return stop();
132
+ if (c === "$" || c === "`") {
133
+ const end = expansionEnd(i);
134
+ if (!end) return { tokens, why: "shell expansion is not allowed" };
135
+ i = end;
136
+ continue;
137
+ }
130
138
  if (c === "'") {
131
139
  const close = command.indexOf("'", i + 1);
132
- if (close < 0) return stop();
140
+ if (close < 0) return { tokens, why: "unclosed single quote" };
133
141
  i = close + 1;
134
142
  } else if (c === '"') {
135
143
  let j = i + 1;
136
144
  for (; j < command.length && command[j] !== '"'; j++) {
137
- if (command[j] === "$" || command[j] === "`") return stop();
145
+ if (command[j] === "$" || command[j] === "`") {
146
+ const end = expansionEnd(j);
147
+ if (!end) return { tokens, why: "shell expansion is not allowed" };
148
+ j = end - 1;
149
+ }
138
150
  if (command[j] === "\\") j++;
139
151
  }
140
- if (j >= command.length) return stop();
152
+ if (j >= command.length) return { tokens, why: "unclosed double quote" };
141
153
  i = j + 1;
142
154
  } else i += c === "\\" ? 2 : 1;
143
155
  }
144
156
  tokens.push({ word: command.slice(start, i), start, end: i });
145
157
  }
146
- return tokens;
158
+ return { tokens };
147
159
  }
148
160
 
149
161
  const SEGMENT_BOUNDARIES = new Set(["&&", "||", ";", "&", "|", "|&", "(", "\n"]);
150
162
 
151
163
  /** Unsupported shell forms: hint only for an anchor prefix in command position, never use a partial parse as evidence. */
152
164
  export function mentionedParts(command: string, parts: readonly string[]): string[] {
153
- const tokens = lex(command, "hintPrefix") ?? [];
165
+ const { tokens } = lex(command, true);
154
166
  const starts: number[] = [];
155
167
  let atStart = true, comment = false;
156
168
  for (const [i, token] of tokens.entries()) {
@@ -183,16 +195,16 @@ export interface PlainRun {
183
195
  }
184
196
 
185
197
  /**
186
- * `command` as one plain command, or `undefined` when it is anything else. One leading `cd <dir> &&` and trailing redirections
198
+ * `command` as one plain command, or the syntax that disqualifies it. One leading `cd <dir> &&` and trailing redirections
187
199
  * (`2>&1`, `> log`, `>>log`) are set aside; what remains must be words only: no other operator (`;`, `|`, `&&`, `||`, `&`, `(`, a
188
200
  * newline), no expansion, no comment, no group or negation, so no function, alias or trap can stand in for the command.
189
201
  */
190
- export function parseRun(command: string): PlainRun | undefined {
191
- const tokens = lex(command.trim());
192
- if (!tokens?.length) return undefined;
202
+ function readPlainRun(command: string): PlainRun | Rejection {
203
+ const { tokens, why } = lex(command.trim());
204
+ if (why) return { why };
193
205
  let from = 0;
194
206
  let cd: string | undefined;
195
- if (tokens[0].word === "cd" && tokens[1]?.word && tokens[2]?.op === "&&") {
207
+ if (tokens[0]?.word === "cd" && tokens[1]?.word && tokens[2]?.op === "&&") {
196
208
  cd = unquote(tokens[1].word);
197
209
  from = 3;
198
210
  }
@@ -203,15 +215,29 @@ export function parseRun(command: string): PlainRun | undefined {
203
215
  if (fd.word && /^\d+$/.test(fd.word) && fd.end === tokens[to].start && to - 1 > from) to -= 1;
204
216
  }
205
217
  const words = tokens.slice(from, to);
206
- if (!words.length || words.some((t) => !t.word || t.word.startsWith("#") || t.word === "{" || t.word === "}" || t.word === "!")) return undefined;
218
+ if (!words.length) return { why: "missing check command" };
219
+ for (const { word, op } of words) {
220
+ if (!word) return { why: `shell operator ${JSON.stringify(op)} is not allowed in a plain check` };
221
+ if (word.startsWith("#") || word === "{" || word === "}" || word === "!") return { why: `shell token ${JSON.stringify(word)} is not allowed in a plain check` };
222
+ }
207
223
  const list = words.map((t) => t.word!);
208
224
  return { ...(cd === undefined ? {} : { cd }), words: list, core: list.join(" ") };
209
225
  }
210
226
 
211
- /** `command` as a plain run (parseRun) that asks for no help or version, else `undefined`. */
227
+ export function parseRun(command: string): PlainRun | undefined {
228
+ const run = readPlainRun(command);
229
+ return "why" in run ? undefined : run;
230
+ }
231
+
232
+ function asCheck(run: PlainRun): PlainRun | Rejection {
233
+ const flag = run.words.find((w) => HELP.has(w));
234
+ return flag ? { why: `step ${JSON.stringify(run.core)} requests help or version (${flag}) instead of running the check` } : run;
235
+ }
236
+
237
+ /** A plain command that requests no help or version. */
212
238
  export function plainRun(command: string): PlainRun | undefined {
213
- const run = parseRun(command);
214
- return run && !run.words.some((w) => HELP.has(w)) ? run : undefined;
239
+ const run = readPlainRun(command);
240
+ return "why" in run || "why" in asCheck(run) ? undefined : run;
215
241
  }
216
242
 
217
243
  /**
@@ -235,37 +261,58 @@ export interface CheckRun {
235
261
  steps: PlainRun[];
236
262
  }
237
263
 
238
- export function checkRun(command: string): CheckRun | undefined {
239
- const one = plainRun(command);
240
- if (one) return { cd: one.cd, steps: [one] };
241
- // Deliberately not a shell interpreter. The batch grammar has no quoting, expansion or operator inside a
242
- // step. Its sole substitution is the literal, read-only HEAD assertion used before long package checks.
264
+ export function inspectCheckRun(command: string): CheckRun | Rejection {
265
+ const one = readPlainRun(command);
266
+ if (!("why" in one)) {
267
+ const step = asCheck(one);
268
+ return "why" in step ? step : { cd: one.cd, steps: [step] };
269
+ }
270
+ // No quoting, expansion or shell operators inside these steps. Only the literal HEAD assertion is stripped.
243
271
  const segments = command.replace(/^[ \t]+|[ \t\n]+$/g, "").split(/[ \t]*&&[ \t]*/);
244
- if (segments.length < 2) return undefined;
272
+ const reject = (step: string, why: string) => ({ why: `step ${JSON.stringify(step)}: ${why}` });
273
+ if (segments.length < 2) return reject(segments[0], one.why);
245
274
  const cd = /^cd[ \t]+((?:\/|~\/|\.\.?\/)[\w./+@-]*)$/.exec(segments[0])?.[1];
246
275
  if (cd) segments.shift();
247
- const pin = /^test[ \t]+"\$\(git rev-parse HEAD\)"[ \t]+=[ \t]+([0-9a-f]{40}|[0-9a-f]{64})$/.exec(segments[0] ?? "")?.[1];
276
+ else if (/^cd(?:[ \t]|$)/.test(segments[0])) return reject(segments[0], "batch cd needs one unquoted literal path starting with /, ~/, ./ or ../");
277
+ const pin = /^test[ \t]+"\$\(git rev-parse HEAD\)"[ \t]+=[ \t]+([0-9a-f]{40}|[0-9a-f]{64})$/.exec(segments[0])?.[1];
248
278
  if (pin) segments.shift();
249
- if (!segments.length || (!pin && segments.length < 2)) return undefined;
279
+ else if (/^test(?:[ \t]|$)/.test(segments[0])) return reject(segments[0], 'HEAD pin must be test "$(git rev-parse HEAD)" = <full lowercase commit SHA>');
280
+ if (!segments.length || !segments[0]) return { why: "missing check command after && or HEAD pin" };
281
+ if (!pin && segments.length < 2) return reject(segments[0], one.why);
282
+ const singlePinned = !!pin && segments.length === 1;
250
283
  const steps: PlainRun[] = [];
251
284
  for (const segment of segments) {
252
- if (!/^(?:npm|pnpm)(?:[ \t]+[\w@./:+-]+)+$/.test(segment)) return undefined;
253
- const step = plainRun(segment);
254
- if (!step) return undefined;
285
+ if (/^(?:cd|pushd|popd)(?:[ \t]|$)/.test(segment)) return reject(segment, "only a leading cd may change the checkout directory");
286
+ if (!/^[\w@./:+-]+(?:[ \t]+[\w@./:+-]+)*$/.test(segment)) return reject(segment, "a pinned or batch step must contain only literal words (letters, digits, _, @, ., /, :, + or -)");
287
+ const words = segment.split(/[ \t]+/);
288
+ if (!singlePinned && words[0] !== "npm" && words[0] !== "pnpm") return reject(segment, "every check in a batch must start with npm or pnpm; run setup in a separate call");
289
+ if (!singlePinned && words.length < 2) return reject(segment, "a batch package check needs an argument");
290
+ const step = asCheck({ words, core: words.join(" ") });
291
+ if ("why" in step) return step;
255
292
  steps.push(step);
256
293
  }
257
294
  return { cd, pin, steps };
258
295
  }
259
296
 
297
+ export function checkRun(command: string): CheckRun | undefined {
298
+ const run = inspectCheckRun(command);
299
+ return "why" in run ? undefined : run;
300
+ }
301
+
260
302
  /** All steps must run declared parts of this anchor; unrelated setup is not a check. */
261
- export function matchedParts(run: CheckRun, parts: readonly string[]): number[] {
303
+ export function matchSteps(run: CheckRun, parts: readonly string[]): { hits: number[] } | { missedStep: number } {
262
304
  const hits = new Set<number>();
263
- for (const step of run.steps) {
305
+ for (const [k, step] of run.steps.entries()) {
264
306
  const matches = parts.flatMap((part, i) => matchesPart(step, part) ? [i] : []);
265
- if (!matches.length) return [];
307
+ if (!matches.length) return { missedStep: k };
266
308
  for (const i of matches) hits.add(i);
267
309
  }
268
- return [...hits];
310
+ return { hits: [...hits] };
311
+ }
312
+
313
+ export function matchedParts(run: CheckRun, parts: readonly string[]): number[] {
314
+ const match = matchSteps(run, parts);
315
+ return "hits" in match ? match.hits : [];
269
316
  }
270
317
 
271
318
  /** Whether evidence `command` (normalized) names witnessed `run`: its whole command, or its plain command without the leading cd and redirections. */