proper-base 0.2.3 → 0.2.5

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/README.md CHANGED
@@ -137,18 +137,14 @@ pi install npm:proper-base
137
137
  From a local checkout:
138
138
 
139
139
  ```bash
140
- npm install
141
140
  pi install /path/to/proper-pi-extensions/proper-base
142
141
  ```
143
142
 
144
143
  Pi supplies the core `@earendil-works/pi-coding-agent` and
145
- `@earendil-works/pi-tui` peer packages. Local `npm install` prepares development
146
- tooling and runs the install-time settings seed; it is not a runtime build.
147
-
148
- When an existing `settings.json` is readable, the postinstall hook sets
149
- `subagents.agentOverrides.worker.defaultContext` to `fresh` if no worker
150
- override exists. It leaves existing overrides, missing files, and unreadable
151
- settings untouched. Installing with `--ignore-scripts` skips that default.
144
+ `@earendil-works/pi-tui` peer packages. The package has no runtime
145
+ dependencies, no build step, and no install-time npm scripts, and it does
146
+ not modify Pi settings during installation or runtime. `npm install` only
147
+ prepares the development checks below.
152
148
 
153
149
  This package replaces the former local `proper-customs` identity. Keep only one
154
150
  registration. Existing data under the legacy `proper-history` path remains
@@ -171,6 +167,7 @@ compatible.
171
167
  ## Development
172
168
 
