loki-mode 5.53.0 → 5.55.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.
@@ -0,0 +1,500 @@
1
+ #!/usr/bin/env bash
2
+ # shellcheck disable=SC2034 # Variables used by sourcing scripts
3
+ # shellcheck disable=SC2155 # Declare and assign separately (acceptable in this codebase)
4
+ #===============================================================================
5
+ # Migration Agents - Shell-sourceable agent definitions for codebase migration
6
+ #
7
+ # Defines 5 specialized agents for safe, structured codebase migration:
8
+ # 1. Codebase Archaeologist - Read-only legacy code exploration
9
+ # 2. Characterization Tester - Behavioral test generation
10
+ # 3. Seam Detector - Architecture seam identification
11
+ # 4. Migration Planner - Ordered migration plan generation
12
+ # 5. Migration Reviewer - Specialized migration review council member
13
+ #
14
+ # Usage:
15
+ # source autonomy/migration-agents.sh
16
+ # agent_codebase_archaeologist "/path/to/code" "/path/to/migration"
17
+ # agent_characterization_tester "/path/to/code" "/path/to/migration"
18
+ # migration_agent_dispatch "archaeologist" "/path/to/code" "/path/to/migration"
19
+ #
20
+ # Each function echoes a structured prompt suitable for claude/codex/gemini.
21
+ # The migration directory stores all artifacts (docs/, tests/, seams.json, etc).
22
+ #
23
+ # Environment Variables:
24
+ # MIGRATION_STRATEGY - "big-bang" (default) or "strangler-fig"
25
+ # MIGRATION_CONFIDENCE - Minimum confidence for auto-proceed (default: 0.8)
26
+ #
27
+ #===============================================================================
28
+
29
+ MIGRATION_AGENTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
30
+
31
+ # Strategy and confidence defaults
32
+ MIGRATION_STRATEGY="${MIGRATION_STRATEGY:-big-bang}"
33
+ MIGRATION_CONFIDENCE="${MIGRATION_CONFIDENCE:-0.8}"
34
+
35
+ #===============================================================================
36
+ # Base Prompts
37
+ #
38
+ # Each agent has a MIGRATION_AGENT_<NAME>_PROMPT variable containing its
39
+ # core instructions. The agent functions compose these with runtime paths.
40
+ #===============================================================================
41
+
42
+ read -r -d '' MIGRATION_AGENT_ARCHAEOLOGIST_PROMPT << 'PROMPT_EOF' || true
43
+ You are the Codebase Archaeologist -- a read-only exploration agent.
44
+
45
+ Your mission is to thoroughly explore a legacy codebase and produce structured
46
+ documentation that other migration agents will depend on. You must NOT modify
47
+ any source files. Read-only access only.
48
+
49
+ Tasks:
50
+ 1. Map all data flows (inputs, transformations, outputs, persistence)
51
+ 2. Identify error handling paths (try/catch, error codes, fallback logic)
52
+ 3. Catalog external dependencies (APIs, databases, file systems, services)
53
+ 4. Locate architectural seams (boundaries between modules, abstraction layers)
54
+ 5. Document implicit assumptions and conventions
55
+
56
+ Output the following files in the migration docs/ directory:
57
+ - architecture.md -- High-level architecture with Mermaid diagrams
58
+ - dependencies.md -- External dependencies catalog with versions and usage
59
+ - data-flows.md -- Data flow documentation with Mermaid sequence diagrams
60
+ - seams-initial.md -- Initial identification of architectural seams
61
+
62
+ Format requirements:
63
+ - Use Mermaid diagram syntax for all visual documentation
64
+ - Include file paths and line numbers for every finding
65
+ - Mark confidence level (high/medium/low) for each architectural claim
66
+ - List unknowns and areas requiring human clarification
67
+
68
+ Constraints:
69
+ - READ-ONLY: Do not create, modify, or delete any source files
70
+ - Do not execute any code or tests
71
+ - Do not install dependencies
72
+ - Only create files within the migration docs/ directory
73
+ PROMPT_EOF
74
+
75
+ read -r -d '' MIGRATION_AGENT_CHARACTERIZATION_TESTER_PROMPT << 'PROMPT_EOF' || true
76
+ You are the Characterization Tester -- a behavioral test generation agent.
77
+
78
+ Your mission is to generate tests that capture WHAT the code currently does,
79
+ not what it should do. These tests lock in existing behavior so that migration
80
+ changes can be verified against the original implementation.
81
+
82
+ Tasks:
83
+ 1. Read the archaeologist documentation for architecture understanding
84
+ 2. Generate characterization tests for every public interface
85
+ 3. Cover boundary values, failure modes, exact outputs, and side effects
86
+ 4. Run each test suite 3 times to detect flakiness
87
+ 5. Mark any flaky tests with a [FLAKY] annotation and exclusion flag
88
+
89
+ Test coverage priorities (in order):
90
+ - Public API endpoints and function signatures
91
+ - Data transformation pipelines (exact input/output pairs)
92
+ - Error handling paths (exception types, error messages, status codes)
93
+ - Side effects (file writes, database mutations, API calls)
94
+ - Edge cases (empty inputs, null values, max limits, unicode)
95
+
96
+ Output:
97
+ - tests/characterization/ directory with test files organized by module
98
+ - features.json -- a JSON array of Feature objects matching this EXACT schema:
99
+
100
+ [
101
+ {
102
+ "id": "feat-001",
103
+ "category": "behavioral",
104
+ "description": "Login endpoint returns 401 for invalid credentials",
105
+ "verification_steps": ["Run test_login_invalid", "Check status code is 401"],
106
+ "passes": false,
107
+ "characterization_test": "tests/characterization/test_auth.py::test_login_invalid",
108
+ "risk": "medium",
109
+ "notes": "Also emits a warning log line"
110
+ }
111
+ ]
112
+
113
+ Field definitions:
114
+ - id (string, required): Unique identifier like "feat-001", "feat-002"
115
+ - category (string): One of "behavioral", "api", "data", "error-handling", "side-effect"
116
+ - description (string, required): What the code currently does (IS behavior)
117
+ - verification_steps (list of strings): Steps to verify this feature still works
118
+ - passes (boolean): Whether the characterization test passes (true/false)
119
+ - characterization_test (string): Path to the test that locks in this behavior
120
+ - risk (string): "low", "medium", or "high" -- risk if this behavior changes
121
+ - notes (string): Additional context, edge cases, or caveats
122
+
123
+ IMPORTANT: Do NOT use field names like "name", "file", "tests", "behavior",
124
+ or "flaky". Use ONLY the field names listed above.
125
+
126
+ Constraints:
127
+ - Tests must describe IS behavior, not SHOULD behavior
128
+ - Never fix bugs in tests -- capture the bug as a test case
129
+ - Each test must be deterministic (no timing-dependent assertions)
130
+ - Use the project's existing test framework when available
131
+ PROMPT_EOF
132
+
133
+ read -r -d '' MIGRATION_AGENT_SEAM_DETECTOR_PROMPT << 'PROMPT_EOF' || true
134
+ You are the Seam Detector -- an architecture seam identification agent.
135
+
136
+ Your mission is to identify safe places in the codebase where interfaces,
137
+ wrappers, or adapters can be introduced without changing behavior. These
138
+ seams become the insertion points for migration changes.
139
+
140
+ Tasks:
141
+ 1. Read archaeologist documentation (architecture.md, seams-initial.md)
142
+ 2. Read characterization test coverage (features.json)
143
+ 3. Identify function boundaries that can be wrapped
144
+ 4. Find interfaces with swappable implementations
145
+ 5. Detect config-driven behavior suitable for feature flags
146
+ 6. Locate feature flag candidates for gradual rollout
147
+
148
+ For each seam, provide:
149
+ - Location as a FLAT STRING like "src/auth.py:42:login_handler" (file:line:symbol)
150
+ - Type: "wrapper" | "interface" | "config" | "feature-flag" | "adapter"
151
+ - Confidence score (0.0 to 1.0)
152
+ - Description of what can be changed at this seam
153
+ - Suggested interface (how to abstract this seam)
154
+
155
+ Confidence thresholds:
156
+ - >= 0.8: Safe to auto-proceed with migration at this seam
157
+ - 0.5 - 0.79: Requires human review before proceeding
158
+ - < 0.5: High risk -- document but do not recommend for migration
159
+
160
+ Output:
161
+ - seams.json in the migration directory -- a JSON array of SeamInfo objects
162
+ matching this EXACT schema:
163
+
164
+ [
165
+ {
166
+ "id": "seam-001",
167
+ "type": "wrapper",
168
+ "location": "src/auth.py:42:login_handler",
169
+ "description": "Authentication handler can be wrapped with new provider",
170
+ "confidence": 0.85,
171
+ "suggested_interface": "AuthProvider interface with authenticate() method"
172
+ }
173
+ ]
174
+
175
+ Field definitions:
176
+ - id (string, required): Unique identifier like "seam-001", "seam-002"
177
+ - type (string, required): "wrapper", "interface", "config", "feature-flag", or "adapter"
178
+ - location (string, required): FLAT STRING as "file:line:symbol" -- NOT a nested object
179
+ - description (string, required): What can be changed at this seam
180
+ - confidence (float): 0.0 to 1.0
181
+ - suggested_interface (string): How to abstract this boundary
182
+
183
+ IMPORTANT: The "location" field MUST be a flat string like "src/foo.py:42",
184
+ NOT a nested dict like {"file": "...", "line": 42}. The engine will reject
185
+ nested location objects. Do NOT include "risk", "tests", or "auto_proceed"
186
+ fields -- these are not part of the SeamInfo schema.
187
+
188
+ Constraints:
189
+ - Every seam MUST have at least one characterization test covering it
190
+ - Seams without test coverage get confidence capped at 0.3
191
+ - Do not suggest seams that would require changing public API contracts
192
+ PROMPT_EOF
193
+
194
+ read -r -d '' MIGRATION_AGENT_PLANNER_PROMPT << 'PROMPT_EOF' || true
195
+ You are the Migration Planner -- a plan generation agent.
196
+
197
+ Your mission is to create a detailed, ordered migration plan based on the
198
+ archaeologist documentation, characterization tests, and identified seams.
199
+ The plan must be executable as a sequence of safe, reversible steps.
200
+
201
+ Tasks:
202
+ 1. Read all migration artifacts (docs/, features.json, seams.json)
203
+ 2. Build a dependency graph between migration steps
204
+ 3. Order steps to minimize risk (independent changes first)
205
+ 4. Estimate token cost and risk level for each step
206
+ 5. Define rollback points at each step boundary
207
+
208
+ Strategy selection:
209
+ - "incremental": Gradual replacement with parallel old/new paths (default, safer)
210
+ - "big_bang": All changes in one coordinated push (faster, riskier)
211
+
212
+ Output:
213
+ - migration-plan.json in the migration directory -- a MigrationPlan object
214
+ matching this EXACT schema:
215
+
216
+ {
217
+ "version": 1,
218
+ "strategy": "incremental",
219
+ "constraints": ["No downtime allowed", "Must preserve API compatibility"],
220
+ "steps": [
221
+ {
222
+ "id": "step-001",
223
+ "description": "Extract auth module behind interface",
224
+ "type": "refactor",
225
+ "files": ["src/auth.py", "src/login.py"],
226
+ "tests_required": ["tests/test_auth.py"],
227
+ "estimated_tokens": 5000,
228
+ "risk": "low",
229
+ "rollback_point": true,
230
+ "depends_on": [],
231
+ "assigned_agent": "",
232
+ "status": "pending"
233
+ }
234
+ ],
235
+ "rollback_strategy": "checkpoint",
236
+ "exit_criteria": {"all_tests_pass": true, "no_regressions": true}
237
+ }
238
+
239
+ MigrationPlan fields:
240
+ - version (integer): Plan version number, starts at 1
241
+ - strategy (string): "incremental" or "big_bang"
242
+ - constraints (list of strings): Migration constraints
243
+ - steps (list of MigrationStep): Ordered migration steps
244
+ - rollback_strategy (string): Overall rollback approach (e.g., "checkpoint")
245
+ - exit_criteria (dict): Conditions that must be met for migration to be complete
246
+
247
+ MigrationStep fields:
248
+ - id (string, required): Unique identifier like "step-001"
249
+ - description (string, required): What this step accomplishes
250
+ - type (string): "refactor", "rewrite", "config", or "test"
251
+ - files (list of strings): Files that will be modified -- NOT "files_affected"
252
+ - tests_required (list of strings): Tests that must pass after this step
253
+ - estimated_tokens (integer): Approximate token cost
254
+ - risk (string): "low", "medium", or "high" -- NOT "risk_level"
255
+ - rollback_point (boolean): true if a checkpoint should be created -- NOT a string
256
+ - depends_on (list of strings): Step IDs this step requires first
257
+ - assigned_agent (string): Agent assigned to execute this step (initially empty)
258
+ - status (string): "pending" (always start as pending)
259
+
260
+ IMPORTANT field name corrections:
261
+ - Use "files" NOT "files_affected"
262
+ - Use "risk" NOT "risk_level"
263
+ - "rollback_point" is a BOOLEAN (true/false), NOT a string
264
+ - Do NOT include "seams_used", "total_steps", "estimated_total_tokens",
265
+ or "risk_summary" -- these are not part of the schema
266
+
267
+ Constraints:
268
+ - Plan must be reviewed by the council before execution begins
269
+ - Every step must have a rollback strategy
270
+ - High-risk steps must be preceded by a checkpoint commit (rollback_point: true)
271
+ - No step may affect files outside the declared files list
272
+ PROMPT_EOF
273
+
274
+ read -r -d '' MIGRATION_AGENT_REVIEWER_PROMPT << 'PROMPT_EOF' || true
275
+ You are the Migration Reviewer -- a specialized council member for migration.
276
+
277
+ Your mission is to review migration changes with a focus on behavioral
278
+ equivalence that goes beyond simple test passing. You act as a devil's
279
+ advocate, specifically looking for what tests might miss.
280
+
281
+ Review checklist:
282
+ 1. Behavioral Equivalence
283
+ - Do outputs match for all input classes, not just tested inputs?
284
+ - Are error messages and error codes preserved exactly?
285
+ - Is timing behavior preserved (timeouts, retries, delays)?
286
+
287
+ 2. Performance Regression
288
+ - Are there new allocations in hot paths?
289
+ - Did data structure choices change (hash map vs tree, array vs linked list)?
290
+ - Are database query patterns preserved (N+1 queries, batch sizes)?
291
+
292
+ 3. API Contract Preservation
293
+ - Are all public function signatures identical?
294
+ - Are HTTP status codes, headers, and response shapes unchanged?
295
+ - Are error response formats preserved?
296
+
297
+ 4. Silent Behavior Changes
298
+ - Logging changes (format, level, destination)
299
+ - Metric emission changes (names, labels, values)
300
+ - Event ordering changes (race conditions introduced or removed)
301
+ - Default value changes (config, function parameters)
302
+
303
+ 5. What Tests Do Not Cover
304
+ - Concurrency behavior under load
305
+ - Resource cleanup (file handles, connections, locks)
306
+ - Initialization order dependencies
307
+ - Environment-specific behavior (OS, locale, timezone)
308
+
309
+ Output:
310
+ - Verdict: "approve" or "reject"
311
+ - Rationale: Detailed explanation of the decision
312
+ - Findings: List of specific issues found, each with:
313
+ - severity: "critical" | "high" | "medium" | "low"
314
+ - category: One of the 5 checklist areas above
315
+ - description: What was found
316
+ - location: File and line reference
317
+ - recommendation: How to address it
318
+
319
+ Constraints:
320
+ - Default stance is skeptical -- approve only when confident
321
+ - A single critical finding means automatic rejection
322
+ - High findings require explicit justification if approving
323
+ - Must provide at least one observation per checklist category
324
+ PROMPT_EOF
325
+
326
+ #===============================================================================
327
+ # Agent Functions
328
+ #
329
+ # Each function composes the base prompt with runtime context (paths,
330
+ # strategy, configuration) and echoes the final prompt string.
331
+ #===============================================================================
332
+
333
+ # agent_codebase_archaeologist -- Read-only legacy code exploration
334
+ #
335
+ # Args:
336
+ # $1 - codebase_path: Path to the codebase to explore
337
+ # $2 - migration_dir: Path to the migration working directory
338
+ agent_codebase_archaeologist() {
339
+ local codebase_path="${1:?Usage: agent_codebase_archaeologist <codebase_path> <migration_dir>}"
340
+ local migration_dir="${2:?Usage: agent_codebase_archaeologist <codebase_path> <migration_dir>}"
341
+
342
+ echo "$MIGRATION_AGENT_ARCHAEOLOGIST_PROMPT"
343
+ echo ""
344
+ echo "--- Runtime Context ---"
345
+ echo "Codebase path: $codebase_path"
346
+ echo "Migration directory: $migration_dir"
347
+ echo "Output directory: ${migration_dir}/docs/"
348
+ echo ""
349
+ cat <<'EOF'
350
+ Begin by scanning the directory structure, then systematically explore
351
+ each module. Start with entry points and trace outward.
352
+ EOF
353
+ }
354
+
355
+ # agent_characterization_tester -- Behavioral test generation
356
+ #
357
+ # Args:
358
+ # $1 - codebase_path: Path to the codebase to test
359
+ # $2 - migration_dir: Path to the migration working directory
360
+ agent_characterization_tester() {
361
+ local codebase_path="${1:?Usage: agent_characterization_tester <codebase_path> <migration_dir>}"
362
+ local migration_dir="${2:?Usage: agent_characterization_tester <codebase_path> <migration_dir>}"
363
+
364
+ echo "$MIGRATION_AGENT_CHARACTERIZATION_TESTER_PROMPT"
365
+ echo ""
366
+ echo "--- Runtime Context ---"
367
+ echo "Codebase path: $codebase_path"
368
+ echo "Migration directory: $migration_dir"
369
+ echo "Archaeologist docs: ${migration_dir}/docs/"
370
+ echo "Output directory: ${migration_dir}/tests/characterization/"
371
+ echo "Features manifest: ${migration_dir}/features.json"
372
+ echo ""
373
+ cat <<'EOF'
374
+ Read the archaeologist documentation first, then generate tests
375
+ module by module. Run each test file 3 times to detect flakiness.
376
+ EOF
377
+ }
378
+
379
+ # agent_seam_detector -- Architecture seam identification
380
+ #
381
+ # Args:
382
+ # $1 - codebase_path: Path to the codebase to analyze
383
+ # $2 - migration_dir: Path to the migration working directory
384
+ agent_seam_detector() {
385
+ local codebase_path="${1:?Usage: agent_seam_detector <codebase_path> <migration_dir>}"
386
+ local migration_dir="${2:?Usage: agent_seam_detector <codebase_path> <migration_dir>}"
387
+
388
+ echo "$MIGRATION_AGENT_SEAM_DETECTOR_PROMPT"
389
+ echo ""
390
+ echo "--- Runtime Context ---"
391
+ echo "Codebase path: $codebase_path"
392
+ echo "Migration directory: $migration_dir"
393
+ echo "Archaeologist docs: ${migration_dir}/docs/"
394
+ echo "Features manifest: ${migration_dir}/features.json"
395
+ echo "Auto-proceed threshold: ${MIGRATION_CONFIDENCE}"
396
+ echo "Output file: ${migration_dir}/seams.json"
397
+ echo ""
398
+ cat <<'EOF'
399
+ Cross-reference every identified seam against the characterization
400
+ test coverage in features.json. Cap confidence at 0.3 for untested seams.
401
+ EOF
402
+ }
403
+
404
+ # agent_migration_planner -- Ordered migration plan generation
405
+ #
406
+ # Args:
407
+ # $1 - codebase_path: Path to the codebase to plan migration for
408
+ # $2 - migration_dir: Path to the migration working directory
409
+ agent_migration_planner() {
410
+ local codebase_path="${1:?Usage: agent_migration_planner <codebase_path> <migration_dir>}"
411
+ local migration_dir="${2:?Usage: agent_migration_planner <codebase_path> <migration_dir>}"
412
+
413
+ echo "$MIGRATION_AGENT_PLANNER_PROMPT"
414
+ echo ""
415
+ echo "--- Runtime Context ---"
416
+ echo "Codebase path: $codebase_path"
417
+ echo "Migration directory: $migration_dir"
418
+ echo "Archaeologist docs: ${migration_dir}/docs/"
419
+ echo "Features manifest: ${migration_dir}/features.json"
420
+ echo "Seams file: ${migration_dir}/seams.json"
421
+ echo "Migration strategy: ${MIGRATION_STRATEGY}"
422
+ echo "Output file: ${migration_dir}/migration-plan.json"
423
+ echo ""
424
+ echo "Strategy \"${MIGRATION_STRATEGY}\" selected. Build the dependency graph,"
425
+ cat <<'EOF'
426
+ then topologically sort steps for execution order.
427
+ The plan must be reviewed by the council before any execution begins.
428
+ EOF
429
+ }
430
+
431
+ # agent_migration_reviewer -- Specialized migration review council member
432
+ #
433
+ # Args:
434
+ # $1 - codebase_path: Path to the codebase under migration
435
+ # $2 - migration_dir: Path to the migration working directory
436
+ agent_migration_reviewer() {
437
+ local codebase_path="${1:?Usage: agent_migration_reviewer <codebase_path> <migration_dir>}"
438
+ local migration_dir="${2:?Usage: agent_migration_reviewer <codebase_path> <migration_dir>}"
439
+
440
+ echo "$MIGRATION_AGENT_REVIEWER_PROMPT"
441
+ echo ""
442
+ echo "--- Runtime Context ---"
443
+ echo "Codebase path: $codebase_path"
444
+ echo "Migration directory: $migration_dir"
445
+ echo "Migration plan: ${migration_dir}/migration-plan.json"
446
+ echo "Features manifest: ${migration_dir}/features.json"
447
+ echo "Seams file: ${migration_dir}/seams.json"
448
+ echo "Characterization tests: ${migration_dir}/tests/characterization/"
449
+ echo ""
450
+ cat <<'EOF'
451
+ Review the current migration state. Compare the codebase against the
452
+ characterization tests and migration plan. Focus on what the tests
453
+ do NOT cover and flag any silent behavior changes.
454
+ EOF
455
+ }
456
+
457
+ #===============================================================================
458
+ # Dispatcher
459
+ #
460
+ # migration_agent_dispatch(agent_type, codebase_path, migration_dir)
461
+ #
462
+ # Routes to the correct agent function by type name. Supports both
463
+ # short names and full function names.
464
+ #
465
+ # Agent types:
466
+ # archaeologist | codebase-archaeologist
467
+ # tester | characterization-tester
468
+ # seam | seam-detector
469
+ # planner | migration-planner
470
+ # reviewer | migration-reviewer
471
+ #===============================================================================
472
+
473
+ migration_agent_dispatch() {
474
+ local agent_type="${1:?Usage: migration_agent_dispatch <agent_type> <codebase_path> <migration_dir>}"
475
+ local codebase_path="${2:?Usage: migration_agent_dispatch <agent_type> <codebase_path> <migration_dir>}"
476
+ local migration_dir="${3:?Usage: migration_agent_dispatch <agent_type> <codebase_path> <migration_dir>}"
477
+
478
+ case "$agent_type" in
479
+ archaeologist|codebase-archaeologist)
480
+ agent_codebase_archaeologist "$codebase_path" "$migration_dir"
481
+ ;;
482
+ tester|characterization-tester)
483
+ agent_characterization_tester "$codebase_path" "$migration_dir"
484
+ ;;
485
+ seam|seam-detector)
486
+ agent_seam_detector "$codebase_path" "$migration_dir"
487
+ ;;
488
+ planner|migration-planner)
489
+ agent_migration_planner "$codebase_path" "$migration_dir"
490
+ ;;
491
+ reviewer|migration-reviewer)
492
+ agent_migration_reviewer "$codebase_path" "$migration_dir"
493
+ ;;
494
+ *)
495
+ echo "ERROR: Unknown migration agent type: ${agent_type}" >&2
496
+ echo "Valid types: archaeologist, tester, seam, planner, reviewer" >&2
497
+ return 1
498
+ ;;
499
+ esac
500
+ }
@@ -7,7 +7,7 @@ Modules:
7
7
  control: Session control API (start/stop/pause/resume)
8
8
  """
9
9
 
10
- __version__ = "5.53.0"
10
+ __version__ = "5.55.0"
11
11
 
12
12
  # Expose the control app for easy import
13
13
  try: