@niwa-labs/pstack 0.0.0-stage → 0.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 (163) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +260 -2
  3. package/package.json +28 -4
  4. package/scripts/upstream-map.ts +90 -0
  5. package/src/author.ts +57 -0
  6. package/src/binding.ts +32 -0
  7. package/src/catalog.ts +86 -0
  8. package/src/composition.ts +66 -0
  9. package/src/index.ts +50 -0
  10. package/src/mapping/analyze.ts +223 -0
  11. package/src/mapping/assemble.ts +96 -0
  12. package/src/mapping/diff.ts +139 -0
  13. package/src/mapping/format.ts +67 -0
  14. package/src/mapping/git.ts +69 -0
  15. package/src/mapping/index.ts +18 -0
  16. package/src/mapping/maintain.ts +36 -0
  17. package/src/mapping/schema.ts +50 -0
  18. package/src/mapping/sources.ts +108 -0
  19. package/src/mapping/tool.ts +77 -0
  20. package/src/mapping/verify.ts +130 -0
  21. package/src/plugin.ts +136 -0
  22. package/src/policy.ts +115 -0
  23. package/src/ports.ts +184 -0
  24. package/src/pr-binding.ts +88 -0
  25. package/src/records.ts +61 -0
  26. package/src/roles.ts +49 -0
  27. package/src/trunk.ts +59 -0
  28. package/src/upstream-actions.ts +135 -0
  29. package/src/upstream-records.ts +71 -0
  30. package/src/upstream.ts +151 -0
  31. package/src/workflows/adapted.md +780 -0
  32. package/src/workflows/authoring-a-skill.ts +52 -0
  33. package/src/workflows/autonomous-run.ts +56 -0
  34. package/src/workflows/autopilot-full.ts +90 -0
  35. package/src/workflows/autopilot-stack.ts +125 -0
  36. package/src/workflows/babysit.ts +124 -0
  37. package/src/workflows/benny-reproduce.ts +122 -0
  38. package/src/workflows/benny-triage.ts +89 -0
  39. package/src/workflows/bug-fix.ts +54 -0
  40. package/src/workflows/entry.ts +130 -0
  41. package/src/workflows/eval.ts +63 -0
  42. package/src/workflows/feature.ts +54 -0
  43. package/src/workflows/hillclimb.ts +78 -0
  44. package/src/workflows/investigation.ts +41 -0
  45. package/src/workflows/lib/catalog.ts +45 -0
  46. package/src/workflows/lib/change.ts +70 -0
  47. package/src/workflows/lib/forensics.ts +37 -0
  48. package/src/workflows/lib/git.ts +30 -0
  49. package/src/workflows/lib/go.ts +58 -0
  50. package/src/workflows/lib/inputs.ts +34 -0
  51. package/src/workflows/lib/lane.ts +170 -0
  52. package/src/workflows/lib/measure.ts +34 -0
  53. package/src/workflows/lib/plan.ts +24 -0
  54. package/src/workflows/lib/script.ts +79 -0
  55. package/src/workflows/lib/ship.ts +110 -0
  56. package/src/workflows/lib/texts.ts +18 -0
  57. package/src/workflows/lib/trunk.ts +91 -0
  58. package/src/workflows/multi-phase-plan.ts +83 -0
  59. package/src/workflows/opening-a-pr.ts +62 -0
  60. package/src/workflows/pause-safely.ts +50 -0
  61. package/src/workflows/perf-issue.ts +87 -0
  62. package/src/workflows/prototype.ts +76 -0
  63. package/src/workflows/refactoring.ts +54 -0
  64. package/src/workflows/runtime-forensics.ts +26 -0
  65. package/src/workflows/scenarios.ts +380 -0
  66. package/src/workflows/session-pickup.ts +57 -0
  67. package/src/workflows/shipping.ts +63 -0
  68. package/src/workflows/suite.ts +129 -0
  69. package/src/workflows/texts/authoring-a-skill.json +5 -0
  70. package/src/workflows/texts/autonomous-run.json +5 -0
  71. package/src/workflows/texts/autopilot-full.json +5 -0
  72. package/src/workflows/texts/autopilot-stack.json +5 -0
  73. package/src/workflows/texts/babysit.json +5 -0
  74. package/src/workflows/texts/benny-reproduce.json +5 -0
  75. package/src/workflows/texts/benny-triage.json +5 -0
  76. package/src/workflows/texts/bug-fix.json +5 -0
  77. package/src/workflows/texts/bugbot-triage.json +5 -0
  78. package/src/workflows/texts/eval.json +5 -0
  79. package/src/workflows/texts/feature.json +5 -0
  80. package/src/workflows/texts/hillclimb.json +5 -0
  81. package/src/workflows/texts/investigation.json +5 -0
  82. package/src/workflows/texts/multi-phase-plan.json +5 -0
  83. package/src/workflows/texts/opening-a-pr.json +5 -0
  84. package/src/workflows/texts/pause-safely.json +5 -0
  85. package/src/workflows/texts/perf-issue.json +5 -0
  86. package/src/workflows/texts/prototype.json +5 -0
  87. package/src/workflows/texts/refactoring.json +5 -0
  88. package/src/workflows/texts/runtime-forensics.json +5 -0
  89. package/src/workflows/texts/session-pickup.json +5 -0
  90. package/src/workflows/texts/trace-forensics.json +5 -0
  91. package/src/workflows/texts/visual-parity.json +5 -0
  92. package/src/workflows/texts/worker.json +5 -0
  93. package/src/workflows/trace-forensics.ts +27 -0
  94. package/src/workflows/upstream-sync.ts +182 -0
  95. package/src/workflows/visual-parity.ts +52 -0
  96. package/src/workflows/worktree-cleanup.ts +57 -0
  97. package/test/author.test.ts +61 -0
  98. package/test/benny.test.ts +138 -0
  99. package/test/binding.test.ts +54 -0
  100. package/test/catalog-helpers.test.ts +49 -0
  101. package/test/closure.test.ts +45 -0
  102. package/test/composition.test.ts +23 -0
  103. package/test/eval.test.ts +23 -0
  104. package/test/lanes.test.ts +334 -0
  105. package/test/mapping-diff.test.ts +64 -0
  106. package/test/mapping-support.ts +110 -0
  107. package/test/mapping-texts.test.ts +106 -0
  108. package/test/mapping.test.ts +276 -0
  109. package/test/package-layout.ts +68 -0
  110. package/test/policy.test.ts +98 -0
  111. package/test/ports.test.ts +45 -0
  112. package/test/ports.ts +173 -0
  113. package/test/roles.test.ts +21 -0
  114. package/test/suite.test.ts +167 -0
  115. package/test/support.ts +541 -0
  116. package/test/texts.test.ts +174 -0
  117. package/test/tool.test.ts +48 -0
  118. package/test/trunk-helpers.test.ts +149 -0
  119. package/test/trunk.test.ts +24 -0
  120. package/test/upstream-sync.test.ts +246 -0
  121. package/test/upstream.test.ts +106 -0
  122. package/test/worktree-cleanup.test.ts +107 -0
  123. package/tsconfig.json +7 -0
  124. package/upstream/LICENSE +21 -0
  125. package/upstream/SOURCE.json +5 -0
  126. package/upstream/benny/FOR_AGENTS.md +89 -0
  127. package/upstream/benny/README.md +23 -0
  128. package/upstream/benny/skills/reproduce-and-fix-issues/SKILL.md +310 -0
  129. package/upstream/benny/skills/reproduce-and-fix-issues/references/control-adapter.md +169 -0
  130. package/upstream/benny/skills/reproduce-and-fix-issues/references/feature-map.example.md +205 -0
  131. package/upstream/benny/skills/reproduce-and-fix-issues/references/verify-existing-fix.md +93 -0
  132. package/upstream/benny/skills/setup-benny/SKILL.md +265 -0
  133. package/upstream/benny/skills/triage-issue-reports/SKILL.md +240 -0
  134. package/upstream/benny/skills/triage-issue-reports/references/routing.example.md +61 -0
  135. package/upstream/benny/templates/configuration.example.yaml +84 -0
  136. package/upstream/benny/templates/reproduce-automation-prompt.md +33 -0
  137. package/upstream/benny/templates/triage-automation-prompt.md +39 -0
  138. package/upstream/mapping.json +699 -0
  139. package/upstream/poteto-mode/SKILL.md +110 -0
  140. package/upstream/poteto-mode/playbooks/authoring-a-skill.md +12 -0
  141. package/upstream/poteto-mode/playbooks/autonomous-run.md +13 -0
  142. package/upstream/poteto-mode/playbooks/autopilot-full.md +25 -0
  143. package/upstream/poteto-mode/playbooks/autopilot-stack.md +8 -0
  144. package/upstream/poteto-mode/playbooks/babysit.md +10 -0
  145. package/upstream/poteto-mode/playbooks/bug-fix.md +15 -0
  146. package/upstream/poteto-mode/playbooks/eval.md +25 -0
  147. package/upstream/poteto-mode/playbooks/feature.md +21 -0
  148. package/upstream/poteto-mode/playbooks/hillclimb.md +21 -0
  149. package/upstream/poteto-mode/playbooks/investigation.md +14 -0
  150. package/upstream/poteto-mode/playbooks/multi-phase-plan.md +11 -0
  151. package/upstream/poteto-mode/playbooks/opening-a-pr.md +9 -0
  152. package/upstream/poteto-mode/playbooks/pause-safely.md +10 -0
  153. package/upstream/poteto-mode/playbooks/perf-issue.md +25 -0
  154. package/upstream/poteto-mode/playbooks/prototype.md +14 -0
  155. package/upstream/poteto-mode/playbooks/refactoring.md +16 -0
  156. package/upstream/poteto-mode/playbooks/runtime-forensics.md +11 -0
  157. package/upstream/poteto-mode/playbooks/session-pickup.md +11 -0
  158. package/upstream/poteto-mode/playbooks/shipping.md +12 -0
  159. package/upstream/poteto-mode/playbooks/trace-forensics.md +14 -0
  160. package/upstream/poteto-mode/playbooks/visual-parity.md +11 -0
  161. package/upstream/poteto-mode/playbooks/worktree-cleanup.md +12 -0
  162. package/upstream/poteto-mode/references/bugbot-triage.md +142 -0
  163. package/upstream/poteto-mode/worker.md +11 -0
