@andares/pi-toolkits 0.13.0 → 1.0.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 (44) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +123 -25
  3. package/README.zh-CN.md +75 -21
  4. package/package.json +14 -4
  5. package/src/features/ask/index.test.ts +15 -0
  6. package/src/features/ask/index.ts +17 -0
  7. package/src/features/init/audit.test.ts +19 -2
  8. package/src/features/init/audit.ts +117 -15
  9. package/src/features/init/index.test.ts +123 -1
  10. package/src/features/init/index.ts +156 -46
  11. package/src/features/init/parity.test.ts +176 -0
  12. package/src/features/init/parity.ts +229 -0
  13. package/src/features/init/plan.ts +25 -3
  14. package/src/features/init/refresh.test.ts +88 -1
  15. package/src/features/init/refresh.ts +43 -64
  16. package/src/features/init/spec.ts +11 -0
  17. package/src/features/init/templates/memory-readme.md +9 -2
  18. package/src/features/init/test-helpers.ts +1 -0
  19. package/src/features/init/workflow.ts +159 -0
  20. package/src/features/permission/policy.test.ts +10 -0
  21. package/src/features/permission/units.test.ts +157 -0
  22. package/src/features/permission/units.ts +317 -15
  23. package/src/features/plan/index.test.ts +51 -0
  24. package/src/features/plan/index.ts +24 -4
  25. package/src/features/quit-guard/constants.ts +18 -5
  26. package/src/features/quit-guard/index.ts +75 -29
  27. package/src/features/quit-guard/killer.test.ts +77 -0
  28. package/src/features/quit-guard/killer.ts +215 -0
  29. package/src/features/review/index.ts +14 -0
  30. package/src/features/review/review.test.ts +34 -2
  31. package/src/features/uat/index.test.ts +15 -0
  32. package/src/features/uat/index.ts +10 -7
  33. package/src/features/uat/record-tool.ts +3 -2
  34. package/src/features/uat/state.ts +13 -5
  35. package/src/features/whats-new/changelog.ts +104 -0
  36. package/src/features/whats-new/constants.ts +35 -0
  37. package/src/features/whats-new/index.ts +146 -0
  38. package/src/features/whats-new/notice.ts +68 -0
  39. package/src/features/whats-new/paths.ts +29 -0
  40. package/src/features/whats-new/store.ts +114 -0
  41. package/src/features/whats-new/version.ts +43 -0
  42. package/src/features/whats-new/whats-new.test.ts +460 -0
  43. package/src/index.ts +3 -0
  44. package/src/lib/phases.ts +37 -0
@@ -11,9 +11,8 @@
11
11
  * changed in between. The cache is the reason a UI refresh does not spawn git.
12
12
  */
13
13
  import { execFileSync } from "node:child_process";
14
- import { existsSync } from "node:fs";
15
- import { join, resolve } from "node:path";
16
- import { STATE_FILE } from "../init/spec.js";
14
+ import { resolve } from "node:path";
15
+ import { frameworkReadiness } from "../init/parity.js";
17
16
  import { deriveState, ledgerPath, readEvents, type UatState } from "./ledger.js";
18
17
  import { listRecords, type RecordEntry } from "./records.js";
19
18
 
@@ -47,9 +46,18 @@ export function resetProjectRootCache(): void {
47
46
  rootCache.clear();
48
47
  }
49
48
 
50
- /** The UAT flow only exists in a project that installed the framework. */
49
+ /**
50
+ * The ask loop needs a usable framework, not byte-identical files: state,
51
+ * AGENTS.md, the memory contract and the evidence directory. Small edits to any
52
+ * of them are the operator's business and do not block acceptance.
53
+ */
51
54
  export function frameworkInstalled(root: string): boolean {
52
- return existsSync(join(root, STATE_FILE));
55
+ return frameworkReadiness(root).ready;
56
+ }
57
+
58
+ /** Missing pieces, for a refusal message that tells the operator what to fix. */
59
+ export function frameworkMissing(root: string): string[] {
60
+ return frameworkReadiness(root).missing;
53
61
  }
