@leejungkiin/awkit 1.7.4 → 1.7.6

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,55 @@
1
+ # Product Requirements Document (PRD) — MemoizedFibonacci
2
+
3
+ ## Revision History
4
+
5
+ | Version | Date | Author | Description |
6
+ | :--- | :--- | :--- | :--- |
7
+ | 1.0 | 2026-06-22 | Antigravity Orchestrator | Initial draft for MemoizedFibonacci feature. |
8
+
9
+ ---
10
+
11
+ ## 1. Vision & Objectives
12
+
13
+ * **Project Summary:** The `MemoizedFibonacci` feature provides a highly optimized, high-performance utility class/module for calculating Fibonacci sequences. It leverages an advanced caching (memoization) mechanism to avoid the exponential time complexity $O(2^n)$ associated with naive recursive methods, turning sequence generation into a linear time $O(n)$ or constant-time $O(1)$ operation for subsequent lookups.
14
+ * **Problem Statement:** Standard recursive calculations of Fibonacci numbers quickly exhaust CPU resources and crash due to call stack size limits or integer overflows when $n \ge 79$ in standard floating-point representation. Naive memory caches can also grow indefinitely, leading to memory leaks in server environments.
15
+ * **Target Audience:** Core application developers, backend engineers running mathematical modeling services, and background agents requiring sequence calculations.
16
+
17
+ ---
18
+
19
+ ## 2. Core Principles & Philosophy
20
+
21
+ * **Performance & Scalability:** Constant lookups $O(1)$ for cached values, linear complexity $O(n)$ for first-time calculations.
22
+ * **Robustness & Accuracy:** Complete support for `BigInt` calculations to prevent integer overflow beyond JS safe limit ($n > 78$).
23
+ * **Memory Safety & Self-Regulation:** Integrated Least Recently Used (LRU) cache eviction strategy to guarantee a fixed maximum memory footprint.
24
+ * **Non-Blocking Operation:** Heavy calculations ($n \ge 100,000$) must run asynchronously (chunked loops or offloaded execution) to prevent thread/event-loop blockage.
25
+
26
+ ---
27
+
28
+ ## 3. Scope & Feature List
29
+
30
+ ### In Scope
31
+ * **Multiple Calculation Modes:** Synchronous calculations for small inputs; asynchronous (non-blocking) computation for larger values.
32
+ * **Flexible Precision:** Standard JS numbers for fast calculations ($n \le 78$) and `BigInt` for arbitrarily large numbers.
33
+ * **LRU Caching Strategy:** A bounded in-memory cache that automatically evicts least recently accessed Fibonacci numbers when the maximum cache capacity is reached.
34
+ * **Cache Metrics:** Reporting of cache metrics such as hit rate, miss rate, current size, and eviction count.
35
+ * **Resource Guardrails:** Hard limits on inputs to prevent CPU exhaustion.
36
+
37
+ ### Out of Scope
38
+ * **Negative/Fractional Fibonacci:** No support for negative numbers or fractional inputs (standard integer sequence only).
39
+ * **Distributed Cache integration:** No built-in Redis/Memcached integration (limited to localized, bounded memory cache with extensible hooks).
40
+
41
+ ---
42
+
43
+ ## 4. Key Performance Indicators (KPIs)
44
+
45
+ * **Execution Time (Cached):** Sub-microsecond response time for any cached value.
46
+ * **Execution Time (Uncached):** Linear scaling $O(n)$. Computing $F(10000)$ uncached must complete in under 5 milliseconds.
47
+ * **Call Stack Safety:** Zero recursion-based Call Stack Size Exceeded errors.
48
+ * **Memory Limit:** Strict enforcement of maximum cache entries (e.g. defaults to 1,000 values), keeping peak memory consumption under 25MB even for large BigInts.
49
+
50
+ ---
51
+
52
+ ## 5. Anti-Patterns (What NOT to do)
53
+ * Do not use recursive calls without tail call optimization or loop conversion. Recursion is forbidden for calculations.
54
+ * Do not store calculated BigInt values as standard floats since precision is lost.
55
+ * Do not allow the cache size to grow indefinitely (bounded cache is mandatory).
@@ -0,0 +1,57 @@
1
+ # Product Requirement Document (PRD) - GreetingApp
2
+
3
+ ## Revision History
4
+ | Version | Date | Description | Author |
5
+ |---|---|---|---|
6
+ | v1.0 | 2026-06-22 | Initial PRD for GreetingApp | Antigravity Orchestrator |
7
+
8
+ ---
9
+
10
+ ## 1. Executive Summary
11
+ GreetingApp is a micro-application designed to deliver personalized, localized, and dynamic greetings to users. It adapts to the user's name, current time of day, and language preferences.
12
+
13
+ ## 2. Objectives & Goals
14
+ - Provide dynamic greetings based on user local time (Morning, Afternoon, Evening, Night).
15
+ - Support multi-language greetings (English, Vietnamese, Japanese).
16
+ - Track user greeting history and statistics.
17
+ - Expose both CLI and REST API interfaces.
18
+
19
+ ## 3. User Personas & Use Cases
20
+ - **End User:** Wants to see a welcoming, contextual message when logging in or using the CLI.
21
+ - **Developer:** Wants an easy-to-integrate greeting microservice API for downstream services.
22
+
23
+ ## 4. Functional Requirements
24
+ 1. **Dynamic Greeting Generation:**
25
+ - Detects local time of user.
26
+ - Personalizes with name (fallback to "Guest").
27
+ 2. **Localization (i18n):**
28
+ - Supports: English (`en`), Vietnamese (`vi`), Japanese (`ja`).
29
+ 3. **Greeting Analytics / History:**
30
+ - Stores logs of generated greetings (User, Timestamp, Language).
31
+ - Exposes statistics (e.g., total greetings generated, most active user).
32
+ 4. **Interfaces:**
33
+ - Command Line Interface (CLI): `awkit greet --name=Alice`
34
+ - REST API endpoint: `GET /api/greet?name=Alice&lang=vi`
35
+
36
+ ## 5. Non-Functional Requirements
37
+ - **Performance:** Response time for greeting generation under 50ms.
38
+ - **Reliability:** Storage fallback to memory if database/file storage is offline.
39
+ - **Extensibility:** Easy configuration to add new languages.
40
+
41
+ ## 6. System Flow & Sequence Diagram
42
+ ```mermaid
43
+ sequenceDiagram
44
+ autonumber
45
+ actor User
46
+ participant Client as CLI / API Client
47
+ participant Engine as Greeting Engine
48
+ participant DB as Storage / History DB
49
+
50
+ User->>Client: Triggers greeting command/request (name, lang)
51
+ Client->>Engine: Resolve greeting configuration
52
+ Engine->>Engine: Validate input & detect Time of Day
53
+ Engine->>DB: Log transaction (user, time, format)
54
+ DB-->>Engine: Log confirmation
55
+ Engine->>Client: Return formatted greeting string
56
+ Client->>User: Display greeting output
57
+ ```
@@ -1,58 +1,62 @@
1
- # Add Game Development Skills (Unity, Godot, Expo)
1
+ # Implementation Plan - GreetingApp Feature
2
2
 
