Skip to content
Closed
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
61 changes: 44 additions & 17 deletions skills/rules-distill/scripts/scan-rules.sh
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,39 @@ if [[ ! -d "$RULES_DIR" ]]; then
exit 1
fi

# Collect all .md files (excluding _archived/)
# Collect markdown files recursively without `find`, `sort`, or Bash 4's
# globstar. A small in-process insertion sort preserves the full-path ordering
# that the previous external `sort` supplied.
files=()
while IFS= read -r f; do
files+=("$f")
done < <(find "$RULES_DIR" -name '*.md' -not -path '*/_archived/*' -print | sort)

total=${#files[@]}
collect_rule_files() {
local dir="$1"
local entry
for entry in "$dir"/..?* "$dir"/.[!.]* "$dir"/*; do
[[ -e "$entry" || -L "$entry" ]] || continue
if [[ -d "$entry" && ! -L "$entry" ]]; then
[[ "${entry##*/}" == "_archived" ]] && continue
collect_rule_files "$entry"
elif [[ -f "$entry" && "$entry" == *.md ]]; then
files+=("$entry")
Comment on lines +30 to +31

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Exclude symbolic links to files outside the scan directory.

[[ -f "$entry" ]] dereferences symbolic links. A linked Markdown or SKILL.md file can resolve outside the supplied scan directory, and the scanners then read and serialize its metadata. Require both -f and ! -L in each file branch.

  • skills/rules-distill/scripts/scan-rules.sh#L30-L31: exclude linked Markdown files before appending to files.
  • skills/skill-stocktake/scripts/scan.sh#L66-L67: exclude linked Markdown files before appending to discovered_files.
  • skills/rules-distill/scripts/scan-skills.sh#L64-L65: exclude linked SKILL.md files before appending to discovered_files.

As per path instructions, treat skills/**/scripts/** as untrusted-input tooling and flag path traversal risks.

📍 Affects 3 files
  • skills/rules-distill/scripts/scan-rules.sh#L30-L31 (this comment)
  • skills/skill-stocktake/scripts/scan.sh#L66-L67
  • skills/rules-distill/scripts/scan-skills.sh#L64-L65
🤖 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 `@skills/rules-distill/scripts/scan-rules.sh` around lines 30 - 31, Update the
file-discovery branches in skills/rules-distill/scripts/scan-rules.sh lines
30-31, skills/skill-stocktake/scripts/scan.sh lines 66-67, and
skills/rules-distill/scripts/scan-skills.sh lines 64-65 to require both a
regular file check and a non-symbolic-link check before appending Markdown or
SKILL.md paths. Ensure these untrusted-input scanners exclude symlinks resolving
outside the scan directory and do not introduce path traversal exposure.

Source: Path instructions

fi
done
}
collect_rule_files "$RULES_DIR"
for ((sort_index = 1; sort_index < ${#files[@]}; sort_index += 1)); do
sort_value="${files[$sort_index]}"
sort_cursor=$((sort_index - 1))
while ((sort_cursor >= 0)) && [[ "${files[$sort_cursor]}" > "$sort_value" ]]; do
files[$((sort_cursor + 1))]="${files[$sort_cursor]}"
sort_cursor=$((sort_cursor - 1))
done
files[$((sort_cursor + 1))]="$sort_value"
done

tmpdir=$(mktemp -d)
_rules_cleanup() { rm -rf "$tmpdir"; }
trap _rules_cleanup EXIT

for i in "${!files[@]}"; do
for ((i = 0; i < ${#files[@]}; i += 1)); do
file="${files[$i]}"
rel_path="${file#"$HOME"/}"
rel_path="~/$rel_path"
Expand All @@ -38,21 +58,28 @@ for i in "${!files[@]}"; do
# Get line count
line_count=$(wc -l < "$file" | tr -d ' ')

# Zero-pad so the later "$tmpdir"/*.json glob keeps insertion order past 9
# files (unpadded, 10.json sorts before 2.json lexicographically).
printf -v fname '%06d.json' "$i"
jq -n \
--arg path "$rel_path" \
--arg file "$(basename "$file")" \
--argjson lines "$line_count" \
--argjson headings "$headings_json" \
'{path:$path,file:$file,lines:$lines,headings:$headings}' \
> "$tmpdir/$i.json"
> "$tmpdir/$fname"
done

if [[ ${#files[@]} -eq 0 ]]; then
jq -n --arg dir "$RULES_DIR" '{rules_dir:$dir,total:0,rules:[]}'
else
jq -n \
--arg dir "$RULES_DIR" \
--argjson total "$total" \
--argjson rules "$(jq -s '.' "$tmpdir"/*.json)" \
'{rules_dir:$dir,total:$total,rules:$rules}'
fi
stream_json_files() {
local dir="$1"
local json_file line
for json_file in "$dir"/*.json; do
[[ -f "$json_file" ]] || continue
while IFS= read -r line || [[ -n "$line" ]]; do
printf '%s\n' "$line"
done < "$json_file"
done
}

stream_json_files "$tmpdir" |
jq -s --arg dir "$RULES_DIR" '{rules_dir:$dir,total:length,rules:.}'
75 changes: 59 additions & 16 deletions skills/rules-distill/scripts/scan-skills.sh
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,46 @@ get_mtime() {
date -u -r "$secs" +%Y-%m-%dT%H:%M:%SZ
}

# Bash-3.2-compatible recursive discovery. Avoids `find | sort` on
# AppLocker-hardened Windows and avoids Bash 4's globstar on stock macOS.
discovered_files=()
collect_skill_files() {
local dir="$1"
local entry
for entry in "$dir"/..?* "$dir"/.[!.]* "$dir"/*; do
[[ -e "$entry" || -L "$entry" ]] || continue
if [[ -d "$entry" && ! -L "$entry" ]]; then
collect_skill_files "$entry"
elif [[ -f "$entry" && "${entry##*/}" == "SKILL.md" ]]; then
discovered_files+=("$entry")
fi
done
}

