2026年4月30日 星期四

momo 購買小米 20000 mAh 行動電源

因下周要帶爸與岳父母去沖繩玩, 今天上網買了一顆小米行動電源 :


100Wh 以下可帶上飛機




用掉 74 元 momo 幣實付 525 元. 

(補記) 購買 HiSKIO 課程 : Claude Code 深度應用

我可能線上課程買太多買到頭昏了, 最近在臉書看到一門 Claude Code 課程 56 折即將結束, 趁中午截止前上網想先買下 (雖然可能要半年後才會開啟 Claude Code 付費) : 


沒想到登入 HiSKIO 赫然看到網站提醒 : 你已購買本課程! 蝦米? 查了訂購記錄, 這門課我今年 2/6 就買了, 當時可能一忙忘了記下來. 這就像我存摺有很多本 (但也不至於到 100 本啦) 藏錢都藏到忘記自己很有錢了. 補記一下免得又忘記了 :




我在 HiSKIO 目前就只有林彥文老師的 "Vibe Coding 全能實戰課" (已上完, 要複習) 與這堂 Claude Code 課, 等沖繩回來要開始上課了 (還有 TibaMe 與 Hahow 的呵呵). 

Python 學習筆記 : 用 plotly 繪製互動式圖表 (三)

本篇旨在測試 Plotly 的圖表匯出功能. 


Plotly 支援多種檔案類型匯出, 可呼叫下表中 Figure 物件的方法匯出 :


Figure 物件的檔案匯出方法 說明
fig.write_image(file, **kwargs) 匯出為靜態圖片(PNG、JPEG、SVG、PDF 等),需安裝 kaleido
fig.write_html(file, **kwargs) 匯出為互動式 HTML 檔,可直接用瀏覽器開啟
fig.to_html(full_html=True, include_plotlyjs='cdn') 將圖表轉為 HTML 字串(用於網頁內嵌或 API 回傳)
fig.to_json() 將圖表轉為 JSON 格式(適合儲存、API 傳遞、版本控管)
fig.write_json(file) 將圖表 JSON 結構直接寫入檔案
fig.to_dict() 將圖表轉為 Python 字典格式,可進一步程式操作


注意, fig.write_image() 方法須依賴 kaleido 模組, 這是 Plotly 官方推出的匯圖引擎模組, 用來將 Plotly 圖表儲存為靜態圖片.


1. 匯出圖檔 : 

呼叫 Figure 物件的 write_image() 方法可將繪製的圖表匯出成圖片檔 (支援 PNG, JPG, SVG, PDF 等檔案類型), 其參數結構如下 :

fig.write_image(
    file,             # 必填,檔案路徑字串或類似檔案的物件
    format=None,      # 圖片格式,如 'png'、'jpeg'、'svg'、'pdf',若省略會自動從副檔名判斷
    width=None,       # 圖片寬度(像素),預設為圖表原始寬度
    height=None,      # 圖片高度(像素),預設為圖表原始高度
    scale=1,          # 圖片縮放倍數(例如 2 表示解析度加倍)
    validate=True,    # 是否檢查圖表是否有效(預設 True)
    engine='kaleido'  # 使用的圖像引擎,預設為 'kaleido'
    )

不過使用此方法之前須先安裝 Plotly 的 kaleido 模組, 而且 plotly 也要提升至最新版 :

pip install kaleido   
pip install plotly -U

在前一篇測試中使用了 plotly.express 來繪製長條圖, 下列沿用此範例來匯出所繪製的圖檔 : 

# plotly_chart_export_1.py
import plotly.express as px
import pandas as pd
import os

# 1. 資料來源
data={
    '月份': ['一月', '二月', '三月', '四月', '五月'],
    '營收': [120000, 135000, 99000, 150000, 170000]    
    }

# 2. 建立 Figure 圖表物件
# 注意:這裡設定了 width 和 height,匯出圖片時會以此為基準
fig=px.bar(data, x='月份', y='營收', width=800, height=600, title="月營收統計圖")

# 3. 顯示圖表 (選用)
fig.show()

# 4. 匯出圖檔 
# 建立儲存目錄(選用,避免檔案雜亂)
if not os.path.exists("output"):
    os.mkdir("output")
# 匯出為 PNG
fig.write_image("output/revenue_report.png", scale=2)
# 匯出為 JPG
fig.write_image("output/revenue_report.jpg", scale=2)
print("圖檔已匯出至 output 資料夾中。")

執行結果除了 fig.show() 會開啟瀏覽器顯示長條圖外, 也會在目前工作目錄下建立 output 子目錄存放匯出的兩個圖檔 :

>>> %Run plotly_chart_export_1.py   
圖檔已匯出至 output 資料夾中。




2. 匯出網頁 : 

呼叫 fig.write_html() 可將繪製之圖表匯出為 HTML 檔, 若傳入 include_plotlyjs='cdn' 參數會使用 CDN 的 plotly 函式庫, 這樣匯出的 HTML 檔較小但須連網才能看到互動圖表; 否則會將 plotly 函式庫一同匯出, 檔案較大些 (約 4MB) 但不須連網, 離線開啟網頁即可看到互動圖表.

程式碼如下 : 

# plotly_chart_export_2.py
import plotly.express as px
import pandas as pd
import os

# 1. 資料來源
data={
    '月份': ['一月', '二月', '三月', '四月', '五月'],
    '營收': [120000, 135000, 99000, 150000, 170000]    
    }

# 2. 建立 Figure 圖表物件
fig=px.bar(data, x='月份', y='營收', width=800, height=600, title="月營收統計圖 (互動式 HTML)")

# 3. 建立儲存目錄
output_dir="output"
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

# --- 匯出 HTML  ---
# 方式 A:標準匯出 (將 Plotly.js 核心程式碼打包進去,檔案約 4 MB,可離線開啟)
fig.write_html(os.path.join(output_dir, "report_full.html"))

# 方式 B:輕量化匯出 (使用 CDN 連結,檔案僅約 50KB,開啟時需連網載入 JS)
fig.write_html(
    os.path.join(output_dir, "report_cdn.html"), 
    include_plotlyjs='cdn'
    )

print(f"✅ HTML 檔案已匯出至 {output_dir} 資料夾。")
print("- report_full.html (可離線檢視)")
print("- report_cdn.html (體積小,需連網)")

# 顯示圖表
fig.show()

執行結果如下 :

>>> %Run plotly_chart_export_2.py
✅ HTML 檔案已匯出至 output 資料夾。
- report_full.html (可離線檢視)
- report_cdn.html (體積小,需連網)

開啟 output 資料夾下的網頁檔即可看到長條圖 :




2026年4月29日 星期三

Python 學習筆記 : 利用語言模型計算技術指標 (一)

最近重讀旗標出版的 "最強 AI 投資分析" 這本書, 此書於 2023 年底買來看了前幾章便擱下, 也沒時間做測試, 今天重讀第四章後, 決定動手來測試看看, 因為去年 10/7 儲值 5 美元的 OpenAI API Key 目前只用了 0.01 美元, 只剩半年就要被清零了, 得在這之前趕快用掉 (在 Vibe coding 時代親自寫程式已淪落為純興趣了). 





