docks-kit 0.22.11 → 0.22.12

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/AGENTS.md CHANGED
@@ -88,9 +88,9 @@ omp SoT notes:
88
88
  - `SoT/.omp/AGENTS.md` carries the rule `Please remove all mannered prose.` Anthropic's Fable 5.1 prompting guide documents mannered prose as a Fable 5.1 behavior and gives that sentence as its short-version fix: https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5-1
89
89
  - `cli/docs/omp-models.md` (topic `omp-models`) records the role map rationale and the Artificial Analysis snapshot behind it. Model choices change with published benchmarks, so update that topic in the same commit as a role change.
90
90
  - `SoT/.omp/config.yml` sets `compaction.thresholdTokens` to `-1`, omp's schema default sentinel selecting reserve-based behavior: the trigger becomes `contextWindow` minus `max(floor(contextWindow * 0.15), 16384)`, which is 231,200 on the 272,000-token Codex window and 850,000 on the 1,000,000-token Anthropic window. The key ships as `-1` rather than being deleted because `ompYaml.ts mergeOmpConfig` is additive, so removing a key from SoT never removes it from a deployed file. `cli/docs/omp-context.md` (topic `omp-context`) carries the derivation and the measured evidence, so update that topic in the same commit as any compaction-setting change.
91
- - Sync registers the `docks` marketplace. It installs or upgrades `docks@docks` and `plan-lifecycle@docks` at user scope.
91
+ - Sync registers the `docks` marketplace. It installs or upgrades `docks@docks` and `plan-lifecycle@docks` at user scope. omp deletes the previous plugin folder on upgrade, so running omp sessions lose that plugin's agents and skill script paths. When an upgrade changes a version, `ompPlugins.ts syncPlugins, upgrade log` warns, sets the `ompPluginUpgraded` next-step trigger, and writes one event file into `~/.cache/docks-kit/omp-plugin-upgrades/`. If the versions cannot be read after the upgrade, it warns once more, and each upgrade counts as a change to the version `unknown`. A failed write of the log only warns; it does not fail the sync. The log keeps the newest 100 event files; `cli/docs/sync-layers.md` gives the file format and the limits.
92
92
  - Sync installs `pi-intercom` at the verified version from `SoT/toolchain.json`.
93
- - Sync materializes the kit omp plugin `docks-kit-omp` from `SoT/.omp/plugin/` to `~/.docks-kit/omp-plugin` (`ompKitPlugin.ts syncKitPlugin`: directories 0700, files 0600, `package.json` `version` set to the kit version, stale files removed, no backups because the directory is kit-owned). `ompPlugins.ts syncPlugins, kit plugin link` then runs `omp plugin link <dir>` unless the `omp plugin list --json` npm row `docks-kit-omp` already has a `path` that resolves to that directory; `--skip-plugin-refresh` does not skip the link. The plugin extension registers `scratch_new`, `scratch_remove`, and `tidy_report`, adds a reminder after each bash command that created a resource, checks at session stop that those resources are gone, and at a main-session start claims `~/.cache/docks-kit/tidy.stamp.claim` and runs `docks-kit tidy --apply` in the background at most once per 12 hours. Every extension subprocess runs without a shell. The plugin also ships the `workspace-hygiene` skill and the `/cleanup` command. The plugin, the deployed rules, and the sweep call `docks-kit scratch` and `docks-kit tidy`, so a checkout sync must not run before the global `docks-kit` carries those commands.
93
+ - Sync materializes the kit omp plugin `docks-kit-omp` from `SoT/.omp/plugin/` to `~/.docks-kit/omp-plugin` (`ompKitPlugin.ts syncKitPlugin`: directories 0700, files 0600, `package.json` `version` set to the kit version, stale files removed, no backups because the directory is kit-owned). `ompPlugins.ts syncPlugins, kit plugin link` then runs `omp plugin link <dir>` unless the `omp plugin list --json` npm row `docks-kit-omp` already has a `path` that resolves to that directory; `--skip-plugin-refresh` does not skip the link. The `hygiene.ts` extension registers `scratch_new`, `scratch_remove`, and `tidy_report`. It adds a reminder after each bash command that created a resource, and it checks at session stop that those resources are gone. At a main-session start, it claims `~/.cache/docks-kit/tidy.stamp.claim` and runs `docks-kit tidy --apply` in the background at most once per 12 hours. Every extension subprocess runs without a shell. The `pluginUpgrades.ts` extension reads the omp plugin upgrade log. In a tool result of each main session, it adds one reminder for the logged upgrades that the session did not get before. It names only the upgrades that finished after its omp process started. The reminder tells the agent to ask the user to restart omp. omp imports extensions only at startup. An omp process that started before a sync deployed `pluginUpgrades.ts` did not load it, so its sessions get no reminder. The plugin also ships the `workspace-hygiene` skill and the `/cleanup` command. The plugin, the deployed rules, and the sweep call `docks-kit scratch` and `docks-kit tidy`. So a checkout sync must not run before the global `docks-kit` carries those commands.
94
94
  - `task.agentIdleTtlMs` is `120000`, so omp parks an idle subagent after 2 minutes instead of 7. `browser.idleCloseSec` is `600`.
95
95
  - By owner decision (0.21.0), resources on the workstation are always development, so `docks-kit tidy` sweeps them without a question. The omp agent prompt, the `workspace-hygiene` skill, `/cleanup`, and the extension reminders limit the cleanup of a remote resource (reached through SSH or a provider CLI such as `wrangler`, `vercel`, `kubectl`, or a remote Docker host) to targets named local, development, dev, test, homolog, homologation, staging, or preview, the plan-lifecycle non-production definition. A production cleanup needs an `ask` immediately before it, must be rare, and a `yolo` invocation does not answer that ask. Prompt rules cannot force an agent to ask, so this rule has no `bash.patterns` guard.
96
96
  - The omp CLI is upstream-owned. It updates through `omp update`, or through the external manager that owns the install, such as Tern or Nix. `omp update` refuses to run on an install that an external manager owns. Sync never installs or upgrades the CLI.
@@ -84,7 +84,59 @@ config-root registry lists `docks`, omp copies it forward itself: the sync runs
84
84
  plugin operation, the sync reads the inventory again and prints one line that
85
85
  names each plugin with its version change, for example
86
86
  `omp plugins synced: docks@docks 0.21.1 -> 0.22.0, pi-intercom 0.14.0 (new), docks-kit-omp linked`.
87
- A dry run invokes no omp subcommand.
87
+ omp deletes the previous plugin folder on `omp plugin upgrade`. A running omp
88
+ session then loses the plugin agents and skill script paths of that folder. For
89
+ each marketplace upgrade that changed the version, the sync prints a warning,
90
+ for example
91
+ `omp plugin docks@docks 0.21.1 -> 0.22.0: running omp sessions lose its plugin agents and skill script paths until they restart.`
92
+ The next step then says
93
+ `Restart running omp sessions: a plugin upgrade removed the plugin folders that they loaded.`
94
+ The sync also writes one event file for each such upgrade into the upgrade log
95
+ `~/.cache/docks-kit/omp-plugin-upgrades/` (folder 0700, files 0600). The file
96
+ name is `<finishedAt ms>-<random>.json`, and the file holds
97
+ `{"version":1,"id":"<id>","before":"<v>","after":"<v>","finishedAt":"<ISO time>"}`.
98
+ `finishedAt` is the time just after the upgrade command returned. Each sync
99
+ writes only new files, through a temporary name and a rename, so concurrent
100
+ syncs keep all events. Then it removes the oldest files beyond the newest 100.
101
+
102
+ If the inventory read after the operations fails, the sync cannot see the new
103
+ versions. It then warns
104
+ `omp plugin versions could not be read after the upgrade — each upgraded plugin counts as changed`.
105
+ Each upgrade of a present marketplace plugin then counts as a change. It gets
106
+ the warning and an event with the after version `unknown`, for example
107
+ `docks@docks 0.21.1 -> unknown`.
108
+
109
+ A failed write or prune of the upgrade log does not fail the sync, because it
110
+ is not a harness CLI operation. A failed write warns
111
+ `omp plugin upgrade log not written: <error> — running omp sessions get no reminder for these upgrades and must restart`.
112
+ The summary line, the upgrade warnings, and the next step stay. A failed prune
113
+ keeps the new events and warns
114
+ `omp plugin upgrade log not pruned: <error> — it can keep more than 100 event files`.
115
+
116
+ The kit plugin extension `pluginUpgrades.ts` reads the upgrade log. In each
117
+ tool result of a main omp session, it takes the events that finished after
118
+ its omp process started. It adds one reminder for the events that the session
119
+ did not get before. The reminder names each plugin with its version change. It
120
+ says that the session may still use the removed folders. It tells the agent to
121
+ ask the user to restart omp. A folder or file that the extension cannot read
122
+ gives no reminder for that tool result. The next tool result reads it again.
123
+ These limits apply:
124
+
125
+ - omp imports extension modules only at startup. An omp process that started
126
+ before a sync deployed `pluginUpgrades.ts` did not load it. Its sessions get
127
+ no reminder, also for the upgrades of that sync.
128
+ - An upgrade that `docks-kit sync` did not run gives no reminder, for example
129
+ `omp plugin upgrade` by hand.
130
+ - The warning, the next step, and the reminder assume that the session loaded
131
+ the user-scope install. omp keeps an old cache folder that a known project
132
+ registry still uses. So a session on a project-scope install keeps its
133
+ folder. For this reason, the reminder says "may".
134
+ - An omp process that started during the upgrade can get a reminder that it
135
+ does not need. A restart is harmless.
136
+ - The log keeps the newest 100 events. A session that stays idle through more
137
+ than 100 later upgrades loses the oldest ones.
138
+
139
+ A dry run invokes no omp subcommand and writes no upgrade event.
88
140
 
89
141
  Paths mirror upstream `dirs.ts` `DirResolver`, resolved from the environment
90
142
  plus directory probes, so a dry run still runs no omp subcommand. The agent
@@ -60,6 +60,8 @@ export interface Ctx {
60
60
  codexRestart: boolean;
61
61
  skillsRestart: boolean;
62
62
  ompRestart: boolean;
63
+ /** A marketplace plugin upgrade changed a version, so running omp sessions lost its folder. */
64
+ ompPluginUpgraded: boolean;
63
65
  };
64
66
  /** Harness-CLI operations that failed this run; a non-empty list fails the sync. */
65
67
  readonly failures: Array<string>;
@@ -148,6 +150,7 @@ export function makeCtx(services: EngineServices, options: CtxOptions): Ctx {
148
150
  codexRestart: false,
149
151
  skillsRestart: false,
150
152
  ompRestart: false,
153
+ ompPluginUpgraded: false,
151
154
  },
152
155
  failures: [],
153
156
  };
@@ -3,18 +3,36 @@
3
3
  * pinned pi-intercom npm plugin, and the link of the kit plugin that
4
4
  * `ompKitPlugin.ts syncKitPlugin` writes. Split from ompSync.ts; the
5
5
  * orchestration still lives there.
6
+ *
7
+ * omp deletes the previous plugin folder on `omp plugin upgrade`, so a running
8
+ * omp session loses the plugin agents and skill script paths of that folder.
9
+ * For each version change, the pass warns and writes one event file into the
10
+ * upgrade log. When the versions cannot be read after the upgrade, each
11
+ * upgrade counts as a change to the version `unknown`. A failed log write
12
+ * gives a warning, not a sync failure. The kit plugin extension
13
+ * `pluginUpgrades.ts` reads that log.
6
14
  */
7
- import { realpathSync } from "node:fs";
15
+ import { randomBytes } from "node:crypto";
16
+ import { chmodSync, mkdirSync, readdirSync, realpathSync, unlinkSync } from "node:fs";
8
17
 
9
- import { processFailureSummary, spawnProcess } from "./exec";
18
+ import { replaceFile } from "./atomicWrite";
19
+ import { p, processFailureSummary, spawnProcess } from "./exec";
10
20
  import { recordFailure } from "./failures";
11
21
  import type { Ctx } from "./index";
12
22
  import { isObject, parseJson } from "./jq";
13
23
  import { KIT_PLUGIN_NAME, kitPluginDir } from "./ompKitPlugin";
24
+ import { kitCacheDir } from "./scratch";
14
25
  import { field } from "./toolchain";
15
26
 
16
27
  const MARKETPLACE_PLUGIN_IDS = ["docks@docks", "plan-lifecycle@docks"] as const;
17
28
 
29
+ /** The upgrade log keeps this number of the newest event files. */
30
+ const UPGRADE_EVENTS_KEPT = 100;
31
+ /** An event file name: the `finishedAt` time in milliseconds, a random part, and `.json`. */
32
+ const UPGRADE_EVENT_FILE = /^(\d+)-[0-9a-f]+\.json$/;
33
+ /** The version of an upgrade event when the inventory read did not give it. */
34
+ const UNKNOWN_VERSION = "unknown";
35
+
18
36
  // -------------------------------------------------------------- plugins ----
