@the-bearded-bear/claude-craft 9.2.0-next.7d84435 → 9.2.0-next.b4098c8

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.
Files changed (102) hide show
  1. package/Dev/i18n/base/Common/hooks/scripts/block-dangerous-commands.sh +93 -48
  2. package/Dev/i18n/base/Common/hooks/scripts/guard-network.sh +58 -0
  3. package/Dev/i18n/base/Common/hooks/scripts/lib/hook-io.sh +181 -0
  4. package/Dev/i18n/base/Common/hooks/scripts/notify-slack.sh +21 -32
  5. package/Dev/i18n/base/Common/hooks/scripts/output-filter.sh +23 -0
  6. package/Dev/i18n/base/Common/hooks/scripts/output-size-hint.sh +19 -0
  7. package/Dev/i18n/base/Common/hooks/scripts/post-edit-lint.sh +29 -53
  8. package/Dev/i18n/base/Common/hooks/scripts/post-tool-failure.sh +50 -0
  9. package/Dev/i18n/base/Common/hooks/scripts/pre-commit-check.sh +59 -63
  10. package/Dev/i18n/base/Common/hooks/scripts/pre-compact.sh +52 -0
  11. package/Dev/i18n/base/Common/hooks/scripts/protect-sensitive-files.sh +16 -0
  12. package/Dev/i18n/base/Common/hooks/scripts/quality-gate.sh +49 -92
  13. package/Dev/i18n/base/Common/hooks/scripts/session-end.sh +51 -0
  14. package/Dev/i18n/base/Common/hooks/scripts/session-init.sh +45 -69
  15. package/Dev/i18n/base/Common/hooks/templates/examples/README.md +59 -0
  16. package/Dev/i18n/base/Common/hooks/templates/examples/auto-format.json +18 -0
  17. package/Dev/i18n/base/Common/hooks/templates/examples/block-dangerous-commands.json +18 -0
  18. package/Dev/i18n/base/Common/hooks/templates/examples/context-reinject.json +28 -0
  19. package/Dev/i18n/base/Common/hooks/templates/examples/output-filter.json +18 -0
  20. package/Dev/i18n/base/Common/hooks/templates/examples/pre-compact.json +18 -0
  21. package/Dev/i18n/base/Common/hooks/templates/examples/protect-files.json +18 -0
  22. package/Dev/i18n/base/Common/hooks/templates/examples/security-block.json +18 -0
  23. package/Dev/i18n/base/Common/hooks/templates/examples/stop-hook.json +16 -0
  24. package/Dev/i18n/base/Common/hooks/templates/examples/user-prompt-submit.json +16 -0
  25. package/Dev/i18n/base/Common/hooks/templates/hooks.default.json +72 -0
  26. package/Dev/i18n/base/Common/hooks/templates/{settings-hooks.json → hooks.full.json} +22 -23
  27. package/Dev/i18n/base/Common/hooks/templates/hooks.memory.json +62 -0
  28. package/Dev/i18n/base/Common/templates/settings.json.template +46 -0
  29. package/Dev/i18n/de/Common/agents/migration-specialist.md +1 -1
  30. package/Dev/i18n/de/Common/commands/ralph-run.md +3 -3
  31. package/Dev/i18n/de/Common/commands/setup-rtk.md +2 -9
  32. package/Dev/i18n/de/Common/hooks/HOOKS-QUICKSTART.md +33 -45
  33. package/Dev/i18n/de/Common/rules/12-context-management.md +5 -3
  34. package/Dev/i18n/en/Common/agents/migration-specialist.md +1 -1
  35. package/Dev/i18n/en/Common/commands/ralph-run.md +3 -3
  36. package/Dev/i18n/en/Common/commands/setup-rtk.md +2 -9
  37. package/Dev/i18n/en/Common/hooks/HOOKS-QUICKSTART.md +31 -43
  38. package/Dev/i18n/en/Common/rules/12-context-management.md +5 -3
  39. package/Dev/i18n/es/Common/agents/migration-specialist.md +1 -1
  40. package/Dev/i18n/es/Common/commands/ralph-run.md +3 -3
  41. package/Dev/i18n/es/Common/commands/setup-rtk.md +2 -9
  42. package/Dev/i18n/es/Common/hooks/HOOKS-QUICKSTART.md +33 -45
  43. package/Dev/i18n/es/Common/rules/12-context-management.md +5 -3
  44. package/Dev/i18n/fr/Common/agents/migration-specialist.md +1 -1
  45. package/Dev/i18n/fr/Common/commands/ralph-run.md +3 -3
  46. package/Dev/i18n/fr/Common/commands/setup-rtk.md +2 -9
  47. package/Dev/i18n/fr/Common/hooks/HOOKS-QUICKSTART.md +32 -44
  48. package/Dev/i18n/fr/Common/rules/12-context-management.md +5 -3
  49. package/Dev/i18n/pt/Common/agents/migration-specialist.md +1 -1
  50. package/Dev/i18n/pt/Common/commands/ralph-run.md +3 -3
  51. package/Dev/i18n/pt/Common/commands/setup-rtk.md +2 -9
  52. package/Dev/i18n/pt/Common/hooks/HOOKS-QUICKSTART.md +33 -45
  53. package/Dev/i18n/pt/Common/rules/12-context-management.md +5 -3
  54. package/Dev/scripts/install-common-rules.sh +65 -0
  55. package/Dev/scripts/lib/merge-hooks.mjs +110 -0
  56. package/Dev/scripts/memory-lifecycle/README.md +10 -9
  57. package/Dev/scripts/memory-lifecycle/_db.sh +1 -1
  58. package/Dev/scripts/memory-lifecycle/post-tool.sh +1 -1
  59. package/Dev/scripts/memory-lifecycle/pre-compact.sh +5 -5
  60. package/Dev/scripts/memory-lifecycle/prompt-submit.sh +1 -1
  61. package/Dev/scripts/memory-lifecycle/session-end.sh +1 -1
  62. package/Dev/scripts/memory-lifecycle/session-start.sh +5 -4
  63. package/README.md +2 -2
  64. package/Tools/PluginExport/export-plugin.sh +15 -17
  65. package/Tools/Ralph/README.md +17 -7
  66. package/Tools/Ralph/hooks/lib/ralph-common.sh +101 -0
  67. package/Tools/Ralph/hooks/pre-tool-context.sh +28 -0
  68. package/Tools/Ralph/hooks/session-restore.sh +94 -0
  69. package/Tools/Ralph/hooks/stop-dod-gate.sh +60 -0
  70. package/Tools/Ralph/lib/hooks-generator.sh +109 -93
  71. package/bundles/cursor/.cursorrules +2 -2
  72. package/bundles/windsurf/.windsurfrules +2 -2
  73. package/cli/index.js +1 -0
  74. package/cli/lib/doctor.js +4 -3
  75. package/cli/lib/help.js +1 -0
  76. package/cli/lib/installer.js +1 -1
  77. package/cli/lib/parse-args.js +12 -0
  78. package/package.json +2 -1
  79. package/Dev/i18n/de/Common/hooks/scripts/post-tool-failure.sh +0 -89
  80. package/Dev/i18n/de/Common/hooks/scripts/pre-compact.sh +0 -53
  81. package/Dev/i18n/de/Common/hooks/scripts/session-end.sh +0 -98
  82. package/Dev/i18n/de/Common/templates/settings.json.template +0 -128
  83. package/Dev/i18n/en/Common/hooks/scripts/post-tool-failure.sh +0 -89
  84. package/Dev/i18n/en/Common/hooks/scripts/pre-compact.sh +0 -53
  85. package/Dev/i18n/en/Common/hooks/scripts/session-end.sh +0 -98
  86. package/Dev/i18n/en/Common/templates/settings.json.template +0 -128
  87. package/Dev/i18n/es/Common/hooks/scripts/post-tool-failure.sh +0 -89
  88. package/Dev/i18n/es/Common/hooks/scripts/pre-compact.sh +0 -53
  89. package/Dev/i18n/es/Common/hooks/scripts/session-end.sh +0 -98
  90. package/Dev/i18n/es/Common/templates/settings.json.template +0 -128
  91. package/Dev/i18n/fr/Common/hooks/scripts/post-tool-failure.sh +0 -88
  92. package/Dev/i18n/fr/Common/hooks/scripts/pre-compact.sh +0 -53
  93. package/Dev/i18n/fr/Common/hooks/scripts/session-end.sh +0 -98
  94. package/Dev/i18n/fr/Common/templates/settings.json.template +0 -128
  95. package/Dev/i18n/pt/Common/hooks/scripts/post-tool-failure.sh +0 -89
  96. package/Dev/i18n/pt/Common/hooks/scripts/pre-compact.sh +0 -53
  97. package/Dev/i18n/pt/Common/hooks/scripts/session-end.sh +0 -98
  98. package/Dev/i18n/pt/Common/templates/settings.json.template +0 -128
  99. package/Tools/Ralph/.ralph/hooks/pre-tool-context.sh +0 -100
  100. package/Tools/Ralph/.ralph/hooks/session-restore.sh +0 -118
  101. package/Tools/Ralph/.ralph/hooks/status-injector.sh +0 -147
  102. package/Tools/Ralph/.ralph/hooks/stop-dod-gate.sh +0 -137
