Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .claude/claudeos/data/reasoning-bank.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"version": "1.0",
"description": "ClaudeOS ReasoningBank — セッション間自己学習パターンストア (Stage-1〜3)",
"entries": [
{
"id": "rb-2026-05-10T02-26-33-v488",
"timestamp": "2026-05-10T02:26:33.877Z",
"project": "ClaudeCode-StartUpTools-New",
"phase": "Improve",
"problem_pattern": "修正 (v3.2.80→v3.2.89) + Watch-ClaudeLog.ps1 FilterLine 名前付き関数化",
"approach": "v3.2.89 (PR #251) merge 完了。README バージョンドリフト修正 (v3.2.80→v3.2.89) + Watch-ClaudeLog.ps1 FilterLine 名前付き関数化 (CodeRabbit Medium対応)。CI 4/4 SUCCESS。",
"tags": [
"ci",
"pr",
"docs",
"powershell"
],
"outcome": "success",
"stable_achieved": true,
"ci_passed": true,
"consecutive_success": 5,
"confidence": 1,
"used_count": 2,
"last_used": "2026-05-10T02:35:22.623Z"
}
]
}
299 changes: 299 additions & 0 deletions .claude/claudeos/scripts/hooks/reasoning-bank.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,299 @@
#!/usr/bin/env node
// ReasoningBank — コアモジュール (ClaudeOS v8.2 / Stage-1)
//
// 役割:
// セッション終了時に「何をしたか・なぜ成功/失敗したか」を構造化して保存し、
// 将来のセッション開始時に類似問題へのヒントとして注入する。
//
// 公開 API:
// loadBank(dataDir) → bank オブジェクトを返す
// saveBank(dataDir, bank) → atomic 書き込み
// buildEntry(state, projectName) → エントリを構築(信頼スコア閾値未満は null)
// upsertEntry(bank, entry) → 追加または重複更新
// pruneBank(bank) → 低品質エントリを整理
// extractTags(text) → タグ配列を返す
// detectProblemPattern(text) → 問題パターン文字列を返す
// calcConfidence(...) → 信頼スコアを返す

"use strict";

const fs = require("fs");
const path = require("path");

// ------------------------------------------------------------------ 定数
const BANK_FILE = "reasoning-bank.json";
const MIN_CONFIDENCE = 0.15; // これ以下は prune で自動削除
const SAVE_THRESHOLD = 0.30; // buildEntry がエントリを返す最低ライン
const MAX_ENTRIES = 200; // バンク上限(超えたら低信頼を削除)
const SIMILARITY_THRESH = 0.60; // Jaccard 類似度がこれ以上なら重複と判定

// ------------------------------------------------------------------ I/O

function readJson(file) {
try { return JSON.parse(fs.readFileSync(file, "utf8")); }
catch { return null; }
}

function writeJsonAtomic(file, data) {
const tmp = `${file}.tmp.${process.pid}`;
fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + "\n", "utf8");
fs.renameSync(tmp, file);
}

function loadBank(dataDir) {
const file = path.join(dataDir, BANK_FILE);
const existing = readJson(file);
if (existing && Array.isArray(existing.entries)) return existing;
return { version: "1.0", description: "ClaudeOS ReasoningBank", entries: [] };
}

function saveBank(dataDir, bank) {
fs.mkdirSync(dataDir, { recursive: true });
writeJsonAtomic(path.join(dataDir, BANK_FILE), bank);
}

// ------------------------------------------------------------------ タグ抽出

