Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ jobs:
path: dist/
retention-days: 1

- name: Test maintenance controls
run: npx jest src/maintenance.test.ts --runInBand

mcp-integration:
name: MCP Protocol & Contract Tests
runs-on: ubuntu-latest
Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/release-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ jobs:
path: dist/
retention-days: 1

- name: Test maintenance controls
run: npx jest src/maintenance.test.ts --runInBand

mcp-integration:
name: MCP Protocol & Contract Tests
runs-on: ubuntu-latest
Expand Down
25 changes: 23 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,9 @@ Set these environment variables to tune behavior:

| Variable | Default | Description |
|---|---|---|
| `SCALEDOWN_UPDATE_CHECK` | `true` | Set to `false` to disable npm registry checks and update notifications |
| `SCALEDOWN_AUTO_UPDATE` | `false` | Set to `true` to allow background installation of minor/patch updates from the status line |
| `SCALEDOWN_AUTO_RECONCILE` | `true` | Set to `false` to disable automatic harness config refresh from postinstall and the status line; explicit `dietcode-reconcile` still works |
| `SCALEDOWN_API_KEY` | — | **Required.** Your Scaledown API key |
| `SCALEDOWN_COMPRESS_THRESHOLD` | `10000` | Token estimate above which prompt auto-compression fires |
| `SCALEDOWN_COMPRESS_RATE` | `0.3` | How aggressively to compress (`0.3` = keep ~30% of tokens; `auto` lets the API decide) |
Expand Down Expand Up @@ -362,7 +365,7 @@ npm update -g dietcode
npm install -g dietcode@latest
```

Your harness config (hooks, status line, Cursor/Codex blocks) is **automatically re-synced on update** for every harness you've already set up — you do not need to re-run setup. This happens two ways:
Unless `SCALEDOWN_AUTO_RECONCILE=false`, your harness config (hooks, status line, Cursor/Codex blocks) is **automatically re-synced on update** for every harness you've already set up — you do not need to re-run setup. This happens two ways:

- A **postinstall** step runs right after `npm install`.
- A **once-a-day self-heal** runs from the Claude Code status line as a safety net (e.g. if `npm install --ignore-scripts` skipped postinstall, or your Node version changed and moved the global install path).
Expand All @@ -373,7 +376,25 @@ Reconcile only touches harnesses you've already configured — it never adds a h
dietcode-reconcile
```

> The status line also shows when a new version is available and auto-updates minor versions in the background; major versions print the upgrade command.
The status line checks for updates and shows an upgrade command by default;
it does **not** install packages unless you opt in with
`SCALEDOWN_AUTO_UPDATE=true`. Opting in allows minor/patch updates in the
background; major updates always show the manual command.

For a pinned or externally managed installation, export these before installing
and launching your coding client (restart existing sessions to inherit them):

```bash
export SCALEDOWN_AUTO_UPDATE=false
export SCALEDOWN_AUTO_RECONCILE=false
# Optional: also disable registry checks and update notifications.
export SCALEDOWN_UPDATE_CHECK=false
```

These controls are independent. Update checks can stay enabled for notifications
without installing anything. Explicit `npm install -g dietcode@latest`,
`dietcode setup`, and `dietcode-reconcile` remain available when automatic
maintenance is disabled.

---

Expand Down
5 changes: 5 additions & 0 deletions bin/postinstall.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,14 @@
// Must never fail the install: a thrown error here would abort `npm install`.
// On a fresh install (no harness configured yet) this is a silent no-op —
// `dietcode setup` does first-time configuration.
import { loadMaintenanceConfig } from "../src/config.js";
import { reconcileAll } from "../src/reconcile.js";

// The same entry point backs the explicit dietcode-reconcile command.
const automatic = process.env.npm_lifecycle_event === "postinstall";