@@ -1,56 +1,101 @@
1
- #!/bin/bash
2
- # PreToolUse hook: Block dangerous shell commands
3
- # Exit code 2 = block the command
4
- set -e
1
+ #!/usr/bin/env bash
2
+ # PreToolUse(Bash) : bloque les commandes système destructrices.
3
+ # - rm récursif + forcé : BLOCK_RM_RF=dangerous (défaut) ne bloque que les cibles
4
+ # critiques (/, ~, $HOME, ., .., *, dossiers système) ; BLOCK_RM_RF=all bloque tout
5
+ # rm -rf (utilisé par le dépôt claude-craft lui-même)
6
+ # - mkfs, dd of=/dev/<disque>, redirection vers un disque, fork bomb
7
+ # - sudo / su / doas, chmod 777, chown -R /
8
+ # - lecture de secrets (cat/less/head/… sur .env, clés, credentials)
9
+ # Les commandes ne sont reconnues qu'en position de commande (début de segment, après
10
+ # sudo/xargs/env/VAR=…, ou find -exec) et les corps de heredoc sont ignorés : `docker run
11
+ # --rm … chown -R`, `grep -r mkfs`, un message de commit ou `2>/dev/null` ne déclenchent rien.
12
+ set -u
13
+ # shellcheck source=lib/hook-io.sh
14
+ . "$(dirname "${BASH_SOURCE[0]}")/lib/hook-io.sh"
5
15
 
6
- # Read JSON input from stdin
7
- INPUT=$(cat)
8
- COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
16
+ hook_require_parser
17
+ hook_input
18
+ CMD=$(hook_get tool_input.command)
19
+ [ -n "$CMD" ] || exit 0
9
20
 
10
- # Dangerous patterns to block (regex)
11
- DANGEROUS_PATTERNS=(
12
- # rm with -r and -f combined in one flag (rm -rf, rm -fr, rm -rfi, etc.)
13
- "rm\s+(-[a-zA-Z]*r[a-zA-Z]*f|-[a-zA-Z]*f[a-zA-Z]*r)\s+/"
14
- "rm\s+(-[a-zA-Z]*r[a-zA-Z]*f|-[a-zA-Z]*f[a-zA-Z]*r)\s+~"
15
- # rm with -r and -f as separate flags in any order (rm -r -f /, rm -f -r /)
16
- "rm\s+-[a-zA-Z]*r[a-zA-Z]*\s+.*-[a-zA-Z]*f[a-zA-Z]*\s+/"
17
- "rm\s+-[a-zA-Z]*f[a-zA-Z]*\s+.*-[a-zA-Z]*r[a-zA-Z]*\s+/"
18
- "rm\s+-[a-zA-Z]*r[a-zA-Z]*\s+.*-[a-zA-Z]*f[a-zA-Z]*\s+~"
19
- "rm\s+-[a-zA-Z]*f[a-zA-Z]*\s+.*-[a-zA-Z]*r[a-zA-Z]*\s+~"
20
- "rm\s+-rf\s+/\*"
21
- "dd\s+if=/dev/zero"
22
- "mkfs"
23
- "chmod\s+-R\s+777\s+/"
24
- "chown\s+-R"
25
- ">\s*/dev/sda"
26
- "mv\s+/\*\s+/dev/null"
27
- )
21
+ MODE=${BLOCK_RM_RF:-dangerous}
22
+ TEXT=$(printf '%s\n' "$CMD" | hook_strip_heredocs | hook_shell_segments)
28
23
 
