antigravity-ai-kit 3.2.0 → 3.3.1

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.
@@ -12,11 +12,14 @@
12
12
 
13
13
  Include in plan:
14
14
 
15
- - **Accessibility (WCAG 2.1 AA)**: Identify components requiring ARIA labels, keyboard navigation, screen reader support, color contrast compliance
16
- - **Responsive Design**: Specify breakpoints to test (mobile 375px, tablet 768px, desktop 1280px), identify layout changes per breakpoint
17
- - **Bundle Size Impact**: Estimate size of new dependencies, identify tree-shaking opportunities, consider code splitting for new routes
18
- - **Core Web Vitals**: Assess impact on LCP (largest contentful paint), CLS (cumulative layout shift), INP (interaction to next paint)
19
- - **Component Composition**: Specify component hierarchy, prop interfaces, state management approach (local vs. global)
15
+ - **Accessibility (WCAG 2.1 AA)**: Identify components requiring ARIA labels, keyboard navigation, screen reader support, color contrast compliance (minimum 4.5:1 normal text, 3:1 large text)
16
+ - **Responsive Design**: Specify breakpoints to test (mobile 375px, tablet 768px, desktop 1280px), identify layout changes per breakpoint, verify touch targets (minimum 44x44px)
17
+ - **Bundle Size Impact**: Estimate size of new dependencies, identify tree-shaking opportunities, consider code splitting for new routes, set bundle budget (initial JS < 200KB gzipped)
18
+ - **Core Web Vitals**: Assess impact on LCP (< 2.5s), CLS (< 0.1), INP (< 200ms), identify render-blocking resources
19
+ - **Component Composition**: Specify component hierarchy, prop interfaces, state management approach (local vs. global), identify shared components for extraction
20
+ - **Rendering Strategy**: SSR vs CSR vs ISR decision for each route, hydration impact assessment, streaming SSR opportunities
21
+ - **Design System Compliance**: Verify alignment with existing design tokens (colors, spacing, typography), identify new tokens required
22
+ - **Error Boundaries**: Define error boundary placement, fallback UI for each failure mode, error reporting integration
20
23
 
21
24
  ---
22
25
 
@@ -26,11 +29,14 @@ Include in plan:
26
29
 
27
30
  Include in plan:
28
31
 
29
- - **API Contract**: Define request/response schemas (Zod validation), HTTP methods, status codes, error response format
30
- - **Error Handling**: Specify error response structure, error codes, client-facing messages vs. internal logging
31
- - **Rate Limiting**: Identify endpoints requiring rate limits, specify limits (requests/minute/user), throttling strategy
32
- - **Middleware Chain**: Document new middleware additions, execution order, impact on existing middleware stack
33
- - **Database Interaction**: Query patterns (parameterized), transaction boundaries, connection pooling impact
32
+ - **API Contract**: Define request/response schemas (Zod validation), HTTP methods, status codes, error response format (RFC 7807 Problem Details), versioning strategy
33
+ - **Error Handling**: Specify error response structure, error codes, client-facing messages vs. internal logging, error correlation IDs for tracing
34
+ - **Rate Limiting**: Identify endpoints requiring rate limits, specify limits (requests/minute/user), throttling strategy (sliding window vs. token bucket), response headers (X-RateLimit-*)
35
+ - **Middleware Chain**: Document new middleware additions, execution order, impact on existing middleware stack, short-circuit conditions
36
+ - **Database Interaction**: Query patterns (parameterized), transaction boundaries, connection pooling impact, N+1 query prevention
37
+ - **Input Validation**: Validation layer placement (controller vs. middleware), sanitization strategy, content-type enforcement, request size limits
38
+ - **Idempotency**: Identify non-idempotent operations, implement idempotency keys for critical mutations, retry safety assessment
39
+ - **Observability**: Structured logging format (JSON), request tracing headers (X-Request-ID propagation), health check endpoint specification
34
40
 
35
41
  ---
36
42
 
@@ -40,11 +46,14 @@ Include in plan:
40
46
 
41
47
  Include in plan:
42
48
 
