Skip to content

test(loom): compare worker cwd by identity - #406

Open
thebtf wants to merge 1 commit into
review/release-integration-r1from
work/prc-macos-cwd-canonical-r1-sol
Open

test(loom): compare worker cwd by identity#406
thebtf wants to merge 1 commit into
review/release-integration-r1from
work/prc-macos-cwd-canonical-r1-sol

Conversation

@thebtf

@thebtf thebtf commented Jul 13, 2026

Copy link
Copy Markdown
Owner

Outcome

Repairs the macOS cross-platform false red from run 29241241316 without changing CLI worker production behavior. The test now validates that the requested and reported CWD are the same existing directory via os.Stat plus os.SameFile, rather than requiring a unique path spelling that Go explicitly does not guarantee.

Evidence

  • RED: macos-14 returned /private/var for the equivalent /var t.TempDir and failed the exact-string assertion.
  • GREEN: target test and full internal/handlers/loom package pass on Windows.
  • Alias replay: Linux TMPDIR symlink alias reproduces different logical/physical spellings and passes with os.SameFile.
  • Prove-It: restoring exact-string equality makes that replay fail 1 test; restoring the candidate returns GREEN.
  • go vet PASS; package coverage 86.9%; staged gitleaks PASS.

External sources: official Go os.SameFile and filepath docs via Context7 and Parallel. Tavily remains OAuth-blocked and was not replaced with model memory.

Production code is unchanged. Final acceptance requires the real macos-14 check on this exact head.

Summary by CodeRabbit

  • Исправления

    • Улучшена проверка текущего рабочего каталога на macOS: эквивалентные системные пути теперь корректно распознаются как одна и та же директория.
    • Устранены ложные сбои тестов, связанные с различиями представления путей /var и /private/var.
  • Тесты

    • Подтверждена корректная работа проверки рабочего каталога на Windows, Ubuntu и macOS.
    • Добавлены структурированные сведения о результатах проверок и покрытии.

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown

Review Change Stack

Walkthrough

Проверка рабочего каталога в production-readiness тесте теперь сравнивает файловую идентичность директорий вместо строковых путей. Добавлены JSON-свидетельства о macOS-кейсе, исправлении и кроссплатформенном результате.

Changes

Каноническая идентичность CWD

Layer / File(s) Summary
Проверка идентичности рабочего каталога
internal/handlers/loom/production_readiness_coverage_test.go, .agent/specs/macos-cwd-canonical/evidence/*
Тест получает метаданные ожидаемого и фактического каталогов через os.Stat и проверяет их через os.SameFile; evidence-файлы фиксируют расхождение /var/... и /private/var/..., результат исправления и параметры прогона.

Estimated code review effort: 2 (Simple) | ~10 minutes

Poem

Я兔ик прыгнул по CWD,
Где /var и /private — не беда.
SameFile путь узнал,
macOS тест не убежал,
И зелёным стал след.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Заголовок точно отражает основное изменение: сравнение рабочей директории воркера по файловой идентичности вместо сравнения строк.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch work/prc-macos-cwd-canonical-r1-sol

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.12.2)

Error: can't load config: unsupported version of the configuration: "" See https://golangci-lint.run/docs/product/migration-guide for migration instructions
The command is terminated due to an error: can't load config: unsupported version of the configuration: "" See https://golangci-lint.run/docs/product/migration-guide for migration instructions


Comment @coderabbitai help to get the list of available commands.

@thebtf

thebtf commented Jul 13, 2026

Copy link
Copy Markdown
Owner Author

Review exact head c0637aa. Please judge semantic correctness of filesystem identity vs path-string equality, cross-platform behavior, test strength, and whether any production regression is hidden. @coderabbitai review @codex review @gemini-code-assist review

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

gh pr view 406 --repo thebtf/engram --json title,body,headRefOid,files
echo "---DIFF---"
gh pr diff 406 --repo thebtf/engram

Length of output: 7526


🏁 Script executed:

#!/bin/bash
set -euo pipefail
sed -n '1,100p' internal/handlers/loom/production_readiness_coverage_test.go

Length of output: 3231


@thebtf Reviewed head c0637aaad88fbc32b9a306c1077e3f7612427891. Confirmed the diff touches only:

  • internal/handlers/loom/production_readiness_coverage_test.go (+5/-1)
  • Two new files under .agent/specs/macos-cwd-canonical/evidence/ (JSON evidence artifacts, non-executable)

No production source files are modified, so the "no hidden production regression" claim holds up structurally.

Semantic correctness (identity vs. string equality):
The fix is correct. os.SameFile compares os.FileInfo values using the underlying device+inode on Unix (or volume serial number + file index on Windows), not the path spelling. That's exactly the right primitive to assert "these two paths refer to the same directory," which is the actual invariant the test cares about — not "the CLI worker echoes back byte-identical path text." The old assert.Equal(t, cwd, state.CWD) was asserting an incidental property (Go's os.Getwd() on macOS can legitimately return the /private/var/... physical spelling for a /var/... logical path due to the platform's symlink), which Go's docs never guaranteed to be stable — so the RED failure was a genuine false negative in the old test, not a real bug in the worker.

Cross-platform behavior:

  • macOS: os.SameFile resolves the /var vs /private/var aliasing correctly since both point to the same inode.
  • Linux: the TMPDIR-symlink alias replay described in the evidence file is a reasonable proxy for the macOS case and is a legitimate way to exercise the same code path without a macOS runner.
  • Windows: os.SameFile uses GetFileInformationByHandle semantics (volume serial + file index), so it should behave correctly there too, and the evidence claims the full package passed on Windows.

Test strength:
The new assertion is not meaningfully weaker for the invariant under test. It still requires:

  1. Both cwd and state.CWD to os.Stat successfully (require.NoError — no silent skip if the worker reports a bogus/missing path).
  2. The two stats to resolve to the same filesystem object.

The only theoretical gap: if state.CWD were ever a relative path (a latent worker bug), os.Stat would resolve it against the test process's own working directory rather than failing outright, which could mask that regression. Worth a quick sanity check — does CLIWorker (or the clihelper testdata binary) always call something like os.Getwd() after os.Chdir(), which is guaranteed absolute? If so, this is a non-issue; otherwise it might be worth an assert.True(t, filepath.IsAbs(state.CWD)) alongside the identity check for extra defense-in-depth. This is a minor suggestion, not a blocker.

Summary: The change is a sound, minimal, test-only fix that correctly swaps path-string equality for filesystem-identity comparison using stdlib primitives, matches the documented Go semantics, and doesn't touch production code. I'd approve this as-is; the optional filepath.IsAbs guard is a nice-to-have, not required.

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request resolves a macOS-specific test failure in TestCliWorker_ProductionReadinessStructuredArgsAndCWD where exact string comparison of the current working directory (CWD) failed due to path aliasing (e.g., /var vs /private/var). The assertion was updated to use os.SameFile to verify directory identity rather than path spelling. No review comments were provided.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: c0637aaad8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request addresses a macOS-specific test failure in TestCliWorker_ProductionReadinessStructuredArgsAndCWD where exact string comparison of the working directory failed due to /var vs /private/var path resolution. The assertion has been updated to use os.SameFile to verify directory identity instead of string equality. Additionally, two specification/evidence JSON files have been added to document this behavior. There are no review comments, so no feedback is provided.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
internal/handlers/loom/production_readiness_coverage_test.go (1)

83-87: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Необязательно: явно проверяйте абсолютность state.CWD.

Сейчас относительный путь перед os.Stat разрешался бы относительно процесса теста, что может скрыть будущую регрессию helper-процесса. os.Getwd() сейчас возвращает абсолютный путь, поэтому это не блокер, но проверка через filepath.IsAbs явно зафиксирует контракт теста.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/handlers/loom/production_readiness_coverage_test.go` around lines 83
- 87, Добавьте явную проверку filepath.IsAbs для state.CWD в тесте, до вызова
os.Stat, чтобы зафиксировать требование абсолютного пути; существующие проверки
requestedDir, reportedDir и os.SameFile сохраните без изменений.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@internal/handlers/loom/production_readiness_coverage_test.go`:
- Around line 83-87: Добавьте явную проверку filepath.IsAbs для state.CWD в
тесте, до вызова os.Stat, чтобы зафиксировать требование абсолютного пути;
существующие проверки requestedDir, reportedDir и os.SameFile сохраните без
изменений.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d693f33d-4c3f-443c-b3ea-494d1560eaf7

📥 Commits

Reviewing files that changed from the base of the PR and between 8279d22 and c0637aa.

📒 Files selected for processing (3)
  • .agent/specs/macos-cwd-canonical/evidence/MACOS-CWD-CANONICAL.red.json
  • .agent/specs/macos-cwd-canonical/evidence/MACOS-CWD-CANONICAL.tdd.json
  • internal/handlers/loom/production_readiness_coverage_test.go

@thebtf

thebtf commented Jul 13, 2026

Copy link
Copy Markdown
Owner Author

Exact-head CI classification for c0637aa: downloaded artifacts from run 29245630994 show go_test_exit=0 on macOS, Ubuntu, and Windows, with 3913 tests and 0 failed on each. The original macOS /var versus /private/var assertion failure is absent, so os.SameFile proves the requested and reported directories identify the same filesystem object on the real macOS runner. The three matrix jobs are red only because the pre-governance base still treats 429 expected DB skips as unexpected and applies DB-owned coverage thresholds to non-DB matrices; the release job is likewise base-equivalent and outside this three-file test/evidence diff. Combined acceptance remains required after #405 and #406 are synthesized. CodeRabbit's filepath.IsAbs suggestion is non-blocking and intentionally not added: the product contract under repair is directory identity across aliases, which SameFile directly checks; widening this test-only batch would not change shipped behavior.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant