You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
As a developer installing KB packages from external sources (ZIP files, URLs) I want to verify package integrity before installation using pair kb verify <package> and automatic verification during pair install So that I can trust the KB content has not been corrupted or tampered with, preventing broken installations and ensuring security
Refined: Story is detailed, estimated, and ready for development ✅
In Progress: Story is actively being developed
Done: Story delivered and accepted ✅
Acceptance Criteria
Functional Requirements
Given-When-Then Format:
Given a valid KB package ZIP created by pair kb package When user runs pair kb verify my-kb.zip Then system outputs a verification report showing: checksum status (PASS), structure validation (PASS), manifest validation (PASS), overall result (PASS), and exits with code 0
Given a KB package ZIP with corrupted content (file bytes modified after packaging) When user runs pair kb verify corrupted-kb.zip Then system outputs a verification report showing checksum status (FAIL) with expected vs actual SHA-256 hashes, overall result (FAIL), and exits with code 1
Given a ZIP file missing required .pair/ directory structure When user runs pair kb verify incomplete-kb.zip Then system outputs a verification report showing structure validation (FAIL) listing missing required directories, overall result (FAIL), and exits with code 1
Given a ZIP file with missing or malformed manifest.json When user runs pair kb verify no-manifest-kb.zip Then system outputs a verification report showing manifest validation (FAIL) with specific error (missing file or invalid JSON or missing required fields), overall result (FAIL), and exits with code 1
Given a valid KB package ZIP and pair install --source ./my-kb.zip When user runs the install command Then system automatically verifies the package before extraction, displays brief verification status ("Verification passed"), and proceeds with installation
Given an invalid KB package ZIP and pair install --source ./bad-kb.zip When user runs the install command Then system automatically verifies the package, displays verification failure details, aborts installation with error message "Package verification failed. Use --skip-verify to bypass.", and exits with code 1
Given an invalid KB package ZIP When user runs pair install --source ./bad-kb.zip --skip-verify Then system skips verification entirely, displays warning "Skipping package verification (--skip-verify)", and proceeds with installation normally
Given user wants machine-readable output When user runs pair kb verify my-kb.zip --json Then system outputs the verification report as a JSON object with fields: { package, timestamp, checks: { checksum, structure, manifest }, overall } and exits with appropriate code
Given a file path that does not exist When user runs pair kb verify nonexistent.zip Then system outputs error "File not found: nonexistent.zip" and exits with code 1
Given a file that is not a valid ZIP archive When user runs pair kb verify not-a-zip.txt Then system outputs error "Invalid ZIP archive: not-a-zip.txt" and exits with code 1
Business Rules
Checksum algorithm: SHA-256 (matches existing calculateSHA256 in @pair/content-ops)
Checksum storage: SHA-256 hash of the packaged content stored in manifest.json field contentChecksum during pair kb package
Verification order: checksum first, then structure, then manifest fields (fail-fast on checksum)
Default behavior during install: verification is ON; opt-out with --skip-verify
Performance target: verification completes in <5 seconds for packages up to 100MB
Exit codes: 0 = all checks pass, 1 = any check fails or error
Final Story Points: 3 Confidence Level: High Sizing Justification: Most cryptographic and ZIP infrastructure already exists in @pair/content-ops (calculateSHA256, validateChecksum, extractZip, adm-zip). The manifest metadata interface (ManifestMetadata) is defined. The command pattern (parser/handler/metadata) is well-established with 6 existing commands to follow. Primary new work is: (1) wiring verification checks into a new command, (2) adding checksum to package creation, (3) integrating verification hook into install flow. No spikes needed.
Sprint Capacity Validation
Sprint Fit Assessment: Fits within a single sprint Development Time Estimate: 2-3 days for a developer familiar with the codebase Testing Time Estimate: Included in development estimate Total Effort Assessment: Fits within sprint capacity: Yes
Story Splitting Recommendations
No splitting needed. The 3 logical units (standalone command, install integration, package checksum) are tightly coupled and individually non-valuable.
Dependencies and Coordination
Story Dependencies
Package KB Content #73 (Package KB Content): DONE. Provides the packaging command that creates ZIPs with manifest.json. This story extends it with contentChecksum.
Validate KB Content #74 (Validate KB Content): DONE. Provides pair kb-validate for structure validation. This story adds ZIP-level verification as a distinct concern.
Skip-verify: Confirm installation proceeds despite invalid package when flag is set
User Validation
Demo: verify a valid package (PASS), then corrupt it and verify again (FAIL)
Demo: attempt install with corrupted package (blocked), then with --skip-verify (proceeds)
Notes and Additional Context
Refinement Session Insights
Verification is intentionally separate from pair kb-validate (which validates an installed/extracted KB directory). pair kb verify operates on ZIP files pre-installation.
The contentChecksum in manifest.json is a SHA-256 hash computed over all non-manifest files in the ZIP during packaging. This enables detecting tampering even without an external .sha256 file.
The existing checksumManager.validateFileWithRemoteChecksum in kb-installer.ts handles remote download checksums (.sha256 sidecar files). This story adds local package verification which is complementary.
Team Concerns
None identified. Well-established patterns and libraries.
Future Considerations
Digital signatures: Future enhancement could add GPG/PGP signature verification for organizational trust chains (explicitly out of scope per epic Simple KB Distribution & Installation #65).
Content-level validation: Post-extraction content validation (link integrity, completeness) is covered by Validate KB Content #74pair kb-validate, not this story.
Remote URL verification: The existing checksumManager handles .sha256 sidecar files for remote downloads. This story's verification could be extended to remote sources in a future story.
Technical Analysis
Implementation Approach
Technical Strategy: Add a new kb-verify command following the established command pattern (parser + handler + metadata + index). Extend pair kb package to embed a contentChecksum field in manifest.json. Hook verification into installKBFromLocalZip with opt-out flag.
Key Components:
apps/pair-cli/src/commands/kb-verify/ (new command directory)
parser.ts: Parse <package> positional arg + --json flag
handler.ts: Orchestrate verification checks, format output
metadata.ts: Command help text, examples, options
index.ts: Re-export for command registry
Verification engine (in handler or extracted utility)
verifyChecksum(zipPath, manifest): Compare contentChecksum from manifest against computed SHA-256 of ZIP content files
verifyStructure(zipEntries, manifest): Check that registry directories declared in manifest.registries exist in the ZIP
verifyManifest(manifestContent): Validate required fields exist and are valid types
Package checksum embedding (modify existing)
Extend createPackageZip in apps/pair-cli/src/commands/package/zip-creator.ts: After copying registry sources to temp dir, compute SHA-256 over all files, add contentChecksum to manifest before writing
Install integration (modify existing)
Add --skip-verify to InstallCommandConfig discriminated union in install/parser.ts
Add verification step in installKBFromLocalZip in kb-manager/kb-installer.ts before extractZip/finalizeZipInstall
Summary: Extend pair kb package to compute SHA-256 over all non-manifest content files in the temp directory, then embed the hash as contentChecksum in manifest.json before creating the ZIP.
Type: Feature Implementation
Description: Currently createPackageZip writes manifest.json first, then copies registry sources, then zips everything. The checksum must be computed after all content files are copied but before the manifest is finalized. This requires reordering: (1) copy registry sources to temp, (2) compute SHA-256 over all temp files, (3) write manifest with contentChecksum, (4) create ZIP. The ManifestMetadata interface gains an optional contentChecksum field — optional so existing consumers don't break.
Acceptance Criteria:
Primary deliverable: manifest.json inside packaged ZIPs contains contentChecksum field with valid SHA-256 hex string
Quality standard: Unit tests verify checksum is present and deterministic (same content → same hash)
Integration requirement: Existing pair kb package behavior unchanged except for added field
Compatibility: contentChecksum is optional — old consumers ignore it
Implementation Approach:
Technical Design: Reorder createPackageZip to copy content first, then compute hash, then write manifest
Bounded Context & Modules: Knowledge Base Management — packaging subsystem
Files to Modify/Create:
apps/pair-cli/src/commands/package/metadata.ts — Add optional contentChecksum: string to ManifestMetadata
apps/pair-cli/src/commands/package/zip-creator.ts — Reorder to compute hash before manifest write, add computeContentChecksum helper
apps/pair-cli/src/commands/package/zip-creator.test.ts — Tests for checksum embedding
Dependencies:
Technical: calculateSHA256 from @pair/content-ops, createHash from Node.js crypto
Tasks: None (first in chain)
Implementation Steps:
Add contentChecksum?: string to ManifestMetadata interface in metadata.ts
Extract content-copy logic in createPackageZip to run before manifest write
Add computeContentChecksum(tempDir, fsService) that walks all files in temp dir, concatenates their SHA-256 hashes in sorted order, and produces a final hash
Pass computed checksum into manifest object before calling writeManifest
Write unit tests: verify checksum present, verify deterministic, verify existing packaging still works
Testing Strategy:
Unit Tests: Test computeContentChecksum produces consistent hash; test ManifestMetadata with checksum field; test full createPackageZip includes checksum in manifest
Integration Tests: Package → extract → parse manifest → verify contentChecksum field exists and is 64-char hex
Manual Testing: Run pair package, unzip output, inspect manifest.json
Notes: The hash is computed over content files sorted by path to ensure deterministic ordering regardless of filesystem traversal order.
T-2: Create kb-verify command with verification engine
Summary: Create the standalone pair kb-verify <package> command that performs checksum, structure, and manifest verification on a KB package ZIP, with human-readable and --json output modes.
Type: Feature Implementation
Description: New command following the established parser/handler/metadata/index pattern. The handler opens the ZIP with adm-zip, extracts and validates manifest.json, computes SHA-256 over non-manifest entries to compare with contentChecksum, and verifies that registry directories declared in manifest.registries exist as ZIP entries. Output is a verification report (human-readable by default, JSON with --json flag). Exits 0 on all-pass, 1 on any failure.
Acceptance Criteria:
Primary deliverable: pair kb-verify command registered and functional with checksum/structure/manifest checks
Quality standard: Full unit test coverage for each check; edge cases (corrupted ZIP, empty ZIP, missing manifest, non-ZIP file, nonexistent path) all handled
Integration requirement: Registered in commandRegistry in commands/index.ts; CommandConfig union extended
Verification method: Run against valid package (PASS), corrupted package (FAIL checksum), incomplete package (FAIL structure), no-manifest package (FAIL manifest)
Technical Requirements:
Functionality: 3 verification checks (checksum, structure, manifest) with fail-fast on checksum; --json flag for machine-readable output
Implement checks/structure-check.ts — verify each registries entry has corresponding directory in ZIP entries
Implement checks/checksum-check.ts — compute SHA-256 over non-manifest ZIP entries, compare with manifest.contentChecksum
Implement report-formatter.ts — format check results as human-readable table or JSON
Implement handler.ts — orchestrate: validate file exists + is ZIP, run checks in order (checksum → structure → manifest), format output, set exit code
Create index.ts re-exports
Register in commands/index.ts — add to imports, CommandConfig union, and commandRegistry
Write unit tests for parser, each check, report formatter, and handler
Testing Strategy:
Unit Tests: Parser option parsing; each check function (PASS and FAIL cases); report formatter (human + JSON); handler integration with mock ZIP data using InMemoryFileSystemService
Integration Tests: End-to-end: create valid ZIP → verify (PASS); corrupt ZIP → verify (FAIL checksum); remove dir from ZIP → verify (FAIL structure); remove manifest field → verify (FAIL manifest)
Notes:adm-zip can read ZIP entries without extracting to disk — use getEntries() to inspect structure and readAsText('manifest.json') for manifest. For checksum, iterate entries and hash content buffers.
T-3: Integrate auto-verification into install flow
Summary: Add --skip-verify flag to the install command parser and hook automatic package verification into installKBFromLocalZip (and resolveLocalDataset for ZIP paths) so that local ZIP installations are verified by default before extraction.
Type: Feature Implementation
Description: When pair install --source ./my-kb.zip is invoked, the system should automatically run the same verification checks from T-2 before extracting the ZIP. If verification fails, abort with a clear message suggesting --skip-verify. The --skip-verify flag bypasses verification with a warning. This hooks into installKBFromLocalZip in kb-installer.ts and the install parser in install/parser.ts.
Quality standard: Unit tests for parser flag, integration test for verify-then-install and skip-verify flows
Integration requirement: No change to pair install default behavior (no source = no verification); verification only on local ZIP sources
Verification method: Install valid ZIP (proceeds), install invalid ZIP (aborts with message), install invalid ZIP with --skip-verify (proceeds with warning)
Technical Requirements:
Functionality: Auto-verification on local ZIP install; --skip-verify opt-out flag; clear error message on failure
Performance: Adds <5s to install for packages up to 100MB
Security: Prevents installing tampered/corrupted packages by default
Compatibility: --skip-verify provides escape hatch; no breaking changes to existing install behavior
Implementation Approach:
Technical Design: Add skipVerify?: boolean to all InstallCommandConfig variants. In installKBFromLocalZip, call verification checks before performExtractForZip. If verification fails and skipVerify is false, throw with actionable message. Pass skipVerify through resolveLocalDataset → installKBFromLocalZip.
apps/pair-cli/src/commands/install/parser.ts — Add --skip-verify option, add skipVerify field to config interfaces
apps/pair-cli/src/commands/install/metadata.ts — Add --skip-verify to options list and notes
apps/pair-cli/src/kb-manager/kb-installer.ts — Add verification step in installKBFromLocalZip before extraction
apps/pair-cli/src/config/kb-resolver.ts — Pass skipVerify through resolveLocalDataset
apps/pair-cli/src/commands/install/parser.test.ts — Tests for --skip-verify parsing
apps/pair-cli/src/kb-manager/kb-installer.test.ts — Tests for verification integration
Dependencies:
Technical: Verification checks from T-2 (checks/ modules), adm-zip
Tasks: T-2 (needs verification engine)
Implementation Steps:
Add skipVerify?: boolean to InstallCommandConfigLocal (and optionally other variants for type consistency) in install/parser.ts
Add --skip-verify option parsing in parseInstallCommand
Add --skip-verify to installMetadata options array in install/metadata.ts
Create a verifyPackage(zipPath, fs) function (or import from kb-verify checks) that runs checksum + structure + manifest checks and returns pass/fail
In installKBFromLocalZip, add verification step before performExtractForZip: if skipVerify is false (default), call verifyPackage; on failure, throw "Package verification failed. Use --skip-verify to bypass."
Thread skipVerify parameter through resolveLocalDataset in kb-resolver.ts
If skipVerify is true, log warning "Skipping package verification (--skip-verify)" and proceed
Write unit tests for parser, integration tests for install-with-verify and skip-verify flows
Testing Strategy:
Unit Tests: Parser correctly extracts --skip-verify flag; installKBFromLocalZip calls verification when skipVerify is false; verification is skipped when skipVerify is true
Notes: The verification function should be importable from the kb-verify command's checks modules to avoid duplication. Consider extracting a shared verifyPackageZip(zipPath, fs) utility that both the standalone command and the install hook can call.
T-4: Update CLI documentation for kb-verify command and --skip-verify flag
Summary: Update all relevant documentation files to reflect the new pair kb-verify standalone command and the --skip-verify flag on pair install.
Type: Documentation
Description: Multiple documentation files reference CLI commands and need updating. The new pair kb-verify command must be added to all command listings with full usage documentation. The --skip-verify flag must be added to the install command reference. Workflow guides should include verification examples and the package→verify→install roundtrip.
Acceptance Criteria:
Primary deliverable: All doc files updated with kb-verify command reference and --skip-verify flag documentation
Quality standard: Documentation is accurate, consistent with implementation, includes examples for both human-readable and JSON output modes
Integration requirement: No code changes; documentation only
Verification method: Manual review; all referenced flags and commands match implementation
Implementation Approach:
Technical Design: Documentation-only changes across multiple files
Bounded Context and Modules: KB Management — documentation
Update README.md: Add pair kb-verify to root command list
Verify all documentation is consistent with implementation
Testing Strategy:
Manual review of all updated docs for accuracy and completeness
Verify examples match the exact CLI flag names and output formats from implementation
Notes: Follow existing documentation style and formatting conventions. Include both human-readable and --json output examples for kb-verify. Document the automatic verification behavior during pair install and the --skip-verify escape hatch.
Resolution
Delivered by PR #138 (merged). Board: Done.
feat: KB package integrity verification.
Story Statement
As a developer installing KB packages from external sources (ZIP files, URLs)
I want to verify package integrity before installation using
pair kb verify <package>and automatic verification duringpair installSo that I can trust the KB content has not been corrupted or tampered with, preventing broken installations and ensuring security
Where: Command-line interface (
pair kb verifystandalone command + automatic hook inpair install)Epic Context
Parent Epic: #65 Enhanced CLI Packaging & Distribution
Status: Done
Priority: P1 (Should-Have)
Status Workflow
Acceptance Criteria
Functional Requirements
Given-When-Then Format:
Given a valid KB package ZIP created by
pair kb packageWhen user runs
pair kb verify my-kb.zipThen system outputs a verification report showing: checksum status (PASS), structure validation (PASS), manifest validation (PASS), overall result (PASS), and exits with code 0
Given a KB package ZIP with corrupted content (file bytes modified after packaging)
When user runs
pair kb verify corrupted-kb.zipThen system outputs a verification report showing checksum status (FAIL) with expected vs actual SHA-256 hashes, overall result (FAIL), and exits with code 1
Given a ZIP file missing required
.pair/directory structureWhen user runs
pair kb verify incomplete-kb.zipThen system outputs a verification report showing structure validation (FAIL) listing missing required directories, overall result (FAIL), and exits with code 1
Given a ZIP file with missing or malformed
manifest.jsonWhen user runs
pair kb verify no-manifest-kb.zipThen system outputs a verification report showing manifest validation (FAIL) with specific error (missing file or invalid JSON or missing required fields), overall result (FAIL), and exits with code 1
Given a valid KB package ZIP and
pair install --source ./my-kb.zipWhen user runs the install command
Then system automatically verifies the package before extraction, displays brief verification status ("Verification passed"), and proceeds with installation
Given an invalid KB package ZIP and
pair install --source ./bad-kb.zipWhen user runs the install command
Then system automatically verifies the package, displays verification failure details, aborts installation with error message "Package verification failed. Use --skip-verify to bypass.", and exits with code 1
Given an invalid KB package ZIP
When user runs
pair install --source ./bad-kb.zip --skip-verifyThen system skips verification entirely, displays warning "Skipping package verification (--skip-verify)", and proceeds with installation normally
Given user wants machine-readable output
When user runs
pair kb verify my-kb.zip --jsonThen system outputs the verification report as a JSON object with fields:
{ package, timestamp, checks: { checksum, structure, manifest }, overall }and exits with appropriate codeGiven a file path that does not exist
When user runs
pair kb verify nonexistent.zipThen system outputs error "File not found: nonexistent.zip" and exits with code 1
Given a file that is not a valid ZIP archive
When user runs
pair kb verify not-a-zip.txtThen system outputs error "Invalid ZIP archive: not-a-zip.txt" and exits with code 1
Business Rules
calculateSHA256in@pair/content-ops)manifest.jsonfieldcontentChecksumduringpair kb package--skip-verifyname,version,created_at,registries(matchingManifestMetadatainterface)manifest.jsonregistriesarray)Edge Cases and Error Handling
createReadStreamregistriesreferences missing directories: report each missing directory in structure checkpair kb packagebehavior)Definition of Done Checklist
Development Completion
pair kb verify <package>command implemented inapps/pair-cli/src/commands/kb-verify/--jsonflag outputs machine-readable verification report--skip-verifyflag added topair installcommand parserinstallKBFromLocalZipinkb-installer.tspair kb packageupdated to compute and embedcontentChecksuminmanifest.jsonQuality Assurance
InMemoryFileSystemService--jsonoutput format--skip-verifyflag in install parserpnpm --filter @pair/pair-cli test)pnpm quality-gate)Deployment and Release
commandRegistryincommands/index.tspair installbehavior (verify is additive)Code Review and Delivery
001232e)Story Sizing and Sprint Readiness
Refined Story Points
Final Story Points: 3
Confidence Level: High
Sizing Justification: Most cryptographic and ZIP infrastructure already exists in
@pair/content-ops(calculateSHA256,validateChecksum,extractZip,adm-zip). The manifest metadata interface (ManifestMetadata) is defined. The command pattern (parser/handler/metadata) is well-established with 6 existing commands to follow. Primary new work is: (1) wiring verification checks into a new command, (2) adding checksum to package creation, (3) integrating verification hook into install flow. No spikes needed.Sprint Capacity Validation
Sprint Fit Assessment: Fits within a single sprint
Development Time Estimate: 2-3 days for a developer familiar with the codebase
Testing Time Estimate: Included in development estimate
Total Effort Assessment: Fits within sprint capacity: Yes
Story Splitting Recommendations
No splitting needed. The 3 logical units (standalone command, install integration, package checksum) are tightly coupled and individually non-valuable.
Dependencies and Coordination
Story Dependencies
manifest.json. This story extends it withcontentChecksum.pair kb-validatefor structure validation. This story adds ZIP-level verification as a distinct concern.installKBFromLocalZipwhere auto-verification hooks in.Team Coordination
External Dependencies
adm-zip(already independenciesfor both@pair/content-opsand@pair/pair-cli)cryptomodule (built-in, already used byintegrity-validator.ts)Validation and Testing Strategy
Acceptance Testing Approach
pair install --sourcewith both valid and invalid packagesUser Validation
--skip-verify(proceeds)Notes and Additional Context
Refinement Session Insights
pair kb-validate(which validates an installed/extracted KB directory).pair kb verifyoperates on ZIP files pre-installation.contentChecksumin manifest.json is a SHA-256 hash computed over all non-manifest files in the ZIP during packaging. This enables detecting tampering even without an external.sha256file.checksumManager.validateFileWithRemoteChecksuminkb-installer.tshandles remote download checksums (.sha256sidecar files). This story adds local package verification which is complementary.Team Concerns
Future Considerations
pair kb-validate, not this story.checksumManagerhandles.sha256sidecar files for remote downloads. This story's verification could be extended to remote sources in a future story.Technical Analysis
Implementation Approach
Technical Strategy: Add a new
kb-verifycommand following the established command pattern (parser + handler + metadata + index). Extendpair kb packageto embed acontentChecksumfield inmanifest.json. Hook verification intoinstallKBFromLocalZipwith opt-out flag.Key Components:
apps/pair-cli/src/commands/kb-verify/(new command directory)parser.ts: Parse<package>positional arg +--jsonflaghandler.ts: Orchestrate verification checks, format outputmetadata.ts: Command help text, examples, optionsindex.ts: Re-export for command registryVerification engine (in handler or extracted utility)
verifyChecksum(zipPath, manifest): ComparecontentChecksumfrom manifest against computed SHA-256 of ZIP content filesverifyStructure(zipEntries, manifest): Check that registry directories declared inmanifest.registriesexist in the ZIPverifyManifest(manifestContent): Validate required fields exist and are valid typesPackage checksum embedding (modify existing)
createPackageZipinapps/pair-cli/src/commands/package/zip-creator.ts: After copying registry sources to temp dir, compute SHA-256 over all files, addcontentChecksumto manifest before writingInstall integration (modify existing)
--skip-verifytoInstallCommandConfigdiscriminated union ininstall/parser.tsinstallKBFromLocalZipinkb-manager/kb-installer.tsbeforeextractZip/finalizeZipInstallData Flow (standalone
pair kb verify):adm-zip, readmanifest.jsonentrymanifest.contentChecksummanifest.registriesexist as ZIP entriesTechnical Requirements
calculateSHA256from@pair/content-ops/file-system/integrity-validatorfor checksum computationadm-zip(already a dependency) for reading ZIP entries without full extractionManifestMetadatainterface fromapps/pair-cli/src/commands/package/metadata.ts, extending it with optionalcontentChecksum: stringFileSystemService{ "package": "my-kb.zip", "timestamp": "2026-02-14T10:00:00Z", "checks": { "checksum": { "status": "PASS|FAIL", "expected": "abc...", "actual": "abc...", "algorithm": "SHA-256" }, "structure": { "status": "PASS|FAIL", "requiredPaths": ["knowledge", "skills"], "missingPaths": [] }, "manifest": { "status": "PASS|FAIL", "errors": [] } }, "overall": "PASS|FAIL" }Technical Risks and Mitigation
adm-zipfails on corrupted ZIP before we can read manifestcreateHash('sha256')+ iterating entries; <5s targetManifestMetadatabreaks existing package consumerscontentChecksumis optional field; existing consumers ignore unknown fields--skip-verifyin install could confuse users unfamiliar with it--help; not prompted during normal flowSpike Requirements
None. All technologies and patterns are already proven in the codebase:
packages/content-ops/src/file-system/integrity-validator.tsadm-zipused infile-system-service.tsandarchive-operations.tsapps/pair-cli/src/commands/apps/pair-cli/src/commands/package/metadata.tsTask Breakdown
contentChecksumin manifest during packagingkb-verifycommand with verification engineDependency Graph
AC Coverage
T-1: Embed
contentChecksumin manifest during packagingPriority: P0 | Estimated Hours: 2h | Bounded Context: Knowledge Base Management
Summary: Extend
pair kb packageto compute SHA-256 over all non-manifest content files in the temp directory, then embed the hash ascontentChecksuminmanifest.jsonbefore creating the ZIP.Type: Feature Implementation
Description: Currently
createPackageZipwritesmanifest.jsonfirst, then copies registry sources, then zips everything. The checksum must be computed after all content files are copied but before the manifest is finalized. This requires reordering: (1) copy registry sources to temp, (2) compute SHA-256 over all temp files, (3) write manifest withcontentChecksum, (4) create ZIP. TheManifestMetadatainterface gains an optionalcontentChecksumfield — optional so existing consumers don't break.Acceptance Criteria:
manifest.jsoninside packaged ZIPs containscontentChecksumfield with valid SHA-256 hex stringpair kb packagebehavior unchanged except for added fieldcontentChecksummatches manual SHA-256 computationTechnical Requirements:
contentChecksumis optional — old consumers ignore itImplementation Approach:
createPackageZipto copy content first, then compute hash, then write manifestapps/pair-cli/src/commands/package/metadata.ts— Add optionalcontentChecksum: stringtoManifestMetadataapps/pair-cli/src/commands/package/zip-creator.ts— Reorder to compute hash before manifest write, addcomputeContentChecksumhelperapps/pair-cli/src/commands/package/zip-creator.test.ts— Tests for checksum embeddingDependencies:
calculateSHA256from@pair/content-ops,createHashfrom Node.jscryptoImplementation Steps:
contentChecksum?: stringtoManifestMetadatainterface inmetadata.tscreatePackageZipto run before manifest writecomputeContentChecksum(tempDir, fsService)that walks all files in temp dir, concatenates their SHA-256 hashes in sorted order, and produces a final hashmanifestobject before callingwriteManifestTesting Strategy:
computeContentChecksumproduces consistent hash; testManifestMetadatawith checksum field; test fullcreatePackageZipincludes checksum in manifestcontentChecksumfield exists and is 64-char hexpair package, unzip output, inspectmanifest.jsonNotes: The hash is computed over content files sorted by path to ensure deterministic ordering regardless of filesystem traversal order.
T-2: Create
kb-verifycommand with verification enginePriority: P0 | Estimated Hours: 6h | Bounded Context: Knowledge Base Management
Summary: Create the standalone
pair kb-verify <package>command that performs checksum, structure, and manifest verification on a KB package ZIP, with human-readable and--jsonoutput modes.Type: Feature Implementation
Description: New command following the established parser/handler/metadata/index pattern. The handler opens the ZIP with
adm-zip, extracts and validatesmanifest.json, computes SHA-256 over non-manifest entries to compare withcontentChecksum, and verifies that registry directories declared inmanifest.registriesexist as ZIP entries. Output is a verification report (human-readable by default, JSON with--jsonflag). Exits 0 on all-pass, 1 on any failure.Acceptance Criteria:
pair kb-verifycommand registered and functional with checksum/structure/manifest checkscommandRegistryincommands/index.ts;CommandConfigunion extendedTechnical Requirements:
--jsonflag for machine-readable outputImplementation Approach:
<package>positional +--jsonflag. Handler orchestrates 3 check functions and formats output. Each check returns{ status: 'PASS'|'FAIL', details }.apps/pair-cli/src/commands/kb-verify/parser.ts— Parse<package>positional +--jsonflag →KbVerifyCommandConfigapps/pair-cli/src/commands/kb-verify/handler.ts— Orchestrate checks, format outputapps/pair-cli/src/commands/kb-verify/metadata.ts— Command help, examples, optionsapps/pair-cli/src/commands/kb-verify/index.ts— Re-exportsapps/pair-cli/src/commands/kb-verify/checks/checksum-check.ts— SHA-256 verification againstcontentChecksumapps/pair-cli/src/commands/kb-verify/checks/structure-check.ts— Verify registry dirs exist in ZIPapps/pair-cli/src/commands/kb-verify/checks/manifest-check.ts— Validate manifest required fieldsapps/pair-cli/src/commands/kb-verify/report-formatter.ts— Human-readable + JSON formattersapps/pair-cli/src/commands/index.ts— Registerkb-verifyincommandRegistryandCommandConfigunionapps/pair-cli/src/commands/kb-verify/*.test.ts— Unit testsDependencies:
adm-zip,calculateSHA256from@pair/content-ops,ManifestMetadatafrom package/metadatacontentChecksumin manifest for checksum verification to be meaningful)Implementation Steps:
apps/pair-cli/src/commands/kb-verify/directoryparser.tswithKbVerifyCommandConfiginterface andparseKbVerifyCommandfunctionmetadata.tswith command help, examples, and optionschecks/manifest-check.ts— extract manifest.json from ZIP, validate required fields (name,version,created_at,registries)checks/structure-check.ts— verify eachregistriesentry has corresponding directory in ZIP entrieschecks/checksum-check.ts— compute SHA-256 over non-manifest ZIP entries, compare withmanifest.contentChecksumreport-formatter.ts— format check results as human-readable table or JSONhandler.ts— orchestrate: validate file exists + is ZIP, run checks in order (checksum → structure → manifest), format output, set exit codeindex.tsre-exportscommands/index.ts— add to imports,CommandConfigunion, andcommandRegistryTesting Strategy:
InMemoryFileSystemServicepair kb-verify valid.zip,pair kb-verify valid.zip --json,pair kb-verify bad.zipNotes:
adm-zipcan read ZIP entries without extracting to disk — usegetEntries()to inspect structure andreadAsText('manifest.json')for manifest. For checksum, iterate entries and hash content buffers.T-3: Integrate auto-verification into install flow
Priority: P0 | Estimated Hours: 3h | Bounded Context: Knowledge Base Management
Summary: Add
--skip-verifyflag to the install command parser and hook automatic package verification intoinstallKBFromLocalZip(andresolveLocalDatasetfor ZIP paths) so that local ZIP installations are verified by default before extraction.Type: Feature Implementation
Description: When
pair install --source ./my-kb.zipis invoked, the system should automatically run the same verification checks from T-2 before extracting the ZIP. If verification fails, abort with a clear message suggesting--skip-verify. The--skip-verifyflag bypasses verification with a warning. This hooks intoinstallKBFromLocalZipinkb-installer.tsand the install parser ininstall/parser.ts.Acceptance Criteria:
pair install --source ./local.zipauto-verifies before extraction;--skip-verifybypassespair installdefault behavior (no source = no verification); verification only on local ZIP sources--skip-verify(proceeds with warning)Technical Requirements:
--skip-verifyopt-out flag; clear error message on failure--skip-verifyprovides escape hatch; no breaking changes to existing install behaviorImplementation Approach:
skipVerify?: booleanto allInstallCommandConfigvariants. IninstallKBFromLocalZip, call verification checks beforeperformExtractForZip. If verification fails andskipVerifyis false, throw with actionable message. PassskipVerifythroughresolveLocalDataset→installKBFromLocalZip.apps/pair-cli/src/commands/install/parser.ts— Add--skip-verifyoption, addskipVerifyfield to config interfacesapps/pair-cli/src/commands/install/metadata.ts— Add--skip-verifyto options list and notesapps/pair-cli/src/kb-manager/kb-installer.ts— Add verification step ininstallKBFromLocalZipbefore extractionapps/pair-cli/src/config/kb-resolver.ts— PassskipVerifythroughresolveLocalDatasetapps/pair-cli/src/commands/install/parser.test.ts— Tests for--skip-verifyparsingapps/pair-cli/src/kb-manager/kb-installer.test.ts— Tests for verification integrationDependencies:
checks/modules),adm-zipImplementation Steps:
skipVerify?: booleantoInstallCommandConfigLocal(and optionally other variants for type consistency) ininstall/parser.ts--skip-verifyoption parsing inparseInstallCommand--skip-verifytoinstallMetadataoptions array ininstall/metadata.tsverifyPackage(zipPath, fs)function (or import from kb-verify checks) that runs checksum + structure + manifest checks and returns pass/failinstallKBFromLocalZip, add verification step beforeperformExtractForZip: ifskipVerifyis false (default), callverifyPackage; on failure, throw "Package verification failed. Use --skip-verify to bypass."skipVerifyparameter throughresolveLocalDatasetinkb-resolver.tsskipVerifyis true, log warning "Skipping package verification (--skip-verify)" and proceedTesting Strategy:
--skip-verifyflag;installKBFromLocalZipcalls verification whenskipVerifyis false; verification is skipped whenskipVerifyis truepair install --source ./valid.zip,pair install --source ./bad.zip,pair install --source ./bad.zip --skip-verifyNotes: The verification function should be importable from the kb-verify command's checks modules to avoid duplication. Consider extracting a shared
verifyPackageZip(zipPath, fs)utility that both the standalone command and the install hook can call.T-4: Update CLI documentation for kb-verify command and --skip-verify flag
Priority: P0 | Estimated Hours: 2h | Bounded Context: Knowledge Base Management
Summary: Update all relevant documentation files to reflect the new
pair kb-verifystandalone command and the--skip-verifyflag onpair install.Type: Documentation
Description: Multiple documentation files reference CLI commands and need updating. The new
pair kb-verifycommand must be added to all command listings with full usage documentation. The--skip-verifyflag must be added to the install command reference. Workflow guides should include verification examples and the package→verify→install roundtrip.Acceptance Criteria:
Implementation Approach:
docs/cli/commands.md— Addpair kb-verifycommand reference section with options (--json), verification checks, exit codes; add--skip-verifyto install command optionsdocs/specs/cli-contracts.md— AddKbVerifyCommandConfigtype, verification report JSON schema, updatedInstallCommandConfigwithskipVerify, updatedManifestMetadatawithcontentChecksumdocs/cli/help-examples.md— Add kb-verify usage examples (pass/fail scenarios), install with --skip-verifyapps/pair-cli/README.md— Update CLI feature overview with verification capabilitydocs/getting-started/02-cli-workflows.md— Add "Package Verification" workflow, update install workflow with auto-verification noteREADME.md— Addpair kb-verifyto root command listDependencies:
Implementation Steps:
docs/cli/commands.md: Add fullpair kb-verify <package>command reference with options (--json), verification checks (checksum, structure, manifest), exit codes (0=pass, 1=fail); add--skip-verifyto install command optionsdocs/specs/cli-contracts.md: AddKbVerifyCommandConfigtype definition, verification report JSON schema, updateInstallCommandConfigwithskipVerify?: boolean, updateManifestMetadatawithcontentChecksum?: stringdocs/cli/help-examples.md: Add verification examples (valid package, corrupted package, JSON output), install with --skip-verify exampleapps/pair-cli/README.md: Add package verification feature to CLI overviewdocs/getting-started/02-cli-workflows.md: Add "Verify KB Package" workflow section, update install workflow with auto-verification noteREADME.md: Addpair kb-verifyto root command listTesting Strategy:
Notes: Follow existing documentation style and formatting conventions. Include both human-readable and
--jsonoutput examples for kb-verify. Document the automatic verification behavior duringpair installand the--skip-verifyescape hatch.Refinement Completed By: Product Manager (AI-assisted)
Refinement Date: 2026-02-14
Review and Approval: Developer approved