43
- - **Migration Rollback**: Write both up and down migrations, test rollback procedure before deploying
44
- - **Index Impact Analysis**: Identify queries affected by schema changes, recommend index additions/removals, estimate query performance impact
45
- - **Data Integrity**: Define constraints (foreign keys, unique, not null, check), cascade behavior for deletions
46
- - **Backup Verification**: Verify backup exists before destructive migrations, test restore procedure for critical tables
47
- - **Query Performance**: Benchmark key queries before and after changes, set acceptable latency thresholds
49
+ - **Migration Rollback**: Write both up and down migrations, test rollback procedure before deploying, zero-downtime migration pattern (expand-contract for schema changes)
50
+ - **Index Impact Analysis**: Identify queries affected by schema changes, recommend index additions/removals, estimate query performance impact, verify composite index column order matches query patterns
51
+ - **Data Integrity**: Define constraints (foreign keys, unique, not null, check), cascade behavior for deletions, domain invariant enforcement at database level
52
+ - **Backup Verification**: Verify backup exists before destructive migrations, test restore procedure for critical tables, point-in-time recovery validation
53
+ - **Query Performance**: Benchmark key queries before and after changes (EXPLAIN ANALYZE), set acceptable latency thresholds (p50 < 10ms, p99 < 100ms for OLTP), identify sequential scan risks
54
+ - **Consistency Model**: Specify required consistency level (strong/eventual), transaction isolation level selection (Read Committed default, Serializable for financial), optimistic vs. pessimistic locking strategy
55
+ - **Data Classification**: Identify PII columns requiring encryption at rest, data retention policy compliance, audit trail requirements for sensitive data mutations
56
+ - **Connection Management**: Connection pool sizing for workload (pool_size = num_cores * 2 + disk_spindles), statement timeout configuration, idle connection cleanup
48
57
 
49
58
  ---
50
59
 
@@ -54,11 +63,14 @@ Include in plan:
54
63
 
55
64
  Include in plan:
56
65
 
57
- - **Infrastructure Changes**: Specify IaC modifications (Dockerfile, docker-compose, CI config), environment variable additions
58
- - **Monitoring & Alerting**: Define new metrics to track, alerting thresholds, dashboard updates
59
- - **Progressive Rollout**: Strategy for deployment (canary → staged → full), rollback triggers, health check endpoints
60
- - **Runbook Updates**: Document operational procedures for the new functionality, incident response steps
61
- - **Environment Parity**: Verify changes work across dev, staging, and production environments
66
+ - **Infrastructure Changes**: Specify IaC modifications (Dockerfile, docker-compose, CI config), environment variable additions, 12-Factor App compliance check
67
+ - **Monitoring & Alerting**: Define new metrics to track, alerting thresholds (SLO-derived), dashboard updates, golden signals coverage (latency, traffic, errors, saturation)
68
+ - **Progressive Rollout**: Strategy for deployment (canary → staged → full), rollback triggers (error rate > 1%, latency p99 > 2x baseline), automated rollback criteria, health check endpoints
69
+ - **Runbook Updates**: Document operational procedures for the new functionality, incident response steps, escalation paths
70
+ - **Environment Parity**: Verify changes work across dev, staging, and production environments, configuration drift detection
71
+ - **GitOps Compliance**: Infrastructure changes committed to version control, declarative configuration (desired state, not imperative scripts), automated drift reconciliation
72
+ - **Container Security**: Base image selection (distroless/alpine preferred), multi-stage build optimization, no secrets in image layers, vulnerability scanning in CI
73
+ - **Observability Pipeline**: Log aggregation configuration, trace sampling strategy, metric cardinality assessment, correlation between logs/traces/metrics
62
74
 
63
75
  ---
64
76
 
@@ -68,11 +80,14 @@ Include in plan:
68
80
 
69
81
  Include in plan (in addition to mandatory security considerations):
70
82
 
71
- - **Threat Model (STRIDE)**: Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of Privilege — assess each for the change
72
- - **Authentication Flow Impact**: How the change affects login, session management, token lifecycle
73
- - **Data Classification**: Identify data sensitivity levels (public, internal, confidential, restricted), storage and transmission requirements
74
- - **Compliance Requirements**: GDPR/CCPA implications (data minimization, consent, right to erasure)
75
- - **Secret Management**: New secrets required, rotation policy, storage mechanism (environment variables only)
83
+ - **Threat Model (STRIDE)**: Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of Privilege — assess each for the change with severity rating
84
+ - **Authentication Flow Impact**: How the change affects login, session management, token lifecycle, OAuth 2.0 flow selection (Authorization Code + PKCE for SPAs, Client Credentials for M2M)
85
+ - **Data Classification**: Identify data sensitivity levels (public, internal, confidential, restricted), storage and transmission requirements per level
86
+ - **Compliance Requirements**: GDPR/CCPA implications (data minimization, consent, right to erasure, breach notification within 72 hours)
87
+ - **Secret Management**: New secrets required, rotation policy, storage mechanism (environment variables only), zero hardcoded credentials enforcement
88
+ - **Zero Trust Assessment**: Authentication at every boundary (never trust, always verify), least privilege access for new endpoints/services, micro-segmentation for new network paths
89
+ - **Supply Chain Security**: New dependency audit (license, maintainer, vulnerability scan), lockfile integrity verification, SRI hashes for CDN resources
90
+ - **Input Boundary Defense**: All external inputs validated and sanitized, output encoding for context (HTML/URL/JS), parameterized queries only (no string concatenation)
76
91
 
77
92
  ---
78
93
 
@@ -82,11 +97,14 @@ Include in plan (in addition to mandatory security considerations):
82
97
 
83
98
  Include in plan:
84
99
 