29
- # Check for fork bomb (fixed string, contains regex special chars)
30
- if echo "$COMMAND" | grep -qF ':(){:|:&};:'; then
31
- echo "BLOCKED: Dangerous command detected: fork bomb" >&2
32
- exit 2
24
+ # Fork bomb `f(){ f|f& }` (f = `:` ou un nom) sur le texte non découpé : texte cité-donnée
25
+ # masqué, texte cité-code (sh -c '…', eval "…") conservé.
26
+ FLAT=$(printf '%s\n' "$CMD" | hook_strip_heredocs | hook_shell_segments flat)
27
+ # (awk plutôt qu'une rétro-référence ERE, absente de grep -E sous busybox/musl)
28
+ if printf '%s\n' "$FLAT" | awk '
29
+ {
30
+ s = $0
31
+ while (match(s, /[A-Za-z_:][A-Za-z0-9_:]*[[:space:]]*\([[:space:]]*\)[[:space:]]*\{/)) {
32
+ name = substr(s, RSTART, RLENGTH); sub(/[[:space:]]*\(.*/, "", name)
33
+ s = substr(s, RSTART + RLENGTH); body = s; sub(/\}.*/, "", body); gsub(/[[:space:]]/, "", body)
34
+ if (index(body, name "|" name)) found = 1
35
+ }
36
+ }
37
+ END { exit !found }'; then
38
+ hook_block "Fork bomb detected"
33
39
  fi
34
-
35
- # Check for dangerous patterns (regex)
36
- for pattern in "${DANGEROUS_PATTERNS[@]}"; do
37
- if echo "$COMMAND" | grep -qE "$pattern"; then
38
- echo "BLOCKED: Dangerous command detected: $pattern" >&2
39
- exit 2
40
- fi
41
- done
42
-
43
- # Check for commands that modify system files
44
- if echo "$COMMAND" | grep -qE "^(sudo|su)\s"; then
45
- echo "BLOCKED: Elevated privilege commands not allowed" >&2
46
- exit 2
40
+ if printf '%s' "$TEXT" | grep -qE '>[[:space:]]*/dev/(sd|hd|nvme|mmcblk|disk|xvd|vd)'; then
41
+ hook_block "Writing to a block device is not allowed"
47
42
  fi
48
43
 
49
- # Check for commands that could expose secrets
50
- if echo "$COMMAND" | grep -qE "(cat|less|head|tail|more|strings)\s.*\.(env|credentials|secret|pem|key)\b"; then
51
- echo "BLOCKED: Command might expose secrets" >&2
52
- exit 2
53
- fi
44
+ # Un segment par ligne (hook_shell_segments) ; chacun est analysé à partir de son premier mot.
45
+ verdicts=$(printf '%s\n' "$TEXT" | awk -v mode="$MODE" '
46
+ function base(t) { sub(/.*\//, "", t); return t }
47
+ function dangerous(a) {
48
+ while (length(a) > 1 && substr(a, length(a)) == "/") a = substr(a, 1, length(a) - 1)
49
+ return a ~ /^(\/|\/\*|~|\$HOME|\.|\.\.|\*)$/ || a ~ /^\/(etc|usr|var|bin|boot|home|lib|opt|root|srv|sbin)$/
50
+ }
51
+ function check_rm(from, j, a, r, f, hit, eod) {
52
+ for (j = from; j <= nt; j++) {
53
+ a = t[j]
54
+ if (!eod && a == "--") { eod = 1; continue }
55
+ if (!eod && a ~ /^-/) {
56
+ if (a == "--recursive" || a ~ /^-[a-zA-Z]*[rR]/) r = 1
57
+ if (a == "--force" || a ~ /^-[a-zA-Z]*f/) f = 1
58
+ continue
59
+ }
60
+ if (dangerous(a)) hit = 1
61
+ }
62
+ if (r && f && (mode == "all" || hit)) { print "BLOCK Destructive rm command detected (recursive+force)"; exit }
63
+ }
64
+ {
65
+ nt = split(substr($0, index($0, "\t") + 1), t); i = 1; pre = 0
66
+ while (i <= nt) {
67
+ if (t[i] ~ /^(env|nohup|command|exec|eval|time|nice|xargs)$/) { pre = 1; i++; continue }
68
+ if (pre && t[i] ~ /^-/) { i++; continue }
69
+ if (t[i] ~ /^[A-Za-z_][A-Za-z0-9_]*=/) { i++; continue }
70
+ if (base(t[i]) ~ /^(sh|bash|zsh|dash|ksh)$/ && i < nt && t[i + 1] ~ /^-[a-z]*c$/) { i += 2; pre = 0; continue }
71
+ break
72
+ }
73
+ for (j = 1; j < nt; j++) if (t[j] ~ /^-exec(dir)?$/ && base(t[j + 1]) == "rm") check_rm(j + 2)
74
+ if (i > nt) next
75
+ cmd = base(t[i])
76
+ if (cmd ~ /^(sudo|su|doas)$/) { print "BLOCK Elevated privilege commands are not allowed"; exit }
77
+ if (cmd ~ /^mkfs/) { print "BLOCK mkfs is not allowed"; exit }
78
+ if (cmd == "rm") check_rm(i + 1)
79
+ if (cmd == "dd") for (j = i + 1; j <= nt; j++) if (t[j] ~ /^of=\/dev\/(sd|hd|nvme|mmcblk|disk|xvd|vd)/) { print "BLOCK dd to a block device is not allowed"; exit }
80
+ if (cmd == "chmod") for (j = i + 1; j <= nt; j++) if (t[j] ~ /^0?777$/) { print "BLOCK chmod 777 is not allowed"; exit }
81
+ if (cmd == "chown") {
82
+ rec = 0; root = 0
83
+ for (j = i + 1; j <= nt; j++) { if (t[j] ~ /^-[a-zA-Z]*R/ || t[j] == "--recursive") rec = 1; if (t[j] == "/") root = 1 }
84
+ if (rec && root) { print "BLOCK chown -R / is not allowed"; exit }
85
+ }
86
+ if (cmd ~ /^(cat|less|more|head|tail|strings|bat)$/)
87
+ for (j = i + 1; j <= nt; j++) if (t[j] !~ /^-/) print "READ " t[j]
88
+ }')
54
89
 
55
- # All checks passed
90
+ while IFS= read -r line; do
91
+ case "$line" in
92
+ "BLOCK "*) hook_block "${line#BLOCK }" ;;
93
+ "READ "*)
94
+ # \037 = blanc à l'intérieur d'un nom cité (`cat "my .env"`)
95
+ f=$(printf '%s' "${line#READ }" | tr '\037' ' ')
96
+ is_sensitive_path "$f" && hook_block "Command might expose secrets ($f)" ;;
97
+ esac
98
+ done <<EOF
99
+ $verdicts
100
+ EOF
56
101
  exit 0
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env bash
2
+ # PreToolUse(Bash) : bloque l'exécution directe d'un script téléchargé.
3
+ # 1. interpréteur nourri par une substitution : bash <(curl …), sh -c "$(curl …)", eval
4
+ # 2. téléchargement suivi d'un interpréteur dans le même pipeline : curl … | [sudo] sh
5
+ # 3. interpréteur lancé sur un fichier qui vient d'être téléchargé : curl -O …/i.sh && bash i.sh
6
+ # Les commandes ne sont reconnues qu'en position de commande (après sudo/env/VAR=…),
7
+ # donc `2>/dev/null`, `grep -o`, un domaine `.pl` ou un message de commit ne comptent pas.
8
+ # Télécharger un fichier (`curl -o`) reste du ressort des permissions, pas de ce hook.
9
+ set -u
10
+ # shellcheck source=lib/hook-io.sh
11
+ . "$(dirname "${BASH_SOURCE[0]}")/lib/hook-io.sh"
12
+
13
+ hook_require_parser
14
+ hook_input
15
+ CMD=$(hook_get tool_input.command)
16
+ [ -n "$CMD" ] || exit 0
17
+
18
+ # Corps de heredoc retirés, puis un segment par ligne (hook_shell_segments) : le texte
19
+ # cité est une donnée, sauf après sh -c / eval et dans $(…) / `…`. Un segment "|"
20
+ # prolonge le pipeline courant ; un segment "(" est le contenu de la substitution
21
+ # portée (__SUB__) par le dernier segment parent.
22
+ verdict=$(printf '%s\n' "$CMD" | hook_strip_heredocs | hook_shell_segments | awk '
23
+ function base(t) { sub(/[?#].*$/, "", t); sub(/.*\//, "", t); return t }
24
+ function is_interp(c) {
25
+ return c == "." || c ~ /^(sh|bash|zsh|dash|ksh|fish|python[0-9.]*|perl|ruby|node|deno|bun|php|pwsh|source|eval)$/
26
+ }
27
+ {
28
+ sep = substr($0, 1, 1)
29
+ if (sep != "|") piped = 0
30
+ nt = split(substr($0, index($0, "\t") + 1), t); i = 1; pre = 0; first = ""; hassub = 0
31
+ for (j = 1; j <= nt; j++) if (t[j] == "__SUB__") hassub = 1
32
+ while (i <= nt) {
33
+ if (t[i] ~ /^(sudo|doas|env|nohup|command|exec|time|nice|xargs)$/) { pre = 1; i++; continue }
34
+ if (pre && t[i] ~ /^-/) { i++; continue }
35
+ if (t[i] ~ /^[A-Za-z_][A-Za-z0-9_]*=/) { i++; continue }
36
+ if (first == "") first = base(t[i])
37
+ if (base(t[i]) ~ /^(sh|bash|zsh|dash|ksh)$/ && i < nt && t[i + 1] ~ /^-[a-z]*c$/) { i += 2; pre = 0; continue }
38
+ break
39
+ }
40
+ cmd = i <= nt ? base(t[i]) : ""
41
+ if (sep == "(" && subint && (cmd == "curl" || cmd == "wget")) { print "sub"; exit }
42
+ if (hassub) subint = is_interp(first)
43
+ if (cmd == "curl" || cmd == "wget") {
44
+ piped = 1
45
+ for (j = i + 1; j <= nt; j++) if (t[j] !~ /^-/ && base(t[j]) != "") dl[base(t[j])] = 1
46
+ next
47
+ }
48
+ if (!is_interp(cmd)) next
49
+ if (piped) { print "pipe"; exit }
50
+ for (j = i + 1; j <= nt; j++) if (t[j] !~ /^-/) { if (base(t[j]) in dl) { print "file"; exit } break }
51
+ }')
52
+
53
+ case "$verdict" in
54
+ sub) hook_block "Feeding a download into an interpreter is not allowed" ;;
55
+ pipe) hook_block "Piping a download into an interpreter is not allowed" ;;
56
+ file) hook_block "Executing a freshly downloaded script is not allowed" ;;
57
+ esac
58
+ exit 0
@@ -0,0 +1,181 @@
1
+ # shellcheck shell=bash
2
+ # Bibliothèque commune des hooks Claude Code (sourcée, jamais exécutée).
3
+ #
4
+ # Contrat Claude Code : payload JSON sur stdin ; exit 2 + stderr = blocage ;
5
+ # seul hookSpecificOutput.additionalContext atteint le modèle (systemMessage = UI).
6
+ # jq est utilisé s'il est présent, sinon node (toujours là pour claude-craft).
7
+
8
+ HOOK_INPUT=""
9
+
10
+ hook_input() { HOOK_INPUT=$(cat); }
11
+
12
+ hook_has_jq() { command -v jq >/dev/null 2>&1; }
13
+
14
+ hook_has_parser() { hook_has_jq || command -v node >/dev/null 2>&1; }
15
+
16
+ # Valeur au chemin pointé (`tool_input.command`) ; objet/tableau => JSON compact.
17
+ hook_get() {
18
+ if hook_has_jq; then
19
+ printf '%s' "$HOOK_INPUT" | jq -r --arg p "$1" \
20
+ 'getpath($p | split(".")) // empty | if type == "string" then . else tojson end'
21
+ else
22
+ printf '%s' "$HOOK_INPUT" | node -e '
23
+ let s = "";
24
+ process.stdin.on("data", (d) => (s += d)).on("end", () => {
25
+ let v = JSON.parse(s || "{}");
26
+ for (const k of process.argv[1].split(".")) v = v == null ? undefined : v[k];
27
+ if (v == null || v === false) return;
28
+ process.stdout.write(typeof v === "string" ? v : JSON.stringify(v));
29
+ });' "$1"
30
+ fi
31
+ }
32
+
33
+ # hook_context <Event> <texte> : contexte additionnel visible par le modèle.
34
+ hook_context() {
35
+ if hook_has_jq; then
36
+ jq -cn --arg e "$1" --arg c "$2" '{hookSpecificOutput: {hookEventName: $e, additionalContext: $c}}'
37
+ else
38
+ node -e 'process.stdout.write(JSON.stringify({hookSpecificOutput: {hookEventName: process.argv[1], additionalContext: process.argv[2]}}) + "\n")' "$1" "$2"
39
+ fi
40
+ }
41
+
42
+ # hook_replace_bash_output <stdout> <stderr> <interrupted:true|false> : PostToolUse(Bash),
43
+ # remplace ce que voit le modèle. updatedToolOutput doit avoir la forme de la sortie de
44
+ # l'outil : pour Bash {stdout, stderr, interrupted, isImage}.
45
+ hook_replace_bash_output() {
46
+ if hook_has_jq; then
47
+ jq -cn --arg o "$1" --arg e "$2" --argjson i "$3" \
48
+ '{hookSpecificOutput: {hookEventName: "PostToolUse", updatedToolOutput: {stdout: $o, stderr: $e, interrupted: $i, isImage: false}}}'
49
+ else
50
+ node -e 'process.stdout.write(JSON.stringify({hookSpecificOutput: {hookEventName: "PostToolUse", updatedToolOutput: {stdout: process.argv[1], stderr: process.argv[2], interrupted: process.argv[3] === "true", isImage: false}}}) + "\n")' "$1" "$2" "$3"
51
+ fi
52
+ }
53
+
54
+ # hook_stop_block <raison> : Stop/SubagentStop — empêche l'arrêt (JSON sur stdout, exit 0).
55
+ hook_stop_block() {
56
+ if hook_has_jq; then
57
+ jq -cn --arg r "$1" '{decision: "block", reason: $r}'
58
+ else
59
+ node -e 'process.stdout.write(JSON.stringify({decision: "block", reason: process.argv[1]}) + "\n")' "$1"
60
+ fi
61
+ }
62
+
63
+ # hook_object <clé> <valeur> [<clé> <valeur>…] : objet JSON compact sur une ligne.
64
+ # Une valeur entière (^-?[0-9]+$) devient un nombre, le reste une chaîne échappée.
65
+ hook_object() {
66
+ if hook_has_jq; then
67
+ jq -cn '$ARGS.positional as $a | reduce range(0; $a | length; 2) as $i ({};
68
+ .[$a[$i]] = ($a[$i + 1] | if test("^-?[0-9]+$") then tonumber else . end))' --args "$@"
69
+ else
70
+ node -e '
71
+ const a = process.argv.slice(1), o = {};
72
+ for (let i = 0; i < a.length; i += 2) o[a[i]] = /^-?[0-9]+$/.test(a[i + 1]) ? Number(a[i + 1]) : a[i + 1];
73
+ process.stdout.write(JSON.stringify(o) + "\n");' "$@"
74
+ fi
75
+ }
76
+
77
+ hook_block() {
78
+ printf 'BLOCKED: %s\n' "$1" >&2
79
+ exit 2
80
+ }
81
+
82
+ # Garde de sécurité sans parseur JSON : on bloque plutôt que de tout laisser passer.
83
+ hook_require_parser() {
84
+ hook_has_parser || hook_block "hook requires jq or node to inspect the tool input"
85
+ }
86
+
87
+ # stdin -> stdout sans le corps des heredocs (`<<EOF`, `<<-'EOF'`) : ce sont des
88
+ # données (message de commit, fichier écrit), pas des commandes à analyser.
89
+ # Les here-strings `<<<` ne sont pas concernées.
90
+ hook_strip_heredocs() {
91
+ awk '
92
+ skip { t = $0; sub(/^[\t]+/, "", t); if (t == delim) skip = 0; next }
93
+ {
94
+ print
95
+ rest = $0
96
+ while (match(rest, /<<-?[ \t]*["\047]?[A-Za-z_][A-Za-z0-9_]*/)) {
97
+ pre = substr(rest, RSTART - 1, 1); tok = substr(rest, RSTART, RLENGTH)
98
+ rest = substr(rest, RSTART + RLENGTH)
99
+ if (RSTART > 1 && pre == "<") continue
100
+ if (substr(rest, 1, 1) == "<") continue
101
+ sub(/^<<-?[ \t]*["\047]?/, "", tok); delim = tok; skip = 1
102
+ }
103
+ }'
104
+ }
105
+
106
+ # stdin (commande shell, heredocs déjà retirés) -> une ligne par segment :
107
+ # "<sep>\t<segment>" avec sep = ";" (nouvelle instruction), "|" (étage de pipe),
108
+ # "(" (contenu d'une substitution $(…), <(…), `…` ; le segment parent porte __SUB__).
109
+ # Une chaîne citée est une donnée : ses blancs et séparateurs deviennent \037 et ne
110
+ # découpent rien (`grep 'rm -rf' f`, `git commit -m "a; sudo b"`). Elle redevient du
111
+ # code après `sh|bash|… -c` ou `eval`, et dans $(…) / `…` même entre guillemets doubles.
112
+ # `hook_shell_segments flat` : une seule ligne, non découpée, où le texte cité-donnée est
113
+ # masqué (\037) et le texte cité-code conservé (motifs multi-segments : fork bomb).
114
+ hook_shell_segments() {
115
+ awk -v flat_mode="${1:-}" '
116
+ function shell(w) { sub(/.*\//, "", w); return w ~ /^(sh|bash|zsh|dash|ksh)$/ }
117
+ function code_quote( w, k) {
118
+ k = split(seg, w)
119
+ return (k >= 1 && w[k] == "eval") || (k >= 2 && w[k] ~ /^-[a-z]*c$/ && shell(w[k - 1]))
120
+ }
121
+ function emit(next_sep) { if (flat_mode != "flat") print sep "\t" seg; seg = ""; sep = next_sep }
122
+ function push(s) { st[++sp] = s }
123
+ function pop() { if (sp > 0) sp-- }
124
+ function data(ch) { seg = seg (ch ~ /[ \t\n;&|(){}<>`]/ ? "\037" : ch); flat = flat "\037" }
125
+ function open_sub(kind) { seg = seg " __SUB__ "; emit("("); push(kind) }
126
+ { src = src $0 "\n" }
127
+ END {
128
+ sep = ";"; seg = ""; sp = 0; n = length(src); prev = ""; invar = 0
129
+ for (i = 1; i <= n; i++) {
130
+ c = substr(src, i, 1); nx = substr(src, i + 1, 1); ctx = sp ? st[sp] : "top"
131
+ if (ctx == "sq") { if (c == "\047") pop(); else data(c); continue }
132
+ if (ctx == "dq") {
133
+ if (c == "\\") { data(nx); i++ }
134
+ else if (c == "\"") pop()
135
+ else if (c == "$" && nx == "(") { open_sub("sub"); i++ }
136
+ else if (c == "`") open_sub("bt")
137
+ else data(c)
138
+ continue
139
+ }
140
+ # Contextes de code : top, sub (…), bt `…`, csq / cdq (quotes après -c / eval).
141
+ if (c != "\047" && c != "\"") flat = flat c
142
+ if (c == "\\") { seg = seg nx; i++; continue }
143
+ if (c == "\047") { if (ctx == "csq") pop(); else push(code_quote() ? "csq" : "sq"); continue }
144
+ if (c == "\"") { if (ctx == "cdq") pop(); else push(code_quote() ? "cdq" : "dq"); continue }
145
+ if (c == "`") { if (ctx == "bt") { pop(); emit(";") } else open_sub("bt"); continue }
146
+ if ((c == "$" || c == "<" || c == ">") && nx == "(") { open_sub("sub"); i++; continue }
147
+ if (c == "$" && nx == "{") { seg = seg "$"; invar = 1; i++; continue }
148
+ if (c == "}" && invar) { invar = 0; continue }
149
+ if (c == "(") { emit(";"); push("sub"); continue }
150
+ if (c == ")") { if (ctx == "sub") pop(); emit(";"); continue }
151
+ if (c == "|") { if (nx == "|") { i++; emit(";") } else emit("|"); continue }
152
+ if (c == "&" && (prev == ">" || prev == "<" || nx == ">")) { seg = seg c; prev = c; continue }
153
+ if (c == "&") { if (nx == "&") i++; emit(";"); continue }
154
+ if (c == ";" || c == "\n" || c == "{" || c == "}") { emit(";"); continue }
155
+ seg = seg c; prev = c
156
+ }
157
+ emit(";")
158
+ if (flat_mode == "flat") print flat
159
+ }'
160
+ }
161
+
162
+ # Chemin sensible (secrets) ? Basename en minuscules + quelques dossiers connus.
163
+ # Les variantes d'exemple (.example, .sample, .template, .dist, .pub) sont sûres.
164
+ is_sensitive_path() {
165
+ local p b
166
+ p=$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')
167
+ b=${p##*/}
168
+ case "$b" in
169
+ *.example | *.sample | *.template | *.dist | *.defaults | *.pub) return 1 ;;
170
+ esac
171
+ case "$b" in
172
+ .env | .env.* | .envrc | .npmrc | .netrc | .pgpass | .htpasswd | kubeconfig) return 0 ;;
173
+ id_rsa | id_dsa | id_ecdsa | id_ed25519) return 0 ;;
174
+ *.pem | *.key | *.p12 | *.pfx | *.jks | *.keystore) return 0 ;;
175
+ credentials | credentials.json | secrets.yml | secrets.yaml | secrets.json | secrets.toml | secrets.env) return 0 ;;
176
+ esac
177
+ case "$p" in
178
+ */.ssh/* | */.aws/* | */.gnupg/* | */.kube/config | */.docker/config.json) return 0 ;;
179
+ esac
180
+ return 1
181
+ }
@@ -1,39 +1,28 @@
1
- #!/bin/bash
2
- # Notification hook: Send Slack notification when permission is requested
3
- # This runs on Notification event with matcher "permission_prompt"
1
+ #!/usr/bin/env bash
2
+ # Notification : envoie une notification Slack quand Claude attend l'utilisateur.
3
+ # Payload JSON lu sur stdin. Sans SLACK_WEBHOOK_URL (ou sans jq/node), ne fait rien.
4
4
  #
5
- # SETUP: Set SLACK_WEBHOOK_URL environment variable
6
- # Get webhook URL from: https://api.slack.com/apps -> Incoming Webhooks
7
- set -e
5
+ # SETUP : définir SLACK_WEBHOOK_URL (https://api.slack.com/apps -> Incoming Webhooks)
6
+ set -u
7
+ # shellcheck source=lib/hook-io.sh
8
+ . "$(dirname "${BASH_SOURCE[0]}")/lib/hook-io.sh"
8
9
 
9
- # Read JSON input from stdin
10
- INPUT=$(cat)
11
- MESSAGE=$(echo "$INPUT" | jq -r '.message // "Claude Code notification"')
12
- NOTIFICATION_TYPE=$(echo "$INPUT" | jq -r '.notification_type // "unknown"')
10
+ [ -n "${SLACK_WEBHOOK_URL:-}" ] || exit 0
11
+ hook_has_parser || exit 0
12
+ hook_input
13
+ MESSAGE=$(hook_get message)
14
+ NOTIFICATION_TYPE=$(hook_get notification_type)
13
15
 
14
- # Only proceed if webhook URL is configured
15
- if [ -z "$SLACK_WEBHOOK_URL" ]; then
16
- exit 0
17
- fi
18
-
19
- # Format message based on notification type
20
16
  case "$NOTIFICATION_TYPE" in
21
- permission_prompt)
22
- SLACK_MESSAGE=":bell: Claude Code needs your attention: $MESSAGE"
23
- ;;
24
- idle_prompt)
25
- SLACK_MESSAGE=":sleeping: Claude Code has been idle for 60+ seconds"
26
- ;;
27
- *)
28
- SLACK_MESSAGE=":robot_face: Claude Code: $MESSAGE"
29
- ;;
17
+ permission_prompt) TEXT=":bell: Claude Code needs your attention: ${MESSAGE:-permission requested}" ;;
18
+ idle_prompt) TEXT=":sleeping: Claude Code has been idle for 60+ seconds" ;;
19
+ *) TEXT=":robot_face: Claude Code: ${MESSAGE:-notification}" ;;
30
20
  esac