書中範例程式碼下載網址 :



1. 利用 pandas_ta 計算 SMA 指標 : 

首先用 pandas_ta 來計算移動平均指標 SMA8 與 SMA13 暖暖身, 畢竟已有近半年沒接觸了, 關於  pandas_ta 套件用法參考 :


下列程式使用 yfinance 取得收盤資料, 然後用 pandas_ta 套件的擴展屬性用法呼叫 df.ta.ma() 計算 SMA 指標, 結果會自動放入 df 的指定欄位, 最後用 kbar 套件繪製 K 線圖, 關於 kbar 套件用法參考 :


# ai_stock_test_1.py
import yfinance as yf
import pandas as pd 
import pandas_ta as ta
from kbar import KBar
          
if __name__ == "__main__":
    df=yf.download('0050.tw', start='2024-07-01', end='2024-08-21', auto_adjust=True)
    df.columns=df.columns.map(lambda x: x[0])
    df['SMA_8']=df.ta.sma(length=8)
    df['SMA_13']=df.ta.sma(length=13)
    print(df.tail())
    kb=KBar(df)
    kb.addplot(df['SMA_8'], panel=2, ylabel='SMA_8')
    kb.addplot(df['SMA_13'], panel=2, ylabel='SMA_13')
    kb.plot(volume=True, mav=[8, 13])
    
此處除了在 panel 2 上繪製 SMA8 與 SMA13 指標外, 同時也在 plot() 方法中指定 mav=[8, 13] 繪製 K 線圖之疊圖 (預設 panel=0), 結果如下 : 

>>> %Run ai_stock_test_1.py   
[*********************100%***********************]  1 of 1 completed
                Close       High        Low  ...    Volume      SMA_8     SMA_13
Date                                         ...                                
2024-08-14  43.643597  43.909202  43.450429  ...  74857276  41.775311  42.438161
2024-08-15  43.305553  43.703958  43.233115  ...  45926588  42.397066  42.414943
2024-08-16  44.283455  44.343819  44.029927  ...  52823660  42.876964  42.466949
2024-08-19  44.343822  44.597354  44.223093  ...  37122372  43.163695  42.518955
2024-08-20  44.367966  44.718080  44.355892  ...  43139504  43.562101  42.514312

[5 rows x 7 columns]
設定字型為: Microsoft JhengHei
使用指定字型: Microsoft JhengHei
字型候選清單: ['Microsoft JhengHei', 'DejaVu Sans', 'Arial']




2. 串接 OpenAI API 計算 SMA 指標 : 

接下來要串接 OpenAI API, 讓 LLM 模型來生成計算技術指標的程式碼後, 用 exec() 執行該程式碼計算技術指標, 好處是毋須去熟悉例如 pandas_ta, ta, 或 Ta-Lib 套件之函式呼叫介面, 直接用自然語言來指揮 LLM 傳回技術指標計算式, 做法參考書中 ˋ4-1 的範例 : 


原程式碼的提示詞使用英文, 作者說經測試使用英文較能得到穩定之回應, 但現在 LLM 日新月異, 對中文的理解能力已非常精準, 因此我將其改寫為中文提示詞, 程式碼如下 :

# ai_stock_test_2.py
from  openai import OpenAI, APIError 
import yfinance as yf
import pandas as pd 
from dotenv import dotenv_values
from kbar import KBar

def ask_gpt(
    messages: list[dict[str, str]],
    model: str='gpt-3.5-turbo'
    ) -> str:
    try:
        reply=client.chat.completions.create(
            model=model, 
            messages=messages
            )
        return reply.choices[0].message.content or ''
    except APIError as e:
        return e.message

def ai_helper(df, user_msg):
    role=f'''
        作為一個專業的程式碼生成機器人,
        我需要您的協助來根據特定的用戶需求生成 Python 程式碼。
        為了進行下去,我將提供給您一個遵循格式 {list(df.columns)} 的 DataFrame(df)。
        您的任務是仔細分析用戶的需求並相應地生成 Python 程式碼。
        請注意,您的回應須僅包含代碼本身,並且不應包含任何額外的資訊。
        '''
    # 把 user_msg 加入到 task 的敘述中,讓 AI 知道要算什麼
    task=f'''
        您的任務是開發一個名為 'calculate(df)' 的 Python 函式。
        這個函式應接受一個 DataFrame 作為其參數。確保您僅使用資料集中存在的欄,
        特別是 {list(df.columns)}。        
        用戶的具體運算需求為:【 {user_msg} 】        
        處理後,該函式應返回處理過的 DataFrame。
        您的回應應嚴格包含 'calculate(df)' 函式的 Python 程式碼,
        並排除任何無關的內容。
        '''
    msg=[{"role": "system", "content": role},
         {"role": "user", "content": task}]
    reply_data=ask_gpt(msg)
    # 清理 markdown 語法
    cleaned_code=reply_data.replace("```", "")
    cleaned_code=cleaned_code.replace("python", "")      
    cleaned_code=cleaned_code.strip() # 建議加上 strip() 去除頭尾多餘的空白或換行
    # 傳回程式碼
    return cleaned_code
          
if __name__ == "__main__":
    config=dotenv_values('.env') 
    openai_api_key=config.get('OPENAI_API_KEY')
    client=OpenAI(api_key=openai_api_key)
    df=yf.download('0050.tw', start='2024-07-01', end='2024-08-21', auto_adjust=True)
    df.columns=df.columns.map(lambda x: x[0])
    code_str=ai_helper(df, "計算 8 日 MA (欄名 SMA_8) 與 13 日 MA (欄名 SMA_13)")
    print(code_str)
    exec(code_str)
    new_df=calculate(df)
    print(new_df.tail())
    kb=KBar(new_df)
    kb.addplot(new_df['SMA_8'], panel=2, ylabel='SMA_8')
    kb.addplot(new_df['SMA_13'], panel=2, ylabel='SMA_13')
    kb.plot(volume=True, mav=[8, 13]) 

此程式的 ask_gpt() 函式負責向 GPT 提問並取得回應, 注意, ask_gpt() 的傳入參數都使用了類型提示語法以增加程式碼可讀性. 例如 ask_gpt() 中的 messages: list[dict[str, str]] 意思是 :
  • messages 是一個串列, 裡面的每個元素都是字典.
  • 字典的鍵與值都是字串, 例如 {"role": "user", "content": "hello"}
參考 :


而 ai_helper() 函式則負責組裝提示詞 (字典串列) 並呼叫 ask_gpt(), 取得回應的指標計算程式碼後進行清理, 傳回純淨之 Python 程式碼給主函式以 exec() 執行, 結果如下 : 

