trunkguard 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 trunkguard contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,166 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # trunkguard
2
+
3
+ **Let AI agents push straight to `main`. Only tested commits reach your server — and a bad deploy rolls itself back.**
4
+
5
+ Coding agents (Claude Code, Codex, Cursor, Aider…) commit fast and often. Pull-request review doesn't keep up,
6
+ and "just push to main" means the first broken commit takes your app down. trunkguard sits between `main` and
7
+ the running app:
8
+
9
+ ```
10
+ agents ──push──▶ main ──▶ robot: tests ──green──▶ release ──▶ serve: deploy in a safe window
11
+ │ │
12
+ └─red──▶ release stays put ├─ healthy? keep it
13
+ (you get a message) └─ not? roll back + never retry that commit
14
+ ```
15
+
16
+ - **Robot** — watches `main`, runs your test command on every new commit in its own checkout, and
17
+ fast-forwards `release` only when it's green. Red → `release` stays on the last green commit.
18
+ - **Serve** — runs your app from the `release` checkout. On a new release commit it waits until the app is
19
+ not busy, restarts on the new code, checks health, and rolls back automatically if the app crashes or
20
+ answers unhealthy. Also restarts the app if it crashes on its own (with a limit).
21
+ - **Zero dependencies.** One `npx` command, Node ≥ 18, Linux / macOS / Windows. Works with any stack —
22
+ the app is just a shell command and an optional health URL.
23
+
24
+ No CI service, no containers, no webhooks to set up. Your git remote is the only shared piece.
25
+
26
+ ## Quick start
27
+
28
+ ```bash
29
+ cd myapp
30
+ npx trunkguard init # writes trunkguard.json, adds .trunkguard/ to .gitignore
31
+ # edit trunkguard.json: robot.test, serve.start, serve.healthUrl — then commit it
32
+ git push origin main:release # once: create the release branch from a known-good commit
33
+ ```
34
+
35
+ **Robot** — in a separate checkout (it switches commits while testing, so not your working copy):
36
+
37
+ ```bash
38
+ git worktree add --detach ../myapp-accept main
39
+ cd ../myapp-accept && npx trunkguard robot
40
+ ```
41
+
42
+ **Server** — in the checkout that runs your app, on the `release` branch:
43
+
44
+ ```bash
45
+ git clone -b release <your-remote> /srv/myapp
46
+ cd /srv/myapp && npx trunkguard serve
47
+ ```
48
+
49
+ Robot and server can be on the same machine or different ones. Keep both running with systemd, a scheduled task,
50
+ pm2 — see [`examples/`](examples). Then tell your agents the rule ([`examples/AGENTS.md`](examples/AGENTS.md)):
51
+ *push to `main`, never to `release`*.
52
+
53
+ ```bash
54
+ npx trunkguard status
55
+ ```
56
+
57
+ ```
58
+ checkout /srv/myapp
59
+ HEAD 9f8e7d6 fix flaky date test
60
+ main a1b2c3d
61
+ release 9f8e7d6 1 commit(s) on main not released yet
62
+
63
+ robot running (PID 4120)
64
+ last run a1b2c3d RED tests failed (exit 1) (2026-12-02T13:58:10.512Z)
65
+ 2026-12-02T13:51:02.004Z 9f8e7d6 GREEN (41s) → release — fix flaky date test
66
+ 2026-12-02T13:58:10.512Z a1b2c3d RED tests failed (exit 1) (38s) — agent: add CSV export
67
+
68
+ serve running (PID 3988)
69
+ current 9f8e7d6 since 2026-12-02T14:02:44.120Z
70
+ blocked 5c4d3e2 (rolled back — never redeployed; push a fix to main)
71
+ 2026-12-02T13:40:12.871Z rolledBack 7a6b5c4 → 5c4d3e2 — app exited (code 1) before health check passed
72
+ 2026-12-02T14:02:44.120Z ok 7a6b5c4 → 9f8e7d6
73
+ ```
74
+
75
+ `status` shows robot details in the robot's checkout and deploy details in the live one.
76
+
77
+ ## What counts as "healthy"
78
+
79
+ A deploy succeeds when:
80
+
81
+ 1. the optional `serve.check` command passes (migrations, a smoke script…),
82
+ 2. `serve.healthUrl` answers **2xx** within `healthTimeoutSec`,
83
+ 3. the app keeps running — and keeps answering 2xx — for `stableSec` more seconds.
84
+
85
+ Without `healthUrl`, "the process is still running after `stableSec`" is the check.
86
+ Anything else → `git reset` back to the previous commit, restart, notify. The failed commit is remembered and is
87
+ **not deployed again** — push a fix to `main` and it flows through the robot as usual. If the app is unhealthy even
88
+ after the rollback, serve stops and tells you, instead of looping.
89
+
90
+ ## Safe window (`busyUrl`)
91
+
92
+ Restarting in the middle of a job is often worse than a bug. If `serve.busyUrl` is set, deploys wait while it
93
+ answers:
94
+
95
+ | Response | Meaning |
96
+ |---------------------------------------|---------|
97
+ | `2xx {"busy": false}` | free — deploy now |
98
+ | `2xx {"busy": true, "why": "..."}` | wait (the reason goes to the log) |
99
+ | `423` or `503` | wait |
100
+ | no answer | wait |
101
+
102
+ A minimal Express version is in [`examples/health.js`](examples/health.js).
103
+
104
+ ## Configuration
105
+
106
+ `trunkguard.json` in the repo root. Everything has a default; `init` writes a starting point.
107
+ Any string value `"env:NAME"` is read from the environment, so tokens never get committed.
108
+
109
+ | Key | Default | |
110
+ |---|---|---|
111
+ | `remote` / `mainBranch` / `releaseBranch` | `origin` / `main` / `release` | |
112
+ | `robot.test` | `npm test` | green = exit code 0 |
113
+ | `robot.install` | `npm ci` | run when a lockfile changed or `node_modules` is missing; `""` to disable |
114
+ | `robot.skip` | `["**/*.md", "docs/**"]` | commits touching only these are not tested and don't move `release` |
115
+ | `robot.retries` | `1` | re-run a red suite; green on re-run = passed, marked *flaky* |
116
+ | `robot.pollSec` / `robot.timeoutMin` | `60` / `60` | |
117
+ | `serve.start` | — | command that runs the app (required) |
118
+ | `serve.env` | `{}` | extra environment for the app |
119
+ | `serve.healthUrl` | — | see above |
120
+ | `serve.healthTimeoutSec` / `serve.stableSec` | `60` / `30` | |
121
+ | `serve.busyUrl` | — | see above |
122
+ | `serve.pollSec` | `300` | how often to look for a new release commit |
123
+ | `serve.auto` | `true` | `false` = only notify; deploy with `trunkguard deploy` |
124
+ | `serve.install` / `serve.check` | `npm ci` / — | |
125
+ | `serve.crash` | `{max: 3, spanMin: 10, delaySec: 5}` | more than `max` crashes in `spanMin` → stop and alert |
126
+ | `notify.telegram` | `{token, chatId}` | Telegram bot messages |
127
+ | `notify.webhook` | — | POST `{"source":"trunkguard","event":"...","text":"..."}` |
128
+ | `notify.onGreen` | `false` | also message on every green run (red, rollbacks and crashes are always sent) |
129
+
130
+ Full example: [`examples/trunkguard.json`](examples/trunkguard.json).
131
+
132
+ ## Commands
133
+
134
+ ```
135
+ trunkguard init [--force] write trunkguard.json (+ .trunkguard/ in .gitignore)
136
+ trunkguard robot [--once] test new main commits, fast-forward release on green
137
+ trunkguard serve run the app, deploy new release commits, roll back on failure
138
+ trunkguard deploy ask a running serve to deploy the current release now
139
+ trunkguard status main / release / live, last runs, deploys, rollbacks
140
+
141
+ --cwd <dir> --config <file>
142
+ ```
143
+
144
+ Logs and state live in `.trunkguard/` next to the config (test output per commit in `.trunkguard/robot/runs/`).
145
+ Only one robot and one serve run per checkout (pid lock).
146
+
147
+ ## Guarantees and non-goals
148
+
149
+ - `release` only ever moves **forward** to a commit that passed the tests. trunkguard never force-pushes.
150
+ - The live checkout is only moved to commits that are on `release`. Hand-edited tracked files in it block deploys
151
+ (it tells you why) instead of being overwritten.
152
+ - It's a single-server tool. For fleets, blue-green or canaries use a real deploy system — trunkguard is for the
153
+ one box running your side project, internal tool or bot, where "an agent broke prod at 3am" is the actual risk.
154
+ - It doesn't replace code review; it makes sure that what isn't reviewed at least passes the tests and boots.
155
+
156
+ To protect `release` on GitHub/GitLab, allow pushes to it only from the account the robot uses.
157
+
158
+ ## Development
159
+
160
+ ```bash
161
+ npm test # real git repos + a real tiny app in temp folders: robot, serve (deploy, rollback, busy, crash), config
162
+ ```
163
+
164
+ ## License
165
+
166
+ MIT
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ const path = require('path');
4
+ const config = require('../src/config');
5
+
6
+ const HELP = `trunkguard — only tested commits reach the live server; bad deploys roll back on their own.
7
+
8
+ Usage:
9
+ trunkguard init [--force] write trunkguard.json (+ .trunkguard/ in .gitignore)
10
+ trunkguard robot [--once] in a separate checkout: new commit on main → tests → fast-forward release
11
+ trunkguard serve in the live checkout: run the app, deploy new release commits, roll back on failure
12
+ trunkguard deploy ask a running "serve" to deploy the current release now (also with auto: false)
13
+ trunkguard status main / release / live commit, last test runs, deploys and rollbacks
14
+
15
+ Options:
16
+ --config <file> config file (default: ./trunkguard.json)
17
+ --cwd <dir> repository directory (default: current directory)
18
+
19
+ Docs: https://github.com/nogcar421-byte/trunkguard#readme`;
20
+
21
+ async function main(argv) {
22
+ const cmd = argv[0];
23
+ const opt = (name) => { const i = argv.indexOf(name); return i >= 0 ? argv[i + 1] : ''; };
24
+ const cwd = path.resolve(opt('--cwd') || process.cwd());
25
+ if (!cmd || cmd === 'help' || cmd === '--help' || cmd === '-h') { console.log(HELP); return 0; }
26
+ if (cmd === '--version' || cmd === '-v') { console.log(require('../package.json').version); return 0; }
27
+ if (cmd === 'init') {
28
+ const r = require('../src/init').init(cwd, { force: argv.includes('--force') });
29
+ if (!r.created) { console.log(r.note); return 1; }
30
+ console.log(`created ${r.file}
31
+
32
+ Next:
33
+ 1. Check robot.test and serve.start / serve.healthUrl in trunkguard.json, commit it.
34
+ 2. Acceptance checkout for the robot (once): git worktree add --detach ../${path.basename(cwd)}-accept ${r.cfg.mainBranch}
35
+ then in that folder: npx trunkguard robot
36
+ 3. In the live checkout (on the release branch): npx trunkguard serve
37
+ 4. Let your agents push to ${r.cfg.mainBranch}. Only green commits reach ${r.cfg.releaseBranch} and the server.`);
38
+ return 0;
39
+ }
40
+ // unknown command → help, before the config is even looked for
41
+ if (!['robot', 'serve', 'deploy', 'status'].includes(cmd)) { console.error(`unknown command: ${cmd}\n\n${HELP}`); return 1; }
42
+ const cfg = config.load(cwd, opt('--config'));
43
+ if (cmd === 'robot') return require('../src/robot').run(cfg, { once: argv.includes('--once') });
44
+ if (cmd === 'serve') return require('../src/serve').run(cfg);
45
+ if (cmd === 'deploy') { const f = require('../src/serve').requestDeploy(cfg); console.log(`deploy requested (${f}); a running "trunkguard serve" picks it up within a second or two`); return 0; }
46
+ console.log(require('../src/status').report(cfg));
47
+ return 0;
48
+ }
49
+
50
+ main(process.argv.slice(2)).then((code) => { process.exitCode = code; }, (e) => { console.error(`trunkguard: ${e.message}`); process.exitCode = 1; });
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "trunkguard",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Release gate for projects where AI coding agents push to main: only commits that pass your tests reach the live server, bad deploys roll back on their own.",
5
+ "homepage": "https://github.com/nogcar421-byte/trunkguard#readme",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/nogcar421-byte/trunkguard.git"
9
+ },
10
+ "bugs": {
11
+ "url": "https://github.com/nogcar421-byte/trunkguard/issues"
12
+ },
13
+ "author": "nogcar421-byte",
14
+ "bin": {
15
+ "trunkguard": "bin/trunkguard.js"
16
+ },
17
+ "main": "src/index.js",
18
+ "files": [
19
+ "bin/",
20
+ "src/",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "scripts": {
25
+ "test": "node test/run.js"
26
+ },
27
+ "engines": {
28
+ "node": ">=18"
29
+ },
30
+ "keywords": [
31
+ "ai-agents",
32
+ "claude-code",
33
+ "codex",
34
+ "deploy",
35
+ "rollback",
36
+ "release",
37
+ "ci",
38
+ "self-hosted",
39
+ "supervisor",
40
+ "git"
41
+ ],
42
+ "license": "MIT"
43
+ }
package/src/config.js ADDED
@@ -0,0 +1,87 @@
1
+ 'use strict';
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+
5
+ const LOCKFILES = ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock', 'pnpm-lock.yaml'];
6
+
7
+ const DEFAULTS = {
8
+ remote: 'origin',
9
+ mainBranch: 'main',
10
+ releaseBranch: 'release',
11
+ robot: {
12
+ test: 'npm test',
13
+ install: 'npm ci',
14
+ installWhen: LOCKFILES,
15
+ skip: ['**/*.md', 'docs/**'],
16
+ retries: 1,
17
+ pollSec: 60,
18
+ timeoutMin: 60,
19
+ },
20
+ serve: {
21
+ start: '',
22
+ env: {},
23
+ healthUrl: '',
24
+ healthTimeoutSec: 60,
25
+ stableSec: 30,
26
+ busyUrl: '',
27
+ pollSec: 300,
28
+ auto: true,
29
+ install: 'npm ci',
30
+ installWhen: LOCKFILES,
31
+ check: '',
32
+ stopTimeoutSec: 15,
33
+ crash: { max: 3, spanMin: 10, delaySec: 5 },
34
+ },
35
+ notify: {
36
+ telegram: { token: '', chatId: '' },
37
+ webhook: '',
38
+ onGreen: false,
39
+ },
40
+ };
41
+
42
+ const isObj = (v) => v && typeof v === 'object' && !Array.isArray(v);
43
+ function merge(base, over) {
44
+ const out = { ...base };
45
+ for (const [k, v] of Object.entries(over || {})) out[k] = isObj(v) && isObj(base[k]) ? merge(base[k], v) : v;
46
+ return out;
47
+ }
48
+
49
+ // "env:NAME" → process.env.NAME, so secrets stay out of the committed config
50
+ function resolveEnv(v) {
51
+ if (typeof v === 'string' && v.startsWith('env:')) return process.env[v.slice(4)] || '';
52
+ if (Array.isArray(v)) return v.map(resolveEnv);
53
+ if (isObj(v)) return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, resolveEnv(x)]));
54
+ return v;
55
+ }
56
+
57
+ function load(cwd = process.cwd(), file = '') {
58
+ const p = path.resolve(cwd, file || 'trunkguard.json');
59
+ if (!fs.existsSync(p)) {
60
+ const e = new Error(`no config: ${p} — run "trunkguard init" first`);
61
+ e.code = 'NO_CONFIG';
62
+ throw e;
63
+ }
64
+ let raw;
65
+ try { raw = JSON.parse(fs.readFileSync(p, 'utf8')); } catch (e) { throw new Error(`bad JSON in ${p}: ${e.message}`); }
66
+ const cfg = resolveEnv(merge(DEFAULTS, raw));
67
+ cfg.file = p;
68
+ cfg.root = path.dirname(p);
69
+ cfg.stateDir = path.join(cfg.root, '.trunkguard');
70
+ return cfg;
71
+ }
72
+
73
+ // minimal glob: ** any path, * any except "/", ? one char
74
+ function globToRe(g) {
75
+ let re = '';
76
+ for (let i = 0; i < g.length; i++) {
77
+ const c = g[i];
78
+ if (c === '*' && g[i + 1] === '*') { re += '.*'; i++; if (g[i + 1] === '/') i++; }
79
+ else if (c === '*') re += '[^/]*';
80
+ else if (c === '?') re += '[^/]';
81
+ else re += c.replace(/[.+^${}()|[\]\\]/g, '\\$&');
82
+ }
83
+ return new RegExp(`^${re}$`);
84
+ }
85
+ const matchAny = (file, globs) => (globs || []).some((g) => globToRe(g).test(file));
86
+
87
+ module.exports = { DEFAULTS, LOCKFILES, load, merge, resolveEnv, globToRe, matchAny };
package/src/index.js ADDED
@@ -0,0 +1,8 @@
1
+ 'use strict';
2
+ module.exports = {
3
+ config: require('./config'),
4
+ robot: require('./robot'),
5
+ serve: require('./serve'),
6
+ status: require('./status'),
7
+ init: require('./init'),
8
+ };
package/src/init.js ADDED
@@ -0,0 +1,41 @@
1
+ 'use strict';
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const { git } = require('./proc');
5
+
6
+ // guess sensible defaults from package.json; everything stays editable in trunkguard.json
7
+ function guess(root) {
8
+ let pkg = null;
9
+ try { pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')); } catch { /* not a node project */ }
10
+ const s = (pkg && pkg.scripts) || {};
11
+ const lock = ['pnpm-lock.yaml', 'yarn.lock', 'package-lock.json'].find((f) => fs.existsSync(path.join(root, f)));
12
+ const pm = lock === 'pnpm-lock.yaml' ? 'pnpm' : lock === 'yarn.lock' ? 'yarn' : 'npm';
13
+ const install = !pkg ? '' : pm === 'npm' ? (lock ? 'npm ci' : 'npm install') : pm === 'yarn' ? 'yarn install --frozen-lockfile' : 'pnpm install --frozen-lockfile';
14
+ return {
15
+ test: s.test ? `${pm} test` : 'echo "set robot.test to your test command" && exit 1',
16
+ start: s.start ? `${pm} start` : (pkg && pkg.main ? `node ${pkg.main}` : ''),
17
+ install,
18
+ };
19
+ }
20
+
21
+ function init(root, { force = false } = {}) {
22
+ const file = path.join(root, 'trunkguard.json');
23
+ if (fs.existsSync(file) && !force) return { file, created: false, note: 'trunkguard.json already exists (use --force to overwrite)' };
24
+ const g = guess(root);
25
+ const cfg = {
26
+ remote: 'origin',
27
+ mainBranch: git(root, 'symbolic-ref', '--short', 'HEAD').out || 'main',
28
+ releaseBranch: 'release',
29
+ robot: { test: g.test, install: g.install, skip: ['**/*.md', 'docs/**'], retries: 1, pollSec: 60, timeoutMin: 60 },
30
+ serve: { start: g.start, healthUrl: 'http://127.0.0.1:3000/health', healthTimeoutSec: 60, stableSec: 30, busyUrl: '', pollSec: 300, auto: true, install: g.install },
31
+ notify: { telegram: { token: 'env:TRUNKGUARD_TG_TOKEN', chatId: 'env:TRUNKGUARD_TG_CHAT' }, webhook: '' },
32
+ };
33
+ fs.writeFileSync(file, `${JSON.stringify(cfg, null, 2)}\n`);
34
+ // runtime state never goes into git
35
+ const gi = path.join(root, '.gitignore');
36
+ const cur = fs.existsSync(gi) ? fs.readFileSync(gi, 'utf8') : '';
37
+ if (!/^\.trunkguard\/?$/m.test(cur)) fs.writeFileSync(gi, `${cur}${cur && !cur.endsWith('\n') ? '\n' : ''}.trunkguard/\n`);
38
+ return { file, created: true, cfg };
39
+ }
40
+
41
+ module.exports = { init, guess };
package/src/proc.js ADDED
@@ -0,0 +1,48 @@
1
+ 'use strict';
2
+ const { spawn, spawnSync } = require('child_process');
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+
6
+ const WIN = process.platform === 'win32';
7
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
8
+ const short = (sha) => String(sha || '').slice(0, 7);
9
+
10
+ function git(cwd, ...args) {
11
+ const r = spawnSync('git', args, { cwd, encoding: 'utf8', windowsHide: true, maxBuffer: 64 * 1024 * 1024 });
12
+ return { ok: r.status === 0 && !r.error, out: String(r.stdout || '').trim(), err: String(r.stderr || (r.error && r.error.message) || '').trim() };
13
+ }
14
+ const revParse = (cwd, ref) => { const r = git(cwd, 'rev-parse', '--verify', '-q', `${ref}^{commit}`); return r.ok ? r.out : ''; };
15
+ const isAncestor = (cwd, a, b) => git(cwd, 'merge-base', '--is-ancestor', a, b).ok;
16
+ const changedFiles = (cwd, a, b) => git(cwd, 'diff', '--name-only', a, b).out.split('\n').filter(Boolean);
17
+
18
+ // run a shell command to completion, output captured (and optionally written to a file)
19
+ function sh(cmd, { cwd, timeoutMs = 0, env, logFile } = {}) {
20
+ const t0 = Date.now();
21
+ const r = spawnSync(cmd, { cwd, shell: true, encoding: 'utf8', windowsHide: true, timeout: timeoutMs || undefined,
22
+ maxBuffer: 256 * 1024 * 1024, env: { ...process.env, ...(env || {}) } });
23
+ const out = `${r.stdout || ''}${r.stderr || ''}${r.error ? `\n${r.error.message}` : ''}`;
24
+ if (logFile) { fs.mkdirSync(path.dirname(logFile), { recursive: true }); fs.writeFileSync(logFile, `$ ${cmd}\n${out}`); }
25
+ return { ok: r.status === 0 && !r.error, code: r.status, timedOut: !!(r.error && r.error.code === 'ETIMEDOUT'), out, sec: Math.round((Date.now() - t0) / 1000) };
26
+ }
27
+
28
+ // long-running app process; own process group on POSIX so the whole tree can be stopped
29
+ function start(cmd, { cwd, env } = {}) {
30
+ return spawn(cmd, { cwd, shell: true, stdio: 'inherit', windowsHide: true, detached: !WIN, env: { ...process.env, ...(env || {}) } });
31
+ }
32
+
33
+ const exited = (child) => child.exitCode !== null || child.signalCode !== null;
34
+
35
+ // stop the app and everything it spawned: polite first, forced after timeoutMs
36
+ async function stopTree(child, timeoutMs = 15000) {
37
+ if (!child || exited(child)) return;
38
+ const done = new Promise((r) => child.once('exit', r));
39
+ if (WIN) spawnSync('taskkill', ['/PID', String(child.pid), '/T'], { windowsHide: true });
40
+ else { try { process.kill(-child.pid, 'SIGTERM'); } catch { /* already gone */ } }
41
+ const graceful = await Promise.race([done.then(() => true), sleep(timeoutMs).then(() => false)]);
42
+ if (graceful || exited(child)) return;
43
+ if (WIN) spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true });
44
+ else { try { process.kill(-child.pid, 'SIGKILL'); } catch { /* already gone */ } }
45
+ await Promise.race([done, sleep(5000)]);
46
+ }
47
+
48
+ module.exports = { WIN, sleep, short, git, revParse, isAncestor, changedFiles, sh, start, stopTree, exited };
package/src/robot.js ADDED
@@ -0,0 +1,109 @@
1
+ 'use strict';
2
+ // Acceptance robot. Runs in a SEPARATE checkout of the repo (a git worktree or clone — never the live one):
3
+ // sees a new commit on <remote>/<main>, runs the full test command and, only if it passes, fast-forwards
4
+ // <remote>/<release> to that commit. Release never moves backwards and is never force-pushed.
5
+ // A red run does not stop the robot: release stays put and the next commit on main gets its own run.
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const { git, revParse, isAncestor, changedFiles, sh, short, sleep } = require('./proc');
9
+ const { matchAny } = require('./config');
10
+ const { lock, readJson, writeJson, appendLine, logger, notify } = require('./util');
11
+
12
+ function paths(cfg) {
13
+ const dir = path.join(cfg.stateDir, 'robot');
14
+ return { dir, status: path.join(dir, 'status.json'), history: path.join(dir, 'history.log'), runs: path.join(dir, 'runs'), log: path.join(dir, 'robot.log') };
15
+ }
16
+
17
+ function fetchRefs(cfg) {
18
+ const { root, remote, mainBranch: m, releaseBranch: r } = cfg;
19
+ for (let i = 0; i < 3; i++) {
20
+ if (!git(root, 'fetch', '-q', remote, `+refs/heads/${m}:refs/remotes/${remote}/${m}`).ok) continue;
21
+ // release may not exist yet (first run) — that is not a network error
22
+ const rel = git(root, 'fetch', '-q', remote, `+refs/heads/${r}:refs/remotes/${remote}/${r}`);
23
+ if (!rel.ok && git(root, 'ls-remote', '--exit-code', remote, `refs/heads/${r}`).ok) continue;
24
+ return true;
25
+ }
26
+ return false;
27
+ }
28
+
29
+ // run the tests for one commit → 'green' | 'red' | 'skip'
30
+ async function accept(cfg, sha, release, say) {
31
+ const P = paths(cfg), R = cfg.robot, root = cfg.root;
32
+ if (!git(root, 'checkout', '-q', '--detach', sha).ok) { say(`cannot check out ${short(sha)} (is this checkout dirty?)`); return 'skip'; }
33
+ const depsChanged = !release || changedFiles(root, release, sha).some((f) => (R.installWhen || []).includes(f));
34
+ const noModules = fs.existsSync(path.join(root, 'package.json')) && !fs.existsSync(path.join(root, 'node_modules'));
35
+ if (R.install && (depsChanged || noModules)) {
36
+ say(`installing dependencies: ${R.install}`);
37
+ const inst = sh(R.install, { cwd: root, timeoutMs: 20 * 60e3, logFile: path.join(P.runs, `${short(sha)}.install.txt`) });
38
+ if (!inst.ok) return finish(cfg, sha, release, { ok: false, sec: inst.sec, reason: `install failed (exit ${inst.code})` }, say);
39
+ }
40
+ const timeoutMs = (R.timeoutMin || 60) * 60e3;
41
+ say(`testing ${short(sha)}: ${R.test}`);
42
+ let t = sh(R.test, { cwd: root, timeoutMs, logFile: path.join(P.runs, `${short(sha)}.txt`), env: { CI: '1', TRUNKGUARD: '1' } });
43
+ let tries = 1, flaky = false;
44
+ // a red run is re-run up to `retries` times: green only if a whole re-run passes (flaky runs are recorded)
45
+ while (!t.ok && tries <= (R.retries || 0)) {
46
+ say(`red (exit ${t.code}${t.timedOut ? ', timed out' : ''}) — re-run ${tries}/${R.retries}`);
47
+ t = sh(R.test, { cwd: root, timeoutMs, logFile: path.join(P.runs, `${short(sha)}.retry${tries}.txt`), env: { CI: '1', TRUNKGUARD: '1' } });
48
+ tries++;
49
+ if (t.ok) flaky = true;
50
+ }
51
+ return finish(cfg, sha, release, { ok: t.ok, sec: t.sec, flaky, reason: t.ok ? '' : `tests failed (exit ${t.code}${t.timedOut ? ', timed out' : ''})`, tail: t.out.slice(-1500) }, say);
52
+ }
53
+
54
+ async function finish(cfg, sha, release, res, say) {
55
+ const P = paths(cfg);
56
+ const subject = git(cfg.root, 'log', '-1', '--format=%s', sha).out.slice(0, 100);
57
+ if (!res.ok) {
58
+ writeJson(P.status, { at: new Date().toISOString(), sha, ok: false, reason: res.reason, sec: res.sec, subject });
59
+ appendLine(P.history, `${short(sha)} RED ${res.reason} (${res.sec}s) — ${subject}`);
60
+ say(`RED ${short(sha)}: ${res.reason} — release stays at ${short(release) || '(none)'}; log: ${path.join(P.runs, `${short(sha)}.txt`)}`);
61
+ await notify(cfg, 'red', `🔴 ${short(sha)} "${subject}" — ${res.reason}. ${cfg.releaseBranch} not moved.`);
62
+ return 'red';
63
+ }
64
+ // fast-forward only: if release was moved meanwhile, a non-ff push is refused
65
+ const p = git(cfg.root, 'push', cfg.remote, `${sha}:refs/heads/${cfg.releaseBranch}`);
66
+ writeJson(P.status, { at: new Date().toISOString(), sha, ok: true, flaky: !!res.flaky, sec: res.sec, released: p.ok, subject });
67
+ appendLine(P.history, `${short(sha)} GREEN (${res.sec}s)${res.flaky ? ' flaky' : ''}${p.ok ? ` → ${cfg.releaseBranch}` : ` — push refused: ${p.err.slice(0, 150)}`} — ${subject}`);
68
+ say(`GREEN ${short(sha)} (${res.sec}s)${res.flaky ? ', passed on re-run' : ''} — ${p.ok ? `${cfg.releaseBranch} = ${short(sha)}` : `push refused: ${p.err.slice(0, 200)}`}`);
69
+ await notify(cfg, p.ok ? 'green' : 'error', p.ok ? `🟢 ${short(sha)} "${subject}" → ${cfg.releaseBranch}` : `⚠️ ${short(sha)} passed but push to ${cfg.releaseBranch} was refused: ${p.err.slice(0, 150)}`);
70
+ return 'green';
71
+ }
72
+
73
+ // one pass: returns what happened, so tests and --once can use it
74
+ async function pass(cfg, memo, say) {
75
+ if (!fetchRefs(cfg)) { say('fetch failed — will retry'); return 'nofetch'; }
76
+ const main = revParse(cfg.root, `${cfg.remote}/${cfg.mainBranch}`);
77
+ const release = revParse(cfg.root, `${cfg.remote}/${cfg.releaseBranch}`);
78
+ if (!main || main === memo.done || main === release) return 'idle';
79
+ if (release && isAncestor(cfg.root, main, release)) { memo.done = main; return 'idle'; }
80
+ // compare with the last commit we already judged: after a red run, a docs-only fix does not re-run the same red code
81
+ const base = memo.done || release;
82
+ const files = base ? changedFiles(cfg.root, base, main) : ['(no release yet)'];
83
+ if (files.length && files.every((f) => matchAny(f, cfg.robot.skip))) {
84
+ // release is not moved for docs-only commits: the server would restart for nothing; the next code commit carries them
85
+ say(`${short(main)}: only skipped paths changed since ${short(base)} (${files.length} files) — no test run, no release`);
86
+ memo.done = main;
87
+ return 'skipped';
88
+ }
89
+ const r = await accept(cfg, main, release, say);
90
+ if (r !== 'skip') memo.done = main;
91
+ return r;
92
+ }
93
+
94
+ async function run(cfg, { once = false } = {}) {
95
+ const P = paths(cfg);
96
+ const say = logger('robot', P.log);
97
+ const l = lock(P.dir, 'robot');
98
+ if (!l.ok) { say(`already running (PID ${l.pid})`); return 3; }
99
+ const memo = { done: (readJson(P.status, {}) || {}).sha || '' };
100
+ say(`watching ${cfg.remote}/${cfg.mainBranch} → tests → ${cfg.remote}/${cfg.releaseBranch} (checkout ${cfg.root})`);
101
+ for (;;) {
102
+ const r = await pass(cfg, memo, say);
103
+ if (once) return r === 'red' ? 2 : 0;
104
+ if (r === 'green' || r === 'red') continue; // main may have moved during the run
105
+ await sleep((cfg.robot.pollSec || 60) * 1000);
106
+ }
107
+ }
108
+
109
+ module.exports = { run, pass, accept, paths };
package/src/serve.js ADDED
@@ -0,0 +1,219 @@
1
+ 'use strict';
2
+ // Supervisor for the live checkout. Keeps the app running and moves it to new release commits:
3
+ // new commit on <remote>/<release> → wait for a safe window (busyUrl) → stop app → git reset to it →
4
+ // install if lockfiles changed → optional check command → start app → health check (healthUrl answers 2xx,
5
+ // then the app must stay up for stableSec). Any failure → back to the previous commit, the bad commit is
6
+ // remembered and never deployed again automatically. Crashes outside a deploy → restart, with a limit.
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const { git, revParse, isAncestor, changedFiles, sh, start, stopTree, exited, short, sleep } = require('./proc');
10
+ const { lock, readJson, writeJson, logger, notify } = require('./util');
11
+
12
+ const TICK_MS = Number(process.env.TRUNKGUARD_TICK_MS) || 1000;
13
+
14
+ function paths(cfg) {
15
+ const dir = path.join(cfg.stateDir, 'serve');
16
+ return { dir, state: path.join(dir, 'state.json'), log: path.join(dir, 'serve.log'), trigger: path.join(dir, 'deploy-now'), runs: path.join(dir, 'runs') };
17
+ }
18
+
19
+ async function probe(url, timeoutMs = 5000) {
20
+ try { const r = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) }); return { ok: r.ok, status: r.status, body: await r.text().catch(() => '') }; }
21
+ catch (e) { return { ok: false, status: 0, body: e.message }; }
22
+ }
23
+
24
+ // busyUrl: 2xx {"busy":false} → free; {"busy":true,"why":"…"} or HTTP 423/503 → busy; unreachable → busy
25
+ async function safeWindow(cfg) {
26
+ if (!cfg.serve.busyUrl) return { ok: true, why: '' };
27
+ const r = await probe(cfg.serve.busyUrl);
28
+ if (r.status === 423 || r.status === 503) return { ok: false, why: `app is busy (HTTP ${r.status})` };
29
+ if (!r.ok) return { ok: false, why: `busyUrl unreachable (${r.status || r.body})` };
30
+ try { const j = JSON.parse(r.body || '{}'); return j.busy ? { ok: false, why: j.why || 'app is busy' } : { ok: true, why: '' }; }
31
+ catch { return { ok: true, why: '' }; }
32
+ }
33
+
34
+ class Serve {
35
+ constructor(cfg) {
36
+ this.cfg = cfg;
37
+ this.P = paths(cfg);
38
+ this.say = logger('serve', this.P.log);
39
+ this.child = null;
40
+ this.crashes = [];
41
+ this.lastPoll = 0;
42
+ this.stopping = false;
43
+ this.st = readJson(this.P.state, {}) || {};
44
+ this.st.bad = this.st.bad || [];
45
+ this.st.history = this.st.history || [];
46
+ }
47
+
48
+ save() { writeJson(this.P.state, this.st); }
49
+ head() { return revParse(this.cfg.root, 'HEAD'); }
50
+ record(rec) { this.st.history.push({ at: new Date().toISOString(), ...rec }); if (this.st.history.length > 50) this.st.history.splice(0, this.st.history.length - 50); this.save(); }
51
+
52
+ startApp() {
53
+ const S = this.cfg.serve;
54
+ this.child = start(S.start, { cwd: this.cfg.root, env: { ...(S.env || {}), TRUNKGUARD_SUPERVISED: '1' } });
55
+ this.child.startedAt = Date.now();
56
+ this.say(`app started at ${short(this.head())} (PID ${this.child.pid}): ${S.start}`);
57
+ }
58
+ async stopApp() { if (this.child) { await stopTree(this.child, (this.cfg.serve.stopTimeoutSec || 15) * 1000); this.child = null; } }
59
+
60
+ installIfNeeded(from, to) {
61
+ const S = this.cfg.serve;
62
+ if (!S.install || !from || !changedFiles(this.cfg.root, from, to).some((f) => (S.installWhen || []).includes(f))) return '';
63
+ this.say(`dependencies changed — ${S.install}`);
64
+ const r = sh(S.install, { cwd: this.cfg.root, timeoutMs: 20 * 60e3, logFile: path.join(this.P.runs, `${short(to)}.install.txt`) });
65
+ return r.ok ? '' : `install failed (exit ${r.code})`;
66
+ }
67
+
68
+ moveTo(to, from) {
69
+ const r = git(this.cfg.root, 'reset', '--hard', '-q', to);
70
+ if (!r.ok) return `git reset to ${short(to)} failed: ${r.err.slice(0, 200)}`;
71
+ const inst = this.installIfNeeded(from, to);
72
+ if (inst) return inst;
73
+ if (this.cfg.serve.check) {
74
+ const c = sh(this.cfg.serve.check, { cwd: this.cfg.root, timeoutMs: 10 * 60e3, logFile: path.join(this.P.runs, `${short(to)}.check.txt`) });
75
+ if (!c.ok) return `check command failed (exit ${c.code})`;
76
+ }
77
+ return '';
78
+ }
79
+
80
+ // healthy = healthUrl answers 2xx within healthTimeoutSec, then the app keeps running for stableSec
81
+ async healthy() {
82
+ const S = this.cfg.serve, child = this.child;
83
+ if (S.healthUrl) {
84
+ const until = Date.now() + (S.healthTimeoutSec || 60) * 1000;
85
+ let last = '';
86
+ for (;;) {
87
+ if (exited(child)) return `app exited (code ${child.exitCode}) before health check passed`;
88
+ const r = await probe(S.healthUrl);
89
+ if (r.ok) break;
90
+ last = r.status ? `HTTP ${r.status}` : r.body;
91
+ if (Date.now() > until) return `health check failed: ${S.healthUrl} → ${last}`;
92
+ await sleep(1000);
93
+ }
94
+ }
95
+ const stableUntil = Date.now() + (S.stableSec || 0) * 1000;
96
+ while (Date.now() < stableUntil) {
97
+ if (exited(child)) return `app exited (code ${child.exitCode}) within ${S.stableSec}s after start`;
98
+ if (S.healthUrl) { const r = await probe(S.healthUrl); if (!r.ok) return `health check failed after start: ${r.status ? `HTTP ${r.status}` : r.body}`; }
99
+ await sleep(1000);
100
+ }
101
+ return '';
102
+ }
103
+
104
+ async deploy(to) {
105
+ const from = this.head();
106
+ const subject = git(this.cfg.root, 'log', '-1', '--format=%s', to).out.slice(0, 100);
107
+ this.say(`deploying ${short(from)} → ${short(to)} "${subject}"`);
108
+ await this.stopApp();
109
+ let why = this.moveTo(to, from);
110
+ if (!why) { this.startApp(); why = await this.healthy(); }
111
+ if (!why) {
112
+ this.st.current = to; this.st.deployedAt = new Date().toISOString();
113
+ this.record({ result: 'ok', from, to, subject });
114
+ this.say(`deployed ${short(to)} — healthy`);
115
+ await notify(this.cfg, 'deployed', `✅ deployed ${short(to)} "${subject}"`);
116
+ return true;
117
+ }
118
+ await this.rollback(from, to, why, subject);
119
+ return false;
120
+ }
121
+
122
+ async rollback(from, to, why, subject = '') {
123
+ this.say(`ROLLBACK ${short(to)} → ${short(from)}: ${why}`);
124
+ await this.stopApp();
125
+ const r = git(this.cfg.root, 'reset', '--hard', '-q', from);
126
+ if (r.ok) this.installIfNeeded(to, from);
127
+ this.st.bad = [...new Set([...this.st.bad, to])].slice(-50);
128
+ this.record({ result: 'rolledBack', from, to, subject, reason: why });
129
+ await notify(this.cfg, 'rollback', `↩️ rolled back ${short(to)} "${subject}" → ${short(from)}: ${why}`);
130
+ if (!r.ok) { this.say(`cannot return to ${short(from)}: ${r.err.slice(0, 200)} — stopping`); return this.fatal(`rollback failed: ${r.err.slice(0, 150)}`); }
131
+ this.startApp();
132
+ const after = await this.healthy();
133
+ if (after) return this.fatal(`app is unhealthy even after rollback to ${short(from)}: ${after}`);
134
+ this.say(`back on ${short(from)} — healthy`);
135
+ }
136
+
137
+ async fatal(msg) {
138
+ this.say(`STOPPED: ${msg}`);
139
+ await notify(this.cfg, 'stopped', `⛔ stopped: ${msg}`);
140
+ this.stopping = true;
141
+ await this.stopApp();
142
+ this.exitCode = 1;
143
+ }
144
+
145
+ // is there a release commit we should deploy now?
146
+ candidate() {
147
+ const { root, remote, releaseBranch } = this.cfg;
148
+ git(root, 'fetch', '-q', remote, `+refs/heads/${releaseBranch}:refs/remotes/${remote}/${releaseBranch}`);
149
+ const rel = revParse(root, `${remote}/${releaseBranch}`), head = this.head();
150
+ if (!rel || rel === head) return { status: 'uptodate' };
151
+ if (this.st.bad.includes(rel)) return { status: 'bad', why: `${short(rel)} was rolled back before` };
152
+ if (!isAncestor(root, head, rel)) return { status: 'diverged', why: `${short(head)} is not in ${releaseBranch}` };
153
+ if (git(root, 'status', '--porcelain', '--untracked-files=no').out) return { status: 'dirty', why: 'tracked files were edited by hand in the live checkout' };
154
+ return { status: 'available', to: rel };
155
+ }
156
+
157
+ async onCrash(code) {
158
+ const C = this.cfg.serve.crash || {};
159
+ const life = Math.round((Date.now() - (this.child ? this.child.startedAt : Date.now())) / 1000);
160
+ this.child = null;
161
+ const now = Date.now();
162
+ this.crashes.push(now);
163
+ while (this.crashes.length && now - this.crashes[0] > (C.spanMin || 10) * 60e3) this.crashes.shift();
164
+ if (this.crashes.length >= (C.max || 3)) return this.fatal(`app crashed ${this.crashes.length} times in ${C.spanMin || 10} min (last exit code ${code})`);
165
+ this.say(`app crashed (exit ${code}) after ${life}s — restart in ${C.delaySec ?? 5}s (${this.crashes.length}/${C.max || 3})`);
166
+ await notify(this.cfg, 'crash', `⚠️ app crashed (exit ${code}) after ${life}s — restarting (${this.crashes.length}/${C.max || 3})`);
167
+ await sleep((C.delaySec ?? 5) * 1000);
168
+ if (!this.stopping) this.startApp();
169
+ }
170
+
171
+ async loop() {
172
+ const S = this.cfg.serve;
173
+ this.startApp();
174
+ let waitingWhy = '';
175
+ while (!this.stopping) {
176
+ await sleep(TICK_MS);
177
+ if (this.stopping) break;
178
+ if (this.child && exited(this.child)) { await this.onCrash(this.child.exitCode); continue; }
179
+ const forced = fs.existsSync(this.P.trigger);
180
+ if (!forced && Date.now() - this.lastPoll < (S.pollSec || 300) * 1000) continue;
181
+ this.lastPoll = Date.now();
182
+ const c = this.candidate();
183
+ if (c.status !== 'available') {
184
+ if (forced) { try { fs.unlinkSync(this.P.trigger); } catch { /* gone */ } }
185
+ if (c.why && c.why !== this.lastWhy) { this.lastWhy = c.why; this.say(`not deploying: ${c.why}`); }
186
+ continue;
187
+ }
188
+ if (!S.auto && !forced) {
189
+ if (c.to !== this.notified) { this.notified = c.to; this.say(`${short(c.to)} is ready — run "trunkguard deploy"`); await notify(this.cfg, 'available', `🆕 ${short(c.to)} is ready to deploy`); }
190
+ continue;
191
+ }
192
+ const w = await safeWindow(this.cfg);
193
+ if (!w.ok) { if (w.why !== waitingWhy) { waitingWhy = w.why; this.say(`waiting for a safe window: ${w.why}`); } this.lastPoll = 0; continue; }
194
+ waitingWhy = '';
195
+ if (forced) { try { fs.unlinkSync(this.P.trigger); } catch { /* gone */ } }
196
+ await this.deploy(c.to);
197
+ }
198
+ await this.stopApp();
199
+ return this.exitCode || 0;
200
+ }
201
+ }
202
+
203
+ async function run(cfg) {
204
+ const P = paths(cfg);
205
+ if (!cfg.serve.start) throw new Error('serve.start is empty in trunkguard.json — the command that runs your app');
206
+ const l = lock(P.dir, 'serve');
207
+ if (!l.ok) { console.log(`[serve] already running (PID ${l.pid})`); return 3; }
208
+ const s = new Serve(cfg);
209
+ const stop = () => { if (!s.stopping) { s.say('stopping (signal)'); s.stopping = true; } };
210
+ process.on('SIGINT', stop);
211
+ process.on('SIGTERM', stop);
212
+ s.say(`watching ${cfg.remote}/${cfg.releaseBranch}, auto deploy ${cfg.serve.auto ? 'on' : 'off'}, health ${cfg.serve.healthUrl || '(process only)'}`);
213
+ return s.loop();
214
+ }
215
+
216
+ // "trunkguard deploy": ask a running serve to deploy now (even with auto off)
217
+ function requestDeploy(cfg) { const P = paths(cfg); fs.mkdirSync(P.dir, { recursive: true }); fs.writeFileSync(P.trigger, new Date().toISOString()); return P.trigger; }
218
+
219
+ module.exports = { run, Serve, paths, safeWindow, requestDeploy };
package/src/status.js ADDED
@@ -0,0 +1,37 @@
1
+ 'use strict';
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const { git, revParse, short } = require('./proc');
5
+ const { readJson, holder, alive } = require('./util');
6
+ const robot = require('./robot');
7
+ const serve = require('./serve');
8
+
9
+ function tail(file, n) { try { return fs.readFileSync(file, 'utf8').trim().split('\n').slice(-n); } catch { return []; } }
10
+
11
+ function report(cfg) {
12
+ const { root, remote, mainBranch: m, releaseBranch: r } = cfg;
13
+ git(root, 'fetch', '-q', remote);
14
+ const head = revParse(root, 'HEAD'), main = revParse(root, `${remote}/${m}`), rel = revParse(root, `${remote}/${r}`);
15
+ const behind = rel && main ? git(root, 'rev-list', '--count', `${rel}..${main}`).out : '?';
16
+ const RP = robot.paths(cfg), SP = serve.paths(cfg);
17
+ const running = (dir, name) => { const pid = holder(path.join(dir, `${name}.pid`)); return pid && alive(pid) ? `running (PID ${pid})` : 'not running'; };
18
+ const rs = readJson(RP.status, null), ss = readJson(SP.state, null);
19
+ const lines = [
20
+ `checkout ${root}`,
21
+ `HEAD ${short(head)} ${git(root, 'log', '-1', '--format=%s', head).out.slice(0, 70)}`,
22
+ `${m.padEnd(10)} ${short(main) || '—'}`,
23
+ `${r.padEnd(10)} ${short(rel) || '— (not created yet)'} ${behind !== '?' && behind !== '0' ? `${behind} commit(s) on ${m} not released yet` : ''}`,
24
+ '',
25
+ `robot ${running(RP.dir, 'robot')}`,
26
+ rs ? ` last run ${short(rs.sha)} ${rs.ok ? 'GREEN' : 'RED'} ${rs.ok ? '' : rs.reason} (${rs.at})` : ' no runs here (the robot runs in its own checkout)',
27
+ ...tail(RP.history, 5).map((l) => ` ${l}`),
28
+ '',
29
+ `serve ${running(SP.dir, 'serve')}`,
30
+ ss && ss.current ? ` current ${short(ss.current)} since ${ss.deployedAt}` : ' no deploys recorded in this checkout',
31
+ ss && ss.bad && ss.bad.length ? ` blocked ${ss.bad.slice(-5).map(short).join(', ')} (rolled back — never redeployed; push a fix to main)` : '',
32
+ ...((ss && ss.history) || []).slice(-5).map((h) => ` ${h.at} ${h.result} ${short(h.from)} → ${short(h.to)}${h.reason ? ` — ${h.reason}` : ''}`),
33
+ ];
34
+ return lines.filter((l) => l !== null).join('\n');
35
+ }
36
+
37
+ module.exports = { report };
package/src/util.js ADDED
@@ -0,0 +1,56 @@
1
+ 'use strict';
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+
5
+ // ---- single instance lock: <dir>/<name>.pid holds the owner's PID ----
6
+ function alive(pid) {
7
+ if (!pid || !Number.isInteger(pid)) return false;
8
+ try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
9
+ }
10
+ const holder = (file) => { try { return Number(String(fs.readFileSync(file, 'utf8')).trim()) || 0; } catch { return 0; } };
11
+ function lock(dir, name) {
12
+ fs.mkdirSync(dir, { recursive: true });
13
+ const file = path.join(dir, `${name}.pid`);
14
+ const pid = holder(file);
15
+ if (pid && pid !== process.pid && alive(pid)) return { ok: false, pid, file };
16
+ fs.writeFileSync(file, String(process.pid));
17
+ process.on('exit', () => { try { if (holder(file) === process.pid) fs.unlinkSync(file); } catch { /* gone */ } });
18
+ return { ok: true, pid: process.pid, file };
19
+ }
20
+
21
+ // ---- JSON state written atomically ----
22
+ function readJson(file, dflt) { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return dflt; } }
23
+ function writeJson(file, obj) {
24
+ fs.mkdirSync(path.dirname(file), { recursive: true });
25
+ fs.writeFileSync(`${file}.tmp`, JSON.stringify(obj, null, 1));
26
+ fs.renameSync(`${file}.tmp`, file);
27
+ }
28
+ const appendLine = (file, line) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.appendFileSync(file, `${new Date().toISOString()} ${line}\n`); };
29
+
30
+ // ---- logging ----
31
+ function logger(tag, file) {
32
+ return (msg) => {
33
+ const line = `${new Date().toISOString().slice(0, 19).replace('T', ' ')} [${tag}] ${msg}`;
34
+ console.log(line);
35
+ if (file) { try { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.appendFileSync(file, `${line}\n`); } catch { /* best effort */ } }
36
+ };
37
+ }
38
+
39
+ // ---- notifications: Telegram and/or a webhook, best effort ----
40
+ async function notify(cfg, event, text) {
41
+ const n = cfg.notify || {};
42
+ if (event === 'green' && !n.onGreen) return;
43
+ const jobs = [];
44
+ if (n.telegram && n.telegram.token && n.telegram.chatId) {
45
+ const base = process.env.TRUNKGUARD_TG_API || 'https://api.telegram.org';
46
+ jobs.push(fetch(`${base}/bot${n.telegram.token}/sendMessage`, { method: 'POST', headers: { 'Content-Type': 'application/json' },
47
+ body: JSON.stringify({ chat_id: n.telegram.chatId, text: `trunkguard: ${text}` }), signal: AbortSignal.timeout(15000) }));
48
+ }
49
+ if (n.webhook) {
50
+ jobs.push(fetch(n.webhook, { method: 'POST', headers: { 'Content-Type': 'application/json' },
51
+ body: JSON.stringify({ source: 'trunkguard', event, text }), signal: AbortSignal.timeout(15000) }));
52
+ }
53
+ await Promise.allSettled(jobs);
54
+ }
55
+
56
+ module.exports = { alive, holder, lock, readJson, writeJson, appendLine, logger, notify };