diff --git a/docs/issue-spec-representation.md b/docs/issue-spec-representation.md index 2595794..f2b8a84 100644 --- a/docs/issue-spec-representation.md +++ b/docs/issue-spec-representation.md @@ -4,7 +4,7 @@ This document defines the forge-neutral issue representation used by `zest-dev d ## Purpose -An Issue Spec Representation stores one complete Zest Dev Spec directory in one forge issue. It is a snapshot format, not a synchronization protocol. +An Issue Spec Representation stores one complete Markdown file snapshot of a Zest Dev Spec directory in one forge issue. It is a snapshot format, not a synchronization protocol. The representation is designed for GitHub and Forgejo issue primitives: - issue title @@ -14,40 +14,49 @@ The representation is designed for GitHub and Forgejo issue primitives: Load correctness depends only on protocol headers and Markdown content in the issue body and protocol comments. The title and labels are archive metadata for people. -## Version +## Versions -The initial protocol version is `1`. +`dump` writes protocol version `2`. `load` accepts versions `1` and `2` so existing archives remain loadable. -Every protocol body/comment starts with a leading HTML comment header: +Every protocol body/comment starts with a leading HTML comment header. A V2 issue body for a normal Spec begins like this: ```markdown ``` -Rules: +Rules common to V2 body and file comments: - The header must start at the beginning of the body or comment. -- The header is YAML-like line data inside an HTML comment. -- `zest-dev-issue-spec` is required and must be `1`. -- `spec-id` is required and identifies the Spec directory. -- `path` is required and identifies the file path inside the Spec directory. -- The Markdown file content starts immediately after the header closing line and one newline. -- The file content is stored as renderable Markdown, not inside a fenced code block. +- The header is YAML inside an HTML comment. +- `zest-dev-issue-spec` and `spec-id` are required. +- The `spec-id` identifies the target Spec directory. +- File content starts immediately after the header closing line and one newline. +- File content is stored as renderable Markdown, not inside a fenced code block. -## Issue Mapping +## V2 Directory Manifest -One issue represents one Spec directory. +The V2 issue body describes the complete represented directory: +- `files` is a required, non-empty array containing every represented Markdown path. +- `body-path` is optional. When present, it identifies which manifested file is stored after the body header. +- Every manifested path other than `body-path` is stored in exactly one protocol comment. +- Manifest paths emitted by `dump` are sorted for deterministic output. -The issue body stores `spec.md`: +When `spec.md` exists, `dump` uses it as `body-path` so the Main Spec File remains readable in the issue body: ```markdown --- id: 20260627-issue-dump-load @@ -61,22 +70,49 @@ created: '2026-06-27' ... ``` -Each additional Markdown file is stored in one issue comment: +When `spec.md` does not exist, the body has no `body-path` or file content. All manifested Markdown files are stored in protocol comments: ```markdown +``` + +A V2 file comment carries its path and exact content: + +```markdown + -# Design +# Historical design ... ``` -Comment order is not meaningful. `load` matches supporting files by `path`. +Comment order is not meaningful. Comments without a leading protocol header are ordinary issue discussion and are ignored by `load`. + +Before writing any files, `load` verifies that the body payload and protocol comments match the manifest exactly. Missing, duplicate, or unlisted represented paths fail instead of producing a partial directory. + +## V1 Load Compatibility -Comments without a leading protocol header are ordinary issue discussion and are ignored by `load`. +V1 archives do not contain a directory manifest. Their issue body header has `path: spec.md`, and the body payload is required to contain the Main Spec File: + +```markdown + +# Existing V1 Spec +``` + +Every V1 supporting Markdown file remains stored in one protocol comment with the same version, `spec-id`, and its own `path`. V1 keeps its original validation behavior during load. New dumps never emit V1. ## Title And Labels @@ -93,20 +129,17 @@ spec:change archive ``` -`load` must not use title or labels as authoritative Spec data. +`load` does not use title or labels as authoritative Spec data. + +## Represented File Set -## File Set +`dump` recursively includes every Markdown file under the Spec directory. A directory does not need a Main Spec File, but it must contain at least one Markdown file. -`dump` walks the Spec directory and includes every Markdown file: -- `spec.md` is written to the issue body. -- Every other Markdown file is written to one protocol comment. +Ordinary non-Markdown files are outside the Issue Spec Representation and are ignored. Unsupported filesystem entry types, including symlinks, fail visibly because they cannot be represented safely. -`dump` fails when: -- `spec.md` is missing. -- The Spec directory contains any non-Markdown file. -- A discovered Markdown path is invalid. +Empty Markdown files are valid and retain their empty content through V2. -Legacy `README.md` main files are not supported by this protocol. +Markdown files must contain valid UTF-8. Invalid byte sequences fail rather than being replaced during decoding. ## Path Rules @@ -125,16 +158,15 @@ Rejected: - paths containing parent-directory traversal - non-Markdown paths - duplicate paths +- paths whose directory segments end in `.md` - path separators that cannot be normalized safely for the current platform -`load` always writes issue body content to `spec.md`. The body header path must be `spec.md`. +In V2, `body-path` must be one of the manifested paths. It describes storage location only and does not designate or create a Main Spec File. -## Spec Identity +## Spec Identity And Local Write The loaded Spec identity comes from the protocol header `spec-id`, not from `spec.md` frontmatter, title, labels, issue number, or URL. -`load` fails when the body protocol header is missing `spec-id` or contains an invalid `spec-id`. - The `spec-id` must be a valid Spec directory name: ```text @@ -147,54 +179,53 @@ YYYYMMDD- specs/change// ``` -Protocol comments must repeat the same `spec-id`. If a protocol comment omits `spec-id` or includes a different `spec-id`, `load` fails. - -If the target Spec directory already exists, `load` fails. +Every protocol comment must use the same version and `spec-id` as the issue body. If the target Spec directory already exists, `load` fails. Files are written to a temporary directory and renamed into place only after validation and successful writes. -`load` does not change `specs/change/active`. +`load` does not change `specs/change/active`. For a directory without `spec.md`, successful output reports the Spec directory path rather than a nonexistent Main Spec File path. ## Local Representation Mode -The same body/comment mapping can be represented locally for dry-run and tests: +The same body/comment mapping can be represented locally as YAML: ```yaml -title: "[archive] 20260627-issue-dump-load" +title: "[archive] 20260812-legacy-spec" labels: - spec:change - archive body: | - ... comments: - | - ... + # Historical design ``` -`dump --dry-run` emits this local representation without creating a remote issue. - -`load --from-file ` loads from this local representation without reading a remote issue. +`dump --dry-run` emits this local representation without creating a remote issue. `load --from-file ` loads it without reading a remote issue. ## Failure Rules The protocol is fail-fast: -- unsupported protocol version fails -- missing body protocol header fails -- malformed protocol header fails -- missing or invalid body `spec-id` fails -- mismatched comment `spec-id` fails -- missing `spec.md` content fails -- invalid or duplicate file paths fail -- existing target Spec directory fails -- unsupported forge transport fails +- unsupported or mismatched protocol versions fail +- missing or malformed body protocol headers fail +- missing or invalid `spec-id` values fail +- V2 missing, empty, invalid, or duplicate manifest paths fail +- V2 body mappings outside the manifest fail +- V2 missing, duplicate, or unlisted represented files fail +- unexpected V2 body content without `body-path` fails +- V1 body paths other than `spec.md` or empty `spec.md` content fail +- invalid file paths fail +- invalid UTF-8 Markdown content fails +- existing target Spec directories fail +- unsupported forge transports fail - failed remote issue or comment operations fail -Remote `dump` is not transactional. If issue creation succeeds and a later comment creation fails, the command fails and reports the created issue URL. It does not silently close, delete, or repair the issue. +Remote `dump` is not transactional. If issue creation succeeds and a later comment creation or issue close fails, the command fails and reports the created issue URL. It does not silently close, delete, or repair the issue. diff --git a/e2e/tests/test_issue_dump_load.py b/e2e/tests/test_issue_dump_load.py index 6389d43..d70653a 100644 --- a/e2e/tests/test_issue_dump_load.py +++ b/e2e/tests/test_issue_dump_load.py @@ -3,6 +3,7 @@ import stat from pathlib import Path +import pytest import yaml @@ -13,7 +14,18 @@ def markdown_files(spec_dir: Path) -> dict[str, str]: } -def test_dump_dry_run_and_load_from_file_round_trip_markdown_files(cli): +def protocol_header(text: str) -> dict: + assert text.startswith("", 1) + return yaml.safe_load(metadata) + + +def protocol_document(metadata: dict, content: str = "") -> str: + header = yaml.safe_dump(metadata, sort_keys=False).rstrip() + return f"\n{content}" + + +def test_v2_directory_manifest_round_trips_spec_with_main_file(cli): created = cli.yaml("create", "dump-load-source")["spec"] source_id = created["id"] source_dir = cli.project_dir / "specs" / "change" / source_id @@ -26,7 +38,10 @@ def test_dump_dry_run_and_load_from_file_round_trip_markdown_files(cli): issue = dumped["issue"] assert issue["title"] == f"[archive] {source_id}" assert issue["labels"] == ["spec:change", "archive"] - assert issue["body"].startswith("\n") + assert [protocol_header(comment)["path"] for comment in issue["comments"]] == [ + "design.md", + "notes/empty.md", + ] + + source_files = markdown_files(source_dir) + source_dir.rename(source_dir.with_name(f"{source_id}.source")) + dump_path = cli.project_dir / "legacy-v2.yml" + dump_path.write_text(yaml.safe_dump(issue, sort_keys=False), encoding="utf-8") + + loaded = cli.yaml("load", "--from-file", str(dump_path)) + assert loaded["spec"] == { + "id": source_id, + "path": f"specs/change/{source_id}", + "active": False, + "status": "new", + } + assert markdown_files(cli.project_dir / "specs" / "change" / source_id) == source_files + + v1_id = "20240101-v1-archive" + v1_path = cli.project_dir / "v1.yml" + v1_path.write_text( + yaml.safe_dump( + { + "body": ( + "\n# V1 body\n" + ), + "comments": [], + }, + sort_keys=False, + ), + encoding="utf-8", + ) + cli.ok("load", "--from-file", str(v1_path)) + assert markdown_files(cli.project_dir / "specs" / "change" / v1_id) == { + "spec.md": "# V1 body\n" + } + + def test_dump_and_load_round_trip_yaml_sensitive_markdown_paths(cli): created = cli.yaml("create", "yaml-sensitive-paths")["spec"] source_id = created["id"] @@ -76,9 +147,17 @@ def test_dump_and_load_fail_fast_for_invalid_local_protocol(cli): assert dumped["ok"] is True assert "asset.txt" not in yaml.safe_dump(dumped["issue"]) - (spec_dir / "asset.txt").unlink() - (spec_dir / "spec.md").unlink() - assert "Issue Spec Representation requires spec.md" in cli.fail("dump", created["id"], "--dry-run") + empty_id = "20240101-empty-directory" + (cli.project_dir / "specs" / "change" / empty_id).mkdir() + assert "requires at least one Markdown file" in cli.fail("dump", empty_id, "--dry-run") + + invalid_utf8_id = "20240101-invalid-utf8" + invalid_utf8_dir = cli.project_dir / "specs" / "change" / invalid_utf8_id + invalid_utf8_dir.mkdir() + (invalid_utf8_dir / "invalid.md").write_bytes(b"\xff") + assert "Invalid UTF-8 Markdown file: invalid.md" in cli.fail( + "dump", invalid_utf8_id, "--dry-run" + ) cases = { "missing-header.yml": {"body": "# Missing\n", "comments": []}, @@ -157,10 +236,96 @@ def test_load_ignores_non_protocol_html_comments(cli): } -def test_github_transport_uses_gh_and_reports_comment_failure(cli): +def test_v2_manifest_fails_fast_for_incomplete_or_invalid_representations(cli): + spec_id = "20240101-v2-invalid" + base_metadata = { + "zest-dev-issue-spec": 2, + "spec-id": spec_id, + "files": ["design.md"], + } + valid_comment = protocol_document( + {"zest-dev-issue-spec": 2, "spec-id": spec_id, "path": "design.md"}, + "# Design\n", + ) + cases = { + "empty-manifest": ( + {"body": protocol_document({**base_metadata, "files": []}), "comments": []}, + "manifest requires at least one file", + ), + "duplicate-manifest": ( + { + "body": protocol_document({**base_metadata, "files": ["design.md", "design.md"]}), + "comments": [valid_comment], + }, + "Duplicate Issue Spec manifest path: design.md", + ), + "body-path-not-listed": ( + { + "body": protocol_document({**base_metadata, "body-path": "spec.md"}, "# Spec\n"), + "comments": [valid_comment], + }, + "Issue body path is not present in manifest: spec.md", + ), + "unexpected-body-content": ( + {"body": protocol_document(base_metadata, "# Not a represented file\n"), "comments": [valid_comment]}, + "Unexpected issue body content without body-path", + ), + "missing-comment": ( + {"body": protocol_document(base_metadata), "comments": []}, + "Missing Issue Spec file: design.md", + ), + "unlisted-comment": ( + { + "body": protocol_document(base_metadata), + "comments": [ + valid_comment, + protocol_document( + {"zest-dev-issue-spec": 2, "spec-id": spec_id, "path": "extra.md"}, + "# Extra\n", + ), + ], + }, + "Unlisted Issue Spec path: extra.md", + ), + "mixed-version": ( + { + "body": protocol_document(base_metadata), + "comments": [ + protocol_document( + {"zest-dev-issue-spec": 1, "spec-id": spec_id, "path": "design.md"}, + "# Design\n", + ) + ], + }, + "Mismatched Issue Spec protocol version", + ), + "mismatched-spec-id": ( + { + "body": protocol_document(base_metadata), + "comments": [ + protocol_document( + {"zest-dev-issue-spec": 2, "spec-id": "20240101-other", "path": "design.md"}, + "# Design\n", + ) + ], + }, + 'Mismatched comment spec-id "20240101-other"', + ), + } + + for name, (representation, expected_error) in cases.items(): + path = cli.project_dir / f"{name}.yml" + path.write_text(yaml.safe_dump(representation, sort_keys=False), encoding="utf-8") + assert expected_error in cli.fail("load", "--from-file", str(path)) + + +@pytest.mark.parametrize("with_spec_md", [True, False]) +def test_github_transport_uses_gh_and_reports_comment_failure(cli, with_spec_md): created = cli.yaml("create", "github-dump-source")["spec"] spec_dir = cli.project_dir / "specs" / "change" / created["id"] (spec_dir / "notes.md").write_text("# Notes\n", encoding="utf-8") + if not with_spec_md: + (spec_dir / "spec.md").unlink() fake_bin = cli.project_dir / "fake-bin" fake_bin.mkdir() diff --git a/lib/spec-manager.js b/lib/spec-manager.js index 948c630..5e57821 100644 --- a/lib/spec-manager.js +++ b/lib/spec-manager.js @@ -16,7 +16,10 @@ const STATUS_ORDER = { planned: 2, implemented: 3 }; -const ISSUE_SPEC_PROTOCOL_VERSION = 1; +const ISSUE_SPEC_PROTOCOL_V1 = 1; +const ISSUE_SPEC_PROTOCOL_V2 = 2; +const ISSUE_SPEC_WRITE_PROTOCOL_VERSION = ISSUE_SPEC_PROTOCOL_V2; +const SUPPORTED_ISSUE_SPEC_PROTOCOL_VERSIONS = [ISSUE_SPEC_PROTOCOL_V1, ISSUE_SPEC_PROTOCOL_V2]; const ISSUE_SPEC_LABELS = ['spec:change', 'archive']; function pathExistsIncludingDanglingSymlink(filePath) { @@ -229,26 +232,45 @@ function walkSpecDirectory(specDirPath, currentDir = specDirPath, files = []) { return files; } +function readMarkdownFile(specDirPath, relativePath) { + const filePath = path.join(specDirPath, ...relativePath.split('/')); + const bytes = fs.readFileSync(filePath); + const content = bytes.toString('utf-8'); + if (!Buffer.from(content, 'utf-8').equals(bytes)) { + throw new Error(`Invalid UTF-8 Markdown file: ${relativePath}`); + } + return content; +} + +function renderIssueSpecDocument(metadata, content = '') { + const renderedMetadata = yaml.dump(metadata, { lineWidth: -1 }).trimEnd(); + return ['', content].join('\n'); +} + function renderIssueSpecFile(specId, relativePath, content) { - const metadata = yaml - .dump( - { - 'zest-dev-issue-spec': ISSUE_SPEC_PROTOCOL_VERSION, - 'spec-id': specId, - path: relativePath - }, - { lineWidth: -1 } - ) - .trimEnd(); - return [ - '', + return renderIssueSpecDocument( + { + 'zest-dev-issue-spec': ISSUE_SPEC_WRITE_PROTOCOL_VERSION, + 'spec-id': specId, + path: relativePath + }, content - ].join('\n'); + ); } -function parseIssueSpecFile(text, location, { requireProtocol = true } = {}) { +function renderIssueSpecManifest(specId, markdownFiles, bodyPath, bodyContent) { + const metadata = { + 'zest-dev-issue-spec': ISSUE_SPEC_WRITE_PROTOCOL_VERSION, + 'spec-id': specId, + files: markdownFiles + }; + if (bodyPath) { + metadata['body-path'] = bodyPath; + } + return renderIssueSpecDocument(metadata, bodyContent); +} + +function parseIssueSpecDocument(text, location, { requireProtocol = true } = {}) { if (typeof text !== 'string') { throw new Error(`${location} must be a string`); } @@ -272,7 +294,8 @@ function parseIssueSpecFile(text, location, { requireProtocol = true } = {}) { throw new Error(`Malformed Issue Spec protocol header in ${location}: ${error.message}`); } - if (metadata['zest-dev-issue-spec'] !== ISSUE_SPEC_PROTOCOL_VERSION) { + const version = metadata['zest-dev-issue-spec']; + if (!SUPPORTED_ISSUE_SPEC_PROTOCOL_VERSIONS.includes(version)) { throw new Error(`Unsupported Issue Spec protocol version in ${location}`); } if (!metadata['spec-id']) { @@ -280,43 +303,58 @@ function parseIssueSpecFile(text, location, { requireProtocol = true } = {}) { } validateSpecId(metadata['spec-id']); - const relativePath = normalizeIssueSpecPath(metadata.path); - return { + version, specId: metadata['spec-id'], - path: relativePath, + metadata, content: text.slice(match[0].length) }; } +function parseIssueSpecFile(text, location, { requireProtocol = true } = {}) { + const document = parseIssueSpecDocument(text, location, { requireProtocol }); + if (!document) { + return null; + } + + return { + version: document.version, + specId: document.specId, + path: normalizeIssueSpecPath(document.metadata.path), + content: document.content + }; +} + function specToIssueRepresentation(specIdentifier) { const spec = getSpec(specIdentifier); validateSpecId(spec.id); const specDirPath = path.join(SPECS_DIR, spec.id); - const specMdPath = path.join(specDirPath, 'spec.md'); - if (!fs.existsSync(specMdPath)) { - throw new Error('Issue Spec Representation requires spec.md'); - } - const markdownFiles = walkSpecDirectory(specDirPath).sort(); - if (!markdownFiles.includes('spec.md')) { - throw new Error('Issue Spec Representation requires spec.md'); + if (markdownFiles.length === 0) { + throw new Error('Issue Spec Representation requires at least one Markdown file'); + } + for (const relativePath of markdownFiles) { + normalizeIssueSpecPath(relativePath); } - const body = renderIssueSpecFile( + const bodyPath = markdownFiles.includes('spec.md') ? 'spec.md' : null; + const bodyContent = bodyPath + ? readMarkdownFile(specDirPath, bodyPath) + : ''; + const body = renderIssueSpecManifest( spec.id, - 'spec.md', - fs.readFileSync(specMdPath, 'utf-8') + markdownFiles, + bodyPath, + bodyContent ); const comments = markdownFiles - .filter(relativePath => relativePath !== 'spec.md') + .filter(relativePath => relativePath !== bodyPath) .map(relativePath => { - normalizeIssueSpecPath(relativePath); return renderIssueSpecFile( spec.id, relativePath, - fs.readFileSync(path.join(specDirPath, ...relativePath.split('/')), 'utf-8') + readMarkdownFile(specDirPath, relativePath) ); }); @@ -328,12 +366,7 @@ function specToIssueRepresentation(specIdentifier) { }; } -function issueRepresentationToFiles(issueRepresentation) { - if (!issueRepresentation || typeof issueRepresentation !== 'object') { - throw new Error('Issue Spec Representation must be an object'); - } - - const bodyFile = parseIssueSpecFile(issueRepresentation.body, 'issue body'); +function issueRepresentationV1ToFiles(bodyFile, comments) { if (bodyFile.path !== 'spec.md') { throw new Error('Issue body path must be spec.md'); } @@ -344,11 +377,6 @@ function issueRepresentationToFiles(issueRepresentation) { const files = new Map(); files.set('spec.md', bodyFile.content); - const comments = issueRepresentation.comments || []; - if (!Array.isArray(comments)) { - throw new Error('Issue Spec comments must be an array'); - } - for (const [index, comment] of comments.entries()) { const commentBody = typeof comment === 'string' ? comment : comment && comment.body; const parsed = parseIssueSpecFile(commentBody, `issue comment ${index + 1}`, { @@ -357,6 +385,9 @@ function issueRepresentationToFiles(issueRepresentation) { if (!parsed) { continue; } + if (parsed.version !== ISSUE_SPEC_PROTOCOL_V1) { + throw new Error(`Mismatched Issue Spec protocol version in issue comment ${index + 1}`); + } if (parsed.specId !== bodyFile.specId) { throw new Error(`Mismatched comment spec-id "${parsed.specId}" for ${parsed.path}`); } @@ -375,6 +406,95 @@ function issueRepresentationToFiles(issueRepresentation) { }; } +function issueRepresentationV2ToFiles(bodyDocument, comments) { + const manifest = bodyDocument.metadata.files; + if (!Array.isArray(manifest) || manifest.length === 0) { + throw new Error('Issue Spec V2 manifest requires at least one file'); + } + + const manifestPaths = []; + const manifestSet = new Set(); + for (const manifestPath of manifest) { + const relativePath = normalizeIssueSpecPath(manifestPath); + if (manifestSet.has(relativePath)) { + throw new Error(`Duplicate Issue Spec manifest path: ${relativePath}`); + } + manifestSet.add(relativePath); + manifestPaths.push(relativePath); + } + + const rawBodyPath = bodyDocument.metadata['body-path']; + const bodyPath = rawBodyPath === undefined ? null : normalizeIssueSpecPath(rawBodyPath); + if (bodyPath && !manifestSet.has(bodyPath)) { + throw new Error(`Issue body path is not present in manifest: ${bodyPath}`); + } + if (!bodyPath && bodyDocument.content.length > 0) { + throw new Error('Unexpected issue body content without body-path'); + } + + const files = new Map(); + if (bodyPath) { + files.set(bodyPath, bodyDocument.content); + } + + for (const [index, comment] of comments.entries()) { + const commentBody = typeof comment === 'string' ? comment : comment && comment.body; + const parsed = parseIssueSpecFile(commentBody, `issue comment ${index + 1}`, { + requireProtocol: false + }); + if (!parsed) { + continue; + } + if (parsed.version !== ISSUE_SPEC_PROTOCOL_V2) { + throw new Error(`Mismatched Issue Spec protocol version in issue comment ${index + 1}`); + } + if (parsed.specId !== bodyDocument.specId) { + throw new Error(`Mismatched comment spec-id "${parsed.specId}" for ${parsed.path}`); + } + if (!manifestSet.has(parsed.path)) { + throw new Error(`Unlisted Issue Spec path: ${parsed.path}`); + } + if (files.has(parsed.path)) { + throw new Error(`Duplicate Issue Spec path: ${parsed.path}`); + } + files.set(parsed.path, parsed.content); + } + + for (const relativePath of manifestPaths) { + if (!files.has(relativePath)) { + throw new Error(`Missing Issue Spec file: ${relativePath}`); + } + } + + return { + specId: bodyDocument.specId, + files: manifestPaths.map(relativePath => ({ path: relativePath, content: files.get(relativePath) })) + }; +} + +function issueRepresentationToFiles(issueRepresentation) { + if (!issueRepresentation || typeof issueRepresentation !== 'object') { + throw new Error('Issue Spec Representation must be an object'); + } + + const comments = issueRepresentation.comments || []; + if (!Array.isArray(comments)) { + throw new Error('Issue Spec comments must be an array'); + } + + const bodyDocument = parseIssueSpecDocument(issueRepresentation.body, 'issue body'); + if (bodyDocument.version === ISSUE_SPEC_PROTOCOL_V1) { + const bodyFile = { + version: bodyDocument.version, + specId: bodyDocument.specId, + path: normalizeIssueSpecPath(bodyDocument.metadata.path), + content: bodyDocument.content + }; + return issueRepresentationV1ToFiles(bodyFile, comments); + } + return issueRepresentationV2ToFiles(bodyDocument, comments); +} + function writeIssueRepresentation(issueRepresentation, source) { const { specId, files } = issueRepresentationToFiles(issueRepresentation); const specDirPath = path.join(SPECS_DIR, specId); @@ -400,13 +520,18 @@ function writeIssueRepresentation(issueRepresentation, source) { throw error; } + const hasMainSpecFile = files.some(file => file.path === 'spec.md'); + const reportedPath = hasMainSpecFile ? path.join(specDirPath, 'spec.md') : specDirPath; + return { ok: true, spec: { id: specId, - path: path.join(SPECS_DIR, specId, 'spec.md'), + path: reportedPath, active: getActiveChangeSpecId() === specId, - status: parseSpecFrontmatter(path.join(specDirPath, 'spec.md')).status || 'new' + status: hasMainSpecFile + ? parseSpecFrontmatter(path.join(specDirPath, 'spec.md')).status || 'new' + : 'new' }, source }; diff --git a/package.json b/package.json index 68e83fd..d548c4c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "zest-dev", - "version": "1.0.12", + "version": "1.0.13", "description": "A lightweight, human-interactive development workflow for AI-assisted coding", "author": { "name": "nettee", diff --git a/specs/change/20260912-issue-spec-v2-directory-manifest/design.md b/specs/change/20260912-issue-spec-v2-directory-manifest/design.md new file mode 100644 index 0000000..a8f15fc --- /dev/null +++ b/specs/change/20260912-issue-spec-v2-directory-manifest/design.md @@ -0,0 +1,58 @@ +# Design Record + +## Research Findings + +### Existing System + +- Issue Spec Representation V1 defines the issue body as `spec.md`, supporting files as comments, and rejects a missing Main Spec File. Source: `docs/issue-spec-representation.md:17-79,98-130`. +- `specToIssueRepresentation` checks for `spec.md` before walking the directory and always renders that file into the body. Source: `lib/spec-manager.js:292-328`. +- `issueRepresentationToFiles` requires the body path to equal `spec.md`, rejects empty body content, then reconstructs supporting files from protocol comments. Source: `lib/spec-manager.js:331-375`. +- Local and GitHub modes share the same core conversion functions; the GitHub adapter transports opaque body/comment strings and does not interpret file roles. Source: `lib/spec-manager.js:509-574`. +- Directory writes already use a temporary directory followed by rename, preventing a validation or write failure from exposing a partially loaded target. Source: `lib/spec-manager.js:378-412`. +- Directory walking collects nested `.md` files, ignores ordinary non-Markdown files, and rejects unsupported entry types such as symlinks. Source: `lib/spec-manager.js:212-229`; `e2e/tests/test_issue_dump_load.py:71-81`. + +### Design Inputs + +- Issue #148 requires lossless dump/load for historical Markdown-only directories without inventing `spec.md`, in dry-run and remote GitHub modes, while preserving normal directories and visible failures. Source: https://github.com/nettee/zest-dev/issues/148. +- All future dumps should use V2 rather than conditionally emitting V1; V1 is retained only for loading existing archives. Source: user decision in this Spec session, 2026-09-12. +- A Spec directory no longer needs `spec.md` to be dumpable, but the represented scope remains its Markdown file set. Source: user decision in this Spec session, 2026-09-12. + +### Constraints And Evidence Gaps + +- Repository error-handling rules prohibit placeholder Main Spec Files, partial success, or hidden recovery from malformed protocol data. Source: `AGENTS.md`, Error Handling / Fast Fail. +- Existing E2E tests exercise the public CLI and are reused by both local and packed-package runners. Source: `e2e/tests/conftest.py:15-55`; `package.json:31-38`. +- The current protocol document says non-Markdown files fail dump, but current implementation and tests intentionally ignore them. The implementation/test behavior is treated as current behavior and the stale documentation will be corrected. Source: `docs/issue-spec-representation.md:98-109`; `lib/spec-manager.js:220-226`; `e2e/tests/test_issue_dump_load.py:71-81`. + +## Design Decisions + +### Protocol And Compatibility + +- `dump` always emits Issue Spec Representation V2. `load` accepts V1 and V2 so previously archived issues remain reconstructable. Rationale: one current write format avoids permanent mode-dependent serialization while explicit version dispatch preserves compatibility. Premises: V1 is currently hard-coded in both directions and historical archives already exist (`lib/spec-manager.js:232-288,331-375`). +- A V2 body header contains `zest-dev-issue-spec: 2`, `spec-id`, a non-empty `files` array of normalized Markdown paths, and optional `body-path`. The manifest paths are emitted in sorted order for deterministic dry-run output. Premise: file discovery is already recursive and sorted before V1 rendering (`lib/spec-manager.js:212-229,302`). +- `body-path` is a storage mapping, not a Main Spec File requirement. When `spec.md` exists, dump sets `body-path: spec.md` and preserves its content after the header; without `spec.md`, `body-path` is absent, the body has no file payload, and every manifested file is a protocol comment. Rationale: normal issues keep their readable body while legacy directories do not receive fabricated content. Premise: issue #148 requires both properties. +- V1 retains its current body-is-`spec.md` rules during load. V1 is not emitted after this change. Premise: existing V1 archives derive identity and `spec.md` content from the body (`docs/issue-spec-representation.md:132-154`). + +### Validation And Write Boundary + +- Parse the leading protocol header independently from file-path validation, then dispatch by version. V1 uses the existing file-body contract; V2 validates its manifest and optional body mapping before returning a common `{ specId, files }` representation. Premise: transport and filesystem writing already consume a common representation (`lib/spec-manager.js:378-412,509-574`). +- V2 loading rejects an absent/empty manifest, invalid or duplicate paths, a `body-path` outside the manifest, unexpected body payload without `body-path`, mismatched versions or Spec IDs, duplicate represented paths, and any missing or extra protocol file relative to the manifest. Ordinary non-protocol comments remain ignored. Rationale: the manifest must detect partial remote archives instead of silently producing an incomplete directory. Premises: issue #148 requires visible data-loss failures; V1 already ignores ordinary discussion (`lib/spec-manager.js:352-369`). +- Empty Markdown files are valid V2 file payloads. A directory with no Markdown files fails dump because there is no preservable Spec representation. Premise: losslessness applies to Markdown paths and exact content, including empty content (issue #148). +- Dump reads Markdown through a strict UTF-8 boundary and fails when decoding would replace invalid bytes. Rationale: replacement characters would violate exact-content preservation. Premises: issue #148 requires lossless content and visible failure for non-preservable input. +- Loading without `spec.md` reports the Spec directory as `spec.path` and status `new`; loading with `spec.md` preserves the existing file path and frontmatter-derived status. Rationale: output must not point to a fabricated or nonexistent Main Spec File. Premise: current output always constructs a `spec.md` path (`lib/spec-manager.js:403-410`). + +### Change Scope + +Impact Areas: +- Core protocol rendering/parsing and directory conversion in `lib/spec-manager.js`. +- Local, package, and fake-GitHub E2E coverage in `e2e/tests/test_issue_dump_load.py`. +- Protocol contract in `docs/issue-spec-representation.md`. + +Planned File Changes: +- `lib/spec-manager.js`: implement V2 writes, V1/V2 reads, manifest validation, and truthful load metadata. +- `e2e/tests/test_issue_dump_load.py`: cover normal and Markdown-only V2 round trips, remote compatibility, V1 reads, and corrupt V2 failures. +- `docs/issue-spec-representation.md`: replace the V1-only write contract with V2 plus V1 compatibility rules. + +### Verification Strategy + +- EAG: run the focused public-CLI test selected by `v2_directory_manifest`, which constructs a nested Markdown-only directory, round-trips it through a local representation, compares exact paths/content, and also checks a normal V2 dump plus V1 load compatibility. +- Regression: run the complete local E2E suite, then the package E2E suite before PR creation. The fake-`gh` coverage proves remote V2 behavior without mutating GitHub issues. diff --git a/specs/change/20260912-issue-spec-v2-directory-manifest/implementation.md b/specs/change/20260912-issue-spec-v2-directory-manifest/implementation.md new file mode 100644 index 0000000..75fae3f --- /dev/null +++ b/specs/change/20260912-issue-spec-v2-directory-manifest/implementation.md @@ -0,0 +1,29 @@ +# Implementation + +## Outcome + +- `dump` now emits one V2 directory-manifest representation for normal and Markdown-only Spec directories; `load` validates V2 completeness and remains compatible with V1 archives. +- Local/file and GitHub transports preserve nested paths, empty files, and exact UTF-8 content without creating a synthetic `spec.md`. + +## Deviations + +### Strict UTF-8 validation at the dump boundary + +Current behavior: Dump rejects a Markdown file whose bytes cannot round-trip through UTF-8 decoding. + +Deviation: The initial Design required exact content and non-preservable-input failures but did not explicitly identify Node's replacement-character decoding risk. Final review made the encoding boundary explicit in the Design and protocol documentation. + +Attention: Future file-reading refactors must preserve strict validation rather than returning a successfully corrupted representation. + +Evidence: `lib/spec-manager.js` `readMarkdownFile`; `e2e/tests/test_issue_dump_load.py` invalid UTF-8 assertion. + +## Verification + +- EAG: `cd e2e && env UV_CACHE_DIR=/tmp/zest-dev-uv-cache uv run pytest -q tests/test_issue_dump_load.py -k 'v2_directory_manifest'` — 2 passed. +- Local E2E: `env UV_CACHE_DIR=/tmp/zest-dev-uv-cache pnpm test:local` — 26 passed, 1 package-only test skipped. +- Package E2E: `env UV_CACHE_DIR=/tmp/zest-dev-uv-cache pnpm test:package` — 27 passed. +- Static checks: `git diff --check` and `node --check lib/spec-manager.js` passed. + +## Spec Retrospective + +The Design should have named the UTF-8 decoding boundary when it first translated “exact content” into failure behavior; final review supplied that missing constraint before completion. diff --git a/specs/change/20260912-issue-spec-v2-directory-manifest/spec.md b/specs/change/20260912-issue-spec-v2-directory-manifest/spec.md new file mode 100644 index 0000000..a2225bf --- /dev/null +++ b/specs/change/20260912-issue-spec-v2-directory-manifest/spec.md @@ -0,0 +1,69 @@ +--- +id: 20260912-issue-spec-v2-directory-manifest +name: Issue Spec V2 Directory Manifest +status: implemented +created: '2026-09-12' +--- + +## Overview + +`zest-dev dump` currently rejects historical Spec directories that contain Markdown files but no `spec.md`. Repositories that adopted Zest Dev incrementally therefore cannot archive those directories without manufacturing false Main Spec File content. + +Change Issue Spec Representation writes to a V2 directory-manifest format for every Spec directory. V2 must preserve the complete Markdown file path/content set whether or not `spec.md` exists, while `load` remains compatible with existing V1 archives. Local dry-run/file loading and remote GitHub dump/loading must share the same representation behavior and continue to fail visibly on malformed or incomplete protocol data. + +The change does not make Issue Spec Representation a general filesystem archive: ordinary non-Markdown files remain outside the represented file set, and unsupported filesystem entries remain errors. + +## Design + +### Summary + +Make V2 the only format emitted by `dump` and retain V1 as a load-only compatibility format. Every V2 issue body carries a complete, deterministic Markdown file manifest and an optional `body-path`; when `spec.md` exists it remains the body payload, otherwise every file is represented by a protocol comment. `load` validates the manifest against the body and protocol comments before writing through the existing temporary-directory boundary. + +See [design.md](./design.md) for the Design Record. + +### E2E Acceptance Gate (EAG) + +Acceptance behavior: A nested Markdown-only Spec directory without `spec.md` can be dumped through V2 and loaded with an identical Markdown path/content set, while a normal Spec is also emitted as V2 and historical V1 input remains loadable. + +Verification path: `cd e2e && env UV_CACHE_DIR=/tmp/zest-dev-uv-cache uv run pytest -q tests/test_issue_dump_load.py -k 'v2_directory_manifest'` + +## Plan + +### Ticket 1 (AFK): V2 Directory Manifest Round Trip + +Goal: Dump and load any non-empty Markdown Spec directory through one lossless V2 representation. +Scope: Add version-aware protocol parsing/rendering, emit a complete manifest for all dumps, support optional body payloads, validate manifest completeness, preserve nested paths and exact content, and add local E2E coverage for directories with and without `spec.md`. +Depends on: None + +### Ticket 2 (AFK): Compatibility And Transport Stabilization + +Goal: Preserve historical archives and prove V2 uses the existing GitHub transport without weakening failure behavior. +Scope: Retain V1 loading, cover remote legacy-directory round trips through the fake `gh` boundary, add malformed/incomplete V2 cases, and keep truthful load metadata when no Main Spec File exists. +Depends on: Ticket 1 + +### Ticket 3 (AFK): EAG Validation + +Goal: Validate the finished behavior through the Spec's E2E Acceptance Gate. +Scope: Run the Design EAG and the complete local E2E suite after functional tickets are complete. +Depends on: Ticket 2 + +### Ticket 4 (AFK): Documentation Sync + +Goal: Align the Issue Spec Representation contract and user-facing behavior with V2. +Scope: Document V2 writes, V1 read compatibility, optional body payloads, manifest validation, Markdown-only scope, and current failure rules. +Depends on: Ticket 3 + +## Progress + +- [x] Ticket 1 (AFK): V2 Directory Manifest Round Trip +- [x] Ticket 2 (AFK): Compatibility And Transport Stabilization +- [x] Ticket 3 (AFK): EAG Validation +- [x] Ticket 4 (AFK): Documentation Sync + +## Implementation + +See [implementation.md](./implementation.md). + +## Deferred Follow-Ups (DFU) + +None.