@phren/cli 0.3.79 → 0.3.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/bridge/dispatch.js +17 -3
  2. package/dist/bridge/housekeeping/command.d.ts +5 -0
  3. package/dist/bridge/housekeeping/command.js +106 -0
  4. package/dist/bridge/housekeeping/housekeeper.d.ts +123 -0
  5. package/dist/bridge/housekeeping/housekeeper.js +459 -0
  6. package/dist/bridge/housekeeping/inventory.d.ts +145 -0
  7. package/dist/bridge/housekeeping/inventory.js +276 -0
  8. package/dist/bridge/housekeeping/report.d.ts +672 -0
  9. package/dist/bridge/housekeeping/report.js +168 -0
  10. package/dist/bridge/housekeeping/safety.d.ts +177 -0
  11. package/dist/bridge/housekeeping/safety.js +466 -0
  12. package/dist/bridge/owner-proof.js +1 -0
  13. package/dist/bridge/push.js +3 -1
  14. package/dist/bridge/resources.d.ts +8 -0
  15. package/dist/bridge/resources.js +18 -5
  16. package/dist/bridge/server-pane-routes.d.ts +6 -0
  17. package/dist/bridge/server-pane-routes.js +1 -1
  18. package/dist/bridge/server-routes.d.ts +5 -0
  19. package/dist/bridge/server-routes.js +44 -3
  20. package/dist/bridge/server.js +44 -8
  21. package/dist/bridge-hook.mjs +2982 -1226
  22. package/dist/cli-registry.js +18 -1
  23. package/dist/fanout/command.js +42 -15
  24. package/dist/heavy/budget-status.d.ts +26 -0
  25. package/dist/heavy/budget-status.js +26 -0
  26. package/dist/heavy/budget.d.ts +39 -0
  27. package/dist/heavy/budget.js +57 -0
  28. package/dist/heavy/command.d.ts +15 -0
  29. package/dist/heavy/command.js +119 -0
  30. package/dist/heavy/reap.d.ts +70 -0
  31. package/dist/heavy/reap.js +211 -0
  32. package/dist/heavy/slots.d.ts +58 -0
  33. package/dist/heavy/slots.js +142 -0
  34. package/dist/modules/registry.js +5 -4
  35. package/package.json +1 -1
  36. package/starter/global/skills/conductor/SKILL.md +10 -0
  37. package/starter/global/skills/fanout/SKILL.md +30 -0