// [正規表現, タグ名] のペア。テキストに含まれるキーワードからタグを生成する。
const TAG_PATTERNS = [
[/\b(typescript|\.tsx?\b)/i, "typescript"],
[/\b(javascript|\.jsx?\b)/i, "javascript"],
[/\b(python|\.py\b)/i, "python"],
[/\b(rust|\.rs\b)/i, "rust"],
[/\b(go|golang)\b/i, "golang"],
[/\b(lint|eslint|prettier|biome)\b/i, "lint"],
[/\b(test|jest|vitest|pytest|spec)\b/i, "test"],
[/\b(build|webpack|vite|tsc|rollup)\b/i, "build"],
[/\b(ci|github.actions|workflow|pipeline)\b/i, "ci"],
[/\b(security|cve|脆弱性|vuln)\b/i, "security"],
[/\b(merge|pr|pull.request|プルリク)\b/i, "pr"],
[/\b(refactor|リファクタリング)\b/i, "refactor"],
[/\b(readme|docs|ドキュメント|document)\b/i, "docs"],
[/\b(docker|container|コンテナ)\b/i, "docker"],
[/\b(database|db|sql|postgres|mysql)\b/i, "database"],
[/\b(auth|authentication|認証|authorization)\b/i, "auth"],
[/\b(fix|修正|バグ|bug|error|エラー)\b/i, "bugfix"],
[/\b(stable|stab|STABLE)\b/, "stable"],
[/\b(cron|schedule|スケジュール)\b/i, "cron"],
[/\b(hook|フック)\b/i, "hook"],
[/\b(powershell|\.ps1\b)/i, "powershell"],
[/\b(shell|bash|\.sh\b)/i, "shell"],
[/\b(version|バージョン|drift|dri)/i, "version"],
[/\b(deploy|デプロイ|release|リリース)\b/i, "deploy"],
[/\b(memory|メモリ|context|コンテキスト)\b/i, "memory"],
];
Comment on lines +58 to +84

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Verify regex patterns are simple keyword matches without complex backtracking

# Check for potentially dangerous regex constructs
echo "Checking TAG_PATTERNS for nested quantifiers or excessive backtracking..."
rg -n "TAG_PATTERNS" .claude/claudeos/scripts/hooks/reasoning-bank.js -A30 | grep -E "(\*\+|\+\*|\{\d+,\}[\*\+])"

Repository: Kensan196948G/ClaudeCode-StartUpTools-New

Length of output: 159


🏁 Script executed:

cat -n .claude/claudeos/scripts/hooks/reasoning-bank.js | head -100

Repository: Kensan196948G/ClaudeCode-StartUpTools-New

Length of output: 4465


🏁 Script executed:

# Count the exact number of patterns in TAG_PATTERNS
rg "TAG_PATTERNS\s*=\s*\[" .claude/claudeos/scripts/hooks/reasoning-bank.js -A 100 | grep -c "\[/"

Repository: Kensan196948G/ClaudeCode-StartUpTools-New

Length of output: 88


🏁 Script executed:

# Search for any security policy or coding guidelines documents
fd -type f \( -name "SECURITY*" -o -name "GUIDELINES*" -o -name "POLICY*" -o -name "*.md" \) | head -20

Repository: Kensan196948G/ClaudeCode-StartUpTools-New

Length of output: 256


🏁 Script executed:

# Check for any mentions of "security-reviewer" or regex security requirements
rg "security-reviewer|AI-generated.*regex" --type md

Repository: Kensan196948G/ClaudeCode-StartUpTools-New

Length of output: 2139


正規表現配列は正式なセキュリティレビューが必要(ポリシー準拠)

TAG_PATTERNS に 25 個の正規表現パターンが含まれています。CLAUDE.md に記載されたコーディングガイドラインに従い、AI生成の正規表現は security-reviewer または人間によるレビューが必須です。パターンは全て単純なキーワードマッチ(\b による単語境界マッチングのみ)であり、危険な構造(ネストされた量指定子や過度なバックトラックなど)は確認されませんが、ポリシー上の形式的なレビューを実施してください。

🤖 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 @.claude/claudeos/scripts/hooks/reasoning-bank.js around lines 58 - 84, The
TAG_PATTERNS array of 25 regexes must be formally flagged for a security review
per policy: open a review ticket and add an in-file comment and metadata next to
the TAG_PATTERNS definition indicating "REQUIRES_SECURITY_REVIEW" and list the
review owner (e.g., security-reviewer), then have a human security reviewer
validate each pattern for catastrophic backtracking/unsafe constructs and
confirm they are safe or provide sanitized replacements; update the file to
include the reviewer sign-off (reviewer name + timestamp) and, if any pattern is
unsafe, replace it with a validated safer regex or a literal string match and
rerun tests.


function extractTags(text) {
if (!text) return [];
const tags = new Set();
for (const [re, tag] of TAG_PATTERNS) {
if (re.test(text)) tags.add(tag);
}
return [...tags];
}

// ------------------------------------------------------------------ 問題パターン検出

// よく使われる問題記述パターンを前から順に試みる。
const PROBLEM_MARKERS = [
/([^。\n]{5,60})(エラー|失敗|error|fail|broken)/i,
/(fix|修正|修復)[:: ]+([^。\n]{5,60})/i,
/(issue|問題|不具合)[:: ]+([^。\n]{5,60})/i,
/(対応|解消|解決)[:: ]+([^。\n]{5,60})/i,
];
Comment on lines +98 to +103

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

正規表現配列のセキュリティレビューが必要

PROBLEM_MARKERS に 4 個の問題検出用正規表現が含まれています。日本語と英語の混在テキストを扱うため、コーディングガイドラインに従った security-reviewer のレビューが必要です。

As per coding guidelines: "Prohibit AI-generated SQL, regex, authorization conditions, and file operations without security-reviewer or human review"

🤖 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 @.claude/claudeos/scripts/hooks/reasoning-bank.js around lines 98 - 103, The
PROBLEM_MARKERS array contains four regex patterns (the array named
PROBLEM_MARKERS and the individual patterns matching error/fail, fix/修正,
issue/問題, 対応/解消) which fall under the repository rule requiring a
security-reviewer sign-off for AI-generated or sensitive regex; mark this change
as requiring review by adding a clear TODO/comment and metadata that requests
"security-reviewer" approval, or move these patterns behind a gated change
request, and do not merge until a security-reviewer/human reviews and approves
the four patterns; ensure the review note references PROBLEM_MARKERS and each
pattern so the reviewer can validate correctness and potential security risks.


