Initial Commit

This commit is contained in:
2026-05-27 23:29:53 +01:00
commit fbc70f96e6
10000 changed files with 1102152 additions and 0 deletions

View File

@@ -0,0 +1,99 @@
# Diff — `stringify(patch)` human-readable patch formatter
**Package**: `@suaveplan/diff`
**Status**: PROPOSED
**Type**: feature
## Why
`@suaveplan/diff` produces RFC 6902 JSON Patch arrays from `diff`, applies them via `applyPatch`, and reverts them via `revertPatch`. What it does not provide is a human-readable rendering of a patch for logs, debug output, or audit trails. The legacy package shipped a `stringify(value)` helper at `packages/universal/diff/src/utils/utils.ts:238-240` that wrapped `JSON.stringify` — useful for one-off value rendering, but indistinguishable from the platform helper. The 2026-05-02 audit found two genesis dependents (`@suaveplan/event-sourcing`, `@suaveplan/crdt`, `@suaveplan/undo`) re-implementing patch-formatting helpers inline (e.g. `patch.map(op => \`${op.op} ${op.path}\`).join('\n')`) because they need readable patch output for debugging.
Genesis has the opportunity to ship a *richer* `stringify(patch)` than legacy did — one that takes a `JsonPatch` (not just a single value) and produces a multi-line `OP path -> value` rendering, rather than re-wrapping `JSON.stringify`. This is what consumers actually want: a single helper they can drop into a logger and get readable output for an entire patch, with stable formatting that's safe to compare in tests. The legacy one-liner wrapper does not pin a stable format, gets mixed up with the platform `JSON.stringify` at call sites, and leaves the patch-formatting use case unsolved.
## What changes
### `@suaveplan/diff`
- ADDED: `src/utils/stringify-patch/stringify-patch.ts` — `stringifyPatch(patch: JsonPatch, options?: StringifyPatchOptions): string` returns a multi-line string with one operation per line in the format `OP PATH [-> VALUE] [(from FROM)]`. Operations:
- `add /path -> value`
- `remove /path`
- `replace /path -> value`
- `move /from -> /path`
- `copy /from -> /path`
- `test /path -> value`
- ADDED: `StringifyPatchOptions` interface — `{ valueFormatter?: (value: unknown) => string; indent?: string; uppercaseOps?: boolean }`. `valueFormatter` defaults to `JSON.stringify(value)`; `indent` defaults to empty string; `uppercaseOps` defaults to `false` (RFC-6902 op names are lowercase).
- ADDED: subpath export `./utils/stringify-patch` in `package.json::exports`.
- ADDED: error code `DIFF.INVALID_PATCH_OP` — thrown when an unknown patch operation is encountered (defensive; upstream RFC 6902 ops are pinned to a closed set, but the runtime guard still emits a structured error).
- ADDED: OTel span event `diff.stringify-patch` annotated with `opCount: number`.
- MODIFIED: `src/index.ts` re-exports `stringifyPatch` from the root barrel.
## Out of scope
- **Replacing the existing `stringify(value)` helper.** Genesis does not currently export `stringify` from `utils/`. The new `stringifyPatch` is a *patch* formatter — distinct name, distinct surface. We deliberately do not also ship a `stringify(value)` wrapper around `JSON.stringify` because the platform helper already exists and the legacy export added no value.
- **Color / ANSI output.** The CLI-coloured rendering belongs in `@suaveplan/cli`. Callers wanting ANSI compose `stringifyPatch` with `cli`'s colour helpers; they do not get colour from this package.
- **Diff-style rendering (`+ a`, `- b`, `c`).** That's a different format (reconstruction of the source / target docs) and a different use case (visual diff). `stringifyPatch` formats the patch operations themselves, not the documents.
- **Patch parsing (`parsePatch(text)`).** Going from text back to a `JsonPatch` array would re-create what `JSON.parse(text) as JsonPatch` already does. Adding a parsing helper here is busywork.
- **Sorting / compaction.** The patch is rendered as-given. `stringifyPatch` is not a normaliser.
## Parity Checklist
| Capability | Upstream | Migrated | Notes |
|---|---|---|---|
| `stringify(value): string` (JSON.stringify wrapper) | ✅ | 🚫 | Replaced: the legacy helper added nothing over the platform `JSON.stringify`. Callers wanting one use the platform helper. The new `stringifyPatch` covers the actual unmet use case. |
| `stringifyPatch(patch, options?): string` (multi-line patch render) | 🚫 (not in upstream) | ⬆️ | Added: the gap that motivated this change. |
| OTel observability for stringify | 🚫 (not in upstream) | ⬆️ | Genesis-wide rule. |
| Structured error code for unknown op | 🚫 (not in upstream) | ⬆️ | Genesis-wide error-routing rule. |
## Source mapping
This change derives from `../suaveplan/packages/universal/diff/src/utils/utils.ts`. The legacy implementation (L238-L240) is:
```ts
export function stringify(value: unknown): string {
return JSON.stringify(value);
}
```
Genesis does not port this verbatim. Source mapping captures the *intent* (a patch-rendering helper) which legacy under-delivered, then maps the new requirements to RFC 6902 itself for the per-operation grammar.
| Requirement | Source file | Source lines | Notes |
|---|---|---|---|
| Concept of a single `stringify` helper exported from `utils/` | `packages/universal/diff/src/utils/utils.ts` | L237-L240 | Inspirational only; legacy was `JSON.stringify` wrapper. Genesis ships a dedicated `stringifyPatch` instead. |
| `add` / `remove` / `replace` / `move` / `copy` / `test` operation grammar | RFC 6902 §4.1-§4.6 | n/a | Spec-driven. Each operation's path / value / from fields are defined by the RFC. |
| `JsonPatch` type used as input | `packages/data/diff/src/operations/operations.ts` (genesis) | (existing) | The new helper consumes the same `JsonPatch` type the rest of genesis-`diff` already uses. |
### Requirements with no source line
| Requirement | Justification |
|---|---|
| Multi-line `OP PATH [-> VALUE] [(from FROM)]` rendering | The 2026-05-02 audit found three downstream packages (`event-sourcing`, `crdt`, `undo`) inlining their own variants. Standardising the format here removes drift. |
| `StringifyPatchOptions.valueFormatter` injection point | Allows callers to swap `JSON.stringify` for a redacting / size-capping / pretty-printing variant (audit logging, log aggregation pipelines). |
| `StringifyPatchOptions.uppercaseOps` flag | Some logging conventions render operation names in uppercase. Cheap config to support; default matches RFC 6902 (lowercase). |
| `StringifyPatchOptions.indent` prefix | Allows callers to nest the rendered patch inside a larger log message without doing the indent themselves. |
| Error code `DIFF.INVALID_PATCH_OP` | Defensive guard — RFC 6902 ops are a closed set, but a malformed in-memory `JsonPatch` could carry an unknown `op`. Genesis routes the error through `DiffError` with a stable code; legacy threw nothing (was unreachable in legacy because legacy didn't render ops). |
| OTel span event `diff.stringify-patch` with `opCount` attribute | Genesis-wide observability rule. |
## Verification approach
- `src/utils/stringify-patch/stringify-patch.test.ts` — every operation type renders correctly; multi-op patches join with `\n`; empty patch returns empty string; long values use the default `JSON.stringify` formatter.
- `src/utils/stringify-patch/stringify-patch.spec-conformance.test.ts` — `valueFormatter` injection point invoked once per value-bearing op; `uppercaseOps` flag changes case; `indent` prefix prepended per line; `DIFF.INVALID_PATCH_OP` thrown on unknown op; OTel span event emitted with correct `opCount`; subpath export resolves.
## Impact
### Affected dependents
Run `bunx turbo ls --filter=...@suaveplan/diff` to enumerate. Three packages depend on `@suaveplan/diff` today.
- `@suaveplan/undo` — [ ] tests run / [ ] docs reviewed / [x] no action needed (uses `applyPatch` / `revertPatch`; new `stringifyPatch` is additive)
- `@suaveplan/event-sourcing` — [x] tests run / [x] docs reviewed / [ ] no action needed (good candidate; doc recommends migrating from inline patch-format helper to `stringifyPatch`)
- `@suaveplan/crdt` — [x] tests run / [x] docs reviewed / [ ] no action needed (good candidate; same recommendation)
`@suaveplan/diff` is not on the foundation-package list, but it is depended on by three packages so the dependent sweep (§13 step 10) is run anyway:
```bash
bunx turbo test --filter=...@suaveplan/diff
```
## Migration impact
None — additive only. No existing `diff` / `applyPatch` / `revertPatch` / `path/*` / `history/*` / `sync/*` surface is touched.

View File

@@ -0,0 +1,114 @@
<!-- markdownlint-disable MD024 -->
# Capability Spec Delta: diff (diff-stringify)
**Package**: `@suaveplan/diff`
**Status**: PROPOSED
> Every requirement below carries a `**Verified by:**` line at authoring time. No exceptions. (See `openspec/AGENTS.md` Section 13.)
## ADDED Requirements
### Requirement: Multi-line patch rendering
The package SHALL expose `stringifyPatch(patch: JsonPatch, options?: StringifyPatchOptions): string` that renders the input `JsonPatch` as a multi-line string, one line per operation, joined by `\n`. The grammar for each line SHALL be:
- `add <path> -> <value>`
- `remove <path>`
- `replace <path> -> <value>`
- `move <from> -> <path>`
- `copy <from> -> <path>`
- `test <path> -> <value>`
Path tokens SHALL be the operation's `path` (or `from`) field rendered verbatim. Value tokens SHALL be produced by `options.valueFormatter` (default: `JSON.stringify`).
When the input patch is empty, the function SHALL return the empty string.
#### Scenario: full RFC 6902 op set renders correctly
- **WHEN** a caller invokes `stringifyPatch([{ op: "add", path: "/a", value: 1 }, { op: "remove", path: "/b" }, { op: "move", from: "/c", path: "/d" }])`
- **THEN** the result equals `"add /a -> 1\nremove /b\nmove /c -> /d"`
#### Scenario: empty patch produces empty string
- **WHEN** a caller invokes `stringifyPatch([])`
- **THEN** the result is the empty string
**Verified by:** `src/utils/stringify-patch/stringify-patch.test.ts::"renders all six RFC 6902 operations"` AND `src/utils/stringify-patch/stringify-patch.test.ts::"returns empty string for empty patch"`
---
### Requirement: Value formatter injection point
`StringifyPatchOptions.valueFormatter?: (value: unknown) => string` SHALL be invoked exactly once per value-bearing operation (`add`, `replace`, `test`) when supplied. When omitted, the default formatter SHALL be `JSON.stringify`. Operations without a `value` field (`remove`, `move`, `copy`) SHALL NOT invoke the formatter.
#### Scenario: custom formatter applied
- **WHEN** a caller invokes `stringifyPatch([{ op: "add", path: "/secret", value: "abc" }], { valueFormatter: (v) =>`***`})`
- **THEN** the result equals `"add /secret -> ***"`
#### Scenario: formatter not invoked for value-less ops
- **WHEN** a caller invokes `stringifyPatch([{ op: "remove", path: "/a" }], { valueFormatter: spy })`
- **THEN** `spy` is invoked zero times
**Verified by:** `src/utils/stringify-patch/stringify-patch.spec-conformance.test.ts::"valueFormatter receives every value-bearing op exactly once"` AND `src/utils/stringify-patch/stringify-patch.spec-conformance.test.ts::"valueFormatter not invoked for remove / move / copy"`
---
### Requirement: Indent prefix and uppercase op casing
`StringifyPatchOptions.indent?: string` SHALL be prepended to every rendered line (default: empty string). `StringifyPatchOptions.uppercaseOps?: boolean` SHALL render op names in uppercase when `true` (default: `false`, matching RFC 6902).
#### Scenario: indent prepended per line
- **WHEN** a caller invokes `stringifyPatch([{ op: "add", path: "/a", value: 1 }, { op: "remove", path: "/b" }], { indent: " " })`
- **THEN** the result equals `" add /a -> 1\n remove /b"`
#### Scenario: uppercase op casing
- **WHEN** a caller invokes `stringifyPatch([{ op: "add", path: "/a", value: 1 }], { uppercaseOps: true })`
- **THEN** the result equals `"ADD /a -> 1"`
**Verified by:** `src/utils/stringify-patch/stringify-patch.spec-conformance.test.ts::"indent prefix prepended to every line"` AND `src/utils/stringify-patch/stringify-patch.spec-conformance.test.ts::"uppercaseOps flag flips op casing"`
---
### Requirement: Defensive guard for unknown ops
When the input patch contains an operation whose `op` field is not one of the six RFC 6902 operations, the function SHALL throw `DiffError` with code `DIFF.INVALID_PATCH_OP`. The `DiffError` message SHALL include the unknown op name for diagnostic purposes.
#### Scenario: unknown op throws structured error
- **WHEN** a caller invokes `stringifyPatch([{ op: "explode" as never, path: "/a" }])`
- **THEN** the call throws `DiffError` with code `DIFF.INVALID_PATCH_OP` AND the message contains `"explode"`
**Verified by:** `src/utils/stringify-patch/stringify-patch.spec-conformance.test.ts::"throws DIFF.INVALID_PATCH_OP for unknown patch operation"`
---
### Requirement: OTel observability for stringify
`stringifyPatch` SHALL emit a passive OTel span event `diff.stringify-patch` carrying a numeric `opCount` attribute equal to `patch.length`. The span event MUST be emitted regardless of whether the caller has configured a tracer.
#### Scenario: span event emitted with correct opCount
- **WHEN** a caller invokes `stringifyPatch(patch)` with `patch.length === 5` under an in-memory `TracerProvider`
- **THEN** one span event named `diff.stringify-patch` is recorded with `opCount: 5`
**Verified by:** `src/utils/stringify-patch/stringify-patch.spec-conformance.test.ts::"emits diff.stringify-patch span event with opCount attribute"`
---
### Requirement: Subpath export
The package SHALL expose the new module at the `./utils/stringify-patch` subpath in `package.json::exports`. Importing only `stringifyPatch` from that subpath SHALL NOT pull in unrelated `@suaveplan/diff` modules (`diff/diff`, `patch/patch`, `history/history`, `sync/sync`).
#### Scenario: subpath import resolves
- **WHEN** a caller writes `import { stringifyPatch } from "@suaveplan/diff/utils/stringify-patch"`
- **THEN** TypeScript resolves the import
**Verified by:** `src/utils/stringify-patch/stringify-patch.spec-conformance.test.ts::"subpath ./utils/stringify-patch resolves and tree-shakes"`
<!-- markdownlint-enable MD024 -->

View File

@@ -0,0 +1,85 @@
# Tasks — Diff `stringifyPatch` human-readable patch formatter
> Every checkbox MUST reflect work actually done in this change. Do not retroactively tick boxes for work that was already in main when this change opened.
## 0. Pre-flight (non-negotiable)
- [ ] 0.1 Confirm clean working tree (`git status` reports nothing) and no in-flight worktrees with uncommitted work (`git worktree list` then `git status` in each)
- [ ] 0.2 If any worktrees exist under `.claude/worktrees/`, account for each one: still-active agent, work-pending-merge, or stale-and-prune. Stale worktrees MUST be removed (`git worktree remove`) before opening a new one — code that has been lost twice on main is the failure mode this guards against.
- [ ] 0.3 Confirm the package set in `MANIFEST.md` matches `find packages -maxdepth 3 -name package.json` count. Drift here means a prior change archived without regenerating the manifest.
## Audit Note (2026-05-02)
**Minimal progress** — DEFERRED, do not archive.
- No `packages/data/diff/src/utils/stringify-patch/` directory exists.
- `grep -rln "stringifyPatch\|stringify-patch" packages/data/diff/src/` returns zero hits.
- `bunx turbo lint typecheck test --filter=@suaveplan/diff` is GREEN — but the new `stringifyPatch` surface is not implemented.
- All 40 tasks remain to be done: error code `DIFF.INVALID_PATCH_OP`, `stringify-patch.ts` feature module, `StringifyPatchOptions`, OTel span event, subpath export, sibling `.md`, conformance + property tests.
## 1. Spec authoring
- [ ] 1.1 Read `../suaveplan/packages/universal/diff/src/utils/utils.ts` (legacy `stringify` at L237-L240)
- [ ] 1.2 Read RFC 6902 §4 for op grammar reference
- [ ] 1.3 Read `openspec/specs/diff/spec.md` and `src/operations/` to confirm the canonical `JsonPatch` type
- [ ] 1.4 Read `openspec/AGENTS.md` Sections 13 and 14
- [ ] 1.5 Draft `proposal.md` from `openspec/templates/proposal.md`
- [ ] 1.6 Fill in `## Source mapping` table — every requirement cites a line range OR appears in the "no source line" table with justification
- [ ] 1.7 Draft `specs/diff/spec.md` from `openspec/templates/spec-delta.md`
- [ ] 1.8 Every requirement in the spec delta carries a `**Verified by:**` line naming concrete `it(...)` titles
## 2. Implementation
- [ ] 2.1 Register error code `DIFF.INVALID_PATCH_OP` in `src/errors/diff-error.ts`
- [ ] 2.2 Create `src/utils/stringify-patch/` feature module with `stringify-patch.ts`, `stringify-patch.types.ts`, `stringify-patch.schemas.ts`, `stringify-patch.md`, `index.ts`
- [ ] 2.3 Define `StringifyPatchOptions` in `stringify-patch.types.ts`
- [ ] 2.4 Implement `stringifyPatch(patch, options?)` rendering one line per op:
- `add /path -> <value>` — value via `valueFormatter`
- `remove /path`
- `replace /path -> <value>`
- `move /from -> /path`
- `copy /from -> /path`
- `test /path -> <value>`
- [ ] 2.5 Apply `options.indent` prefix per line and `options.uppercaseOps` casing transform
- [ ] 2.6 Throw `DiffError(DIFF.INVALID_PATCH_OP)` on unknown op (defensive)
- [ ] 2.7 Wire OTel span event `diff.stringify-patch` with `opCount` attribute
- [ ] 2.8 Add subpath export `./utils/stringify-patch` to `package.json::exports`
- [ ] 2.9 Re-export `stringifyPatch` from the root barrel `src/index.ts`
## 3. Tests
- [ ] 3.1 Unit tests at `src/utils/stringify-patch/stringify-patch.test.ts` — every operation type rendered; multi-op join with `\n`; empty patch returns empty string; default formatter uses `JSON.stringify`
- [ ] 3.2 Spec-conformance tests at `src/utils/stringify-patch/stringify-patch.spec-conformance.test.ts` — `valueFormatter` invoked once per value-bearing op; `uppercaseOps` flips case; `indent` prefix prepended per line; `DIFF.INVALID_PATCH_OP` thrown on unknown op; OTel span event emitted with correct `opCount`; subpath import resolves
- [ ] 3.3 Property test (fast-check): for any well-formed `JsonPatch`, `stringifyPatch(patch).split('\n').length === patch.length`
- [ ] 3.4 Every `it(...)` carries `{ timeout: 5000 }`
## 4. Documentation
- [ ] 4.1 `src/utils/stringify-patch/stringify-patch.md` — sibling doc (≥200 words, basic + advanced examples including `valueFormatter` redaction usage, full API reference)
- [ ] 4.2 README links `./utils/stringify-patch/stringify-patch.md` under `## Modules`
- [ ] 4.3 Update `CLAUDE.md` `@suaveplan/diff` entry to mention `stringifyPatch`
## 5. Pre-archive verification (the 5-gate triple)
- [ ] 5.1 `bun run check` — Biome 0 errors / 0 warnings / 0 info across the whole monorepo
- [ ] 5.2 `bunx turbo lint typecheck test --filter=@suaveplan/diff` — green
- [ ] 5.3 `bunx turbo test:coverage --filter=@suaveplan/diff` — 100/100/100/100
- [ ] 5.4 `bun scripts/openspec-conformance.ts @suaveplan/diff` — exit 0, no `error` findings
- [ ] 5.5 `bunx turbo build --filter=@suaveplan/diff` — green
- [ ] 5.6 `bunx turbo test --filter=...@suaveplan/diff` — every dependent (undo, event-sourcing, crdt) passes
## 6. Pre-archive 7-row checklist (AGENTS.md Section 13)
- [ ] 6.1 Generics threaded; `expectTypeOf` confirms `stringifyPatch` returns `string` (not `string | undefined`)
- [ ] 6.2 Zod schema wired at `StringifyPatchOptions` boundary
- [ ] 6.3 `DIFF.INVALID_PATCH_OP` thrown by at least one production path
- [ ] 6.4 Strict-mode behaviors tested (`uppercaseOps: false` vs `true`; default vs custom `valueFormatter`)
- [ ] 6.5 OTel span event emitted from production paths and asserted with a real in-memory `TracerProvider`
- [ ] 6.6 Lifecycle dedup — N/A (stateless function)
- [ ] 6.7 No retroactive tick — every box above reflects work done in this change
## 7. Archive
- [ ] 7.1 Fold spec delta into `openspec/specs/diff/spec.md`
- [ ] 7.2 Move `openspec/changes/diff-stringify/` → `openspec/archive/<yyyy-mm-dd>-diff-stringify/`
- [ ] 7.3 Refresh `MANIFEST.md` if dep set changed (no expected change)