173
169
  ```bash
170
+ npm install
174
171
  npm test
175
172
  npm run typecheck
176
173
  npm run test:coverage
package/index.ts CHANGED
@@ -23,6 +23,7 @@ import {
23
23
  installModelAutocompleteSubmit,
24
24
  sortModelAutocompleteDescending,
25
25
  } from "./src/autocomplete-details.ts";
26
+ import { commitGuardReason } from "./src/commit-guard.ts";
26
27
  import {
27
28
  installEditorNavigation,
28
29
  installPromptClear,
@@ -146,7 +147,9 @@ function installKeybindings(keybindings: EditorKeybindings): void {
146
147
  controller.apply();
147
148
  }
148
149
 
149
- type EditorTui = Parameters<EditorFactory>[0];
150
+ type EditorTui = Parameters<EditorFactory>[0] & {
151
+ scrollToBottom?(): void;
152
+ };
150
153
  type PromptEditor = ReturnType<EditorFactory> & {
151
154
  isShowingAutocomplete?(): boolean;
152
155
  };
@@ -306,6 +309,8 @@ export default function (pi: ExtensionAPI) {
306
309
 
307
310
  pi.on("input", (event) => {
308
311
  if (event.source === "interactive") {
312
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Pinned transcript scrolling]]
313
+ if (event.text.trim()) activeTui?.scrollToBottom?.();
309
314
  promptDisplay.captureInput(event.text, pi.getCommands());
310
315
  }
311
316
  if (
@@ -405,6 +410,15 @@ export default function (pi: ExtensionAPI) {
405
410
  transcriptCleanup?.start();
406
411
  });
407
412
 
413
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Commit message guard]]
414
+ pi.on("tool_call", (event) => {
415
+ if (event.toolName !== "bash" && event.toolName !== "quill_execute") return;
416
+ const command = (event.input as { command?: unknown } | undefined)?.command;
417
+ if (typeof command !== "string") return;
418
+ const reason = commitGuardReason(command);
419
+ if (reason) return { block: true, reason };
420
+ });
421
+
408
422
  pi.on("tool_execution_start", () => {
409
423
  if (pendingPrompt) pendingPrompt.processed = true;
410
424
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "proper-base",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
4
4
  "description": "Baseline Pi behavior for session naming, history, prompt editing, fullscreen navigation, and footer styling",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -35,13 +35,11 @@
35
35
  "type": "module",
36
36
  "files": [
37
37
  "index.ts",
38
- "install.mjs",
39
38
  "src",
40
39
  "README.md",
41
40
  "LICENSE"
42
41
  ],
43
42
  "scripts": {
44
- "postinstall": "node install.mjs",
45
43
  "prepack": "npm test && npm run typecheck",
46
44
  "test": "node --test test/*.test.ts",
47
45
  "test:coverage": "node --experimental-test-coverage --test --test-coverage-lines=93 --test-coverage-branches=78 --test-coverage-functions=90 test/*.test.ts",
@@ -0,0 +1,673 @@
1
+ /**
2
+ * Commit-command guard: validates `git commit` invocations before the bash
3
+ * tool executes them. Port of the Claude Code PreToolUse hook
4
+ * `commit_message_validator.py` (command mode; the amend guard is
5
+ * intentionally not ported).
6
+ *
7
+ * The command must be one direct `git … commit …` — no wrappers, env
8
+ * prefixes, compound shell, or dynamic tokens — with literal `-m`/`--message`
9
+ * text only. Message text must keep the subject and non-trailer body lines
10
+ * within 72 characters, a blank second line, and no attribution lines.
11
+ */
12
+
13
+ const MAX_LINE_LENGTH = 72;
14
+
15
+ const TRAILER_RE = /^[A-Za-z0-9][A-Za-z0-9-]*:\s+\S/;
16
+ const CONTINUATION_RE = /^[ \t]/;
17
+ const ASSIGNMENT_RE = /^[A-Za-z_][A-Za-z0-9_]*=/;
18
+ const FORBIDDEN_PATTERNS: readonly (readonly [RegExp, string])[] = [
19
+ [/\bco[-_ ]*authored[-_ ]*by\b/i, "co-authored-by"],
20
+ [/\bco[-_ ]*author\b/i, "co-author"],
21
+ [/\bauthored[-_ ]*by\b.*\bclaude\b/i, "authored-by Claude"],
22
+ [/\bnoreply@anthropic\b/i, "noreply@anthropic"],
23
+ [/\bclaude\b.*<[^>]+@[^>]+>/i, "Claude email"],
24
+ [/^\s*generated with claude(?: code)?\s*$/i, "Claude attribution"],
25
+ ];
26
+
27
+ interface ShellToken {
28
+ text: string;
29
+ dynamic: boolean;
30
+ }
31
+
32
+ const CONTROL_OPERATORS = new Set(["&&", "||", ";", "|", "&", "\n"]);
33
+ const COMMAND_START_KEYWORDS = new Set([
34
+ "(",
35
+ "{",
36
+ "then",
37
+ "do",
38
+ "else",
39
+ "elif",
40
+ "if",
41
+ "while",
42
+ "until",
43
+ "!",
44
+ ]);
45
+ const WRAPPER_COMMANDS = new Set([
46
+ "env",
47
+ "command",
48
+ "sudo",
49
+ "time",
50
+ "builtin",
51
+ "nohup",
52
+ "sh",
53
+ "bash",
54
+ "zsh",
55
+ "fish",
56
+ "timeout",
57
+ "nice",
58
+ "setsid",
59
+ "stdbuf",
60
+ "ionice",
61
+ ]);
62
+ const SHELL_WRAPPER_COMMANDS = new Set(["sh", "bash", "zsh", "fish"]);
63
+
64
+ const GIT_GLOBAL_OPTS_WITH_VALUES = new Set([
65
+ "-C",
66
+ "-c",
67
+ "--git-dir",
68
+ "--work-tree",
69
+ "--namespace",
70
+ "--super-prefix",
71
+ "--config-env",
72
+ ]);
73
+ const GIT_GLOBAL_OPTS_WITH_EQUALS = [
74
+ "--git-dir=",
75
+ "--work-tree=",
76
+ "--namespace=",
77
+ "--super-prefix=",
78
+ "--config-env=",
79
+ ];
80
+
81
+ const UNSUPPORTED_MESSAGE_FLAGS: Record<string, string> = {
82
+ "-F": "Use literal -m/--message text instead of -F/--file.",
83
+ "--file": "Use literal -m/--message text instead of -F/--file.",
84
+ "-c": "Do not reuse commit messages with -c/--reedit-message.",
85
+ "-C": "Do not reuse commit messages with -C/--reuse-message.",
86
+ "--reuse-message": "Do not reuse commit messages with -C/--reuse-message.",
87
+ "--reedit-message": "Do not reuse commit messages with -c/--reedit-message.",
88
+ "-t": "Do not use commit templates with -t/--template.",
89
+ "--template": "Do not use commit templates with -t/--template.",
90
+ "-e": "Do not open the editor with -e/--edit; use literal -m/--message text.",
91
+ "--edit":
92
+ "Do not open the editor with -e/--edit; use literal -m/--message text.",
93
+ "-s": "Do not use -s/--signoff because it mutates the final commit message.",
94
+ "--fixup": "Do not use --fixup because it rewrites the commit message.",
95
+ "--squash": "Do not use --squash because it rewrites the commit message.",
96
+ "--signoff":
97
+ "Do not use --signoff because it mutates the final commit message.",
98
+ "--trailer":
99
+ "Do not use --trailer because it mutates the final commit message.",
100
+ "--cleanup":
101
+ "Do not use --cleanup because it can mutate the final commit message.",
102
+ "--allow-empty-message": "Do not use --allow-empty-message.",
103
+ "--no-verify": "Do not use --no-verify because it bypasses commit hooks.",
104
+ };
105
+
106
+ function basename(token: string): string {
107
+ return token.slice(token.lastIndexOf("/") + 1);
108
+ }
109
+
110
+ function isGitBinary(token: string): boolean {
111
+ return basename(token) === "git";
112
+ }
113
+
114
+ const DYNAMIC_FOLLOWERS =
115
+ "({0123456789@*#?$!-ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_";
116
+
117
+ function startsDynamicValue(command: string, index: number): boolean {
118
+ const char = command[index];
119
+ if (char === "`") return true;
120
+ if (char !== "$" || index + 1 >= command.length) return false;
121
+ return DYNAMIC_FOLLOWERS.includes(command[index + 1] as string);
122
+ }
123
+
124
+ function tokenizeShellCommand(command: string): ShellToken[] {
125
+ const tokens: ShellToken[] = [];
126
+ let chars: string[] = [];
127
+ let tokenStarted = false;
128
+ let dynamic = false;
129
+ let state: "plain" | "single" | "double" = "plain";
130
+ let index = 0;
131
+
132
+ const flush = () => {
133
+ if (tokenStarted) tokens.push({ text: chars.join(""), dynamic });
134
+ chars = [];
135
+ tokenStarted = false;
136
+ dynamic = false;
137
+ };
138
+
139
+ while (index < command.length) {
140
+ const char = command[index] as string;
141
+
142
+ if (state === "plain") {
143
+ if (char === "\n") {
144
+ flush();
145
+ tokens.push({ text: "\n", dynamic: false });
146
+ index += 1;
147
+ continue;
148
+ }
149
+ if (/\s/.test(char)) {
150
+ flush();
151
+ index += 1;
152
+ continue;
153
+ }
154
+ if (";|&(){}!".includes(char)) {
155
+ flush();
156
+ if (
157
+ index + 1 < command.length &&
158
+ command[index + 1] === char &&
159
+ (char === "|" || char === "&")
160
+ ) {
161
+ tokens.push({ text: char + char, dynamic: false });
162
+ index += 2;
163
+ continue;
164
+ }
165
+ tokens.push({ text: char, dynamic: false });
166
+ index += 1;
167
+ continue;
168
+ }
169
+ if (char === "'") {
170
+ tokenStarted = true;
171
+ state = "single";
172
+ index += 1;
173
+ continue;
174
+ }
175
+ if (char === '"') {
176
+ tokenStarted = true;
177
+ state = "double";
178
+ index += 1;
179
+ continue;
180
+ }
181
+ if (char === "\\") {
182
+ tokenStarted = true;
183
+ index += 1;
184
+ if (index >= command.length)
185
+ throw new Error("unterminated escape sequence");
186
+ chars.push(command[index] as string);
187
+ index += 1;
188
+ continue;
189
+ }
190
+
191
+ tokenStarted = true;
192
+ if (startsDynamicValue(command, index)) dynamic = true;
193
+ chars.push(char);
194
+ index += 1;
195
+ continue;
196
+ }
197
+
198
+ if (state === "single") {
199
+ if (char === "'") {
200
+ state = "plain";
201
+ index += 1;
202
+ continue;
203
+ }
204
+ chars.push(char);
205
+ index += 1;
206
+ continue;
207
+ }
208
+
209
+ // state === "double"
210
+ if (char === '"') {
211
+ state = "plain";
212
+ index += 1;
213
+ continue;
214
+ }
215
+ if (char === "\\") {
216
+ index += 1;
217
+ if (index >= command.length)
218
+ throw new Error("unterminated escape sequence");
219
+ const escaped = command[index] as string;
220
+ if ('"\\$`\n'.includes(escaped)) {
221
+ chars.push(escaped);
222
+ } else {
223
+ chars.push("\\", escaped);
224
+ }
225
+ index += 1;
226
+ continue;
227
+ }
228
+ if (startsDynamicValue(command, index)) dynamic = true;
229
+ chars.push(char);
230
+ index += 1;
231
+ }
232
+
233
+ if (state !== "plain") throw new Error("unterminated quote");
234
+
235
+ flush();
236
+ return tokens;
237
+ }
238
+
239
+ function isTrailerLine(line: string): boolean {
240
+ return TRAILER_RE.test(line);
241
+ }
242
+
243
+ function isContinuationLine(line: string): boolean {
244
+ return CONTINUATION_RE.test(line);
245
+ }
246
+
247
+ function finalTrailerBlock(lines: string[]): Set<number> {
248
+ let end = lines.length - 1;
249
+ while (end >= 0 && (lines[end] as string).trim() === "") end -= 1;
250
+
251
+ if (end < 0) return new Set();
252
+
253
+ let start = end;
254
+ while (
255
+ start >= 0 &&
256
+ (isTrailerLine(lines[start] as string) ||
257
+ isContinuationLine(lines[start] as string))
258
+ ) {
259
+ start -= 1;
260
+ }
261
+
262
+ if (start >= 0 && (lines[start] as string).trim() !== "") return new Set();
263
+
264
+ const block = lines.slice(start + 1, end + 1);
265
+ if (!block.length || !block.some((line) => isTrailerLine(line)))
266
+ return new Set();
267
+
268
+ let sawTrailer = false;
269
+ for (const line of block) {
270
+ if (isTrailerLine(line)) {
271
+ sawTrailer = true;
272
+ continue;
273
+ }
274
+ if (isContinuationLine(line) && sawTrailer) continue;
275
+ return new Set();
276
+ }
277
+
278
+ const indexes = new Set<number>();
279
+ for (let i = start + 1; i <= end; i += 1) indexes.add(i);
280
+ return indexes;
281
+ }
282
+
283
+ /** Validate final commit message text against the house rules. */
284
+ export function validateMessageText(text: string): string[] {
285
+ const lines = text.split(/\r\n|\r|\n/);
286
+ if (text === "") lines.length = 0;
287
+ const errors: string[] = [];
288
+ const trailerBlock = finalTrailerBlock(lines);
289
+
290
+ if (!lines.length || (lines[0] as string).trim() === "") {
291
+ return ["line 1: subject line is missing or empty"];
292
+ }
293
+
294
+ if ((lines[0] as string).length > MAX_LINE_LENGTH) {
295
+ errors.push(`line 1: line exceeds ${MAX_LINE_LENGTH} characters`);
296
+ }
297
+
298
+ if (lines.length > 1 && (lines[1] as string).trim() !== "") {
299
+ errors.push("line 2: body must start with a blank line after the subject");
300
+ }
301
+
302
+ lines.forEach((line, index) => {
303
+ const lineNumber = index + 1;
304
+ if (!trailerBlock.has(index) && line.length > MAX_LINE_LENGTH) {
305
+ errors.push(
306
+ `line ${lineNumber}: line exceeds ${MAX_LINE_LENGTH} characters`,
307
+ );
308
+ }
309
+ for (const [pattern, label] of FORBIDDEN_PATTERNS) {
310
+ if (pattern.test(line)) {
311
+ errors.push(
312
+ `line ${lineNumber}: forbidden attribution line (${label})`,
313
+ );
314
+ break;
315
+ }
316
+ }
317
+ });
318
+
319
+ return errors;
320
+ }
321
+
322
+ function commandStartIndexes(tokens: ShellToken[]): number[] {
323
+ const starts = tokens.length ? [0] : [];
324
+ tokens.slice(0, -1).forEach((token, index) => {
325
+ if (
326
+ CONTROL_OPERATORS.has(token.text) ||
327
+ COMMAND_START_KEYWORDS.has(token.text)
328
+ ) {
329
+ starts.push(index + 1);
330
+ }
331
+ });
332
+ return starts;
333
+ }
334
+
335
+ function findCommitArgs(tokens: ShellToken[]): ShellToken[] | null {
336
+ if (!tokens.length || !isGitBinary((tokens[0] as ShellToken).text))
337
+ return null;
338
+
339
+ let idx = 1;
340
+ while (idx < tokens.length) {
341
+ const token = (tokens[idx] as ShellToken).text;
342
+ if (token === "commit") return tokens.slice(idx + 1);
343
+ if (token === "--") return null;
344
+ if (GIT_GLOBAL_OPTS_WITH_VALUES.has(token)) {
345
+ idx += 2;
346
+ continue;
347
+ }
348
+ if (
349
+ GIT_GLOBAL_OPTS_WITH_EQUALS.some((prefix) => token.startsWith(prefix))
350
+ ) {
351
+ idx += 1;
352
+ continue;
353
+ }
354
+ if (token.startsWith("-")) {
355
+ idx += 1;
356
+ continue;
357
+ }
358
+ return null;
359
+ }
360
+
361
+ return null;
362
+ }
363
+
364
+ function startsDirectGitCommit(tokens: ShellToken[], start: number): boolean {
365
+ if (
366
+ start >= tokens.length ||
367
+ !isGitBinary((tokens[start] as ShellToken).text)
368
+ )
369
+ return false;
370
+ return findCommitArgs(tokens.slice(start)) !== null;
371
+ }
372
+
373
+ function startsWrappedGitCommit(tokens: ShellToken[], start: number): boolean {
374
+ if (start >= tokens.length) return false;
375
+
376
+ let index = start;
377
+ const first = tokens[index] as ShellToken;
378
+ if (first.dynamic && first.text.toLowerCase().endsWith("git")) {
379
+ return (
380
+ index + 1 < tokens.length &&
381
+ (tokens[index + 1] as ShellToken).text === "commit"
382
+ );
383
+ }
384
+
385
+ const command = basename(first.text);
386
+ if (WRAPPER_COMMANDS.has(command)) {
387
+ if (SHELL_WRAPPER_COMMANDS.has(command)) {
388
+ return tokens
389
+ .slice(index + 1)
390
+ .some(
391
+ (token) =>
392
+ token.text.includes("git") && token.text.includes("commit"),
393
+ );
394
+ }
395
+
396
+ index += 1;
397
+ while (
398
+ index < tokens.length &&
399
+ ((tokens[index] as ShellToken).text.startsWith("-") ||
400
+ ASSIGNMENT_RE.test((tokens[index] as ShellToken).text))
401
+ ) {
402
+ if (
403
+ (tokens[index] as ShellToken).text.startsWith("-") &&
404
+ index + 1 < tokens.length &&
405
+ !(tokens[index + 1] as ShellToken).text.startsWith("-") &&
406
+ !ASSIGNMENT_RE.test((tokens[index + 1] as ShellToken).text)
407
+ ) {
408
+ index += 2;
409
+ continue;
410
+ }
411
+ index += 1;
412
+ }
413
+ if (
414
+ startsDirectGitCommit(tokens, index) ||
415
+ startsWrappedGitCommit(tokens, index)
416
+ ) {
417
+ return true;
418
+ }
419
+
420
+ let scan = index + 1;
421
+ while (scan < tokens.length) {
422
+ const text = (tokens[scan] as ShellToken).text;
423
+ if (CONTROL_OPERATORS.has(text) || COMMAND_START_KEYWORDS.has(text))
424
+ break;
425
+ if (
426
+ startsDirectGitCommit(tokens, scan) ||
427
+ startsWrappedGitCommit(tokens, scan)
428
+ ) {
429
+ return true;
430
+ }
431
+ scan += 1;
432
+ }
433
+ return false;
434
+ }
435
+
436
+ if (ASSIGNMENT_RE.test(first.text)) {
437
+ while (
438
+ index < tokens.length &&
439
+ ASSIGNMENT_RE.test((tokens[index] as ShellToken).text)
440
+ ) {
441
+ index += 1;
442
+ }
443
+ return startsDirectGitCommit(tokens, index);
444
+ }
445
+
446
+ return false;
447
+ }
448
+
449
+ function unsupportedFlagMessage(flag: string): string | undefined {
450
+ if (flag in UNSUPPORTED_MESSAGE_FLAGS) return UNSUPPORTED_MESSAGE_FLAGS[flag];
451
+ const prefixed: readonly (readonly [string, string])[] = [
452
+ ["--file=", UNSUPPORTED_MESSAGE_FLAGS["--file"] as string],
453
+ [
454
+ "--reuse-message=",
455
+ UNSUPPORTED_MESSAGE_FLAGS["--reuse-message"] as string,
456
+ ],
457
+ [
458
+ "--reedit-message=",
459
+ UNSUPPORTED_MESSAGE_FLAGS["--reedit-message"] as string,
460
+ ],
461
+ ["--template=", UNSUPPORTED_MESSAGE_FLAGS["--template"] as string],
462
+ ["--fixup=", UNSUPPORTED_MESSAGE_FLAGS["--fixup"] as string],
463
+ ["--squash=", UNSUPPORTED_MESSAGE_FLAGS["--squash"] as string],
464
+ ["--trailer=", UNSUPPORTED_MESSAGE_FLAGS["--trailer"] as string],
465
+ ["--cleanup=", UNSUPPORTED_MESSAGE_FLAGS["--cleanup"] as string],
466
+ ];
467
+ for (const [prefix, message] of prefixed) {
468
+ if (flag.startsWith(prefix)) return message;
469
+ }
470
+ return undefined;
471
+ }
472
+
473
+ function parseShortOptions(
474
+ token: ShellToken,
475
+ args: ShellToken[],
476
+ index: number,
477
+ ): { messages: ShellToken[]; index: number; errors: string[] } {
478
+ const messages: ShellToken[] = [];
479
+ const errors: string[] = [];
480
+ const shortFlags = token.text.slice(1);
481
+ let cursor = 0;
482
+
483
+ while (cursor < shortFlags.length) {
484
+ const flag = shortFlags[cursor] as string;
485
+ if (flag === "m") {
486
+ const attachedValue = shortFlags.slice(cursor + 1);
487
+ if (attachedValue) {
488
+ messages.push({ text: attachedValue, dynamic: token.dynamic });
489
+ return { messages, index, errors };
490
+ }
491
+ if (index + 1 >= args.length) {
492
+ errors.push("Commit message is missing after -m.");
493
+ return { messages, index, errors };
494
+ }
495
+ messages.push(args[index + 1] as ShellToken);
496
+ return { messages, index: index + 1, errors };
497
+ }
498
+
499
+ if ("FcCtes".includes(flag)) {
500
+ errors.push(
501
+ unsupportedFlagMessage(`-${flag}`) ?? `Unsupported flag: -${flag}`,
502
+ );
503
+ if (
504
+ cursor === shortFlags.length - 1 &&
505
+ flag !== "e" &&
506
+ index + 1 < args.length
507
+ ) {
508
+ return { messages, index: index + 1, errors };
509
+ }
510
+ return { messages, index, errors };
511
+ }
512
+
513
+ cursor += 1;
514
+ }
515
+
516
+ return { messages, index, errors };
517
+ }
518
+
519
+ /**
520
+ * Extract the literal commit message from a shell command. Returns the
521
+ * joined message when the command is a valid direct commit, `null` with no
522
+ * errors when the command contains no commit, and `null` with errors when
523
+ * the commit invocation itself is not allowed.
524
+ */
525
+ export function extractMessageFromCommand(command: string): {
526
+ message: string | null;
527
+ errors: string[];
528
+ } {
529
+ let tokens: ShellToken[];
530
+ try {
531
+ tokens = tokenizeShellCommand(command);
532
+ } catch (error) {
533
+ return {
534
+ message: null,
535
+ errors: [
536
+ `Unable to parse git commit command: ${error instanceof Error ? error.message : String(error)}`,
537
+ ],
538
+ };
539
+ }
540
+
541
+ const starts = commandStartIndexes(tokens);
542
+ const directStart = starts.find((start) =>
543
+ startsDirectGitCommit(tokens, start),
544
+ );
545
+
546
+ if (directStart === undefined) {
547
+ if (starts.some((start) => startsWrappedGitCommit(tokens, start))) {
548
+ return {
549
+ message: null,
550
+ errors: [
551
+ "Commit command must be a direct `git ... commit ...` invocation. Wrappers, env prefixes, and compound shell commands are not allowed.",
552
+ ],
553
+ };
554
+ }
555
+ return { message: null, errors: [] };
556
+ }
557
+
558
+ if (directStart !== 0 || starts.length > 1) {
559
+ return {
560
+ message: null,
561
+ errors: [
562
+ "Commit command must be a direct `git ... commit ...` invocation. Wrappers, env prefixes, and compound shell commands are not allowed.",
563
+ ],
564
+ };
565
+ }
566
+
567
+ const commitArgs = findCommitArgs(tokens);
568
+ if (commitArgs === null) return { message: null, errors: [] };
569
+
570
+ if (commitArgs.some((token) => token.dynamic)) {
571
+ return {
572
+ message: null,
573
+ errors: [
574
+ "Commit command must not contain shell expansion, command substitution, or variables in commit arguments. Use literal flags and literal message text only.",
575
+ ],
576
+ };
577
+ }
578
+
579
+ const messages: ShellToken[] = [];
580
+ const errors: string[] = [];
581
+ let idx = 0;
582
+
583
+ while (idx < commitArgs.length) {
584
+ const token = commitArgs[idx] as ShellToken;
585
+ const tokenText = token.text;
586
+
587
+ const unsupported = unsupportedFlagMessage(tokenText);
588
+ if (unsupported !== undefined) {
589
+ errors.push(unsupported);
590
+ idx += 1;
591
+ continue;
592
+ }
593
+
594
+ if (tokenText === "--message") {
595
+ if (idx + 1 >= commitArgs.length) {
596
+ errors.push("Commit message is missing after --message.");
597
+ break;
598
+ }
599
+ messages.push(commitArgs[idx + 1] as ShellToken);
600
+ idx += 2;
601
+ continue;
602
+ }
603
+
604
+ if (tokenText.startsWith("--message=")) {
605
+ messages.push({
606
+ text: tokenText.split(/=(.*)/s)[1] as string,
607
+ dynamic: token.dynamic,
608
+ });
609
+ idx += 1;
610
+ continue;
611
+ }
612
+
613
+ if (tokenText.startsWith("--")) {
614
+ idx += 1;
615
+ continue;
616
+ }
617
+
618
+ if (tokenText.startsWith("-") && tokenText !== "-") {
619
+ const parsed = parseShortOptions(token, commitArgs, idx);
620
+ messages.push(...parsed.messages);
621
+ errors.push(...parsed.errors);
622
+ idx = parsed.index + 1;
623
+ continue;
624
+ }
625
+
626
+ idx += 1;
627
+ }
628
+
629
+ if (errors.length) return { message: null, errors };
630
+
631
+ if (!messages.length) {
632
+ return {
633
+ message: null,
634
+ errors: [
635
+ "Commit has no literal -m/--message content. Use -m or --message with full commit text.",
636
+ ],
637
+ };
638
+ }
639
+
640
+ if (messages.some((message) => message.dynamic)) {
641
+ return {
642
+ message: null,
643
+ errors: [
644
+ "Commit messages must be literal text. Shell expansion, command substitution, and variables are not allowed.",
645
+ ],
646
+ };
647
+ }
648
+
649
+ return {
650
+ message: messages.map((message) => message.text).join("\n\n"),
651
+ errors: [],
652
+ };
653
+ }
654
+
655
+ /**
656
+ * Return a block reason for a shell command containing an invalid `git
657
+ * commit`, or `undefined` when the command is fine (valid commit or no
658
+ * commit at all). Commands that never mention `git` and `commit` are
659
+ * skipped without tokenizing, so unrelated commands with heredocs or odd
660
+ * quoting are never blocked.
661
+ */
662
+ export function commitGuardReason(command: string): string | undefined {
663
+ if (!/\bgit\b/.test(command) || !/\bcommit\b/.test(command)) return undefined;
664
+
665
+ const { message, errors } = extractMessageFromCommand(command);
666
+ const allErrors =
667
+ errors.length || message === null ? errors : validateMessageText(message);
668
+ if (!allErrors.length) return undefined;
669
+ return [
670
+ "Commit message validation failed:",
671
+ ...allErrors.map((e) => `- ${e}`),
672
+ ].join("\n");
673
+ }
@@ -75,6 +75,7 @@ export function installFooterColors(
75
75
 
76
76
  let state = { ctx, tui };
77
77
  let timer: ReturnType<typeof setInterval> | undefined;
78
+ const ownsRender = Object.hasOwn(footer, "render");
78
79
  const render = footer.render;
79
80
  const dispose = footer.dispose;
80
81
  const stopAnimation = () => {
@@ -101,7 +102,8 @@ export function installFooterColors(
101
102
  uninstall() {
102
103
  if (footer[INSTALLED] !== controller) return;
103
104
  stopAnimation();
104
- footer.render = render;
105
+ if (ownsRender) footer.render = render;
106
+ else Reflect.deleteProperty(footer, "render");
105
107
  if (dispose) footer.dispose = dispose;
106
108
  else delete footer.dispose;
107
109
  delete footer[INSTALLED];
@@ -112,12 +114,17 @@ export function installFooterColors(
112
114
  if (level === "max" || level === "ultra") startAnimation();
113
115
  else stopAnimation();
114
116
  const theme = state.ctx.ui.theme;
115
- return colorFooter(layoutFooter(render.call(footer, width), width, theme), {
116
- level,
117
- model: state.ctx.model?.id,
118
- now: Date.now(),
119
- theme,
120
- });
117
+ return colorFooter(
118
+ layoutFooter(render.call(footer, width), width, theme, (wide) =>
119
+ render.call(footer, wide),
120
+ ),
121
+ {
122
+ level,
123
+ model: state.ctx.model?.id,
124
+ now: Date.now(),
125
+ theme,
126
+ },
127
+ );
121
128
  };
122
129
  footer.dispose = () => {
123
130
  controller.uninstall();
@@ -131,12 +138,13 @@ function layoutFooter(
131
138
  lines: string[],
132
139
  width: number,
133
140
  theme: FooterTheme,
141
+ reRender?: (width: number) => string[],
134
142
  ): string[] {
135
143
  if (lines.length < 2 || !Number.isFinite(width) || width < 20) return lines;
136
144
 
137
- const statsLine = lines[1];
145
+ let statsLine = lines[1];
138
146
  if (!statsLine) return lines;
139
- const match = stripTerminalSequences(statsLine).match(USAGE_THROUGH_COST);
147
+ let match = stripTerminalSequences(statsLine).match(USAGE_THROUGH_COST);
140
148
  const usage = match?.[1];
141
149
  if (!match || !usage) return lines;
142
150
 
@@ -145,6 +153,22 @@ function layoutFooter(
145
153
  const availablePathWidth = contentWidth - usageWidth - 1;
146
154
  if (availablePathWidth < 8) return lines;
147
155
 
156
+ // Pi right-aligns the model segment against the original width and cuts
157
+ // its tail (thinking level, fast, paused) with no ellipsis when the
158
+ // one-line stats row overflows. This layout frees exactly the usage
159
+ // block's columns, so re-render at that width to recover the cut tags.
160
+ if (reRender) {
161
+ const wide = reRender(width + usageWidth);
162
+ const wideStats = wide[1] ?? "";
163
+ const wideMatch =
164
+ stripTerminalSequences(wideStats).match(USAGE_THROUGH_COST);
165
+ if (wideMatch?.[1] === usage) {
166
+ lines = wide;
167
+ statsLine = wideStats;
168
+ match = wideMatch;
169
+ }
170
+ }
171
+
148
172
  const result = [...lines];
149
173
  const path = truncateToWidth(
150
174
  result[0] ?? "",
@@ -164,6 +188,13 @@ function layoutFooter(
164
188
  true,
165
189
  );
166
190
  result[1] = realignFooterRemainder(remainder, contentWidth, theme);
191
+ for (let index = 2; index < result.length; index++) {
192
+ result[index] = truncateToWidth(
193
+ result[index] ?? "",
194
+ width,
195
+ theme.fg("dim", "..."),
196
+ );
197
+ }
167
198
  return result;
168
199
  }
169
200
 
@@ -43,6 +43,12 @@ type State = {
43
43
  ids: WeakMap<object, string>;
44
44
  nextId: number;
45
45
  globalExpanded: boolean;
46
+ assistantCache: WeakMap<AssistantComponent, AssistantRenderCache>;
47
+ };
48
+ type AssistantRenderCache = {
49
+ message: AssistantMessage;
50
+ width: number;
51
+ lines: Map<string, string[]>;
46
52
  };
47
53
  type DetailKind = "tool" | "error";
48
54
  type Detail = {
@@ -55,6 +61,7 @@ type ToolComponent = Component & {
55
61
  toolName?: string;
56
62
  args?: unknown;
57
63
  result?: { isError?: boolean };
64
+ expanded?: boolean;
58
65
  setExpanded?(expanded: boolean): void;
59
66
  };
60
67
  type MouseTui = TUI & {
@@ -96,8 +103,10 @@ export function installTranscriptCleanup(
96
103
  ids: new WeakMap(),
97
104
  nextId: 0,
98
105
  globalExpanded: ctx.ui.getToolsExpanded(),
106
+ assistantCache: new WeakMap(),
99
107
  };
100
108
  const render = chat.render;
109
+ const invalidate = chat.invalidate;
101
110
  const listener: TuiInputListener = (data) => handleClick(data, state);
102
111
  const unsubscribe = tui.addInputListener(listener);
103
112
  prioritize(tui, listener);
@@ -166,9 +175,16 @@ export function installTranscriptCleanup(
166
175
  if (chat[INSTALLED] !== controller) return;
167
176
  unsubscribe();
168
177
  chat.render = render;
178
+ chat.invalidate = invalidate;
169
179
  delete chat[INSTALLED];
170
180
  },
171
181
  };
182
+ // Theme or terminal changes rebuild component content, so drop memoized
183
+ // assistant lines along with the native caches.
184
+ chat.invalidate = () => {
185
+ state = { ...state, assistantCache: new WeakMap() };
186
+ invalidate.call(chat);
187
+ };
172
188
  chat.render = (width: number) => {
173
189
  const globalExpanded = state.ctx.ui.getToolsExpanded();
174
190
  if (globalExpanded !== state.globalExpanded) {
@@ -278,13 +294,13 @@ function renderGroup(
278
294
  message.content.forEach((part) => {
279
295
  if (part.type === "thinking" && part.thinking?.trim()) {
280
296
  lines.push(
281
- ...renderAssistantContent(assistant, message, [part], width),
297
+ ...renderAssistantContent(assistant, message, [part], width, state),
282
298
  );
283
299
  }
284
300
  if (hasToolCall && part.type === "text" && part.text?.trim()) {
285
301
  lines.push(
286
302
  ...withVerticalSpacing(
287
- renderAssistantContent(assistant, message, [part], width),
303
+ renderAssistantContent(assistant, message, [part], width, state),
288
304
  ),
289
305
  );
290
306
  }
@@ -314,7 +330,7 @@ function renderGroup(
314
330
  );
315
331
  if (direct.length) {
316
332
  lines.push(
317
- ...renderAssistantContent(assistant, message, direct, width),
333
+ ...renderAssistantContent(assistant, message, direct, width, state),
318
334
  );
319
335
  }
320
336
  }
@@ -351,12 +367,26 @@ function renderAssistantContent(
351
367
  message: AssistantMessage,
352
368
  content: AssistantMessage["content"],
353
369
  width: number,
370
+ state: State,
354
371
  ): string[] {
355
372
  if (!assistant.updateContent) return assistant.render(width);
373
+ // The updateContent swap below rebuilds the component's children and
374
+ // discards their internal render caches, so re-running it every frame
375
+ // re-parses the whole transcript's markdown. Memoize per content subset.
376
+ let cache = state.assistantCache.get(assistant);
377
+ if (!cache || cache.message !== message || cache.width !== width) {
378
+ cache = { message, width, lines: new Map() };
379
+ state.assistantCache.set(assistant, cache);
380
+ }
381
+ const key = content.map((part) => message.content.indexOf(part)).join(",");
382
+ const cached = cache.lines.get(key);
383
+ if (cached) return cached;
356
384
  const { errorMessage: _errorMessage, ...rest } = message;
357
385
  assistant.updateContent({ ...rest, content, stopReason: "stop" }, false);
358
386
  try {
359
- return assistant.render(width);
387
+ const lines = assistant.render(width);
388
+ cache.lines.set(key, lines);
389
+ return lines;
360
390
  } finally {
361
391
  assistant.updateContent(message, false);
362
392
  }
@@ -400,7 +430,9 @@ function renderDetail(detail: Detail, width: number, state: State): string[] {
400
430
  `${header}${" ".repeat(Math.max(0, width - visibleWidth(header)))}`,
401
431
  ];
402
432
  const expandable = detail.component as ToolComponent;
403
- expandable.setExpanded?.(expanded);
433
+ // setExpanded rebuilds the tool's result renderer even when the state is
434
+ // unchanged, which re-sanitizes full outputs on every frame. Skip no-ops.
435
+ if (expandable.expanded !== expanded) expandable.setExpanded?.(expanded);
404
436
  if (expanded) {
405
437
  lines.push(...detail.component.render(width));
406
438
  const button = `\x1b[7m ${state.ctx.ui.theme.fg(detailColor(detail.kind), "collapse")} \x1b[27m`;
package/install.mjs DELETED
@@ -1,84 +0,0 @@
1
- /**
2
- * npm `postinstall` hook.
3
- *
4
- * Pi has no package install hook of its own, so a default that another
5
- * extension reads only from `settings.json` is written here: once, when the
6
- * package is installed, never from a running session. Plain JavaScript because
7
- * npm runs this with bare `node`.
8
- *
9
- * Runs for `pi install npm:proper-base`, for git sources, and for `npm
10
- * install` in a local checkout. A local path registered with `pi install
11
- * /path/to/proper-base` is only recorded in settings, so it seeds when that
12
- * checkout's own `npm install` runs.
13
- */
14
-
15
- import { readFileSync, renameSync, writeFileSync } from "node:fs";
16
- import { homedir } from "node:os";
17
- import { join } from "node:path";
18
- import { fileURLToPath } from "node:url";
19
-
20
- /** Pi's user agent directory: `PI_CODING_AGENT_DIR`, else `~/.pi/agent`. */
21
- export function agentDir() {
22
- const configured = process.env.PI_CODING_AGENT_DIR;
23
- if (!configured) return join(homedir(), ".pi", "agent");
24
- return configured.startsWith("~/")
25
- ? join(homedir(), configured.slice(2))
26
- : configured;
27
- }
28
-
29
- function asObject(value) {
30
- return typeof value === "object" && value !== null && !Array.isArray(value)
31
- ? value
32
- : undefined;
33
- }
34
-
35
- /**
36
- * Give pi-subagents' packaged `worker` agent a fresh context by default.
37
- *
38
- * `worker` ships `defaultContext: fork`, which replays the parent transcript
39
- * into every child. When parent and child resolve to the same model, Pi keeps
40
- * the inherited signed thinking blocks and Anthropic rejects the request with
41
- * "`thinking` blocks in the latest assistant message cannot be modified".
42
- *
43
- * Returns true only when the file was rewritten.
44
- */
45
- export function seedWorkerContext(dir) {
46
- const file = join(dir, "settings.json");
47
- let settings;
48
- try {
49
- settings = asObject(JSON.parse(readFileSync(file, "utf-8")));
50
- } catch {
51
- // No settings file yet, or one Pi itself cannot read. Writing here would
52
- // destroy content we failed to parse, so leave it untouched.
53
- return false;
54
- }
55
- if (!settings) return false;
56
-
57
- const subagents = asObject(settings.subagents) ?? {};
58
- const overrides = asObject(subagents.agentOverrides) ?? {};
59
- if ("worker" in overrides) return false;
60
-
61
- settings.subagents = {
62
- ...subagents,
63
- agentOverrides: { ...overrides, worker: { defaultContext: "fresh" } },
64
- };
65
-
66
- // Rename onto the target so a crash mid-write cannot truncate settings.
67
- const staged = `${file}.proper-base`;
68
- writeFileSync(staged, `${JSON.stringify(settings, null, 2)}\n`, "utf-8");
69
- renameSync(staged, file);
70
- return true;
71
- }
72
-
73
- if (process.argv[1] === fileURLToPath(import.meta.url)) {
74
- try {
75
- if (seedWorkerContext(agentDir())) {
76
- console.log(
77
- "proper-base: set subagents.agentOverrides.worker.defaultContext to fresh",
78
- );
79
- }
80
- } catch (error) {
81
- // A failed convenience default must never fail the install.
82
- console.warn(`proper-base: could not seed settings.json: ${error}`);
83
- }
84
- }