>>> %Run ai_stock_test_2.py  
[*********************100%***********************]  1 of 1 completed
def calculate(df):
    df['SMA_8'] = df['Close'].rolling(window=8).mean()
    df['SMA_13'] = df['Close'].rolling(window=13).mean()
    return df
                Close       High        Low  ...    Volume      SMA_8     SMA_13
Date                                         ...                                
2024-08-14  43.643597  43.909202  43.450429  ...  74857276  41.775311  42.438161
2024-08-15  43.305553  43.703958  43.233115  ...  45926588  42.397066  42.414943
2024-08-16  44.283455  44.343819  44.029927  ...  52823660  42.876964  42.466949
2024-08-19  44.343822  44.597354  44.223093  ...  37122372  43.163695  42.518955
2024-08-20  44.367966  44.718080  44.355892  ...  43139504  43.562101  42.514312

[5 rows x 7 columns]
設定字型為: Microsoft JhengHei
使用指定字型: Microsoft JhengHei
字型候選清單: ['Microsoft JhengHei', 'DejaVu Sans', 'Arial']




計算出來的 SMA 數值與用 pandas_ta 計算的結果相同, 可見即使沒學過技術指標套件, 也可以利用 LLM 來進行技術指標的量化分析. 


3. 串接 Gemini API 計算 SMA 指標 : 

Gemini 版本的函式要改成 ask_gemini(), 而 ai_helper() 函式基本不變, 只有提示詞類型不同, OpenAI 的提示詞為字典字串, 而 Gemini 則是純字串. 程式碼如下 :

# ai_stock_test_3.py
from google import genai
from google.genai.errors import APIError
import yfinance as yf
import pandas as pd 
from dotenv import dotenv_values
from kbar import KBar

def ask_gemini(messages: str, model: str='gemini-2.5-flash') -> str:
    try:
        reply=client.models.generate_content(
            model=model, 
            contents=messages
            )
        return reply.text or ''
    except APIError as e:
        return e.message

def ai_helper(df, user_msg):
    role=f'''
        作為一個專業的程式碼生成機器人,
        我需要您的協助來根據特定的用戶需求生成 Python 程式碼。
        為了進行下去,我將提供給您一個遵循格式 {list(df.columns)} 的 DataFrame(df)。
        您的任務是仔細分析用戶的需求並相應地生成 Python 程式碼。
        請注意,您的回應須僅包含代碼本身,並且不應包含任何額外的資訊。
        '''
    task=f'''
        您的任務是開發一個名為 'calculate(df)' 的 Python 函式。
        這個函式應接受一個 DataFrame 作為其參數。確保您僅使用資料集中存在的欄,
        特別是 {list(df.columns)}。        
        用戶的具體運算需求為:【 {user_msg} 】        
        處理後,該函式應返回處理過的 DataFrame。
        您的回應應嚴格包含 'calculate(df)' 函式的 Python 程式碼,
        並排除任何無關的內容。
        '''
    # Gemini 的提示詞為字串型態 : 將系統設定與任務直接合併成一段完整的字串
    msg=f"{role}\n\n{task}"    
    # 呼叫 ask_gemini
    reply_data=ask_gemini(msg)
    # 清理傳回 markdown 語法
    cleaned_code=reply_data.replace("```", "")
    cleaned_code=cleaned_code.replace("python", "")      
    cleaned_code=cleaned_code.strip() # 去除頭尾多餘的空白或換行
    # 傳回程式碼
    return cleaned_code
          
if __name__ == "__main__":
    config=dotenv_values('.env') 
    gemini_api_key=config.get('GEMINI_API_KEY')
    client=genai.Client(api_key=gemini_api_key)
    df=yf.download('0050.tw', start='2024-07-01', end='2024-08-21', auto_adjust=True)
    df.columns=df.columns.map(lambda x: x[0])
    code_str=ai_helper(df, "計算 8 日 MA (欄名 SMA_8) 與 13 日 MA (欄名 SMA_13)")
    print(code_str)
    exec(code_str)
    new_df=calculate(df)
    print(new_df.tail())
    kb=KBar(new_df)
    kb.addplot(new_df['SMA_8'], panel=2, ylabel='SMA_8')
    kb.addplot(new_df['SMA_13'], panel=2, ylabel='SMA_13')
    kb.plot(volume=True, mav=[8, 13]) 

結果與上面是一樣的 :

>>> %Run ai_stock_test_3.py
[*********************100%***********************]  1 of 1 completed
import pandas as pd

def calculate(df):
    """
    計算 8 日 MA (欄名 SMA_8) 與 13 日 MA (欄名 SMA_13)。

    Args:
        df (pd.DataFrame): 包含 'Close', 'High', 'Low', 'Open', 'Volume' 欄位的 DataFrame。

    Returns:
        pd.DataFrame: 處理後包含 'SMA_8' 和 'SMA_13' 欄位的 DataFrame。
    """
    df['SMA_8'] = df['Close'].rolling(window=8).mean()
    df['SMA_13'] = df['Close'].rolling(window=13).mean()
    return df
                Close       High        Low  ...    Volume      SMA_8     SMA_13
Date                                         ...                                
2024-08-14  43.643597  43.909202  43.450429  ...  74857276  41.775310  42.438160
2024-08-15  43.305553  43.703958  43.233115  ...  45926588  42.397066  42.414943
2024-08-16  44.283459  44.343823  44.029930  ...  52823660  42.876964  42.466949
2024-08-19  44.343822  44.597354  44.223093  ...  37122372  43.163696  42.518955
2024-08-20  44.367966  44.718080  44.355892  ...  43139504  43.562102  42.514312

[5 rows x 7 columns]
設定字型為: Microsoft JhengHei
使用指定字型: Microsoft JhengHei
字型候選清單: ['Microsoft JhengHei', 'DejaVu Sans', 'Arial']



2026年4月28日 星期二

市圖還書兩本 (React)

前陣子因為在 Vibe Coding 開發中, 發現 AI 經常使用 React 作為前端框架, 於是興起一股學學看的念頭, 從市圖借來幾本 React 的書, 沒有打算深入研究, 只想對核心運作有個基本認識. 不過還沒開卷呢, 下面兩本已被預約須還 :
No.1 作者是 ReacJS 新聞站長, 此書雖較舊了, 但前半部有豐富的 ES6 語法介紹; No.2 書況極新 (2024 年出版), 內容也更豐富, 包含伺服端 React, 與 Next.js 框架等, 下次再回借. 

2026年4月26日 星期日

2026 年第 16 周記事

週五天氣轉陰, 下班時差點淋到雨, 傍晚回鄉下時開始下起小雨, 整個晚上都在下, 甚至連周六也是下整天, 雨天無訪客剛好在家趕 SDD 線上課程的作業, 花了整整一天終於在周六晚上午夜關檔前完成作業上傳, 好險! 45 個學員也只有 9 個趕上截止期限 (我是最後一個哈哈).