3
- Implement dedicated game development skills inside `main-awf/skills` to enhance the orchestrator's capability in building games using Unity, Godot, and Expo.
4
-
5
- ## User Review Required
6
-
7
- > [!NOTE]
8
- > All new skills will be created directly in `skills/` of `main-awf` workspace and then deployed to `~/.gemini/antigravity` via `awkit install`.
9
-
10
- ## Proposed Changes
11
-
12
- ### AWKit Skills
3
+ ## Revision History
4
+ | Version | Date | Description | Author |
5
+ |---|---|---|---|
6
+ | v1.0 | 2026-06-22 | Initial implementation plan for GreetingApp | Antigravity Orchestrator |
13
7
 
14
8
  ---
15
9
 
16
- #### [NEW] [unity-game-development/SKILL.md](file:///Users/trungkientn/Dev/NodeJS/main-awf/skills/unity-game-development/SKILL.md)
17
- Contains high-density instructions for Unity game development, enforcing:
18
- - C# coding style (PascalCase public, camelCase private, `m_` fields prefix).
19
- - Component-based architecture and ScriptableObjects for data-driven game structures.
20
- - Performance optimization: avoiding `Find`/`GetComponent` in hot paths (`Update()`), caching, object pooling.
21
- - Separate Editor code via `#if UNITY_EDITOR`.
22
- - Direct Unity MCP server integration.
23
-
24
- #### [NEW] [godot-game-development/SKILL.md](file:///Users/trungkientn/Dev/NodeJS/main-awf/skills/godot-game-development/SKILL.md)
25
- Contains guidelines for Godot 4.x game development, enforcing:
26
- - Godot 4 API standards (rejecting Godot 3 syntax).
27
- - GDScript style preferences (`@export`, `@onready`, `await` signals).
28
- - Composition-first scene tree structure over deep class inheritance.
29
- - Signal connection best practices (`signal.connect(callback)`).
30
- - Physics and locomotion handling via parameterless `move_and_slide()`.
31
-
32
- #### [NEW] [expo-game-development/SKILL.md](file:///Users/trungkientn/Dev/NodeJS/main-awf/skills/expo-game-development/SKILL.md)
33
- Contains instructions for Expo/React Native game development, covering:
34
- - High-frequency drawing techniques (React Native Skia, Expo GL/Three.js).
35
- - State optimization: keeping physics/game tick loop decoupled from heavy React re-renders.
36
- - User input handling (React Native Gesture Handler).
37
- - Game loop implementations using `requestAnimationFrame`.
38
- - Asset management and sound effects via `expo-av`.
10
+ ## 1. Objectives
11
+ Implement the GreetingApp feature within the `main-awf` workspace, integrating:
12
+ - A shared Greeting Engine at `core/GreetingEngine`.
13
+ - CLI Interface command `awkit greet` in `bin/awk.js`.
14
+ - REST API endpoint `GET /api/greet` in `symphony/app/api/greet/route.js`.
15
+ - Light history logging via JSON Lines at `~/.gemini/antigravity/greeting_history.jsonl` (and local project fallback).
39
16
 