try {
if (automatic && !loadMaintenanceConfig().autoReconcile) process.exit(0);
const result = reconcileAll();
const touched = Object.entries(result)
.filter(([, v]) => v)
Expand Down
7 changes: 5 additions & 2 deletions hooks/status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,11 @@ async function main(): Promise<void> {
const update = await checkForUpdate();
if (update && update.kind === "minor") {
if (!update.alreadyTriggered) {
triggerBackgroundUpdate();
parts.push(`updating to v${update.latest}...`);
if (triggerBackgroundUpdate()) {
parts.push(`updating to v${update.latest}...`);
} else {
parts.push(`v${update.latest} available: npm i -g dietcode@latest`);
}
} else {
parts.push(`restart to activate v${update.latest}`);
}
Expand Down
9 changes: 9 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,3 +124,12 @@ export function loadConfig(): Config {
proxy: loadProxyConfig(),
};
}

// Maintenance must also work without an API key (e.g. postinstall/status).
export function loadMaintenanceConfig() {
return {
updateCheck: process.env.SCALEDOWN_UPDATE_CHECK !== "false",
autoUpdate: process.env.SCALEDOWN_AUTO_UPDATE === "true",
autoReconcile: process.env.SCALEDOWN_AUTO_RECONCILE !== "false",
};
}
150 changes: 150 additions & 0 deletions src/maintenance.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import { execFileSync } from "child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { resolve } from "path";

const version = JSON.parse(readFileSync(resolve("package.json"), "utf8")).version as string;
const [major, minor, patch] = version.split(".").map(Number);
const latest = `${major}.${minor}.${patch + 1}`;

// Run built entry points in fresh processes so module-level paths use an
// isolated home. Stub both external side effects before importing the code.
const stubs = `
import childProcess from "node:child_process";
import { syncBuiltinESMExports } from "node:module";
childProcess.spawn = (...args) => {
console.log("SPAWN " + JSON.stringify(args));
return { unref() {} };
};
syncBuiltinESMExports();
globalThis.fetch = async () => {
console.log("FETCH");
return new Response(JSON.stringify({ version: "${latest}" }));
};
`;
let testHome: string;
let settingsPath: string;
let configPath: string;
const settings = JSON.stringify({
custom: "preserve me",
hooks: { UserPromptSubmit: [{ hooks: [{ type: "command", command: "old/dietcode-hook" }] }] },
});

beforeEach(() => {
testHome = mkdtempSync(resolve(tmpdir(), "dietcode-maintenance-"));
settingsPath = resolve(testHome, ".claude/settings.json");
configPath = resolve(testHome, ".scaledown/config.json");
mkdirSync(resolve(testHome, ".claude"));
mkdirSync(resolve(testHome, ".scaledown"));
writeFileSync(settingsPath, settings);
});
afterEach(() => rmSync(testHome, { recursive: true, force: true }));

function run(code: string, overrides: NodeJS.ProcessEnv = {}): string {
const env = { ...process.env, HOME: testHome, DIETCODE_PROXY: "1" };
for (const key of ["SCALEDOWN_UPDATE_CHECK", "SCALEDOWN_AUTO_UPDATE", "SCALEDOWN_AUTO_RECONCILE", "npm_lifecycle_event"]) {
delete (env as NodeJS.ProcessEnv)[key];
}
return execFileSync(process.execPath, ["--input-type=module", "-e", stubs + code], {
env: { ...env, ...overrides }, input: "{}", encoding: "utf8", timeout: 5000,
});
}

function cache(updateTriggered = false): void {
writeFileSync(configPath, JSON.stringify({ apiKey: "fixture-key", _updateCache: {
latestVersion: latest, lastChecked: new Date().toISOString(), updateTriggered,
} }));
}

it("disables registry access and cache writes when checks are off", () => {
expect(run(`const u = await import('./dist/src/update.js'); console.log(await u.checkForUpdate());`, {
SCALEDOWN_UPDATE_CHECK: "false",
}).trim()).toBe("null");
expect(existsSync(configPath)).toBe(false);
});

it("suppresses cached notifications when checks are off", () => {
cache(true);
const before = readFileSync(configPath, "utf8");
const output = run(`await import('./dist/hooks/status.js');`, {
SCALEDOWN_UPDATE_CHECK: "false", SCALEDOWN_AUTO_RECONCILE: "false",
});
expect(output).toBe("↓ 0 saved");
expect(readFileSync(configPath, "utf8")).toBe(before);
expect(readFileSync(settingsPath, "utf8")).toBe(settings);
});

it("checks for updates and notifies without installing by default", () => {
const output = run(`await import('./dist/hooks/status.js');`, { SCALEDOWN_AUTO_RECONCILE: "false" });
expect(output).toContain("FETCH");
expect(output).toContain(`v${latest} available: npm i -g dietcode@latest`);
expect(output).not.toContain("SPAWN");
expect(JSON.parse(readFileSync(configPath, "utf8"))._updateCache.updateTriggered).toBe(false);
expect(readFileSync(settingsPath, "utf8")).toBe(settings);
});

it.each([undefined, "false"])("guards direct background installation when auto-update is %s", (value) => {
const output = run(`const u = await import('./dist/src/update.js'); console.log(u.triggerBackgroundUpdate());`, {
SCALEDOWN_AUTO_UPDATE: value,
});
expect(output.trim()).toBe("false");
expect(existsSync(configPath)).toBe(false);
});

it("installs a cached minor update only after explicit opt-in", () => {
cache();
const output = run(`await import('./dist/hooks/status.js');`, {
SCALEDOWN_AUTO_UPDATE: "true", SCALEDOWN_AUTO_RECONCILE: "false",
});
expect(output).toContain('SPAWN ["npm",["install","-g","dietcode@latest"]');
expect(output).toContain(`updating to v${latest}...`);
expect(output).not.toContain("FETCH");
const config = JSON.parse(readFileSync(configPath, "utf8"));
expect(config._updateCache.updateTriggered).toBe(true);
expect(config.apiKey).toBe("fixture-key");
});

it("shows pending installations without starting another", () => {
cache(true);
const output = run(`await import('./dist/hooks/status.js');`, {
SCALEDOWN_AUTO_RECONCILE: "false", SCALEDOWN_AUTO_UPDATE: "true",
});
expect(output).toContain(`restart to activate v${latest}`);
expect(output).not.toContain("SPAWN");
});

it("leaves all files untouched when automatic maintenance is disabled", () => {
const output = run(`await import('./dist/hooks/status.js');`, {
SCALEDOWN_AUTO_RECONCILE: "false", SCALEDOWN_UPDATE_CHECK: "false", SCALEDOWN_AUTO_UPDATE: "false",
});
expect(output).toBe("↓ 0 saved");
expect(readFileSync(settingsPath, "utf8")).toBe(settings);
expect(existsSync(configPath)).toBe(false);
});

it("retains automatic reconciliation by default independently of update checks", () => {
run(`await import('./dist/hooks/status.js');`, { SCALEDOWN_UPDATE_CHECK: "false" });
const refreshed = JSON.parse(readFileSync(settingsPath, "utf8"));
expect(refreshed.statusLine.command).toContain("status.js");
expect(refreshed.custom).toBe("preserve me");
});

it("skips postinstall reconciliation when disabled", () => {
run(`await import('./dist/bin/postinstall.js');`, {
npm_lifecycle_event: "postinstall", SCALEDOWN_AUTO_RECONCILE: "false",
});
expect(readFileSync(settingsPath, "utf8")).toBe(settings);
expect(existsSync(configPath)).toBe(false);
});

it("keeps explicit reconciliation available when automatic reconciliation is off", () => {
run(`await import('./dist/bin/postinstall.js');`, { SCALEDOWN_AUTO_RECONCILE: "false" });
const refreshed = JSON.parse(readFileSync(settingsPath, "utf8"));
expect(refreshed.statusLine.command).toContain("status.js");
expect(refreshed.custom).toBe("preserve me");
});

it("retains postinstall reconciliation by default", () => {
run(`await import('./dist/bin/postinstall.js');`, { npm_lifecycle_event: "postinstall" });
expect(JSON.parse(readFileSync(settingsPath, "utf8")).statusLine.command).toContain("status.js");
});
9 changes: 7 additions & 2 deletions src/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { homedir } from "os";
import { dirname, resolve } from "path";
import { spawn } from "child_process";
import { fileURLToPath } from "url";
import { loadMaintenanceConfig } from "./config.js";
import { reconcileAll } from "./reconcile.js";

const __dirname = dirname(fileURLToPath(import.meta.url));
Expand Down Expand Up @@ -91,6 +92,7 @@ function writeCache(cache: UpdateCache): void {
// install path changed (Node version bump) without a reinstall. Cheap and
// fail-soft — called from the status line, which already runs ~daily logic.
export function reconcileIfStale(): void {
if (!loadMaintenanceConfig().autoReconcile) return;
try {
const cache = readCache();
if (cache?.lastReconciled) {
Expand All @@ -115,7 +117,8 @@ function needsCheck(cache: UpdateCache | null): boolean {
return elapsed > 24 * 60 * 60 * 1000;
}

export function triggerBackgroundUpdate(): void {
export function triggerBackgroundUpdate(): boolean {
if (!loadMaintenanceConfig().autoUpdate) return false;
try {
const child = spawn("npm", ["install", "-g", "dietcode@latest"], {
detached: true,
Expand All @@ -129,12 +132,14 @@ export function triggerBackgroundUpdate(): void {
latestVersion: cache?.latestVersion ?? CURRENT_VERSION,
updateTriggered: true,
});
return true;
} catch {
// non-fatal
return false;
}
}

export async function checkForUpdate(): Promise<UpdateResult | null> {
if (!loadMaintenanceConfig().updateCheck) return null;
try {
const cache = readCache();

Expand Down