Skip to content

feat(#71): current-vs-slicing experiment scaffold + portable timing fix - #86

Merged
mohanagy merged 1 commit into
mainfrom
feat/issue-71-current-vs-slicing-spike
May 10, 2026
Merged

mohanagy merged 1 commit into
mainfrom
feat/issue-71-current-vs-slicing-spike

Conversation

@mohanagy

@mohanagy mohanagy commented May 10, 2026 •

Copy link
Copy Markdown
Owner

Scoped half of #71 (option B from our discussion). Tracking issue: #71 — Research spike: compare current graph retrieval vs task-conditioned program slicing. Milestone: v0.14-substrate.

Also bundles a fix for a latent macOS portability bug in #69's already-merged harness — discovered during this PR's smoke testing, same one-line root cause, didn't want to leave it broken.

What ships

docs/experiments/2026-05-10-current-vs-slicing/

The runnable half of the spike. Strategies 1, 2, and 4 work today; strategy 3 (slicer) is an explicit stub blocked on #73.

Strategy Status Adapter
1. Current graphify-ts pack ✅ runnable strategies/current-graphify.sh
2. Lexical baseline (ripgrep) ✅ runnable strategies/lexical-baseline.sh
3. Task-conditioned slicer 🟡 stub (rc=78) strategies/slicer-stub.sh
4. Full-context baseline ✅ runnable strategies/full-context.sh

The orchestrator (run.sh) runs each enabled strategy for each prompt in prompts.json, captures meta.json per run, optionally pipes the resulting context through an --exec model runner, and writes a side-by-side summary.json. The aggregator (aggregate.sh) prints a per-prompt comparison table.

Bundled bug fix: portable millisecond timing

Every date +%s%3N invocation across both #69's and #71's harnesses now uses node -e 'process.stdout.write(String(Date.now()))'. Symptom on macOS BSD date was value too great for base (error token is "1778399122N") because BSD date doesn't support %N and returned the literal string 1778399122N for $START. Caught by smoke-testing #71's harness; same root cause was sitting in #69's already-merged run.sh so the next user run on macOS would have hit it too.

Smoke test (in this PR)

End-to-end run against this repo, no --exec:

prompt                        full-context              lexical-baseline      slicer-stub
debug-config-env              97,152t / 50f / 4,269ms   4,995t / 3f / 71ms    (stub)
explain-auth-flow             97,152t / 50f / 4,461ms   4,894t / 2f / 56ms    (stub)

Confirms strategies execute, produce well-formed meta.json, and the aggregator renders the table correctly.

Honesty constraints I held to

  • The slicer adapter does not pretend to be a slicer. It exits rc=78 with a clear stub message linking Prototype task-conditioned program slicing for context packs #73, and summary.json records the stub state explicitly so anyone reading later can see exactly which strategies were measured.
  • README explicitly says: "the spike answers the narrower question: 'is current retrieval clearly better than dumb lexical at the same budget?'" — the full pivot recommendation has to wait on Prototype task-conditioned program slicing for context packs #73.
  • All token counts are local cl100k_base estimates (the same gpt-tokenizer package the rest of graphify-ts uses), not provider-billed — explicitly labeled as such in the README. Provider-billed numbers only appear if the user passes --exec and the runner emits a structured JSON usage block.
  • results/ is gitignored so accidental run outputs never get committed.

Test plan

  • npm run test:run — 1395/1395 pass (was 1388 on main; +7 new doc-honesty assertions).
  • bash run.sh --help renders cleanly.
  • Smoke test against this repo: 3 strategies × 2 prompts → valid summary.json + aggregator table.
  • bash -n clean for all 6 shell scripts.
  • jq validates prompts.json (8 prompts, all four task modes covered).
  • npm run typecheck — clean.
  • Reviewer runs --quick-style invocation against a real local monorepo and confirms the output bundle.

Deliverables remaining for #71

After this lands and someone has a real summary.json from a monorepo, the user-facing deliverable is findings.md next to the README — the recommendation paragraph #71 explicitly asks for. Until #73 ships, that recommendation is bounded to "current retrieval vs lexical baseline (and full-context upper bound)"; the slicing-pivot decision still waits on #73.

Summary by CodeRabbit

  • New Features

    • Added a new experiment framework comparing retrieval strategies with orchestration and aggregation tooling.
    • Implemented multiple retrieval strategy adapters (current retrieval, lexical baseline, full-context baseline, and slicing stub).
  • Tests

    • Added documentation verification tests ensuring experiment setup integrity and CLI contract compliance.

Review Change Stack

Implements the runnable half of #71 (Research spike: compare current
graph retrieval vs task-conditioned program slicing). Per the agreed
scope, ships strategies 1, 2, and 4 today; strategy 3 (slicer) is an
intentional stub blocked on #73.

Adds docs/experiments/2026-05-10-current-vs-slicing/:
  README.md         spike framing + 4-strategy contract + how-to-run
  prompts.json      8 prompts spanning explain/debug/review/impact
  strategies/
    current-graphify.sh  strategy 1: graphify-ts pack -> rendered context
    lexical-baseline.sh  strategy 2: ripgrep + window expansion
    slicer-stub.sh       strategy 3: stub, exits rc=78, blocks on #73
    full-context.sh      strategy 4: cat all TS/JS up to char budget
  run.sh            orchestrator: per prompt x strategy, capture meta+context,
                    optionally pipe through --exec for model answers
  aggregate.sh      side-by-side reader for summary.json
  .gitignore        keep results/ local until promoted

Bundled fix: replaces every 'date +%s%3N' invocation (GNU coreutils
only) with a portable 'node -e Date.now()' so the harnesses work on
macOS BSD date. Same change applied to #69's already-merged
docs/benchmarks/2026-05-10-backend-vs-monorepo/run.sh, since it has
the same latent bug.

Tests: +7 doc-honesty assertions in tests/unit/why-graphify-doc.test.ts
covering the new scaffold's contract (tracking issue link, four
strategy adapters, slicer-stub honesty, prompts.json shape, portable
timing for both #71 and #69 harnesses). Full suite: 1395/1395 passing.

Verified end-to-end against this repo: lexical-baseline 56-71ms /
~5K tokens / 2-3 files; full-context 4-4.5s / 97K tokens / 50 files;
slicer-stub rc=78 with the documented stub message.
@coderabbitai

coderabbitai Bot commented May 10, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR introduces a comprehensive experimental framework for comparing context retrieval strategies. A new experiment harness orchestrates four retrieval adapters (current graphify-ts, lexical search baseline, full-context concatenation, and a stub for task-conditioned slicing) across eight prompts spanning four task modes, producing comparable metrics and optional model-based answers. Test coverage verifies design contracts and timing portability.

Changes

Context Retrieval Experiment

