Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(cli): penguin version reports build and harness information (#382)

Myriad-Dreamin46a26dda0b53
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 5ca150bd..28280b9e 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -179,6 +179,19 @@ jobs:
# BRE: the unescaped | in these patterns is literal (grep/sed default to POSIX BRE, where | is not alternation).
grep -q 'export const BUILD_DATE: string | null = ' packages/core/src/index.ts
sed -i "s/export const BUILD_DATE: string | null = [^;]*/export const BUILD_DATE: string | null = \"$D\"/" packages/core/src/index.ts
+ # The commit is what separates two builds of the same version, which BUILD_DATE cannot:
+ # a release and a same-day rebuild share a date. GITHUB_SHA is the checked-out tag's sha
+ # and needs no git, which matters because the checkout is shallow and carries no tags.
+ # Absence is tolerated rather than guarded, on both arms: tags predating this constant
+ # must stay rebuildable, and a replay outside Actions has no GITHUB_SHA to stamp.
+ if ! grep -q 'export const BUILD_COMMIT: string | null = ' packages/core/src/index.ts; then
+ echo "Legacy tag without a BUILD_COMMIT constant; leaving the commit unstamped."
+ elif [ -z "${GITHUB_SHA:-}" ]; then
+ echo "GITHUB_SHA is unset; leaving the commit unstamped."
+ else
+ sed -i "s/export const BUILD_COMMIT: string | null = [^;]*/export const BUILD_COMMIT: string | null = \"$GITHUB_SHA\"/" packages/core/src/index.ts
+ grep -Fq "export const BUILD_COMMIT: string | null = \"$GITHUB_SHA\"" packages/core/src/index.ts
+ fi
- name: Build (tsup + vite)
run: pnpm build
@@ -594,6 +607,19 @@ jobs:
# BRE: the unescaped | in these patterns is literal (grep/sed default to POSIX BRE, where | is not alternation).
grep -q 'export const BUILD_DATE: string | null = ' packages/core/src/index.ts
sed -i "s/export const BUILD_DATE: string | null = [^;]*/export const BUILD_DATE: string | null = \"$D\"/" packages/core/src/index.ts
+ # The commit is what separates two builds of the same version, which BUILD_DATE cannot:
+ # a release and a same-day rebuild share a date. GITHUB_SHA is the checked-out tag's sha
+ # and needs no git, which matters because the checkout is shallow and carries no tags.
+ # Absence is tolerated rather than guarded, on both arms: tags predating this constant
+ # must stay rebuildable, and a replay outside Actions has no GITHUB_SHA to stamp.
+ if ! grep -q 'export const BUILD_COMMIT: string | null = ' packages/core/src/index.ts; then
+ echo "Legacy tag without a BUILD_COMMIT constant; leaving the commit unstamped."
+ elif [ -z "${GITHUB_SHA:-}" ]; then
+ echo "GITHUB_SHA is unset; leaving the commit unstamped."
+ else
+ sed -i "s/export const BUILD_COMMIT: string | null = [^;]*/export const BUILD_COMMIT: string | null = \"$GITHUB_SHA\"/" packages/core/src/index.ts
+ grep -Fq "export const BUILD_COMMIT: string | null = \"$GITHUB_SHA\"" packages/core/src/index.ts
+ fi
(cd packages/skills && npm version --no-git-tag-version --allow-same-version "$V")
(cd packages/core && npm version --no-git-tag-version --allow-same-version "$V")
(cd packages/server && npm version --no-git-tag-version --allow-same-version "$V")
diff --git a/changelog/unreleased/2026-08-20-build-identity.md b/changelog/unreleased/2026-08-20-build-identity.md
new file mode 100644
index 00000000..ae12f6d0
--- /dev/null
+++ b/changelog/unreleased/2026-08-20-build-identity.md
@@ -0,0 +1,36 @@
+# penguin version reports which build is running
+
+- **Date:** 2026-08-20
+- **Type:** feature
+- **Scope:** `cli`, `core`, `server`, `docs`, `ci`
+- **PR:** [#382](https://github.com/Prism-Shadow/penguin-harness/pull/382)
+
+[中文版](2026-08-20-build-identity.zh.md)
+
+Added `penguin version`, which prints the running build's identity as one line — `v0.2.3` for a release, and `git describe --tags --dirty` output such as `v0.2.3-14-g9e8f7d6-dirty` for a build made from a checkout. `-v, --version` prints that same line. `penguin version --json` prints the full record, and `GET /api/version` serves that same record, so the two cannot report different things about one install.
+
+The record's `harness` half names what a hot update pushed to the machine, read from that data root's HMR store. A pushed bundle lands outside any checkout, so its revision reaches the target twice over: inlined into the artifact at build time, and recorded beside it in `harness.json`.
+
+## Details
+
+- Core gained `buildInfo()`, the single producer of the `BuildInfo` record: `version`, `describe`, `channel` (`release` or `source`), `buildDate`, `commit`, `branch`, `dirty`, and a `runtime` block naming the Node version, platform and architecture. The CLI and the version route render it and add nothing of their own.
+- A release carries its identity in constants: the release workflow already stamped `VERSION` and `BUILD_DATE`, and now stamps `BUILD_COMMIT` with the tag's commit sha from `GITHUB_SHA`. Both stamping jobs — release artifacts and npm publish — stamp it, so the two channels report the same commit. Tags cut before the constant existed, and replays outside Actions, are stamped as far as they can be and report the rest as unstamped rather than failing.
+- Every other build has its git position — description, commit, branch, dirty flag — inlined into the artifact by the bundler that produced it, from one shared `scripts/build-git-stamp.mjs` wired into core, cli and desktop's tsup configs and into `scripts/deploy.mjs`'s esbuild. A built artifact carries no path back to its origin: a bundle pushed into `<root>/hmr/store/` sits outside any checkout, and the working directory would answer about the user's own repository. The stamp holds nothing that varies between two builds of identical source, so the HMR store's content addressing still collapses a re-push of unchanged code onto one entry.
+- The inlined stamp wins over asking git at run time, because it describes the code that is executing rather than whatever the surrounding tree has moved on to: a stale `dist/` in a checkout ten commits further along reports the revision it was built at.
+- An installed penguin never runs git; it reads those constants. Asking git is the fallback for an un-bundled run — `tsx`, `vitest`, `pnpm dev` — and asks only about the checkout the running module sits in, located by walking up from its own directory for a directory holding both `.git` and `pnpm-workspace.yaml`. Starting from the module rather than the working directory is what makes `penguin version` report the harness's revision when it is run inside another repository; requiring the workspace marker is what keeps an install that merely sits under an unrelated repository — a home directory that is itself a dotfiles repo — from reporting that repository's commits. A linked worktree, where `.git` is a file, is recognized.
+- `dirty` is null rather than false for a release: the workflow stamps its constants into the tree before building, so cleanliness is not a property of a release artifact.
+- `scripts/test-installer.sh` replays the workflow's stamping block against fixtures covering a stamped commit, a run with no `GITHUB_SHA`, and a tag whose source predates the constant.
+
+## Harness provenance
+
+- `scripts/deploy.mjs` now sends the `source` the upgrade protocol already carried, filling it from its own checkout: `revision` is spelled exactly as `describe`, `-dirty` included, because a deploy from an uncommitted tree is ordinary and the sha alone would name code that never existed. A push from outside a git checkout carries no `source` rather than a fabricated one.
+- `HmrHost.persistVersion` commits that `source` to `harness.json` alongside a `pushedAt` timestamp, so provenance travels with the version it describes. The upgrade route accepts `source` only when both halves are non-empty strings — it now outlives the request, and a malformed record would outlive the push that sent it.
+- `readHarnessInfo` in `hmr/manifest.ts` reads it back defensively, degrading to null fields rather than throwing: the command a user runs to find out what is wrong must not be the one that breaks. Versions committed before provenance existed report their bundle pointers with a null `source`.
+- The `harness` field describes the data root's store, not the reporting process. `penguin` runs the packaged CLI while `penguin-hmr` runs the store's, so a non-null `harness` does not by itself mean the command printing it is the pushed code.
+- `versionReport()` — a new `@prismshadow/penguin-server/version-report` entry point — joins core's `buildInfo()` with that reader, and both the CLI and the version route render it. Neither layer can produce the other half: core knows the artifact and nothing about data roots, the store knows the root and nothing about the process reading it.
+
+## Compatibility
+
+`GET /api/version` gained fields and removed none; `version` and `buildDate` keep their meanings, so existing clients are unaffected. `VersionResponse` became an alias of core's `VersionReport`, which is a widening for any TypeScript consumer that reads the two original fields.
+
+`harness.json` gained two optional fields. Older records read back with `source` and `pushedAt` null and are never rewritten; nothing re-pushes on their behalf, so a root keeps reporting a null provenance until its next hot update. No migration is needed and none is performed.
diff --git a/changelog/unreleased/2026-08-20-build-identity.zh.md b/changelog/unreleased/2026-08-20-build-identity.zh.md
new file mode 100644
index 00000000..96f72b4c
--- /dev/null
+++ b/changelog/unreleased/2026-08-20-build-identity.zh.md
@@ -0,0 +1,36 @@
+# penguin version 报告当前运行的是哪个构建
+
+- **Date:** 2026-08-20
+- **Type:** feature
+- **Scope:** `cli`, `core`, `server`, `docs`, `ci`
+- **PR:** [#382](https://github.com/Prism-Shadow/penguin-harness/pull/382)
+
+[English](2026-08-20-build-identity.md)
+
+新增 `penguin version`,以单行输出当前构建的身份:发布版为 `v0.2.3`,源码 checkout 构建则为 `git describe --tags --dirty` 的结果,形如 `v0.2.3-14-g9e8f7d6-dirty`。`-v, --version` 输出同一行。`penguin version --json` 输出完整记录,`GET /api/version` 提供的正是同一份记录,因此两者不会对同一个安装给出不同说法。
+
+记录中的 `harness` 部分说明这台机器上被热更新推送的是什么,取自该数据根目录的 HMR store。推送过去的 bundle 落在任何 checkout 之外,因此它的 revision 会以两条路径抵达目标机器:构建时内联进产物本身,以及记录在其旁边的 `harness.json` 中。
+
+## 细节
+
+- core 新增 `buildInfo()`,作为 `BuildInfo` 记录的唯一生产者:`version`、`describe`、`channel`(`release` 或 `source`)、`buildDate`、`commit`、`branch`、`dirty`,以及记录 Node 版本、平台与架构的 `runtime` 块。CLI 与 version 路由只负责呈现,不添加任何自己的字段。
+- 发布版的身份由常量携带:发布流程原本就打入 `VERSION` 与 `BUILD_DATE`,现在还会用 `GITHUB_SHA` 打入 tag 所在提交的 `BUILD_COMMIT`。发布产物与 npm 发布这两个打入任务都会写入,因此两条发布通道报告的是同一个提交。早于该常量的旧 tag、以及在 Actions 之外的重放,会尽可能打入,其余部分如实报告为未打入,而不是直接失败。
+- 其余构建的 git 位置——描述、提交、分支、是否有未提交改动——由生成它的打包器内联进产物,取值来自同一个 `scripts/build-git-stamp.mjs`,接入 core、cli、desktop 的 tsup 配置以及 `scripts/deploy.mjs` 的 esbuild。构建产物没有任何回溯到其来源的路径:被推送到 `<root>/hmr/store/` 的 bundle 位于任何 checkout 之外,而工作目录给出的是用户自己仓库的答案。该 stamp 不含任何在相同源码的两次构建之间会变化的内容,因此 HMR store 的内容寻址依然能把未改动代码的重复推送归并为同一个条目。
+- 内联的 stamp 优先于运行时询问 git,因为它描述的是正在执行的代码,而非其周围工作树此后的走向:位于已前进十个提交的 checkout 中的旧 `dist/`,报告的是它被构建时的 revision。
+- 已安装的 penguin 从不执行 git,只读取这些常量。询问 git 只是未经打包运行(`tsx`、`vitest`、`pnpm dev`)时的兜底,且只询问运行中模块所在的那个 checkout——从其自身所在目录逐级向上,寻找同时含有 `.git` 与 `pnpm-workspace.yaml` 的目录来定位。以模块而非工作目录为起点,正是「在别的仓库里执行 `penguin version` 仍报告 harness 自身版本」的原因;要求 workspace 标记存在,则避免了仅仅位于某个无关仓库之下的安装(例如家目录本身就是 dotfiles 仓库)报告出该仓库的提交。`.git` 为文件的 linked worktree 同样能被识别。
+- 发布版的 `dirty` 是 null 而非 false:发布流程会先把常量写进工作区再构建,因此「是否干净」对发布产物本就不是一个属性。
+- `scripts/test-installer.sh` 会把发布流程的打入代码块对着 fixture 重放,覆盖成功打入提交、无 `GITHUB_SHA` 运行、以及源码早于该常量的 tag 三种情形。
+
+## Harness 来源信息
+
+- `scripts/deploy.mjs` 现在会填上升级协议本就带有的 `source`,取自它自身的 checkout:`revision` 的拼写与 `describe` 完全一致,包含 `-dirty`——从有未提交改动的工作区部署在这里是常态,而仅凭 sha 会指向一份从未存在过的代码。不在 git checkout 中发起的推送则不带 `source`,而非编造一个。
+- `HmrHost.persistVersion` 会把该 `source` 连同 `pushedAt` 时间戳一并提交进 `harness.json`,使来源信息与它所描述的版本同行。升级路由仅在两个字段都是非空字符串时才接受 `source`——它现在会比请求活得更久,格式错误的记录会比产生它的那次推送活得更久。
+- `hmr/manifest.ts` 中的 `readHarnessInfo` 以容错方式读回:字段缺失时退化为 null 而非抛错——用户为排查问题才执行的命令,不能反过来成为出错的那一个。在来源机制存在之前提交的版本,会带着 null 的 `source` 报告其 bundle 指针。
+- `harness` 字段描述的是数据根目录的 store,而非上报它的进程。`penguin` 运行随包发布的 CLI,`penguin-hmr` 才运行 store 里的那份,因此 `harness` 非 null 本身并不意味着打印它的这条命令就是被推送的代码。
+- 新增入口 `@prismshadow/penguin-server/version-report` 提供的 `versionReport()` 将 core 的 `buildInfo()` 与该读取器合并,CLI 与 version 路由都渲染它。任何一层都无法独自产出另一半:core 只了解制品、不了解数据根目录,store 只了解根目录、不了解读取它的进程。
+
+## 兼容性
+
+`GET /api/version` 只增字段、未删字段;`version` 与 `buildDate` 含义不变,现有客户端不受影响。`VersionResponse` 改为 core 中 `VersionReport` 的别名,对只读取原有两个字段的 TypeScript 消费方而言是一次放宽。
+
+`harness.json` 新增两个可选字段。旧记录读回时 `source` 与 `pushedAt` 为 null,且不会被改写;也没有任何机制代其重新推送,因此某个根目录会一直报告 null 来源,直到它下一次热更新为止。无需迁移,也不执行任何迁移。
diff --git a/packages/cli/src/commands/version.ts b/packages/cli/src/commands/version.ts
new file mode 100644
index 00000000..5cc13b0c
--- /dev/null
+++ b/packages/cli/src/commands/version.ts
@@ -0,0 +1,41 @@
+/**
+ * `penguin version` — what is running here.
+ *
+ * Two audiences, one producer. Bare, it prints the single line core computed as the build's
+ * identity, which for a source build is git's own description (`v0.2.3-14-g9e8f7d6-dirty`)
+ * and for a release is the plain `v0.2.3`. With `--json` it prints the whole VersionReport,
+ * the same record GET /api/version serves — a bug report can be filed from either side of
+ * the HTTP boundary and say the same thing.
+ *
+ * The JSON carries a second half the line cannot: the harness this data root has in its HMR
+ * store — what a hot update put there, which a restart resumes. It is a property of the root
+ * rather than of this process, so it answers "what was pushed to this machine" where the line
+ * answers "what am I". The two differ whenever `penguin` runs the packaged CLI on a machine
+ * that has a pushed one in its store.
+ *
+ * The subcommand exists alongside `-v, --version` rather than replacing it: both render
+ * `describe`, so they agree, but a subcommand can take options where the global flag cannot
+ * (see update.ts on how commander's program-level `--version` swallows a subcommand's own).
+ */
+import path from "node:path";
+import type { Command } from "commander";
+import { buildInfo, resolveRoot } from "@prismshadow/penguin-core";
+import { versionReport } from "@prismshadow/penguin-server/version-report";
+import type { Messages } from "../i18n.js";
+
+export function registerVersionCommand(program: Command, t: Messages): void {
+ program
+ .command("version")
+ .description(t.version.description)
+ .option("--json", t.version.json)
+ .option("--root <dir>", t.common.root)
+ .action(async (options: { json?: boolean; root?: string }) => {
+ if (options.json !== true) {
+ // The one-line form is a property of the artifact alone, so it never reads a root.
+ process.stdout.write(`${buildInfo().describe}\n`);
+ return;
+ }
+ const root = options.root !== undefined ? path.resolve(options.root) : resolveRoot();
+ process.stdout.write(`${JSON.stringify(await versionReport(root), null, 2)}\n`);
+ });
+}
diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.ts
index b34fdf9b..6153f9ac 100644
--- a/packages/cli/src/i18n.ts
+++ b/packages/cli/src/i18n.ts
@@ -109,6 +109,11 @@ export interface Messages {
/** Hint printed below the notice. */
next(): string;
};
+ /** `penguin version`: help text only — the command's output is data, never prose. */
+ version: {
+ description: string;
+ json: string;
+ };
/** `penguin update`: help text and every line the command can print. */
update: {
desc: string;
@@ -427,6 +432,10 @@ const en: Messages = {
`Admin password reset for data root ${root}. All admin sign-in sessions were cleared.`,
next: () => "Start the service (`penguin web`) and sign in with the password above.",
},
+ version: {
+ description: "Show which build is running",
+ json: "Print the full build info as JSON (the body of GET /api/version)",
+ },
update: {
desc: "Upgrade this PenguinHarness install in place",
check: "Only report the current and latest versions; change nothing",
@@ -707,6 +716,10 @@ const zh: Messages = {
done: (root) => `已重置数据根目录 ${root} 的管理员密码,并清空其全部登录会话。`,
next: () => "启动服务(`penguin web`)后用上方密码登录。",
},
+ version: {
+ description: "显示当前运行的是哪个构建",
+ json: "以 JSON 输出完整构建信息(即 GET /api/version 的响应体)",
+ },
update: {
desc: "原地升级当前的 PenguinHarness 安装",
check: "只报告当前版本与最新版本,不做任何修改",
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index af21b798..914cad4c 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -7,12 +7,13 @@
* the HMR store instead (see scripts/deploy.mjs).
*/
import { Command, CommanderError } from "commander";
-import { VERSION } from "@prismshadow/penguin-core";
+import { buildInfo } from "@prismshadow/penguin-core";
import { registerConfigCommand } from "./commands/config.js";
import { registerRunCommand } from "./commands/run.js";
import { registerChatCommand } from "./commands/chat.js";
import { registerServeCommands } from "./commands/serve.js";
import { registerUpdateCommand } from "./commands/update.js";
+import { registerVersionCommand } from "./commands/version.js";
import { defaultMessages } from "./i18n.js";
/**
@@ -26,7 +27,10 @@ export async function cli(argv: string[]): Promise<number> {
program
.name("penguin")
.description(t.cliDescription)
- .version(VERSION, "-v, --version", t.versionDesc)
+ // The same string `penguin version` prints, so the flag and the subcommand can never
+ // disagree. Commander stores it eagerly, which costs a source build its two git calls on
+ // every startup; a release build reads stamped constants and spawns nothing.
+ .version(buildInfo().describe, "-v, --version", t.versionDesc)
.exitOverride();
registerConfigCommand(program, t);
@@ -34,6 +38,7 @@ export async function cli(argv: string[]): Promise<number> {
registerChatCommand(program, t);
registerServeCommands(program, t);
registerUpdateCommand(program, t);
+ registerVersionCommand(program, t);
// Show help only when no subcommand is given (empty input); do not error.
program.action(() => {
diff --git a/packages/cli/test/version.test.ts b/packages/cli/test/version.test.ts
new file mode 100644
index 00000000..10339dc3
--- /dev/null
+++ b/packages/cli/test/version.test.ts
@@ -0,0 +1,111 @@
+/**
+ * `penguin version`: the two output modes, and the property that `-v` cannot drift from the
+ * subcommand. Both render core's buildInfo() and add nothing, so the assertions compare
+ * against that producer rather than against literals — the release workflow stamps core's
+ * constants before it runs these tests, and a hardcoded version would only fail there.
+ */
+import fsp from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { Command } from "commander";
+import { buildInfo } from "@prismshadow/penguin-core";
+import type { VersionReport } from "@prismshadow/penguin-core/interfaces";
+import { versionReport } from "@prismshadow/penguin-server/version-report";
+import { registerVersionCommand } from "../src/commands/version.js";
+import { cli } from "../src/index.js";
+import { getMessages } from "../src/i18n.js";
+
+/** Collects everything `body` writes to stdout, alongside whatever it returns. */
+async function captureStdout<T>(body: () => Promise<T>): Promise<{ out: string; result: T }> {
+ const written: string[] = [];
+ const original = process.stdout.write.bind(process.stdout);
+ process.stdout.write = ((chunk: string | Uint8Array) => {
+ written.push(typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8"));
+ return true;
+ }) as typeof process.stdout.write;
+ try {
+ const result = await body();
+ return { out: written.join(""), result };
+ } finally {
+ process.stdout.write = original;
+ }
+}
+
+/** Runs one argv through a bare program carrying only the version command; returns stdout. */
+async function run(argv: string[]): Promise<string> {
+ const program = new Command();
+ program.exitOverride();
+ registerVersionCommand(program, getMessages("en"));
+ const { out } = await captureStdout(() => program.parseAsync(argv, { from: "user" }));
+ return out;
+}
+
+describe("penguin version", () => {
+ it("prints the one-line identity and nothing else", async () => {
+ expect(await run(["version"])).toBe(`${buildInfo().describe}\n`);
+ });
+
+ it("prints the whole version report as JSON under --json", async () => {
+ const root = await fsp.mkdtemp(path.join(os.tmpdir(), "penguin-cli-version-"));
+ try {
+ const out = await run(["version", "--json", "--root", root]);
+ expect(JSON.parse(out)).toEqual(await versionReport(root));
+ // Indented, because a human reads this out of a bug report.
+ expect(out).toContain("\n ");
+ } finally {
+ await fsp.rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it("reports the harness pushed to the root it was pointed at", async () => {
+ // What the version line cannot carry: the store describes the ROOT, not this process,
+ // so it still answers when the packaged CLI runs on a machine holding a pushed one.
+ const root = await fsp.mkdtemp(path.join(os.tmpdir(), "penguin-cli-version-"));
+ try {
+ await fsp.mkdir(path.join(root, "hmr"), { recursive: true });
+ await fsp.writeFile(
+ path.join(root, "hmr", "harness.json"),
+ JSON.stringify({
+ cli: { bundle: "store/cli/abc123.mjs" },
+ source: { repo: "https://example.com/penguin.git", revision: "v0.2.3-7-gabc1234-dirty" },
+ pushedAt: "2026-08-20T10:15:00.000Z",
+ }),
+ );
+
+ const report = JSON.parse(await run(["version", "--json", "--root", root])) as VersionReport;
+ expect(report.harness?.source?.revision).toBe("v0.2.3-7-gabc1234-dirty");
+ expect(report.harness?.pushedAt).toBe("2026-08-20T10:15:00.000Z");
+ expect(report.harness?.bundles.cli).toBe("store/cli/abc123.mjs");
+ } finally {
+ await fsp.rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it("omits a harness for a root with nothing pushed", async () => {
+ const root = await fsp.mkdtemp(path.join(os.tmpdir(), "penguin-cli-version-"));
+ try {
+ const report = JSON.parse(await run(["version", "--json", "--root", root])) as VersionReport;
+ expect(report.harness).toBeNull();
+ } finally {
+ await fsp.rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it("describes this build in a form that names a version", async () => {
+ // Not `v${version}`: git's tag description names the nearest reachable tag, which lags
+ // the constant for the whole of release preparation. `v` and a digit is the guarantee.
+ expect(buildInfo().describe).toMatch(/^v\d/);
+ });
+
+ it("agrees with -v", async () => {
+ const { out } = await captureStdout(() => cli(["-v"]));
+ expect(out).toBe(`${buildInfo().describe}\n`);
+ });
+
+ it("is reachable as a subcommand of the real CLI", async () => {
+ const { out, result } = await captureStdout(() => cli(["version"]));
+ expect(result).toBe(0);
+ expect(out).toBe(`${buildInfo().describe}\n`);
+ });
+});
diff --git a/packages/cli/tsup.config.ts b/packages/cli/tsup.config.ts
index 816ce81b..0cf9a677 100644
--- a/packages/cli/tsup.config.ts
+++ b/packages/cli/tsup.config.ts
@@ -1,4 +1,7 @@
import { defineConfig } from "tsup";
+// Inlines this checkout's git identity into the artifact — see the helper's module doc:
+// the penguin binary bundles core, and a shipped bundle has no path back to the checkout it came from.
+import { buildGitDefine } from "../../scripts/build-git-stamp.mjs";
export default defineConfig({
entry: ["src/penguin.ts", "src/penguin-hmr.ts"],
@@ -19,4 +22,5 @@ export default defineConfig({
// deps are already declared there.
noExternal: ["@prismshadow/penguin-core"],
banner: { js: "#!/usr/bin/env node" },
+ define: buildGitDefine(),
});
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 06c15926..aeef65d1 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -15,6 +15,9 @@
* ```
*/
+import type { BuildInfo } from "./interfaces.js";
+import { resolveBuildInfo } from "./internal/build-info.js";
+
// Protocol and interface contracts (foundation)
export * from "./omnimessage/index.js";
export * from "./interfaces.js";
@@ -67,5 +70,17 @@ export type { CreateAgentOptions, CreateSessionOptions, ResumeSessionOptions } f
export const VERSION = "0.2.4";
/** Release build date (UTC yyyy-mm-dd), stamped by the release workflow next to VERSION; null in a dev/source build. */
export const BUILD_DATE: string | null = null;
+/** Full commit sha the release was built from, stamped by the release workflow next to VERSION; null in a dev/source build. */
+export const BUILD_COMMIT: string | null = null;
+
+/**
+ * Identity of the running build — the sole producer behind `penguin version [--json]` and
+ * GET /api/version. The three stamped constants above are the only inputs the release
+ * workflow rewrites, so they are declared here and passed in rather than imported by
+ * build-info.ts, which would make this barrel and that module a cycle.
+ */
+export function buildInfo(): BuildInfo {
+ return resolveBuildInfo({ version: VERSION, buildDate: BUILD_DATE, commit: BUILD_COMMIT });
+}
// Version-string helpers (shared by the CLI's `penguin update` and the server's update check).
export { compareVersions, normalizeVersion } from "./internal/version.js";
diff --git a/packages/core/src/interfaces.ts b/packages/core/src/interfaces.ts
index 83ab910a..3ba510c3 100644
--- a/packages/core/src/interfaces.ts
+++ b/packages/core/src/interfaces.ts
@@ -514,6 +514,111 @@ export interface BackgroundCommandInfo {
serviceUrl?: string;
}
+/**
+ * Node and OS the build is executing on — the part of a build's identity that is a property
+ * of the run rather than of the artifact.
+ */
+export interface BuildRuntimeInfo {
+ /** `process.versions.node`. */
+ node: string;
+ /** `process.platform`. */
+ platform: string;
+ /** `process.arch`. */
+ arch: string;
+}
+
+/**
+ * Identity of the running build: everything `penguin version --json` prints and everything
+ * GET /api/version returns. Both render this object without adding facts of their own, so a
+ * report gathered over HTTP and one gathered at a shell are the same report.
+ *
+ * Produced by core's `buildInfo()`. Which fields carry information depends on `channel`: a
+ * release knows its date and the commit it was built from, a source build knows its git
+ * position instead.
+ */
+export interface BuildInfo {
+ /** Dotted release number, from core's VERSION constant. Never null, never prefixed. */
+ version: string;
+ /**
+ * The one-line human identity, and the whole of `penguin version`'s output: `v0.2.3` for a
+ * release, and git's own description for a source build — `v0.2.3-14-g9e8f7d6-dirty` reads
+ * as fourteen commits past v0.2.3, at 9e8f7d6, with uncommitted changes. Always begins
+ * `v` followed by a digit, so any form reads as a version.
+ *
+ * Not necessarily `v{version}`: a tag description names the nearest reachable TAG, which
+ * during release preparation is the previous one — `VERSION` is bumped in its own commit
+ * and the new tag is created afterwards, so a build from that window truthfully reports
+ * `v0.2.3-N-g…` while `version` already reads 0.2.4. Compare `version` when you mean the
+ * release number and `describe` when you mean the position in history.
+ */
+ describe: string;
+ /** `release` once the release workflow has stamped the build; `source` for every other build. */
+ channel: "release" | "source";
+ /** Release build date (UTC yyyy-mm-dd); null in a source build. */
+ buildDate: string | null;
+ /** Full commit sha this build came from; null when neither the stamp nor git supplied one. */
+ commit: string | null;
+ /** Branch checked out at build time; null for a release, and for a detached HEAD. */
+ branch: string | null;
+ /**
+ * Whether tracked files differed from the commit. Null means the question does not apply
+ * rather than "clean": a release stamps its constants into the tree before building, so
+ * cleanliness is not a fact about release artifacts.
+ */
+ dirty: boolean | null;
+ runtime: BuildRuntimeInfo;
+}
+
+/**
+ * Where a hot update was pushed from, as the pusher recorded it. Provenance only: nothing
+ * here is ever executed or resolved, and both fields are whatever the pushing client sent.
+ */
+export interface HarnessSource {
+ /** The pushing checkout's origin remote, or its directory name when it has no remote. */
+ repo: string;
+ /** `git describe --tags --dirty` of the pushing checkout, spelled as {@link BuildInfo.describe}. */
+ revision: string;
+}
+
+/**
+ * What this machine's HMR store has committed — the harness code a hot update put there,
+ * which a restart resumes. A property of the data root rather than of the running process:
+ * it answers "which harness was pushed here", not "which code is executing".
+ *
+ * That distinction matters because the two can differ. `penguin` runs the packaged CLI
+ * while `penguin-hmr` runs the store's; a server whose committed version failed to restore
+ * warns and falls back to its packaged platform. Null in {@link VersionReport} means
+ * nothing was ever pushed to this root.
+ */
+export interface HarnessInfo {
+ /** Null for a version pushed by a client that recorded no provenance. */
+ source: HarnessSource | null;
+ /** When the version was committed to the store (ISO 8601); null if it predates the record. */
+ pushedAt: string | null;
+ /**
+ * The committed artifacts' content-addressed pointers, relative to `<root>/hmr` — the
+ * identity of the pushed code itself, independent of what the pusher claimed about it.
+ */
+ bundles: {
+ platform: string | null;
+ cli: string | null;
+ web: string | null;
+ };
+}
+
+/**
+ * What `penguin version --json` prints and what GET /api/version returns: the running
+ * build's identity, plus the harness this machine has in its HMR store.
+ *
+ * The two halves come from different places and neither can supply the other. {@link
+ * BuildInfo} describes the artifact this process is executing and core resolves it alone;
+ * `harness` describes the data root's store, so only a caller that knows which root is in
+ * play can fill it.
+ */
+export interface VersionReport extends BuildInfo {
+ harness: HarnessInfo | null;
+}
+
/**
* One live subagent child session owned by the environment: the child Session id (the origin
* hop the frontend already correlates by), the registry handle when the session was promoted
diff --git a/packages/core/src/internal/build-info.ts b/packages/core/src/internal/build-info.ts
new file mode 100644
index 00000000..c1c33a1e
--- /dev/null
+++ b/packages/core/src/internal/build-info.ts
@@ -0,0 +1,176 @@
+/**
+ * Resolves the identity of the running build, once per process.
+ *
+ * The version number alone cannot answer "which code is this?": every build made from a
+ * checkout between two releases also calls itself 0.2.3. So the answer is assembled from
+ * two disjoint sources, picked by whether the release workflow stamped this build.
+ *
+ * A stamped release carries everything it needs in constants (see the barrel's VERSION /
+ * BUILD_DATE / BUILD_COMMIT) and asks git nothing — an installed penguin never shells out
+ * for its own version.
+ *
+ * An unstamped build reads its git position from the stamp a bundler inlined at build time
+ * (see __PENGUIN_BUILD_GIT__), which is what lets an artifact identify itself after it has
+ * left the checkout that produced it. Asking git at run time is only the fallback, for a run
+ * that never went through a bundler at all.
+ *
+ * The single consumer-visible product is {@link BuildInfo}, which `penguin version`,
+ * `penguin version --json` and GET /api/version all render without adding facts of their
+ * own, so those three can never disagree about what is running.
+ */
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import type { BuildInfo } from "../interfaces.js";
+import type { CheckoutFacts } from "./git-facts.js";
+import { findCheckoutRoot, readCheckout } from "./git-facts.js";
+
+/** The stamped constants this module reads, passed in by the barrel that declares them. */
+export interface BuildStamp {
+ version: string;
+ buildDate: string | null;
+ commit: string | null;
+}
+
+/** Where this build's own files are — the only honest place to start looking for its checkout. */
+const moduleDir = path.dirname(fileURLToPath(import.meta.url));
+
+/**
+ * The git identity of the checkout this artifact was BUILT from, inlined verbatim at bundle
+ * time (scripts/build-git-stamp.mjs supplies it to core/cli/desktop's tsup configs and to
+ * scripts/deploy.mjs's esbuild).
+ *
+ * It is the only thing that can identify a bundle which no longer sits in a checkout — one
+ * pushed into `<root>/hmr/store/`, or a dist copied onto a server — where the walk-up below
+ * finds nothing and the working directory would answer about the user's own repository.
+ *
+ * Authoritative over anything git says at run time, because it describes the code that is
+ * EXECUTING, while the surrounding tree may have moved on since the build: running a stale
+ * `dist/` from a checkout that is now ten commits further along reports the build's own
+ * revision, not the tree's.
+ *
+ * Declared and never defined: `typeof` on a missing identifier is legal JavaScript, so an
+ * un-bundled run — `tsx`, `vitest`, `pnpm dev` — finds no stamp and falls through to git.
+ * When a bundler does substitute it, that same `typeof` folds to a constant and the fallback
+ * is eliminated with it.
+ */
+declare const __PENGUIN_BUILD_GIT__: string | undefined;
+
+/**
+ * A tag description this build can present as its own identity: `v` followed by a digit,
+ * which is the shape of every tag this project publishes. Anything else `git describe
+ * --always` produced — a bare commit sha from a shallow clone or a fork with no tags — is
+ * true but does not name a version, so it gets composed into one instead.
+ */
+const TAG_DESCRIPTION = /^v\d/;
+
+/**
+ * The inlined stamp, or null when this artifact carries none. Every field is re-checked
+ * rather than trusted: the value is a string literal a bundler substituted, and a
+ * hand-edited or half-substituted bundle must degrade to fewer facts, not throw on startup.
+ */
+function stampedCheckout(): CheckoutFacts | null {
+ if (typeof __PENGUIN_BUILD_GIT__ !== "string") return null;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(__PENGUIN_BUILD_GIT__);
+ } catch {
+ return null;
+ }
+ // JSON.parse yields any JSON value, not necessarily an object: `null`, a number and a
+ // string all parse successfully, and reading a field off them is a TypeError.
+ if (typeof parsed !== "object" || parsed === null) return null;
+
+ const fields = parsed as Partial<CheckoutFacts>;
+ const facts: CheckoutFacts = {
+ described: typeof fields.described === "string" ? fields.described : null,
+ commit: typeof fields.commit === "string" ? fields.commit : null,
+ branch: typeof fields.branch === "string" ? fields.branch : null,
+ dirty: typeof fields.dirty === "boolean" ? fields.dirty : null,
+ };
+ // A stamp naming neither a description nor a commit says nothing about this artifact, so
+ // it counts as absent — the same condition under which build-git-stamp.mjs emits none.
+ return facts.described === null && facts.commit === null ? null : facts;
+}
+
+/** The checkout this artifact reports: its build-time stamp, else the tree it is sitting in. */
+function checkoutFacts(): CheckoutFacts {
+ const stamped = stampedCheckout();
+ if (stamped !== null) return stamped;
+ const root = findCheckoutRoot(moduleDir);
+ return root === null
+ ? { described: null, commit: null, branch: null, dirty: null }
+ : readCheckout(root);
+}
+
+let cached: BuildInfo | null = null;
+
+/**
+ * Assembles the running build's identity from the stamped constants, consulting git only
+ * for an unstamped build. Cached: the answer cannot change within a process, and the CLI
+ * asks for it on every startup to render `-v`.
+ */
+export function resolveBuildInfo(stamp: BuildStamp): BuildInfo {
+ if (cached !== null) return cached;
+
+ const runtime = {
+ node: process.versions.node,
+ platform: process.platform,
+ arch: process.arch,
+ };
+
+ // BUILD_DATE is the marker: the release workflow always stamps it, whereas BUILD_COMMIT
+ // is only stamped where the workflow knows the sha.
+ if (stamp.buildDate !== null) {
+ cached = {
+ version: stamp.version,
+ describe: `v${stamp.version}`,
+ channel: "release",
+ buildDate: stamp.buildDate,
+ commit: stamp.commit,
+ branch: null,
+ // Not false: the release workflow stamps its constants into the tree before building,
+ // so the checkout a release is built from is dirty by construction and claiming
+ // otherwise would be a lie. Cleanliness is simply not a fact about a release build.
+ dirty: null,
+ runtime,
+ };
+ return cached;
+ }
+
+ const checkout = checkoutFacts();
+
+ cached = {
+ version: stamp.version,
+ describe: composeDescribe(stamp.version, checkout.described),
+ channel: "source",
+ buildDate: null,
+ commit: checkout.commit ?? stamp.commit,
+ branch: checkout.branch,
+ dirty: checkout.dirty,
+ runtime,
+ };
+ return cached;
+}
+
+/**
+ * The one-line identity: git's description when it already names a version, the version
+ * number carrying git's commit when it does not, and the bare version number when there is
+ * no git answer at all. Every form starts with `v` and a digit, so `penguin version` always
+ * reads as a version — but only the two composed forms start with `v{version}`: a tag
+ * description is git's own answer, passed through, and it names the nearest reachable tag
+ * rather than the version constant. The two disagree throughout release preparation, when
+ * VERSION is bumped in its own commit and the tag follows; git's answer is the honest one
+ * there, so it wins.
+ */
+export function composeDescribe(version: string, described: string | null): string {
+ if (described === null) return `v${version}`;
+ if (TAG_DESCRIPTION.test(described)) return described;
+ // A bare sha (with git's own `-dirty` suffix already attached, if any); `g` prefixes it to
+ // match the way `git describe` spells a commit inside a description.
+ return `v${version}-g${described}`;
+}
+
+/** Test seam: drops the process-lifetime cache so a test can resolve against a new stamp. */
+export function resetBuildInfoCache(): void {
+ cached = null;
+}
diff --git a/packages/core/src/internal/git-facts.ts b/packages/core/src/internal/git-facts.ts
new file mode 100644
index 00000000..8c238a83
--- /dev/null
+++ b/packages/core/src/internal/git-facts.ts
@@ -0,0 +1,100 @@
+/**
+ * How this repository reads git — the one implementation, shared by the two places that ask.
+ *
+ * Both a build and a run need the same four facts about a checkout, and they have to agree:
+ * a bundled artifact reports the stamp a build captured (see build-info.ts's
+ * __PENGUIN_BUILD_GIT__, fed by scripts/build-git-stamp.mjs), while an un-bundled run asks
+ * git directly. Two implementations of "what does `-dirty` mean" or "what is a detached
+ * HEAD" would make `penguin version` answer differently depending on how it was launched,
+ * which is the one thing version reporting must not do.
+ *
+ * The build script imports this module directly: Node strips the types (>=24, which this
+ * package requires), and esbuild does the same when a tsup config loads the script.
+ */
+import { execFileSync } from "node:child_process";
+import { existsSync } from "node:fs";
+import path from "node:path";
+
+/** A hung git (a network-backed filesystem, a stale lock) must not hang `penguin -v`. */
+const GIT_TIMEOUT_MS = 2000;
+
+/** What a checkout says about itself. Every field independently degrades to null. */
+export interface CheckoutFacts {
+ /**
+ * Raw `git describe` output, which may name no version at all — a bare sha from a shallow
+ * clone or a tagless fork. Distinct from BuildInfo's `describe`, which always names one.
+ */
+ described: string | null;
+ commit: string | null;
+ branch: string | null;
+ dirty: boolean | null;
+}
+
+/**
+ * One git invocation against `root`, or null for any failure at all — git missing from
+ * PATH, a repository too broken to answer, the timeout. Version reporting is never worth an
+ * exception, and a null degrades to fewer facts rather than none.
+ */
+export function git(root: string, args: string[]): string | null {
+ try {
+ const out = execFileSync("git", args, {
+ cwd: root,
+ encoding: "utf8",
+ timeout: GIT_TIMEOUT_MS,
+ // git's own diagnostics would otherwise land on the CLI's stderr.
+ stdio: ["ignore", "pipe", "ignore"],
+ windowsHide: true,
+ });
+ return out.trim() || null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Locates a checkout of THIS repository at or above `startDir`: the first directory holding
+ * both `.git` and `pnpm-workspace.yaml`.
+ *
+ * Both halves of that test are load-bearing. Callers start from a module's or a script's own
+ * directory rather than the working directory, which is what makes `penguin version` report
+ * the harness's revision when run inside somebody else's repository. Requiring the workspace
+ * marker beside `.git` is what stops a tree that merely sits under an unrelated repository —
+ * a home directory that is itself a dotfiles repo, which is common — from reporting a
+ * stranger's commits; finding nothing is the better answer there.
+ *
+ * `.git` is tested for existence rather than for being a directory: in a linked worktree it
+ * is a file pointing at the real git directory, and this project's own work happens in
+ * worktrees.
+ */
+export function findCheckoutRoot(startDir: string): string | null {
+ let dir = startDir;
+ for (;;) {
+ if (existsSync(path.join(dir, ".git")) && existsSync(path.join(dir, "pnpm-workspace.yaml"))) {
+ return dir;
+ }
+ const parent = path.dirname(dir);
+ if (parent === dir) return null;
+ dir = parent;
+ }
+}
+
+/** Reads a checkout's facts. This is the only place the four rules below are decided. */
+export function readCheckout(root: string): CheckoutFacts {
+ // `--always` keeps this useful in a shallow clone or a tagless fork, where a description
+ // relative to a tag cannot be produced; `--dirty` is the uncommitted-changes marker.
+ const described = git(root, ["describe", "--tags", "--dirty", "--always"]);
+ // One invocation for both: rev-parse resolves its arguments in order, and --abbrev-ref
+ // applies to the ones after it, so this prints the full sha then the branch name.
+ const [commit = null, branch = null] =
+ git(root, ["rev-parse", "HEAD", "--abbrev-ref", "HEAD"])
+ ?.split("\n")
+ .map((line) => line.trim()) ?? [];
+
+ return {
+ described,
+ commit,
+ // Detached HEAD is git's own literal "HEAD" here, which names no branch.
+ branch: branch === "HEAD" ? null : branch,
+ dirty: described === null ? null : described.endsWith("-dirty"),
+ };
+}
diff --git a/packages/core/test/build-info.test.ts b/packages/core/test/build-info.test.ts
new file mode 100644
index 00000000..d083fb0d
--- /dev/null
+++ b/packages/core/test/build-info.test.ts
@@ -0,0 +1,317 @@
+/**
+ * Build identity: what `penguin version [--json]` and GET /api/version report.
+ *
+ * The git-backed cases run against real throwaway repositories rather than a stubbed git,
+ * because the facts under test are the exact output shapes of `git describe --tags --dirty
+ * --always` and of a single `rev-parse` asked for a sha and a branch at once — a stub would
+ * assert this file's beliefs about git instead of git's behavior.
+ */
+import { execFileSync } from "node:child_process";
+import fsp from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import {
+ composeDescribe,
+ resetBuildInfoCache,
+ resolveBuildInfo,
+} from "../src/internal/build-info.js";
+import { findCheckoutRoot, readCheckout } from "../src/internal/git-facts.js";
+
+let tmp: string;
+
+beforeEach(async () => {
+ tmp = await fsp.mkdtemp(path.join(os.tmpdir(), "penguin-build-info-"));
+ resetBuildInfoCache();
+});
+
+afterEach(async () => {
+ resetBuildInfoCache();
+ await fsp.rm(tmp, { recursive: true, force: true });
+});
+
+/**
+ * git against a fixture repository. stderr is dropped rather than inherited: on Windows,
+ * `git add` warns about LF being replaced by CRLF for every file, which floods the CI log
+ * with dozens of lines that say nothing about the test.
+ */
+function git(cwd: string, ...args: string[]): string {
+ return execFileSync("git", args, {
+ cwd,
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "ignore"],
+ windowsHide: true,
+ }).trim();
+}
+
+/**
+ * A repository with one commit, plus the workspace marker that makes it "ours".
+ *
+ * Identity rides on the commit as `-c` flags rather than two `git config` calls: this file
+ * builds nine of these, and process spawning is expensive enough on a Windows runner to be
+ * worth not paying for twice per repository.
+ */
+async function makeCheckout(dir: string): Promise<void> {
+ await fsp.mkdir(dir, { recursive: true });
+ git(dir, "init", "-q", "-b", "main", ".");
+ await fsp.writeFile(path.join(dir, "pnpm-workspace.yaml"), "packages:\n - packages/*\n");
+ await fsp.writeFile(path.join(dir, "tracked.txt"), "one\n");
+ git(dir, "add", ".");
+ commit(dir, "initial");
+}
+
+/** A commit that carries its own author identity, so the fixture needs no `git config`. */
+function commit(dir: string, message: string): void {
+ git(dir, "-c", "[email protected]", "-c", "user.name=Test", "commit", "-qm", message);
+}
+
+describe("resolveBuildInfo", () => {
+ it("reports a stamped build as a release and never consults git", () => {
+ const info = resolveBuildInfo({
+ version: "1.2.3",
+ buildDate: "2026-08-20",
+ commit: "a".repeat(40),
+ });
+
+ expect(info).toEqual({
+ version: "1.2.3",
+ describe: "v1.2.3",
+ channel: "release",
+ buildDate: "2026-08-20",
+ commit: "a".repeat(40),
+ branch: null,
+ // Null rather than false: a release is built from a tree the workflow just stamped.
+ dirty: null,
+ runtime: { node: process.versions.node, platform: process.platform, arch: process.arch },
+ });
+ });
+
+ it("keeps a release identity even where a checkout surrounds the build", () => {
+ // BUILD_DATE alone decides the channel, so a release built and then run from inside the
+ // source tree still reports itself as a release rather than picking up the tree's HEAD.
+ const info = resolveBuildInfo({ version: "1.2.3", buildDate: "2026-08-20", commit: null });
+ expect(info.channel).toBe("release");
+ expect(info.branch).toBeNull();
+ });
+
+ it("caches, so the CLI rendering -v on every startup pays for git at most once", () => {
+ const first = resolveBuildInfo({ version: "1.2.3", buildDate: "2026-08-20", commit: null });
+ const second = resolveBuildInfo({ version: "9.9.9", buildDate: "2000-01-01", commit: null });
+ expect(second).toBe(first);
+ });
+});
+
+describe("findCheckoutRoot", () => {
+ it("finds the root from a nested directory", async () => {
+ await makeCheckout(tmp);
+ const nested = path.join(tmp, "packages", "core", "dist");
+ await fsp.mkdir(nested, { recursive: true });
+
+ expect(await fsp.realpath(findCheckoutRoot(nested) ?? "")).toBe(await fsp.realpath(tmp));
+ });
+
+ it("ignores a repository without the workspace marker", async () => {
+ // The case this protects: an install living under a home directory that is itself a
+ // dotfiles repo. Reporting a stranger's commits as this build's would be worse than
+ // reporting nothing.
+ await makeCheckout(tmp);
+ await fsp.rm(path.join(tmp, "pnpm-workspace.yaml"));
+
+ expect(findCheckoutRoot(tmp)).toBeNull();
+ });
+
+ it("ignores a workspace that is not a repository", async () => {
+ await fsp.writeFile(path.join(tmp, "pnpm-workspace.yaml"), "packages: []\n");
+ expect(findCheckoutRoot(tmp)).toBeNull();
+ });
+
+ it("accepts a linked worktree, where .git is a file", async () => {
+ await makeCheckout(tmp);
+ const worktree = path.join(tmp, "..", `${path.basename(tmp)}-wt`);
+ git(tmp, "worktree", "add", "-q", "-b", "topic", worktree);
+ try {
+ const stat = await fsp.stat(path.join(worktree, ".git"));
+ expect(stat.isFile()).toBe(true);
+ expect(await fsp.realpath(findCheckoutRoot(worktree) ?? "")).toBe(
+ await fsp.realpath(worktree),
+ );
+ } finally {
+ await fsp.rm(worktree, { recursive: true, force: true });
+ }
+ });
+});
+
+describe("readCheckout", () => {
+ it("reads the sha, the branch and a clean tree", async () => {
+ await makeCheckout(tmp);
+ const facts = readCheckout(tmp);
+
+ expect(facts.commit).toBe(git(tmp, "rev-parse", "HEAD"));
+ expect(facts.branch).toBe("main");
+ expect(facts.dirty).toBe(false);
+ });
+
+ it("describes a tagged commit, and counts commits past the tag", async () => {
+ await makeCheckout(tmp);
+ git(tmp, "tag", "v0.2.3");
+ expect(readCheckout(tmp).described).toBe("v0.2.3");
+
+ await fsp.writeFile(path.join(tmp, "tracked.txt"), "two\n");
+ git(tmp, "add", ".");
+ commit(tmp, "second");
+ expect(readCheckout(tmp).described).toMatch(/^v0\.2\.3-1-g[0-9a-f]+$/);
+ });
+
+ it("marks a tree with uncommitted changes as dirty", async () => {
+ await makeCheckout(tmp);
+ git(tmp, "tag", "v0.2.3");
+ await fsp.writeFile(path.join(tmp, "tracked.txt"), "changed\n");
+
+ const facts = readCheckout(tmp);
+ expect(facts.dirty).toBe(true);
+ expect(facts.described).toBe("v0.2.3-dirty");
+ });
+
+ it("falls back to a bare sha where no tag is reachable", async () => {
+ await makeCheckout(tmp);
+ expect(readCheckout(tmp).described).toMatch(/^[0-9a-f]+$/);
+ });
+
+ it("reports a detached HEAD as no branch", async () => {
+ await makeCheckout(tmp);
+ git(tmp, "checkout", "-q", "--detach");
+ expect(readCheckout(tmp).branch).toBeNull();
+ });
+
+ it("returns nulls instead of throwing outside a repository", () => {
+ expect(readCheckout(tmp)).toEqual({
+ described: null,
+ commit: null,
+ branch: null,
+ dirty: null,
+ });
+ });
+});
+
+describe("stampedCheckout", () => {
+ // The stamp is a string literal a bundler substituted for a declared-but-never-defined
+ // identifier. These drive it through the same globalThis slot the substitution produces,
+ // because the alternative — running a real bundler per case — tests esbuild, not this.
+ const KEY = "__PENGUIN_BUILD_GIT__";
+ const withStamp = <T>(value: unknown, body: () => T): T => {
+ const had = KEY in (globalThis as Record<string, unknown>);
+ const before = (globalThis as Record<string, unknown>)[KEY];
+ (globalThis as Record<string, unknown>)[KEY] = value;
+ try {
+ return body();
+ } finally {
+ if (had) (globalThis as Record<string, unknown>)[KEY] = before;
+ else delete (globalThis as Record<string, unknown>)[KEY];
+ }
+ };
+
+ it("reads an inlined stamp, so an artifact identifies itself away from its checkout", () => {
+ const stamp = JSON.stringify({
+ described: "v0.2.4-3-gfeedface-dirty",
+ commit: "f".repeat(40),
+ branch: "topic",
+ dirty: true,
+ });
+ const info = withStamp(stamp, () => {
+ resetBuildInfoCache();
+ return resolveBuildInfo({ version: "0.2.4", buildDate: null, commit: null });
+ });
+
+ expect(info.describe).toBe("v0.2.4-3-gfeedface-dirty");
+ expect(info.commit).toBe("f".repeat(40));
+ expect(info.branch).toBe("topic");
+ expect(info.dirty).toBe(true);
+ });
+
+ it("prefers the stamp over the tree it happens to be sitting in", () => {
+ // A stale `dist/` inside a checkout that has moved on must report the revision it was
+ // BUILT from — that is the code actually executing — not the tree's current HEAD.
+ const stamp = JSON.stringify({
+ described: "v0.0.1-1-gstale00",
+ commit: "0".repeat(40),
+ branch: "old",
+ dirty: false,
+ });
+ const info = withStamp(stamp, () => {
+ resetBuildInfoCache();
+ return resolveBuildInfo({ version: "0.2.4", buildDate: null, commit: null });
+ });
+
+ expect(info.describe).toBe("v0.0.1-1-gstale00");
+ expect(info.commit).toBe("0".repeat(40));
+ // This suite runs from a real checkout, so the fallback would have answered otherwise.
+ expect(findCheckoutRoot(process.cwd())).not.toBeNull();
+ });
+
+ it("falls back to git for a malformed or half-substituted stamp", () => {
+ for (const bad of ["not json at all", "", "null", '{"described":42}']) {
+ const info = withStamp(bad, () => {
+ resetBuildInfoCache();
+ return resolveBuildInfo({ version: "0.2.4", buildDate: null, commit: null });
+ });
+ // Never a throw, and never the garbage: either git answered or every field is null.
+ expect(info.describe).toMatch(/^v\d/);
+ expect(info.commit === null || /^[0-9a-f]{40}$/.test(info.commit)).toBe(true);
+ }
+ });
+
+ it("is ignored entirely by a stamped release", () => {
+ const stamp = JSON.stringify({
+ described: "v9.9.9-1-gbadbad0",
+ commit: "9".repeat(40),
+ branch: "nope",
+ dirty: true,
+ });
+ const info = withStamp(stamp, () => {
+ resetBuildInfoCache();
+ return resolveBuildInfo({
+ version: "1.0.0",
+ buildDate: "2026-08-20",
+ commit: "a".repeat(40),
+ });
+ });
+
+ expect(info.channel).toBe("release");
+ expect(info.describe).toBe("v1.0.0");
+ expect(info.commit).toBe("a".repeat(40));
+ expect(info.branch).toBeNull();
+ });
+});
+
+describe("composeDescribe", () => {
+ it("passes a tag description through unchanged", () => {
+ expect(composeDescribe("0.2.3", "v0.2.3")).toBe("v0.2.3");
+ expect(composeDescribe("0.2.3", "v0.2.3-14-g9e8f7d6-dirty")).toBe("v0.2.3-14-g9e8f7d6-dirty");
+ });
+
+ it("composes a version around a bare sha, keeping git's dirty marker", () => {
+ expect(composeDescribe("0.2.3", "9e8f7d6")).toBe("v0.2.3-g9e8f7d6");
+ expect(composeDescribe("0.2.3", "9e8f7d6-dirty")).toBe("v0.2.3-g9e8f7d6-dirty");
+ });
+
+ it("falls back to the bare version when git answered nothing", () => {
+ expect(composeDescribe("0.2.3", null)).toBe("v0.2.3");
+ });
+
+ it("keeps git's tag even when it names an earlier version than the constant", () => {
+ // The release-preparation window: `release: X.Y.Z` bumps VERSION in its own commit and
+ // the tag is created afterwards, so a build from that window has VERSION 0.2.4 while
+ // the nearest reachable tag is still v0.2.3. Git's answer is the truthful one — it
+ // states where in history this build sits — so it is passed through unchanged rather
+ // than rewritten to agree with the constant.
+ expect(composeDescribe("0.2.4", "v0.2.3-52-g9e8f7d6")).toBe("v0.2.3-52-g9e8f7d6");
+ });
+
+ it("always produces something that reads as a version", () => {
+ // `v` and a digit is the guarantee across every input — not `v${version}`, which only
+ // the two composed forms can promise.
+ for (const described of [null, "v0.2.3", "v0.1.0-1-gabc-dirty", "abc1234", "abc1234-dirty"]) {
+ expect(composeDescribe("0.2.3", described)).toMatch(/^v\d/);
+ }
+ });
+});
diff --git a/packages/core/tsup.config.ts b/packages/core/tsup.config.ts
index f310d37c..79e2ee27 100644
--- a/packages/core/tsup.config.ts
+++ b/packages/core/tsup.config.ts
@@ -1,4 +1,7 @@
import { defineConfig } from "tsup";
+// Inlines this checkout's git identity into the artifact — see the helper's module doc:
+// core's dist is what the server imports at run time, and a shipped bundle has no path back to the checkout it came from.
+import { buildGitDefine } from "../../scripts/build-git-stamp.mjs";
export default defineConfig({
// model-catalog gets its own entry point: pure data, no Node dependency, so web can bundle it directly via subpath import.
@@ -18,4 +21,5 @@ export default defineConfig({
dts: true,
clean: true,
sourcemap: true,
+ define: buildGitDefine(),
});
diff --git a/packages/desktop/tsup.config.ts b/packages/desktop/tsup.config.ts
index 68ded027..240cc168 100644
--- a/packages/desktop/tsup.config.ts
+++ b/packages/desktop/tsup.config.ts
@@ -1,4 +1,7 @@
import { defineConfig } from "tsup";
+// Inlines this checkout's git identity into the artifact — see the helper's module doc:
+// the app bundles the server and the CLI whole, and a shipped bundle has no path back to the checkout it came from.
+import { buildGitDefine } from "../../scripts/build-git-stamp.mjs";
/**
* Five self-contained bundles, no shared chunks: the shell itself, the server it forks as a
@@ -42,4 +45,5 @@ export default defineConfig({
// `noExternal: [/.*/]` gets you. Everything else is bundled by default: tsup externalizes
// this package's `dependencies`, and it deliberately declares none.
external: ["electron"],
+ define: buildGitDefine(),
});
diff --git a/packages/docs/content/cli.en.md b/packages/docs/content/cli.en.md
index 44ab89cc..6496a2b0 100644
--- a/packages/docs/content/cli.en.md
+++ b/packages/docs/content/cli.en.md
@@ -3,7 +3,7 @@ title: CLI Reference
description: Complete reference for the penguin command, its subcommands, and options.
---
-The CLI ships as the npm package `@prismshadow/penguin-cli`; the command is `penguin`. Running bare `penguin` prints help; `-v, --version` prints the version. A `.env` file in the working directory is loaded automatically on startup.
+The CLI ships as the npm package `@prismshadow/penguin-cli`; the command is `penguin`. Running bare `penguin` prints help; `-v, --version` prints the running build's one-line identity, and `penguin version --json` prints the whole of it. A `.env` file in the working directory is loaded automatically on startup.
## Global conventions
@@ -165,6 +165,45 @@ penguin server reset-admin-password
The built-in `admin` gets a fresh initial password of the usual `penguin-1234` form, printed in the framed notice — and re-printed on every server start until it is changed — and all of admin's sign-in sessions are cleared. Other accounts are reset by the admin on the user-management page; this command only touches `admin`. The data root is selected by `PENGUIN_HOME` as usual.
+## penguin version
+
+Reports which build is running. The version number alone cannot answer that — every build made from a checkout between two releases also calls itself `0.2.3` — so a release and a source build identify themselves differently.
+
+```bash
+penguin version # v0.2.3 (a release)
+penguin version # v0.2.3-14-g9e8f7d6-dirty (built from a checkout)
+penguin version --json # the full build info
+```
+
+| Option | Description |
+| --- | --- |
+| `--json` | Print the full version report instead of the one line: `{version, describe, channel, buildDate, commit, branch, dirty, runtime, harness}` |
+| `--root <dir>` | Data root whose HMR store to report as `harness`. Priority: `--root` > `PENGUIN_HOME` > `~/.penguin/data` |
+
+The bare form prints one line, which for a source build is `git describe --tags --dirty` output — `v0.2.3-14-g9e8f7d6-dirty` reads as fourteen commits past `v0.2.3`, at `9e8f7d6`, with uncommitted changes. `-v, --version` prints that same line.
+
+`describe` names the nearest reachable git tag, which is not always `v` + `version`: release preparation bumps `version` in its own commit and creates the tag afterwards, so a build from that window reports `v0.2.3-14-g9e8f7d6` while `version` already reads `0.2.4`. Read `version` for the release number and `describe` for the position in history.
+
+The JSON is the same record `GET /api/version` returns, so a bug report can be gathered from either side of the HTTP boundary. In it, `channel` is `release` or `source`; `buildDate` and `commit` are stamped into the build by the release workflow and are null for a source build; `branch` and `dirty` describe a source build's git position and are null for a release, where the question does not apply — the workflow stamps its constants into the tree before building.
+
+### harness: what was hot-pushed here
+
+`harness` describes the data root's HMR store — the harness code a hot update committed, which a restart resumes. It is null when nothing was ever pushed to that root.
+
+```json
+"harness": {
+ "source": { "repo": "…/penguin-harness", "revision": "v0.2.3-7-gabc1234-dirty" },
+ "pushedAt": "2026-08-20T10:15:00.000Z",
+ "bundles": { "platform": "store/platform/…", "cli": "store/cli/…", "web": "store/web/…" }
+}
+```
+
+This is the one thing the version line cannot report. A pushed bundle lands outside any checkout, so it identifies itself by the version it was compiled from and nothing more; `source.revision` — recorded by the pusher, spelled the same way as `describe` — is the only thing that names the revision behind it. `bundles` holds the committed artifacts' content-addressed pointers, which identify the pushed code itself regardless of what the pusher claimed about it.
+
+It describes the store, not the process: `penguin` runs the packaged CLI while `penguin-hmr` runs the store's, so a non-null `harness` does not by itself mean the command printing it is the pushed code. `source` is null for a version pushed by a client that recorded no provenance, including anything pushed before it was recorded at all.
+
+An installed penguin never shells out to git: it reads constants stamped into the build. A release gets them from the release workflow; every other build gets its git position inlined by the bundler that produced it, so an artifact still identifies itself after it has left the checkout it came from — a hot-pushed bundle under `<root>/hmr/store/` reports the revision it was built at, on a machine with no checkout and no git installed. Asking git at run time is only the fallback, for an un-bundled `tsx` run; even then it asks about its own checkout, so `penguin version` inside an unrelated repository reports the harness's revision and not that repository's.
+
## penguin update
Upgrades this install in place, using the mechanism it was installed with. The install kind is detected from the real path of the running CLI, never guessed.
diff --git a/packages/docs/content/cli.zh.md b/packages/docs/content/cli.zh.md
index 8c9bd421..d4faa173 100644
--- a/packages/docs/content/cli.zh.md
+++ b/packages/docs/content/cli.zh.md
@@ -3,7 +3,7 @@ title: CLI 参考
description: penguin 命令的子命令与选项完整参考。
---
-CLI 由 npm 包 `@prismshadow/penguin-cli` 提供,命令为 `penguin`。不带子命令执行 `penguin` 时打印帮助;`-v, --version` 打印版本号。启动时自动加载工作目录下的 `.env`。
+CLI 由 npm 包 `@prismshadow/penguin-cli` 提供,命令为 `penguin`。不带子命令执行 `penguin` 时打印帮助;`-v, --version` 打印当前构建的单行身份,`penguin version --json` 打印其完整信息。启动时自动加载工作目录下的 `.env`。
## 全局约定
@@ -165,6 +165,45 @@ penguin server reset-admin-password
内置 `admin` 会得到一个新的初始密码(形如 `penguin-1234`),以边框提示打印——此后每次启动服务端都会重印,直到密码被修改——并清空 admin 的全部登录会话。其他账号由管理员在用户管理页重置,本命令只作用于 `admin`。数据根目录照常由 `PENGUIN_HOME` 决定。
+## penguin version
+
+报告当前运行的是哪个构建。仅凭版本号回答不了这个问题——两次发布之间由源码 checkout 构建出来的每一个版本也都自称 `0.2.3`——因此发布版与源码构建给出的身份并不相同。
+
+```bash
+penguin version # v0.2.3 (发布版)
+penguin version # v0.2.3-14-g9e8f7d6-dirty (源码构建)
+penguin version --json # 完整构建信息
+```
+
+| 选项 | 说明 |
+| --- | --- |
+| `--json` | 输出完整版本报告而非单行:`{version, describe, channel, buildDate, commit, branch, dirty, runtime, harness}` |
+| `--root <dir>` | 以哪个数据根目录的 HMR store 作为 `harness` 上报。优先级:`--root` > `PENGUIN_HOME` > `~/.penguin/data` |
+
+不带选项时输出单行;源码构建下该行即 `git describe --tags --dirty` 的结果——`v0.2.3-14-g9e8f7d6-dirty` 表示位于 `v0.2.3` 之后 14 个提交、当前提交为 `9e8f7d6`、且工作区有未提交改动。`-v, --version` 输出的是同一行。
+
+`describe` 指向的是最近的可达 git tag,因此并不总是 `v` + `version`:发布准备会先用一个单独的提交抬升 `version`、之后才打 tag,所以这一窗口内的构建会报告 `v0.2.3-14-g9e8f7d6`,而 `version` 已经是 `0.2.4`。要版本号看 `version`,要在历史中的位置看 `describe`。
+
+JSON 与 `GET /api/version` 返回的是同一份记录,因此在 HTTP 边界的任意一侧都能采集到同样的排障信息。其中 `channel` 取 `release` 或 `source`;`buildDate` 与 `commit` 由发布流程在构建时打入,源码构建为 null;`branch` 与 `dirty` 描述源码构建的 git 位置,发布版为 null——发布流程会先把常量写进工作区再构建,所以「是否干净」对发布产物本就不成立。
+
+### harness:这台机器上热更新推了什么
+
+`harness` 描述的是该数据根目录的 HMR store——某次热更新提交进去、并会在重启后被恢复的 harness 代码。该根目录从未被推送过时为 null。
+
+```json
+"harness": {
+ "source": { "repo": "…/penguin-harness", "revision": "v0.2.3-7-gabc1234-dirty" },
+ "pushedAt": "2026-08-20T10:15:00.000Z",
+ "bundles": { "platform": "store/platform/…", "cli": "store/cli/…", "web": "store/web/…" }
+}
+```
+
+这正是单行版本无法表达的部分:推送过去的 bundle 落在任何 checkout 之外,它只能以自己被编译时的版本号自称;`source.revision`(由推送方记录,拼写方式与 `describe` 一致)是唯一能指明其背后 revision 的信息。`bundles` 是已提交产物的内容寻址指针,无论推送方声称了什么,它标识的都是被推送代码本身。
+
+它描述的是 store 而非当前进程:`penguin` 运行的是随包发布的 CLI,`penguin-hmr` 才运行 store 里的那份,因此 `harness` 非 null 并不意味着打印它的这条命令本身就是被推送的代码。若推送方未记录来源(包括在该机制存在之前推送的版本),`source` 为 null。
+
+已安装的 penguin 从不调用 git,只读取构建时打入的常量:发布版由发布流程打入,其余构建则由打包器把 git 位置内联进产物,因此产物离开生成它的 checkout 之后依然能说明自己的身份——位于 `<root>/hmr/store/` 下被热推送的 bundle,在既无 checkout 也未安装 git 的机器上,仍会报告它被构建时的 revision。运行时询问 git 只是兜底,用于未经打包的 `tsx` 运行;即便如此它也只问自己所在的那个 checkout,所以在无关仓库里执行 `penguin version` 报告的仍是 harness 自身的版本,而非该仓库的。
+
## penguin update
原地升级当前安装,并沿用它当初的安装方式。安装方式由运行中 CLI 的真实路径判定,不做猜测。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 922f2481..539beb7f 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -95,7 +95,7 @@ In every on-state the effective NO_PROXY always includes `localhost,127.0.0.1,::
| Method | Path | Description |
| --- | --- | --- |
-| GET | /api/version | Running release identity: `{version, buildDate}` (`buildDate` is the running version's release date, stamped at build time — no network; null in a dev/source build or a release that predates the stamping) |
+| GET | /api/version | Identity of the running build plus this root's pushed harness: `{version, describe, channel, buildDate, commit, branch, dirty, runtime, harness}` — the same record `penguin version --json` prints. `harness` describes the data root's HMR store (`{source, pushedAt, bundles}`, where `source` is the pushing checkout's `{repo, revision}`) and is null when nothing was ever pushed there. `describe` is the one-line identity (`v0.2.3` for a release, `v0.2.3-14-g9e8f7d6-dirty` for a build from a checkout); `channel` is `release` or `source`; `buildDate` (UTC yyyy-mm-dd) and `commit` are stamped at build time, so no network is needed, and are null in a source build or a release predating the stamping; `branch` and `dirty` carry a source build's git position and are null for a release |
| GET | /api/version/update-check | Compares the newest GitHub release with the running version: `{currentVersion, latestVersion, updateAvailable, releaseUrl, publishedAt, checkedAt, disabled?, error?}`; `?force=1` (the manual "check for updates" action) bypasses the TTL cache, and the outcome is cached as usual |
| POST | /api/version/update | **Admin only.** Runs the CLI self-update (`penguin update --yes`) on the server host: `{status, output, needsRestart}` |
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 0892b8d4..0fc2ff62 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -95,7 +95,7 @@ curl -c cookies.txt -H "Content-Type: application/json" \
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | /api/version | 当前运行版本:`{version, buildDate}`(`buildDate` 是当前运行版本的发布日期,构建时打入、无需联网;开发/源码构建以及打入机制之前的发布版为 null) |
+| GET | /api/version | 当前运行构建的身份,外加该根目录被推送的 harness:`{version, describe, channel, buildDate, commit, branch, dirty, runtime, harness}`,与 `penguin version --json` 输出同一份记录。`harness` 描述该数据根目录的 HMR store(`{source, pushedAt, bundles}`,其中 `source` 为推送方 checkout 的 `{repo, revision}`),从未被推送过时为 null。`describe` 是单行身份(发布版为 `v0.2.3`,源码构建为 `v0.2.3-14-g9e8f7d6-dirty`);`channel` 取 `release` 或 `source`;`buildDate`(UTC yyyy-mm-dd)与 `commit` 在构建时打入、无需联网,源码构建以及打入机制之前的发布版为 null;`branch` 与 `dirty` 记录源码构建的 git 位置,发布版为 null |
| GET | /api/version/update-check | 对比 GitHub 最新 Release 与当前版本:`{currentVersion, latestVersion, updateAvailable, releaseUrl, publishedAt, checkedAt, disabled?, error?}`;`?force=1`(手动「检查更新」)绕过 TTL 缓存,结果照常写入缓存 |
| POST | /api/version/update | **仅管理员。**在服务器上执行 CLI 在线更新(`penguin update --yes`):`{status, output, needsRestart}` |
diff --git a/packages/server/package.json b/packages/server/package.json
index 5a5e9d35..e3658c05 100644
--- a/packages/server/package.json
+++ b/packages/server/package.json
@@ -33,6 +33,10 @@
"./hmr/manifest": {
"types": "./dist/hmr/manifest.d.ts",
"import": "./dist/hmr/manifest.js"
+ },
+ "./version-report": {
+ "types": "./dist/version-report.d.ts",
+ "import": "./dist/version-report.js"
}
},
"main": "./dist/index.js",
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 5ac56e4c..1079509f 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -19,9 +19,11 @@ import type {
ToolCallPayload,
} from "@prismshadow/penguin-core/omnimessage";
import type {
+ HarnessInfo,
MCPServerConfig,
ThinkingLevelName,
ToolDefinitionConfig,
+ VersionReport,
} from "@prismshadow/penguin-core/interfaces";
// ---------------------------------------------------------------------------
@@ -2387,17 +2389,15 @@ export interface SkillArchiveInstallRequest {
// Version and self-update
// ---------------------------------------------------------------------------
-/** GET /api/version: the running server's release identity (from core's VERSION / BUILD_DATE). */
-export interface VersionResponse {
- version: string;
- /**
- * The **running** version's release date (UTC yyyy-mm-dd), stamped into core's
- * BUILD_DATE at build time by the release workflow — the web's "last updated" date
- * needs no network. Null for a dev/source build and for releases that predate the
- * stamping (v0.1.2 and earlier): the UI then shows the version alone.
- */
- buildDate: string | null;
-}
+/**
+ * GET /api/version: the running build's identity plus this root's pushed harness, verbatim
+ * from `versionReport()` — the same record `penguin version --json` prints, so the two
+ * cannot drift apart. Field meanings live on {@link VersionReport} and {@link HarnessInfo};
+ * the ones the web reads are `version` and `buildDate` (the stamped release date behind the
+ * sidebar's "last updated", needing no network, and null for a source build or a release
+ * predating the stamping — v0.1.2 and earlier — where the UI shows the version alone).
+ */
+export type VersionResponse = VersionReport;
/**
* GET /api/version/update-check: newest published release vs the running version.
diff --git a/packages/server/src/hmr/host.ts b/packages/server/src/hmr/host.ts
index 88e640db..a5f332a7 100644
--- a/packages/server/src/hmr/host.ts
+++ b/packages/server/src/hmr/host.ts
@@ -409,6 +409,7 @@ export class HmrHost {
gz,
digest.slice(0, 16),
assetsDir,
+ source,
);
return {
@@ -588,6 +589,7 @@ export class HmrHost {
webGz: Buffer,
webSha: string,
assetsDir: string | null,
+ source: GitSource | null,
): Promise<boolean> {
try {
// The platform bundle is already in the store: storePlatformBundle put it at its
@@ -609,6 +611,11 @@ export class HmrHost {
...(assetsDir === null
? {}
: { assets: { dir: path.relative(this.hmrDir, assetsDir).split(path.sep).join("/") } }),
+ // Provenance travels with the version it describes, so `penguin version` on this
+ // machine can name the revision a pushed harness came from — the bundles are
+ // content-addressed and say nothing about their origin on their own.
+ ...(source === null ? {} : { source }),
+ pushedAt: new Date().toISOString(),
}));
return true;
} catch (err) {
diff --git a/packages/server/src/hmr/manifest.ts b/packages/server/src/hmr/manifest.ts
index 972269e9..a3b9e080 100644
--- a/packages/server/src/hmr/manifest.ts
+++ b/packages/server/src/hmr/manifest.ts
@@ -19,6 +19,7 @@
import fs from "node:fs";
import fsp from "node:fs/promises";
import path from "node:path";
+import type { HarnessInfo } from "@prismshadow/penguin-core/interfaces";
/**
* The committed on-disk record: a runtime restart resumes exactly this CODE (platform,
@@ -48,6 +49,49 @@ export interface Manifest {
* filesystem, with its exec bit intact.
*/
assets?: { dir: string };
+ /**
+ * Provenance of the push that produced this version, exactly as the pushing client sent
+ * it (scripts/deploy.mjs fills it from its own checkout). Recorded, never executed or
+ * resolved. Absent for a version pushed without it, and for every version committed
+ * before the field existed — which is why every reader treats it as optional.
+ */
+ source?: { repo: string; revision: string };
+ /** When this version was committed to the store (ISO 8601). Absent on older records. */
+ pushedAt?: string;
+}
+
+/** A string field of an untrusted manifest, or null unless it is a non-empty string. */
+function str(value: unknown): string | null {
+ return typeof value === "string" && value.length > 0 ? value : null;
+}
+
+/**
+ * What the store has committed, for version reporting: provenance, commit time, and the
+ * three artifact pointers. Null when nothing has ever been pushed to this root.
+ *
+ * Read defensively rather than cast: harness.json is written only by persistVersion, but a
+ * truncated or hand-edited file must degrade a `penguin version` to missing fields, never
+ * crash it. A record missing every artifact pointer counts as nothing pushed.
+ */
+export async function readHarnessInfo(root: string): Promise<HarnessInfo | null> {
+ const manifest = await readManifest(root);
+ if (manifest === null) return null;
+
+ const bundles = {
+ platform: str(manifest.platform?.bundle),
+ cli: str(manifest.cli?.bundle),
+ web: str(manifest.web?.manifest),
+ };
+ if (bundles.platform === null && bundles.cli === null && bundles.web === null) return null;
+
+ const repo = str(manifest.source?.repo);
+ const revision = str(manifest.source?.revision);
+ return {
+ // Both halves or neither: half a provenance names nothing.
+ source: repo !== null && revision !== null ? { repo, revision } : null,
+ pushedAt: str(manifest.pushedAt),
+ bundles,
+ };
}
/** Reads and parses `<root>/hmr/harness.json`; null when missing or corrupt (nothing committed yet). */
diff --git a/packages/server/src/hmr/routes.ts b/packages/server/src/hmr/routes.ts
index a79da446..d417dd10 100644
--- a/packages/server/src/hmr/routes.ts
+++ b/packages/server/src/hmr/routes.ts
@@ -159,7 +159,17 @@ export function hmrRoutes(deps: AppDeps): Hono<AppEnv> {
},
}
: {}),
- ...(payload.source ? { source: payload.source } : {}),
+ // Provenance is optional and, unlike the bundles, now outlives the request in
+ // harness.json — so it is accepted only fully formed. A half-filled or
+ // wrong-typed `source` is dropped rather than committed: readers already
+ // tolerate its absence, and a malformed record on disk would outlive the push
+ // that produced it.
+ ...(typeof payload.source?.repo === "string" &&
+ typeof payload.source.revision === "string" &&
+ payload.source.repo.length > 0 &&
+ payload.source.revision.length > 0
+ ? { source: { repo: payload.source.repo, revision: payload.source.revision } }
+ : {}),
});
} catch (err) {
throw new HttpError(400, "bad_request", err instanceof Error ? err.message : String(err));
diff --git a/packages/server/src/http/routes/version.ts b/packages/server/src/http/routes/version.ts
index 85deabe5..73c7bfa1 100644
--- a/packages/server/src/http/routes/version.ts
+++ b/packages/server/src/http/routes/version.ts
@@ -2,7 +2,9 @@
* Version routes: the running release identity, the update-check reminder, and the
* admin-only self-update.
*
- * GET /api/version -> {version, buildDate} from core's VERSION / BUILD_DATE
+ * GET /api/version -> versionReport(): the running build's identity plus
+ * this root's pushed harness, the same record
+ * `penguin version --json` prints
* GET /api/version/update-check -> UpdateCheckService (fail-soft, cached, opt-out env;
* ?force=1 bypasses the cache for the manual check)
* POST /api/version/update -> admin only: re-runs the CLI as `penguin update --yes`
@@ -24,7 +26,7 @@
* the same install — the strings can never be from a different release than this code.
*/
import { spawn } from "node:child_process";
-import { BUILD_DATE, VERSION } from "@prismshadow/penguin-core";
+import { versionReport } from "../../version-report.js";
import { Hono } from "hono";
import type { UpdateRunResponse, VersionResponse } from "../../api/types.js";
import { HttpError } from "../errors.js";
@@ -121,8 +123,8 @@ export function versionRoutes(deps: AppDeps): Hono<AppEnv> {
// install dir: concurrent requests share the one in-flight run (and its result).
let inflightRun: Promise<UpdateRunResponse> | null = null;
- app.get("/", (c) => {
- return c.json({ version: VERSION, buildDate: BUILD_DATE } satisfies VersionResponse);
+ app.get("/", async (c) => {
+ return c.json((await versionReport(deps.config.root)) satisfies VersionResponse);
});
app.get("/update-check", async (c) => {
diff --git a/packages/server/src/version-report.ts b/packages/server/src/version-report.ts
new file mode 100644
index 00000000..b55bb21c
--- /dev/null
+++ b/packages/server/src/version-report.ts
@@ -0,0 +1,27 @@
+/**
+ * The one assembler behind `penguin version --json` and GET /api/version.
+ *
+ * The report has two halves that no single layer can produce. Core knows the artifact this
+ * process is executing and nothing about data roots; the HMR store knows what harness was
+ * pushed to a root and nothing about the process reading it. Joining them here — rather
+ * than in each caller — is what makes "the CLI and the API report the same thing" a
+ * structural fact instead of two spreads that have to be kept in step.
+ *
+ * It lives in the server package because that is where the harness.json format is owned
+ * (see ./hmr/manifest.ts), and is exported as its own entry point so the CLI can reach it
+ * without pulling in a server: the module graph here is core plus a `node:fs` read.
+ */
+import { buildInfo } from "@prismshadow/penguin-core";
+import type { VersionReport } from "@prismshadow/penguin-core/interfaces";
+import { readHarnessInfo } from "./hmr/manifest.js";
+
+/**
+ * The running build's identity plus the harness committed to `root`'s HMR store.
+ *
+ * Never throws: an unreadable or malformed store reports `harness: null`, which is also
+ * what a root with nothing ever pushed to it reports. Version reporting degrades to fewer
+ * facts, never to a failure.
+ */
+export async function versionReport(root: string): Promise<VersionReport> {
+ return { ...buildInfo(), harness: await readHarnessInfo(root) };
+}
diff --git a/packages/server/test/hmr-host.test.ts b/packages/server/test/hmr-host.test.ts
index ecf7eaf0..736f515e 100644
--- a/packages/server/test/hmr-host.test.ts
+++ b/packages/server/test/hmr-host.test.ts
@@ -2,7 +2,8 @@
* HmrHost mechanism tests that don't fit the seam's own file: the single-flight first
* boot, "code persists across a restart, state does not" (see host.ts's module doc),
* a bundle missing `context` being rejected the same way a missing `hotPlatform` is,
- * and the durability flag an upgrade's HTTP response carries.
+ * the durability flag an upgrade's HTTP response carries, and the provenance a push
+ * commits alongside the version it describes.
*/
import fs from "node:fs/promises";
import fsSync from "node:fs";
@@ -12,6 +13,7 @@ import { afterEach, describe, expect, it } from "vitest";
import type { Hono } from "hono";
import type { AppEnv } from "../src/auth/middleware.js";
import { HmrHost } from "../src/hmr/host.js";
+import { readHarnessInfo } from "../src/hmr/manifest.js";
import { apiClient, createTestApp, loginAdmin } from "./helpers.js";
import type { TestApp } from "./helpers.js";
@@ -559,3 +561,88 @@ describe("the store is the only place a pushed platform bundle lands", () => {
expect((await t.app.request("/api/demo/v4", { headers: { cookie } })).status).toBe(200);
});
});
+
+/**
+ * Provenance is the one part of a push that describes where the code came from: the bundles
+ * are content-addressed, and a pushed bundle lands outside any checkout, so unless the
+ * pusher's revision is committed with the version nothing on the target can name it. These
+ * assert the round trip a `penguin version --json` on the target depends on.
+ */
+describe("upgrade provenance: recorded with the version, or not at all", () => {
+ let t: TestApp | undefined;
+ afterEach(async () => {
+ if (t) await t.cleanup();
+ t = undefined;
+ });
+
+ async function pushWithSource(app: Hono<AppEnv>, cookie: string, source: unknown) {
+ const gz = zlib.gzipSync(
+ Buffer.from(
+ JSON.stringify({
+ platform: platformServing(["/api/demo/ping"], "pushed"),
+ cli: MINIMAL_CLI,
+ web: { files: MINIMAL_WEB },
+ ...(source === undefined ? {} : { source }),
+ }),
+ ),
+ );
+ return app.request("/api/hmr/upgrade", {
+ method: "POST",
+ headers: { cookie, "content-type": "application/gzip" },
+ body: gz,
+ });
+ }
+
+ async function manifestOf(root: string): Promise<Record<string, unknown>> {
+ return JSON.parse(await fs.readFile(path.join(root, "hmr", "harness.json"), "utf8")) as Record<
+ string,
+ unknown
+ >;
+ }
+
+ it("commits a pusher's repo and revision, and stamps when the version landed", async () => {
+ t = await createTestApp();
+ const cookie = (await loginAdmin(t.app)).cookie;
+ const before = Date.now();
+ const push = await pushWithSource(t.app, cookie, {
+ repo: "https://example.com/penguin.git",
+ revision: "v0.2.3-7-gabc1234-dirty",
+ });
+ expect(push.status).toBe(200);
+ expect(((await push.json()) as { persisted: boolean }).persisted).toBe(true);
+
+ const manifest = await manifestOf(t.root);
+ expect(manifest.source).toEqual({
+ repo: "https://example.com/penguin.git",
+ revision: "v0.2.3-7-gabc1234-dirty",
+ });
+ expect(Date.parse(manifest.pushedAt as string)).toBeGreaterThanOrEqual(before);
+
+ // And the reader the version report uses sees exactly that.
+ await expect(readHarnessInfo(t.root)).resolves.toMatchObject({
+ source: { revision: "v0.2.3-7-gabc1234-dirty" },
+ bundles: { cli: expect.stringContaining("store/cli/") },
+ });
+ });
+
+ it("stamps the push time even when the pusher recorded no provenance", async () => {
+ t = await createTestApp();
+ const cookie = (await loginAdmin(t.app)).cookie;
+ expect((await pushWithSource(t.app, cookie, undefined)).status).toBe(200);
+
+ const manifest = await manifestOf(t.root);
+ expect(manifest.source).toBeUndefined();
+ expect(typeof manifest.pushedAt).toBe("string");
+ });
+
+ it("drops a malformed source rather than committing it to disk", async () => {
+ // A wrong-typed source would otherwise outlive the push that sent it, and every later
+ // reader would have to cope with it.
+ t = await createTestApp();
+ const cookie = (await loginAdmin(t.app)).cookie;
+ expect((await pushWithSource(t.app, cookie, { repo: 42, revision: "" })).status).toBe(200);
+
+ expect((await manifestOf(t.root)).source).toBeUndefined();
+ await expect(readHarnessInfo(t.root)).resolves.toMatchObject({ source: null });
+ });
+});
diff --git a/packages/server/test/hmr-manifest.test.ts b/packages/server/test/hmr-manifest.test.ts
index 35d1bdf0..889e7a66 100644
--- a/packages/server/test/hmr-manifest.test.ts
+++ b/packages/server/test/hmr-manifest.test.ts
@@ -7,7 +7,7 @@ import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
-import { resolveCliBundlePath } from "../src/hmr/manifest.js";
+import { readHarnessInfo, resolveCliBundlePath } from "../src/hmr/manifest.js";
async function makeRoot(): Promise<string> {
return fs.mkdtemp(path.join(os.tmpdir(), "penguin-hmr-manifest-test-"));
@@ -86,3 +86,97 @@ describe("resolveCliBundlePath", () => {
await expect(resolveCliBundlePath(root)).resolves.toBeNull();
});
});
+
+/**
+ * readHarnessInfo: the same disk, read for version reporting instead of for loading. It
+ * feeds `penguin version --json` and GET /api/version, so like resolveCliBundlePath it must
+ * degrade to missing fields rather than throw — a malformed store cannot be allowed to break
+ * the command a user runs to find out what is wrong.
+ */
+describe("readHarnessInfo", () => {
+ let root: string | undefined;
+ afterEach(async () => {
+ if (root) await fs.rm(root, { recursive: true, force: true });
+ root = undefined;
+ });
+
+ it("returns null for a root with nothing ever pushed", async () => {
+ root = await makeRoot();
+ await expect(readHarnessInfo(root)).resolves.toBeNull();
+ });
+
+ it("returns null for a manifest carrying no artifact pointer at all", async () => {
+ root = await makeRoot();
+ await writeManifest(root, { pushedAt: "2026-08-20T10:15:00.000Z" });
+ await expect(readHarnessInfo(root)).resolves.toBeNull();
+ });
+
+ it("reads provenance, commit time and all three bundle pointers", async () => {
+ root = await makeRoot();
+ await writeManifest(root, {
+ platform: { bundle: "store/platform/dead00.mjs" },
+ cli: { bundle: "store/cli/abc123.mjs" },
+ web: { manifest: "store/web/cafe01.webz" },
+ source: { repo: "https://example.com/penguin.git", revision: "v0.2.3-7-gabc1234-dirty" },
+ pushedAt: "2026-08-20T10:15:00.000Z",
+ });
+
+ await expect(readHarnessInfo(root)).resolves.toEqual({
+ source: { repo: "https://example.com/penguin.git", revision: "v0.2.3-7-gabc1234-dirty" },
+ pushedAt: "2026-08-20T10:15:00.000Z",
+ bundles: {
+ platform: "store/platform/dead00.mjs",
+ cli: "store/cli/abc123.mjs",
+ web: "store/web/cafe01.webz",
+ },
+ });
+ });
+
+ it("reports a version pushed before provenance was recorded", async () => {
+ // Every field a pusher may omit reads as null, so an older store still describes
+ // which bundles are committed rather than reading as "nothing pushed".
+ root = await makeRoot();
+ await writeManifest(root, {
+ platform: { bundle: "store/platform/dead00.mjs" },
+ cli: { bundle: "store/cli/abc123.mjs" },
+ web: { manifest: "store/web/cafe01.webz" },
+ });
+
+ const info = await readHarnessInfo(root);
+ expect(info?.source).toBeNull();
+ expect(info?.pushedAt).toBeNull();
+ expect(info?.bundles.cli).toBe("store/cli/abc123.mjs");
+ });
+
+ it("drops a half-filled provenance rather than reporting half a source", async () => {
+ root = await makeRoot();
+ await writeManifest(root, {
+ cli: { bundle: "store/cli/abc123.mjs" },
+ source: { repo: "https://example.com/penguin.git" },
+ });
+ await expect(readHarnessInfo(root)).resolves.toMatchObject({ source: null });
+ });
+
+ it("drops wrong-typed fields instead of passing them through", async () => {
+ root = await makeRoot();
+ await writeManifest(root, {
+ cli: { bundle: "store/cli/abc123.mjs" },
+ source: { repo: 42, revision: ["nope"] },
+ pushedAt: 1_755_000_000,
+ });
+
+ await expect(readHarnessInfo(root)).resolves.toEqual({
+ source: null,
+ pushedAt: null,
+ bundles: { platform: null, cli: "store/cli/abc123.mjs", web: null },
+ });
+ });
+
+ it("returns null (not a throw) for a truncated harness.json", async () => {
+ root = await makeRoot();
+ const hmrDir = path.join(root, "hmr");
+ await fs.mkdir(hmrDir, { recursive: true });
+ await fs.writeFile(path.join(hmrDir, "harness.json"), '{"cli": {"bundle":');
+ await expect(readHarnessInfo(root)).resolves.toBeNull();
+ });
+});
diff --git a/packages/server/test/version.test.ts b/packages/server/test/version.test.ts
index 79165deb..5ee691c0 100644
--- a/packages/server/test/version.test.ts
+++ b/packages/server/test/version.test.ts
@@ -7,7 +7,10 @@
* classifier and the "not launched via the CLI" early exit.
*/
import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import { BUILD_DATE, VERSION } from "@prismshadow/penguin-core";
+import fs from "node:fs/promises";
+import path from "node:path";
+import { VERSION } from "@prismshadow/penguin-core";
+import { versionReport } from "../src/version-report.js";
import type { UpdateCheckResponse, UpdateRunResponse, VersionResponse } from "../src/api/types.js";
import {
FAILURE_TTL_MS,
@@ -51,18 +54,53 @@ describe("GET /api/version", () => {
await t.cleanup();
});
- it("requires auth and reports core's version identity (dev build: buildDate null)", async () => {
+ it("requires auth and serves the version report unchanged", async () => {
expect((await t.app.request("/api/version")).status).toBe(401);
const admin = await loginAdmin(t.app);
const res = await apiClient(t.app, admin.cookie).get("/api/version");
expect(res.status).toBe(200);
const body = (await res.json()) as VersionResponse;
- // Both values come from core's constants, which the release workflow STAMPS before it
- // builds and tests (VERSION from the tag, BUILD_DATE with the run's UTC date). Asserting
- // a literal null passed everywhere except the one job that matters — the npm publish —
- // where it failed the release. Compare against the constants themselves.
- expect(body).toEqual({ version: VERSION, buildDate: BUILD_DATE });
+ // Compared against the producer, never against literals. The release workflow STAMPS
+ // core's constants before it builds and tests, so a hardcoded null passes everywhere
+ // except the one job that matters — the npm publish — where it failed the release.
+ // This is also the contract that `penguin version --json` prints the same record: the
+ // route adds no field of its own and drops none.
+ expect(body).toEqual(await versionReport(t.root));
+ // Non-vacuous floor, in case the report itself ever comes back degenerate.
+ expect(body.version).toBe(VERSION);
+ // `v` and a digit is the whole guarantee: a tag description names the nearest reachable
+ // tag, which is the PREVIOUS version throughout release preparation (VERSION is bumped
+ // in its own commit, the tag follows), so pinning `v${VERSION}` would fail on exactly
+ // the branch that cuts a release.
+ expect(body.describe).toMatch(/^v\d/);
+ expect(["release", "source"]).toContain(body.channel);
+ });
+
+ it("reports no harness for a root with nothing pushed, and the store's once there is", async () => {
+ const admin = await loginAdmin(t.app);
+ const get = async () =>
+ (await (await apiClient(t.app, admin.cookie).get("/api/version")).json()) as VersionResponse;
+
+ // A fresh test root has an empty HMR store: the build is packaged, not hot-updated.
+ expect((await get()).harness).toBeNull();
+
+ const hmrDir = path.join(t.root, "hmr");
+ await fs.mkdir(hmrDir, { recursive: true });
+ await fs.writeFile(
+ path.join(hmrDir, "harness.json"),
+ JSON.stringify({
+ cli: { bundle: "store/cli/abc123.mjs" },
+ source: { repo: "https://example.com/penguin.git", revision: "v0.2.3-7-gabc1234" },
+ pushedAt: "2026-08-20T10:15:00.000Z",
+ }),
+ );
+
+ expect((await get()).harness).toEqual({
+ source: { repo: "https://example.com/penguin.git", revision: "v0.2.3-7-gabc1234" },
+ pushedAt: "2026-08-20T10:15:00.000Z",
+ bundles: { platform: null, cli: "store/cli/abc123.mjs", web: null },
+ });
});
});
diff --git a/packages/server/tsup.config.ts b/packages/server/tsup.config.ts
index 0ff15803..2a86afbc 100644
--- a/packages/server/tsup.config.ts
+++ b/packages/server/tsup.config.ts
@@ -5,7 +5,9 @@ export default defineConfig({
// "./initial-password" and "./reset-admin-password" (lock, initial-password and
// reset-admin-password are side-effect-free for CLI pre-checks and the offline
// admin-password rescue); "./hmr/manifest" is the host-less harness.json reader the
- // CLI's thin loader resolves the current cli bundle through. There is deliberately no
+ // CLI's thin loader resolves the current cli bundle through, and "./version-report" is
+ // the shared assembler `penguin version` and GET /api/version both render (core plus
+ // that same reader — no server). There is deliberately no
// "./platform" subpath: src/hmr/entry.ts (this package's platform artifact
// compile target — see its own module doc) is compiled straight from source by
// esbuild in scripts/deploy.mjs, never through this package's published dist,
@@ -17,6 +19,7 @@ export default defineConfig({
"initial-password": "src/initial-password.ts",
"reset-admin-password": "src/reset-admin-password.ts",
"hmr/manifest": "src/hmr/manifest.ts",
+ "version-report": "src/version-report.ts",
},
format: ["esm"],
target: "node24",
diff --git a/scripts/build-git-stamp.mjs b/scripts/build-git-stamp.mjs
new file mode 100644
index 00000000..9577cb7b
--- /dev/null
+++ b/scripts/build-git-stamp.mjs
@@ -0,0 +1,73 @@
+/**
+ * The git identity of the checkout a build is made FROM, shaped as an esbuild/tsup `define`
+ * entry so every bundler inlines it verbatim into the artifact.
+ *
+ * This exists because a built artifact carries no path back to its origin. A bundle pushed
+ * into `<root>/hmr/store/cli/<sha>.mjs`, or a dist copied onto a server, sits outside any
+ * checkout — asking git at run time from there finds nothing, and asking from the user's
+ * working directory would answer about the user's repository instead of the harness. The
+ * information only exists while the build is running, so this captures it there.
+ *
+ * It reads git through core's own `internal/git-facts.ts` rather than reimplementing it: the
+ * stamp and the runtime fallback answer the same question, so one rule set decides what
+ * `-dirty` means and what a detached HEAD is. Importing TypeScript from a plain `.mjs` works
+ * because Node strips types (>=24, which this repo requires) and esbuild does the same when a
+ * tsup config loads this module.
+ *
+ * Deliberately free of anything that changes between two builds of identical source — no
+ * timestamp, no counter. The HMR store addresses bundles by content hash, so a stamp that
+ * varied per build would turn every re-push of unchanged code into a new store entry.
+ *
+ * Returns `{}` when there is nothing to stamp (no git, or a tree that is not this
+ * repository's checkout). The artifact then carries no stamp and the runtime falls back to
+ * asking git about its own checkout, which is what an un-bundled `tsx` or `vitest` run does.
+ */
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { findCheckoutRoot, git, readCheckout } from "../packages/core/src/internal/git-facts.ts";
+
+const HERE = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+
+/** The identifier the bundlers replace; `build-info.ts` declares and reads the same name. */
+export const BUILD_GIT_DEFINE = "__PENGUIN_BUILD_GIT__";
+
+/**
+ * The checkout this build is running from, or null when it is not one of ours — the same
+ * `.git` + `pnpm-workspace.yaml` test the runtime fallback applies, so a source tree
+ * extracted inside an unrelated repository stamps nothing rather than that repository.
+ */
+function root() {
+ return findCheckoutRoot(HERE);
+}
+
+/**
+ * This checkout's origin remote, falling back to its directory name — the `repo` half of a
+ * push's recorded provenance. Null outside a checkout of this repository.
+ */
+export function originUrl() {
+ const dir = root();
+ if (dir === null) return null;
+ return git(dir, ["remote", "get-url", "origin"]) ?? path.basename(dir);
+}
+
+/** The facts a build or a push reports about this checkout, or null outside one. */
+export function checkoutFacts() {
+ const dir = root();
+ if (dir === null) return null;
+ const facts = readCheckout(dir);
+ // Naming neither a description nor a commit says nothing about the artifact; the runtime
+ // treats such a stamp as absent too, so do not emit one.
+ return facts.described === null && facts.commit === null ? null : facts;
+}
+
+/**
+ * `{ [BUILD_GIT_DEFINE]: <JS expression> }` for a bundler's `define`, or `{}`.
+ *
+ * The value is double-encoded on purpose: `define` substitutes a JS *expression*, so the
+ * expression has to be a quoted string literal whose contents are the JSON the runtime
+ * parses back into CheckoutFacts.
+ */
+export function buildGitDefine() {
+ const facts = checkoutFacts();
+ return facts === null ? {} : { [BUILD_GIT_DEFINE]: JSON.stringify(JSON.stringify(facts)) };
+}
diff --git a/scripts/deploy.mjs b/scripts/deploy.mjs
index 452e3eed..85d4a967 100644
--- a/scripts/deploy.mjs
+++ b/scripts/deploy.mjs
@@ -27,6 +27,7 @@ import path from "node:path";
import zlib from "node:zlib";
import { fileURLToPath } from "node:url";
import { unsafePlaintextTarget } from "./deploy-target-safety.mjs";
+import { buildGitDefine, checkoutFacts, originUrl } from "./build-git-stamp.mjs";
const require = createRequire(import.meta.url);
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
@@ -38,6 +39,23 @@ const CLI_BUNDLE = path.join(os.tmpdir(), `penguin-deploy-cli-${process.pid}.mjs
const log = (msg) => console.log(`[deploy] ${msg}`);
+/**
+ * Provenance for this push, recorded with the version so `penguin version --json` on the
+ * target can name where its harness came from — harness.json's copy, alongside the same
+ * revision inlined into the bundles themselves.
+ *
+ * `revision` is spelled exactly as core's BuildInfo.describe, `-dirty` included: a deploy
+ * from an uncommitted tree is normal here and the record has to admit it, since the sha
+ * alone would name code that never existed. Null when this is not a checkout of this
+ * repository, in which case the push carries no `source` rather than a fabricated one.
+ */
+function pushSource() {
+ const facts = checkoutFacts();
+ const repo = originUrl();
+ if (facts?.described == null || repo === null) return null;
+ return { repo, revision: facts.described };
+}
+
function usage(problem) {
console.error(
`${problem}\n\n` +
@@ -138,6 +156,12 @@ async function compileEntry(entry, outfile) {
alias: {
"@prismshadow/penguin-core/kernel": require.resolve("@prismshadow/penguin-core/kernel"),
},
+ // The pushed bundle lands under `<root>/hmr/store/`, outside any checkout, so its own
+ // revision has to be inlined here or it can never be recovered: `penguin version` from
+ // a hot-loaded CLI would otherwise report the bare version it was compiled from. This is
+ // the same value the push records as `source`, reaching the target by a second route —
+ // in the artifact itself rather than in harness.json.
+ define: buildGitDefine(),
});
}
@@ -219,6 +243,7 @@ async function main() {
const files = await readWebManifest();
const assets = await readNativeAssets();
+ const source = pushSource();
const gz = zlib.gzipSync(
Buffer.from(
JSON.stringify({
@@ -226,9 +251,11 @@ async function main() {
cli: await fsp.readFile(CLI_BUNDLE, "utf8"),
web: { files },
assets,
+ ...(source === null ? {} : { source }),
}),
),
);
+ if (source !== null) log(`provenance: ${source.revision}`);
log(
`pushing ${Object.keys(files).length} web files + ${Object.keys(assets.files).length} native assets + 2 bundles (${(gz.length / 1048576).toFixed(1)} MB) to ${baseUrl}…`,
);
diff --git a/scripts/test-installer.sh b/scripts/test-installer.sh
index ed2bd0b4..825976c0 100755
--- a/scripts/test-installer.sh
+++ b/scripts/test-installer.sh
@@ -111,6 +111,8 @@ sed -i 's/^TAG=.*/TAG="${TEST_RELEASE_TAG:?}"/' "$STAMP_SCRIPT"
grep -q 'SH_HAS_MARKER' "$STAMP_SCRIPT" \
|| fail_test "release workflow stamping block could not be extracted"
+# Mirrors the three stamped constants of packages/core/src/index.ts. `make_stamp_case legacy`
+# drops BUILD_COMMIT, standing in for a tag cut before that constant existed.
make_stamp_case() {
case_dir="$1"
mkdir -p "$case_dir/packages/core/src"
@@ -118,25 +120,70 @@ make_stamp_case() {
'export const VERSION = "0.0.0";' \
'export const BUILD_DATE: string | null = null;' \
> "$case_dir/packages/core/src/index.ts"
+ [ "${2:-}" = legacy ] || printf '%s\n' 'export const BUILD_COMMIT: string | null = null;' \
+ >> "$case_dir/packages/core/src/index.ts"
}
+# GITHUB_SHA is exported to every step of a real Actions run, so each case below pins it
+# rather than inheriting whatever the host happens to have set.
+STAMP_SHA=0123456789abcdef0123456789abcdef01234567
+
STAMP_NEW_DIR="$WORK_DIR/stamp-new"
make_stamp_case "$STAMP_NEW_DIR"
printf '%s\n' 'EMBEDDED_RELEASE_VERSION="__PENGUIN_RELEASE_VERSION__"' \
> "$STAMP_NEW_DIR/install.sh"
printf '%s\n' '$EmbeddedReleaseVersion = "__PENGUIN_RELEASE_VERSION__"' \
> "$STAMP_NEW_DIR/install.ps1"
-(cd "$STAMP_NEW_DIR" && TEST_RELEASE_TAG=v9.8.7 sh -e "$STAMP_SCRIPT")
+(cd "$STAMP_NEW_DIR" && TEST_RELEASE_TAG=v9.8.7 GITHUB_SHA="$STAMP_SHA" sh -e "$STAMP_SCRIPT")
grep -Fq 'EMBEDDED_RELEASE_VERSION="v9.8.7"' "$STAMP_NEW_DIR/install.sh" \
|| fail_test "release workflow did not stamp the POSIX installer"
grep -Fq '$EmbeddedReleaseVersion = "v9.8.7"' "$STAMP_NEW_DIR/install.ps1" \
|| fail_test "release workflow did not stamp the PowerShell installer"
+grep -Fq 'export const VERSION = "9.8.7";' "$STAMP_NEW_DIR/packages/core/src/index.ts" \
+ || fail_test "release workflow did not stamp core's VERSION"
+grep -Eq 'export const BUILD_DATE: string \| null = "[0-9]{4}-[0-9]{2}-[0-9]{2}";' \
+ "$STAMP_NEW_DIR/packages/core/src/index.ts" \
+ || fail_test "release workflow did not stamp core's BUILD_DATE"
+grep -Fq "export const BUILD_COMMIT: string | null = \"$STAMP_SHA\";" \
+ "$STAMP_NEW_DIR/packages/core/src/index.ts" \
+ || fail_test "release workflow did not stamp core's BUILD_COMMIT"
+
+# Without GITHUB_SHA (a replay outside Actions) the commit stays null and the rest still stamps.
+STAMP_NOSHA_DIR="$WORK_DIR/stamp-no-sha"
+make_stamp_case "$STAMP_NOSHA_DIR"
+printf '%s\n' 'EMBEDDED_RELEASE_VERSION="__PENGUIN_RELEASE_VERSION__"' \
+ > "$STAMP_NOSHA_DIR/install.sh"
+printf '%s\n' '$EmbeddedReleaseVersion = "__PENGUIN_RELEASE_VERSION__"' \
+ > "$STAMP_NOSHA_DIR/install.ps1"
+(cd "$STAMP_NOSHA_DIR" && TEST_RELEASE_TAG=v9.8.7 GITHUB_SHA= sh -e "$STAMP_SCRIPT") \
+ > "$WORK_DIR/stamp-no-sha.output"
+grep -Fq 'GITHUB_SHA is unset' "$WORK_DIR/stamp-no-sha.output" \
+ || fail_test "release workflow did not report the unstamped commit"
+grep -Fq 'export const BUILD_COMMIT: string | null = null;' \
+ "$STAMP_NOSHA_DIR/packages/core/src/index.ts" \
+ || fail_test "release workflow stamped a commit without GITHUB_SHA"
+grep -Fq 'export const VERSION = "9.8.7";' "$STAMP_NOSHA_DIR/packages/core/src/index.ts" \
+ || fail_test "release workflow skipped the version stamp when GITHUB_SHA was unset"
+
+# A tag predating the BUILD_COMMIT constant must still rebuild.
+STAMP_NOCONST_DIR="$WORK_DIR/stamp-no-commit-const"
+make_stamp_case "$STAMP_NOCONST_DIR" legacy
+printf '%s\n' 'EMBEDDED_RELEASE_VERSION="__PENGUIN_RELEASE_VERSION__"' \
+ > "$STAMP_NOCONST_DIR/install.sh"
+printf '%s\n' '$EmbeddedReleaseVersion = "__PENGUIN_RELEASE_VERSION__"' \
+ > "$STAMP_NOCONST_DIR/install.ps1"
+(cd "$STAMP_NOCONST_DIR" && TEST_RELEASE_TAG=v9.8.7 GITHUB_SHA="$STAMP_SHA" sh -e "$STAMP_SCRIPT") \
+ > "$WORK_DIR/stamp-no-commit-const.output"
+grep -Fq 'Legacy tag without a BUILD_COMMIT constant' "$WORK_DIR/stamp-no-commit-const.output" \
+ || fail_test "release workflow did not use the legacy path for a missing BUILD_COMMIT"
+grep -Fq 'export const VERSION = "9.8.7";' "$STAMP_NOCONST_DIR/packages/core/src/index.ts" \
+ || fail_test "release workflow failed to stamp a tag without BUILD_COMMIT"
STAMP_LEGACY_DIR="$WORK_DIR/stamp-legacy"
make_stamp_case "$STAMP_LEGACY_DIR"
printf '%s\n' 'legacy POSIX installer' > "$STAMP_LEGACY_DIR/install.sh"
printf '%s\n' 'legacy PowerShell installer' > "$STAMP_LEGACY_DIR/install.ps1"
-(cd "$STAMP_LEGACY_DIR" && TEST_RELEASE_TAG=v9.8.7 sh -e "$STAMP_SCRIPT") \
+(cd "$STAMP_LEGACY_DIR" && TEST_RELEASE_TAG=v9.8.7 GITHUB_SHA="$STAMP_SHA" sh -e "$STAMP_SCRIPT") \
> "$WORK_DIR/stamp-legacy.output"
grep -Fq 'leaving installers unstamped' "$WORK_DIR/stamp-legacy.output" \
|| fail_test "release workflow did not use the legacy installer path"
@@ -157,8 +204,8 @@ for inconsistent_side in posix powershell; do
printf '%s\n' '$EmbeddedReleaseVersion = "__PENGUIN_RELEASE_VERSION__"' \
> "$STAMP_INCONSISTENT_DIR/install.ps1"
fi
- if (cd "$STAMP_INCONSISTENT_DIR" && TEST_RELEASE_TAG=v9.8.7 sh -e "$STAMP_SCRIPT") \
- > /dev/null 2>&1; then
+ if (cd "$STAMP_INCONSISTENT_DIR" && TEST_RELEASE_TAG=v9.8.7 GITHUB_SHA="$STAMP_SHA" \
+ sh -e "$STAMP_SCRIPT") > /dev/null 2>&1; then
fail_test "release workflow accepted inconsistent $inconsistent_side installer markers"
fi
done