40
17
  ---
41
18
 
42
- #### [MODIFY] [CATALOG.md](file:///Users/trungkientn/Dev/NodeJS/main-awf/skills/CATALOG.md)
43
- Add the three new skills to the active skills table.
44
-
45
- #### [MODIFY] [TRIGGER_INDEX.md](file:///Users/trungkientn/Dev/NodeJS/main-awf/skills/TRIGGER_INDEX.md)
46
- Register keywords and triggers for the new game skills.
19
+ ## 2. Proposed Changes
20
+
21
+ ### Phase A: Core Engine and Locales
22
+ #### 1. Locales Definition
23
+ Create locales JSON files under `core/GreetingEngine/locales/`:
24
+ - `en.json`: English templates.
25
+ - `vi.json`: Vietnamese templates.
26
+ - `ja.json`: Japanese templates.
27
+
28
+ #### 2. Greeting Engine (`core/GreetingEngine/index.js`)
29
+ Create the core processor. It will:
30
+ - Parse `name` (default: "Guest"), `lang` (default: "en"), and `timezone` (default: local).
31
+ - Determine time-of-day period (`morning` 5-11:59, `afternoon` 12-17:59, `evening` 18-21:59, `night` 22-4:59).
32
+ - Load localization strings, format the template by replacing `{name}`, and return the object.
33
+ - Record transactions to `greeting_history.jsonl`.
34
+ - Provide stats functions.
35
+
36
+ ### Phase B: CLI Integration
37
+ #### 1. CLI Commands (`bin/awk.js`)
38
+ - Register the `greet` subcommand in the main switch-case.
39
+ - Parse flags: `--name` / `-n`, `--lang` / `-l`, and `--timezone` / `-t` (or use system timezone).
40
+ - Print the generated greeting and save to the history log.
41
+
42
+ ### Phase C: REST API Integration
43
+ #### 1. API Route Handler (`symphony/app/api/greet/route.js`)
44
+ - Define `GET` handler.
45
+ - Extract `name`, `lang`, and `timezone` query parameters.
46
+ - Call the Greeting Engine.
47
+ - Return structured JSON response following spec.
47
48
 
48
49
  ---
49
50
 
50
- ## Verification Plan
51
+ ## 3. Verification Plan
51
52
 