@@ -0,0 +1,168 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { z } from "zod";
3
+ /**
4
+ * The housekeeping report. A pass produces a stored report (every item it
5
+ * found, with its section); `GET /v1/housekeeping` serves a view of it shaped
6
+ * for the phone (warnings, suggestions, kept, cleaned), minus dismissed items.
7
+ * The view's schema below is the contract: docs/housekeeping.md documents it,
8
+ * fixtures/conformance/housekeeping-*.json exercise it, and the apps decode
9
+ * those fixtures. Add fields freely; change or remove one only with `schema` + 1.
10
+ */
11
+ export const SCHEMA = 1;
12
+ export const AREAS = ["memory", "disk", "sessions", "worktrees", "simulators", "docker"];
13
+ const iso = z.string().datetime({ offset: true });
14
+ const paneSchema = z.object({
15
+ target: z.object({ server: z.string(), workspace: z.string().optional(), tab: z.string().optional(), pane: z.string() }).passthrough(),
16
+ label: z.string().optional(),
17
+ });
18
+ const targetSchema = z.object({
19
+ path: z.string().optional(), repo: z.string().optional(), branch: z.string().optional(),
20
+ pid: z.number().int().optional(), udid: z.string().optional(), name: z.string().optional(),
21
+ });
22
+ const area = z.enum(AREAS);
23
+ const severity = z.enum(["high", "warn", "info"]);
24
+ export const warningSchema = z.object({
25
+ id: z.string(), area, severity, title: z.string(), detail: z.string(), since: iso,
26
+ fix: z.string().optional(), pane: paneSchema.optional(), session: z.string().optional(), dispatch: z.string().optional(), notify: z.boolean().optional(),
27
+ });
28
+ export const suggestionSchema = z.object({
29
+ id: z.string(), area, kind: z.string(), title: z.string(), target: targetSchema, reason: z.string(), evidence: z.array(z.string()),
30
+ sizeBytes: z.number().optional(), actionLabel: z.string(), since: iso,
31
+ pane: paneSchema.optional(), session: z.string().optional(), dispatch: z.string().optional(),
32
+ });
33
+ export const keptSchema = z.object({ id: z.string(), area, title: z.string(), target: targetSchema, reason: z.string() });
34
+ export const cleanedSchema = z.object({
35
+ id: z.string(), at: iso, area, kind: z.string(), title: z.string(), target: targetSchema,
36
+ freedBytes: z.number(), reportedBytes: z.number().optional(), by: z.enum(["auto", "phone", "conductor", "cli"]),
37
+ });
38
+ export const dismissedSchema = z.object({ id: z.string(), section: z.enum(["warnings", "suggestions", "kept"]), area, title: z.string(), dismissedAt: iso });
39
+ const actionSchema = z.object({ id: z.string(), kind: z.string(), label: z.string(), allowed: z.boolean(), reason: z.string().optional(), confirm: z.string().optional() });
40
+ /** Everything on the computer the owner may handle, with `?inventory=1` (inventory.ts). */
41
+ export const inventorySchema = z.object({
42
+ collectedAt: iso, durationMs: z.number(), scanning: z.boolean().optional(), stale: z.boolean().optional(),
43
+ worktrees: z.array(z.object({
44
+ id: z.string(), repo: z.string(), branch: z.string().optional(), path: z.string(), main: z.boolean(), sizeBytes: z.number().optional(), lastCommitAt: iso.optional(),
45
+ dirty: z.number(), untracked: z.number(), unpushed: z.number(), stashes: z.number(), inProgress: z.string().optional(), locked: z.literal(true).optional(),
46
+ sessions: z.array(z.object({ pane: paneSchema, agent: z.string().optional(), title: z.string().optional() })),
47
+ processes: z.array(z.object({ pid: z.number(), command: z.string().optional() })),
48
+ action: actionSchema,
49
+ })),
50
+ space: z.array(z.object({
51
+ id: z.string(), area, kind: z.string(), title: z.string(), path: z.string().optional(), udid: z.string().optional(), sizeBytes: z.number(),
52
+ lastUsedAt: iso.optional(), inUse: z.string().optional(), note: z.string().optional(), action: actionSchema.optional(),
53
+ })),
54
+ sessions: z.array(z.object({
55
+ id: z.string(), pane: paneSchema, agent: z.string().optional(), title: z.string().optional(), project: z.string().optional(), status: z.string().optional(),
56
+ idleSeconds: z.number().optional(), cwd: z.string().optional(), dispatch: z.string().optional(), role: z.string().optional(),
57
+ receipt: z.object({ id: z.string(), returnRead: z.boolean() }).optional(), action: actionSchema,
58
+ })),
59
+ errors: z.array(z.object({ check: z.string(), message: z.string() })).optional(),
60
+ });
61
+ export const viewSchema = z.object({
62
+ /** Which Hook answered (added by the route). */
63
+ computer: z.object({ id: z.string(), name: z.string(), aliases: z.array(z.string()) }).optional(),
64
+ schema: z.literal(SCHEMA),
65
+ revision: z.string(),
66
+ generatedAt: iso,
67
+ nextCheckAt: iso.optional(),
68
+ health: z.object({
69
+ load1: z.number(), cores: z.number(), memoryUsedBytes: z.number(), memoryTotalBytes: z.number(),
70
+ memoryPressure: z.enum(["normal", "warn", "critical"]), diskFreeBytes: z.number(), diskTotalBytes: z.number(), tmpBytes: z.number().optional(),
71
+ }),
72
+ warnings: z.array(warningSchema),
73
+ suggestions: z.array(suggestionSchema),
74
+ kept: z.array(keptSchema),
75
+ cleaned: z.array(cleanedSchema),
76
+ dismissed: z.array(dismissedSchema).optional(),
77
+ /** Only with `?inventory=1`, and only once the first scan finished. */
78
+ inventory: inventorySchema.optional(),
79
+ errors: z.array(z.object({ check: z.string(), message: z.string() })).optional(),
80
+ });
81
+ export const approveResultSchema = z.object({
82
+ results: z.array(z.object({ id: z.string(), status: z.enum(["done", "refused", "failed", "gone", "started"]), reason: z.string().optional(), freedBytes: z.number().optional() })),
83
+ revision: z.string(),
84
+ });
85
+ export const badgeSchema = z.object({ revision: z.string(), warnings: z.number(), suggestions: z.number(), worst: severity.nullable(), freedTodayBytes: z.number() });
86
+ export function itemId(kind, target, fingerprint) {
87
+ const identity = [kind, target.path ?? "", target.repo ?? "", target.branch ?? "", target.pid ?? "", target.udid ?? "", target.name ?? "", fingerprint];
88
+ return createHash("sha256").update(JSON.stringify(identity)).digest("hex").slice(0, 16);
89
+ }
90
+ /** Only a cache may be cleaned without the owner; anything else proposing `auto` becomes a suggestion. */
91
+ export function clampSection(kind, section) {
92
+ return section === "auto" && kind !== "cache" ? "suggestion" : section;
93
+ }
94
+ export function healthOf(resources) {
95
+ const total = resources.memory.totalBytes;
96
+ const available = resources.memory.availablePercent;
97
+ return {
98
+ load1: resources.cpu.load1, cores: resources.cpu.cores,
99
+ memoryUsedBytes: available === undefined ? 0 : Math.round(total * (1 - available / 100)), memoryTotalBytes: total,
100
+ memoryPressure: resources.memory.pressure ?? "normal",
101
+ diskFreeBytes: resources.disk?.freeBytes ?? 0, diskTotalBytes: resources.disk?.totalBytes ?? 0,
102
+ };
103
+ }
104
+ const RANK = { high: 0, warn: 1, info: 2 };
105
+ export function buildReport(input) {
106
+ const before = new Map((input.previous?.items ?? []).map(item => [item.id, item]));
107
+ const generatedAt = new Date(input.finishedAt).toISOString();
108
+ const items = [];
109
+ const seen = new Set();
110
+ for (const draft of input.drafts) {
111
+ const id = draft.id ?? itemId(draft.kind, draft.target, draft.fingerprint);
112
+ if (seen.has(id))
113
+ continue;
114
+ seen.add(id);
115
+ const section = clampSection(draft.kind, draft.section);
116
+ const prior = before.get(id);
117
+ // A fixed id (a health finding) is the same item only while its fingerprint holds.
118
+ const since = prior && prior.fingerprint === draft.fingerprint ? prior.since : generatedAt;
119
+ items.push({ ...draft, id, section, since });
120
+ }
121
+ items.sort((a, b) => RANK[a.severity ?? "info"] - RANK[b.severity ?? "info"] || (b.sizeBytes ?? 0) - (a.sizeBytes ?? 0) || a.title.localeCompare(b.title));
122
+ return {
123
+ version: 1, id: randomBytes(6).toString("hex"), computer: input.computer, generatedAt, trigger: input.trigger,
124
+ durationMs: Math.max(0, input.finishedAt - input.startedAt), health: input.health, items,
125
+ ...(input.errors?.length ? { errors: input.errors } : {}),
126
+ };
127
+ }
128
+ const SECTION_NAME = { warning: "warnings", suggestion: "suggestions", kept: "kept" };
129
+ /** The phone's view: dismissed items left out (listed when asked), cleaned from the log, a revision over all of it. */
130
+ export function viewOf(report, options) {
131
+ const warnings = [], suggestions = [], kept = [], dismissed = [];
132
+ for (const item of report.items) {
133
+ if (item.section === "auto")
134
+ continue; // shown in `cleaned` once done, or as a warning if it failed
135
+ const mark = options.dismissed.get(item.id);
136
+ if (mark && mark.fingerprint === item.fingerprint) {
137
+ dismissed.push({ id: item.id, section: SECTION_NAME[item.section], area: item.area, title: item.title, dismissedAt: mark.at });
138
+ continue;
139
+ }
140
+ const links = { ...(item.pane ? { pane: item.pane } : {}), ...(item.session ? { session: item.session } : {}), ...(item.dispatch ? { dispatch: item.dispatch } : {}) };
141
+ if (item.section === "warning")
142
+ warnings.push({ id: item.id, area: item.area, severity: item.severity ?? "info", title: item.title, detail: item.reason,
143
+ since: item.since, ...(item.fix ? { fix: item.fix } : {}), ...links, ...(item.notify ? { notify: true } : {}) });
144
+ else if (item.section === "suggestion")
145
+ suggestions.push({ id: item.id, area: item.area, kind: item.kind, title: item.title, target: item.target, reason: item.reason,
146
+ evidence: item.evidence ?? [], ...(item.sizeBytes !== undefined ? { sizeBytes: item.sizeBytes } : {}), actionLabel: item.actionLabel ?? "Apply", since: item.since, ...links });
147
+ else
148
+ kept.push({ id: item.id, area: item.area, title: item.title, target: item.target, reason: item.reason });
149
+ }
150
+ const body = { warnings, suggestions, kept, cleaned: options.cleaned };
151
+ // The inventory counts by its scan time and action ids, not by every size it measured.
152
+ // A finished scan or a handled row changes the revision, so the badge tells the phone to re-fetch the inventory too.
153
+ const inventoryKey = options.inventory ? [options.inventory.collectedAt, options.inventory.scanning ?? false, options.inventory.ids] : null;
154
+ const revision = createHash("sha256").update(JSON.stringify([body, dismissed.map(d => d.id), inventoryKey])).digest("hex").slice(0, 16);
155
+ return {
156
+ schema: SCHEMA, revision, generatedAt: report.generatedAt, ...(options.nextCheckAt ? { nextCheckAt: options.nextCheckAt } : {}),
157
+ health: report.health, ...body, ...(options.includeDismissed ? { dismissed } : {}), ...(options.include ? { inventory: options.include } : {}), ...(report.errors?.length ? { errors: report.errors } : {}),
158
+ };
159
+ }
160
+ export function badgeOf(view, now) {
161
+ const worst = view.warnings.reduce((w, item) => w === null || RANK[item.severity] < RANK[w] ? item.severity : w, null);
162
+ const day = new Date(now);
163
+ day.setHours(0, 0, 0, 0);
164
+ return {
165
+ revision: view.revision, warnings: view.warnings.length, suggestions: view.suggestions.length, worst,
166
+ freedTodayBytes: view.cleaned.filter(entry => Date.parse(entry.at) >= day.getTime()).reduce((sum, entry) => sum + entry.freedBytes, 0),
167
+ };
168
+ }
@@ -0,0 +1,177 @@
1
+ export declare class SafetyViolation extends Error {
2
+ readonly code: string;
3
+ constructor(code: string, message: string);
4
+ }
5
+ /** Throws unless `args` is a git invocation housekeeping may run. Global
6
+ * options before the subcommand (-c, -C, --git-dir, --work-tree) are refused
7
+ * outright: they could re-target or reconfigure the command. */
8
+ export declare function assertHousekeepingGit(args: readonly string[]): void;
9
+ /** The only git runner housekeeping uses. */
10
+ export declare function housekeepingGit(cwd: string, ...args: string[]): Promise<string>;
11
+ export type BlockerCode = "not-a-checkout" | "symlink" | "inspection-failed" | "main-checkout" | "linked-worktrees" | "locked" | "uncommitted-changes" | "untracked-files" | "unpushed-commits" | "stash" | "in-progress-operation" | "dirty-submodule" | "unpushed-submodule" | "live-process" | "bound-pane" | "in-use";
12
+ export interface Blocker {
13
+ code: BlockerCode;
14
+ detail: string;
15
+ }
16
+ /** One plain sentence for the first blocker, for the phone. */
17
+ export declare function plainReason(blockers: readonly Blocker[]): string;
18
+ /** A process and the folder it runs in. */
19
+ export interface LiveProcess {
20
+ pid: number;
21
+ cwd: string;
22
+ command?: string;
23
+ }
24
+ /** A pane and the folder its agent runs in. */
25
+ export interface BoundPane {
26
+ pane: string;
27
+ cwd: string;
28
+ title?: string;
29
+ }
30
+ export interface InUseSources {
31
+ processes: () => Promise<LiveProcess[]>;
32
+ panes: () => Promise<BoundPane[]>;
33
+ }
34
+ /** Processes and panes whose folder is `dir` or inside it. */
35
+ export declare function inUseBlockers(dir: string, sources: InUseSources): Promise<Blocker[]>;
36
+ export type CheckoutTarget = "worktree" | "repository";
37
+ /** What a checkout holds, as the inventory shows it. */
38
+ export interface CheckoutFacts {
39
+ main: boolean;
40
+ branch?: string;
41
+ /** The repository's main checkout (for a linked worktree, the one it belongs to). */
42
+ repo?: string;
43
+ dirty: number;
44
+ untracked: number;
45
+ unpushed: number;
46
+ stashes: number;
47
+ inProgress: string[];
48
+ locked: boolean;
49
+ lastCommitAt?: string;
50
+ }
51
+ /**
52
+ * What `dir` holds and every reason it must not be deleted (no blockers means
53
+ * nothing would be lost). `worktree`: a linked worktree, removed with `git
54
+ * worktree remove`; only its HEAD's commits matter, since its branch stays.
55
+ * `repository`: the whole repository folder; every local branch counts, and
56
+ * linked worktrees block. Stashes block either way: the owner's rule names
57
+ * them without exception.
58
+ */
59
+ export declare function inspectCheckout(dir: string, target: CheckoutTarget, sources: InUseSources): Promise<{
60
+ facts?: CheckoutFacts;
61
+ blockers: Blocker[];
62
+ }>;
63
+ /** Every reason `dir` must not be deleted; see `inspectCheckout`. */
64
+ export declare function checkoutBlockers(dir: string, target: CheckoutTarget, sources: InUseSources): Promise<Blocker[]>;
65
+ export interface WorktreeEntry {
66
+ path: string;
67
+ branch?: string;
68
+ locked?: string;
69
+ prunable?: string;
70
+ bare?: boolean;
71
+ }
72
+ export declare function parseWorktreeList(porcelain: string): WorktreeEntry[];
73
+ /** Remove a linked worktree only if it has no blockers right now, re-checked
74
+ * against fresh state, and only with plain `git worktree remove`. A refusal
75
+ * from git leaves the worktree where it is; nothing retries with force. */
76
+ export declare function removeWorktreeSafely(dir: string, sources: InUseSources): Promise<{
77
+ removed: boolean;
78
+ blockers: Blocker[];
79
+ }>;
80
+ export interface CacheRule {
81
+ id: string;
82
+ /** Absolute root; only entries strictly inside it qualify. */
83
+ root: string;
84
+ /** Minimum age of an entry, by mtime, before it may be acted on. */
85
+ minAgeDays: number;
86
+ }
87
+ /** Caches the disk-janitor proved safe to remove; every other path is
88
+ * suggest-only. Platform-specific roots are listed only where they exist. */
89
+ export declare function cacheRules(home?: string, platform?: NodeJS.Platform): CacheRule[];
90
+ /** Paths housekeeping never acts on, whatever a rule says. DeviceFS is a live
91
+ * view of booted simulators that `du` reports as ~160 GB; docker volumes hold
92
+ * data; the store and project folders hold work. */
93
+ export declare function protectedRoots(home?: string): string[];
94
+ export type CacheDecision = {
95
+ verdict: "auto";
96
+ rule: string;
97
+ } | {
98
+ verdict: "suggest" | "keep";
99
+ rule?: string;
100
+ reason: string;
101
+ blockers?: Blocker[];
102
+ };
103
+ export interface CacheContext extends InUseSources {
104
+ rules?: CacheRule[];
105
+ protected?: string[];
106
+ now?: number;
107
+ }
108
+ /**
109
+ * Whether `target` may be removed without the owner. `auto` only for an entry
110
+ * strictly inside an allow-listed root (resolved without following a link at
111
+ * the target), past the rule's age, under no protected root, and with no
112
+ * process or pane in it. Anything else is `suggest` (the owner may approve)
113
+ * or `keep` (a safety rule holds it).
114
+ */
115
+ export declare function cacheDecision(target: string, context: CacheContext): Promise<CacheDecision>;
116
+ /** Delete an allow-listed cache entry, re-deciding against fresh state first.
117
+ * Refuses (returns the decision) unless the decision is `auto` now, or the
118
+ * owner approved it and the only thing short of `auto` is its age: an owner
119
+ * may clear a recent cache entry, never a path outside the cache roots. */
120
+ export declare function removeCacheEntry(target: string, context: CacheContext, ownerApproved?: boolean): Promise<{
121
+ removed: boolean;
122
+ decision: CacheDecision;
123
+ }>;
124
+ /** Scratch roots whose direct children the owner may delete. */
125
+ export declare function tmpRoots(platform?: NodeJS.Platform): string[];
126
+ export type PathDecision = {
127
+ allowed: true;
128
+ rule: string;
129
+ } | {
130
+ allowed: false;
131
+ reason: string;
132
+ blockers?: Blocker[];
133
+ };
134
+ export interface DeletionContext extends CacheContext {
135
+ tmpRoots?: string[];
136
+ uid?: number;
137
+ }
138
+ /**
139
+ * Whether the owner may delete `target`, decided now against the disk:
140
+ * - an entry inside an allow-listed cache root (any age, since the owner asked);
141
+ * - a direct child of a scratch root this user owns, untouched for a day, not
142
+ * a git checkout (those go through the worktree rules), with nothing in it;
143
+ * - a checkout's own `node_modules` (it has package.json), with nothing
144
+ * running in that checkout.
145
+ * Never a symlink, never under a protected root except that node_modules.
146
+ */
147
+ export declare function deletionDecision(target: string, context: DeletionContext): Promise<PathDecision>;
148
+ /** Delete what the owner approved, deciding again just before. */
149
+ export declare function removeApprovedPath(target: string, context: DeletionContext): Promise<{
150
+ removed: boolean;
151
+ decision: PathDecision;
152
+ }>;
153
+ export interface PaneState {
154
+ server: string;
155
+ pane: string;
156
+ status?: string;
157
+ role?: string;
158
+ }
159
+ export interface PaneDispatch {
160
+ id?: string;
161
+ server: string;
162
+ pane: string;
163
+ returned?: {
164
+ read: boolean;
165
+ };
166
+ closedAt?: string;
167
+ }
168
+ /** Why a pane must stay open, or undefined if the owner may close it. A
169
+ * pane whose dispatch return is unread keeps the evidence (the 2026-11-08
170
+ * lesson); a working or waiting agent and the conductor stay too. */
171
+ export declare function paneCloseBlock(pane: PaneState, dispatches: readonly PaneDispatch[]): string | undefined;
172
+ /** What an item of a given kind may be: only a cache can ever be `auto`. */
173
+ export declare function allowedVerdict(kind: string, proposed: "auto" | "suggest" | "keep"): "auto" | "suggest" | "keep";
174
+ /** Every process's working directory this user can see: `lsof` on macOS,
175
+ * `/proc/<pid>/cwd` on Linux. A failure throws, so callers fail closed. */
176
+ export declare function liveProcessCwds(platform?: NodeJS.Platform): Promise<LiveProcess[]>;
177
+ export declare function parseLsofCwds(output: string): LiveProcess[];