31
21
 
32
- # Send to Slack (safe JSON payload via jq)
33
- PAYLOAD=$(jq -n --arg text "$SLACK_MESSAGE" '{text: $text}')
34
- curl -s -X POST \
35
- -H 'Content-type: application/json' \
36
- --data "$PAYLOAD" \
37
- "$SLACK_WEBHOOK_URL" > /dev/null 2>&1 || true
38
-
22
+ if hook_has_jq; then
23
+ PAYLOAD=$(jq -cn --arg text "$TEXT" '{text: $text}')
24
+ else
25
+ PAYLOAD=$(node -e 'process.stdout.write(JSON.stringify({text: process.argv[1]}))' "$TEXT")
26
+ fi
27
+ curl -s -X POST -H 'Content-type: application/json' --data "$PAYLOAD" "$SLACK_WEBHOOK_URL" >/dev/null 2>&1 || true
39
28
  exit 0
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env bash
2
+ # PostToolUse(Bash), opt-in (voir templates/examples/output-filter.json) : une sortie
3
+ # de plus de 50 000 caractères est REMPLACÉE par ses 8 000 premiers caractères, pour
4
+ # que le modèle n'ingère jamais le blob entier. Contrairement à output-size-hint.sh
5
+ # (simple conseil), cela économise réellement du contexte.
6
+ set -u
7
+ # shellcheck source=lib/hook-io.sh
8
+ . "$(dirname "${BASH_SOURCE[0]}")/lib/hook-io.sh"
9
+
10
+ hook_has_parser || exit 0
11
+ hook_input
12
+ OUT=$(hook_get tool_response.stdout)
13
+ LEN=${#OUT}
14
+ [ "$LEN" -gt 50000 ] || exit 0
15
+
16
+ INTERRUPTED=false
17
+ [ "$(hook_get tool_response.interrupted)" != true ] || INTERRUPTED=true
18
+ HEAD=$(printf '%s' "$OUT" | head -c 8000)
19
+ hook_replace_bash_output \
20
+ "[output truncated by the output-filter hook: ${LEN} chars total, first 8000 shown. Re-run with a narrower command (grep/head/tail) to see more.]
21
+ ${HEAD}" \
22
+ "$(hook_get tool_response.stderr)" "$INTERRUPTED"
23
+ exit 0
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env bash
2
+ # PostToolUse(Bash|Grep|Glob) : sortie volumineuse => conseil de synthèse envoyé
3
+ # au modèle via additionalContext (un echo sur stdout ne lui parvient pas).
4
+ set -u
5
+ # shellcheck source=lib/hook-io.sh
6
+ . "$(dirname "${BASH_SOURCE[0]}")/lib/hook-io.sh"
7
+
8
+ hook_has_parser || exit 0
9
+ hook_input
10
+ OUT=$(hook_get tool_response.stdout)
11
+ [ -n "$OUT" ] || OUT=$(hook_get tool_response)
12
+ LEN=${#OUT}
13
+
14
+ if [ "$LEN" -gt 50000 ]; then
15
+ hook_context PostToolUse "Output very large (${LEN} chars). Summarize key findings only; do not repeat output verbatim."
16
+ elif [ "$(hook_get tool_name)" = "Bash" ] && [ "$LEN" -gt 10000 ]; then
17
+ hook_context PostToolUse "Output: $(printf '%s\n' "$OUT" | wc -l | tr -d ' ') lines. Extract only relevant information."
18
+ fi
19
+ exit 0
@@ -1,58 +1,34 @@
1
- #!/bin/bash
2
- # Post-edit hook: Auto-lint modified files
3
- # This hook runs after Write or Edit operations
4
- set -e
1
+ #!/usr/bin/env bash
2
+ # PostToolUse (Edit|Write) : formate/lint le fichier modifié selon son extension.
3
+ # Payload JSON lu sur stdin ; informatif, ne bloque jamais.
4
+ set -u
5
+ # shellcheck source=lib/hook-io.sh
6
+ . "$(dirname "${BASH_SOURCE[0]}")/lib/hook-io.sh"
5
7
 
6
- # Read JSON input from stdin
7
- INPUT=$(cat)
8
+ hook_has_parser || exit 0
9
+ hook_input
10
+ FILE_PATH=$(hook_get tool_input.file_path)
11
+ [ -n "$FILE_PATH" ] || exit 0
8
12
 
9
- # Extract the file path that was modified
10
- FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
13
+ have() { command -v "$1" >/dev/null 2>&1; }
11
14
 
12
- if [ -z "$FILE_PATH" ]; then
13
- exit 0
14
- fi
15
-
16
- # Get file extension
17
- EXT="${FILE_PATH##*.}"
18
-
19
- # Run appropriate linter based on file type
20
- case "$EXT" in
21
- js|jsx|ts|tsx)
22
- if command -v npx &> /dev/null && [ -f "package.json" ]; then
23
- npx eslint --fix "$FILE_PATH" 2>/dev/null || true
24
- fi
25
- ;;
26
- php)
27
- if command -v php-cs-fixer &> /dev/null; then
28
- php-cs-fixer fix "$FILE_PATH" --quiet 2>/dev/null || true
29
- elif command -v vendor/bin/php-cs-fixer &> /dev/null; then
30
- vendor/bin/php-cs-fixer fix "$FILE_PATH" --quiet 2>/dev/null || true
31
- fi
32
- ;;
33
- py)
34
- if command -v black &> /dev/null; then
35
- black --quiet "$FILE_PATH" 2>/dev/null || true
36
- fi
37
- if command -v isort &> /dev/null; then
38
- isort --quiet "$FILE_PATH" 2>/dev/null || true
39
- fi
40
- ;;
41
- dart)
42
- if command -v dart &> /dev/null; then
43
- dart format "$FILE_PATH" 2>/dev/null || true
44
- fi
45
- ;;
46
- go)
47
- if command -v gofmt &> /dev/null; then
48
- gofmt -w "$FILE_PATH" 2>/dev/null || true
49
- fi
50
- ;;
51
- rs)
52
- if command -v rustfmt &> /dev/null; then
53
- rustfmt "$FILE_PATH" 2>/dev/null || true
54
- fi
55
- ;;
15
+ case "${FILE_PATH##*.}" in
16
+ js | jsx | ts | tsx)
17
+ if have npx && [ -f package.json ]; then npx --no-install eslint --fix "$FILE_PATH" >/dev/null 2>&1 || true; fi
18
+ ;;
19
+ php)
20
+ if have php-cs-fixer; then
21
+ php-cs-fixer fix "$FILE_PATH" --quiet >/dev/null 2>&1 || true
22
+ elif [ -x vendor/bin/php-cs-fixer ]; then
23
+ vendor/bin/php-cs-fixer fix "$FILE_PATH" --quiet >/dev/null 2>&1 || true
24
+ fi
25
+ ;;
26
+ py)
27
+ if have black; then black --quiet "$FILE_PATH" >/dev/null 2>&1 || true; fi
28
+ if have isort; then isort --quiet "$FILE_PATH" >/dev/null 2>&1 || true; fi
29
+ ;;
30
+ dart) if have dart; then dart format "$FILE_PATH" >/dev/null 2>&1 || true; fi ;;
31
+ go) if have gofmt; then gofmt -w "$FILE_PATH" >/dev/null 2>&1 || true; fi ;;
32
+ rs) if have rustfmt; then rustfmt "$FILE_PATH" >/dev/null 2>&1 || true; fi ;;
56
33
  esac