19
37
 
20
38
  interface InstalledNpmPlugin {
@@ -29,20 +47,35 @@ interface InstalledPlugins {
29
47
  readonly npm: Map<string, InstalledNpmPlugin>;
30
48
  }
31
49
 
50
+ /** The fields of an install or upgrade that the sync summary line needs. */
51
+ interface VersionedOperation {
52
+ readonly id: string;
53
+ /**
54
+ * Whether the inventory listed the plugin before the operation, or
55
+ * undefined when that inventory could not be read.
56
+ */
57
+ readonly present: boolean | undefined;
58
+ readonly before: string | undefined;
59
+ }
60
+
32
61
  /** One successful plugin operation, named in the sync summary line. */
33
62
  type PluginOperation =
34
- | {
35
- readonly kind: "marketplace" | "npm";
36
- readonly id: string;
37
- /**
38
- * Whether the inventory listed the plugin before the operation, or
39
- * undefined when that inventory could not be read.
40
- */
41
- readonly present: boolean | undefined;
42
- readonly before: string | undefined;
43
- }
63
+ | (VersionedOperation & {
64
+ readonly kind: "marketplace";
65
+ /** The time in milliseconds just after the omp command returned. */
66
+ readonly finishedAt: number;
67
+ })
68
+ | (VersionedOperation & { readonly kind: "npm" })
44
69
  | { readonly kind: "link"; readonly id: string };
45
70
 
71
+ /** One marketplace plugin upgrade that changed the installed version or can have changed it. */
72
+ interface PluginUpgrade {
73
+ readonly id: string;
74
+ readonly before: string;
75
+ readonly after: string;
76
+ readonly finishedAt: number;
77
+ }
78
+
46
79
  /** The version of the first entry that reports one; a marketplace row has no top-level version. */
47
80
  function marketplaceEntryVersion(entries: unknown): string | undefined {
48
81
  if (!Array.isArray(entries)) return undefined;
@@ -136,6 +169,87 @@ function realPath(path: string): string | undefined {
136
169
  }
137
170
  }
138
171
 
172
+ /**
173
+ * The marketplace upgrades that changed the version or can have changed it.
174
+ * `after` is the inventory read after all operations. When that read failed,
175
+ * each upgrade of a present plugin counts as a change to `unknown`.
176
+ */
177
+ function versionChanges(
178
+ operations: ReadonlyArray<PluginOperation>,
179
+ after: InstalledPlugins | undefined,
180
+ ): Array<PluginUpgrade> {
181
+ const upgrades: Array<PluginUpgrade> = [];
182
+ for (const operation of operations) {
183
+ // Only `omp plugin upgrade` removes a folder, and only a present plugin gets that command.
184
+ if (operation.kind !== "marketplace" || operation.present !== true) continue;
185
+ const { id, before, finishedAt } = operation;
186
+ if (after === undefined) {
187
+ upgrades.push({ id, before: before ?? UNKNOWN_VERSION, after: UNKNOWN_VERSION, finishedAt });
188
+ continue;
189
+ }
190
+ const version = after.marketplace.get(id);
191
+ if (before === undefined || version === undefined || version === before) continue;
192
+ upgrades.push({ id, before, after: version, finishedAt });
193
+ }
194
+ return upgrades;
195
+ }
196
+
197
+ /** Removes the oldest event files beyond the newest UPGRADE_EVENTS_KEPT. */
198
+ function pruneUpgradeLog(dir: string): void {
199
+ const events = readdirSync(dir).flatMap((name) => {
200
+ const match = UPGRADE_EVENT_FILE.exec(name);
201
+ return match === null ? [] : [{ name, finishedAt: Number(match[1]) }];
202
+ });
203
+ events.sort((a, b) => a.finishedAt - b.finishedAt || (a.name < b.name ? -1 : 1));
204
+ for (const event of events.slice(0, Math.max(0, events.length - UPGRADE_EVENTS_KEPT))) {
205
+ try {
206
+ unlinkSync(p(dir, event.name));
207
+ } catch (error) {
208
+ // A concurrent sync removed the same file first.
209
+ const code = typeof error === "object" && error !== null && "code" in error ? error.code : "";
210
+ if (code !== "ENOENT") throw error;
211
+ }
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Writes one new event file for each upgrade, then prunes the log. A writer
217
+ * creates only its own files, so concurrent syncs keep the events of each other.
218
+ * Returns a warning when a step fails. It does not throw, because the
219
+ * upgrades are already done and the sync must still give its restart advice.
220
+ */
221
+ function recordUpgrades(home: string, upgrades: ReadonlyArray<PluginUpgrade>): string | undefined {
222
+ // The kit plugin extension `pluginUpgrades.ts` reads the same folder.
223
+ const dir = p(kitCacheDir(home), "omp-plugin-upgrades");
224
+ try {
225
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
226
+ chmodSync(dir, 0o700);
227
+ for (const upgrade of upgrades) {
228
+ const event = {
229
+ version: 1,
230
+ id: upgrade.id,
231
+ before: upgrade.before,
232
+ after: upgrade.after,
233
+ finishedAt: new Date(upgrade.finishedAt).toISOString(),
234
+ };
235
+ const name = `${upgrade.finishedAt}-${randomBytes(8).toString("hex")}.json`;
236
+ // replaceFile writes a temporary name in the same folder and renames it into place.
237
+ replaceFile(p(dir, name), `${JSON.stringify(event)}\n`, { mode: 0o600 });
238
+ }
239
+ } catch (error) {
240
+ const detail = error instanceof Error ? error.message : String(error);
241
+ return `omp plugin upgrade log not written: ${detail} — running omp sessions get no reminder for these upgrades and must restart`;
242
+ }
243
+ try {
244
+ pruneUpgradeLog(dir);
245
+ } catch (error) {
246
+ // The events are written, so the sessions still get their reminders.
247
+ const detail = error instanceof Error ? error.message : String(error);
248
+ return `omp plugin upgrade log not pruned: ${detail} — it can keep more than ${UPGRADE_EVENTS_KEPT} event files`;
249
+ }
250
+ return undefined;
251
+ }
252
+
139
253
  export async function syncPlugins(ctx: Ctx): Promise<number> {
140
254
  const { change, clearProgress, echo, progress, verbose, warn } = ctx.services.logger;
141
255
 
@@ -199,12 +313,16 @@ export async function syncPlugins(ctx: Ctx): Promise<number> {
199
313
  const args = present
200
314
  ? ["plugin", "upgrade", "--scope", "user", pluginId]
201
315
  : ["plugin", "install", "--scope", "user", pluginId];
202
- if (await runPluginCommand(ctx, pluginId, args)) {
316
+ const succeeded = await runPluginCommand(ctx, pluginId, args);
317
+ // The operation boundary: an omp process that started later loaded the new folder.
318
+ const finishedAt = Date.now();
319
+ if (succeeded) {
203
320
  operations.push({
204
321
  kind: "marketplace",
205
322
  id: pluginId,
206
323
  present: installed === undefined ? undefined : present,
207
324
  before: installed?.marketplace.get(pluginId),
325
+ finishedAt,
208
326
  });
209
327
  if (!present) pluginsInstalled++;
210
328
  }
@@ -255,6 +373,22 @@ export async function syncPlugins(ctx: Ctx): Promise<number> {
255
373
  const items = operations.map((operation) => describeOperation(operation, after));
256
374
  change(`omp plugins synced: ${items.join(", ")}`);
257
375
  ctx.nextStepTriggers.ompRestart = true;
376
+ const upgrades = versionChanges(operations, after);
377
+ if (after === undefined && upgrades.length > 0) {
378
+ warn(
379
+ "omp plugin versions could not be read after the upgrade — each upgraded plugin counts as changed",
380
+ );
381
+ }
382
+ for (const upgrade of upgrades) {
383
+ warn(
384
+ `omp plugin ${upgrade.id} ${upgrade.before} -> ${upgrade.after}: running omp sessions lose its plugin agents and skill script paths until they restart.`,
385
+ );
386
+ }
387
+ if (upgrades.length > 0) {
388
+ ctx.nextStepTriggers.ompPluginUpgraded = true;
389
+ const logFailure = recordUpgrades(ctx.home, upgrades);
390
+ if (logFailure !== undefined) warn(logFailure);
391
+ }
258
392
  } else {
259
393
  verbose("omp plugins already in sync");
260
394
  }
@@ -104,6 +104,11 @@ export function ompSummary(ctx: Ctx, state: OmpState): void {
104
104
  }
105
105
 
106
106
  export function ompNextSteps(ctx: Ctx): Array<string> {
107
+ if (ctx.nextStepTriggers.ompPluginUpgraded) {
108
+ return [
109
+ "Restart running omp sessions: a plugin upgrade removed the plugin folders that they loaded.",
110
+ ];
111
+ }
107
112
  return ctx.verbose || ctx.nextStepTriggers.ompRestart
108
113
  ? ["Restart omp to load any refreshed plugins, skills, or tools."]
109
114
  : [];
@@ -1,7 +1,7 @@
1
1
  // Generated by cli/scripts/generate-sot-payload.ts. DO NOT EDIT.
2
2
  // Edit SoT/, notification.mp3, or package.json, then run: bun cli/scripts/generate-sot-payload.ts
3
3
 
4
- export const GENERATED_PACKAGE_VERSION = "0.22.11"
4
+ export const GENERATED_PACKAGE_VERSION = "0.22.12"
5
5
 
6
6
  export const GENERATED_PAYLOAD_TEXT = {
7
7
  "SoT/.agents/skills.txt": "# Universal AI-agent skill manifest intentionally empty.\n# Global skill discovery is opt-in: add one slug per installed skill: <owner>/<repo>@<skill-name> (or a path to one skill directory).\n# EngineNative ignores comments and blank lines.\n",
@@ -22,8 +22,9 @@ export const GENERATED_PAYLOAD_TEXT = {
22
22
  "SoT/.omp/intercom.json": "{\n \"brokerCommand\": \"bun\",\n \"brokerArgs\": []\n}\n",
23
23
  "SoT/.omp/mcp.json": "{\n \"$schema\": \"https://raw.githubusercontent.com/can1357/oh-my-pi/main/packages/coding-agent/src/config/mcp-schema.json\",\n \"disabledServers\": [\n \"chrome-devtools\",\n \"context7:context7\",\n \"openaiDeveloperDocs\"\n ]\n}\n",
24
24
  "SoT/.omp/models.yml": "providers:\n openai-codex:\n modelOverrides:\n gpt-6-astra:\n thinking:\n mode: effort\n efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n defaultLevel: xhigh\n",
25
- "SoT/.omp/plugin/package.json": "{\n \"name\": \"docks-kit-omp\",\n \"version\": \"0.0.0\",\n \"private\": true,\n \"type\": \"module\",\n \"description\": \"docks-kit integration for omp: workspace hygiene tools, reminders, and the automatic tidy sweep\",\n \"omp\": { \"extensions\": [\"./extensions/hygiene.ts\"] }\n}\n",
25
+ "SoT/.omp/plugin/package.json": "{\n \"name\": \"docks-kit-omp\",\n \"version\": \"0.0.0\",\n \"private\": true,\n \"type\": \"module\",\n \"description\": \"docks-kit integration for omp: workspace hygiene tools, reminders, the automatic tidy sweep, and plugin upgrade reminders\",\n \"omp\": { \"extensions\": [\"./extensions/hygiene.ts\", \"./extensions/pluginUpgrades.ts\"] }\n}\n",
26
26
  "SoT/.omp/plugin/extensions/hygiene.ts": "/**\n * docks-kit-omp extension: workspace hygiene for omp sessions.\n *\n * - The tools scratch_new, scratch_remove, and tidy_report run docks-kit.\n * - The tool_result handler records each resource that a bash command\n * creates, and it adds a reminder that names the cleanup command.\n * - The session_stop handler lists the recorded resources that still exist.\n * - The session_start handler of a main session starts `docks-kit tidy --apply`\n * in the background, at most one time in each sweep interval.\n *\n * The module imports only node: modules, so omp loads it without a package\n * install. No subprocess uses a command interpreter, so a tool argument never\n * gets to a shell.\n */\nimport { execFile, spawn } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport {\n accessSync,\n chmodSync,\n closeSync,\n constants,\n existsSync,\n mkdirSync,\n openSync,\n readFileSync,\n statSync,\n unlinkSync,\n utimesSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, isAbsolute, join, posix, resolve, win32 } from \"node:path\";\n\n// ------------------------------------------------------------- constants ----\n\nconst SWEEP_INTERVAL_MS = 12 * 60 * 60 * 1000;\nconst CLAIM_STALE_MS = 60 * 1000;\nconst STAMP_FILE = \"tidy.stamp\";\nconst CLAIM_FILE = \"tidy.stamp.claim\";\nconst TAKEOVER_FILE = \"tidy.stamp.takeover\";\nconst DOCKER_CHECK_TIMEOUT_MS = 5000;\nconst SCRATCH_TIMEOUT_MS = 60_000;\nconst REPORT_TIMEOUT_MS = 120_000;\nconst OUTPUT_LIMIT_BYTES = 16 * 1024 * 1024;\nconst COMMAND_TEXT_LIMIT = 120;\nconst LABEL_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;\nconst LABEL_ERROR = \"label must match ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$\";\nconst NOT_ON_PATH = \"docks-kit is not on PATH; install docks-kit and run docks-kit sync omp\";\n\n/**\n * A bash command that does not match this pattern creates no tracked\n * resource. Each detection rule below has a word in this pattern.\n */\nconst TRIGGER =\n /worktree\\s+add|compose|docker|scratch\\s+new|mktemp|nohup|setsid|disown|&|tmux|screen|ngrok|cloudflared|port-forward|ssh|cluster|minikube|multipass|limactl|machine|colima|crontab|\\bat\\b|systemctl|systemd-run|launchctl|install|(?:^|\\s)-g(?:\\s|$)|global|branches|branch\\s+create|vercel|netlify|wrangler|fly\\s|fork|codespace|stash/;\n\n/** The scope of the top-level command; a subshell scope extends it with `/<n>`. */\nconst ROOT_SCOPE = \"0\";\n\nconst UNRESOLVED = /[$`*]/;\nconst ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;\nconst VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst REDIRECT_OPERATOR = /^(?:\\d+|&)?(?:<<<|<<-?|>>|>&|<&|>\\||<>|>|<)$/;\nconst ATTACHED_REDIRECT = /^(?:\\d+|&)?[<>]/;\nconst SHORT_CLUSTER_WITH_D = /^-[A-Za-z]*d[A-Za-z]*$/;\n/** The long options of GNU mktemp, which also accepts a unique prefix of each. */\nconst MKTEMP_LONG_OPTIONS: ReadonlyArray<string> = [\n \"--directory\",\n \"--dry-run\",\n \"--quiet\",\n \"--suffix\",\n \"--tmpdir\",\n \"--help\",\n \"--version\",\n];\nconst CONTAINER_ID = /^[0-9a-f]{64}$/;\nconst SAFE_WORD = /^[A-Za-z0-9_/.:@%+=,-]+$/;\nconst RESERVED_WORDS: Record<string, true> = {\n \"{\": true,\n \"}\": true,\n \"!\": true,\n if: true,\n then: true,\n else: true,\n elif: true,\n do: true,\n while: true,\n until: true,\n time: true,\n};\n\nconst GIT_VALUE_OPTIONS: Record<string, true> = { \"-C\": true, \"-c\": true };\nconst WORKTREE_VALUE_OPTIONS: Record<string, true> = { \"-b\": true, \"-B\": true, \"--reason\": true };\n/** Docker global options that select the daemon, mapped to their long names. */\nconst DOCKER_CONNECTION_VALUE_OPTIONS: Record<string, string> = {\n \"-c\": \"--context\",\n \"--context\": \"--context\",\n \"-H\": \"--host\",\n \"--host\": \"--host\",\n \"--config\": \"--config\",\n \"--tlscacert\": \"--tlscacert\",\n \"--tlscert\": \"--tlscert\",\n \"--tlskey\": \"--tlskey\",\n};\nconst DOCKER_CONNECTION_FLAGS: Record<string, true> = { \"--tls\": true, \"--tlsverify\": true };\nconst DOCKER_LOG_LEVEL_OPTIONS: Record<string, true> = { \"-l\": true, \"--log-level\": true };\n/** Environment variables that select the Docker daemon. */\nconst DOCKER_ENVIRONMENT: Record<string, true> = {\n DOCKER_HOST: true,\n DOCKER_CONTEXT: true,\n DOCKER_CONFIG: true,\n DOCKER_TLS_VERIFY: true,\n DOCKER_CERT_PATH: true,\n};\n/** Builtins that declare shell variables, with options and `NAME=value` words. */\nconst DECLARATION_COMMANDS: Record<string, true> = {\n declare: true,\n typeset: true,\n local: true,\n readonly: true,\n};\n/** Builtins that run shell code that detection does not read. */\nconst SHELL_CODE_COMMANDS: Record<string, true> = { eval: true, source: true, \".\": true };\nconst COMPOSE_VALUE_OPTIONS: Record<string, true> = {\n \"-f\": true,\n \"--file\": true,\n \"-p\": true,\n \"--project-name\": true,\n \"--project-directory\": true,\n \"--env-file\": true,\n \"--profile\": true,\n \"--ansi\": true,\n \"--progress\": true,\n};\nconst SSH_VALUE_FLAGS = \"BbcDEeFIiJLlmOoPpQRSWw\";\nconst STASH_WITHOUT_ENTRY: Record<string, true> = {\n list: true,\n show: true,\n pop: true,\n apply: true,\n drop: true,\n clear: true,\n branch: true,\n};\n\nconst RM_NOTE = \"Add `--rm` to `docker run` so that Docker removes the container when it stops.\";\nconst SCRATCH_NOTE =\n \"Create temporary files and directories inside a directory from the `scratch_new` tool or `docks-kit scratch new <label>`, not in `/tmp`.\";\nconst KEEP_SENTENCE =\n \"Remove each resource that the task no longer needs. Keep a resource only when the user asked for it or a later step needs it, and name it with the reason in your final answer. Never stop or delete a production resource without an ask in the main session.\";\n\ninterface OtherRule {\n readonly category: string;\n readonly hint: string;\n}\n\nconst BACKGROUND: OtherRule = {\n category: \"background process\",\n hint: \"Stop it before your final answer, or start it as a named bash service.\",\n};\nconst TERMINAL: OtherRule = {\n category: \"detached terminal session\",\n hint: \"Kill the session when the task no longer needs it.\",\n};\nconst TUNNEL: OtherRule = {\n category: \"tunnel\",\n hint: \"Stop the tunnel when the task no longer needs it.\",\n};\nconst CLUSTER: OtherRule = {\n category: \"cluster or virtual machine\",\n hint: \"Stop or delete it with the same tool when the task no longer needs it.\",\n};\nconst DOCKER_RESOURCE: OtherRule = {\n category: \"Docker resource\",\n hint: \"Remove it with docker volume rm, docker network rm, or docker buildx rm when the task no longer needs it.\",\n};\nconst SCHEDULED: OtherRule = {\n category: \"scheduled job or service\",\n hint: \"Remove the entry or unit that you added, or name it in your final answer.\",\n};\nconst GLOBAL_INSTALL: OtherRule = {\n category: \"global install\",\n hint: \"Uninstall it unless the user asked for it.\",\n};\nconst REMOTE: OtherRule = {\n category: \"remote resource\",\n hint: \"Delete it with the provider's command only when its target is development, test, homologation, staging, or preview, and the task no longer needs it. For a production target, ask the user first. If you do not delete it, name it in your final answer.\",\n};\nconst STASH: OtherRule = {\n category: \"git stash\",\n hint: \"Apply the stash, or name it in your final answer.\",\n};\n\nconst CLUSTER_COMMANDS: ReadonlyArray<ReadonlyArray<string>> = [\n [\"kind\", \"create\", \"cluster\"],\n [\"k3d\", \"cluster\", \"create\"],\n [\"minikube\", \"start\"],\n [\"multipass\", \"launch\"],\n [\"limactl\", \"start\"],\n [\"podman\", \"machine\", \"start\"],\n [\"colima\", \"start\"],\n];\nconst REMOTE_COMMANDS: ReadonlyArray<ReadonlyArray<string>> = [\n [\"supabase\", \"branches\", \"create\"],\n [\"neonctl\", \"branches\", \"create\"],\n [\"pscale\", \"branch\", \"create\"],\n [\"netlify\", \"deploy\"],\n [\"wrangler\", \"deploy\"],\n [\"fly\", \"deploy\"],\n [\"fly\", \"launch\"],\n [\"gh\", \"repo\", \"fork\"],\n [\"gh\", \"codespace\", \"create\"],\n];\n\n// ----------------------------------------------------------------- types ----\n\n/**\n * The Docker daemon that a command used: the `DOCKER_*` environment variables\n * and the global options before the subcommand. An empty target is the\n * default daemon of the omp process.\n */\nexport interface DockerTarget {\n environment: Record<string, string>;\n options: Array<string>;\n}\n\nexport type HygieneResource =\n | { kind: \"worktree\"; path: string }\n | { kind: \"compose\"; workingDir: string; down: string; docker: DockerTarget }\n | { kind: \"container\"; id: string; down: string; docker: DockerTarget }\n | { kind: \"scratch\"; path: string }\n | { kind: \"tempDir\"; path: string }\n | { kind: \"tempFile\"; path: string }\n | { kind: \"other\"; category: string; command: string; hint: string };\n\ntype PathResource = Exclude<HygieneResource, { kind: \"other\" }>;\n\nexport interface ShellSegment {\n words: Array<string>;\n background: boolean;\n}\n\n/** A segment with its subshell scope. A `cd` changes only its own scope. */\ninterface ScopedSegment extends ShellSegment {\n scope: string;\n}\n\nexport interface RunOptions {\n readonly signal?: AbortSignal;\n readonly timeoutMs: number;\n readonly env?: NodeJS.ProcessEnv;\n}\n\nexport interface RunResult {\n /** The exit code, or null when a signal or the timeout stopped the process. */\n readonly code: number | null;\n readonly stdout: string;\n readonly stderr: string;\n}\n\n// The local structural types below name only the omp extension API parts\n// that this module uses. The module does not import @oh-my-pi packages.\n\ninterface TextContent {\n readonly type: string;\n readonly text?: string;\n}\n\ninterface ExtensionContext {\n readonly cwd: string;\n readonly agent?: { readonly kind: \"main\" | \"sub\" };\n}\n\ninterface ToolResultEvent {\n readonly toolName: string;\n readonly input?: Readonly<Record<string, unknown>>;\n readonly content?: ReadonlyArray<TextContent>;\n readonly isError?: boolean;\n}\n\ninterface SessionStopEvent {\n readonly stop_hook_active?: boolean;\n}\n\ninterface Schema {\n describe(description: string): Schema;\n}\n\ninterface SchemaBuilder {\n object(shape: Record<string, Schema>): Schema;\n string(): Schema;\n array(item: Schema): Schema;\n}\n\ninterface ToolResult {\n content: Array<{ type: \"text\"; text: string }>;\n details: Record<string, unknown>;\n}\n\ninterface ToolDefinition<Params> {\n name: string;\n label: string;\n description: string;\n parameters: Schema;\n execute(\n toolCallId: string,\n params: Params,\n signal: AbortSignal | undefined,\n onUpdate: unknown,\n ctx: ExtensionContext,\n ): Promise<ToolResult>;\n}\n\nexport interface ExtensionApi {\n readonly zod: SchemaBuilder;\n on(\n event: \"tool_result\",\n handler: (\n event: ToolResultEvent,\n ctx: ExtensionContext,\n ) => Promise<{ additionalContext: string } | undefined>,\n ): void;\n on(\n event: \"session_stop\",\n handler: (\n event: SessionStopEvent,\n ctx: ExtensionContext,\n ) => Promise<{ continue: true; additionalContext: string } | undefined>,\n ): void;\n on(\n event: \"session_start\",\n handler: (event: unknown, ctx: ExtensionContext) => Promise<undefined>,\n ): void;\n registerTool<Params>(definition: ToolDefinition<Params>): void;\n}\n\n// ------------------------------------------------------------ subprocess ----\n\n/**\n * Runs `command` with `args` through execFile without a shell. Each argument\n * gets to the child as one literal argv entry. A non-zero exit, a signal, or\n * the timeout resolves; a spawn failure or an abort rejects.\n */\nexport function run(\n command: string,\n args: ReadonlyArray<string>,\n options: RunOptions,\n): Promise<RunResult> {\n const { promise, resolve: resolveRun, reject: rejectRun } = Promise.withResolvers<RunResult>();\n execFile(\n command,\n [...args],\n {\n encoding: \"utf8\",\n env: options.env,\n maxBuffer: OUTPUT_LIMIT_BYTES,\n shell: false,\n signal: options.signal,\n timeout: options.timeoutMs,\n windowsHide: true,\n },\n (error, stdout, stderr) => {\n if (error === null) resolveRun({ code: 0, stdout, stderr });\n else if (typeof error.code === \"number\") resolveRun({ code: error.code, stdout, stderr });\n else if (\n error.name !== \"AbortError\" &&\n (error.killed === true || (error.signal ?? null) !== null)\n ) {\n resolveRun({ code: null, stdout, stderr });\n } else rejectRun(error);\n },\n );\n return promise;\n}\n\n/**\n * Finds docks-kit on PATH. Windows accepts only `docks-kit.exe`, because\n * execFile without a shell cannot start a `.cmd` or `.bat` shim. A relative\n * PATH entry is skipped.\n */\nexport function resolveDocksKit(\n env: NodeJS.ProcessEnv = process.env,\n platform: NodeJS.Platform = process.platform,\n): string {\n const windows = platform === \"win32\";\n const paths = windows ? win32 : posix;\n const searchPath = env[\"PATH\"] ?? env[\"Path\"] ?? \"\";\n for (const entry of searchPath.split(windows ? \";\" : \":\")) {\n const directory = entry.replace(/^\"(.*)\"$/, \"$1\");\n if (directory === \"\" || !paths.isAbsolute(directory)) continue;\n const candidate = paths.join(directory, windows ? \"docks-kit.exe\" : \"docks-kit\");\n if (isRunnableFile(candidate, windows)) return candidate;\n }\n throw new Error(NOT_ON_PATH);\n}\n\nfunction isRunnableFile(path: string, windows: boolean): boolean {\n try {\n if (!statSync(path).isFile()) return false;\n if (!windows) accessSync(path, constants.X_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction errorCode(error: unknown): unknown {\n return typeof error === \"object\" && error !== null && \"code\" in error ? error.code : undefined;\n}\n\nfunction toError(error: unknown): Error {\n if (errorCode(error) === \"ENOENT\") return new Error(NOT_ON_PATH);\n return error instanceof Error ? error : new Error(String(error));\n}\n\nasync function runDocksKit(\n args: ReadonlyArray<string>,\n signal: AbortSignal | undefined,\n timeoutMs: number,\n): Promise<string> {\n const result = await run(resolveDocksKit(), args, { signal, timeoutMs });\n const output = [result.stdout.trim(), result.stderr.trim()].filter((text) => text !== \"\");\n if (result.code === 0) return result.stdout;\n const status = result.code === null ? \"was stopped\" : `exited with code ${result.code}`;\n throw new Error(\n output.length > 0 ? output.join(\"\\n\") : `docks-kit ${args.join(\" \")} ${status}`,\n );\n}\n\n// --------------------------------------------------------- shell parsing ----\n\n/**\n * Splits a bash command into simple-command segments. This is a minimal\n * tokenizer: it removes single quotes, double quotes, and backslash escapes,\n * and it splits on `&&`, `||`, `;`, `|`, `&`, parentheses, and newlines.\n * `background` is true when a single `&` ended the segment. The command of a\n * `$(...)` or backtick substitution becomes a segment before its container.\n * A heredoc body is skipped.\n */\nexport function splitShellSegments(command: string): Array<ShellSegment> {\n return scopedSegments(command, ROOT_SCOPE).map(({ words, background }) => ({\n words,\n background,\n }));\n}\n\n/**\n * Does the work of splitShellSegments, and gives each segment its subshell\n * scope. A `( ... )` group, a `$( ... )` substitution, and a backtick\n * substitution each get a new scope `<parent>/<n>`. A `{ ...; }` group stays\n * in the scope around it, as in bash.\n */\nfunction scopedSegments(command: string, rootScope: string): Array<ScopedSegment> {\n const segments: Array<ScopedSegment> = [];\n const nested: Array<ScopedSegment> = [];\n const heredocs: Array<{ delimiter: string; strip: boolean }> = [];\n const scopes = [rootScope];\n let childScopes = 0;\n let words: Array<string> = [];\n let word = \"\";\n let inWord = false;\n /** The strip flag of a `<<` operator whose delimiter is the next word. */\n let heredocOperator: boolean | undefined;\n\n const currentScope = (): string => scopes.at(-1) ?? rootScope;\n const childScope = (): string => `${currentScope()}/${childScopes++}`;\n const finishWord = (): void => {\n if (!inWord) return;\n if (heredocOperator !== undefined) {\n heredocs.push({ delimiter: word, strip: heredocOperator });\n heredocOperator = undefined;\n } else if (!word.includes(\"<<<\")) {\n const match = /^\\d*<<(-?)(.*)$/.exec(word);\n if (match !== null) {\n const strip = match[1] === \"-\";\n const delimiter = match[2] ?? \"\";\n if (delimiter === \"\") heredocOperator = strip;\n else heredocs.push({ delimiter, strip });\n }\n }\n words.push(word);\n word = \"\";\n inWord = false;\n };\n\n const finishSegment = (background: boolean): void => {\n finishWord();\n segments.push(...nested.splice(0));\n if (words.length > 0) segments.push({ words, background, scope: currentScope() });\n words = [];\n };\n\n const readSubstitution = (start: number): number => {\n let depth = 0;\n let openQuote: string | undefined;\n let index = start + 1;\n for (; index < command.length; index++) {\n const char = command[index];\n if (openQuote !== undefined) {\n if (char === \"\\\\\" && openQuote === '\"') index++;\n else if (char === openQuote) openQuote = undefined;\n continue;\n }\n if (char === \"\\\\\") index++;\n else if (char === \"'\" || char === '\"') openQuote = char;\n else if (char === \"(\") depth++;\n else if (char === \")\" && --depth === 0) break;\n }\n nested.push(...scopedSegments(command.slice(start + 2, index), childScope()));\n word += command.slice(start, index + 1);\n inWord = true;\n return index + 1;\n };\n\n const readBacktick = (start: number): number => {\n let index = start + 1;\n while (index < command.length && command[index] !== \"`\") {\n index += command[index] === \"\\\\\" ? 2 : 1;\n }\n nested.push(...scopedSegments(command.slice(start + 1, index), childScope()));\n word += command.slice(start, index + 1);\n inWord = true;\n return index + 1;\n };\n\n const readDoubleQuoted = (start: number): number => {\n let index = start;\n inWord = true;\n while (index < command.length && command[index] !== '\"') {\n const char = command[index];\n const next = command[index + 1];\n if (char === \"\\\\\" && next !== undefined && '\"\\\\$`\\n'.includes(next)) {\n if (next !== \"\\n\") word += next;\n index += 2;\n } else if (char === \"$\" && next === \"(\") {\n index = readSubstitution(index);\n } else if (char === \"`\") {\n index = readBacktick(index);\n } else {\n word += char;\n index++;\n }\n }\n return index + 1;\n };\n\n const skipHeredocBodies = (start: number): number => {\n let index = start;\n for (const { delimiter, strip } of heredocs.splice(0)) {\n while (index < command.length) {\n const newline = command.indexOf(\"\\n\", index);\n const end = newline === -1 ? command.length : newline;\n let line = command.slice(index, end);\n if (line.endsWith(\"\\r\")) line = line.slice(0, -1);\n index = end + 1;\n if ((strip ? line.replace(/^\\t+/, \"\") : line) === delimiter) break;\n }\n }\n heredocOperator = undefined;\n return index;\n };\n\n let index = 0;\n while (index < command.length) {\n const char = command[index] ?? \"\";\n const next = command[index + 1];\n if (char === \"'\") {\n const close = command.indexOf(\"'\", index + 1);\n const end = close === -1 ? command.length : close;\n word += command.slice(index + 1, end);\n inWord = true;\n index = end + 1;\n } else if (char === '\"') {\n index = readDoubleQuoted(index + 1);\n } else if (char === \"\\\\\") {\n if (next !== undefined && next !== \"\\n\") {\n word += next;\n inWord = true;\n }\n index += 2;\n } else if (char === \"$\" && next === \"(\") {\n index = readSubstitution(index);\n } else if (char === \"`\") {\n index = readBacktick(index);\n } else if (char === \" \" || char === \"\\t\" || char === \"\\r\") {\n finishWord();\n index++;\n } else if (char === \"#\" && !inWord) {\n const newline = command.indexOf(\"\\n\", index);\n index = newline === -1 ? command.length : newline;\n } else if (char === \"\\n\") {\n finishSegment(false);\n index = skipHeredocBodies(index + 1);\n } else if (char === \"(\" && !inWord) {\n finishSegment(false);\n scopes.push(childScope());\n index++;\n } else if (char === \")\") {\n finishSegment(false);\n if (scopes.length > 1) scopes.pop();\n index++;\n } else if (char === \";\") {\n finishSegment(false);\n index++;\n } else if (char === \"|\") {\n finishSegment(false);\n index += next === \"|\" || next === \"&\" ? 2 : 1;\n } else if (char === \"&\") {\n if (next === \"&\") {\n finishSegment(false);\n index += 2;\n } else if (next === \">\" || word.endsWith(\">\") || word.endsWith(\"<\")) {\n // A redirection such as `&>file` or `2>&1`.\n word += char;\n inWord = true;\n index++;\n } else {\n finishSegment(true);\n index++;\n }\n } else {\n word += char;\n inWord = true;\n index++;\n }\n }\n finishSegment(false);\n return segments;\n}\n\n/**\n * Removes redirections and leading reserved words, then splits off the\n * `NAME=value` words before the command, also after an `env`. The first of\n * the returned words is the command name. The words are empty when `sudo`\n * or an `env` option hides the command, its directory, or its Docker daemon.\n * `assignsShell` is true when the segment has only `NAME=value` words, which\n * then set shell variables.\n */\nfunction commandWords(segmentWords: ReadonlyArray<string>): {\n assignments: Array<string>;\n words: Array<string>;\n assignsShell: boolean;\n} {\n const result: Array<string> = [];\n for (let index = 0; index < segmentWords.length; index++) {\n const word = segmentWords[index] ?? \"\";\n if (REDIRECT_OPERATOR.test(word)) {\n index++;\n continue;\n }\n if (ATTACHED_REDIRECT.test(word)) continue;\n result.push(word);\n }\n const assignments: Array<string> = [];\n let start = 0;\n while (RESERVED_WORDS[result[start] ?? \"\"] === true) start++;\n while (ASSIGNMENT.test(result[start] ?? \"\")) assignments.push(result[start++] ?? \"\");\n if (start === result.length) return { assignments, words: [], assignsShell: true };\n // A command under sudo runs as another user, in an environment and a\n // directory that the sudoers policy controls, so it records nothing.\n if (result[start] === \"sudo\") return { assignments, words: [], assignsShell: false };\n if (result[start] === \"env\") {\n start++;\n // `env -u NAME` keeps the command and its directory when NAME is a literal\n // name that does not select the daemon. Another option can run another\n // program (`env -S`), change the directory (`env -C`), or clear the\n // environment (`env -i`), and `env -u DOCKER_HOST` or `env -u \"$name\"`\n // can change the daemon, so the command records nothing.\n while ((result[start] ?? \"\").startsWith(\"-\")) {\n const option = result[start] ?? \"\";\n if (option === \"--\") {\n start++;\n break;\n }\n const name = result[start + 1] ?? \"\";\n const keepsDaemon = VARIABLE_NAME.test(name) && DOCKER_ENVIRONMENT[name] !== true;\n if ((option !== \"-u\" && option !== \"--unset\") || !keepsDaemon) {\n return { assignments, words: [], assignsShell: false };\n }\n start += 2;\n }\n }\n while (ASSIGNMENT.test(result[start] ?? \"\")) assignments.push(result[start++] ?? \"\");\n return { assignments, words: result.slice(start), assignsShell: false };\n}\n\n/** Applies the `DOCKER_*=value` words of `assignments` to a copy of `environment`. */\nfunction dockerEnvironment(\n environment: Readonly<Record<string, string>>,\n assignments: ReadonlyArray<string>,\n): Record<string, string> {\n const result = { ...environment };\n for (const assignment of assignments) {\n if (!ASSIGNMENT.test(assignment)) continue;\n const equals = assignment.indexOf(\"=\");\n const variable = assignment.slice(0, equals);\n if (DOCKER_ENVIRONMENT[variable] === true) result[variable] = assignment.slice(equals + 1);\n }\n return result;\n}\n\n/** True when the `NAME` or `NAME=value` word names a variable that selects the Docker daemon. */\nfunction namesDaemonVariable(word: string): boolean {\n const equals = word.indexOf(\"=\");\n return DOCKER_ENVIRONMENT[equals < 0 ? word : word.slice(0, equals)] === true;\n}\n\n/**\n * True when detection can apply the `export` arguments: each operand is a\n * literal `NAME=value`, or a literal NAME that does not select the daemon.\n * An option such as `-n`, an operand that is not literal, or a daemon\n * variable without a value can give the daemon a value that detection does\n * not know. For example, `export DOCKER_HOST` exports a shell variable that\n * detection does not track.\n */\nfunction exportIsTracked(args: ReadonlyArray<string>): boolean {\n const operands = args[0] === \"--\" ? args.slice(1) : args;\n return operands.every(\n (word) => ASSIGNMENT.test(word) || (VARIABLE_NAME.test(word) && !namesDaemonVariable(word)),\n );\n}\n\n/**\n * Returns the variables that the `unset` arguments remove, or undefined when\n * detection cannot know them. Only `-v` and literal names keep them known:\n * `unset -f` and `unset -n` act on functions and name references, and\n * `unset \"$name\"` removes a variable that the command does not name.\n */\nfunction unsetVariables(args: ReadonlyArray<string>): ReadonlyArray<string> | undefined {\n let start = 0;\n while (args[start] === \"-v\") start++;\n if (args[start] === \"--\") start++;\n const operands = args.slice(start);\n return operands.every((word) => VARIABLE_NAME.test(word)) ? operands : undefined;\n}\n\n/**\n * True when the `declare`, `typeset`, `local`, or `readonly` arguments keep\n * the daemon variables unchanged: each word is a literal option, a literal\n * NAME, or a literal `NAME=value`, and no word names a daemon variable.\n */\nfunction declarationIsTracked(args: ReadonlyArray<string>): boolean {\n return args.every((word) => {\n if (word.startsWith(\"-\") || word.startsWith(\"+\")) return !UNRESOLVED.test(word);\n return (ASSIGNMENT.test(word) || VARIABLE_NAME.test(word)) && !namesDaemonVariable(word);\n });\n}\n\nfunction quote(word: string): string {\n return SAFE_WORD.test(word) ? word : `'${word.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\n/** Resolves a path word, or returns undefined when the word is not literal. */\nfunction resolvePath(word: string, base: string | undefined, home: string): string | undefined {\n if (UNRESOLVED.test(word)) return undefined;\n if (word === \"~\") return resolve(home);\n if (word.startsWith(\"~/\")) return resolve(home, word.slice(2));\n if (word.startsWith(\"~\")) return undefined;\n if (isAbsolute(word)) return resolve(word);\n return base === undefined ? undefined : resolve(base, word);\n}\n\nfunction changeDirectory(\n args: ReadonlyArray<string>,\n directory: string | undefined,\n home: string,\n): string | undefined {\n const target = args.find((word) => word === \"-\" || !word.startsWith(\"-\"));\n if (target === undefined) return resolve(home);\n if (target === \"-\") return undefined;\n return resolvePath(target, directory, home);\n}\n\nfunction lastAbsoluteLine(output: string): string | undefined {\n return output\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line !== \"\" && isAbsolute(line))\n .pop();\n}\n\n/** True when `sequence` occurs in `words` in order, with other words between. */\nfunction containsInOrder(words: ReadonlyArray<string>, sequence: ReadonlyArray<string>): boolean {\n let position = 0;\n for (const word of words) {\n if (word === sequence[position]) position++;\n if (position === sequence.length) return true;\n }\n return sequence.length === 0;\n}\n\nfunction matchesCommand(\n name: string,\n words: ReadonlyArray<string>,\n pattern: ReadonlyArray<string>,\n): boolean {\n return name === pattern[0] && containsInOrder(words.slice(1), pattern.slice(1));\n}\n\n/** Skips git global options and returns the effective directory and arguments. */\nfunction gitArguments(\n words: ReadonlyArray<string>,\n directory: string | undefined,\n home: string,\n): { directory: string | undefined; args: Array<string> } {\n let current = directory;\n let index = 1;\n while (index < words.length) {\n const word = words[index] ?? \"\";\n if (GIT_VALUE_OPTIONS[word] === true) {\n const value = words[index + 1];\n if (word === \"-C\") current = value === undefined ? undefined : resolvePath(value, current, home);\n index += 2;\n } else if (word.startsWith(\"-\")) {\n index++;\n } else {\n break;\n }\n }\n return { directory: current, args: words.slice(index) };\n}\n\n/**\n * Reads a docker command: the daemon target and the arguments after the\n * global options. `target` is undefined when the Docker environment is\n * unknown or a value of the target is not literal. Returns undefined for a\n * command that is not docker.\n */\nfunction dockerCommand(\n name: string,\n words: ReadonlyArray<string>,\n environment: Readonly<Record<string, string>> | undefined,\n): { target: DockerTarget | undefined; args: Array<string> } | undefined {\n if (name !== \"docker\" && name !== \"docker-compose\") return undefined;\n const target: DockerTarget = { environment: {}, options: [] };\n let literal = environment !== undefined;\n for (const [variable, value] of Object.entries(environment ?? {})) {\n if (value === \"\") continue;\n if (UNRESOLVED.test(value)) literal = false;\n target.environment[variable] = value;\n }\n if (name === \"docker-compose\") {\n return { target: literal ? target : undefined, args: [\"compose\", ...words.slice(1)] };\n }\n\n let index = 1;\n while (index < words.length && (words[index] ?? \"\").startsWith(\"-\")) {\n const word = words[index] ?? \"\";\n const equals = word.indexOf(\"=\");\n const option = equals > 0 ? word.slice(0, equals) : word;\n const longName = DOCKER_CONNECTION_VALUE_OPTIONS[option];\n if (longName !== undefined) {\n const value = equals > 0 ? word.slice(equals + 1) : words[index + 1];\n index += equals > 0 ? 1 : 2;\n if (value === undefined) break;\n if (UNRESOLVED.test(value)) literal = false;\n target.options.push(longName, value);\n } else {\n if (DOCKER_CONNECTION_FLAGS[option] === true) target.options.push(word);\n index += DOCKER_LOG_LEVEL_OPTIONS[option] === true && equals < 0 ? 2 : 1;\n }\n }\n return { target: literal ? target : undefined, args: words.slice(index) };\n}\n\n/** The docker command prefix that reaches `target`, for a cleanup command. */\nfunction dockerPrefix(target: DockerTarget): string {\n return [\n ...Object.entries(target.environment).map(([variable, value]) => `${variable}=${quote(value)}`),\n \"docker\",\n ...target.options.map(quote),\n ].join(\" \");\n}\n\nfunction sshFlags(args: ReadonlyArray<string>): Set<string> {\n const flags = new Set<string>();\n for (let index = 0; index < args.length; index++) {\n const word = args[index] ?? \"\";\n if (!word.startsWith(\"-\") || word.startsWith(\"--\") || word === \"-\") continue;\n for (let position = 1; position < word.length; position++) {\n const letter = word[position] ?? \"\";\n flags.add(letter);\n if (SSH_VALUE_FLAGS.includes(letter)) {\n if (position === word.length - 1) index++;\n break;\n }\n }\n }\n return flags;\n}\n\nfunction unresolvedNote(noun: string, command: string): string {\n return `You created a ${noun}. When the task no longer needs it, run \\`${command}\\`.`;\n}\n\n// ---------------------------------------------------------------- detect ----\n\ninterface Findings {\n readonly resource: (resource: HygieneResource) => void;\n readonly note: (note: string) => void;\n}\n\n/** The state that a `cd` or an `export` changes, one for each subshell scope. */\ninterface ScopeState {\n directory: string | undefined;\n /**\n * The `DOCKER_*` variables that the scope exported, or undefined when a\n * command changed them in a way that detection does not know. An unknown\n * environment stays unknown for the rest of the scope.\n */\n dockerEnvironment: Record<string, string> | undefined;\n}\n\n/** One simple command, with the state of its scope applied. */\ninterface CommandContext {\n readonly name: string;\n readonly words: ReadonlyArray<string>;\n readonly directory: string | undefined;\n /** The Docker environment of the command, or undefined when it is unknown. */\n readonly dockerEnvironment: Readonly<Record<string, string>> | undefined;\n}\n\n/**\n * Finds the resources that a successful bash command created. A resource\n * whose path or id is not literal in the command or the output gives a\n * generic note in place of a ledger entry.\n */\nexport function detectResources(\n command: string,\n cwd: string,\n output: string,\n home: string,\n platform: NodeJS.Platform = process.platform,\n): { resources: Array<HygieneResource>; notes: Array<string> } {\n const found = new Map<string, HygieneResource>();\n const notes: Array<string> = [];\n const findings: Findings = {\n resource: (resource) => {\n found.set(resourceKey(resource), resource);\n },\n note: (note) => {\n if (!notes.includes(note)) notes.push(note);\n },\n };\n\n // A subshell scope starts with a copy of its parent state at its first\n // command, so a `cd` or an unknown Docker environment in a subshell does\n // not change the commands after it.\n const states = new Map<string, ScopeState>([\n [ROOT_SCOPE, { directory: cwd, dockerEnvironment: {} }],\n ]);\n const stateOf = (scope: string): ScopeState => {\n const known = states.get(scope);\n if (known !== undefined) return known;\n const parent = stateOf(scope.slice(0, scope.lastIndexOf(\"/\")));\n const environment = parent.dockerEnvironment;\n const state = {\n directory: parent.directory,\n dockerEnvironment: environment === undefined ? undefined : { ...environment },\n };\n states.set(scope, state);\n return state;\n };\n\n const segments = scopedSegments(command, ROOT_SCOPE);\n // Only a command that runs alone, without a wrapper, and prints to the tool\n // output owns that output. A substitution such as `f=$(mktemp)` captures\n // what mktemp prints, a later command can print an unrelated path, a\n // wrapper such as `env` or `time` stands between the command and the\n // output, and a redirection or a process substitution sends the output\n // elsewhere, so these get the generic note.\n const sole = segments.length === 1 ? segments[0] : undefined;\n const ownPath =\n sole !== undefined && printsToOutput(sole.words) && runsWithoutWrapper(sole.words)\n ? lastAbsoluteLine(output)\n : undefined;\n for (const segment of segments) {\n const { assignments, words, assignsShell } = commandWords(segment.words);\n const first = words[0];\n if (first === undefined) {\n // `DOCKER_HOST=value` without a command changes the daemon when the\n // shell already exports DOCKER_HOST, which detection does not know.\n if (assignsShell && assignments.some(namesDaemonVariable)) {\n stateOf(segment.scope).dockerEnvironment = undefined;\n }\n continue;\n }\n const name = (first.split(/[\\\\/]/).pop() ?? first).replace(/\\.exe$/i, \"\");\n const state = stateOf(segment.scope);\n const args = words.slice(1);\n if (name === \"cd\" || name === \"pushd\") {\n state.directory = changeDirectory(args, state.directory, home);\n continue;\n }\n if (name === \"export\") {\n state.dockerEnvironment =\n state.dockerEnvironment !== undefined && exportIsTracked(args)\n ? dockerEnvironment(state.dockerEnvironment, args)\n : undefined;\n continue;\n }\n if (name === \"unset\") {\n const variables = unsetVariables(args);\n if (variables === undefined) state.dockerEnvironment = undefined;\n for (const variable of variables ?? []) delete state.dockerEnvironment?.[variable];\n continue;\n }\n if (\n SHELL_CODE_COMMANDS[name] === true ||\n (DECLARATION_COMMANDS[name] === true && !declarationIsTracked(args))\n ) {\n state.dockerEnvironment = undefined;\n }\n const context: CommandContext = {\n name,\n words,\n directory: state.directory,\n dockerEnvironment:\n state.dockerEnvironment === undefined\n ? undefined\n : dockerEnvironment(state.dockerEnvironment, assignments),\n };\n detectCreation(context, home, output, ownPath, platform, findings);\n const text = segment.words.map(quote).join(\" \").slice(0, COMMAND_TEXT_LIMIT);\n for (const rule of otherRules(context, segment.background, home)) {\n findings.resource({ kind: \"other\", category: rule.category, command: text, hint: rule.hint });\n }\n }\n return { resources: [...found.values()], notes };\n}\n\nfunction detectCreation(\n context: CommandContext,\n home: string,\n output: string,\n ownPath: string | undefined,\n platform: NodeJS.Platform,\n findings: Findings,\n): void {\n const { name, words, directory } = context;\n if (name === \"git\") {\n const git = gitArguments(words, directory, home);\n if (git.args[0] === \"worktree\" && git.args[1] === \"add\") {\n detectWorktree(git.args.slice(2), git.directory, home, findings);\n }\n return;\n }\n\n const docker = dockerCommand(name, words, context.dockerEnvironment);\n if (docker !== undefined) {\n const { target, args } = docker;\n if (args[0] === \"compose\") detectCompose(args.slice(1), target, directory, home, findings);\n else if (args[0] === \"run\") detectContainer(args.slice(1), target, output, findings);\n else if (args[0] === \"container\" && args[1] === \"run\") {\n detectContainer(args.slice(2), target, output, findings);\n }\n return;\n }\n\n if (name === \"docks-kit\" && words[1] === \"scratch\" && words[2] === \"new\") {\n if (ownPath === undefined) {\n findings.note(unresolvedNote(\"scratch directory\", \"docks-kit scratch remove <path>\"));\n } else {\n findings.resource({ kind: \"scratch\", path: ownPath });\n }\n return;\n }\n\n if (name === \"mktemp\") detectMktemp(words.slice(1), ownPath, platform, findings);\n}\n\n/** mktemp creates a file, or a directory with `-d`; a dry run (`-u`) creates nothing. */\nfunction detectMktemp(\n args: ReadonlyArray<string>,\n path: string | undefined,\n platform: NodeJS.Platform,\n findings: Findings,\n): void {\n const effect = mktempEffect(args, platform);\n if (effect === \"nothing\") return;\n const directory = effect === \"directory\";\n if (path === undefined) {\n const noun = directory ? \"temporary directory\" : \"temporary file\";\n findings.note(unresolvedNote(noun, \"docks-kit scratch remove <path>\"));\n } else {\n findings.resource({ kind: directory ? \"tempDir\" : \"tempFile\", path });\n }\n findings.note(SCRATCH_NOTE);\n}\n\n/**\n * Reads the options of an mktemp call. GNU mktemp accepts options before and\n * after the template and a unique prefix of each long option; macOS mktemp\n * takes a prefix after `-t`. An option value, the template, and every word\n * after `--` are not options, so `--suffix -upload` is no dry run.\n */\nfunction mktempEffect(\n args: ReadonlyArray<string>,\n platform: NodeJS.Platform,\n): \"file\" | \"directory\" | \"nothing\" {\n let directory = false;\n for (let index = 0; index < args.length; index++) {\n const word = args[index] ?? \"\";\n if (word === \"--\") break;\n if (!word.startsWith(\"-\") || word === \"-\") continue;\n if (word.startsWith(\"--\")) {\n const typed = word.split(\"=\", 1)[0] ?? word;\n const matches = MKTEMP_LONG_OPTIONS.filter((option) => option.startsWith(typed));\n const option = matches.includes(typed) ? typed : matches.length === 1 ? matches[0] : undefined;\n // mktemp stops on an unknown or ambiguous option, so it creates nothing.\n if (option === undefined || option === \"--dry-run\" || option === \"--help\") return \"nothing\";\n if (option === \"--version\") return \"nothing\";\n if (option === \"--directory\") directory = true;\n if (option === \"--suffix\" && !word.includes(\"=\")) index++;\n continue;\n }\n for (let at = 1; at < word.length; at++) {\n const flag = word[at];\n if (flag === \"u\") return \"nothing\";\n if (flag === \"d\") directory = true;\n if (flag === \"p\" || (flag === \"t\" && platform === \"darwin\")) {\n // `-p DIR` takes the next word; in `-pDIR` the rest of the word is the value.\n if (at === word.length - 1) index++;\n break;\n }\n }\n }\n return directory ? \"directory\" : \"file\";\n}\n\n/** True when the command of the segment is its first word after the `NAME=value` words. */\nfunction runsWithoutWrapper(words: ReadonlyArray<string>): boolean {\n const first = words.find((word) => !ASSIGNMENT.test(word));\n return first !== undefined && first === commandWords(words).words[0];\n}\n\n/** True when no word of the segment redirects its output or runs a process substitution. */\nfunction printsToOutput(words: ReadonlyArray<string>): boolean {\n return !words.some(\n (word) =>\n REDIRECT_OPERATOR.test(word) ||\n ATTACHED_REDIRECT.test(word) ||\n word.includes(\"<(\") ||\n word.includes(\">(\"),\n );\n}\n\nfunction detectWorktree(\n args: ReadonlyArray<string>,\n directory: string | undefined,\n home: string,\n findings: Findings,\n): void {\n let optionsEnded = false;\n for (let index = 0; index < args.length; index++) {\n const word = args[index] ?? \"\";\n if (!optionsEnded && word === \"--\") {\n optionsEnded = true;\n } else if (!optionsEnded && WORKTREE_VALUE_OPTIONS[word] === true) {\n index++;\n } else if (optionsEnded || !word.startsWith(\"-\") || word === \"-\") {\n const path = resolvePath(word, directory, home);\n if (path === undefined) {\n findings.note(unresolvedNote(\"git worktree\", \"git worktree remove -- <path>\"));\n } else {\n findings.resource({ kind: \"worktree\", path });\n }\n return;\n }\n }\n}\n\nfunction detectCompose(\n args: ReadonlyArray<string>,\n target: DockerTarget | undefined,\n directory: string | undefined,\n home: string,\n findings: Findings,\n): void {\n const files: Array<string> = [];\n let project: string | undefined;\n let projectDirectory: string | undefined;\n let subcommand: string | undefined;\n for (let index = 0; index < args.length; index++) {\n const word = args[index] ?? \"\";\n const equals = word.startsWith(\"-\") ? word.indexOf(\"=\") : -1;\n const option = equals > 0 ? word.slice(0, equals) : word;\n if (COMPOSE_VALUE_OPTIONS[option] === true) {\n const value = equals > 0 ? word.slice(equals + 1) : args[++index];\n if (value === undefined) break;\n if (option === \"-f\" || option === \"--file\") files.push(value);\n else if (option === \"-p\" || option === \"--project-name\") project = value;\n else if (option === \"--project-directory\") projectDirectory = value;\n } else if (!word.startsWith(\"-\")) {\n subcommand = word;\n break;\n }\n }\n if (subcommand !== \"up\" && subcommand !== \"start\") return;\n\n const unresolved = unresolvedNote(\n \"detached container\",\n \"docker compose --project-directory <path> down\",\n );\n const resolvedFiles: Array<string> = [];\n for (const file of files) {\n const path = file === \"-\" ? undefined : resolvePath(file, directory, home);\n if (path === undefined) {\n findings.note(unresolved);\n return;\n }\n resolvedFiles.push(path);\n }\n const firstFile = resolvedFiles[0];\n const workingDir =\n projectDirectory !== undefined\n ? resolvePath(projectDirectory, directory, home)\n : firstFile !== undefined\n ? dirname(firstFile)\n : directory;\n if (\n target === undefined ||\n workingDir === undefined ||\n (project !== undefined && UNRESOLVED.test(project))\n ) {\n findings.note(unresolved);\n return;\n }\n\n const down = [dockerPrefix(target), \"compose\"];\n if (project !== undefined) down.push(\"-p\", quote(project));\n if (projectDirectory !== undefined || resolvedFiles.length === 0) {\n down.push(\"--project-directory\", quote(workingDir));\n }\n for (const file of resolvedFiles) down.push(\"-f\", quote(file));\n down.push(\"down\");\n findings.resource({ kind: \"compose\", workingDir, down: down.join(\" \"), docker: target });\n}\n\nfunction detectContainer(\n args: ReadonlyArray<string>,\n target: DockerTarget | undefined,\n output: string,\n findings: Findings,\n): void {\n const detached = args.some(\n (word) => word === \"--detach\" || word === \"--detach=true\" || SHORT_CLUSTER_WITH_D.test(word),\n );\n const removesItself = args.some((word) => word === \"--rm\" || word === \"--rm=true\");\n if (detached) {\n const line = output\n .split(/\\r?\\n/)\n .map((text) => text.trim())\n .filter((text) => text !== \"\")\n .pop();\n if (target !== undefined && line !== undefined && CONTAINER_ID.test(line)) {\n const id = line.slice(0, 12);\n const prefix = dockerPrefix(target);\n const down = removesItself\n ? `${prefix} stop ${id}`\n : `${prefix} stop ${id} && ${prefix} rm ${id}`;\n findings.resource({ kind: \"container\", id, down, docker: target });\n } else {\n findings.note(unresolvedNote(\"detached container\", \"docker stop <id>\"));\n }\n }\n if (!removesItself) findings.note(RM_NOTE);\n}\n\nfunction otherRules(\n context: CommandContext,\n background: boolean,\n home: string,\n): Array<OtherRule> {\n const { name, words } = context;\n const rules: Array<OtherRule> = [];\n const args = words.slice(1);\n const has = (word: string): boolean => args.includes(word);\n const hasAny = (...candidates: Array<string>): boolean => candidates.some(has);\n const global = hasAny(\"-g\", \"--global\");\n\n if (\n background ||\n name === \"nohup\" ||\n name === \"setsid\" ||\n name === \"disown\" ||\n has(\"disown\")\n ) {\n rules.push(BACKGROUND);\n }\n\n const detachFlag = args.some((word) => SHORT_CLUSTER_WITH_D.test(word));\n if (\n ((name === \"tmux\" && hasAny(\"new\", \"new-session\")) || name === \"screen\") &&\n detachFlag\n ) {\n rules.push(TERMINAL);\n }\n\n const ssh = name === \"ssh\" ? sshFlags(args) : undefined;\n if (\n name === \"ngrok\" ||\n (name === \"cloudflared\" && has(\"tunnel\")) ||\n (name === \"kubectl\" && has(\"port-forward\")) ||\n (ssh !== undefined &&\n (ssh.has(\"L\") || ssh.has(\"R\") || ssh.has(\"D\")) &&\n (ssh.has(\"N\") || ssh.has(\"f\")))\n ) {\n rules.push(TUNNEL);\n }\n\n if (CLUSTER_COMMANDS.some((pattern) => matchesCommand(name, words, pattern))) {\n rules.push(CLUSTER);\n }\n\n const docker = dockerCommand(name, words, context.dockerEnvironment)?.args;\n if (\n docker !== undefined &&\n (docker[0] === \"volume\" || docker[0] === \"network\" || docker[0] === \"buildx\") &&\n docker[1] === \"create\"\n ) {\n rules.push(DOCKER_RESOURCE);\n }\n\n if (\n (name === \"crontab\" && !has(\"-l\")) ||\n name === \"at\" ||\n (name === \"systemctl\" && has(\"--user\") && hasAny(\"enable\", \"start\")) ||\n (name === \"systemd-run\" && has(\"--user\")) ||\n (name === \"launchctl\" && hasAny(\"load\", \"bootstrap\"))\n ) {\n rules.push(SCHEDULED);\n }\n\n if (\n (name === \"npm\" && hasAny(\"i\", \"install\") && global) ||\n (name === \"bun\" && hasAny(\"add\", \"install\", \"i\") && global) ||\n (name === \"pnpm\" && has(\"add\") && global) ||\n (name === \"yarn\" && containsInOrder(args, [\"global\", \"add\"])) ||\n (/^pip[0-9.]*$/.test(name) && has(\"install\") && has(\"--user\")) ||\n ((name === \"pipx\" || name === \"cargo\" || name === \"go\") && has(\"install\"))\n ) {\n rules.push(GLOBAL_INSTALL);\n }\n\n if (\n (name === \"vercel\" && !has(\"env\")) ||\n REMOTE_COMMANDS.some((pattern) => matchesCommand(name, words, pattern))\n ) {\n rules.push(REMOTE);\n }\n\n if (name === \"git\") {\n const git = gitArguments(words, context.directory, home);\n if (git.args[0] === \"stash\" && STASH_WITHOUT_ENTRY[git.args[1] ?? \"\"] !== true) {\n rules.push(STASH);\n }\n }\n return rules;\n}\n\n// ----------------------------------------------------------- reminders ----\n\nfunction resourceKey(resource: HygieneResource): string {\n switch (resource.kind) {\n case \"worktree\":\n case \"scratch\":\n case \"tempDir\":\n case \"tempFile\":\n return `${resource.kind}:${resource.path}`;\n case \"compose\":\n return `compose:${dockerPrefix(resource.docker)}:${resource.workingDir}`;\n case \"container\":\n return `container:${dockerPrefix(resource.docker)}:${resource.id}`;\n case \"other\":\n return `other:${resource.category}:${resource.command}`;\n }\n}\n\nfunction describeResource(resource: PathResource): string {\n switch (resource.kind) {\n case \"worktree\":\n return `the worktree ${resource.path}`;\n case \"compose\":\n return `the compose project in ${resource.workingDir}`;\n case \"container\":\n return `the container ${resource.id}`;\n case \"scratch\":\n return `the scratch directory ${resource.path}`;\n case \"tempDir\":\n return `the temporary directory ${resource.path}`;\n case \"tempFile\":\n return `the temporary file ${resource.path}`;\n }\n}\n\nexport function cleanupCommand(resource: HygieneResource): string {\n switch (resource.kind) {\n case \"worktree\":\n return `git worktree remove -- ${quote(resource.path)}`;\n case \"compose\":\n case \"container\":\n return resource.down;\n case \"scratch\":\n case \"tempDir\":\n case \"tempFile\":\n return `docks-kit scratch remove ${quote(resource.path)}`;\n case \"other\":\n return resource.hint;\n }\n}\n\nexport function creationReminder(resource: HygieneResource): string {\n if (resource.kind === \"other\") {\n return `This command created a ${resource.category} (\\`${resource.command}\\`). ${resource.hint}`;\n }\n return `You created ${describeResource(resource)}. When the task no longer needs it, run \\`${cleanupCommand(resource)}\\`.`;\n}\n\nfunction stopLine(resource: HygieneResource): string {\n if (resource.kind === \"other\") {\n return `- ${resource.category}: \\`${resource.command}\\` (${resource.hint})`;\n }\n return `- ${describeResource(resource)}: run \\`${cleanupCommand(resource)}\\``;\n}\n\nexport function stopReminder(\n verified: ReadonlyArray<HygieneResource>,\n unverified: ReadonlyArray<HygieneResource>,\n): string {\n const lines: Array<string> = [];\n if (verified.length > 0) {\n lines.push(\"These resources from this session still exist:\", ...verified.map(stopLine));\n }\n if (unverified.length > 0) {\n lines.push(\n \"These commands from this session may have left something running, installed, or created:\",\n ...unverified.map(stopLine),\n );\n }\n lines.push(KEEP_SENTENCE);\n return lines.join(\"\\n\");\n}\n\n// ----------------------------------------------------------------- sweep ----\n\nexport function sweepDue(stampMtimeMs: number | undefined, nowMs: number): boolean {\n return stampMtimeMs === undefined || nowMs - stampMtimeMs >= SWEEP_INTERVAL_MS;\n}\n\nfunction mtimeMs(path: string): number | undefined {\n try {\n return statSync(path).mtimeMs;\n } catch {\n return undefined;\n }\n}\n\nfunction removeIfPresent(path: string): void {\n try {\n unlinkSync(path);\n } catch (error) {\n if (errorCode(error) !== \"ENOENT\") throw error;\n }\n}\n\n/**\n * Creates `path` with `wx` and writes an owner token into it. Returns the\n * token, or undefined when the file exists.\n */\nfunction createOwned(path: string): string | undefined {\n let descriptor: number;\n try {\n descriptor = openSync(path, \"wx\", 0o600);\n } catch (error) {\n if (errorCode(error) === \"EEXIST\") return undefined;\n throw error;\n }\n const token = `${process.pid} ${randomUUID()}`;\n try {\n writeFileSync(descriptor, token);\n } finally {\n closeSync(descriptor);\n }\n return token;\n}\n\n/** Removes `path` only when it still holds `token`, so that no process removes the file of another. */\nfunction releaseOwned(path: string, token: string): void {\n try {\n if (readFileSync(path, \"utf8\") === token) unlinkSync(path);\n } catch (error) {\n if (errorCode(error) !== \"ENOENT\") throw error;\n }\n}\n\n/** True when `path` is missing or older than CLAIM_STALE_MS: its process stopped. */\nfunction isStale(path: string, nowMs: number): boolean {\n const mtime = mtimeMs(path);\n return mtime === undefined || nowMs - mtime > CLAIM_STALE_MS;\n}\n\n/**\n * Creates the claim and returns its token, or returns undefined when another\n * process holds it. Only the holder of the takeover mutex replaces a stale\n * claim, and it checks the claim again while it holds the mutex. Thus two\n * processes cannot both replace the same stale claim.\n */\nfunction acquireClaim(cacheDir: string, nowMs: number): string | undefined {\n const claim = join(cacheDir, CLAIM_FILE);\n const token = createOwned(claim);\n if (token !== undefined || !isStale(claim, nowMs)) return token;\n\n const takeover = join(cacheDir, TAKEOVER_FILE);\n let mutex = createOwned(takeover);\n if (mutex === undefined && isStale(takeover, nowMs)) {\n removeIfPresent(takeover);\n mutex = createOwned(takeover);\n }\n if (mutex === undefined) return undefined;\n try {\n if (!isStale(claim, nowMs)) return undefined;\n removeIfPresent(claim);\n return createOwned(claim);\n } finally {\n releaseOwned(takeover, mutex);\n }\n}\n\n/**\n * Lets one process in each sweep interval start the sweep. The process that\n * holds `tidy.stamp.claim` reads the stamp again. When the sweep is still\n * due, it writes the stamp and returns true. It always releases its claim.\n */\nexport function claimSweep(cacheDir: string, nowMs: number): boolean {\n mkdirSync(cacheDir, { recursive: true, mode: 0o700 });\n chmodSync(cacheDir, 0o700);\n const token = acquireClaim(cacheDir, nowMs);\n if (token === undefined) return false;\n try {\n const stamp = join(cacheDir, STAMP_FILE);\n if (!sweepDue(mtimeMs(stamp), nowMs)) return false;\n writeFileSync(stamp, \"\", { mode: 0o600 });\n chmodSync(stamp, 0o600);\n const seconds = nowMs / 1000;\n utimesSync(stamp, seconds, seconds);\n return true;\n } finally {\n releaseOwned(join(cacheDir, CLAIM_FILE), token);\n }\n}\n\n// ---------------------------------------------------------------- ledger ----\n\n/**\n * One omp process shares module state across its sessions, so the main\n * session also sees the resources that its subagents created.\n */\nconst ledger = new Map<string, HygieneResource>();\nconst reminded = new Set<string>();\n\nasync function dockerListsAny(\n target: DockerTarget,\n args: ReadonlyArray<string>,\n): Promise<boolean> {\n try {\n const result = await run(\"docker\", [...target.options, ...args], {\n env: { ...process.env, ...target.environment },\n timeoutMs: DOCKER_CHECK_TIMEOUT_MS,\n });\n return result.code === 0 && result.stdout.trim() !== \"\";\n } catch {\n return false;\n }\n}\n\nasync function stillExists(resource: HygieneResource): Promise<boolean> {\n switch (resource.kind) {\n case \"worktree\":\n case \"scratch\":\n case \"tempDir\":\n case \"tempFile\":\n return existsSync(resource.path);\n case \"compose\":\n return dockerListsAny(resource.docker, [\n \"ps\",\n \"-q\",\n \"--filter\",\n `label=com.docker.compose.project.working_dir=${resource.workingDir}`,\n ]);\n case \"container\":\n return dockerListsAny(resource.docker, [\"ps\", \"-aq\", \"--filter\", `id=${resource.id}`]);\n case \"other\":\n return true;\n }\n}\n\nfunction textResult(text: string, details: Record<string, unknown>): ToolResult {\n return { content: [{ type: \"text\", text }], details };\n}\n\n// ------------------------------------------------------------- extension ----\n\nexport default function docksKitOmp(pi: ExtensionApi): void {\n const z = pi.zod;\n\n pi.registerTool<{ label: string }>({\n name: \"scratch_new\",\n label: \"Scratch New\",\n description:\n \"Create a private temporary directory under the docks-kit scratch root and return its path. Use it instead of /tmp, also for a single temporary file. Remove it with scratch_remove when the task no longer needs it.\",\n parameters: z.object({\n label: z.string().describe(\"Short name: letters, digits, dot, underscore, or hyphen\"),\n }),\n async execute(_toolCallId, params, signal) {\n try {\n if (!LABEL_PATTERN.test(params.label)) throw new Error(LABEL_ERROR);\n const output = await runDocksKit(\n [\"scratch\", \"new\", params.label],\n signal,\n SCRATCH_TIMEOUT_MS,\n );\n const path = lastAbsoluteLine(output);\n if (path === undefined) throw new Error(`docks-kit scratch new printed no path: ${output}`);\n const resource: HygieneResource = { kind: \"scratch\", path };\n ledger.set(resourceKey(resource), resource);\n return textResult(path, { path });\n } catch (error) {\n throw toError(error);\n }\n },\n });\n\n pi.registerTool<{ paths: Array<string> }>({\n name: \"scratch_remove\",\n label: \"Scratch Remove\",\n description:\n \"Remove temporary files and directories that you created. Use it instead of gio trash, which does not work on a tmpfs /tmp. Accepts only absolute paths inside the docks-kit scratch root, the system temporary directory, or /var/tmp; refuses every other path.\",\n parameters: z.object({\n paths: z.array(z.string()).describe(\"Absolute paths\"),\n }),\n async execute(_toolCallId, params, signal) {\n try {\n if (params.paths.length === 0) throw new Error(\"paths must not be empty\");\n const relative = params.paths.find((path) => !isAbsolute(path));\n if (relative !== undefined) throw new Error(`path must be absolute: ${relative}`);\n const output = await runDocksKit(\n [\"scratch\", \"remove\", ...params.paths],\n signal,\n SCRATCH_TIMEOUT_MS,\n );\n return textResult(output.trim(), { paths: params.paths });\n } catch (error) {\n throw toError(error);\n }\n },\n });\n\n pi.registerTool<Record<string, never>>({\n name: \"tidy_report\",\n label: \"Tidy Report\",\n description:\n \"List agent leftovers and other disk and memory use (worktrees, containers, orphaned processes, scratch, /tmp, caches, Trash, branches, scheduled jobs, global installs). Read-only.\",\n parameters: z.object({}),\n async execute(_toolCallId, _params, signal) {\n try {\n const output = await runDocksKit([\"tidy\", \"--report\"], signal, REPORT_TIMEOUT_MS);\n return textResult(output.trim(), {});\n } catch (error) {\n throw toError(error);\n }\n },\n });\n\n pi.on(\"tool_result\", async (event, ctx) => {\n try {\n if (event.toolName !== \"bash\" || event.isError === true) return undefined;\n const command = event.input?.[\"command\"];\n if (typeof command !== \"string\" || !TRIGGER.test(command)) return undefined;\n const cwd = resolve(ctx.cwd, String(event.input?.[\"cwd\"] ?? \".\"));\n const output = (event.content ?? [])\n .map((block) => (block.type === \"text\" && typeof block.text === \"string\" ? block.text : \"\"))\n .join(\"\\n\");\n const { resources, notes } = detectResources(command, cwd, output, homedir());\n for (const resource of resources) ledger.set(resourceKey(resource), resource);\n const lines = [...resources.map(creationReminder), ...notes];\n return lines.length === 0 ? undefined : { additionalContext: lines.join(\"\\n\") };\n } catch {\n return undefined;\n }\n });\n\n pi.on(\"session_stop\", async (event) => {\n try {\n if (event.stop_hook_active === true) return undefined;\n const pending = [...ledger].filter(([key]) => !reminded.has(key));\n if (pending.length === 0) return undefined;\n const states = await Promise.all(\n pending.map(async ([key, resource]) => ({\n key,\n resource,\n exists: await stillExists(resource),\n })),\n );\n const verified: Array<HygieneResource> = [];\n const unverified: Array<HygieneResource> = [];\n for (const { key, resource, exists } of states) {\n if (!exists) {\n ledger.delete(key);\n continue;\n }\n reminded.add(key);\n if (resource.kind === \"other\") unverified.push(resource);\n else verified.push(resource);\n }\n if (verified.length === 0 && unverified.length === 0) return undefined;\n return { continue: true, additionalContext: stopReminder(verified, unverified) };\n } catch {\n return undefined;\n }\n });\n\n pi.on(\"session_start\", async (_event, ctx) => {\n try {\n if (ctx.agent?.kind === \"sub\") return undefined;\n // The same directory as kitCacheDir in the docks-kit CLI.\n const cacheDir = join(homedir(), \".cache\", \"docks-kit\");\n const now = Date.now();\n if (!sweepDue(mtimeMs(join(cacheDir, STAMP_FILE)), now)) return undefined;\n const docksKit = resolveDocksKit();\n if (!claimSweep(cacheDir, now)) return undefined;\n const child = spawn(docksKit, [\"tidy\", \"--apply\"], {\n cwd: homedir(),\n detached: true,\n shell: false,\n stdio: \"ignore\",\n windowsHide: true,\n });\n child.on(\"error\", () => {});\n child.unref();\n } catch {\n // A sweep that cannot start must not stop the session.\n }\n return undefined;\n });\n}\n",
27
+ "SoT/.omp/plugin/extensions/pluginUpgrades.ts": "/**\n * docks-kit-omp extension: plugin upgrade reminders for omp sessions.\n *\n * omp deletes the previous plugin folder on `omp plugin upgrade`. A running\n * omp session keeps the plugin folders that it found at startup. So its plugin\n * agents and skill script paths can fail after an upgrade. `docks-kit sync`\n * writes one event file for each upgrade that changed a version, or that can\n * have changed it (the version `unknown`).\n *\n * In each tool_result of a main session, this extension reads the events that\n * finished after this omp process started. It adds one reminder for the events\n * that the session did not get before. A folder or file that it cannot read\n * gives no reminder for that tool result. The next tool result reads it again.\n *\n * The module imports only node: modules, so omp loads it without a package\n * install.\n */\nimport { readdirSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\n// ------------------------------------------------------------- constants ----\n\n/**\n * The start of this omp process. omp finds the plugin folders before it\n * imports extension modules, so a later upgrade can remove a loaded folder.\n */\nconst PROCESS_START_MS = Date.now() - process.uptime() * 1000;\n\n/** An event file name that `docks-kit sync` writes; a temporary name does not match. */\nconst EVENT_FILE = /^\\d+-[0-9a-f]+\\.json$/;\n/** A plugin id or version that the reminder can name without a quote. */\nconst SAFE_TOKEN = /^[A-Za-z0-9._@+-]+$/;\n\n// ----------------------------------------------------------- omp API types ----\n\n// The local structural types below name only the omp extension API parts\n// that this module uses. The module does not import @oh-my-pi packages.\n\ninterface ExtensionContext {\n readonly agent?: { readonly kind: \"main\" | \"sub\" };\n readonly sessionManager?: { getSessionId(): string };\n}\n\nexport interface ExtensionApi {\n on(\n event: \"tool_result\",\n handler: (\n event: unknown,\n ctx: ExtensionContext,\n ) => Promise<{ additionalContext: string } | undefined>,\n ): void;\n}\n\n// ---------------------------------------------------------------- events ----\n\n/** One plugin upgrade that `docks-kit sync` recorded. */\nexport interface PluginUpgradeEvent {\n readonly id: string;\n readonly before: string;\n readonly after: string;\n /** The time in milliseconds just after the upgrade command returned. */\n readonly finishedAtMs: number;\n}\n\n/** The upgrade log folder; `ompPlugins.ts syncPlugins` in the docks-kit CLI writes it. */\nexport function upgradeLogDir(home: string): string {\n return join(home, \".cache\", \"docks-kit\", \"omp-plugin-upgrades\");\n}\n\n/** The event in one event file, or undefined when the file is not a version 1 event. */\nexport function parseUpgradeEvent(text: string): PluginUpgradeEvent | undefined {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n return undefined;\n }\n if (typeof value !== \"object\" || value === null) return undefined;\n const { version, id, before, after, finishedAt } = value as Record<string, unknown>;\n if (version !== 1) return undefined;\n if (typeof id !== \"string\" || typeof before !== \"string\" || typeof after !== \"string\") {\n return undefined;\n }\n if (![id, before, after].every((token) => SAFE_TOKEN.test(token))) return undefined;\n const finishedAtMs = typeof finishedAt === \"string\" ? Date.parse(finishedAt) : Number.NaN;\n if (!Number.isFinite(finishedAtMs)) return undefined;\n return { id, before, after, finishedAtMs };\n}\n\n/** The reminder that names each upgrade. */\nexport function upgradeReminder(events: ReadonlyArray<PluginUpgradeEvent>): string {\n const upgrades = events.map((event) => `${event.id} ${event.before} -> ${event.after}`);\n return [\n `docks-kit sync upgraded these omp plugins after this omp process started: ${upgrades.join(\", \")}.`,\n \"omp removes the old plugin folder on upgrade.\",\n \"This session may still use the removed folders, so its plugin agents and skill script paths may fail.\",\n \"You must ask the user to restart omp.\",\n ].join(\" \");\n}\n\n// ------------------------------------------------------------- extension ----\n\nexport interface PluginUpgradesOptions {\n /** The home folder that holds the upgrade log. */\n readonly home: string;\n /** Events that finished at or before this time give no reminder. */\n readonly processStartMs: number;\n}\n\n/** The extension factory for one home folder and one process start. */\nexport function pluginUpgrades(options: PluginUpgradesOptions): (pi: ExtensionApi) => void {\n const dir = upgradeLogDir(options.home);\n /** Each event file read so far; undefined marks a file whose content is not an event. */\n const read = new Map<string, PluginUpgradeEvent | undefined>();\n /** For each session id, the event files that its reminders named. */\n const told = new Map<string, Set<string>>();\n\n /** The events of the log. Each file name is read until one read succeeds. */\n function currentEvents(): Array<{ name: string; event: PluginUpgradeEvent }> {\n let names: Array<string>;\n try {\n names = readdirSync(dir).filter((name) => EVENT_FILE.test(name));\n } catch {\n // A missing folder holds no events. Another error gives no events now,\n // and the next tool result reads the folder again.\n return [];\n }\n const present = new Set(names);\n // Sync prunes old files, so the cache forgets the names that are gone.\n for (const name of read.keys()) if (!present.has(name)) read.delete(name);\n const events: Array<{ name: string; event: PluginUpgradeEvent }> = [];\n for (const name of names) {\n if (!read.has(name)) {\n let text: string;\n try {\n text = readFileSync(join(dir, name), \"utf8\");\n } catch {\n // A prune removed the file (ENOENT), or the read failed for now.\n // The name stays out of the cache, so the next tool result reads it again.\n continue;\n }\n read.set(name, parseUpgradeEvent(text));\n }\n const event = read.get(name);\n if (event !== undefined) events.push({ name, event });\n }\n return events;\n }\n\n return (pi) => {\n pi.on(\"tool_result\", async (_event, ctx) => {\n try {\n if (ctx.agent?.kind !== \"main\") return undefined;\n const sessionId = ctx.sessionManager?.getSessionId();\n if (sessionId === undefined || sessionId === \"\") return undefined;\n const toldSession = told.get(sessionId) ?? new Set<string>();\n const fresh = currentEvents()\n .filter(\n ({ name, event }) =>\n event.finishedAtMs > options.processStartMs && !toldSession.has(name),\n )\n .sort(\n (a, b) => a.event.finishedAtMs - b.event.finishedAtMs || (a.name < b.name ? -1 : 1),\n );\n if (fresh.length === 0) return undefined;\n for (const { name } of fresh) toldSession.add(name);\n told.set(sessionId, toldSession);\n return { additionalContext: upgradeReminder(fresh.map(({ event }) => event)) };\n } catch {\n return undefined;\n }\n });\n };\n}\n\nexport default function docksKitPluginUpgrades(pi: ExtensionApi): void {\n pluginUpgrades({ home: homedir(), processStartMs: PROCESS_START_MS })(pi);\n}\n",
27
28
  "SoT/.omp/plugin/skills/workspace-hygiene/SKILL.md": "---\nname: workspace-hygiene\ndescription: Use when a task creates or ends with worktrees, temporary files or directories, servers, watchers, test runners, containers, clusters, tunnels, scheduled jobs, global installs, or remote test resources, or when disk or memory fills up. Says where to create each resource and how to remove it. Not for git history cleanup or dead-code removal.\n---\n\n# Workspace hygiene\n\n<constraint>\nRemove only what this task created. Never delete user data, named Docker volumes, or anything outside the classes in this skill. In the main session, ask the user first; in a subagent, list the item in your final report. Every local workstation resource is a development resource. Stop or delete a production resource only after an `ask` in the main session; see Production resources.\n</constraint>\n\n## Track what you create\n\nWhile you work, keep a list of each resource that you create.\nFor each resource, write its path, id, port, or remote name.\n\n## Resource classes\n\n| Class | Create | Remove | Keep when |\n|---|---|---|---|\n| Git worktree | `<data>/agent-worktrees/<repo>/<name>`; reuse a worktree of the same branch | `git worktree remove -- <path>`, then `git worktree prune`; one `--force` only after the commits are on the remote and the changes are generated files | its pull request is open |\n| Temporary file or directory | a directory from `scratch_new` or `docks-kit scratch new <label>`; each temporary file inside it; never `/tmp` | `scratch_remove`, or `docks-kit scratch remove <path>`; `gio trash` does not work on a `tmpfs` `/tmp` | a later step reads it |\n| Test artifacts (coverage, test results, traces, screenshots, videos) | inside the worktree, git-ignored | removed with the worktree; in the user's checkout, `gio trash -- <path>` | the user asked for them |\n| Server, watcher, test runner, browser | named bash service or async job; single-run tests | `write proc://<id>/kill`; outside omp, `kill <pid>` | the user asked for it |\n| Container or compose stack | `docker run --rm`; `docker compose up` in the worktree; no restart policy | `docker compose down`; `docker stop <id>`; on a remote Docker host, only for a development target; ask first for production | its worktree is kept |\n| Docker volume, network, or buildx builder that the task created | only for the task | `docker volume rm`, `docker network rm`, `docker buildx rm` | never |\n| Cluster or virtual machine | only on request | the tool's stop or delete command; for a remote cluster, only for a development target; ask first for production | the user asked for it |\n| Tunnel or port forward | named bash service | stop the local service; delete a remote tunnel only for a development target; ask first for production | the user asked for it |\n| Detached terminal session | do not create | `tmux kill-session -t <name>`, `screen -S <name> -X quit` | never |\n| Scheduled job or service | only on request | remove the entry or unit | the user asked for it |\n| Global install | only on request | the matching uninstall command | the user asked for it |\n| Git stash or local branch | avoid stash; one branch per plan | apply the stash; `git branch -d <branch>` after the merge | the branch has an open pull request |\n| Remote test resource (database branch, preview deployment, fork, cloud instance) | only for the task | the provider's delete command, only for a development or preview target; ask first for production | the user asked for it |\n| Package or tool cache | never in `/tmp` | do not prune; report the size | always |\n\n## Production resources\n\n- A local workstation resource is always a development resource. This includes worktrees, local compose stacks, local servers and processes, scratch directories, and temporary files and directories. Remove it as this skill says, without an additional question.\n- A remote resource is a resource that you reach through SSH or a provider CLI, for example `wrangler`, `vercel`, `netlify`, `fly`, `supabase`, `neonctl`, `pscale`, `kubectl`, or `gh`. A Docker host that `DOCKER_HOST`, `DOCKER_CONTEXT`, or `docker --context` selects is also remote.\n- A remote target is a development target only when its name is `local`, `development`, `dev`, `test`, `homolog`, `homologation`, `staging`, or `preview`. Every other target is production.\n- Clean up a remote resource with a development target as this skill says.\n- Stop, remove, undeploy, or delete a production resource only after an `ask` in the main session immediately before the action. Do this rarely. A yolo run does not answer this ask.\n- In a subagent, never clean up a production resource. Name it in your final report.\n- Example: `wrangler delete` without `--env` acts on the top-level Worker. That Worker is usually production, so ask first.\n\n## Before your final answer\n\n1. Find each resource of your list in the table.\n2. Remove each resource that the task no longer needs. Use the command in the `Remove` column.\n3. Name each resource that you keep, and give the reason from the `Keep when` column.\n\n## Find what you cannot see\n\nRun the `tidy_report` tool, or run `docks-kit tidy --report`.\nAct only on the items that this task created.\nReport the other items to the user.\n\n## Plan runs\n\n- For a plan run, follow the Teardown rule in the `plan-lifecycle` plan contract (`plan-manager/references/plan-contract.md`). That rule decides when the run stops stacks and processes, removes the linked worktree, deletes the branch, and keeps a resource.\n\n## Automatic sweep\n\nOne time in 12 hours, a main session starts `docks-kit tidy --apply`.\nThe sweep removes merged idle worktrees and their containers.\nIt stops orphaned processes in agent directories.\nIt removes scratch directories that are idle for 7 days.\nDo not rely on the sweep for a resource that the task can remove itself.\n",
28
29
  "SoT/.omp/plugin/commands/cleanup.md": "---\ndescription: Remove what this session created and list other leftovers\n---\nFollow the workspace-hygiene skill. List each resource that this session created. Remove each one that the task no longer needs. Remove only local resources and remote resources whose target is not production. For a production resource, ask first, and keep it if you get no answer. Then run tidy_report, and report the items that this session did not create without removing them.\n"
29
30
  } as const
@@ -53,9 +54,10 @@ export const GENERATED_PAYLOAD_PATHS = [
53
54
  "SoT/.omp/models.yml",
54
55
  "SoT/.omp/plugin/package.json",
55
56
  "SoT/.omp/plugin/extensions/hygiene.ts",
57
+ "SoT/.omp/plugin/extensions/pluginUpgrades.ts",
56
58
  "SoT/.omp/plugin/skills/workspace-hygiene/SKILL.md",
57
59
  "SoT/.omp/plugin/commands/cleanup.md",
58
60
  "notification.mp3"
59
61
  ] as const
60
62
 
61
- export const GENERATED_PAYLOAD_HASH = "4b028aa77b7e0e293f6de7f9c3021e862cd6e381886f15cbd7b0503f2fd17521"
63
+ export const GENERATED_PAYLOAD_HASH = "5f2337513404a602ee0f22f93d476aa724a0aa83533b47f444bdad4e1acee6f5"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "docks-kit",
3
- "version": "0.22.11",
3
+ "version": "0.22.12",
4
4
  "description": "Portable AI coding agent config kit — SoT sync engine + typed CLI for Claude Code, Codex, and universal agent skills",
5
5
  "type": "module",
6
6
  "license": "MIT",