@giamme/forge 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -27,6 +27,9 @@
27
27
  # forge-memory.sh spend <repo> [--run <run-id>]
28
28
  # forge-memory.sh learnings <repo> [--json] every ledger learning and its state, as JSON
29
29
  # forge-memory.sh forget <repo> <category:key>... [--dry-run] [--json] [--actor ui|cli]
30
+ # forge-memory.sh add <repo> --category <verify|trap|finding> --text TEXT [--path P]...
31
+ # [--actor ui|cli] [--json]
32
+ # forge-memory.sh edit <repo> <category:key> --text TEXT [--path P]... [--actor ui|cli] [--json]
30
33
  #
31
34
  # Exit codes: 0 ok | 2 usage error
32
35
  set -uo pipefail
@@ -126,21 +129,31 @@ section_title() {
126
129
  # With <ledger>, that file is read instead of the repo's ledger. `forget --dry-run` passes a
127
130
  # scratch copy that already has the rows removed, and a scratch <out>, so the repo is not touched.
128
131
  rebuild() { # rebuild <repo> [<out> [<ledger>]] -> prints "kept<TAB>pruned_stale<TAB>pruned_cap"
129
- local repo="$1" led mem tmp cand jev_loaded=0
132
+ local repo="$1" led mem tmp cand jev_loaded=0 personf tmproles
130
133
  if [ "${FORGE_MEMORY_DEEP_PRUNE:-0}" = 1 ] && [ -f "$SKILL_DIR/scripts/forge-jev-options.sh" ]; then
131
134
  source "$SKILL_DIR/scripts/forge-jev-options.sh" 2>/dev/null && jev_loaded=1
132
135
  fi
133
136
  led="${3:-$(ledger_for "$repo")}"; mem="${2:-$(memory_for "$repo")}"
134
137
  [ -f "$led" ] || return 0
135
138
  tmp="$mem.tmp.$$"; cand="$mem.cand.$$"
139
+ # Learnings a person wrote are kept on the first row and trimmed last. The cand
140
+ # file itself stays the old four columns: sort's tie-break is the whole line, so an
141
+ # extra column would reshuffle two facts that share a count and a timestamp.
142
+ personf="$mem.person.$$"; tmproles="$mem.roles.$$"
143
+ rm -f "$personf" "$tmproles"
144
+ : > "$tmproles"
136
145
 
137
146
  # Group by (category, key). count = number of DISTINCT runs the key appeared in,
138
147
  # which is what makes a recurrence threshold meaningful: one run emitting the
139
- # same learning twice is still one occurrence.
140
- awk -F'\t' '
148
+ # same learning twice is still one occurrence. A row with role person, injectable
149
+ # or not, marks the learning so the finding threshold below does not apply.
150
+ FORGE_MEMORY_PERSON="$personf" awk -F'\t' '
151
+ BEGIN { personfile = ENVIRON["FORGE_MEMORY_PERSON"] }
141
152
  /^#/ || NF < 9 { next }
153
+ { if ($4 == "person") person[$7 "\034" $8] = 1 }
142
154
  # Column 11 is the injectable flag. Rows written before it existed have NF == 10
143
155
  # and are treated as injectable, so an existing ledger keeps behaving as it did.
156
+ # Column 12 (paths) is only for edit; rebuild does not read it.
144
157
  NF >= 11 && $11 == "0" { next }
145
158
  {
146
159
  ts=$1; run=$2; cat=$7; key=$8; txt=$9
@@ -149,21 +162,30 @@ rebuild() { # rebuild <repo> [<out> [<ledger>]] -> prints "kept<TAB>pruned_stale
149
162
  if (ts >= lastts[k]) { lastts[k]=ts; last[k]=txt }
150
163
  catof[k]=cat
151
164
  }
152
- END { for (k in cnt) printf "%s\t%d\t%s\t%s\n", catof[k], cnt[k], lastts[k], last[k] }
165
+ END {
166
+ for (k in cnt) printf "%s\t%d\t%s\t%s\n", catof[k], cnt[k], lastts[k], last[k]
167
+ for (k in cnt) if (person[k]) printf "%s\t%s\t%s\n", catof[k], lastts[k], last[k] > personfile
168
+ }
153
169
  ' "$led" > "$cand" 2>/dev/null
154
170
 
155
171
  local kept=0 stale=0 capped=0
156
172
  : > "$tmp"
157
- local sec cat count ts text anchor line
173
+ local sec cat count ts text anchor line person browns
158
174
  for sec in verify trap finding; do
159
175
  local body="$mem.sec.$$"; : > "$body"
176
+ browns="$body.roles"; : > "$browns"
160
177
  # Highest count first, then most recent — the ordering a human scans for a
161
178
  # systemic problem, and deterministic so tests can assert on it.
162
179
  while IFS=$'\t' read -r cat count ts text; do
163
180
  [ "$cat" = "$sec" ] || continue
181
+ person=0
182
+ if [ -s "$personf" ] && grep -F -x -q -- "$cat"$'\t'"$ts"$'\t'"$text" "$personf"; then
183
+ person=1
184
+ fi
164
185
  # A finding seen once is an incident, not a pattern. Promoting it would fill
165
186
  # memory with one-offs, which is exactly how this becomes a junk drawer.
166
- if [ "$sec" = finding ] && [ "$count" -lt 2 ]; then continue; fi
187
+ # A person's own learning is kept on its first row, in every category.
188
+ if [ "$sec" = finding ] && [ "$count" -lt 2 ] && [ "$person" != 1 ]; then continue; fi
167
189
  anchor="$(anchor_of "$text")"
168
190
  # An entry anchored to a path that no longer exists is stale by construction:
169
191
  # the code it describes is gone, so the fact is at best useless and at worst
@@ -191,19 +213,21 @@ rebuild() { # rebuild <repo> [<out> [<ledger>]] -> prints "kept<TAB>pruned_stale
191
213
  else
192
214
  printf '%s\t- %s\n' "$count" "$text" >> "$body"
193
215
  fi
216
+ if [ "$person" = 1 ]; then printf 'p\n' >> "$browns"; else printf 'n\n' >> "$browns"; fi
194
217
  done < <(sort -t"$TAB" -k2,2nr -k3,3r "$cand")
195
218
 
196
219
  if [ -s "$body" ]; then
197
220
  { section_title "$sec"; cut -f2- "$body"; echo; } >> "$tmp"
221
+ { printf '.\n'; cat "$browns"; printf '.\n'; } >> "$tmproles"
198
222
  kept=$((kept + $(wc -l < "$body" | tr -d ' ')))
199
223
  fi
200
- rm -f "$body"
224
+ rm -f "$body" "$browns"
201
225
  done
202
- rm -f "$cand"
226
+ rm -f "$cand" "$personf"
203
227
 
204
- if [ ! -s "$tmp" ]; then rm -f "$tmp" "$mem"; printf '0\t%s\t0\n' "$stale"; return 0; fi
228
+ if [ ! -s "$tmp" ]; then rm -f "$tmp" "$tmproles" "$mem"; printf '0\t%s\t0\n' "$stale"; return 0; fi
205
229
 
206
- local header="$mem.hdr.$$"
230
+ local header="$mem.hdr.$$" roles="$mem.caproles.$$"
207
231
  {
208
232
  echo "# forge project memory"
209
233
  echo "<!-- Maintained by forge from what its own runs observed. Do not edit this file"
@@ -212,17 +236,37 @@ rebuild() { # rebuild <repo> [<out> [<ledger>]] -> prints "kept<TAB>pruned_stale
212
236
  echo
213
237
  cat "$tmp"
214
238
  } > "$header"
239
+ # One role per header line, in lockstep: n a run fact, p a person's fact, . the rest.
240
+ # The five dots are the header lines above. With no person rows every fact is n, so the
241
+ # trim below still deletes the last fact line and memory.md stays byte-identical.
242
+ {
243
+ printf '.\n.\n.\n.\n.\n'
244
+ cat "$tmproles"
245
+ } > "$roles"
215
246
 
216
247
  # Cap enforcement. Everything above already dropped stale entries and unpromoted
217
- # findings, so what is left is real; trimming happens from the bottom, which the
218
- # sort above has arranged to be the lowest-count, least-recent facts.
248
+ # findings, so what is left is real. A run fact is trimmed from the bottom, which the
249
+ # sort above has arranged to be the lowest-count, least-recent. A person's fact goes
250
+ # only once no run fact is left.
219
251
  while [ "$(wc -l < "$header" | tr -d ' ')" -gt "$MAX_LINES" ] || \
220
252
  [ "$(wc -c < "$header" | tr -d ' ')" -gt "$MAX_BYTES" ]; do
221
253
  local last_fact
222
- last_fact="$(grep -n '^- ' "$header" | tail -1 | cut -d: -f1)"
254
+ last_fact="$(awk '
255
+ { role[NR] = $0 }
256
+ END {
257
+ last_n = 0; last_any = 0
258
+ for (i = 1; i <= NR; i++) {
259
+ if (role[i] == "n") last_n = i
260
+ if (role[i] == "n" || role[i] == "p") last_any = i
261
+ }
262
+ if (last_n) print last_n
263
+ else if (last_any) print last_any
264
+ }
265
+ ' "$roles")"
223
266
  [ -n "$last_fact" ] || break
224
267
  [ -z "$MEMORY_DROPS" ] || printf 'cap\t-\t%s\n' "$(sed -n "${last_fact}p" "$header")" >> "$MEMORY_DROPS"
225
268
  sed "${last_fact}d" "$header" > "$header.x" && mv "$header.x" "$header"
269
+ sed "${last_fact}d" "$roles" > "$roles.x" && mv "$roles.x" "$roles"
226
270
  capped=$((capped+1)); kept=$((kept-1))
227
271
  done
228
272
  # The cap can eat a section's last fact, leaving a heading over nothing.
@@ -230,7 +274,7 @@ rebuild() { # rebuild <repo> [<out> [<ledger>]] -> prints "kept<TAB>pruned_stale
230
274
 
231
275
  [ -n "${2:-}" ] || mkdir -p "$(dir_for "$repo")"
232
276
  mv "$header" "$mem"
233
- rm -f "$tmp"
277
+ rm -f "$tmp" "$tmproles" "$roles"
234
278
  printf '%s\t%s\t%s\n' "$kept" "$stale" "$capped"
235
279
  }
236
280
 
@@ -594,15 +638,17 @@ do_spend() {
594
638
  # edit of that same ledger, so it runs when memory is off too. There is no early return.
595
639
  #
596
640
  # Sets FORGET_CANON to the ledger's "category:key" form (norm_key on each part), or exits 2.
597
- parse_forget_key() {
598
- local raw="$1" cat key
641
+ # <cmd> is the word in the error (default forget). edit uses the same parse and must not
642
+ # tell the person they ran forget.
643
+ parse_forget_key() { # parse_forget_key <raw> [cmd]
644
+ local raw="$1" cmd="${2:-forget}" cat key
599
645
  case "$raw" in
600
646
  *:*) ;;
601
- *) die "forget: KEY must be category:key, got '$raw'" ;;
647
+ *) die "$cmd: KEY must be category:key, got '$raw'" ;;
602
648
  esac
603
649
  cat="$(norm_key "${raw%%:*}")"
604
650
  key="$(norm_key "${raw#*:}")"
605
- [ -n "$cat" ] && [ -n "$key" ] || die "forget: KEY must be category:key with neither part empty, got '$raw'"
651
+ [ -n "$cat" ] && [ -n "$key" ] || die "$cmd: KEY must be category:key with neither part empty, got '$raw'"
606
652
  FORGET_CANON="$cat:$key"
607
653
  }
608
654
 
@@ -822,6 +868,404 @@ do_forget() { # do_forget <repo> <category:key>... [--dry-run] [--json] [--actor
822
868
  return "$status"
823
869
  }
824
870
 
871
+ # --- add / edit ---------------------------------------------------------------
872
+ # A person writes one ledger row (role person, run id manual-<epoch>) and rebuild runs.
873
+ # Column 12 is paths, comma-joined, empty when there are none. Rows of 11 columns still
874
+ # read as before; only edit reads column 12. Refusals die before either file is written.
875
+
876
+ # Text is one line, 1..300 characters, with no tab. Checked before sanitize, which is what
877
+ # do_record runs next. Dies with one forge: line.
878
+ refuse_memory_text() { # refuse_memory_text <cmd> <text>
879
+ local cmd="$1" text="$2" n cleaned
880
+ case "$text" in
881
+ *$'\n'*|*$'\t'*) die "$cmd: text must be one line without a tab" ;;
882
+ esac
883
+ n=${#text}
884
+ if [ "$n" -lt 1 ] || [ "$n" -gt 300 ]; then
885
+ die "$cmd: text must be 1 to 300 characters"
886
+ fi
887
+ cleaned="$(sanitize "$text")"
888
+ [ -n "$cleaned" ] || die "$cmd: text must be 1 to 300 characters"
889
+ }
890
+
891
+ # 0 when a path can sit in column 12 and be parsed back out of a trailing [anchor].
892
+ # anchor_of stops at the first '[' or ']', so a path like app/[id]/page.tsx would be
893
+ # stored and then never go stale. Same rule as check_memory_path, without the message.
894
+ memory_path_ok() { # memory_path_ok <path>
895
+ local p="$1" rest part
896
+ [ -n "$p" ] || return 1
897
+ [ "${#p}" -le 300 ] || return 1
898
+ case "$p" in
899
+ *$'\n'*|*$'\t'*|*,*|*'['*|*']'*|/*) return 1 ;;
900
+ esac
901
+ rest="$p"
902
+ while [ -n "$rest" ]; do
903
+ part="${rest%%/*}"
904
+ if [ "$part" = ".." ]; then return 1; fi
905
+ case "$rest" in
906
+ */*) rest="${rest#*/}" ;;
907
+ *) rest="" ;;
908
+ esac
909
+ done
910
+ return 0
911
+ }
912
+
913
+ # A path stored in column 12 or used as an anchor: relative, no .. component, at most
914
+ # 300 characters, and none of the characters that would break the column, the line,
915
+ # or anchor_of's bracket match.
916
+ check_memory_path() { # check_memory_path <cmd> <path>
917
+ local cmd="$1" p="$2" rest part
918
+ [ -n "$p" ] || die "$cmd: path is empty"
919
+ [ "${#p}" -le 300 ] || die "$cmd: path is longer than 300 characters"
920
+ case "$p" in
921
+ *$'\n'*|*$'\t'*|*,*) die "$cmd: path must not contain a tab, newline or comma" ;;
922
+ *'['*|*']'*) die "$cmd: path must not contain '[' or ']'" ;;
923
+ /*) die "$cmd: path must be relative" ;;
924
+ esac
925
+ rest="$p"
926
+ while [ -n "$rest" ]; do
927
+ part="${rest%%/*}"
928
+ if [ "$part" = ".." ]; then die "$cmd: path must not contain '..'"; fi
929
+ case "$rest" in
930
+ */*) rest="${rest#*/}" ;;
931
+ *) rest="" ;;
932
+ esac
933
+ done
934
+ }
935
+
936
+ # First-seen order, at most 20 distinct paths that memory_path_ok accepts. A --path
937
+ # argument is refused before it gets here. An old column-12 entry or anchor that fails
938
+ # the same rule is omitted: it was not typed as --path, and refusing the edit would
939
+ # leave that learning uncorrectable. Returns 1 when more than 20 remain.
940
+ # Sets MEM_PATHS (csv) and MEM_FIRST (the anchor to append, or empty).
941
+ collect_paths() {
942
+ local p f n=0
943
+ MEM_PATHS=""
944
+ MEM_FIRST=""
945
+ [ "$#" -gt 0 ] || return 0
946
+ f="$(mktemp "${TMPDIR:-/tmp}/forge-memory-paths.XXXXXX")" || die "memory: no scratch file"
947
+ : > "$f"
948
+ for p in "$@"; do
949
+ memory_path_ok "$p" || continue
950
+ if grep -F -x -q -- "$p" "$f"; then continue; fi
951
+ n=$((n + 1))
952
+ if [ "$n" -gt 20 ]; then
953
+ rm -f "$f"
954
+ MEM_PATHS=""
955
+ MEM_FIRST=""
956
+ return 1
957
+ fi
958
+ printf '%s\n' "$p" >> "$f"
959
+ [ -n "$MEM_FIRST" ] || MEM_FIRST="$p"
960
+ done
961
+ while IFS= read -r p; do
962
+ [ -n "$p" ] || continue
963
+ if [ -n "$MEM_PATHS" ]; then MEM_PATHS="$MEM_PATHS,$p"; else MEM_PATHS="$p"; fi
964
+ done < "$f"
965
+ rm -f "$f"
966
+ }
967
+
968
+ # Sanitize, append the first path as [anchor] when the text has none, then clamp and
969
+ # key the same way do_record does. Sets MEM_TEXT and MEM_KEY.
970
+ prepare_memory_text() { # prepare_memory_text <cmd> <text> <first-path>
971
+ local cmd="$1" text="$2" first="$3"
972
+ refuse_memory_text "$cmd" "$text"
973
+ text="$(sanitize "$text")"
974
+ if [ -n "$first" ] && [ -z "$(anchor_of "$text")" ]; then
975
+ text="$text [$first]"
976
+ fi
977
+ MEM_TEXT="$(clamp_fact "$text")"
978
+ MEM_KEY="$(norm_key "$(strip_anchor "$MEM_TEXT")")"
979
+ [ -n "$MEM_KEY" ] || die "$cmd: text has nothing to keep"
980
+ }
981
+
982
+ # One person row. The header matches do_record when the file is missing or empty;
983
+ # an existing header is left as it is. The data row always has the 12th column.
984
+ # forget_filter keeps a ledger whose last line has no newline. The append below would
985
+ # glue this row onto that line, so a non-empty ledger is given its missing newline first.
986
+ write_person_row() { # write_person_row <ledger> <category> <paths-csv>
987
+ local led="$1" cat="$2" paths="$3" ts run_id
988
+ ts="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
989
+ run_id="manual-$(date +%s)"
990
+ mkdir -p "$(dirname "$led")"
991
+ if [ ! -s "$led" ]; then
992
+ printf '# ts\trun_id\ttask\trole\tmodel\tverdict\tcategory\tkey\ttext\tduration_s\tinjectable\n' > "$led" \
993
+ || return 1
994
+ else
995
+ ensure_trailing_newline "$led" || return 1
996
+ fi
997
+ printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \
998
+ "$ts" "$run_id" "-" "person" "-" "-" "$cat" "$MEM_KEY" "$MEM_TEXT" "0" "1" "$paths" >> "$led"
999
+ }
1000
+
1001
+ ensure_trailing_newline() {
1002
+ python3 - "$1" <<'PY'
1003
+ import sys
1004
+ path = sys.argv[1]
1005
+ with open(path, 'rb') as handle:
1006
+ data = handle.read()
1007
+ if data and not data.endswith(b'\n'):
1008
+ with open(path, 'ab') as handle:
1009
+ handle.write(b'\n')
1010
+ PY
1011
+ }
1012
+
1013
+ # Paths of one learning, in ledger order: each row's column 12, then that row's anchor.
1014
+ # Prints how many rows matched. The category:key is the form parse_forget_key stores.
1015
+ edit_old_paths() { # edit_old_paths <ledger> <canon> <out>
1016
+ python3 - "$@" <<'PY'
1017
+ import re
1018
+ import sys
1019
+ ledger_path, canon, out_path = sys.argv[1:4]
1020
+ cat, _, key = canon.partition(':')
1021
+ anchor = re.compile(r'\[([^\[\]]+)\]\s*$')
1022
+ found = 0
1023
+ paths = []
1024
+ with open(ledger_path, 'rb') as handle:
1025
+ data = handle.read()
1026
+ for line in data.splitlines():
1027
+ if line.startswith(b'#') or line.count(b'\t') < 8:
1028
+ continue
1029
+ cols = line.split(b'\t')
1030
+ if len(cols) < 9:
1031
+ continue
1032
+ if cols[6].decode('utf-8', 'surrogateescape') != cat:
1033
+ continue
1034
+ if cols[7].decode('utf-8', 'surrogateescape') != key:
1035
+ continue
1036
+ found += 1
1037
+ if len(cols) >= 12 and cols[11]:
1038
+ for part in cols[11].decode('utf-8', 'surrogateescape').split(','):
1039
+ if part:
1040
+ paths.append(part)
1041
+ text = cols[8].decode('utf-8', 'surrogateescape')
1042
+ match = anchor.search(text)
1043
+ if match:
1044
+ paths.append(match.group(1))
1045
+ with open(out_path, 'wb') as handle:
1046
+ for path in paths:
1047
+ handle.write(path.encode('utf-8', 'surrogateescape') + b'\n')
1048
+ sys.stdout.write('%d\n' % found)
1049
+ PY
1050
+ }
1051
+
1052
+ # `- ` lines gained and lost between two rebuilds. forget_removed is the multiset
1053
+ # difference in the first file's order; swapping the files is the lines that were added.
1054
+ memory_line_changes() { # memory_line_changes <before> <after> <added-out> <removed-out>
1055
+ forget_removed "$1" "$2" "$4" || return 1
1056
+ forget_removed "$2" "$1" "$3" || return 1
1057
+ }
1058
+
1059
+ memory_change_report() { # memory_change_report <json 0|1> <added|edited> <category:key> <added> <removed>
1060
+ if [ "$1" = 1 ]; then
1061
+ python3 - "$3" "$4" "$5" <<'PY'
1062
+ import json
1063
+ import sys
1064
+ key, added_path, removed_path = sys.argv[1:4]
1065
+
1066
+ def load(path):
1067
+ try:
1068
+ lines = open(path, encoding='utf-8').read().splitlines()
1069
+ except FileNotFoundError:
1070
+ return []
1071
+ return [line for line in lines if line]
1072
+
1073
+ json.dump({"ok": True, "key": key, "memory_lines_added": load(added_path),
1074
+ "memory_lines_removed": load(removed_path)}, sys.stdout)
1075
+ sys.stdout.write('\n')
1076
+ PY
1077
+ else
1078
+ printf '%s %s\n' "$2" "$3"
1079
+ fi
1080
+ }
1081
+
1082
+ do_add() { # do_add <repo> --category C --text TEXT [--path P]... [--actor ui|cli] [--json]
1083
+ local repo="" cat="" text="" actor="cli" as_json=0 have_text=0 scratch="" led mem status=0 p
1084
+ local -a paths=()
1085
+ while [ $# -gt 0 ]; do
1086
+ case "$1" in
1087
+ -h|--help) memory_usage; exit 0 ;;
1088
+ --json) as_json=1; shift ;;
1089
+ --category)
1090
+ [ $# -ge 2 ] || die "add: --category needs verify, trap or finding"
1091
+ cat="$2"; shift 2
1092
+ case "$cat" in
1093
+ verify|trap|finding) ;;
1094
+ *) die "add: --category must be verify, trap or finding" ;;
1095
+ esac
1096
+ ;;
1097
+ --text)
1098
+ [ $# -ge 2 ] || die "add: --text needs a value"
1099
+ text="$2"; have_text=1; shift 2
1100
+ ;;
1101
+ --path)
1102
+ [ $# -ge 2 ] || die "add: --path needs a value"
1103
+ paths+=("$2"); shift 2
1104
+ ;;
1105
+ --actor)
1106
+ [ $# -ge 2 ] || die "add: --actor needs ui or cli"
1107
+ actor="$2"; shift 2
1108
+ case "$actor" in
1109
+ ui|cli) ;;
1110
+ *) die "add: --actor must be ui or cli" ;;
1111
+ esac
1112
+ ;;
1113
+ --) shift; break ;;
1114
+ -*) die "add: unknown option '$1'" ;;
1115
+ *)
1116
+ [ -z "$repo" ] || die "add: unexpected argument '$1'"
1117
+ repo="$1"; shift
1118
+ ;;
1119
+ esac
1120
+ done
1121
+ while [ $# -gt 0 ]; do
1122
+ [ -z "$repo" ] || die "add: unexpected argument '$1'"
1123
+ repo="$1"; shift
1124
+ done
1125
+ [ -n "$repo" ] && [ -n "$cat" ] && [ "$have_text" = 1 ] \
1126
+ || die "add: usage: add <repo> --category verify|trap|finding --text TEXT [--path P]... [--actor ui|cli] [--json]"
1127
+ [ -d "$repo" ] || die "add: '$repo' is not a directory"
1128
+ [ "${#paths[@]}" -le 20 ] || die "add: at most 20 paths"
1129
+ if [ "${#paths[@]}" -gt 0 ]; then
1130
+ for p in "${paths[@]}"; do check_memory_path add "$p"; done
1131
+ collect_paths "${paths[@]}" || die "add: at most 20 paths"
1132
+ else
1133
+ MEM_PATHS=""
1134
+ MEM_FIRST=""
1135
+ fi
1136
+ # Text, paths and the key are settled before any file in the repo is created.
1137
+ prepare_memory_text add "$text" "$MEM_FIRST"
1138
+ scratch="$(mktemp -d "${TMPDIR:-/tmp}/forge-memory-add.XXXXXX")" || die "add: no scratch dir"
1139
+ led="$(ledger_for "$repo")"
1140
+ mem="$(memory_for "$repo")"
1141
+ if [ -f "$led" ]; then
1142
+ rebuild "$repo" "$scratch/before.md" "$led" >/dev/null \
1143
+ || forget_fail "$scratch" "add: could not preview memory"
1144
+ fi
1145
+ mkdir -p "$(dir_for "$repo")"
1146
+ write_person_row "$led" "$cat" "$MEM_PATHS" \
1147
+ || forget_fail "$scratch" "add: could not write the ledger"
1148
+ rebuild "$repo" >/dev/null || forget_fail "$scratch" "add: could not rebuild memory"
1149
+ memory_line_changes "$scratch/before.md" "$mem" "$scratch/added" "$scratch/removed" \
1150
+ || forget_fail "$scratch" "add: could not compare memory"
1151
+ memory_dataset_event memory_add "$repo" "" --set "key=$cat:$MEM_KEY" --set "actor=$actor"
1152
+ memory_change_report "$as_json" added "$cat:$MEM_KEY" "$scratch/added" "$scratch/removed" || status=$?
1153
+ rm -rf "$scratch"
1154
+ return "$status"
1155
+ }
1156
+
1157
+ do_edit() { # do_edit <repo> <category:key> --text TEXT [--path P]... [--actor ui|cli] [--json]
1158
+ local repo="" rawkey="" text="" actor="cli" as_json=0 have_text=0
1159
+ local scratch="" led mem status=0 p count cat total tmp
1160
+ local -a paths=() union=()
1161
+ while [ $# -gt 0 ]; do
1162
+ case "$1" in
1163
+ -h|--help) memory_usage; exit 0 ;;
1164
+ --json) as_json=1; shift ;;
1165
+ --text)
1166
+ [ $# -ge 2 ] || die "edit: --text needs a value"
1167
+ text="$2"; have_text=1; shift 2
1168
+ ;;
1169
+ --path)
1170
+ [ $# -ge 2 ] || die "edit: --path needs a value"
1171
+ paths+=("$2"); shift 2
1172
+ ;;
1173
+ --actor)
1174
+ [ $# -ge 2 ] || die "edit: --actor needs ui or cli"
1175
+ actor="$2"; shift 2
1176
+ case "$actor" in
1177
+ ui|cli) ;;
1178
+ *) die "edit: --actor must be ui or cli" ;;
1179
+ esac
1180
+ ;;
1181
+ --) shift; break ;;
1182
+ -*) die "edit: unknown option '$1'" ;;
1183
+ *)
1184
+ if [ -z "$repo" ]; then repo="$1"
1185
+ elif [ -z "$rawkey" ]; then rawkey="$1"
1186
+ else die "edit: unexpected argument '$1'"
1187
+ fi
1188
+ shift
1189
+ ;;
1190
+ esac
1191
+ done
1192
+ while [ $# -gt 0 ]; do
1193
+ if [ -z "$repo" ]; then repo="$1"
1194
+ elif [ -z "$rawkey" ]; then rawkey="$1"
1195
+ else die "edit: unexpected argument '$1'"
1196
+ fi
1197
+ shift
1198
+ done
1199
+ [ -n "$repo" ] && [ -n "$rawkey" ] && [ "$have_text" = 1 ] \
1200
+ || die "edit: usage: edit <repo> <category:key> --text TEXT [--path P]... [--actor ui|cli] [--json]"
1201
+ [ -d "$repo" ] || die "edit: '$repo' is not a directory"
1202
+ [ "${#paths[@]}" -le 20 ] || die "edit: at most 20 paths"
1203
+ if [ "${#paths[@]}" -gt 0 ]; then
1204
+ for p in "${paths[@]}"; do check_memory_path edit "$p"; done
1205
+ fi
1206
+ # Same parser forget uses, so Trap:Foo_Bar is the ledger's trap:foo bar.
1207
+ parse_forget_key "$rawkey" edit
1208
+ refuse_memory_text edit "$text"
1209
+ led="$(ledger_for "$repo")"
1210
+ [ -f "$led" ] || die "edit: no ledger row for '$FORGET_CANON'"
1211
+ scratch="$(mktemp -d "${TMPDIR:-/tmp}/forge-memory-edit.XXXXXX")" || die "edit: no scratch dir"
1212
+ count="$(edit_old_paths "$led" "$FORGET_CANON" "$scratch/oldpaths")" \
1213
+ || forget_fail "$scratch" "edit: could not read '$led'"
1214
+ case "$count" in
1215
+ ''|*[!0-9]*) forget_fail "$scratch" "edit: could not read '$led'" ;;
1216
+ 0) forget_fail "$scratch" "edit: no ledger row for '$FORGET_CANON'" ;;
1217
+ esac
1218
+ if [ -s "$scratch/oldpaths" ]; then
1219
+ while IFS= read -r p; do
1220
+ [ -n "$p" ] || continue
1221
+ union+=("$p")
1222
+ done < "$scratch/oldpaths"
1223
+ fi
1224
+ if [ "${#paths[@]}" -gt 0 ]; then
1225
+ for p in "${paths[@]}"; do union+=("$p"); done
1226
+ fi
1227
+ # Old paths that cannot be an anchor were dropped inside collect_paths. What remains,
1228
+ # including every new --path, is still at most 20. Past that, write nothing.
1229
+ if [ "${#union[@]}" -gt 0 ]; then
1230
+ collect_paths "${union[@]}" || forget_fail "$scratch" "edit: at most 20 paths"
1231
+ else
1232
+ MEM_PATHS=""
1233
+ MEM_FIRST=""
1234
+ fi
1235
+ prepare_memory_text edit "$text" "$MEM_FIRST"
1236
+ # The category is the one in the key. edit has no way to file the text elsewhere.
1237
+ cat="${FORGET_CANON%%:*}"
1238
+ mem="$(memory_for "$repo")"
1239
+ rebuild "$repo" "$scratch/before.md" "$led" >/dev/null \
1240
+ || forget_fail "$scratch" "edit: could not preview memory"
1241
+ printf '%s\n' "$FORGET_CANON" > "$scratch/keys"
1242
+ total="$(forget_filter "$led" "$scratch/keys" "$scratch/ledger.new" "$scratch/counts")" \
1243
+ || forget_fail "$scratch" "edit: could not read '$led'"
1244
+ case "$total" in
1245
+ ''|*[!0-9]*) forget_fail "$scratch" "edit: could not read '$led'" ;;
1246
+ 0) forget_fail "$scratch" "edit: no ledger row for '$FORGET_CANON'" ;;
1247
+ esac
1248
+ # One rewrite of the ledger, then one rebuild of memory.md. The preview above
1249
+ # writes only the scratch copy used to name the lines that changed.
1250
+ ensure_trailing_newline "$scratch/ledger.new" \
1251
+ || forget_fail "$scratch" "edit: could not write the ledger"
1252
+ write_person_row "$scratch/ledger.new" "$cat" "$MEM_PATHS" \
1253
+ || forget_fail "$scratch" "edit: could not write the ledger"
1254
+ tmp="$(mktemp "$(dir_for "$repo")/ledger.tsv.tmp.XXXXXX")" \
1255
+ || forget_fail "$scratch" "edit: could not write the ledger"
1256
+ { cp -p "$led" "$tmp" && cat "$scratch/ledger.new" > "$tmp"; } \
1257
+ || { rm -f "$tmp"; forget_fail "$scratch" "edit: could not write the ledger"; }
1258
+ mv -f "$tmp" "$led" \
1259
+ || { rm -f "$tmp"; forget_fail "$scratch" "edit: could not replace the ledger"; }
1260
+ rebuild "$repo" >/dev/null || forget_fail "$scratch" "edit: could not rebuild memory"
1261
+ memory_line_changes "$scratch/before.md" "$mem" "$scratch/added" "$scratch/removed" \
1262
+ || forget_fail "$scratch" "edit: could not compare memory"
1263
+ memory_dataset_event memory_edit "$repo" "" --set "key=$cat:$MEM_KEY" --set "actor=$actor"
1264
+ memory_change_report "$as_json" edited "$cat:$MEM_KEY" "$scratch/added" "$scratch/removed" || status=$?
1265
+ rm -rf "$scratch"
1266
+ return "$status"
1267
+ }
1268
+
825
1269
  # --- main ---------------------------------------------------------------------