sort_discovered_files() {
local sort_index sort_cursor sort_value
for ((sort_index = 1; sort_index < ${#discovered_files[@]}; sort_index += 1)); do
sort_value="${discovered_files[$sort_index]}"
sort_cursor=$((sort_index - 1))
while ((sort_cursor >= 0)) && [[ "${discovered_files[$sort_cursor]}" > "$sort_value" ]]; do
discovered_files[$((sort_cursor + 1))]="${discovered_files[$sort_cursor]}"
sort_cursor=$((sort_cursor - 1))
done
discovered_files[$((sort_cursor + 1))]="$sort_value"
done
}

stream_json_files() {
local dir="$1"
local json_file line
for json_file in "$dir"/*.json; do
[[ -f "$json_file" ]] || continue
while IFS= read -r line || [[ -n "$line" ]]; do
printf '%s\n' "$line"
done < "$json_file"
done
}

# Scan a directory and produce a JSON array of skill objects
scan_dir_to_json() {
local dir="$1"
Expand All @@ -61,29 +101,34 @@ scan_dir_to_json() {
_scan_cleanup() { rm -rf "$_scan_tmpdir"; }
trap _scan_cleanup RETURN

discovered_files=()
collect_skill_files "$dir"
sort_discovered_files

local i=0
while IFS= read -r file; do
local name desc mtime dp
local file
local file_index
for ((file_index = 0; file_index < ${#discovered_files[@]}; file_index += 1)); do
file="${discovered_files[$file_index]}"
local name desc mtime dp fname
name=$(extract_field "$file" "name")
desc=$(extract_field "$file" "description")
mtime=$(get_mtime "$file")
dp="${file/#$HOME/~}"

# Zero-pad so the later "$tmpdir"/*.json glob keeps insertion order past 9
# files (unpadded, 10.json sorts before 2.json lexicographically).
printf -v fname '%06d.json' "$i"
jq -n \
--arg path "$dp" \
--arg name "$name" \
--arg description "$desc" \
--arg mtime "$mtime" \
'{path:$path,name:$name,description:$description,mtime:$mtime}' \
> "$tmpdir/$i.json"
> "$tmpdir/$fname"
i=$((i+1))
done < <(find "$dir" -name "SKILL.md" -type f 2>/dev/null | sort)

if [[ $i -eq 0 ]]; then
echo "[]"
else
jq -s '.' "$tmpdir"/*.json
fi
done
stream_json_files "$tmpdir" | jq -s '.'
}

# --- Main ---
Expand All @@ -110,20 +155,18 @@ if [[ -n "$CWD_SKILLS_DIR" && -d "$CWD_SKILLS_DIR" ]]; then
project_count=$(echo "$project_skills" | jq 'length')
fi

# Merge global + project skills into one array
all_skills=$(jq -s 'add' <(echo "$global_skills") <(echo "$project_skills"))

jq -n \
# Stream arrays on stdin: this works with native Windows jq and cannot exceed
# the operating system's command-line argument limit.
printf '%s\n%s\n' "$global_skills" "$project_skills" | jq -s \
--arg global_found "$global_found" \
--argjson global_count "$global_count" \
--arg project_found "$project_found" \
--arg project_path "$project_path" \
--argjson project_count "$project_count" \
--argjson skills "$all_skills" \
'{
scan_summary: {
global: { found: ($global_found == "true"), count: $global_count },
project: { found: ($project_found == "true"), path: $project_path, count: $project_count }
},
skills: $skills
skills: (.[0] + .[1])
}'
105 changes: 73 additions & 32 deletions skills/skill-stocktake/scripts/scan.sh
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,44 @@ date_ago() {
date -u -d "${n} days ago" +%Y-%m-%dT%H:%M:%SZ
}

# Count observations matching a file path since a cutoff timestamp
count_obs() {
local file="$1" cutoff="$2"
if [[ ! -f "$OBSERVATIONS" ]]; then
echo 0
return
fi
jq -r --arg p "$file" --arg c "$cutoff" \
'select(.tool=="Read" and .path==$p and .timestamp>=$c) | 1' \
"$OBSERVATIONS" 2>/dev/null | wc -l | tr -d ' '
# Bash-3.2-compatible recursive discovery. Avoids `find | sort` on
# AppLocker-hardened Windows and avoids Bash 4's globstar on stock macOS.
discovered_files=()
collect_markdown_files() {
local dir="$1"
local entry
for entry in "$dir"/..?* "$dir"/.[!.]* "$dir"/*; do
[[ -e "$entry" || -L "$entry" ]] || continue
if [[ -d "$entry" && ! -L "$entry" ]]; then
collect_markdown_files "$entry"
elif [[ -f "$entry" && "$entry" == *.md ]]; then
discovered_files+=("$entry")
fi
done
}

sort_discovered_files() {
local sort_index sort_cursor sort_value
for ((sort_index = 1; sort_index < ${#discovered_files[@]}; sort_index += 1)); do
sort_value="${discovered_files[$sort_index]}"
sort_cursor=$((sort_index - 1))
while ((sort_cursor >= 0)) && [[ "${discovered_files[$sort_cursor]}" > "$sort_value" ]]; do
discovered_files[$((sort_cursor + 1))]="${discovered_files[$sort_cursor]}"
sort_cursor=$((sort_cursor - 1))
done
discovered_files[$((sort_cursor + 1))]="$sort_value"
done
}

stream_json_files() {
local dir="$1"
local json_file line
for json_file in "$dir"/*.json; do
[[ -f "$json_file" ]] || continue
while IFS= read -r line || [[ -n "$line" ]]; do
printf '%s\n' "$line"
done < "$json_file"
done
}

# Scan a directory and produce a JSON array of skill objects
Expand All @@ -85,29 +113,49 @@ scan_dir_to_json() {
local obs_7d_counts obs_30d_counts
obs_7d_counts=""
obs_30d_counts=""
# awk counting instead of `sort | uniq -c`: AppLocker-hardened machines shim
# sort (silent-empty on GNU flags); awk needs no sorted input.
if [[ -f "$OBSERVATIONS" ]]; then
obs_7d_counts=$(jq -r --arg c "$c7" \
'select(.tool=="Read" and .timestamp>=$c) | .path' \
"$OBSERVATIONS" 2>/dev/null | sort | uniq -c)
"$OBSERVATIONS" 2>/dev/null | awk '{c[$0]++} END {for (p in c) printf "%d %s\n", c[p], p}')
obs_30d_counts=$(jq -r --arg c "$c30" \
'select(.tool=="Read" and .timestamp>=$c) | .path' \
"$OBSERVATIONS" 2>/dev/null | sort | uniq -c)
"$OBSERVATIONS" 2>/dev/null | awk '{c[$0]++} END {for (p in c) printf "%d %s\n", c[p], p}')
fi
Comment on lines 118 to 125

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Report invalid observation data.

Lines 119-124 discard jq diagnostics for the external OBSERVATIONS file. If the file is malformed or unreadable, the scan can emit partial counts or fail without a clear error.

Remove 2>/dev/null. Check each jq result before aggregation. Write a clear error to stderr and return nonzero on failure.

🤖 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 `@skills/skill-stocktake/scripts/scan.sh` around lines 118 - 125, Update the
observation-counting logic in the scan flow around OBSERVATIONS to preserve jq
diagnostics, validate each jq invocation before passing output to awk, and write
a clear failure message to stderr followed by a nonzero return when either query
fails. Keep successful 7-day and 30-day aggregation behavior unchanged.

Source: Coding guidelines


discovered_files=()
collect_markdown_files "$dir"
sort_discovered_files

local i=0
while IFS= read -r file; do
local name desc mtime u7 u30 dp
local file
local file_index
for ((file_index = 0; file_index < ${#discovered_files[@]}; file_index += 1)); do
file="${discovered_files[$file_index]}"
local name desc mtime u7 u30 dp fname
name=$(extract_field "$file" "name")
desc=$(extract_field "$file" "description")
mtime=$(date -u -r "$file" +%Y-%m-%dT%H:%M:%SZ)
# Use awk exact field match to avoid substring false-positives from grep -F.
# uniq -c output format: " N /path/to/file" — path is always field 2.
u7=$(echo "$obs_7d_counts" | awk -v f="$file" '$2 == f {print $1}' | head -1)
# Parse only the leading count and compare the complete remaining path so
# spaces in directory or skill names remain significant.
u7=$(printf '%s\n' "$obs_7d_counts" | awk -v f="$file" '
match($0, /^[0-9]+ /) && substr($0, RLENGTH + 1) == f {
print substr($0, 1, RLENGTH - 1)
exit
}')
u7="${u7:-0}"
u30=$(echo "$obs_30d_counts" | awk -v f="$file" '$2 == f {print $1}' | head -1)
u30=$(printf '%s\n' "$obs_30d_counts" | awk -v f="$file" '
match($0, /^[0-9]+ /) && substr($0, RLENGTH + 1) == f {
print substr($0, 1, RLENGTH - 1)
exit
}')
u30="${u30:-0}"
dp="${file/#$HOME/~}"

# Zero-pad so the later "$tmpdir"/*.json glob keeps insertion order past 9
# files (unpadded, 10.json sorts before 2.json lexicographically).
printf -v fname '%06d.json' "$i"
jq -n \
--arg path "$dp" \
--arg name "$name" \
Expand All @@ -116,15 +164,10 @@ scan_dir_to_json() {
--argjson use_7d "$u7" \
--argjson use_30d "$u30" \
'{path:$path,name:$name,description:$description,use_7d:$use_7d,use_30d:$use_30d,mtime:$mtime}' \
> "$tmpdir/$i.json"
> "$tmpdir/$fname"
i=$((i+1))
done < <(find "$dir" -name "*.md" -type f 2>/dev/null | sort)

if [[ $i -eq 0 ]]; then
echo "[]"
else
jq -s '.' "$tmpdir"/*.json
fi
done
stream_json_files "$tmpdir" | jq -s '.'
}

# --- Main ---
Expand All @@ -151,20 +194,18 @@ if [[ -n "$CWD_SKILLS_DIR" && -d "$CWD_SKILLS_DIR" ]]; then
project_count=$(echo "$project_skills" | jq 'length')
fi

# Merge global + project skills into one array
all_skills=$(jq -s 'add' <(echo "$global_skills") <(echo "$project_skills"))

jq -n \
# Stream arrays on stdin: this works with native Windows jq and cannot exceed
# the operating system's command-line argument limit.
printf '%s\n%s\n' "$global_skills" "$project_skills" | jq -s \
--arg global_found "$global_found" \
--argjson global_count "$global_count" \
--arg project_found "$project_found" \
--arg project_path "$project_path" \
--argjson project_count "$project_count" \
--argjson skills "$all_skills" \
'{
scan_summary: {
global: { found: ($global_found == "true"), count: $global_count },
project: { found: ($project_found == "true"), path: $project_path, count: $project_count }
},
skills: $skills
skills: (.[0] + .[1])
}'
Loading
Loading