幸好今天出太陽, 趕緊將沙發罩洗好拿去曬, 因下周大帥與仲仔要造訪鄉下家, 得事先整理一下客廳. 下午把馬路邊的三棵芒果樹都套袋完畢, 約莫 60 顆左右, 樹梢還有很多太高無法套袋, 下周要去小漢買網子攤開綁在樹下, 這樣等自然熟掉下來時才不會摔壞. 




由於雨季即將來臨, 蔥價會攀高, 早上跑了一趟種子行買了 20 株青蔥苗+一株九層塔+六株皇宮菜, 年初種了一盆香菜長不好, 傍晚全部拔掉改種青蔥, 九層塔也是盆栽, 皇宮菜則暫時放著澆水, 小舅五月初要叫小耕耘機把菜園的土翻一遍, 說之後保留兩畦給他秋天時種小番茄, 其餘我要種菜或種果樹均好, 因為他家那邊也有一個菜園要顧 (去年他朋友借他使用). 菜園南側因為較遠, 種菜澆水較不便, 打算再種兩棵芭樂樹與木瓜樹. 

毛小妹第二胎 (也是四隻) 小貓現在都在室外了, 這梯都很怕人不親, 我一靠近就跑掉. 上一梯的四隻目前只剩小黑與吉哇哇在家, 小乖與哇哇吉都離家超過一個月不回來了. 毛小妹的妹妹捲尾阿姨我也一周未見她出現, 恐怕也不回來了. 雖說不回來, 其實我認為它們應該都是遇險 (中毒/車禍) 回不來. 




車庫雜物實在太多了, 等沖繩回來得來個斷捨離大清理了. 

2026年4月25日 星期六

Gemini CLI 學習筆記 : OpenSpec 初體驗 (三)

離作業交卷只剩 2.5 小時, 刻不容緩繼續進行第三次迭代.

本系列全部測試文章參考 : 


第三次迭代要在前次基礎上添加對數與三角函數科學計算功能, 同樣使用逐步推進模式, 工作流所需指令如下 : 
  • /opsx:new <iteration_name> (建立迭代之專屬的工作區)
  • /opsx:propose <requirements> (依需求起草提案書, 規格定義書, 架構設計書, 與任務清單)
  • /opsx:apply <iteration_name> (依照 tasks.md 中的任務清單逐一實作此迭代功能)
  • /opsx:archive (迭代完成歸檔)
廢話不多說以免誤了軍期, 馬上開工. 


1. 建立迭代之專屬工作區 :   

第三次迭代工作區取名為 calc-scientific :

/opsx:new calc-scientific   



... (略) ...



2. 根據需求填寫提案書 :   

> /opsx:propose "在現有計算器專案上擴充科學計算功能, 包含三角函數 (sin, cos, tan) 與對數 (以 10 為底的 log, 以及自然對數 ln), 請務必處理以下邊界與轉換邏輯:1. 三角函數的輸入值預設為「角度 (Degree)」, 後端需自行轉換為弧度進行計算, 2. 處理 tan(90) 等無效角度的防呆機制, 3. 對數運算需阻擋小於或等於 0 的無效輸入, 並回傳明確的 HTTP 錯誤, 4. 前端介面需優雅地加入這些新按鈕. "



... (略) ...



3. 依據任務清單實作程式碼 :   

> /opsx:apply calc-scientific   



... (略) ...



完成專案實作馬上作人工測試, 開啟 127.0.0.1:5000 網頁果然多了很多科學計算按鈕 :



輸入 30 或 390 按 sin 都會得到正確結果 0.5 :




輸入 -30 按 sin 也得到正確結果 -0.5 :




接下來做 cos 的精度測試, 輸入 90 按 cos 得到一個接近 0 的極小值而非 0, 這是因為我們忘了要 AI 做微小誤差抹零處理之故, 可以在後續迭代中處理掉. 做對數測試, 輸入 1 按 log 得到正確 0, 輸入 0 按 log 則得到 Error (無限大) :




4. 歸檔結案 : 

/opsx: archive   



... (略) ...


第三次迭代歸檔完畢, 終於搞定了, 趕緊來去交作業啦! 


5. 打包專案上傳 GitHub : 

作業繳交要求將專案上傳 GitHub, 然後將 repo 網址填入 Google 試算表內. 


(1). 將所有變更加入暫存區 (打包) : 

D:\gemini\calculator-project>git add .  
warning: in the working copy of '.gemini/commands/opsx/apply.toml', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of '.gemini/commands/opsx/archive.toml', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of '.gemini/commands/opsx/explore.toml', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of '.gemini/commands/opsx/propose.toml', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of '.gemini/skills/openspec-apply-change/SKILL.md', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of '.gemini/skills/openspec-archive-change/SKILL.md', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of '.gemini/skills/openspec-explore/SKILL.md', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of '.gemini/skills/openspec-propose/SKILL.md', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of '.gitignore', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of '.python-version', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'main.py', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'openspec/changes/archive/2026-04-25-calc-basic/.openspec.yaml', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'openspec/changes/archive/2026-04-25-calc-power-root/.openspec.yaml', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'openspec/changes/archive/2026-04-25-calc-scientific/.openspec.yaml', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'openspec/config.yaml', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'pyproject.toml', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'uv.lock', LF will be replaced by CRLF the next time Git touches it

出現的這些 warning 是在 Windows 環境下執行 Git 時常見的警告, 它完全不影響程式碼功能或 GitHub 的上傳結果, 這只是 Git 在提醒換行符號的格式要統一, 因為 OpenSpec 工具或 AI 產生的檔案可能預設使用了 Unix 格式的換行字符 LF, 在 Windows 的命令提示字元下操作時 Git 偵測到這種不一致, 所以主動告知它會自動把這些檔案轉換成 Windows 標準的 CRLF, 因此毋須理會. 


(2). 設定使用者名稱與 Email : 
 
D:\gemini\calculator-project>git config --global user.name "Tony"
D:\gemini\calculator-project>git config --global user.email "blablabla@ms5.hinet.net"   


(3). 提交變更 (貼標籤/存檔) : 

