tazuna 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -219,6 +219,8 @@ changes.md (AI 出力)・クリップボード・リポジトリに同梱され
219
219
  - 書き込み先パスは**プロジェクトルート相対のみ**。絶対パス・UNC・ドライブレター・`..`・`~`・
220
220
  `:` (NTFS 代替データストリーム)・Windows 予約デバイス名 (CON/NUL/COM1 等、末尾ドット・
221
221
  空白による偽装を含む) を拒否します
222
+ - `.git` の中と `.tazuna/`・`.petari/` の中も変更させません (git の設定やフックの書き換えは、git の操作の
223
+ ときにコマンドを動かし、しかも git diff に出ないため)
222
224
  - シンボリックリンク自体の書き換えに加え、**symlink ディレクトリ経由でルート外へ出るパスも
223
225
  realpath 検証で拒否**します
224
226
  - パス検証は apply だけでなく undo / show (履歴 manifest 由来のパス) にも適用します
@@ -234,6 +236,8 @@ changes.md (AI 出力)・クリップボード・リポジトリに同梱され
234
236
  - すべての適用は `.tazuna/history/` に **適用前後のファイル・指示原本・SHA-256 付き
235
237
  manifest** として記録され、`tazuna undo` で巻き戻せます (監査証跡)
236
238
  - Git 作業ツリーに未コミット変更がある場合は警告し、適用前に確認を求めます
239
+ - `tazuna commit` と設定の `git.commitEachApply` (次の適用の前に前回の分をコミット) は、tazuna が書いた
240
+ ファイルだけを `git add` / `git commit` します (フックは動かさず、push はしません)。それ以外に git へ書き込みません
237
241
  - 失敗レポート (AI に貼り返す前提) の実ファイルの抜粋は、認証情報らしき値を `[MASKED]` に
238
242
  伏せてから載せます。伏せ字のまま書き込んで実際の値を消すこともありません (戻せなければ止める)
239
243
 
package/dist/cli.js CHANGED
@@ -4,7 +4,7 @@ import { fileURLToPath } from "node:url";
4
4
  import { join, dirname } from "node:path";
5
5
  import { TOOL_NAME } from "./brand.js";
6
6
  import { err as errLine } from "./infra/term.js";