54
62
 
55
63
  export interface UatSnapshot {
@@ -0,0 +1,104 @@
1
+ /**
2
+ * whats-new feature — `CHANGELOG.md` parsing.
3
+ *
4
+ * Contract with the release script (scripts/lib/changelog.mjs):
5
+ *
6
+ * - one `## <version>` section per released version, optionally decorated
7
+ * (`## [0.14.0] — 2026-11-12`); the first `X.Y.Z` in the heading wins;
8
+ * - `## Unreleased` holds the notes for the next release; `pnpm release`
9
+ * renames that heading to the version it is about to publish;
10
+ * - top-level bullets are the notes shown in the notice; nested bullets are
11
+ * detail for humans reading the file and are not repeated in the TUI.
12
+ *
13
+ * Parsing is tolerant on purpose: a malformed section is skipped, never fatal.
14
+ * A missing file degrades to "no notes" with one warning — an extension must
15
+ * not break a session because a documentation file moved.
16
+ */
17
+ import { readFileSync } from "node:fs";
18
+ import { defaultChangelogFile } from "./paths.js";
19
+ import { compareVersions, parseVersion } from "./version.js";
20
+
21
+ export interface ReleaseNote {
22
+ version: string;
23
+ notes: string[];
24
+ }
25
+
26
+ const HEADING_RE = /^##\s+(.+?)\s*$/;
27
+ const VERSION_IN_HEADING_RE = /\[?v?(\d+\.\d+\.\d+)\]?/;
28
+ const BULLET_RE = /^[-*]\s+(.+?)\s*$/;
29
+
30
+ /** Split a changelog into version sections, in document order. */
31
+ export function parseChangelog(markdown: string): ReleaseNote[] {
32
+ const releases: ReleaseNote[] = [];
33
+ let current: ReleaseNote | undefined;
34
+
35
+ for (const line of markdown.split(/\r?\n/)) {
36
+ const heading = HEADING_RE.exec(line);
37
+ if (heading) {
38
+ const match = VERSION_IN_HEADING_RE.exec(heading[1]);
39
+ current = match ? { version: match[1], notes: [] } : undefined;
40
+ if (current) releases.push(current);
41
+ continue;
42
+ }
43
+ if (!current) continue;
44
+ const bullet = BULLET_RE.exec(line);
45
+ if (bullet) current.notes.push(bullet[1]);
46
+ }
47
+
48
+ return releases;
49
+ }
50
+
51
+ /** Newest first. */
52
+ export function sortReleasesDescending(releases: ReleaseNote[]): ReleaseNote[] {
53
+ return [...releases].sort((a, b) => compareVersions(b.version, a.version));
54
+ }
55
+
56
+ /**
57
+ * Notes for a `from → to` upgrade: `from < version <= to`, newest first.
58
+ * Equal and older versions are excluded so a downgrade never replays notes.
59
+ */
60
+ export function releasesForUpgrade(
61
+ releases: ReleaseNote[],
62
+ from: string,
63
+ to: string,
64
+ ): ReleaseNote[] {
65
+ return sortReleasesDescending(releases).filter(
66
+ (release) =>
67
+ compareVersions(release.version, from) > 0 &&
68
+ compareVersions(release.version, to) <= 0,
69
+ );
70
+ }
71
+
72
+ /** Paths already warned about, so a missing file warns once per process. */
73
+ const warned = new Set<string>();
74
+
75
+ /** Read and parse the notes; a missing/invalid file becomes an empty list. */
76
+ export function readChangelog(file: string = defaultChangelogFile()): ReleaseNote[] {
77
+ try {
78
+ return parseChangelog(readFileSync(file, "utf8"));
79
+ } catch (error) {
80
+ if (!warned.has(file)) {
81
+ warned.add(file);
82
+ // pi-lens-ignore: no-console-except-error,console-statement, — deliberate degradation log
83
+ console.warn(
84
+ "[pi-toolkits/whats-new] Failed to read release notes:",
85
+ error instanceof Error ? error.message : String(error),
86
+ );
87
+ }
88
+ return [];
89
+ }
90
+ }
91
+
92
+ /** The version this copy of the package was published as, if readable. */
93
+ export function readPackageVersion(file: string): string | undefined {
94
+ try {
95
+ const parsed: unknown = JSON.parse(readFileSync(file, "utf8"));
96
+ if (!parsed || typeof parsed !== "object") return undefined;
97
+ const version = (parsed as { version?: unknown }).version;
98
+ return typeof version === "string" && parseVersion(version) !== undefined
99
+ ? version
100
+ : undefined;
101
+ } catch {
102
+ return undefined;
103
+ }
104
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * whats-new feature — constants and the reasoning behind the notice shape.
3
+ *
4
+ * The feature answers one question — "what changed in the version I just
5
+ * installed?" — and answers it exactly once per upgrade. Release notes live in
6
+ * the repository's `CHANGELOG.md`, which ships inside the npm package and is
7
+ * promoted from `## Unreleased` by `pnpm release` (see scripts/publish.mjs), so
8
+ * the text is written at release time instead of being reconstructed from
9
+ * commit subjects at runtime.
10
+ *
11
+ * Why a custom session entry instead of `ctx.ui.notify`: a startup notice needs
12
+ * its own text and must survive `ui.invalidate()` — the same reason the
13
+ * permission feature renders its autostart notice as an entry (see
14
+ * src/features/permission/index.ts). An entry also stays out of the model
15
+ * context, so release notes never cost a token.
16
+ */
17
+
18
+ /** State file in pi's agent dir (same convention as the other feature stores). */
19
+ export const WHATS_NEW_FILE = "pi-toolkits-whats-new.json";
20
+
21
+ /** Custom entry type; also the renderer key. */
22
+ export const NOTICE_ENTRY = "whats-new:notice";
23
+
24
+ /** Release notes file shipped at the package root. */
25
+ export const CHANGELOG_FILENAME = "CHANGELOG.md";
26
+
27
+ /**
28
+ * Newest N versions shown in the startup notice. An operator upgrading from a
29
+ * much older release gets the versions that actually matter, not a wall of
30
+ * text; the complete notes stay in `CHANGELOG.md`.
31
+ */
32
+ export const MAX_VERSIONS_IN_NOTICE = 4;
33
+
34
+ /** Notes per version in the startup notice; the rest stay in `CHANGELOG.md`. */
35
+ export const MAX_NOTES_PER_VERSION = 6;
@@ -0,0 +1,146 @@
1
+ /**
2
+ * whats-new feature — release notes on the first start after an upgrade.
3
+ *
4
+ * Behavior:
5
+ * - `session_start(reason="startup")` in the TUI is the only trigger. A
6
+ * `reload` / `resume` / `new` / `fork` is an in-process transition and must
7
+ * not replay notes the operator already saw. print/json/rpc sessions have no
8
+ * transcript to append to, so they leave the notice for the first interactive
9
+ * start instead of silently consuming it.
10
+ * - The store records the highest version already handled. A missing record
11
+ * means a fresh install: the running version is recorded silently, because
12
+ * there is no "previous version" to report from. A version at or below the
13
+ * record (downgrade, reinstall) is not an upgrade and shows nothing.
14
+ * - Notes come from the bundled `CHANGELOG.md`, filtered to
15
+ * `lastSeen < version <= running`. A version with no section reports the
16
+ * version change and says that no notes are bundled.
17
+ * - The notice is a custom session entry — own text, immune to
18
+ * `ui.invalidate()` and out of the model context (same reason as the
19
+ * permission feature's autostart notice; see that module's header).
20
+ * - Deliberately no global slash command: this package is a plugin, and the
21
+ * automatic notice must not claim command namespace from the host.
22
+ */
23
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
24
+ import { Text } from "@earendil-works/pi-tui";
25
+ import {
26
+ readChangelog,
27
+ readPackageVersion,
28
+ releasesForUpgrade,
29
+ } from "./changelog.js";
30
+ import { NOTICE_ENTRY } from "./constants.js";
31
+ import { buildUpgradeNotice, type NoticeData } from "./notice.js";
32
+ import { defaultChangelogFile, defaultPackageFile } from "./paths.js";
33
+ import { WhatsNewStore } from "./store.js";
34
+ import { compareVersions } from "./version.js";
35
+
36
+ export interface WhatsNewOptions {
37
+ /** State file; defaults to `<agent-dir>/pi-toolkits-whats-new.json`. */
38
+ readonly storeFile?: string;
39
+ /** Release notes file; defaults to the packaged `CHANGELOG.md`. */
40
+ readonly changelogFile?: string;
41
+ /** Package manifest to read the running version from. */
42
+ readonly packageFile?: string;
43
+ /** Explicit running version (tests); overrides `packageFile`. */
44
+ readonly version?: string;
45
+ }
46
+
47
+ interface WhatsNewRuntime {
48
+ readonly store: WhatsNewStore;
49
+ readonly changelogFile: string;
50
+ readonly packageFile: string;
51
+ readonly version?: string;
52
+ /** Versions already handled in this process (a store write may fail). */
53
+ readonly announced: Set<string>;
54
+ present(ctx: ExtensionContext, data: NoticeData): void;
55
+ }
56
+
57
+ function runningVersion(runtime: WhatsNewRuntime): string | undefined {
58
+ return runtime.version ?? readPackageVersion(runtime.packageFile);
59
+ }
60
+
61
+ /** Show the notes for a genuine upgrade, then record the running version. */
62
+ function announceUpgrade(runtime: WhatsNewRuntime, ctx: ExtensionContext): void {
63
+ const version = runningVersion(runtime);
64
+ if (version === undefined || runtime.announced.has(version)) return;
65
+
66
+ const { store } = runtime;
67
+ const from = store.get().lastSeenVersion;
68
+ if (from !== undefined && compareVersions(version, from) <= 0) return;
69
+
70
+ // A fresh install has no previous version to report from.
71
+ if (from !== undefined) {
72
+ try {
73
+ const releases = releasesForUpgrade(
74
+ readChangelog(runtime.changelogFile),
75
+ from,
76
+ version,
77
+ );
78
+ runtime.present(ctx, buildUpgradeNotice(from, version, releases));
79
+ } catch (error) {
80
+ // pi-lens-ignore: no-console-except-error,console-statement, — deliberate degradation log
81
+ console.warn(
82
+ "[pi-toolkits/whats-new] Failed to render release notes:",
83
+ error instanceof Error ? error.message : String(error),
84
+ );
85
+ }
86
+ }
87
+
88
+ // Marked even if rendering failed: a broken notice must not repeat on every
89
+ // start (the notes remain in the package's CHANGELOG.md).
90
+ store.markSeen(version);
91
+ runtime.announced.add(version);
92
+ }
93
+
94
+ export function registerWhatsNew(
95
+ pi: ExtensionAPI,
96
+ options: WhatsNewOptions = {},
97
+ ): void {
98
+ const supportsEntryRenderer =
99
+ typeof pi.registerEntryRenderer === "function";
100
+ if (supportsEntryRenderer) {
101
+ pi.registerEntryRenderer<NoticeData>(NOTICE_ENTRY, (entry, _options, theme) => {
102
+ const data = entry.data;
103
+ if (!data || !Array.isArray(data.lines)) return undefined;
104
+ return new Text(
105
+ [
106
+ theme.bold(data.title),
107
+ ...data.lines.map((line) => theme.fg("dim", line)),
108
+ ].join("\n"),
109
+ 1,
110
+ 0,
111
+ );
112
+ });
113
+ }
114
+
115
+ const runtime: WhatsNewRuntime = {
116
+ store: new WhatsNewStore(options.storeFile),
117
+ changelogFile: options.changelogFile ?? defaultChangelogFile(),
118
+ packageFile: options.packageFile ?? defaultPackageFile(),
119
+ version: options.version,
120
+ announced: new Set<string>(),
121
+ /** Entry when the host can render one, one status notice otherwise. */
122
+ present(ctx, data) {
123
+ if (supportsEntryRenderer) {
124
+ pi.appendEntry<NoticeData>(NOTICE_ENTRY, data);
125
+ return;
126
+ }
127
+ ctx.ui.notify([data.title, ...data.lines].join("\n"), "info");
128
+ },
129
+ };
130
+
131
+ let currentSessionId: string | undefined;
132
+
133
+ pi.on("session_start", (event, ctx) => {
134
+ if (event.reason !== "startup") return;
135
+ // No transcript to append to (print/json/rpc): keep the notice for the
136
+ // first interactive start rather than burning it here.
137
+ if (ctx.mode !== "tui") return;
138
+
139
+ // A runtime rebind can emit session_start again for the same session.
140
+ const sessionId = ctx.sessionManager.getSessionId();
141
+ if (sessionId !== undefined && sessionId === currentSessionId) return;
142
+ currentSessionId = sessionId;
143
+
144
+ announceUpgrade(runtime, ctx);
145
+ });
146
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * whats-new feature — startup notice text.
3
+ *
4
+ * Pure string building, capped so an upgrade across many releases cannot push
5
+ * the first prompt off the screen. The full text always stays in the bundled
6
+ * `CHANGELOG.md`.
7
+ */
8
+ import type { ReleaseNote } from "./changelog.js";
9
+ import {
10
+ MAX_NOTES_PER_VERSION,
11
+ MAX_VERSIONS_IN_NOTICE,
12
+ } from "./constants.js";
13
+
14
+ /** Data carried by the `whats-new:notice` session entry. */
15
+ export interface NoticeData {
16
+ title: string;
17
+ lines: string[];
18
+ }
19
+
20
+ export interface SectionOptions {
21
+ maxVersions?: number;
22
+ maxNotesPerVersion?: number;
23
+ }
24
+
25
+ /** `version` heading plus indented bullets, newest first. */
26
+ export function renderReleaseSections(
27
+ releases: ReleaseNote[],
28
+ options: SectionOptions = {},
29
+ ): string[] {
30
+ const maxVersions = options.maxVersions ?? MAX_VERSIONS_IN_NOTICE;
31
+ const maxNotes = options.maxNotesPerVersion ?? MAX_NOTES_PER_VERSION;
32
+ const shown = releases.slice(0, maxVersions);
33
+ const lines: string[] = [];
34
+
35
+ for (const release of shown) {
36
+ lines.push(release.version);
37
+ for (const note of release.notes.slice(0, maxNotes)) {
38
+ lines.push(` - ${note}`);
39
+ }
40
+ const hiddenNotes = release.notes.length - Math.min(release.notes.length, maxNotes);
41
+ if (hiddenNotes > 0) {
42
+ lines.push(` - (+${hiddenNotes} more in CHANGELOG.md)`);
43
+ }
44
+ }
45
+
46
+ const hiddenVersions = releases.length - shown.length;
47
+ if (hiddenVersions > 0) {
48
+ lines.push(
49
+ `(+${hiddenVersions} older version${hiddenVersions === 1 ? "" : "s"} — see CHANGELOG.md)`,
50
+ );
51
+ }
52
+
53
+ return lines;
54
+ }
55
+
56
+ /** Startup notice: what changed between the recorded version and this one. */
57
+ export function buildUpgradeNotice(
58
+ from: string,
59
+ to: string,
60
+ releases: ReleaseNote[],
61
+ ): NoticeData {
62
+ const sections = renderReleaseSections(releases);
63
+ const lines =
64
+ sections.length > 0
65
+ ? sections
66
+ : ["No release notes are bundled for this version."];
67
+ return { title: `pi-toolkits updated ${from} → ${to}`, lines };
68
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * whats-new feature — locates files shipped next to this module.
3
+ *
4
+ * The published package contains `src/` plus `CHANGELOG.md` (package.json
5
+ * `files`), so both are reachable by URL relative to this module. The host
6
+ * loads extensions through jiti, which preserves `import.meta.url` (verified:
7
+ * a probed extension reports `file:///…/src/…`), so the resolution works in a
8
+ * checkout and in an installed package alike.
9
+ *
10
+ * Everything here is best-effort: callers treat a missing file as "no notes"
11
+ * rather than failing the feature.
12
+ */
13
+ import { fileURLToPath } from "node:url";
14
+ import { CHANGELOG_FILENAME } from "./constants.js";
15
+
16
+ /** Absolute path of a file at the package root. */
17
+ export function packageAsset(name: string): string {
18
+ return fileURLToPath(new URL(`../../../${name}`, import.meta.url));
19
+ }
20
+
21
+ /** `package.json` — the runtime source of the version being run. */
22
+ export function defaultPackageFile(): string {
23
+ return packageAsset("package.json");
24
+ }
25
+
26
+ /** `CHANGELOG.md` — the bundled release notes. */
27
+ export function defaultChangelogFile(): string {
28
+ return packageAsset(CHANGELOG_FILENAME);
29
+ }
@@ -0,0 +1,114 @@
1
+ /**
2
+ * whats-new feature — persisted "which version has the operator seen" state.
3
+ *
4
+ * State lives in `<agent-dir>/pi-toolkits-whats-new.json` (agent-dir from
5
+ * getAgentDir(), same convention as the other feature stores):
6
+ *
7
+ * { "lastSeenVersion": "0.13.0" }
8
+ *
9
+ * `lastSeenVersion` is the highest version whose notes were already handled —
10
+ * shown, or recorded silently because this is a fresh install. A missing field
11
+ * means a fresh install: there is no previous version to report from.
12
+ *
13
+ * Robustness: a missing file means defaults, a corrupted file falls back to
14
+ * defaults with one warning, writes are atomic (tmp + rename) and never throw.
15
+ * A failed write only means the notice may appear once more; it must never
16
+ * block a session.
17
+ */
18
+ import {
19
+ existsSync,
20
+ mkdirSync,
21
+ readFileSync,
22
+ renameSync,
23
+ writeFileSync,
24
+ } from "node:fs";
25
+ import { dirname, join } from "node:path";
26
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
27
+ import { WHATS_NEW_FILE } from "./constants.js";
28
+ import { parseVersion } from "./version.js";
29
+
30
+ export interface WhatsNewState {
31
+ /** Highest version already handled; absent on a fresh install. */
32
+ lastSeenVersion?: string;
33
+ }
34
+
35
+ export const DEFAULT_STATE: WhatsNewState = {};
36
+
37
+ /** Coerce an unknown JSON blob into state (defaults for gaps). */
38
+ export function normalizeState(input: unknown): WhatsNewState {
39
+ const state: WhatsNewState = { ...DEFAULT_STATE };
40
+ if (!input || typeof input !== "object") return state;
41
+ const raw = input as Partial<WhatsNewState>;
42
+ if (
43
+ typeof raw.lastSeenVersion === "string" &&
44
+ parseVersion(raw.lastSeenVersion) !== undefined
45
+ ) {
46
+ state.lastSeenVersion = raw.lastSeenVersion;
47
+ }
48
+ return state;
49
+ }
50
+
51
+ export class WhatsNewStore {
52
+ private state: WhatsNewState = { ...DEFAULT_STATE };
53
+ private readonly file: string;
54
+ private loaded = false;
55
+
56
+ constructor(file: string = join(getAgentDir(), WHATS_NEW_FILE)) {
57
+ this.file = file;
58
+ }
59
+
60
+ /** Path of the JSON file. */
61
+ get path(): string {
62
+ return this.file;
63
+ }
64
+
65
+ private ensureLoaded(): void {
66
+ if (this.loaded) return;
67
+ this.loaded = true;
68
+ try {
69
+ if (!existsSync(this.file)) return;
70
+ const parsed: unknown = JSON.parse(readFileSync(this.file, "utf8"));
71
+ this.state = normalizeState(parsed);
72
+ } catch (error) {
73
+ // pi-lens-ignore: no-console-except-error,console-statement, — deliberate degradation log
74
+ console.warn(
75
+ "[pi-toolkits/whats-new] Failed to load state, using defaults:",
76
+ error instanceof Error ? error.message : String(error),
77
+ );
78
+ this.state = { ...DEFAULT_STATE };
79
+ }
80
+ }
81
+
82
+ /** Current state (a copy). */
83
+ get(): WhatsNewState {
84
+ this.ensureLoaded();
85
+ return { ...this.state };
86
+ }
87
+
88
+ /** Remember that `version` was handled. */
89
+ markSeen(version: string): void {
90
+ this.ensureLoaded();
91
+ if (parseVersion(version) === undefined) return;
92
+ this.state.lastSeenVersion = version;
93
+ this.save();
94
+ }
95
+
96
+ /** Atomically persist (tmp + rename). Never throws. */
97
+ private save(): void {
98
+ try {
99
+ const dir = dirname(this.file);
100
+ if (!existsSync(dir)) {
101
+ mkdirSync(dir, { recursive: true });
102
+ }
103
+ const tmp = `${this.file}.tmp`;
104
+ writeFileSync(tmp, `${JSON.stringify(this.state, null, 2)}\n`, "utf8");
105
+ renameSync(tmp, this.file);
106
+ } catch (error) {
107
+ // pi-lens-ignore: no-console-except-error,console-statement, — deliberate degradation log
108
+ console.warn(
109
+ "[pi-toolkits/whats-new] Failed to save state:",
110
+ error instanceof Error ? error.message : String(error),
111
+ );
112
+ }
113
+ }
114
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * whats-new feature — strict `X.Y.Z` versions.
3
+ *
4
+ * Package versions in this repo are always plain `X.Y.Z` (the release script
5
+ * rejects anything else), so prerelease/build metadata is deliberately not
6
+ * parsed. An unparseable version yields `undefined`, and callers treat that as
7
+ * "do not announce" instead of guessing an ordering — a wrong comparison would
8
+ * replay notes the operator already saw.
9
+ */
10
+
11
+ export interface VersionParts {
12
+ major: number;
13
+ minor: number;
14
+ patch: number;
15
+ }
16
+
17
+ const VERSION_RE = /^v?(\d+)\.(\d+)\.(\d+)$/;
18
+
19
+ /** Parse `X.Y.Z` (an optional leading `v` is tolerated). */
20
+ export function parseVersion(value: string): VersionParts | undefined {
21
+ const match = VERSION_RE.exec(value.trim());
22
+ if (!match) return undefined;
23
+ return {
24
+ major: Number(match[1]),
25
+ minor: Number(match[2]),
26
+ patch: Number(match[3]),
27
+ };
28
+ }
29
+
30
+ /**
31
+ * Numeric ordering: negative when `a < b`, positive when `a > b`, 0 when equal
32
+ * or when either side is unparseable (never announce on an unknown ordering).
33
+ */
34
+ export function compareVersions(a: string, b: string): number {
35
+ const left = parseVersion(a);
36
+ const right = parseVersion(b);
37
+ if (!left || !right) return 0;
38
+ return (
39
+ left.major - right.major ||
40
+ left.minor - right.minor ||
41
+ left.patch - right.patch
42
+ );
43
+ }