D:\gemini\calculator-project>git commit -m "feat: 完成計算機專案 (基礎運算、次方根號、科學計算)"   
[master (root-commit) 17a5d99] feat: 完成計算機專案 (基礎運算、次方根號、科學計算)   
 44 files changed, 2523 insertions(+)
 create mode 100644 .gemini/commands/opsx/apply.toml
 create mode 100644 .gemini/commands/opsx/archive.toml
 create mode 100644 .gemini/commands/opsx/explore.toml
 create mode 100644 .gemini/commands/opsx/propose.toml
 create mode 100644 .gemini/skills/openspec-apply-change/SKILL.md
 create mode 100644 .gemini/skills/openspec-archive-change/SKILL.md
 create mode 100644 .gemini/skills/openspec-explore/SKILL.md
 create mode 100644 .gemini/skills/openspec-propose/SKILL.md
 create mode 100644 .gitignore
 create mode 100644 .python-version
 create mode 100644 GEMINI.md
 create mode 100644 README.md
 create mode 100644 calculator/__init__.py
 create mode 100644 calculator/logic.py
 create mode 100644 main.py
 create mode 100644 openspec/changes/archive/2026-04-25-calc-basic/.openspec.yaml
 create mode 100644 openspec/changes/archive/2026-04-25-calc-basic/design.md
 create mode 100644 openspec/changes/archive/2026-04-25-calc-basic/proposal.md
 create mode 100644 openspec/changes/archive/2026-04-25-calc-basic/specs/arithmetic-api/spec.md
 create mode 100644 openspec/changes/archive/2026-04-25-calc-basic/specs/calculator-ui/spec.md
 create mode 100644 openspec/changes/archive/2026-04-25-calc-basic/tasks.md
 create mode 100644 openspec/changes/archive/2026-04-25-calc-power-root/.openspec.yaml
 create mode 100644 openspec/changes/archive/2026-04-25-calc-power-root/design.md
 create mode 100644 openspec/changes/archive/2026-04-25-calc-power-root/proposal.md
 create mode 100644 openspec/changes/archive/2026-04-25-calc-power-root/specs/advanced-arithmetic/spec.md
 create mode 100644 openspec/changes/archive/2026-04-25-calc-power-root/specs/calculator-ui/spec.md
 create mode 100644 openspec/changes/archive/2026-04-25-calc-power-root/tasks.md
 create mode 100644 openspec/changes/archive/2026-04-25-calc-scientific/.openspec.yaml
 create mode 100644 openspec/changes/archive/2026-04-25-calc-scientific/design.md
 create mode 100644 openspec/changes/archive/2026-04-25-calc-scientific/proposal.md
 create mode 100644 openspec/changes/archive/2026-04-25-calc-scientific/specs/calculator-ui/spec.md
 create mode 100644 openspec/changes/archive/2026-04-25-calc-scientific/specs/scientific-functions/spec.md
 create mode 100644 openspec/changes/archive/2026-04-25-calc-scientific/tasks.md
 create mode 100644 openspec/config.yaml
 create mode 100644 openspec/specs/advanced-arithmetic/spec.md
 create mode 100644 openspec/specs/arithmetic-api/spec.md
 create mode 100644 openspec/specs/calculator-ui/spec.md
 create mode 100644 openspec/specs/scientific-functions/spec.md
 create mode 100644 pyproject.toml
 create mode 100644 static/index.html
 create mode 100644 static/script.js
 create mode 100644 static/style.css
 create mode 100644 test_api.py
 create mode 100644 uv.lock


(4). 在 GitHub 建立空的儲存庫 (Repository) : 

建立一個空專案 (剛好 calculator-project 可用), 注意, 因為在本機已經有 README.md 與 .gitignore 檔案了, 不要勾選 "Add a README" 或 "Add .gitignore" 這兩項, 保持預設的空專案即可, 點擊 Create repository 新增 repo. 



(5). 綁定並推上雲端 : 

告訴本機 Git 這個專案要連線到哪個 GitHub 網址 : 

D:\gemini\calculator-project>git remote add origin https://github.com/tony1966/calculator-project.git  

把專案推上雲端  : 

D:\gemini\calculator-project>git push -u origin main   
Enumerating objects: 67, done.
Counting objects: 100% (67/67), done.
Delta compression using up to 16 threads
Compressing objects: 100% (51/51), done.
Writing objects: 100% (67/67), 39.46 KiB | 3.04 MiB/s, done.
Total 67 (delta 3), reused 0 (delta 0), pack-reused 0 (from 0)
remote: Resolving deltas: 100% (3/3), done.
To https://github.com/tony1966/calculator-project.git
 * [new branch]      main -> main
branch 'main' set up to track 'origin/main'.

此指令會出現詢問視窗, 用預設 manager 按 Select 鈕即可, 然後登入 GitHub 帳號即可上傳. 成功後到 Google sheet 登錄專案 repo 的 GitHub 網址即完成作業繳交啦! 我原以為時間太趕只能聽完課程, 沒想到忙了一整天居然搞定作業了, 哈哈. 

心得 : 親自動手做一遍才能真正學會. 


6. 跳出 Gemini CLI : 

專案結束, 輸入 exit 離開專案 : 




used 從 2% 到 10%, 用掉了 8% 資源. 連續按兩次 Ctrl+C 即可跳出 Gemini CLI 回到 PS 視窗. 

Gemini CLI 學習筆記 : OpenSpec 初體驗 (二)

白天完成初次迭代後, 傍晚快馬加鞭進行第二次迭代.

本系列全部測試文章參考 : 


前一篇的初次迭代由於功能較簡單, 我們使用了 /opsx:ff 快轉指令一鍵生成模式, 快速地完成了從規劃到程式碼生成與測試驗證的工作流. 本篇將在初次碟待的基礎上為基本的四則運算計算器添加次方與根號功能. 

此二次迭代將改用逐步推進模式, 舊版 OpenSec 原本的的工作流需要依序執行下列指令 :
  • /opsx:new <iteration_name> (建立迭代之專屬的工作區)
  • /opsx:propose <requirements> (依需求起草提案書)
  • /opsx:continue (完成規格定義書 spec.md)
  • /opsx:continue (完成架構設計書 design.md)
  • /opsx:continue (完成任務清單 tasks.md)
  • /opsx:apply (依照 tasks.md 中的任務清單逐一實作功能)
  • /opsx:verify (驗證程式碼與規格完整性, 正確性, 一致性)
  • /opsx:archive (迭代完成歸檔)
執行 /opsx:propose 後, AI 只會生成第一份文件 proposal.md (提案書) 並把控制權交還給我們來審查功能描述是否與需求符合. 審查通過後就可執行三個連續的 /opsx:continue 指令, 一次只產出一份文件, 審查通過後再執行下一個 continue 指令. 

第一個 /opsx:continue 指令, 它會生成規格定義書 spec.md, 注意, 這個檔案可能不只一個, 因為在模組化的軟體架構中, 功能會被解耦分拆在不同資料夾, 例如 :

openspec/changes/calc-power-root/specs/arithmetic-api/spec.md
openspec/changes/calc-power-root/specs/calculator-ui/spec.md

每一個功能都會有一個 spec.md 檔, 這些分散的規格定義書共同構成了這次迭代的完整規格.

第二個 /opsx:continue 指令會產生架構設計書 design.md, 主要是描述內部程式碼要怎麼實作, 審查重點在於有沒有過度設計 (Over-engineering), 例如明明 math 套件能做到的功能卻使用 numpy, 這實要將其改為 "使用 Python 內建 math 即可". 

第三個 (也是最後一個) /opsx:continue 指令會生成任務清單 (施工單) tasks.md 檔, 這份文件是設計階段與實作階段之間的最後一座橋樑, 也是 AI 執行 /opsx:apply 時唯一的行動指南, 它只關注具體要做哪些動作. 審查時要檢查施工順序是否合理, 若無問題就可以下達 /opsx:apply 指令叫 AI 依照清單逐一實作程式碼, 完成驗證後即可歸檔. 

但新版的 OpenSec 已經把三次 /opsx: continue 指令整合進 /opsx:propose 裡面了, 所以新版的工作流指令序列改為 :
  • /opsx:new <iteration_name> (建立迭代之專屬的工作區)
  • /opsx:propose <requirements> (依需求起草提案書, 規格定義書, 架構設計書, 與任務清單)
  • /opsx:apply <iteration_name> (依照 tasks.md 中的任務清單逐一實作此迭代功能)
  • /opsx:archive (迭代完成歸檔)
填寫四大核心工件的步驟其實都整合到 /opsx:propose 指令裡了. 


1. 建立迭代之專屬工作區 :   

第二次迭代的目標是要為四則運算計算器添加次方與開根號功能, 因此迭代名稱可取為 calc-power-root : 

> /opsx:new calc-power-root   

同樣地會有一連串的授權詢問, 一律選擇預設的 Allow once 觀察每一步在做甚麼 :



... (略) ...



可見 /opsx: new 指令主要是生成四個核心工件 (artifacts) 的待填空模板, 其中的 spec.md 是每個功能會有一個, 放在各自功能的資料夾下面. 


2. 根據需求填寫提案書 :   

有了核心工件的空模板後, 接下來要用 /opsx: propose 指令注入需求, 讓 AI 協助填寫提案書 : 

> /opsx:propose "在現有的基礎四則運算計算器專案上, 加上次方與開根號功能. 請確保處理好基礎的邊界條件與防呆機制 (例如對負數開偶數根的錯誤處理) 等. "

這時 OpenSpec 偵測到這個需求的主題跟上面剛剛用 /opsx:new calc-power-root 建好的 calc-power-root 工作區完全契合, 詢問是否要把這份提案放進剛才那個工作區? 那是當然的, 選  1. 繼續使用 calc-power-root : 




... (略) ...



可見四大核心工件檔案的填寫都已完成, 開啟這些檔案審查若不需要修改就可以下 /opsx:apply 指令來實作程式碼了. 


3. 依據任務清單實作程式碼 :   

用 /opsx: apply 指令並指定迭代工作區名稱 (防呆防猜測) :

> /opsx:apply calc-power-root  

此指令將依照任務清單 tasks.md 內容依序實作程式碼, 同樣地會有一連串的授權詢問, 一律選擇預設的 Allow once 觀察每一步在做甚麼 :



... (略) ...



這樣就完成專案實作了 (咦, 這次沒跟我說要開啟 127.0.0.1:5000 來測試?), 我前次迭代執行的 uv rum main.py 沒關掉, 馬上測試 2 的 3 次方得到正確結果 8 : 




按 C 鍵清除輸入 49 按開根號也正確得到 7 : 




原先的基本四則運算功能維持一樣沒被改壞, 二次迭代終於完成了. 


4. 歸檔結案 : 

下 /opsx: archive 指令歸檔  :

> /opsx: archive   



... (略) ...



終於完成二次迭代了. 

Gemini CLI 學習筆記 : OpenSpec 初體驗 (一)

最近幾天上完 TibaMe 的規格驅動開發 (SDD) 課程, 準備找一個小專案 (計算器) 用 Gemini CLI 來跑一下 OpenSpec 交作業. 

本系列全部測試文章參考 : 


關於 SDD 我已看完高見龍老師的部落格文章, 摘要整理在這篇 : 



1. Gemini CLI 升版 :

距離上次測試已經過了快三個月了, Gemini CLI 版本應該也演進了不少, 所以先來升版. 開啟 PS 視窗, 輸入下列指令查詢目前本機版本 :

PS D:\gemini> gemini --version  
0.26.0

用下列指令升到最新版 : 

PS D:\gemini> npm install -g @google/gemini-cli@latest   

added 1 package, removed 609 packages, and changed 6 packages in 3m
npm notice
npm notice New minor version of npm available! 11.6.2 -> 11.13.0
npm notice Changelog: https://github.com/npm/cli/releases/tag/v11.13.0
npm notice To update run: npm install -g npm@11.13.0
npm notice
PS D:\gemini> gemini --version
0.39.1   

哇, 一季不見已從 0.26.0 跳到 0.39.1 版. npm 也有新版, 順便也升版 :

PS D:\gemini> npm install -g npm@11.13.0   

removed 60 packages, and changed 90 packages in 9s
PS D:\gemini> npm --version   
11.13.0


2. 安裝 OpenSpec :

OpenSpec 是一款由 Fission AI 研發的開源輕量級規格驅動開發 (SDD) 工具, 是一套讓 AI 程式助理 (coding agents) 遵循規格的工作流程與 CLI 工具, 目前支援 20 種以上 AI 工具, 它的目標是讓工程師與 AI 在開發軟體之前先對規格達成共識, 減少 vibe coding 常見的偏題與反覆修改弊病, 並且能留下規格紀錄與決策脈絡備查, 提高軟體可維護性. 

安裝 OpenSpec 須有 Node v20.19.0 以上執行環境, 先檢視 Node 版本 :

PS D:\gemini> node --version  
v25.2.1

我的 Node 是利用 Scoop 安裝 Node 的, 可管理多版本的 Node, 參考 : 


這樣就可以在 PS 視窗安裝 OpenSpec 了 : 

PS D:\gemini> npm -g install @fission-ai/openspec@latest   

added 74 packages in 34s

這樣就完成 OpenSpec 安裝了. 


3. 用 uv 建立專案目錄 & 加入版控 :

由於作業要求用 OpenSpe 做三次迭代, 我打算用 OpenSpec 來實作一個網頁計算器專案, 第一次迭代要實作基本的四則運算計算機, 第二次迭代添加次方與開根號功能; 第三次迭代則添加對數, 指數, 與三角函數. 

首先用 uv init 指令建立一個專案目錄 : 

PS D:\gemini> uv init calculator-project     
Initialized project `calculator-project` at `D:\gemini\calculator-project`

然後切換到專案目錄下 : 

PS D:\gemini> cd calculator-project     

對此專案進行版本控制, 先檢視 Git 是否已安裝 : 

PS D:\gemini\calculator-project> git --version   
git version 2.52.0.windows.1

關於 Git 安裝與用法參考 :


在專案目錄下用 git init 初始化版控 : 

PS D:\gemini\calculator-project> git init   
Reinitialized existing Git repository in D:/gemini/calculator-project/.git/

版控資訊會儲存在隱藏目錄 .git 底下. 


4. 初始化 OpenSpec :   

接著用 openspec init 指令為此專案做 OpenSpec 的初始化 :

PS D:\gemini\calculator-project> openspec init 

這時會出現 OpenSpec 歡迎畫面 :




按 Enter 會出現 AI 程式代理工具選單, 可以按上下鍵移動指標來選擇要用的 AI 工具, 按 Space 鍵選擇要使用的代理工具 (可複選, 目前已支援 28 種 AI 程式代理工具), 此處我只選 Gemini CLI :




選定的工具名稱會被列在上方的 Selected : 後面




選完後按 Enter 退出 OpenSpec 初始化畫面回到 PS 終端機, 可見已為 Gemini CLI 程式代理建立了 4 個技能 (skills) 與 OpenSpeck 相關之命令 :

Note: OpenSpec collects anonymous usage stats. Opt out: OPENSPEC_TELEMETRY=0
√ Select tools to set up (28 available) Gemini CLI
▌ OpenSpec structure created
√ Setup complete for Gemini CLI

OpenSpec Setup Complete

Created: Gemini CLI
4 skills and 4 commands in .gemini/
Config: openspec/config.yaml (schema: spec-driven)

Getting started:
  Start your first change: /opsx:propose "your idea"

Learn more: https://github.com/Fission-AI/OpenSpec
Feedback:   https://github.com/Fission-AI/OpenSpec/issues

Restart your IDE for slash commands to take effect.

做完上面初始化後, 用 tree /f 指令檢視專案目錄 :

PS D:\gemini\calculator-project> tree /f   
列出磁碟區 新增磁碟區 的資料夾 PATH
磁碟區序號為 1258-16B8
D:.
│  .gitignore
│  .python-version
│  main.py
│  pyproject.toml
│  README.md
├─.gemini
│  ├─commands
│  │  └─opsx
│  │          apply.toml
│  │          archive.toml
│  │          explore.toml
│  │          propose.toml
│  │
│  └─skills
│      ├─openspec-apply-change
│      │      SKILL.md
│      │
│      ├─openspec-archive-change
│      │      SKILL.md
│      │
│      ├─openspec-explore
│      │      SKILL.md
│      │
│      └─openspec-propose
│              SKILL.md
└─openspec
    │  config.yaml
    │
    ├─changes
    │  └─archive
    └─specs

可見 OpenSec 初始化時已在


5. 安裝專案所需套件 :   

雖然對一個計算器專案來說, 只需要純前端 (HTML/CSS/JavaScript) 技術就能完成所有功能, 但為了模擬真實軟體架構常見的前後端搭配組態, 我打算將計算功能邏輯交給後端 Flask 框架來完成, 所以必須先用 uv 工具安裝 Flask, 這樣當 AI 生成程式碼後就可以叫 Gemini CLI  用 uv run 執行專案與驗證結果, 不需要再跳出來處理環境問題. 其次, 在使用 /opsx:verify 進行自動化檢查或測試時, 系統會依賴現有的虛擬環境, 如果環境未就緒 (例如缺少 Flask 套件), 驗證步驟可能會出錯. 

PS D:\gemini\calculator-project> uv add flask   
Using CPython 3.12.1 interpreter at: C:\Users\tony1\AppData\Local\Programs\Python\Python312\python.exe
Creating virtual environment at: .venv
Resolved 9 packages in 758ms
Prepared 7 packages in 466ms
░░░░░░░░░░░░░░░░░░░░ [0/8] Installing wheels...                                                                         warning: Failed to hardlink files; falling back to full copy. This may lead to degraded performance.
         If the cache and target directories are on different filesystems, hardlinking may not be supported.
         If this is intentional, set `export UV_LINK_MODE=copy` or use `--link-mode=copy` to suppress this warning.
Installed 8 packages in 98ms
 + blinker==1.9.0
 + click==8.3.3
 + colorama==0.4.6
 + flask==3.1.3
 + itsdangerous==2.2.0
 + jinja2==3.1.6
 + markupsafe==3.0.3
 + werkzeug==3.1.8

安裝完後用 tree /f 檢視專案目錄, 會多出一個 .venv 隱藏子目錄, 裡面有包含 Flask 與所依賴的 Jinjia 等套件 :

├─.venv
│  │  .gitignore
│  │  .lock
│  │  CACHEDIR.TAG
│  │  pyvenv.cfg
│  │
│  ├─Lib
│  │  └─site-packages
│  │      │  _virtualenv.pth
│  │      │  _virtualenv.py
│  │      │
│  │      ├─blinker
│  │      │      base.py
│  │      │      py.typed
│  │      │      _utilities.py
│  │      │      __init__.py

... (略) ...

│  │      ├─flask
│  │      │  │  app.py
│  │      │  │  blueprints.py
│  │      │  │  cli.py
│  │      │  │  config.py
│  │      │  │  ctx.py
│  │      │  │  debughelpers.py
│  │      │  │  globals.py
│  │      │  │  helpers.py
│  │      │  │  logging.py
│  │      │  │  py.typed
│  │      │  │  sessions.py
│  │      │  │  signals.py
│  │      │  │  templating.py
│  │      │  │  testing.py
│  │      │  │  typing.py
│  │      │  │  views.py
│  │      │  │  wrappers.py
│  │      │  │  __init__.py
│  │      │  │  __main__.py

... (略) ...


6. 編輯專案語境檔 GEMINI.md : 

在之前使用 Vibe coding 的進階方式開發時, 我們透過事先編輯好的專案語境檔 GEMINI.md 一次將專案需求與結構, 程式風格, 任務模板, 限制和偏好等資訊一口氣描述好, 當啟動 Gemini CLI 時它便能了解專案內容, 從而減少來回問答的次數. 這種語境檔因為要交待較多訊息, 所以內容比較冗長, 參考 :


如果使用 OpenSpec 做 SDD 開發, GEMINI.md 就會比較簡短, 例如下面的通用模板 :

# Project Global Guidelines (GEMINI.md)

## 1. AI 角色設定 (通用)
你是一位資深的 [Python 後端與全端] 開發專家,精通 [Flask 框架與現代前端技術],並具備極高的軟體工程素養。

## 2. 技術棧與環境配置 (專案特製)
* 核心語言:Python 3.12+ (嚴格使用 `uv` 進行依賴與環境管理)
* 後端框架:[Flask]
* 前端技術:[Vanilla JS, HTML5, CSS3]
* 其他工具:[若無則免,例如 SQLite, 特定硬體 SDK 等]

## 3. 開發流程與規格遵循 (通用,針對 OpenSpec 用戶)
* 本專案嚴格遵循 Fission AI 的 OpenSpec 工作流 (`/opsx` 指令集)。
* 你的所有實作必須以 `specs/` 目錄下的文件與 `tasks.md` 為「唯一真相來源 (Single Source of Truth)」。
* 絕對禁止在未經使用者同意且未更新 Spec 的情況下,自行發明、擴充或竄改 API 規格與業務邏輯。

## 4. 程式碼風格守則 (通用,Python 標準)
* 必須包含 Type Hints (型別提示) 與清楚的 Docstrings。
* 遵守 PEP 8 命名規範 (變數與函式使用 `snake_case`,類別使用 `PascalCase`)。
* 保持模組化,避免單一檔案過於龐大。

其中專案特製部分視專案而異, 括號 [] 內容需要手動修改, 其他通用部分則適用於任何用 OpenSpec 開發的專案. GEMINI.md 的角色是專案的憲法, 負責告訴 AI 我們這個專案要用甚麼 approach 來做 (How), 而專案的需求 (what) 會放在 /opsx: propose 指令來交待.  

在 PS 視窗的專案目錄下輸入 notepad GEMINI.md :

PS D:\gemini\calculator-project> notepad GEMINI.md  

這時 PS 發現專案目錄下並無 GEMINI.md 檔, 就彈出詢問是否新建此檔, 按是就會開啟記事本 :




複製上面的語境檔通用範本貼到 GEMINI.md 後存檔 (此處我將 ## 2 的其他工具內容改為 [無]) : 




再次用 tree /s 檢視專案目錄下已有此 GEMINI.md 檔了 :

PS D:\gemini\calculator-project> tree /f   
列出磁碟區 新增磁碟區 的資料夾 PATH
磁碟區序號為 1258-16B8
D:.
│  .gitignore
│  .python-version
│  GEMINI.md
│  main.py
│  pyproject.toml
│  README.md
│  uv.lock
├─.gemini
│  ├─commands
│  │  └─opsx
│  │          apply.toml
│  │          archive.toml
│  │          explore.toml
│  │          propose.toml
│  │
│  └─skills
... (略) ...


7. 啟動 Gemini CLI 進行初次迭代  : 

完成上面準備工作後, 終於要開啟 Gemini CLI 開始用 OpenSpec 幹活了. 在專案目錄下輸入 gemini 指令 : 

PS D:\gemini\calculator-project> gemini    

詢問是否信任此目錄, 當然要選 1. Trust folder (calculator-project) 才會進入 Gemini CLI 介面 :





出現 > 提示號表示 AI 已經讀取了 GEMINI.md 內容知道自己是誰, 也知道這個資料夾裡有 OpenSpec 環境, 這樣就可以開始用 OpenSpec 的 斜線指令集 /opsx 進行 SDD 開發了. 

如上所述, 這個專案作業要求至少進行三次開發迭代, 第一次迭代是要做出一個基本的四則運算計算器, 由於較簡單, 此處會使用快轉模式, 直接用 /opsx: ff 指令一鍵生成完成專案規劃與程式碼生成與測試, 整個工作流只需要的指令如下 (依序) :
  • /opsx:new <iteration_name> (建立迭代之專屬的工作區)
  • /opsx:ff <requirements> (依需求快轉生成設計文件與程式碼並完成測試)
  • /opsx:archive (迭代完成歸檔)
其中 iteration_name 是自訂的, 為了專案的易讀性以及讓 AI 能隱約猜到任務方向, 通常會遵循以下命名最佳實踐來取名 :
  • 使用 Kebab-case (連字號命名法) :
    全小寫英文, 單字之間用連字號 - 隔開, 避免使用空格, 大寫或特殊符號. 
  • 具備語意 (Semantic) : 名稱要能直接反映這次迭代的核心目的.
初次迭代我選用 cals-basic 作為工作區名稱. 


(1). 建立迭代之專屬工作區 : 

這會在專案目錄下建立此次迭代之專屬工作區, 例如迭代名稱是 calc-basic 的話就建立對應的資料夾 specs/changes/calc-basic/ 來收納這次迭代的所有相關討論與設計文件. 

系統會自動生成標準 SDD 流程所需的空文件或帶有基礎標題的模板, 例如空的 proposal.md, spec.md, design.md 以及 tasks.md, 此階段相當於是買了一本有分類索引標籤 (提案, 規格, 設計, 任務) 的空白筆記本, 以便在後續工作流中依需求來填空或修改. 

輸入下列指令並於一連串授權詢問時一律選擇預設的 Allow once :

/opsx:new calc-basic  



... (略) ...



工作區建完後, 專案所需的 OpenSpec 模板文件也都已建好, 但它們目前只是空洞的骨架而已, 接下來的工作流 (/opsx:ff 或 /opsx:continue) 就會根據需求來填寫這些標準 SSD 流程的四份核心文件模板 (proposal.md, spec.md, design.md 以及 tasks.md), 如果需求較複雜, 可能也會生成額外的 spec-xxx.md 文件, 相當於是在骨架中進行靈魂注入. 


(2). 依需求快轉 (ff) 生成設計文件與程式碼 : 

此階段 OpenSpec 會根據我們提供的專案需求, 透過 AI 去修改或填空上一個指令 (/opsx: new) 生出的四份核心文件 proposal.md (提案), spec.md (介面規格), design.md (架構設計) 與 tasks.md (任務清單), 並且據此生成程式碼同時完成測試, 可說是集成了 /opsx:propose, /opsx:continue, /opsx: apply, 以及 /opsx: verify 這四個指令的功能於一身, 一氣呵成完成專案實作. 

輸入如下指令來進行快轉 : 

> /opsx:ff "請幫我規劃一個基礎四則運算計算機軟體, 後端使用 Flask 提供 POST API, 前端使用純 HTML/JS, 並提供基本的使用者介面."   



... (略) ...



同樣地, 在它修改生成檔案與依此生成整個專案程式碼過程中會不斷要求授權, 我都選預設的 Allow once, 這樣可以一步步觀察 OpenSpec 做了哪些事, 過程中會顯示生成的程式碼與單元測試檔, 完成後結果如下 :  




這時可以另開一個命令提示字元或 PS 視窗, 切到專案目錄下, 用 python main.py 或 uv run main.py 執行此專案, 然後開啟瀏覽器訪問 http://127.0.0.1:5000 : 

PS D:\gemini> cd calculator-project   
PS D:\gemini\calculator-project> uv run main.py
 * Serving Flask app 'main'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 125-928-819
127.0.0.1 - - [25/Apr/2026 16:44:54] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [25/Apr/2026 16:44:54] "GET /static/style.css HTTP/1.1" 200 -
127.0.0.1 - - [25/Apr/2026 16:44:54] "GET /static/script.js HTTP/1.1" 200 -
127.0.0.1 - - [25/Apr/2026 16:44:54] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [25/Apr/2026 16:45:11] "POST /api/multiply HTTP/1.1" 200 -
127.0.0.1 - - [25/Apr/2026 16:45:23] "POST /api/divide HTTP/1.1" 400 -

果然顯示了四則運算計算器頁面, 測試計算功能正常 (7 * 8=56, 1 除以 0 顯示 Error ) :





(3). 歸檔結案 : 

完成以上功能驗證後, 就可以用 /opsx: archive 指令檢查所有的 Artifacts 是否齊全, 是的話將此次迭代的所有紀錄, 文件, 與過程收整, 並移動到 archive 資料夾收存 :

> /opsx:archive

同樣地會有一連串的授權請求, 一律選擇預設的 Allow once : 




... (略) ...




可見所有此次迭代的紀錄文件都已歸檔於 openspec/changes/archive/2026-04-25-calc-basic/ 資料夾底下, 這些都是未來維護軟體的重要資料. 好啦! 終於完成初次迭代.