85
- - **Performance Budget**: Define acceptable thresholds (page load time, API response time, memory usage)
86
- - **Profiling Strategy**: Tools and methods to measure before/after (Lighthouse, Chrome DevTools, load testing)
87
- - **Caching Strategy**: Cache layers (browser, CDN, application, database), TTL values, invalidation approach
88
- - **Lazy Loading**: Identify resources for deferred loading, intersection observer patterns, dynamic imports
89
- - **Benchmarking**: Define benchmark suite, baseline measurements, regression detection
100
+ - **Performance Budget**: Define acceptable thresholds (LCP < 2.5s, FID < 100ms, page load < 3s, API p99 < 500ms, memory < 512MB per process)
101
+ - **Profiling Strategy**: Tools and methods to measure before/after (Lighthouse, Chrome DevTools, load testing with k6/Artillery), baseline measurement requirements
102
+ - **Caching Architecture**: Cache layers (browser CDN application database), TTL values per layer, invalidation strategy (time-based, event-driven, version-key), cache stampede prevention (stale-while-revalidate, locking)
103
+ - **Lazy Loading**: Identify resources for deferred loading, intersection observer patterns, dynamic imports for route-level code splitting, image loading strategy (responsive images, next-gen formats)
104
+ - **Benchmarking**: Define benchmark suite, baseline measurements, regression detection thresholds, automated performance gates in CI
105
+ - **Database Query Optimization**: EXPLAIN ANALYZE for new/modified queries, index coverage verification, N+1 detection, read replica routing for heavy reads
106
+ - **Concurrency Model**: Event loop impact assessment, worker thread candidates for CPU-intensive operations, connection pool saturation risk
107
+ - **CDN Strategy**: Edge caching rules for static assets, cache-control header specification, origin shield configuration, geographic distribution assessment
90
108
 
91
109
  ---
92
110
 
@@ -96,11 +114,61 @@ Include in plan:
96
114
 
97
115
  Include in plan:
98
116
 
99
- - **Platform Parity**: Identify iOS vs. Android differences in behavior, UI, or API access
100
- - **Offline Support**: Define offline behavior, data sync strategy, conflict resolution
101
- - **App Store Guidelines**: Compliance with Apple/Google review guidelines for the feature
102
- - **Native Modules**: Bridge requirements, native module dependencies, build configuration changes
103
- - **Device Testing**: Target device matrix, screen size variations, OS version compatibility
117
+ - **Platform Parity**: Identify iOS vs. Android differences in behavior, UI, or API access, platform-specific code paths (#ifdef equivalent)
118
+ - **Offline Support**: Define offline behavior, data sync strategy (optimistic vs. pessimistic), conflict resolution (last-write-wins, CRDT, manual merge), network-aware queries
119
+ - **App Store Guidelines**: Compliance with Apple HIG and Material Design 3, review guideline risks, in-app purchase requirements
120
+ - **Native Modules**: Bridge requirements, native module dependencies, build configuration changes (Podfile/build.gradle)
121
+ - **Device Testing**: Target device matrix, screen size variations, OS version compatibility (minimum iOS 15 / Android API 26)
122
+ - **Navigation Architecture**: Navigation pattern selection (stack, tab, drawer), deep linking support, back navigation handling per platform
123
+ - **Mobile Performance Budget**: App startup time < 2s, frame rate 60fps minimum, memory usage < 150MB, APK/IPA size budget
124
+ - **State Persistence**: Local storage strategy (AsyncStorage, SQLite, MMKV), state rehydration on app resume, background task handling
125
+
126
+ ---
127
+
128
+ ## Reliability Domain
129
+
130
+ **Triggered when**: `reliability` domain matched (keywords: reliability, uptime, monitoring, sre, sla, slo, sli, etc.)
131
+
132
+ Include in plan:
133
+
134
+ - **SLO Definition**: Define Service Level Objectives for affected services (availability target, latency targets at p50/p95/p99, error rate budget)
135
+ - **SLI Instrumentation**: Specify Service Level Indicators to measure (request success rate, request latency, system throughput), measurement method and data source
136
+ - **Error Budget Impact**: Assess how the change affects existing error budgets, define acceptable error budget consumption for rollout
137
+ - **Golden Signals**: Monitoring for all four golden signals (latency, traffic, errors, saturation) for new/modified services
138
+ - **Resilience Patterns**: Circuit breaker placement, retry policy (exponential backoff with jitter), timeout configuration, bulkhead isolation for critical paths
139
+ - **Incident Preparedness**: Runbook for new failure modes, alerting rules (page vs. ticket), escalation matrix, blast radius assessment
140
+ - **Chaos Engineering**: Identify failure injection points for validation, steady-state hypothesis, abort conditions for chaos experiments
141
+ - **Capacity Planning**: Resource requirements (CPU, memory, network, storage), scaling triggers (auto-scale thresholds), load testing validation for expected traffic growth
142
+
143
+ ---
144
+
145
+ ## Observability Domain
146
+
147
+ **Triggered when**: `observability` domain matched (keywords: logging, tracing, metrics, monitoring, alerting, opentelemetry, etc.)
148
+
149
+ Include in plan:
150
+
151
+ - **Three Pillars Coverage**: Specify logging additions (structured JSON), metrics (counters, histograms, gauges), traces (span creation, context propagation)
152
+ - **OpenTelemetry Integration**: SDK initialization, auto-instrumentation scope, manual span creation for business-critical paths, sampling strategy (head-based vs. tail-based)
153
+ - **Log Architecture**: Log levels and when to use each (ERROR: actionable failures, WARN: degradation, INFO: business events, DEBUG: development only), structured fields, correlation ID propagation
154
+ - **Alerting Strategy**: Alert conditions derived from SLOs, notification channels (PagerDuty/Slack), alert fatigue prevention (multi-window burn rate), silence/snooze policies
155
+ - **Dashboard Design**: Key metrics visualization, RED method (Rate, Errors, Duration) per service, drill-down capability from overview to detail
156
+ - **Cost Management**: Metric cardinality assessment, log volume projection, trace sampling rate optimization, retention policy per signal type
157
+
158
+ ---
159
+
160
+ ## Distributed Systems Domain
161
+
162
+ **Triggered when**: `architecture` domain matched AND task involves multiple services, message queues, or event-driven patterns
163
+
164
+ Include in plan:
165
+
166
+ - **Consistency Strategy**: CAP theorem trade-off for the specific use case, consistency model selection (strong, eventual, causal), Saga pattern for distributed transactions (choreography vs. orchestration)
167
+ - **Communication Pattern**: Synchronous (REST/gRPC) vs. asynchronous (message queue/event stream) decision per interaction, protocol selection criteria
168
+ - **Fault Tolerance**: Failure mode analysis for each service interaction, fallback behavior, partial failure handling, data loss prevention
169
+ - **Event-Driven Design**: Event schema definition (CloudEvents format), event ordering guarantees, idempotent consumers, dead letter queue strategy
170
+ - **Service Discovery**: Registration mechanism, health check protocol, load balancing strategy (client-side vs. server-side), circuit breaker integration
171
+ - **Data Sovereignty**: Which service owns which data, cross-service data access patterns (API calls, not shared databases), eventual consistency reconciliation
104
172
 
105
173
  ---
106
174
 
@@ -112,3 +180,5 @@ The planner reads this file when domain-specific sections are needed:
112
180
  2. For each matched domain, include the corresponding enhancer section
113
181
  3. Domain sections are added AFTER the base plan schema sections
114
182
  4. Multiple domains can be active simultaneously (e.g., frontend + backend for a full-stack feature)
183
+ 5. Each domain section contributes to the plan quality score (+2 bonus per matched domain section present, -2 penalty per missing)
184
+ 6. Domain enhancers leverage the specialized knowledge of their corresponding elevated agents (e.g., reliability domain draws from reliability-engineer's SRE Golden Signals framework)
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: security-practices
3
- description: Application security best practices and vulnerability prevention
3
+ description: Application security best practices including Zero Trust principles, OAuth 2.0 / OpenID Connect flows, API security, supply chain security, and vulnerability prevention
4
4
  triggers: [context, security, auth, vulnerability]
5
5
  ---
6
6
 
@@ -21,7 +21,7 @@ This skill provides security guidelines following OWASP standards and industry b
21
21
  ### Password Security
22
22
 
23
23
  ```typescript
24
- // Use bcrypt with cost factor 12
24
+ // Use bcrypt with cost factor 12
25
25
  import bcrypt from "bcrypt";
26
26
 
27
27
  const SALT_ROUNDS = 12;
@@ -55,20 +55,20 @@ const refreshToken = jwt.sign({ userId }, REFRESH_SECRET, { expiresIn: "7d" });
55
55
  ### Never Trust User Input
56
56
 
57
57
  ```typescript
58
- // SQL Injection vulnerable
58
+ // SQL Injection vulnerable
59
59
  const query = `SELECT * FROM users WHERE id = ${userId}`;
60
60
 
61
- // Parameterized query
61
+ // Parameterized query
62
62
  const user = await prisma.user.findUnique({ where: { id: userId } });
63
63
  ```
64
64
 
65
65
  ### Sanitize Output
66
66
 
67
67
  ```typescript
68
- // XSS vulnerable
68
+ // XSS vulnerable
69
69
  element.innerHTML = userInput;
70
70
 
71
- // Escape HTML
71
+ // Escape HTML
72
72
  import DOMPurify from "dompurify";
73
73
  element.innerHTML = DOMPurify.sanitize(userInput);
74
74
  ```
@@ -114,18 +114,194 @@ res.setHeader("Content-Security-Policy", "default-src 'self'");
114
114
  ## Secrets Management
115
115
 
116
116
  ```bash
117
- # Never commit secrets
117
+ # Never commit secrets
118
118
  # .env file with API_KEY=sk-1234...
119
119
 
120
- # Use environment variables
120
+ # Use environment variables
121
121
  export API_KEY=$(vault read secret/api-key)
122
122
 
123
- # Use secret managers
123
+ # Use secret managers
124
124
  # AWS Secrets Manager, HashiCorp Vault, etc.
125
125
  ```
126
126
 
127
127
  ---
128
128
 
129
+ ## Zero Trust Principles
130
+
131
+ Zero Trust assumes no implicit trust for any entity inside or outside the network perimeter. Every access request is fully authenticated, authorized, and encrypted before granting access.
132
+
133
+ | Principle | Implementation | Verification |
134
+ | :--- | :--- | :--- |
135
+ | **Never trust, always verify** | Authenticate every request regardless of origin; treat internal traffic the same as external | Audit logs confirm no unauthenticated requests reach protected resources |
136
+ | **Least privilege** | Grant minimum permissions required; use role-based and attribute-based access control | Periodic access reviews; automated permission drift detection |
137
+ | **Assume breach** | Encrypt data at rest and in transit; segment blast radius; implement intrusion detection | Red team exercises; incident response drills validate containment |
138
+ | **Micro-segmentation** | Isolate workloads with network policies; service mesh mTLS between microservices | Verify lateral movement is blocked between segments with penetration testing |
139
+ | **Continuous validation** | Re-evaluate trust on every request; session tokens with short TTL; step-up auth for sensitive ops | Monitor for session hijacking; alert on anomalous access patterns |
140
+ | **Device trust** | Require managed/compliant devices; verify device posture before granting access | Device compliance checks run at connection time and periodically |
141
+
142
+ ---
143
+
144
+ ## OAuth 2.0 / OpenID Connect Flows
145
+
146
+ ### Flow Selection Matrix
147
+
148
+ | Client Type | Recommended Flow | Reason |
149
+ | :--- | :--- | :--- |
150
+ | **Web app (SPA)** | Authorization Code + PKCE | No client secret in browser; PKCE prevents interception |
151
+ | **Web app (server)** | Authorization Code | Client secret stored server-side securely |
152
+ | **Mobile / Desktop** | Authorization Code + PKCE | Public client; PKCE mandatory |
153
+ | **Machine-to-Machine** | Client Credentials | No user interaction; service identity via client secret |
154
+ | **Legacy (avoid)** | Implicit | Deprecated; tokens exposed in URL fragment |
155
+
156
+ ### Token Storage Requirements
157
+
158
+ ```typescript
159
+ // NEVER store access tokens in localStorage (XSS-accessible)
160
+ // NEVER store tokens in sessionStorage for long-lived sessions
161
+
162
+ // Use httpOnly, Secure, SameSite cookies for refresh tokens
163
+ res.cookie("refresh_token", token, {
164
+ httpOnly: true,
165
+ secure: true,
166
+ sameSite: "strict",
167
+ maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
168
+ path: "/api/auth/refresh",
169
+ });
170
+
171
+ // Keep access tokens in memory only (JS variable)
172
+ // They are short-lived (15 min) and re-obtained via refresh
173
+ ```
174
+
175
+ ### PKCE Implementation
176
+
177
+ ```typescript
178
+ import crypto from "crypto";
179
+
180
+ // Generate code verifier (43-128 chars, unreserved URI characters)
181
+ function generateCodeVerifier(): string {
182
+ return crypto.randomBytes(32).toString("base64url");
183
+ }
184
+
185
+ // Derive code challenge from verifier
186
+ function generateCodeChallenge(verifier: string): string {
187
+ return crypto.createHash("sha256").update(verifier).digest("base64url");
188
+ }
189
+
190
+ // All public clients MUST use PKCE (RFC 7636)
191
+ // Send code_challenge with authorization request
192
+ // Send code_verifier with token exchange request
193
+ ```
194
+
195
+ ---
196
+
197
+ ## API Security
198
+
199
+ ### Rate Limiting Patterns
200
+
201
+ | Strategy | Use Case | Example |
202
+ | :--- | :--- | :--- |
203
+ | **Per-endpoint** | Protect expensive operations | `/api/search`: 10 req/min |
204
+ | **Per-user** | Fair usage enforcement | Authenticated: 1000 req/hr |
205
+ | **Sliding window** | Smooth traffic spikes | Rolling 60s window, max 100 |
206
+ | **Token bucket** | Burst tolerance | 10 tokens, refill 1/sec |
207
+ | **IP-based** | Unauthenticated endpoints | Login: 5 attempts/15 min |
208
+
209
+ ```typescript
210
+ import rateLimit from "express-rate-limit";
211
+
212
+ const apiLimiter = rateLimit({
213
+ windowMs: 15 * 60 * 1000, // 15 minutes
214
+ max: 100,
215
+ standardHeaders: true,
216
+ legacyHeaders: false,
217
+ keyGenerator: (req) => req.user?.id ?? req.ip,
218
+ });
219
+
220
+ app.use("/api/", apiLimiter);
221
+ ```
222
+
223
+ ### API Key Management
224
+
225
+ - **Rotate keys** on a regular schedule (90 days max) and immediately on suspected compromise
226
+ - **Scope keys** to specific endpoints, methods, and IP ranges
227
+ - **Never embed keys** in client-side code or version control
228
+ - **Use separate keys** for each environment (dev, staging, production)
229
+ - **Log key usage** to detect anomalous patterns
230
+
231
+ ### Request Signing
232
+
233
+ ```typescript
234
+ // Sign requests with HMAC to prevent tampering
235
+ import crypto from "crypto";
236
+
237
+ function signRequest(payload: string, secret: string): string {
238
+ return crypto.createHmac("sha256", secret).update(payload).digest("hex");
239
+ }
240
+
241
+ // Verify on server side; reject requests with invalid or expired signatures
242
+ // Include timestamp in signed payload to prevent replay attacks
243
+ ```
244
+
245
+ ### API Versioning Security
246
+
247
+ - Deprecate and remove old API versions that lack current security controls
248
+ - Apply the same authentication and authorization to all active versions
249
+ - Monitor traffic to deprecated versions for potential abuse
250
+ - Never maintain insecure legacy endpoints for backward compatibility
251
+
252
+ ---
253
+
254
+ ## Supply Chain Security
255
+
256
+ ### Dependency Auditing
257
+
258
+ ```bash
259
+ # Run audit on every CI build
260
+ npm audit --audit-level=high
261
+
262
+ # Fix known vulnerabilities
263
+ npm audit fix
264
+
265
+ # Use lockfile-only installs in CI to prevent supply chain attacks
266
+ npm ci
267
+ ```
268
+
269
+ ### Lockfile Integrity
270
+
271
+ - **Always commit** `package-lock.json` to version control
272
+ - **Use `npm ci`** in CI/CD pipelines (installs from lockfile exactly)
273
+ - **Review lockfile diffs** in pull requests for unexpected changes
274
+ - **Enable lockfile-lint** to enforce registry and integrity hash policies
275
+
276
+ ### Dependency Pinning
277
+
278
+ ```json
279
+ {
280
+ "dependencies": {
281
+ "express": "4.18.2",
282
+ "prisma": "5.10.0"
283
+ }
284
+ }
285
+ ```
286
+
287
+ - Pin exact versions in production applications (no `^` or `~`)
288
+ - Use Dependabot or Renovate for controlled, reviewed updates
289
+ - Separate security patches from feature updates in dependency PRs
290
+
291
+ ### Typosquatting Detection
292
+
293
+ | Technique | Example |
294
+ | :--- | :--- |
295
+ | **Character swap** | `expresss` instead of `express` |
296
+ | **Hyphen confusion** | `lodash-utils` mimicking `lodash` |
297
+ | **Scope squatting** | `@myorg/config` vs `@my-org/config` |
298
+
299
+ - Verify package publisher and download counts before installing
300
+ - Use `npm config set ignore-scripts true` for initial installs, then review scripts
301
+ - Consider using Socket.dev or Snyk to detect malicious packages automatically
302
+
303
+ ---
304
+
129
305
  ## Quick Reference
130
306
 
131
307
  | Practice | Implementation |
@@ -138,3 +314,7 @@ export API_KEY=$(vault read secret/api-key)
138
314
  | Secrets | Environment, vaults |
139
315
  | Dependencies | npm audit, Snyk |
140
316
  | Logging | Audit trail, no PII |
317
+ | Zero Trust | Verify every request |
318
+ | OAuth 2.0 | Auth Code + PKCE |
319
+ | API Keys | Scoped, rotated |
320
+ | Supply Chain | Lockfile, pin deps |
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # 🚀 Antigravity AI Kit
2
2
 
3
- ![version](https://img.shields.io/badge/version-3.2.0-blue)
3
+ ![version](https://img.shields.io/badge/version-3.3.1-blue)
4
4
  ![license](https://img.shields.io/badge/license-MIT-green)
5
5
  ![AI Agents](https://img.shields.io/badge/AI%20Agents-19-purple)
6
6
  ![Skills](https://img.shields.io/badge/Skills-32-orange)
@@ -100,22 +100,14 @@ Creates a new project with `.agent/` pre-configured. Templates: `minimal`, `node
100
100
  npx antigravity-ai-kit init
101
101
  ```
102
102
 
103
- This automatically copies the `.agent/` folder to your project.
104
-
105
- ### Option 3: Manual Installation
103
+ ### 🔄 Updating
106
104
 
107
105
  ```bash
108
- # 1. Clone the repository
109
- git clone https://github.com/besync-labs/antigravity-ai-kit.git
110
-
111
- # 2. Copy .agent/ to your project
112
- cp -r antigravity-ai-kit/.agent/ your-project/.agent/
113
-
114
- # 3. Start your session
115
- /status
106
+ ag-kit update # Non-destructive preserves your customizations
107
+ ag-kit update --dry-run # Preview changes without applying
116
108
  ```
117
109
 
118
- That's it! The kit is now active and ready to accelerate your development.
110
+ > **Prefer `ag-kit update` over `ag-kit init --force`**. The update command preserves your session data, ADRs, learning contexts, and customizations. Use `init --force` only for clean reinstalls.
119
111
 
120
112
  ### ✅ Verify Installation
121
113
 
@@ -124,6 +116,31 @@ ag-kit verify # Manifest integrity check
124
116
  ag-kit scan # Security scan
125
117
  ```
126
118
 
119
+ ### 🛡️ Safety Guarantees
120
+
121
+ Antigravity AI Kit is designed to **never touch your project files**. All operations are scoped to the `.agent/` directory.
122
+
123
+ | Your Project Files | Safe? | Details |
124
+ |:---|:---|:---|
125
+ | Source code (`src/`, `lib/`, `app/`) | ✅ Never touched | Init/update only operates on `.agent/` |
126
+ | Config files (`.env`, `package.json`) | ✅ Never touched | No project config is read or written |
127
+ | Documentation (`docs/`, `README.md`) | ✅ Never touched | Only `.agent/` docs are managed |
128
+ | Tests (`tests/`, `__tests__/`) | ✅ Never touched | Kit tests are internal to the package |
129
+ | Platform files (`android/`, `ios/`) | ✅ Never touched | No platform-specific operations |
130
+
131
+ **`init --force` safety features (v3.3.1+):**
132
+ - 🔒 **Auto-backup**: Creates timestamped backup of existing `.agent/` before overwriting
133
+ - ⚛️ **Atomic copy**: Uses temp directory + rename to prevent corruption on failure
134
+ - 🔗 **Symlink guard**: Skips symbolic links to prevent path traversal attacks
135
+ - ⚠️ **Session warning**: Alerts if active work-in-progress would be destroyed
136
+ - 🔍 **Dry-run preview**: `--dry-run --force` shows exactly which user files would be overwritten
137
+
138
+ **`update` preserved files:**
139
+ - `session-context.md` — Your active session notes
140
+ - `session-state.json` — Your session metadata
141
+ - `decisions/` — Your Architecture Decision Records
142
+ - `contexts/` — Your learning data and plan quality logs
143
+
127
144
  ---
128
145
 
129
146
  ## 🏗️ Architecture Overview
package/bin/ag-kit.js CHANGED
@@ -16,6 +16,7 @@ const path = require('path');
16
16
 
17
17
  const VERSION = require('../package.json').version;
18
18
  const AGENT_FOLDER = '.agent';
19
+ const { safeCopyDirSync, readJsonSafe } = require('../lib/io');
19
20
 
20
21
  // ANSI colors
21
22
  const colors = {
@@ -49,7 +50,7 @@ ${colors.reset}
49
50
  ${colors.green}🚀 Antigravity AI Kit v${VERSION}${colors.reset}
50
51
  ${colors.yellow} Transform Your IDE into an Autonomous Engineering Team${colors.reset}
51
52
 
52
- • 19 AI Agents • 31 Skills
53
+ • 19 AI Agents • 32 Skills
53
54
  • 31 Commands • 14 Workflows
54
55
  • Runtime Engine • Error Budget
55
56
  `);
@@ -95,23 +96,28 @@ ${colors.bright}IDE Reference:${colors.reset}
95
96
  `);
96
97
  }
97
98
 
98
- function copyFolderSync(src, dest) {
99
- if (!fs.existsSync(dest)) {
100
- fs.mkdirSync(dest, { recursive: true });
101
- }
102
-
103
- const entries = fs.readdirSync(src, { withFileTypes: true });
104
-
105
- for (const entry of entries) {
106
- const srcPath = path.join(src, entry.name);
107
- const destPath = path.join(dest, entry.name);
108
-
109
- if (entry.isDirectory()) {
110
- copyFolderSync(srcPath, destPath);
111
- } else {
112
- fs.copyFileSync(srcPath, destPath);
113
- }
114
- }
99
+ /**
100
+ * Creates a timestamped backup of a directory.
101
+ * @param {string} dirPath - Directory to back up
102
+ * @returns {string} Path to the backup directory
103
+ */
104
+ function backupDirectory(dirPath) {
105
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
106
+ const backupPath = `${dirPath}.backup-${timestamp}`;
107
+ safeCopyDirSync(dirPath, backupPath);
108
+ return backupPath;
109
+ }
110
+
111
+ /**
112
+ * Checks if there is an active session with in-progress work.
113
+ * @param {string} agentPath - Path to existing .agent directory
114
+ * @returns {boolean} True if session-state indicates active work
115
+ */
116
+ function hasActiveSession(agentPath) {
117
+ const statePath = path.join(agentPath, 'session-state.json');
118
+ const state = readJsonSafe(statePath, null);
119
+ if (!state) return false;
120
+ return state.currentTask || state.inProgress || state.activeWorkflow;
115
121
  }
116
122
 
117
123
  function countItems(dir, type = 'dir') {
@@ -146,24 +152,76 @@ function initCommand(options) {
146
152
  // Check if already exists
147
153
  if (fs.existsSync(agentPath) && !options.force) {
148
154
  log(`\n⚠️ ${AGENT_FOLDER} folder already exists!`, 'yellow');
149
- log(' Use --force to overwrite\n', 'yellow');
155
+ log(' Use --force to overwrite', 'yellow');
156
+ log(' Use ag-kit update for non-destructive updates\n', 'yellow');
150
157
  process.exit(1);
151
158
  }
152
159
 
160
+ // M-3: Active session warning for --force
161
+ if (options.force && fs.existsSync(agentPath) && hasActiveSession(agentPath)) {
162
+ log('\n⚠️ Active session detected! Force-overwrite will destroy in-progress work.', 'yellow');
163
+ log(' Consider using ag-kit update instead.\n', 'yellow');
164
+ }
165
+
153
166
  if (options.dryRun) {
154
167
  log('\n🔍 Dry run mode - no changes will be made\n', 'cyan');
155
168
  log(` Would copy: ${sourcePath}`, 'cyan');
156
169
  log(` To: ${agentPath}\n`, 'cyan');
170
+ // M-2: Show force damage preview
171
+ if (options.force && fs.existsSync(agentPath)) {
172
+ log(' ⚠️ --force would overwrite these user files:', 'yellow');
173
+ const userFiles = ['session-context.md', 'session-state.json'];
174
+ const userDirs = ['decisions', 'contexts'];
175
+ for (const f of userFiles) {
176
+ if (fs.existsSync(path.join(agentPath, f))) {
177
+ log(` • ${f}`, 'yellow');
178
+ }
179
+ }
180
+ for (const d of userDirs) {
181
+ if (fs.existsSync(path.join(agentPath, d))) {
182
+ log(` • ${d}/ (directory)`, 'yellow');
183
+ }
184
+ }
185
+ log('', 'reset');
186
+ }
157
187
  return;
158
188
  }
159
189
 
160
- // Copy .agent folder
161
- logStep('1/3', 'Copying .agent folder...');
190
+ // C-2: Auto-backup before force-overwrite
191
+ if (options.force && fs.existsSync(agentPath)) {
192
+ logStep('1/4', 'Backing up existing .agent folder...');
193
+ try {
194
+ const backupPath = backupDirectory(agentPath);
195
+ log(` ✓ Backup created: ${path.basename(backupPath)}`, 'green');
196
+ } catch (err) {
197
+ log(` ⚠️ Backup failed: ${err.message}`, 'yellow');
198
+ log(' Proceeding without backup...', 'yellow');
199
+ }
200
+ }
201
+
202
+ // C-3: Atomic copy via temp directory
203
+ const stepPrefix = options.force && fs.existsSync(agentPath) ? '2/4' : '1/3';
204
+ logStep(stepPrefix, 'Copying .agent folder...');
162
205
 
206
+ const tempPath = `${agentPath}.tmp-${Date.now()}`;
163
207
  try {
164
- copyFolderSync(sourcePath, agentPath);
208
+ safeCopyDirSync(sourcePath, tempPath);
209
+ // Remove old directory if force-overwriting
210
+ if (fs.existsSync(agentPath)) {
211
+ fs.rmSync(agentPath, { recursive: true, force: true });
212
+ }
213
+ // Atomic rename: move temp to final
214
+ fs.renameSync(tempPath, agentPath);
165
215
  log(' ✓ Copied successfully', 'green');
166
216
  } catch (err) {
217
+ // Cleanup temp directory on failure
218
+ try {
219
+ if (fs.existsSync(tempPath)) {
220
+ fs.rmSync(tempPath, { recursive: true, force: true });
221
+ }
222
+ } catch {
223
+ // Cleanup failure is non-critical
224
+ }
167
225
  log(` ✗ Failed to copy: ${err.message}`, 'red');
168
226
  process.exit(1);
169
227
  }
@@ -366,6 +424,13 @@ function updateCommand(updateOptions) {
366
424
  const updater = require('../lib/updater');
367
425
  const isDryRun = updateOptions.dryRun;
368
426
 
427
+ // M-1: Show version transition
428
+ const currentManifest = readJsonSafe(path.join(agentPath, 'manifest.json'), {});
429
+ const currentVersion = currentManifest.kitVersion || 'unknown';
430
+ if (currentVersion !== VERSION) {
431
+ log(`\n 📦 Upgrading from v${currentVersion} → v${VERSION}`, 'cyan');
432
+ }
433
+
369
434
  if (isDryRun) {
370
435
  log('\n🔍 Dry run mode — no changes will be made\n', 'cyan');
371
436
  }