7
- const SUBCOMMANDS = ["pack", "build", "undo", "show", "list", "protocol", "init", "watch"];
7
+ const SUBCOMMANDS = ["pack", "build", "undo", "show", "list", "protocol", "init", "watch", "commit"];
8
8
  function version() {
9
9
  const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
10
10
  return JSON.parse(readFileSync(pkgPath, "utf8")).version;
@@ -22,6 +22,8 @@ Usage:
22
22
  ${T} undo [ID] 履歴を巻き戻す (ID 省略時: 直近)
23
23
  ${T} show [ID] 履歴の差分を表示 (VS Code / ブラウザ)。--edit で手修正 (VS Code)
24
24
  ${T} list 履歴の一覧を表示
25
+ ${T} commit 直近の適用で書いたファイルだけを、changes.md の概要でコミット (push はしない)。
26
+ 設定の git.commitEachApply を有効にすると、次の適用の前に自動で行う
25
27
  ${T} build [入力] MSBuild でビルドし、失敗したらエラーと周辺のコードをクリップボードへ
26
28
  ${T} protocol AI への規約文を標準出力に出す (パックには内蔵の規約文が自動で入る。
27
29
  repomix など別の道具で使うとき用)
@@ -86,6 +88,10 @@ export async function main(argv) {
86
88
  const { watchCommand } = await import("./commands/watch.js");
87
89
  return watchCommand(rest);
88
90
  }
91
+ case "commit": {
92
+ const { commitCommand } = await import("./commands/commit.js");
93
+ return commitCommand(rest);
94
+ }
89
95
  default:
90
96
  process.stderr.write(`${TOOL_NAME}: "${sub}" は未実装です\n`);
91
97
  return 1;
@@ -8,6 +8,7 @@ import { existsSync, readFileSync } from "node:fs";
8
8
  import { join, resolve } from "node:path";
9
9
  import { parseArgs } from "node:util";
10
10
  import { invalidPathReason, planChangeSet, } from "../core/applier.js";
11
+ import { buildCommitMessage } from "../core/commit-message.js";
11
12
  import { changeSetFingerprint } from "../core/fingerprint.js";
12
13
  import { fileNameKey, looksLikeOtherRepository } from "../core/other-repo.js";
13
14
  import { PRESENCE_STAGE_LABEL } from "../core/matcher.js";
@@ -19,12 +20,13 @@ import { loadConfig } from "../infra/config.js";
19
20
  import { findRecentChangesFiles, resolveDownloadsDir, } from "../infra/downloads.js";
20
21
  import { deleteFile, isInsideRoot, readFileState, sha256, writeBytes } from "../infra/files.js";
21
22
  import { stateDir } from "../infra/history.js";
22
- import { gitDirtyFiles, listGitFiles } from "../infra/git.js";
23
+ import { gitDirtyFiles, gitHeadCommit, listGitFiles } from "../infra/git.js";
23
24
  import { collectStyleSampleGroups } from "../infra/new-file-style.js";
24
25
  import { err, out, outEmphasis } from "../infra/term.js";
25
26
  import { beginHistory, createHistoryId, findAppliedHistory, finishHistory, pruneHistory, } from "../infra/history.js";
26
27
  import { confirm } from "../infra/prompt.js";
27
28
  import { findProjectRoot } from "../infra/root.js";
29
+ import { commitPending, lookupPendingCommit, shortSha } from "./commit-apply.js";
28
30
  import { formatVbprojPlan, planVbprojRegistrations } from "./vbproj-register.js";
29
31
  /** このファイルは書き込み対象か (適用済みのみのファイルは書き込み不要なので含めない) */
30
32
  function isApplicable(o) {
@@ -355,10 +357,25 @@ export async function runApply(argv, detected) {
355
357
  return done("duplicate", 1);
356
358
  }
357
359
  }
360
+ // 1 回の適用 = 1 コミット (config git.commitEachApply): 当てる直前に前回の適用の分をコミットする
361
+ const commitLookup = config.git.commitEachApply
362
+ ? lookupPendingCommit(root, { requireSameHead: true })
363
+ : null;
364
+ const printCommitPlan = () => {
365
+ if (commitLookup === null || commitLookup.kind === "none")
366
+ return;
367
+ if (commitLookup.kind === "skip") {
368
+ out(`コミット: ${commitLookup.reason}`);
369
+ return;
370
+ }
371
+ const p = commitLookup.pending;
372
+ out(`コミット: 当てる前に、前回の適用 (履歴 ${p.id}・${p.paths.length} ファイル) を「${p.subject}」でコミットします`);
373
+ };
358
374
  if (values["dry-run"]) {
359
375
  out(`dry-run: 適用予定 ${applicable.length} ファイル (書き込みなし)`);
360
376
  printPreview(applicable);
361
377
  printExtras();
378
+ printCommitPlan();
362
379
  printAlreadyApplied(plan.outcomes);
363
380
  const dryRunNote = buildBlankInsensitiveNote(plan.outcomes);
364
381
  if (dryRunNote !== null)
@@ -385,6 +402,7 @@ export async function runApply(argv, detected) {
385
402
  if (plan.failures.length > 0) {
386
403
  out(` (検証失敗 ${plan.failures.length} 件は --partial によりスキップ)`);
387
404
  }
405
+ printCommitPlan();
388
406
  const dirty = await gitDirtyFiles(root);
389
407
  if (dirty !== null && dirty.length > 0) {
390
408
  out(`警告: Git 作業ツリーに未コミットの変更が ${dirty.length} 件あります`);
@@ -395,6 +413,27 @@ export async function runApply(argv, detected) {
395
413
  return done("aborted", 1);
396
414
  }
397
415
  }
416
+ if (commitLookup?.kind === "pending") {
417
+ const p = commitLookup.pending;
418
+ const r = commitPending(root, p, new Date());
419
+ if (r.kind === "committed") {
420
+ out(`前回の適用 (履歴 ${p.id}) をコミットしました: ${shortSha(r.sha)} ${p.subject}`);
421
+ }
422
+ else if (r.kind === "nothing") {
423
+ out(`前回の適用 (履歴 ${p.id}) のファイルには変更が無いため、コミットしませんでした`);
424
+ }
425
+ else if (r.kind === "not-repo") {
426
+ err(`${TOOL_NAME}: 前回の適用をコミットできません (${r.message})。コミットせずに当てます`);
427
+ }
428
+ else {
429
+ // 1 回 1 コミットを崩さないよう、前回の分をコミットできないうちは次を当てない
430
+ err(`${TOOL_NAME}: 前回の適用 (履歴 ${p.id}) をコミットできなかったため、この changes.md は当てていません:`);
431
+ for (const line of r.message.split("\n"))
432
+ err(` ${line}`);
433
+ err(` git の問題を直してから、もう一度当ててください (前回の分だけを先にコミットするなら ${TOOL_NAME} commit)`);
434
+ return done("commit-failed", 1);
435
+ }
436
+ }
398
437
  // 4. before 保存 → 書き換え → after 保存 (§4.1 手順 4, §5)
399
438
  const id = createHistoryId(root, new Date());
400
439
  const before = new Map();
@@ -469,6 +508,8 @@ export async function runApply(argv, detected) {
469
508
  afterSha256: sha256(w.after),
470
509
  });
471
510
  }
511
+ // 適用したときの HEAD (次の適用の前の自動コミットで、その間に利用者がコミットしたかを見分ける)
512
+ const gitHead = gitHeadCommit(root);
472
513
  const manifest = {
473
514
  id,
474
515
  appliedAt: new Date().toISOString(),
@@ -476,6 +517,7 @@ export async function runApply(argv, detected) {
476
517
  partial: values.partial,
477
518
  source,
478
519
  changesFingerprint: fingerprint,
520
+ ...(gitHead !== undefined ? { gitHead } : {}),
479
521
  files: entries,
480
522
  };
481
523
  finishHistory(root, id, manifest, after);
@@ -519,6 +561,11 @@ export async function runApply(argv, detected) {
519
561
  }
520
562
  out("");
521
563
  out(`git diff で差分を確認してください。巻き戻しは \`${TOOL_NAME} undo\` です。`);
564
+ if (config.git.commitEachApply) {
565
+ const next = buildCommitMessage(changeSet.header, id, applicable.length);
566
+ out(`コミット: 次の changes.md を当てる前に「${next.subject}」でコミットします ` +
567
+ `(区切りで締めるときは ${TOOL_NAME} commit。メッセージを変えたいときは、その前にご自身でコミットしてください)`);
568
+ }
522
569
  return done("applied", 0, applicable.length);
523
570
  }
524
571
  /** リポジトリのファイル名 (小文字) の集合。git のリポジトリでなければ null (別のリポジトリ向けの判定をしない) */
@@ -0,0 +1,77 @@
1
+ /**
2
+ * 1 回の適用 = 1 コミット (config の git.commitEachApply と tazuna commit)。
3
+ *
4
+ * 適用の直後にはコミットせず、次の changes.md を当てる直前に前回の分をコミットする。git diff には常に
5
+ * 「最後に当てた分と、その後の手修正」だけが出るので、git diff で確かめてからビルドする流れが変わらない。
6
+ * バッチの最後の 1 回は tazuna commit で締める。
7
+ *
8
+ * コミットするのは前回の適用で tazuna が書いたファイルだけ (手で変えたほかのファイル・ステージ済みの変更は
9
+ * 入れない)。メッセージは changes.md の概要から作る (core/commit-message.ts)。push はしない。
10
+ */
11
+ import { readFileSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import { invalidPathReason } from "../core/applier.js";
14
+ import { buildCommitMessage } from "../core/commit-message.js";
15
+ import { parseChangesRecovering } from "../core/parser.js";
16
+ import { commitPaths, gitHeadCommit } from "../infra/git.js";
17
+ import { findUncommittedApply, historyRoot, markCommitted } from "../infra/history.js";
18
+ /** 保存済みの changes.md の概要 (読めなければ空。件名は既定の文になる) */
19
+ function savedSummary(root, id) {
20
+ try {
21
+ const text = readFileSync(join(historyRoot(root), id, "changes.md"), "utf8").replace(/^/, "");
22
+ return parseChangesRecovering(text).changeSet.header;
23
+ }
24
+ catch {
25
+ return "";
26
+ }
27
+ }
28
+ /**
29
+ * コミットしていない直近の適用。
30
+ * @param requireSameHead 次の適用の前の自動コミットでは true: 適用したときから HEAD が動いていれば、
31
+ * 利用者が自分でコミットした (または ブランチを切り替えた) とみなしてコミットしない。tazuna commit は false
32
+ */
33
+ export function lookupPendingCommit(root, options) {
34
+ const found = findUncommittedApply(root);
35
+ if (found === null)
36
+ return { kind: "none" };
37
+ const { id, manifest } = found;
38
+ const paths = [];
39
+ for (const f of manifest.files) {
40
+ if (f?.applied !== true)
41
+ continue;
42
+ // manifest は非信頼入力。apply と同じパスの検証を通らないものがあればコミットしない
43
+ if (typeof f.path !== "string" || invalidPathReason(f.path) !== null) {
44
+ return { kind: "skip", id, reason: `履歴 ${id} の manifest に不正なパスがあるため、コミットしません` };
45
+ }
46
+ paths.push(f.path);
47
+ }
48
+ if (options.requireSameHead) {
49
+ if (manifest.gitHead === undefined) {
50
+ return { kind: "skip", id, reason: `履歴 ${id} は適用したときの HEAD の記録がないため、自動ではコミットしません` };
51
+ }
52
+ const head = gitHeadCommit(root);
53
+ if (head !== undefined && head !== manifest.gitHead) {
54
+ return {
55
+ kind: "skip",
56
+ id,
57
+ reason: `履歴 ${id} を当てた後にコミットが増えている (またはブランチが変わった) ため、前回の分はご自身でコミットしたものとみなします`,
58
+ };
59
+ }
60
+ }
61
+ const { subject, message } = buildCommitMessage(savedSummary(root, id), id, paths.length);
62
+ return { kind: "pending", pending: { id, paths, subject, message, manifest } };
63
+ }
64
+ /** コミットし、できたら manifest に記録する */
65
+ export function commitPending(root, pending, now) {
66
+ const result = commitPaths(root, pending.paths, pending.message);
67
+ if (result.kind === "committed") {
68
+ try {
69
+ markCommitted(root, pending.id, result.sha, now);
70
+ }
71
+ catch {
72
+ // 記録できなくても、次の自動コミットは HEAD が動いたことで見送られる (二重にコミットしない)
73
+ }
74
+ }
75
+ return result;
76
+ }
77
+ export const shortSha = (sha) => (/^[0-9a-f]{7,64}$/.test(sha) ? sha.slice(0, 7) : "");
@@ -0,0 +1,63 @@
1
+ /**
2
+ * tazuna commit — 直近の適用 (まだコミットしていないもの) で tazuna が書いたファイルだけを、changes.md の概要を
3
+ * メッセージにしてコミットする。config の git.commitEachApply では次の適用の前に自動で行う分を、バッチの最後に
4
+ * 締めるときに使う (設定によらず使える)。push はしない。フックは動かさない (infra/git.ts の commitPaths)
5
+ */
6
+ import { parseArgs } from "node:util";
7
+ import { TOOL_NAME } from "../brand.js";
8
+ import { loadConfig } from "../infra/config.js";
9
+ import { findProjectRoot } from "../infra/root.js";
10
+ import { err, out } from "../infra/term.js";
11
+ import { commitPending, lookupPendingCommit, shortSha } from "./commit-apply.js";
12
+ export async function commitCommand(argv) {
13
+ const { values } = parseArgs({
14
+ args: argv,
15
+ options: {
16
+ root: { type: "string" },
17
+ "dry-run": { type: "boolean", default: false },
18
+ },
19
+ allowPositionals: false,
20
+ });
21
+ const root = findProjectRoot(process.cwd(), values.root);
22
+ loadConfig(root); // 設定エラーの早期検出のみ
23
+ const lookup = lookupPendingCommit(root, { requireSameHead: false });
24
+ if (lookup.kind === "none") {
25
+ out("コミットしていない適用はありません (直近の適用はコミット済みか、巻き戻し済みです)");
26
+ return 0;
27
+ }
28
+ if (lookup.kind === "skip") {
29
+ err(`${TOOL_NAME}: ${lookup.reason}`);
30
+ return 1;
31
+ }
32
+ const { pending } = lookup;
33
+ if (values["dry-run"]) {
34
+ out(`dry-run: 履歴 ${pending.id} の ${pending.paths.length} ファイルを、次のメッセージでコミットします (コミットはしていません)`);
35
+ out("");
36
+ for (const line of pending.message.trimEnd().split("\n"))
37
+ out(` ${line}`);
38
+ out("");
39
+ for (const p of pending.paths)
40
+ out(` ${p}`);
41
+ return 0;
42
+ }
43
+ const result = commitPending(root, pending, new Date());
44
+ switch (result.kind) {
45
+ case "committed":
46
+ out(`コミットしました: ${shortSha(result.sha)} ${pending.subject} (履歴 ${pending.id}・${result.files.length} ファイル)`);
47
+ for (const p of result.files)
48
+ out(` ${p}`);
49
+ out("push はしていません。共有するときはご自身で push してください");
50
+ return 0;
51
+ case "nothing":
52
+ out(`履歴 ${pending.id} のファイルには、コミットする変更がありません (コミット済みか、元に戻されています)`);
53
+ return 0;
54
+ case "not-repo":
55
+ err(`${TOOL_NAME}: コミットできません: ${result.message}`);
56
+ return 1;
57
+ case "failed":
58
+ err(`${TOOL_NAME}: コミットできませんでした:`);
59
+ for (const line of result.message.split("\n"))
60
+ err(` ${line}`);
61
+ return 1;
62
+ }
63
+ }
@@ -64,7 +64,8 @@ export async function listCommand(argv) {
64
64
  }
65
65
  const appliedCount = m.files.filter((f) => f.applied).length;
66
66
  const status = (m.success ? "成功" : m.partial ? "部分適用" : "失敗") +
67
- (m.undoneAt !== undefined ? " (巻き戻し済み)" : "");
67
+ (m.undoneAt !== undefined ? " (巻き戻し済み)" : "") +
68
+ (m.committed !== undefined ? " (コミット済み)" : "");
68
69
  const summary = summaryLine(dir);
69
70
  out(`${id} ${status} ${appliedCount} ファイル ${summary}`);
70
71
  }
@@ -15,6 +15,7 @@ import { historyRoot, listHistoryIds, markUndone, readManifest, } from "../infra
15
15
  import { confirm } from "../infra/prompt.js";
16
16
  import { findProjectRoot } from "../infra/root.js";
17
17
  import { err, out } from "../infra/term.js";
18
+ import { shortSha } from "./commit-apply.js";
18
19
  /**
19
20
  * 巻き戻していない直近の履歴 ID。manifest を読めない履歴はそこで止めて返す
20
21
  * (後の readManifest で「見つかりません」と知らせる。読めない履歴を飛ばして古いものを戻さない)
@@ -60,6 +61,13 @@ export async function undoCommand(argv) {
60
61
  err(`${TOOL_NAME}: 履歴 ${id} は巻き戻し済みです (${TOOL_NAME} list で確認してください)`);
61
62
  return 1;
62
63
  }
64
+ // tazuna がコミットした適用は git で戻す (作業ツリーだけ戻すと、コミットと食い違った変更が残るため)
65
+ if (manifest.committed !== undefined) {
66
+ const sha = typeof manifest.committed?.sha === "string" ? shortSha(manifest.committed.sha) : "";
67
+ err(`${TOOL_NAME}: 履歴 ${id} はコミット済みです${sha !== "" ? ` (${sha})` : ""}。` +
68
+ `戻すときは ${sha !== "" ? `git revert ${sha}` : "git revert"} を使ってください`);
69
+ return 1;
70
+ }
63
71
  const hdir = join(historyRoot(root), id);
64
72
  const applied = manifest.files.filter((f) => f.applied);
65
73
  if (applied.length === 0) {
@@ -77,6 +77,15 @@ export function describeWatchResult(result, file) {
77
77
  `このリポジトリ向けなら ${TOOL_NAME} ${quoted(file.path)}${rootSuffix(file.rootOption)} で失敗の理由を確かめられます`,
78
78
  ],
79
79
  };
80
+ case "commit-failed":
81
+ return {
82
+ title: "✗ コミットできず止めました",
83
+ headline: "✗ 前回の適用をコミットできなかったため、この changes.md は当てていません (理由は上)",
84
+ details: [
85
+ `git の問題を直してから ${TOOL_NAME} ${quoted(file.path)}${rootSuffix(file.rootOption)} で当ててください`,
86
+ `changes.md は ${file.path} に残しています`,
87
+ ],
88
+ };
80
89
  case "dry-run":
81
90
  return {
82
91
  title: "dry-run: 検証しました",
@@ -3,7 +3,7 @@
3
3
  * I/O を持たない純粋層: ファイル状態 (FileState) を受け取り、
4
4
  * 書き込むべきバイト列と失敗一覧を返す。実際の読み書きは commands/ が行う。
5
5
  */
6
- import { TOOL_NAME } from "../brand.js";
6
+ import { LEGACY_STATE_DIRECTORY, STATE_DIRECTORY, TOOL_NAME } from "../brand.js";
7
7
  import { EncodingError, decodeFile, encodeDocument, findUnencodable, makeDocument, } from "./encoding.js";
8
8
  import { STAGE_LABEL, contentEqualsStage, findContentStage, findInsertionPresenceStage, matchBlock, } from "./matcher.js";
9
9
  import { MASK_TOKEN, hasMaskToken, maskLinesForDisplay, maskedValueCounts, maskedViews, restoreMaskedLines, } from "./mask.js";
@@ -11,7 +11,45 @@ import { analyzeNearest } from "./nearest.js";
11
11
  import { describeChars, foldToCp932 } from "./sjis.js";
12
12
  /** Windows の予約デバイス名 (拡張子付きも不可) */
13
13
  const WINDOWS_RESERVED = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..+)?$/i;
14
- /** §9: プロジェクトルート相対のみ。絶対パス・`..`・`~`・Windows 特殊パスを拒否 */
14
+ /**
15
+ * macOS の HFS+ が名前の比較で無視する文字 (git の core.protectHFS と同じ範囲)。
16
+ * `.g‌it` が `.git` と同じディレクトリを指すため、除いてから名前を比べる
17
+ */
18
+ const HFS_IGNORABLE = /[‌-‏‪-‮-]/g;
19
+ /**
20
+ * changes.md で変更させないディレクトリ (どの階層にあっても)。
21
+ * - `.git`: 設定 (core.fsmonitor など) やフックを書き換えると、git の操作 (tazuna 自身の git status、
22
+ * VS Code のソース管理、利用者の git diff) のときに任意のコマンドが実行される。しかも .git の中の変更は
23
+ * git diff に出ないため、適用後の確認で気づけない
24
+ * - 状態ディレクトリ (`.tazuna` / 旧名 `.petari`): PC ごとの設定・適用の履歴。プロジェクトのファイルではない
25
+ * Windows の短い名前 (8.3 形式。`.git` → `GIT~1`) も同じものとして扱う
26
+ */
27
+ const PROTECTED_DIRECTORIES = [
28
+ { name: ".git", reason: "'.git' の中は変更できません (git の設定やフックを書き換えると、git の操作のときにコマンドが実行されるため)" },
29
+ {
30
+ name: STATE_DIRECTORY,
31
+ reason: `${TOOL_NAME} の状態ディレクトリ (${STATE_DIRECTORY} / ${LEGACY_STATE_DIRECTORY}) の中は変更できません`,
32
+ },
33
+ {
34
+ name: LEGACY_STATE_DIRECTORY,
35
+ reason: `${TOOL_NAME} の状態ディレクトリ (${STATE_DIRECTORY} / ${LEGACY_STATE_DIRECTORY}) の中は変更できません`,
36
+ },
37
+ ].map((d) => ({
38
+ ...d,
39
+ // 8.3 形式の短い名前: 先頭のドットを除いた最初の 6 文字 + ~ + 数字 (名前は英小文字だけ)
40
+ shortName: new RegExp(`^${d.name.slice(1, 7)}~[0-9]+$`),
41
+ }));
42
+ /** 保護するディレクトリに当たる名前なら、その理由 */
43
+ function protectedSegmentReason(segment) {
44
+ // Windows は末尾のドット/空白を無視し、大文字小文字を区別しない。macOS も既定で区別しない
45
+ const name = segment.replace(HFS_IGNORABLE, "").replace(/[. ]+$/, "").toLowerCase();
46
+ for (const d of PROTECTED_DIRECTORIES) {
47
+ if (name === d.name || d.shortName.test(name))
48
+ return d.reason;
49
+ }
50
+ return null;
51
+ }
52
+ /** §9: プロジェクトルート相対のみ。絶対パス・`..`・`~`・Windows 特殊パス・.git と状態ディレクトリを拒否 */
15
53
  export function invalidPathReason(path) {
16
54
  if (path.trim() === "")
17
55
  return "パスが空です";
@@ -20,7 +58,9 @@ export function invalidPathReason(path) {
20
58
  }
21
59
  if (path.includes(":"))
22
60
  return "':' を含むパスは使えません (Windows の代替データストリーム対策)";
23
- const segments = path.split("/");
61
+ // changes.md のパスはパーサーが `/` にそろえる。manifest (非信頼入力) のパスは `\` のこともあり、
62
+ // Windows では `\` も区切りになるため、どちらでも区切る
63
+ const segments = path.split(/[\\/]/);
24
64
  if (segments.includes(".."))
25
65
  return "'..' を含むパスは使えません";
26
66
  if (path.startsWith("~"))
@@ -29,6 +69,11 @@ export function invalidPathReason(path) {
29
69
  if (segments.some((s) => WINDOWS_RESERVED.test(s.replace(/[. ]+$/, "")))) {
30
70
  return "Windows の予約デバイス名 (CON, NUL, COM1 等) を含むパスは使えません";
31
71
  }
72
+ for (const s of segments) {
73
+ const reason = protectedSegmentReason(s);
74
+ if (reason !== null)
75
+ return reason;
76
+ }
32
77
  return null;
33
78
  }
34
79
  function fileFailure(change, kind, message) {
@@ -0,0 +1,103 @@
1
+ /**
2
+ * changes.md の概要 (## CHANGES と最初の ### FILE: の間) からコミットメッセージを作る (純粋関数)。
3
+ * 1 回の適用 = 1 コミット (config の git.commitEachApply と tazuna commit) で使う。
4
+ *
5
+ * - 件名: 概要の最初の内容のある行。最初の「。」の前まで、長ければ切り詰める
6
+ * - 本文: 概要の全文 (件名がその行そのものなら、その次の行から)。Mermaid などのコードブロックと
7
+ * 「影響ファイル:」の一覧は除く (ファイルの一覧はコミット自体に残る)
8
+ * - 末尾: 履歴 ID のトレーラー (コミットと tazuna の履歴を突き合わせるため)
9
+ *
10
+ * 概要は AI の書いたテキストなので、制御文字 (改行とタブを除く) と双方向制御文字を除く
11
+ */
12
+ import { TOOL_NAME } from "../brand.js";
13
+ /** 件名の長さの上限 (文字数) */
14
+ export const SUBJECT_MAX_CHARS = 60;
15
+ /** コミットメッセージの末尾に付けるトレーラーの名前 */
16
+ export const HISTORY_TRAILER = "Tazuna-History";
17
+ // 改行 (\n) とタブ以外の C0、DEL、C1、双方向制御文字 (Trojan Source)
18
+ const UNSAFE_CHARS = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F؜‎‏‪-‮⁦-⁩]/g;
19
+ function cleanSummary(header) {
20
+ const lines = header.replace(/\r\n?/g, "\n").replace(UNSAFE_CHARS, "").split("\n");
21
+ const kept = [];
22
+ let fence = null;
23
+ let inFileList = false;
24
+ for (const raw of lines) {
25
+ const line = raw.trimEnd();
26
+ const trimmed = line.trim();
27
+ if (fence !== null) {
28
+ if (trimmed.startsWith(fence))
29
+ fence = null;
30
+ continue;
31
+ }
32
+ const fenceMatch = /^(`{3,}|~{3,})/.exec(trimmed);
33
+ if (fenceMatch !== null) {
34
+ fence = fenceMatch[1];
35
+ continue;
36
+ }
37
+ if (/^影響ファイル\s*[::]/.test(trimmed)) {
38
+ inFileList = true;
39
+ continue;
40
+ }
41
+ if (inFileList) {
42
+ if (/^[-*+]\s/.test(trimmed))
43
+ continue;
44
+ inFileList = false;
45
+ }
46
+ kept.push(line);
47
+ }
48
+ // 前後の空行を落とし、続く空行は 1 つにまとめる
49
+ const collapsed = [];
50
+ for (const line of kept) {
51
+ if (line.trim() === "" && (collapsed.length === 0 || collapsed[collapsed.length - 1]?.trim() === ""))
52
+ continue;
53
+ collapsed.push(line);
54
+ }
55
+ while (collapsed.length > 0 && collapsed[collapsed.length - 1]?.trim() === "")
56
+ collapsed.pop();
57
+ return collapsed;
58
+ }
59
+ /** Markdown の見出し・箇条書き・引用・強調の記号を件名から外す */
60
+ function plainSubject(line) {
61
+ return line
62
+ .trim()
63
+ .replace(/^(#{1,6}\s+|[-*+]\s+|>\s*|\d+[.)]\s+)/, "")
64
+ .replace(/\*\*|__/g, "")
65
+ .trim();
66
+ }
67
+ function truncate(text, max) {
68
+ const chars = [...text];
69
+ return chars.length <= max ? text : `${chars.slice(0, max - 1).join("")}…`;
70
+ }
71
+ /**
72
+ * @param header ChangeSet.header (概要)
73
+ * @param historyId 適用の履歴 ID
74
+ * @param fileCount コミットするファイル数 (概要が空のときの件名に使う)
75
+ */
76
+ export function buildCommitMessage(header, historyId, fileCount) {
77
+ const lines = cleanSummary(header);
78
+ const firstIndex = lines.findIndex((l) => plainSubject(l) !== "");
79
+ let subject;
80
+ let body;
81
+ if (firstIndex === -1) {
82
+ subject = `${TOOL_NAME} で changes.md を適用 (${fileCount} ファイル)`;
83
+ body = [];
84
+ }
85
+ else {
86
+ const first = plainSubject(lines[firstIndex]);
87
+ const period = first.indexOf("。");
88
+ const head = period > 0 ? first.slice(0, period) : first;
89
+ const rest = period > 0 ? first.slice(period + 1).trim() : "";
90
+ subject = truncate(head, SUBJECT_MAX_CHARS);
91
+ // 件名が最初の行 (の 1 文) そのものなら本文はその次の行から。途中で切ったなら、情報を落とさないよう
92
+ // その行から本文に入れる
93
+ const cut = rest !== "" || subject !== head;
94
+ body = cut ? lines.slice(firstIndex) : lines.slice(firstIndex + 1);
95
+ while (body.length > 0 && body[0]?.trim() === "")
96
+ body.shift();
97
+ }
98
+ const parts = [subject];
99
+ if (body.length > 0)
100
+ parts.push("", ...body);
101
+ parts.push("", `${HISTORY_TRAILER}: ${historyId}`);
102
+ return { subject, message: `${parts.join("\n")}\n` };
103
+ }
@@ -10,6 +10,7 @@ export const DEFAULT_CONFIG = {
10
10
  vscodeCommand: "code",
11
11
  clipReportOnFailure: true,
12
12
  vbproj: { register: true },
13
+ git: { commitEachApply: false },
13
14
  };
14
15
  /** tazuna init が書く .tazuna/config.json の雛形 (PC ごとの設定。git の管理外) */
15
16
  export const CONFIG_TEMPLATE = `{
@@ -18,7 +19,8 @@ export const CONFIG_TEMPLATE = `{
18
19
  "historyLimit": null,
19
20
  "vscodeCommand": "code",
20
21
  "clipReportOnFailure": true,
21
- "vbproj": { "register": true }
22
+ "vbproj": { "register": true },
23
+ "git": { "commitEachApply": false }
22
24
  }
23
25
  `;
24
26
  function globalConfigBase() {
@@ -65,6 +67,10 @@ function validateConfig(c) {
65
67
  if (typeof c.vbproj !== "object" || c.vbproj === null || typeof register !== "boolean") {
66
68
  throw new Error('config の vbproj が不正です ({ "register": true | false } を指定)');
67
69
  }
70
+ const commitEachApply = c.git?.commitEachApply;
71
+ if (typeof c.git !== "object" || c.git === null || typeof commitEachApply !== "boolean") {
72
+ throw new Error('config の git が不正です ({ "commitEachApply": true | false } を指定)');
73
+ }
68
74
  const limit = c.historyLimit;
69
75
  if (limit !== null && (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1)) {
70
76
  throw new Error(`config の historyLimit が不正です: ${String(limit)} (null または 1 以上の整数)`);
@@ -94,6 +100,11 @@ export function loadConfig(root) {
94
100
  ...(global.vbproj ?? {}),
95
101
  ...(project.vbproj ?? {}),
96
102
  },
103
+ git: {
104
+ ...DEFAULT_CONFIG.git,
105
+ ...(global.git ?? {}),
106
+ ...(project.git ?? {}),
107
+ },
97
108
  });
98
109
  }
99
110
  /**
package/dist/infra/git.js CHANGED
@@ -1,13 +1,33 @@
1
1
  import { execFile, spawnSync } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
2
5
  import { promisify } from "node:util";
6
+ import { TOOL_NAME } from "../brand.js";
3
7
  const execFileP = promisify(execFile);
8
+ /**
9
+ * git を読み取りだけで呼ぶための共通の指定。
10
+ * - `core.fsmonitor=false`: リポジトリの設定 (.git/config) に書かれたコマンドを git status / ls-files の
11
+ * ついでに実行させない (設定が書き換えられていた場合の備え。changes.md からは .git に書けない)
12
+ * - `GIT_OPTIONAL_LOCKS=0`: git status が索引 (.git/index) を書き直さない。VS Code のソース管理などが
13
+ * 同時に動いていても index.lock でぶつからない。古い git は知らない環境変数を無視する
14
+ * (`--no-optional-locks` は git 2.15 未満で使えない)
15
+ */
16
+ const GIT_READ_ONLY_ARGS = ["-c", "core.fsmonitor=false"];
17
+ function gitEnv() {
18
+ return { ...process.env, GIT_OPTIONAL_LOCKS: "0" };
19
+ }
4
20
  /**
5
21
  * 未コミット変更のあるファイル一覧 (§9)。
6
22
  * Git が使えない / リポジトリでない場合は null (Git は必須ではない)。
7
23
  */
8
24
  export async function gitDirtyFiles(root) {
9
25
  try {
10
- const { stdout } = await execFileP("git", ["status", "--porcelain"], { cwd: root });
26
+ const { stdout } = await execFileP("git", [...GIT_READ_ONLY_ARGS, "status", "--porcelain"], {
27
+ cwd: root,
28
+ env: gitEnv(),
29
+ windowsHide: true,
30
+ });
11
31
  return stdout.split("\n").filter((l) => l.trim() !== "");
12
32
  }
13
33
  catch {
@@ -20,8 +40,9 @@ export async function gitDirtyFiles(root) {
20
40
  * 子プロセスは配列引数(シェル非経由)。
21
41
  */
22
42
  export function listGitFiles(rootDir) {
23
- const result = spawnSync("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], {
43
+ const result = spawnSync("git", [...GIT_READ_ONLY_ARGS, "ls-files", "-z", "--cached", "--others", "--exclude-standard"], {
24
44
  cwd: rootDir,
45
+ env: gitEnv(),
25
46
  maxBuffer: 256 * 1024 * 1024,
26
47
  windowsHide: true,
27
48
  timeout: 60_000,
@@ -38,3 +59,98 @@ export function listGitFiles(rootDir) {
38
59
  const files = [...new Set(result.stdout.toString("utf8").split("\0").filter((p) => p !== ""))];
39
60
  return { ok: true, files };
40
61
  }
62
+ /** git を同期で実行する (読み取りと同じ指定に加えて、パスを文字どおりに扱い、フックを動かさない) */
63
+ function runGit(cwd, args, noHooksDir, input) {
64
+ const result = spawnSync("git", [...GIT_READ_ONLY_ARGS, "-c", `core.hooksPath=${noHooksDir}`, ...args], {
65
+ cwd,
66
+ // パスの * や :(glob) をパターンとして読ませない (ファイル名どおりのものだけを対象にする)
67
+ env: { ...gitEnv(), GIT_LITERAL_PATHSPECS: "1" },
68
+ input,
69
+ maxBuffer: 64 * 1024 * 1024,
70
+ windowsHide: true,
71
+ timeout: 120_000,
72
+ });
73
+ return {
74
+ status: result.status,
75
+ stdout: result.stdout ?? Buffer.alloc(0),
76
+ stderr: (result.stderr ?? Buffer.alloc(0)).toString("utf8"),
77
+ ...(result.error !== undefined ? { error: result.error } : {}),
78
+ };
79
+ }
80
+ const nulList = (out) => out.toString("utf8").split("\0").filter((p) => p !== "");
81
+ /** git の出力の先頭の数行 (失敗の理由として見せる) */
82
+ const firstLines = (text, n = 8) => text
83
+ .split(/\r?\n/)
84
+ .map((l) => l.trimEnd())
85
+ .filter((l) => l !== "")
86
+ .slice(0, n)
87
+ .join("\n");
88
+ /**
89
+ * 指定したファイル (ルート相対・`/` 区切り) だけをコミットする (1 回の適用 = 1 コミット)。
90
+ * - 未追跡のものは `git add` してから (.gitignore に一致するものは入れない)
91
+ * - `git commit --only` なので、ほかのファイルの手元の変更・ステージ済みの変更はコミットに入らない
92
+ * - メッセージは標準入力から渡す (AI の書いた概要を引数にしない。長さの制限も受けない)
93
+ * - フックは動かさない (core.hooksPath を存在しない場所に向ける)。フックの置き場が作業ツリーにある
94
+ * リポジトリ (husky など) では、確かめる前の changes.md が書き換えたフックを動かしてしまうため
95
+ */
96
+ export function commitPaths(rootDir, paths, message) {
97
+ if (paths.length === 0)
98
+ return { kind: "nothing" };
99
+ // 存在しないディレクトリ (乱数入り) をフックの置き場に指定して、どのフックも見つからないようにする
100
+ const noHooksDir = join(tmpdir(), `${TOOL_NAME}-no-hooks-${randomBytes(8).toString("hex")}`);
101
+ const git = (args, input) => runGit(rootDir, args, noHooksDir, input);
102
+ const inside = git(["rev-parse", "--is-inside-work-tree"]);
103
+ if (inside.error !== undefined) {
104
+ return {
105
+ kind: "not-repo",
106
+ message: inside.error.code === "ENOENT" ? "git が見つかりません" : inside.error.message,
107
+ };
108
+ }
109
+ if (inside.status !== 0 || inside.stdout.toString("utf8").trim() !== "true") {
110
+ return { kind: "not-repo", message: firstLines(inside.stderr, 1) || "git のリポジトリではありません" };
111
+ }
112
+ const tracked = git(["ls-files", "-z", "--cached", "--", ...paths]);
113
+ const untracked = git(["ls-files", "-z", "--others", "--exclude-standard", "--", ...paths]);
114
+ if (tracked.status !== 0 || untracked.status !== 0) {
115
+ return { kind: "failed", message: firstLines(tracked.stderr || untracked.stderr) || "git ls-files に失敗しました" };
116
+ }
117
+ const added = nulList(untracked.stdout);
118
+ const targets = [...new Set([...nulList(tracked.stdout), ...added])];
119
+ if (targets.length === 0)
120
+ return { kind: "nothing" };
121
+ if (added.length > 0) {
122
+ const add = git(["add", "--", ...added]);
123
+ if (add.status !== 0)
124
+ return { kind: "failed", message: firstLines(add.stderr) || "git add に失敗しました" };
125
+ }
126
+ const status = git(["status", "--porcelain", "-z", "--", ...targets]);
127
+ if (status.status !== 0)
128
+ return { kind: "failed", message: firstLines(status.stderr) || "git status に失敗しました" };
129
+ if (nulList(status.stdout).length === 0)
130
+ return { kind: "nothing" };
131
+ const commit = git(["commit", "--only", "--no-verify", "--cleanup=whitespace", "-F", "-", "--", ...targets], message);
132
+ if (commit.error !== undefined)
133
+ return { kind: "failed", message: commit.error.message };
134
+ if (commit.status !== 0) {
135
+ return {
136
+ kind: "failed",
137
+ message: firstLines(commit.stderr) || firstLines(commit.stdout.toString("utf8")) || "git commit に失敗しました",
138
+ };
139
+ }
140
+ const head = git(["rev-parse", "HEAD"]);
141
+ return { kind: "committed", sha: head.stdout.toString("utf8").trim(), files: targets };
142
+ }
143
+ /**
144
+ * 今の HEAD のコミット。コミットがまだ無いリポジトリでは null、git が無い・リポジトリでなければ undefined。
145
+ * 適用のときに manifest に残し、次の適用の前のコミットで「その間に利用者がコミットしたか」を見分ける
146
+ */
147
+ export function gitHeadCommit(rootDir) {
148
+ const run = (args) => spawnSync("git", [...GIT_READ_ONLY_ARGS, ...args], { cwd: rootDir, env: gitEnv(), windowsHide: true, timeout: 60_000 });
149
+ const inside = run(["rev-parse", "--is-inside-work-tree"]);
150
+ if (inside.error !== undefined || inside.status !== 0 || inside.stdout.toString("utf8").trim() !== "true")
151
+ return undefined;
152
+ const head = run(["rev-parse", "--verify", "-q", "HEAD"]);
153
+ if (head.error !== undefined)
154
+ return undefined;
155
+ return head.status === 0 ? head.stdout.toString("utf8").trim() : null;
156
+ }
@@ -90,6 +90,39 @@ export function markUndone(root, id, at) {
90
90
  manifest.undoneAt = at.toISOString();
91
91
  writeFileSync(p, JSON.stringify(manifest, null, 2) + "\n", "utf8");
92
92
  }
93
+ /** tazuna がこの適用の分をコミットしたことを manifest に記録する (undo と次のコミットの対象から外すため) */
94
+ export function markCommitted(root, id, sha, at) {
95
+ const p = join(historyRoot(root), id, "manifest.json");
96
+ const manifest = JSON.parse(readFileSync(p, "utf8"));
97
+ manifest.committed = { sha, at: at.toISOString() };
98
+ writeFileSync(p, JSON.stringify(manifest, null, 2) + "\n", "utf8");
99
+ }
100
+ /**
101
+ * まだコミットしていない直近の適用。巻き戻していない直近の履歴がコミット済みなら null
102
+ * (それより前には戻らない。前の分は、その次の適用の前にコミットしたか、利用者に任せたもの)。
103
+ * manifest は非信頼入力なので、読めない・形が違う履歴に当たったら null (推測でコミットしない)
104
+ */
105
+ export function findUncommittedApply(root) {
106
+ for (const id of listHistoryIds(root).reverse()) {
107
+ let manifest;
108
+ try {
109
+ manifest = readManifest(root, id);
110
+ }
111
+ catch {
112
+ return null;
113
+ }
114
+ if (manifest === null || typeof manifest !== "object" || !Array.isArray(manifest.files))
115
+ return null;
116
+ if (manifest.undoneAt !== undefined)
117
+ continue;
118
+ if (manifest.committed !== undefined)
119
+ return null;
120
+ if (!manifest.files.some((f) => f?.applied === true))
121
+ continue;
122
+ return { id, manifest };
123
+ }
124
+ return null;
125
+ }
93
126
  /**
94
127
  * 同じ指紋の changes.md を適用した履歴 (巻き戻し済み・書き込みなしを除く) を新しい順に
95
128
  * 探し、最初に見つかった履歴 ID を返す。指紋を持たない旧形式の manifest は、保存済みの
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tazuna",
3
- "version": "0.22.0",
3
+ "version": "0.23.0",
4
4
  "description": "Build with AI chat, without handing over the reins: pack your codebase for the chat, then verify and apply its patches locally (zero dependencies; formerly petari and slnmix)",
5
5
  "keywords": [
6
6
  "cli",
@@ -37,18 +37,17 @@
37
37
  "engines": {
38
38
  "node": ">=20.19.0"
39
39
  },
40
+ "devDependencies": {
41
+ "@types/node": "^24.3.0",
42
+ "typescript": "^5.9.2",
43
+ "vitest": "^3.2.4"
44
+ },
40
45
  "scripts": {
41
46
  "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
42
47
  "typecheck": "tsc --noEmit",
43
48
  "test": "vitest run",
44
49
  "test:watch": "vitest",
45
50
  "dev": "node src/cli.ts",
46
- "prepublishOnly": "pnpm typecheck && pnpm test && pnpm build",
47
51
  "gen:sjis": "node scripts/generate-sjis-table.ts"
48
- },
49
- "devDependencies": {
50
- "@types/node": "^24.3.0",
51
- "typescript": "^5.9.2",
52
- "vitest": "^3.2.4"
53
52
  }
54
- }
53
+ }