@@ -0,0 +1,135 @@
1
+ /**
2
+ * The upstream sync's own steps, done by the plugin in a worktree of niwa. A real `proc.run` box reads only its own
3
+ * directory, so it can read neither an upstream checkout nor the repository a worktree belongs to, and git does not
4
+ * run in a worktree there; the tool and git therefore run here, on the host. Each step is held to a worktree of niwa
5
+ * (checked before anything is read or written), reads the upstream checkout through git only, and writes inside the
6
+ * worktree and nowhere else.
7
+ */
8
+
9
+ import { existsSync, realpathSync, statSync, writeFileSync } from "node:fs";
10
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
11
+
12
+ import { action } from "@niwa-labs/core";
13
+ import type { Action } from "@niwa-labs/core";
14
+
15
+ import { worktreePlace, worktreesOf } from "./author.ts";
16
+ import { Git, openMap, recordMap, summaryOf, unreadable, writeAssembled } from "./mapping/index.ts";
17
+ import type { ToolContext } from "./mapping/index.ts";
18
+ import { pathsIn, refreshUpstream } from "./upstream.ts";
19
+ import {
20
+ pstackUpstreamAssemble,
21
+ pstackUpstreamCommit,
22
+ pstackUpstreamMeasure,
23
+ pstackUpstreamRecord,
24
+ pstackUpstreamRefresh,
25
+ pstackUpstreamState,
26
+ } from "./upstream-records.ts";
27
+ import type { UpstreamSummary } from "./upstream-records.ts";
28
+
29
+ /** Where the full report of a measurement is written, in the worktree. */
30
+ export const REPORT_FILE = ".upstream-map-report.json";
31
+
32
+ /** A path that stays inside `place`: the real path of the worktree, and the path resolved from it. */
33
+ function inside(place: string, path: string, what: string): string {
34
+ if (isAbsolute(path) || path.split(/[\\/]/).includes("..") || path.startsWith("-")) throw new Error(`${what} ${JSON.stringify(path)} must be a path inside the worktree`);
35
+ const found = resolve(place, path);
36
+ const back = relative(place, found);
37
+ if (back === "" || back.startsWith("..") || isAbsolute(back)) throw new Error(`${what} ${JSON.stringify(path)} must be a path inside the worktree`);
38
+ // A link inside the worktree must not lead out of it.
39
+ if (existsSync(found) && !realpathSync(found).startsWith(place + sep)) throw new Error(`${what} ${JSON.stringify(path)} leads out of the worktree`);
40
+ return found;
41
+ }
42
+
43
+ /** An upstream checkout: an existing folder. */
44
+ function checkoutOf(checkout: string): string {
45
+ if (!isAbsolute(checkout) || !existsSync(checkout) || !statSync(checkout).isDirectory()) throw new Error(`the upstream checkout ${JSON.stringify(checkout)} is not a folder`);
46
+ return realpathSync(checkout);
47
+ }
48
+
49
+ /** What the tool is given for a step: the package folder of the worktree, the worktree as the repository's root, the checkout. */
50
+ function contextOf(home: string, input: { place: string; package: string; checkout: string }): { place: string; ctx: ToolContext } {
51
+ const place = worktreePlace("the upstream sync", input.place, worktreesOf(home));
52
+ return { place, ctx: { paths: pathsIn(inside(place, input.package, "the package folder")), root: place, checkout: checkoutOf(input.checkout) } };
53
+ }
54
+
55
+ /** The upstream sync's actions, for a host whose niwa home is `home()`. */
56
+ export function upstreamActions(home: () => string): Action<any, any>[] {
57
+ return [
58
+ action(pstackUpstreamRefresh, {
59
+ recovery: "repeat",
60
+ effect: "write",
61
+ world: "local",
62
+ run: (input) => {
63
+ const { ctx } = contextOf(home(), input);
64
+ const source = refreshUpstream(ctx.checkout as string, { upstream: ctx.paths.upstream, ...(input.commit === undefined ? {} : { commit: input.commit }) });
65
+ return { commit: source.commit };
66
+ },
67
+ }),
68
+ action(pstackUpstreamMeasure, {
69
+ recovery: "repeat",
70
+ effect: "write",
71
+ world: "local",
72
+ run: (input): UpstreamSummary => {
73
+ const { place, ctx } = contextOf(home(), input);
74
+ const report = join(place, REPORT_FILE);
75
+ try {
76
+ const opened = openMap(ctx);
77
+ writeFileSync(report, `${JSON.stringify(opened.report, null, 2)}\n`);
78
+ return summaryOf(opened.report);
79
+ } catch (error) {
80
+ // A map that cannot be read at all is a problem of the map, said as one: the author mends it.
81
+ const said = unreadable(error);
82
+ writeFileSync(report, `${JSON.stringify({ error: said.error }, null, 2)}\n`);
83
+ return said;
84
+ }
85
+ },
86
+ }),
87
+ action(pstackUpstreamRecord, {
88
+ recovery: "repeat",
89
+ effect: "write",
90
+ world: "local",
91
+ run: (input) => {
92
+ const { ctx } = contextOf(home(), input);
93
+ try {
94
+ const advanced = recordMap(ctx, "unchanged");
95
+ return { recorded: advanced + (input.accept.length > 0 ? recordMap(ctx, input.accept) : 0) };
96
+ } catch (error) {
97
+ return { recorded: 0, refused: (error as Error).message.slice(0, 500) };
98
+ }
99
+ },
100
+ }),
101
+ action(pstackUpstreamAssemble, {
102
+ recovery: "repeat",
103
+ effect: "write",
104
+ world: "local",
105
+ run: (input) => ({ texts: writeAssembled(contextOf(home(), input).ctx) }),
106
+ }),
107
+ action(pstackUpstreamCommit, {
108
+ recovery: "repeat",
109
+ effect: "write",
110
+ world: "local",
111
+ run: (input) => {
112
+ const place = worktreePlace("the upstream sync", input.place, worktreesOf(home()));
113
+ const git = new Git(place);
114
+ const paths = input.paths.map((one) => relative(place, inside(place, one, "the path")));
115
+ git.out(["add", "--", ...paths]);
116
+ const staged = git.out(["diff", "--cached", "--name-only"]).trim();
117
+ if (staged !== "") git.out(["commit", "-q", "-m", input.message]);
118
+ return { head: git.out(["rev-parse", "HEAD"]).trim(), committed: staged !== "" };
119
+ },
120
+ }),
121
+ action(pstackUpstreamState, {
122
+ recovery: "repeat",
123
+ effect: "read",
124
+ world: "local",
125
+ run: (input) => {
126
+ const place = worktreePlace("the upstream sync", input.place, worktreesOf(home()));
127
+ const git = new Git(place);
128
+ const head = git.out(["rev-parse", "HEAD"]).trim();
129
+ const paths = input.paths.map((one) => relative(place, inside(place, one, "the path")));
130
+ const changed = input.base === undefined ? [] : git.out(["diff", "--name-only", `${input.base}...${head}`, ...(paths.length > 0 ? ["--", ...paths] : [])]).split("\n").filter((line) => line !== "");
131
+ return { head, changed };
132
+ },
133
+ }),
134
+ ];
135
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * The action references of the upstream sync: what its script calls on the pstack plugin.
3
+ */
4
+
5
+ import { actionRef } from "@niwa-labs/core";
6
+ import { z } from "zod";
7
+
8
+ /** The upstream sync's own steps, done by the plugin in a worktree: the tool and git run on the host, not in a box. */
9
+ const UpstreamPlace = {
10
+ place: z.string().min(1).describe("One of niwa's worktrees: the only place the step reads our files from and writes to"),
11
+ package: z.string().min(1).default("packages/pstack").describe("The folder of the package in the worktree, with no `..`"),
12
+ };
13
+ const UpstreamCheckout = { checkout: z.string().min(1).describe("The real path of a checkout of upstream's pstack folder: it is read through git, never written") };
14
+
15
+ /** The numbers the map tool prints for a measurement. */
16
+ export const UpstreamSummary = z.strictObject({
17
+ problems: z.number(),
18
+ textProblems: z.number(),
19
+ coverage: z.number(),
20
+ entries: z.number(),
21
+ unchanged: z.number(),
22
+ touched: z.number(),
23
+ gone: z.number(),
24
+ uncovered: z.number(),
25
+ error: z.string().optional(),
26
+ });
27
+ export type UpstreamSummary = z.infer<typeof UpstreamSummary>;
28
+
29
+ export const pstackUpstreamRefresh = actionRef("pstack.upstream.refresh", {
30
+ description:
31
+ "Take a new snapshot of an upstream pstack checkout, at a commit of it (its HEAD by default), into the package folder of a worktree of niwa. " +
32
+ "The checkout is read through git and never written; the snapshot is replaced whole and the map stays. Answers the commit taken.",
33
+ input: z.strictObject({ ...UpstreamPlace, ...UpstreamCheckout, commit: z.string().min(1).optional() }),
34
+ output: z.strictObject({ commit: z.string() }),
35
+ });
36
+
37
+ export const pstackUpstreamMeasure = actionRef("pstack.upstream.measure", {
38
+ description:
39
+ "Measure the upstream map of the package folder of a worktree: its coverage, what became of each entry, and what is wrong with the texts. " +
40
+ "Writes the whole report as JSON to `.upstream-map-report.json` in the worktree and answers the numbers. A map that cannot be read answers one problem and the reason.",
41
+ input: z.strictObject({ ...UpstreamPlace, ...UpstreamCheckout }),
42
+ output: UpstreamSummary,
43
+ });
44
+
45
+ export const pstackUpstreamRecord = actionRef("pstack.upstream.record", {
46
+ description:
47
+ "Record the entries of the map that are unchanged at the current commits, then the named ones at the positions their ranges were carried to. " +
48
+ "A map with problems, or an id that is not an entry, records nothing and says why. Answers how many entries changed.",
49
+ input: z.strictObject({ ...UpstreamPlace, ...UpstreamCheckout, accept: z.array(z.string().min(1)).max(1000).default([]) }),
50
+ output: z.strictObject({ recorded: z.number(), refused: z.string().optional() }),
51
+ });
52
+
53
+ export const pstackUpstreamAssemble = actionRef("pstack.upstream.assemble", {
54
+ description: "Write the texts the scripts import into the package folder of a worktree, assembled from its map. Answers how many.",
55
+ input: z.strictObject({ ...UpstreamPlace, ...UpstreamCheckout }),
56
+ output: z.strictObject({ texts: z.number() }),
57
+ });
58
+
59
+ export const pstackUpstreamCommit = actionRef("pstack.upstream.commit", {
60
+ description:
61
+ "Commit what changed under the given paths of a worktree of niwa (paths relative to it, none leading out). Nothing staged means no commit. " +
62
+ "Answers the head and whether a commit was made.",
63
+ input: z.strictObject({ place: z.string().min(1), message: z.string().min(1).max(500), paths: z.array(z.string().min(1)).min(1).max(50) }),
64
+ output: z.strictObject({ head: z.string(), committed: z.boolean() }),
65
+ });
66
+
67
+ export const pstackUpstreamState = actionRef("pstack.upstream.state", {
68
+ description: "The head of a worktree of niwa, and the files under the given paths that changed from `base` to the head.",
69
+ input: z.strictObject({ place: z.string().min(1), base: z.string().min(1).optional(), paths: z.array(z.string().min(1)).max(50).default([]) }),
70
+ output: z.strictObject({ head: z.string(), changed: z.array(z.string()) }),
71
+ });
@@ -0,0 +1,151 @@
1
+ /**
2
+ * The snapshot of the upstream pstack playbooks that this package carries, and how it is refreshed.
3
+ *
4
+ * Upstream is the `pstack` plugin of `cursor/plugins` (MIT). The snapshot keeps its operator skill, the worker rules,
5
+ * the playbooks, the references they name, and the Benny automation pack, byte for byte, under `upstream/`, with the
6
+ * commit they were taken from. A refresh reads a commit of an upstream checkout through git and replaces the snapshot
7
+ * whole; the checkout's working tree is never read, and the checkout is never written. What the snapshot became in
8
+ * pstack is recorded in `upstream/mapping.json`; see `mapping/`.
9
+ */
10
+
11
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
12
+ import { basename, dirname, join } from "node:path";
13
+
14
+ import { Git } from "./mapping/git.ts";
15
+
16
+ /** Where the parts of a package folder that the upstream map works on are: its snapshot, its texts and its mapping. */
17
+ export interface PackagePaths {
18
+ /** The folder of the package. */
19
+ readonly dir: string;
20
+ /** Where the snapshot lives. */
21
+ readonly upstream: string;
22
+ /** Where the texts the scripts import live. */
23
+ readonly texts: string;
24
+ /** Where the mapping of the snapshot lives, in the snapshot's folder. */
25
+ readonly mapping: string;
26
+ }
27
+
28
+ /** The paths of the package folder `dir`: the folder of this package, or the same folder in a worktree of its repository. */
29
+ export function pathsIn(dir: string): PackagePaths {
30
+ const upstream = join(dir, "upstream");
31
+ return { dir, upstream, texts: join(dir, "src", "workflows", "texts"), mapping: join(upstream, "mapping.json") };
32
+ }
33
+
34
+ /** The folder of this package. */
35
+ export const PACKAGE_DIR = join(import.meta.dir, "..");
36
+
37
+ /** The paths of this package. */
38
+ export const PACKAGE_PATHS = pathsIn(PACKAGE_DIR);
39
+
40
+ /** Where the snapshot lives in this package. */
41
+ export const UPSTREAM_DIR = PACKAGE_PATHS.upstream;
42
+
43
+ /** Where the texts the scripts import live in this package. */
44
+ export const TEXTS_DIR = PACKAGE_PATHS.texts;
45
+
46
+ /** Where the mapping of the snapshot lives, in the snapshot's folder. */
47
+ export const MAPPING_FILE = PACKAGE_PATHS.mapping;
48
+
49
+ /**
50
+ * Where the snapshot's files come from in an upstream checkout (the `pstack` folder of `cursor/plugins`): a folder of
51
+ * the snapshot, the folder of the checkout it is taken from, and the files of it the snapshot keeps (all, when none).
52
+ */
53
+ export const SNAPSHOT_PATHS = [
54
+ { snapshot: "LICENSE", from: "LICENSE" },
55
+ { snapshot: "poteto-mode", from: join("skills", "poteto-mode"), keep: ["SKILL.md", "worker.md", "playbooks/", "references/"] },
56
+ { snapshot: "benny", from: join("automations", "benny") },
57
+ ] as const;
58
+
59
+ /** The files of the snapshot that are not upstream's text: what the snapshot says about itself, and the license. */
60
+ export const SNAPSHOT_META: readonly string[] = ["SOURCE.json", "LICENSE", "mapping.json"];
61
+
62
+ /** Where the snapshot was taken from. */
63
+ export interface UpstreamSource {
64
+ readonly repository: string;
65
+ readonly path: string;
66
+ readonly commit: string;
67
+ }
68
+
69
+ /** The path of a snapshot file in an upstream checkout. */
70
+ export function checkoutPathOf(file: string): string {
71
+ for (const one of SNAPSHOT_PATHS) {
72
+ if (file === one.snapshot) return one.from;
73
+ if (file.startsWith(`${one.snapshot}/`)) return `${one.from}/${file.slice(one.snapshot.length + 1)}`;
74
+ }
75
+ throw new Error(`${file} is not a file of the upstream snapshot`);
76
+ }
77
+
78
+ /** The path in the snapshot of a file of an upstream checkout, or undefined when the snapshot keeps no such file. */
79
+ export function snapshotPathOf(path: string): string | undefined {
80
+ for (const one of SNAPSHOT_PATHS) {
81
+ const root = one.from.split("\\").join("/");
82
+ if (path !== root && !path.startsWith(`${root}/`)) continue;
83
+ const rest = path === root ? "" : path.slice(root.length + 1);
84
+ if ("keep" in one && !one.keep.some((entry) => (entry.endsWith("/") ? rest.startsWith(entry) : rest === entry))) return undefined;
85
+ return rest === "" ? one.snapshot : `${one.snapshot}/${rest}`;
86
+ }
87
+ return undefined;
88
+ }
89
+
90
+ /** The commit the snapshot was taken at. */
91
+ export function sourceOf(upstream: string = UPSTREAM_DIR): UpstreamSource {
92
+ return JSON.parse(readFileSync(join(upstream, "SOURCE.json"), "utf8")) as UpstreamSource;
93
+ }
94
+
95
+ /** The files of a snapshot, as paths from its folder with `/`, sorted. */
96
+ export function snapshotFiles(upstream: string = UPSTREAM_DIR): string[] {
97
+ const found: string[] = [];
98
+ const walk = (dir: string, prefix: string): void => {
99
+ for (const name of readdirSync(dir).sort()) {
100
+ const path = join(dir, name);
101
+ if (statSync(path).isDirectory()) walk(path, `${prefix}${name}/`);
102
+ else found.push(`${prefix}${name}`);
103
+ }
104
+ };
105
+ walk(upstream, "");
106
+ return found.sort();
107
+ }
108
+
109
+ /** The names of the playbooks of a snapshot, sorted. */
110
+ export function playbookNames(upstream: string = UPSTREAM_DIR): string[] {
111
+ return readdirSync(join(upstream, "poteto-mode", "playbooks"))
112
+ .filter((file) => file.endsWith(".md"))
113
+ .map((file) => basename(file, ".md"))
114
+ .sort();
115
+ }
116
+
117
+ /**
118
+ * Take a new snapshot from an upstream checkout (the `pstack` folder of `cursor/plugins`) at a commit, the checkout's
119
+ * HEAD by default: the snapshot is replaced whole, so a file upstream removed goes too. A checkout that lacks what a
120
+ * snapshot needs is refused before anything is replaced.
121
+ */
122
+ export function refreshUpstream(checkout: string, into: { upstream?: string; commit?: string } = {}): UpstreamSource {
123
+ const upstream = into.upstream ?? UPSTREAM_DIR;
124
+ const git = new Git(checkout);
125
+ const commit = git.resolve(into.commit ?? "HEAD");
126
+ if (commit === undefined) throw new Error(`${checkout} has no commit ${into.commit ?? "HEAD"}: it is not a git checkout of upstream`);
127
+ const files = new Map<string, string>();
128
+ for (const one of SNAPSHOT_PATHS) {
129
+ for (const path of git.list(commit, one.from)) {
130
+ const file = snapshotPathOf(path.split("\\").join("/"));
131
+ const text = file === undefined ? undefined : git.show(commit, path);
132
+ if (file !== undefined && text !== undefined) files.set(file, text);
133
+ }
134
+ }
135
+ const playbooks = [...files.keys()].filter((file) => file.startsWith("poteto-mode/playbooks/"));
136
+ for (const needed of ["LICENSE", "poteto-mode/SKILL.md", "poteto-mode/worker.md"]) {
137
+ if (!files.has(needed)) throw new Error(`${checkout} is not an upstream pstack checkout at ${commit}: ${checkoutPathOf(needed)} is missing`);
138
+ }
139
+ if (playbooks.length === 0) throw new Error(`${checkout} is not an upstream pstack checkout at ${commit}: it has no playbooks`);
140
+ const source: UpstreamSource = { repository: "https://github.com/cursor/plugins", path: "pstack", commit };
141
+ // The mapping belongs to the snapshot's folder and survives a refresh; the old files go.
142
+ const kept = existsSync(join(upstream, "mapping.json")) ? readFileSync(join(upstream, "mapping.json"), "utf8") : undefined;
143
+ rmSync(upstream, { recursive: true, force: true });
144
+ for (const [file, text] of files) {
145
+ mkdirSync(dirname(join(upstream, file)), { recursive: true });
146
+ writeFileSync(join(upstream, file), text);
147
+ }
148
+ writeFileSync(join(upstream, "SOURCE.json"), `${JSON.stringify(source, null, 2)}\n`);
149
+ if (kept !== undefined) writeFileSync(join(upstream, "mapping.json"), kept);
150
+ return source;
151
+ }