// 途中で切れた括弧・記号を末尾から取り除いて返す
function trimIncomplete(s) {
return s.replace(/[\s((【「『〔\[{、,,]+$/, "").trim();
}

function detectProblemPattern(text) {
if (!text) return "";
for (const re of PROBLEM_MARKERS) {
const m = text.match(re);
if (m) return trimIncomplete(m[0].slice(0, 100));
}
// フォールバック: 先頭 100 文字を正規化して返す
return trimIncomplete(text.slice(0, 100).replace(/\s+/g, " "));
}

// ------------------------------------------------------------------ 信頼スコア計算

function calcConfidence(stableAchieved, ciPassed, consecutiveSuccess) {
let score = 0.20; // ベーススコア
if (stableAchieved) score += 0.40; // STABLE 達成で大幅加算
if (ciPassed) score += 0.25; // CI 通過
if ((consecutiveSuccess || 0) >= 3) score += 0.10; // 連続成功 3+ で加算
if ((consecutiveSuccess || 0) >= 5) score += 0.05; // 連続成功 5+ でさらに加算
return Math.min(1.0, Math.round(score * 100) / 100);
}

// ------------------------------------------------------------------ エントリ構築

function buildEntry(state, projectName) {
if (!state) return null;

const exec = state.execution || {};
const stab = state.stable || {};
const dbg = state.debug || {};
const summary = exec.last_session_summary || "";

// CI 合否は debug.last_failure_category が "none" または空で判定
const failCat = (dbg.last_failure_category || "").toLowerCase();
const ciPassed = (failCat === "none" || failCat === "");

const confidence = calcConfidence(
!!stab.stable_achieved,
ciPassed,
stab.consecutive_success
);

// 閾値未満は保存しない(部分失敗ノイズを排除)
if (confidence < SAVE_THRESHOLD) return null;
if (!summary) return null;

const now = new Date().toISOString();
const uid = `${now.slice(0, 19).replace(/[:.]/g, "-")}-${Math.random().toString(36).slice(2, 6)}`;

return {
id: `rb-${uid}`,
timestamp: now,
project: projectName || "unknown",
phase: exec.phase || "unknown",
problem_pattern: detectProblemPattern(summary),
approach: summary.slice(0, 250),
tags: extractTags(summary),
outcome: stab.stable_achieved ? "success" : "partial",
stable_achieved: !!stab.stable_achieved,
ci_passed: ciPassed,
consecutive_success: stab.consecutive_success || 0,
confidence,
used_count: 0,
last_used: now,
};
}

// ------------------------------------------------------------------ 重複排除 (Jaccard 類似度)

function jaccardSimilarity(a, b) {
const wa = new Set((a || "").toLowerCase().split(/[\s。、,./\-_]+/).filter(Boolean));
const wb = new Set((b || "").toLowerCase().split(/[\s。、,./\-_]+/).filter(Boolean));
const inter = [...wa].filter(w => wb.has(w)).length;
const union = new Set([...wa, ...wb]).size;
return union === 0 ? 0 : inter / union;
}

function isSimilar(existing, incoming) {
if (existing.project !== incoming.project) return false;
if (existing.phase !== incoming.phase) return false;
// 同一日以外は別エントリ扱い(違う日の同パターンも記録する)
if ((existing.timestamp || "").slice(0, 10) !== (incoming.timestamp || "").slice(0, 10)) return false;
return jaccardSimilarity(existing.problem_pattern, incoming.problem_pattern) >= SIMILARITY_THRESH;
}

function upsertEntry(bank, entry) {
const dup = bank.entries.find(e => isSimilar(e, entry));
if (dup) {
// 既存エントリの信頼スコアをより高い方に更新
dup.confidence = Math.min(1.0, Math.max(dup.confidence, entry.confidence));
dup.last_used = entry.timestamp;
dup.used_count = (dup.used_count || 0) + 1;
dup.approach = entry.approach; // 最新のアプローチで上書き
return bank;
}
bank.entries.push(entry);
return bank;
}

// ------------------------------------------------------------------ バンク整理

function pruneBank(bank) {
bank.entries = bank.entries
.filter(e => (e.confidence || 0) >= MIN_CONFIDENCE)
.sort((a, b) => (b.confidence || 0) - (a.confidence || 0))
.slice(0, MAX_ENTRIES);
return bank;
}

// ------------------------------------------------------------------ Stage 2: SONA 重み更新(時間減衰 + アウトカムデルタ)

// セッション終了時に呼び出す。
// - 同プロジェクトの既存エントリに時間減衰を適用する(1日あたり 2% 減衰)。
// - 今セッションのタグと重なるエントリには成功/失敗デルタも加算する。
// - 当日作成の新規エントリはスキップ(buildEntry で設定済みのため二重更新を防ぐ)。
function updateSONAWeights(bank, currentProject, currentTags, outcomeSuccess) {
const now = Date.now();
const today = new Date().toISOString().slice(0, 10);

bank.entries = bank.entries.map(entry => {
// 今日作成したエントリはスキップ
if ((entry.timestamp || "").slice(0, 10) === today) return entry;
// 別プロジェクトは減衰のみ(デルタなし)
const sameProject = entry.project === currentProject;

// 時間減衰: last_used からの経過日数で指数減衰
const refDate = entry.last_used || entry.timestamp;
const ageDays = Math.max(0, (now - Date.parse(refDate)) / 86400000);
const decayed = entry.confidence * Math.pow(0.98, ageDays);

if (!sameProject) {
// 別プロジェクトは減衰のみ
const updated = Math.max(MIN_CONFIDENCE, Math.round(decayed * 100) / 100);
return { ...entry, confidence: updated };
}

// タグ重複数でデルタの適用可否を決定
const tagOverlap = (entry.tags || []).filter(t => (currentTags || []).includes(t)).length;
if (tagOverlap === 0) {
const updated = Math.max(MIN_CONFIDENCE, Math.round(decayed * 100) / 100);
return { ...entry, confidence: updated };
}

// タグ関連エントリ: 成功 +0.10、失敗 -0.10
const delta = outcomeSuccess ? +0.10 : -0.10;
const updated = Math.min(1.0, Math.max(MIN_CONFIDENCE,
Math.round((decayed + delta) * 100) / 100
));
return { ...entry, confidence: updated };
});

return bank;
}

// ------------------------------------------------------------------ Stage 3: 関連パターン検索(session-start 注入用)

const RETRIEVE_CONF_THRESHOLD = 0.40; // これ以下のエントリは注入しない

// 現在のセッションコンテキストに最も関連するパターンを上位 topN 件返す。
// スコア = entry.confidence + 同プロジェクト(+0.30) + 同フェーズ(+0.20) + タグ重複数×0.10
function retrieveRelevantPatterns(bank, projectName, phase, currentTags, topN) {
topN = topN || 3;
return bank.entries
.filter(e => (e.confidence || 0) >= RETRIEVE_CONF_THRESHOLD)
.map(e => {
let score = e.confidence;
if (e.project === projectName) score += 0.30;
if (e.phase === phase) score += 0.20;
const tagOverlap = (e.tags || []).filter(t => (currentTags || []).includes(t)).length;
score += tagOverlap * 0.10;
return { entry: e, score: Math.round(score * 100) / 100 };
})
.sort((a, b) => b.score - a.score)
.slice(0, topN)
.map(x => x.entry);
}

// ------------------------------------------------------------------ 公開 API

module.exports = {
loadBank,
saveBank,
buildEntry,
upsertEntry,
pruneBank,
updateSONAWeights,
retrieveRelevantPatterns,
extractTags,
detectProblemPattern,
calcConfidence,
};
33 changes: 33 additions & 0 deletions .claude/claudeos/scripts/hooks/session-end.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,39 @@ try {
console.error(`[SessionEnd] state update failed: ${err.message}`);
}

// ReasoningBank: セッション終了時にパターンを保存する(fail-soft)。
// state.json の atomic write が完了した直後に実行し、最新の stable / debug を参照する。
try {
const rb = require("./reasoning-bank.js");
const stateRB = readJson(STATE_FILE);
if (stateRB) {
const projectName = path.basename(process.cwd());
const dataDir = path.join(__dirname, "..", "..", "data");
const bank = rb.loadBank(dataDir);
const entry = rb.buildEntry(stateRB, projectName);
if (entry) {
// Stage 2: 既存エントリに SONA 重み更新(時間減衰 + アウトカムデルタ)を適用してから新規追加
rb.updateSONAWeights(bank, entry.project, entry.tags, entry.stable_achieved);
rb.upsertEntry(bank, entry);
rb.pruneBank(bank);
rb.saveBank(dataDir, bank);
const sonaUpdated = bank.entries.filter(e => e.id !== entry.id).length;
console.log(`[ReasoningBank] Saved: ${entry.id} conf=${entry.confidence.toFixed(2)} tags=[${entry.tags.join(",")}] | SONA updated ${sonaUpdated} existing entries`);
} else {
// 低信頼でも既存エントリの時間減衰だけは実行する
const stateRBStab = (stateRB.stable || {});
const stateRBExec = (stateRB.execution || {});
const fallbackTags = rb.extractTags(stateRBExec.last_session_summary || "");
rb.updateSONAWeights(bank, path.basename(process.cwd()), fallbackTags, !!stateRBStab.stable_achieved);
rb.pruneBank(bank);
rb.saveBank(dataDir, bank);
console.log("[ReasoningBank] Entry skipped (confidence < 0.30 or no summary) | SONA decay applied");
}
}
} catch (rbErr) {
console.error(`[ReasoningBank] ${rbErr.message}`);
}

// notify-stable を同期実行する(state.json への書き込みが完了してから)。
// 失敗しても Stop hook をブロックしない。
try {
Expand Down
Loading
Loading