alibai 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +150 -2
- package/dist/cli.js +212 -0
- package/dist/git.js +148 -0
- package/dist/report.js +37 -0
- package/dist/run.schema.json +100 -0
- package/dist/store.js +199 -0
- package/dist/viewer.js +100 -0
- package/package.json +24 -4
- package/viewer/favicon.svg +6 -0
- package/viewer/fonts/IBMPlexMono-Bold-Latin1.woff2 +0 -0
- package/viewer/fonts/IBMPlexMono-Regular-Latin1.woff2 +0 -0
- package/viewer/fonts/IBMPlexMono-SemiBold-Latin1.woff2 +0 -0
- package/viewer/fonts/IBMPlexSans-Regular-Latin1.woff2 +0 -0
- package/viewer/fonts/IBMPlexSans-SemiBold-Latin1.woff2 +0 -0
- package/viewer/fonts/IBMPlexSansCondensed-Bold-Latin1.woff2 +0 -0
- package/viewer/fonts/OFL.txt +92 -0
- package/viewer/fonts/README.md +9 -0
- package/viewer/index.html +31 -0
- package/viewer/messages.js +245 -0
- package/viewer/tokens.css +66 -0
- package/viewer/viewer.css +425 -0
- package/viewer/viewer.js +451 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 kut7728
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,151 @@
|
|
|
1
|
-
|
|
1
|
+
<h1 align="center">
|
|
2
|
+
<picture>
|
|
3
|
+
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/logo-dark.png">
|
|
4
|
+
<img src="docs/assets/logo-light.png" alt="Alibi for AI (alibai)" width="240">
|
|
5
|
+
</picture>
|
|
6
|
+
</h1>
|
|
2
7
|
|
|
3
|
-
|
|
8
|
+
<p align="center"><strong>Your AI says it's fixed. Here's the evidence.</strong></p>
|
|
9
|
+
<p align="center">AI 코딩 에이전트의 테스트 증거를 로컬에 기록하고 브라우저에서 확인합니다. UI 전후 스크린샷과 로직 입출력 diff를 실행별로 모아 볼 수 있습니다.</p>
|
|
10
|
+
|
|
11
|
+
<p align="center">
|
|
12
|
+
<a href="https://github.com/kut7728/alibi-for-ai/releases"><img alt="GitHub 최신 릴리스" src="https://img.shields.io/github/v/release/kut7728/alibi-for-ai?color=F2C230&labelColor=14171D"></a>
|
|
13
|
+
<img alt="Node.js 22 이상 필요" src="https://img.shields.io/badge/node-%E2%89%A522-4A5161?labelColor=14171D">
|
|
14
|
+
<img alt="뷰어 지원 언어 영어, 한국어, 일본어" src="https://img.shields.io/badge/viewer-EN%20%C2%B7%20%ED%95%9C%20%C2%B7%20%E6%97%A5-4A5161?labelColor=14171D">
|
|
15
|
+
<a href="LICENSE"><img alt="라이선스 MIT" src="https://img.shields.io/badge/license-MIT-4A5161?labelColor=14171D"></a>
|
|
16
|
+
</p>
|
|
17
|
+
|
|
18
|
+
<p align="center">
|
|
19
|
+
<img src="docs/assets/hero.gif" alt="실패한 장바구니 테스트를 열어 UI 전후 슬라이더와 쿠폰 계산 diff를 확인하고 뷰어 언어를 바꾸는 과정" width="860">
|
|
20
|
+
</p>
|
|
21
|
+
|
|
22
|
+
<p align="center">
|
|
23
|
+
<a href="https://kut7728.github.io/alibi-for-ai/">Live demo</a> ·
|
|
24
|
+
<a href="docs/assets/hero.mp4?raw=true">데모 영상 (MP4 다운로드)</a>
|
|
25
|
+
</p>
|
|
26
|
+
|
|
27
|
+
<details>
|
|
28
|
+
<summary>정지 화면 보기</summary>
|
|
29
|
+
|
|
30
|
+
<picture>
|
|
31
|
+
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/still-dark.png">
|
|
32
|
+
<img src="docs/assets/still-light.png" alt="장바구니 테스트 목록과 실패한 케이스의 UI 전후 비교가 보이는 alibai 뷰어" width="860">
|
|
33
|
+
</picture>
|
|
34
|
+
|
|
35
|
+
</details>
|
|
36
|
+
|
|
37
|
+
| 기록 명령 | 뷰어에서 확인 |
|
|
38
|
+
| --- | --- |
|
|
39
|
+
| `alibai step` | UI 전후 스크린샷 슬라이더 |
|
|
40
|
+
| `alibai check` | 로직 수정 전·후와 기대값 비교 |
|
|
41
|
+
| `alibai run end` | 실행별 판정과 요약 |
|
|
42
|
+
|
|
43
|
+
## 빠른 시작
|
|
44
|
+
|
|
45
|
+
Node.js 22 이상과 Git이 필요합니다. 저장소를 클론하고 패키지를 빌드해 설치합니다.
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
git clone https://github.com/kut7728/alibi-for-ai.git
|
|
49
|
+
cd alibi-for-ai
|
|
50
|
+
npm ci
|
|
51
|
+
pack_dir="$(mktemp -d)"
|
|
52
|
+
npm pack --pack-destination "$pack_dir"
|
|
53
|
+
npm install --global "$pack_dir/alibai-0.1.0.tgz"
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
같은 디렉터리에서 예제 장바구니 테스트를 엽니다. 예제는 가상의 데이터만 사용하며 임시 Git 작업 트리에 복사됩니다.
|
|
57
|
+
|
|
58
|
+
```sh
|
|
59
|
+
example_root="$(mktemp -d)"
|
|
60
|
+
git init -q "$example_root"
|
|
61
|
+
mkdir -p "$example_root/.alibai/runs"
|
|
62
|
+
cp -R examples/cart-rounding "$example_root/.alibai/runs/8b37f2ac-7506-4585-9d86-4a0e21c44c12"
|
|
63
|
+
(cd "$example_root" && alibai open)
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## 에이전트 스킬 설치
|
|
67
|
+
|
|
68
|
+
CLI를 로컬에 설치한 뒤 [공용 스킬](skills/alibai/SKILL.md)을 연결합니다. 연결 후 에이전트에 `alibai로 테스트해줘`라고 요청할 수 있습니다.
|
|
69
|
+
|
|
70
|
+
### Claude Code
|
|
71
|
+
|
|
72
|
+
이 저장소의 `skills/alibai` 디렉터리를 `~/.claude/skills/` 또는 테스트 대상 프로젝트의 `.claude/skills/`에 복사합니다. Claude Code에서 `/alibai`로도 실행할 수 있습니다. [Claude Code 스킬 문서](https://code.claude.com/docs/en/skills)
|
|
73
|
+
|
|
74
|
+
### Codex
|
|
75
|
+
|
|
76
|
+
`skills/alibai` 디렉터리를 테스트 대상 프로젝트의 `.agents/skills/` 또는 사용자용 `~/.agents/skills/`에 복사합니다. [Codex 스킬 문서](https://learn.chatgpt.com/docs/build-skills)
|
|
77
|
+
|
|
78
|
+
스킬 자동 검색을 사용할 수 없는 환경에서는 프로젝트의 `AGENTS.md`에 Alibai 테스트 요청 시 이 저장소의 `skills/alibai/SKILL.md`를 읽고 따르라는 지침을 추가하고, 파일의 실제 절대 경로를 적습니다.
|
|
79
|
+
|
|
80
|
+
### Cursor
|
|
81
|
+
|
|
82
|
+
`skills/alibai` 디렉터리를 테스트 대상 프로젝트의 `.cursor/skills/` 또는 `.agents/skills/`에 복사합니다. 사용자용 경로는 `~/.cursor/skills/` 또는 `~/.agents/skills/`입니다. [Cursor 스킬 문서](https://cursor.com/docs/skills)
|
|
83
|
+
|
|
84
|
+
스킬 자동 검색을 사용할 수 없는 환경에서는 `.cursor/rules/alibai.mdc`에 **Apply Intelligently** 규칙을 만듭니다. 설명에는 Alibai 테스트 요청 시 적용한다고 적고, 본문에는 공용 스킬의 실제 절대 경로를 읽고 따르라고 적습니다. [Cursor 규칙 문서](https://cursor.com/docs/rules)
|
|
85
|
+
|
|
86
|
+
## 기록하기
|
|
87
|
+
|
|
88
|
+
테스트 대상 Git 작업 트리에서 실행합니다. `before.png`와 `after.png`는 미리 캡처한 스크린샷 경로로 바꿉니다. 파일 경로는 명령을 실행한 디렉터리 기준입니다.
|
|
89
|
+
|
|
90
|
+
```sh
|
|
91
|
+
alibai run start --title "Login fix" --platform flutter --agent Codex
|
|
92
|
+
alibai step --action "Tap Sign in" --before before.png --after after.png --result pass
|
|
93
|
+
alibai check --target validateLogin --input '{"email":"a@example.com"}' \
|
|
94
|
+
--before false --after true --expected true --result pass
|
|
95
|
+
alibai run end --verdict pass --summary "Login succeeds with a valid email."
|
|
96
|
+
alibai list --json
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
예외가 발생한 검사도 실행을 종료하기 전에 기록할 수 있습니다.
|
|
100
|
+
|
|
101
|
+
```sh
|
|
102
|
+
alibai check --target parseAge --input '"invalid"' --before null --error TypeError --result fail
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
- `run start`는 제목만 필수입니다. 플랫폼은 `flutter`, `ios`, `android`, `web` 중 하나이며 기본값은 `web`입니다. 에이전트 이름은 선택 사항입니다.
|
|
106
|
+
- `step`에는 `--before` 또는 `--after` 스크린샷이 하나 이상 필요합니다. 파일 확장자는 대소문자 구분 없이 `.png`, `.jpg`, `.jpeg`, `.webp`를 지원합니다. 순서는 1부터 기록하며 `--note`의 기본값은 빈 문자열입니다.
|
|
107
|
+
- `check`의 `--input`, `--before`, `--after`, 선택 항목인 `--expected`는 JSON 값입니다. `--error`에 오류 코드나 예외 이름 또는 메시지를 전달하면 `--after`를 생략할 수 있습니다. `--after null`은 JSON `null`을 기록합니다.
|
|
108
|
+
- 음수는 `--before=-1`처럼 전달할 수 있고, JSON 문자열은 `--after '"ok"'`처럼 JSON 따옴표를 포함합니다. JavaScript 안전 정수 범위(±9,007,199,254,740,991)를 벗어나는 정수는 반올림될 수 있으므로 정확한 값이 필요하면 JSON 문자열로 전달합니다.
|
|
109
|
+
- `step`과 `check`의 `--result`, `run end`의 `--verdict`에는 `pass`, `fail`, `info`를 사용합니다. 항목의 결과는 기본 `info`이며, 실행을 종료할 때는 판정을 지정합니다. `--summary`를 생략하면 판정을 담은 한 줄이 자동으로 기록됩니다.
|
|
110
|
+
- `step`, `check`, `run end`는 가장 최근에 시작한 열린 실행에 기록합니다. 특정 실행을 지정하려면 `--run <id>`를 사용합니다. 종료한 실행에는 항목을 추가할 수 없습니다.
|
|
111
|
+
|
|
112
|
+
기록 명령은 실행 ID와 `run.json`의 절대 경로를 출력합니다. `--json`을 쓰면 기록 명령은 `{"id":"…","path":"…"}`를, `list`는 `{"runs":[…],"invalidRuns":[…]}`를 stdout에 출력합니다. `runs`는 최신순이며 열린 실행의 `verdict`는 `null`입니다. `invalidRuns`에는 읽거나 검증할 수 없는 실행의 `{"id":"…","path":"…","error":"…"}` 항목이 담깁니다. 일반 `list` 출력과 기본 실행을 선택하는 기록 명령은 읽을 수 없는 실행을 건너뛰고 stderr에 경고를 출력합니다. 이 경고는 기록 명령에 `--json`을 붙여도 표시됩니다. `--run <id>`를 지정하면 해당 실행에 바로 접근합니다. `--json`에서 CLI 오류는 종료 코드 1과 함께 stderr에 `{"error":"…"}`로 출력됩니다. `fail` 결과나 판정도 기록에 성공하면 종료 코드는 0입니다.
|
|
113
|
+
|
|
114
|
+
## 브라우저에서 증거 보기
|
|
115
|
+
|
|
116
|
+
기록이 있는 Git 작업 트리에서 `alibai open`을 실행합니다. 기본 브라우저가 열리며 터미널에 출력된 `http://127.0.0.1:…/` 주소로 직접 접속할 수도 있습니다. 뷰어는 출력된 `127.0.0.1` 주소만 허용합니다. `alibai open --json`은 `{"url":"…"}`을 출력합니다. `Ctrl+C`로 서버를 종료합니다. 기록을 추가한 뒤에는 페이지를 새로고침하면 됩니다.
|
|
117
|
+
|
|
118
|
+
뷰어는 읽을 수 없는 기록을 목록에 표시합니다. 타임라인은 UI 단계의 `order`와 로직 검사의 저장 순서를 유지하면서, 각 시퀀스의 다음 항목에 시간이 모두 있으면 기록 시각을 비교합니다. 시간이 같거나 한쪽에 시각이 없으면 UI 단계를 먼저 표시합니다.
|
|
119
|
+
|
|
120
|
+
뷰어 상단의 EN / 한 / 日 버튼으로 언어를 바꿀 수 있습니다. 처음 열 때 언어를 지정하려면 `alibai open --lang ko`처럼 `en`, `ko`, `ja` 중 하나를 전달합니다. 주소의 `lang` 값, 같은 뷰어 주소에 저장된 선택, 브라우저의 언어 설정 순으로 적용하며 기본값은 영어입니다.
|
|
121
|
+
|
|
122
|
+
## 포맷과 Git 기준
|
|
123
|
+
|
|
124
|
+
실행을 시작한 시점의 Git 브랜치, 커밋, 작업 트리 상태를 저장합니다. `git.dirty`는 추적되지 않은 파일을 포함한 `git status --porcelain` 출력이 있을 때 `true`입니다. `--base <ref>`를 지정하면 해당 로컬 커밋을 기준으로 사용하며, 해석할 수 없는 ref는 오류로 처리합니다. 기본 기준은 현재 커밋과 다른 공통 조상을 `origin/HEAD` → `origin/main` → 로컬 `main` → `origin/master` → 로컬 `master` 순으로 찾아 사용합니다. 없으면 현재 커밋의 첫 번째 부모를 사용합니다. 기준이나 HEAD 커밋이 없으면 해당 SHA는 `null`이며, detached HEAD의 브랜치도 `null`입니다.
|
|
125
|
+
|
|
126
|
+
Git 작업 트리 루트의 `.alibai/runs/<run-id>/run.json`에 [버전 1 스키마](src/run.schema.json)를 따르는 기록을 저장합니다. 스크린샷은 실행 디렉터리의 `screenshots/`에 복사되며, JSON에는 실행 디렉터리 기준 상대 경로가 들어갑니다. 처음 실행을 시작할 때 `.alibai/.gitignore`를 만들어 증거를 Git에서 제외합니다.
|
|
127
|
+
|
|
128
|
+
<details>
|
|
129
|
+
<summary>타임스탬프, 작업 트리 스냅샷과 잠금</summary>
|
|
130
|
+
|
|
131
|
+
새 UI 단계와 로직 검사에는 UTC `createdAt`, 종료한 실행에는 UTC `endedAt`을 기록합니다. 기존 버전 1 기록은 이 시간이나 `git.dirty`가 없어도 읽을 수 있습니다.
|
|
132
|
+
|
|
133
|
+
시작과 종료 시점에 미커밋 변경이 있으면 각각 `git.startChanges`, `git.endChanges`에 스냅샷을 기록합니다. `paths`는 작업 트리 루트 기준이며, 추적 파일의 스테이징된 변경과 작업 트리 변경, Git이 무시하지 않는 미추적 파일을 포함합니다. 루트의 `.alibai`는 제외하고, 이름이 바뀐 파일은 이전 경로와 새 경로로 기록합니다. 뷰어의 작업 트리 정보에서 각 시점의 파일 목록을 펼쳐 볼 수 있습니다.
|
|
134
|
+
|
|
135
|
+
`diffSha256`은 HEAD 대비 인덱스 패치, 인덱스 대비 작업 트리 패치, 미추적 파일의 경로와 내용에서 계산합니다. 두 패치의 바이트 길이를 각각 십진수와 개행으로 기록한 뒤 패치 바이트를 순서대로 해시에 넣습니다. 두 패치 모두 기본 경로 순서, `a/`와 `b/` 접두사, Myers 알고리즘, 문맥 3줄, 변경 덩어리 사이 문맥 0줄, 들여쓰기 휴리스틱 및 전체 객체 ID를 사용합니다. 색상, 이름 변경 감지, 외부 diff, textconv는 끕니다.
|
|
136
|
+
|
|
137
|
+
미추적 항목은 루트 기준 경로의 원본 바이트 순으로 정렬합니다. 각 항목의 종류(`f` 또는 `l`), 경로의 바이트 길이와 개행, 경로의 원본 바이트, 내용의 32바이트 SHA-256을 차례로 해시에 넣습니다. 심볼릭 링크는 대상 파일 대신 링크에 저장된 경로를 해시합니다. 패치와 파일 본문은 저장하지 않습니다. Git 읽기나 미추적 파일 하나가 32 MiB를 넘거나, 입력을 읽을 수 없거나, HEAD 또는 해시할 입력이 없으면 경로는 저장하고 해시는 `null`로 기록합니다. Git 속성이나 체크아웃 설정이 바꾼 패치 내용과 실행 중 파일 읽기 사이에 일어난 변경은 해시에 영향을 줄 수 있습니다.
|
|
138
|
+
|
|
139
|
+
Git 상태 읽기가 실패하면 해당 시점의 스냅샷을 `null`로 기록하고, 시작 시점이면 `git.dirty`를 생략합니다. 변경 경로가 없으면 스냅샷 필드를 생략합니다. 기존 버전 1 기록에도 이 필드가 없을 수 있습니다. Git 작업 트리가 아닌 곳에서는 기록 명령이 기존과 같이 오류를 반환합니다.
|
|
140
|
+
|
|
141
|
+
같은 실행에 쓰는 명령은 최대 5초 동안 잠금을 기다립니다. 잠금은 시간이 지나도 자동으로 해제되지 않습니다. 강제 종료 뒤 잠금이 남아 있다면 해당 실행에 쓰거나 대기 중인 프로세스가 모두 종료됐는지 먼저 확인합니다. 그다음 오류에 표시된 `rmdir -- '<절대 경로>/.lock'` 명령으로 빈 잠금 디렉터리를 제거하고 다시 시도합니다. 기록은 임시 파일을 작성한 뒤 교체하는 방식으로 저장됩니다.
|
|
142
|
+
|
|
143
|
+
</details>
|
|
144
|
+
|
|
145
|
+
## 개발 및 테스트
|
|
146
|
+
|
|
147
|
+
테스트는 `npm test`로 실행합니다. 브라우저 렌더링 테스트는 선택 실행입니다. Chromium 계열 브라우저의 실행 파일 경로를 `ALIBAI_TEST_CHROMIUM`에 지정합니다. macOS의 Chrome에서는 다음 명령을 사용합니다.
|
|
148
|
+
|
|
149
|
+
```sh
|
|
150
|
+
ALIBAI_TEST_CHROMIUM='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' npm test
|
|
151
|
+
```
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
const node_path_1 = require("node:path");
|
|
6
|
+
const node_util_1 = require("node:util");
|
|
7
|
+
const git_1 = require("./git");
|
|
8
|
+
const report_1 = require("./report");
|
|
9
|
+
const store_1 = require("./store");
|
|
10
|
+
const viewer_1 = require("./viewer");
|
|
11
|
+
const flagNames = {
|
|
12
|
+
"run start": ["title", "platform", "agent", "base"],
|
|
13
|
+
step: ["run", "action", "before", "after", "note", "result"],
|
|
14
|
+
check: ["run", "target", "input", "before", "after", "expected", "error", "result"],
|
|
15
|
+
"run end": ["run", "verdict", "summary"],
|
|
16
|
+
list: [],
|
|
17
|
+
open: ["lang"],
|
|
18
|
+
};
|
|
19
|
+
const usage = `Usage
|
|
20
|
+
alibai run start --title <title> [--platform <platform>] [--agent <name>] [--base <ref>]
|
|
21
|
+
alibai step --action <action> [--before <file>] [--after <file>] [--note <text>] [--result <result>] [--run <id>]
|
|
22
|
+
alibai check --target <target> --input <json> --before <json> [--after <json>]
|
|
23
|
+
[--expected <json>] [--error <text>] [--result <result>] [--run <id>]
|
|
24
|
+
alibai run end --verdict <result> [--summary <text>] [--run <id>]
|
|
25
|
+
alibai list
|
|
26
|
+
alibai open [--lang <en|ko|ja>]
|
|
27
|
+
|
|
28
|
+
Provide at least one PNG, JPG, JPEG, or WebP screenshot for step.
|
|
29
|
+
Provide --after for check unless recording --error. Results and verdicts are pass, fail, or info.
|
|
30
|
+
Add --json to any command for machine-readable output.`;
|
|
31
|
+
const platforms = ["flutter", "ios", "android", "web"];
|
|
32
|
+
const results = ["pass", "fail", "info"];
|
|
33
|
+
const options = {
|
|
34
|
+
...Object.fromEntries(Object.values(flagNames).flat().map((flag) => [flag, { type: "string" }])),
|
|
35
|
+
json: { type: "boolean" },
|
|
36
|
+
help: { type: "boolean", short: "h" },
|
|
37
|
+
};
|
|
38
|
+
function textFlag(value, flag) {
|
|
39
|
+
const trimmed = value?.trim();
|
|
40
|
+
if (!trimmed)
|
|
41
|
+
throw new Error(`--${flag} requires a non-empty value.`);
|
|
42
|
+
return trimmed;
|
|
43
|
+
}
|
|
44
|
+
function choice(value, flag, allowed) {
|
|
45
|
+
const selected = allowed.find((option) => option === value);
|
|
46
|
+
if (!selected)
|
|
47
|
+
throw new Error(`--${flag} must be one of ${allowed.join(", ")}.`);
|
|
48
|
+
return selected;
|
|
49
|
+
}
|
|
50
|
+
const args = process.argv.slice(2);
|
|
51
|
+
const terminator = args.indexOf("--");
|
|
52
|
+
const trailing = terminator === -1 ? [] : args.slice(terminator + 1);
|
|
53
|
+
const { values, positionals } = (0, node_util_1.parseArgs)({
|
|
54
|
+
args: terminator === -1 ? args : args.slice(0, terminator),
|
|
55
|
+
options,
|
|
56
|
+
strict: false,
|
|
57
|
+
allowPositionals: true,
|
|
58
|
+
});
|
|
59
|
+
const json = values.json === true;
|
|
60
|
+
async function main() {
|
|
61
|
+
for (const flag of ["json", "help"]) {
|
|
62
|
+
if (typeof values[flag] === "string")
|
|
63
|
+
throw new Error(`--${flag} does not take a value.`);
|
|
64
|
+
}
|
|
65
|
+
const optionNames = Object.keys(values).filter((flag) => flag !== "json" && flag !== "help");
|
|
66
|
+
if (values.help === true || (positionals.length === 0 && trailing.length === 0 && optionNames.length === 0)) {
|
|
67
|
+
console.log(json ? JSON.stringify({ usage }) : usage);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
const [first, second] = positionals;
|
|
71
|
+
const command = first === "run" ? `run ${second ?? ""}` : first;
|
|
72
|
+
if (!command || !Object.hasOwn(flagNames, command)) {
|
|
73
|
+
throw new Error(`Unknown command "${command?.trim()}". See alibai --help.`);
|
|
74
|
+
}
|
|
75
|
+
const allowed = flagNames[command];
|
|
76
|
+
for (const flag of optionNames) {
|
|
77
|
+
if (!allowed.includes(flag))
|
|
78
|
+
throw new Error(`Unknown option '--${flag}'.`);
|
|
79
|
+
if (typeof values[flag] !== "string")
|
|
80
|
+
throw new Error(`--${flag} requires a value.`);
|
|
81
|
+
}
|
|
82
|
+
const unexpected = positionals[first === "run" ? 2 : 1] ?? trailing[0];
|
|
83
|
+
if (unexpected !== undefined)
|
|
84
|
+
throw new Error(`Unexpected argument "${unexpected}".`);
|
|
85
|
+
const flags = values;
|
|
86
|
+
if (command === "open") {
|
|
87
|
+
const lang = flags.lang === undefined ? undefined : choice(flags.lang, "lang", ["en", "ko", "ja"]);
|
|
88
|
+
await (0, viewer_1.openViewer)((0, git_1.gitRoot)(), json, lang);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
const root = (0, git_1.gitRoot)();
|
|
92
|
+
const store = new store_1.RunStore(root);
|
|
93
|
+
const printMutation = ({ path, run }) => {
|
|
94
|
+
console.log(json ? JSON.stringify({ id: run.id, path }) : `${run.id}\t${path}`);
|
|
95
|
+
};
|
|
96
|
+
const warnInvalid = (invalidRuns) => {
|
|
97
|
+
for (const { path, error } of invalidRuns)
|
|
98
|
+
console.error(`alibai: Skipping invalid run at ${path} (${error}).`);
|
|
99
|
+
};
|
|
100
|
+
const selectRun = async () => {
|
|
101
|
+
if (flags.run !== undefined)
|
|
102
|
+
return flags.run;
|
|
103
|
+
const { runs, invalidRuns } = await store.list();
|
|
104
|
+
warnInvalid(invalidRuns);
|
|
105
|
+
const selected = runs.find(({ run }) => run.verdict === undefined);
|
|
106
|
+
if (!selected)
|
|
107
|
+
throw new Error("No open run. Start one with alibai run start.");
|
|
108
|
+
return selected.run.id;
|
|
109
|
+
};
|
|
110
|
+
switch (command) {
|
|
111
|
+
case "run start": {
|
|
112
|
+
const title = textFlag(flags.title, "title");
|
|
113
|
+
const platform = choice(flags.platform ?? "web", "platform", platforms);
|
|
114
|
+
const agent = flags.agent === undefined ? undefined : textFlag(flags.agent, "agent");
|
|
115
|
+
const base = flags.base === undefined ? undefined : textFlag(flags.base, "base");
|
|
116
|
+
printMutation(await store.start({
|
|
117
|
+
formatVersion: 1,
|
|
118
|
+
id: (0, node_crypto_1.randomUUID)(),
|
|
119
|
+
title,
|
|
120
|
+
createdAt: new Date().toISOString(),
|
|
121
|
+
platform,
|
|
122
|
+
git: (0, git_1.gitMetadata)(root, base),
|
|
123
|
+
agent,
|
|
124
|
+
steps: [],
|
|
125
|
+
checks: [],
|
|
126
|
+
}));
|
|
127
|
+
break;
|
|
128
|
+
}
|
|
129
|
+
case "step": {
|
|
130
|
+
const action = textFlag(flags.action, "action");
|
|
131
|
+
const result = choice(flags.result ?? "info", "result", results);
|
|
132
|
+
if (flags.before === undefined && flags.after === undefined) {
|
|
133
|
+
throw new Error("Provide at least one screenshot with --before or --after.");
|
|
134
|
+
}
|
|
135
|
+
for (const source of [flags.before, flags.after]) {
|
|
136
|
+
if (source !== undefined && !/^\.(?:png|jpe?g|webp)$/i.test((0, node_path_1.extname)(source))) {
|
|
137
|
+
throw new Error(`Screenshot must use a PNG, JPG, JPEG, or WebP extension: ${source}`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
printMutation(await store.mutate(await selectRun(), async (run, screenshot) => {
|
|
141
|
+
const step = {
|
|
142
|
+
id: (0, node_crypto_1.randomUUID)(), order: run.steps.length + 1, action, createdAt: new Date().toISOString(),
|
|
143
|
+
note: flags.note ?? "", result,
|
|
144
|
+
};
|
|
145
|
+
if (flags.before !== undefined)
|
|
146
|
+
step.before = await screenshot(flags.before, `${step.id}-before`);
|
|
147
|
+
if (flags.after !== undefined)
|
|
148
|
+
step.after = await screenshot(flags.after, `${step.id}-after`);
|
|
149
|
+
run.steps.push(step);
|
|
150
|
+
}));
|
|
151
|
+
break;
|
|
152
|
+
}
|
|
153
|
+
case "check": {
|
|
154
|
+
const target = textFlag(flags.target, "target");
|
|
155
|
+
const input = (0, report_1.parseJson)(textFlag(flags.input, "input"), "--input");
|
|
156
|
+
const before = (0, report_1.parseJson)(textFlag(flags.before, "before"), "--before");
|
|
157
|
+
const expected = flags.expected === undefined ? undefined : (0, report_1.parseJson)(flags.expected, "--expected");
|
|
158
|
+
const error = flags.error === undefined ? undefined : textFlag(flags.error, "error");
|
|
159
|
+
if (flags.after === undefined && error === undefined) {
|
|
160
|
+
throw new Error("Provide --after with a JSON value or --error for an exception.");
|
|
161
|
+
}
|
|
162
|
+
const outcome = flags.after === undefined && error !== undefined
|
|
163
|
+
? { error }
|
|
164
|
+
: { after: (0, report_1.parseJson)(textFlag(flags.after, "after"), "--after"), error };
|
|
165
|
+
const result = choice(flags.result ?? "info", "result", results);
|
|
166
|
+
printMutation(await store.mutate(await selectRun(), async (run) => {
|
|
167
|
+
run.checks.push({ id: (0, node_crypto_1.randomUUID)(), target, createdAt: new Date().toISOString(), input, before, expected, result, ...outcome });
|
|
168
|
+
}));
|
|
169
|
+
break;
|
|
170
|
+
}
|
|
171
|
+
case "run end": {
|
|
172
|
+
const verdict = choice(flags.verdict, "verdict", results);
|
|
173
|
+
const summary = flags.summary ?? `Verdict recorded as ${verdict}.`;
|
|
174
|
+
if (!summary.trim() || /[\r\n\u2028\u2029]/u.test(summary)) {
|
|
175
|
+
throw new Error("--summary requires one non-empty line.");
|
|
176
|
+
}
|
|
177
|
+
printMutation(await store.mutate(await selectRun(), async (run) => {
|
|
178
|
+
run.verdict = verdict;
|
|
179
|
+
run.summary = summary.trim();
|
|
180
|
+
run.endedAt = new Date().toISOString();
|
|
181
|
+
run.git.endChanges = (0, git_1.gitChanges)(root).changes;
|
|
182
|
+
}));
|
|
183
|
+
break;
|
|
184
|
+
}
|
|
185
|
+
case "list": {
|
|
186
|
+
const { runs: stored, invalidRuns } = await store.list();
|
|
187
|
+
const runs = stored.map(({ path, run }) => ({
|
|
188
|
+
id: run.id,
|
|
189
|
+
path,
|
|
190
|
+
title: run.title,
|
|
191
|
+
createdAt: run.createdAt,
|
|
192
|
+
platform: run.platform,
|
|
193
|
+
verdict: run.verdict ?? null,
|
|
194
|
+
}));
|
|
195
|
+
if (json)
|
|
196
|
+
console.log(JSON.stringify({ runs, invalidRuns }));
|
|
197
|
+
else {
|
|
198
|
+
warnInvalid(invalidRuns);
|
|
199
|
+
if (runs.length === 0)
|
|
200
|
+
console.log("No runs recorded.");
|
|
201
|
+
else
|
|
202
|
+
for (const run of runs)
|
|
203
|
+
console.log(`${run.id}\t${run.verdict ?? "open"}\t${run.title}\t${run.path}`);
|
|
204
|
+
}
|
|
205
|
+
break;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
main().catch((error) => {
|
|
210
|
+
console.error(json ? JSON.stringify({ error: error.message }) : `alibai: ${error.message}`);
|
|
211
|
+
process.exitCode = 1;
|
|
212
|
+
});
|
package/dist/git.js
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.gitRoot = gitRoot;
|
|
4
|
+
exports.gitChanges = gitChanges;
|
|
5
|
+
exports.gitMetadata = gitMetadata;
|
|
6
|
+
const node_child_process_1 = require("node:child_process");
|
|
7
|
+
const node_crypto_1 = require("node:crypto");
|
|
8
|
+
const node_fs_1 = require("node:fs");
|
|
9
|
+
const node_path_1 = require("node:path");
|
|
10
|
+
const readLimit = 32 * 1024 * 1024;
|
|
11
|
+
function gitCommand(cwd, ...args) {
|
|
12
|
+
const env = { ...process.env, GIT_NO_LAZY_FETCH: "1", LC_ALL: "C" };
|
|
13
|
+
// Git gives this environment variable precedence over --unified.
|
|
14
|
+
delete env.GIT_DIFF_OPTS;
|
|
15
|
+
return (0, node_child_process_1.spawnSync)("git", args, {
|
|
16
|
+
cwd,
|
|
17
|
+
env,
|
|
18
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
19
|
+
// shortcut: cap each Git read at 32 MiB, stream patches if larger snapshots are needed.
|
|
20
|
+
maxBuffer: readLimit,
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
function gitBytes(result) {
|
|
24
|
+
return !result.error && result.status === 0 ? result.stdout : null;
|
|
25
|
+
}
|
|
26
|
+
function gitText(result) {
|
|
27
|
+
return gitBytes(result)?.toString("utf8").replace(/\r?\n$/, "") ?? null;
|
|
28
|
+
}
|
|
29
|
+
function gitRoot() {
|
|
30
|
+
const result = gitCommand(process.cwd(), "rev-parse", "--show-toplevel");
|
|
31
|
+
if (result.error?.code === "ENOENT") {
|
|
32
|
+
throw new Error("Git must be installed to use alibai.");
|
|
33
|
+
}
|
|
34
|
+
if (result.error)
|
|
35
|
+
throw result.error;
|
|
36
|
+
const root = gitText(result);
|
|
37
|
+
if (!root)
|
|
38
|
+
throw new Error("Run alibai from a Git working tree.");
|
|
39
|
+
return root;
|
|
40
|
+
}
|
|
41
|
+
function untrackedDigest(file, rootPrefix) {
|
|
42
|
+
const entry = (0, node_fs_1.lstatSync)(file);
|
|
43
|
+
if (entry.isSymbolicLink()) {
|
|
44
|
+
return { kind: "l", digest: (0, node_crypto_1.createHash)("sha256").update((0, node_fs_1.readlinkSync)(file, { encoding: "buffer" })).digest() };
|
|
45
|
+
}
|
|
46
|
+
// Git lists paths below the root. Check that parent links haven't redirected a file outside it.
|
|
47
|
+
if (!entry.isFile())
|
|
48
|
+
return null;
|
|
49
|
+
const resolved = node_fs_1.realpathSync.native(file, { encoding: "buffer" });
|
|
50
|
+
if (!resolved.subarray(0, rootPrefix.length).equals(rootPrefix))
|
|
51
|
+
return null;
|
|
52
|
+
const fd = (0, node_fs_1.openSync)(resolved, node_fs_1.constants.O_RDONLY | node_fs_1.constants.O_NOFOLLOW | node_fs_1.constants.O_NONBLOCK);
|
|
53
|
+
try {
|
|
54
|
+
const stat = (0, node_fs_1.fstatSync)(fd);
|
|
55
|
+
if (!stat.isFile() || stat.dev !== entry.dev || stat.ino !== entry.ino || stat.size > readLimit)
|
|
56
|
+
return null;
|
|
57
|
+
const hash = (0, node_crypto_1.createHash)("sha256");
|
|
58
|
+
const buffer = Buffer.allocUnsafe(64 * 1024);
|
|
59
|
+
let total = 0;
|
|
60
|
+
for (;;) {
|
|
61
|
+
const size = (0, node_fs_1.readSync)(fd, buffer, 0, Math.min(buffer.length, readLimit - total + 1), null);
|
|
62
|
+
if (size === 0)
|
|
63
|
+
return { kind: "f", digest: hash.digest() };
|
|
64
|
+
total += size;
|
|
65
|
+
if (total > readLimit)
|
|
66
|
+
return null;
|
|
67
|
+
hash.update(buffer.subarray(0, size));
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
(0, node_fs_1.closeSync)(fd);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
function snapshotDigest(root, headSha, untracked) {
|
|
75
|
+
const diff = (...revisions) => gitBytes(gitCommand(root, "--no-optional-locks", "-c", "core.quotePath=true", "-c", "core.bigFileThreshold=512m", "-c", "diff.suppressBlankEmpty=false", "-c", "diff.mnemonicPrefix=false", "-c", "diff.noprefix=false", "diff", "--binary", "--full-index", "--no-ext-diff", "--no-textconv", "--no-color", "--no-renames", "--no-relative", "--submodule=short", "--src-prefix=a/", "--dst-prefix=b/", "-O/dev/null", "--diff-algorithm=myers", "--unified=3", "--inter-hunk-context=0", "--indent-heuristic", ...revisions, "--", ":(top,exclude,literal).alibai"));
|
|
76
|
+
const staged = diff("--cached", headSha);
|
|
77
|
+
const unstaged = diff();
|
|
78
|
+
if (!staged || !unstaged || !(staged.length || unstaged.length || untracked.length))
|
|
79
|
+
return null;
|
|
80
|
+
// Lengths distinguish the two patches and each path. File digests are always 32 bytes.
|
|
81
|
+
const hash = (0, node_crypto_1.createHash)("sha256").update(`${staged.length}\n${unstaged.length}\n`).update(staged).update(unstaged);
|
|
82
|
+
try {
|
|
83
|
+
if (untracked.length) {
|
|
84
|
+
const realRoot = (0, node_fs_1.realpathSync)(root);
|
|
85
|
+
const rootPrefix = Buffer.from(realRoot.endsWith(node_path_1.sep) ? realRoot : realRoot + node_path_1.sep);
|
|
86
|
+
for (const path of untracked.sort(Buffer.compare)) {
|
|
87
|
+
const file = untrackedDigest(Buffer.concat([rootPrefix, path]), rootPrefix);
|
|
88
|
+
if (!file)
|
|
89
|
+
return null;
|
|
90
|
+
hash.update(`${file.kind}${path.length}\n`).update(path).update(file.digest);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return hash.digest("hex");
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
function gitChanges(root, headSha = gitText(gitCommand(root, "rev-parse", "--verify", "HEAD^{commit}"))) {
|
|
100
|
+
const status = gitBytes(gitCommand(root, "--no-optional-locks", "status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames"));
|
|
101
|
+
if (!status)
|
|
102
|
+
return { changes: null };
|
|
103
|
+
const dirty = status.length > 0;
|
|
104
|
+
const paths = new Set();
|
|
105
|
+
const untracked = [];
|
|
106
|
+
for (let offset = 0; offset < status.length;) {
|
|
107
|
+
const end = status.indexOf(0, offset);
|
|
108
|
+
if (end < offset + 4)
|
|
109
|
+
return { changes: null };
|
|
110
|
+
const path = status.subarray(offset + 3, end);
|
|
111
|
+
const name = path.toString("utf8");
|
|
112
|
+
if (name !== ".alibai" && !name.startsWith(".alibai/")) {
|
|
113
|
+
paths.add(name);
|
|
114
|
+
if (status.toString("ascii", offset, offset + 2) === "??")
|
|
115
|
+
untracked.push(path);
|
|
116
|
+
}
|
|
117
|
+
offset = end + 1;
|
|
118
|
+
}
|
|
119
|
+
if (paths.size === 0)
|
|
120
|
+
return { dirty };
|
|
121
|
+
const diffSha256 = headSha ? snapshotDigest(root, headSha, untracked) : null;
|
|
122
|
+
return { dirty, changes: { paths: [...paths].sort(), diffSha256 } };
|
|
123
|
+
}
|
|
124
|
+
function gitMetadata(root, base) {
|
|
125
|
+
const git = (...args) => gitText(gitCommand(root, ...args));
|
|
126
|
+
const branch = git("symbolic-ref", "--quiet", "HEAD")?.replace(/^refs\/heads\//, "") ?? null;
|
|
127
|
+
const headSha = git("rev-parse", "--verify", "HEAD^{commit}");
|
|
128
|
+
const { dirty, changes: startChanges } = gitChanges(root, headSha);
|
|
129
|
+
const metadata = { branch, headSha, dirty, startChanges };
|
|
130
|
+
if (base !== undefined) {
|
|
131
|
+
const baseSha = git("rev-parse", "--verify", "--end-of-options", `${base}^{commit}`);
|
|
132
|
+
if (!baseSha)
|
|
133
|
+
throw new Error(`--base does not resolve to a local commit: ${base}`);
|
|
134
|
+
return { ...metadata, baseSha };
|
|
135
|
+
}
|
|
136
|
+
if (headSha) {
|
|
137
|
+
for (const ref of [
|
|
138
|
+
"refs/remotes/origin/HEAD", "refs/remotes/origin/main", "refs/heads/main",
|
|
139
|
+
"refs/remotes/origin/master", "refs/heads/master",
|
|
140
|
+
]) {
|
|
141
|
+
const baseSha = git("merge-base", headSha, ref);
|
|
142
|
+
if (baseSha && baseSha !== headSha)
|
|
143
|
+
return { ...metadata, baseSha };
|
|
144
|
+
}
|
|
145
|
+
return { ...metadata, baseSha: git("rev-parse", "--verify", `${headSha}^1`) };
|
|
146
|
+
}
|
|
147
|
+
return { ...metadata, baseSha: null };
|
|
148
|
+
}
|
package/dist/report.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.runId = void 0;
|
|
7
|
+
exports.assertRun = assertRun;
|
|
8
|
+
exports.parseJson = parseJson;
|
|
9
|
+
const _2020_1 = __importDefault(require("ajv/dist/2020"));
|
|
10
|
+
const run_schema_json_1 = __importDefault(require("./run.schema.json"));
|
|
11
|
+
exports.runId = new RegExp(run_schema_json_1.default.$defs.id.pattern);
|
|
12
|
+
let validate;
|
|
13
|
+
function assertRun(value, label) {
|
|
14
|
+
validate ??= new _2020_1.default({ strictRequired: false })
|
|
15
|
+
.addFormat("date-time", (value) => {
|
|
16
|
+
const time = Date.parse(value);
|
|
17
|
+
return Number.isFinite(time) && new Date(time).toISOString() === value;
|
|
18
|
+
})
|
|
19
|
+
.compile(run_schema_json_1.default);
|
|
20
|
+
if (!validate(value)) {
|
|
21
|
+
const error = validate.errors?.[0];
|
|
22
|
+
throw new Error(`${label}: invalid run format at ${error?.instancePath || "/"} (${error?.message}).`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function parseJson(value, label) {
|
|
26
|
+
try {
|
|
27
|
+
return JSON.parse(value, (_key, parsed) => {
|
|
28
|
+
if (typeof parsed === "number" && !Number.isFinite(parsed)) {
|
|
29
|
+
throw new Error("number is outside the supported range");
|
|
30
|
+
}
|
|
31
|
+
return parsed;
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
throw new Error(`${label}: invalid JSON (${error.message}).`);
|
|
36
|
+
}
|
|
37
|
+
}
|