Layer / File(s) Summary
Experiment Design
docs/experiments/2026-05-10-current-vs-slicing/README.md, .gitignore
README defines experiment scope (issue #71), strategy adapter contract (inputs/outputs), execution instructions, reporting requirements, and honesty notes; .gitignore excludes local results/ directory.
Prompt Data
docs/experiments/2026-05-10-current-vs-slicing/prompts.json
Eight task-specific prompts (explain, debug, review, impact modes) with id, task, and instruction text.
Orchestration Scripts
docs/experiments/2026-05-10-current-vs-slicing/run.sh, aggregate.sh
run.sh validates workspace/strategies, loops over prompts and adapters, captures context/metrics, optionally executes models, and generates summary.json; aggregate.sh parses results into formatted comparison tables.
Strategy Adapters
docs/experiments/2026-05-10-current-vs-slicing/strategies/*
Four scripts implement retrieval: current-graphify.sh (graphify-ts pack + text extraction), lexical-baseline.sh (rg term search), full-context.sh (TS/JS file concatenation), slicer-stub.sh (placeholder, exit 78, blocked on #73). Each produces context.txt and meta.json with timing/token/file metrics.
Test Coverage
tests/unit/why-graphify-doc.test.ts
Vitest assertions verify experiment README/scripts conform to contracts: scope reference (#71), adapter CLI arguments (--prompt, --workspace, --out), portable Date.now() timing (not GNU date +%s%3N), prompt structure (version, 8 prompts, task modes), and orchestrator/aggregator interfaces.
Timing Portability
docs/benchmarks/2026-05-10-backend-vs-monorepo/run.sh
Minor fix: generate_one replaces date +%s%3N with Node.js Date.now() to ensure portable millisecond timing.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

  • mohanagy/graphify-ts#71: This PR implements the exact experimental framework and research spike described in issue #71, adding all required harness scripts, strategy adapters, prompts, and verification tests to compare current graph retrieval against task-conditioned slicing.

Possibly related PRs

  • mohanagy/graphify-ts#85: Both PRs modify docs/benchmarks/2026-05-10-backend-vs-monorepo/run.sh to replace GNU-only date +%s%3N with portable Node.js Date.now() timing.

Poem

🐰 A researcher's dream now takes its flight,
Four strategies meet in experimental light,
Prompts, harnesses, stubs, and sleek script affairs—
We'll measure the context that really compares!
With portable timers and honest notes true,
The slicer awaits when #73 comes due. 🔬

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main changes: adding the current-vs-slicing experiment scaffold (addressing #71) and fixing a portability bug with millisecond timing.
Description check ✅ Passed The description is comprehensive and well-structured, covering the summary of changes, testing verification, related issues, and the required checklist items; all template sections are addressed.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/issue-71-current-vs-slicing-spike

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🤖 Prompt for all review comments with 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.

Inline comments:
In `@docs/experiments/2026-05-10-current-vs-slicing/aggregate.sh`:
- Around line 28-33: fmtState() is defined to render run state strings but isn't
being used for non-stub failures, so failed runs show as normal metric cells;
locate the table/cell rendering logic that currently only checks for stub exit
code or treats non-zero exits as ok (the blocks referenced around fmtState at
lines 28-33 and the similar code at 49-57) and replace the direct state-handling
with a call to fmtState(s) (or otherwise route all state-to-string formatting
through fmtState) so that "failed (rc=...)" is rendered for non-zero exits and
"stub" remains when exit === 78.

In `@docs/experiments/2026-05-10-current-vs-slicing/README.md`:
- Line 9: Escape the leading '#' in the issue reference to avoid markdownlint
MD018 by changing the token "#71" to "\#71" (or alternatively wrap it in
backticks as "`#71`") in the sentence that begins with "#71 asks: *should
graphify-ts move from `repo → graph → retrieval`..." so the markdown parser
doesn't treat it as a heading; update the text containing "#71" accordingly.

In `@docs/experiments/2026-05-10-current-vs-slicing/run.sh`:
- Around line 43-52: Flag handlers in the while-case loop read $2
unconditionally (for --workspace, --strategies, --exec, --prompt-ids, --out-dir)
which under set -u will blow up when a value is missing; update each case in
that block to first validate there is a following argument (e.g., test that $#
-ge 2 and the next token is not another flag) before assigning
WORKSPACE/STRATEGIES/EXEC/PROMPT_IDS/OUT_BASE and shifting, and call usage (or
print a clear error) if the check fails so missing values produce harness errors
instead of unbound variable errors.
- Around line 133-136: The substituted runner string inserts an unescaped path
into EXEC and then passes it to bash -c (runner, EXEC, outdir, bash -c), which
breaks or misinterprets paths with spaces or metacharacters; fix by escaping or
shell-quoting the inserted prompt file when constructing runner (e.g., use
printf '%q' on "$outdir/merged-prompt.txt" or otherwise shell-quote the
{prompt_file} replacement) or, better, avoid embedding user-controlled paths in
a single bash -c string by building and executing a command array / passing the
file as a separate argument to bash to eliminate word-splitting and unintended
expansion.

In
`@docs/experiments/2026-05-10-current-vs-slicing/strategies/current-graphify.sh`:
- Around line 50-52: The catch block that handles JSON.parse failure for
packPath currently uses a top-level "return" (in the try/catch around pack =
JSON.parse(fs.readFileSync(packPath, "utf8"))) which is invalid in a Node -e
script; replace that top-level return with process.exit(0) after writing the
fallback content to txt so the script exits cleanly: locate the try/catch that
references pack, packPath and txt and change the control flow to call
process.exit(0) instead of returning.

In `@docs/experiments/2026-05-10-current-vs-slicing/strategies/slicer-stub.sh`:
- Around line 21-31: Check for the required OUT argument (the $OUT variable)
before creating files; if $OUT is empty or unset, print a clear usage/error
message to stderr and exit non-zero (non-78) so the script fails fast instead of
producing unexpected shell errors. Add a guard at the top of slicer-stub.sh that
tests [ -z "$OUT" ] (or similar), writes a helpful error to stderr, and exits
(e.g., exit 2); otherwise proceed to mkdir -p "$OUT" and write context.txt and
meta.json and finally exit 78 as the intended stub contract.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 88284cba-db2b-482e-9b22-b61e83e192ef

📥 Commits

Reviewing files that changed from the base of the PR and between fb14e20 and b10f16a.

📒 Files selected for processing (11)
  • docs/benchmarks/2026-05-10-backend-vs-monorepo/run.sh
  • docs/experiments/2026-05-10-current-vs-slicing/.gitignore
  • docs/experiments/2026-05-10-current-vs-slicing/README.md
  • docs/experiments/2026-05-10-current-vs-slicing/aggregate.sh
  • docs/experiments/2026-05-10-current-vs-slicing/prompts.json
  • docs/experiments/2026-05-10-current-vs-slicing/run.sh
  • docs/experiments/2026-05-10-current-vs-slicing/strategies/current-graphify.sh
  • docs/experiments/2026-05-10-current-vs-slicing/strategies/full-context.sh
  • docs/experiments/2026-05-10-current-vs-slicing/strategies/lexical-baseline.sh
  • docs/experiments/2026-05-10-current-vs-slicing/strategies/slicer-stub.sh
  • tests/unit/why-graphify-doc.test.ts

Comment on lines +28 to +33
function fmtState(s) {
if (!s) return "missing";
if (s.exit === 78) return "stub";
if (s.exit !== null && s.exit !== 0) return `failed (rc=${s.exit})`;
return "ok";
}

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 | 🟠 Major | ⚡ Quick win

Failed strategy runs are not surfaced in the table.

fmtState() is defined but not used for non-stub failures, so failed runs can appear as regular metric cells. This can mislead experiment conclusions.

💡 Suggested fix
       for (const s of strategies) {
         const entry = per[id][s];
         if (!entry) { row.push("—".padEnd(colWidth)); continue; }
-        if (entry.exit === 78) { row.push("(stub)".padEnd(colWidth)); continue; }
+        const state = fmtState(entry);
+        if (state !== "ok") { row.push(`(${state})`.padEnd(colWidth)); continue; }
         const meta = entry.meta || {};
         const tokens = fmtNum(meta.est_tokens);
         const ms = fmtNum(meta.duration_ms);
         const files = fmtNum(meta.file_count);
         row.push(`${tokens}t / ${files}f / ${ms}ms`.padEnd(colWidth));

Also applies to: 49-57

🤖 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 `@docs/experiments/2026-05-10-current-vs-slicing/aggregate.sh` around lines 28
- 33, fmtState() is defined to render run state strings but isn't being used for
non-stub failures, so failed runs show as normal metric cells; locate the
table/cell rendering logic that currently only checks for stub exit code or
treats non-zero exits as ok (the blocks referenced around fmtState at lines
28-33 and the similar code at 49-57) and replace the direct state-handling with
a call to fmtState(s) (or otherwise route all state-to-string formatting through
fmtState) so that "failed (rc=...)" is rendered for non-zero exits and "stub"
remains when exit === 78.


## Why this exists

#71 asks: *should graphify-ts move from `repo → graph → retrieval` to `task → anchors → program slice → budgeted context pack`?* That's an architectural pivot, not an optimization. Before any rewrite, we need a measured comparison of:

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

Avoid markdown heading-lint ambiguity on issue references.

Line 9 starts with #71 and trips MD018 in common markdownlint setups. Escaping the hash (e.g., \#71) avoids false heading parsing.

🧰 Tools
🪛 markdownlint-cli2 (0.22.1)

[warning] 9-9: No space after hash on atx style heading

(MD018, no-missing-space-atx)

🤖 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 `@docs/experiments/2026-05-10-current-vs-slicing/README.md` at line 9, Escape
the leading '#' in the issue reference to avoid markdownlint MD018 by changing
the token "#71" to "\#71" (or alternatively wrap it in backticks as "`#71`") in
the sentence that begins with "#71 asks: *should graphify-ts move from `repo →
graph → retrieval`..." so the markdown parser doesn't treat it as a heading;
update the text containing "#71" accordingly.

Comment on lines +43 to +52
while [ $# -gt 0 ]; do
case "$1" in
--workspace) WORKSPACE="$2"; shift 2 ;;
--strategies) STRATEGIES="$2"; shift 2 ;;
--exec) EXEC="$2"; shift 2 ;;
--prompt-ids) PROMPT_IDS="$2"; shift 2 ;;
--out-dir) OUT_BASE="$2"; shift 2 ;;
-h|--help) usage ;;
*) echo "[harness] unknown arg: $1" >&2; usage ;;
esac

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
set -euo pipefail
file="docs/experiments/2026-05-10-current-vs-slicing/run.sh"

# Inspect the parser branch that consumes $2.
nl -ba "$file" | sed -n '43,53p'

Repository: mohanagy/graphify-ts

Length of output: 107


🏁 Script executed:

cat -n docs/experiments/2026-05-10-current-vs-slicing/run.sh | head -60

Repository: mohanagy/graphify-ts

Length of output: 2818


Guard value-taking flags before reading $2.

Lines 45–49 read $2 unconditionally. With set -u (line 9), missing flag values cause unbound variable errors instead of harness error messages.

 while [ $# -gt 0 ]; do
   case "$1" in
-    --workspace)   WORKSPACE="$2"; shift 2 ;;
-    --strategies)  STRATEGIES="$2"; shift 2 ;;
-    --exec)        EXEC="$2"; shift 2 ;;
-    --prompt-ids)  PROMPT_IDS="$2"; shift 2 ;;
-    --out-dir)     OUT_BASE="$2"; shift 2 ;;
+    --workspace)   [ $# -ge 2 ] || { echo "[harness] --workspace requires a value" >&2; usage; }; WORKSPACE="$2"; shift 2 ;;
+    --strategies)  [ $# -ge 2 ] || { echo "[harness] --strategies requires a value" >&2; usage; }; STRATEGIES="$2"; shift 2 ;;
+    --exec)        [ $# -ge 2 ] || { echo "[harness] --exec requires a value" >&2; usage; }; EXEC="$2"; shift 2 ;;
+    --prompt-ids)  [ $# -ge 2 ] || { echo "[harness] --prompt-ids requires a value" >&2; usage; }; PROMPT_IDS="$2"; shift 2 ;;
+    --out-dir)     [ $# -ge 2 ] || { echo "[harness] --out-dir requires a value" >&2; usage; }; OUT_BASE="$2"; shift 2 ;;
     -h|--help)     usage ;;
     *) echo "[harness] unknown arg: $1" >&2; usage ;;
   esac
 done
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
while [ $# -gt 0 ]; do
case "$1" in
--workspace) WORKSPACE="$2"; shift 2 ;;
--strategies) STRATEGIES="$2"; shift 2 ;;
--exec) EXEC="$2"; shift 2 ;;
--prompt-ids) PROMPT_IDS="$2"; shift 2 ;;
--out-dir) OUT_BASE="$2"; shift 2 ;;
-h|--help) usage ;;
*) echo "[harness] unknown arg: $1" >&2; usage ;;
esac
while [ $# -gt 0 ]; do
case "$1" in
--workspace) [ $# -ge 2 ] || { echo "[harness] --workspace requires a value" >&2; usage; }; WORKSPACE="$2"; shift 2 ;;
--strategies) [ $# -ge 2 ] || { echo "[harness] --strategies requires a value" >&2; usage; }; STRATEGIES="$2"; shift 2 ;;
--exec) [ $# -ge 2 ] || { echo "[harness] --exec requires a value" >&2; usage; }; EXEC="$2"; shift 2 ;;
--prompt-ids) [ $# -ge 2 ] || { echo "[harness] --prompt-ids requires a value" >&2; usage; }; PROMPT_IDS="$2"; shift 2 ;;
--out-dir) [ $# -ge 2 ] || { echo "[harness] --out-dir requires a value" >&2; usage; }; OUT_BASE="$2"; shift 2 ;;
-h|--help) usage ;;
*) echo "[harness] unknown arg: $1" >&2; usage ;;
esac
done
🤖 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 `@docs/experiments/2026-05-10-current-vs-slicing/run.sh` around lines 43 - 52,
Flag handlers in the while-case loop read $2 unconditionally (for --workspace,
--strategies, --exec, --prompt-ids, --out-dir) which under set -u will blow up
when a value is missing; update each case in that block to first validate there
is a following argument (e.g., test that $# -ge 2 and the next token is not
another flag) before assigning WORKSPACE/STRATEGIES/EXEC/PROMPT_IDS/OUT_BASE and
shifting, and call usage (or print a clear error) if the check fails so missing
values produce harness errors instead of unbound variable errors.

Comment on lines +133 to +136
local runner="${EXEC//\{prompt_file\}/$outdir/merged-prompt.txt}"
set +e
bash -c "$runner" > "$outdir/answer.json" 2> "$outdir/answer.log"
local arc=$?

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 | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
python - <<'PY'
import shlex
exec_tpl = 'cat {prompt_file} | jq .'
path = '/tmp/results bundle/prompt-1/merged-prompt.txt'
runner = exec_tpl.replace('{prompt_file}', path)
print("Interpolated:", runner)
print("Shell tokens:", shlex.split(runner))
print("Observation: path is split because it is unquoted.")
PY

Repository: mohanagy/graphify-ts

Length of output: 278


🏁 Script executed:

# Locate and verify the file
find . -name "run.sh" -path "*experiments*" -type f | head -20

Repository: mohanagy/graphify-ts

Length of output: 120


🏁 Script executed:

# Check if the specific file exists and read the context around lines 133-136
if [ -f "docs/experiments/2026-05-10-current-vs-slicing/run.sh" ]; then
  echo "=== File exists ===" 
  wc -l "docs/experiments/2026-05-10-current-vs-slicing/run.sh"
  echo ""
  echo "=== Lines 130-145 (context) ==="
  sed -n '130,145p' "docs/experiments/2026-05-10-current-vs-slicing/run.sh"
else
  echo "File not found"
fi

Repository: mohanagy/graphify-ts

Length of output: 810


🏁 Script executed:

# Verify the bash syntax of the suggested fix
bash -n - <<'BASH'
# Simulating the suggested fix
outdir="/tmp/test"
EXEC="cat {prompt_file} | jq ."

# Original code (problematic)
local runner="${EXEC//\{prompt_file\}/$outdir/merged-prompt.txt}"

# Suggested fix
local prompt_file="$outdir/merged-prompt.txt"
local prompt_file_q
printf -v prompt_file_q '%q' "$prompt_file"
local runner_fixed="${EXEC//\{prompt_file\}/$prompt_file_q}"

echo "Original runner: $runner"
echo "Fixed runner: $runner_fixed"
BASH

Repository: mohanagy/graphify-ts

Length of output: 46


🏁 Script executed:

# Find the EXEC variable definition and how outdir is constructed
grep -n "EXEC=" "docs/experiments/2026-05-10-current-vs-slicing/run.sh" | head -5

Repository: mohanagy/graphify-ts

Length of output: 160


🏁 Script executed:

# Search for outdir initialization
grep -n "outdir=" "docs/experiments/2026-05-10-current-vs-slicing/run.sh" | head -10

Repository: mohanagy/graphify-ts

Length of output: 123


🏁 Script executed:

# Get more context about the script structure and EXEC usage
sed -n '1,50p' "docs/experiments/2026-05-10-current-vs-slicing/run.sh"

Repository: mohanagy/graphify-ts

Length of output: 2044


🏁 Script executed:

# Check RUN_DIR initialization and how prompt_id/strategy values are sourced
grep -n "RUN_DIR=" "docs/experiments/2026-05-10-current-vs-slicing/run.sh"

Repository: mohanagy/graphify-ts

Length of output: 91


🏁 Script executed:

# Check how ID_ARR and strategy values are populated
grep -n "ID_ARR\|strategy" "docs/experiments/2026-05-10-current-vs-slicing/run.sh" | head -20

Repository: mohanagy/graphify-ts

Length of output: 1336


🏁 Script executed:

# Verify the actual vulnerability: test bash string substitution with spaces
bash -n - <<'BASH'
set -euo pipefail

# Simulate the code path with problematic input
EXEC="cat {prompt_file} | jq ."
outdir="/tmp/results bundle/2026-05-10/prompts/q1/strategy"

# Original code (vulnerable)
runner_original="${EXEC//\{prompt_file\}/$outdir/merged-prompt.txt}"

# Suggested fix
prompt_file="$outdir/merged-prompt.txt"
prompt_file_q=""
printf -v prompt_file_q '%q' "$prompt_file"
runner_fixed="${EXEC//\{prompt_file\}/$prompt_file_q}"

echo "Original runner command:"
echo "  $runner_original"
echo ""
echo "Fixed runner command:"
echo "  $runner_fixed"
BASH

Repository: mohanagy/graphify-ts

Length of output: 46


🏁 Script executed:

# Verify the fix more thoroughly - test that printf %q works correctly in bash context
bash << 'BASH'
set -euo pipefail

EXEC="cat {prompt_file} | jq ."
outdir="/tmp/results bundle/prompts/q1/strategy"

echo "=== Original (vulnerable) ==="
runner_orig="${EXEC//\{prompt_file\}/$outdir/merged-prompt.txt}"
echo "Runner: $runner_orig"

echo ""
echo "=== Fixed version ==="
prompt_file="$outdir/merged-prompt.txt"
printf -v prompt_file_q '%q' "$prompt_file"
echo "Quoted path: $prompt_file_q"
runner_fixed="${EXEC//\{prompt_file\}/$prompt_file_q}"
echo "Runner: $runner_fixed"

echo ""
echo "=== Verification: would the commands execute correctly? ==="
echo "Original would execute:"
echo "  bash -c '$runner_orig'"
echo "Which parses to tokens:"
echo "$runner_orig" | xargs -I {} bash -c 'echo "Token: {}"' 2>/dev/null || echo "(Would break due to unquoted spaces)"
BASH

Repository: mohanagy/graphify-ts

Length of output: 610


🏁 Script executed:

# Check if prompt_id or strategy values could contain problematic characters
sed -n '70,80p' "docs/experiments/2026-05-10-current-vs-slicing/run.sh"

Repository: mohanagy/graphify-ts

Length of output: 343


🏁 Script executed:

# Review the complete run_strategy_for_prompt function to understand all interactions
sed -n '104,140p' "docs/experiments/2026-05-10-current-vs-slicing/run.sh"

Repository: mohanagy/graphify-ts

Length of output: 1209


Escape {prompt_file} before passing interpolated command to bash -c.

Line 133 inserts a raw file path into the runner template, then Line 135 executes it through the shell. Paths with spaces or metacharacters can break execution or trigger unintended expansion.

The outdir value (constructed from user-controlled prompt IDs and strategy names) is inserted unquoted into the command string. A path containing spaces would split into separate shell tokens, causing the command to fail or misinterpret arguments.

Suggested fix
-    local runner="${EXEC//\{prompt_file\}/$outdir/merged-prompt.txt}"
+    local prompt_file="$outdir/merged-prompt.txt"
+    local prompt_file_q
+    printf -v prompt_file_q '%q' "$prompt_file"
+    local runner="${EXEC//\{prompt_file\}/$prompt_file_q}"
     set +e
     bash -c "$runner" > "$outdir/answer.json" 2> "$outdir/answer.log"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
local runner="${EXEC//\{prompt_file\}/$outdir/merged-prompt.txt}"
set +e
bash -c "$runner" > "$outdir/answer.json" 2> "$outdir/answer.log"
local arc=$?
local prompt_file="$outdir/merged-prompt.txt"
local prompt_file_q
printf -v prompt_file_q '%q' "$prompt_file"
local runner="${EXEC//\{prompt_file\}/$prompt_file_q}"
set +e
bash -c "$runner" > "$outdir/answer.json" 2> "$outdir/answer.log"
local arc=$?
🤖 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 `@docs/experiments/2026-05-10-current-vs-slicing/run.sh` around lines 133 -
136, The substituted runner string inserts an unescaped path into EXEC and then
passes it to bash -c (runner, EXEC, outdir, bash -c), which breaks or
misinterprets paths with spaces or metacharacters; fix by escaping or
shell-quoting the inserted prompt file when constructing runner (e.g., use
printf '%q' on "$outdir/merged-prompt.txt" or otherwise shell-quote the
{prompt_file} replacement) or, better, avoid embedding user-controlled paths in
a single bash -c string by building and executing a command array / passing the
file as a separate argument to bash to eliminate word-splitting and unintended
expansion.

Comment on lines +50 to +52
try { pack = JSON.parse(fs.readFileSync(packPath, "utf8")); }
catch { fs.writeFileSync(txt, fs.readFileSync(packPath, "utf8")); return; }

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 | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

# First, let's find and examine the file
find . -name "current-graphify.sh" -type f

Repository: mohanagy/graphify-ts

Length of output: 144


🏁 Script executed:

# If the file exists, read the relevant section with context
cat -n docs/experiments/2026-05-10-current-vs-slicing/strategies/current-graphify.sh | sed -n '40,60p'

Repository: mohanagy/graphify-ts

Length of output: 1017


🏁 Script executed:

# Verify JavaScript syntax rules by testing the exact scenario
node -e '
try { console.log("test"); }
catch { return; }
' 2>&1 || true

Repository: mohanagy/graphify-ts

Length of output: 422


🏁 Script executed:

# Verify the suggested fix works
node -e '
try { console.log("test"); }
catch { process.exit(0); }
console.log("after");
' 2>&1 || true

Repository: mohanagy/graphify-ts

Length of output: 75


🏁 Script executed:

# Verify the semantic correctness of process.exit(0) vs other alternatives
# Test if the original intent is preserved: exit early if parse fails
node -e '
try { JSON.parse("invalid json"); }
catch { console.log("Fallback written"); process.exit(0); }
console.log("This should NOT print");
' 2>&1
echo "Exit code: $?"

Repository: mohanagy/graphify-ts

Length of output: 94


Replace invalid top-level return with process.exit(0).

Line 51 uses return outside a function scope in a Node -e script, causing a syntax error: "Illegal return statement". This will crash the strategy execution.

Suggested fix
-  try { pack = JSON.parse(fs.readFileSync(packPath, "utf8")); }
-  catch { fs.writeFileSync(txt, fs.readFileSync(packPath, "utf8")); return; }
+  try { pack = JSON.parse(fs.readFileSync(packPath, "utf8")); }
+  catch { fs.writeFileSync(txt, fs.readFileSync(packPath, "utf8")); process.exit(0); }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try { pack = JSON.parse(fs.readFileSync(packPath, "utf8")); }
catch { fs.writeFileSync(txt, fs.readFileSync(packPath, "utf8")); return; }
try { pack = JSON.parse(fs.readFileSync(packPath, "utf8")); }
catch { fs.writeFileSync(txt, fs.readFileSync(packPath, "utf8")); process.exit(0); }
🤖 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
`@docs/experiments/2026-05-10-current-vs-slicing/strategies/current-graphify.sh`
around lines 50 - 52, The catch block that handles JSON.parse failure for
packPath currently uses a top-level "return" (in the try/catch around pack =
JSON.parse(fs.readFileSync(packPath, "utf8"))) which is invalid in a Node -e
script; replace that top-level return with process.exit(0) after writing the
fallback content to txt so the script exits cleanly: locate the try/catch that
references pack, packPath and txt and change the control flow to call
process.exit(0) instead of returning.

Comment on lines +21 to +31
mkdir -p "$OUT"
cat > "$OUT/context.txt" <<'EOF'
[slicer-stub] Task-conditioned slicing strategy is not yet implemented.

Tracking issue: https://github.com/mohanagy/graphify-ts/issues/73
Until #73 ships, this experiment compares strategies 1, 2, and 4 only.
EOF
printf '{ "strategy": "slicer-stub", "duration_ms": 0, "est_tokens": 0, "file_count": 0, "notes": "stub; blocked on #73 prototype" }\n' \
> "$OUT/meta.json"
echo "[slicer-stub] not implemented; see https://github.com/mohanagy/graphify-ts/issues/73" >&2
exit 78

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

Validate required args before writing outputs.

Without an explicit guard, missing --out can fail with a shell error instead of the intentional stub contract (context.txt/meta.json + rc=78).

💡 Suggested fix
 done
+[ -n "$PROMPT" ] && [ -n "$WORKSPACE" ] && [ -n "$OUT" ] || {
+  echo "[slicer-stub] usage: $0 --prompt <text> --workspace <path> --out <dir>" >&2; exit 1; }
 mkdir -p "$OUT"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
mkdir -p "$OUT"
cat > "$OUT/context.txt" <<'EOF'
[slicer-stub] Task-conditioned slicing strategy is not yet implemented.
Tracking issue: https://github.com/mohanagy/graphify-ts/issues/73
Until #73 ships, this experiment compares strategies 1, 2, and 4 only.
EOF
printf '{ "strategy": "slicer-stub", "duration_ms": 0, "est_tokens": 0, "file_count": 0, "notes": "stub; blocked on #73 prototype" }\n' \
> "$OUT/meta.json"
echo "[slicer-stub] not implemented; see https://github.com/mohanagy/graphify-ts/issues/73" >&2
exit 78
[ -n "$PROMPT" ] && [ -n "$WORKSPACE" ] && [ -n "$OUT" ] || {
echo "[slicer-stub] usage: $0 --prompt <text> --workspace <path> --out <dir>" >&2; exit 1; }
mkdir -p "$OUT"
cat > "$OUT/context.txt" <<'EOF'
[slicer-stub] Task-conditioned slicing strategy is not yet implemented.
Tracking issue: https://github.com/mohanagy/graphify-ts/issues/73
Until `#73` ships, this experiment compares strategies 1, 2, and 4 only.
EOF
printf '{ "strategy": "slicer-stub", "duration_ms": 0, "est_tokens": 0, "file_count": 0, "notes": "stub; blocked on `#73` prototype" }\n' \
> "$OUT/meta.json"
echo "[slicer-stub] not implemented; see https://github.com/mohanagy/graphify-ts/issues/73" >&2
exit 78
🤖 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 `@docs/experiments/2026-05-10-current-vs-slicing/strategies/slicer-stub.sh`
around lines 21 - 31, Check for the required OUT argument (the $OUT variable)
before creating files; if $OUT is empty or unset, print a clear usage/error
message to stderr and exit non-zero (non-78) so the script fails fast instead of
producing unexpected shell errors. Add a guard at the top of slicer-stub.sh that
tests [ -z "$OUT" ] (or similar), writes a helpful error to stderr, and exits
(e.g., exit 2); otherwise proceed to mkdir -p "$OUT" and write context.txt and
meta.json and finally exit 78 as the intended stub contract.

@mohanagy
mohanagy merged commit efde016 into main May 10, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant