@mmerterden/multi-agent-pipeline 20.40.0 → 20.42.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.
Files changed (143) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/README.md +5 -2
  3. package/README.tr.md +5 -2
  4. package/docs/adr/0019-product-tree.md +143 -0
  5. package/docs/adr/README.md +1 -0
  6. package/docs/ecosystem.md +51 -14
  7. package/docs/facts.json +7 -7
  8. package/docs/features.md +15 -4
  9. package/install/claude.mjs +45 -3
  10. package/install/templates/claude-hooks.json +23 -1
  11. package/manifest.json +146 -107
  12. package/package.json +3 -2
  13. package/pipeline/commands/multi-agent/autopilot/SKILL.md +11 -0
  14. package/pipeline/commands/multi-agent/review-analysis/SKILL.md +1 -1
  15. package/pipeline/commands/multi-agent/setup/SKILL.md +1 -1
  16. package/pipeline/contract/types/index.d.ts +53 -49
  17. package/pipeline/lib/args.mjs +131 -4
  18. package/pipeline/lib/bg-launch.mjs +5 -2
  19. package/pipeline/lib/context-budget.mjs +5 -42
  20. package/pipeline/lib/credential-store.sh +11 -1
  21. package/pipeline/lib/hook-once.mjs +134 -0
  22. package/pipeline/lib/hook-registration.mjs +5 -0
  23. package/pipeline/lib/isotonic.mjs +73 -0
  24. package/pipeline/lib/low-disk.mjs +153 -0
  25. package/pipeline/lib/mcp-schema-load.mjs +90 -0
  26. package/pipeline/lib/md2confluence-v3.py +19 -10
  27. package/pipeline/lib/model-dispatch.sh +26 -2
  28. package/pipeline/lib/normalize-text.mjs +135 -0
  29. package/pipeline/lib/outbound-gate.mjs +21 -3
  30. package/pipeline/lib/plan-todos.sh +17 -4
  31. package/pipeline/lib/redact.mjs +12 -3
  32. package/pipeline/lib/risky-settings.mjs +198 -0
  33. package/pipeline/lib/route-state.sh +1 -0
  34. package/pipeline/lib/secret-patterns.generated.mjs +6 -2
  35. package/pipeline/lib/session-usage.mjs +232 -0
  36. package/pipeline/lib/source-digest.mjs +211 -0
  37. package/pipeline/lib/tdd-evidence.mjs +250 -17
  38. package/pipeline/lib/tiered-budget.mjs +87 -0
  39. package/pipeline/lib/untrusted-fence.mjs +132 -1
  40. package/pipeline/multi-agent-refs/analysis/locked.md +1 -1
  41. package/pipeline/multi-agent-refs/analysis/review.md +23 -1
  42. package/pipeline/multi-agent-refs/features/code-graph.md +11 -1
  43. package/pipeline/multi-agent-refs/features/cost-analysis.md +37 -2
  44. package/pipeline/multi-agent-refs/features/doctor.md +82 -4
  45. package/pipeline/multi-agent-refs/features/model-fallback.md +25 -0
  46. package/pipeline/multi-agent-refs/features/plan-todos.md +4 -0
  47. package/pipeline/multi-agent-refs/features/product-tree.md +68 -0
  48. package/pipeline/multi-agent-refs/features/unattended-gates.md +5 -3
  49. package/pipeline/multi-agent-refs/features/unattended-security.md +88 -1
  50. package/pipeline/multi-agent-refs/features/usage-reporting.md +33 -0
  51. package/pipeline/multi-agent-refs/help/en.md +2 -1
  52. package/pipeline/multi-agent-refs/help/tr.md +2 -1
  53. package/pipeline/multi-agent-refs/knowledge.md +58 -0
  54. package/pipeline/multi-agent-refs/outside-the-pipeline.md +6 -0
  55. package/pipeline/multi-agent-refs/phases/phase-0-init.md +4 -0
  56. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +5 -1
  57. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
  58. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -2
  59. package/pipeline/multi-agent-refs/phases/phase-5-report.md +4 -0
  60. package/pipeline/multi-agent-refs/progress-contract.md +3 -1
  61. package/pipeline/office/index.html +13 -7
  62. package/pipeline/office/toolkit.json +1 -1
  63. package/pipeline/preferences-template.json +1 -0
  64. package/pipeline/rules/outside-the-pipeline.md +1 -1
  65. package/pipeline/schemas/doctor-report.schema.json +47 -0
  66. package/pipeline/schemas/learnings-ledger.schema.json +35 -2
  67. package/pipeline/schemas/office-archive.schema.json +225 -128
  68. package/pipeline/schemas/plan-todos.schema.json +29 -1
  69. package/pipeline/schemas/prefs.schema.json +146 -0
  70. package/pipeline/schemas/product-tree-overlay.schema.json +57 -0
  71. package/pipeline/schemas/product-tree.schema.json +136 -0
  72. package/pipeline/schemas/route-config.schema.json +51 -0
  73. package/pipeline/schemas/secret-patterns.json +17 -1
  74. package/pipeline/schemas/toolkit-path-params.json +15 -1
  75. package/pipeline/scripts/_cost-advise.mjs +357 -0
  76. package/pipeline/scripts/_cost-budget.mjs +78 -0
  77. package/pipeline/scripts/_cost.mjs +29 -0
  78. package/pipeline/scripts/_decode_text.py +107 -0
  79. package/pipeline/scripts/_eval-stats.mjs +182 -0
  80. package/pipeline/scripts/_guard-probe.mjs +406 -0
  81. package/pipeline/scripts/_guard_rules.py +336 -1
  82. package/pipeline/scripts/_learnings-promotion.mjs +229 -0
  83. package/pipeline/scripts/_locate.mjs +539 -0
  84. package/pipeline/scripts/_memory-policy.mjs +208 -33
  85. package/pipeline/scripts/_product-tree-extract.mjs +761 -0
  86. package/pipeline/scripts/_product-tree.mjs +923 -0
  87. package/pipeline/scripts/_retrieval.mjs +161 -4
  88. package/pipeline/scripts/_secret-scan.mjs +6 -1
  89. package/pipeline/scripts/_stack-routing.mjs +2 -0
  90. package/pipeline/scripts/_test-gaming.mjs +346 -0
  91. package/pipeline/scripts/_user_guard_rules.py +744 -0
  92. package/pipeline/scripts/agent-guard.py +69 -6
  93. package/pipeline/scripts/agent-guard.sh +8 -1
  94. package/pipeline/scripts/argv-secret-scan.mjs +2 -1
  95. package/pipeline/scripts/autopilot-loop.mjs +407 -0
  96. package/pipeline/scripts/autopilot-runner.mjs +38 -25
  97. package/pipeline/scripts/capture-resume.sh +9 -1
  98. package/pipeline/scripts/cost-analyze.mjs +66 -4
  99. package/pipeline/scripts/cost-budget-check.mjs +5 -13
  100. package/pipeline/scripts/disk-cleaner.mjs +1418 -0
  101. package/pipeline/scripts/doctor.mjs +324 -43
  102. package/pipeline/scripts/evidence-gate.mjs +90 -0
  103. package/pipeline/scripts/gate-ledger.mjs +76 -21
  104. package/pipeline/scripts/gc-tmp.sh +5 -0
  105. package/pipeline/scripts/graph-query.mjs +257 -17
  106. package/pipeline/scripts/guard-probe-known-holes.json +3 -0
  107. package/pipeline/scripts/learnings-ledger.mjs +680 -55
  108. package/pipeline/scripts/note-agent-event.mjs +2 -0
  109. package/pipeline/scripts/note-mcp-failure.mjs +363 -0
  110. package/pipeline/scripts/note-mcp-failure.sh +19 -0
  111. package/pipeline/scripts/note-skill-use.mjs +96 -23
  112. package/pipeline/scripts/office-archive.mjs +23 -10
  113. package/pipeline/scripts/office-memory.mjs +4 -1
  114. package/pipeline/scripts/persona-walk-anchors.mjs +443 -0
  115. package/pipeline/scripts/pre-commit-check.sh +2 -2
  116. package/pipeline/scripts/pre-push-check.sh +8 -1
  117. package/pipeline/scripts/product-tree-eval.mjs +685 -0
  118. package/pipeline/scripts/product-tree.mjs +544 -0
  119. package/pipeline/scripts/publish-staged.mjs +324 -0
  120. package/pipeline/scripts/route-learn.mjs +628 -0
  121. package/pipeline/scripts/run-scope-guard.mjs +55 -1
  122. package/pipeline/scripts/scan-agent-config.sh +1 -1
  123. package/pipeline/scripts/statusline.mjs +309 -0
  124. package/pipeline/scripts/test-integrity-gate.mjs +97 -2
  125. package/pipeline/scripts/triage-memory.mjs +12 -4
  126. package/pipeline/scripts/uninstall.mjs +1 -0
  127. package/pipeline/skills/.skill-manifest.json +15 -7
  128. package/pipeline/skills/.skills-index.json +25 -3
  129. package/pipeline/skills/shared/README.md +6 -4
  130. package/pipeline/skills/shared/core/google-play-compliance/references/examples.md +1 -1
  131. package/pipeline/skills/shared/core/multi-agent-review-analysis/SKILL.md +1 -1
  132. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  133. package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +105 -0
  134. package/pipeline/skills/shared/external/disk-cleaner/evals/evals.json +62 -0
  135. package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +1418 -0
  136. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  137. package/pipeline/skills/shared/external/spec-persona-walk/SKILL.md +118 -0
  138. package/pipeline/skills/shared/external/spec-persona-walk/evals/evals.json +50 -0
  139. package/pipeline/skills/shared/external/spec-persona-walk/scripts/persona-walk-anchors.mjs +443 -0
  140. package/pipeline/skills/shared/external/storekit/SKILL.md +1 -1
  141. package/pipeline/skills/shared/external/swiftdata/SKILL.md +1 -1
  142. package/pipeline/skills/skill-copies.json +9 -1
  143. package/pipeline/skills/skills-index.md +4 -2
@@ -25,6 +25,7 @@ a body is where a commit message usually is.
25
25
  read_only_* a commit, push or file write into a repository
26
26
  listed in prefs.global.readOnlyRepos
27
27
  """
28
+ import fnmatch
28
29
  import hashlib
29
30
  import json
30
31
  import os
@@ -609,10 +610,321 @@ def _cleanup_ask(argv):
609
610
  return f"{name} deletes run logs or worktrees for good; the user confirms each clean-up"
610
611
 
611
612
 
613
+ PRODUCT_TREE_OVERLAY_NAME = "product-tree-overlay.jsonl"
614
+
615
+ PRODUCT_TREE_OVERLAY_WRITE = re.compile(
616
+ r"(?:>>?|\btee\b[^;&|]*?)\s*['\"]?[^\s;&|'\"]*product-tree-overlay\.jsonl",
617
+ re.I,
618
+ )
619
+
620
+ # product-tree.mjs flags that take the next token as their value; every other
621
+ # flag stands alone, so the token after it can be the subcommand.
622
+ PRODUCT_TREE_VALUE_FLAGS = {
623
+ "--tree", "--root", "--out", "--graph", "--stack", "--max-chars",
624
+ "--kind", "--name", "--id", "--parent", "--note",
625
+ }
626
+
627
+ PRODUCT_TREE_DECISIONS = ("agree", "reject")
628
+
629
+ SCRIPT_RUNNERS = {"node", "nodejs", "bun", "deno", "tsx", "ts-node"}
630
+
631
+ # Commands that only read a file they name; naming the overlay to one of them
632
+ # writes nothing.
633
+ OVERLAY_READERS = {
634
+ "cat", "head", "tail", "less", "more", "wc", "grep", "egrep", "fgrep", "rg",
635
+ "jq", "ls", "stat", "file", "diff", "cmp", "shasum", "sha256sum", "md5", "md5sum",
636
+ }
637
+
638
+
639
+ def _names_overlay(tok, cwd=None):
640
+ """True when a token names the overlay: its casefolded text holds the
641
+ overlay's name, or it is a path whose real target is the overlay."""
642
+ folded = tok.casefold()
643
+ if PRODUCT_TREE_OVERLAY_NAME in folded:
644
+ return True
645
+ if tok.startswith("-") or not tok or len(tok) > 4096:
646
+ return False
647
+ path = tok.split("=", 1)[1] if re.match(r"^[a-z]+=", tok) else tok
648
+ path = os.path.expanduser(path)
649
+ try:
650
+ real = os.path.realpath(os.path.join(cwd or os.getcwd(), path))
651
+ except (OSError, ValueError):
652
+ return False
653
+ return os.path.basename(real).casefold() == PRODUCT_TREE_OVERLAY_NAME
654
+
655
+
656
+ def _product_tree_decision(argv):
657
+ """The decision a product-tree invocation records, or None. A token named
658
+ product-tree.mjs is followed past its flags to the subcommand; a variable
659
+ there could expand to either decision. Any script run through node and
660
+ friends, or a .mjs/.js file run directly, that carries an agree or reject
661
+ token is treated the same, which covers a copy of the script under
662
+ another name."""
663
+ for i, tok in enumerate(argv):
664
+ base = os.path.basename(tok)
665
+ if base == "product-tree.mjs":
666
+ rest = argv[i + 1:]
667
+ j = 0
668
+ while j < len(rest) and rest[j].startswith("-"):
669
+ flag = rest[j].split("=", 1)[0]
670
+ j += 2 if flag in PRODUCT_TREE_VALUE_FLAGS and "=" not in rest[j] else 1
671
+ if j < len(rest) and (rest[j] in PRODUCT_TREE_DECISIONS or rest[j].startswith("$")):
672
+ return rest[j] if rest[j] in PRODUCT_TREE_DECISIONS else "agree or reject"
673
+ if base in SCRIPT_RUNNERS or re.search(r"\.(?:mjs|cjs|js)$", base):
674
+ for later in argv[i + 1:]:
675
+ if later in PRODUCT_TREE_DECISIONS:
676
+ return later
677
+ return None
678
+
679
+
680
+ def _product_tree_ask(argv, seg, cwd=None):
681
+ """An agree or reject on a product-tree proposal, or a direct write to its
682
+ overlay, records a person's decision. The script's own terminal check does
683
+ not hold against an agent that allocates a pseudo-terminal, so the person
684
+ confirms it here. Any command that names the overlay, by a casefolded
685
+ name or through a symlink, asks unless it only reads it."""
686
+ decision = _product_tree_decision(argv)
687
+ if decision:
688
+ return (
689
+ f"product-tree.mjs {decision} records a person's decision on the product tree; "
690
+ "the user runs it or confirms it"
691
+ )
692
+ overlay_write = (
693
+ "this writes the product tree overlay directly; only product-tree.mjs propose writes "
694
+ "it, and a decision is the user's"
695
+ )
696
+ if PRODUCT_TREE_OVERLAY_WRITE.search(seg):
697
+ return overlay_write
698
+ for m in re.finditer(r">>?\s*['\"]?([^\s;&|'\"<>]+)", seg):
699
+ if _names_overlay(m.group(1), cwd):
700
+ return overlay_write
701
+ if argv and os.path.basename(argv[0]) not in OVERLAY_READERS:
702
+ if any(_names_overlay(t, cwd) for t in argv[1:]):
703
+ return overlay_write
704
+ return None
705
+
706
+
707
+ def _learnings_ask(argv):
708
+ """promote --accept, promote --retract and feedback on a G: id write the
709
+ global learnings ledger or hide a global learning, a person's decision.
710
+ learnings-ledger.mjs asks y/N on a terminal, but a pseudo-terminal answers
711
+ that prompt as well as a person does, so the user confirms it here."""
712
+ for i, tok in enumerate(argv):
713
+ if os.path.basename(tok) != "learnings-ledger.mjs":
714
+ continue
715
+ rest = argv[i + 1:]
716
+ if not rest:
717
+ return None
718
+ flags = [a.split("=", 1)[0] for a in rest[1:]]
719
+ if rest[0] == "promote" and ("--accept" in flags or "--retract" in flags):
720
+ what = "promote --accept" if "--accept" in flags else "promote --retract"
721
+ elif rest[0] == "feedback":
722
+ ids = _flag_values(rest[1:], {"--id"}, None)
723
+ if not any(str(v).strip("[]").upper().startswith(("G:", "$")) for v in ids):
724
+ return None
725
+ what = "feedback on a G: id"
726
+ else:
727
+ return None
728
+ return (
729
+ f"learnings-ledger.mjs {what} changes a global learning every repository reads; "
730
+ "the user runs it or confirms it"
731
+ )
732
+ return None
733
+
734
+
735
+ HOME_VAR = re.compile(r"^(?:\$HOME|\$\{HOME\})(?=/|$)")
736
+ ROOT_DELETE = (
737
+ "rm -r on the filesystem root deletes everything this account can write; "
738
+ "the user confirms it"
739
+ )
740
+ HOME_DELETE = (
741
+ "rm -r on $HOME or a directory above it deletes every project, credential and setting "
742
+ "under home; the user confirms it"
743
+ )
744
+
745
+
746
+ def _rm_recursive(args):
747
+ for a in args:
748
+ if a == "--":
749
+ return False
750
+ if a == "--recursive" or (
751
+ a.startswith("-") and not a.startswith("--") and ("r" in a[1:] or "R" in a[1:])
752
+ ):
753
+ return True
754
+ return False
755
+
756
+
757
+ def _rm_operands(args):
758
+ out, ended = [], False
759
+ for a in args:
760
+ if not ended and a == "--":
761
+ ended = True
762
+ elif ended or not a.startswith("-"):
763
+ out.append(a)
764
+ return out
765
+
766
+
767
+ HOME_BRACED = re.compile(r"^\$\{HOME(?:(?P<op>:?[-=?+]|%%?|##?)(?P<word>[^}]*))?\}(?=/|$)")
768
+ TILDE_USER = re.compile(r"^~(?P<user>[A-Za-z0-9_][A-Za-z0-9_.-]*)(?=/|$)")
769
+
770
+
771
+ def _user_home(user):
772
+ """The home directory ~user names, or None when no such account exists
773
+ (the shell then leaves ~user as a literal relative name)."""
774
+ try:
775
+ import pwd
776
+ except ImportError:
777
+ return None
778
+ try:
779
+ return pwd.getpwnam(user).pw_dir or None
780
+ except KeyError:
781
+ return None
782
+
783
+
784
+ def _trim(value, pattern, op):
785
+ """${HOME%pat}, ${HOME%%pat}, ${HOME#pat} and ${HOME##pat} on value, the
786
+ pattern matched as a shell glob."""
787
+ n = len(value)
788
+ if op in ("%", "%%"):
789
+ cuts = range(n, -1, -1) if op == "%" else range(0, n + 1)
790
+ for i in cuts:
791
+ if fnmatch.fnmatchcase(value[i:], pattern):
792
+ return value[:i]
793
+ else:
794
+ cuts = range(0, n + 1) if op == "#" else range(n, -1, -1)
795
+ for i in cuts:
796
+ if fnmatch.fnmatchcase(value[:i], pattern):
797
+ return value[i:]
798
+ return value
799
+
800
+
801
+ def _home_expansion(tok, home):
802
+ """tok with a leading $HOME form replaced by what the shell expands it to:
803
+ $HOME, ${HOME}, ${HOME:?..}, ${HOME:-..}, ${HOME:=..} (home is set, so
804
+ each is home), ${HOME:+word} (the word), the trims ${HOME%pat} and the
805
+ like, ~ and ~user. Anything else comes back unchanged."""
806
+ if tok == "~" or tok.startswith("~/"):
807
+ return home + tok[1:]
808
+ m = TILDE_USER.match(tok)
809
+ if m:
810
+ user_home = _user_home(m.group("user"))
811
+ return tok if user_home is None else user_home + tok[m.end():]
812
+ m = HOME_VAR.match(tok)
813
+ if m:
814
+ return home + tok[m.end():]
815
+ m = HOME_BRACED.match(tok)
816
+ if not m:
817
+ return tok
818
+ op, word, rest = m.group("op"), m.group("word") or "", tok[m.end():]
819
+ if not op:
820
+ return home + rest
821
+ if op.endswith("+"):
822
+ return word + rest
823
+ if op[0] in "%#":
824
+ if "$" in word or "`" in word:
825
+ return tok
826
+ return _trim(home, word, op) + rest
827
+ return home + rest
828
+
829
+
830
+ def _rm_target(tok, cwd):
831
+ """The absolute, normalised path an rm operand names, or None when it
832
+ depends on something other than $HOME (another variable, a substitution)
833
+ or is relative with no known working directory. A trailing `*` or `.*`
834
+ component stands for the directory it lists."""
835
+ t = _home_expansion(tok, os.path.expanduser("~"))
836
+ if "$" in t or "`" in t:
837
+ return None
838
+ parts = t.rstrip("/").split("/") if t.rstrip("/") else [""]
839
+ while len(parts) > 1 and parts[-1] in ("*", ".*"):
840
+ parts.pop()
841
+ t = "/".join(parts) or "/"
842
+ if t in ("*", ".*"):
843
+ t = "."
844
+ if not os.path.isabs(t):
845
+ if not cwd:
846
+ return None
847
+ t = os.path.join(cwd, t)
848
+ return re.sub(r"^/+", "/", os.path.normpath(t))
849
+
850
+
851
+ def _destructive_rm_ask(argv, cwd):
852
+ """rm -r on the filesystem root, on $HOME, or on a directory above it.
853
+ Anything inside home or inside the project is an ordinary delete."""
854
+ if not argv or os.path.basename(argv[0]) != "rm":
855
+ return None
856
+ args = argv[1:]
857
+ if "--no-preserve-root" in args:
858
+ return ROOT_DELETE
859
+ if not _rm_recursive(args):
860
+ return None
861
+ homes = {
862
+ os.path.normpath(os.path.expanduser("~")),
863
+ os.path.realpath(os.path.expanduser("~")),
864
+ }
865
+ for tok in _rm_operands(args):
866
+ p = _rm_target(tok, cwd)
867
+ if p is None:
868
+ continue
869
+ if p == "/":
870
+ return ROOT_DELETE
871
+ named = TILDE_USER.match(tok)
872
+ owner = _user_home(named.group("user")) if named else None
873
+ for h in homes | ({os.path.normpath(owner)} if owner else set()):
874
+ if p == h or h.startswith(p.rstrip("/") + "/"):
875
+ return HOME_DELETE
876
+ return None
877
+
878
+
879
+ FORK_HEAD = re.compile(r"\(\s*\)\s*\{")
880
+ FORK_NAME_MAX = 64
881
+ FORK_NAME_STOP = set(" \t\n(){}|&;<>")
882
+ PERL_FORK_BOMB = re.compile(r"\bfork\s+while\s+fork\b")
883
+ FORK_BOMB = (
884
+ "a fork bomb: a function that starts two copies of itself in the background "
885
+ "exhausts the process table; the user confirms it"
886
+ )
887
+
888
+
889
+ def fork_bomb_reason(cmd):
890
+ """A shell function whose body pipes itself into itself in the background,
891
+ then is called (`:(){ :|:& };:`), or perl's `fork while fork`. Each
892
+ `(){` head is examined once with a bounded name, so the scan is linear."""
893
+ if not isinstance(cmd, str):
894
+ return None
895
+ if PERL_FORK_BOMB.search(cmd):
896
+ return FORK_BOMB
897
+ for m in FORK_HEAD.finditer(cmd):
898
+ end = m.start()
899
+ while end > 0 and cmd[end - 1] in " \t":
900
+ end -= 1
901
+ start = end
902
+ while start > 0 and end - start < FORK_NAME_MAX and cmd[start - 1] not in FORK_NAME_STOP:
903
+ start -= 1
904
+ name = cmd[start:end]
905
+ if not name:
906
+ continue
907
+ n = re.escape(name)
908
+ tail = re.compile(
909
+ r"\s*" + n + r"\s*\|\s*" + n + r"\s*&\s*;?\s*\}\s*;?\s*" + n + r"(?![^\s;&|])"
910
+ )
911
+ if tail.match(cmd, m.end()):
912
+ return FORK_BOMB
913
+ return None
914
+
915
+
612
916
  def ask_reason(toks, seg, cwd=None):
613
917
  """Why a person should confirm this segment, or None."""
614
918
  _, argv = command_word(toks)
615
- return _gh_ask(argv, cwd) or _jira_ask(argv, seg) or _shared_ask(argv, seg) or _cleanup_ask(argv)
919
+ return (
920
+ _gh_ask(argv, cwd)
921
+ or _jira_ask(argv, seg)
922
+ or _shared_ask(argv, seg)
923
+ or _cleanup_ask(argv)
924
+ or _product_tree_ask(argv, seg, cwd)
925
+ or _learnings_ask(argv)
926
+ or _destructive_rm_ask(argv, cwd)
927
+ )
616
928
 
617
929
 
618
930
  GH_TEXT_SUBS = {
@@ -676,6 +988,29 @@ def secret_echo_reason(cmd):
676
988
  return None
677
989
 
678
990
 
991
+ # The guard answers inside its own deadline, so it decodes less than the
992
+ # outbound gate: a command line longer than this is not a hiding place a
993
+ # reviewer would miss anyway.
994
+ GUARD_DECODE_LIMITS = {"maxInputChars": 64 * 1024, "maxDecodedChars": 64 * 1024}
995
+
996
+
997
+ def encoded_secret_read_reason(cmd):
998
+ """A stored-secret read hidden inside base64, hex or rot13 text
999
+ (_decode_text.py, bounded). Reading a secret has a plain spelling; an
1000
+ encoded one only hides it from review."""
1001
+ import _decode_text
1002
+
1003
+ if not isinstance(cmd, str) or not cmd:
1004
+ return None
1005
+ for v in _decode_text.decoded_variants(cmd, GUARD_DECODE_LIMITS):
1006
+ if SECRET_READ.search(v["text"]):
1007
+ return (
1008
+ "the command carries a stored-secret read hidden in " + v["kind"]
1009
+ + " text; run the read in plain text, where it can be judged"
1010
+ )
1011
+ return None
1012
+
1013
+
679
1014
  # --- the run this session drives ----------------------------------------------
680
1015
 
681
1016
 
@@ -0,0 +1,229 @@
1
+ /**
2
+ * @file _learnings-promotion.mjs - which per-repository learnings recur
3
+ * across repositories, as candidates for one global learning.
4
+ *
5
+ * eligibleEntries(slug, rows, feedbackById)
6
+ * the rows of one ledger that may stand as evidence:
7
+ * high confidence, not superseded, and never marked
8
+ * dead_end or corrected
9
+ * promotionCandidates(entries, globalRows, opts)
10
+ * entries of the same kind from two or more
11
+ * repositories whose statements score at or above the
12
+ * threshold pairwise (shingleSimilarity), one entry per
13
+ * repository per candidate, each tagged with the global
14
+ * row that already covers it, if any
15
+ * globalVisible(globalRow, slug, localRows)
16
+ * whether a global row belongs in this repository's
17
+ * brief and profile
18
+ *
19
+ * Pure: the caller reads the ledgers, decides which repositories are excluded
20
+ * from memory, and writes. Zero dependencies.
21
+ *
22
+ * @module pipeline/scripts/_learnings-promotion
23
+ */
24
+
25
+ import { shortId } from "./_retrieval.mjs";
26
+ import {
27
+ PROMOTION_SIMILARITY,
28
+ globalRowId,
29
+ ledgerRowId,
30
+ shingleProfile,
31
+ shingleSimilarity,
32
+ supersededBy,
33
+ } from "./_memory-policy.mjs";
34
+
35
+ const round = (n) => Math.round(n * 1000) / 1000;
36
+ const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
37
+
38
+ /**
39
+ * A promotion asks more of an entry than a brief does: one dead end or one
40
+ * correction is enough to keep it out, because the global ledger reaches
41
+ * every other repository and is never rewritten.
42
+ *
43
+ * @param {string} slug
44
+ * @param {object[]} rows ledger rows in file order
45
+ * @param {Map<string, Array<{outcome: string}>>} feedbackById
46
+ */
47
+ export function eligibleEntries(slug, rows, feedbackById) {
48
+ const by = supersededBy(rows);
49
+ const seen = new Set();
50
+ const out = [];
51
+ rows.forEach((r, i) => {
52
+ if (!r || typeof r.statement !== "string" || typeof r.kind !== "string") return;
53
+ if (by[i] !== null || r.confidence !== "high") return;
54
+ const id = ledgerRowId(r);
55
+ if (seen.has(id)) return;
56
+ const outcomes = feedbackById.get(id) ?? [];
57
+ if (outcomes.some((f) => f.outcome === "dead_end" || f.outcome === "corrected")) return;
58
+ seen.add(id);
59
+ out.push({ repo: slug, id, row: r, order: i, profile: shingleProfile(r.statement) });
60
+ });
61
+ return out;
62
+ }
63
+
64
+ const keyOf = (e) => `${e.repo}\u0000${e.id}`;
65
+
66
+ /** Lowest pairwise score inside a group of entries. */
67
+ function weakest(members, score) {
68
+ let low = 1;
69
+ for (let i = 0; i < members.length; i++)
70
+ for (let j = i + 1; j < members.length; j++) low = Math.min(low, score(members[i], members[j]));
71
+ return low;
72
+ }
73
+
74
+ /** Does `extra` join `group` without repeating a repository or a weak pair? */
75
+ function fits(group, extra, score, threshold) {
76
+ const repos = new Set(group.map((e) => e.repo));
77
+ if (extra.some((e) => repos.has(e.repo))) return false;
78
+ return group.every((g) => extra.every((e) => score(g, e) >= threshold));
79
+ }
80
+
81
+ /** The global row that already holds this group's learning, or null. */
82
+ function coveredBy(group, globals, threshold) {
83
+ const members = new Set(group.map((e) => `${e.repo}\u0000${e.id}`));
84
+ for (const g of globals) {
85
+ if (g.row.kind !== group[0].row.kind) continue;
86
+ const sources = Array.isArray(g.row.promoted_from?.sources) ? g.row.promoted_from.sources : [];
87
+ if (sources.some((s) => members.has(`${s?.repo}\u0000${s?.id}`))) return g.id;
88
+ if (group.some((e) => shingleSimilarity(g.profile, e.profile) >= threshold)) return g.id;
89
+ }
90
+ return null;
91
+ }
92
+
93
+ /**
94
+ * Candidates for promotion.
95
+ *
96
+ * Pairs from different repositories are joined strongest first. A group grows
97
+ * only while every pair inside it stays at or above the threshold and no
98
+ * repository appears twice, so a chain of loosely similar statements never
99
+ * collapses into one learning that no two of its members actually share.
100
+ *
101
+ * The candidate id is derived from its members, so an approval binds to the
102
+ * evidence it was shown: when a repository joins or leaves, the id changes and
103
+ * the earlier approval no longer applies.
104
+ *
105
+ * @param {ReturnType<typeof eligibleEntries>} entries
106
+ * @param {object[]} globalRows rows of the global ledger
107
+ * @param {{threshold?: number}} [opts]
108
+ */
109
+ export function promotionCandidates(
110
+ entries,
111
+ globalRows,
112
+ { threshold = PROMOTION_SIMILARITY } = {},
113
+ ) {
114
+ const cache = new Map();
115
+ const score = (a, b) => {
116
+ const k = keyOf(a) < keyOf(b) ? `${keyOf(a)}|${keyOf(b)}` : `${keyOf(b)}|${keyOf(a)}`;
117
+ if (!cache.has(k)) cache.set(k, shingleSimilarity(a.profile, b.profile));
118
+ return cache.get(k);
119
+ };
120
+ const ordered = entries.slice().sort((a, b) => cmp(a.repo, b.repo) || a.order - b.order);
121
+ const pairs = [];
122
+ for (let i = 0; i < ordered.length; i++)
123
+ for (let j = i + 1; j < ordered.length; j++) {
124
+ const a = ordered[i];
125
+ const b = ordered[j];
126
+ if (a.repo === b.repo || a.row.kind !== b.row.kind) continue;
127
+ const s = score(a, b);
128
+ if (s >= threshold) pairs.push({ a, b, s, i, j });
129
+ }
130
+ pairs.sort((x, y) => y.s - x.s || x.i - y.i || x.j - y.j);
131
+
132
+ const groupOf = new Map();
133
+ const groups = [];
134
+ for (const { a, b } of pairs) {
135
+ const ga = groupOf.get(keyOf(a));
136
+ const gb = groupOf.get(keyOf(b));
137
+ if (!ga && !gb) {
138
+ const g = [a, b];
139
+ groups.push(g);
140
+ groupOf.set(keyOf(a), g);
141
+ groupOf.set(keyOf(b), g);
142
+ } else if (ga && !gb) {
143
+ if (fits(ga, [b], score, threshold)) {
144
+ ga.push(b);
145
+ groupOf.set(keyOf(b), ga);
146
+ }
147
+ } else if (!ga && gb) {
148
+ if (fits(gb, [a], score, threshold)) {
149
+ gb.push(a);
150
+ groupOf.set(keyOf(a), gb);
151
+ }
152
+ } else if (ga !== gb && fits(ga, gb, score, threshold)) {
153
+ for (const e of gb) {
154
+ ga.push(e);
155
+ groupOf.set(keyOf(e), ga);
156
+ }
157
+ gb.length = 0;
158
+ }
159
+ }
160
+
161
+ const globals = globalRows
162
+ .filter((r) => r && typeof r.statement === "string" && typeof r.kind === "string")
163
+ .map((r) => ({ id: globalRowId(r), row: r, profile: shingleProfile(r.statement) }));
164
+
165
+ return groups
166
+ .filter((g) => g.length >= 2)
167
+ .map((g) => {
168
+ const members = g.slice().sort((x, y) => cmp(x.repo, y.repo) || x.order - y.order);
169
+ const lowest = (e) => Math.min(...members.filter((m) => m !== e).map((m) => score(e, m)));
170
+ const mean = (e) =>
171
+ members.filter((m) => m !== e).reduce((s, m) => s + score(e, m), 0) / (members.length - 1);
172
+ const representative = members
173
+ .slice()
174
+ .sort(
175
+ (x, y) =>
176
+ mean(y) - mean(x) ||
177
+ cmp(String(x.row.ts ?? ""), String(y.row.ts ?? "")) ||
178
+ cmp(x.repo, y.repo),
179
+ )[0];
180
+ return {
181
+ id: shortId(
182
+ "P",
183
+ representative.row.kind,
184
+ members.map((e) => `${e.repo}/${e.id}`).join(" "),
185
+ ),
186
+ kind: representative.row.kind,
187
+ statement: representative.row.statement,
188
+ representative,
189
+ similarity: round(weakest(members, score)),
190
+ repos: [...new Set(members.map((e) => e.repo))],
191
+ evidence: members.map((e) => ({
192
+ repo: e.repo,
193
+ id: e.id,
194
+ statement: e.row.statement,
195
+ score: round(lowest(e)),
196
+ })),
197
+ global: coveredBy(members, globals, threshold),
198
+ };
199
+ })
200
+ .sort((x, y) => y.similarity - x.similarity || cmp(x.id, y.id));
201
+ }
202
+
203
+ /**
204
+ * A global row is shown in a repository unless the repository is one of its
205
+ * sources (its own entry, or the entry that replaced it, already says what
206
+ * holds there) or already carries a current entry of the same kind that says
207
+ * the same thing.
208
+ *
209
+ * @param {object} globalRow
210
+ * @param {string} slug
211
+ * @param {object[]} localRows the repository's current rows
212
+ */
213
+ export function globalVisible(
214
+ globalRow,
215
+ slug,
216
+ localRows,
217
+ { threshold = PROMOTION_SIMILARITY } = {},
218
+ ) {
219
+ const sources = Array.isArray(globalRow?.promoted_from?.sources)
220
+ ? globalRow.promoted_from.sources
221
+ : [];
222
+ if (sources.some((s) => s?.repo === slug)) return false;
223
+ const p = shingleProfile(String(globalRow?.statement ?? ""));
224
+ return !localRows.some(
225
+ (r) =>
226
+ r.kind === globalRow.kind &&
227
+ shingleSimilarity(p, shingleProfile(String(r.statement ?? ""))) >= threshold,
228
+ );
229
+ }