52
- ### Automated Verification
53
- - Run `awkit status` to inspect mapping diffs.
54
- - Deploy to runtime using `awkit install`.
55
- - Verify CLI integration and syntax using `awkit doctor`.
53
+ ### Automated/Unit Tests
54
+ - Verify engine resolves times and timezones correctly.
55
+ - Verify fallback to `en` on unrecognized language inputs.
56
+ - Verify JSON structure matches specifications.
56
57
 
57
58
  ### Manual Verification
58
- - Ask the user to verify the added skills locally or confirm availability in future workspace tasks.
59
+ - Execute `node bin/awk.js greet --name="Alice" --lang="vi"`.
60
+ - Execute `node bin/awk.js greet --name="Bob" --lang="ja"`.
61
+ - Query Symphony REST API `/api/greet?name=Charlie&lang=en` locally.
62
+ - Inspect the history log at the designated path.
@@ -0,0 +1,87 @@
1
+ # Implementation Plan - Codex Goal Mode Integration
2
+
3
+ ## Revision History
4
+ | Version | Date | Description | Author |
5
+ |---|---|---|---|
6
+ | v1.0 | 2026-06-22 | Initial plan for Codex Goal Mode, skill, and workflow integration | Antigravity Orchestrator |
7
+
8
+ ---
9
+
10
+ ## Goal Description
11
+ Implement a **Goal Mode** (including a new **Skill** and a **Workflow**) that utilizes the Codex goal-execution capabilities for centralized task orchestration. In this mode, Codex serves as the master coordinator (Goal Conductor), partitioning a high-level user goal into subtasks, tracking progress in Symphony, and delegating specific duties back to other specialized agents (Claude, Qwen, Gemini/AGY) or its own independent sub-agents (e.g., critic, coder, tester, ios-engineer) in a collaborative loop.
12
+
13
+ ---
14
+
15
+ ## User Review Required
16
+
17
+ > [!IMPORTANT]
18
+ > **Orchestration Loop Protocol:** Codex Goal Mode runs as a closed-loop execution system. Checkpoints are automatically bypassed when `goal_mode = true` (using best-effort AI verification) except for safety-critical, destructive, or security tasks.
19
+
20
+ ---
21
+
22
+ ## Open Questions
23
+ - Do we want to support persistent background session resume for long-running goals (e.g., using `codex resume --last`)? *(Currently planned to support resume by storing execution states in `codex-reports/goals/`).*
24
+
25
+ ---
26
+
27
+ ## Proposed Changes
28
+
29
+ ### Core Orchestration Layer
30
+
31
+ #### [NEW] [codex-goal.js](file:///Users/trungkientn/Dev/NodeJS/main-awf/scripts/codex-goal.js)
32
+ Create a new script that coordinates the Goal loop:
33
+ 1. Initializes a goal workspace under `codex-reports/goals/<goal_id>/`.
34
+ 2. Sets `goal_mode = true` in the process context.
35
+ 3. Invokes Codex CLI to analyze the initial goal, parse it into subtasks, and map them to appropriate agents.
36
+ 4. Orchestrates task execution:
37
+ - For architecture & specs: Delegates to Claude via `scripts/claude-plan.js`.
38
+ - For coding/refactoring: Delegates to Qwen via `scripts/qwen-exec.js`.
39
+ - For general tasks/fallbacks: Delegates to AGY (Gemini).
40
+ - For reviews, tests, visual QA: Delegates to Codex sub-agents (`critic`, `tester`, `ios-visual-qa-strategist`).
41
+ 5. Tracks states, saves progress reports to `.md` files, and updates Symphony tickets.
42
+
43
+ ---
44
+
45
+ ### Workflows
46
+
47
+ #### [NEW] [goal.md](file:///Users/trungkientn/Dev/NodeJS/main-awf/workflows/lifecycle/goal.md)
48
+ Define the `/goal` workflow containing:
49
+ - Pre-requisites checks for Codex CLI.
50
+ - Workflow subcommands: `/goal "[objective]"`, `/goal:status`, `/goal:resume`, `/goal:pause`, `/goal:cancel`.
51
+ - Detailed description of the autonomous goal execution loop.
52
+ - Fallback policies and recovery steps.
53
+
54
+ ---
55
+
56
+ ### Skills
57
+
58
+ #### [NEW] [SKILL.md](file:///Users/trungkientn/Dev/NodeJS/main-awf/skills/codex-goal/SKILL.md)
59
+ Create a new skill for the Codex Goal Orchestrator defining:
60
+ - Developer instructions for the master Goal Conductor role.
61
+ - Task breakdown schemas and JSON mapping format.
62
+ - Sub-agent specifications (definitions, system prompts, capabilities).
63
+ - Call-back protocols for Claude, Qwen, and AGY.
64
+
65
+ ---
66
+
67
+ ### CLI & Code Integration
68
+
69
+ #### [MODIFY] [awk.js](file:///Users/trungkientn/Dev/NodeJS/main-awf/bin/awk.js)
70
+ 1. Register `goal` in the CLI command list and register the command parser.
71
+ 2. Include the new `/goal` and `/goal-mode` commands in the help usage block.
72
+ 3. Add the `codex-goal` skill folder to the default runtime list, ensuring it gets synced during `awkit install`.
73
+
74
+ #### [MODIFY] [codex-generators.js](file:///Users/trungkientn/Dev/NodeJS/main-awf/bin/codex-generators.js)
75
+ Add `codex-goal` to `SPECIALIST_SKILLS` list so that a Codex-compatible `.toml` agent spec is automatically generated for it.
76
+
77
+ ---
78
+
79
+ ## Verification Plan
80
+
81
+ ### Automated Tests
82
+ - Run `node bin/awk.js doctor` to check installation state.
83
+ - Run `awkit status` to ensure all files are synchronized.
84
+
85
+ ### Manual Verification
86
+ - Execute `node bin/awk.js goal "Build a simple greeting command line tool"` and verify that the orchestration loop initializes the plan, registers tasks, calls Qwen for implementation, and reviews using the critic sub-agent.
87
+ - Verify status checks, pause, and resume capabilities.
@@ -0,0 +1,127 @@
1
+ # Technical Specification — MemoizedFibonacci
2
+
3
+ ## Revision History
4
+
5
+ | Version | Date | Author | Description |
6
+ | :--- | :--- | :--- | :--- |
7
+ | 1.0 | 2026-06-22 | Antigravity Orchestrator | Initial technical design with Mermaid diagram, class architecture, and caching strategy. |
8
+
9
+ ---
10
+
11
+ ## 1. System Architecture
12
+
13
+ The `MemoizedFibonacci` feature consists of three primary layers:
14
+ 1. **API & Interface Layer:** Exposes synchronous and asynchronous methods to users.
15
+ 2. **LRU Cache Layer:** Manages in-memory storage of computed sequences with automatic eviction based on Least Recently Used patterns.
16
+ 3. **Computation Engine:** Performs iterative sequence calculations to prevent call stack overflow, handles dynamic upgrading to `BigInt` for large numbers, and schedules asynchronous chunks for heavy inputs.
17
+
18
+ ---
19
+
20
+ ## 2. API Design & Core Interface
21
+
22
+ ```typescript
23
+ interface FibonacciConfig {
24
+ maxCacheSize?: number; // Maximum number of entries in the cache (default: 1000)
25
+ useBigInt?: boolean; // Force BigInt computation even for small inputs (default: false)
26
+ asyncThreshold?: number; // Input size to trigger asynchronous execution (default: 50000)
27
+ }
28
+
29
+ interface CacheStats {
30
+ hits: number;
31
+ misses: number;
32
+ size: number;
33
+ evictions: number;
34
+ }
35
+
36
+ class MemoizedFibonacci {
37
+ private cache: Map<number, number | bigint>;
38
+ private lruList: number[]; // Tracks usage order (least recently used at the front)
39
+ private config: Required<FibonacciConfig>;
40
+ private stats: CacheStats;
41
+
42
+ constructor(config?: FibonacciConfig);
43
+
44
+ /**
45
+ * Calculates Fibonacci of n. Automatically picks sync/async mode based on threshold.
46
+ */
47
+ public async calculate(n: number): Promise<number | bigint>;
48
+
49
+ /**
50
+ * Synchronously calculates Fibonacci of n.
51
+ * Throws warning/error if n is larger than asyncThreshold.
52
+ */
53
+ public calculateSync(n: number): number | bigint;
54
+
55
+ /**
56
+ * Retreives cache usage statistics.
57
+ */
58
+ public getStats(): CacheStats;
59
+
60
+ /**
61
+ * Clears all cache entries and metrics.
62
+ */
63
+ public clearCache(): void;
64
+
65
+ /**
66
+ * Private helper implementing iterative Fibonacci sequence.
67
+ */
68
+ private computeIterative(n: number, isBigInt: boolean): number | bigint;
69
+ }
70
+ ```
71
+
72
+ ---
73
+
74
+ ## 3. Detailed Logic Flow (Mermaid Diagram)
75
+
76
+ The following diagram illustrates the routing, validation, precision selection, and caching logic:
77
+
78
+ ```mermaid
79
+ graph TD
80
+ A[Start: Calculate F(n)] --> B{Validate input n >= 0}
81
+ B -- No --> C[Throw Error: Invalid Input]
82
+ B -- Yes --> D{Check Cache for n}
83
+ D -- Hit (Yes) --> E[Update LRU Order]
84
+ E --> F[Return Cached Value]
85
+ D -- Miss (No) --> G{Check Precision Mode: n > 78 or useBigInt}
86
+ G -- Standard Number (n <= 78) --> H[Compute using standard arithmetic]
87
+ G -- BigInt (n > 78) --> I{Is n >= asyncThreshold?}
88
+ I -- No (Sync BigInt) --> J[Compute iteratively using BigInt]
89
+ I -- Yes (Async BigInt) --> K[Offload computation to worker thread / chunked loop]
90
+ K --> L[Iterate asynchronously without blocking event loop]
91
+ H --> M[Store Result in Cache]
92
+ J --> M
93
+ L --> M
94
+ M --> N{Cache Size > maxCacheSize?}
95
+ N -- Yes --> O[Evict Least Recently Used entry]
96
+ O --> P[Return Computed Result]
97
+ N -- No --> P
98
+ ```
99
+
100
+ ---
101
+
102
+ ## 4. Key Implementation Mechanics
103
+
104
+ ### 4.1 LRU Eviction Implementation
105
+ To avoid linear scanning for evictions, the cache is backed by:
106
+ - A `Map` mapping `n` to the value (either `Number` or `BigInt`).
107
+ - A doubly-linked list or ordered array (`lruList`) tracking usage keys. On a cache hit, the key is moved to the end. On a cache insertion, if the map exceeds `maxCacheSize`, the key at the front of `lruList` is deleted from both the list and the map.
108
+
109
+ ### 4.2 Precision Safeguards
110
+ - **Standard Float Limits:** Standard numbers in JavaScript lose precision above $F(78)$ ($F(78) = 8944394323791464$, whereas $F(79) = 14472334024559020$ which exceeds `Number.MAX_SAFE_INTEGER`).
111
+ - **Automatic BigInt Upgrade:** If the class configuration is not explicitly set, inputs $n \ge 79$ automatically upgrade execution to `BigInt` mode.
112
+
113
+ ### 4.3 Async Slicing / Non-blocking Loop
114
+ For large values of $n$ (e.g. $n \ge 500,000$), calculating Fibonacci in a single synchronous loop blocks the JS single-threaded event loop for several milliseconds. The `MemoizedFibonacci` class handles this via:
115
+ - **Chunked execution:** Splitting the loop into chunks of 10,000 iterations and yielding back control using `setImmediate` or `setTimeout(..., 0)` to allow standard event-loop ticks to execute.
116
+ - Alternatively, utilizing **Worker Threads** via `node:worker_threads` for CPU offloading in Node.js environments.
117
+
118
+ ---
119
+
120
+ ## 5. Error Handling & Edge Cases
121
+
122
+ | Condition | System Response |
123
+ | :--- | :--- |
124
+ | Negative Input ($n < 0$) | Throws `RangeError: Input must be a non-negative integer.` |
125
+ | Floating point Input (e.g., $n = 3.5$) | Automatically truncated using `Math.floor(n)` with a console warning, or throws a `TypeError`. |
126
+ | Out of Memory Risk ($n > 1,000,000$) | Rejects promise with a warning about resource exhaustion unless a `force` flag is set. |
127
+ | Cache Collision (Standard vs BigInt) | Values in cache are stored with consistent type based on configuration to avoid mixed-type arithmetic downstream. |
@@ -0,0 +1,97 @@
1
+ # Technical Specification - GreetingApp
2
+
3
+ ## Revision History
4
+ | Version | Date | Description | Author |
5
+ |---|---|---|---|
6
+ | v1.0 | 2026-06-22 | Technical specification for GreetingApp | Antigravity Orchestrator |
7
+
8
+ ---
9
+
10
+ ## 1. System Architecture
11
+ The GreetingApp consists of three major components:
12
+ 1. **Greeting Engine (Core):** Performs validation, detects time-of-day categories, maps to localization files, and builds the string.
13
+ 2. **Storage Layer:** A lightweight JSON/SQLite file logger to record history.
14
+ 3. **Interfaces:**
15
+ - CLI Controller: Handles flags and standard output formatting.
16
+ - REST Controller: Express.js routes and JSON responses.
17
+
18
+ ## 2. Detailed Component Specs
19
+
20
+ ### 2.1 Greeting Engine (`core/GreetingEngine`)
21
+ - **Input:**
22
+ - `name`: string (optional, default: "Guest")
23
+ - `lang`: string (optional, default: "en")
24
+ - `timezone`: string (optional, default: system timezone)
25
+ - **Time Periods:**
26
+ - `Morning`: 05:00 - 11:59
27
+ - `Afternoon`: 12:00 - 17:59
28
+ - `Evening`: 18:00 - 21:59
29
+ - `Night`: 22:00 - 04:59
30
+ - **Localization Files (`locales/*.json`):**
31
+ - Example `en.json`:
32
+ ```json
33
+ {
34
+ "morning": "Good morning, {name}!",
35
+ "afternoon": "Good afternoon, {name}!",
36
+ "evening": "Good evening, {name}!",
37
+ "night": "Good night, {name}!"
38
+ }
39
+ ```
40
+
41
+ ### 2.2 Storage Schema
42
+ A SQLite or JSON lines file containing:
43
+ - `id`: UUID / Auto-increment integer
44
+ - `name`: String
45
+ - `language`: String
46
+ - `timestamp`: ISO-8601 string
47
+ - `greeting_message`: String
48
+
49
+ ## 3. Interface Design
50
+
51
+ ### 3.1 CLI Interface
52
+ `awkit greet [options]`
53
+ - `--name, -n`: Name of the user to greet.
54
+ - `--lang, -l`: Language code (en, vi, ja).
55
+ - `--help, -h`: Show usage description.
56
+
57
+ ### 3.2 REST API Specification
58
+ `GET /api/greet`
59
+ - **Query Parameters:**
60
+ - `name` (string)
61
+ - `lang` (string)
62
+ - **Response (200 OK):**
63
+ - Content-Type: `application/json`
64
+ - Body:
65
+ ```json
66
+ {
67
+ "status": "success",
68
+ "data": {
69
+ "message": "Good morning, Alice!",
70
+ "name": "Alice",
71
+ "lang": "en",
72
+ "timestamp": "2026-06-22T05:35:15Z"
73
+ }
74
+ }
75
+ ```
76
+
77
+ ## 4. Error Handling
78
+ - **Invalid Language:** Fallback to `en` and log warning.
79
+ - **Invalid Input characters:** Sanitize inputs to prevent command line injection or XSS (on API side).
80
+
81
+ ## 5. Flow Diagram
82
+ ```mermaid
83
+ graph TD
84
+ A[Start Request] --> B{Validate Inputs}
85
+ B -- Invalid --> C[Use Defaults: Guest/en]
86
+ B -- Valid --> D[Resolve User Local Time]
87
+ C --> D
88
+ D --> E{Determine Time of Day}
89
+ E -->|05:00-11:59| F[Morning Template]
90
+ E -->|12:00-17:59| G[Afternoon Template]
91
+ E -->|18:00-21:59| H[Evening Template]
92
+ E -->|22:00-04:59| I[Night Template]
93
+ F & G & H & I --> J[Replace {name} in Template]
94
+ J --> K[Log Transaction to History DB]
95
+ K --> L[Format Output CLI/REST]
96
+ L --> M[End Request]
97
+ ```