petari 0.5.0 → 0.7.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 +13 -0
- package/dist/commands/apply.js +5 -4
- package/dist/commands/init.js +25 -8
- package/dist/core/applier.js +37 -7
- package/dist/core/matcher.js +1 -1
- package/dist/core/nearest.js +359 -0
- package/dist/core/report.js +111 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -48,6 +48,19 @@ petari # 返答 (changes.md) を適用
|
|
|
48
48
|
petari の更新で規約文が変わった場合は、`petari init` を再実行すると protocol.md の
|
|
49
49
|
差分を検出して更新を提案します (slnmix 側の更新は不要)。
|
|
50
50
|
|
|
51
|
+
### 適用が繰り返し失敗するとき
|
|
52
|
+
|
|
53
|
+
失敗レポート (自動でクリップボードにコピーされます) をそのまま AI に貼り返すのが
|
|
54
|
+
最短です。レポートには実ファイルの該当箇所の抜粋と、どの行がどう違うかの診断が
|
|
55
|
+
含まれるため、AI は推測ではなくコピーで SEARCH を直せます。
|
|
56
|
+
|
|
57
|
+
それでも同じ箇所が失敗を繰り返す場合は、**AI に渡したスナップショット (repomix /
|
|
58
|
+
slnmix の出力) が実ファイルとずれている**可能性が高いです。特にチャットサービスは
|
|
59
|
+
長い添付を要約・検索処理で部分的にしか読まないことがあり、AI が見えなかった箇所を
|
|
60
|
+
もっともらしく補って出力することがあります。SEARCH の空白調整や言い換えを繰り返す
|
|
61
|
+
より、スナップショットを取り直して渡し直すのが確実です (petari 側は空白・インデント・
|
|
62
|
+
文字コードの差を吸収して照合するため、それらが原因で失敗することはありません)。
|
|
63
|
+
|
|
51
64
|
### コマンド
|
|
52
65
|
|
|
53
66
|
| コマンド | 説明 |
|
package/dist/commands/apply.js
CHANGED
|
@@ -204,7 +204,7 @@ export async function applyCommand(argv) {
|
|
|
204
204
|
// 3. 失敗があれば何も書き込まずレポート (§4.1, §7)
|
|
205
205
|
if (!plan.ok && !values.partial) {
|
|
206
206
|
err(`petari: 検証に失敗しました (${plan.failures.length} 件)。何も書き込んでいません。\n`);
|
|
207
|
-
await emitReport(buildFailureReport(plan.failures));
|
|
207
|
+
await emitReport(buildFailureReport(plan.failures, { outcomes: plan.outcomes, nothingWritten: true }));
|
|
208
208
|
return 1;
|
|
209
209
|
}
|
|
210
210
|
const applicable = plan.outcomes.filter(isApplicable);
|
|
@@ -217,7 +217,7 @@ export async function applyCommand(argv) {
|
|
|
217
217
|
return 0;
|
|
218
218
|
}
|
|
219
219
|
err("petari: 適用できる変更がありません。\n");
|
|
220
|
-
await emitReport(buildFailureReport(plan.failures));
|
|
220
|
+
await emitReport(buildFailureReport(plan.failures, { outcomes: plan.outcomes, nothingWritten: true }));
|
|
221
221
|
return 1;
|
|
222
222
|
}
|
|
223
223
|
if (values["dry-run"]) {
|
|
@@ -226,7 +226,7 @@ export async function applyCommand(argv) {
|
|
|
226
226
|
printAlreadyApplied(plan.outcomes);
|
|
227
227
|
if (plan.failures.length > 0) {
|
|
228
228
|
out("");
|
|
229
|
-
await emitReport(buildFailureReport(plan.failures));
|
|
229
|
+
await emitReport(buildFailureReport(plan.failures, { outcomes: plan.outcomes, nothingWritten: true }));
|
|
230
230
|
}
|
|
231
231
|
return 0;
|
|
232
232
|
}
|
|
@@ -315,7 +315,8 @@ export async function applyCommand(argv) {
|
|
|
315
315
|
if (plan.failures.length > 0) {
|
|
316
316
|
out(`スキップした失敗 ${plan.failures.length} 件のレポート:`);
|
|
317
317
|
out("");
|
|
318
|
-
|
|
318
|
+
// --partial で成功分は書き込み済みのため nothingWritten は付けない
|
|
319
|
+
await emitReport(buildFailureReport(plan.failures, { outcomes: plan.outcomes }));
|
|
319
320
|
}
|
|
320
321
|
// 6. 自動検出 (Downloads / プロジェクト直下) 由来なら changes.md を履歴へ移動
|
|
321
322
|
// (原本は history に保存済み・§4.1)。全件適用済みで履歴を作らなかった場合は削除しない
|
package/dist/commands/init.js
CHANGED
|
@@ -63,15 +63,32 @@ export async function initCommand(argv) {
|
|
|
63
63
|
}
|
|
64
64
|
catch {
|
|
65
65
|
err(`3. ${repomixPath} を JSON として読めないためスキップします`);
|
|
66
|
-
parsed =
|
|
66
|
+
parsed = null;
|
|
67
67
|
}
|
|
68
|
-
if (parsed
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
68
|
+
if (parsed !== null) {
|
|
69
|
+
let changed = false;
|
|
70
|
+
if (parsed.output?.instructionFilePath !== undefined) {
|
|
71
|
+
out(`3. repomix.config.json は instructionFilePath 設定済みです (変更しません)`);
|
|
72
|
+
}
|
|
73
|
+
else if (await ask('3. repomix.config.json に output.instructionFilePath: "protocol.md" を追記しますか?')) {
|
|
74
|
+
parsed.output = { ...(parsed.output ?? {}), instructionFilePath: "protocol.md" };
|
|
75
|
+
changed = true;
|
|
76
|
+
}
|
|
77
|
+
// 空行を落としたスナップショットは SEARCH 不一致 (空行欠落) の定番原因 (2026-08-25 実運用事例)
|
|
78
|
+
const output = parsed.output;
|
|
79
|
+
if (output !== undefined && output.removeEmptyLines === true) {
|
|
80
|
+
if (await ask("3. repomix.config.json の output.removeEmptyLines: true は、スナップショットと実ファイルの空行がずれて SEARCH 不一致の原因になります。false に変更しますか?")) {
|
|
81
|
+
output.removeEmptyLines = false;
|
|
82
|
+
changed = true;
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
err(" removeEmptyLines: true のままでは AI の SEARCH から空行が欠けやすくなります (petari は失敗レポートの + 印で検出します)");
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
if (changed) {
|
|
89
|
+
writeFileSync(repomixPath, JSON.stringify(parsed, null, 2) + "\n", "utf8");
|
|
90
|
+
out(` 更新しました: ${repomixPath}`);
|
|
91
|
+
}
|
|
75
92
|
}
|
|
76
93
|
}
|
|
77
94
|
else if (await ask("3. repomix 連携用の repomix.config.json (最小構成) を作成しますか?")) {
|
package/dist/core/applier.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { EncodingError, decodeFile, encodeDocument, findUnencodable, makeDocument, } from "./encoding.js";
|
|
2
2
|
import { STAGE_LABEL, contentEqualsStage, findContentStage, matchBlock, } from "./matcher.js";
|
|
3
|
+
import { analyzeNearest } from "./nearest.js";
|
|
3
4
|
/** Windows の予約デバイス名 (拡張子付きも不可) */
|
|
4
5
|
const WINDOWS_RESERVED = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..+)?$/i;
|
|
5
6
|
/** §9: プロジェクトルート相対のみ。絶対パス・`..`・`~`・Windows 特殊パスを拒否 */
|
|
@@ -70,14 +71,43 @@ function planReplace(change, state, fallbackEol) {
|
|
|
70
71
|
continue;
|
|
71
72
|
}
|
|
72
73
|
}
|
|
74
|
+
if (m.reason === "ambiguous") {
|
|
75
|
+
// 位置は同一ファイル内の先行ブロック適用後の行配列に対する行番号 (通常は実ファイルと一致)
|
|
76
|
+
const positions = (m.positions ?? []).map((p) => `${p + 1}`);
|
|
77
|
+
const shown = positions.length > 5
|
|
78
|
+
? `${positions.slice(0, 5).join(", ")} 行目 他 ${positions.length - 5} 箇所`
|
|
79
|
+
: `${positions.join(", ")} 行目`;
|
|
80
|
+
failures.push({
|
|
81
|
+
path: change.path,
|
|
82
|
+
kind: "block-ambiguous",
|
|
83
|
+
message: `ブロック ${block.index}: SEARCH が ${m.count} 箇所にマッチしました (${STAGE_LABEL[m.stage]}: ${shown})。前後の行を追加して一意に特定できる範囲にしてください`,
|
|
84
|
+
block,
|
|
85
|
+
});
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
73
88
|
const checkedReplace = block.replace.some((l) => l.trim() !== "");
|
|
74
|
-
const message =
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
89
|
+
const message = `ブロック ${block.index}: SEARCH が現在のファイル内容に見つかりません` +
|
|
90
|
+
(checkedReplace
|
|
91
|
+
? " (REPLACE の内容も見つからないため、changes.md の基準スナップショットが現在のコードベースとずれている可能性があります)"
|
|
92
|
+
: "");
|
|
93
|
+
const nearest = analyzeNearest(textLines, block.search, applied.length > 0);
|
|
94
|
+
// SEARCH が全滅のときのみ REPLACE 側で近傍を推定する (本来当てたかった箇所のヒント)。
|
|
95
|
+
// fold 段のみの偶然一致をノイズとして弾くため matchCount >= 1 を要求する
|
|
96
|
+
let nearestReplace;
|
|
97
|
+
if (nearest.window === null && checkedReplace) {
|
|
98
|
+
const byReplace = analyzeNearest(textLines, block.replace, applied.length > 0, "REPLACE");
|
|
99
|
+
if (byReplace.window !== null && byReplace.window.matchCount >= 1) {
|
|
100
|
+
nearestReplace = byReplace;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
failures.push({
|
|
104
|
+
path: change.path,
|
|
105
|
+
kind: "block-not-found",
|
|
106
|
+
message,
|
|
107
|
+
block,
|
|
108
|
+
nearest,
|
|
109
|
+
...(nearestReplace !== undefined ? { nearestReplace } : {}),
|
|
110
|
+
});
|
|
81
111
|
continue;
|
|
82
112
|
}
|
|
83
113
|
const replacement = m.replacement;
|
package/dist/core/matcher.js
CHANGED
|
@@ -102,7 +102,7 @@ export function matchBlock(lines, block) {
|
|
|
102
102
|
return { ok: true, block, stage, start, end, replacement };
|
|
103
103
|
}
|
|
104
104
|
if (found.length > 1) {
|
|
105
|
-
return { ok: false, block, reason: "ambiguous", stage, count: found.length };
|
|
105
|
+
return { ok: false, block, reason: "ambiguous", stage, count: found.length, positions: found };
|
|
106
106
|
}
|
|
107
107
|
}
|
|
108
108
|
return { ok: false, block, reason: "not-found" };
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SEARCH 不一致時の近傍診断 (§7 失敗レポートの拡充)。
|
|
3
|
+
* 実ファイル内で SEARCH に最も近い領域を特定し、どの行がどう違うかを構造化して返す。
|
|
4
|
+
* I/O を持たない純粋ロジック。レポートの文字列化は renderNearest が行う。
|
|
5
|
+
*
|
|
6
|
+
* 2026-08-25 の実運用事例 (AI が失敗原因を空白/エンコーディングと誤診し 4 往復) を受けて追加。
|
|
7
|
+
* 抜粋行は verbatim で保持する — AI がそのまま次の SEARCH へコピーする前提のため、
|
|
8
|
+
* 制御文字の可視化などの加工は行わない (差分の説明は note 側に分離する)。
|
|
9
|
+
*
|
|
10
|
+
* 2026-08-25 追記 (空行欠落事例): スナップショット生成ツール側で空行が落ち、SEARCH に
|
|
11
|
+
* 空行が不足するだけで不一致になる事例が確認された。固定幅ウィンドウのスライド照合では
|
|
12
|
+
* 1 行の過不足で位置合わせ全体がずれ、別の類似箇所 (End Sub 等) を抜粋してしまうため、
|
|
13
|
+
* ギャップ (行の挿入・欠落) を許容するアラインメント (fit alignment) へ変更した。
|
|
14
|
+
* 実ファイル側にだけある行は "+" として抜粋に含め、空行なら専用の注記と修正ヒントを出す。
|
|
15
|
+
*/
|
|
16
|
+
/** 前後のコンテキストとして抜粋に含める行数 */
|
|
17
|
+
const CONTEXT_LINES = 4;
|
|
18
|
+
/** レポートに載せるウィンドウの最大行数 (巨大 SEARCH の暴走防止) */
|
|
19
|
+
const MAX_RENDER_LINES = 40;
|
|
20
|
+
/** 「存在しない行」一覧の最大表示数 */
|
|
21
|
+
const MAX_MISSING_LINES = 8;
|
|
22
|
+
/** アラインメント DP のセル数上限 (巨大ファイル × 巨大 SEARCH のメモリ暴走防止) */
|
|
23
|
+
const MAX_DP_CELLS = 20_000_000;
|
|
24
|
+
/**
|
|
25
|
+
* アラインメントのスコア。置換 (SUB) は gap 2 個 (削除+挿入) より高くする —
|
|
26
|
+
* 内容の異なる行同士でも位置が対応するなら「!」として同じ行に並べて見せたいため。
|
|
27
|
+
*/
|
|
28
|
+
const SCORE_MATCH = 6; // 前後空白無視で一致
|
|
29
|
+
const SCORE_WS = 4; // 行内空白の圧縮まで許すと一致
|
|
30
|
+
const SCORE_FOLD = 2; // 不可視文字の畳み込みまで許すと一致
|
|
31
|
+
const SCORE_SUB = -2; // 内容の異なる行同士の対応付け
|
|
32
|
+
const GAP = -3; // 片側にしかない行 1 行あたり
|
|
33
|
+
const collapseWs = (s) => s.replace(/[ \t]+/g, " ");
|
|
34
|
+
/**
|
|
35
|
+
* 目視で区別しづらい文字を通常の文字へ畳み込む。畳み込み後に一致するなら、
|
|
36
|
+
* その行の差は「見えない文字」だけに因る (レポートでコードポイントを示す価値がある)。
|
|
37
|
+
*/
|
|
38
|
+
const FOLD_RULES = [
|
|
39
|
+
[/[\u3000\u00A0]/g, " "], // 全角スペース / ノーブレークスペース
|
|
40
|
+
[/[\u200B-\u200D\uFEFF]/g, ""], // ゼロ幅文字
|
|
41
|
+
[/\u301C/g, "\uFF5E"], // 波ダッシュ ↔ 全角チルダ (Shift_JIS デコーダ差の定番)
|
|
42
|
+
];
|
|
43
|
+
const foldConfusable = (s) => FOLD_RULES.reduce((t, [re, rep]) => t.replace(re, rep), s);
|
|
44
|
+
function verdictOf(fileTrim, searchTrim) {
|
|
45
|
+
if (fileTrim === searchTrim)
|
|
46
|
+
return "match";
|
|
47
|
+
if (collapseWs(fileTrim) === collapseWs(searchTrim))
|
|
48
|
+
return "ws-only";
|
|
49
|
+
return "differ";
|
|
50
|
+
}
|
|
51
|
+
/** 最初に異なるコードポイントの位置と内容 (前後空白は無視して比較) */
|
|
52
|
+
function describeFirstDiff(fileLine, searchLine) {
|
|
53
|
+
const a = [...fileLine.trim()];
|
|
54
|
+
const b = [...searchLine.trim()];
|
|
55
|
+
let i = 0;
|
|
56
|
+
while (i < a.length && i < b.length && a[i] === b[i])
|
|
57
|
+
i++;
|
|
58
|
+
const cp = (arr, idx) => {
|
|
59
|
+
const ch = arr[idx];
|
|
60
|
+
if (ch === undefined)
|
|
61
|
+
return "行末";
|
|
62
|
+
return `U+${ch.codePointAt(0).toString(16).toUpperCase().padStart(4, "0")}`;
|
|
63
|
+
};
|
|
64
|
+
return `${i + 1} 文字目から異なります (実ファイル側: ${cp(a, i)} / SEARCH 側: ${cp(b, i)})`;
|
|
65
|
+
}
|
|
66
|
+
function noteFor(fileLine, searchLine, verdict, subject) {
|
|
67
|
+
if (verdict === "ws-only") {
|
|
68
|
+
return "行内の連続空白の個数のみが異なります (実ファイル側の行をそのままコピーしてください)";
|
|
69
|
+
}
|
|
70
|
+
if (verdict === "differ") {
|
|
71
|
+
const ft = fileLine.trim();
|
|
72
|
+
const st = searchLine.trim();
|
|
73
|
+
if (ft === "" && st !== "") {
|
|
74
|
+
return `実ファイル側のこの行は空行です。空行も 1 行として照合されるため、${subject} 側の空行の過不足を確認してください`;
|
|
75
|
+
}
|
|
76
|
+
if (st === "" && ft !== "") {
|
|
77
|
+
return `${subject} 側の対応行は空行ですが、実ファイルのこの行は空行ではありません (${subject} 側の空行の位置を確認してください)`;
|
|
78
|
+
}
|
|
79
|
+
if (collapseWs(foldConfusable(ft)) === collapseWs(foldConfusable(st))) {
|
|
80
|
+
return `見た目で区別しづらい文字の差です。${describeFirstDiff(fileLine, searchLine)}`;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* fit alignment: SEARCH 全行を実ファイルのどこかの連続領域に、行の挿入・欠落 (gap) を
|
|
87
|
+
* 許容しつつ最良スコアで対応付ける。局所アラインメントと違い SEARCH 側は必ず全行を
|
|
88
|
+
* 消費する (先頭・末尾の不一致行も「!」として抜粋に残すため)。
|
|
89
|
+
* 実ファイル側の開始位置は自由 (H[i][0] = 0)、同点なら最初 (最も上) の領域を採用。
|
|
90
|
+
*/
|
|
91
|
+
function alignSearch(fTrim, sTrimAll, fColl, sCollAll, fFold, sFoldAll) {
|
|
92
|
+
const n = fTrim.length;
|
|
93
|
+
if (n === 0 || sTrimAll.length === 0)
|
|
94
|
+
return null;
|
|
95
|
+
// セル数上限を超える場合は SEARCH 側を先頭から切り詰める (残りは unmatched 扱い)
|
|
96
|
+
const m = Math.min(sTrimAll.length, Math.max(1, Math.floor(MAX_DP_CELLS / n)));
|
|
97
|
+
const pairScore = (fi, sj) => {
|
|
98
|
+
if (fTrim[fi] === sTrimAll[sj])
|
|
99
|
+
return SCORE_MATCH;
|
|
100
|
+
if (fColl[fi] === sCollAll[sj])
|
|
101
|
+
return SCORE_WS;
|
|
102
|
+
if (fFold[fi] === sFoldAll[sj])
|
|
103
|
+
return SCORE_FOLD;
|
|
104
|
+
return SCORE_SUB;
|
|
105
|
+
};
|
|
106
|
+
// 1 = diag (pair), 2 = up (実ファイル側の挿入行), 3 = left (SEARCH 側の欠落行)
|
|
107
|
+
const dirs = new Uint8Array(n * m);
|
|
108
|
+
let prev = new Int32Array(m + 1);
|
|
109
|
+
let curr = new Int32Array(m + 1);
|
|
110
|
+
for (let j = 1; j <= m; j++)
|
|
111
|
+
prev[j] = j * GAP;
|
|
112
|
+
let bestScore = Number.NEGATIVE_INFINITY;
|
|
113
|
+
let bestI = -1;
|
|
114
|
+
for (let i = 1; i <= n; i++) {
|
|
115
|
+
curr[0] = 0;
|
|
116
|
+
for (let j = 1; j <= m; j++) {
|
|
117
|
+
const diag = prev[j - 1] + pairScore(i - 1, j - 1);
|
|
118
|
+
const up = prev[j] + GAP;
|
|
119
|
+
const left = curr[j - 1] + GAP;
|
|
120
|
+
let v = diag;
|
|
121
|
+
let d = 1;
|
|
122
|
+
if (up > v) {
|
|
123
|
+
v = up;
|
|
124
|
+
d = 2;
|
|
125
|
+
}
|
|
126
|
+
if (left > v) {
|
|
127
|
+
v = left;
|
|
128
|
+
d = 3;
|
|
129
|
+
}
|
|
130
|
+
curr[j] = v;
|
|
131
|
+
dirs[(i - 1) * m + (j - 1)] = d;
|
|
132
|
+
}
|
|
133
|
+
if (curr[m] > bestScore) {
|
|
134
|
+
bestScore = curr[m];
|
|
135
|
+
bestI = i;
|
|
136
|
+
}
|
|
137
|
+
[prev, curr] = [curr, prev];
|
|
138
|
+
}
|
|
139
|
+
if (bestI < 0)
|
|
140
|
+
return null;
|
|
141
|
+
const rev = [];
|
|
142
|
+
let i = bestI;
|
|
143
|
+
let j = m;
|
|
144
|
+
while (j > 0) {
|
|
145
|
+
if (i === 0) {
|
|
146
|
+
rev.push({ kind: "missing", searchIdx: j - 1 });
|
|
147
|
+
j--;
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
const d = dirs[(i - 1) * m + (j - 1)];
|
|
151
|
+
if (d === 1) {
|
|
152
|
+
rev.push({ kind: "pair", fileIdx: i - 1, searchIdx: j - 1 });
|
|
153
|
+
i--;
|
|
154
|
+
j--;
|
|
155
|
+
}
|
|
156
|
+
else if (d === 2) {
|
|
157
|
+
rev.push({ kind: "extra", fileIdx: i - 1 });
|
|
158
|
+
i--;
|
|
159
|
+
}
|
|
160
|
+
else {
|
|
161
|
+
rev.push({ kind: "missing", searchIdx: j - 1 });
|
|
162
|
+
j--;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return { steps: rev.reverse(), clippedSearchFrom: m };
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* SEARCH に最も近い実ファイル領域を探す。
|
|
169
|
+
* 行の対応付けはギャップ許容アラインメント (alignSearch)。1 行も (空白圧縮・不可視文字の
|
|
170
|
+
* 畳み込みでも) 一致しないときのみ window は null。
|
|
171
|
+
*/
|
|
172
|
+
export function analyzeNearest(fileLines, search, afterPriorBlocks = false, subject = "SEARCH") {
|
|
173
|
+
const fTrim = fileLines.map((l) => l.trim());
|
|
174
|
+
const sTrim = search.map((l) => l.trim());
|
|
175
|
+
const fColl = fTrim.map(collapseWs);
|
|
176
|
+
const sColl = sTrim.map(collapseWs);
|
|
177
|
+
const fFold = fTrim.map((t) => collapseWs(foldConfusable(t)));
|
|
178
|
+
const sFold = sTrim.map((t) => collapseWs(foldConfusable(t)));
|
|
179
|
+
const lineHits = [];
|
|
180
|
+
search.forEach((text, i) => {
|
|
181
|
+
const t = sTrim[i];
|
|
182
|
+
if (t === "")
|
|
183
|
+
return; // 空行はどこにでも一致するため対象外
|
|
184
|
+
let count = 0;
|
|
185
|
+
for (const f of fTrim)
|
|
186
|
+
if (f === t)
|
|
187
|
+
count++;
|
|
188
|
+
lineHits.push({ index: i + 1, text, count });
|
|
189
|
+
});
|
|
190
|
+
const aligned = alignSearch(fTrim, sTrim, fColl, sColl, fFold, sFold);
|
|
191
|
+
if (aligned === null)
|
|
192
|
+
return { lineHits, window: null, afterPriorBlocks, subject };
|
|
193
|
+
const { steps, clippedSearchFrom } = aligned;
|
|
194
|
+
// どの段の一致も 1 行も無いアラインメントは領域として無意味 (従来の null 条件を維持)
|
|
195
|
+
const anyHit = steps.some((s) => s.kind === "pair" &&
|
|
196
|
+
(fTrim[s.fileIdx] === sTrim[s.searchIdx] ||
|
|
197
|
+
fColl[s.fileIdx] === sColl[s.searchIdx] ||
|
|
198
|
+
fFold[s.fileIdx] === sFold[s.searchIdx]));
|
|
199
|
+
if (!anyHit)
|
|
200
|
+
return { lineHits, window: null, afterPriorBlocks, subject };
|
|
201
|
+
const fileIdxs = steps.flatMap((s) => (s.kind === "missing" ? [] : [s.fileIdx]));
|
|
202
|
+
const startFile = Math.min(...fileIdxs);
|
|
203
|
+
const endFile = Math.max(...fileIdxs) + 1;
|
|
204
|
+
const lines = [];
|
|
205
|
+
const unmatchedSearch = [];
|
|
206
|
+
let matchCount = 0;
|
|
207
|
+
let extraCount = 0;
|
|
208
|
+
let extraBlankCount = 0;
|
|
209
|
+
const pushContext = (from, to) => {
|
|
210
|
+
for (let i = from; i < to; i++) {
|
|
211
|
+
lines.push({ lineNo: i + 1, text: fileLines[i], verdict: null });
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
pushContext(Math.max(0, startFile - CONTEXT_LINES), startFile);
|
|
215
|
+
for (const step of steps) {
|
|
216
|
+
if (step.kind === "missing") {
|
|
217
|
+
unmatchedSearch.push({
|
|
218
|
+
index: step.searchIdx + 1,
|
|
219
|
+
text: search[step.searchIdx],
|
|
220
|
+
blank: sTrim[step.searchIdx] === "",
|
|
221
|
+
});
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
if (step.kind === "extra") {
|
|
225
|
+
extraCount++;
|
|
226
|
+
const blank = fTrim[step.fileIdx] === "";
|
|
227
|
+
if (blank)
|
|
228
|
+
extraBlankCount++;
|
|
229
|
+
const note = blank
|
|
230
|
+
? `実ファイル側にある空行です。${subject} にこの空行が欠けているため一致しませんでした (空行も 1 行として照合されます)`
|
|
231
|
+
: `${subject} に含まれていない行です。この行も含めてコピーしてください`;
|
|
232
|
+
lines.push({
|
|
233
|
+
lineNo: step.fileIdx + 1,
|
|
234
|
+
text: fileLines[step.fileIdx],
|
|
235
|
+
verdict: "extra",
|
|
236
|
+
note,
|
|
237
|
+
});
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
const verdict = verdictOf(fTrim[step.fileIdx], sTrim[step.searchIdx]);
|
|
241
|
+
if (verdict === "match")
|
|
242
|
+
matchCount++;
|
|
243
|
+
const note = noteFor(fileLines[step.fileIdx], search[step.searchIdx], verdict, subject);
|
|
244
|
+
lines.push({
|
|
245
|
+
lineNo: step.fileIdx + 1,
|
|
246
|
+
text: fileLines[step.fileIdx],
|
|
247
|
+
verdict,
|
|
248
|
+
...(note !== undefined ? { note } : {}),
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
pushContext(endFile, Math.min(fileLines.length, endFile + CONTEXT_LINES));
|
|
252
|
+
// DP セル数上限で切り詰めた SEARCH 末尾は対応なし扱い
|
|
253
|
+
for (let k = clippedSearchFrom; k < search.length; k++) {
|
|
254
|
+
unmatchedSearch.push({ index: k + 1, text: search[k], blank: sTrim[k] === "" });
|
|
255
|
+
}
|
|
256
|
+
return {
|
|
257
|
+
lineHits,
|
|
258
|
+
window: {
|
|
259
|
+
total: search.length,
|
|
260
|
+
matchCount,
|
|
261
|
+
lines,
|
|
262
|
+
extraCount,
|
|
263
|
+
extraBlankCount,
|
|
264
|
+
unmatchedSearch,
|
|
265
|
+
},
|
|
266
|
+
afterPriorBlocks,
|
|
267
|
+
subject,
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
const MARK = { match: "=", "ws-only": "~", differ: "!", extra: "+" };
|
|
271
|
+
/** 抜粋 (コードブロック + 凡例 + 行ごとの注記)。SEARCH / REPLACE 両方の診断で共用 */
|
|
272
|
+
function renderWindowBody(w, subject) {
|
|
273
|
+
const out = ["```"];
|
|
274
|
+
for (const line of w.lines.slice(0, MAX_RENDER_LINES)) {
|
|
275
|
+
const mark = line.verdict === null ? " " : MARK[line.verdict];
|
|
276
|
+
out.push(`${mark} ${String(line.lineNo).padStart(5)}│${line.text}`);
|
|
277
|
+
}
|
|
278
|
+
if (w.lines.length > MAX_RENDER_LINES) {
|
|
279
|
+
out.push(`… (以下 ${w.lines.length - MAX_RENDER_LINES} 行省略)`);
|
|
280
|
+
}
|
|
281
|
+
out.push("```", `凡例: ! = ${subject} と内容が異なる行 / ~ = 空白の個数のみ異なる行 / + = 実ファイルにあるが ${subject} にない行 / = = 一致した行 / 無印 = 前後の文脈`);
|
|
282
|
+
for (const line of w.lines) {
|
|
283
|
+
if (line.note !== undefined)
|
|
284
|
+
out.push(`- ${line.lineNo} 行目: ${line.note}`);
|
|
285
|
+
}
|
|
286
|
+
for (const u of w.unmatchedSearch) {
|
|
287
|
+
out.push(u.blank
|
|
288
|
+
? `- ${subject} ${u.index} 行目の空行に対応する行がこの領域にありません (${subject} 側の空行が余分の可能性)`
|
|
289
|
+
: `- ${subject} ${u.index} 行目 (${u.text.trim()}) に対応する行がこの領域にありません`);
|
|
290
|
+
}
|
|
291
|
+
return out;
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* 修正のヒント (near-miss 自動サジェスト)。SEARCH の全行が順序どおり実ファイルに存在し、
|
|
295
|
+
* 間に SEARCH 側に無い行が挟まっているだけなら「抜粋のコピーで一致する」と機械的に言える。
|
|
296
|
+
* 全部が空行なら空行欠落を名指しする (2026-08-25 の実運用事例の直接対策)。
|
|
297
|
+
*/
|
|
298
|
+
function buildHint(w) {
|
|
299
|
+
if (w.extraCount === 0 || w.unmatchedSearch.length > 0)
|
|
300
|
+
return [];
|
|
301
|
+
if (w.lines.some((l) => l.verdict === "differ"))
|
|
302
|
+
return [];
|
|
303
|
+
const head = w.extraBlankCount === w.extraCount
|
|
304
|
+
? `▶ 修正のヒント: SEARCH の全行はこの順で実ファイルに存在しますが、間に空行 ${w.extraCount} 行が挟まっています。空行も 1 行として照合されるため一致しませんでした。`
|
|
305
|
+
: `▶ 修正のヒント: SEARCH の全行はこの順で実ファイルに存在しますが、間に SEARCH にない行が ${w.extraCount} 行 (うち空行 ${w.extraBlankCount} 行) 挟まっています。`;
|
|
306
|
+
return [
|
|
307
|
+
"",
|
|
308
|
+
head,
|
|
309
|
+
"上の抜粋の「│」より右側を、+ の行も含めてそのままコピーした SEARCH に置き換えれば一致します。",
|
|
310
|
+
];
|
|
311
|
+
}
|
|
312
|
+
/** 失敗レポートに埋め込む診断テキスト。抜粋行は「│」の右側が実ファイルの verbatim */
|
|
313
|
+
export function renderNearest(a) {
|
|
314
|
+
const out = ["#### 参考: 実ファイルの該当箇所 (petari が現在のファイル内容から自動抽出)"];
|
|
315
|
+
if (a.afterPriorBlocks) {
|
|
316
|
+
out.push("(同一ファイル内の先行ブロックを適用した後の想定内容です。SEARCH はこの内容に一致させてください)");
|
|
317
|
+
}
|
|
318
|
+
out.push("");
|
|
319
|
+
const missing = a.lineHits.filter((h) => h.count === 0);
|
|
320
|
+
if (missing.length > 0) {
|
|
321
|
+
out.push("SEARCH のうち実ファイルに存在しない行 (前後の空白は無視して照合):");
|
|
322
|
+
for (const h of missing.slice(0, MAX_MISSING_LINES)) {
|
|
323
|
+
out.push(`- SEARCH ${h.index} 行目: ${h.text.trim()}`);
|
|
324
|
+
}
|
|
325
|
+
if (missing.length > MAX_MISSING_LINES) {
|
|
326
|
+
out.push(`- …他 ${missing.length - MAX_MISSING_LINES} 行`);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
else if (a.window !== null) {
|
|
330
|
+
out.push("SEARCH の各行は実ファイル内に個別には存在しますが、この並びでは連続していません。");
|
|
331
|
+
}
|
|
332
|
+
if (a.window === null) {
|
|
333
|
+
out.push("", "SEARCH のどの行も (前後の空白を無視しても) 現在のファイルに見つかりません。", "changes.md の基準にしたスナップショット (repomix 等) が古いか、チャット側の要約・", "検索処理により実在しないコードを参照している可能性があります。推測で SEARCH を", "書き換えず、最新のファイル内容の共有を受けてから作り直してください。");
|
|
334
|
+
return out;
|
|
335
|
+
}
|
|
336
|
+
const w = a.window;
|
|
337
|
+
out.push("", `最も近い領域 (SEARCH ${w.total} 行中 ${w.matchCount} 行が一致):`);
|
|
338
|
+
out.push(...renderWindowBody(w, a.subject));
|
|
339
|
+
out.push(...buildHint(w));
|
|
340
|
+
return out;
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* SEARCH がどの行も見つからなかったときの補助診断: REPLACE 側の内容に近い実ファイル領域。
|
|
344
|
+
* 「本来変更を当てたかった箇所」の推定と、変更が既に別の形で入っている可能性の提示に使う。
|
|
345
|
+
*/
|
|
346
|
+
export function renderNearestReplace(a) {
|
|
347
|
+
if (a.window === null)
|
|
348
|
+
return [];
|
|
349
|
+
const w = a.window;
|
|
350
|
+
return [
|
|
351
|
+
"#### 参考: REPLACE 側の内容に近い実ファイル領域",
|
|
352
|
+
"(SEARCH はどの行も見つかりませんでしたが、REPLACE の内容に近い箇所が実ファイルにあります。",
|
|
353
|
+
"この変更が既に別の形で適用されているか、SEARCH の基準にしたスナップショットが古い可能性が",
|
|
354
|
+
"あります。変更がまだ必要な場合は、以下の抜粋を現在の内容として SEARCH を作り直してください)",
|
|
355
|
+
"",
|
|
356
|
+
`最も近い領域 (REPLACE ${w.total} 行中 ${w.matchCount} 行が一致):`,
|
|
357
|
+
...renderWindowBody(w, a.subject),
|
|
358
|
+
];
|
|
359
|
+
}
|
package/dist/core/report.js
CHANGED
|
@@ -1,21 +1,126 @@
|
|
|
1
|
+
import { STAGE_LABEL } from "./matcher.js";
|
|
2
|
+
import { renderNearest, renderNearestReplace } from "./nearest.js";
|
|
3
|
+
const MATCH_SPEC_NOTE = [
|
|
4
|
+
"## petari の照合仕様 (SEARCH を修正する前に必ず読んでください)",
|
|
5
|
+
"",
|
|
6
|
+
"- petari は行末空白・インデントの深さ (タブ/スペース混在含む)・改行コード・文字コード",
|
|
7
|
+
" (UTF-8 / Shift_JIS) の違いを自動で吸収して照合しています",
|
|
8
|
+
"- ただし空行は「内容のある 1 行」として数えます。SEARCH と実ファイルで空行の位置・数が",
|
|
9
|
+
" 違うと一致しません (スナップショット生成ツールやチャット側の表示で空行が落ちる事例が",
|
|
10
|
+
" あります。抜粋では実ファイル側にだけある行を + で示します)",
|
|
11
|
+
"- したがって「SEARCH が見つかりません」は行内の空白・インデント・エンコーディングの問題では",
|
|
12
|
+
" ありません。行の文字内容か、行の構成 (空行を含む行の過不足) が現在のファイルと異なっています",
|
|
13
|
+
"- 行内空白の調整・ASCII 行だけへの縮小・別アンカーへの乗り換えでは解決しません。各失敗に",
|
|
14
|
+
" 添付した「実ファイルの該当箇所」の抜粋から、行をそのままコピーしてください",
|
|
15
|
+
];
|
|
1
16
|
const RE_REQUEST = `## 依頼
|
|
2
17
|
|
|
3
18
|
上記の失敗した各ブロックについて、SEARCH 部分を現在のファイル内容と完全に一致するよう修正し、
|
|
4
19
|
changes.md 全体を元の規約フォーマット (## CHANGES から始まる形式) で再出力してください。
|
|
20
|
+
- SEARCH の修正には「実ファイルの該当箇所」の抜粋を使い、「│」より右側を一字一句そのまま
|
|
21
|
+
コピーしてください (行頭の「! ~ = +」の記号と行番号は含めません。+ の行 (空行含む) も
|
|
22
|
+
SEARCH に含めます)
|
|
5
23
|
- SEARCH ブロックにはファイル内で一意に特定できる範囲を含めてください
|
|
6
|
-
- 失敗していないファイル・ブロックも含めた完全な changes.md
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
24
|
+
- 失敗していないファイル・ブロックも含めた完全な changes.md を出力してください
|
|
25
|
+
- 抜粋にも SEARCH に相当する行が見当たらない場合は、推測で書き換えず、その旨を報告して
|
|
26
|
+
最新のファイル内容の共有を依頼してください`;
|
|
27
|
+
/** 検証結果の一覧 (成功したブロックも含めて全て)。ファイル間の対比が診断材料になる */
|
|
28
|
+
function outcomeSummary(outcomes) {
|
|
29
|
+
const lines = ["## 検証結果の一覧 (全ファイル・全ブロック)", ""];
|
|
30
|
+
for (const o of outcomes) {
|
|
31
|
+
const c = o.change;
|
|
32
|
+
if (c.op !== "replace") {
|
|
33
|
+
const status = o.failures.length > 0
|
|
34
|
+
? `NG (${o.failures[0]?.message})`
|
|
35
|
+
: o.alreadyApplied
|
|
36
|
+
? "OK (適用済みのためスキップ)"
|
|
37
|
+
: "OK (検証通過)";
|
|
38
|
+
lines.push(`- ${c.path} (${c.op}): ${status}`);
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
const fileLevel = o.failures.find((f) => f.block === undefined);
|
|
42
|
+
if (fileLevel !== undefined) {
|
|
43
|
+
lines.push(`- ${c.path} (replace): NG (${fileLevel.message})`);
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
const okCount = o.appliedBlocks.length + o.alreadyAppliedBlocks.length;
|
|
47
|
+
lines.push(`- ${c.path} (replace): ${okCount}/${o.totalBlocks} ブロック一致`);
|
|
48
|
+
const byIndex = new Map();
|
|
49
|
+
for (const b of o.appliedBlocks) {
|
|
50
|
+
byIndex.set(b.block.index, `OK 一致 (${STAGE_LABEL[b.stage]})`);
|
|
51
|
+
}
|
|
52
|
+
for (const b of o.alreadyAppliedBlocks) {
|
|
53
|
+
byIndex.set(b.block.index, "OK 適用済み (REPLACE が既に存在)");
|
|
54
|
+
}
|
|
55
|
+
for (const f of o.failures) {
|
|
56
|
+
if (f.block === undefined)
|
|
57
|
+
continue;
|
|
58
|
+
const label = f.kind === "block-ambiguous"
|
|
59
|
+
? "NG 複数箇所に一致 (一意でない)"
|
|
60
|
+
: f.kind === "unencodable"
|
|
61
|
+
? "NG 変換できない文字を含む"
|
|
62
|
+
: "NG SEARCH 不一致 (詳細は下記)";
|
|
63
|
+
byIndex.set(f.block.index, label);
|
|
64
|
+
}
|
|
65
|
+
for (const [index, status] of [...byIndex.entries()].sort((a, b) => a[0] - b[0])) {
|
|
66
|
+
lines.push(` - ブロック ${index}: ${status}`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
lines.push(...remainingSummary(outcomes));
|
|
70
|
+
return lines;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* 「残り何ブロックを直せば全適用できるか」の構造化サマリ (§7)。
|
|
74
|
+
* all-or-nothing の設計上、あと 1 ブロックで全通しの状態を明示すると再出力の
|
|
75
|
+
* 修正ポイントが絞れる (2026-08-25 実運用フィードバック)。
|
|
76
|
+
*/
|
|
77
|
+
function remainingSummary(outcomes) {
|
|
78
|
+
let totalUnits = 0;
|
|
79
|
+
let failedUnits = 0;
|
|
80
|
+
for (const o of outcomes) {
|
|
81
|
+
if (o.change.op === "replace" && o.totalBlocks > 0) {
|
|
82
|
+
totalUnits += o.totalBlocks;
|
|
83
|
+
const fileLevel = o.failures.some((f) => f.block === undefined);
|
|
84
|
+
failedUnits += fileLevel ? o.totalBlocks : o.failures.length;
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
totalUnits += 1;
|
|
88
|
+
if (o.failures.length > 0)
|
|
89
|
+
failedUnits += 1;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (failedUnits === 0 || failedUnits >= totalUnits)
|
|
93
|
+
return [];
|
|
94
|
+
const passed = totalUnits - failedUnits;
|
|
95
|
+
return [
|
|
11
96
|
"",
|
|
12
|
-
|
|
97
|
+
failedUnits === 1
|
|
98
|
+
? `→ 失敗は全 ${totalUnits} ブロック中この 1 ブロックだけです。この 1 ブロックの SEARCH を修正すれば全体が適用可能になります。`
|
|
99
|
+
: `→ 全 ${totalUnits} ブロック中 ${passed} ブロックは検証を通過しています。残る ${failedUnits} ブロックの SEARCH を修正すれば全体が適用可能になります。`,
|
|
13
100
|
];
|
|
101
|
+
}
|
|
102
|
+
/** 検証失敗 (マッチング・パス・エンコーディング) のレポート */
|
|
103
|
+
export function buildFailureReport(failures, ctx = {}) {
|
|
104
|
+
const parts = ["以下の変更ブロックが現在のコードベースに適用できませんでした。"];
|
|
105
|
+
if (ctx.nothingWritten === true) {
|
|
106
|
+
parts.push("", "※ この失敗により petari は何も書き込んでいません (all-or-nothing)。下の一覧で「一致」と", "表示されたブロックもまだファイルには適用されていないため、再出力には失敗していない", "ブロックもすべて含めてください。");
|
|
107
|
+
}
|
|
108
|
+
parts.push("", ...MATCH_SPEC_NOTE);
|
|
109
|
+
if (ctx.outcomes !== undefined) {
|
|
110
|
+
parts.push("", ...outcomeSummary(ctx.outcomes));
|
|
111
|
+
}
|
|
112
|
+
parts.push("", "## 適用失敗の詳細");
|
|
14
113
|
for (const f of failures) {
|
|
15
114
|
parts.push("", `### ${f.path}`, `失敗理由: ${f.message}`);
|
|
16
115
|
if (f.block !== undefined) {
|
|
17
116
|
parts.push("", "```", "<<<<<<< SEARCH", ...f.block.search, "=======", ...f.block.replace, ">>>>>>> REPLACE", "```");
|
|
18
117
|
}
|
|
118
|
+
if (f.nearest !== undefined) {
|
|
119
|
+
parts.push("", ...renderNearest(f.nearest));
|
|
120
|
+
}
|
|
121
|
+
if (f.nearestReplace !== undefined) {
|
|
122
|
+
parts.push("", ...renderNearestReplace(f.nearestReplace));
|
|
123
|
+
}
|
|
19
124
|
}
|
|
20
125
|
parts.push("", RE_REQUEST, "");
|
|
21
126
|
return parts.join("\n");
|