826
1270
  memory_usage() {
827
1271
  cat <<'USAGE'
@@ -835,9 +1279,15 @@ usage: forge memory <command> <repo> [...] (scripts/forge-memory.sh)
835
1279
  inject <repo> <role> the block forge prepends to a planner, dwarf or qa prompt
836
1280
  forget <repo> <cat:key>... remove those learnings from the ledger and rebuild memory.md
837
1281
  (--dry-run, --json, --actor ui|cli); a missing key is not an error
1282
+ add <repo> --category C --text T
1283
+ append one learning (C is verify, trap or finding) and rebuild;
1284
+ a finding is kept at once (--path P, repeatable; --actor ui|cli; --json)
1285
+ edit <repo> <cat:key> --text T
1286
+ replace that learning and rebuild once, keeping its paths
1287
+ (--path P, --actor ui|cli, --json); an unknown key is an error
838
1288
  USAGE
839
1289
  }
840
- [ $# -ge 1 ] || die "usage: forge-memory.sh <inject|note|record|show|prune|spend|learnings|forget> [repo] [...]"
1290
+ [ $# -ge 1 ] || die "usage: forge-memory.sh <inject|note|record|show|prune|spend|learnings|forget|add|edit> [repo] [...]"
841
1291
  CMD="$1"; shift
842
1292
  case "$CMD" in
843
1293
  -h|--help|help) memory_usage; exit 0 ;;
@@ -850,5 +1300,7 @@ case "$CMD" in
850
1300
  prune) do_prune "${1:?prune needs a repo}" >/dev/null
