ggen-cli-lib 26.7.3

CLI interface for ggen
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
#!/usr/bin/env bash
# =============================================================================
# ln_ctrl Regeneration Script - Test Determinism
#
# Deletes generated/, re-runs sync, verifies, and compares hashes to ensure
# deterministic code generation (μ ∘ μ = μ).
#
# Generated by ggen from ln_ctrl wizard - DO NOT EDIT MANUALLY
# Regenerate with: ggen sync --audit true
# =============================================================================

set -euo pipefail

# Configuration
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
readonly GENERATED_DIR="${PROJECT_ROOT}/generated"
readonly BACKUP_DIR="${PROJECT_ROOT}/.generated-backup"
readonly LOG_DIR="${PROJECT_ROOT}/logs"

# Colors
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly BLUE='\033[0;34m'
readonly CYAN='\033[0;36m'
readonly MAGENTA='\033[0;35m'
readonly NC='\033[0m'

# Flags
SKIP_BACKUP=false
VERBOSE=false

# Ensure directories exist
mkdir -p "${LOG_DIR}"

# Print functions
print_pass() { echo -e "${GREEN}✅ PASS${NC}: $*"; }
print_fail() { echo -e "${RED}❌ FAIL${NC}: $*"; }
print_info() { echo -e "${BLUE}ℹ️  INFO${NC}: $*"; }
print_warn() { echo -e "${YELLOW}⚠️  WARN${NC}: $*"; }
print_step() { echo -e "${CYAN}${NC}  $*"; }
print_test() { echo -e "${MAGENTA}🧪 TEST${NC}: $*"; }

# Usage
usage() {
    cat << 'EOF'
ln_ctrl Regeneration Script - Test Determinism

Validates that ggen produces identical output on repeated runs (μ ∘ μ = μ).

Usage: ./regen.sh [options]

Options:
    --skip-backup      Skip backing up current generated/
    -v, --verbose      Enable verbose output
    -h, --help         Show this help message

Process:
    1. Backup current generated/ directory
    2. Compute hash of current artifacts (HASH_1)
    3. Delete generated/ directory
    4. Re-run ggen sync (full pipeline)
    5. Compute hash of new artifacts (HASH_2)
    6. Compare HASH_1 vs HASH_2 (must match)
    7. Run verification
    8. Restore from backup if regeneration fails

Examples:
    ./regen.sh                 # Full determinism test
    ./regen.sh --verbose       # With detailed output
    ./regen.sh --skip-backup   # No backup (faster, risky)

Exit codes:
    0 - Success (deterministic generation confirmed)
    1 - Failure (non-deterministic or verification failed)
    2 - Error (missing dependencies, invalid state)

EOF
}

# Compute hash of generated directory
compute_hash() {
    local dir="$1"

    if [[ ! -d "$dir" ]]; then
        echo "NONE"
        return
    fi

    # Hash all files, excluding target/ and .ggen-hash
    find "$dir" -type f ! -path "*/target/*" ! -name ".ggen-hash" -exec sha256sum {} \; 2>/dev/null \
        | sort \
        | sha256sum \
        | cut -d' ' -f1
}

# Backup generated directory
backup_generated() {
    print_step "Backing up generated directory..."

    if [[ ! -d "${GENERATED_DIR}" ]]; then
        print_info "No generated directory to backup"
        return 0
    fi

    if [[ "$SKIP_BACKUP" == "true" ]]; then
        print_info "Skipping backup (--skip-backup flag)"
        return 0
    fi

    # Remove old backup if exists
    if [[ -d "${BACKUP_DIR}" ]]; then
        rm -rf "${BACKUP_DIR}"
    fi

    # Create backup
    cp -r "${GENERATED_DIR}" "${BACKUP_DIR}"

    local file_count
    file_count=$(find "${BACKUP_DIR}" -type f | wc -l)

    print_pass "Backup created (${file_count} files)"
    return 0
}

# Restore from backup
restore_backup() {
    print_step "Restoring from backup..."

    if [[ ! -d "${BACKUP_DIR}" ]]; then
        print_warn "No backup found to restore"
        return 1
    fi

    # Remove failed generated directory
    if [[ -d "${GENERATED_DIR}" ]]; then
        rm -rf "${GENERATED_DIR}"
    fi

    # Restore backup
    cp -r "${BACKUP_DIR}" "${GENERATED_DIR}"

    print_pass "Backup restored"
    return 0
}

# Delete generated directory
delete_generated() {
    print_step "Deleting generated directory..."

    if [[ ! -d "${GENERATED_DIR}" ]]; then
        print_info "Generated directory does not exist"
        return 0
    fi

    local file_count
    file_count=$(find "${GENERATED_DIR}" -type f | wc -l)

    rm -rf "${GENERATED_DIR}"

    print_pass "Deleted ${file_count} files"
    return 0
}

# Run sync
run_sync() {
    print_step "Running ggen sync (full pipeline)..."

    local run_script="${SCRIPT_DIR}/run.sh"

    if [[ ! -f "$run_script" ]]; then
        print_fail "Run script not found: ${run_script}"
        return 1
    fi

    if [[ ! -x "$run_script" ]]; then
        chmod +x "$run_script"
    fi

    local log_file="${LOG_DIR}/regen-sync-$(date +%Y%m%d-%H%M%S).log"

    if [[ "$VERBOSE" == "true" ]]; then
        if bash "$run_script" --no-audit 2>&1 | tee "$log_file"; then
            print_pass "Sync completed"
            return 0
        else
            print_fail "Sync failed (see ${log_file})"
            return 1
        fi
    else
        if bash "$run_script" --no-audit > "$log_file" 2>&1; then
            print_pass "Sync completed"
            return 0
        else
            print_fail "Sync failed (see ${log_file})"
            tail -n 20 "$log_file"
            return 1
        fi
    fi
}

# Compare hashes
compare_hashes() {
    local hash1="$1"
    local hash2="$2"

    print_test "Comparing hashes (determinism check)..."

    if [[ "$VERBOSE" == "true" ]]; then
        print_info "HASH_1 (original): ${hash1}"
        print_info "HASH_2 (regenerated): ${hash2}"
    fi

    if [[ "$hash1" == "NONE" ]]; then
        print_warn "Original hash not available (first run)"
        return 0
    fi

    if [[ "$hash2" == "NONE" ]]; then
        print_fail "Regeneration produced no output"
        return 1
    fi

    if [[ "$hash1" == "$hash2" ]]; then
        print_pass "Hashes match (μ ∘ μ = μ confirmed)"
        return 0
    else
        print_fail "Hash mismatch (non-deterministic generation detected)"
        print_info "This indicates the generation process is not deterministic"
        print_info "Possible causes: timestamps, random values, file ordering"
        return 1
    fi
}

# Run verification
run_verification() {
    print_step "Running verification..."

    local verify_script="${SCRIPT_DIR}/verify.sh"

    if [[ ! -f "$verify_script" ]]; then
        print_warn "Verification script not found: ${verify_script}"
        return 0
    fi

    if [[ ! -x "$verify_script" ]]; then
        chmod +x "$verify_script"
    fi

    if bash "$verify_script"; then
        print_pass "Verification passed"
        return 0
    else
        print_fail "Verification failed"
        return 1
    fi
}

# Print summary
print_summary() {
    local hash1="$1"
    local hash2="$2"
    local deterministic="$3"
    local verification="$4"
    local overall="$5"

    echo ""
    echo "=============================================="
    echo "ln_ctrl Regeneration Summary"
    echo "=============================================="
    echo "Project:      ${PROJECT_ROOT}"
    echo "Timestamp:    $(date -u +"%Y-%m-%dT%H:%M:%SZ")"
    echo "----------------------------------------------"
    echo "HASH_1:       ${hash1}"
    echo "HASH_2:       ${hash2}"
    echo "----------------------------------------------"

    if [[ "$deterministic" -eq 0 ]]; then
        echo -e "Determinism:  ${GREEN}✅ PASS${NC}"
    else
        echo -e "Determinism:  ${RED}❌ FAIL${NC}"
    fi

    if [[ "$verification" -eq 0 ]]; then
        echo -e "Verification: ${GREEN}✅ PASS${NC}"
    else
        echo -e "Verification: ${RED}❌ FAIL${NC}"
    fi

    echo "=============================================="

    if [[ "$overall" -eq 0 ]]; then
        echo -e "${GREEN}RESULT: SUCCESS${NC}"
        echo -e "${GREEN}Formula μ ∘ μ = μ validated${NC}"
    else
        echo -e "${RED}RESULT: FAILURE${NC}"
    fi

    echo ""
}

# Main execution
main() {
    # Parse arguments
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --skip-backup)
                SKIP_BACKUP=true
                shift
                ;;
            -v|--verbose)
                VERBOSE=true
                shift
                ;;
            -h|--help)
                usage
                exit 0
                ;;
            *)
                echo "Unknown option: $1"
                usage
                exit 2
                ;;
        esac
    done

    echo ""
    echo "=============================================="
    echo "ln_ctrl Regeneration - Determinism Test"
    echo "=============================================="
    echo "Formula: μ ∘ μ = μ"
    echo "Testing: HASH(μ(O)) = HASH(μ(μ(O)))"
    echo "----------------------------------------------"
    echo ""

    local hash1="NONE"
    local hash2="NONE"
    local deterministic=1
    local verification=1
    local overall=1

    # Step 1: Backup current state
    if ! backup_generated; then
        print_fail "Backup failed"
        exit 2
    fi

    # Step 2: Compute original hash
    print_step "Computing original hash..."
    hash1=$(compute_hash "${GENERATED_DIR}")
    if [[ "$hash1" != "NONE" ]]; then
        print_info "HASH_1: ${hash1}"
    else
        print_info "No existing generated/ directory"
    fi

    # Step 3: Delete generated directory
    if ! delete_generated; then
        print_fail "Failed to delete generated directory"
        exit 2
    fi

    # Step 4: Re-run sync
    if ! run_sync; then
        print_fail "Regeneration failed"
        restore_backup
        exit 1
    fi

    # Step 5: Compute new hash
    print_step "Computing regenerated hash..."
    hash2=$(compute_hash "${GENERATED_DIR}")
    if [[ "$hash2" != "NONE" ]]; then
        print_info "HASH_2: ${hash2}"
    fi

    # Step 6: Compare hashes
    if compare_hashes "$hash1" "$hash2"; then
        deterministic=0
    else
        deterministic=1
    fi

    # Step 7: Run verification
    if run_verification; then
        verification=0
    else
        verification=1
    fi

    # Determine overall result
    if [[ $deterministic -eq 0 ]] && [[ $verification -eq 0 ]]; then
        overall=0
    else
        overall=1
    fi

    # Print summary
    print_summary "$hash1" "$hash2" "$deterministic" "$verification" "$overall"

    # Clean up backup on success
    if [[ $overall -eq 0 ]] && [[ -d "${BACKUP_DIR}" ]]; then
        rm -rf "${BACKUP_DIR}"
        print_info "Backup removed (regeneration successful)"
    fi

    exit $overall
}

main "$@"