@andares/pi-toolkits 0.12.4 → 0.14.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.
- package/CHANGELOG.md +43 -0
- package/README.md +134 -17
- package/README.zh-CN.md +115 -16
- package/package.json +24 -11
- package/src/features/ask/index.ts +6 -0
- package/src/features/init/apply.ts +32 -12
- package/src/features/init/audit-uat.test.ts +103 -0
- package/src/features/init/audit.ts +148 -0
- package/src/features/init/detect.ts +4 -0
- package/src/features/init/index.ts +47 -2
- package/src/features/init/plan.ts +11 -0
- package/src/features/init/refresh.test.ts +208 -0
- package/src/features/init/refresh.ts +255 -0
- package/src/features/init/spec.ts +20 -0
- package/src/features/init/templates/agents-skeleton.md +2 -0
- package/src/features/init/templates/uat-readme.md +53 -0
- package/src/features/init/templates/workflow-block.md +21 -0
- package/src/features/init/templates.test.ts +3 -1
- package/src/features/init/templates.ts +2 -0
- package/src/features/init/types.ts +12 -1
- package/src/features/permission/index.ts +32 -0
- package/src/features/permission/policy.test.ts +10 -0
- package/src/features/permission/units.test.ts +157 -0
- package/src/features/permission/units.ts +317 -15
- package/src/features/plan/assets/index-C1YLIi4I.js +1 -0
- package/src/features/plan/assets/index-DMEpYC3V.css +1 -0
- package/src/features/plan/assets/index.html +14 -0
- package/src/features/plan/assets.test.ts +64 -0
- package/src/features/plan/blocks.test.ts +77 -0
- package/src/features/plan/blocks.ts +153 -0
- package/src/features/plan/diff.test.ts +144 -0
- package/src/features/plan/diff.ts +193 -0
- package/src/features/plan/feedback.test.ts +233 -0
- package/src/features/plan/feedback.ts +182 -0
- package/src/features/plan/index.test.ts +385 -0
- package/src/features/plan/index.ts +433 -0
- package/src/features/plan/prompt.test.ts +91 -0
- package/src/features/plan/prompt.ts +110 -0
- package/src/features/plan/render.test.ts +94 -0
- package/src/features/plan/render.ts +131 -0
- package/src/features/plan/server.test.ts +374 -0
- package/src/features/plan/server.ts +272 -0
- package/src/features/plan/store.test.ts +145 -0
- package/src/features/plan/store.ts +244 -0
- package/src/features/review/index.ts +54 -28
- package/src/features/review/review.test.ts +46 -1
- package/src/features/uat/assets/index-D-W9zj0w.css +1 -0
- package/src/features/uat/assets/index-DCBQCsli.js +1 -0
- package/src/features/uat/assets/index.html +14 -0
- package/src/features/uat/constants.ts +23 -0
- package/src/features/uat/index.test.ts +404 -0
- package/src/features/uat/index.ts +329 -0
- package/src/features/uat/item-tool.ts +280 -0
- package/src/features/uat/ledger.test.ts +249 -0
- package/src/features/uat/ledger.ts +504 -0
- package/src/features/uat/prompt.ts +78 -0
- package/src/features/uat/record-tool.ts +167 -0
- package/src/features/uat/records.test.ts +145 -0
- package/src/features/uat/records.ts +268 -0
- package/src/features/uat/server.ts +181 -0
- package/src/features/uat/state.test.ts +41 -0
- package/src/features/uat/state.ts +67 -0
- package/src/features/whats-new/changelog.ts +104 -0
- package/src/features/whats-new/constants.ts +35 -0
- package/src/features/whats-new/index.ts +146 -0
- package/src/features/whats-new/notice.ts +68 -0
- package/src/features/whats-new/paths.ts +29 -0
- package/src/features/whats-new/store.ts +114 -0
- package/src/features/whats-new/version.ts +43 -0
- package/src/features/whats-new/whats-new.test.ts +460 -0
- package/src/index.ts +13 -1
- package/src/lib/ask-control.ts +25 -0
- package/src/lib/opener.test.ts +72 -0
- package/src/lib/opener.ts +121 -0
- package/src/lib/permission-control.ts +39 -0
- package/src/lib/startup.test.ts +1 -1
- package/src/lib/web-review.ts +341 -0
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* UAT feature — the `record_change` tool.
|
|
3
|
+
*
|
|
4
|
+
* One call does two things that must not drift apart:
|
|
5
|
+
*
|
|
6
|
+
* 1. writes the prose change record with a canonical file name and a first
|
|
7
|
+
* line precise to the minute (the frame the operator asked for);
|
|
8
|
+
* 2. appends a `candidate` event to the acceptance ledger — one sentence of
|
|
9
|
+
* user-visible behaviour, plus a 1-3 line test hint.
|
|
10
|
+
*
|
|
11
|
+
* The prose stays free-form: it is the agent's own reading material. The ledger
|
|
12
|
+
* line is the bridge to UAT, and it is written *at implementation time*, when
|
|
13
|
+
* the diff is still in context and describing "what can the operator now do"
|
|
14
|
+
* costs one sentence. Reconstructing that weeks later, from a diff, is the
|
|
15
|
+
* expensive and lossy path.
|
|
16
|
+
*
|
|
17
|
+
* Registered inactive; the feature activates it only in a project that
|
|
18
|
+
* installed the framework (`.agents/framework/state.toml`).
|
|
19
|
+
*/
|
|
20
|
+
import { Type } from "typebox";
|
|
21
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
22
|
+
import { RECORD_CHANGE_TOOL } from "./constants.js";
|
|
23
|
+
import { appendEvent, ledgerPath, newEventId } from "./ledger.js";
|
|
24
|
+
import { createRecord } from "./records.js";
|
|
25
|
+
import { frameworkInstalled, resolveProjectRoot } from "./state.js";
|
|
26
|
+
|
|
27
|
+
const PARAMS = Type.Object({
|
|
28
|
+
title: Type.String({
|
|
29
|
+
description: "One line: what changed. Becomes the record's header.",
|
|
30
|
+
}),
|
|
31
|
+
body: Type.String({
|
|
32
|
+
description:
|
|
33
|
+
"The prose record: what was done, why, and the evidence (tests run, commands, files). Free-form Markdown; do not repeat the title as a heading.",
|
|
34
|
+
}),
|
|
35
|
+
behavior: Type.String({
|
|
36
|
+
description:
|
|
37
|
+
"One sentence describing the change as the operator experiences it: who does what and what they now see. No file names, function names or implementation detail.",
|
|
38
|
+
}),
|
|
39
|
+
hint: Type.Optional(
|
|
40
|
+
Type.String({
|
|
41
|
+
description:
|
|
42
|
+
'How to verify it by hand, 1-3 lines. Write "none: <reason>" when the change has no user-visible effect (docs, refactor, dependency bump).',
|
|
43
|
+
}),
|
|
44
|
+
),
|
|
45
|
+
area: Type.Optional(
|
|
46
|
+
Type.String({ description: 'Short area label used for clustering, e.g. "ask-plan", "auth".' }),
|
|
47
|
+
),
|
|
48
|
+
files: Type.Optional(
|
|
49
|
+
Type.Array(Type.String({ description: "File touched by this change." }), {
|
|
50
|
+
description: "Main files touched. Used to spot records that overlap.",
|
|
51
|
+
}),
|
|
52
|
+
),
|
|
53
|
+
spec: Type.Optional(
|
|
54
|
+
Type.String({ description: "Spec this change implements, e.g. specs/ask-uat.md." }),
|
|
55
|
+
),
|
|
56
|
+
slug: Type.Optional(
|
|
57
|
+
Type.String({ description: "ASCII slug for the file name. Defaults to the title." }),
|
|
58
|
+
),
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
const DESCRIPTION = `Write the change record for the work just done, and register it for acceptance.
|
|
62
|
+
|
|
63
|
+
Creates .agents/implementations/YYYY-MM-DD_HHMM_<slug>.md (first line precise to the minute)
|
|
64
|
+
and appends one candidate entry to the acceptance ledger (.agents/uat/ledger.jsonl).
|
|
65
|
+
|
|
66
|
+
Call it once per completed change round, after the code is written and tested — not per file,
|
|
67
|
+
not per commit. The prose body is for later readers; the \`behavior\` sentence is what the
|
|
68
|
+
operator will see in the acceptance page.`;
|
|
69
|
+
|
|
70
|
+
const GUIDELINES = [
|
|
71
|
+
"After finishing a change round in a project that has an agent framework, call `record_change` before reporting the work as done.",
|
|
72
|
+
'Write `behavior` as one user-facing sentence — "the operator does X and now sees Y" — never as a code description; UAT clusters these sentences into acceptance items.',
|
|
73
|
+
'When the change has no user-visible effect, say so: `hint: "none: <reason>"`. That is a recorded decision, not a missing field.',
|
|
74
|
+
"Do not call `record_change` for exploratory work that was reverted; write it for what actually shipped.",
|
|
75
|
+
];
|
|
76
|
+
|
|
77
|
+
function errorResult(text: string) {
|
|
78
|
+
return { content: [{ type: "text" as const, text }], details: {}, isError: true };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface RecordToolOptions {
|
|
82
|
+
now?: () => Date;
|
|
83
|
+
/** Resolve the project root (main worktree). Injectable for tests. */
|
|
84
|
+
root?: (cwd: string) => string;
|
|
85
|
+
/**
|
|
86
|
+
* Phase guard, not just a registration guard: read-only consult and planning
|
|
87
|
+
* must not acquire a project-writing tool merely because the framework exists.
|
|
88
|
+
*/
|
|
89
|
+
canRecord?: () => boolean;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function registerRecordTool(pi: ExtensionAPI, options: RecordToolOptions = {}): void {
|
|
93
|
+
const now = options.now ?? (() => new Date());
|
|
94
|
+
const rootOf = options.root ?? resolveProjectRoot;
|
|
95
|
+
|
|
96
|
+
pi.registerTool<typeof PARAMS, { id?: string; path?: string }>({
|
|
97
|
+
name: RECORD_CHANGE_TOOL,
|
|
98
|
+
label: "Record change",
|
|
99
|
+
description: DESCRIPTION,
|
|
100
|
+
promptSnippet: "Write the change record and register it for acceptance (framework projects only)",
|
|
101
|
+
promptGuidelines: GUIDELINES,
|
|
102
|
+
parameters: PARAMS,
|
|
103
|
+
defaultActive: false,
|
|
104
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx: ExtensionContext) {
|
|
105
|
+
if (options.canRecord && !options.canRecord()) {
|
|
106
|
+
return errorResult(
|
|
107
|
+
"record_change: disabled during read-only consult or planning — exit /ask, or approve the plan and finish the implementation first.",
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
const root = rootOf(ctx.cwd || process.cwd());
|
|
111
|
+
if (!frameworkInstalled(root)) {
|
|
112
|
+
return errorResult(
|
|
113
|
+
"record_change: this project has no agent framework (.agents/framework/state.toml). Run /ask-init first, or write the record by hand.",
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
const title = params.title.trim();
|
|
117
|
+
const behavior = params.behavior.trim();
|
|
118
|
+
if (title === "") return errorResult("record_change: `title` is required.");
|
|
119
|
+
if (behavior === "") {
|
|
120
|
+
return errorResult(
|
|
121
|
+
'record_change: `behavior` is required — one user-facing sentence, or say why there is none.',
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const at = now();
|
|
126
|
+
let created;
|
|
127
|
+
try {
|
|
128
|
+
created = createRecord(root, {
|
|
129
|
+
title,
|
|
130
|
+
body: params.body,
|
|
131
|
+
now: at,
|
|
132
|
+
slug: params.slug,
|
|
133
|
+
});
|
|
134
|
+
} catch (error) {
|
|
135
|
+
return errorResult(
|
|
136
|
+
`record_change: ${error instanceof Error ? error.message : String(error)}`,
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
appendEvent(ledgerPath(root), {
|
|
141
|
+
v: 1,
|
|
142
|
+
id: newEventId(at),
|
|
143
|
+
// Ledger events order acceptance decisions; keep full precision even
|
|
144
|
+
// though the human-facing record header is minute-precision.
|
|
145
|
+
ts: at.toISOString(),
|
|
146
|
+
type: "candidate",
|
|
147
|
+
report: created.entry.id,
|
|
148
|
+
title: created.entry.title,
|
|
149
|
+
behavior,
|
|
150
|
+
hint: params.hint?.trim() || undefined,
|
|
151
|
+
area: params.area?.trim() || undefined,
|
|
152
|
+
files: params.files?.filter((file) => file.trim() !== ""),
|
|
153
|
+
spec: params.spec?.trim() || undefined,
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
return {
|
|
157
|
+
content: [
|
|
158
|
+
{
|
|
159
|
+
type: "text" as const,
|
|
160
|
+
text: `Wrote ${created.entry.path} (record ${created.entry.id}) and registered it for acceptance. It is pending until /ask-uat clusters it.`,
|
|
161
|
+
},
|
|
162
|
+
],
|
|
163
|
+
details: { id: created.entry.id, path: created.entry.path },
|
|
164
|
+
};
|
|
165
|
+
},
|
|
166
|
+
});
|
|
167
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
5
|
+
import {
|
|
6
|
+
canonicalRecordName,
|
|
7
|
+
createRecord,
|
|
8
|
+
isoMinute,
|
|
9
|
+
listRecords,
|
|
10
|
+
parseRecordFileName,
|
|
11
|
+
parseRecordHeader,
|
|
12
|
+
readRecordText,
|
|
13
|
+
slugify,
|
|
14
|
+
} from "./records.js";
|
|
15
|
+
|
|
16
|
+
let root: string;
|
|
17
|
+
|
|
18
|
+
beforeEach(() => {
|
|
19
|
+
root = mkdtempSync(join(tmpdir(), "uat-records-"));
|
|
20
|
+
mkdirSync(join(root, ".agents/implementations"), { recursive: true });
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
afterEach(() => {
|
|
24
|
+
rmSync(root, { recursive: true, force: true });
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
function writeRaw(name: string, text: string): void {
|
|
28
|
+
writeFileSync(join(root, ".agents/implementations", name), text, "utf8");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
describe("header and name shapes", () => {
|
|
32
|
+
it("parses the canonical minute header", () => {
|
|
33
|
+
const parsed = parseRecordHeader("# 2026-11-13T21:07+08:00 — Ask UAT lands");
|
|
34
|
+
expect(parsed).toEqual({
|
|
35
|
+
at: "2026-11-13T21:07+08:00",
|
|
36
|
+
title: "Ask UAT lands",
|
|
37
|
+
minute: "2026-11-13T21:07",
|
|
38
|
+
hasSeconds: false,
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it("still parses the older seconds-precision header", () => {
|
|
43
|
+
const parsed = parseRecordHeader("# 2026-11-11T02:55:59+08:00 — legacy");
|
|
44
|
+
expect(parsed?.hasSeconds).toBe(true);
|
|
45
|
+
expect(parsed?.title).toBe("legacy");
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("rejects a plain heading", () => {
|
|
49
|
+
expect(parseRecordHeader("# Just a title")).toBeUndefined();
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it("reads both file-name generations", () => {
|
|
53
|
+
expect(parseRecordFileName("2026-11-13_2107_ask-uat.md")).toEqual({
|
|
54
|
+
date: "2026-11-13",
|
|
55
|
+
hhmm: "2107",
|
|
56
|
+
slug: "ask-uat",
|
|
57
|
+
});
|
|
58
|
+
expect(parseRecordFileName("2026-11-11_ask-plan.md")).toEqual({
|
|
59
|
+
date: "2026-11-11",
|
|
60
|
+
hhmm: undefined,
|
|
61
|
+
slug: "ask-plan",
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it("builds the canonical name and slug", () => {
|
|
66
|
+
expect(canonicalRecordName("2026-11-13T21:07+08:00", "ask-uat")).toBe("2026-11-13_2107_ask-uat");
|
|
67
|
+
expect(slugify("Ask UAT 落地!")).toBe("ask-uat");
|
|
68
|
+
expect(slugify("验收台")).toBe("change");
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
describe("listRecords", () => {
|
|
73
|
+
it("accepts old records and marks them non-canonical", () => {
|
|
74
|
+
writeRaw("2026-11-11_ask-plan.md", "# 2026-11-11T02:55:59+08:00 — plan review\n\nbody\n");
|
|
75
|
+
const [record] = listRecords(root);
|
|
76
|
+
expect(record.id).toBe("2026-11-11_ask-plan");
|
|
77
|
+
expect(record.title).toBe("plan review");
|
|
78
|
+
expect(record.canonical).toBe(false);
|
|
79
|
+
expect(record.epochMs).toBeGreaterThan(0);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it("marks canonical records and sorts newest first", () => {
|
|
83
|
+
writeRaw("2026-11-12_0900_old.md", "# 2026-11-12T09:00+08:00 — old\n");
|
|
84
|
+
writeRaw("2026-11-13_2107_new.md", "# 2026-11-13T21:07+08:00 — new\n");
|
|
85
|
+
const records = listRecords(root);
|
|
86
|
+
expect(records.map((record) => record.id)).toEqual([
|
|
87
|
+
"2026-11-13_2107_new",
|
|
88
|
+
"2026-11-12_0900_old",
|
|
89
|
+
]);
|
|
90
|
+
expect(records[0].canonical).toBe(true);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it("falls back to the file name when the header is unparsable", () => {
|
|
94
|
+
writeRaw("2026-11-10_0800_freeform.md", "# Whatever happened\n");
|
|
95
|
+
const [record] = listRecords(root);
|
|
96
|
+
expect(record.title).toBe("Whatever happened");
|
|
97
|
+
expect(record.epochMs).toBe(Date.parse("2026-11-10T08:00"));
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("ignores archived subdirectories", () => {
|
|
101
|
+
mkdirSync(join(root, ".agents/implementations/archive/2025"), { recursive: true });
|
|
102
|
+
writeFileSync(
|
|
103
|
+
join(root, ".agents/implementations/archive/2025/2025-01-01_old.md"),
|
|
104
|
+
"# 2025-01-01T10:00+00:00 — archived\n",
|
|
105
|
+
);
|
|
106
|
+
expect(listRecords(root)).toEqual([]);
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
describe("createRecord", () => {
|
|
111
|
+
it("writes the canonical header, name and body", () => {
|
|
112
|
+
const now = new Date(2026, 10, 13, 21, 7, 30);
|
|
113
|
+
const { entry } = createRecord(root, {
|
|
114
|
+
title: "Ask UAT lands",
|
|
115
|
+
body: "# A duplicate title\n\nWhat changed.",
|
|
116
|
+
now,
|
|
117
|
+
});
|
|
118
|
+
expect(entry.path).toBe(`.agents/implementations/${canonicalRecordName(isoMinute(now), "ask-uat-lands")}.md`);
|
|
119
|
+
const text = readFileSync(join(root, entry.path), "utf8");
|
|
120
|
+
expect(text.split("\n")[0]).toBe(`# ${isoMinute(now)} — Ask UAT lands`);
|
|
121
|
+
expect(text).not.toContain("A duplicate title");
|
|
122
|
+
expect(text).toContain("What changed.");
|
|
123
|
+
expect(entry.canonical).toBe(true);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it("does not overwrite a record written in the same minute", () => {
|
|
127
|
+
const now = new Date(2026, 10, 13, 21, 7);
|
|
128
|
+
createRecord(root, { title: "same", body: "one", now, slug: "same" });
|
|
129
|
+
const second = createRecord(root, { title: "same", body: "two", now, slug: "same" });
|
|
130
|
+
expect(second.entry.id.endsWith("-2")).toBe(true);
|
|
131
|
+
expect(listRecords(root)).toHaveLength(2);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
it("rejects an empty title", () => {
|
|
135
|
+
expect(() => createRecord(root, { title: " ", body: "x" })).toThrow(/title/);
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
describe("readRecordText", () => {
|
|
140
|
+
it("reads by id and refuses traversal", () => {
|
|
141
|
+
const { entry } = createRecord(root, { title: "read me", body: "body" });
|
|
142
|
+
expect(readRecordText(root, entry.id)).toContain("read me");
|
|
143
|
+
expect(readRecordText(root, "../etc/passwd")).toBeUndefined();
|
|
144
|
+
});
|
|
145
|
+
});
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* UAT feature — change records on disk, read and written.
|
|
3
|
+
*
|
|
4
|
+
* A change record is one Markdown file in `.agents/implementations/`. The shape
|
|
5
|
+
* is deliberately thin: the first line carries the time to the minute, the rest
|
|
6
|
+
* is free prose the agent reads later. This module owns exactly three things:
|
|
7
|
+
*
|
|
8
|
+
* 1. the canonical first line (`# YYYY-MM-DDTHH:MM±HH:MM — title`);
|
|
9
|
+
* 2. the canonical file name (`YYYY-MM-DD_HHMM_slug.md`);
|
|
10
|
+
* 3. a lenient reader that also accepts the older `YYYY-MM-DD_slug.md` /
|
|
11
|
+
* seconds-precision files, because renaming history would break every
|
|
12
|
+
* pointer written into FINISHED.md, specs and other records.
|
|
13
|
+
*
|
|
14
|
+
* The reader is the fallback index of the whole UAT flow: a record exists as
|
|
15
|
+
* soon as the file exists, whether or not `record_change` was used. That keeps
|
|
16
|
+
* acceptance usable in a project that never adopted the tool.
|
|
17
|
+
*/
|
|
18
|
+
import {
|
|
19
|
+
existsSync,
|
|
20
|
+
mkdirSync,
|
|
21
|
+
readFileSync,
|
|
22
|
+
readdirSync,
|
|
23
|
+
statSync,
|
|
24
|
+
writeFileSync,
|
|
25
|
+
} from "node:fs";
|
|
26
|
+
import { join, posix } from "node:path";
|
|
27
|
+
|
|
28
|
+
export interface RecordEntry {
|
|
29
|
+
/** File name without `.md`; also the ledger's report id. */
|
|
30
|
+
id: string;
|
|
31
|
+
/** Path relative to the project root, POSIX separators. */
|
|
32
|
+
path: string;
|
|
33
|
+
title: string;
|
|
34
|
+
/** Timestamp exactly as parsed from the first line (may be second-precision). */
|
|
35
|
+
at?: string;
|
|
36
|
+
/** Ordering key; 0 when nothing could be parsed. */
|
|
37
|
+
epochMs: number;
|
|
38
|
+
firstLine: string;
|
|
39
|
+
/** First line and file name already follow the canonical minute shape. */
|
|
40
|
+
canonical: boolean;
|
|
41
|
+
/** File name carries `_HHMM`. */
|
|
42
|
+
nameHasTime: boolean;
|
|
43
|
+
slug: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface CreateRecordInput {
|
|
47
|
+
title: string;
|
|
48
|
+
/** Prose body. A leading `# title` line is dropped — the tool owns the header. */
|
|
49
|
+
body: string;
|
|
50
|
+
/** Clock injection for tests. */
|
|
51
|
+
now?: Date;
|
|
52
|
+
slug?: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const HEADER_RE =
|
|
56
|
+
/^#\s+(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2})(?::(\d{2}))?(Z|[+-]\d{2}:\d{2})?\s+[—–-]\s+(.+)$/;
|
|
57
|
+
const NAME_RE = /^(\d{4}-\d{2}-\d{2})(?:_(\d{2})(\d{2}))?_(.+)$/;
|
|
58
|
+
|
|
59
|
+
function pad(value: number, width = 2): string {
|
|
60
|
+
return String(value).padStart(width, "0");
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Local time with the numeric offset, to the minute: `2026-11-13T21:07+08:00`. */
|
|
64
|
+
export function isoMinute(date: Date): string {
|
|
65
|
+
const offset = -date.getTimezoneOffset();
|
|
66
|
+
const sign = offset >= 0 ? "+" : "-";
|
|
67
|
+
const absolute = Math.abs(offset);
|
|
68
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(
|
|
69
|
+
date.getHours(),
|
|
70
|
+
)}:${pad(date.getMinutes())}${sign}${pad(Math.floor(absolute / 60))}:${pad(absolute % 60)}`;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The canonical first line of a change record. */
|
|
74
|
+
export function formatRecordHeader(title: string, at: string): string {
|
|
75
|
+
return `# ${at} — ${title}`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function parseRecordHeader(line: string):
|
|
79
|
+
| { at: string; title: string; minute: string; hasSeconds: boolean }
|
|
80
|
+
| undefined {
|
|
81
|
+
const match = HEADER_RE.exec(line.trim());
|
|
82
|
+
if (!match) return undefined;
|
|
83
|
+
const [, date, hours, minutes, seconds, offset, title] = match;
|
|
84
|
+
const zone = offset ?? "";
|
|
85
|
+
const at = `${date}T${hours}:${minutes}${seconds ? `:${seconds}` : ""}${zone}`;
|
|
86
|
+
return {
|
|
87
|
+
at,
|
|
88
|
+
title: (title ?? "").trim(),
|
|
89
|
+
minute: `${date}T${hours}:${minutes}`,
|
|
90
|
+
hasSeconds: seconds !== undefined,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** `2026-11-13_2107_slug` → `{date: "2026-11-13", hhmm: "2107", slug}`. */
|
|
95
|
+
export function parseRecordFileName(name: string):
|
|
96
|
+
| { date: string; hhmm?: string; slug: string }
|
|
97
|
+
| undefined {
|
|
98
|
+
const base = name.endsWith(".md") ? name.slice(0, -3) : name;
|
|
99
|
+
const match = NAME_RE.exec(base);
|
|
100
|
+
if (!match) return undefined;
|
|
101
|
+
const [, date, hh, mm, slug] = match;
|
|
102
|
+
return { date, hhmm: hh && mm ? `${hh}${mm}` : undefined, slug };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** ASCII slug from a title; non-ASCII titles fall back to `change`. */
|
|
106
|
+
export function slugify(value: string): string {
|
|
107
|
+
const slug = value
|
|
108
|
+
.toLowerCase()
|
|
109
|
+
.normalize("NFKD")
|
|
110
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
111
|
+
.replace(/^-+|-+$/g, "")
|
|
112
|
+
.slice(0, 60)
|
|
113
|
+
.replace(/-+$/g, "");
|
|
114
|
+
return slug.length >= 3 ? slug : "change";
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Rewrite one file name into the canonical minute-precision shape. */
|
|
118
|
+
export function canonicalRecordName(at: string, slug: string): string {
|
|
119
|
+
const [date, time] = at.split("T");
|
|
120
|
+
const hhmm = (time ?? "").slice(0, 2).concat((time ?? "").slice(3, 5));
|
|
121
|
+
return `${date}_${hhmm}_${slug}`;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Read every top-level change record. Subdirectories (`archive/<year>/`) are
|
|
126
|
+
* skipped on purpose: archived records are rolled up already and would
|
|
127
|
+
* resurrect acceptance debt that was settled before the roll-up.
|
|
128
|
+
*/
|
|
129
|
+
export function listRecords(root: string): RecordEntry[] {
|
|
130
|
+
const dir = join(root, ".agents/implementations");
|
|
131
|
+
if (!existsSync(dir)) return [];
|
|
132
|
+
const entries: RecordEntry[] = [];
|
|
133
|
+
for (const name of readdirSync(dir)) {
|
|
134
|
+
if (!name.endsWith(".md")) continue;
|
|
135
|
+
const absolute = join(dir, name);
|
|
136
|
+
let stat;
|
|
137
|
+
try {
|
|
138
|
+
stat = statSync(absolute);
|
|
139
|
+
} catch {
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
if (!stat.isFile()) continue;
|
|
143
|
+
let text = "";
|
|
144
|
+
try {
|
|
145
|
+
text = readFileSync(absolute, "utf8");
|
|
146
|
+
} catch {
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
const firstLine = (text.split("\n", 1)[0] ?? "").trim();
|
|
150
|
+
const header = parseRecordHeader(firstLine);
|
|
151
|
+
const parsedName = parseRecordFileName(name);
|
|
152
|
+
const id = name.slice(0, -3);
|
|
153
|
+
|
|
154
|
+
let epochMs = header ? Date.parse(header.at) : Number.NaN;
|
|
155
|
+
if (!Number.isFinite(epochMs)) {
|
|
156
|
+
// Fall back to the file name, then to mtime. Never invent "now": an
|
|
157
|
+
// undated record must not jump to the top of the acceptance queue.
|
|
158
|
+
const fromName = parsedName
|
|
159
|
+
? Date.parse(
|
|
160
|
+
`${parsedName.date}T${
|
|
161
|
+
parsedName.hhmm
|
|
162
|
+
? `${parsedName.hhmm.slice(0, 2)}:${parsedName.hhmm.slice(2)}`
|
|
163
|
+
: "00:00"
|
|
164
|
+
}`,
|
|
165
|
+
)
|
|
166
|
+
: Number.NaN;
|
|
167
|
+
epochMs = Number.isFinite(fromName) ? fromName : stat.mtimeMs;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const nameMinute = parsedName?.hhmm
|
|
171
|
+
? `${parsedName.date}T${parsedName.hhmm.slice(0, 2)}:${parsedName.hhmm.slice(2)}`
|
|
172
|
+
: undefined;
|
|
173
|
+
const canonical =
|
|
174
|
+
header !== undefined &&
|
|
175
|
+
!header.hasSeconds &&
|
|
176
|
+
nameMinute !== undefined &&
|
|
177
|
+
header.minute === nameMinute;
|
|
178
|
+
|
|
179
|
+
entries.push({
|
|
180
|
+
id,
|
|
181
|
+
path: posix.join(".agents/implementations", name),
|
|
182
|
+
title: header?.title ?? (firstLine.replace(/^#+\s*/, "") || parsedName?.slug || id),
|
|
183
|
+
at: header?.at,
|
|
184
|
+
epochMs: Number.isFinite(epochMs) ? epochMs : 0,
|
|
185
|
+
firstLine,
|
|
186
|
+
canonical,
|
|
187
|
+
nameHasTime: nameMinute !== undefined,
|
|
188
|
+
slug: parsedName?.slug ?? id,
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
for (const entry of entries) entry.epochMs = entry.epochMs || 0;
|
|
192
|
+
entries.sort((a, b) => b.epochMs - a.epochMs || a.id.localeCompare(b.id));
|
|
193
|
+
return entries;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** One-line title: collapse whitespace so the header stays one line. */
|
|
197
|
+
export function normalizeTitle(value: string): string {
|
|
198
|
+
return value.replace(/\s+/g, " ").trim();
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Write one record and return its entry. Collisions inside the same minute get
|
|
203
|
+
* a `-2`, `-3` suffix instead of overwriting a sibling.
|
|
204
|
+
*/
|
|
205
|
+
export function createRecord(
|
|
206
|
+
root: string,
|
|
207
|
+
input: CreateRecordInput,
|
|
208
|
+
): { entry: RecordEntry; absolute: string } {
|
|
209
|
+
const now = input.now ?? new Date();
|
|
210
|
+
const at = isoMinute(now);
|
|
211
|
+
const title = normalizeTitle(input.title);
|
|
212
|
+
if (title === "") throw new Error("record title is required");
|
|
213
|
+
const slug = input.slug ? slugify(input.slug) : slugify(title);
|
|
214
|
+
const dir = join(root, ".agents/implementations");
|
|
215
|
+
mkdirSync(dir, { recursive: true });
|
|
216
|
+
|
|
217
|
+
const header = formatRecordHeader(title, at);
|
|
218
|
+
const body = stripLeadingHeading(input.body ?? "");
|
|
219
|
+
const content = body === "" ? `${header}\n` : `${header}\n\n${body}\n`;
|
|
220
|
+
|
|
221
|
+
let name = `${canonicalRecordName(at, slug)}.md`;
|
|
222
|
+
// `existsSync` + a normal write has a race between two sessions in the same
|
|
223
|
+
// minute. Exclusive create makes the filename claim atomic: only the loser
|
|
224
|
+
// advances to `-2`, and neither process can overwrite the other's record.
|
|
225
|
+
for (let suffix = 2; ; suffix += 1) {
|
|
226
|
+
if (suffix > 99) throw new Error("too many records in the same minute");
|
|
227
|
+
const absolute = join(dir, name);
|
|
228
|
+
try {
|
|
229
|
+
writeFileSync(absolute, content, { encoding: "utf8", flag: "wx" });
|
|
230
|
+
const entry: RecordEntry = {
|
|
231
|
+
id: name.slice(0, -3),
|
|
232
|
+
path: posix.join(".agents/implementations", name),
|
|
233
|
+
title,
|
|
234
|
+
at,
|
|
235
|
+
epochMs: Date.parse(at) || now.getTime(),
|
|
236
|
+
firstLine: header,
|
|
237
|
+
canonical: true,
|
|
238
|
+
nameHasTime: true,
|
|
239
|
+
slug,
|
|
240
|
+
};
|
|
241
|
+
return { entry, absolute };
|
|
242
|
+
} catch (error) {
|
|
243
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
244
|
+
name = `${canonicalRecordName(at, slug)}-${suffix}.md`;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Drop a leading `# ...` line: the tool owns the header, the body is prose. */
|
|
250
|
+
function stripLeadingHeading(body: string): string {
|
|
251
|
+
const trimmed = body.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n").trim();
|
|
252
|
+
if (!trimmed.startsWith("#")) return trimmed;
|
|
253
|
+
const newline = trimmed.indexOf("\n");
|
|
254
|
+
return newline === -1 ? "" : trimmed.slice(newline + 1).trim();
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Text of one record by id, bounded so a huge file cannot flood the page. */
|
|
258
|
+
export function readRecordText(root: string, id: string, limit = 128 * 1024): string | undefined {
|
|
259
|
+
if (!/^[A-Za-z0-9._-]+$/.test(id)) return undefined;
|
|
260
|
+
const absolute = join(root, ".agents/implementations", `${id}.md`);
|
|
261
|
+
if (!existsSync(absolute)) return undefined;
|
|
262
|
+
try {
|
|
263
|
+
const text = readFileSync(absolute, "utf8");
|
|
264
|
+
return text.length > limit ? `${text.slice(0, limit)}\n\n… (truncated)` : text;
|
|
265
|
+
} catch {
|
|
266
|
+
return undefined;
|
|
267
|
+
}
|
|
268
|
+
}
|