851
1301
  do_inject "${1}" dwarf ;;
852
1302
  forget) do_forget "$@" ;;
1303
+ add) do_add "$@" ;;
1304
+ edit) do_edit "$@" ;;
853
1305
  *) die "unknown subcommand '$CMD'" ;;
854
1306
  esac
@@ -40,8 +40,9 @@
40
40
  # (internal; merge a PASS group's members with one merge, #140)
41
41
  # forge-parallel.sh _qa_only <plan-dir> <task-id> (internal; exit 0 when the next entry only re-runs QA)
42
42
  # forge-parallel.sh _waves <plan-dir> (internal; rewrite waves.tsv after a live `forge control add`)
43
- # forge-parallel.sh _sweep <plan-dir> --severity Pn [--plausible] [--max N]
44
- # (internal; plan the finding sweep, print its task ids)
43
+ # forge-parallel.sh _sweep <plan-dir> --severity Pn [--plausible] [--max N] [--check]
44
+ # (internal; plan a finding sweep round, print its task ids;
45
+ # --check only counts what a round would sweep)
45
46
  #
46
47
  # Routing flags (plan):
47
48
  # --dwarf <spec> fallback for any difficulty tier not named below
@@ -133,8 +134,9 @@
133
134
  # --sweep Pn once every task has merged, before verification: the open findings
134
135
  # at Pn or worse (tolerated, and PLAUSIBLE with --sweep-plausible) become
135
136
  # at most --sweep-max N fix tasks (default 5), one per file, each with a
136
- # narrow review; the sweep plan is printed and kept in sweep/. Once per
137
- # plan; what it does not fix stays for `forge issues`
137
+ # narrow review; the sweep plan is printed and kept in sweep/. A rerun
138
+ # that merged new findings sweeps them in a next round, never the same
139
+ # finding twice; what it does not fix stays for `forge issues`
138
140
  # --sweep-ahead a task is also told the open findings in files it owns, to fix only
139
141
  # on its way (kept for the plan; --no-sweep-ahead turns it off)
140
142
  # --attribute when the run's combined verification fails, search the merge order for