ai-engineering-loop 1.0.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 (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +272 -0
  3. package/adapters/dot/README.md +55 -0
  4. package/adapters/dot/coreview.md +88 -0
  5. package/adapters/dot/gitlab.md +128 -0
  6. package/adapters/dot/mattermost.md +102 -0
  7. package/adapters/dot/multi-branch.md +89 -0
  8. package/agents/devil-advocate.md +111 -0
  9. package/agents/judge.md +69 -0
  10. package/agents/maker.md +66 -0
  11. package/bin/ai-engineering-loop.js +633 -0
  12. package/core/configuration-precedence.md +102 -0
  13. package/core/context-impact-assessment.md +127 -0
  14. package/core/context-refresh-policy.md +116 -0
  15. package/core/definition-of-done.md +79 -0
  16. package/core/escalation-policy.md +99 -0
  17. package/core/goal-contract.md +88 -0
  18. package/core/iteration-policy.md +108 -0
  19. package/core/judge-policy.md +123 -0
  20. package/core/project-initialization.md +97 -0
  21. package/core/repo-config-schema.md +72 -0
  22. package/core/verification-loop.md +97 -0
  23. package/docs/antigravity-feasibility.md +90 -0
  24. package/docs/migration-plan.md +70 -0
  25. package/examples/backend-api/payment-idempotency/README.md +33 -0
  26. package/examples/backend-api/payment-idempotency/goal-contract.md +33 -0
  27. package/examples/backend-api/payment-idempotency/judge-verdict.md +28 -0
  28. package/examples/backend-api/payment-idempotency/review-findings.md +50 -0
  29. package/examples/dot/attendance-confirmation/README.md +22 -0
  30. package/examples/dot/attendance-confirmation/delivery-report.md +51 -0
  31. package/examples/dot/attendance-confirmation/goal-contract.md +39 -0
  32. package/examples/dot/attendance-confirmation/judge-verdict.md +43 -0
  33. package/examples/dot/attendance-confirmation/review-findings.md +57 -0
  34. package/examples/initialization/README.md +19 -0
  35. package/examples/initialization/discovery-trace.md +63 -0
  36. package/examples/initialization/generated-context.md +110 -0
  37. package/examples/mobile-app/offline-sync-queue/README.md +33 -0
  38. package/examples/mobile-app/offline-sync-queue/goal-contract.md +32 -0
  39. package/examples/mobile-app/offline-sync-queue/judge-verdict.md +27 -0
  40. package/examples/mobile-app/offline-sync-queue/review-findings.md +30 -0
  41. package/package.json +31 -0
  42. package/policies/discovery-safety-policy.md +51 -0
  43. package/policies/evidence-policy.md +70 -0
  44. package/policies/finding-policy.md +102 -0
  45. package/policies/no-progress-policy.md +92 -0
  46. package/profiles/README.md +42 -0
  47. package/profiles/backend-api.md +64 -0
  48. package/profiles/library.md +51 -0
  49. package/profiles/mobile-app.md +59 -0
  50. package/profiles/monorepo.md +46 -0
  51. package/profiles/web-app.md +65 -0
  52. package/scripts/init.sh +85 -0
  53. package/templates/repo-config/adapter.md +11 -0
  54. package/templates/repo-config/architecture.md +15 -0
  55. package/templates/repo-config/config.md +11 -0
  56. package/templates/repo-config/conventions.md +16 -0
  57. package/templates/repo-config/verification.md +13 -0
@@ -0,0 +1,33 @@
1
+ # Reference Example: Backend API Payment Idempotency & Race Condition Fix
2
+
3
+ ## 1. Scenario Overview
4
+
5
+ This walkthrough demonstrates the **AI Engineering Loop** operating in a **Backend API** repository (`backend-api` profile) with standard GitHub adapter integration.
6
+
7
+ ### The Problem
8
+ A Go/PostgreSQL payment processing microservice experienced double-spend vulnerabilities when users clicked the payment confirmation button multiple times in rapid succession. The database updated account balances without transactional row-level locks or idempotency key uniqueness checks.
9
+
10
+ ---
11
+
12
+ ## 2. Dynamic Context Resolution
13
+
14
+ ```text
15
+ Engine: AI Engineering Loop Core
16
+ Profile: profiles/backend-api.md
17
+ Repo Config: payment-service/.ai-engineering-loop/ (Go 1.22, pgx, GitHub Adapter)
18
+ Task: Implement atomic idempotency key validation and SELECT FOR UPDATE row locking
19
+ ```
20
+
21
+ ---
22
+
23
+ ## 3. Walkthrough Artifacts
24
+
25
+ 1. **[Goal Contract (`goal-contract.md`)](file:///Users/egagofur/Development/work/ai-engineering-loop/examples/backend-api/payment-idempotency/goal-contract.md)**:
26
+ - AC-1: Idempotency-Key header mandatory on POST `/api/v1/payments/charge`.
27
+ - AC-2: Atomic reservation using PostgreSQL `INSERT ... ON CONFLICT DO NOTHING`.
28
+ - AC-3: Concurrent requests for same user wallet serialized with `SELECT ... FOR UPDATE`.
29
+ 2. **[Adversarial Review Findings (`review-findings.md`)](file:///Users/egagofur/Development/work/ai-engineering-loop/examples/backend-api/payment-idempotency/review-findings.md)**:
30
+ - Devil's Advocate activates `backend-api` rules (concurrency, database atomicity).
31
+ - Flags missing rollback on external gateway timeout (`ERR-001`).
32
+ 3. **[Judge Verdict (`judge-verdict.md`)](file:///Users/egagofur/Development/work/ai-engineering-loop/examples/backend-api/payment-idempotency/judge-verdict.md)**:
33
+ - Evaluates parallel test execution (`go test -race ./...`), verifies concurrency safety, and issues `PASS` verdict.
@@ -0,0 +1,33 @@
1
+ # Goal Contract: Payment Idempotency & Concurrency Lock
2
+
3
+ ## 1. Objective
4
+ Eliminate double-spending and balance corruption in the `payment-service` by enforcing mandatory `Idempotency-Key` headers, database transaction isolation, and row-level wallet locks.
5
+
6
+ ## 2. Business Outcome & User Lifecycle Impact
7
+ - **Customers**: Guaranteed never to be charged twice for identical checkout operations regardless of network retries or multiple clicks.
8
+ - **Finance**: 100% auditability and balance ledger integrity.
9
+
10
+ ## 3. Acceptance Criteria (AC)
11
+ - [ ] **AC-1**: Reject `POST /api/v1/payments/charge` with HTTP 400 if `Idempotency-Key` header is missing or empty.
12
+ - [ ] **AC-2**: Idempotency records stored atomically with 24-hour expiration window. Duplicate requests return cached original response with `X-Cache: HIT`.
13
+ - [ ] **AC-3**: User wallet balance updates serialized via `SELECT balance, version FROM wallets WHERE id = $1 FOR UPDATE`.
14
+ - [ ] **AC-4**: Zero race conditions detected under 50 simultaneous parallel requests.
15
+
16
+ ## 4. Technical Constraints
17
+ - Maintain Go 1.22 standard library and `github.com/jackc/pgx/v5`.
18
+ - No distributed Redis locks unless DB transactions prove insufficient.
19
+ - Zero breaking changes to response JSON schemas.
20
+
21
+ ## 5. Out of Scope
22
+ - Modifying refund or settlement batch jobs.
23
+
24
+ ## 6. Verification Requirements
25
+ - **Unit & Race Tests**: `go test -race -v -count=1 ./internal/payment/...`
26
+ - **Lint**: `golangci-lint run ./...`
27
+ - **Build**: `go build -o /dev/null ./cmd/server`
28
+
29
+ ## 7. Definition of Done (DoD)
30
+ - [ ] AC-1 through AC-4 verified via automated race test suites.
31
+ - [ ] Deterministic verification 100% green.
32
+ - [ ] Devil's Advocate review conducted with 0 open SEV-1/2 findings.
33
+ - [ ] Judge issues PASS verdict.
@@ -0,0 +1,28 @@
1
+ # Judge Evaluation Report: Payment Idempotency
2
+
3
+ ## 1. Executive Verdict
4
+ - **Verdict**: `PASS`
5
+ - **Iteration**: `Iteration 2 of 3`
6
+ - **Confidence**: `HIGH`
7
+
8
+ ---
9
+
10
+ ## 2. Deterministic Verification Audit
11
+
12
+ | Check | Command Executed | Raw Result | Status |
13
+ |---|---|---|:---:|
14
+ | **Race Tests** | `go test -race -v ./internal/payment/...` | `PASS: TestConcurrentPaymentDeductions (50 goroutines). 0 race warnings. ok 2.18s` | ✅ PASS |
15
+ | **Idempotency Suite**| `go test -v ./internal/payment/idempotency_test.go` | `PASS: TestIdempotencyDuplicateRequestReturnsCached. ok 0.42s` | ✅ PASS |
16
+ | **Linter** | `golangci-lint run ./...` | `0 issues found.` | ✅ PASS |
17
+ | **Build** | `go build -o /dev/null ./cmd/server` | `Exit code 0.` | ✅ PASS |
18
+
19
+ ---
20
+
21
+ ## 3. Finding Triage Audit
22
+ - **CONC-001 (Critical - Dangling DB Transaction)**: Resolved with `defer tx.Rollback(ctx)`. Verified by timeout test suite. **Status: RESOLVED & VERIFIED**.
23
+
24
+ ---
25
+
26
+ ## 4. Hand-off
27
+ The Definition of Done has been completely satisfied.
28
+ **Authorized next action**: Hand off to configured GitHub Adapter for Pull Request generation.
@@ -0,0 +1,50 @@
1
+ # Adversarial Review Findings: Payment Idempotency
2
+
3
+ ## 1. Review Summary
4
+ - **Reviewer**: Devil's Advocate Agent (Profile: `backend-api`)
5
+ - **Active Review Domains**: Auth, Database Transactions, Concurrency/Race, N+1, API Contracts
6
+ - **Total Findings**: 1
7
+ - **Blocking (SEV-1/2)**: 1
8
+
9
+ ---
10
+
11
+ ## 2. Findings Ledger
12
+
13
+ ### Finding CONC-001: Missing transaction rollback when external payment gateway times out
14
+ - **Severity**: `CRITICAL` (SEV-1)
15
+ - **Category**: `Concurrency & Error Handling`
16
+ - **Location**: `internal/payment/service.go:88-102`
17
+ - **Evidence**:
18
+ ```go
19
+ tx, _ := s.db.Begin(ctx)
20
+ wallet.Deduct(amount)
21
+ resp, err := s.gatewayClient.Charge(ctx, req)
22
+ if err != nil {
23
+ return nil, err // Exits without tx.Rollback(ctx)
24
+ }
25
+ tx.Commit(ctx)
26
+ ```
27
+ - **Problem**:
28
+ If the external payment gateway call returns a timeout or network error, the function exits early without invoking `tx.Rollback(ctx)`. In Go `pgx`, the connection remains locked in a dangling transaction until connection pool cleanup, and the user's wallet balance stays locked.
29
+ - **Impact**:
30
+ Connection pool exhaustion and locked wallet accounts during network blips.
31
+ - **Recommendation**:
32
+ ```diff
33
+ tx, err := s.db.Begin(ctx)
34
+ if err != nil {
35
+ return nil, err
36
+ }
37
+ + defer tx.Rollback(ctx)
38
+
39
+ wallet.Deduct(amount)
40
+ resp, err := s.gatewayClient.Charge(ctx, req)
41
+ if err != nil {
42
+ return nil, err
43
+ }
44
+ - tx.Commit(ctx)
45
+ + return resp, tx.Commit(ctx)
46
+ ```
47
+ - **Confidence**: `HIGH`
48
+ - **Status**: `TRIAGED_VALID`
49
+ - **Resolution**:
50
+ Maker Agent implemented `defer tx.Rollback(ctx)` and verified with a unit test simulating gateway timeout.
@@ -0,0 +1,22 @@
1
+ # Reference Example: Attendance Confirmation Status Fix
2
+
3
+ ## 1. Context & Scenario
4
+
5
+ This reference walkthrough demonstrates how a complex real-world bug in the DOT ecosystem moves through the complete **AI Engineering Loop** and is subsequently delivered via the **DOT Delivery Adapter**.
6
+
7
+ ### The Problem
8
+ In the Dotify employee portal, attendance confirmation cards displayed an incorrect status (`"PENDING"`) for employees working overtime or on weekends, even when all underlying time logs had already been approved or rejected. Furthermore, non-normal hours employees (shift workers) had their records mistakenly treated under standard 9-to-5 rules.
9
+
10
+ ---
11
+
12
+ ## 2. Walkthrough Stages & Artifacts
13
+
14
+ 1. **[Stage 1: Goal Contract (`goal-contract.md`)](file:///Users/egagofur/Development/work/ai-engineering-loop/examples/dot/attendance-confirmation/goal-contract.md)**:
15
+ - Formalized objective, acceptance criteria (normal hours, weekends, non-normal hours, null values), and verification plan.
16
+ 2. **[Stage 2: Adversarial Review & Triage (`review-findings.md`)](file:///Users/egagofur/Development/work/ai-engineering-loop/examples/dot/attendance-confirmation/review-findings.md)**:
17
+ - Independent Devil's Advocate review flagging a timezone offset bug (`COR-001`) and an invalid nitpick (`MAINT-001`).
18
+ - Maker Agent triage and surgical resolution.
19
+ 3. **[Stage 3: Judge Evaluation & Verdict (`judge-verdict.md`)](file:///Users/egagofur/Development/work/ai-engineering-loop/examples/dot/attendance-confirmation/judge-verdict.md)**:
20
+ - Audit of unit test results, typecheck logs, finding resolutions, and issuance of `PASS` verdict.
21
+ 4. **[Stage 4: DOT Delivery Pipeline (`delivery-report.md`)](file:///Users/egagofur/Development/work/ai-engineering-loop/examples/dot/attendance-confirmation/delivery-report.md)**:
22
+ - Creation of GitLab Issue #307, base MR !946, multi-branch propagation to `staging` (!947) and `develop` (!948), Coreview bot triage, and automated Mattermost channel notification.
@@ -0,0 +1,51 @@
1
+ # DOT Delivery Report: Attendance Confirmation Fix
2
+
3
+ ## 1. Summary of Delivery Actions
4
+
5
+ Upon receiving the `PASS` verdict from the Judge Agent, the DOT Delivery Adapter executed the following release actions:
6
+
7
+ 1. **GitLab Issue Created**: [Issue #307 - [BE] [Attendance] Fix Attendance Confirmation Display Status](https://gitlab.dot.co.id/dot-system/dotify-new/-/issues/307).
8
+ 2. **Primary MR Created**: [MR !946 targeting `main`](https://gitlab.dot.co.id/dot-system/dotify-new/-/merge_requests/946).
9
+ 3. **Multi-Branch Cherry-Pick**:
10
+ - [MR !947 targeting `staging`](https://gitlab.dot.co.id/dot-system/dotify-new/-/merge_requests/947).
11
+ - [MR !948 targeting `develop`](https://gitlab.dot.co.id/dot-system/dotify-new/-/merge_requests/948).
12
+ 4. **Coreview Bot Triage**:
13
+ - Comments fetched on MR !948. Zero blocking comments found.
14
+ 5. **Mattermost Notification**:
15
+ - Resolved repository `dot-system/dotify-new` to channel `"internal-dotify"`.
16
+ - Dispatched Markdown report via MCP `mattermost_send_message` with `from: "AI Agent"`.
17
+
18
+ ---
19
+
20
+ ## 2. GitLab Links
21
+
22
+ | Artifact | Branch | Link |
23
+ |---|---|---|
24
+ | **GitLab Issue** | — | `[Issue #307](https://gitlab.dot.co.id/dot-system/dotify-new/-/issues/307)` |
25
+ | **Merge Request DEV** | `develop` | `[MR !948](https://gitlab.dot.co.id/dot-system/dotify-new/-/merge_requests/948)` |
26
+ | **Merge Request STAGING** | `staging` | `[MR !947](https://gitlab.dot.co.id/dot-system/dotify-new/-/merge_requests/947)` |
27
+ | **Merge Request MAIN** | `main` | `[MR !946](https://gitlab.dot.co.id/dot-system/dotify-new/-/merge_requests/946)` |
28
+
29
+ ---
30
+
31
+ ## 3. Dispatched Mattermost Notification
32
+
33
+ ```text
34
+ [MR DEV] https://gitlab.dot.co.id/dot-system/dotify-new/-/merge_requests/948
35
+ Changes log
36
+ - Include user.type.hasNormalHours and timeEntities.overtimeNote in attendanceConfirmationPagination Prisma query.
37
+ - Create resolveAttendanceConfirmationDisplayStatus utility to properly evaluate hasPendingTimeEntities by checking overtimeNote, isWeekend, duration > 8, non-normal hours employees, and null statuses.
38
+ - Add comprehensive unit tests in src/server/attendance-confirmations/utils/resolve-display-status.test.ts covering all status permutations.
39
+
40
+ [MR STAGING] https://gitlab.dot.co.id/dot-system/dotify-new/-/merge_requests/947
41
+ Changes log
42
+ - Include user.type.hasNormalHours and timeEntities.overtimeNote in attendanceConfirmationPagination Prisma query.
43
+ - Create resolveAttendanceConfirmationDisplayStatus utility to properly evaluate hasPendingTimeEntities by checking overtimeNote, isWeekend, duration > 8, non-normal hours employees, and null statuses.
44
+ - Add comprehensive unit tests in src/server/attendance-confirmations/utils/resolve-display-status.test.ts covering all status permutations.
45
+
46
+ [MR MAIN] https://gitlab.dot.co.id/dot-system/dotify-new/-/merge_requests/946
47
+ Changes log
48
+ - Include user.type.hasNormalHours and timeEntities.overtimeNote in attendanceConfirmationPagination Prisma query.
49
+ - Create resolveAttendanceConfirmationDisplayStatus utility to properly evaluate hasPendingTimeEntities by checking overtimeNote, isWeekend, duration > 8, non-normal hours employees, and null statuses.
50
+ - Add comprehensive unit tests in src/server/attendance-confirmations/utils/resolve-display-status.test.ts covering all status permutations.
51
+ ```
@@ -0,0 +1,39 @@
1
+ # Goal Contract: Attendance Confirmation Display Status Fix
2
+
3
+ ## 1. Objective
4
+ Fix the incorrect calculation of attendance confirmation display statuses across list and pagination endpoints when time entities contain overtime notes, weekend logs, non-normal hours employees, or null record states.
5
+
6
+ ## 2. Business Outcome & User Lifecycle Impact
7
+ - **Employees**: View accurate confirmation statuses (APPROVED, REJECTED, NEED_APPROVAL) reflecting their true attendance record.
8
+ - **Managers / Reviewers**: Stop receiving false-positive pending approval notifications for already-settled weekend logs.
9
+ - **HR & Payroll**: Accurate cumulative duration calculations for payroll export.
10
+
11
+ ## 3. Acceptance Criteria (AC)
12
+ - [ ] **AC-1**: If an employee has `hasNormalHours = true` and `duration <= 8` on a standard weekday without overtime notes, display status must resolve to `APPROVED` or `NEED_APPROVAL` strictly based on clock-in/out presence.
13
+ - [ ] **AC-2**: If `overtimeNote` exists or `duration > 8` or `isWeekend = true`, evaluate pending status across all associated `timeEntities`.
14
+ - [ ] **AC-3**: Non-normal hours employees (`user.type.hasNormalHours = false`) must not be evaluated under 8-hour weekday thresholds.
15
+ - [ ] **AC-4**: Null or missing time entity collections must default safely to `APPROVED` without throwing runtime `TypeError`.
16
+ - [ ] **AC-5**: Backward compatibility of the tRPC/REST response contract must be strictly preserved.
17
+
18
+ ## 4. Technical Constraints
19
+ - Preserve existing Prisma query schemas in `attendanceConfirmationPagination`.
20
+ - Centralize logic in a pure, testable utility function: `resolveAttendanceConfirmationDisplayStatus`.
21
+ - No new external runtime dependencies (use existing `dayjs` and `lodash` packages).
22
+ - 0 TypeScript compiler errors on `tsc --noEmit`.
23
+
24
+ ## 5. Out of Scope
25
+ - Modifying the UI frontend component layouts in `dotify-new/web`.
26
+ - Database schema migrations or alter table statements.
27
+ - Changing payroll export report generation scripts.
28
+
29
+ ## 6. Verification Requirements
30
+ - **Unit Tests**: Comprehensive Jest test suite in `src/server/attendance-confirmations/utils/resolve-display-status.test.ts` covering 100% of branches.
31
+ - **Typecheck**: `npx tsc --noEmit` exits with 0.
32
+ - **Linter**: `npx eslint --fix` on modified files with 0 errors.
33
+ - **Regression**: Run entire test suite: `npx jest --testPathIgnorePatterns="dotify-api"`.
34
+
35
+ ## 7. Definition of Done (DoD)
36
+ - [ ] All AC-1 through AC-5 proven by unit tests.
37
+ - [ ] Deterministic verification passes 100%.
38
+ - [ ] Devil's Advocate review conducted with 0 unresolved blocking findings.
39
+ - [ ] Judge issues PASS verdict.
@@ -0,0 +1,43 @@
1
+ # Judge Evaluation Report: Attendance Confirmation Fix
2
+
3
+ ## 1. Executive Verdict
4
+ - **Verdict**: `PASS`
5
+ - **Iteration**: `Iteration 2 of 3`
6
+ - **Confidence**: `HIGH`
7
+
8
+ ---
9
+
10
+ ## 2. Deterministic Verification Audit
11
+
12
+ | Check | Command Executed | Raw Result | Status |
13
+ |---|---|---|:---:|
14
+ | **Unit Tests** | `npx jest src/server/attendance-confirmations/utils/resolve-display-status.test.ts` | `Tests: 12 passed, 12 total. Snapshots: 0. Time: 1.42s` | ✅ PASS |
15
+ | **Full Suite** | `npx jest --testPathIgnorePatterns="dotify-api"` | `Test Suites: 48 passed, 48 total. Tests: 382 passed.` | ✅ PASS |
16
+ | **TypeScript** | `npx tsc --noEmit` | `Exit code 0. Zero errors.` | ✅ PASS |
17
+ | **Linter** | `npx eslint --fix src/server/attendance-confirmations/**` | `0 errors, 0 warnings found.` | ✅ PASS |
18
+
19
+ ---
20
+
21
+ ## 3. Goal Contract Compliance Audit
22
+
23
+ | Criterion | Verified By Test / Artifact | Result |
24
+ |---|---|:---:|
25
+ | **AC-1**: Normal hours weekday calculation | `resolve-display-status.test.ts > normal hours` | ✅ PASS |
26
+ | **AC-2**: Weekend & duration > 8 handling | `resolve-display-status.test.ts > weekend overtime` | ✅ PASS |
27
+ | **AC-3**: Non-normal hours employee rules | `resolve-display-status.test.ts > shift worker` | ✅ PASS |
28
+ | **AC-4**: Null & undefined timeEntities safety | `resolve-display-status.test.ts > null safety` | ✅ PASS |
29
+ | **AC-5**: API Contract Preservation | `tRPC router typecheck` | ✅ PASS |
30
+
31
+ ---
32
+
33
+ ## 4. Finding Triage Audit
34
+
35
+ - **COR-001 (High - Null Safety)**: Maker applied null coalescing in Iteration 2. Verified via fresh test execution. **Status: RESOLVED & VERIFIED**.
36
+ - **MAINT-001 (Low - Factory Suggestion)**: Overridden by Judge as invalid speculative nitpick. **Status: DISMISSED / INVALID**.
37
+
38
+ ---
39
+
40
+ ## 5. Formal Conclusion & Hand-off
41
+
42
+ The Definition of Done has been 100% satisfied with reproducible evidence.
43
+ **Authorized next action**: Proceed to [DOT Delivery Adapter](file:///Users/egagofur/Development/work/ai-engineering-loop/adapters/dot/README.md) for GitLab MR generation, multi-branch cherry-picking, Coreview triage, and Mattermost notification.
@@ -0,0 +1,57 @@
1
+ # Adversarial Review Findings & Triage: Attendance Confirmation Fix
2
+
3
+ ## 1. Review Summary
4
+
5
+ - **Reviewer**: Devil's Advocate Agent
6
+ - **Target Branch**: `main...fix/attendance-confirmation-status`
7
+ - **Total Findings**: 2
8
+ - **Blocking (SEV-1/2)**: 1
9
+ - **Non-Blocking / Invalid**: 1
10
+
11
+ ---
12
+
13
+ ## 2. Findings Ledger
14
+
15
+ ### Finding COR-001: Missing null safety when iterating `timeEntities`
16
+ - **Severity**: `HIGH` (SEV-2)
17
+ - **Category**: `Correctness`
18
+ - **Location**: `src/server/attendance-confirmations/utils/resolve-display-status.ts:34-41`
19
+ - **Evidence**:
20
+ ```typescript
21
+ const hasPending = confirmation.timeEntities.some(
22
+ (entity) => entity.status === "NEED_APPROVAL"
23
+ );
24
+ ```
25
+ - **Problem**:
26
+ If `confirmation.timeEntities` is `null` or `undefined` (which occurs for historical attendance records prior to migration v2.4), calling `.some()` throws a runtime `TypeError: Cannot read properties of undefined (reading 'some')`.
27
+ - **Impact**:
28
+ Crashing pagination API for employees with legacy historical attendance records.
29
+ - **Recommendation**:
30
+ ```diff
31
+ - const hasPending = confirmation.timeEntities.some(
32
+ + const hasPending = (confirmation.timeEntities ?? []).some(
33
+ (entity) => entity.status === "NEED_APPROVAL"
34
+ );
35
+ ```
36
+ - **Confidence**: `HIGH`
37
+ - **Status**: `TRIAGED_VALID`
38
+ - **Resolution**:
39
+ Maker Agent applied optional chaining and null coalescing `(confirmation.timeEntities ?? [])` and added unit test case `should return APPROVED when timeEntities is null or undefined` in `resolve-display-status.test.ts`.
40
+
41
+ ---
42
+
43
+ ### Finding MAINT-001: Suggestion to convert helper into an abstract factory class
44
+ - **Severity**: `LOW` (SEV-4)
45
+ - **Category**: `Maintainability`
46
+ - **Location**: `src/server/attendance-confirmations/utils/resolve-display-status.ts:1-50`
47
+ - **Evidence**:
48
+ Utility is authored as a pure exported function `export function resolveAttendanceConfirmationDisplayStatus(...)`.
49
+ - **Problem**:
50
+ Reviewer claimed that an object-oriented Strategy/Factory pattern would allow swapping attendance status calculators in the future.
51
+ - **Impact**:
52
+ None. Pure functions are more testable, tree-shakeable, and align with current repository conventions.
53
+ - **Recommendation**: Refactor to `class AttendanceStatusCalculatorFactory`.
54
+ - **Confidence**: `LOW`
55
+ - **Status**: `TRIAGED_INVALID`
56
+ - **Triage Reason**:
57
+ Dismissed as speculative overengineering. Repository architecture uses functional utilities with tRPC. Adding a class factory violates Technical Constraint: *"Produce minimal, surgical changes without speculative abstractions."*
@@ -0,0 +1,19 @@
1
+ # Reference Example: Automatic Project Initialization & Discovery
2
+
3
+ ## 1. Overview & Scenario
4
+
5
+ This walkthrough demonstrates how the **AI Engineering Loop** automatically initializes an unconfigured full-stack TypeScript and Go monorepo (`acme-platform`) that contains **zero** existing `.ai-engineering-loop/` configuration.
6
+
7
+ ### The Codebase State:
8
+ - **Repository**: `acme-corp/acme-platform`
9
+ - **Existing Config**: `pnpm-workspace.yaml`, `turbo.json`, `apps/web/package.json` (Next.js), `apps/api/go.mod` (Go/Gin), `packages/ui/`
10
+ - **Initial Status**: No `.ai-engineering-loop/` folder present.
11
+
12
+ ---
13
+
14
+ ## 2. Walkthrough Artifacts
15
+
16
+ 1. **[Discovery Execution Trace (`discovery-trace.md`)](file:///Users/egagofur/Development/work/ai-engineering-loop/examples/initialization/discovery-trace.md)**:
17
+ - Full 5-pass log of directory inspection, manifest parsing, script discovery, architecture tracing, and second-pass quality check.
18
+ 2. **[Generated Context Artifacts (`generated-context.md`)](file:///Users/egagofur/Development/work/ai-engineering-loop/examples/initialization/generated-context.md)**:
19
+ - The exact evidence-based `.ai-engineering-loop/` files generated automatically by the agent without user intervention.
@@ -0,0 +1,63 @@
1
+ # Discovery Execution Trace: `acme-platform`
2
+
3
+ ## 1. Trigger & Initial Detection
4
+
5
+ ```text
6
+ [ENGINE] Initializing workspace in /workspaces/acme-platform
7
+ [ENGINE] Checking for .ai-engineering-loop/... NOT FOUND.
8
+ [ENGINE] Triggering State B: Autonomous Project Initialization & Discovery.
9
+ ```
10
+
11
+ ---
12
+
13
+ ## 2. The 5-Pass Discovery Log
14
+
15
+ ### Pass 1: Topology & Workspace Inspection
16
+ - `list_dir /workspaces/acme-platform`:
17
+ - `apps/` (contains `web/`, `api/`)
18
+ - `packages/` (contains `ui/`, `database/`, `shared/`)
19
+ - `pnpm-workspace.yaml` (detected `pnpm` monorepo)
20
+ - `turbo.json` (detected Turborepo pipeline)
21
+ - **Profile Binding**: Bound [`profiles/monorepo.md`](file:///Users/egagofur/Development/work/ai-engineering-loop/profiles/monorepo.md).
22
+
23
+ ### Pass 2: Manifests & Verification Commands Discovery
24
+ - Parsed `package.json` (root):
25
+ - `"test"`: `"turbo run test"`
26
+ - `"typecheck"`: `"turbo run typecheck"`
27
+ - `"lint"`: `"turbo run lint"`
28
+ - `"build"`: `"turbo run build"`
29
+ - Parsed `apps/api/go.mod`:
30
+ - Go 1.22, Gin framework, pgx
31
+ - Extracted Commands:
32
+ - Unit Tests: `pnpm test` (or `pnpm --filter @acme/web test` for focused web)
33
+ - Typecheck: `pnpm typecheck`
34
+ - Linter: `pnpm lint`
35
+ - Build: `pnpm build`
36
+
37
+ ### Pass 3: Architecture & Invariant Mapping
38
+ - **Presentation**: Next.js 14 App Router in `apps/web/src/app`, Gin REST API in `apps/api/cmd/server`.
39
+ - **Data Access**: PostgreSQL + Prisma in `packages/database`.
40
+ - **Shared UI**: Tailwind + Radix UI in `packages/ui`.
41
+ - **Boundaries**: `packages/ui` and `packages/database` are shared dependencies; `apps/web` must not import `apps/api` internal code.
42
+
43
+ ### Pass 4: Observed Conventions Extraction
44
+ - File naming: `kebab-case` throughout `apps/web` and `packages/ui`.
45
+ - Error handling: Go API returns `{"error": {"code": "...", "message": "..."}}`.
46
+ - Git remote: `origin -> https://github.com/acme-corp/acme-platform.git`.
47
+ - Adapter: Bound GitHub Adapter.
48
+
49
+ ### Pass 5: Second-Pass Context Quality Audit
50
+ - Evidence check: 100% of claims attributed to files.
51
+ - Secret check: `.env` and `.env.local` skipped; `.env.example` verified safe. Zero leaked credentials.
52
+ - Conciseness check: 180 total lines generated across `.ai-engineering-loop/`.
53
+ - Status: **PASSED QUALITY AUDIT**.
54
+
55
+ ---
56
+
57
+ ## 3. Completion & Hand-off
58
+
59
+ ```text
60
+ [ENGINE] Generated .ai-engineering-loop/ (config.md, architecture.md, conventions.md, verification.md, adapter.md)
61
+ [ENGINE] Project Context successfully initialized!
62
+ [ENGINE] Proceeding to Goal Contract formulation...
63
+ ```
@@ -0,0 +1,110 @@
1
+ # Generated Context Artifacts: `acme-platform`
2
+
3
+ Below are the exact 5 files generated automatically inside `/workspaces/acme-platform/.ai-engineering-loop/`:
4
+
5
+ ---
6
+
7
+ ## 1. `.ai-engineering-loop/config.md`
8
+
9
+ ```markdown
10
+ # Project Configuration
11
+
12
+ ## Metadata
13
+ - **project_name**: "acme-platform"
14
+ - **project_profile**: "monorepo" # Archetype bound from profiles/monorepo.md
15
+ - **languages**:
16
+ - TypeScript 5.4 (Node.js 20.x)
17
+ - Go 1.22
18
+ - **frameworks**:
19
+ - Next.js 14 (App Router)
20
+ - Gin Web Framework
21
+ - Prisma ORM
22
+ - **package_manager**: "pnpm" (Turborepo workspace)
23
+ - **default_base_branch**: "main"
24
+
25
+ ## Evidence
26
+ - Topology: `pnpm-workspace.yaml`, `turbo.json`
27
+ - Apps: `apps/web/package.json`, `apps/api/go.mod`
28
+ - Shared: `packages/ui/package.json`, `packages/database/prisma/schema.prisma`
29
+ ```
30
+
31
+ ---
32
+
33
+ ## 2. `.ai-engineering-loop/architecture.md`
34
+
35
+ ```markdown
36
+ # Project Architecture
37
+
38
+ ## System Overview
39
+ Full-stack monorepo featuring a Next.js 14 web application, a Go backend API service, and shared UI/database packages.
40
+
41
+ ## Applications & Packages
42
+ - `apps/web`: Next.js 14 frontend client rendering UI.
43
+ - `apps/api`: Go Gin REST service handling payments and user records.
44
+ - `packages/ui`: Shared React/Tailwind component library.
45
+ - `packages/database`: Centralized Prisma client and database schemas.
46
+
47
+ ## Boundary Invariants
48
+ - `packages/ui` must not import backend API logic.
49
+ - `apps/web` must not connect directly to the database; it queries `apps/api` via REST.
50
+ - Shared packages must maintain zero cyclic dependencies.
51
+
52
+ ## Evidence & Confidence
53
+ - Observed from: `apps/`, `packages/`, `turbo.json`
54
+ - Confidence: HIGH
55
+ ```
56
+
57
+ ---
58
+
59
+ ## 3. `.ai-engineering-loop/conventions.md`
60
+
61
+ ```markdown
62
+ # Project Conventions
63
+
64
+ ## Code Standards
65
+ - File naming: `kebab-case` for TypeScript components and Go files.
66
+ - Test placement: Colocated `*.test.tsx` in `apps/web`; `*_test.go` in `apps/api`.
67
+ - Design tokens: Use Tailwind utility classes with colors defined in `packages/ui/tailwind.config.js`.
68
+
69
+ ## Forbidden Anti-Patterns
70
+ - Zero `any` types in TypeScript packages.
71
+ - Zero unchecked error returns in Go (`if err != nil` is mandatory).
72
+ - Do not commit or hardcode environment URLs.
73
+ ```
74
+
75
+ ---
76
+
77
+ ## 4. `.ai-engineering-loop/verification.md`
78
+
79
+ ```markdown
80
+ # Project Verification Commands
81
+
82
+ ## Workspace Package Manager
83
+ pnpm (Turborepo)
84
+
85
+ ## Commands
86
+ - **test_unit**: `pnpm test`
87
+ - **test_scoped**: `pnpm --filter <package-name> test`
88
+ - **typecheck**: `pnpm typecheck`
89
+ - **lint**: `pnpm lint`
90
+ - **build**: `pnpm build`
91
+
92
+ ## Required Verification by Scope
93
+ - **Web changes**: `pnpm --filter @acme/web test` and `pnpm --filter @acme/web typecheck`.
94
+ - **API changes**: `cd apps/api && go test -v ./...` and `golangci-lint run`.
95
+ - **Database changes**: `pnpm --filter @acme/database test`.
96
+ ```
97
+
98
+ ---
99
+
100
+ ## 5. `.ai-engineering-loop/adapter.md`
101
+
102
+ ```markdown
103
+ # Project Delivery Adapter Configuration
104
+
105
+ ## Delivery Pipeline
106
+ - **adapter_type**: "github"
107
+ - **repository**: "acme-corp/acme-platform"
108
+ - **default_target_branch**: "main"
109
+ - **ci_workflows**: GitHub Actions (`.github/workflows/ci.yml`)
110
+ ```
@@ -0,0 +1,33 @@
1
+ # Reference Example: Mobile App Offline Sync Queue
2
+
3
+ ## 1. Scenario Overview
4
+
5
+ This walkthrough demonstrates the **AI Engineering Loop** operating in a **Mobile Application** repository (`mobile-app` profile) for a field survey application built in Flutter / SQLite.
6
+
7
+ ### The Problem
8
+ Field inspectors working in remote areas without cellular coverage experienced loss of submitted inspection forms when the application was closed or terminated by the OS before regaining an internet connection.
9
+
10
+ ---
11
+
12
+ ## 2. Dynamic Context Resolution
13
+
14
+ ```text
15
+ Engine: AI Engineering Loop Core
16
+ Profile: profiles/mobile-app.md
17
+ Repo Config: inspector-app/.ai-engineering-loop/ (Flutter 3.22, sqflite, Riverpod)
18
+ Task: Implement persistent offline SQLite mutation queue with exponential backoff sync
19
+ ```
20
+
21
+ ---
22
+
23
+ ## 3. Walkthrough Artifacts
24
+
25
+ 1. **[Goal Contract (`goal-contract.md`)](file:///Users/egagofur/Development/work/ai-engineering-loop/examples/mobile-app/offline-sync-queue/goal-contract.md)**:
26
+ - AC-1: All form submissions persist immediately to local SQLite `mutation_queue` table before network dispatch.
27
+ - AC-2: Background sync engine triggers on network restoration with exponential backoff.
28
+ - AC-3: OS suspension / app kill must not drop un-synced items.
29
+ 2. **[Adversarial Review Findings (`review-findings.md`)](file:///Users/egagofur/Development/work/ai-engineering-loop/examples/mobile-app/offline-sync-queue/review-findings.md)**:
30
+ - Devil's Advocate activates `mobile-app` rules (offline persistence, lifecycle, battery).
31
+ - Flags missing disk write error handling when device storage is full (`PERF-001`).
32
+ 3. **[Judge Verdict (`judge-verdict.md`)](file:///Users/egagofur/Development/work/ai-engineering-loop/examples/mobile-app/offline-sync-queue/judge-verdict.md)**:
33
+ - Audits Flutter unit & mock network tests, verifies 100% pass, and issues `PASS` verdict.
@@ -0,0 +1,32 @@
1
+ # Goal Contract: Offline Mutation Queue & Sync Engine
2
+
3
+ ## 1. Objective
4
+ Implement an offline-first transactional queue in SQLite that captures user inspection submissions locally and synchronizes reliably with the cloud API upon network reconnection.
5
+
6
+ ## 2. Business Outcome & User Lifecycle Impact
7
+ - **Field Inspectors**: Can complete and save survey reports anywhere with zero risk of data loss.
8
+ - **Operations**: Automatic background upload with zero manual re-entry.
9
+
10
+ ## 3. Acceptance Criteria (AC)
11
+ - [ ] **AC-1**: Submissions write to local SQLite `mutation_queue` with status `PENDING` before network attempt.
12
+ - [ ] **AC-2**: Connectivity changes trigger FIFO queue processing with max 3 retry attempts per item.
13
+ - [ ] **AC-3**: Simulated app kill during background sync resumes cleanly upon next launch.
14
+ - [ ] **AC-4**: Zero data loss under intermittent network flapping (3G/offline transitions).
15
+
16
+ ## 4. Technical Constraints
17
+ - Flutter 3.22, Dart 3.4, `sqflite` for local DB, `connectivity_plus` for network state.
18
+ - Pure Dart logic for sync manager with zero direct UI widget dependencies.
19
+
20
+ ## 5. Out of Scope
21
+ - Modifying survey form UI layout or camera image capture compression.
22
+
23
+ ## 6. Verification Requirements
24
+ - **Unit & Mock Tests**: `flutter test test/core/sync/offline_queue_test.dart`
25
+ - **Static Analysis**: `dart analyze`
26
+ - **Build Check**: `flutter build bundle`
27
+
28
+ ## 7. Definition of Done (DoD)
29
+ - [ ] All AC-1 through AC-4 proven via unit & repository test suites.
30
+ - [ ] Static analysis 0 issues.
31
+ - [ ] Devil's Advocate review conducted with 0 unresolved blocking findings.
32
+ - [ ] Judge issues PASS verdict.
@@ -0,0 +1,27 @@
1
+ # Judge Evaluation Report: Offline Sync Queue
2
+
3
+ ## 1. Executive Verdict
4
+ - **Verdict**: `PASS`
5
+ - **Iteration**: `Iteration 2 of 3`
6
+ - **Confidence**: `HIGH`
7
+
8
+ ---
9
+
10
+ ## 2. Deterministic Verification Audit
11
+
12
+ | Check | Command Executed | Raw Result | Status |
13
+ |---|---|---|:---:|
14
+ | **Unit & Sync Tests** | `flutter test test/core/sync/` | `00:04 +18: All tests passed!` | ✅ PASS |
15
+ | **Static Analysis** | `dart analyze` | `No issues found! (ran in 1.8s)` | ✅ PASS |
16
+ | **Asset Bundle** | `flutter build bundle` | `Bundle built successfully.` | ✅ PASS |
17
+
18
+ ---
19
+
20
+ ## 3. Finding Triage Audit
21
+ - **ERR-001 (High - SQLite Disk Full Crash)**: Resolved by wrapping insert operations with domain exception handlers and fallback telemetry. **Status: RESOLVED & VERIFIED**.
22
+
23
+ ---
24
+
25
+ ## 4. Hand-off
26
+ All Definition of Done criteria are satisfied.
27
+ **Authorized next action**: Proceed to designated mobile release pipeline.