Skip to content

refactor(snapshot): load the source tree once at the boundary and ban reads in computation - #229

Merged
furedea merged 4 commits into
mainfrom
refactor/load-source-snapshot-at-boundary
Nov 11, 2026
Merged

furedea merged 4 commits into
mainfrom
refactor/load-source-snapshot-at-boundary

Conversation

@furedea-agent

@furedea-agent furedea-agent Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

計算の層がディスクを読まないようにした.source・外部 bundle・インストール済みの設定は境界で一度だけ Snapshot に読み込み,計算はそれに問い合わせるだけにする.読み込み系 API を clippy で禁止し,計算の層は forbid で外せない.

Refs #217(波 2-b snapshot.波 3 が残る).計画: #217 (comment)

flowchart LR
  Disk[(disk)] --> Load[shell::load<br/>唯一の読み手]
  Load --> Snap[Snapshot / Tree]
  Snap --> Gen[generation・renderer・sync<br/>forbid]
  Gen --> Ops[Vec&lt;FileOp&gt;]
  Ops --> Exec[shell::execute]
Loading
項目 変更前 変更後
計算の読み込み std::fs::read_to_string,Path::exists などを直接呼ぶ Tree/ConfigFiles 経由で Snapshot に問い合わせる
禁止リスト 書き込みのみ std::fs の読み込み,Path の exists/is_dir/read_dir/metadata,std::env,Command::new も禁止
例外 shell::io shell::load,shell::io,および cli/source/runtime/github_app/shell::hook_bundle/build.rs が理由付き #![expect]
forbid generation 等 snapshot,layout,manifest,inventory,render を追加

検証

  • cargo test: 単体 206 件,統合テスト,golden テストがすべて成功(golden は無変更で,生成物は byte 単位で同一)
  • cargo clippy -- -D warnings,cargo fmt --check(lefthook の pre-commit)
  • ローダーのテストを追加: テキストの記録範囲,symlink(1 段だけ辿る.循環しない),listing,probe と document の併用
  • CI all-green,レビュー対応
設計上の判断・範囲・注意
  • 設計は ADR-0028 に追記し,docs/DESIGN.md と docs/DESIGN_ja.md も更新した.
  • install は段階的に描画する.各段階は前段の適用後に自分の snapshot を取る(carry-over した設定,bundle アセットの衝突確認).
  • symlink された hooks ディレクトリ(profile 間の共有)は 1 段だけ辿る.辿らないと保護パスが黙って空になるため.regular_files は symlink の先を除く(従来の走査と同じ).
  • snapshot は生のテキストを持ち,文書の解析は使う場所で行う.型への一度きりの解析は波 3 に回す.
  • source ツリー全体を走査するため,巨大な source では文書の読み込み量が増える.
  • コミットは snapshot・ローダー・移行・禁止を 1 つにまとめた.pre-commit の clippy(dead code 警告)で,使われない型を単独ではコミットできないため.
  • 範囲外: 所有範囲の宣言と sync 統一(波 3).

🤖 Generated with Claude Code

furedea and others added 2 commits November 12, 2026 02:53
… reads in computation

Computation used to read the source tree and installed configs while it ran, so a result
depended on the disk at that instant. The shell now reads what a computation needs once into a
Snapshot, and generation, rendering, and sync functions query that value instead of the disk.

- add `Snapshot`, `Tree`, `ConfigFiles`, and `SnapshotRequest` in `snapshot.rs`
- add `shell::load`, the only reader, with its symlink and text rules
- take a `Tree` or `ConfigFiles` in `generation`, `layout`, `manifest`, `inventory`, and the
  renderer; render in stages that each take their own snapshot
- ban std reads, `Path` probes, `std::env`, and `Command::new` in `clippy.toml`, with scoped
  `#![expect]` in the imperative edge modules and `forbid` on the rest

Generated output is unchanged; the golden tests pass as they were.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@furedea

furedea commented Nov 11, 2026

Copy link
Copy Markdown
Owner

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-11T18:20:14.133383Z a11d36c Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Comment thread src/render.rs Outdated
for bundle in context.external_hooks {
targets.extend(bundle.open(files)?.asset_install_paths()?);
}
let existing = load_snapshot(&SnapshotRequest {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 — Bundle-to-bundle conflict detection is lost. The existing snapshot is taken once, before any bundle's assets get copied, so asset_op's !output.files().exists(&target) check can no longer see files that an earlier bundle in the same loop just wrote. Before this PR, asset_ops(out) checked the live disk after each previous bundle had been executed.

Example: install --extra-hook foo=/a --extra-hook foo=/b (same name, or the same bundle passed twice). Both bundles map to .../external/foo/.... Before, this failed with "external hook bundle foo conflicts with …". Now the second CopyFile overwrites the first without any error, and both bundles' hooks still get merged into the provider configs. I couldn't find any other place that rejects duplicate bundle names.

Possible fix: collect every bundle's ops first and reject duplicate targets across bundles, or take a fresh probe snapshot after each bundle's execute. There is also no test for the "conflicts with" path, so a regression test would help.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

修正しました(89b129d).各 bundle が直前の bundle の適用後に out を probe し直すようにし,同じ bundle を 2 回渡すと conflicts with で失敗する回帰テスト(tests/external-hook-bundles/asset_conflict.rs)を追加しました.

Comment thread src/shell/load.rs Outdated
fn resolve_kind(path: &Path, is_symlink: bool) -> Result<Option<EntryKind>> {
match std::fs::metadata(path) {
Ok(metadata) => Ok(Some(kind_of(&metadata))),
Err(error) if error.kind() != std::io::ErrorKind::NotFound => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 — The walk now aborts on symlinks that the old code ignored. record_path calls resolve_kind → std::fs::metadata (which follows links) on every entry under the whole source root and under every bundle root. Any error other than NotFound is returned, and the whole run fails with it.

The old regular_files walker only covered the synced directories. It skipped symlinks via file_type() and never stat'ed their targets.

So these cases used to be harmless and now make install, list, the generate-* commands and so on fail with "failed to inspect …":

  • a self-referencing or looping symlink (ELOOP)
  • a symlink into a directory the user can't access (EACCES)
  • an unreadable subdirectory anywhere in the source, e.g. under docs/logs/

Consider treating these resolve errors like a broken link (EntryKind::Other) when is_symlink is true. That matches how Path::is_file answers and keeps the old tolerance. A loader test with a symlink loop would cover it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

symlink については修正しました(89b129d).辿れない symlink(循環,権限なし)は EntryKind::Other として記録し,走査を止めません.ループする symlink のローダーテストも追加しました.一方,走査中に読めない通常のサブディレクトリは,同期対象の中だと保護パスが黙って欠けるため,あえてエラーのままにしています.

@github-actions

Copy link
Copy Markdown
Contributor

Review summary

I reviewed the snapshot loader, its migration into generation, render and sync, and the new clippy bans. The design holds up. Every path the computation code reads as text has an extension the loader records, or is requested explicitly as a document. Symlink handling in regular_files matches the old walker, and the order of the load passes keeps document text. I found no blocking issues.

Findings (both non-blocking):

  • P2 src/render.rs install_bundle_assets: the conflict snapshot is taken before any bundle's assets are copied. Duplicate or colliding bundles (for example the same --extra-hook name passed twice) used to fail with "conflicts with"; now the second one silently overwrites the first. No test covers this path.
  • P2 src/shell/load.rs resolve_kind: the loader now follows (stats) every symlink across the whole source and bundle trees. Symlink loops or links the user can't access now abort the run, while the old walker simply skipped symlinks.

Blocking findings (P0/P1): 0

🤖 Generated with Claude Code

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f7b2fd4249

ℹ️ 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".

Comment thread src/render.rs Outdated
..SnapshotRequest::default()
})?;
for bundle in context.external_hooks {
execute(&bundle.open(files)?.asset_ops(Tree::new(out, &existing))?)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject duplicate bundle targets before installing

When two --extra-hook arguments reuse the same bundle name and provide the same namespaced asset path, existing was captured before either bundle was installed, so both asset_ops calls see the target as absent. The second bundle then silently overwrites the first bundle's script, potentially making the first bundle's merged hook commands execute different content; check for duplicate targets across bundles or update the snapshot after each installation.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

上のスレッドと同じ原因です.89b129d で bundle ごとに snapshot を取り直すようにしました.

…le symlinks

Each external bundle now probes the output after the previous bundle was applied, so two
bundles mapping to one path conflict again. A symlink that cannot be followed is recorded as
`Other` instead of aborting the walk.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@furedea

furedea commented Nov 11, 2026

Copy link
Copy Markdown
Owner

@codex review

Comment thread src/render.rs
})?;
let seeds: Vec<FileOp> = paths
.into_iter()
.filter(|path| files.exists(&installed.join(path)))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2: Snapshot::exists doesn't behave like the Path::exists it replaces when a symlink is dangling. The loader records a symlink it can't follow as EntryKind::Other (resolve_kind in shell/load.rs), so exists() returns true. Path::exists returns false in that case.

How it breaks: ~/.codex/config.toml or ~/.pi/agent/settings.json is a symlink whose target is gone (for example a dotfile manager or home-manager link after GC). Before this PR, install skipped the carry-over and generated a fresh config. Now it plans CopyFile from the broken link, copy_file fails, and install aborts. The same change affects codex_config::sync_managed_document_ops (files.exists(target_path), then read_text): that sync used to start from an empty document and now fails with "not a file that could be read as UTF-8 text".

Suggested fix: use files.is_file(..) here and in sync_managed_document_ops, or make exists() follow links the way Path::exists does. A test with a dangling symlink would lock in the behaviour.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

修正しました(a11d36c).辿れない symlink を新しい EntryKind::Unreachable で記録し,Snapshot::exists は Path::exists と同じく false を返します.任意の文書は不在として読まれます.dangling な Codex 設定への sync テストと,ローダーのテスト(dangling/loop)を追加しました.

@github-actions

Copy link
Copy Markdown
Contributor

Review summary

I read the snapshot model, the loader (shell/load.rs), the install, sync and source-resolution paths, and the migrated generation modules.

Findings

  • P2 src/render.rs:121: Snapshot::exists returns true for a dangling symlink, but Path::exists (which it replaces) returns false. If the installed Codex or Pi config is a broken link, install now aborts on a CopyFile from that link. Before, it skipped the carry-over. Codex config sync has the same problem: it now fails instead of starting from an empty document.

Checked and found no problem:

  • Snapshot listing and file walk: children and regular_files rely on the BTreeMap keeping a directory's descendants together, and they do. regular_files skips anything behind a symlink, as the old directory walk did.
  • Symlinks in the loader: it follows one hop and cannot loop. The load passes are ordered so a path named twice keeps its text.
  • What gets read: every file whose text is used is either a .json, .toml, .yaml or .md file inside a loaded tree, or is requested as a document. External skills are only checked for existence and copied, so they need no text.
  • Install config snapshot: the snapshot of merged configs is taken after the carry-over. The steps that run after it don't touch the Codex or Pi config files.
  • Bundle assets: the step-by-step conflict check works and has a new test.

The one finding is P2, so nothing here blocks the merge.

🤖 Generated with Claude Code

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 89b129d7ca

ℹ️ 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".

Comment thread src/shell/load.rs Outdated
Ok(metadata) => Ok(Some(kind_of(&metadata))),
// A link that cannot be followed (broken, looping, or into a place it may not enter) is
// `Other`, as `Path::is_file` would answer for it.
Err(_) if is_symlink => Ok(Some(EntryKind::Other)),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Treat dangling document symlinks as missing

When an optional config target is a dangling symlink, metadata returns NotFound, but this arm records it as Other before the NotFound arm can return None. The sync readers then call read_text_if_present, see a present entry without text, and abort; previously read_to_string returned NotFound, so commands such as Devin/Hermes/pi sync created an empty target and dsh sync skipped an uninitialized target. Preserve the missing-file behavior for explicitly loaded documents while retaining Other where needed for tree walks.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

上のスレッドと同じ原因です.a11d36c で dangling な symlink は不在として扱い,read_text_if_present が None を返すようにしました.

…ists

A dangling or looping symlink is recorded as `Unreachable`, so `exists` is false and an optional
document reads as missing. A dangling config link no longer aborts carry-over or sync.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@furedea

furedea commented Nov 11, 2026

Copy link
Copy Markdown
Owner

@codex review

@github-actions

Copy link
Copy Markdown
Contributor

Review summary (read-only)

I found no blocking issues and posted no inline comments.

What I checked:

  • shell::load / Snapshot: symlink handling follows one hop and cannot loop (Visit::inside_link). regular_files skips anything behind a symlink below the directory, the same as the old regular_files walk. The BTreeMap range plus starts_with keeps a directory's entries together because Path ordering compares whole components. When a path is requested twice, the later pass keeps its text, because documents are recorded last.
  • Text coverage: every read_text / read_text_if_present call targets a .json/.toml/.yaml/.md file inside a walked tree, or a path listed under documents. That covers the source layout files, bundle hook_bundle.json and hook JSON, staged hook-bundle files, sync targets, and the Codex managed-state file. External skills are only probed, which is enough because they are copied, never parsed.
  • Snapshot timing in install: carry-over runs before render_installation_for takes its snapshot, so merged configs are seen. Each bundle's conflict probe runs after the earlier operations have been applied. preserve_claude_settings takes a fresh snapshot after rendering. Within the provider loop, nothing reads a file through the snapshot that an earlier provider wrote; CopyTree from rendered skills runs in the shell.
  • Sync: each ConfigSync variant's inputs (generated file, target, managed state) are in the request. Canonicalizing the dsh bundle path now happens at the boundary.

Minor notes, not filed:

  • Source discovery now returns an error instead of falling through when a probe fails with something other than NotFound (for example, a regular file named profiles in the cwd). Previously that case quietly fell back to the packaged source.
  • A whole-tree walk fails on any unreadable subdirectory, even one computation never uses. The PR already mentions the cost of walking large sources.

I couldn't run cargo test in this environment, so I relied on the PR's reported results.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: a11d36cb17

ℹ️ 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".

@furedea
furedea merged commit bf6524d into main Nov 11, 2026
21 checks passed
@furedea
furedea deleted the refactor/load-source-snapshot-at-boundary branch November 11, 2026 18:31
furedea added a commit that referenced this pull request Nov 17, 2026
## 概要

共有の ADR チェック(`adr-check`,markdownlint,lychee)と ast-grep を採用し,CI
で実行する.ADR 本文は変更しない(agent-config ADR-0025).

Refs furedea/agent-config#169

## 変更

- 全 30 件の ADR のメタデータ行(Status,Date,Supersedes,Superseded
by,Related,Amends)を YAML front matter に移した.
- `docs/adr/.markdownlint.yml` を追加した.`default: true`,`MD013:
false`,`MD024: false` に加え,既存本文が違反する次のルールだけを無効にした.
  - MD007: 5 件(ADR-0029 のリスト字下げ)
  - MD033: 1 件(ADR-0027 の `<name>`)
- `ci.yml` に `adr-lint`(`madr-from: 31`)と
`ast-grep`(v1.6.0)を追加し,`all-green` の `needs` に加えた.
- ファイル名は既に `NNNN_words.md` 形式のため,リネームは不要.

## 保守的・曖昧な front matter の値

- ADR-0026: 本文に「superseded by」がない.スキーマが `superseded-by`
を必須とするため,ADR-0027 の `Supersedes: ADR-0026` から `superseded-by:
[ADR-0027]` を補った.
- ADR-0014: `Amends: ADR-0012` に対応するキーがない.precedent に従い `related:
[ADR-0012] # amends ADR-0012` とした.
- ADR-0021: 本文の `## Amendment (2026-10-20)` から `amended`
を作った.要約文は新しく書いた.
- ADR-0028: 2 つの Amendment 節に日付がない.git 履歴(#229,#231)から 2026-11-12 を補った.

## 確認

- `adr-check docs/adr`: 通過
- markdownlint-cli2: 0 エラー
- `lychee --offline docs/adr`: 0 エラー,壊れたリンクなし
- actionlint: `ci.yml` はエラーなし

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: furedea <[email protected]>
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
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