From 87999536f2b73319dfb19043c50a724302824425 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 28 Jun 2026 07:32:16 +0000 Subject: [PATCH 1/5] chore(release): 2.2.0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Agent gate coverage (7 agents) + the first 3.0 primitive (kit identity). Additive minor — no breaking changes to any stable surface. See CHANGELOG. Co-Authored-By: Claude Opus 4.8 (1M context) Claude-Session: https://claude.ai/code/session_015ERHw6bVUz39sAuoQZ1iyg --- CHANGELOG.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++ package.json | 2 +- 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 59a0dcd0..f13804dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,52 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] +## [2.2.0] - 2026-06-28 + +kit 2.2 — agent gate coverage + the first 3.0 primitive. Additive minor: new +experimental commands and adapters, no breaking changes to any `stable` surface. + +### Added + +- **Install-gate now covers 7 agents.** `kit agent-config --install-gate` wires a + pre-tool gate that blocks an un-triaged package install before it runs. + Deterministic core (`parseInstallCommand` + `decideBashGate`, npm/pnpm/yarn/bun + /npx + pip/pip3/pipx/uv; fail-closed; out-of-scope ecosystems pass through) plus + per-agent adapters: Claude Code / Codex / Amazon Q / Gemini CLI / Cursor (exit-2 + hooks), OpenCode (generated `.opencode/plugin` hooking `tool.execute.before`, + throws), and Cline (executable `.clinerules/hooks/PreToolUse` shim → `{cancel:true}` + stdout contract). Each adapter was built only after verifying the agent's hook + + payload schema against primary sources. Continue has no external pre-tool hook + surface (declarative permissions only). `gate-bash` (experimental) is the handler. +- **`kit identity`** (experimental) — a local Ed25519 machine/agent identity + (init / show [--public] / rotate). Asymmetric, attributable signing: a verifier + needs only the public key, never a forge-capable secret. Private key stored + owner-only under `~/.kit`. +- **`kit ci --init gitlab|bitbucket`** — generate a pipeline snippet that runs + `kit ci` (GitLab job → JUnit; Bitbucket step). Prints to stdout; `--write` writes + the file only when absent. Plus `docs/CI_AND_GIT_HOSTS.md` (the 4-layer gate model + + per-host enforcement guidance). +- **`kit gha-audit` extended to GitLab CI + Bitbucket Pipelines** — lints + `.gitlab-ci.yml` / `bitbucket-pipelines.yml` for unpinned `:latest`/untagged + images (CWE-1104), remote `include:` (OWASP-A08), and pipe-to-shell (CWE-494). +- **OpenCode coverage** — SQLite (`opencode.db`) memory parser (with the legacy + flat-JSON path as fallback), and `agent-audit` now scans `.opencode/plugin`. +- **trivy + trufflehog declared as managed tools** (`.kit.toml [tools]`) so + `kit install` provisions them; a non-gating CI job dogfoods the provision+scan path. + +### Changed + +- **Memory: debounced mid-session indexing** — recall stays fresh within a long or + ephemeral session (a detached `kit memory index` at most once per 10 min on the + UserPromptSubmit hook), not only at SessionEnd. +- Pinned the 7 previously range-specced dependencies to exact versions. + +### Fixed + +- ci-audit no longer mis-reports a bare `name:` label (e.g. a Bitbucket step name) + as an unpinned image. +- gitignore `.kit-triage.jsonl` (kit's local triage audit log). + ## [2.1.1] - 2026-06-27 kit 2.1 (Reach) — native Windows. The build + ~all tests already ran on windows-latest; this closes the remaining cross-platform gaps so kit runs natively on Windows (PowerShell/cmd), not only via WSL2. diff --git a/package.json b/package.json index 500deb49..a81641f2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sandstream-kit", - "version": "2.1.1", + "version": "2.2.0", "description": "developer kit. zero LLM, local-first, multi-vault. one command from git clone to working dev environment.", "license": "MIT", "funding": "https://buymeacoffee.com/sandstream", From e2e713ace3eb7a7615314b1d218af4ef1ad6e987 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 28 Jun 2026 09:02:48 +0000 Subject: [PATCH 2/5] feat(audit): identity-signed audit entries + signature verify MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add the asymmetric ATTRIBUTION layer on top of the hash chain (integrity) and HMAC anchor. When a local `kit identity` exists, each appended `.kit-audit.jsonl` line is signed: kit signs the line `hash` and attaches non-hashed `kid` + `sig` (Ed25519). Best-effort and append-safe — no identity means entries are written exactly as before, and a signing failure never blocks the append. - audit.ts: appendChained best-effort signs via signLineHash(); verifyAuditChain excludes sig/kid from the hashed remainder (mixed signed/unsigned/legacy logs still verify); new pure verifyAuditSignatures(content, resolvePubkey) returning {total, signed, verified, invalid, unverifiable, unsigned, ok}. Forged sig => hard fail; unknown/absent key => fail-open. - identity.ts: localPublicKeys() builds a kid->pubkey trust map from the current identity plus archived rotated (.bak) records. - commands/audit.ts: `kit audit verify` reports the signature tally and fails on a forged signature. - docs/AUDIT_ATTESTATION.md §2.5 + CHANGELOG Unreleased. - Tests: chain stays valid with sig/kid present, signed entries verify, forged sig fails, unknown key is unverifiable (fail-open), legacy keyless is unsigned-ok, localPublicKeys resolves current + rotated keys. Co-Authored-By: Claude Opus 4.8 (1M context) Claude-Session: https://claude.ai/code/session_015ERHw6bVUz39sAuoQZ1iyg --- CHANGELOG.md | 16 ++++- docs/AUDIT_ATTESTATION.md | 39 +++++++++++ src/audit.test.ts | 132 ++++++++++++++++++++++++++++++++++++++ src/audit.ts | 117 ++++++++++++++++++++++++++++++++- src/commands/audit.ts | 27 ++++++++ src/identity.test.ts | 19 ++++++ src/identity.ts | 40 +++++++++++- 7 files changed, 386 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f13804dd..fb7f965a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,20 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] +### Added + +- **Identity-signed audit entries.** When a local `kit identity` exists, each + appended `.kit-audit.jsonl` line is signed: kit attaches `kid` (signer id) + + `sig` (Ed25519 signature over the line hash). Best-effort and append-safe — no + identity means entries are written as before, and a signing failure never + blocks the append. `kid`/`sig` sit outside the hashed remainder, so the hash + chain still verifies across mixed signed/unsigned/legacy logs. `kit audit +verify` now reports the signature tally (verified / unknown-key / unsigned) + against the locally-known keys (current + rotated) and FAILS hard on a forged + signature, while fail-opening on absent/unknown trust. This is the asymmetric + ATTRIBUTION layer (who produced an entry, verifiable with only the public key) + orthogonal to the symmetric HMAC INTEGRITY anchor. See `docs/AUDIT_ATTESTATION.md` §2.5. + ## [2.2.0] - 2026-06-28 kit 2.2 — agent gate coverage + the first 3.0 primitive. Additive minor: new @@ -30,7 +44,7 @@ experimental commands and adapters, no breaking changes to any `stable` surface. - **`kit ci --init gitlab|bitbucket`** — generate a pipeline snippet that runs `kit ci` (GitLab job → JUnit; Bitbucket step). Prints to stdout; `--write` writes the file only when absent. Plus `docs/CI_AND_GIT_HOSTS.md` (the 4-layer gate model - + per-host enforcement guidance). + - per-host enforcement guidance). - **`kit gha-audit` extended to GitLab CI + Bitbucket Pipelines** — lints `.gitlab-ci.yml` / `bitbucket-pipelines.yml` for unpinned `:latest`/untagged images (CWE-1104), remote `include:` (OWASP-A08), and pipe-to-shell (CWE-494). diff --git a/docs/AUDIT_ATTESTATION.md b/docs/AUDIT_ATTESTATION.md index e7157c01..a173c473 100644 --- a/docs/AUDIT_ATTESTATION.md +++ b/docs/AUDIT_ATTESTATION.md @@ -79,6 +79,45 @@ tamper-proof against a same-UID local principal: an attacker running as the same user can read `~/.kit/audit-anchor.key` AND the anchor record, recompute the tip, and re-seal a forged log. Do not describe this as tamper-proof. +## 2.5. Identity signatures on audit entries (`kit identity` + `kit audit verify`) + +The HMAC anchor is the INTEGRITY layer (was anything edited / rolled back). It is +symmetric, so it answers "was this tampered" but not "who wrote it" — a verifier +holding the anchor key could itself have produced any entry. The identity layer +is the orthogonal ATTRIBUTION layer. + +When a local `kit identity` exists (an Ed25519 keypair under `~/.kit`, see +`kit identity`), each appended audit line is additionally signed: kit signs the +line's `hash` and attaches two fields the chain does NOT cover, `kid` (the +signer's identity id) and `sig` (base64 Ed25519 signature over `hash`). + +- **Signing is best-effort and append-safe.** No identity → entries are written + exactly as before (no `kid`/`sig`). A signing failure never blocks the append. +- **`kid`/`sig` sit OUTSIDE the hashed remainder.** `verifyAuditChain` strips + them before recomputing the hash, so a log mixes signed and unsigned lines and + the chain still verifies end to end. Existing/legacy logs are unaffected. +- **`kit audit verify` reports the signature tally** after the chain + anchor + checks: `verified / signed` against the locally-known keys (the current + identity plus archived rotated keys), how many were signed by an unknown key + (`unverifiable`), and how many were keyless (`unsigned`). + +Verdict rules (`verifyAuditSignatures`): + +| Condition | Effect on verify | +| ------------------------------------------ | ------------------------------------------------------- | +| Signature valid for a known `kid` | counted `verified` | +| Signature INVALID (forged / hash tampered) | hard FAIL (`invalid > 0`) | +| `kid` not resolvable to a public key | `unverifiable` — fail-OPEN (absence of trust ≠ forgery) | +| No `kid`/`sig` (legacy/keyless) | `unsigned` — fail-OPEN | + +Asymmetric payoff: a remote / CI / teammate verifies WHO produced an entry with +only the PUBLIC key — never a forge-capable secret, unlike the HMAC anchor. Same +same-UID boundary applies for _production_: a same-UID principal can read the +0600 private key and sign as this identity (closed later by non-exportable key +storage — TPM/keychain/HSM, the 3.0 regulated tier). What it buys today is +offline, third-party-verifiable attribution that the symmetric anchor cannot +express. + ## 3. Signed check-attestation receipt (`kit check --attest`) With `--attest` (or `KIT_ATTEST=1`), `kit check` / `kit ci` writes diff --git a/src/audit.test.ts b/src/audit.test.ts index 67f48314..683b4985 100644 --- a/src/audit.test.ts +++ b/src/audit.test.ts @@ -10,7 +10,9 @@ import { formatAuditLog, appendAuditEventDirect, verifyAuditChain, + verifyAuditSignatures, } from "./audit.js"; +import { loadOrCreateIdentity, localPublicKeys } from "./identity.js"; import type { GovernanceConfig } from "./config.js"; describe("logAuditEvent", () => { @@ -416,6 +418,136 @@ describe("verifyAuditChain (tamper-evidence)", () => { }); }); +describe("verifyAuditSignatures (identity attribution)", () => { + async function writeEvents(dir: string, n: number): Promise { + for (let i = 0; i < n; i++) { + const ok = await appendAuditEventDirect( + { operation: `op-${i}`, environment: "dev", success: true }, + { cwd: dir }, + ); + assert.equal(ok, true); + } + } + + // Run a body with a fresh, isolated identity dir (KIT_IDENTITY_DIR), restoring + // the prior env afterward — so signing happens against a temp keypair. + async function withIdentity(fn: (idDir: string) => Promise): Promise { + const prev = process.env.KIT_IDENTITY_DIR; + const idDir = mkdtempSync(join(tmpdir(), "kit-audit-id-")); + process.env.KIT_IDENTITY_DIR = idDir; + try { + await fn(idDir); + } finally { + if (prev === undefined) delete process.env.KIT_IDENTITY_DIR; + else process.env.KIT_IDENTITY_DIR = prev; + rmSync(idDir, { recursive: true, force: true }); + } + } + + it("signs appended entries and the chain still verifies (sig/kid excluded from hash)", async () => { + await withIdentity(async () => { + const { identity } = loadOrCreateIdentity(); + const dir = mkdtempSync(join(tmpdir(), "kit-audit-s-")); + try { + await writeEvents(dir, 3); + const content = readFileSync(join(dir, ".kit-audit.jsonl"), "utf8"); + // Each line carries kid + sig... + for (const line of content.trim().split("\n")) { + const obj = JSON.parse(line); + assert.equal(obj.kid, identity.id); + assert.equal(typeof obj.sig, "string"); + } + // ...and the hash chain is still intact despite the extra fields. + const chain = verifyAuditChain(content); + assert.equal(chain.ok, true); + assert.equal(chain.entries, 3); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + }); + + it("verifies signatures against the local public key", async () => { + await withIdentity(async () => { + loadOrCreateIdentity(); + const dir = mkdtempSync(join(tmpdir(), "kit-audit-sv-")); + try { + await writeEvents(dir, 3); + const content = readFileSync(join(dir, ".kit-audit.jsonl"), "utf8"); + const trust = localPublicKeys(); + const s = verifyAuditSignatures(content, (kid) => trust.get(kid) ?? null); + assert.equal(s.total, 3); + assert.equal(s.signed, 3); + assert.equal(s.verified, 3); + assert.equal(s.invalid, 0); + assert.equal(s.unsigned, 0); + assert.equal(s.ok, true); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + }); + + it("flags a forged signature (invalid > 0 ⇒ not ok)", async () => { + await withIdentity(async () => { + loadOrCreateIdentity(); + const dir = mkdtempSync(join(tmpdir(), "kit-audit-f-")); + try { + await writeEvents(dir, 2); + const lines = readFileSync(join(dir, ".kit-audit.jsonl"), "utf8").trim().split("\n"); + const obj = JSON.parse(lines[0]); + // Swap the signature for a valid-base64 but wrong signature. + obj.sig = Buffer.from("not-the-real-signature-bytes-xx").toString("base64"); + lines[0] = JSON.stringify(obj); + const content = lines.join("\n") + "\n"; + const trust = localPublicKeys(); + const s = verifyAuditSignatures(content, (kid) => trust.get(kid) ?? null); + assert.equal(s.invalid, 1); + assert.equal(s.verified, 1); + assert.equal(s.ok, false); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + }); + + it("reports tampered content under an unknown key as unverifiable (not a forge)", async () => { + await withIdentity(async () => { + loadOrCreateIdentity(); + const dir = mkdtempSync(join(tmpdir(), "kit-audit-u-")); + try { + await writeEvents(dir, 2); + const content = readFileSync(join(dir, ".kit-audit.jsonl"), "utf8"); + // Resolver that knows no keys → signed entries can't be checked. + const s = verifyAuditSignatures(content, () => null); + assert.equal(s.signed, 2); + assert.equal(s.unverifiable, 2); + assert.equal(s.verified, 0); + assert.equal(s.invalid, 0); + assert.equal(s.ok, true, "unknown key is fail-open, not a forge"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + }); + + it("treats a keyless (legacy) log as unsigned, ok", () => { + const legacy = + JSON.stringify({ + timestamp: "t", + operation: "x", + environment: "dev", + success: true, + prev: "0".repeat(64), + hash: "abc", + }) + "\n"; + const s = verifyAuditSignatures(legacy, () => "irrelevant"); + assert.equal(s.signed, 0); + assert.equal(s.unsigned, 1); + assert.equal(s.ok, true); + }); +}); + describe("logAuditEvent return value (fail-closed signal)", () => { function cfg(logFile: string): any { return { diff --git a/src/audit.ts b/src/audit.ts index 9d01fdde..5faf6c16 100644 --- a/src/audit.ts +++ b/src/audit.ts @@ -2,6 +2,7 @@ import { appendFile, readFile, writeFile, rename } from "node:fs/promises"; import { resolve } from "node:path"; import { createHash } from "node:crypto"; import type { GovernanceConfig } from "./config.js"; +import { tryLoadIdentity, signWithIdentity, verifySignature } from "./identity.js"; // ── Tamper-evident hash chain ─────────────────────────────────────────────── // Each appended line carries `prev` (the previous line's hash) and `hash` @@ -34,7 +35,34 @@ async function appendChained(logPath: string, event: AuditEvent): Promise const prev = await lastChainHash(logPath); const preHash = JSON.stringify({ ...event, prev }); const hash = hashLine(preHash); - await appendFile(logPath, JSON.stringify({ ...event, prev, hash }) + "\n", "utf-8"); + // Best-effort identity signing: if a local kit identity exists, sign the + // line hash with it and attach non-hashed `kid` + `sig`. This adds + // ASYMMETRIC, ATTRIBUTABLE provenance on top of the (symmetric) hash chain — + // any verifier with the public key can confirm WHO produced the entry. Both + // fields sit OUTSIDE the hashed remainder (verifyAuditChain strips them), so + // the chain stays valid whether or not an entry is signed; legacy/keyless + // appends are unaffected. Failure to sign never blocks the append. + const signed = signLineHash(hash); + const line = signed + ? { ...event, prev, hash, kid: signed.kid, sig: signed.sig } + : { ...event, prev, hash }; + await appendFile(logPath, JSON.stringify(line) + "\n", "utf-8"); +} + +/** + * Sign a line hash with the local kit identity, if one is present. Returns the + * key id + base64 Ed25519 signature, or null when no identity exists / signing + * fails. Pure best-effort: callers never gate on the result. + */ +function signLineHash(hash: string): { kid: string; sig: string } | null { + const identity = tryLoadIdentity(); + if (!identity) return null; + try { + const sig = signWithIdentity(hash).toString("base64"); + return { kid: identity.id, sig }; + } catch { + return null; // record present but key unreadable → unsigned, not a failure + } } export interface ChainVerifyResult { @@ -60,7 +88,10 @@ export function verifyAuditChain(content: string): ChainVerifyResult { } catch { return { ok: false, entries: i, brokenAt: i, reason: "unparseable line" }; } - const { hash, ...rest } = obj; + // `sig`/`kid` are attached AFTER the hash is computed (see appendChained), + // so they must be excluded from the hashed remainder. Lines without them + // (legacy/keyless) leave `rest` unchanged → backward-compatible. + const { hash, sig: _sig, kid: _kid, ...rest } = obj; if (typeof hash !== "string") { return { ok: false, entries: i, brokenAt: i, reason: "missing hash (unchained entry)" }; } @@ -85,6 +116,88 @@ export function verifyAuditChain(content: string): ChainVerifyResult { return { ok: true, entries: lines.length }; } +export interface SignatureVerifyResult { + /** Total non-empty lines inspected. */ + total: number; + /** Lines carrying both `kid` and `sig`. */ + signed: number; + /** Signed lines whose signature verified against the resolved public key. */ + verified: number; + /** Signed lines whose signature FAILED to verify (forged/tampered). */ + invalid: number; + /** Signed lines whose `kid` could not be resolved to a public key. */ + unverifiable: number; + /** Lines with no signature (legacy/keyless appends). */ + unsigned: number; + /** + * True when no signed entry FAILED verification. Unsigned and unverifiable + * entries do not flip this to false — absence of a signature is not tamper + * evidence (the hash chain covers that); a *bad* signature is. + */ + ok: boolean; +} + +/** + * Verify identity signatures across a `.kit-audit.jsonl` body. Each signed line + * carries `kid` (the signer's identity id) and `sig` (base64 Ed25519 signature + * over the line `hash`). `resolvePubkey` maps a `kid` to its SPKI-PEM public key + * (or null if unknown — e.g. a key not in the trust store / revoked). + * + * This is the ATTRIBUTION layer, orthogonal to verifyAuditChain (the integrity + * layer). The chain proves nothing was edited/reordered; the signatures prove + * WHO produced each entry. Pure — no I/O, fully testable. Fail-closed on a bad + * signature (`invalid` > 0 ⇒ `ok=false`), fail-open on missing/unknown keys. + */ +export function verifyAuditSignatures( + content: string, + resolvePubkey: (kid: string) => string | null | undefined, +): SignatureVerifyResult { + const lines = content.split("\n").filter((l) => l.trim().length > 0); + let signed = 0; + let verified = 0; + let invalid = 0; + let unverifiable = 0; + let unsigned = 0; + for (const line of lines) { + let obj: Record; + try { + obj = JSON.parse(line) as Record; + } catch { + // Unparseable lines are the chain verifier's concern; ignore here. + continue; + } + const { hash, kid, sig } = obj as { hash?: unknown; kid?: unknown; sig?: unknown }; + if (typeof kid !== "string" || typeof sig !== "string") { + unsigned++; + continue; + } + signed++; + if (typeof hash !== "string") { + invalid++; // signed but no hash to have signed → malformed + continue; + } + const pubkey = resolvePubkey(kid); + if (!pubkey) { + unverifiable++; + continue; + } + if (verifySignature(hash, Buffer.from(sig, "base64"), pubkey)) { + verified++; + } else { + invalid++; + } + } + return { + total: lines.length, + signed, + verified, + invalid, + unverifiable, + unsigned, + ok: invalid === 0, + }; +} + const PENDING_QUEUE_FILE = ".kit-audit.pending"; const MAX_PENDING_ENTRIES = 500; const RETRY_BACKOFF_MS = [250, 1_000, 4_000]; diff --git a/src/commands/audit.ts b/src/commands/audit.ts index 2b9b433f..5e14e8be 100644 --- a/src/commands/audit.ts +++ b/src/commands/audit.ts @@ -122,6 +122,33 @@ async function cmdAuditVerify(): Promise { } console.log(`${c.green}✓ audit chain intact${c.reset} ${c.dim}${r.entries} entries${c.reset}`); + // Identity-signature layer (orthogonal to the chain): proves WHO produced each + // entry, not just that nothing was edited. Best-effort attribution — entries + // signed by a locally-known key verify; unsigned (legacy/keyless) and entries + // signed by an unknown key are reported but do not fail verify. A FORGED + // signature (invalid > 0) is a hard failure. + const { verifyAuditSignatures } = await import("../audit.js"); + const { localPublicKeys } = await import("../identity.js"); + const trust = localPublicKeys(); + const s = verifyAuditSignatures(content, (kid) => trust.get(kid) ?? null); + if (s.signed > 0) { + if (s.invalid > 0) { + console.error( + `${c.red}✗ ${s.invalid} signed entr${s.invalid === 1 ? "y has" : "ies have"} an INVALID signature (forged/tampered)${c.reset}`, + ); + } + const parts = [`${s.verified}/${s.signed} signatures verified`]; + if (s.unverifiable > 0) parts.push(`${s.unverifiable} from unknown key(s)`); + if (s.unsigned > 0) parts.push(`${s.unsigned} unsigned`); + const icon = s.ok ? `${c.green}✓` : `${c.red}✗`; + console.log(`${icon} identity signatures${c.reset} ${c.dim}${parts.join(", ")}${c.reset}`); + if (!s.ok) return false; + } else if (s.unsigned > 0) { + console.log( + `${c.dim}· no identity signatures (${s.unsigned} keyless entries — run \`kit identity\` to start signing)${c.reset}`, + ); + } + const { readAnchorRecord, tryReadAuditAnchorKey, diff --git a/src/identity.test.ts b/src/identity.test.ts index d1e67383..e83bc503 100644 --- a/src/identity.test.ts +++ b/src/identity.test.ts @@ -11,6 +11,7 @@ import { signWithIdentity, verifySignature, identityId, + localPublicKeys, } from "./identity.js"; describe("identity", () => { @@ -83,6 +84,24 @@ describe("identity", () => { assert.equal(tryLoadIdentity()?.id, after.id); }); + it("localPublicKeys returns the current key plus archived (rotated) keys", () => { + const own = mkdtempSync(join(tmpdir(), "kit-identity-keys-")); + try { + process.env.KIT_IDENTITY_DIR = own; + const first = loadOrCreateIdentity().identity; + const { identity: second } = rotateIdentity(); + const keys = localPublicKeys(); + // Current identity resolves... + assert.equal(keys.get(second.id), second.publicKey); + // ...and so does the rotated-away predecessor (archived .bak record). + assert.equal(keys.get(first.id), first.publicKey); + assert.equal(keys.size, 2); + } finally { + process.env.KIT_IDENTITY_DIR = dir; + rmSync(own, { recursive: true, force: true }); + } + }); + it("tryLoadIdentity returns null when no identity exists", () => { const empty = mkdtempSync(join(tmpdir(), "kit-identity-empty-")); try { diff --git a/src/identity.ts b/src/identity.ts index 40d609b7..858bb8c9 100644 --- a/src/identity.ts +++ b/src/identity.ts @@ -27,7 +27,14 @@ import { verify as edVerify, createHash, } from "node:crypto"; -import { readFileSync, writeFileSync, existsSync, mkdirSync, renameSync } from "node:fs"; +import { + readFileSync, + writeFileSync, + existsSync, + mkdirSync, + renameSync, + readdirSync, +} from "node:fs"; import { join } from "node:path"; import { homedir } from "node:os"; import { secureFile } from "./utils/secure-perms.js"; @@ -123,6 +130,37 @@ export function loadOrCreateIdentity( return { identity, created: true }; } +/** + * Build a kid → public-key (PEM) map from the locally-known identity records: + * the current identity plus any archived `identity.json.*.bak` records left by + * rotation (so entries signed by a previous, rotated key still verify). This is + * the Phase-0 local trust store; a shared/fleet trust store + revocation list + * layer on top later. Best-effort: unreadable/malformed records are skipped. + */ +export function localPublicKeys(dir?: string): Map { + const map = new Map(); + const base = identityDir(dir); + const add = (rec: Identity | null) => { + if (rec && typeof rec.id === "string" && typeof rec.publicKey === "string") { + map.set(rec.id, rec.publicKey); + } + }; + add(tryLoadIdentity(dir)); + try { + for (const name of readdirSync(base)) { + if (!name.startsWith(`${RECORD_FILE}.`) || !name.endsWith(".bak")) continue; + try { + add(JSON.parse(readFileSync(join(base, name), "utf-8")) as Identity); + } catch { + /* skip malformed archived record */ + } + } + } catch { + /* identity dir absent → just the current identity (if any) */ + } + return map; +} + /** Sign data with the identity's private key (Ed25519). Throws if no identity exists. */ export function signWithIdentity(data: Buffer | string, dir?: string): Buffer { const pem = readFileSync(keyPath(dir), "utf-8"); From 207de37b70569d61c2cbadd1dce3a0f3fcbc7e26 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 28 Jun 2026 12:50:03 +0000 Subject: [PATCH 3/5] feat(services): register Berget AI + Grunden.ai as known providers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add `berget` and `grunden` (EU-sovereign, OpenAI-compatible inference) to the service registry with their canonical key names and where to get them, so kit's secrets layer treats them as known, vault-resolved keys. Catalog-only by design: both are consumed through the `openai` SDK with a custom base URL, so there is no unique package/file signal to auto-detect on — keying on the `openai` dep would misattribute every OpenAI user. Generic kv-secret redaction already covers BERGET_API_KEY/GRUNDEN_API_KEY, so no new redaction pattern is needed. Agent-backend wiring (point an agent's OpenAI-compatible base URL at these providers) and a Berget Code gate adapter are deferred to future work. Tests: both entries expose their *_API_KEY and declare no auto-detection; a plain `openai`-SDK repo does not auto-detect either provider. Co-Authored-By: Claude Opus 4.8 (1M context) Claude-Session: https://claude.ai/code/session_015ERHw6bVUz39sAuoQZ1iyg --- CHANGELOG.md | 10 ++++++++++ src/service-registry.test.ts | 24 ++++++++++++++++++++++++ src/service-registry.ts | 25 +++++++++++++++++++++++++ 3 files changed, 59 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fb7f965a..40201c39 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ### Added +- **Berget AI + Grunden.ai as known providers.** Added `berget` and `grunden` + (EU-sovereign, OpenAI-compatible inference) to the service registry with their + canonical key names (`BERGET_API_KEY`/`BERGET_BASE_URL`, + `GRUNDEN_API_KEY`/`GRUNDEN_BASE_URL`) and where to get them, so `kit secrets` + treats them as known, vault-resolved keys (never plaintext). Catalog-only by + design: both are used via the `openai` SDK with a custom base URL, so there is + no unique package signal to auto-detect on (keying on the `openai` dep would + misattribute every OpenAI user). Agent-backend wiring + a Berget Code gate + adapter are deferred. + - **Identity-signed audit entries.** When a local `kit identity` exists, each appended `.kit-audit.jsonl` line is signed: kit attaches `kid` (signer id) + `sig` (Ed25519 signature over the line hash). Best-effort and append-safe — no diff --git a/src/service-registry.test.ts b/src/service-registry.test.ts index b6a8ec8e..a5df2c29 100644 --- a/src/service-registry.test.ts +++ b/src/service-registry.test.ts @@ -132,5 +132,29 @@ describe("service-registry", () => { assert.ok(SERVICE_BY_ID[id], `missing new service: ${id}`); } }); + + it("berget/grunden are catalog-only EU inference providers (keys, no auto-detect)", () => { + const berget = SERVICE_BY_ID["berget"]; + const grunden = SERVICE_BY_ID["grunden"]; + assert.ok(berget, "missing berget"); + assert.ok(grunden, "missing grunden"); + // Canonical key names are declared for the generator / secrets layer. + assert.ok(berget.secrets?.includes("BERGET_API_KEY")); + assert.ok(grunden.secrets?.includes("GRUNDEN_API_KEY")); + // OpenAI-compatible ⇒ no unique package/file signal, so no auto-detection + // (keying on the `openai` dep would misattribute every OpenAI user). + for (const def of [berget, grunden]) { + assert.equal(def.deps, undefined); + assert.equal(def.pyDeps, undefined); + assert.equal(def.files, undefined); + assert.equal(def.tool, undefined); + } + }); + + it("a plain OpenAI-SDK repo does NOT auto-detect berget/grunden", async () => { + const s = await detectServices({ deps: ["openai"], fileExists: noFiles }); + assert.ok(!s.includes("berget"), "openai dep must not imply berget"); + assert.ok(!s.includes("grunden"), "openai dep must not imply grunden"); + }); }); }); diff --git a/src/service-registry.ts b/src/service-registry.ts index 63c43824..4057274b 100644 --- a/src/service-registry.ts +++ b/src/service-registry.ts @@ -309,6 +309,31 @@ export const SERVICE_REGISTRY: ServiceDef[] = [ secrets: ["ATLASSIAN_API_TOKEN", "ATLASSIAN_SITE_URL"], tool: "acli", }, + + // ── EU-sovereign, OpenAI-compatible LLM inference providers. Deliberately NOT + // auto-detected: both are consumed through the standard `openai` SDK with a + // custom base URL, so there is no unique package/file signal (keying on the + // `openai` dep would misattribute every OpenAI user as Berget/Grunden). + // These are catalog entries — canonical key names + where to get them — so + // `kit secrets` knows the keys (vault-resolved, never plaintext) and a + // future agent-backend wiring can point an agent's base URL here. In + // practice a project's `.env.example` keys are what surface them today. + { + id: "berget", + // https://api.berget.ai/v1 — OpenAI-compatible, GPUs in Swedish datacentres. + login: + "# berget - OpenAI-compatible EU-sovereign inference (SE); get key at https://berget.ai, base URL https://api.berget.ai/v1", + check: "# berget - check BERGET_API_KEY is set", + secrets: ["BERGET_API_KEY", "BERGET_BASE_URL"], + }, + { + id: "grunden", + // GLM on own hardware in Sweden; OpenAI-compatible, SEK billing. + login: + "# grunden - OpenAI-compatible EU-sovereign inference (SE); get key at https://grunden.ai", + check: "# grunden - check GRUNDEN_API_KEY is set", + secrets: ["GRUNDEN_API_KEY", "GRUNDEN_BASE_URL"], + }, ]; /** Lookup by service id, for the generator. */ From 172101065d0a7d709b9829b67fba30add760bd03 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 29 Jun 2026 16:25:24 +0000 Subject: [PATCH 4/5] feat(memory): fold curated shared tier into search + session recovery Wire the committed .kit/shared/memory.jsonl tier into the recall paths (memory design gap #1): - `kit memory search` now also runs searchShared() and surfaces matching team decisions/conventions ABOVE raw transcript hits. `--json` returns `{ messages, shared }` (was a bare hits array). Project-local even under `--global` (shared memory travels with the repo). Fail-open. - SessionStart recovery re-injects the project's most recent durable shared decisions (kinds decision/convention/security/status; notes/how-built excluded) via new exported `recentDecisions(root, limit)`, so a resumed session regains the SETTLED context, not only the last few raw turns. Deterministic, zero-LLM, fail-open throughout (a missing/broken shared store never breaks recall). Tests cover durable-kind filtering, newest-first ordering, the limit, and the empty-store fail-open path. Co-Authored-By: Claude Opus 4.8 (1M context) Claude-Session: https://claude.ai/code/session_015ERHw6bVUz39sAuoQZ1iyg --- CHANGELOG.md | 10 ++++++- src/commands/memory.ts | 35 ++++++++++++++++++++++-- src/memory/hook.test.ts | 59 +++++++++++++++++++++++++++++++++++++++++ src/memory/hook.ts | 34 ++++++++++++++++++++++-- 4 files changed, 133 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 50da1e8f..d64e9dc4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ### Added +- **Shared (curated) memory folded into recall.** `kit memory search` now also + searches the committed `.kit/shared/memory.jsonl` tier and surfaces matching + team decisions/conventions _above_ raw transcript hits (`--json` now returns + `{ messages, shared }`). SessionStart recovery re-injects the project's most + recent durable shared decisions (kinds: decision/convention/security/status), + so a resumed session regains the settled context, not just the last few raw + turns. Both paths are project-local and fail-open (a missing/broken shared + store never breaks recall). - **Berget AI + Grunden.ai as known providers.** Added `berget` and `grunden` (EU-sovereign, OpenAI-compatible inference) to the service registry with their canonical key names (`BERGET_API_KEY`/`BERGET_BASE_URL`, @@ -54,7 +62,7 @@ experimental commands and adapters, no breaking changes to any `stable` surface. - **`kit ci --init gitlab|bitbucket`** — generate a pipeline snippet that runs `kit ci` (GitLab job → JUnit; Bitbucket step). Prints to stdout; `--write` writes the file only when absent. Plus `docs/CI_AND_GIT_HOSTS.md` (the 4-layer gate model - + per-host enforcement guidance). + - per-host enforcement guidance). - **`kit gha-audit` extended to GitLab CI + Bitbucket Pipelines** — lints `.gitlab-ci.yml` / `bitbucket-pipelines.yml` for unpinned `:latest`/untagged images (CWE-1104), remote `include:` (OWASP-A08), and pipe-to-shell (CWE-494). diff --git a/src/commands/memory.ts b/src/commands/memory.ts index bfa935a7..9760803c 100644 --- a/src/commands/memory.ts +++ b/src/commands/memory.ts @@ -25,8 +25,10 @@ import { shareEntry, listAreas, queryArea, + searchShared, getSharedPath, type SharedKind, + type SharedEntry, } from "../memory/shared.js"; import { userPromptSubmitReminder, @@ -210,7 +212,9 @@ async function memHelp(): Promise { console.log( " kit memory index Index all agent transcripts (Claude Code, Codex, Gemini, Cursor, …) into the store", ); - console.log(" kit memory search Search memory (current project; --global for all)"); + console.log( + " kit memory search Search memory + curated shared decisions (current project; --global for all)", + ); console.log(" kit memory stats Show what the memory store contains"); console.log(" kit memory merge Merge another machine's memory.db into this one"); console.log( @@ -442,12 +446,39 @@ async function memSearch(): Promise { // logging is non-critical } db.close(); + + // Curated shared tier (.kit/shared/memory.jsonl) — high-signal, team-reviewed + // decisions/conventions that travel with the repo. Always project-local (so + // `--global`, which widens the raw-recall scope across projects, still reads + // THIS repo's shared store). Fail-open: a missing/broken file never breaks search. + const sharedRoot = flagValue(process.argv, "--project") ?? getCurrentProjectRoot(); + let shared: SharedEntry[] = []; + try { + shared = searchShared(sharedRoot, query); + } catch { + // shared tier is best-effort context, never gates raw recall + } + if (jsonMode) { - console.log(JSON.stringify(hits)); + console.log(JSON.stringify({ messages: hits, shared })); return true; } + + // Curated decisions first — they're the durable context, not a raw transcript line. + if (shared.length) { + console.log( + `${c.bold}${shared.length}${c.reset} curated (shared) match(es) ${c.dim}— team decisions${c.reset}`, + ); + for (const e of shared) { + const prov = `${e.area} · ${e.author}${e.source_ref ? ` @${e.source_ref}` : ""}`; + console.log(` ${c.bold}[${e.kind}]${c.reset} ${e.title} ${c.dim}— ${prov}${c.reset}`); + if (e.body) console.log(` ${c.dim}${e.body.replace(/\s+/g, " ").slice(0, 160)}${c.reset}`); + } + } + const scope = projectPath ? `${c.dim}in ${projectPath}${c.reset}` : `${c.dim}(global)${c.reset}`; if (!hits.length) { + if (shared.length) return true; // curated results already shown; raw recall empty console.log(`${c.dim}no matches for "${query}" ${projectPath ?? "(global)"}${c.reset}`); return true; } diff --git a/src/memory/hook.test.ts b/src/memory/hook.test.ts index b48ad9b6..5c3abb3a 100644 --- a/src/memory/hook.test.ts +++ b/src/memory/hook.test.ts @@ -7,10 +7,12 @@ import { openMemoryDb, upsertSession, insertMessage } from "./db.js"; import { userPromptSubmitReminder, sessionStartRecovery, + recentDecisions, dueForHarnessSweep, dueForMidSessionIndex, } from "./hook.js"; import { getCurrentProjectRoot } from "./project.js"; +import { shareEntry } from "./shared.js"; describe("memory hook — UserPromptSubmit reminder", () => { let tmp: string; @@ -93,6 +95,63 @@ describe("memory hook — SessionStart recovery", () => { }); }); +describe("memory hook — recentDecisions (shared curated tier)", () => { + let root: string; + + before(() => { + root = mkdtempSync(join(tmpdir(), "kit-shared-")); + // Durable kinds (newest last so we can assert newest-first ordering) + shareEntry( + root, + { area: "auth", kind: "decision", title: "use Ed25519", body: "" }, + "2026-01-01T00:00:00Z", + ); + shareEntry( + root, + { area: "ci", kind: "convention", title: "pin actions by sha", body: "" }, + "2026-02-01T00:00:00Z", + ); + // Lower-signal kinds that must be excluded + shareEntry( + root, + { area: "misc", kind: "note", title: "a passing note", body: "" }, + "2026-03-01T00:00:00Z", + ); + shareEntry( + root, + { area: "misc", kind: "how-built", title: "wired the gate", body: "" }, + "2026-03-02T00:00:00Z", + ); + }); + + after(() => rmSync(root, { recursive: true, force: true })); + + it("returns only durable kinds, newest-first, capped at the limit", () => { + const d = recentDecisions(root, 3); + const kinds = d.map((e) => e.kind); + assert.ok(!kinds.includes("note"), "notes excluded"); + assert.ok(!kinds.includes("how-built"), "how-built excluded"); + assert.deepEqual( + d.map((e) => e.title), + ["pin actions by sha", "use Ed25519"], + "newest durable first", + ); + }); + + it("respects the limit", () => { + assert.equal(recentDecisions(root, 1).length, 1); + }); + + it("fail-open on a project with no shared store", () => { + const empty = mkdtempSync(join(tmpdir(), "kit-noshared-")); + try { + assert.deepEqual(recentDecisions(empty, 3), []); + } finally { + rmSync(empty, { recursive: true, force: true }); + } + }); +}); + describe("memory hook — harness sweep debounce", () => { let tmp: string; const prevDir = process.env.KIT_MEMORY_DIR; diff --git a/src/memory/hook.ts b/src/memory/hook.ts index 760c55b9..031d7dda 100644 --- a/src/memory/hook.ts +++ b/src/memory/hook.ts @@ -14,6 +14,7 @@ import { spawn } from "node:child_process"; import { openMemoryDb, getStats, recentMessages, getMemoryDir, ensureMemoryDir } from "./db.js"; import { indexClaudeTranscripts, indexAllHarnesses } from "./parser.js"; import { palList } from "./pal.js"; +import { readShared, type SharedEntry } from "./shared.js"; import { getCurrentProjectRoot } from "./project.js"; import { readCachedUpdateSync, getKitVersionSync } from "../update-check.js"; @@ -60,6 +61,24 @@ export function userPromptSubmitReminder(): string { } } +/** + * The most recent durable shared decisions for a project, newest first. "Durable" + * = the curated kinds worth re-surfacing on resume (decision / convention / + * security / status); notes/how-built are excluded as lower-signal. Fail-open: + * readShared returns [] on a missing/broken store. Deterministic, no model. + */ +export function recentDecisions(root: string, limit: number): SharedEntry[] { + const DURABLE = new Set(["decision", "convention", "security", "status"]); + try { + return readShared(root) + .filter((e) => DURABLE.has(e.kind)) + .sort((a, b) => (a.ts < b.ts ? 1 : a.ts > b.ts ? -1 : 0)) + .slice(0, limit); + } catch { + return []; + } +} + /** * SessionStart recovery — re-inject "where you left off" for THIS project after a * resume/compact, so the agent regains continuity instead of starting blank. Pulls @@ -73,8 +92,13 @@ export function sessionStartRecovery(opts: { limit?: number } = {}): string { const recent = recentMessages(db, { projectPath: root, limit: opts.limit ?? 6 }); const openItems = palList(db, { scope: basename(root) }); db.close(); + // Curated shared tier — re-inject the team's durable decisions on resume so + // the agent regains the SETTLED context, not just the last few raw turns. + // Fail-open (readShared swallows a missing/broken file → []). + const decisions = recentDecisions(root, 3); const stale = staleKitNotice(); - if (recent.length === 0 && openItems.length === 0 && !stale) return ""; + if (recent.length === 0 && openItems.length === 0 && decisions.length === 0 && !stale) + return ""; const lines: string[] = []; if (stale) lines.push(stale); @@ -86,6 +110,12 @@ export function sessionStartRecovery(opts: { limit?: number } = {}): string { const text = (m.content ?? "").replace(/\s+/g, " ").trim().slice(0, 200); if (text) lines.push(` · ${who}: ${text}`); } + if (decisions.length > 0) { + lines.push("Curated team decisions (shared memory):"); + for (const d of decisions) { + lines.push(` · [${d.kind}] ${d.area}: ${d.title}`); + } + } if (openItems.length > 0) { const titles = openItems .slice(0, 3) @@ -93,7 +123,7 @@ export function sessionStartRecovery(opts: { limit?: number } = {}): string { .join("; "); lines.push(`Open action items blocked on you: ${titles}${openItems.length > 3 ? " …" : ""}.`); } - if (recent.length > 0 || openItems.length > 0) { + if (recent.length > 0 || openItems.length > 0 || decisions.length > 0) { lines.push("Run `kit memory search ` to pull more of what was actually said."); } return lines.join("\n"); From 5a4235eb3b593ff1d8462618986e0d07a66cee90 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 29 Jun 2026 16:40:21 +0000 Subject: [PATCH 5/5] =?UTF-8?q?feat(memory):=20living=20shared=20decisions?= =?UTF-8?q?=20=E2=80=94=20status=20/=20supersedes=20/=20reverses?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Decision lifecycle for the curated shared tier (memory design gap #2). Append-only: a change is a NEW entry that supersedes/reverses an old id; `active` stays implicit (absent field) so pre-lifecycle entries are byte-identical and diffs stay clean. - shared.ts: SharedEntry/ShareInput gain status/supersedes/reverses; shareEntry persists them only when non-default. New pure helpers effectiveStatus (explicit status wins, else referenced-by-later ⇒ superseded/reversed; reverses outranks), activeShared, formatAge. - commands/memory.ts: `kit memory share --supersedes/--reverses/--status` (validates the referenced id exists); `kit memory area`/`search` badge superseded/reversed entries + show the chain and age; area --json carries the effective status. - hook.ts: SessionStart recovery surfaces only ACTIVE durable decisions (recentDecisions → activeShared) with age, so a resume sees the decision HEAD, not a graveyard. Surfacing shows facts (status, age, supersedes-chain); the relevance call stays human (zero-LLM, deterministic). Tests cover supersede/reverse resolution, reverses>supersedes precedence, explicit-status, the active filter, age bucketing, and recovery exclusion of superseded decisions. Co-Authored-By: Claude Opus 4.8 (1M context) Claude-Session: https://claude.ai/code/session_015ERHw6bVUz39sAuoQZ1iyg --- CHANGELOG.md | 9 +++++ src/commands/memory.ts | 71 +++++++++++++++++++++++++++++------ src/memory/hook.test.ts | 20 ++++++++++ src/memory/hook.ts | 19 ++++++---- src/memory/shared.test.ts | 79 ++++++++++++++++++++++++++++++++++++++- src/memory/shared.ts | 60 +++++++++++++++++++++++++++++ 6 files changed, 238 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d64e9dc4..174a3cbe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ### Added +- **Living shared decisions — lifecycle (status / supersedes / reverses).** + Shared memory entries are now versioned: a change is a NEW append-only entry + that `--supersedes ` or `--reverses ` an old one (or carries an explicit + `--status`). `kit memory share` validates the referenced id exists. Surfacing + shows only ACTIVE decisions with their age (e.g. `2y ago`) so an aging decision + is flagged for review, never blind obedience; `kit memory area`/`search` badge + superseded/reversed entries (and show the chain) so "this was tried + reversed" + still surfaces. `active` stays implicit (absent field) so pre-lifecycle entries + are byte-identical. New `effectiveStatus`, `activeShared`, `formatAge`. - **Shared (curated) memory folded into recall.** `kit memory search` now also searches the committed `.kit/shared/memory.jsonl` tier and surfaces matching team decisions/conventions _above_ raw transcript hits (`--json` now returns diff --git a/src/commands/memory.ts b/src/commands/memory.ts index 9760803c..497ab21a 100644 --- a/src/commands/memory.ts +++ b/src/commands/memory.ts @@ -24,10 +24,13 @@ import { syncFromExport } from "../memory/sync.js"; import { shareEntry, listAreas, - queryArea, searchShared, + readShared, + effectiveStatus, + formatAge, getSharedPath, type SharedKind, + type SharedStatus, type SharedEntry, } from "../memory/shared.js"; import { @@ -464,14 +467,23 @@ async function memSearch(): Promise { return true; } - // Curated decisions first — they're the durable context, not a raw transcript line. + // Curated decisions first — they're the durable context, not a raw transcript + // line. Superseded/reversed matches are still shown (so "this was tried + undone" + // surfaces) but badged, with age — relevance stays the reader's call. if (shared.length) { + const allShared = readShared(sharedRoot); console.log( `${c.bold}${shared.length}${c.reset} curated (shared) match(es) ${c.dim}— team decisions${c.reset}`, ); for (const e of shared) { - const prov = `${e.area} · ${e.author}${e.source_ref ? ` @${e.source_ref}` : ""}`; - console.log(` ${c.bold}[${e.kind}]${c.reset} ${e.title} ${c.dim}— ${prov}${c.reset}`); + const st = effectiveStatus(e, allShared); + const badge = + st === "active" ? "" : ` ${st === "reversed" ? c.red : c.yellow}[${st}]${c.reset}`; + const age = formatAge(e.ts); + const prov = `${e.area} · ${e.author}${e.source_ref ? ` @${e.source_ref}` : ""}${age ? ` · ${age}` : ""}`; + console.log( + ` ${c.bold}[${e.kind}]${c.reset} ${e.title}${badge} ${c.dim}— ${prov}${c.reset}`, + ); if (e.body) console.log(` ${c.dim}${e.body.replace(/\s+/g, " ").slice(0, 160)}${c.reset}`); } } @@ -558,21 +570,43 @@ async function memShare(): Promise { const kind = (flagValue(process.argv, "--kind") ?? "note") as SharedKind; const body = flagValue(process.argv, "--body") ?? ""; const ref = flagValue(process.argv, "--ref"); + // Lifecycle: a change is a NEW entry that supersedes/reverses an old id (append-only). + const supersedes = flagValue(process.argv, "--supersedes"); + const reverses = flagValue(process.argv, "--reverses"); + const status = flagValue(process.argv, "--status") as SharedStatus | undefined; if (!area || !title) { console.error( - `${c.red}usage: kit memory share --area --title [--kind decision|convention|how-built|status|security|note] [--body ] [--ref ]${c.reset}`, + `${c.red}usage: kit memory share --area --title [--kind decision|convention|how-built|status|security|note] [--body ] [--ref ] [--supersedes ] [--reverses ]${c.reset}`, ); return false; } const root = getCurrentProjectRoot(); + // Validate any referenced id exists, so a typo'd --supersedes/--reverses can't + // silently leave the old decision active (it would never be marked superseded). + if (supersedes || reverses) { + const ids = new Set(readShared(root).map((e) => e.id)); + for (const [flag, id] of [ + ["--supersedes", supersedes], + ["--reverses", reverses], + ] as const) { + if (id && !ids.has(id)) { + console.error(`${c.red}${flag} ${id}: no shared entry with that id${c.reset}`); + return false; + } + } + } try { const e = shareEntry( root, - { area, kind, title, body, refs: ref ? [ref] : [] }, + { area, kind, title, body, refs: ref ? [ref] : [], status, supersedes, reverses }, new Date().toISOString(), ); + const rel = + e.reverses || e.supersedes + ? ` ${c.dim}(${e.reverses ? "reverses" : "supersedes"} ${e.reverses ?? e.supersedes})${c.reset}` + : ""; console.log( - `${c.green}✓${c.reset} shared ${c.bold}${e.id}${c.reset} to area ${c.bold}${area}${c.reset} ${c.dim}(${getSharedPath(root)})${c.reset}`, + `${c.green}✓${c.reset} shared ${c.bold}${e.id}${c.reset} to area ${c.bold}${area}${c.reset}${rel} ${c.dim}(${getSharedPath(root)})${c.reset}`, ); console.log( `${c.dim}commit .kit/shared/memory.jsonl + open a PR — shared memory is reviewed like code${c.reset}`, @@ -611,9 +645,12 @@ async function memArea(): Promise { console.error(`${c.red}usage: kit memory area ${c.reset}`); return false; } - const entries = queryArea(getCurrentProjectRoot(), name); + const root = getCurrentProjectRoot(); + const all = readShared(root); + const entries = all.filter((e) => e.area === name); if (jsonMode) { - console.log(JSON.stringify(entries)); + // Enrich with the EFFECTIVE lifecycle status (computed against the full set). + console.log(JSON.stringify(entries.map((e) => ({ ...e, status: effectiveStatus(e, all) })))); return true; } if (!entries.length) { @@ -624,8 +661,20 @@ async function memArea(): Promise { `${c.bold}${name}${c.reset} ${c.dim}· ${entries.length} entr${entries.length === 1 ? "y" : "ies"}${c.reset}`, ); for (const e of entries) { - const prov = `${e.author}${e.source_ref ? ` @${e.source_ref}` : ""}`; - console.log(` ${c.bold}[${e.kind}]${c.reset} ${e.title} ${c.dim}— ${prov}${c.reset}`); + const st = effectiveStatus(e, all); + // Active entries read clean; superseded/reversed are badged + dimmed (history, not HEAD). + const badge = + st === "active" ? "" : ` ${st === "reversed" ? c.red : c.yellow}[${st}]${c.reset}`; + const rel = e.reverses + ? ` ${c.dim}↩ ${e.reverses}${c.reset}` + : e.supersedes + ? ` ${c.dim}→ ${e.supersedes}${c.reset}` + : ""; + const age = formatAge(e.ts); + const prov = `${e.author}${e.source_ref ? ` @${e.source_ref}` : ""}${age ? ` · ${age}` : ""}`; + console.log( + ` ${c.bold}[${e.kind}]${c.reset} ${e.title}${badge}${rel} ${c.dim}— ${prov}${c.reset}`, + ); if (e.body) console.log(` ${e.body}`); if (e.refs.length) console.log(` ${c.dim}refs: ${e.refs.join(", ")}${c.reset}`); } diff --git a/src/memory/hook.test.ts b/src/memory/hook.test.ts index 5c3abb3a..028b463a 100644 --- a/src/memory/hook.test.ts +++ b/src/memory/hook.test.ts @@ -142,6 +142,26 @@ describe("memory hook — recentDecisions (shared curated tier)", () => { assert.equal(recentDecisions(root, 1).length, 1); }); + it("excludes superseded decisions (shows the HEAD, not the graveyard)", () => { + const r = mkdtempSync(join(tmpdir(), "kit-super-")); + try { + const old = shareEntry( + r, + { area: "auth", kind: "decision", title: "use RSA", body: "" }, + "2026-01-01T00:00:00Z", + ); + shareEntry( + r, + { area: "auth", kind: "decision", title: "use Ed25519", body: "", supersedes: old.id }, + "2026-02-01T00:00:00Z", + ); + const titles = recentDecisions(r, 5).map((e) => e.title); + assert.deepEqual(titles, ["use Ed25519"], "superseded RSA decision is not surfaced"); + } finally { + rmSync(r, { recursive: true, force: true }); + } + }); + it("fail-open on a project with no shared store", () => { const empty = mkdtempSync(join(tmpdir(), "kit-noshared-")); try { diff --git a/src/memory/hook.ts b/src/memory/hook.ts index 031d7dda..96badf1c 100644 --- a/src/memory/hook.ts +++ b/src/memory/hook.ts @@ -14,7 +14,7 @@ import { spawn } from "node:child_process"; import { openMemoryDb, getStats, recentMessages, getMemoryDir, ensureMemoryDir } from "./db.js"; import { indexClaudeTranscripts, indexAllHarnesses } from "./parser.js"; import { palList } from "./pal.js"; -import { readShared, type SharedEntry } from "./shared.js"; +import { activeShared, formatAge, type SharedEntry } from "./shared.js"; import { getCurrentProjectRoot } from "./project.js"; import { readCachedUpdateSync, getKitVersionSync } from "../update-check.js"; @@ -62,15 +62,17 @@ export function userPromptSubmitReminder(): string { } /** - * The most recent durable shared decisions for a project, newest first. "Durable" - * = the curated kinds worth re-surfacing on resume (decision / convention / - * security / status); notes/how-built are excluded as lower-signal. Fail-open: - * readShared returns [] on a missing/broken store. Deterministic, no model. + * The most recent ACTIVE durable shared decisions for a project, newest first. + * "Durable" = the curated kinds worth re-surfacing on resume (decision / + * convention / security / status); notes/how-built are excluded as lower-signal. + * Superseded/reversed entries are filtered out (activeShared) — a resumed session + * sees the current HEAD of the decision tree, not a graveyard. Fail-open: + * activeShared returns [] on a missing/broken store. Deterministic, no model. */ export function recentDecisions(root: string, limit: number): SharedEntry[] { const DURABLE = new Set(["decision", "convention", "security", "status"]); try { - return readShared(root) + return activeShared(root) .filter((e) => DURABLE.has(e.kind)) .sort((a, b) => (a.ts < b.ts ? 1 : a.ts > b.ts ? -1 : 0)) .slice(0, limit); @@ -111,9 +113,10 @@ export function sessionStartRecovery(opts: { limit?: number } = {}): string { if (text) lines.push(` · ${who}: ${text}`); } if (decisions.length > 0) { - lines.push("Curated team decisions (shared memory):"); + lines.push("Curated team decisions (shared memory, active):"); for (const d of decisions) { - lines.push(` · [${d.kind}] ${d.area}: ${d.title}`); + const age = formatAge(d.ts); + lines.push(` · [${d.kind}] ${d.area}: ${d.title}${age ? ` (${age})` : ""}`); } } if (openItems.length > 0) { diff --git a/src/memory/shared.test.ts b/src/memory/shared.test.ts index 9a1d9412..d7d1a458 100644 --- a/src/memory/shared.test.ts +++ b/src/memory/shared.test.ts @@ -3,7 +3,16 @@ import assert from "node:assert/strict"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { shareEntry, readShared, listAreas, queryArea, searchShared } from "./shared.js"; +import { + shareEntry, + readShared, + listAreas, + queryArea, + searchShared, + effectiveStatus, + activeShared, + formatAge, +} from "./shared.js"; const ALLOWED = new Set([ "id", @@ -15,6 +24,9 @@ const ALLOWED = new Set([ "author", "ts", "source_ref", + "status", + "supersedes", + "reverses", ]); describe("shared project memory (Track D)", () => { @@ -86,3 +98,68 @@ describe("shared project memory (Track D)", () => { rmSync(r, { recursive: true, force: true }); }); }); + +describe("shared memory — decision lifecycle (gap #2)", () => { + const root = () => mkdtempSync(join(tmpdir(), "kit-life-")); + + it("a plain entry omits status (byte-identical to pre-lifecycle) and is active", () => { + const r = root(); + const e = shareEntry(r, { area: "a", kind: "decision", title: "x", body: "" }, "t1"); + assert.equal(Object.prototype.hasOwnProperty.call(e, "status"), false, "no status field"); + assert.equal(effectiveStatus(e, [e]), "active"); + rmSync(r, { recursive: true, force: true }); + }); + + it("supersedes marks the old entry superseded; reverses marks it reversed", () => { + const r = root(); + const old = shareEntry( + r, + { area: "auth", kind: "decision", title: "use RSA", body: "" }, + "2026-01-01T00:00:00Z", + ); + shareEntry( + r, + { area: "auth", kind: "decision", title: "use Ed25519", body: "", supersedes: old.id }, + "2026-02-01T00:00:00Z", + ); + const all = readShared(r); + const oldRead = all.find((e) => e.id === old.id)!; + assert.equal(effectiveStatus(oldRead, all), "superseded"); + // activeShared keeps only the successor. + const active = activeShared(r); + assert.deepEqual( + active.map((e) => e.title), + ["use Ed25519"], + ); + rmSync(r, { recursive: true, force: true }); + }); + + it("reverses outranks supersedes and an explicit status wins", () => { + const r = root(); + const a = shareEntry(r, { area: "x", kind: "decision", title: "A", body: "" }, "t1"); + shareEntry( + r, + { area: "x", kind: "decision", title: "B", body: "", reverses: a.id, supersedes: a.id }, + "t2", + ); + const all = readShared(r); + assert.equal(effectiveStatus(all.find((e) => e.id === a.id)!, all), "reversed"); + // explicit status on an unreferenced entry wins + const c = shareEntry( + r, + { area: "x", kind: "decision", title: "C", body: "", status: "superseded" }, + "t3", + ); + assert.equal(effectiveStatus(c, readShared(r)), "superseded"); + rmSync(r, { recursive: true, force: true }); + }); + + it("formatAge buckets into today / days / months / years", () => { + const now = new Date("2026-06-29T00:00:00Z"); + assert.equal(formatAge("2026-06-29T00:00:00Z", now), "today"); + assert.equal(formatAge("2026-06-24T00:00:00Z", now), "5d ago"); + assert.equal(formatAge("2026-03-01T00:00:00Z", now), "4mo ago"); // 120d / 30 + assert.equal(formatAge("2024-01-01T00:00:00Z", now), "2y ago"); + assert.equal(formatAge("not-a-date", now), ""); + }); +}); diff --git a/src/memory/shared.ts b/src/memory/shared.ts index a11153e1..69314853 100644 --- a/src/memory/shared.ts +++ b/src/memory/shared.ts @@ -22,6 +22,13 @@ import { findSecrets } from "../utils/redactSecrets.js"; export type SharedKind = "decision" | "convention" | "how-built" | "status" | "security" | "note"; +/** + * Lifecycle of a decision. Append-only: we never edit an old entry, a change is a + * NEW entry that `supersedes`/`reverses` the old id. "active" is the default and + * is left IMPLICIT (absent field) so existing/committed entries stay byte-identical. + */ +export type SharedStatus = "active" | "superseded" | "reversed"; + export interface SharedEntry { id: string; area: string; @@ -32,6 +39,12 @@ export interface SharedEntry { author: string; ts: string; source_ref?: string; + /** Explicit lifecycle marker; absent ⇒ active (unless a later entry supersedes/reverses it). */ + status?: SharedStatus; + /** Id of the entry this one replaces (its successor). */ + supersedes?: string; + /** Id of the entry this one reverses (tried + undone — re-introducing it should warn). */ + reverses?: string; } export interface ShareInput { @@ -40,6 +53,9 @@ export interface ShareInput { title: string; body: string; refs?: string[]; + status?: SharedStatus; + supersedes?: string; + reverses?: string; } export function getSharedPath(root: string): string { @@ -120,6 +136,11 @@ export function shareEntry(root: string, input: ShareInput, now: string): Shared ts: now, source_ref: gitHead(root), }; + // Lifecycle fields are written only when meaningful, so a plain `active` entry + // stays byte-identical to pre-lifecycle entries (clean diffs, backward-compat). + if (input.status && input.status !== "active") entry.status = input.status; + if (input.supersedes) entry.supersedes = input.supersedes; + if (input.reverses) entry.reverses = input.reverses; const path = getSharedPath(root); mkdirSync(dirname(path), { recursive: true }); appendFileSync(path, JSON.stringify(entry) + "\n"); @@ -144,3 +165,42 @@ export function searchShared(root: string, query: string): SharedEntry[] { (e) => e.title.toLowerCase().includes(q) || e.body.toLowerCase().includes(q), ); } + +/** + * Effective lifecycle status of an entry given the full set. An explicit + * `status` field wins; otherwise an entry is `superseded`/`reversed` if a LATER + * entry points at it (deny-by-default toward "active": only an unreferenced, + * unmarked entry is active). `reverses` outranks `supersedes` if both reference it. + * Pure — the surfacing layer decides what to show; kit never auto-decides relevance. + */ +export function effectiveStatus(entry: SharedEntry, all: SharedEntry[]): SharedStatus { + if (entry.status === "superseded" || entry.status === "reversed") return entry.status; + let result: SharedStatus = "active"; + for (const e of all) { + if (e.id === entry.id) continue; + if (e.reverses === entry.id) return "reversed"; + if (e.supersedes === entry.id) result = "superseded"; + } + return result; +} + +/** The currently-active shared entries (effectiveStatus === "active"). */ +export function activeShared(root: string): SharedEntry[] { + const all = readShared(root); + return all.filter((e) => effectiveStatus(e, all) === "active"); +} + +/** + * Coarse human age of a timestamp ("today" / "5d ago" / "3mo ago" / "2y ago"), + * or "" if unparseable. Display-only — surfacing shows age so an old decision is + * flagged for REVIEW, never blind obedience (the relevance call stays human). + */ +export function formatAge(ts: string, now: Date = new Date()): string { + const then = new Date(ts).getTime(); + if (!Number.isFinite(then)) return ""; + const days = Math.floor((now.getTime() - then) / 86_400_000); + if (days <= 0) return "today"; + if (days < 30) return `${days}d ago`; + if (days < 365) return `${Math.floor(days / 30)}mo ago`; + return `${Math.floor(days / 365)}y ago`; +}