diff --git a/.gitattributes b/.gitattributes index d207b18..0a3a1cd 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,2 @@ *.go text eol=lf +docs/releases/*-SHA256SUMS.txt text eol=lf diff --git a/AGENTS.md b/AGENTS.md index 798c4e5..989655b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # AGENTS.md — Engineering Mastery project policy -Work directly in the current VS Code Codex session on this original project inside the user's F: workspace. Keep the workspace manifest and progress report current. +Work directly in the current session on this original project. Keep the Engineering Mastery manifest and progress report current when working in that workspace. ## Scope and ethics - Never access, rewrite, delete or search outside the active project directory. diff --git a/CHANGELOG.md b/CHANGELOG.md index 3702d16..5a8baf0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,17 @@ # Changelog -## 0.1.0 — Release candidate +## 0.1.1 — Streaming search + +- Process files in a reusable read buffer while preserving the literal CLI contract. +- Stage matches per file and spill large result sets to temporary storage. Emit results only after complete UTF-8 and NUL checks. +- Scan oversized lines in fragments. When staging an oversized match, reread its range from the same open file and verify the copied bytes against the scan's SHA-256. +- Cover boundary-spanning literals, long lines, late invalid bytes, read errors, and spill cleanup with regression tests. +- Record elapsed time and peak process memory for the streaming candidate against `v0.1.0` on five reproducible Windows workloads. The benchmark report describes the measured inputs and the long-line tradeoffs. [Benchmark results](docs/BENCHMARKS.md) +- License the original project material under MIT and include the project license, third-party notices and dependency license texts in the binary archives. + +Download Windows amd64, Linux amd64 and macOS arm64 packages, `SHA256SUMS.txt`, and source archives from the release page. [v0.1.1 release](https://github.com/soroushneyestani/developer-cli-toolkit/releases/tag/v0.1.1) · [Release evidence](docs/RELEASE_EVIDENCE.md) + +## 0.1.0 — Initial release - Search UTF-8 text recursively for a case-sensitive literal. - Inspect regular files and report their relative paths and byte sizes. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..f40c070 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,19 @@ +# Contributing to Developer CLI Toolkit + +Use a GitHub issue for bug reports or proposals about the CLI. Show the command, `dct --version`, OS, exit status, and relevant stdout and stderr. Use a small synthetic workspace that reproduces the behavior. Report security concerns through the private process. [Security policy](SECURITY.md) + +## Build and test + +Create a topic branch from `main` in your fork or authorized checkout. Install Go 1.26 or later and PowerShell 7 on Linux or macOS. CI uses Go 1.27.4. From the project directory, run the verifier. Windows PowerShell can invoke it with `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/verify.ps1`. + +```sh +pwsh -NoProfile -File scripts/verify.ps1 +``` + +The verifier checks Go formatting, module checksums, vet, uncached tests, and the native build. Exercise changed command behavior with process-level fixtures that check stdout, stderr, and exit status. Keep sorting, symlink handling, UTF-8 validation, and error semantics covered. Document any intentional contract change and explain its compatibility impact. Cite the reproducible workload when proposing a performance change. [CLI contract](docs/SPEC.md) · [Benchmark method](docs/BENCHMARKS.md) + +## Submit a pull request + +Open a PR against `main` with the reason for the change, the tests you ran, and any limitations. Use a draft for work that still needs verification. Keep changes small enough to review and preserve the notices of any third-party material you have permission to use. The maintainer reviews changes and merges through a merge commit after CI succeeds and review conversations are resolved. [Verification workflow](.github/workflows/ci.yml) + +Submit work you have the right to contribute. Original contributions are made under the project's MIT license. Preserve existing third-party license terms and attribution. [Project license](LICENSE) · [Third-party notices](THIRD_PARTY_NOTICES.md) diff --git a/FINAL_PUBLICATION_CHECKLIST.md b/FINAL_PUBLICATION_CHECKLIST.md new file mode 100644 index 0000000..889a0d5 --- /dev/null +++ b/FINAL_PUBLICATION_CHECKLIST.md @@ -0,0 +1,45 @@ +# A02 final publication checklist + +Developer CLI Toolkit is in `release_review`. The owner authorized public release of `v0.1.1` in this repository. The historical baseline is `v0.1.0`. [PR #2](https://github.com/soroushneyestani/developer-cli-toolkit/pull/2) · [CI checks](https://github.com/soroushneyestani/developer-cli-toolkit/pull/2/checks) + +The final decisions report records the verified address categories, publication paths, and historical asset treatment. [Final publication decisions](FINAL_PUBLICATION_DECISIONS.md) + +## Source and license audit + +- [x] Matched all three remote branches and `v0.1.0` against the local refs. The pre-preparation history at `f6c3b9727c2fcfbf067de2c6472862818c6bcde7` contains 15 commits, 44 paths and 110 unique tracked blobs. Inspected the original Go source, scripts, fixtures, documentation, attribution and historical file inventory. The tracked blobs are regular UTF-8 text. The audit found no vendored application code or recorded outside contributors. One unreachable local blob was outside the ref history. +- [x] Redacted Gitleaks and focused blob and commit-message screening found no credentials or matching private paths in the reviewed refs. Screened two PRs, their conversations, one release record and 14 of 14 then-retained Actions log archives for credential and personal-data patterns. The profile-path indications matched hosted Windows runner names. Findings are scoped to the inspected records and patterns. +- [x] Prepared the standard MIT notice for original source and documentation, naming Soroush Neyestani based on recorded authorship and repository ownership. The existing third-party license texts remain in place. Verified their text against the pinned module and Go distributions. The three build dependency closures include Cobra and pflag, Go's runtime and standard library with its bundled DNS package, and mousetrap on Windows. [MIT license](LICENSE) · [Standard MIT text](https://spdx.org/licenses/MIT.html) · [Third-party notices](THIRD_PARTY_NOTICES.md) +- [x] The owner confirmed this is a personal project and authorized MIT for the original material for which they hold the necessary rights. +- [x] The owner accepted public disclosure of their own historical Git author and committer metadata. Fourteen commits include a non-GitHub-no-reply address. Its value is excluded from this checklist. The existing commits and tag preserve their original hashes. [GitHub commit email guidance](https://docs.github.com/en/account-and-profile/how-tos/email-preferences/setting-your-commit-email-address) + +## CI and release candidate + +- [x] Verified the `f6c3b972` pre-preparation head on both push and Draft PR CI. The Windows, Linux and macOS jobs and packaging passed. The local Windows verifier passed again with the expected filename and POSIX-permission fixture skips. The sharing-violation regression passed. [Push CI](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44540885418) · [PR CI](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44540899232) · [Test summary](docs/TEST_SUMMARY.md) +- [x] Reviewed full-file validation, oversized line scanning, positional rereads, match replay, spill cleanup and filesystem assumptions. Seventy-two seeded Windows comparisons against the released binary matched stdout, stderr and exit status, including buffer boundaries, UTF-8 and NUL cases and dense spill. The review found no reproducible runtime defect. +- [ ] Verify the exact stable preparation revision, merge commit, and release evidence. [PR checks](https://github.com/soroushneyestani/developer-cli-toolkit/pull/2/checks) + +## Benchmark results + +- [x] Recomputed the 50 recorded process measurements across five generated Windows workloads. The sparse 96 MiB case used 7.57 MiB median peak working set versus 57.24 MiB in `v0.1.0`, and fell from 67.403 to 56.175 ms. The unmatched 48 MiB line used 7.32 MiB versus 56.31 MiB, taking 50.269 ms versus 41.872 ms. The matching 16 MiB line used 41.28 MiB versus 56.93 MiB and took 69.589 ms versus 40.292 ms. These are measured inputs on the recorded Windows host. [Reproduction and full results](docs/BENCHMARKS.md) · [Raw samples](docs/BENCHMARKS_WINDOWS.json) + +## Release assets and complete source + +- [x] Preserved the private `v0.1.0` tag, all five existing release assets, and the earlier pinned RC evidence. Their checksums and source commits remain scoped to those exact builds. [Verified v0.1.0 provenance](docs/releases/v0.1.0.md) · [Pinned RC evidence](docs/RELEASE_EVIDENCE.md) +- [x] Built and inspected all three local preparation ZIPs for Windows amd64, Linux amd64 and macOS arm64. Checked CRC, SHA-256, architecture, the project MIT license, all four upstream license texts, and changelog. The executables match the already-reviewed RC binaries byte for byte. The ZIPs have separate checksums because their contents include new release material. +- [x] Record an express MIT grant for eligible original `v0.1.0` material. Its original archives predate the project MIT notice. [Historical grant](docs/releases/v0.1.0-MIT.md) +- [ ] After approval, verify the stable package and full source archive at the same accepted `main` commit and tag. Confirm that an unauthenticated user can read and clone the source and download the tagged source archive. The release procedure covers these checks and the stable version update. [Release procedure](docs/releases/OPEN_SOURCE_RELEASE.md) + +## GitHub configuration + +- [x] Verified private visibility, default branch `main`, enabled merge commits, and accurate project description and homepage metadata. The current `main` is unprotected. GitHub reported a plan restriction for private rulesets on this repository. +- [ ] When available, protect `main` with PRs, conversation resolution, the exact three native jobs and `Package binaries`, and block force pushes and deletion. Use the sole-maintainer workflow with zero required approving reviews. Enable private vulnerability reporting and verify its availability. [Required checks and launch settings](docs/releases/OPEN_SOURCE_RELEASE.md#github-settings-for-launch) +- [x] The owner approved visibility on this existing repository subject to the publication audit. Screen third-party data and credentials before making it public. [GitHub visibility effects](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/managing-repository-settings/setting-repository-visibility#making-a-repository-public) + +## Documentation + +- [x] Prepared source and binary instructions, contribution guidance, private reporting guidance, final learning material, and platform and performance limitations. [README](README.md) · [Contributing](CONTRIBUTING.md) · [Security policy](SECURITY.md) · [Persian learning guide](docs/LEARNING_FA.md) · [Portfolio article](docs/WEBSITE_EN.md) · [Instagram copy](docs/INSTAGRAM_EN.md) +- [ ] Verify working public release and source links. The English portfolio and Instagram copy are supplied as repository documentation. + +## Remaining risks + +The owner decisions above govern public disclosure and licensing. The public stable release requires exact post-merge CI and assets. Temporary disk can grow with dense output. The sorted paths and the largest emitted record still affect memory and the input tree needs to stay stable during execution. The benchmark samples are Windows-only, and the binaries are unsigned. [Benchmark scope](docs/BENCHMARKS.md) · [Release limits](docs/releases/OPEN_SOURCE_RELEASE.md#limits-to-disclose) diff --git a/FINAL_PUBLICATION_DECISIONS.md b/FINAL_PUBLICATION_DECISIONS.md new file mode 100644 index 0000000..8e1cc65 --- /dev/null +++ b/FINAL_PUBLICATION_DECISIONS.md @@ -0,0 +1,74 @@ +# A02 final publication decisions + +This document preserves the pre-publication audit. At its checkpoint the repository was private, `main` and `v0.1.0` pointed to `02472793619d8a644634068759ecb2e826a39797`, and PR #2 was Draft. The owner subsequently confirmed personal ownership and authority for eligible original material, consented to public disclosure of their own Git metadata, and selected publication in this existing repository with its history intact. [Historical MIT grant](docs/releases/v0.1.0-MIT.md) [PR #2](https://github.com/soroushneyestani/developer-cli-toolkit/pull/2) · [Publication checklist](FINAL_PUBLICATION_CHECKLIST.md) + +## 1. MIT and ownership + +The audited Git history and recorded provenance support original A02 development. The original Go source, scripts, tests, synthetic fixtures and documentation trace to the project owner's commits and a GitHub-generated merge. The review found no identified employer, client or unrelated-project code, vendor source import, or separately identified outside contributor. Git and GitHub record attribution and repository control. Licensing authority still depends on ownership or permission, including any employment, client, contributor or assignment terms that the repository cannot establish. There is no identified competing ownership claim. The unresolved item is the owner's confirmation that they have authority to grant MIT for the original material in the scope they approve. If any file or portion is subject to conflicting terms, identify it before publishing. [WIPO copyright guidance](https://www.wipo.int/en/web/copyright/protection) + +MIT is the selected policy for original A02 material, subject to the authority confirmation above. The root `LICENSE` uses the standard MIT text. Preserve its copyright and permission notices in copies and substantial portions of the original work. The dependency notices and terms apply to the respective third-party portions. [Project license](LICENSE) · [SPDX MIT text](https://spdx.org/licenses/MIT.html) + +| Linked component | Pinned license and distribution evidence | +| --- | --- | +| Cobra 1.10.2 | Apache-2.0. The full upstream license matches the collected text. The pinned module has no separate upstream `NOTICE` file. | +| mousetrap 1.1.0 | Apache-2.0 and linked on Windows. Its full license matches the collected text and the pinned module has no separate upstream `NOTICE` file. | +| pflag 1.0.9 | BSD-3-Clause. The collected text preserves copyright, conditions, disclaimer and non-endorsement terms. | +| Go runtime and standard library as built with Go 1.27.4 | BSD-3-Clause, including the linked Go-vendored DNS message package with the same license text. | + +The pinned module and toolchain texts match the collected texts after line-ending normalization. The audited binary ZIPs carry the four upstream texts and third-party notices. Retain full Apache license texts and applicable source notices, include supplied upstream `NOTICE` material if introduced, and mark relevant modifications to Apache-licensed files if made. Retain BSD copyright, conditions and disclaimer in the appropriate source or binary distribution material. [Bundled notices](THIRD_PARTY_NOTICES.md) · [Apache-2.0 redistribution terms](https://www.apache.org/licenses/LICENSE-2.0#redistribution) · [BSD-3-Clause text](https://spdx.org/licenses/BSD-3-Clause.html) + +## 2. Historical Git email privacy + +Compared the raw author and committer fields of all 16 commits at the audited preparation checkpoint with authenticated GitHub commit records. The 14 historical commits use one shared address in both fields. The current public GitHub profile does not list that address, and there is no verified designation for public professional contact. Treat it as potentially sensitive. The report omits address values. + +| Classification | Distinct addresses | Author fields | Committer fields | +| --- | ---: | ---: | ---: | +| GitHub noreply, owner and GitHub platform identities | 2 | 2 | 2 | +| Public professional address, confirmed | 0 | 0 | 0 | +| Personal or potentially sensitive address | 1 | 14 | 14 | + +The affected commit prefixes are `1dbf562`, `170dc70`, `6d78a2e`, `ee3cb74`, `cb952c8`, `482ebac`, `367acfe`, `1d41dcc`, `7927304`, `95fd1cc`, `1bb67e8`, `aaf9a9c`, `541aff8`, and `f6c3b97`. The signed release merge `0247279` and the preparation commit `b43e08c` use noreply in both fields. The release tag is lightweight and points directly to its commit. + +| Audited GitHub branch, tag or pull request | History or PR commit count | Commits with the potentially sensitive address | +| --- | ---: | ---: | +| `main` | 10 | 9 | +| `v0.1.0` | 10 | 9 | +| `codex/a02` | 9 | 9 | +| `codex/a02-streaming` at `b43e08c` | 16 | 14 | +| Merged PR #1, commits listed on the PR | 8 | 8 | +| Draft PR #2, commits listed on the PR at `b43e08c` | 6 | 5 | + +The server's PR head refs matched the two reviewed head commits. The temporary GitHub merge ref for Draft PR #2 used noreply metadata and also references the existing ancestry. The earlier publication preparation screened 16 retained Actions log archives and the two PR and release records for address and credential patterns. The public-disclosure decision covers the Git objects as well as the existing GitHub surface. A clone exposes the raw fields even when a profile or UI hides the email. [GitHub email settings](https://docs.github.com/en/account-and-profile/how-tos/email-preferences/setting-your-commit-email-address) · [Visibility change effects](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/managing-repository-settings/setting-repository-visibility#making-a-repository-public) + +Only the local A02 repository now has its default commit email set to the account's verified GitHub noreply. The active account ID and login matched the address already used in the release merge and preparation commit. Both effective Git identity fields resolve to noreply. This configuration applies to future commits. + +| Publication option | Effects on hashes, tags, PRs, releases and CI | +| --- | --- | +| Keep the existing repository private and publish a separate, standalone source snapshot after approval. Recommended when withholding the address. | The private repository continues to hold its original hashes, signed merge, `v0.1.0` tag, PRs, releases and CI. Export the approved source into a fresh repository with verified noreply and a separately reviewed public tree. The public repository gets its own commit hashes, PRs, tags, builds, release records and provenance. Copy source and license material without carrying private Git objects, PR threads, logs or artifacts. | +| Make the existing repository public after informed consent to disclose the address. | Existing hashes, tag, PRs, release and exact-commit CI stay attached to the same history. The raw address in 14 commits becomes accessible through the public history, including nine commits reachable from `v0.1.0`. Existing repository records and Actions history also need to be suitable for public access. | +| Rewrite the existing repository's history to change historical addresses. | Changes affected commit IDs and descendant IDs, including the signed release merge. Preserving a tag at the original SHA retains access to the old metadata. PR diffs and references can break, exact-commit CI and old release provenance refer to the original IDs, and cached objects, forks and clones can retain the old data. This conflicts with the requirement to preserve the original tag and history in place. | + +Profile settings and display aliases leave stored commit fields available. An independent source snapshot provides isolation while retaining all original private records. [GitHub's history rewrite caveats](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/removing-sensitive-data-from-a-repository) + +## 3. Historical v0.1.0 + +Live downloads of GitHub's automatic source ZIP and tarball matched all 33 files at `02472793619d8a644634068759ecb2e826a39797`. Both formats lack a project MIT `LICENSE` and contain the four upstream texts. Re-downloaded all five uploaded release assets and matched their recorded IDs, sizes and SHA-256 hashes. The three target ZIPs passed CRC and contain the third-party notice, upstream texts and changelog. They lack a project MIT notice. The published checksum file remains tied to those original ZIP bytes. [v0.1.0 release](https://github.com/soroushneyestani/developer-cli-toolkit/releases/tag/v0.1.0) · [Exact build evidence](docs/releases/v0.1.0.md) · [Original manifest](docs/releases/v0.1.0-SHA256SUMS.txt) + +If the person or entity with the relevant rights authorizes it, they can expressly grant MIT for the original A02 material at that exact tagged revision, including their portions of the identified binaries. Use a dated grant identifying the commit, covered originals and original binary payloads by package or digest. Attach or link the exact MIT text and preserve the original upstream terms. This is a new grant for identified existing material. GitHub's automatic tag archives continue to contain the tag's original tree. [GitHub source archives](https://docs.github.com/en/repositories/working-with-files/using-files/downloading-source-code-archives) · [MIT terms](https://spdx.org/licenses/MIT.html) + +Keep the original tag and the five original release assets as the historical record. If an approved distribution needs self-contained MIT notices, create distinctly named licensed companion archives. The source companion should contain the exact tagged files plus the new project license and provenance notice. For binary companions, preserve the verified original executable bytes, add the project license and provenance notice, and retain all upstream texts. Compute separate outer archive hashes and a separate manifest. Record the source SHA, original package and executable digests, and repackaging date. Describe the new files as licensed wrappers of the original build. Use a separately approved distribution location if the original release disallows asset additions. [GitHub release asset management](https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository) + +With the separate public snapshot option, the existing `v0.1.0` release can remain private. Under the same-repository option the old tag and release become visible with the repository, so explicitly decide how their license status will be presented before switching visibility. + +## 4. v0.1.1 readiness + +The exact preparation checkpoint `b43e08c36e4ee893164df23fb48ccf11a4a6e886` passed the three native jobs and packaging on both push and Draft PR workflows. The extracted 49-file source archive built and passed the native verifier. The source and three target packages contain the root MIT text and four upstream license texts. Their ZIP CRCs and checksums verified. The Windows executable reports `0.1.1-rc.1`, and all three packaged executables match the reviewed candidate. [Push CI](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44570221378) · [Draft PR CI](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44570237842) · [Preparation artifact](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44570221378/artifacts/14553008712) + +After choosing the publication destination and approving the scope, set the [CLI version](main.go) to `0.1.1` and prepare the [stable changelog entry](CHANGELOG.md) and release notes on the chosen path. Review that exact source revision, verify fresh Windows, Linux and macOS CI, and build and check newly checksummed source and binary archives with the project and upstream licenses. If integrating into the existing repository, merge only the approved PR revision. Match the future `v0.1.1` tag and release provenance to the exact verified stable commit in the publication repository. The verified prerelease evidence continues to describe the RC. [Stable release procedure](docs/releases/OPEN_SOURCE_RELEASE.md) + +## Decisions requested at the audit checkpoint + +1. Confirm your authority to grant MIT for the original A02 work, including relevant employment, client, contributor and assignment rights. Identify any specific exceptions. +2. Choose the publication destination. Authorize public exposure of the existing Git metadata, or authorize preparation of a separate standalone public repository from a reviewed source snapshot. For the second option, provide the destination owner and repository name. The independent snapshot is recommended if you want the historical address kept private. +3. Decide the scope of the historical release. Authorize a dated, explicit MIT grant for original `v0.1.0` material and separately identified licensed companions, or retain that release as a private archive on the separate-repository path. If publishing the existing repository while withholding a historical grant, approve how to label the visible legacy material and its license status. +4. Approve the exact stable publication work after choosing the route. Specify authorization for the stable version change and, once its revision and fresh evidence are reviewed, any PR merge, new version tag, visibility change or release. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9628b59 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Soroush Neyestani + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/PROJECT_STATE.json b/PROJECT_STATE.json index 9e5e304..17654bf 100644 --- a/PROJECT_STATE.json +++ b/PROJECT_STATE.json @@ -1,15 +1,44 @@ { - "next_action": "Await explicit user acceptance of the A02 release review", - "status": "release_review", - "blocker": null, - "evidence": "docs/RELEASE_EVIDENCE.md", - "candidate_version": "0.1.0", - "verified_implementation_commit": "482ebacf9d2dcc940c1e6931652b49610dee797a", - "verified_release_source_commit": "1d41dcc0184a7fad5e09e1e7c9ee6cefc37dd930", - "verified_ci_run": 44523796632, - "verified_release_artifact": 14528472864, - "verified_release_sha256": "2261c04556de25eb3d793d1b1da5ebc716171ccf450ec944d841d20652ef7fa1", - "verified_windows": true, - "verified_hosted_linux_macos": true, - "verified": true + "next_action": "Verify the authorized v0.1.1 main build and public release, then await final owner review", + "status": "release_review", + "blocker": null, + "evidence": "docs/RELEASE_EVIDENCE.md", + "publication_preparation": { + "checklist": "FINAL_PUBLICATION_CHECKLIST.md", + "decisions_report": "FINAL_PUBLICATION_DECISIONS.md", + "license_preference": "MIT", + "visibility": "private", + "draft_pr": 2, + "pending_owner_decisions": [], + "approved_visibility": "public", + "approved_destination": "soroushneyestani/developer-cli-toolkit" + }, + "latest_private_release": { + "tag": "v0.1.0", + "source_commit": "02472793619d8a644634068759ecb2e826a39797", + "ci_run": 44536777289, + "source_artifact": 14536722607, + "url": "https://github.com/soroushneyestani/developer-cli-toolkit/releases/tag/v0.1.0", + "manifest": "docs/releases/v0.1.0-SHA256SUMS.txt" + }, + "candidate_version": "0.1.1-rc.1", + "reviewed_v0_1_0_candidate": { + "implementation_commit": "482ebacf9d2dcc940c1e6931652b49610dee797a", + "source_commit": "1d41dcc0184a7fad5e09e1e7c9ee6cefc37dd930", + "ci_run": 44523796632, + "artifact": 14528472864, + "outer_sha256": "2261c04556de25eb3d793d1b1da5ebc716171ccf450ec944d841d20652ef7fa1", + "manifest": "docs/RELEASE_SHA256SUMS.txt" + }, + "verified_candidate": { + "source_commit": "541aff83f8675b5d6aac9c98a28adcc1228fb052", + "implementation_commit": "aaf9a9c05b9a93fb77a517215c99dddc93a26df3", + "branch": "codex/a02-streaming", + "ci_run": 44540116482, + "artifact": 14537687323, + "outer_sha256": "53afa2a5d787f023210e39a127d4bc2da12c86913efec3909bc7b80b798d6677", + "manifest": "docs/releases/v0.1.1-rc.1-SHA256SUMS.txt", + "draft_pr": 2 + }, + "planned_stable_version": "0.1.1" } diff --git a/README.md b/README.md index 302d07f..2b1e64d 100644 --- a/README.md +++ b/README.md @@ -2,13 +2,13 @@ `dct` searches workspace text for a literal and lists regular files with their byte sizes. Both commands produce sorted, relative paths and can emit newline-delimited JSON (NDJSON) for scripts. -The original Go/Cobra implementation takes inspiration from the recursive search and file filters in [ripgrep](https://github.com/BurntSushi/ripgrep). `dct` includes hidden files, uses case-sensitive literal matching, and applies only explicit suffix filters. Its scope and performance goals are defined by the [v0.1 contract](docs/SPEC.md). +The original Go/Cobra implementation takes inspiration from recursive search and file filters. `dct` includes hidden files, uses case-sensitive literal matching, and applies explicit suffix filters. [CLI contract](docs/SPEC.md) · [ripgrep reference](https://github.com/BurntSushi/ripgrep) -## Install the 0.1.0 candidate +Version `v0.1.1` adds streaming search and keeps the existing command and exit-code contract. The original project source and documentation are available under the MIT license. [Changelog](CHANGELOG.md) · [MIT license](LICENSE) -Use the `dct-packages` bundle from CI run `44523796632` at source commit `1d41dcc0184a7fad5e09e1e7c9ee6cefc37dd930`. GitHub listed November 26, 2026 at 13:27:23 CET as the download expiration. The outer archive, the three target ZIPs, and `SHA256SUMS.txt` are retained privately in `dist/hosted-44523796632/` in the original workspace. [Private artifact 14528472864](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44523796632/artifacts/14528472864) +## Install v0.1.1 -Compare the outer ZIP's SHA-256 with the digest in the release evidence. From the extracted bundle directory, compare `SHA256SUMS.txt` with the checked-in manifest and verify the three target ZIPs before choosing the archive for your platform. The candidate packages are unsigned. [Release evidence](docs/RELEASE_EVIDENCE.md) · [Pinned SHA-256 manifest](docs/RELEASE_SHA256SUMS.txt) +Download the ZIP for your platform and `SHA256SUMS.txt` from the same release. Verify the ZIP before extracting it. The packages are unsigned. [v0.1.1 release assets](https://github.com/soroushneyestani/developer-cli-toolkit/releases/tag/v0.1.1) · [Release evidence](docs/RELEASE_EVIDENCE.md) | Target | Archive | Executable | | --- | --- | --- | @@ -17,20 +17,31 @@ Compare the outer ZIP's SHA-256 with the digest in the release evidence. From th | macOS arm64 | `dct-darwin-arm64.zip` | `dct` | ```powershell -Get-Content SHA256SUMS.txt | ForEach-Object { - $expected, $name = $_ -split '\s+', 2 - $actual = (Get-FileHash -LiteralPath $name -Algorithm SHA256).Hash - if ($actual -ine $expected) { throw "Checksum mismatch for $name" } -} -Expand-Archive -LiteralPath dct-windows-amd64.zip -DestinationPath dct-windows +$archive = 'dct-windows-amd64.zip' +$rows = @(Get-Content -LiteralPath SHA256SUMS.txt | Where-Object { + ($_ -split '\s+', 2)[1] -ceq $archive +}) +if ($rows.Count -ne 1) { throw "Missing or ambiguous checksum for $archive" } +$expected = ($rows[0] -split '\s+', 2)[0] +$actual = (Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash +if ($actual -ine $expected) { throw "Checksum mismatch for $archive" } +Expand-Archive -LiteralPath $archive -DestinationPath dct-windows .\dct-windows\dct.exe --version ``` -On Linux, verify with `sha256sum -c SHA256SUMS.txt`. On macOS, use `shasum -a 256 -c SHA256SUMS.txt`. Extract the target ZIP, set its run permission with `chmod +x dct` if needed, and run `./dct --version`. The packaged executable runs without a local Go installation. +On Linux, run `sha256sum dct-linux-amd64.zip`. On macOS, run `shasum -a 256 dct-darwin-arm64.zip`. Compare the result with the matching line in `SHA256SUMS.txt`. Extract the target ZIP, set its run permission with `chmod +x dct` if needed, and run `./dct --version`. The packaged executable reports `dct version 0.1.1` and runs without a local Go installation. ## Build and verify -Use Go 1.26 or newer. Use Go 1.27.4 to match the verified native CI and packaging toolchain. +Clone the repository and check out the stable tag, or extract its source ZIP or tarball. [Source repository](https://github.com/soroushneyestani/developer-cli-toolkit) · [Source archives](https://github.com/soroushneyestani/developer-cli-toolkit/releases/tag/v0.1.1) + +```sh +git clone https://github.com/soroushneyestani/developer-cli-toolkit.git +cd developer-cli-toolkit +git switch --detach v0.1.1 +``` + +Use Go 1.26 or newer. Go 1.27.4 matches the CI and packaging toolchain. On Linux and macOS, run `go build -mod=readonly -trimpath -o dct .` and `./dct --version`. On Windows, run `go build -mod=readonly -trimpath -o dct.exe .` and `.\dct.exe --version`. ```powershell powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/verify.ps1 @@ -57,13 +68,13 @@ Search emits one record per matching line and skips files containing NUL or inva | --- | --- | | 0 | Search found matches, or inspection succeeded. | | 1 | Search completed with no matches. | -| 2 | Invalid invocation, filesystem failure, or output failure. Diagnostics go to stderr. | +| 2 | Invalid invocation, filesystem, temporary-storage, or output failure. Diagnostics go to stderr. | Check the exit code before treating output as complete. Errors may follow partial results. ## Sample workflow -In PowerShell from the project directory, create a synthetic workspace and run the built binary. +After running the verifier in Windows PowerShell, create a synthetic workspace and run the resulting binary. ```powershell $demo = Join-Path (Get-Location).Path ('bin/dct-demo-' + [guid]::NewGuid().ToString('N')) @@ -81,10 +92,16 @@ Use NDJSON when paths or contents can contain output delimiters. Read it one lin Run `pwsh -NoProfile -File scripts/package.ps1` with Go 1.27.4. On Windows PowerShell, use `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/package.ps1`. A successful run creates a directory under `dist/` with ZIP archives for Linux amd64, Windows amd64, and macOS arm64, plus `SHA256SUMS.txt`. Verify each archive's SHA-256 before extraction. On a Unix host, run `chmod +x dct` if the extracted binary lacks the execute bit. -The [CI workflow](.github/workflows/ci.yml) runs native integration tests and builds on Windows, Linux and macOS, and makes archive upload depend on those jobs. The [release evidence](docs/RELEASE_EVIDENCE.md) records the tested commit, checksum results, and what ran on each platform. +All three `v0.1.1` binary packages include the project license and dependency license texts. CI runs native integration tests on Windows, Linux and macOS before building the release packages. [CI workflow](.github/workflows/ci.yml) · [Release evidence](docs/RELEASE_EVIDENCE.md) · [Release procedure](docs/releases/OPEN_SOURCE_RELEASE.md) ## Architecture and limits -`main.go` parses commands with Cobra, renders output and maps errors to exit codes. `workspace.go` scopes filesystem access to the opened directory, sorts relative paths, and checks each search file before matching its lines. Memory usage grows with the number of selected paths and the size of the largest searched file. Results describe a live filesystem, so keep the tree stable for reproducible output. On Unix, filenames with invalid UTF-8 bytes are represented with replacement characters in JSON. Search takes its literal and root from command arguments. Regex matching, stdin search, ignore-file rules and numeric performance targets are outside the 0.1.0 contract. +`main.go` parses commands with Cobra, renders output and maps errors to exit codes. `workspace.go` scopes filesystem access to the opened directory and sorts relative paths. The search engine reads files in chunks and stages results until each file reaches a clean, valid EOF. Oversized nonmatching lines are scanned without accumulating their text. When staging an oversized match, the engine rereads its range from the same open file and verifies the bytes by SHA-256. Dense match sets can use temporary disk. Memory still grows with the selected paths and the size of a matching record during output. [Streaming design](docs/adr/0003-streaming-search.md) · [Measured benchmark cases](docs/BENCHMARKS.md) + +Results describe a live filesystem, so keep the tree stable for reproducible output. On Unix, filenames with invalid UTF-8 bytes are represented with replacement characters in JSON. Search takes its literal and root from command arguments. Regex matching, stdin search, and ignore-file rules are outside the CLI contract. + +## License and participation + +The MIT license covers the original source and documentation. The Go toolchain and libraries retain their respective licenses. The historical `v0.1.0` archives contain the earlier project tree and dependency notices. Consult that release's notes for its licensing and provenance. [MIT license](LICENSE) · [Third-party notices](THIRD_PARTY_NOTICES.md) · [Historical v0.1.0 release](https://github.com/soroushneyestani/developer-cli-toolkit/releases/tag/v0.1.0) -See the [Persian tutorial](docs/LEARNING_FA.md), [technical article](docs/WEBSITE_EN.md), [design decisions](docs/adr/), [test evidence](docs/EVIDENCE.md), and [third-party notices](THIRD_PARTY_NOTICES.md). +See the [contribution guide](CONTRIBUTING.md), [security policy](SECURITY.md), [Persian tutorial](docs/LEARNING_FA.md), [technical article](docs/WEBSITE_EN.md), and [test evidence](docs/EVIDENCE.md). diff --git a/REVIEW_INDEX.md b/REVIEW_INDEX.md index 2d047e5..b5cbf48 100644 --- a/REVIEW_INDEX.md +++ b/REVIEW_INDEX.md @@ -1,25 +1,31 @@ -# A02 Developer CLI Toolkit v0.1.0 review index +# A02 Developer CLI Toolkit engineering review -A02 is in `release_review`. The implementation, tests, and review documents follow their repository paths in the review ZIP. Extract the whole archive into one directory and open this file to follow the relative links offline. +A02 is in `release_review` for `v0.1.1`. The historical `v0.1.0` release is the baseline. [Historical v0.1.0 release](https://github.com/soroushneyestani/developer-cli-toolkit/releases/tag/v0.1.0) · [Published asset provenance](docs/releases/v0.1.0.md) + +PR #2 carries the open-source release preparation. The checklist tracks release verification, and the release procedure records how the full source and packages are published. [Final publication checklist](FINAL_PUBLICATION_CHECKLIST.md) · [Release procedure](docs/releases/OPEN_SOURCE_RELEASE.md) · [PR #2](https://github.com/soroushneyestani/developer-cli-toolkit/pull/2) + +The ownership, historical email, and release-asset decisions are recorded separately. [Final publication decisions](FINAL_PUBLICATION_DECISIONS.md) ## Documentation - [README](README.md) covers setup, installation, and command examples. -- [Changelog](CHANGELOG.md) describes the v0.1.0 changes. +- [Changelog](CHANGELOG.md) describes both the released baseline and the streaming candidate. - [Persian learning guide](docs/LEARNING_FA.md), [English portfolio article](docs/WEBSITE_EN.md), and [English Instagram copy](docs/INSTAGRAM_EN.md) are ready for content review. - [Project state](PROJECT_STATE.json) records the release review status. [Project tasks](docs/TASKS.md) record the outstanding approval. ## Implementation and verification -- [CLI specification](docs/SPEC.md), [CLI contract decision](docs/adr/0001-cli-contract.md), and [workspace I/O decision](docs/adr/0002-workspace-io.md) explain the implemented behavior. -- [Command entry points](main.go) and [workspace traversal, search, and inspection](workspace.go) contain the implementation. +- [CLI specification](docs/SPEC.md), [CLI contract decision](docs/adr/0001-cli-contract.md), and [streaming search decision](docs/adr/0003-streaming-search.md) explain the implemented behavior. +- [Command entry points](main.go), [workspace traversal and inspection](workspace.go), and [streaming search](stream_search.go) contain the implementation. - [Search integration tests](search_test.go), [inspection and options integration tests](options_test.go), and [Windows sharing-violation test](search_windows_test.go) exercise the executable. -- [Test summary](docs/TEST_SUMMARY.md), [release evidence](docs/RELEASE_EVIDENCE.md), and [verification history](docs/EVIDENCE.md) record the checked results and their scope. +- [Test summary](docs/TEST_SUMMARY.md), [release evidence](docs/RELEASE_EVIDENCE.md), [benchmark evidence](docs/BENCHMARKS.md), and [verification history](docs/EVIDENCE.md) record the checked results and their scope. - [Local verifier](scripts/verify.ps1), [packaging script](scripts/package.ps1), and [GitHub Actions workflow](.github/workflows/ci.yml) define the runnable checks. -- [Release SHA-256 manifest](docs/RELEASE_SHA256SUMS.txt) lists the three distribution archive digests. [Third-party notices](THIRD_PARTY_NOTICES.md) identify their redistributed components. +- [Published v0.1.0 SHA-256 manifest](docs/releases/v0.1.0-SHA256SUMS.txt) lists the three released distribution archive digests. [Third-party notices](THIRD_PARTY_NOTICES.md) identify their redistributed components. + +## Verified 0.1.1-rc.1 package -## Release candidate package +The candidate is pinned to `541aff83f8675b5d6aac9c98a28adcc1228fb052`. Verify the three platform archives against the candidate manifest before extracting a platform package. The retained package path and outer checksum are in the release evidence. [Release evidence](docs/RELEASE_EVIDENCE.md) · [Candidate SHA-256 manifest](docs/releases/v0.1.1-rc.1-SHA256SUMS.txt) · [PR #2](https://github.com/soroushneyestani/developer-cli-toolkit/pull/2) · [Exact CI run 44540116482](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44540116482) · [Verified build artifact 14537687323](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44540116482/artifacts/14537687323) -The v0.1.0 binary candidate comes from run `44523796632` at `1d41dcc0184a7fad5e09e1e7c9ee6cefc37dd930` on `codex/a02`. The link to the artifact requires repository access and is subject to GitHub Actions retention. [Private candidate CI run](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44523796632) · [Private candidate artifact 14528472864](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44523796632/artifacts/14528472864) · [Private draft PR #1](https://github.com/soroushneyestani/developer-cli-toolkit/pull/1) +## Archived v0.1.0 review package -In the extracted review ZIP, `artifacts/dct-packages.zip` is the preserved copy of the candidate artifact. Its outer digest is recorded in the [test summary](docs/TEST_SUMMARY.md). Extract it into a separate directory to see the three target ZIPs and their bundled checksum manifest. The review ZIP also includes `SOURCE_OVERVIEW.md`, `RELEASE_CHECKLIST.md`, `REVIEW_PACKAGE_CHANGES.md`, and saved CI metadata and verification output for offline review. +The v0.1.0 review ZIP preserved artifact `14528472864` from run `44523796632`, previously reviewed in PR #1. That source revision and manifest differ from the subsequently published release assets. [Historical review evidence](docs/RELEASE_EVIDENCE.md#archived-v010-review-evidence) · [Merged PR #1](https://github.com/soroushneyestani/developer-cli-toolkit/pull/1) diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..ade1931 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,11 @@ +# Security policy + +## Supported versions + +Security fixes target the latest stable release. Give the exact version and, for a development build, the commit or Actions run. [Release list](https://github.com/soroushneyestani/developer-cli-toolkit/releases) + +## Report a vulnerability + +If private vulnerability reporting is available, open the repository's **Security** tab, choose **Advisories**, and select **Report a vulnerability**. Otherwise use an existing private channel with the maintainer. If you need a channel, ask only for private contact through an issue and keep the details out of the issue. [Security advisories](https://github.com/soroushneyestani/developer-cli-toolkit/security/advisories) + +Include the affected version, OS, impact, and enough context to verify the behavior using an authorized synthetic workspace. Leave out credentials, private data, and production files. Coordinate any public disclosure with the maintainer so a fix and advisory can be prepared. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index ddde81a..8f962e4 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -1,10 +1,10 @@ # Third-party notices -The command uses the Go standard library and runtime and these Go modules. Redistributed binaries should be accompanied by this notice and the license texts in `licenses/`. +The command uses the Go standard library and runtime and these Go modules. Include this notice and the license texts in `licenses/` when redistributing the binaries. The [project MIT license](LICENSE) covers the original A02 material. The components below retain their own licenses and attribution. | Component | Version | License | | --- | --- | --- | -| [Go runtime and standard library](https://github.com/golang/go/tree/go1.27.4) | 1.27.4 in packaged builds | [BSD 3-Clause](licenses/go.txt) | +| [Go runtime and standard library](https://github.com/golang/go/tree/go1.27.4), including Go's bundled DNS message implementation | 1.27.4 in packaged builds | [BSD 3-Clause](licenses/go.txt) | | [Cobra](https://github.com/spf13/cobra/tree/v1.10.2) | 1.10.2 | [Apache 2.0](licenses/cobra.txt) | | [pflag](https://github.com/spf13/pflag/tree/v1.0.9) | 1.0.9 | [BSD 3-Clause](licenses/pflag.txt) | -| [mousetrap](https://github.com/inconshreveable/mousetrap/tree/v1.1.0) | 1.1.0 | [Apache 2.0](licenses/mousetrap.txt) | +| [mousetrap](https://github.com/inconshreveable/mousetrap/tree/v1.1.0), linked in the Windows build | 1.1.0 | [Apache 2.0](licenses/mousetrap.txt) | diff --git a/docs/BENCHMARKS.md b/docs/BENCHMARKS.md new file mode 100644 index 0000000..d6168f2 --- /dev/null +++ b/docs/BENCHMARKS.md @@ -0,0 +1,44 @@ +# A02 streaming search benchmarks + +On November 19, 2026, the Windows amd64 build of `0.1.1-rc.1` reduced median peak working set by approximately 87% on both the sparse 96 MiB fixture and the 48 MiB single-line no-match fixture. The candidate had a lower median peak working set in all five measured workloads. End-to-end time varied with the input and number of matches. [Raw measurements and SHA-256 values](BENCHMARKS_WINDOWS.json) + +## Builds and method + +- Baseline `0.1.0` uses the Windows amd64 executable from the official private release at source commit `02472793619d8a644634068759ecb2e826a39797`. Executable SHA-256 `a84e51fff68fec0e450e5e2ca763d4ebf48d8595c281705b99a1427a94e598a5`. [Private release](https://github.com/soroushneyestani/developer-cli-toolkit/releases/tag/v0.1.0) +- Candidate `0.1.1-rc.1` was built locally from exact code commit `aaf9a9c05b9a93fb77a517215c99dddc93a26df3` using Go `1.27.4`, `CGO_ENABLED=0`, `-trimpath` and `-buildvcs=false`. Executable SHA-256 `c11ecb7fef161c1ae0933a8dff5da2862bd8dd55cd7b365852cda61b27dce56b`. +- Both builds run `dct search DCT_BENCHMARK_MATCH --ext .txt --json`. The harness creates deterministic fixtures and separately verifies the expected exit, empty stderr, and exact NDJSON length and SHA-256 before timing. Each build gets one warmup and five measured invocations per fixture. The build order alternates and both builds use the same temporary directory. +- Wall time includes child creation, traversal, matching and output encoding. The timing pass sends stdout and stderr to the null device and uses warmed filesystem caches. Effective MiB/s divides fixture bytes by median wall time. Windows memory is the peak working set of the individual child process throughout its lifetime. +- The measured host was Windows 11 amd64 build `10.0.26300`, with 16 logical processors, CPython `3.13.1`, and default Go runtime settings. Linux and macOS performance measurements remain open. The test summary records the separate integration-test scope. [Harness](../scripts/benchmark.py) · [Test summary](TEST_SUMMARY.md) + +## Median results + +| Synthetic fixture | Input | Records | v0.1.0 time (ms) | RC time (ms) | v0.1.0 MiB/s | RC MiB/s | v0.1.0 peak (MiB) | RC peak (MiB) | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| Sparse short lines, 4 files × 24 MiB | 96 MiB | 4 | 67.403 | 56.175 | 1424.3 | 1709.0 | 57.24 | 7.57 | +| Dense short lines, every line matches | 2 MiB | 16,384 | 28.731 | 29.326 | 69.6 | 68.2 | 13.09 | 11.70 | +| Many small files, 1,024 files × 4 KiB | 4 MiB | 1,024 | 90.100 | 79.352 | 44.4 | 50.4 | 12.52 | 9.22 | +| One unterminated line without a match | 48 MiB | 0 | 41.872 | 50.269 | 1146.4 | 954.9 | 56.31 | 7.32 | +| One long CRLF line with a match near the end | 16 MiB + 21 bytes | 1 | 40.292 | 69.589 | 397.1 | 229.9 | 56.93 | 41.28 | + +The sparse and small-file fixtures took less time in this run. Dense results can spill to temporary storage and the dense case took slightly longer. The oversized no-match probe kept the 48 MiB line out of memory and increased elapsed time by about 20%. The oversized matching line required a verified positional read, temporary staging and a complete rendered record. Its peak working set decreased by about 27% and elapsed time increased by about 73%. These figures describe the specified synthetic inputs and measured host. [Streaming ADR](adr/0003-streaming-search.md) · [Raw trials](BENCHMARKS_WINDOWS.json) + +## Reproduce the comparison + +Extract `dct.exe` from the private `dct-windows-amd64.zip` for v0.1.0 after verifying the archive against its release manifest. In a clean source checkout of `aaf9a9c05b9a93fb77a517215c99dddc93a26df3`, build the candidate with Go `1.27.4` on Windows amd64. [Release manifest](releases/v0.1.0-SHA256SUMS.txt) + +If the archived baseline binary is unavailable, use the same compiler and flags in a clean checkout of the released `v0.1.0` commit `02472793619d8a644634068759ecb2e826a39797`. Record the SHA-256 of the rebuilt executable and compare it with the baseline digest above. This keeps new measurements tied to the binary actually used. + +```powershell +$env:CGO_ENABLED = '0' +go build -mod=readonly -trimpath -buildvcs=false -o dct-rc.exe . +``` + +From the review checkout containing the benchmark driver, point it to the two executables. CPython 3.11 or newer is required. The driver writes disposable fixtures under the ignored `bin/.benchmark/` directory. The driver can collect per-child `wait4` peak RSS on Linux and macOS when given binaries for those platforms. + +```powershell +python -B scripts/benchmark.py --baseline path/to/v0.1.0/dct.exe ` + --baseline-commit 02472793619d8a644634068759ecb2e826a39797 ` + --candidate path/to/candidate/dct-rc.exe ` + --candidate-commit aaf9a9c05b9a93fb77a517215c99dddc93a26df3 ` + --runs 5 --output bin/.benchmark/reproduced.json +``` diff --git a/docs/BENCHMARKS_WINDOWS.json b/docs/BENCHMARKS_WINDOWS.json new file mode 100644 index 0000000..3c67677 --- /dev/null +++ b/docs/BENCHMARKS_WINDOWS.json @@ -0,0 +1,365 @@ +{ + "environment": { + "os": "Windows", + "os_release": "11", + "os_version": "10.0.26300", + "architecture": "AMD64", + "processor": "Intel64 Family 6 Model 186 Stepping 2, GenuineIntel", + "logical_processors": 16, + "python": "3.13.1", + "go_runtime_overrides": {} + }, + "method": { + "runs_per_build": 5, + "warmups_per_build": 1, + "timeout_seconds_per_process": 180, + "stdout_validation": "One separate digest, length, stderr and exit check per build and workload.", + "time": "Elapsed wall time from before process creation through exit. Both output streams are sent to the null device while timing. Build order alternates each iteration.", + "cache": "Generated locally, verified and warmed before timing. OS caches are shared.", + "peak_rss": "Win32 GetProcessMemoryInfo PeakWorkingSetSize in bytes" + }, + "builds": { + "baseline": { + "commit": "02472793619d8a644634068759ecb2e826a39797", + "binary_sha256": "a84e51fff68fec0e450e5e2ca763d4ebf48d8595c281705b99a1427a94e598a5", + "version": "dct version 0.1.0" + }, + "candidate": { + "commit": "aaf9a9c05b9a93fb77a517215c99dddc93a26df3", + "binary_sha256": "c11ecb7fef161c1ae0933a8dff5da2862bd8dd55cd7b365852cda61b27dce56b", + "version": "dct version 0.1.1-rc.1" + } + }, + "workloads": [ + { + "name": "sparse-short-lines", + "input_bytes": 100663296, + "expected_exit": 0, + "expected_records": 4, + "expected_stdout_bytes": 696, + "expected_stdout_sha256": "4e17eb0c925aa27c5226e51f1beebc984f4b508ed0b3f452d88d28b5b4aa8da6", + "builds": { + "baseline": { + "runs": [ + { + "elapsed_nanoseconds": 70728700, + "peak_rss_bytes": 60051456 + }, + { + "elapsed_nanoseconds": 70334800, + "peak_rss_bytes": 60428288 + }, + { + "elapsed_nanoseconds": 65364400, + "peak_rss_bytes": 60022784 + }, + { + "elapsed_nanoseconds": 67403300, + "peak_rss_bytes": 60006400 + }, + { + "elapsed_nanoseconds": 66850900, + "peak_rss_bytes": 59916288 + } + ], + "median_elapsed_ms": 67.403, + "median_input_mib_per_second": 1424.263, + "median_peak_rss_bytes": 60022784, + "max_peak_rss_bytes": 60428288 + }, + "candidate": { + "runs": [ + { + "elapsed_nanoseconds": 56174700, + "peak_rss_bytes": 7860224 + }, + { + "elapsed_nanoseconds": 55270600, + "peak_rss_bytes": 7933952 + }, + { + "elapsed_nanoseconds": 57797300, + "peak_rss_bytes": 7847936 + }, + { + "elapsed_nanoseconds": 53551000, + "peak_rss_bytes": 7995392 + }, + { + "elapsed_nanoseconds": 56859400, + "peak_rss_bytes": 7933952 + } + ], + "median_elapsed_ms": 56.175, + "median_input_mib_per_second": 1708.954, + "median_peak_rss_bytes": 7933952, + "max_peak_rss_bytes": 7995392 + } + } + }, + { + "name": "dense-short-lines", + "input_bytes": 2097152, + "expected_exit": 0, + "expected_records": 16384, + "expected_stdout_bytes": 2823326, + "expected_stdout_sha256": "579751172e871bc906206e756f77a4e2ae3e767ff41f85de05159b7ac0222f1e", + "builds": { + "baseline": { + "runs": [ + { + "elapsed_nanoseconds": 25040700, + "peak_rss_bytes": 13725696 + }, + { + "elapsed_nanoseconds": 28747800, + "peak_rss_bytes": 13701120 + }, + { + "elapsed_nanoseconds": 28730800, + "peak_rss_bytes": 13709312 + }, + { + "elapsed_nanoseconds": 30388500, + "peak_rss_bytes": 14057472 + }, + { + "elapsed_nanoseconds": 26510800, + "peak_rss_bytes": 14487552 + } + ], + "median_elapsed_ms": 28.731, + "median_input_mib_per_second": 69.612, + "median_peak_rss_bytes": 13725696, + "max_peak_rss_bytes": 14487552 + }, + "candidate": { + "runs": [ + { + "elapsed_nanoseconds": 27480300, + "peak_rss_bytes": 12218368 + }, + { + "elapsed_nanoseconds": 25786600, + "peak_rss_bytes": 12267520 + }, + { + "elapsed_nanoseconds": 31025700, + "peak_rss_bytes": 12734464 + }, + { + "elapsed_nanoseconds": 30613600, + "peak_rss_bytes": 12931072 + }, + { + "elapsed_nanoseconds": 29326100, + "peak_rss_bytes": 12193792 + } + ], + "median_elapsed_ms": 29.326, + "median_input_mib_per_second": 68.199, + "median_peak_rss_bytes": 12267520, + "max_peak_rss_bytes": 12931072 + } + } + }, + { + "name": "many-small-files", + "input_bytes": 4194304, + "expected_exit": 0, + "expected_records": 1024, + "expected_stdout_bytes": 176128, + "expected_stdout_sha256": "714ddb571e1f02ae0652c043514340c6216b14f87395555e55a090331a8ed611", + "builds": { + "baseline": { + "runs": [ + { + "elapsed_nanoseconds": 94653500, + "peak_rss_bytes": 13508608 + }, + { + "elapsed_nanoseconds": 87153800, + "peak_rss_bytes": 13062144 + }, + { + "elapsed_nanoseconds": 85425600, + "peak_rss_bytes": 13123584 + }, + { + "elapsed_nanoseconds": 104275200, + "peak_rss_bytes": 12976128 + }, + { + "elapsed_nanoseconds": 90099700, + "peak_rss_bytes": 13279232 + } + ], + "median_elapsed_ms": 90.1, + "median_input_mib_per_second": 44.395, + "median_peak_rss_bytes": 13123584, + "max_peak_rss_bytes": 13508608 + }, + "candidate": { + "runs": [ + { + "elapsed_nanoseconds": 77389900, + "peak_rss_bytes": 9666560 + }, + { + "elapsed_nanoseconds": 79351700, + "peak_rss_bytes": 9695232 + }, + { + "elapsed_nanoseconds": 78457700, + "peak_rss_bytes": 9498624 + }, + { + "elapsed_nanoseconds": 79764100, + "peak_rss_bytes": 9551872 + }, + { + "elapsed_nanoseconds": 92486200, + "peak_rss_bytes": 9703424 + } + ], + "median_elapsed_ms": 79.352, + "median_input_mib_per_second": 50.408, + "median_peak_rss_bytes": 9666560, + "max_peak_rss_bytes": 9703424 + } + } + }, + { + "name": "long-no-match", + "input_bytes": 50331648, + "expected_exit": 1, + "expected_records": 0, + "expected_stdout_bytes": 0, + "expected_stdout_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "builds": { + "baseline": { + "runs": [ + { + "elapsed_nanoseconds": 42428900, + "peak_rss_bytes": 59105280 + }, + { + "elapsed_nanoseconds": 42417100, + "peak_rss_bytes": 59002880 + }, + { + "elapsed_nanoseconds": 41654400, + "peak_rss_bytes": 59011072 + }, + { + "elapsed_nanoseconds": 41359400, + "peak_rss_bytes": 59068416 + }, + { + "elapsed_nanoseconds": 41871800, + "peak_rss_bytes": 59047936 + } + ], + "median_elapsed_ms": 41.872, + "median_input_mib_per_second": 1146.356, + "median_peak_rss_bytes": 59047936, + "max_peak_rss_bytes": 59105280 + }, + "candidate": { + "runs": [ + { + "elapsed_nanoseconds": 49361700, + "peak_rss_bytes": 7671808 + }, + { + "elapsed_nanoseconds": 50015500, + "peak_rss_bytes": 7741440 + }, + { + "elapsed_nanoseconds": 52348100, + "peak_rss_bytes": 7856128 + }, + { + "elapsed_nanoseconds": 51876100, + "peak_rss_bytes": 7671808 + }, + { + "elapsed_nanoseconds": 50268800, + "peak_rss_bytes": 7663616 + } + ], + "median_elapsed_ms": 50.269, + "median_input_mib_per_second": 954.867, + "median_peak_rss_bytes": 7671808, + "max_peak_rss_bytes": 7856128 + } + } + }, + { + "name": "long-one-match", + "input_bytes": 16777237, + "expected_exit": 0, + "expected_records": 1, + "expected_stdout_bytes": 16777274, + "expected_stdout_sha256": "2da32c84e919baf48e82d573de49405380b8a132c801c5c1ed1de6c8c09c1801", + "builds": { + "baseline": { + "runs": [ + { + "elapsed_nanoseconds": 40291600, + "peak_rss_bytes": 59711488 + }, + { + "elapsed_nanoseconds": 37108700, + "peak_rss_bytes": 59711488 + }, + { + "elapsed_nanoseconds": 36993500, + "peak_rss_bytes": 59547648 + }, + { + "elapsed_nanoseconds": 40498700, + "peak_rss_bytes": 59691008 + }, + { + "elapsed_nanoseconds": 42257300, + "peak_rss_bytes": 59695104 + } + ], + "median_elapsed_ms": 40.292, + "median_input_mib_per_second": 397.106, + "median_peak_rss_bytes": 59695104, + "max_peak_rss_bytes": 59711488 + }, + "candidate": { + "runs": [ + { + "elapsed_nanoseconds": 69588900, + "peak_rss_bytes": 43286528 + }, + { + "elapsed_nanoseconds": 68507900, + "peak_rss_bytes": 43425792 + }, + { + "elapsed_nanoseconds": 70718100, + "peak_rss_bytes": 43274240 + }, + { + "elapsed_nanoseconds": 68281900, + "peak_rss_bytes": 43266048 + }, + { + "elapsed_nanoseconds": 73084200, + "peak_rss_bytes": 43499520 + } + ], + "median_elapsed_ms": 69.589, + "median_input_mib_per_second": 229.922, + "median_peak_rss_bytes": 43286528, + "max_peak_rss_bytes": 43499520 + } + } + } + ] +} diff --git a/docs/EVIDENCE.md b/docs/EVIDENCE.md index 243e073..67202e2 100644 --- a/docs/EVIDENCE.md +++ b/docs/EVIDENCE.md @@ -70,3 +70,15 @@ Human action: install Go with go and gofmt on PATH, reopen the shell and confirm - The authenticated download for artifact `14528472864` matched the retained local outer archive byte for byte. SHA-256 and CRC verification passed for the outer ZIP and three target ZIPs. The retained manifest matches the outer ZIP member, and each target digest matches that manifest. The three candidate executable payloads match their historical equivalents byte for byte. - Ran the Windows executable extracted from artifact `14528472864` against synthetic fixtures. It reported `dct version 0.1.0` and produced the expected README and Persian tutorial NDJSON with inspection sizes of 24 and 29 bytes. The no-match case returned 1 and the malformed suffix case returned 2. Linux and macOS archive payloads were checked for integrity and executable format. Native execution on those platforms was exercised by CI's native builds. - The canonical artifact, retained local paths, and checksum manifest are now aligned for `release_review`. Final acceptance is pending. [Release evidence](RELEASE_EVIDENCE.md) · [Pinned manifest](RELEASE_SHA256SUMS.txt) + +## 2026-11-19 — Streaming engineering candidate + +- Native Windows verification passed locally. Eighteen synthetic differential cases preserved the v0.1.0 text and JSON output, status and absence of spilled files after exit. +- CI for `541aff83f8675b5d6aac9c98a28adcc1228fb052` passed on all three native platforms and uploaded the candidate package. Checked its outer and per-platform hashes and ran the direct packaged Windows smoke. [Exact CI run 44540116482](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44540116482) · [Verified build artifact 14537687323](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44540116482/artifacts/14537687323) +- Recorded the representative working-set and elapsed-time changes and their tradeoffs separately from the product contract. [Benchmark evidence](BENCHMARKS.md) · [Release evidence](RELEASE_EVIDENCE.md) + +## 2026-11-19 — Open-source preparation + +- Rechecked the native Windows verifier with Go 1.27.4. Seventy-two additional seeded comparisons against the released binary preserved stdout, stderr and exit status across short and oversized lines, invalid bytes, and dense output. +- Confirmed the 50 recorded benchmark samples and both benchmark executable digests. The three local preparation ZIPs retained the previously reviewed runtime bytes and passed CRC, SHA-256, release-material and machine-header checks after adding required license packaging. [Benchmark evidence](BENCHMARKS.md) · [Release procedure](releases/OPEN_SOURCE_RELEASE.md) +- Compared the historical Git refs with the private remote, verified the dependency notices, and screened the existing history and hosted records. The owner's decisions about rights, historical Git author metadata and the older release remain open. [Publication checklist](../FINAL_PUBLICATION_CHECKLIST.md) diff --git a/docs/INSTAGRAM_EN.md b/docs/INSTAGRAM_EN.md index 2e3d1da..217fd8b 100644 --- a/docs/INSTAGRAM_EN.md +++ b/docs/INSTAGRAM_EN.md @@ -4,8 +4,12 @@ A script should be able to distinguish an empty search from a failed run. That r `dct search` finds literal text. `dct inspect` lists files with their byte sizes. Both support suffix filters, sorted relative paths, and newline-delimited JSON. I designed the exit codes so scripts can handle a match, an empty search, and an error explicitly. -The release candidate passed native CI on Windows, Linux, and macOS. A separate packaging job built three platform archives and generated SHA-256 checksums. +Developer CLI Toolkit v0.1.1 is open source under MIT, with native CI on Windows, Linux and macOS. Search reads files in chunks and waits for full validation before sending matches to stdout. If a NUL byte appears at the end of a file, a match in its first line still gets discarded. + +I compared the two versions on five reproducible synthetic Windows workloads and verified their output before timing. On a sparse 96 MiB fixture, median peak process memory fell from 57.24 to 7.57 MiB. The long matching line used less memory and took longer to process. The engineering lesson was to treat the command line as an interface. Output, error messages, and exit codes all need a documented contract and tests. +Source, downloads and reproducible benchmark data are on GitHub. [Developer CLI Toolkit v0.1.1](https://github.com/soroushneyestani/developer-cli-toolkit/releases/tag/v0.1.1) + #GoLang #DeveloperTools #CLI #SoftwareEngineering #EngineeringMastery diff --git a/docs/LEARNING_FA.md b/docs/LEARNING_FA.md index 36b3144..a12ef2f 100644 --- a/docs/LEARNING_FA.md +++ b/docs/LEARNING_FA.md @@ -1,6 +1,6 @@ # راهنمای فنی و آموزشی جعبه‌ابزار خط فرمان توسعه‌دهنده -`dct` نسخهٔ `0.1.0` برای دو کار در یک پوشهٔ کاری ساخته شده است. با `search` می‌توان یک عبارت مشخص را در فایل‌های متنی پیدا کرد. با `inspect` می‌توان فهرستی مرتب از مسیر فایل‌ها و اندازهٔ آن‌ها به بایت گرفت. هر دو دستور می‌توانند نتیجه را برای خواندن در ترمینال یا پردازش در یک اسکریپت چاپ کنند. +`dct` برای دو کار در یک پوشهٔ کاری ساخته شده است. با `search` می‌توان یک عبارت مشخص را در فایل‌های متنی پیدا کرد. با `inspect` می‌توان فهرستی مرتب از مسیر فایل‌ها و اندازهٔ آن‌ها به بایت گرفت. هر دو دستور می‌توانند نتیجه را برای خواندن در ترمینال یا پردازش در یک اسکریپت چاپ کنند. نسخهٔ پایدار `v0.1.1` پردازش جریانی متن را با همان قرارداد خط فرمان پیاده می‌کند. سورس اصیل پروژه تحت مجوز MIT در دسترس است. [مجوز پروژه](../LICENSE) ## در چه موقعیتی به کار می‌آید؟ @@ -8,7 +8,7 @@ - برای یک اسکریپت بررسی، مسیرهای نسبی و اندازهٔ فایل‌های عادی یک نمونهٔ محلی را به شکل رکوردهای JSON دریافت کنید. - در یک گردش‌کار خودکار، با کد خروج تشخیص دهید که جست‌وجو نتیجه داشته، بدون نتیجه تمام شده یا به خطایی رسیده است. -ایدهٔ پیمایش بازگشتی و فیلتر فایل از مطالعهٔ ripgrep آمده است. این پروژه قرارداد خط فرمان و پیاده‌سازی مستقل خودش را دارد. جزئیات رفتار در [قرارداد v0.1](SPEC.md) آمده است. +ایدهٔ پیمایش بازگشتی و فیلتر فایل از مطالعهٔ ripgrep آمده است. این پروژه قرارداد خط فرمان و پیاده‌سازی مستقل خودش را دارد. [قرارداد خط فرمان](SPEC.md) ## نصب از بستهٔ اجرایی @@ -18,7 +18,7 @@ | Linux amd64 | `dct-linux-amd64.zip` | `dct` | | macOS arm64 | `dct-darwin-arm64.zip` | `dct` | -از [شواهد انتشار](RELEASE_EVIDENCE.md) به خروجی خصوصی `dct-packages` در CI برسید. پس از استخراج فایل دریافتی از CI، سه ZIP هدف و `SHA256SUMS.txt` در دسترس‌اند. ابتدا بستهٔ سیستم خود را با مقدار متناظر در همان فایل مقایسه کنید. نمونهٔ زیر را در پوشه‌ای اجرا کنید که بسته و فایل checksum در آن قرار دارند. +از صفحهٔ انتشار `v0.1.1`، بستهٔ مناسب دستگاه و `SHA256SUMS.txt` را بگیرید. بستهٔ سیستم خود را با مقدار متناظر در همان فایل مقایسه کنید. نمونهٔ زیر را در پوشه‌ای اجرا کنید که بسته و فایل checksum در آن قرار دارند. [انتشار v0.1.1](https://github.com/soroushneyestani/developer-cli-toolkit/releases/tag/v0.1.1) · [شواهد انتشار](RELEASE_EVIDENCE.md) ```powershell $archive = 'dct-windows-amd64.zip' @@ -33,23 +33,32 @@ Expand-Archive -LiteralPath $archive -DestinationPath dct-windows .\dct-windows\dct.exe --version ``` -وقتی هر سه بسته کنار فایل checksum باشند، در Linux از `sha256sum -c SHA256SUMS.txt` و در macOS از `shasum -a 256 -c SHA256SUMS.txt` می‌توان استفاده کرد. پس از تطبیق checksum، بستهٔ متناسب با دستگاه را استخراج کنید و `./dct --version` را اجرا کنید. اگر مجوز اجرا هنگام استخراج منتقل نشده بود، ابتدا `chmod +x dct` بزنید. فایل `THIRD_PARTY_NOTICES.md` و پوشهٔ `licenses/` همراه بسته نگه‌داری می‌شوند. +وقتی هر سه بسته کنار فایل checksum باشند، در Linux از `sha256sum -c SHA256SUMS.txt` و در macOS از `shasum -a 256 -c SHA256SUMS.txt` می‌توان استفاده کرد. پس از تطبیق checksum، بستهٔ متناسب با دستگاه را استخراج کنید و `./dct --version` را اجرا کنید. اگر مجوز اجرا هنگام استخراج منتقل نشده بود، ابتدا `chmod +x dct` بزنید. فایل‌های `LICENSE`، `THIRD_PARTY_NOTICES.md` و پوشهٔ `licenses/` همراه بسته نگه‌داری می‌شوند. -خروجی نسخه به این شکل است. +فایل اجرایی بستهٔ انتشار این نسخه را گزارش می‌کند. ```text -dct version 0.1.0 +dct version 0.1.1 ``` ## ساخت از سورس +مخزن شامل سورس Go، تست‌ها، ابزار بسته‌بندی و داده‌های خام بنچمارک است. مخزن عمومی و آرشیو سورسِ تگ نسخه، هر دو این فایل‌ها را در اختیار شما می‌گذارند. [مخزن پروژه](https://github.com/soroushneyestani/developer-cli-toolkit) + +```sh +git clone https://github.com/soroushneyestani/developer-cli-toolkit.git +cd developer-cli-toolkit +``` + +برای ساخت نسخهٔ مشخص، ابتدا همان تگ یا کامیت را انتخاب کنید. دستور `git switch --detach v0.1.1` سورس نسخهٔ پایدار جریانی را انتخاب می‌کند. [منشأ سورس و بسته‌ها](RELEASE_EVIDENCE.md) + در ریشهٔ مخزن پروژه، Go و `gofmt` باید در `PATH` باشند. حداقل نسخه در `go.mod` برابر `1.26.0` است و CI از `1.27.4` استفاده می‌کند. در PowerShell 7 دستور زیر آزمون‌ها را اجرا و باینری بومی را در `bin/dct.exe` روی Windows یا `bin/dct` روی Linux و macOS می‌سازد. ```powershell pwsh -NoProfile -File scripts/verify.ps1 ``` -در Windows PowerShell نیز می‌توان از `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/verify.ps1` استفاده کرد. برای ساخت سه بستهٔ هدف، `pwsh -NoProfile -File scripts/package.ps1` را با Go `1.27.4` اجرا کنید. هر اجرا در `dist/` یک پوشهٔ جداگانه برای بسته‌ها و `SHA256SUMS.txt` می‌سازد. +در Windows PowerShell نیز می‌توان از `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/verify.ps1` استفاده کرد. باینری ساخته‌شده از تگ پایدار با `--version` مقدار `0.1.1` را گزارش می‌کند. برای ساخت سه بستهٔ هدف از همان سورس، `pwsh -NoProfile -File scripts/package.ps1` را با Go `1.27.4` اجرا کنید. هر اجرا در `dist/` یک پوشهٔ جداگانه برای بسته‌ها و `SHA256SUMS.txt` می‌سازد. بسته‌ها و چک‌سام‌های هر انتشار به ساخت همان نسخه تعلق دارند. ## اجرای یک نمونهٔ قابل بازتولید @@ -89,7 +98,18 @@ $LASTEXITCODE # 1 $LASTEXITCODE # 2 ``` -جست‌وجوی بدون نتیجه خروجی ندارد. دستور دوم پیام `dct: invalid extension "txt": expected a dot-prefixed suffix without path separators` را در `stderr` می‌نویسد. این دو حالت در PowerShell با باینری موجود و دادهٔ مصنوعی بررسی شدند. +جست‌وجوی بدون نتیجه خروجی ندارد. دستور دوم پیام `dct: invalid extension "txt": expected a dot-prefixed suffix without path separators` را در `stderr` می‌نویسد. + +رفتار فایل دارای NUL را هم می‌توان با یک نمونهٔ کوچک دید. با اینکه خط اول عبارت `TODO` دارد، کل فایل کنار گذاشته می‌شود. نتیجهٔ جست‌وجو خالی است و کد خروج `1` برمی‌گردد. + +```powershell +$invalidDemo = Join-Path $demo 'late-nul' +New-Item -ItemType Directory -Path $invalidDemo | Out-Null +$payload = $utf8.GetBytes("TODO: valid line`ninvalid tail") +[IO.File]::WriteAllBytes((Join-Path $invalidDemo 'invalid.txt'), [byte[]]($payload + 0)) +.\bin\dct.exe search TODO $invalidDemo --json +$LASTEXITCODE # 1 +``` ## قرارداد خط فرمان @@ -118,10 +138,11 @@ dct --version 1. [main.go](../main.go) با Cobra فرمان‌ها و گزینه‌ها را تعریف می‌کند. تابع `run` آرگومان و مقصدهای خروجی را می‌گیرد، ورودی را اعتبارسنجی می‌کند و نتیجهٔ لایهٔ فایل را به متن یا NDJSON تبدیل می‌کند. جدا بودن `stdout` و `stderr` قرارداد اجرای اسکریپتی را روشن می‌کند. 2. [workspace.go](../workspace.go) ریشه را بررسی و با `os.OpenRoot` باز می‌کند. پیمایش بازگشتی با `fs.WalkDir` انجام می‌شود. فایل‌های عادی پس از فیلترشدن بر اساس پسوند، با مسیر نسبی و مستقل از ترتیب بازگشت سیستم‌فایل مرتب می‌شوند. این مرتب‌سازی باعث می‌شود یک درخت ثابت خروجی قابل مقایسه‌ای بدهد. -3. موتور جست‌وجو یک فایل را کامل می‌خواند و پیش از انتشار هر نتیجه، وجود NUL و اعتبار UTF-8 آن را بررسی می‌کند. در نتیجه، حتی اگر بایت نامعتبر بعد از یک خطِ منطبق آمده باشد، از همان فایل رکوردی منتشر نمی‌شود. سپس خطوط LF، CRLF و خط پایانی بدون جداکننده را جدا و با `bytes.Contains` مقایسه می‌کند. -4. مسیر بازرسی از `Lstat` برای خواندن اندازه و نوع فایل استفاده می‌کند. بازرسی برای گزارش بایت‌ها محتوای فایل را باز نمی‌کند، بنابراین فایل عادیِ دارای دادهٔ دودویی نیز می‌تواند در فهرست ظاهر شود. +3. موتور جست‌وجو از بافر خواندن ۶۴ کیبی‌بایتی استفاده می‌کند. رکوردهای منطبق تا پایان موفق خواندن همان فایل در انتظار می‌مانند. با عبور اندازهٔ رکوردهای در انتظار از ۲۵۶ کیبی‌بایت، برنامه آن‌ها را در فایل موقت قرار می‌دهد. بنابراین اگر پس از یک خط منطبق، NUL یا UTF-8 نامعتبر پیدا شود، هیچ رکوردی از آن فایل به `stdout` نمی‌رسد. [سورس جست‌وجو](../stream_search.go) +4. برنامه خط بلندتر از ظرفیت بافر را قطعه‌به‌قطعه اعتبارسنجی و بررسی می‌کند. بخش ناتمام یک نویسهٔ UTF-8 و بایت‌های لازم برای تشخیص تطبیق در مرز قطعه‌ها حفظ می‌شوند. خط بلندِ بدون تطبیق جایی ذخیره نمی‌شود. اگر خط بلند منطبق باشد، برنامه فقط بازهٔ همان خط را از فایلِ ازپیش‌بازشده دوباره می‌خواند و پیش از پذیرش رکورد، SHA-256 متن را با گذر اول مقایسه می‌کند. قرارداد LF، CRLF و خط پایانی بدون جداکننده همچنان برقرار است. [پردازش خط بلند](../long_line.go) +5. مسیر بازرسی از `Lstat` برای خواندن اندازه و نوع فایل استفاده می‌کند. بازرسی برای گزارش بایت‌ها محتوای فایل را باز نمی‌کند، بنابراین فایل عادیِ دارای دادهٔ دودویی نیز می‌تواند در فهرست ظاهر شود. -Go برای دسترسی به فایل‌ها، UTF-8، JSON و آزمون فرایند ابزارهای استاندارد دارد. Cobra `1.10.2` بخش تعریف فرمان و اعتبارسنجی گزینه‌ها را بر عهده دارد. `go.mod` و `go.sum` نسخه‌ها و checksum وابستگی‌ها را ثبت می‌کنند. دلیل این انتخاب‌ها و موازنهٔ حافظه و صحت در [ADR 0001](adr/0001-cli-contract.md) و [ADR 0002](adr/0002-workspace-io.md) ثبت شده است. نسخه و مجوز اجزای ثالث در [اعلامیهٔ وابستگی‌ها](../THIRD_PARTY_NOTICES.md) آمده است. +Go برای دسترسی به فایل‌ها، UTF-8، JSON و آزمون فرایند ابزارهای استاندارد دارد. Cobra `1.10.2` بخش تعریف فرمان و اعتبارسنجی گزینه‌ها را بر عهده دارد. `go.mod` و `go.sum` نسخه‌ها و checksum وابستگی‌ها را ثبت می‌کنند. تصمیم جدید، اعتبارسنجی کامل فایل را حفظ می‌کند و مصرف حافظه را از اندازهٔ کل فایل جدا می‌کند. [ADR قرارداد](adr/0001-cli-contract.md) · [ADR خواندن کامل در v0.1.0](adr/0002-workspace-io.md) · [ADR جست‌وجوی جریانی](adr/0003-streaming-search.md) · [اعلامیهٔ وابستگی‌ها](../THIRD_PARTY_NOTICES.md) ## روند ساخت و شواهد آزمون @@ -129,12 +150,18 @@ Go برای دسترسی به فایل‌ها، UTF-8، JSON و آزمون فر اسکریپت `scripts/verify.ps1` قالب فایل‌های Go، یکپارچگی ماژول‌ها، `go vet`، آزمون‌های Go و ساخت بومی را بررسی می‌کند. آزمون‌ها یک باینری واقعی می‌سازند، آن را روی فایل‌های مصنوعی با `os/exec` اجرا می‌کنند و `stdout`، `stderr` و کد خروج را جداگانه می‌سنجند. نمونه‌های آزمون شامل ترتیب مسیر، متن Unicode، خطوط بلند، پسوندهای تکرارشونده، فایل‌های دارای NUL، UTF-8 نامعتبر و آرگومان نامعتبر است. آزمون اختصاصی Windows با یک فایل قفل‌شده نشان می‌دهد که خطای خواندن پس از چاپ نتایج قبلی چگونه گزارش می‌شود. اگر میزبان امکانات لازم برای بعضی نمونه‌های نام فایل، مجوز یا ساخت symlink را نداشته باشد، آزمون با دلیل مشخص به‌صورت `SKIP` ثبت می‌شود. -در CI، مرحلهٔ بسته‌بندی بعد از موفقیت هر سه اجرای بومی آغاز می‌شود. اسکریپت با `CGO_ENABLED=0` برای سه مقصد باینری می‌سازد، باینری و اعلامیه‌ها را در ZIP قرار می‌دهد و SHA-256 هر ZIP را ثبت می‌کند. کامپایل برای مقصدهای مختلف باینری قابل بسته‌بندی تولید می‌کند. شواهد اجرای بومی از آزمون‌هایی می‌آید که باینری را روی همان خانوادهٔ سیستم‌عامل ساخته و اجرا کرده‌اند. [شواهد آزمون](EVIDENCE.md) · [شواهد انتشار](RELEASE_EVIDENCE.md) +در CI، مرحلهٔ بسته‌بندی بعد از موفقیت هر سه اجرای بومی آغاز می‌شود. اسکریپت با `CGO_ENABLED=0` برای سه مقصد باینری می‌سازد، باینری و اعلامیه‌ها را در ZIP قرار می‌دهد و SHA-256 هر ZIP را ثبت می‌کند. شواهد اجرای بومی از آزمون‌هایی می‌آید که باینری را روی همان خانوادهٔ سیستم‌عامل ساخته و اجرا کرده‌اند. شواهد نسخهٔ پایدار و نامزد جریانی به کامیت‌های ساخت خودشان ارجاع می‌دهند. [شواهد آزمون](EVIDENCE.md) · [شواهد انتشار](RELEASE_EVIDENCE.md) + +## سنجش زمان و حافظه + +در سنجش Windows، باینری انتشار `0.1.0` و باینری نامزد روی دادهٔ مصنوعی یکسان اجرا شدند. سناریوها شامل تطبیق کم یا زیاد، یک خط بسیار بلند با تطبیق یا بدون آن، و یک درخت با ۱۰۲۴ فایل کوچک بودند. پیش از اندازه‌گیری، برابری نتیجهٔ دو نسخه بررسی شد. برای هر سناریو، زمان اجرا، نرخ پردازش ورودی و بیشترین اندازهٔ حافظهٔ مقیم فرایند یا Peak Working Set در پنج اجرا ثبت شد. برای بازتولید سنجش از نسخه‌های ثبت‌شدهٔ دو باینری و `scripts/benchmark.py` با CPython 3.11 یا جدیدتر استفاده کنید. خود اسکریپت داده‌های مصنوعی را می‌سازد. [اسکریپت بنچمارک](../scripts/benchmark.py) · [داده‌های خام اندازه‌گیری](BENCHMARKS_WINDOWS.json) + +در ورودی کم‌تطبیق ۹۶ میبی‌بایتی، میانهٔ اوج حافظه از `57.24 MiB` به `7.57 MiB` رسید و زمان میانه از `67.403 ms` به `56.175 ms` کاهش یافت. برای خط بدون تطبیق ۴۸ میبی‌بایتی، میانهٔ اوج حافظه از `56.31 MiB` به `7.32 MiB` رسید و زمان بیشتر شد. پردازش خط منطبق ۱۶ میبی‌بایتی هم در این آزمون حافظهٔ کمتری گرفت و زمان بیشتری برد. این نتایج به ورودی‌ها و دستگاه ثبت‌شده مربوط‌اند. زمان‌ها هزینهٔ راه‌اندازی ابزار و تولید خروجی را نیز شامل می‌شوند. [روش بازتولید و نتایج کامل](BENCHMARKS.md) ## محدودیت‌ها و شیوهٔ استفادهٔ مطمئن - دامنهٔ نسخهٔ فعلی جست‌وجوی literal روی فایل UTF-8، فیلتر پسوند و فهرست متادیتاست. فایل‌های پنهان در پیمایش لحاظ می‌شوند و قواعد فایل‌های ignore به انتخاب فایل اعمال نمی‌شوند. برای کنترل دامنه، ریشه و پسوندها را صریح انتخاب کنید. -- برنامه فهرست مسیرهای انتخاب‌شده را در حافظه مرتب می‌کند و حداکثر محتوای یک فایل جست‌وجو را در هر مرحله پردازش می‌کند. به همین دلیل، تعداد مسیرها و اندازهٔ بزرگ‌ترین فایل روی مصرف حافظه اثر دارند. عددی به‌عنوان سرعت یا کارایی تضمین‌شده منتشر نشده است. +- برنامه فهرست مسیرهای انتخاب‌شده را در حافظه مرتب می‌کند و برای تطبیق در مرز قطعه‌ها مقداری از بایت‌ها را متناسب با طول عبارت نگه می‌دارد. قالب‌بندی خروجی یک خط منطبقِ بسیار بلند همچنان می‌تواند حافظهٔ زیادی بخواهد. اگر رکوردهای در انتظار از ظرفیت حافظه عبور کنند، فضای موقت متناسب با حجم همان رکوردها مصرف می‌شود. خطای خواندن، نوشتن نتیجه یا دسترسی به فضای موقت کد خروج `2` دارد. - درخت فایل زنده است. تغییر هم‌زمان فایل یا جایگزینی مسیر داخل ریشه می‌تواند نتیجه یا خطای خواندن را تغییر دهد. برای بازتولید خروجی، هنگام اجرا درخت را ثابت نگه دارید. - در Unix، بایت نامعتبر UTF-8 در نام مسیر هنگام تولید JSON با نویسهٔ جایگزین نمایش داده می‌شود. NDJSON برای نام‌های عادی و دادهٔ ماشینی مناسب است و برای نگه‌داری نام‌های بایتی نامعتبر به‌صورت بدون اتلاف طراحی نشده است. - checksum تطابق بایت‌های بسته با فهرست همان اجرا را می‌سنجد. شواهد اصالت به منبع قابل‌اعتماد بسته و اجرای CI وابسته‌اند. بسته‌های این نسخه در برابر manifest همان اجرا بررسی می‌شوند. diff --git a/docs/RELEASE_EVIDENCE.md b/docs/RELEASE_EVIDENCE.md index 7991ce4..1dac71d 100644 --- a/docs/RELEASE_EVIDENCE.md +++ b/docs/RELEASE_EVIDENCE.md @@ -1,12 +1,40 @@ # A02 Developer CLI Toolkit release evidence -## Candidate and source +## Stable v0.1.1 + +The stable version uses streaming search with the reviewed literal-search and inspection contract. The public release supplies Windows amd64, Linux amd64 and macOS arm64 packages and tagged source archives. Its SHA-256 manifest applies to that exact package set. The previous RC and historical build records below describe their own source and bytes. [Stable release](https://github.com/soroushneyestani/developer-cli-toolkit/releases/tag/v0.1.1) · [Changelog](../CHANGELOG.md) + +## Open-source preparation + +Draft PR #2 adds the project MIT license, retains the existing dependency licenses, and requires them in new binary packages. The review added no stream-runtime change. All three local preparation archives passed CRC, checksum, license and machine-header checks and contained executables identical to the pinned RC. The PR's preparation summary records the exact hosted asset and test runs. [Publication checklist](../FINAL_PUBLICATION_CHECKLIST.md) · [Release procedure](releases/OPEN_SOURCE_RELEASE.md) · [Draft PR #2](https://github.com/soroushneyestani/developer-cli-toolkit/pull/2) + +## 0.1.1-rc.1 engineering candidate + +The pinned candidate was built by the private branch push workflow from commit `541aff83f8675b5d6aac9c98a28adcc1228fb052` on `codex/a02-streaming`. Its code is at checkpoint `aaf9a9c05b9a93fb77a517215c99dddc93a26df3`. Native Windows, Linux, and macOS verification and packaging passed on both the branch push and Draft PR runs. The subsequent evidence checkpoint keeps the runtime, tests, and packaging inputs from the pinned source. [Draft PR #2](https://github.com/soroushneyestani/developer-cli-toolkit/pull/2) · [Exact CI run 44540116482](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44540116482) · [Verified build artifact 14537687323](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44540116482/artifacts/14537687323) + +The authenticated download's outer ZIP is 9,474,410 bytes with SHA-256 `53afa2a5d787f023210e39a127d4bc2da12c86913efec3909bc7b80b798d6677`. Its three platform archives passed CRC and SHA-256 checks and contained the expected executable targets and licenses. The manifest's SHA-256 is `f770371ec7a65240881ffa898745426bbbc42765ebe64e3151ecd6e63066d45a`. The outer ZIP, platform archives, and manifest are retained privately under `dist/hosted-44540116482/` in the workspace. [Candidate SHA-256 manifest](releases/v0.1.1-rc.1-SHA256SUMS.txt) · [0.1.1-rc.1 build evidence](releases/v0.1.1-rc.1-build.json) + +The packaged Windows binary passed a direct smoke test with 5,002 ordered NDJSON records, dense temporary staging, late NUL and truncated UTF-8 suppression, boundary-spanning Unicode, CRLF and final CR, exits 0 through 2, and temporary-file cleanup. The packaged Windows executable matches the benchmarked candidate binary byte for byte. Linux and macOS native CI executed the CLI built on each runner. Distribution packages for those two targets were inspected for integrity and build settings. [Test summary](TEST_SUMMARY.md) + +The benchmark compares the released v0.1.0 binary with an exact streaming checkpoint build. It verifies output equivalence and measures time and peak working set on generated Windows workloads. This candidate keeps the ordinary validation buffers bounded and still materializes each complete matching line for output. Dense output can require space in the temporary directory. [Benchmark results](BENCHMARKS.md) · [Streaming ADR](adr/0003-streaming-search.md) + +A02 remains in `release_review` awaiting explicit final engineering acceptance. + +## Approved v0.1.0 release + +GitHub PR #1 was merged with both original parents preserved. The historical `v0.1.0` release points to the accepted commit `02472793619d8a644634068759ecb2e826a39797`. It was originally published privately. Its uploaded packages came from the exact main workflow run `44536777289`, artifact `14536722607`. Every uploaded asset matched its verified local copy byte for byte. [Historical release](https://github.com/soroushneyestani/developer-cli-toolkit/releases/tag/v0.1.0) · [Source and asset verification](releases/v0.1.0.md) · [Historical MIT grant](releases/v0.1.0-MIT.md) + +## Archived v0.1.0 review evidence + +The following sections record the artifact seen during review. Its checksums apply to those archived bytes. [Published asset manifest](releases/v0.1.0-SHA256SUMS.txt) + +### Candidate and source - Version `0.1.0`. The candidate archive was built from commit `1d41dcc0184a7fad5e09e1e7c9ee6cefc37dd930` on `codex/a02`. The pull request CI run started on November 19, 2026 at 13:25:48 CET and recorded success at 13:27:29 CET. [Private workflow run 44523796632](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44523796632) - Subsequent documentation-only CI runs verify their own source revisions. The candidate package remains pinned to run `44523796632` and artifact `14528472864` so readers can independently verify the exact archive reviewed here. -- The repository is private and the pull request targeting `main` is still Draft. [Draft pull request #1](https://github.com/soroushneyestani/developer-cli-toolkit/pull/1) +- The repository was private and PR #1 was Draft during this verification. The approved PR has since been merged. [Pull request #1](https://github.com/soroushneyestani/developer-cli-toolkit/pull/1) -## What was verified +### What was verified | Gate | Result and scope | | --- | --- | @@ -21,7 +49,7 @@ The native integration tests build and run executables on their own runners. The separate package build produces the distribution archives. Linux and macOS archive payloads were checked for integrity and architecture during review. Direct execution of those extracted payloads was outside this verification. [Test history](EVIDENCE.md) · [CLI contract](SPEC.md) -## Verified packages +### Verified packages GitHub artifact `14528472864` is **8,982,978 bytes**. Its outer `dct-packages.zip` SHA-256 is `2261c04556de25eb3d793d1b1da5ebc716171ccf450ec944d841d20652ef7fa1`. GitHub listed expiration on November 26, 2026 at 13:27:23 CET (`2026-11-26T12:27:23Z`). [Private dct-packages artifact](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44523796632/artifacts/14528472864) @@ -33,13 +61,13 @@ GitHub artifact `14528472864` is **8,982,978 bytes**. Its outer `dct-packages.zi The verified outer ZIP, the three target ZIPs, and their original `SHA256SUMS.txt` are retained privately in `dist/hosted-44523796632/` in the original workspace. This copy remains available locally when the GitHub Actions download expires. The checked-in manifest records the three target ZIP digests for this artifact. [Pinned SHA-256 manifest](RELEASE_SHA256SUMS.txt) -## Historical verification +### Historical verification The implementation baseline is `482ebacf9d2dcc940c1e6931652b49610dee797a`. Its native matrix and package job passed on November 18, 2026 in run `44307143679`, resolving the Windows CRLF checkout blocker. The dependency and history scanners reported no vulnerabilities and no leaks in that run. [Private workflow run 44307143679](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44307143679) Historical artifact `14428662773` is 8,982,494 bytes with outer SHA-256 `1630089350a96cc38169b634a7a5a5cf4ab8407c2b85f7cdf2c7df028b7c1d46`. Its listed expiration was November 25, 2026 at 13:49:02 CET. The corresponding local archives and manifest remain under `dist/hosted-44307143679/`. Each package set has its own ZIP digests. The three candidate executable payloads match the corresponding historical executable payloads byte for byte. [Historical private artifact](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44307143679/artifacts/14428662773) -## Reproduce the checks +### Reproduce the checks From the project directory with Go `1.27.4` and PowerShell 7 available, run the real verifier and packaging script as needed. @@ -48,13 +76,13 @@ pwsh -NoProfile -File scripts/verify.ps1 pwsh -NoProfile -File scripts/package.ps1 ``` -To verify the candidate download or retained copy, check `dct-packages.zip` with `Get-FileHash -Algorithm SHA256` against the outer digest above. Extract the bundle and verify the three target ZIPs using the manifest for artifact `14528472864`. The packaging script creates a new archive set with its own manifest. [README verification and extraction steps](../README.md#install-the-010-candidate) +To verify the candidate download or retained copy, check `dct-packages.zip` with `Get-FileHash -Algorithm SHA256` against the outer digest above. Extract the bundle and verify the three target ZIPs using the manifest for artifact `14528472864`. The packaging script creates a new archive set with its own manifest. [Pinned review manifest](RELEASE_SHA256SUMS.txt) -## Release review items +### Release review items - Product scope is recursive, literal, case-sensitive UTF-8 search and regular-file inspection. Hidden entries follow normal selection. Regex, stdin input, ignore-file processing, and numeric performance targets are outside the candidate scope. - The selected path list and a full search file affect memory use. Keep the live file tree stable for repeatable output. A read or write error can follow earlier results. Consumers should check the exit code before using all records as complete output. - Unix JSON paths containing invalid UTF-8 use replacement characters. Linux and macOS archives may extract with mode `0644`; set the execute bit when needed. - The packages are unsigned and include third-party notices and licenses. SHA-256 verifies package bytes against the pinned digests. Signing, public licensing and wider distribution remain separate review decisions. -- The project remains in `release_review` pending explicit user acceptance. Tagging `v0.1.0`, creating a private GitHub Release with the verified assets and checksums, and any PR merge require approval. [Draft pull request #1](https://github.com/soroushneyestani/developer-cli-toolkit/pull/1) +- The review gate for these materials was satisfied by the user's explicit v0.1.0 approval. The accepted merge and published binaries are recorded separately. [Published v0.1.0 evidence](releases/v0.1.0.md) - The review includes the user documentation and release notes. [Persian tutorial](LEARNING_FA.md) · [English website article](WEBSITE_EN.md) · [English Instagram copy](INSTAGRAM_EN.md) · [Changelog](../CHANGELOG.md) diff --git a/docs/SPEC.md b/docs/SPEC.md index 9086f0f..c3692bc 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -11,7 +11,7 @@ Executable: `dct`, an original implementation inspired by ripgrep behavior, with Use relative paths with `/` separators and lexicographic path ordering. Search line numbers start at 1. Support LF, CRLF, and unterminated final lines; exclude terminators from output. Reject empty literals, extra arguments, unknown flags, file roots, and extension filters lacking a leading dot or containing path separators. -Include hidden files. Do not interpret ignore files or follow symlinks; reject symlink roots. Inspect only regular files. Search skips files containing NUL or invalid UTF-8. Process one file at a time. Traversal/read failures are errors, not silent nonmatches. +Include hidden files. Ignore-file rules do not affect selection. Skip symlink entries during traversal and reject symlink roots. Inspect only regular files. Search reads one file at a time and publishes its records only after the source has been read successfully and validated in full. A NUL byte or invalid UTF-8 anywhere in the file discards every match from it. A source read failure returns an error even after invalid content has been detected. Keep the workspace stable while a command runs because traversal and reading observe a live tree. ## Output @@ -19,7 +19,11 @@ Search text: `path:line:text`. Inspect text: `pathbytes`. Text delimiters c Search JSON fields: `path` (string), `line` (integer), `text` (string). Inspect JSON fields: `path` (string), `bytes` (integer). Emit diagnostics only to stderr. Empty results emit no records. -Exit 0: search has matches, or inspection succeeds (including empty directories). Exit 1: completed search has no matches. Exit 2: usage, root, traversal, read, or output error. Partial results may precede errors; consumers must check exit status. An empty root argument is invalid. On Unix, NDJSON represents any invalid UTF-8 in filenames with replacement characters. +- Exit 0 means a search has matches or inspection succeeds, including in an empty directory. +- Exit 1 means a completed search has no matches. +- Exit 2 means usage, root, traversal, read, temporary storage, or output failed. Consumers must check exit status because errors can follow records from earlier files or records already written during output. + +An empty root argument is invalid. On Unix, NDJSON represents any invalid UTF-8 in filenames with replacement characters. ## Integration proof @@ -30,7 +34,8 @@ Build and invoke the binary using Go os/exec and synthetic temporary fixtures, w 3. Inspect: nested/empty directories, byte sizes, hidden files, spaces and delimiters in filenames, JSON escaping. 4. Safety: local symlinks, NUL files, invalid UTF-8, unreadable files. Explicitly skip permission/symlink tests with a reason when the host cannot enforce/create fixtures. Never test external targets. 5. Packaging: CGO-disabled Linux amd64, Windows amd64, macOS arm64 builds. Cross-compilation proves buildability only; run integration tests natively on all three OS families before release. +6. Streaming regressions cover buffer boundaries, long lines, a matched source range that changes before it can be staged, and suppression when NUL or invalid UTF-8 appears after earlier matches. [Resource limits and validation order in ADR 0003](adr/0003-streaming-search.md) ## Implementation order -Cobra skeleton and literal search with contract/misuse tests; extension filters; JSON; inspection; packaging and native CI. Performance benchmarking follows correctness; there is no numeric speed promise for v0.1. +The v0.1.0 baseline established the Cobra interface, contract tests, suffix filters, NDJSON, inspection, packaging, and native CI. The follow-up keeps that interface and replaces whole-file allocation with streaming and staged matches. Measure performance on reproducible synthetic datasets against the v0.1.0 baseline. The contract makes no numeric speed promise. diff --git a/docs/TASKS.md b/docs/TASKS.md index d6f8362..bdecf7d 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -12,6 +12,17 @@ - [x] Check hosted package integrity and execute the packaged Windows smoke fixture. - [x] Finish the README, changelog, Persian education, English website and Instagram copy, and release evidence. - [x] Reconcile the release evidence with CI run `44523796632`, artifact `14528472864`, and the retained private archive and manifest. -- [ ] Obtain explicit user acceptance of the A02 release review. +- [x] Obtain explicit user acceptance of v0.1.0. +- [x] Merge PR #1 preserving the original commits and verify `main`. +- [x] Publish v0.1.0 privately with packages built from the tagged `main` commit and verify all uploaded assets. +- [x] Stream source validation and preserve literal results, ordering, and process exit semantics. +- [x] Verify oversized lines, temporary match staging, read failures, and cleanup. +- [x] Compare v0.1.0 and the streaming build using reproducible time and memory measurements. +- [x] Verify the streaming candidate on native CI and check its exact distribution archive. +- [x] Review the streaming candidate and verify its contract, regression tests, and benchmark evidence. +- [x] Prepare the original MIT license, keep dependency licenses and notices, and audit the published surface and Git history. +- [x] Prepare the source build and release procedure, contribution and security policies, and publication documents. +- [x] Audit historical Git and GitHub email fields, verify the published assets and tag archives, and configure A02's verified noreply for future commits. [Publication decisions](../FINAL_PUBLICATION_DECISIONS.md) +- [ ] Obtain explicit final acceptance and resolve the historical disclosure and licensing decisions. [Final publication checklist](../FINAL_PUBLICATION_CHECKLIST.md) -The corrected hosted Windows checkout and the entire native matrix and packaging pipeline passed. The project remains in `release_review`. Tagging `v0.1.0` and creating a private release require explicit user approval. [Release evidence](RELEASE_EVIDENCE.md) +The project remains in `release_review` for the final engineering acceptance. [Release evidence](RELEASE_EVIDENCE.md) diff --git a/docs/TEST_SUMMARY.md b/docs/TEST_SUMMARY.md index 618e2c2..d1ce14e 100644 --- a/docs/TEST_SUMMARY.md +++ b/docs/TEST_SUMMARY.md @@ -1,8 +1,20 @@ -# A02 v0.1.0 test summary +# A02 verification summary + +## 0.1.1-rc.1 + +At source `541aff83f8675b5d6aac9c98a28adcc1228fb052`, the Windows, Linux, and macOS native gates passed formatting, module integrity, vet, integration tests, and build. Packaging passed after the matrix. The Linux dependency and Git history scans passed. [Exact CI run 44540116482](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44540116482) · [Verified build artifact 14537687323](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44540116482/artifacts/14537687323) · [0.1.1-rc.1 build evidence](releases/v0.1.1-rc.1-build.json) + +The streaming tests cover early matches followed by invalid UTF-8 or NUL, dense replay and cleanup, oversized lines, cross-buffer literals and Unicode, CRLF boundary handling, and read and output error behavior. Windows skips the colon/tab filename fixture and can skip the POSIX chmod fixture. The Windows sharing-violation test covers a read failure separately. [Integration tests](../search_test.go) · [Streaming fault tests](../stream_search_test.go) · [Windows read error test](../search_windows_test.go) + +The packaged Windows binary reproduced 5,002 ordered records with exit and spill-cleanup checks. The native Windows verifier passed locally, and 18 deterministic Windows fixtures matched v0.1.0 output and status byte for byte. Working set and elapsed time were measured separately on generated data. [Release evidence](RELEASE_EVIDENCE.md) · [Benchmark results](BENCHMARKS.md) + +## Pre-merge v0.1.0 verification + +The v0.1.0 review measurements and artifact references below describe the archived pre-merge evidence. The later approved main build has its own run and published asset checksums. [Published v0.1.0 evidence](releases/v0.1.0.md) The binary candidate was built and verified at `1d41dcc0184a7fad5e09e1e7c9ee6cefc37dd930` on `codex/a02`. All three native verification jobs and the subsequent packaging job passed. The candidate is pinned to this run and artifact for release review. [Private candidate CI run 44523796632](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44523796632) · [Private artifact 14528472864](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44523796632/artifacts/14528472864) -## Native verification +### Native verification | GitHub Actions runner | Result | Distribution package and binary type | | --- | --- | --- | @@ -14,7 +26,7 @@ The native tests compile and run the CLI against synthetic fixtures. They cover The candidate Linux scan steps finished successfully using `govulncheck v1.10.0` and `gitleaks v8.30.1`. These are scoped to the workflow's dependency and checked-out Git history checks. [CI workflow](../.github/workflows/ci.yml) -## Verified candidate artifact +### Verified candidate artifact The retained `dct-packages.zip` for artifact `14528472864` is 8,982,978 bytes. Its SHA-256 is `2261c04556de25eb3d793d1b1da5ebc716171ccf450ec944d841d20652ef7fa1`. The outer ZIP and all three inner ZIPs passed CRC checks. Every inner ZIP matched the bundled `SHA256SUMS.txt`, whose SHA-256 is `032ce1fe00289796f0f1b831b62c3c987e816e97d93b00589f918638daea0afa`. The archives include executables, release notes, and third-party notices and licenses. [Pinned checksum manifest](RELEASE_SHA256SUMS.txt) · [Release evidence](RELEASE_EVIDENCE.md) @@ -30,13 +42,13 @@ The Windows executable was extracted directly from the verified candidate archiv The Linux and macOS distribution executables were checked for archive integrity and target architecture. Direct execution of those extracted distribution executables remains outside this review. Native CLI execution on both platforms was covered by the integration tests. -## Historical verification +### Historical verification Run `44307143679` at implementation checkpoint `482ebacf9d2dcc940c1e6931652b49610dee797a` passed the same runner matrix and packaging. The historical Windows archive's executable passed a separate smoke test. The executable payloads in the candidate and historical packages were compared byte for byte and matched for all three targets. [Historical CI run 44307143679](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44307143679) · [Verification history](EVIDENCE.md) Historical artifact `14428662773` had outer SHA-256 `1630089350a96cc38169b634a7a5a5cf4ab8407c2b85f7cdf2c7df028b7c1d46`. Its ZIP digests apply to that artifact only. -## Outstanding limitations +### Outstanding limitations - Search is literal, case-sensitive, and operates on UTF-8 text. Hidden entries participate in selection. Regex, stdin input, and ignore-file processing are outside v0.1.0. - Memory grows with the selected path list and the largest search file. Filesystem changes during execution can affect results. A read or write error can leave earlier records on stdout before exit 2. diff --git a/docs/WEBSITE_EN.md b/docs/WEBSITE_EN.md index 420c21e..4d3900f 100644 --- a/docs/WEBSITE_EN.md +++ b/docs/WEBSITE_EN.md @@ -18,18 +18,28 @@ dct search TODO demo --ext .txt --json Search records contain `path`, `line`, and `text`. Inspection records contain `path` and `bytes`. Exit code `0` means a search found results or an inspection completed. Exit code `1` means a search completed without a match. Exit code `2` covers invalid input and runtime errors. Diagnostics go to standard error. A script should check the exit code before treating output as complete because a read error can occur after earlier results have been emitted. -## Design decisions +## Streaming search with whole-file validation -Cobra parses commands and flags in `main.go`, where text and JSON output are also formatted. The workspace layer in `workspace.go` opens the requested directory using Go's `os.OpenRoot`, enumerates matching regular files, and sorts their relative paths. Paths use forward slashes on each platform. Enumeration includes qualifying hidden files and files listed in ignore rules, skips symbolic-link entries, and applies the requested suffix filters. The command rejects a symbolic link supplied as the root. +Cobra parses commands and flags in `main.go`, where text and JSON output are also formatted. The workspace layer in `workspace.go` opens the requested directory using Go's `os.OpenRoot`, enumerates matching regular files, and sorts their relative paths. Paths use forward slashes on each platform. Enumeration includes qualifying hidden files, skips symbolic-link entries, and applies the requested suffix filters. The command rejects a symbolic link supplied as the root. Ignore rules are outside the CLI contract. -Search reads one file at a time and validates its whole contents before emitting matches from that file. This matters when a file appears to contain a valid match before an invalid UTF-8 sequence or a NUL byte. The file is skipped in either case. Search handles LF, CRLF, and an unterminated final line. Inspection reads metadata for byte sizes, with no need to open file contents. +Version `0.1.0` read an entire file into memory before scanning it. I kept the whole-file validation guarantee and changed how v0.1.1 uses memory. It checks for invalid UTF-8 and NUL through a reusable 64 KiB reader. Matching records stay pending until the source reaches a clean end of file. If invalid data appears near the end, the command discards the file's pending matches, even if the first line looked usable. -The selected paths remain in memory for sorting, and whole-file validation uses memory proportional to the largest file read during the search. A stable workspace gives reproducible results because the filesystem stays live during a scan. Newline-delimited JSON preserves record boundaries when names or matched text contain delimiters. On Unix, filenames containing invalid UTF-8 bytes are represented with replacement characters in JSON. +The streaming implementation holds up to 256 KiB of encoded matches in memory per file and uses temporary disk when the pending results exceed that budget. It checks long lines in pieces, retaining only enough UTF-8 and literal bytes to handle buffer boundaries. Unmatched long lines require no second read. For a matching long line, the CLI rereads just that range from the same open file and checks its SHA-256 against the original scan before output. LF, CRLF, and unterminated final lines retain their original behavior. + +The sorted path list and the longest emitted line still affect memory, and dense matches can incur temporary I/O. Inspection reads file sizes from metadata. A stable workspace gives repeatable results because traversal and reads observe a live filesystem. On Unix, filenames containing invalid UTF-8 bytes are represented with replacement characters in JSON. + +## Measuring the tradeoff + +I compared the streaming candidate with the released `v0.1.0` binary on five generated Windows workloads, checking output equivalence before measuring. Each median uses five fresh CLI processes. On the 96 MiB sparse fixture, median peak working set fell from 57.24 to 7.57 MiB. The 48 MiB unmatched line went from 56.31 to 7.32 MiB, with a longer median runtime. The 16 MiB matching line also reduced memory and took longer, with median time rising from 40.292 to 69.589 ms. These measurements include CLI startup and output encoding and apply to the recorded inputs and machine. [Benchmark method and full results](https://github.com/soroushneyestani/developer-cli-toolkit/blob/541aff83f8675b5d6aac9c98a28adcc1228fb052/docs/BENCHMARKS.md) ## Verification and packaging -The release candidate passed native CI on Windows, Linux, and macOS. Integration tests build and invoke the executable against synthetic workspaces, checking standard output, standard error, and exit status separately. The cases cover deterministic ordering, long lines, Unicode, malformed usage, and file handling. Some permission and filename fixtures depend on host capabilities. A Windows-specific test uses a sharing lock to exercise partial output followed by a read error. +The `v0.1.0` release comes from the accepted main commit. Integration tests build and invoke the CLI on Windows, Linux, and macOS, checking standard output, standard error, and exit status separately. Version `v0.1.1` adds coverage for validation across buffer boundaries, long lines, and a late invalid byte after matches have already been staged. Some permission and filename fixtures depend on host capabilities. A Windows-specific test uses a sharing lock to exercise a read error after output from an earlier file. The first hosted Windows run exposed a Git checkout issue. CRLF conversion made the Go source files appear unformatted to `gofmt`. I set a repository attribute to keep Go source checkouts in LF, then verified the corrected native matrix. -After the native jobs passed, a separate packaging job built ZIP archives for Windows amd64, Linux amd64, and macOS arm64. Each archive includes the executable and dependency notices. The job also generates a SHA-256 manifest for checking the ZIPs before extraction. The native results cover executables built for the tests, and the packaging job records which archives were produced. +The stable `v0.1.1` release provides ZIPs for Windows amd64, Linux amd64 and macOS arm64. Its packaging job follows successful native CI. The packages include the project MIT license and dependency notices, and the release includes a SHA-256 manifest and release notes. [v0.1.1 release](https://github.com/soroushneyestani/developer-cli-toolkit/releases/tag/v0.1.1) · [Streaming review](https://github.com/soroushneyestani/developer-cli-toolkit/pull/2) + +## Source and builds + +The project repository contains the complete Go source, the CLI contract, integration tests, packaging instructions, and the benchmark harness. The original project is available publicly under MIT. Check out the release tag to build the same source used for the stable downloads. [Project source](https://github.com/soroushneyestani/developer-cli-toolkit) diff --git a/docs/adr/0002-workspace-io.md b/docs/adr/0002-workspace-io.md index 6b1656a..2a1e210 100644 --- a/docs/adr/0002-workspace-io.md +++ b/docs/adr/0002-workspace-io.md @@ -1,6 +1,6 @@ # ADR 0002: Scoped filesystem reads and complete-file validation -Status: accepted +Status: accepted for v0.1.0. The [streaming search ADR](0003-streaming-search.md) supersedes the complete-file allocation decision. Filesystem scope and ordering still use this design. `dct` checks that the supplied root is a directory and rejects a symbolic link at that path. It opens the directory with `os.OpenRoot` to constrain descendant operations to the opened tree. The filesystem walk skips symlink entries and sorts all selected, slash-separated paths because recursive directory order can differ from relative path order. diff --git a/docs/adr/0003-streaming-search.md b/docs/adr/0003-streaming-search.md new file mode 100644 index 0000000..f349fea --- /dev/null +++ b/docs/adr/0003-streaming-search.md @@ -0,0 +1,25 @@ +# ADR 0003: Stream source files and stage matches until validation + +Status: accepted for the 0.1.1-rc.1 implementation. + +## Context + +The original implementation read an entire file into memory before looking for matches. Complete validation matters because a match can appear before a NUL byte or an invalid UTF-8 sequence. The CLI contract discards all matches from such a file. On common inputs with short lines, keeping a complete source file in memory also makes process memory depend on file size. + +## Decision + +Read one source file at a time from the opened workspace. A reusable 64 KiB buffered reader supplies the search. If a logical line fits in the buffer, validate its UTF-8 and NUL rules and match it directly, using the text without its documented terminator. A final line without LF is processed as-is. + +Scan a longer line in fixed-size fragments. Keep up to three bytes for an incomplete UTF-8 rune, a pending carriage return for CRLF detection, and overlap proportional to the literal length for matches crossing fragments. Hash the text of the long line while scanning it. An unmatched line requires no full-line allocation, staging, or second read. For a matching line, read the bounded source range again through the same open file handle and confirm its SHA-256 before accepting the staged result. Changed or truncated content can raise a staging error. The workspace still needs to remain stable during traversal and reads. + +Stage matching records until the source reaches a clean end of file. Up to 256 KiB of encoded matches per file fit in memory. A larger set of matches spills to a temporary file created on demand. Each record has a 16-byte little-endian header with the line number and text byte length, followed by the line text without its terminator. Once the file is validated, replay the staged records in line order through the usual text or JSON renderer. Only matching records go to staging. + +If invalid data follows earlier matches, discard the stage and consume the remaining source bytes so a later read error still produces exit 2. Temporary staging is closed and removed as the operation unwinds. A staging I/O failure can produce exit 2 for an otherwise valid file. + +## Consequences + +Ordinary scans read the source once. Matching lines that cross the reader capacity require a second read limited to the matched line. Moderately sized result sets need only in-memory staging. Dense results can use temporary disk proportional to their encoded matches and incur an additional write and read. This path requires writable temporary storage. A temporary file can contain input text, so it is created with restricted permissions where supported and removed during ordinary cleanup. Process termination can interrupt cleanup. + +During the scan, memory includes the sorted path list, the literal and its boundary overlap, and the fixed-size buffers. Emitting a result still requires memory proportional to the longest matching line. The implementation has no fixed maximum line length. A single very long matching line can require substantial output memory, and a large tree can retain many paths. + +This decision preserves the command interface, skip rules, relative path ordering, and exit codes. It supersedes only the whole-file allocation decision. [Previous workspace I/O decision](0002-workspace-io.md) · [CLI contract](../SPEC.md) diff --git a/docs/releases/OPEN_SOURCE_RELEASE.md b/docs/releases/OPEN_SOURCE_RELEASE.md new file mode 100644 index 0000000..84a8686 --- /dev/null +++ b/docs/releases/OPEN_SOURCE_RELEASE.md @@ -0,0 +1,33 @@ +# Open-source release procedure + +The owner approved public MIT distribution of eligible original material in the existing repository. The historical `v0.1.0` tag and its assets trace to their original main build. PR #2 carries streaming and the stable `v0.1.1` preparation. [Private baseline](v0.1.0.md) · [Draft PR #2](https://github.com/soroushneyestani/developer-cli-toolkit/pull/2) · [Publication checklist](../../FINAL_PUBLICATION_CHECKLIST.md) + +## Review before a visibility change + +Confirm the owner holds the rights to license the original A02 work. Review the historical author metadata, pull requests, older releases and retained Actions records for public disclosure. GitHub exposes the code and Actions history and logs when a repository changes from private to public. Review how to license or retain the historical `v0.1.0` source and binaries, which were built before the project MIT notice was present. Keep their existing tag, assets and checksums traceable to their original build. [Project license](../../LICENSE) · [Third-party notices](../../THIRD_PARTY_NOTICES.md) · [GitHub visibility changes](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/managing-repository-settings/setting-repository-visibility#making-a-repository-public) + +## Build the approved release + +1. Review the stable version update before merging. Confirm that `dct --version` would report `0.1.1` and that the changelog and known limitations agree. Accept the exact PR revision and preserve its commits through a merge commit. +2. Wait for the native matrix and packaging to pass on the resulting `main` commit. Use the push run for the exact source SHA. Match the final tag to that SHA. [Verify and package workflow](../../.github/workflows/ci.yml) +3. Recheck the three target ZIPs, `SHA256SUMS.txt`, version output, and smoke results. Check each ZIP for the original project `LICENSE`, `THIRD_PARTY_NOTICES.md`, bundled license texts, and changelog. Retain the exact artifact and record its provenance. +4. Check a source archive of that same commit. It should contain the Go source, `go.mod`, `go.sum`, the license, and the build and test instructions. Build and test from the extracted tree. +5. After separate public-visibility approval, verify from an unauthenticated session that visitors can read and clone `main` and download the release tag's source ZIP or tarball. The release should link to the source tag and offer the verified binaries, SHA-256 manifest, release notes and known limitations. [GitHub source archives](https://docs.github.com/en/repositories/working-with-files/using-files/downloading-source-code-archives) +6. Verify the public sources and downloadable assets against the approved ref and SHA-256 manifest. Confirm branch rules and private vulnerability reporting, then publish the portfolio and social copy with working public links. + +The `0.1.1-rc.1` review builds have prerelease version output. The historical RC and preparation packages remain useful as evidence for their own revisions. The eventual stable assets need their own exact source and checksums. [Release evidence](../RELEASE_EVIDENCE.md) + +## GitHub settings for launch + +The default branch is `main`. Keep merge commits enabled. On the public repository, protect `main` by requiring a PR, resolved conversations, current CI and the checks below. Block force pushes and branch deletion. Use merge-commit history. Set the required approval count to zero for the sole maintainer. Keep the PR, CI and conversation-resolution requirements. [GitHub protected branches](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches) + +- `Native verification (ubuntu-24.04)` +- `Native verification (windows-2025)` +- `Native verification (macos-15)` +- `Package binaries` + +GitHub rejected private ruleset inspection with a plan restriction on the current repository. Record the protections as recommendations until available and verify their effective state around the visibility transition. Enable private vulnerability reporting when GitHub makes it available and check the reporting form. Keep the current descriptive repository title, project homepage, and accurate Go, CLI, search, inspection, and NDJSON topics. [GitHub vulnerability reporting](https://docs.github.com/en/code-security/how-tos/report-and-fix-vulnerabilities/configure-vulnerability-reporting/configure-for-a-repository) + +## Limits to disclose + +The CLI performs deterministic, literal search on a stable input tree. Paths and the largest emitted record affect memory, and dense matching output can require temporary disk. The Windows benchmark compares specific synthetic fixtures. The oversized matching line uses less memory and takes longer than `v0.1.0` on that fixture. Binaries are unsigned. [CLI contract](../SPEC.md) · [Benchmark evidence](../BENCHMARKS.md) diff --git a/docs/releases/v0.1.0-MIT.md b/docs/releases/v0.1.0-MIT.md new file mode 100644 index 0000000..c63d2a2 --- /dev/null +++ b/docs/releases/v0.1.0-MIT.md @@ -0,0 +1,9 @@ +# MIT grant for original v0.1.0 material + +Copyright (c) 2026 Soroush Neyestani. + +Soroush Neyestani, as the project owner and authorized copyright holder, grants the permissions in the project [MIT License](../../LICENSE) for the original Developer CLI Toolkit material in tag `v0.1.0` at commit `02472793619d8a644634068759ecb2e826a39797` for which he holds the necessary rights. This grant covers the eligible original source and associated documentation at that revision and the corresponding original portions of the executables in the three historical binary archives identified by the [original SHA-256 manifest](v0.1.0-SHA256SUMS.txt). + +The author authorized this grant as part of the public launch of the existing repository. The historical GitHub-generated source archives and released binary ZIPs were created before a project MIT file was included. When redistributing eligible original material from them, include the project copyright and MIT permission notice. The third-party portions remain governed by the notices and license texts accompanying those archives. + +The historical lightweight tag and original asset bytes identify the original build. [Historical release record](v0.1.0.md) · [Third-party notices](../../THIRD_PARTY_NOTICES.md) diff --git a/docs/releases/v0.1.0-SHA256SUMS.txt b/docs/releases/v0.1.0-SHA256SUMS.txt new file mode 100644 index 0000000..646b313 --- /dev/null +++ b/docs/releases/v0.1.0-SHA256SUMS.txt @@ -0,0 +1,3 @@ +4c7e53662296d38c3f34d61959c16b8121dd55ce719246527f18996c6a9c6f4a dct-linux-amd64.zip +55ef7929b84336834e7f92593a1d7b538ff4f2b310ce7e55b08fbf64c0e3ffe4 dct-windows-amd64.zip +fd3ee17e206a6d79c8b5cd80842b589478b615022efd820a846dec8f3059ad13 dct-darwin-arm64.zip diff --git a/docs/releases/v0.1.0.md b/docs/releases/v0.1.0.md new file mode 100644 index 0000000..d9d8f42 --- /dev/null +++ b/docs/releases/v0.1.0.md @@ -0,0 +1,15 @@ +# Historical v0.1.0 release + +The approved build was published on November 19, 2026 while the `developer-cli-toolkit` repository was private. The lightweight tag `v0.1.0` resolves to the accepted main commit `02472793619d8a644634068759ecb2e826a39797`. The merge preserves its two parents `1dbf562db926c19d2c68ccfdc4052b1e52ed8cfd` and `7927304ab99a88f5ec6d5f1db7f3a68b2ede2317`. [Historical release](https://github.com/soroushneyestani/developer-cli-toolkit/releases/tag/v0.1.0) · [Approved PR #1](https://github.com/soroushneyestani/developer-cli-toolkit/pull/1) + +## Build provenance + +The approved PR passed native CI and packaging at its review tip. Main push run `44536777289` passed native verification on Windows, Linux, and macOS and packaged the exact tagged commit using Go 1.27.4. Its Linux job passed the dependency and Git history scans. The published ZIPs came from artifact `14536722607` (8,982,977 bytes, outer SHA-256 `691270afb391c8eb091c01bda54d8211664e5a3d4ac8b383ed9b7b6e0ced8df9`). The earlier PR review artifact has its own revision, outer ZIP and manifest. [Main workflow](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44536777289) · [Main build artifact](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44536777289/artifacts/14536722607) + +## Asset verification + +- Checked the outer ZIP and all three platform ZIPs for CRC integrity. The three inner archives matched the downloaded manifest and contained the expected executables, changelog, third-party notices and licenses. +- Verified the three binary target settings and CGO-disabled build metadata. The extracted Windows binary reported `0.1.0`, reproduced the expected literal-search record, and reported the fixture's 24-byte file size. +- Downloaded the five uploaded assets from the private release and compared them byte for byte with the verified local copies. The published `SHA256SUMS.txt` is 261 bytes with SHA-256 `47c0020aa9c2317b9431c6e1c0929a229f5a05934c16a40fec15a902da232616`. [Committed checksum manifest](v0.1.0-SHA256SUMS.txt) + +The released v0.1.0 binaries use whole-file search validation and are unsigned. The release's notes include known limitations, and the `v0.1.0` tag preserves the historical CLI contract and implementation. The historical source archives and original binary ZIPs predate inclusion of the project-level MIT file. [Express MIT grant for eligible original material](v0.1.0-MIT.md) diff --git a/docs/releases/v0.1.1-rc.1-SHA256SUMS.txt b/docs/releases/v0.1.1-rc.1-SHA256SUMS.txt new file mode 100644 index 0000000..239780c --- /dev/null +++ b/docs/releases/v0.1.1-rc.1-SHA256SUMS.txt @@ -0,0 +1,3 @@ +e105c75b1769d7656d85011cdf9bd2ee33c0bab0cbef3cfbf411a2c30a35faad dct-linux-amd64.zip +a62da09e8797b5a163b3d9c1120386c0e9f4b4681b73d10c14e742ebfe20d5e0 dct-windows-amd64.zip +f6a35da05264460d60f80659efa8c18512508db328fb826d26eb7512c1ec1037 dct-darwin-arm64.zip diff --git a/docs/releases/v0.1.1-rc.1-build.json b/docs/releases/v0.1.1-rc.1-build.json new file mode 100644 index 0000000..1462cf6 --- /dev/null +++ b/docs/releases/v0.1.1-rc.1-build.json @@ -0,0 +1,198 @@ +{ + "source_commit": "541aff83f8675b5d6aac9c98a28adcc1228fb052", + "branch": "codex/a02-streaming", + "mode": "candidate", + "repository_visibility": "private", + "pull_request": { + "baseRefName": "main", + "headRefName": "codex/a02-streaming", + "headRefOid": "541aff83f8675b5d6aac9c98a28adcc1228fb052", + "isDraft": true, + "number": 2, + "url": "https://github.com/soroushneyestani/developer-cli-toolkit/pull/2" + }, + "released_main": "02472793619d8a644634068759ecb2e826a39797", + "published_releases": [ + "v0.1.0" + ], + "run": { + "id": 44540116482, + "event": "push", + "status": "completed", + "conclusion": "success", + "head_sha": "541aff83f8675b5d6aac9c98a28adcc1228fb052", + "html_url": "https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44540116482", + "run_started_at": "2026-11-19T14:06:04Z", + "updated_at": "2026-11-19T14:08:28Z" + }, + "jobs": [ + { + "name": "Native verification (ubuntu-24.04)", + "status": "completed", + "conclusion": "success", + "html_url": "https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44540116482/job/135615855694" + }, + { + "name": "Native verification (macos-15)", + "status": "completed", + "conclusion": "success", + "html_url": "https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44540116482/job/135615856291" + }, + { + "name": "Native verification (windows-2025)", + "status": "completed", + "conclusion": "success", + "html_url": "https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44540116482/job/135615856345" + }, + { + "name": "Package binaries", + "status": "completed", + "conclusion": "success", + "html_url": "https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44540116482/job/135616514302" + } + ], + "runs_for_commit": [ + { + "id": 44540134558, + "event": "pull_request", + "status": "completed", + "conclusion": "success", + "head_sha": "541aff83f8675b5d6aac9c98a28adcc1228fb052", + "html_url": "https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44540134558", + "run_started_at": "2026-11-19T14:06:10Z", + "updated_at": "2026-11-19T14:08:32Z" + }, + { + "id": 44540116482, + "event": "push", + "status": "completed", + "conclusion": "success", + "head_sha": "541aff83f8675b5d6aac9c98a28adcc1228fb052", + "html_url": "https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44540116482", + "run_started_at": "2026-11-19T14:06:04Z", + "updated_at": "2026-11-19T14:08:28Z" + } + ], + "draft_pr_jobs": [ + { + "name": "Native verification (macos-15)", + "status": "completed", + "conclusion": "success", + "html_url": "https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44540134558/job/135615918254" + }, + { + "name": "Native verification (ubuntu-24.04)", + "status": "completed", + "conclusion": "success", + "html_url": "https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44540134558/job/135615918930" + }, + { + "name": "Native verification (windows-2025)", + "status": "completed", + "conclusion": "success", + "html_url": "https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44540134558/job/135615919135" + }, + { + "name": "Package binaries", + "status": "completed", + "conclusion": "success", + "html_url": "https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44540134558/job/135616762142" + } + ], + "artifact": { + "id": 14537687323, + "name": "dct-packages", + "digest": "sha256:53afa2a5d787f023210e39a127d4bc2da12c86913efec3909bc7b80b798d6677", + "size_in_bytes": 9474410, + "expires_at": "2026-11-26T14:08:24Z" + }, + "selected_log_lines": [ + "Native verification (ubuntu-24.04)\tVerify native CLI\t2026-11-19T14:06:34.0073360Z --- PASS: TestSearchCLI/UTF-8_across_read_boundaries_and_final_carriage_return (0.01s)", + "Native verification (ubuntu-24.04)\tVerify native CLI\t2026-11-19T14:06:34.0095667Z --- PASS: TestSearchCLI/late_invalid_bytes_discard_staged_matches (0.02s)", + "Native verification (ubuntu-24.04)\tVerify native CLI\t2026-11-19T14:06:34.0129052Z --- PASS: TestSearchCLI/high-output_file_replays_records_in_order (0.03s)", + "Native verification (ubuntu-24.04)\tVerify native CLI\t2026-11-19T14:06:34.0189131Z --- PASS: TestCollectMatchesReturnsLateSourceReadErrors (0.00s)", + "Native verification (ubuntu-24.04)\tVerify native CLI\t2026-11-19T14:06:34.0215885Z --- PASS: TestCollectMatchesDefersStagingErrorUntilValidatedEOF (0.00s)", + "Native verification (ubuntu-24.04)\tVerify native CLI\t2026-11-19T14:06:34.0260818Z --- PASS: TestLongLineStagingRejectsChangedBytes (0.00s)", + "Native verification (ubuntu-24.04)\tVerify native CLI\t2026-11-19T14:06:34.0269094Z --- PASS: TestLongLineStagingRejectsChangedBytes/memory (0.00s)", + "Native verification (ubuntu-24.04)\tVerify native CLI\t2026-11-19T14:06:34.0283694Z --- PASS: TestLongLineStagingRejectsChangedBytes/spill (0.00s)", + "Native verification (ubuntu-24.04)\tVerify native CLI\t2026-11-19T14:06:34.0312092Z --- PASS: TestLongUnmatchedLineDoesNotStage (0.00s)", + "Native verification (ubuntu-24.04)\tVerify native CLI\t2026-11-19T14:06:34.0328319Z --- PASS: TestLongLiteralCrossesSeveralFragments (0.00s)", + "Native verification (ubuntu-24.04)\tVerify native CLI\t2026-11-19T14:06:34.0332582Z --- PASS: TestSearchFilesRemovesSpill (0.01s)", + "Native verification (ubuntu-24.04)\tVerify native CLI\t2026-11-19T14:06:34.0333547Z --- PASS: TestSearchFilesRemovesSpill/valid_file (0.00s)", + "Native verification (ubuntu-24.04)\tVerify native CLI\t2026-11-19T14:06:34.0334575Z --- PASS: TestSearchFilesRemovesSpill/invalid_file (0.00s)", + "Native verification (ubuntu-24.04)\tVerify native CLI\t2026-11-19T14:06:34.0335619Z --- PASS: TestSearchFilesRemovesSpill/output_error (0.00s)", + "Native verification (ubuntu-24.04)\tVerify native CLI\t2026-11-19T14:06:35.4497769Z Formatting, module integrity, vet, tests, and native build passed.", + "Native verification (ubuntu-24.04)\tScan Go dependencies\t2026-11-19T14:06:38.1782965Z No vulnerabilities found.", + "Native verification (ubuntu-24.04)\tScan Git history for secrets\t2026-11-19T14:06:38.7313820Z 2:06PM INF no leaks found", + "Native verification (macos-15)\tVerify native CLI\t2026-11-19T14:06:16.4325020Z --- PASS: TestSearchCLI/UTF-8_across_read_boundaries_and_final_carriage_return (0.01s)", + "Native verification (macos-15)\tVerify native CLI\t2026-11-19T14:06:16.4325970Z --- PASS: TestSearchCLI/late_invalid_bytes_discard_staged_matches (0.04s)", + "Native verification (macos-15)\tVerify native CLI\t2026-11-19T14:06:16.4326460Z --- PASS: TestSearchCLI/high-output_file_replays_records_in_order (0.02s)", + "Native verification (macos-15)\tVerify native CLI\t2026-11-19T14:06:16.4331710Z --- PASS: TestCollectMatchesReturnsLateSourceReadErrors (0.00s)", + "Native verification (macos-15)\tVerify native CLI\t2026-11-19T14:06:16.4332440Z --- PASS: TestCollectMatchesDefersStagingErrorUntilValidatedEOF (0.00s)", + "Native verification (macos-15)\tVerify native CLI\t2026-11-19T14:06:16.4352030Z --- PASS: TestLongLineStagingRejectsChangedBytes (0.00s)", + "Native verification (macos-15)\tVerify native CLI\t2026-11-19T14:06:16.4352550Z --- PASS: TestLongLineStagingRejectsChangedBytes/memory (0.00s)", + "Native verification (macos-15)\tVerify native CLI\t2026-11-19T14:06:16.4354110Z --- PASS: TestLongLineStagingRejectsChangedBytes/spill (0.00s)", + "Native verification (macos-15)\tVerify native CLI\t2026-11-19T14:06:16.4359480Z --- PASS: TestLongUnmatchedLineDoesNotStage (0.00s)", + "Native verification (macos-15)\tVerify native CLI\t2026-11-19T14:06:16.4360970Z --- PASS: TestLongLiteralCrossesSeveralFragments (0.00s)", + "Native verification (macos-15)\tVerify native CLI\t2026-11-19T14:06:16.4432590Z --- PASS: TestSearchFilesRemovesSpill (0.01s)", + "Native verification (macos-15)\tVerify native CLI\t2026-11-19T14:06:16.4433470Z --- PASS: TestSearchFilesRemovesSpill/valid_file (0.00s)", + "Native verification (macos-15)\tVerify native CLI\t2026-11-19T14:06:16.4434310Z --- PASS: TestSearchFilesRemovesSpill/invalid_file (0.00s)", + "Native verification (macos-15)\tVerify native CLI\t2026-11-19T14:06:16.4435160Z --- PASS: TestSearchFilesRemovesSpill/output_error (0.00s)", + "Native verification (macos-15)\tVerify native CLI\t2026-11-19T14:06:17.3038040Z Formatting, module integrity, vet, tests, and native build passed.", + "Native verification (windows-2025)\tVerify native CLI\t2026-11-19T14:06:58.1227144Z --- SKIP: TestInspectAndOptionsCLI/inspect_JSON_escapes_filename_delimiters (0.00s)", + "Native verification (windows-2025)\tVerify native CLI\t2026-11-19T14:06:59.2771059Z --- PASS: TestSearchCLI/UTF-8_across_read_boundaries_and_final_carriage_return (0.03s)", + "Native verification (windows-2025)\tVerify native CLI\t2026-11-19T14:06:59.2772657Z --- PASS: TestSearchCLI/late_invalid_bytes_discard_staged_matches (0.05s)", + "Native verification (windows-2025)\tVerify native CLI\t2026-11-19T14:06:59.2773484Z --- PASS: TestSearchCLI/high-output_file_replays_records_in_order (0.03s)", + "Native verification (windows-2025)\tVerify native CLI\t2026-11-19T14:06:59.2781986Z --- SKIP: TestSearchCLI/unreadable_file_is_an_error (0.00s)", + "Native verification (windows-2025)\tVerify native CLI\t2026-11-19T14:07:00.1724366Z --- PASS: TestSearchReportsWindowsSharingViolation (0.80s)", + "Native verification (windows-2025)\tVerify native CLI\t2026-11-19T14:07:00.1725621Z --- PASS: TestCollectMatchesReturnsLateSourceReadErrors (0.00s)", + "Native verification (windows-2025)\tVerify native CLI\t2026-11-19T14:07:00.1727073Z --- PASS: TestCollectMatchesDefersStagingErrorUntilValidatedEOF (0.00s)", + "Native verification (windows-2025)\tVerify native CLI\t2026-11-19T14:07:00.1729116Z --- PASS: TestLongLineStagingRejectsChangedBytes (0.00s)", + "Native verification (windows-2025)\tVerify native CLI\t2026-11-19T14:07:00.1729726Z --- PASS: TestLongLineStagingRejectsChangedBytes/memory (0.00s)", + "Native verification (windows-2025)\tVerify native CLI\t2026-11-19T14:07:00.1731675Z --- PASS: TestLongLineStagingRejectsChangedBytes/spill (0.00s)", + "Native verification (windows-2025)\tVerify native CLI\t2026-11-19T14:07:00.1732801Z --- PASS: TestLongUnmatchedLineDoesNotStage (0.00s)", + "Native verification (windows-2025)\tVerify native CLI\t2026-11-19T14:07:00.1733732Z --- PASS: TestLongLiteralCrossesSeveralFragments (0.00s)", + "Native verification (windows-2025)\tVerify native CLI\t2026-11-19T14:07:00.1735861Z --- PASS: TestSearchFilesRemovesSpill (0.01s)", + "Native verification (windows-2025)\tVerify native CLI\t2026-11-19T14:07:00.1736379Z --- PASS: TestSearchFilesRemovesSpill/valid_file (0.00s)", + "Native verification (windows-2025)\tVerify native CLI\t2026-11-19T14:07:00.1736957Z --- PASS: TestSearchFilesRemovesSpill/invalid_file (0.00s)", + "Native verification (windows-2025)\tVerify native CLI\t2026-11-19T14:07:00.1737540Z --- PASS: TestSearchFilesRemovesSpill/output_error (0.00s)", + "Native verification (windows-2025)\tVerify native CLI\t2026-11-19T14:07:03.5634358Z Formatting, module integrity, vet, tests, and native build passed." + ], + "retained_package": { + "retained_under": "dist/hosted-44540116482", + "manifest_sha256": "f770371ec7a65240881ffa898745426bbbc42765ebe64e3151ecd6e63066d45a", + "packages": { + "dct-linux-amd64.zip": { + "sha256": "e105c75b1769d7656d85011cdf9bd2ee33c0bab0cbef3cfbf411a2c30a35faad", + "bytes": 3181590, + "executable_sha256": "b872fc6b56326fd4367c1beb426f050c5c8c4a2cde0e553e11acbf43220c08ff" + }, + "dct-windows-amd64.zip": { + "sha256": "a62da09e8797b5a163b3d9c1120386c0e9f4b4681b73d10c14e742ebfe20d5e0", + "bytes": 3256568, + "executable_sha256": "c11ecb7fef161c1ae0933a8dff5da2862bd8dd55cd7b365852cda61b27dce56b" + }, + "dct-darwin-arm64.zip": { + "sha256": "f6a35da05264460d60f80659efa8c18512508db328fb826d26eb7512c1ec1037", + "bytes": 3043552, + "executable_sha256": "7f869b787bf4ab5c9a7adebe195c1400ef21c3812660ff8dc780f0278f58aceb" + } + }, + "windows_smoke": { + "platform": "Windows amd64", + "version": "0.1.1-rc.1", + "ordered_records": 5002, + "stdout_sha256": "860ad4aaf1f67955160179a14d6d30ceeafe472de1db891193e74d946fdc5cef", + "cases": [ + "dense spill", + "late NUL and truncated UTF-8 suppress all records", + "UTF-8 on reader boundary", + "CRLF and final CR", + "exits 0, 1, and 2", + "temporary file cleanup" + ] + }, + "windows_benchmark_binary_sha256": "c11ecb7fef161c1ae0933a8dff5da2862bd8dd55cd7b365852cda61b27dce56b", + "windows_binary_matches_benchmark": true + } +} diff --git a/long_line.go b/long_line.go new file mode 100644 index 0000000..91206a7 --- /dev/null +++ b/long_line.go @@ -0,0 +1,145 @@ +package main + +import ( + "bufio" + "bytes" + "crypto/sha256" + "hash" + "io" + "unicode/utf8" +) + +type longLineResult struct { + valid bool + matched bool + size int64 + consumed int64 + digest [sha256.Size]byte +} + +// scanLongLine probes a line in fixed-size fragments without buffering its contents. +func scanLongLine(reader *bufio.Reader, first, literal []byte) (longLineResult, error) { + probe := longLineProbe{valid: true, literal: literal, digest: sha256.New()} + part, err := first, bufio.ErrBufferFull + var consumed int64 + pendingCR := false + carriageReturn := []byte{'\r'} + for { + if err != nil && err != io.EOF && err != bufio.ErrBufferFull { + return longLineResult{}, err + } + consumed += int64(len(part)) + if err == nil { + part = part[:len(part)-1] + if len(part) == 0 { + // The previous fragment's trailing CR is part of this CRLF. + pendingCR = false + } else { + part = bytes.TrimSuffix(part, carriageReturn) + } + } + if pendingCR { + probe.add(carriageReturn) + } + // A CR at the end of a fragment might precede a LF in the next read. + pendingCR = err == bufio.ErrBufferFull && len(part) > 0 && part[len(part)-1] == '\r' + if pendingCR { + part = part[:len(part)-1] + } + probe.add(part) + if err != bufio.ErrBufferFull { + break + } + if !probe.valid { + return longLineResult{}, nil + } + part, err = reader.ReadSlice('\n') + } + result := longLineResult{ + valid: probe.valid && probe.utf8.pendingLen == 0, + matched: probe.matched, + size: probe.size, + consumed: consumed, + } + if result.valid && result.matched { + probe.digest.Sum(result.digest[:0]) + } + return result, err +} + +type longLineProbe struct { + valid bool + matched bool + literal []byte + overlap []byte + utf8 utf8Boundary + digest hash.Hash + size int64 +} + +func (p *longLineProbe) add(part []byte) { + if !p.valid || len(part) == 0 { + return + } + p.valid = bytes.IndexByte(part, 0) < 0 && p.utf8.accept(part) + if !p.valid { + return + } + p.size += int64(len(part)) + p.digest.Write(part) + if p.matched || bytes.Contains(part, p.literal) { + p.matched = true + return + } + keep := len(p.literal) - 1 + if keep <= 0 { + return + } + p.overlap = append(p.overlap, part[:min(keep, len(part))]...) + if bytes.Contains(p.overlap, p.literal) { + p.matched = true + return + } + switch { + case len(part) >= keep: + p.overlap = append(p.overlap[:0], part[len(part)-keep:]...) + case len(p.overlap) > keep: + copy(p.overlap, p.overlap[len(p.overlap)-keep:]) + p.overlap = p.overlap[:keep] + } +} + +// utf8Boundary retains an incomplete rune between otherwise validated fragments. +type utf8Boundary struct { + pending [utf8.UTFMax]byte + pendingLen int +} + +func (v *utf8Boundary) accept(part []byte) bool { + if v.pendingLen > 0 { + copied := copy(v.pending[v.pendingLen:], part) + prefix := v.pending[:v.pendingLen+copied] + if !utf8.FullRune(prefix) { + v.pendingLen += copied + return true + } + _, width := utf8.DecodeRune(prefix) + if width == 1 { + return false + } + part = part[width-v.pendingLen:] + v.pendingLen = 0 + } + if len(part) == 0 { + return true + } + tail := len(part) - 1 + for tail > 0 && len(part)-tail < utf8.UTFMax && !utf8.RuneStart(part[tail]) { + tail-- + } + if !utf8.FullRune(part[tail:]) { + v.pendingLen = copy(v.pending[:], part[tail:]) + part = part[:tail] + } + return utf8.Valid(part) +} diff --git a/main.go b/main.go index dc655f7..dabfb02 100644 --- a/main.go +++ b/main.go @@ -12,7 +12,7 @@ import ( "github.com/spf13/cobra" ) -const version = "0.1.0" +const version = "0.1.1" func main() { os.Exit(run(os.Args[1:], os.Stdout, os.Stderr)) diff --git a/scripts/benchmark.py b/scripts/benchmark.py new file mode 100644 index 0000000..20d793a --- /dev/null +++ b/scripts/benchmark.py @@ -0,0 +1,311 @@ +"""Compare two dct builds with deterministic fixtures and per-process peak memory.""" + +import argparse +from dataclasses import dataclass +import hashlib +import json +import os +from pathlib import Path +import platform +import signal +from statistics import median +import subprocess +import sys +from tempfile import TemporaryDirectory +from time import perf_counter_ns + + +MIB = 1024 * 1024 +NEEDLE = "DCT_BENCHMARK_MATCH" +BENCH_DIR = Path(__file__).resolve().parents[1] / "bin" / ".benchmark" +PROCESS_TIMEOUT_SECONDS = 180 + + +@dataclass(frozen=True) +class Workload: + name: str + root: Path + input_bytes: int + records: int + stdout_bytes: int + stdout_sha256: str + + @property + def exit_code(self): + return 0 if self.records else 1 + + +def write_repeated(file, unit, count): + units_per_block = min(count, MIB // len(unit)) + if not units_per_block: + return + full_blocks, tail_units = divmod(count, units_per_block) + block = unit * units_per_block + for _ in range(full_blocks): + file.write(block) + file.write(unit * tail_units) + + +def record(path, line, text): + output = {"path": path, "line": line, "text": text} + return json.dumps(output, separators=(",", ":")).encode("ascii") + b"\n" + + +def short_line_fixture(root, name, file_count, lines_per_file, every_line_matches): + directory = root / name + directory.mkdir() + miss = b"x" * 127 + b"\n" + matched = NEEDLE.ljust(127, "x") + expected = hashlib.sha256() + record_count = 0 + output_count = 0 + name_width = max(2, len(str(file_count - 1))) + for index in range(file_count): + filename = f"file-{index:0{name_width}d}.txt" + with (directory / filename).open("wb") as file: + if every_line_matches: + write_repeated(file, matched.encode("ascii") + b"\n", lines_per_file) + matching_lines = range(1, lines_per_file + 1) + else: + write_repeated(file, miss, lines_per_file - 1) + file.write(matched.encode("ascii") + b"\n") + matching_lines = (lines_per_file,) + for line in matching_lines: + output = record(filename, line, matched) + expected.update(output) + output_count += len(output) + record_count += 1 + return Workload(name, directory, file_count * lines_per_file * 128, + record_count, output_count, expected.hexdigest()) + + +def long_line_fixture(root, name, payload_size, matches): + directory = root / name + directory.mkdir() + expected = hashlib.sha256() + with (directory / "line.txt").open("wb") as file: + write_repeated(file, b"x", payload_size) + if matches: + file.write(NEEDLE.encode("ascii") + b"\r\n") + if not matches: + return Workload(name, directory, payload_size, 0, 0, expected.hexdigest()) + + prefix = b'{"path":"line.txt","line":1,"text":"' + suffix = NEEDLE.encode("ascii") + b'"}\n' + expected.update(prefix) + block = b"x" * MIB + full_blocks, remainder = divmod(payload_size, MIB) + for _ in range(full_blocks): + expected.update(block) + expected.update(block[:remainder]) + expected.update(suffix) + return Workload(name, directory, payload_size + len(NEEDLE) + 2, 1, + len(prefix) + payload_size + len(suffix), expected.hexdigest()) + + +def make_workloads(root): + return ( + short_line_fixture(root, "sparse-short-lines", 4, 24 * MIB // 128, False), + short_line_fixture(root, "dense-short-lines", 1, 2 * MIB // 128, True), + short_line_fixture(root, "many-small-files", 1024, 4 * 1024 // 128, False), + long_line_fixture(root, "long-no-match", 48 * MIB, False), + long_line_fixture(root, "long-one-match", 16 * MIB, True), + ) + + +def windows_peak_rss(process): + import ctypes + from ctypes import wintypes + + class ProcessMemoryCounters(ctypes.Structure): + _fields_ = [ + ("size", wintypes.DWORD), + ("page_faults", wintypes.DWORD), + ("peak_working_set", ctypes.c_size_t), + ("working_set", ctypes.c_size_t), + ("peak_paged_pool", ctypes.c_size_t), + ("paged_pool", ctypes.c_size_t), + ("peak_nonpaged_pool", ctypes.c_size_t), + ("nonpaged_pool", ctypes.c_size_t), + ("pagefile", ctypes.c_size_t), + ("peak_pagefile", ctypes.c_size_t), + ] + + counters = ProcessMemoryCounters(size=ctypes.sizeof(ProcessMemoryCounters)) + query = ctypes.WinDLL("psapi", use_last_error=True).GetProcessMemoryInfo + query.argtypes = (wintypes.HANDLE, ctypes.POINTER(ProcessMemoryCounters), wintypes.DWORD) + query.restype = wintypes.BOOL + # CPython retains the child handle after wait, which allows reading the high-water mark. + if not query(int(process._handle), ctypes.byref(counters), counters.size): + raise ctypes.WinError(ctypes.get_last_error()) + return counters.peak_working_set + + +def wait_posix(process): + def timeout(_signum, _frame): + raise subprocess.TimeoutExpired(process.args, PROCESS_TIMEOUT_SECONDS) + + previous_handler = signal.signal(signal.SIGALRM, timeout) + try: + signal.setitimer(signal.ITIMER_REAL, PROCESS_TIMEOUT_SECONDS) + return os.wait4(process.pid, 0) + finally: + signal.setitimer(signal.ITIMER_REAL, 0) + signal.signal(signal.SIGALRM, previous_handler) + + +def timed_process(command, environment, expected_exit): + start = perf_counter_ns() + with subprocess.Popen(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + env=environment) as process: + try: + if sys.platform == "win32": + process.wait(timeout=PROCESS_TIMEOUT_SECONDS) + elapsed = perf_counter_ns() - start + peak_rss = windows_peak_rss(process) + else: + _, status, usage = wait_posix(process) + elapsed = perf_counter_ns() - start + process.returncode = os.waitstatus_to_exitcode(status) + peak_rss = usage.ru_maxrss * (1 if sys.platform == "darwin" else 1024) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + raise + if process.returncode != expected_exit or peak_rss <= 0: + raise RuntimeError(f"{command[0]} returned {process.returncode}, expected " + f"{expected_exit}, peak RSS reported: {peak_rss}") + return {"elapsed_nanoseconds": elapsed, "peak_rss_bytes": peak_rss} + + +def sha256_file(path): + with path.open("rb") as file: + return hashlib.file_digest(file, "sha256").hexdigest() + + +def assert_expected_output(command, environment, workload, workdir): + stdout = workdir / "stdout" + stderr = workdir / "stderr" + with stdout.open("wb") as output, stderr.open("wb") as errors: + completed = subprocess.run(command, stdout=output, stderr=errors, env=environment, + timeout=PROCESS_TIMEOUT_SECONDS, check=False) + if (completed.returncode != workload.exit_code + or stderr.stat().st_size + or stdout.stat().st_size != workload.stdout_bytes + or sha256_file(stdout) != workload.stdout_sha256): + raise RuntimeError(f"{command[0]} changed the {workload.name} fixture output " + f"(exit {completed.returncode}, stdout {stdout.stat().st_size} bytes, " + f"stderr {stderr.stat().st_size} bytes)") + + +def summarize(trials, input_bytes): + elapsed = median(trial["elapsed_nanoseconds"] for trial in trials) + return { + "runs": trials, + "median_elapsed_ms": round(elapsed / 1_000_000, 3), + "median_input_mib_per_second": round(input_bytes / MIB / (elapsed / 1_000_000_000), 3), + "median_peak_rss_bytes": median(trial["peak_rss_bytes"] for trial in trials), + "max_peak_rss_bytes": max(trial["peak_rss_bytes"] for trial in trials), + } + + +def run_workload(workload, binaries, environment, workdir, runs): + commands = { + label: [str(binary), "search", NEEDLE, str(workload.root), "--ext", ".txt", "--json"] + for label, binary in binaries.items() + } + for command in commands.values(): + assert_expected_output(command, environment, workload, workdir) + timed_process(command, environment, workload.exit_code) + measurements = {label: [] for label in commands} + order = tuple(commands) + for iteration in range(runs): + for label in order if iteration % 2 == 0 else reversed(order): + measurements[label].append(timed_process(commands[label], environment, workload.exit_code)) + results = {label: summarize(trials, workload.input_bytes) for label, trials in measurements.items()} + for label, result in results.items(): + peak = result["median_peak_rss_bytes"] / MIB + throughput = result["median_input_mib_per_second"] + print(f"{workload.name:20s} {label:9s} {result['median_elapsed_ms']:8.3f} ms " + f"{throughput:8.1f} MiB/s {peak:7.2f} MiB peak RSS", flush=True) + return { + "name": workload.name, + "input_bytes": workload.input_bytes, + "expected_exit": workload.exit_code, + "expected_records": workload.records, + "expected_stdout_bytes": workload.stdout_bytes, + "expected_stdout_sha256": workload.stdout_sha256, + "builds": results, + } + + +def commit_sha(value): + if len(value) != 40 or any(character not in "0123456789abcdef" for character in value): + raise argparse.ArgumentTypeError("expected a 40-character lowercase Git commit SHA") + return value + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--baseline", type=Path, required=True) + parser.add_argument("--baseline-commit", type=commit_sha, required=True) + parser.add_argument("--candidate", type=Path, required=True) + parser.add_argument("--candidate-commit", type=commit_sha, required=True) + parser.add_argument("--runs", type=int, default=5) + parser.add_argument("--output", type=Path, help="Write the full results to this JSON file.") + args = parser.parse_args() + if sys.version_info < (3, 11) or platform.python_implementation() != "CPython": + parser.error("CPython 3.11 or newer is required") + if sys.platform not in ("win32", "darwin", "linux"): + parser.error("peak RSS measurement is implemented for Windows, macOS, and Linux") + if args.runs < 1: + parser.error("--runs must be positive") + binaries = {label: getattr(args, label).resolve(strict=True) for label in ("baseline", "candidate")} + evidence = { + "environment": { + "os": platform.system(), + "os_release": platform.release(), + "os_version": platform.version(), + "architecture": platform.machine(), + "processor": platform.processor(), + "logical_processors": os.cpu_count(), + "python": platform.python_version(), + "go_runtime_overrides": {name: os.environ[name] for name in + ("GOMAXPROCS", "GOGC", "GOMEMLIMIT") if name in os.environ}, + }, + "method": { + "runs_per_build": args.runs, + "warmups_per_build": 1, + "timeout_seconds_per_process": PROCESS_TIMEOUT_SECONDS, + "stdout_validation": "One separate digest, length, stderr and exit check per build and workload.", + "time": "Elapsed wall time from before process creation through exit. Both output streams " + "are sent to the null device while timing. Build order alternates each iteration.", + "cache": "Generated locally, verified and warmed before timing. OS caches are shared.", + "peak_rss": ("Win32 GetProcessMemoryInfo PeakWorkingSetSize in bytes" if sys.platform == "win32" + else "wait4 ru_maxrss converted to bytes"), + }, + "builds": { + label: { + "commit": getattr(args, f"{label}_commit"), + "binary_sha256": sha256_file(binary), + "version": subprocess.check_output([str(binary), "--version"], text=True, timeout=5).strip(), + } + for label, binary in binaries.items() + }, + } + BENCH_DIR.mkdir(parents=True, exist_ok=True) + with TemporaryDirectory(prefix="run-", dir=BENCH_DIR) as directory: + workdir = Path(directory) + temp_dir = workdir / "temp" + temp_dir.mkdir() + environment = {**os.environ, "TEMP": str(temp_dir), "TMP": str(temp_dir), "TMPDIR": str(temp_dir)} + workloads = make_workloads(workdir) + evidence["workloads"] = [ + run_workload(workload, binaries, environment, workdir, args.runs) for workload in workloads + ] + if args.output: + args.output.write_text(json.dumps(evidence, indent=2) + "\n", encoding="utf-8", newline="\n") + + +if __name__ == "__main__": + main() diff --git a/scripts/package.ps1 b/scripts/package.ps1 index ca5a57a..7fb820e 100644 --- a/scripts/package.ps1 +++ b/scripts/package.ps1 @@ -27,16 +27,12 @@ $staging = Join-Path $dist ".staging-$runId" $destination = Join-Path $dist "dct-$runId" $checksumsName = 'SHA256SUMS.txt' -$requiredNotices = @('THIRD_PARTY_NOTICES.md', 'licenses') +$requiredNotices = @('LICENSE', 'THIRD_PARTY_NOTICES.md', 'licenses', 'CHANGELOG.md') $notices = @($requiredNotices | ForEach-Object { $source = Join-Path $projectRoot $_ if (-not (Test-Path -LiteralPath $source)) { throw "Required package content is missing: $_" } $source }) -$notices += @('CHANGELOG.md', 'LICENSE' | ForEach-Object { - $source = Join-Path $projectRoot $_ - if (Test-Path -LiteralPath $source -PathType Leaf) { $source } -}) $savedEnvironment = @{} foreach ($name in 'GOOS', 'GOARCH', 'CGO_ENABLED') { diff --git a/search_test.go b/search_test.go index 76b39fb..c4238dc 100644 --- a/search_test.go +++ b/search_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "errors" + "fmt" "os" "os/exec" "path/filepath" @@ -56,6 +57,61 @@ func TestSearchCLI(t *testing.T) { assertCLI(t, result, 0, "long.txt:1:"+line+"\n", false) }) + t.Run("UTF-8 across read boundaries and final carriage return", func(t *testing.T) { + root := t.TempDir() + line := strings.Repeat("x", 64*1024-1) + "🚀 needle \uFFFD" + writeFixture(t, root, "boundary.txt", line+"\r\n\r\nneedle\r") + + result := runCLI(t, binary, root, "search", "needle") + assertCLI(t, result, 0, "boundary.txt:1:"+line+"\nboundary.txt:3:needle\r\n", false) + result = runCLI(t, binary, root, "search", "x🚀 needle") + assertCLI(t, result, 0, "boundary.txt:1:"+line+"\n", false) + }) + + t.Run("carriage return at a read boundary", func(t *testing.T) { + root := t.TempDir() + withReturn := strings.Repeat("x", 64*1024-1) + "\r" + writeFixture(t, root, "returns.txt", withReturn+"\n"+withReturn) + + result := runCLI(t, binary, root, "search", "\r") + assertCLI(t, result, 0, "returns.txt:2:"+withReturn+"\n", false) + }) + + t.Run("late invalid bytes discard staged matches", func(t *testing.T) { + root := t.TempDir() + prefix := strings.Repeat("needle "+strings.Repeat("x", 96)+"\n", 5000) + writeFixture(t, root, "a-nul.txt", prefix+"\x00\n") + writeFixture(t, root, "b-invalid.txt", prefix+"\xff\n") + writeFixture(t, root, "c-truncated.txt", prefix+"\xe2\x82") + writeFixture(t, root, "d-long-invalid.txt", "needle "+strings.Repeat("x", 3*64*1024)+"\xe2\x82\n") + + result := runCLI(t, binary, root, "search", "needle", "--json") + if result.exit != 1 || result.stdout != "" || result.stderr != "" { + t.Fatalf("invalid files produced exit %d and %d stdout bytes, stderr %q", result.exit, len(result.stdout), result.stderr) + } + writeFixture(t, root, "z-valid.txt", "needle in valid file") + result = runCLI(t, binary, root, "search", "needle", "--json") + assertCLI(t, result, 0, "{\"path\":\"z-valid.txt\",\"line\":1,\"text\":\"needle in valid file\"}\n", false) + }) + + t.Run("high-output file replays records in order", func(t *testing.T) { + root := t.TempDir() + const repetitions = 5000 + line := "needle " + strings.Repeat("x", 96) + writeFixture(t, root, "a-many.txt", strings.Repeat(line+"\n", repetitions)) + writeFixture(t, root, "b-after.txt", "needle after replay") + var want strings.Builder + for i := 1; i <= repetitions; i++ { + fmt.Fprintf(&want, "a-many.txt:%d:%s\n", i, line) + } + want.WriteString("b-after.txt:1:needle after replay\n") + + result := runCLI(t, binary, root, "search", "needle") + if result.exit != 0 || result.stdout != want.String() || result.stderr != "" { + t.Fatalf("exit %d, stdout bytes %d (want %d), stderr %q", result.exit, len(result.stdout), want.Len(), result.stderr) + } + }) + t.Run("unmatched search", func(t *testing.T) { root := t.TempDir() writeFixture(t, root, "file.txt", "unrelated\n") diff --git a/stream_search.go b/stream_search.go new file mode 100644 index 0000000..894f8b5 --- /dev/null +++ b/stream_search.go @@ -0,0 +1,267 @@ +package main + +import ( + "bufio" + "bytes" + "crypto/sha256" + "encoding/binary" + "errors" + "fmt" + "io" + "os" + "slices" + "strings" + "unicode/utf8" +) + +const ( + searchBufferSize = 64 * 1024 + matchMemoryLimit = 256 * 1024 + matchHeaderSize = 16 +) + +type searchMatch struct { + Path string `json:"path"` + Line int `json:"line"` + Text string `json:"text"` +} + +func searchFiles(root *os.Root, files []string, literal []byte, emit func(searchMatch) error) (bool, error) { + reader := bufio.NewReaderSize(nil, searchBufferSize) + var matches stagedMatches + found := false + for _, path := range files { + file, err := root.Open(path) + if err != nil { + return found, err + } + reader.Reset(file) + valid, err := collectMatches(reader, file, literal, &matches) + file.Close() + + if valid && err == nil { + var emitted bool + emitted, err = matches.replay(path, reader, emit) + found = found || emitted + } + cleanupErr := matches.reset() + if err != nil { + return found, err + } + if cleanupErr != nil { + return found, fmt.Errorf("remove temporary search matches: %w", cleanupErr) + } + } + return found, nil +} + +func collectMatches(reader *bufio.Reader, source io.ReaderAt, literal []byte, matches *stagedMatches) (bool, error) { + var offset int64 + var stagingErr error + for lineNumber := 1; ; lineNumber++ { + line, err := reader.ReadSlice('\n') + if err == bufio.ErrBufferFull { + long, err := scanLongLine(reader, line, literal) + if err != nil && err != io.EOF { + return false, err + } + if !long.valid { + return false, drainRejectedSource(reader, err) + } + if stagingErr == nil && long.matched { + if err := matches.stageLongLine(lineNumber, source, offset, long); err != nil { + stagingErr = fmt.Errorf("stage search matches: %w", err) + } + } + offset += long.consumed + if err == io.EOF { + return true, stagingErr + } + continue + } + if err != nil && err != io.EOF { + return false, err + } + if len(line) == 0 && err == io.EOF { + return true, stagingErr + } + if bytes.IndexByte(line, 0) >= 0 || !utf8.Valid(line) { + return false, drainRejectedSource(reader, err) + } + offset += int64(len(line)) + if err == nil { + line = line[:len(line)-1] + line = bytes.TrimSuffix(line, []byte{'\r'}) + } + if stagingErr == nil && bytes.Contains(line, literal) { + // The staging error matters only if the source is valid and readable. + if err := matches.add(lineNumber, line); err != nil { + stagingErr = fmt.Errorf("stage search matches: %w", err) + } + } + if err == io.EOF { + return true, stagingErr + } + } +} + +func drainRejectedSource(reader *bufio.Reader, lastRead error) error { + // A read failure makes the command fail even for a file we would skip. + if lastRead == io.EOF { + return nil + } + _, err := io.Copy(io.Discard, reader) + return err +} + +// stagedMatches preserves full-file validation without retaining all matching +// text in memory. Each record stores its line number, byte length, and text. +type stagedMatches struct { + memory []byte + spill *os.File + writer *bufio.Writer + header [matchHeaderSize]byte +} + +func (s *stagedMatches) add(lineNumber int, line []byte) error { + s.encodeHeader(lineNumber, int64(len(line))) + if memory, ok := s.reserveMemory(int64(len(line))); ok { + copy(memory, line) + return nil + } + if err := s.startSpill(); err != nil { + return err + } + if _, err := s.writer.Write(s.header[:]); err != nil { + return err + } + _, err := s.writer.Write(line) + return err +} + +func (s *stagedMatches) stageLongLine(lineNumber int, source io.ReaderAt, offset int64, line longLineResult) error { + s.encodeHeader(lineNumber, line.size) + section := io.NewSectionReader(source, offset, line.size) + if memory, ok := s.reserveMemory(line.size); ok { + _, err := io.ReadFull(section, memory) + if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF { + return err + } + if err != nil || sha256.Sum256(memory) != line.digest { + return fmt.Errorf("source changed while staging long line %d", lineNumber) + } + return nil + } + if err := s.startSpill(); err != nil { + return err + } + if _, err := s.writer.Write(s.header[:]); err != nil { + return err + } + digest := sha256.New() + copied, err := io.Copy(io.MultiWriter(s.writer, digest), section) + if err != nil { + return err + } + var actual [sha256.Size]byte + digest.Sum(actual[:0]) + if copied != line.size || actual != line.digest { + return fmt.Errorf("source changed while staging long line %d", lineNumber) + } + return nil +} + +func (s *stagedMatches) reserveMemory(width int64) ([]byte, bool) { + if s.spill != nil || width > int64(matchMemoryLimit-len(s.memory)-matchHeaderSize) { + return nil, false + } + start := len(s.memory) + needed := start + matchHeaderSize + int(width) + if needed > cap(s.memory) { + larger := make([]byte, start, min(matchMemoryLimit, max(needed, cap(s.memory)*2))) + copy(larger, s.memory) + s.memory = larger + } + s.memory = s.memory[:needed] + copy(s.memory[start:], s.header[:]) + return s.memory[start+matchHeaderSize:], true +} + +func (s *stagedMatches) encodeHeader(lineNumber int, width int64) { + binary.LittleEndian.PutUint64(s.header[:8], uint64(lineNumber)) + binary.LittleEndian.PutUint64(s.header[8:], uint64(width)) +} + +func (s *stagedMatches) startSpill() error { + if s.spill != nil { + return nil + } + file, err := os.CreateTemp("", "dct-matches-*") + if err != nil { + return err + } + s.spill = file + s.writer = bufio.NewWriterSize(file, searchBufferSize) + _, err = s.writer.Write(s.memory) + return err +} + +func (s *stagedMatches) replay(path string, buffer *bufio.Reader, emit func(searchMatch) error) (bool, error) { + if s.spill == nil && len(s.memory) == 0 { + return false, nil + } + var input io.Reader = bytes.NewReader(s.memory) + if s.spill != nil { + if err := s.writer.Flush(); err != nil { + return false, fmt.Errorf("stage search matches: %w", err) + } + if _, err := s.spill.Seek(0, io.SeekStart); err != nil { + return false, fmt.Errorf("rewind temporary search matches: %w", err) + } + buffer.Reset(s.spill) + input = buffer + } + + found := false + var line []byte + for { + if _, err := io.ReadFull(input, s.header[:]); err != nil { + if err == io.EOF { + return found, nil + } + return found, fmt.Errorf("read temporary search match header: %w", err) + } + lineNumber := int(binary.LittleEndian.Uint64(s.header[:8])) + width := int(binary.LittleEndian.Uint64(s.header[8:])) + var text string + if width > searchBufferSize { + var builder strings.Builder + builder.Grow(width) + if _, err := io.CopyN(&builder, input, int64(width)); err != nil { + return found, fmt.Errorf("read temporary search match text: %w", err) + } + text = builder.String() + } else { + line = slices.Grow(line[:0], width)[:width] + if _, err := io.ReadFull(input, line); err != nil { + return found, fmt.Errorf("read temporary search match text: %w", err) + } + text = string(line) + } + if err := emit(searchMatch{Path: path, Line: lineNumber, Text: text}); err != nil { + return found, fmt.Errorf("write search result: %w", err) + } + found = true + } +} + +func (s *stagedMatches) reset() error { + s.memory = s.memory[:0] + if s.spill == nil { + return nil + } + err := errors.Join(s.spill.Close(), os.Remove(s.spill.Name())) + s.spill = nil + s.writer = nil + return err +} diff --git a/stream_search_test.go b/stream_search_test.go new file mode 100644 index 0000000..0db7ce0 --- /dev/null +++ b/stream_search_test.go @@ -0,0 +1,167 @@ +package main + +import ( + "bufio" + "errors" + "io" + "os" + "strings" + "testing" + "testing/iotest" +) + +func TestCollectMatchesReturnsLateSourceReadErrors(t *testing.T) { + failure := errors.New("test source read failure") + for _, tail := range []string{"valid text\n", "\x00\n", "\xff\n"} { + data := "needle before error\n" + tail + "data beyond first buffer\n" + source := io.MultiReader( + strings.NewReader(data), + iotest.ErrReader(failure), + ) + var staged stagedMatches + t.Cleanup(func() { + if err := staged.reset(); err != nil { + t.Error(err) + } + }) + valid, err := collectMatches(bufio.NewReaderSize(source, 16), strings.NewReader(data), []byte("needle"), &staged) + if valid || !errors.Is(err, failure) { + t.Errorf("source with tail %q: valid %t, error %v, want source read failure", tail, valid, err) + } + } +} + +func TestCollectMatchesDefersStagingErrorUntilValidatedEOF(t *testing.T) { + file, err := os.CreateTemp(t.TempDir(), "closed-spill-*") + if err != nil { + t.Fatal(err) + } + if err := file.Close(); err != nil { + t.Fatal(err) + } + for _, valid := range []bool{true, false} { + text := "needle\n" + if !valid { + text += "\x00\n" + } + staged := stagedMatches{spill: file, writer: bufio.NewWriterSize(file, 1)} + source := strings.NewReader(text) + gotValid, err := collectMatches(bufio.NewReader(source), source, []byte("needle"), &staged) + if valid != gotValid || (valid && !errors.Is(err, os.ErrClosed)) || (!valid && err != nil) { + t.Errorf("valid source %t: valid %t, error %v", valid, gotValid, err) + } + } +} + +func TestLongLineStagingRejectsChangedBytes(t *testing.T) { + for _, tc := range []struct { + name string + size int + }{ + {name: "memory", size: 2 * searchBufferSize}, + {name: "spill", size: matchMemoryLimit}, + } { + t.Run(tc.name, func(t *testing.T) { + line := "needle " + strings.Repeat("x", tc.size) + for _, suffix := range []string{"a\n", "a\n\x00\n"} { + probe := bufio.NewReaderSize(strings.NewReader(line+suffix), searchBufferSize) + readerAt := strings.NewReader(line + "b\n") + var matches stagedMatches + valid, err := collectMatches(probe, readerAt, []byte("needle"), &matches) + if suffix == "a\n" { + if !valid || err == nil || !strings.Contains(err.Error(), "source changed while staging long line 1") { + t.Errorf("changed line was eligible for replay: valid %t, error %v", valid, err) + } + } else if valid || err != nil { + t.Errorf("later NUL should skip file despite changed bytes: valid %t, error %v", valid, err) + } + if err := matches.reset(); err != nil { + t.Error(err) + } + } + }) + } +} + +func TestLongUnmatchedLineDoesNotStage(t *testing.T) { + source := strings.NewReader(strings.Repeat("x", 8*searchBufferSize)) + var matches stagedMatches + // Passing no ReaderAt also proves the unmatched content is never reread. + valid, err := collectMatches(bufio.NewReaderSize(source, searchBufferSize), nil, []byte("needle"), &matches) + if !valid || err != nil || matches.spill != nil || cap(matches.memory) != 0 { + t.Fatalf("unmatched long line: valid %t, error %v, spill %v, stage capacity %d", valid, err, matches.spill, cap(matches.memory)) + } +} + +func TestLongLiteralCrossesSeveralFragments(t *testing.T) { + literal := strings.Repeat("☕abc", 12) + line := "123456789012345" + literal + " end" + source := strings.NewReader("header\n" + line + "\r\ntrailer\n") + reader := bufio.NewReaderSize(source, 16) + var matches stagedMatches + if valid, err := collectMatches(reader, source, []byte(literal), &matches); !valid || err != nil || matches.spill != nil { + t.Fatalf("long literal: valid %t, error %v, spill %v", valid, err, matches.spill) + } + found, err := matches.replay("file.txt", reader, func(match searchMatch) error { + if match.Path != "file.txt" || match.Line != 2 || match.Text != line { + t.Errorf("wrong match: %#v", match) + } + return nil + }) + if !found || err != nil { + t.Errorf("replay found %t, error %v", found, err) + } +} + +func TestSearchFilesRemovesSpill(t *testing.T) { + writeFailure := errors.New("test search output failure") + longLine := "needle " + strings.Repeat("x", matchMemoryLimit) + cases := []struct { + name string + tail string + writeErr error + visits int + found bool + }{ + {name: "valid file", visits: 2, found: true}, + {name: "invalid file", tail: "\x00\n"}, + {name: "output error", writeErr: writeFailure, visits: 1}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rootPath := t.TempDir() + spillDir := t.TempDir() + t.Setenv("TMPDIR", spillDir) + t.Setenv("TMP", spillDir) + t.Setenv("TEMP", spillDir) + writeFixture(t, rootPath, "file.txt", "needle short\n"+longLine+"\n"+tc.tail) + root, err := openDirectory(rootPath) + if err != nil { + t.Fatal(err) + } + defer root.Close() + + visits := 0 + found, err := searchFiles(root, []string{"file.txt"}, []byte("needle"), func(match searchMatch) error { + if entries, err := os.ReadDir(spillDir); err != nil || len(entries) != 1 { + t.Errorf("expected one active spill: %v, error %v", entries, err) + } + visits++ + wantText := "needle short" + if visits == 2 { + wantText = longLine + } + if match.Path != "file.txt" || match.Line != visits || match.Text != wantText { + t.Errorf("match %d: wrong path, line number or content", visits) + } + return tc.writeErr + }) + if found != tc.found || visits != tc.visits || !errors.Is(err, tc.writeErr) { + t.Errorf("found %t, visited %d, error %v; want %t, %d, %v", found, visits, err, tc.found, tc.visits, tc.writeErr) + } + if entries, err := os.ReadDir(spillDir); err != nil || len(entries) != 0 { + t.Errorf("spill directory after search: %v, error %v", entries, err) + } + }) + } +} diff --git a/workspace.go b/workspace.go index 1b05f51..edac80f 100644 --- a/workspace.go +++ b/workspace.go @@ -1,14 +1,12 @@ package main import ( - "bytes" "fmt" "io/fs" "os" "path/filepath" "slices" "strings" - "unicode/utf8" ) func openDirectory(path string) (*os.Root, error) { @@ -61,40 +59,6 @@ func listFiles(root *os.Root, extensions []string) ([]string, error) { return files, nil } -type searchMatch struct { - Path string `json:"path"` - Line int `json:"line"` - Text string `json:"text"` -} - -func searchFiles(root *os.Root, files []string, literal []byte, emit func(searchMatch) error) (bool, error) { - found := false - for _, file := range files { - contents, err := root.ReadFile(file) - if err != nil { - return found, err - } - // Validate the whole file before emitting any matches from it. - if bytes.IndexByte(contents, 0) >= 0 || !utf8.Valid(contents) { - continue - } - for lineNumber := 1; len(contents) > 0; lineNumber++ { - line, rest, terminated := bytes.Cut(contents, []byte{'\n'}) - contents = rest - if terminated { - line = bytes.TrimSuffix(line, []byte{'\r'}) - } - if bytes.Contains(line, literal) { - if err := emit(searchMatch{Path: file, Line: lineNumber, Text: string(line)}); err != nil { - return found, fmt.Errorf("write search result: %w", err) - } - found = true - } - } - } - return found, nil -} - type fileSize struct { Path string `json:"path"` Bytes int64 `json:"bytes"`