57
-
58
34
  exit 0
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env bash
2
+ # PostToolUseFailure : journalise l'échec d'un outil et, quand une piste de
3
+ # récupération est connue, la transmet au modèle (hookSpecificOutput.additionalContext).
4
+ # Les messages ci-dessous s'adressent au modèle et aux journaux : en anglais, quelle
5
+ # que soit la langue d'installation.
6
+ set -u
7
+ # shellcheck source=lib/hook-io.sh
8
+ . "$(dirname "${BASH_SOURCE[0]}")/lib/hook-io.sh"
9
+
10
+ hook_has_parser || exit 0
11
+ hook_input
12
+ TOOL=$(hook_get tool_name)
13
+ ERROR=$(hook_get error)
14
+ CWD=$(hook_get cwd)
15
+ [ -z "$CWD" ] || cd "$CWD" 2>/dev/null || true
16
+
17
+ has() { printf '%s' "$ERROR" | grep -qiE -e "$1"; }
18
+
19
+ # Piste de récupération (vide = aucune) selon l'outil et le message d'erreur.
20
+ recovery_hint() {
21
+ case "$TOOL" in
22
+ Bash)
23
+ if has "command not found"; then printf 'Command not found. Check that it is installed, or run it in a Docker container.'
24
+ elif has "permission denied"; then printf 'Permission denied. Check file permissions instead of retrying with elevated rights.'
25
+ elif has "no such file or directory"; then printf 'File or directory not found. Check that the path exists.'
26
+ elif has "timeout|timed out"; then printf 'Command timed out. Raise the timeout or narrow the command.'
27
+ fi ;;
28
+ Edit | Write)
29
+ if has "permission denied"; then printf 'Write permission denied. Check the file permissions.'
30
+ elif has "no such file"; then printf 'The target directory may not exist. Create the parent directories first.'
31
+ elif has "not unique|multiple matches|found [0-9]+ matches"; then printf 'old_string is not unique. Provide more surrounding context.'
32
+ fi ;;
33
+ Read)
34
+ if has "no such file"; then printf 'File not found. Use Glob to locate the right path.'
35
+ elif has "is a directory"; then printf 'The target is a directory, not a file. Use ls or Glob to list its content.'
36
+ fi ;;
37
+ Glob | Grep) printf 'Search failed. Check the pattern syntax and the path.' ;;
38
+ Agent | Task) has "timeout|timed out" && printf 'Sub-agent timed out. Consider splitting the task into smaller parts.' ;;
39
+ esac
40
+ }
41
+
42
+ severity=ERROR
43
+ case "$TOOL" in Read | Glob | Grep) severity=WARN ;; esac
44
+ mkdir -p .claude/logs 2>/dev/null
45
+ printf '[%s] [%s] [%s] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$severity" "$TOOL" \
46
+ "$(printf '%s' "$ERROR" | tr '\n' ' ' | cut -c1-300)" >>.claude/logs/tool-failures.log 2>/dev/null
47
+
48
+ HINT=$(recovery_hint)
49
+ [ -z "$HINT" ] || hook_context PostToolUseFailure "$HINT"
50
+ exit 0